branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for PaintSelector.xaml /// </summary> public partial class PaintSelector : Window { public static string PaintColor; public PaintSelector() { InitializeComponent(); //this.window = window; //PaintColor = window.PaintColor; } private void button_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; Brush b = button.Background; textbox_color.Text = "#"+ (b as SolidColorBrush).Color.ToString().Substring(3); } private void textbox_color_TextChanged(object sender, TextChangedEventArgs e) { changeTextBoxColor(); } private void changeTextBoxColor() { if(textbox_color.Text.Length==7) { try { var bc = new BrushConverter(); string color = "#FF" + textbox_color.Text.Substring(1); textbox_color.Background = (Brush)bc.ConvertFrom(color); } catch { MessageBox.Show("Please use the right format\n \"#123abc\" where 1-9,a-f (hex)"); } } else { var bc = new BrushConverter(); textbox_color.Background = (Brush)bc.ConvertFrom("#eeeeee"); } PaintColor = textbox_color.Text; } private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { string red = Convert.ToInt32(slider_red.Value).ToString("X"); string green = Convert.ToInt32(slider_green.Value).ToString("X"); string blue = Convert.ToInt32(slider_blue.Value).ToString("X"); string color = "#" + red.PadLeft(2,'0') +""+ green.PadLeft(2,'0') +""+ blue.PadLeft(2,'0'); textbox_color.Text = color; } private void textbox_color_MouseEnter(object sender, MouseEventArgs e) { changeTextBoxColor(); } private void Button_Click_1(object sender, RoutedEventArgs e) { textbox_color.Text = "#"; } //onpaint change: this.window.paint = #iets; } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for ProgressWindow.xaml /// </summary> public partial class ProgressWindow : Window { BackgroundWorker BackgroundWorker; public ProgressWindow(BackgroundWorker backgroundworker, string doing ) { this.BackgroundWorker = backgroundworker; InitializeComponent(); doing_label.Content = doing; } public void Cancel_Click(object sender, RoutedEventArgs e) { if (BackgroundWorker != null) BackgroundWorker.CancelAsync(); } public void UpdateProgress(int currentprogress) { progressbar.Value = currentprogress; } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Assimp; using Assimp.Unmanaged; namespace Advanced_Blueprint_Tools { using System.Windows.Media; using System.Windows.Media.Media3D; using HelixToolkit.Wpf; using Assimp.Configs; using System.Net.Http; using System.Net; using Newtonsoft.Json.Linq; /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public BP OpenedBlueprint { get; set; } public Model3DGroup Model { get; set; } public Model3DGroup Marker { get; set; } public Model3DGroup Marker2 { get; set; } public Model3DGroup Glass { get; set; } public Model3DGroup Wires { get; set; } OpenWindow openwindow; //public cuz need to update(); when new creation loaded: public AdvancedConnections advancedconnections; public AdvancedColor advancedcolorwindow; public SwapBlocksWindow swapblockswindow; public BlockProperties blockProperties; public AreaProperties areaProperties; public BlockPropertiesRAW blockPropertiesRAW; Circle_generator circle_generator; Ellipsoid_Generator ellpisoid_generator; Cuboid_Generator cuboid_Generator; NotificationWindow notificationWindow; Settings settings; public MainWindow() { new Thread(() => { MessageBox.Show("This version of the tool should work with scrap mechanic 0.4.5, if for any reason this breaks or you found a bug: contact Brent Batch#9261"); }).Start(); InitializeComponent(); //LOAD RESOURCES: Database.findPaths(); new Thread(() => { try { Database.LoadAllBlocks(); } catch (Exception e) { MessageBox.Show("Error: Could not load parts. Further program functions may fail.\n" + e.Message); } }).Start(); new Thread(() => { try { Database.LoadAllBlueprints(); } catch (Exception e) { MessageBox.Show("Error: Could not load Blueprints. Further program functions may fail.\n" + e.Message); } }).Start(); new Task(() => { try { new Updater().CheckForUpdates(); } catch (Exception e) { MessageBox.Show("Error: could not check for an updated version.\n" + e.Message); } }).Start(); new Thread(() => { try { while (true) { this.Dispatcher.Invoke((Action)(() => { if (Database.Notifications.Count > 0) { Notifications.Visibility = Visibility.Visible; Notifications.Content = Database.Notifications.Count; } else { Notifications.Visibility = Visibility.Collapsed; } })); Thread.Sleep(1500); } } catch { } }).Start(); helix.Camera = helix_wires.Camera; } public void RenderBlueprint() { try { TextBox_Name.Text = BP.Description.name; TextBox_Description.Text = BP.Description.description; Tuple<Model3DGroup, Model3DGroup> renders = BP.RenderBlocks();//backgroundtask ? this.Model = renders.Item1; this.Glass = renders.Item2; this.Marker = null; CenterMass.Content = null; this.Marker2 = new Model3DGroup(); RenderWires(); if (listBox_parts.Visibility == Visibility.Visible) fillparts(); Image_blueprint.DataContext = null; Image_blueprint.DataContext = this; helix.ResetCamera(); helix_wires.Camera = helix.Camera; //Model.Children[5].Transform = new ScaleTransform3D(2,2,2); if (connections.IsEnabled == false) { connections.IsEnabled = true; blockproperties.IsEnabled = true; paint.IsEnabled = true; fixcreation.IsEnabled = true; areaproperties.IsEnabled = true; swapblocks.IsEnabled = true; paintpicker.IsEnabled = true; mirrorcreation.IsEnabled = true; requiredmods.IsEnabled = true; } if (!Properties.Settings.Default.safemode) blockpropertiesRAW.IsEnabled = true; else blockpropertiesRAW.IsEnabled = false; } catch (Exception e) { MessageBox.Show(e.Message + "\nin most cases the creation should be fine, something just went wrong while rendering", "failed to render"); } } public void RenderWires() { this.Wires = new Model3DGroup(); if (Properties.Settings.Default.wires) { var wires = BP.GetWires(); foreach (dynamic wire in wires.Values) { Addblob(wire.pos, wire.color.ToString()); if (wire.connections != null) foreach (dynamic connid in wire.connections) if (wires.ContainsKey(Convert.ToInt32(connid.id.ToString()))) { Addwire(wire.pos, wires[Convert.ToInt32(connid.id.ToString())].pos, wire.color.ToString()); } } Image_blueprint.DataContext = null; Image_blueprint.DataContext = this; } } private void ToggleWires_Click(object sender, RoutedEventArgs e) { if (BP.Blueprint != null) { Properties.Settings.Default.wires = !Properties.Settings.Default.wires; if (Properties.Settings.Default.wires) RenderWires(); else { this.Wires = null; Image_blueprint.DataContext = null; Image_blueprint.DataContext = this; } } } private void CenterMass_Click(object sender, RoutedEventArgs e) { try { if (CenterMass.Content == null) { Point3D point = BP.GetCenterOffMass().Item1; Material material = new DiffuseMaterial(new SolidColorBrush(Color.FromArgb(255,230,30,30))); var meshBuilder = new MeshBuilder(false, false); meshBuilder.AddSphere(point, 0.3); var Mesh = meshBuilder.ToMesh(true); CenterMass.Content = new GeometryModel3D { Geometry = Mesh, Material = material }; } else CenterMass.Content = null; } catch (Exception ex) { MessageBox.Show(ex.Message); } } public void Addblob(dynamic pos, string color) { try { if (!Properties.Settings.Default.colorwires) color = Properties.Settings.Default.blobcolor.Substring(1,6); Material material = new DiffuseMaterial(new SolidColorBrush(Color.FromArgb(Properties.Settings.Default.coloropacity, Convert.ToByte(color.Substring(0, 2), 16), Convert.ToByte(color.Substring(2, 2), 16), Convert.ToByte(color.Substring(4, 2), 16)))); var meshBuilder = new MeshBuilder(false, false); meshBuilder.AddSphere(new Point3D(Convert.ToDouble(pos.x.ToString()) , Convert.ToDouble(pos.y.ToString()) , Convert.ToDouble(pos.z.ToString()) ), 0.25); var Mesh = meshBuilder.ToMesh(true); this.Wires.Children.Add(new GeometryModel3D { Geometry = Mesh, Material = material }); } catch (Exception e) { MessageBox.Show(e.Message, "wire render failed"); } } public void Addwire(dynamic pos1, dynamic pos2, string color) { try { if (!Properties.Settings.Default.colorwires) color = Properties.Settings.Default.wirecolor.Substring(1, 6); Material material = new DiffuseMaterial(new SolidColorBrush(Color.FromArgb(Properties.Settings.Default.coloropacity, Convert.ToByte(color.Substring(0, 2), 16), Convert.ToByte(color.Substring(2, 2), 16), Convert.ToByte(color.Substring(4, 2), 16)))); var meshBuilder = new MeshBuilder(false, false); meshBuilder.AddArrow(new Point3D(Convert.ToDouble(pos1.x.ToString()), Convert.ToDouble(pos1.y.ToString()) , Convert.ToDouble(pos1.z.ToString()) ), new Point3D(Convert.ToDouble(pos2.x.ToString()) , Convert.ToDouble(pos2.y.ToString()) , Convert.ToDouble(pos2.z.ToString()) ), 0.15, 4); var Mesh = meshBuilder.ToMesh(true); this.Wires.Children.Add(new GeometryModel3D { Geometry = Mesh, Material = material }); } catch (Exception e) { MessageBox.Show(e.Message, "wire render failed"); } } public void setMarker(double x, double y, double z) {//cross marker Model3DGroup marker = new Model3DGroup(); Material material = new DiffuseMaterial(new SolidColorBrush(Color.FromArgb(100, 51, 204, 51))); var meshBuilder = new MeshBuilder(false, false); meshBuilder.AddBox(new Point3D(x, y, z), 0.2, 0.2, 1000); meshBuilder.AddBox(new Point3D(x, y, z), 0.2, 1000, 0.2); meshBuilder.AddBox(new Point3D(x, y, z), 1000, 0.2, 0.2); // Create a mesh from the builder (and freeze it) var Mesh = meshBuilder.ToMesh(true); marker.Children.Add(new GeometryModel3D { Geometry = Mesh, Material = material }); this.Marker = marker; Image_blueprint.DataContext = ""; Image_blueprint.DataContext = this; helix_wires.Camera.LookAt(new Point3D(x, y, z), 1000); //helix.Camera = helix_wires.Camera; } public void setMarker2(double x, double y, double z, double boundsx, double boundsy, double boundsz) {//cuboid marker Model3DGroup marker = new Model3DGroup(); Material material = new DiffuseMaterial(new SolidColorBrush(Color.FromArgb(50, 20, 50, 50))); var meshBuilder = new MeshBuilder(false, false); meshBuilder.AddBox(new Point3D(x, y, z), boundsx+0.1, boundsy+0.1, boundsz+0.1); // Create a mesh from the builder (and freeze it) var Mesh = meshBuilder.ToMesh(true); marker.Children.Add(new GeometryModel3D { Geometry = Mesh, Material = material }); this.Marker2 = marker; Image_blueprint.DataContext = ""; Image_blueprint.DataContext = this; } private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e) { if (openwindow != null && openwindow.IsLoaded) { openwindow.Focus(); } else { openwindow = new OpenWindow(this); openwindow.Owner = this; openwindow.Show(); } openwindow.TextBox_Search.Focus(); } private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)//possible to save/saveas? { e.CanExecute = false; if (BP.Blueprint != null) e.CanExecute = true; } private void SaveCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { button_overwrite_click(sender, e); } private void SaveAsCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { button_save_click(sender, e); } private void button_overwrite_click(object sender, RoutedEventArgs e)//save/overwrite { if (BP.Blueprint != null) { newtumbnail(); BP.Description.name = TextBox_Name.Text; BP.Description.description = TextBox_Description.Text; BP.Save(); } } private void button_save_click(object sender, RoutedEventArgs e)//save as { if (BP.Blueprint != null) { newtumbnail(); BP.Description.name = TextBox_Name.Text; BP.Description.description = TextBox_Description.Text; Random r = new Random(); //GENERATE NEW UUID AND CHANGE DESCRIPTION LOCALID --todo BP.SaveAs("Blueprint" + r.Next() + "-" + r.Next()); } } private void newtumbnail() { RenderTargetBitmap bmp = new RenderTargetBitmap(500, 500, 96, 96, PixelFormats.Pbgra32); bmp.Render(helix); Clipboard.SetImage(bmp); PngBitmapEncoder png = new PngBitmapEncoder(); png.Frames.Add(BitmapFrame.Create(bmp)); BP.Icon = png; } private void Click_advancedwiring(object sender, RoutedEventArgs e) { if (advancedconnections != null) advancedconnections.Close(); advancedconnections = new AdvancedConnections(this); advancedconnections.Owner = this; advancedconnections.Show(); } private void Click_blockproperties(object sender, RoutedEventArgs e) { if (blockProperties != null) blockProperties.Close(); blockProperties = new BlockProperties(this); blockProperties.Owner = this; blockProperties.Show(); } private void Click_areaproperties(object sender, RoutedEventArgs e) { if (areaProperties != null) areaProperties.Close(); areaProperties = new AreaProperties(this); areaProperties.Owner = this; areaProperties.Show(); } private void Click_blockpropertiesRAW(object sender, RoutedEventArgs e) { if (blockPropertiesRAW != null) blockPropertiesRAW.Close(); blockPropertiesRAW = new BlockPropertiesRAW(this); blockPropertiesRAW.Owner = this; blockPropertiesRAW.Show(); } private void Click_advancedcolor(object sender, RoutedEventArgs e) {//paint tool if (advancedcolorwindow != null) advancedcolorwindow.Close(); advancedcolorwindow = new AdvancedColor(this); advancedcolorwindow.Owner = this; advancedcolorwindow.Show(); } private void Click_fixcreation(object sender, RoutedEventArgs e) { dynamic blueprint = new JObject(); blueprint.bodies = new JArray(); blueprint.version = 1; blueprint.bodies.Add(new JObject()); blueprint.bodies[0].childs = new JArray(); //BP.Blueprint.joints = null; foreach (dynamic body in BP.Blueprint.bodies) { //remove bearings/springs/pistons foreach (dynamic child in body.childs) { if (child.joints != null) child.joints = null; if (child.controller != null) { if (child.controller.joints != null) child.controller.joints = null; if (child.controller.controllers != null) child.controller.controllers = null; } blueprint.bodies[0].childs.Add(child); } } BP.Description.description = BP.Description.description + "\n++ removed joints & glitchwelded"; BP.setblueprint(blueprint); this.RenderBlueprint(); } private void Click_swapblocks(object sender, RoutedEventArgs e) { if (swapblockswindow != null) swapblockswindow.Close(); swapblockswindow = new SwapBlocksWindow(this); swapblockswindow.Owner = this; swapblockswindow.Show(); } public static PaintSelector paintSelector; private void Click_paintpicker(object sender, RoutedEventArgs e) //paint picker { { paintSelector = new PaintSelector(); paintSelector.Owner = this; paintSelector.Show(); //MainWindow.openpainpicker(); } } public void openpaintpicker()//opens the paintpicker if mainwindow doesn't have one open { if (paintSelector == null || !(paintSelector.IsActive || paintSelector.IsFocused || paintSelector.IsVisible)) { paintSelector = new PaintSelector(); paintSelector.Owner = this; //static function :( paintSelector.Show(); } } private void Click_mirrormode(object sender, RoutedEventArgs e)//needs work { dynamic blueprint = BP.Blueprint; if (blueprint.joints == null) { foreach (dynamic body in blueprint.bodies) foreach (dynamic block in body.childs) { { dynamic realpos = BP.getposandbounds(block); int xaxis = Convert.ToInt32(block.xaxis); int zaxis = Convert.ToInt32(block.zaxis); if (!((xaxis == 1 && zaxis == -2) || (Math.Abs(xaxis) == 1 && Math.Abs(zaxis) == 3) || (xaxis == -1 && zaxis == 2))) { realpos.xaxis = -xaxis; realpos.zaxis = Math.Abs( zaxis)==1? -zaxis : zaxis; } //Bounds bounds = Blockobject.BoundsByRotation(new Bounds(realpos.bounds),1,3); realpos.pos.x = -Convert.ToInt32(block.pos.x) - ((realpos.pos.x == block.pos.x)? Convert.ToInt32(realpos.bounds.x) :0); //realpos.pos.y = Convert.ToInt32(block.pos.y) - Convert.ToInt32(block.bounds.y); block.pos = BP.calcbppos(realpos).pos; block.xaxis = BP.calcbppos(realpos).xaxis; block.zaxis = BP.calcbppos(realpos).zaxis; //block.pos.x = -Convert.ToInt32(block.pos.x); //works thus far for blocks, not parts tho /* if(Math.Abs(Convert.ToInt32(block.zaxis)) == 3 || Math.Abs(Convert.ToInt32(block.zaxis)) == 2) { block.xaxis = -Convert.ToInt32(block.xaxis); } if(Math.Abs(Convert.ToInt32(block.zaxis)) == 1) { block.zaxis = -Convert.ToInt32(block.zaxis); }*/ /*block.pos.x = -Convert.ToInt32(block.pos.x); if(Convert.ToInt32(block.xaxis) == 1 || Convert.ToInt32(block.xaxis) == -1) block.xaxis = -Convert.ToInt32(block.xaxis); else block.zaxis = -Convert.ToInt32(block.zaxis);*/ } } BP.setblueprint(blueprint); this.RenderBlueprint(); } else MessageBox.Show("Mirror mode can't mirror blueprints with joints inside yet!"); MessageBox.Show("Mirror mode did it's best to mirror things though there may be some parts that didn't turn out great."); } private void Click_ellipsoidgenerator(object sender, RoutedEventArgs e) { if (ellpisoid_generator != null) ellpisoid_generator.Close(); ellpisoid_generator = new Ellipsoid_Generator(this); ellpisoid_generator.Owner = this; ellpisoid_generator.Show(); } private void circlegenerator_Click(object sender, RoutedEventArgs e) { if (circle_generator != null) circle_generator.Close(); circle_generator = new Circle_generator(this); circle_generator.Owner = this; circle_generator.Show(); } private void Click_cuboidgenerator(object sender, RoutedEventArgs e) { if (cuboid_Generator != null) cuboid_Generator.Close(); cuboid_Generator = new Cuboid_Generator(this); cuboid_Generator.Owner = this; cuboid_Generator.Show(); } private void Click_requiredmods(object sender, RoutedEventArgs e) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://scrapmechanic.xesau.eu/uuidservice/get_mods"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; string postData = ""; foreach(string uuid in BP.GetUsedUuids()) { postData+="&uuid[]=" + uuid; } postData = postData.Substring(1); byte[] bytes = Encoding.UTF8.GetBytes(postData); request.ContentLength = bytes.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); var result = reader.ReadToEnd(); dynamic Mods = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(result); foreach (dynamic missingmod in Mods.missing) { if (Database.blocks.ContainsKey(missingmod.ToString())) { string modid = System.IO.Path.GetFileName(Database.blocks[missingmod.ToString()].id.ToString()); dynamic mod = new JObject(); mod.name = Database.blocks[missingmod.ToString()].Mod; mod.ok = "✔"; mod.author = "Unavailable, service couldn't find it"; mod.url = "http://steamcommunity.com/workshop/filedetails/?id=" + modid; if(!((JArray)Mods.mods).Contains(mod)) Mods.mods.Add(mod); } else { MessageBox.Show("couldn't find required mod for: " + missingmod.ToString()); } } foreach (dynamic mod in Mods.mods) { string fileId = mod.url.ToString().Substring(51); if (Database.usedmods.ContainsKey(fileId)) mod.ok = "✔"; else if(mod.ok == null) mod.ok = "X"; } new required_mods(Mods).Show(); stream.Dispose(); reader.Dispose(); } private void Notifications_Click(object sender, RoutedEventArgs e) { if (notificationWindow != null) notificationWindow.Close(); notificationWindow = new NotificationWindow(); notificationWindow.Owner = this; notificationWindow.Show(); } private void Settings_Click(object sender, RoutedEventArgs e) { if (settings != null) settings.Close(); settings = new Settings(this); settings.Owner = this; settings.Show(); } private void Help_Click(object sender, RoutedEventArgs e) { MessageBoxResult result = MessageBox.Show("Need help?","",MessageBoxButton.YesNo); if(result == MessageBoxResult.Yes) { System.Diagnostics.Process.Start("https://discord.gg/HXFqUqF"); } } private void About_Click(object sender, RoutedEventArgs e) { MessageBox.Show("A tool that provides lots of awesome features for you to make blueprint editing fun and easy!\n" + "\nMade by <NAME> (youtube.com/c.brentbatch)\n'Required Mods'-feature: help by Xesau/Aaron\n\n" + "And a BIG thanks to all the testers: @GamerGuy, @iceboundGlaceon, @lmaster, @the_killerbanana, @ThePiGuy24Gaming, @Remynem, @xXTBR and @zOmbie1919nl.\n\n" + "Version: " + Properties.Settings.Default.version,"About"); } private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if(TextBox_Description.Text == "Easter Egg") MessageBox.Show(@" / \" + "\n" + @" / _ ^\" + "\n" + @" | / \ |" + "\n" + @" || || _______" + "\n" + @" || || |\ \" + "\n" + @" || || ||\ \" + "\n" + @" || || || \ |" + "\n" + @" || || || \__/" + "\n" + @" || || || ||" + "\n" + @" \\_/ \_/ \_//" + "\n" + @" / _ _ \" + "\n" + @" / \" + "\n" + @" | O O |" + "\n" + @" | \ ___ / |" + "\n" + @" / \ \_/ / \" + "\n" + @" / ----- | --\ \" + "\n" + @" | \__/|\__/ \ |" + "\n" + @" \ |_|_| /" + "\n" + @" \_____ _____/" + "\n" + @" \ /" + "\n" + @" | |","Easter Egg!"); } private void ObjToBlueprint_Click(object sender, RoutedEventArgs e) { new ObjToBlueprint(this) { Owner = this }.Show(); } private void PixelArt_Click(object sender, RoutedEventArgs e) { MessageBox.Show("coming soon!","create 2d/3d pixelart, be able to import png"); } private void Enable_Mode_Click(object sender, RoutedEventArgs e) { MessageBox.Show("coming soon!","Enable Mods, make certain mods invisible in features"); } private void logicgenerator_Click(object sender, RoutedEventArgs e) { MessageBox.Show("coming soon!","Logic Diagram to Blueprint convertor"); } private void midiconvertor_Click(object sender, RoutedEventArgs e) { MessageBox.Show("coming soon!", "import MIDI track, convert to blueprint"); } private void mergecreation_Click(object sender, RoutedEventArgs e) { MessageBox.Show("coming soon!", "hold creation in ram, import new, merge"); } private void gif3d_Click(object sender, RoutedEventArgs e) { MessageBox.Show("coming soon!", "import multiple blueprints, craft a 3dgif with them"); } private void dupecreation_Click(object sender, RoutedEventArgs e) { MessageBox.Show("coming soon!", "stack/dupe creation in x/y/z"); } private void listBox_parts_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void label_desc_Click(object sender, RoutedEventArgs e) { var bc = new BrushConverter(); label_desc.Background = (Brush)bc.ConvertFrom("#FFFBD300"); label_parts.Background = (Brush)bc.ConvertFrom("#FF61737C"); TextBox_Description.Visibility = Visibility.Visible; listBox_parts.Visibility = Visibility.Hidden; } private void label_parts_Click(object sender, RoutedEventArgs e) { //thread: var bc = new BrushConverter(); label_desc.Background = (Brush)bc.ConvertFrom("#FF61737C"); label_parts.Background = (Brush)bc.ConvertFrom("#FFFBD300"); TextBox_Description.Visibility = Visibility.Hidden; listBox_parts.Visibility = Visibility.Visible; fillparts(); } Dictionary<string, Tuple<string, BitmapSource, int>> parts; public void fillparts() { var parts = BP.GetUsedPartsList(); if (parts != null) if (!parts.Equals(this.parts) || true) { new Thread(() => { List<Part_listitem> part_Listitems = new List<Part_listitem>(); foreach (var uuid in parts.Keys) { part_Listitems.Add(new Part_listitem() { name = parts[uuid].Item1, amount = parts[uuid].Item3.ToString(), uuid = uuid}); } this.Dispatcher.Invoke((Action)(() => { //listBox_parts.ItemsSource = null; listBox_parts.ItemsSource = part_Listitems; })); ImageToBitmapSourceConverter converter = new ImageToBitmapSourceConverter(); foreach (Part_listitem item in part_Listitems) { var bmp = Database.blocks[item.uuid].GetIcon(item.uuid); if(bmp != null) { item.icon = (BitmapSource)converter.Convert(bmp.Clone(),null, typeof(BitmapSource),null); item.emptysurface = 0; item.iconheight = 100; } } this.Dispatcher.Invoke((Action)(() => { listBox_parts.ItemsSource = null; listBox_parts.ItemsSource = part_Listitems; })); } ).Start(); this.parts = parts; } } } public class Part_listitem { public int emptysurface { get; set; } = 100; public int iconheight { get; set; } = 0; public BitmapSource icon { get; set; } = null; public string uuid { get; set; } public string name { get; set; } = "unnamed"; public string amount { get; set; } public override string ToString() { return name + "\n" + amount; } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for BlockPropertiesRAW.xaml /// </summary> public partial class BlockPropertiesRAW : Window { MainWindow mainwindow; HashSet<string> uuidsbackup = new HashSet<string>(); dynamic blueprint; public BlockPropertiesRAW(MainWindow mainwindow) { this.mainwindow = mainwindow; InitializeComponent(); Loadwindow w = new Loadwindow(); w.Show(); Update(); w.Close(); } private void button_help_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start("https://discord.gg/HXFqUqF"); } private void Filter_pos_TextChanged(object sender, RoutedEventArgs e) { TextBox t = (TextBox)sender; try { if (Convert.ToInt32(t.Text) >= 0) { } } catch { if (t.Text == "-") { t.Text = "-0"; t.Select(1, 1); } else { t.Text = "0"; t.Select(0, 1); } } if (this.IsLoaded) filterupdate(); } private void filter_type_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.IsLoaded) filterupdate(); } private void Filter_SET_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); filter_color.Text = PaintSelector.PaintColor; } private void color_TextChanged(object sender, TextChangedEventArgs e) { TextBox textbox_color = (TextBox)sender; if (textbox_color.Text.Length == 7) { try { var bc = new BrushConverter(); string color = "#FF" + textbox_color.Text.Substring(1); textbox_color.Background = (Brush)bc.ConvertFrom(color); if (textbox_color.Name == "filter_color") filtercolor = textbox_color.Text.Substring(1, 6).ToLower(); } catch { //MessageBox.Show("Please use the right format\n \"#123abc\" where 1-9,a-f (hex)"); textbox_color.Text = ""; } } else { var bc = new BrushConverter(); textbox_color.Background = (Brush)bc.ConvertFrom("#eeeeee"); if (textbox_color.Name == "filter_color") filtercolor = null; } if (textbox_color.Name == "filter_color") if (this.IsLoaded) filterupdate(); } public void Update()//new bp, items replaced, ... whatever { disableAll(); blueprint = BP.Blueprint; if (filter_x1.Text == "" || uuidsbackup != BP.GetUsedUuids()) { dynamic bounds = BP.GetBounds(); filter_x1.Text = bounds.minx.ToString(); filter_y1.Text = bounds.miny.ToString(); filter_z1.Text = bounds.minz.ToString(); filter_x2.Text = bounds.maxx.ToString(); filter_y2.Text = bounds.maxy.ToString(); filter_z2.Text = bounds.maxz.ToString(); } if (uuidsbackup != BP.GetUsedUuids())//fill the combobox once { filter_type.Items.Clear(); filter_type.Items.Add(new Item("any", "*")); foreach (string uuid in BP.GetUsedUuids()) { if (Database.blocks.ContainsKey(uuid)) filter_type.Items.Add(new Item(Database.blocks[uuid].Name.ToString(), uuid)); } uuidsbackup.Clear(); uuidsbackup.UnionWith(BP.GetUsedUuids()); filter_type.SelectedIndex = 0; } filterupdate(); } string filtercolor = null; Thread filter; private void filterupdate() { var l = new Loadwindow(); l.Show(); disableAll(); filter_output.Items.Clear(); if (Convert.ToInt32(filter_x1.Text) > Convert.ToInt32(filter_x2.Text)) { string h = filter_x1.Text; filter_x1.Text = filter_x2.Text; filter_x2.Text = h; } if (Convert.ToInt32(filter_y1.Text) > Convert.ToInt32(filter_y2.Text)) { string h = filter_y1.Text; filter_y1.Text = filter_y2.Text; filter_y2.Text = h; } if (Convert.ToInt32(filter_z1.Text) > Convert.ToInt32(filter_z2.Text)) { string h = filter_z1.Text; filter_z1.Text = filter_z2.Text; filter_z2.Text = h; } int x1 = Convert.ToInt32(filter_x1.Text); int y1 = Convert.ToInt32(filter_y1.Text); int z1 = Convert.ToInt32(filter_z1.Text); int x2 = Convert.ToInt32(filter_x2.Text); int y2 = Convert.ToInt32(filter_y2.Text); int z2 = Convert.ToInt32(filter_z2.Text); this.mainwindow.setMarker2((x1 + x2 + 0.0f) / 2, (y1 + y2 + 0.0f) / 2, (z1 + z2 + 0.0f) / 2, (x2 - x1), (y2 - y1), (z2 - z1)); string targetuuid = null; if (filter_type.SelectedIndex < 0) filter_type.SelectedIndex = 0; if (filter_type.SelectedIndex > 0) targetuuid = ((Item)filter_type.SelectedItem).UUID; //thread: if (filter != null && filter.IsAlive) filter.Abort(); filter = new Thread(() => { //filter correct blocks: int i = 0; foreach (dynamic body in blueprint.bodies) foreach (dynamic child in body.childs) { if (child.color.ToString().StartsWith("#")) child.color = child.color.ToString().Substring(1, 6).ToLower(); dynamic realpos = BP.getposandbounds(child); if ((filtercolor == null || filtercolor == child.color.ToString()) && (targetuuid == null || targetuuid == child.shapeId.ToString()) && (x1 <= (int)realpos.pos.x && (int)realpos.pos.x + (int)realpos.bounds.x <= x2) && (y1 <= (int)realpos.pos.y && (int)realpos.pos.y + (int)realpos.bounds.y <= y2) && (z1 <= (int)realpos.pos.z && (int)realpos.pos.z + (int)realpos.bounds.z <= z2)) { dynamic listitem = new JObject(); listitem.pos = new JObject(); listitem.pos.x = (int)realpos.pos.x; listitem.pos.y = (int)realpos.pos.y; listitem.pos.z = (int)realpos.pos.z; listitem.bounds = new JObject(); listitem.bounds.x = (int)realpos.bounds.x; listitem.bounds.y = (int)realpos.bounds.y; listitem.bounds.z = (int)realpos.bounds.z; listitem.blockname = "unnamed shape" + child.shapeId.ToString(); listitem.index = i; if (Database.blocks.ContainsKey(child.shapeId.ToString())) listitem.blockname = Database.blocks[child.shapeId.ToString()].Name; listitem.color = child.color.ToString(); listitem.child = child.ToString(); this.Dispatcher.Invoke((Action)(() => { filter_output.Items.Add(listitem); })); } i++; } if (blueprint.joints != null) foreach (dynamic child in blueprint.joints) { if (child.color.ToString().StartsWith("#")) child.color = child.color.ToString().Substring(1, 6).ToLower(); dynamic c = child; c.pos = child.posA; c.xaxis = child.xaxisA; c.zaxis = child.zaxisA; dynamic realpos = BP.getposandbounds(c); realpos.pos = child.posA; if (!(Convert.ToInt32(child.zaxis.ToString()) > 0 || !(realpos.bounds.x != 1 || realpos.bounds.y != 1 || realpos.bounds.z != 1))) { int zaxis = Convert.ToInt32(child.zaxis.ToString()); if (zaxis == -1) realpos.pos.x -= realpos.bounds.x - 1; if (zaxis == -2) realpos.pos.y -= realpos.bounds.y - 1; if (zaxis == -3) realpos.pos.z -= realpos.bounds.z - 1; } if ((filtercolor == null || filtercolor == child.color.ToString()) && (targetuuid == null || targetuuid == child.shapeId.ToString()) && (x1 <= (int)realpos.pos.x && (int)realpos.pos.x + (int)realpos.bounds.x <= x2) && (y1 <= (int)realpos.pos.y && (int)realpos.pos.y + (int)realpos.bounds.y <= y2) && (z1 <= (int)realpos.pos.z && (int)realpos.pos.z + (int)realpos.bounds.z <= z2)) { dynamic listitem = new JObject(); listitem.pos = new JObject(); listitem.pos.x = (int)realpos.pos.x; listitem.pos.y = (int)realpos.pos.y; listitem.pos.z = (int)realpos.pos.z; listitem.bounds = new JObject(); listitem.bounds.x = (int)realpos.bounds.x; listitem.bounds.y = (int)realpos.bounds.y; listitem.bounds.z = (int)realpos.bounds.z; listitem.blockname = "unnamed shape" + child.shapeId.ToString(); if (Database.blocks.ContainsKey(child.shapeId.ToString())) listitem.blockname = Database.blocks[child.shapeId.ToString()].Name; listitem.color = child.color.ToString(); listitem.child = child.ToString(); listitem.index = i; this.Dispatcher.Invoke((Action)(() => { filter_output.Items.Add(listitem); })); } i++; } }); filter.IsBackground = true; filter.Start(); l.Close(); } private void filter_output_SelectionChanged(object sender, SelectionChangedEventArgs e) { if(filter_output.SelectedIndex>=0) { dynamic selected = ((dynamic)filter_output.SelectedItem); string child = selected.child.ToString(); this.mainwindow.setMarker(Convert.ToInt32(selected.pos.x) + (Convert.ToDouble(selected.bounds.x) / 2), Convert.ToInt32(selected.pos.y) + (Convert.ToDouble(selected.bounds.y) / 2), Convert.ToDouble(selected.pos.z) + (Convert.ToDouble(selected.bounds.z) / 2)); Edit_child.Text = child; button_render.IsEnabled = true; } } private void button_render_Click(object sender, RoutedEventArgs e) { //string blueprintstr = blueprint.ToString(); //string child = ((dynamic)filter_output.SelectedItem).child.ToString(); Loadwindow w = new Loadwindow(); try { w.Show(); dynamic child = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(Edit_child.Text); int i = 0; int index = ((dynamic)filter_output.SelectedItem).index; for (int j=0; j<blueprint.bodies.Count; j++) for(int k=0; k<blueprint.bodies[j].childs.Count; k++) { if (index == i) { blueprint.bodies[j].childs[k] = child; BP.setblueprint(blueprint); BP.Description.description = BP.Description.description + "\n++Applied RAW changes"; mainwindow.RenderBlueprint(); //Update(); w.Close(); MessageBox.Show("edit successful"); filterupdate(); return; } i++; } for (int j = 0; j < blueprint.joints.Count; j++) { if (index == i) { blueprint.joints[j] = child; BP.setblueprint(blueprint); BP.Description.description = BP.Description.description + "\n++Applied RAW changes"; mainwindow.RenderBlueprint(); //Update(); w.Close(); MessageBox.Show("edit successful"); filterupdate(); return; } i++; } w.Close(); MessageBox.Show("edit UNsuccessfull :("); } catch (Exception exc) { w.Close(); MessageBox.Show(exc.Message); } } private void disableAll() { Edit_child.Text = ""; button_render.IsEnabled = false; this.mainwindow.Marker = null; mainwindow.Image_blueprint.DataContext = ""; mainwindow.Image_blueprint.DataContext = mainwindow; } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { base.OnClosing(e); this.mainwindow.Marker = null; this.mainwindow.Marker2 = null; mainwindow.Image_blueprint.DataContext = null; mainwindow.Image_blueprint.DataContext = mainwindow; this.mainwindow.helix.ResetCamera(); } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for SwapBlocksWindow.xaml /// </summary> public partial class SwapBlocksWindow : Window { MainWindow window; private dynamic uuidsbackup; private dynamic blockstoreplace; private dynamic replacebyblocks; public SwapBlocksWindow(MainWindow window) { this.window = window; InitializeComponent(); Update(); } public void Update() { if (uuidsbackup != BP.GetUsedUuids()) { blockstoreplace = new JArray(); replacebyblocks = new JArray(); foreach (string uuid in BP.GetUsedUuids()) { if (Database.blocks.ContainsKey(uuid)) { dynamic blok = new JObject(); blok.name = Database.blocks[uuid].Name; blok.bounds = (Database.blocks[uuid] is Part)? ((Part)Database.blocks[uuid]).GetBoundsDynamic() : null; blok.uuid = uuid; blockstoreplace.Add(blok); } } this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application comboBox_old.Items.Clear(); comboBox_new.Items.Clear(); })); foreach (dynamic blok in blockstoreplace) { this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application comboBox_old.Items.Add(blok.name); })); } } uuidsbackup = BP.GetUsedUuids(); } private void textBox_color1_TextChanged(object sender, TextChangedEventArgs e) { TextBox textbox_color = (TextBox)sender; if (textbox_color.Text.Length == 7) { try { var bc = new BrushConverter(); string color = "#FF" + textbox_color.Text.Substring(1); textbox_color.Background = (Brush)bc.ConvertFrom(color); } catch { MessageBox.Show("Please use the right format\n \"#123abc\" where 1-9,a-f (hex)"); } } else { var bc = new BrushConverter(); textbox_color.Background = (Brush)bc.ConvertFrom("#eeeeee"); } } private void comboBox_old_SelectionChanged(object sender, SelectionChangedEventArgs e) { replacebyblocks = new JArray(); comboBox_new.Items.Clear(); if(comboBox_old.SelectedIndex>=0) { dynamic selectedblok = blockstoreplace[comboBox_old.SelectedIndex]; var keys = Database.blocks.Keys; try { foreach (string uuid in keys) { dynamic bounds = null; if (Database.blocks[uuid] is Part) { bounds = ((Part)Database.blocks[uuid]).GetBoundsDynamic(); } //if (bounds == null || (selectedblok.bounds != null && bounds == selectedblok.bounds)) { dynamic block = new JObject(); block.name = Database.blocks[uuid].Name; block.bounds = bounds; block.uuid = uuid; replacebyblocks.Add(block); comboBox_new.Items.Add(block.name); } } } catch { } } } private void comboBox_new_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void button_set_Click(object sender, RoutedEventArgs e) { this.window.openpaintpicker(); textBox_color1.Text = PaintSelector.PaintColor; } private void button_swap_Click(object sender, RoutedEventArgs e) { if(comboBox_new.SelectedIndex>-1&& comboBox_old.SelectedIndex > -1) { dynamic blocktoreplace = blockstoreplace[comboBox_old.SelectedIndex]; dynamic replacebyblock = replacebyblocks[comboBox_new.SelectedIndex]; int amountchanged = 0; dynamic blueprint = BP.Blueprint; foreach (dynamic body in blueprint.bodies) foreach (dynamic child in body.childs) { if (child.shapeId == blocktoreplace.uuid && (textBox_color1.Text.ToString().ToLower() == child.color.ToString().ToLower() || textBox_color1.Text.ToString().ToLower() == "#"+child.color.ToString().ToLower() || textBox_color1.Text == "" || textBox_color1.Text =="#")) { if (child.bounds == null) { child.bounds = blocktoreplace.bounds; } child.shapeId = replacebyblock.uuid; amountchanged++; } } string message = "++ " + amountchanged + " " + blocktoreplace.name + " are now changed to " + replacebyblock.name; MessageBox.Show(message); if (amountchanged > 0) { BP.setblueprint(blueprint); BP.Description.description = BP.Description.description + "\n" + message; window.RenderBlueprint(); } } } //get bounds from private dynamic getbounds(dynamic part) { dynamic bounds = null; if (part.box != null) { return part.box; } if (part.hull != null) { bounds = new JObject(); bounds.x = part.hull.x; bounds.y = part.hull.y; bounds.z = part.hull.z; return bounds; } if (part.cylinder != null) { if (part.cylinder.axis.ToString().ToLower() == "x") { bounds = new JObject(); bounds.x = part.cylinder.depth; bounds.y = part.cylinder.diameter * 2; bounds.z = part.cylinder.diameter * 2; return bounds; } else if (part.cylinder.axis.ToString().ToLower() == "y") { bounds = new JObject(); bounds.x = part.cylinder.diameter * 2; bounds.y = part.cylinder.depth; bounds.z = part.cylinder.diameter * 2; return bounds; } else if (part.cylinder.axis.ToString().ToLower() == "z") { bounds = new JObject(); bounds.x = part.cylinder.diameter * 2; bounds.y = part.cylinder.diameter * 2; bounds.z = part.cylinder.depth; return bounds; } } return bounds; } } } <file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for AdvancedConnections.xaml /// </summary> public partial class AdvancedConnections : Window { MainWindow mainwindow; private dynamic uuidsbackup; HashSet<Connectable> connectable_UUIDS = new HashSet<Connectable>(); //List<Item> ItemList; public AdvancedConnections(MainWindow window) { this.mainwindow = window; InitializeComponent(); this.Update(); } public void Update() { if(uuidsbackup != BP.GetUsedUuids()) { connectable_UUIDS.Clear(); foreach (string uuid in BP.GetUsedUuids()) { if (Database.blocks.ContainsKey(uuid) && Database.blocks[uuid] is Part && (Database.blocks[uuid] as Part).IsConnectable) { connectable_UUIDS.Add(new Connectable(uuid.ToString(), ((Part)Database.blocks[uuid]).GetBoundsDynamic(), Database.blocks[uuid].Name)); } } this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application comboBox_items1.Items.Clear(); comboBox_items2.Items.Clear(); })); foreach (Connectable i in connectable_UUIDS) { this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application comboBox_items1.Items.Add(i); comboBox_items2.Items.Add(i); })); } } uuidsbackup = BP.GetUsedUuids(); } private void TextBox_color_TextChanged(object sender, TextChangedEventArgs e) { this.Update(); TextBox textbox_color = (TextBox)sender; if (textbox_color.Text.Length == 7) { try { var bc = new BrushConverter(); string color = "#FF" + textbox_color.Text.Substring(1); textbox_color.Background = (Brush)bc.ConvertFrom(color); } catch { MessageBox.Show("Please use the right format\n \"#123abc\" where 1-9,a-f (hex)"); } } else { var bc = new BrushConverter(); textbox_color.Background = (Brush)bc.ConvertFrom("#eeeeee"); } } private void Button3_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); textBox_color1.Text = PaintSelector.PaintColor; } private void Button3_Copy_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); textBox_color2.Text = PaintSelector.PaintColor; } private void Button_Click(object sender, RoutedEventArgs e) { this.Update(); PaintSelector p = new PaintSelector { Owner = this.mainwindow }; p.Show(); } public struct Controller { public int id; public int x; public int y; public int z; public string color; public string uuid; public List<int> connections; } private void WireIt(dynamic a, string sourcecolor, string destinationcolor, string sourcetype, string destinationtype, int offsetx, int offsety, int offsetz, string offsetcolor ) { Dictionary<int,Controller> controllers = new Dictionary<int, Controller>(); bool dirx = checkBox_X.IsChecked == true; bool diry = checkBox_Y.IsChecked == true; bool dirz = checkBox_Z.IsChecked == true; bool self = checkBox_0.IsChecked == true; bool matchoffset = MatchOffset.IsChecked == true; //safemode enable? Dictionary<string, List<int>> filtercrap = new Dictionary<string, List<int>>();//can be glitchwelded //x.y.z = int foreach (dynamic body in BP.Blueprint.bodies) foreach (dynamic child in body.childs) if (child.controller != null) { dynamic rpos = BP.getposandbounds(child); int x = Convert.ToInt32(rpos.pos.x.ToString()); int y = Convert.ToInt32(rpos.pos.y.ToString()); int z = Convert.ToInt32(rpos.pos.z.ToString()); string color = child.color.ToString().ToLower(); if (color.StartsWith("#")) color = color.Substring(1, 6); int id = Convert.ToInt32(child.controller.id.ToString()); controllers.Add(id,new Controller {id= id, x = x, y = y, z = z, color = color, uuid = child.shapeId.ToString(), connections = new List<int>() }); string key = x.ToString() + "." + y.ToString() + "." + z.ToString(); if (!filtercrap.ContainsKey(key)) filtercrap.Add(key, new List<int> { id }); else filtercrap[key].Add(id); } if(matchoffset) {//filter only the block with color,type,offset from source foreach (Controller source in controllers.Values) if ((sourcecolor == null || sourcecolor == source.color) && (sourcetype == source.uuid)) foreach (Controller destination in controllers.Values) if((destinationcolor == null || destinationcolor == destination.color) && ( destinationtype == null || destinationtype == destination.uuid) && (self || !source.Equals(destination)) && (dirx || source.x+offsetx == destination.x) && (diry || source.y + offsety == destination.y) && (dirz || source.z + offsetz == destination.z)) { source.connections.Add(destination.id); } } else//filter all blocks no offset with col&type, then get the ones offset from them (any color, any type) foreach (Controller source in controllers.Values) if ((sourcecolor == null || sourcecolor == source.color) && (sourcetype == source.uuid)) foreach (Controller destination in controllers.Values) if ((destinationcolor == null || destinationcolor == destination.color) && (destinationtype == null || destinationtype == destination.uuid) && (self || !source.Equals(destination)) && (dirx || source.x == destination.x) && (diry || source.y == destination.y) && (dirz || source.z == destination.z)) { string key = (offsetx+ destination.x).ToString() + "." + (offsety + destination.y).ToString() + "." + (offsetz + destination.z).ToString(); //get block offset from destination if (filtercrap.ContainsKey(key)) source.connections.AddRange(filtercrap[key]); //source.connections.Add(destination.id); } //apply controllers to bp: int amountwired = 0; foreach (dynamic body in BP.Blueprint.bodies) foreach (dynamic child in body.childs) if (child.controller != null && controllers.ContainsKey(Convert.ToInt32(child.controller.id.ToString()))) { int id = Convert.ToInt32(child.controller.id.ToString()); if (child.controller.controllers == null) child.controller.controllers = new JArray(); if(controllers[id].connections != null) foreach (int destid in controllers[id].connections) { child.controller.controllers.Add(new JObject { ["id"] = destid }); amountwired++; } } new System.Threading.Thread(new System.Threading.ThreadStart(() => { MessageBox.Show("Successfully made " + amountwired + " connections! :D"); })).Start(); if (amountwired > 0) { mainwindow.TextBox_Description.Text += "\n--> " + amountwired + " connections made\n"; BP.Description.description = BP.Description.description + "\n--> " + amountwired + " connections made\n"; } mainwindow.RenderWires(); #region somecode /* dynamic controllersold = new JObject(); dynamic sources = new JObject(); foreach (dynamic body in blueprint.bodies) foreach (dynamic child in body.childs) { if (child.controller != null) { dynamic rpos = BP.getposandbounds(child); string x = rpos.pos.x.ToString(); string y = rpos.pos.y.ToString(); string z = rpos.pos.z.ToString(); string color = child.color.ToString(); if (color.StartsWith("#")) color = color.Substring(1, 6); //child.shapeId.ToString() // Convert.ToInt32(child.controller.id.ToString()) dynamic controller = new JObject { [x] = new JObject { [y] = new JObject { [z] = new JObject { [child.color.ToString()] = new JObject { [child.shapeId.ToString()] = new JObject { [color] = Convert.ToInt32(child.controller.id.ToString()) } } } } } }; controllersold.Merge(controller); if ((sourcecolor == null || sourcecolor == color) && (sourcetype == null || sourcetype == child.shapeId.ToString())) sources.Merge(controller); } } dynamic result = new JObject();//result.DeepClone(); //Newtonsoft.Json.Linq.JProperty // keypair if (matchoffset) //ON {//filter only the block with color,type,offset from source dynamic searchfrom = controllersold.DeepClone(); if (dirx) { result = searchfrom; } else { foreach(JProperty Jprop in sources) //Jprop.Name = "X" { string coord = (Convert.ToInt32(Jprop.Name) + offsetx).ToString(); if (searchfrom[coord] != null) { result.Merge(new JObject { [coord] = searchfrom[coord] }); } } } searchfrom = result.DeepClone(); result = new JObject(); if (diry) { result = searchfrom; } else { foreach (JProperty JpropSource in sources) { string coord = (Convert.ToInt32(JpropSource.Name) + offsetx).ToString(); if (searchfrom[coord] != null) { result.Merge(new JObject { [coord] = searchfrom[coord] }); } } } } else {//filter all blocks no offset with col&type, then get the ones offset from them (any color, any type) } foreach (dynamic body in blueprint.bodies) foreach(dynamic child in body.childs) { if(child.controller != null && (sourcetype == null || sourcetype == child.shapeId.ToString())) { string color = child.color.ToString(); if (color.StartsWith("#")) color = color.Substring(1, 6); if(sourcecolor == null || color == sourcecolor) { dynamic rpos = BP.getposandbounds(child); int x = Convert.ToInt32(rpos.pos.x.ToString()); int y = Convert.ToInt32(rpos.pos.y.ToString()); int z = Convert.ToInt32(rpos.pos.z.ToString()); } } } if (blueprint == "")//false using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.scrapshitConnectionString)) { //conn.ConnectionString = "MyDB";c int i = 0; conn.Open(); using (SqlCommand insertCommand = new SqlCommand("DELETE FROM Connections", conn)) { insertCommand.ExecuteNonQuery(); } foreach (dynamic body in blueprint.bodies) foreach (dynamic child in body.childs) { if(child.controller != null) { dynamic rpos = BP.getposandbounds(child); string x = rpos.pos.x.ToString(); string y = rpos.pos.y.ToString(); string z = rpos.pos.z.ToString(); string color = child.color.ToString(); if (color.StartsWith("#")) color = color.Substring(1, 6); using (SqlCommand insertCommand = new SqlCommand("INSERT INTO Connections (Controller_Id, posx, posy, posz, color, uuid) VALUES (@controllerid, @x, @y, @z, @color, @uuid)", conn)) { insertCommand.Parameters.AddWithValue("@controllerid", Convert.ToInt32(child.controller.id.ToString())); insertCommand.Parameters.AddWithValue("@x", x); insertCommand.Parameters.AddWithValue("@y", y); insertCommand.Parameters.AddWithValue("@z", z); insertCommand.Parameters.AddWithValue("@color", color); insertCommand.Parameters.AddWithValue("@uuid", child.shapeId.ToString()); try { i+= insertCommand.ExecuteNonQuery(); } catch (Exception e) { MessageBox.Show(e.Message); } } } } //SqlCommand cmd = new SqlCommand("SELECT * FROM Connections WHERE login = @login", conn); //find all sources "SELECT * AS 'Sources' FROM Connections" + "WHERE color = @sourcecolor AND uuid = @sourceuuid" //find all dests? //string cmd = "SELECT * FROM Description" //cmd+= "Where uuid = @uuid" //cmd+= @"AND color = @color" //all with uuid x / other / all other (match offset block color) //all with color / all other / all other (match offset block color) //all with x + offsetx / other(all in this dir) /x //all with y + offsety / other / y //all with z + offsetz /other / z //exclude self wire? //if match offset block color search offset from x y z found blocks (from all, check all current found + offset with color x and type x) } //<x, y, z, color, shapeId>, controllerid Dictionary<Tuple<int, int, int, string, string>, int> dict = new Dictionary<Tuple<int, int, int, string, string>, int>(); Dictionary<int, Dictionary<int, Dictionary<int, int>>> testdict = new Dictionary<int, Dictionary<int, Dictionary<int, int>>>(); //testdict[5][2][3] = 5; */ #endregion } //Wire it! private void Button1_Click(object sender, RoutedEventArgs e) {//WIRE IT! if(comboBox_items1.SelectedIndex!=-1 && comboBox_items2.SelectedIndex != -1 && BP.Blueprint != null) { dynamic backupbp = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(BP.Blueprint.ToString()); string sourcecolor = textBox_color1.Text.ToLower(); string destinationcolor = textBox_color2.Text.ToLower(); Connectable sourceblock = (Connectable) comboBox_items1.SelectedItem; Connectable destinationblock = (Connectable) comboBox_items2.SelectedItem; int offsetx = Convert.ToInt32(textBox_X.Text); int offsety = Convert.ToInt32(textBox_Y.Text); int offsetz = Convert.ToInt32(textBox_Z.Text); if (sourcecolor.Length == 7) sourcecolor = sourcecolor.Substring(1, 6); else sourcecolor = null; if (destinationcolor.Length == 7) destinationcolor = destinationcolor.Substring(1, 6); else destinationcolor = null; //try { WireIt(null, sourcecolor, destinationcolor, sourceblock.UUID, destinationblock.UUID, offsetx, offsety, offsetz, destinationcolor); } //catch (Exception ex) { // MessageBox.Show(ex.Message + "\n\n Blueprint connections abrupted\nrestoring blueprint", "ERROR"); //BP.setblueprint(backupbp); } if(false) { #region oldcode //list all destionationblocks and their ID's dynamic destids = new JObject(); int minx = 10000, maxx = -10000, miny = 10000, maxy = -10000, minz = 10000, maxz = -10000; //loop over all blocks: foreach (dynamic body in BP.Blueprint.bodies) { foreach(dynamic child in body.childs) { if(child.shapeId.Value.ToLower() == destinationblock.UUID.ToLower() /*&& (child.color.Value.ToLower() == destinationcolor.ToLower() || "#"+child.color.Value.ToLower() == destinationcolor.ToLower() || destinationcolor == "" || destinationcolor == "#")*/) { dynamic dest = BP.getposandbounds(child);//outputs corrected child (default rotation, correct position) string x = dest.pos.x.ToString(); string y = dest.pos.y.ToString(); string z = dest.pos.z.ToString(); if (destids[x] == null) destids[x] = new JObject(); if (destids[x][y] == null) destids[x][y] = new JObject(); if (destids[x][y][z] == null) destids[x][y][z] = new JObject(); if (destids[x][y][z].ids == null) destids[x][y][z].ids = new JArray(); dynamic id = new JObject(); id.id = child.controller.id; destids[x][y][z].ids.Add(id); destids[x][y][z].color = child.color; //get whole creation bounds: if (dest.pos.x < minx) minx = dest.pos.x; if (dest.pos.x > maxx) maxx = dest.pos.x; if (dest.pos.y < miny) miny = dest.pos.y; if (dest.pos.y > maxy) maxy = dest.pos.y; if (dest.pos.z < minz) minz = dest.pos.z; if (dest.pos.z > maxz) maxz = dest.pos.z; /* {//test if (destids[x + "." + y + "." + z] == null) destids[x + "." + y + "." + z] = new JArray(); dynamic blockproperties = new JObject(); blockproperties.id = new JObject(); blockproperties.id.id = child.controller.id; blockproperties.uuid = child.shapeId; if (child.color.ToString().StartsWith("#")) child.color = child.color.ToString().subString(1); blockproperties.color = child.color; destids[x + "." + y + "." + z].Add(blockproperties); }*/ } } } if(BP.Blueprint.joints != null) foreach(dynamic child in BP.Blueprint.joints) { if (child.shapeId.Value.ToLower() == destinationblock.UUID.ToLower() /*&& (child.color.Value.ToLower() == destinationcolor.ToLower() || "#"+child.color.Value.ToLower() == destinationcolor.ToLower() || destinationcolor == "" || destinationcolor == "#")*/) { dynamic dest = (child);//outputs corrected child (default rotation, correct position) string x = dest.pos.x.ToString(); string y = dest.pos.y.ToString(); string z = dest.pos.z.ToString(); if (destids[x] == null) destids[x] = new JObject(); if (destids[x][y] == null) destids[x][y] = new JObject(); if (destids[x][y][z] == null) destids[x][y][z] = new JObject(); if (destids[x][y][z].ids == null) destids[x][y][z].ids = new JArray(); dynamic id = new JObject(); id.id = child.controller.id; destids[x][y][z].ids.Add(id); destids[x][y][z].color = child.color; //get whole creation bounds: if (dest.pos.x < minx) minx = dest.pos.x; if (dest.pos.x > maxx) maxx = dest.pos.x; if (dest.pos.y < miny) miny = dest.pos.y; if (dest.pos.y > maxy) maxy = dest.pos.y; if (dest.pos.z < minz) minz = dest.pos.z; if (dest.pos.z > maxz) maxz = dest.pos.z; } } int amountwired=0; try { //can be improved! foreach(dynamic body in BP.Blueprint.bodies) foreach(dynamic child in body.childs) if (child.shapeId.Value.ToLower() == sourceblock.UUID.ToLower() && (child.color.Value.ToLower() == sourcecolor.ToLower() || "#" + child.color.Value.ToLower() == sourcecolor.ToLower() || sourcecolor == "" || sourcecolor == "#")) {//COLOR AND UUID CORRECT, FURTHER WIRING PROCESS: dynamic source = BP.getposandbounds(child);//outputs corrected child (default rotation, correct position) string x = source.pos.x.ToString(); string y = source.pos.y.ToString(); string z = source.pos.z.ToString(); if (checkBox_X.IsChecked == false) { minx = source.pos.x; maxx = source.pos.x;//bounds? } if (checkBox_Y.IsChecked == false) { miny = source.pos.y; maxy = source.pos.y; } if (checkBox_Z.IsChecked == false) { minz = source.pos.z; maxz = source.pos.z; } string color = child.color.ToString(); if (color.StartsWith("#")) color.Substring(1, 6); for (int i = minx; i <= maxx; i++) if (destids[i.ToString()] != null) for (int j = miny; j <= maxy; j++) if (destids[i.ToString()][j.ToString()] != null) for (int k = minz; k <= maxz; k++) if (destids[i.ToString()][j.ToString()][k.ToString()] != null) if (destids[i.ToString()][j.ToString()][k.ToString()].color.ToString().ToLower() == destinationcolor.ToLower() || "#" + destids[i.ToString()][j.ToString()][k.ToString()].color.ToString().ToLower() == destinationcolor.ToLower() || destinationcolor == "" || destinationcolor == "#") if (destids[(i+ Convert.ToInt32(textBox_X.Text)).ToString()] !=null && destids[(i + Convert.ToInt32(textBox_X.Text)).ToString()][(j + Convert.ToInt32(textBox_Y.Text)).ToString()] != null && destids[(i + Convert.ToInt32(textBox_X.Text)).ToString()][(j + Convert.ToInt32(textBox_Y.Text)).ToString()][(k + Convert.ToInt32(textBox_Z.Text)).ToString()] != null) foreach (dynamic id in destids[(i + Convert.ToInt32(textBox_X.Text)).ToString()][(j + Convert.ToInt32(textBox_Y.Text)).ToString()][(k + Convert.ToInt32(textBox_Z.Text)).ToString()].ids) if (!(checkBox_0.IsChecked == false && child.controller.id == id.id)) { if (child.controller.controllers == null) child.controller.controllers = new JArray(); child.controller.controllers.Add(id); amountwired++; } /* for (int i = minx; i <= maxx; i++) for (int j = miny; j <= maxy; j++) for (int k = minz; k <= maxz; k++) if ( destids[i.ToString() + "." + j.ToString() + "." + k.ToString()] != null && destids[(i + Convert.ToInt32(textBox_X.Text)).ToString() + "." + (j + Convert.ToInt32(textBox_Y.Text)).ToString() + "." + (k + Convert.ToInt32(textBox_Z.Text)).ToString()] != null ) foreach ( dynamic destblocknooffset in destids[i.ToString() + "." + j.ToString() + "." + k.ToString()]) if((destblocknooffset.color.ToLower() == destinationcolor.ToLower() || destinationcolor == "" || destinationcolor == "#")) foreach(dynamic blockoffset in destids[(i + Convert.ToInt32(textBox_X.Text)).ToString() + "." + (j + Convert.ToInt32(textBox_Y.Text)).ToString() + "." + (k + Convert.ToInt32(textBox_Z.Text)).ToString()]) if(!(checkBox_0.IsChecked == false && child.controller.id == blockoffset.id.id)) { if (child.controller.controllers == null) child.controller.controllers = new JArray(); child.controller.controllers.Add(blockoffset.id); amountwired++; } */ mainwindow.Image_blueprint.DataContext = null; mainwindow.Image_blueprint.DataContext = mainwindow; } new System.Threading.Thread(new System.Threading.ThreadStart(() => { if(Properties.Settings.Default.wires) MessageBox.Show("Successfully made " + amountwired + " connections! :D\n\n'Wires'-feature will render wires upon load from openwindow->needs work"); else MessageBox.Show("Successfully made " + amountwired + " connections! :D"); })).Start(); //window.UpdateOpenedBlueprint(); if (amountwired>0) BP.Description.description = BP.Description.description + "\n--> " + amountwired + " connections made between " + sourcecolor + " " + sourceblock.name + " and " + destinationcolor + " " + destinationblock.name; } catch(Exception exception) { MessageBox.Show(exception.Message+"\n\n Blueprint connections abrupted\nrestoring blueprint","ERROR"); BP.setblueprint(backupbp); } #endregion } } else { MessageBox.Show("Something went wrong!\nno harm done"); } } private void Button2_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start("https://youtu.be/glLgQemUS2I?t=270"); }//help private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox t = (TextBox)sender; try { if (Convert.ToInt32(t.Text) >= 0) { } } catch { if (t.Text == "-") { t.Text = "-0"; t.Select(1, 1); } else { t.Text = "0"; t.Select(0, 1); } } } // } public class Connectable { public string name = "unnamed block"; public string UUID; public dynamic bounds; public Connectable(string UUID, dynamic bounds) { this.UUID = UUID; this.bounds = bounds; } public Connectable(string UUID, dynamic bounds, string name) { this.UUID = UUID; this.bounds = bounds; this.name = name; } public override string ToString() { return name; } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using static Advanced_Blueprint_Tools.Part; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for AreaProperties.xaml /// </summary> public partial class AreaProperties : Window { MainWindow mainwindow; HashSet<string> uuidsbackup = new HashSet<string>(); public AreaProperties(MainWindow mainwindow) { this.mainwindow = mainwindow; InitializeComponent(); Loadwindow w = new Loadwindow(); w.Show(); Update(); w.Close(); } private void Button_Help_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start("https://discord.gg/HXFqUqF"); } private void Filter_pos_TextChanged(object sender, RoutedEventArgs e) { TextBox t = (TextBox)sender; try { if (Convert.ToInt32(t.Text) >= 0) { } } catch { if (t.Text == "-") { t.Text = "-0"; t.Select(1, 1); } else { t.Text = "0"; t.Select(0, 1); } } if (this.IsLoaded) { int x1 = Convert.ToInt32(filter_x1.Text); int y1 = Convert.ToInt32(filter_y1.Text); int z1 = Convert.ToInt32(filter_z1.Text); int x2 = Convert.ToInt32(filter_x2.Text); int y2 = Convert.ToInt32(filter_y2.Text); int z2 = Convert.ToInt32(filter_z2.Text); this.mainwindow.setMarker2((x1 + x2 + 0.0f) / 2, (y1 + y2 + 0.0f) / 2, (z1 + z2 + 0.0f) / 2, (x2 - x1), (y2 - y1), (z2 - z1)); } } private void filter_type_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.IsLoaded) filterupdate(); } private void Filter_SET_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); filter_color.Text = PaintSelector.PaintColor; } private void color_TextChanged(object sender, TextChangedEventArgs e) { TextBox textbox_color = (TextBox)sender; if (textbox_color.Text.Length == 7) { try { var bc = new BrushConverter(); string color = "#FF" + textbox_color.Text.Substring(1); textbox_color.Background = (Brush)bc.ConvertFrom(color); if (textbox_color.Name == "filter_color") filtercolor = textbox_color.Text; } catch { //MessageBox.Show("Please use the right format\n \"#123abc\" where 1-9,a-f (hex)"); textbox_color.Text = ""; } } else { var bc = new BrushConverter(); textbox_color.Background = (Brush)bc.ConvertFrom("#eeeeee"); if (textbox_color.Name == "filter_color") filtercolor = null; } if (textbox_color.Name == "filter_color") if (this.IsLoaded) filterupdate(); } public void Update()//new bp, items replaced, ... whatever { disableAll(); if (filter_x1.Text == "" || uuidsbackup != BP.GetUsedUuids()) { dynamic bounds = BP.GetBounds(); filter_x1.Text = bounds.minx.ToString(); filter_y1.Text = bounds.miny.ToString(); filter_z1.Text = bounds.minz.ToString(); filter_x2.Text = bounds.maxx.ToString(); filter_y2.Text = bounds.maxy.ToString(); filter_z2.Text = bounds.maxz.ToString(); } if (uuidsbackup != BP.GetUsedUuids() | true)//fill the combobox once { filter_type.Items.Clear(); filter_type.Items.Add(new Item("any","*")); foreach (string uuid in BP.GetUsedUuids()) { if (Database.blocks.ContainsKey(uuid)) filter_type.Items.Add(new Item(Database.blocks[uuid].Name.ToString(), uuid)); } uuidsbackup.Clear(); uuidsbackup.UnionWith(BP.GetUsedUuids()); filter_type.SelectedIndex = 0; } filterupdate(); } private string filtercolor = null; private void filterupdate() // enable specific boxes { disableAll(); if (filter_type.SelectedIndex>0) { string uuid = ((Item)filter_type.SelectedItem).UUID.ToString(); if(Database.blocks.ContainsKey(uuid) && Database.blocks[uuid] is Part) { properties property = ((Part)Database.blocks[uuid]).GetProperty(); if (property == properties.sensor) Edit_sensor.Visibility = Visibility.Visible; if (property == properties.spotlight) Edit_lamp.Visibility = Visibility.Visible; if (property == properties.logic) Edit_gate.Visibility = Visibility.Visible; if (property == properties.timer) Edit_Timer.Visibility = Visibility.Visible; } } Edit_general.Visibility = Visibility.Visible; int x1 = Convert.ToInt32(filter_x1.Text); int y1 = Convert.ToInt32(filter_y1.Text); int z1 = Convert.ToInt32(filter_z1.Text); int x2 = Convert.ToInt32(filter_x2.Text); int y2 = Convert.ToInt32(filter_y2.Text); int z2 = Convert.ToInt32(filter_z2.Text); this.mainwindow.setMarker2((x1 + x2 + 0.0f) / 2, (y1 + y2 + 0.0f) / 2, (z1 + z2 + 0.0f) / 2, (x2 - x1), (y2 - y1), (z2 - z1)); button_render.IsEnabled = true; } private void button_render_Click(object sender, RoutedEventArgs e) { //apply changes if (Convert.ToInt32(filter_x1.Text) > Convert.ToInt32(filter_x2.Text)) { string h = filter_x1.Text; filter_x1.Text = filter_x2.Text; filter_x2.Text = h; } if (Convert.ToInt32(filter_y1.Text) > Convert.ToInt32(filter_y2.Text)) { string h = filter_y1.Text; filter_y1.Text = filter_y2.Text; filter_y2.Text = h; } if (Convert.ToInt32(filter_z1.Text) > Convert.ToInt32(filter_z2.Text)) { string h = filter_z1.Text; filter_z1.Text = filter_z2.Text; filter_z2.Text = h; } int x1 = Convert.ToInt32(filter_x1.Text); int y1 = Convert.ToInt32(filter_y1.Text); int z1 = Convert.ToInt32(filter_z1.Text); int x2 = Convert.ToInt32(filter_x2.Text); int y2 = Convert.ToInt32(filter_y2.Text); int z2 = Convert.ToInt32(filter_z2.Text); string targetuuid = null; if (filter_type.SelectedIndex < 0) filter_type.SelectedIndex = 0; if (filter_type.SelectedIndex > 0) targetuuid = ((Item)filter_type.SelectedItem).UUID; dynamic blueprint = BP.Blueprint; if (filtercolor != null&& filtercolor.StartsWith("#")) filtercolor = filtercolor.Substring(1, 6).ToLower(); foreach(dynamic body in blueprint.bodies) foreach(dynamic child in body.childs) { if (child.color.ToString().StartsWith("#")) child.color = child.color.ToString().Substring(1, 6).ToLower(); dynamic realpos = BP.getposandbounds(child); if((filtercolor == null || filtercolor == child.color.ToString()) && (targetuuid == null || targetuuid == child.shapeId.ToString()) && (x1 <= (int)realpos.pos.x && (int)realpos.pos.x + (int)realpos.bounds.x <= x2) && (y1 <= (int)realpos.pos.y && (int)realpos.pos.y + (int)realpos.bounds.y <= y2) && (z1 <= (int)realpos.pos.z && (int)realpos.pos.z + (int)realpos.bounds.z <= z2) ) { child.pos.x = child.pos.x + Convert.ToInt32(new_x.Text); child.pos.y = child.pos.y + Convert.ToInt32(new_y.Text); child.pos.z = child.pos.z + Convert.ToInt32(new_z.Text); if (new_color.Text != "") child.color = new_color.Text.ToString().Substring(1, 6); if (Edit_gate.IsVisible && new_gatemode.SelectedIndex > 0) child.controller.mode = new_gatemode.SelectedIndex - 1; if(Edit_lamp.IsVisible) { if (new_luminance.Text != "") child.controller.luminance = Convert.ToInt32(new_luminance.Text); if (new_coneangle.Text != "") child.controller.coneAngle = Convert.ToInt32(new_coneangle.Text); if (new_lampcolor.Text != "") child.controller.color = new_lampcolor.Text; } if(Edit_sensor.IsVisible && (new_sensorrange.Text != "" || new_sensorcolormode.IsChecked==true)) { if (new_sensorrange.Text != "") child.controller.range = Convert.ToInt32(new_sensorrange.Text); child.controller.colorMode = new_sensorcolormode.IsChecked==true?true:false; child.controller.color = new_sensorcolor.Text; } if(Edit_Timer.IsVisible && new_timerseconds.Text != null) { child.controller.seconds = Convert.ToInt32(new_timerseconds.Text); child.controller.ticks = Convert.ToInt32(new_timerticks.Text); } } } if(blueprint.joints != null) foreach (dynamic child in blueprint.joints) { if (child.color.ToString().StartsWith("#")) child.color = child.color.ToString().Substring(1, 6); dynamic c = child; c.pos = child.posA; c.xaxis = child.xaxisA; c.zaxis = child.zaxisA; dynamic realpos = BP.getposandbounds(c); realpos.pos = child.posA; if (!(Convert.ToInt32(child.zaxis.ToString())>0 || !(realpos.bounds.x != 1 || realpos.bounds.y != 1 || realpos.bounds.z != 1))) { int zaxis = Convert.ToInt32(child.zaxis.ToString()); if (zaxis == -1) realpos.pos.x -= realpos.bounds.x - 1; if (zaxis == -2) realpos.pos.y -= realpos.bounds.y - 1; if (zaxis == -3) realpos.pos.z -= realpos.bounds.z - 1; } if ((filtercolor == null || filtercolor == child.color.ToString()) && (targetuuid == null || targetuuid == child.shapeId.ToString()) && (x1 <= (int)realpos.pos.x && (int)realpos.pos.x + (int)realpos.bounds.x <= x2) && (y1 <= (int)realpos.pos.y && (int)realpos.pos.y + (int)realpos.bounds.y <= y2) && (z1 <= (int)realpos.pos.z && (int)realpos.pos.z + (int)realpos.bounds.z <= z2)) { child.posA.x = child.posA.x + Convert.ToInt32(new_x.Text); child.posA.y = child.posA.y + Convert.ToInt32(new_y.Text); child.posA.z = child.posA.z + Convert.ToInt32(new_z.Text); if (new_color.Text != "") child.color = new_color.Text.ToString().Substring(1, 6); } } Loadwindow w = new Loadwindow(); w.Show(); BP.Description.description = BP.Description.description += "++ Applied some area property changes "; BP.setblueprint(BP.Blueprint); this.mainwindow.RenderBlueprint(); //Update(); filterupdate(); w.Close(); } private void SET_Copy_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); new_sensorcolor.Text = PaintSelector.PaintColor; } private void SET_Copy1_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); new_lampcolor.Text = PaintSelector.PaintColor; } private void SET_Copy2_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); new_color.Text = PaintSelector.PaintColor; } private void disableAll() { Edit_gate.Visibility = Visibility.Collapsed; Edit_general.Visibility = Visibility.Collapsed; Edit_lamp.Visibility = Visibility.Collapsed; Edit_sensor.Visibility = Visibility.Collapsed; Edit_Timer.Visibility = Visibility.Collapsed; button_render.IsEnabled = false; this.mainwindow.Marker = null; mainwindow.Image_blueprint.DataContext = ""; mainwindow.Image_blueprint.DataContext = mainwindow; } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { base.OnClosing(e); this.mainwindow.Marker = null; this.mainwindow.setMarker2(0, 0, 0, 0, 0, 0); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using System.Windows; using System.IO; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; namespace Advanced_Blueprint_Tools { public class BP { public static string Blueprintpath { get; private set; } public static dynamic Blueprint { get; private set; } public static dynamic Description { get; private set; } public static PngBitmapEncoder Icon { get; set; } private static Dictionary<int, dynamic> Wires { get; set; } private static HashSet<string> Useduuids = new HashSet<string>(); public static bool missingmod = false; public static bool brokenrotation = false; public static void setblueprint(dynamic bp) { Blueprint = bp; missingmod = false; brokenrotation = false; Useduuids.Clear(); GetUsedUuids(); Wires = new Dictionary<int, dynamic>(); } public BP(string bppath, dynamic bp, dynamic desc) { Blueprintpath = bppath; Blueprint = bp; Description = desc; setblueprint(bp); } public BP(string bppath) { Blueprint = null; Description = null; Blueprintpath = bppath; //load directory of blueprints try { Blueprint = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(System.IO.File.ReadAllText(Blueprintpath + @"\blueprint.json")); Description = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(System.IO.File.ReadAllText(Blueprintpath + @"\description.json")); setblueprint(Blueprint); } catch (Exception e) { MessageBox.Show(e.Message); } } public static HashSet<string> GetUsedUuids() { if (Useduuids.Count > 0) return Useduuids; Useduuids = new HashSet<string>(); if (Blueprint.bodies != null) foreach (dynamic body in Blueprint.bodies) foreach (dynamic child in body.childs) Useduuids.Add(child.shapeId.ToString()); if (Blueprint.joints != null) foreach(dynamic joint in Blueprint.joints) Useduuids.Add(joint.shapeId.ToString()); return Useduuids; } public static Dictionary<string, Tuple<string, BitmapSource, int>> GetUsedPartsList() { Dictionary<string, int> uuidamounts = new Dictionary<string, int>(); try { if (Blueprint.bodies != null) foreach (dynamic body in Blueprint.bodies) foreach (dynamic child in body.childs) { int modifier = 1; if (child.bounds != null) modifier = Convert.ToInt32(child.bounds.x.ToString()) * Convert.ToInt32(child.bounds.y.ToString()) * Convert.ToInt32(child.bounds.z.ToString()); string uuid = child.shapeId.ToString(); if (!uuidamounts.ContainsKey(uuid)) uuidamounts.Add(uuid, modifier); else uuidamounts[uuid]+=modifier; } if (Blueprint.joints != null) foreach (dynamic joint in Blueprint.joints) { string uuid = joint.shapeId.ToString(); if (!uuidamounts.ContainsKey(uuid)) uuidamounts.Add(uuid, 1); else uuidamounts[uuid]++; } Dictionary<string, Tuple<string, BitmapSource, int>> list = new Dictionary<string, Tuple<string, BitmapSource, int>>(); foreach (string uuid in uuidamounts.Keys) { if (Database.blocks.ContainsKey(uuid)) { list.Add(uuid, new Tuple<string, BitmapSource, int>(Database.blocks[uuid].Name, null, uuidamounts[uuid])); } } return list; } catch { return null; } } public static Dictionary<int, dynamic> GetWires() { Wires = new Dictionary<int, dynamic>(); if (Blueprint.bodies != null) foreach (dynamic body in Blueprint.bodies) foreach (dynamic child in body.childs) if (child.controller != null && child.controller.id != null) { dynamic correctedchild = getposandbounds(child); dynamic wire = new JObject(); wire.pos = new JObject() { ["x"]= Convert.ToInt32(correctedchild.pos.x.ToString()) + Convert.ToInt32(correctedchild.bounds.x.ToString()) / 2.0, ["y"]= Convert.ToInt32(correctedchild.pos.y.ToString()) + Convert.ToInt32(correctedchild.bounds.y.ToString()) / 2.0, ["z"]= Convert.ToInt32(correctedchild.pos.z.ToString()) + Convert.ToInt32(correctedchild.bounds.z.ToString()) / 2.0 }; string color = child.color.ToString(); if (color.StartsWith("#")) color = color.Substring(1); wire.color = color; wire.connections = child.controller.controllers; Wires.Add(Convert.ToInt32(child.controller.id.ToString()), wire); } if (Blueprint.joints != null) foreach (dynamic joint in Blueprint.joints) if (joint.controller != null && joint.controller.id != null) { dynamic correctedchild = getposandbounds(joint); dynamic wire = new JObject(); wire.pos = new JObject() { ["x"] = Convert.ToInt32(correctedchild.pos.x.ToString()) + Convert.ToInt32(correctedchild.bounds.x.ToString()) / 2.0, ["y"] = Convert.ToInt32(correctedchild.pos.y.ToString()) + Convert.ToInt32(correctedchild.bounds.y.ToString()) / 2.0, ["z"] = Convert.ToInt32(correctedchild.pos.z.ToString()) + Convert.ToInt32(correctedchild.bounds.z.ToString()) / 2.0 }; string color = joint.color.ToString(); if (color.StartsWith("#")) color = color.Substring(1); wire.color = color; wire.connections = joint.controller.controllers; Wires.Add(Convert.ToInt32(joint.controller.id.ToString()), wire); } return Wires; } public static dynamic GetBounds() { int minx = 10000, maxx = -10000, miny = 10000, maxy = -10000, minz = 10000, maxz = -10000; foreach(dynamic body in Blueprint.bodies) foreach(dynamic child in body.childs) { dynamic correctedchild = getposandbounds(child); if (correctedchild.pos.x < minx) minx = correctedchild.pos.x; else if (correctedchild.pos.x + correctedchild.bounds.x > maxx) maxx = correctedchild.pos.x + correctedchild.bounds.x; if (correctedchild.pos.y < miny) miny = correctedchild.pos.y; else if (correctedchild.pos.y + correctedchild.bounds.y > maxy) maxy = correctedchild.pos.y + correctedchild.bounds.y; if (correctedchild.pos.z < minz) minz = correctedchild.pos.z; else if (correctedchild.pos.z + correctedchild.bounds.z > maxz) maxz = correctedchild.pos.z + correctedchild.bounds.z; } if (Blueprint.joints != null) foreach (dynamic joint in Blueprint.joints) { dynamic correctedchild = getposandbounds(joint); if (correctedchild.pos.x < minx) minx = correctedchild.pos.x; else if (correctedchild.pos.x + correctedchild.bounds.x > maxx) maxx = correctedchild.pos.x + correctedchild.bounds.x; if (correctedchild.pos.y < miny) miny = correctedchild.pos.y; else if (correctedchild.pos.y + correctedchild.bounds.y > maxy) maxy = correctedchild.pos.y + correctedchild.bounds.y; if (correctedchild.pos.z < minz) minz = correctedchild.pos.z; else if (correctedchild.pos.z + correctedchild.bounds.z > maxz) maxz = correctedchild.pos.z + correctedchild.bounds.z; } return new JObject() { ["minx"] = minx, ["maxx"] = maxx, ["miny"] = miny, ["maxy"] = maxy, ["minz"] = minz, ["maxz"] = maxz }; } public static Tuple<Point3D,int> GetCenterOffMass() { Point3D center = new Point3D(0, 0, 0); int totalweight = 0; foreach(dynamic body in Blueprint.bodies) foreach(dynamic child in body.childs) if(Database.blocks.ContainsKey(child.shapeId.ToString())) { dynamic realpos = getposandbounds(child); int weight = Database.blocks[child.shapeId.ToString()].GetWeight(realpos.bounds); var point = new Point3D((int)realpos.pos.x + (int)realpos.bounds.x/ 2.0, (int)realpos.pos.y + (int)realpos.bounds.y / 2.0, (int)realpos.pos.z + (int)realpos.bounds.z / 2.0); int tot = totalweight + weight; center = new Point3D((center.X * totalweight + point.X * weight) / tot, (center.Y * totalweight + point.Y * weight) / tot, (center.Z * totalweight + point.Z * weight) / tot); totalweight = tot; } return new Tuple<Point3D, int>(center, totalweight); } public static Tuple<Model3DGroup, Model3DGroup> RenderBlocks() { Model3DGroup blocks = new Model3DGroup(); Model3DGroup glass = new Model3DGroup(); Block block = new Block(null, "unknown", "unknown", null, null); if (Blueprint.bodies != null) foreach (dynamic body in Blueprint.bodies) foreach (dynamic child in body.childs) { dynamic realpos = getposandbounds(child); int x = realpos.pos.x; int y = realpos.pos.y; int z = realpos.pos.z; if (Database.blocks.ContainsKey(child.shapeId.ToString())) { Blockobject blockobject = Database.blocks[child.shapeId.ToString()]; if (blockobject is Block) { Model3D model = (blockobject as Block).Render(x, y, z, realpos.bounds, child.color.ToString(), Convert.ToInt32(realpos.xaxis), Convert.ToInt32(realpos.zaxis)); if (!blockobject.glass) blocks.Children.Add(model); else glass.Children.Add(model); } else//part { Model3D model = (blockobject as Part).Render(x , y, z, child.color.ToString(), Convert.ToInt32(realpos.xaxis), Convert.ToInt32(realpos.zaxis)); if (!blockobject.glass) blocks.Children.Add(model); else glass.Children.Add(model); } } else//not in database { dynamic bounds = new JObject() { ["x"] = 1, ["y"] = 1, ["z"] = 1 }; if (realpos.bounds != null) bounds = realpos.bounds; Model3D model = block.Render(x, y, z, bounds, child.color.ToString(), Convert.ToInt32(realpos.xaxis), Convert.ToInt32(realpos.zaxis)); blocks.Children.Add(model); } } if(Blueprint.joints != null) foreach(dynamic joint in Blueprint.joints) { dynamic realpos = getposandbounds(joint); int x = realpos.pos.x; int y = realpos.pos.y; int z = realpos.pos.z; if (Database.blocks.ContainsKey(joint.shapeId.ToString())) { Blockobject blockobject = Database.blocks[joint.shapeId.ToString()]; if (blockobject is Block) { Model3D model = (blockobject as Block).Render(x, y, z, realpos.bounds, joint.color.ToString(), Convert.ToInt32(realpos.xaxis), Convert.ToInt32(realpos.zaxis)); if (!blockobject.glass) blocks.Children.Add(model); else glass.Children.Add(model); } else//part { Model3D model = (blockobject as Part).Render(x, y, z, joint.color.ToString(), Convert.ToInt32(realpos.xaxis), Convert.ToInt32(realpos.zaxis)); if (!blockobject.glass) blocks.Children.Add(model); else glass.Children.Add(model); } } else//not in database { dynamic bounds = new JObject() { ["x"] = 1, ["y"] = 1, ["z"] = 1 }; if (realpos.bounds != null) bounds = realpos.bounds; Model3D model = block.Render(x, y, z, bounds, joint.color.ToString(), Convert.ToInt32(realpos.xaxis), Convert.ToInt32(realpos.zaxis)); blocks.Children.Add(model); } } new Task(() => { if (BP.missingmod) MessageBox.Show("Missing mod for this blueprint! \nPlease download the required mod!\n\nwill work for now tho wiring/moving blocks not recommended!"); }).Start(); new Task(() => { if (BP.brokenrotation) MessageBox.Show("Broken Rotation in this blueprint!\n\nTools 'mirror tool', [] ,.. will BREAK your blueprint!"); }).Start(); return new Tuple<Model3DGroup, Model3DGroup>(blocks,glass); } public static void Save() { string blueprinttext = Convert.ToString(Blueprint); string descriptiontext = Newtonsoft.Json.JsonConvert.SerializeObject(Description); if(!Directory.Exists(Blueprintpath)) System.IO.Directory.CreateDirectory(Blueprintpath); backup(); System.IO.File.WriteAllText(Blueprintpath + "\\blueprint.json", blueprinttext); //save blueprint System.IO.File.WriteAllText(Blueprintpath + "\\description.json", descriptiontext); //save description using (Stream stm = File.Create(Blueprintpath + "\\icon.png")) { Icon.Save(stm); } Database.LoadBpsIn(Database.User_ + "\\blueprints");//refresh icon Database.bprefresh = true; new System.Threading.Thread(new System.Threading.ThreadStart(()=> { MessageBox.Show("Blueprint saved!"); })).Start(); } public static void backup() { if(File.Exists(Blueprintpath + "\\blueprint.json")) { for(int i = 1; i<30; i++) { if (!File.Exists(Blueprintpath + "\\blueprint_backup_" + i.ToString() + ".json")) { System.IO.File.Copy(Blueprintpath + "\\blueprint.json", Blueprintpath + "\\blueprint_backup_" + i.ToString() + ".json"); break; } } } } public static void SaveAs(string name)//in scrapdata dir { string newbp = Database.User_ + @"\Blueprints\" + name; System.IO.Directory.CreateDirectory(newbp); string blueprinttext = Convert.ToString(Blueprint); Description.localId = System.Guid.NewGuid(); string descriptiontext = Newtonsoft.Json.JsonConvert.SerializeObject(Description); System.IO.File.WriteAllText(newbp + "\\blueprint.json", blueprinttext); //save blueprint System.IO.File.WriteAllText(newbp + "\\description.json", descriptiontext); //save description using (Stream stm = File.Create(newbp+"\\icon.png")) { Icon.Save(stm); } Database.LoadBpsIn(Database.User_ + "\\blueprints"); Database.bprefresh = true; new System.Threading.Thread(() => { MessageBox.Show("Saved as new blueprint!\nwill require game restart to be able to find it in-game!\n(blame axolot)"); }).Start(); } //get bounds from private static dynamic getbounds(dynamic part) { dynamic bounds = new Newtonsoft.Json.Linq.JObject(); if (part.box != null) { return part.box; } if (part.hull != null) { bounds.x = part.hull.x; bounds.y = part.hull.y; bounds.z = part.hull.z; return bounds; } if (part.cylinder != null) { if (part.cylinder.axis.ToString().ToLower() == "x") { bounds.x = part.cylinder.depth; bounds.y = part.cylinder.diameter; bounds.z = part.cylinder.diameter; return bounds; } else if (part.cylinder.axis.ToString().ToLower() == "y") { bounds.x = part.cylinder.diameter; bounds.y = part.cylinder.depth; bounds.z = part.cylinder.diameter; return bounds; } else if (part.cylinder.axis.ToString().ToLower() == "z") { bounds.x = part.cylinder.diameter; bounds.y = part.cylinder.diameter; bounds.z = part.cylinder.depth; return bounds; } } bounds.X = 1; bounds.Y = 1; bounds.Z = 1; MessageBox.Show("no bounds\n\nImpossible senario. please report"); return bounds; } //Reorganize bounds according to rotation: private static dynamic flip(dynamic child, string neworder) { int x = child.bounds.x; int y = child.bounds.y; int z = child.bounds.z; if (neworder == "zxy") //shift { child.bounds.x = z; child.bounds.y = x; child.bounds.z = y; } if (neworder == "yzx") //" { child.bounds.x = y; child.bounds.y = z; child.bounds.z = x; } if (neworder == "xzy") //switch { child.bounds.x = x; child.bounds.y = z; child.bounds.z = y; } if (neworder == "zyx") { child.bounds.x = z; child.bounds.y = y; child.bounds.z = x; } if (neworder == "yxz") { child.bounds.x = y; child.bounds.y = x; child.bounds.z = z; } return child; } //get new pos and correct ingame bounds for child public static dynamic getposandbounds(dynamic whatever) { dynamic child = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(whatever)); string uuid = child.shapeId; //if (child.bounds == null) //add bounds to parts (blocks do not get affected) { if (Database.blocks.ContainsKey(uuid)) { Blockobject b = Database.blocks[uuid]; if (b is Part) { child.bounds = ((Part)b).GetBoundsDynamic(); } } else { missingmod = true; } if (child.bounds == null) { child.bounds = new JObject { ["x"] = 1, ["y"] = 1, ["z"] = 1 }; } } bool IsJoint = false; if (child.posA != null) { IsJoint = true; child.pos = child.posA; child.xaxis = child.xaxisA; child.zaxis = child.zaxisA; } try { int xaxis = Convert.ToInt32(child.xaxis); int zaxis = Convert.ToInt32(child.zaxis); int xaxisabs = Math.Abs(xaxis); int zaxisabs = Math.Abs(zaxis); //switch bounds here if (Math.Abs(Convert.ToInt32(child.xaxis)) == 3) { if (Math.Abs(Convert.ToInt32(child.zaxis)) == 2) { flip(child, "yzx"); } if (Math.Abs(Convert.ToInt32(child.zaxis)) == 1) { flip(child, "zyx"); } } if (Math.Abs(Convert.ToInt32(child.xaxis)) == 2) { if (Math.Abs(Convert.ToInt32(child.zaxis)) == 3) { flip(child, "yxz"); } if (Math.Abs(Convert.ToInt32(child.zaxis)) == 1) { flip(child, "zxy"); } } if (Math.Abs(Convert.ToInt32(child.xaxis)) == 1) { if (Math.Abs(Convert.ToInt32(child.zaxis)) == 2) { flip(child, "xzy"); } } //this updating pos only applies to parts, blocks do not get affected as they always have xaxis 1 zaxis 3 if (!IsJoint) { // //if (xaxis == -1 | zaxis == -1 | (xaxis == 2 && zaxis == 3) | (xaxis == 3 && zaxis == -2) | (xaxis == -2 && zaxis == -3) | (xaxis == -3 && zaxis == 2)) // child.pos.x -= child.bounds.x; //if (xaxis == -2 | zaxis == -2 | (xaxis == -1 && zaxis == 3) | (xaxis == -3 && zaxis == -1) | (xaxis == 1 && zaxis == -3) | (xaxis == 3 && zaxis == 1)) // child.pos.y -= child.bounds.y; //if (xaxis == -3 | zaxis == -3 | (xaxis == -2 && zaxis == 1) | (xaxis == -1 && zaxis == -2) | (xaxis == 1 && zaxis == 2) | (xaxis == 2 && zaxis == -1)) // child.pos.z -= child.bounds.z; if (child.xaxis == -1 | child.zaxis == -1 | (child.xaxis == 2 && child.zaxis == 3) | (child.xaxis == 3 && child.zaxis == -2) | (child.xaxis == -2 && child.zaxis == -3) | (child.xaxis == -3 && child.zaxis == 2)) child.pos.x -= child.bounds.x; if (child.xaxis == -2 | child.zaxis == -2 | (child.xaxis == -1 && child.zaxis == 3) | (child.xaxis == -3 && child.zaxis == -1) | (child.xaxis == 1 && child.zaxis == -3) | (child.xaxis == 3 && child.zaxis == 1)) child.pos.y -= child.bounds.y; if (child.xaxis == -3 | child.zaxis == -3 | (child.xaxis == -2 && child.zaxis == 1) | (child.xaxis == -1 && child.zaxis == -2) | (child.xaxis == 1 && child.zaxis == 2) | (child.xaxis == 2 && child.zaxis == -1)) child.pos.z -= child.bounds.z; } else { if (!(zaxis > 0 || !(child.bounds.x != 1 || child.bounds.y != 1 || child.bounds.z != 1))) { //correctedchild.pos = Blueprint.joints[i].posB; if (zaxis == -1) child.pos.x -= child.bounds.x - 1; if (zaxis == -2) child.pos.y -= child.bounds.y - 1; if (zaxis == -3) child.pos.z -= child.bounds.z - 1; } } } catch { } return child; } public static dynamic calcbppos(dynamic whatever) { dynamic child = Newtonsoft.Json.JsonConvert.DeserializeObject(Convert.ToString(whatever)); //this updating pos only applies to parts, blocks do not get affected as they always have xaxis 1 zaxis 3 if (child.xaxis == -1 | child.zaxis == -1 | (child.xaxis == 2 && child.zaxis == 3) | (child.xaxis == 3 && child.zaxis == -2) | (child.xaxis == -2 && child.zaxis == -3) | (child.xaxis == -3 && child.zaxis == 2)) child.pos.x += child.bounds.x; if (child.xaxis == -2 | child.zaxis == -2 | (child.xaxis == -1 && child.zaxis == 3) | (child.xaxis == -3 && child.zaxis == -1) | (child.xaxis == 1 && child.zaxis == -3) | (child.xaxis == 3 && child.zaxis == 1)) child.pos.y += child.bounds.y; if (child.xaxis == -3 | child.zaxis == -3 | (child.xaxis == -2 && child.zaxis == 1) | (child.xaxis == -1 && child.zaxis == -2) | (child.xaxis == 1 && child.zaxis == 2) | (child.xaxis == 2 && child.zaxis == -1)) child.pos.z += child.bounds.z; return child; } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for Sphere_generator.xaml /// </summary> public partial class Ellipsoid_Generator : Window { private MainWindow mainwindow; public Ellipsoid_Generator(MainWindow window) { this.mainwindow = window; InitializeComponent(); } private void Button_Help_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start("https://youtu.be/glLgQemUS2I?t=1479"); } private void Button_Create_Click(object sender, RoutedEventArgs e) { float X = Convert.ToInt32(TextBox_X.Text); float Y = Convert.ToInt32(TextBox_Y.Text); float Z = Convert.ToInt32(TextBox_Z.Text); float t = Convert.ToInt32(TextBox_thickness.Text); dynamic Sphere = new JObject(); Sphere.bodies = new JArray(); Sphere.bodies.Add(new JObject() as dynamic); Sphere.bodies[0].childs = new JArray(); dynamic blocksXYZ = new JObject(); int amountgenerated=0; for (float x = -X; x < X; x++) for (float y = -Y; y < Y; y++) for (float z = -Z; z < Z; z++) { if ((Math.Pow(x / X, 2) + Math.Pow(y / Y, 2) + Math.Pow(z / Z, 2)) < 0.95 && (Math.Pow(x / (X-t), 2) + Math.Pow((y ) / (Y-t), 2) + Math.Pow(z / (Z-t), 2)) > 0.95) { if (blocksXYZ[x.ToString()] == null) blocksXYZ[x.ToString()] = new JObject(); if (blocksXYZ[x.ToString()][y.ToString()] == null) blocksXYZ[x.ToString()][y.ToString()] = new JObject(); if (blocksXYZ[x.ToString()][y.ToString()][z.ToString()] == null) blocksXYZ[x.ToString()][y.ToString()][z.ToString()] = new JObject(); dynamic bounds = new JObject(); bounds.x = 1; bounds.y = 1; bounds.z = 1; blocksXYZ[x.ToString()][y.ToString()][z.ToString()].bounds = bounds; amountgenerated++; } } foreach (dynamic x in blocksXYZ) foreach (dynamic y in x.Value) foreach (dynamic z in y.Value) { dynamic bounds = z.Value.bounds; if (bounds != null) { for (int i = Convert.ToInt32(z.Name) + 1; i < 64; i++) { if (blocksXYZ[x.Name][y.Name][i.ToString()] != null && blocksXYZ[x.Name][y.Name][i.ToString()].bounds != null) { blocksXYZ[x.Name][y.Name][i.ToString()].bounds = null; blocksXYZ[x.Name][y.Name][z.Name].bounds.z = Convert.ToInt32(blocksXYZ[x.Name][y.Name][z.Name].bounds.z) + 1; } else break; } } } foreach (dynamic x in blocksXYZ) foreach (dynamic y in x.Value) foreach (dynamic z in y.Value) { dynamic bounds = z.Value.bounds; if (bounds != null) { for (int i = Convert.ToInt32(y.Name) + 1; i < 64; i++) { if (blocksXYZ[x.Name][i.ToString()] != null && blocksXYZ[x.Name][i.ToString()][z.Name] != null && blocksXYZ[x.Name][i.ToString()][z.Name].bounds != null && blocksXYZ[x.Name][i.ToString()][z.Name].bounds.z == blocksXYZ[x.Name][y.Name][z.Name].bounds.z) { blocksXYZ[x.Name][i.ToString()][z.Name].bounds = null; blocksXYZ[x.Name][y.Name][z.Name].bounds.y = Convert.ToInt32(blocksXYZ[x.Name][y.Name][z.Name].bounds.y) + 1; } else break; } } } foreach (dynamic x in blocksXYZ) foreach (dynamic y in x.Value) foreach (dynamic z in y.Value) { dynamic bounds = z.Value.bounds; if (bounds != null) { for (int i = Convert.ToInt32(x.Name) + 1; i < 64; i++) { if (blocksXYZ[i.ToString()] != null && blocksXYZ[i.ToString()][y.Name] != null && blocksXYZ[i.ToString()][y.Name][z.Name] != null && blocksXYZ[i.ToString()][y.Name][z.Name].bounds != null && blocksXYZ[i.ToString()][y.Name][z.Name].bounds.z == blocksXYZ[x.Name][y.Name][z.Name].bounds.z && blocksXYZ[i.ToString()][y.Name][z.Name].bounds.y == blocksXYZ[x.Name][y.Name][z.Name].bounds.y) { blocksXYZ[i.ToString()][y.Name][z.Name].bounds = null; blocksXYZ[x.Name][y.Name][z.Name].bounds.x = Convert.ToInt32(blocksXYZ[x.Name][y.Name][z.Name].bounds.x) + 1; } else break; } } } foreach (dynamic x in blocksXYZ) foreach (dynamic y in x.Value) foreach (dynamic z in y.Value) if(z.Value.bounds != null) Sphere.bodies[0].childs.Add(block(Convert.ToInt32(x.Name), Convert.ToInt32(y.Name), Convert.ToInt32(z.Name), z.Value.bounds)); if (amountgenerated > 0) { string message = "++ An ellipsoid with " + amountgenerated + " blocks has been generated!"; //MessageBox.Show(message+"\n\nOptimized to: "+count+" shapes"); Random r = new Random(); string blueprintpath = Database.User_ + "\\Blueprints\\GeneratedEllipsoid-"+r.Next()+r.Next(); dynamic description = new JObject(); description.description = "generated ellipsoid"; description.name = "generated sphere" + r.Next(); description.type = "Blueprint"; description.version = 0; if (BP.Blueprintpath== null) {//no blueprint exists, initialize new one new BP(blueprintpath, Sphere, description); } else {//overwrite current blueprint BP.setblueprint(Sphere); BP.Description.description += message; } mainwindow.RenderBlueprint(); } else { MessageBox.Show("no ellipsoid has been generated"); } } private dynamic block(int x, int y, int z, dynamic bounds) { dynamic block = new JObject(); block.color = "5DB7E7"; block.pos = new JObject(); block.pos.x = x; block.pos.y = y; block.pos.z = z; block.bounds = new JObject(); block.bounds.x = bounds.x; block.bounds.y = bounds.y; block.bounds.z = bounds.z; block.shapeId = "a6c6ce30-dd47-4587-b475-085d55c6a3b4"; block.xaxis = 1; block.zaxis = 3; return block; } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox t = (TextBox)sender; try { if (Convert.ToInt32(t.Text) >= 0 || Convert.ToInt32(t.Text) <= 0) { } } catch { t.Text = "0"; } } } } <file_sep>using Assimp; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Shapes; using System.ComponentModel; using System.Threading; using System.IO; using System.Drawing; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for ObjToBlueprint.xaml /// </summary> public partial class ObjToBlueprint : Window { MainWindow mainWindow; string file; string texture; Dictionary<Point3D, Point3D> coloredpoints; double scale=1; Assimp.Vector3D bounds = new Assimp.Vector3D(1, 1, 1); BackgroundWorker backgroundWorker = new BackgroundWorker(); ProgressWindow progressWindow; HashSet<Point3D> pointlist = new HashSet<Point3D>();//Tuple<Point3D,color> bool flipyz = false; bool flipxz = false; int flipz = 1; bool texturepossible = false; public ObjToBlueprint(MainWindow mainWindow) { this.mainWindow = mainWindow; InitializeComponent(); } private void objPath_MouseDoubleClick(object sender, MouseButtonEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.DefaultExt = ".obj"; openFileDialog.Filter = "Obj files (*.obj)|*.obj|Mesh files (*.mesh)|*.mesh|Fbx Files(*.fbx)|*.fbx|stl files(*.stl)|*.stl|All Files(*.*)|*.*"; openFileDialog.InitialDirectory = Database.ScrapData; openFileDialog.ShowDialog(); string file = openFileDialog.FileName; if (file != null && file != "") { objPath.Text = file; } } private void objPath_TextChanged(object sender, TextChangedEventArgs e) { string file = objPath.Text; if (file != null && file != "" && File.Exists(file)) { this.file = file; //objPath.Text = file; new Thread(() => { try { this.texturepossible = false; int minx = 1000000, maxx = -1000000, miny = 1000000, maxy = -1000000, minz = 1000000, maxz = -1000000; Scene scene = new AssimpImporter().ImportFile(file); foreach (Mesh m in scene.Meshes) { if (m.TextureCoordsChannelCount>0) this.texturepossible = true; foreach (Assimp.Vector3D p in m.Vertices) { if (p.X < minx) minx = (int)p.X; else if (p.X > maxx) maxx = (int)p.X; if (p.Y < miny) miny = (int)p.Y; else if (p.Y > maxy) maxy = (int)p.Y; if (p.Z < minz) minz = (int)p.Z; else if (p.Z > maxz) maxz = (int)p.Z; } } this.Dispatcher.Invoke((Action)(() => { BoundsBox.Content = @"(" + (maxx - minx) + "x" + (maxy - miny) + "x" + (maxz - minz) + ")"; })); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message, "Couldn't load mesh file"); this.file = null; } }).Start(); } } private void TexturePath_MouseDoubleClick(object sender, MouseButtonEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.DefaultExt = ".png"; openFileDialog.Filter = "png files (*.png)|*.png|jpg files (*.jpg)|*.jpg|All Files(*.*)|*.*"; openFileDialog.InitialDirectory = Database.ScrapData; openFileDialog.ShowDialog(); string file = openFileDialog.FileName; if (file != null && file != "") { TexturePath.Text = file; } } private void TexturePath_TextChanged(object sender, TextChangedEventArgs e) { string file = TexturePath.Text; if (file != null && file != "" && File.Exists(file)) { this.texture = file; } else this.texture = null; } private void Button_Click(object sender, RoutedEventArgs e) { if(this.file != null) { flipyz = flipYZ.IsChecked == true; flipxz = flipXZ.IsChecked == true; flipz = flipZ.IsChecked == true ? -1 : 1; backgroundWorker = new BackgroundWorker(); backgroundWorker.WorkerSupportsCancellation = true; backgroundWorker.WorkerReportsProgress = true; progressWindow = new ProgressWindow(backgroundWorker, "Converting OBJ to Pointlist"); progressWindow.Show(); if(this.texture != null && this.texturepossible) backgroundWorker.DoWork += new DoWorkEventHandler(Convertobjwtexture); else backgroundWorker.DoWork += new DoWorkEventHandler(Convertobj); backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(conversioncompleted); backgroundWorker.ProgressChanged += BackgroundWorker1_ProgressChanged; backgroundWorker.RunWorkerAsync(); } } private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressWindow.UpdateProgress(e.ProgressPercentage); } private void Convertobjwtexture(object sender, DoWorkEventArgs e) { try { Scene scene = new AssimpImporter().ImportFile(file, PostProcessSteps.Triangulate); coloredpoints = new Dictionary<Point3D, Point3D>(); //List<Triangle> splittriangles = new List<Triangle>(); //pointlist = new HashSet<Point3D>(); //pointlist.ToDictionary<> int progress = 0; int total = 0; foreach (Mesh m in scene.Meshes) foreach (Face face in m.Faces) total++; foreach (Mesh m in scene.Meshes) { var texturecoords = m.GetTextureCoords(0); foreach (Face face in m.Faces) { IList<Point3D> vertices = new List<Point3D>(); IList<Point3D> texturepoints = new List<Point3D>(); foreach (uint i in face.Indices) { double x = m.Vertices[i].X * scale; double y = m.Vertices[i].Y * scale; double z = m.Vertices[i].Z * scale; Point3D point; Assimp.Vector3D texturep = texturecoords[i]; Point3D texturepoint = new Point3D(texturep.X,1-texturep.Y,texturep.Z); if (flipyz) { if (flipxz) { point = new Point3D(y, z, flipz * x); } else { point = new Point3D(x, z, flipz * y); } } else { if (flipxz) { point = new Point3D(z, y, flipz * x); } else point = new Point3D(x, y, flipz * z); } vertices.Add(point); texturepoints.Add(texturepoint); Point3D flooredpoint = new Point3D((int)Math.Floor(point.X), (int)Math.Floor(point.Y), (int)Math.Floor(point.Z)); if (!coloredpoints.ContainsKey(flooredpoint)) coloredpoints.Add(flooredpoint, texturepoint); } if (vertices.Count == 3) { ColorTriangle triangle = new ColorTriangle(vertices,texturepoints); if (!triangle.BoundsSmallerThan(bounds)) Splitcolortriangles(triangle); } else { } progress++; backgroundWorker.ReportProgress((progress * 100) / total); if (backgroundWorker.CancellationPending) e.Cancel = true; } } } catch (Exception ex) { if (!(ex is OperationCanceledException)) System.Windows.MessageBox.Show(ex.Message, "Something went wrong converting the obj+texture"); else e.Cancel = true; } try { if (backgroundWorker.CancellationPending) throw new OperationCanceledException(); dynamic blueprint = new JObject(); try { Bitmap texturemap = new Bitmap(this.texture); HashSet<Tuple<Point3D, string>> pointswithcolor = new HashSet<Tuple<Point3D, string>>(); int width = texturemap.Width; int height = texturemap.Height; foreach (var pair in coloredpoints) { int x = (int)(pair.Value.X * width); int y = (int)(pair.Value.Y * height); if (pair.Value.Y > 1) { } while (y < 0) y ++; while (x < 0) x ++; if(Math.Abs(x)>width/2) { } while (x >= width) x -= width; while (y>= height) y -= height; System.Drawing.Color color = texturemap.GetPixel(x , y); string c = color.Name.Substring(2); pointswithcolor.Add(new Tuple<Point3D, string>(pair.Key, c)); } coloredpoints.Clear(); blueprint = BlueprintOptimizer.CreateBlueprintFromPointsAndColor(pointswithcolor); } catch (Exception bpex) { System.Windows.MessageBox.Show(bpex.Message, "Something went wrong building the blueprint"); } int amountgenerated = blueprint.bodies[0].childs.Count; string message = "converted obj to blueprint with " + amountgenerated + " blocks !"; //MessageBox.Show(message+"\n\nOptimized to: "+count+" shapes"); Random r = new Random(); string blueprintpath = Database.User_ + "\\Blueprints\\Generatedblueprintobj-" + r.Next() + r.Next(); dynamic description = new JObject(); description.description = "generated obj blueprint with " + amountgenerated + " block"; description.name = "generated blueprint" + r.Next(); description.type = "Blueprint"; description.version = 0; new Task(() => { System.Windows.MessageBox.Show(message + "\nPLEASE WAIT for the rendering to complete"); }).Start(); if (BP.Blueprintpath == null) {//no blueprint exists, initialize new one new BP(blueprintpath, blueprint, description); } else {//overwrite current blueprint BP.setblueprint(blueprint); BP.Description.description += message; } } catch (Exception exc) { System.Windows.MessageBox.Show(exc.Message, "error"); } } private void Splitcolortriangles(ColorTriangle triangle) { if (backgroundWorker.CancellationPending) throw new OperationCanceledException(); //split triangle in 4 triangles: Point3D mid1 = Average(triangle.vertices[0], triangle.vertices[1]); Point3D mid2 = Average(triangle.vertices[1], triangle.vertices[2]); Point3D mid3 = Average(triangle.vertices[0], triangle.vertices[2]); Point3D tmid1 = Average(triangle.texturecoords[0], triangle.texturecoords[1]); Point3D tmid2 = Average(triangle.texturecoords[1], triangle.texturecoords[2]); Point3D tmid3 = Average(triangle.texturecoords[0], triangle.texturecoords[2]); List<ColorTriangle> triangles = new List<ColorTriangle> { new ColorTriangle(new List<Point3D> { mid1, mid2, mid3 }, new List<Point3D>{ tmid1, tmid2, tmid3 }), new ColorTriangle(new List<Point3D> { mid1, mid3, triangle.vertices[0] },new List<Point3D> { tmid1, tmid3, triangle.texturecoords[0] }), new ColorTriangle(new List<Point3D> { mid1, mid2, triangle.vertices[1] },new List<Point3D> { tmid1, tmid2, triangle.texturecoords[1] }), new ColorTriangle(new List<Point3D> { mid2, mid3, triangle.vertices[2] },new List<Point3D> { tmid2, tmid3, triangle.texturecoords[2] }) }; Point3D flooredpoint1 = new Point3D((int)Math.Floor(mid1.X), (int)Math.Floor(mid1.Y), (int)Math.Floor(mid1.Z)); if (!coloredpoints.ContainsKey(flooredpoint1)) coloredpoints.Add(flooredpoint1, tmid1); Point3D flooredpoint2 = new Point3D((int)Math.Floor(mid2.X), (int)Math.Floor(mid2.Y), (int)Math.Floor(mid2.Z)); if (!coloredpoints.ContainsKey(flooredpoint2)) coloredpoints.Add(flooredpoint2, tmid2); Point3D flooredpoint3 = new Point3D((int)Math.Floor(mid3.X), (int)Math.Floor(mid3.Y), (int)Math.Floor(mid3.Z)); if (!coloredpoints.ContainsKey(flooredpoint3)) coloredpoints.Add(flooredpoint3, tmid3); // coloredpoints.Add(new Tuple<Point3D,Point3D>( new Point3D((int)Math.Floor(mid1.X), (int)Math.Floor(mid1.Y), (int)Math.Floor(mid1.Z)),tmid1)); // coloredpoints.Add(new Tuple<Point3D,Point3D>( new Point3D((int)Math.Floor(mid2.X), (int)Math.Floor(mid2.Y), (int)Math.Floor(mid2.Z)),tmid2)); // coloredpoints.Add(new Tuple<Point3D,Point3D>( new Point3D((int)Math.Floor(mid3.X), (int)Math.Floor(mid3.Y), (int)Math.Floor(mid3.Z)),tmid3)); //triangles.Add(new Triangle(new List<Point3D> { mid1, mid2, mid3 })); //triangles.Add(new Triangle(new List<Point3D> { mid1, mid3, triangle.vertices[0] })); //triangles.Add(new Triangle(new List<Point3D> { mid1, mid2, triangle.vertices[1] })); //triangles.Add(new Triangle(new List<Point3D> { mid2, mid3, triangle.vertices[2] })); //check for each triangle if bounds are smaller than 1x1x1, if not, split each again: foreach (ColorTriangle splittriangle in triangles) { // foreach(Point3D point in splittriangle.vertices) // pointlist.Add(new Point3D((int)Math.Floor(point.X), (int)Math.Floor(point.Y), (int)Math.Floor(point.Z))); if (!splittriangle.BoundsSmallerThan(bounds)) Splitcolortriangles(splittriangle); } //return splittriangles; } private void Convertobj(object sender, DoWorkEventArgs e) { Scene scene = new AssimpImporter().ImportFile(file, PostProcessSteps.Triangulate); //List<Triangle> splittriangles = new List<Triangle>(); pointlist = new HashSet<Point3D>(); //pointlist.ToDictionary<> int progress = 0; int total = 0; try { foreach (Mesh m in scene.Meshes) foreach (Face face in m.Faces) total++; foreach (Mesh m in scene.Meshes) { foreach (Face face in m.Faces) { IList<Point3D> vertices = new List<Point3D>(); foreach (uint i in face.Indices) { double x = m.Vertices[i].X * scale; double y = m.Vertices[i].Y * scale; double z = m.Vertices[i].Z * scale; Point3D point; if (flipyz) { if(flipxz) { point = new Point3D(y,z, flipz * x); } else { point = new Point3D(x,z, flipz * y); } } else { if (flipxz) { point = new Point3D(z,y, flipz * x); } else point = new Point3D(x,y, flipz * z); } vertices.Add(point); pointlist.Add(new Point3D((int)Math.Floor(point.X), (int)Math.Floor(point.Y), (int)Math.Floor(point.Z))); } if (vertices.Count == 3) { Triangle triangle = new Triangle(vertices); if (!triangle.BoundsSmallerThan(bounds)) Splittriangles(triangle); } else { } progress++; backgroundWorker.ReportProgress((progress * 100) / total); if (backgroundWorker.CancellationPending) e.Cancel = true; } } } catch(Exception ex) { if(!(ex is OperationCanceledException)) System.Windows.MessageBox.Show(ex.Message, "Something went wrong converting the obj"); else e.Cancel = true; } try { if (backgroundWorker.CancellationPending) throw new OperationCanceledException(); dynamic blueprint = new JObject(); try { blueprint = BlueprintOptimizer.CreateBlueprintFromPoints(pointlist); } catch(Exception bpex) { System.Windows.MessageBox.Show(bpex.Message, "Something went wrong building the blueprint"); } int amountgenerated = blueprint.bodies[0].childs.Count; string message = "converted obj to blueprint with " + amountgenerated + " blocks !"; //MessageBox.Show(message+"\n\nOptimized to: "+count+" shapes"); Random r = new Random(); string blueprintpath = Database.User_ + "\\Blueprints\\Generatedblueprintobj-" + r.Next() + r.Next(); dynamic description = new JObject(); description.description = "generated obj blueprint with "+amountgenerated+" block"; description.name = "generated blueprint" + r.Next(); description.type = "Blueprint"; description.version = 0; new Task(() => { System.Windows.MessageBox.Show(message + "\nPLEASE WAIT for the rendering to complete"); }).Start(); if (BP.Blueprintpath == null) {//no blueprint exists, initialize new one new BP(blueprintpath, blueprint, description); } else {//overwrite current blueprint BP.setblueprint(blueprint); BP.Description.description += message; } } catch (Exception exc) { System.Windows.MessageBox.Show(exc.Message, "error"); } } private void Splittriangles(Triangle triangle) { if (backgroundWorker.CancellationPending) throw new OperationCanceledException(); //split triangle in 4 triangles: Point3D mid1 = Average(triangle.vertices[0], triangle.vertices[1]); Point3D mid2 = Average(triangle.vertices[1], triangle.vertices[2]); Point3D mid3 = Average(triangle.vertices[0], triangle.vertices[2]); List<Triangle> triangles = new List<Triangle> { new Triangle(new List<Point3D> { mid1, mid2, mid3 }), new Triangle(new List<Point3D> { mid1, mid3, triangle.vertices[0] }), new Triangle(new List<Point3D> { mid1, mid2, triangle.vertices[1] }), new Triangle(new List<Point3D> { mid2, mid3, triangle.vertices[2] }) }; pointlist.Add(new Point3D((int)Math.Floor(mid1.X), (int)Math.Floor(mid1.Y), (int)Math.Floor(mid1.Z))); pointlist.Add(new Point3D((int)Math.Floor(mid2.X), (int)Math.Floor(mid2.Y), (int)Math.Floor(mid2.Z))); pointlist.Add(new Point3D((int)Math.Floor(mid3.X), (int)Math.Floor(mid3.Y), (int)Math.Floor(mid3.Z))); //triangles.Add(new Triangle(new List<Point3D> { mid1, mid2, mid3 })); //triangles.Add(new Triangle(new List<Point3D> { mid1, mid3, triangle.vertices[0] })); //triangles.Add(new Triangle(new List<Point3D> { mid1, mid2, triangle.vertices[1] })); //triangles.Add(new Triangle(new List<Point3D> { mid2, mid3, triangle.vertices[2] })); //check for each triangle if bounds are smaller than 1x1x1, if not, split each again: foreach (Triangle splittriangle in triangles) { // foreach(Point3D point in splittriangle.vertices) // pointlist.Add(new Point3D((int)Math.Floor(point.X), (int)Math.Floor(point.Y), (int)Math.Floor(point.Z))); if (!splittriangle.BoundsSmallerThan(bounds)) Splittriangles(splittriangle); } //return splittriangles; } private Point3D Average(Point3D point1, Point3D point2) { return new Point3D((point1.X + point2.X) / 2.0, (point1.Y + point2.Y) / 2.0, (point1.Z + point2.Z) / 2.0); } private void conversioncompleted(object sender, RunWorkerCompletedEventArgs e) { progressWindow.Close(); pointlist.Clear(); if (!e.Cancelled) { mainWindow.RenderBlueprint(); } backgroundWorker.Dispose(); } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { System.Windows.Controls.TextBox t = (System.Windows.Controls.TextBox)sender; try { if (Convert.ToDouble(t.Text) >= 0) { } } catch { if (t.Text == "-") { t.Text = "-0"; t.Select(1, 1); } else { t.Text = "0"; t.Select(0, 1); } } this.scale = Convert.ToDouble(t.Text); } } public class Triangle { public IList<Point3D> vertices; public Triangle(IList<Point3D> vertices) { this.vertices = vertices; } public bool BoundsSmallerThan(Assimp.Vector3D bounds) { return (Math.Abs(vertices[0].X - vertices[1].X) < bounds.X && Math.Abs(vertices[0].X - vertices[2].X) < bounds.X && Math.Abs(vertices[2].X - vertices[1].X) < bounds.X && Math.Abs(vertices[0].Y - vertices[1].Y) < bounds.Y && Math.Abs(vertices[0].Y - vertices[2].Y) < bounds.Y && Math.Abs(vertices[2].Y - vertices[1].Y) < bounds.Y && Math.Abs(vertices[0].Z - vertices[1].Z) < bounds.Z && Math.Abs(vertices[0].Z - vertices[2].Z) < bounds.Z && Math.Abs(vertices[2].Z - vertices[1].Z) < bounds.Z); } } public class ColorTriangle : Triangle { public IList<Point3D> texturecoords; public ColorTriangle(IList<Point3D> vertices, IList<Point3D> texturecoords) : base(vertices) { this.texturecoords = texturecoords; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for Settings.xaml /// </summary> public partial class Settings : Window { MainWindow mainWindow; public Settings(MainWindow mainWindow) { this.mainWindow = mainWindow; InitializeComponent(); color_wire.Text = Properties.Settings.Default.wirecolor; color_blob.Text = Properties.Settings.Default.blobcolor; Update(); } void Update() { Button_Branch.Content = "Branch: \t\t" + Properties.Settings.Default.branch.ToString(); Button_SafeMode.Content = "Safe mode: \t" + (Properties.Settings.Default.safemode ? "ON" : "OFF"); Button_Debug.Content = "Debug Mode: \tNot Available"; Text_Path.Text = Properties.Settings.Default.steamapps; Text_Version.Content = "Version: \tV" + Properties.Settings.Default.version.ToString(); Button_wires.Content = "Wires: \t\t" + (Properties.Settings.Default.wires == true ? "ON" : "OFF"); Button_colorwires.Content = "ColorWires:\t" + (Properties.Settings.Default.colorwires == true ? "ON" : "OFF"); WiresOpacity.Text = Properties.Settings.Default.coloropacity.ToString(); } private void Button_Branch_Click(object sender, RoutedEventArgs e) { if(Properties.Settings.Default.branch.ToString() == "Test") { Properties.Settings.Default.branch = "Public"; } else { Properties.Settings.Default.branch = "Test"; } Update(); } private void Button_SafeMode_Click(object sender, RoutedEventArgs e) { Properties.Settings.Default.safemode = !Properties.Settings.Default.safemode; //MessageBox.Show("this doesn't affect anything yet\nWill allow you to swap any blocks with any blocks, can possibly brick your blueprint"); Update(); } private void Button_Debug_Click(object sender, RoutedEventArgs e) { } private void Text_Path_TextChanged(object sender, TextChangedEventArgs e) { var bc = new BrushConverter(); if (System.IO.Directory.Exists(Text_Path.Text)) { Text_Path.Background = (Brush)bc.ConvertFrom("#61937C"); Properties.Settings.Default.steamapps = Text_Path.Text; } else { Text_Path.Background = (Brush)bc.ConvertFrom("#81737C"); } } private void Button_update_Click(object sender, RoutedEventArgs e) { if(new Updater().CheckForUpdates()) { MessageBox.Show("updates available!"); } else { MessageBox.Show("up to date!"); } } private void Button_wires_Click(object sender, RoutedEventArgs e) { Properties.Settings.Default.wires = !Properties.Settings.Default.wires; Update(); } private void Save_settings_Click(object sender, RoutedEventArgs e) { if (!System.IO.Directory.Exists(Text_Path.Text)) { var bc = new BrushConverter(); Text_Path.Background = (Brush)bc.ConvertFrom("#ff0000"); } Properties.Settings.Default.Save(); this.Close(); MessageBox.Show("Settings saved!"); } private void Button_colorwires_Click(object sender, RoutedEventArgs e) { Properties.Settings.Default.colorwires = !Properties.Settings.Default.colorwires; Update(); } private void color_TextChanged(object sender, TextChangedEventArgs e) { TextBox textbox_color = (TextBox)sender; if (textbox_color.Text.Length == 7) { try { var bc = new BrushConverter(); string color = "#FF" + textbox_color.Text.Substring(1); textbox_color.Background = (Brush)bc.ConvertFrom(color); } catch { //MessageBox.Show("Please use the right format\n \"#123abc\" where 1-9,a-f (hex)"); textbox_color.Text = ""; } } else { var bc = new BrushConverter(); textbox_color.Text = "#2CE6E6"; textbox_color.Background = (Brush)bc.ConvertFrom("#2CE6E6"); } } private void color_SET_Click(object sender, RoutedEventArgs e) { this.mainWindow.openpaintpicker(); color_wire.Text = PaintSelector.PaintColor; Properties.Settings.Default.wirecolor = color_wire.Text; } private void color_SET2_Click(object sender, RoutedEventArgs e) { this.mainWindow.openpaintpicker(); color_blob.Text = PaintSelector.PaintColor; Properties.Settings.Default.blobcolor = color_blob.Text; } private void Opacity_TextChanged(object sender, TextChangedEventArgs e) { TextBox t = (TextBox)sender; try { if (Convert.ToInt32(t.Text) < 0) t.Text = "0"; if (Convert.ToInt32(t.Text) >255) t.Text = "255"; } catch { t.Text = "0"; t.Select(0, 1); } Properties.Settings.Default.coloropacity = Convert.ToByte(t.Text); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using Newtonsoft.Json.Linq; using System.Threading; using System.Drawing; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for OpenWindow.xaml /// </summary> public partial class OpenWindow : Window { MainWindow mainwindow; Thread loadbp; public OpenWindow(MainWindow mainWindow) { this.mainwindow = mainWindow; InitializeComponent(); //load mainwindow.blueprints in list loadbp = new Thread(new ThreadStart(Loadblueprints)); loadbp.SetApartmentState(ApartmentState.STA); loadbp.IsBackground = true; loadbp.Start(); //Loadblueprints(""); } public void Loadblueprints()//threaded { string searchby = ""; int totalbps = 0; while (true) { while(totalbps != Database.blueprints.Count()) { this.Dispatcher.Invoke((Action)(() => { searchby = TextBox_Search.Text; })); //filter: //if() try { List<Blueprint> items = new List<Blueprint>(); foreach (string path in Database.blueprints.Keys) { Blueprint blueprint = new Blueprint(path, Database.blueprints[path]); string name = blueprint.getname(); if ((searchby == "" || blueprint.getname().ToLower().Contains(searchby.ToLower()))&& Directory.Exists(path)) { items.Add(blueprint); } } this.Dispatcher.Invoke((Action)(() => { listBox_blueprints.ItemsSource = null; listBox_blueprints.Items.Clear(); listBox_blueprints.ItemsSource = items; })); } catch { } totalbps = Database.blueprints.Count(); } try { this.Dispatcher.Invoke((Action)(() => { if (Database.bprefresh == true) { Database.bprefresh = false; button_refresh_Copy_Click(null, null); } })); } catch { break; } Thread.Sleep(1000); } } private void button_refresh_Copy_Click(object sender, RoutedEventArgs e) { Label_name.Content = "/"; loadbp.Abort(); loadbp = new Thread(new ThreadStart(Loadblueprints)); loadbp.Start(); } private void ListBox_Selectionchanged(object sender, RoutedEventArgs e) { if(listBox_blueprints.SelectedIndex!=-1) { try { string bp = ((Blueprint)listBox_blueprints.SelectedItem).blueprintpath.ToString(); dynamic desc = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(System.IO.File.ReadAllText(bp + @"\description.json")); Label_name.Content = desc.name; } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void button_LOAD_Click(object sender, RoutedEventArgs e) { Load(); } public void Load() { Loadwindow l = new Loadwindow(); string bppath = ""; try { bppath = ((Blueprint)listBox_blueprints.SelectedItem).blueprintpath.ToString(); l.Show(); new BP(bppath); mainwindow.RenderBlueprint(); if (mainwindow.advancedconnections != null && mainwindow.advancedconnections.IsLoaded) mainwindow.advancedconnections.Update(); if (mainwindow.advancedcolorwindow != null && mainwindow.advancedcolorwindow.IsLoaded) mainwindow.advancedcolorwindow.Update(); if (mainwindow.swapblockswindow != null && mainwindow.swapblockswindow.IsLoaded) mainwindow.swapblockswindow.Update(); if (mainwindow.blockProperties != null && mainwindow.blockProperties.IsLoaded) mainwindow.blockProperties.Update(); if (mainwindow.areaProperties != null && mainwindow.areaProperties.IsLoaded) mainwindow.areaProperties.Update(); if (mainwindow.blockPropertiesRAW != null && mainwindow.blockPropertiesRAW.IsLoaded) mainwindow.blockPropertiesRAW.Update(); l.Close(); } catch (Exception e) { MessageBox.Show(e.Message); l.Close(); } } private void button_DELETE_Click(object sender, RoutedEventArgs e) { //messagebox YES/NO MessageBoxResult result = MessageBox.Show("Are you sure you want to remove this blueprint?"," ",MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.DefaultDesktopOnly); if(result == MessageBoxResult.Yes) { try { if(((Blueprint)listBox_blueprints.SelectedItem).blueprintpath.Contains(Database.steamapps)) { MessageBoxResult res2 = MessageBox.Show("Removing a workshop blueprint will result in the game complaining:\n'failed to find blahblah, verify integrity'!\n\nAre you sure you want to continue?\nYou will have to 'verify integrity' through steam", "WORKSHOP BLUEPRINT!", MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.DefaultDesktopOnly); if (res2 == MessageBoxResult.No) throw new OperationCanceledException("Canceled removing workshop blueprint"); } Directory.Delete(((Blueprint)listBox_blueprints.SelectedItem).blueprintpath, true); //Database.LoadBpsIn(Database.User_ + "\\blueprints"); Database.blueprints.Remove(((Blueprint)listBox_blueprints.SelectedItem).blueprintpath); button_refresh_Copy_Click(null, null); } catch (Exception ex) { MessageBox.Show(ex.Message,"failed to remove"); } } } } public class Blueprint { public string image { get; set; } public string blueprintpath { get; private set; } public BitmapSource imsource { get; private set; } //public string name { get; private set; } public Blueprint(string blueprintpath, BitmapSource src) { this.blueprintpath = blueprintpath; this.imsource = src; this.image = blueprintpath + "\\icon.png"; //name = getname(); } public string getname() { try { dynamic desc = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(System.IO.File.ReadAllText(blueprintpath + @"\description.json")); return desc.name.ToString().ToLower(); } catch { return null; } } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for AdvancedColor.xaml /// </summary> public partial class AdvancedColor : Window { MainWindow window; List<Item> ItemList; dynamic uuidsbackup; public AdvancedColor(MainWindow window) { this.window = window; InitializeComponent(); this.Update(); } public void Update() { if (uuidsbackup != BP.GetUsedUuids()) { ItemList = new List<Item> { new Item("any", "*") }; foreach (string uuid in BP.GetUsedUuids()) { if (Database.blocks.ContainsKey(uuid)) { ItemList.Add(new Item(Database.blocks[uuid].Name, uuid)); } } dynamic colorlist = new JObject(); foreach (dynamic body in BP.Blueprint.bodies) foreach(dynamic child in body.childs) { if (child.color.ToString().StartsWith("#")) child.color = child.color.ToString().Substring(1); if (colorlist[child.color.ToString().ToLower()] == null) { colorlist[child.color.ToString().ToLower()] = true; string c = child.color.ToString(); Button b = new Button(); var bc = new BrushConverter(); b.Background = (Brush)bc.ConvertFrom("#"+c); color_list.Items.Add(b); } } this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application comboBox_old.Items.Clear(); })); foreach (Item item in ItemList) { this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application comboBox_old.Items.Add(item); })); } } uuidsbackup = BP.GetUsedUuids(); } private void TextBox_color_TextChanged(object sender, TextChangedEventArgs e) { TextBox textbox_color = (TextBox)sender; if (textbox_color.Text.Length == 7) { try { var bc = new BrushConverter(); string color = "#FF" + textbox_color.Text.Substring(1); textbox_color.Background = (Brush)bc.ConvertFrom(color); } catch { MessageBox.Show("Please use the right format\n \"#123abc\" where 1-9,a-f (hex)"); } } else { var bc = new BrushConverter(); textbox_color.Background = (Brush)bc.ConvertFrom("#eeeeee"); } } private void Button3_Click(object sender, RoutedEventArgs e) { window.openpaintpicker(); textBox_color1.Text = PaintSelector.PaintColor; } private void Button3_Copy_Click(object sender, RoutedEventArgs e) { window.openpaintpicker(); textBox_color2.Text = PaintSelector.PaintColor; } private void Button1_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start("https://youtu.be/glLgQemUS2I?t=677"); } private void Button_Click(object sender, RoutedEventArgs e) { TextBox t1 = (TextBox)textBox_color1; Brush b = t1.Background; string oldcolor = "#" + (b as SolidColorBrush).Color.ToString().Substring(3); TextBox t2 = (TextBox)textBox_color2; Brush b1 = t2.Background; string newcolor = "#" + (b1 as SolidColorBrush).Color.ToString().Substring(3); int amountcolored = 0; foreach (dynamic body in BP.Blueprint.bodies) { foreach (dynamic child in body.childs) { string token = "#"; string color = child.color.ToString(); if (color[0] == '#') token = ""; if ((token + child.color.ToString().ToLower() == oldcolor.ToLower() || textBox_color1.Text == "#" || textBox_color1.Text == "") && ((comboBox_old.SelectedIndex <= 0) || child.shapeId.ToString() == ((Item)comboBox_old.SelectedItem).UUID.ToLower())) { amountcolored++; child.color = newcolor; } } } if(BP.Blueprint.joints != null) foreach (dynamic child in BP.Blueprint.joints) { string token = "#"; string color = child.color.ToString(); if (color[0] == '#') token = ""; if ((token + child.color.ToString().ToLower() == oldcolor.ToLower() || textBox_color1.Text == "#" || textBox_color1.Text == "") && ((comboBox_old.SelectedIndex <= 0) || child.shapeId.ToString() == ((Item)comboBox_old.SelectedItem).UUID.ToLower())) { amountcolored++; child.color = newcolor.Substring(1); } } if (comboBox_old.SelectedIndex < 0) comboBox_old.SelectedIndex = 0; string message = "++ " + amountcolored + " " + oldcolor + " " + ((Item)comboBox_old.SelectedItem).Name + " are now painted " + newcolor + " color"; if (textBox_color1.Text == "#" || textBox_color1.Text == "") message = "++ " + amountcolored + ((Item)comboBox_old.SelectedItem).Name + " are now painted " + newcolor + " color"; new System.Threading.Thread(new System.Threading.ThreadStart(() => { MessageBox.Show(message); })).Start(); if (amountcolored > 0) { BP.setblueprint(BP.Blueprint); BP.Description.description = BP.Description.description + "\n" + message; window.RenderBlueprint(); } } private void Color_list_SelectionChanged(object sender, SelectionChangedEventArgs e) { this.window.openpaintpicker(); PaintSelector.PaintColor = "#" + ((string)((dynamic)color_list.SelectedItem).Background.ToString()).Substring(3,6); if (MainWindow.paintSelector.IsLoaded) MainWindow.paintSelector.textbox_color.Text = PaintSelector.PaintColor; } } public class Item { public string Name { get; set; } public string UUID { get; set; } public Item(string Name, string UUID) { this.Name = Name; this.UUID = UUID; } public override string ToString() { return Name; } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.ComponentModel; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for Properties.xaml /// </summary> public partial class BlockProperties : Window { MainWindow mainwindow; List<Item> usedblocks; HashSet<string> uuidsbackup; dynamic backuplist; public BlockProperties(MainWindow mainwindow) { this.mainwindow = mainwindow; InitializeComponent(); //new Loadwindow(this).Show(); Loadwindow w = new Loadwindow(); w.Show(); Update(); w.Close(); } public void Update() { if (uuidsbackup != BP.GetUsedUuids()) { usedblocks = new List<Item> { new Item("any", "*") }; foreach (string uuid in BP.GetUsedUuids()) { if (Database.blocks.ContainsKey(uuid)) { usedblocks.Add(new Item(Database.blocks[uuid].Name.ToString(), uuid)); // fill the combobox! only runs once! } } filter_type.Items.Clear(); foreach (Item useditem in usedblocks) filter_type.Items.Add(useditem); } uuidsbackup = BP.GetUsedUuids(); filter_type.SelectedIndex = 0; int i = 0; { backuplist = new JObject(); //fill 'backup'list with all childs! foreach (dynamic body in BP.Blueprint.bodies) foreach (dynamic child in body.childs) { if (child.color.ToString().StartsWith("#")) child.color = child.color.ToString().Substring(1); child.blueprintIndex = i; child.blockname = Database.blocks.ContainsKey(child.shapeId.ToString()) ? Database.blocks[child.shapeId.ToString()].Name : "unknown part"; dynamic realpos = BP.getposandbounds(child); if (backuplist[realpos.pos.x.ToString()] == null) backuplist[realpos.pos.x.ToString()] = new JObject(); if (backuplist[realpos.pos.x.ToString()][realpos.pos.y.ToString()] == null) backuplist[realpos.pos.x.ToString()][realpos.pos.y.ToString()] = new JObject(); if (backuplist[realpos.pos.x.ToString()][realpos.pos.y.ToString()][realpos.pos.z.ToString()] == null) backuplist[realpos.pos.x.ToString()][realpos.pos.y.ToString()][realpos.pos.z.ToString()] = new JObject(); if (backuplist[realpos.pos.x.ToString()][realpos.pos.y.ToString()][realpos.pos.z.ToString()][realpos.color.ToString().ToLower()] == null) backuplist[realpos.pos.x.ToString()][realpos.pos.y.ToString()][realpos.pos.z.ToString()][realpos.color.ToString().ToLower()] = new JObject(); if (backuplist[realpos.pos.x.ToString()][realpos.pos.y.ToString()][realpos.pos.z.ToString()][realpos.color.ToString().ToLower()][realpos.shapeId.ToString().ToLower()] == null) backuplist[realpos.pos.x.ToString()][realpos.pos.y.ToString()][realpos.pos.z.ToString()][realpos.color.ToString().ToLower()][realpos.shapeId.ToString().ToLower()] = new JObject(); backuplist[realpos.pos.x.ToString()][realpos.pos.y.ToString()][realpos.pos.z.ToString()][realpos.color.ToString().ToLower()][realpos.shapeId.ToString().ToLower()][i.ToString()] = child; i++; } } //fill xyz: dynamic bounds = BP.GetBounds(); filter_x1.Text = bounds.minx.ToString(); filter_y1.Text = bounds.miny.ToString(); filter_z1.Text = bounds.minz.ToString(); filter_x2.Text = bounds.maxx.ToString(); filter_y2.Text = bounds.maxy.ToString(); filter_z2.Text = bounds.maxz.ToString(); filterupdate(); } private void Button_Help_Click(object sender, RoutedEventArgs e) { MessageBox.Show("find help here: \nhttp://youtube.com/c/brentbatch"); } private void Filter_SET_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); filter_color.Text = PaintSelector.PaintColor; } private void Filter_pos_TextChanged(object sender, TextChangedEventArgs e) { TextBox t = (TextBox)sender; try { if (Convert.ToInt32(t.Text) >= 0) { } } catch { if (t.Text == "-") { t.Text = "-0"; t.Select(1, 1); } else { t.Text = "0"; t.Select(0, 1); } } if (this.IsLoaded) filterupdate(); } private void filter_type_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.IsLoaded) filterupdate(); } private string filtercolor = null; private void filter_color_TextChanged(object sender, TextChangedEventArgs e) { TextBox textbox_color = (TextBox)sender; if (textbox_color.Text.Length == 7) { try { var bc = new BrushConverter(); string color = "#FF" + textbox_color.Text.Substring(1); textbox_color.Background = (Brush)bc.ConvertFrom(color); if (textbox_color.Name == "filter_color") filtercolor = textbox_color.Text; } catch { //MessageBox.Show("Please use the right format\n \"#123abc\" where 1-9,a-f (hex)"); textbox_color.Text = ""; } } else { var bc = new BrushConverter(); textbox_color.Background = (Brush)bc.ConvertFrom("#eeeeee"); if (textbox_color.Name == "filter_color") filtercolor = null; } if (this.IsLoaded) filterupdate(); } private void color_TextChanged(Object sender , TextChangedEventArgs e) { TextBox textbox_color = (TextBox)sender; if (textbox_color.Text.Length == 7) { try { var bc = new BrushConverter(); string color = "#FF" + textbox_color.Text.Substring(1); textbox_color.Background = (Brush)bc.ConvertFrom(color); } catch { //MessageBox.Show("Please use the right format\n \"#123abc\" where 1-9,a-f (hex)"); textbox_color.Text = ""; } } else { var bc = new BrushConverter(); textbox_color.Background = (Brush)bc.ConvertFrom("#eeeeee"); } } private void filterupdate() { // if (filter != null && filter.IsAlive) filter.Abort(); // filter = new Thread(new ThreadStart(filter_output_update)); // filter.SetApartmentState(ApartmentState.STA); // filter.Start(); Loadwindow l = new Loadwindow(); l.Show(); filter_output_update(); l.Close(); } //Thread filter; private void filter_output_update() { { dynamic bounds = BP.GetBounds(); int x1 = bounds.minx, y1 = bounds.maxx, z1 = bounds.miny, x2 = bounds.maxy, y2 = bounds.minz, z2 = bounds.maxz; string type = "*";//nullable! = any this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application if (filter_output.Items.Count > 0) filter_output.Items.Clear(); if (filter_x1.Text != "") x1 = Convert.ToInt32(filter_x1.Text); if (filter_y1.Text != "") y1 = Convert.ToInt32(filter_y1.Text); if (filter_z1.Text != "") z1 = Convert.ToInt32(filter_z1.Text); if (filter_x2.Text != "") x2 = Convert.ToInt32(filter_x2.Text); if (filter_y2.Text != "") y2 = Convert.ToInt32(filter_y2.Text); if (filter_z2.Text != "") z2 = Convert.ToInt32(filter_z2.Text);//0.1! = any if (filter_type.SelectedIndex < 0) filter_type.SelectedIndex = 0; if (filter_type.SelectedIndex >= 0) type = ((Item) filter_type.SelectedItem).UUID; this.mainwindow.setMarker2((x1 + x2+0.0f) / 2, (y1 + y2 + 0.0f) / 2, (z1 + z2 + 0.0f) / 2, (x2 - x1), (y2 - y1), (z2 - z1)); })); string color = filtercolor;//nullable! = any for (int x = x1; x <= x2; x++) if (backuplist[x.ToString()] != null) for (int y = y1; y < y2; y++) if (backuplist[x.ToString()][y.ToString()] != null) for (int z = z1; z < z2; z++) if (backuplist[x.ToString()][y.ToString()][z.ToString()] != null) { if (color == null) { foreach (dynamic xyzcolor in backuplist[x.ToString()][y.ToString()][z.ToString()]) if (type == "*") { foreach (dynamic childuuid in xyzcolor.Value) { foreach (dynamic child in childuuid.Value) this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application filter_output.Items.Add(child.Value); //any color any type })); } } else { if (xyzcolor.Value[type.ToLower()] != null) foreach (dynamic child in xyzcolor.Value[type.ToLower()]) this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application filter_output.Items.Add(child.Value); //any color , one type })); } } else { if (color.StartsWith("#")) color = color.Substring(1).ToLower(); if (backuplist[x.ToString()][y.ToString()][z.ToString()][color] != null) { if (type == "*") { foreach (dynamic childuuid in backuplist[x.ToString()][y.ToString()][z.ToString()][color]) { foreach (dynamic child in childuuid.Value) this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application filter_output.Items.Add(child.Value); //one color , any type })); } } else { if (backuplist[x.ToString()][y.ToString()][z.ToString()][color][type] != null) foreach (dynamic child in backuplist[x.ToString()][y.ToString()][z.ToString()][color][type]) this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application filter_output.Items.Add(child.Value); //one color, one type })); } } } } try { this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application disableAll(); })); } catch { } } } int selectedchildindex=-1; private void filter_output_SelectionChanged(object sender, SelectionChangedEventArgs e) { disableAll(); if (filter_output.SelectedIndex != -1) { var bc = new BrushConverter(); string selectedcolor = ((dynamic)filter_output.SelectedItem).color; string color = "#FF" + (selectedcolor.StartsWith("#")==true? selectedcolor.Substring(1): selectedcolor); //filter_output_color.Fill = (Brush)bc.ConvertFrom(color); //clear other options, enable/disable several dynamic selectedblock = ((dynamic)filter_output.SelectedItem); dynamic realpos = BP.getposandbounds(selectedblock); this.mainwindow.setMarker(Convert.ToInt32(realpos.pos.x) + (Convert.ToDouble(realpos.bounds.x)/2), Convert.ToInt32(realpos.pos.y) + (Convert.ToDouble(realpos.bounds.y) / 2), Convert.ToDouble(realpos.pos.z) + (Convert.ToDouble(realpos.bounds.z) / 2)); selectedchildindex = selectedblock.blueprintIndex; Edit_general.Visibility = Visibility.Visible; new_x.Text = selectedblock.pos.x; new_y.Text = selectedblock.pos.y; new_z.Text = selectedblock.pos.z; new_color.Text = "#" + selectedblock.color; new_xaxis.Text = selectedblock.xaxis; new_zaxis.Text = selectedblock.zaxis; if(selectedblock.controller != null) // { if(selectedblock.controller.mode != null) //logic gate! { new_gatemode.SelectedIndex = selectedblock.controller.mode; Edit_gate.Visibility = Visibility.Visible; //mode 0-5 } if(selectedblock.controller.buttonMode != null)//sensor! { // colorMode & range & color new_sensorcolormode.IsChecked = selectedblock.controller.colorMode; if (selectedblock.controller.colorMode == null) new_sensorcolormode.IsChecked = false; new_sensorrange.Text = selectedblock.controller.range; new_sensorcolor.Text = "#"+selectedblock.controller.color; if (selectedblock.controller.color == null) new_sensorcolor.Text = "#eeeeee"; Edit_sensor.Visibility = Visibility.Visible; } if (selectedblock.controller.luminance != null)//light! { //coneAngle & luminance new_coneangle.Text = selectedblock.controller.coneAngle; new_luminance.Text = selectedblock.controller.luminance; Edit_lamp.Visibility = Visibility.Visible; } if(selectedblock.controller.seconds != null)//timer { //seconds ticks new_timerseconds.Text = selectedblock.controller.seconds; new_timerticks.Text = selectedblock.controller.ticks; Edit_Timer.Visibility = Visibility.Visible; } if (selectedblock.controller.timePerFrame != null)//controller! { //playMode timePerFrame joints new_controllerloopmode.IsChecked = selectedblock.controller.playMode; new_controllertimeperframe.Text = selectedblock.controller.timePerFrame; new_controllercontrolls.Items.Clear(); if (selectedblock.controller.joints != null) foreach (dynamic joint in selectedblock.controller.joints) { joint.controller0 = joint.frames[0].targetAngle.ToString(); joint.controller1 = joint.frames[1].targetAngle.ToString(); joint.controller2 = joint.frames[2].targetAngle.ToString(); joint.controller3 = joint.frames[3].targetAngle.ToString(); joint.controller4 = joint.frames[4].targetAngle.ToString(); joint.controller5 = joint.frames[5].targetAngle.ToString(); joint.controller6 = joint.frames[6].targetAngle.ToString(); joint.controller7 = joint.frames[7].targetAngle.ToString(); joint.controller8 = joint.frames[8].targetAngle.ToString(); joint.controller9 = joint.frames[9].targetAngle.ToString(); new_controllercontrolls.Items.Add(joint); } /* if (selectedblock.controller.controllers != null) foreach (dynamic joint in selectedblock.controller.frames) { joint.controller0 = joint.frames[0].targetAngle.ToString(); joint.controller1 = joint.frames[1].targetAngle.ToString(); joint.controller2 = joint.frames[2].targetAngle.ToString(); joint.controller3 = joint.frames[3].targetAngle.ToString(); joint.controller4 = joint.frames[4].targetAngle.ToString(); joint.controller5 = joint.frames[5].targetAngle.ToString(); joint.controller6 = joint.frames[6].targetAngle.ToString(); joint.controller7 = joint.frames[7].targetAngle.ToString(); joint.controller8 = joint.frames[8].targetAngle.ToString(); joint.controller9 = joint.frames[9].targetAngle.ToString(); new_controllercontrolls.Items.Add(joint); }*/ Edit_controller.Visibility = Visibility.Visible; } } button_render.IsEnabled = true; } } private void disableAll() { Edit_controller.Visibility = Visibility.Collapsed; Edit_gate.Visibility = Visibility.Collapsed; Edit_general.Visibility = Visibility.Collapsed; Edit_lamp.Visibility = Visibility.Collapsed; Edit_sensor.Visibility = Visibility.Collapsed; Edit_Timer.Visibility = Visibility.Collapsed; button_render.IsEnabled = false; this.mainwindow.Marker = null; mainwindow.Image_blueprint.DataContext = ""; mainwindow.Image_blueprint.DataContext = mainwindow; } private void SET_Copy_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); new_sensorcolor.Text = PaintSelector.PaintColor; } private void SET_Copy1_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); new_lampcolor.Text = PaintSelector.PaintColor; } private void SET_Copy2_Click(object sender, RoutedEventArgs e) { this.mainwindow.openpaintpicker(); new_color.Text = PaintSelector.PaintColor; } private void new_controllercontrolls_SelectionChanged(object sender, SelectionChangedEventArgs e) { new_selectedcontroller.DataContext = (dynamic)new_controllercontrolls.SelectedItem; if (new_controllercontrolls.SelectedItem != null && ((dynamic)new_controllercontrolls.SelectedItem).reverse == true) new_controllerreverse.IsChecked = true; } private void new_controller_joint_Changed(object sender, TextChangedEventArgs e) { dynamic test = (dynamic)new_selectedcontroller.DataContext; } private void new_controllerreverse_Click(object sender, RoutedEventArgs e) { new_controller_joint_Changed(null, null); } private void button_help_Click_1(object sender, RoutedEventArgs e) { System.Windows.MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Watch this video on how to use: \nhttps://www.youtube.com/c/brentbatch", "Tutorial?", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk); if (messageBoxResult.ToString() == "Yes") { System.Diagnostics.Process.Start("https://youtu.be/glLgQemUS2I?t=799"); } } private void button_render_Click(object sender, RoutedEventArgs e) { //blueprintIndex foreach(dynamic body in BP.Blueprint.bodies) foreach(dynamic child in body.childs) if (Convert.ToInt32(child.blueprintIndex) == selectedchildindex) { if (Edit_controller.IsVisible) { child.controller.joints.Clear(); foreach (dynamic item in (dynamic)new_controllercontrolls.Items) { item.startAngle = Convert.ToInt32(item.startAngle); item.frames[0].targetAngle = Convert.ToInt32(item.controller0); item.frames[1].targetAngle = Convert.ToInt32(item.controller1); item.frames[2].targetAngle = Convert.ToInt32(item.controller2); item.frames[3].targetAngle = Convert.ToInt32(item.controller3); item.frames[4].targetAngle = Convert.ToInt32(item.controller4); item.frames[5].targetAngle = Convert.ToInt32(item.controller5); item.frames[6].targetAngle = Convert.ToInt32(item.controller6); item.frames[7].targetAngle = Convert.ToInt32(item.controller7); item.frames[8].targetAngle = Convert.ToInt32(item.controller8); item.frames[9].targetAngle = Convert.ToInt32(item.controller9); child.controller.joints.Add(item); } } if(Edit_gate.IsVisible) { child.controller.mode = new_gatemode.SelectedIndex; } if(Edit_general.IsVisible) { child.pos.x = Convert.ToInt32(new_x.Text); child.pos.y = Convert.ToInt32(new_y.Text); child.pos.z = Convert.ToInt32(new_z.Text); child.color = new_color.Text; child.xaxis = Convert.ToInt32(new_xaxis.Text); child.zaxis = Convert.ToInt32(new_zaxis.Text); dynamic selectedblock = ((dynamic)filter_output.SelectedItem); selectedblock.pos.x = child.pos.x; selectedblock.pos.y = child.pos.y; selectedblock.pos.z = child.pos.z; selectedblock.xaxis = child.xaxis; selectedblock.zaxis = child.zaxis; } if(Edit_sensor.IsVisible) { child.controller.colorMode = new_sensorcolormode.IsChecked; child.controller.range = Convert.ToInt32(new_sensorrange.Text); child.controller.color = new_sensorcolor.Text; } if(Edit_lamp.IsVisible) { child.controller.coneAngle = Convert.ToInt32(new_coneangle.Text); child.controller.luminance = Convert.ToInt32(new_luminance.Text); } if(Edit_Timer.IsVisible) { child.controller.seconds = Convert.ToInt32(new_timerseconds.Text); child.controller.ticks = Convert.ToInt32(new_timerticks.Text); } } Loadwindow w = new Loadwindow(); w.Show(); BP.Description.description = BP.Description.description += "++ Applied some block property changes "; BP.setblueprint(BP.Blueprint); this.mainwindow.RenderBlueprint(); //Update(); dynamic bounds = BP.GetBounds(); int x1 = bounds.minx, y1 = bounds.maxx, z1 = bounds.miny, x2 = bounds.maxy, y2 = bounds.minz, z2 = bounds.maxz; this.Dispatcher.Invoke((Action)(() => {//this refer to form in WPF application if (filter_x1.Text != "") x1 = Convert.ToInt32(filter_x1.Text); if (filter_y1.Text != "") y1 = Convert.ToInt32(filter_y1.Text); if (filter_z1.Text != "") z1 = Convert.ToInt32(filter_z1.Text); if (filter_x2.Text != "") x2 = Convert.ToInt32(filter_x2.Text); if (filter_y2.Text != "") y2 = Convert.ToInt32(filter_y2.Text); if (filter_z2.Text != "") z2 = Convert.ToInt32(filter_z2.Text);//0.1! = any this.mainwindow.setMarker2((x1 + x2 + 0.0f) / 2, (y1 + y2 + 0.0f) / 2, (z1 + z2 + 0.0f) / 2, (x2 - x1), (y2 - y1), (z2 - z1)); })); w.Close(); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); this.mainwindow.Marker = null; this.mainwindow.setMarker2(0, 0, 0, 0, 0, 0); this.mainwindow.Marker2 = new System.Windows.Media.Media3D.Model3DGroup(); } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; using System.Windows.Input; using System.Text; using Assimp; using System.Threading; using System.Threading.Tasks; using System.Windows.Media.Media3D; using HelixToolkit.Wpf; using System.Windows.Media; using System.Drawing; using System.Windows.Threading; using System.Windows.Data; using System.Windows.Media.Imaging; using System.Runtime.InteropServices; using System.Xml; using System.Text.RegularExpressions; using Newtonsoft.Json; namespace Advanced_Blueprint_Tools { public static class Database { public static string steamapps { get; private set; } public static string User_ { get; private set; } //path public static string ScrapData { get; private set; } = ""; public static string SurvivalData { get; private set; } = ""; private static string ModDatabase = ""; public static long UserID { get; private set; } public static Dictionary<string, Blockobject> blocks = new Dictionary<string, Blockobject>();//uuid, block public static Dictionary<string, string> usedmods = new Dictionary<string, string>();//id, name public static Dictionary<string, BitmapSource> blueprints = new Dictionary<string, BitmapSource>();//path, img public static List<Notification> Notifications = new List<Notification>(); public static bool bprefresh; public static void LoadAllBlocks() { LoadVanillaObjects(); LoadModObjects(); } public static string findPaths() { string userdir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Axolot Games\\Scrap Mechanic\\User"; DateTime lasthigh = new DateTime(1900, 1, 1); string dir = ""; foreach (string subdir in Directory.GetDirectories(userdir)) //get user_numbers folder that is last used { DirectoryInfo fi1 = new DirectoryInfo(subdir + @"\blueprints"); DateTime created = fi1.LastWriteTime; fi1 = new DirectoryInfo(subdir); if (created > lasthigh) { dir = subdir; lasthigh = created; } } User_ = dir; steamapps = Properties.Settings.Default.steamapps; /* {//not yet if(Properties.Settings.Default.times == 3) System.Diagnostics.Process.Start("http://www.youtube.com/c/brentbatch?sub_confirmation=1"); }*/ if (File.Exists("steamapps") && !File.Exists("config")) File.Copy("steamapps", "config"); dynamic config = new JObject(); if (File.Exists("config") && !System.IO.Directory.Exists(steamapps + @"\common\Scrap Mechanic\Data\Objects\Database\ShapeSets")) { try { config = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(File.ReadAllText("steamapps")); } catch { } if (config.steamapps != null) { steamapps = config.steamapps.ToString(); Properties.Settings.Default.steamapps = config.steamapps.ToString(); } if (config.times != null) Properties.Settings.Default.times = Convert.ToInt32(config.times.ToString()); if (config.safemode == true) Properties.Settings.Default.safemode = config.safemode == true ? true : false; if (config.wires == true) Properties.Settings.Default.wires = config.wires == true ? true : false; if (config.colorwires == true) Properties.Settings.Default.colorwires = config.colorwires == true ? true : false; if (config.wirecolor != null) Properties.Settings.Default.wirecolor = config.wirecolor; if (config.blobcolor != null) Properties.Settings.Default.blobcolor = config.blobcolor; if (config.coloropacity != null) Properties.Settings.Default.coloropacity = Convert.ToByte(config.coloropacity.ToString()); } Properties.Settings.Default.times++; if (steamapps == null) { steamapps = ""; } if (System.IO.Directory.Exists(Environment.GetEnvironmentVariable("ProgramFiles(x86)") + @"\Steam\SteamApps\common\Scrap Mechanic\Data\Objects\Database\ShapeSets")) { steamapps = Environment.GetEnvironmentVariable("ProgramFiles(x86)") + "\\steam\\SteamApps"; } else if (System.IO.Directory.Exists(@"C:\Program Files (x86)\Steam\SteamApps\common\Scrap Mechanic\Data\Objects\Database\ShapeSets")) { steamapps = @"C:\Program Files (x86)\Steam\SteamApps"; } else if (System.IO.Directory.Exists(@"D:\Program Files (x86)\Steam\SteamApps\common\Scrap Mechanic\Data\Objects\Database\ShapeSets")) { steamapps = @"D:\Program Files (x86)\Steam\SteamApps"; } else if (System.IO.Directory.Exists(steamapps + @"\common\Scrap Mechanic\Data\Objects\Database\ShapeSets")) { //i already know steamapps! } else { while (!System.IO.Directory.Exists(ScrapData + @"\Objects\Database\ShapeSets")) { MessageBoxResult result = MessageBox.Show("could not find the gamefiles folder which is needed to get the block properties\nPlease select the Scrap Mechanic folder, It contains: Cache,Data,Logs,Release,...\n\nSteam Library > Right click scrap mechanic > properties > Local Files > browse local files > Copy path from the folder", "Unusual folder location!", MessageBoxButton.OKCancel); if (result != MessageBoxResult.OK) { MessageBox.Show("continuing without loading resources.\nWorking processes: \n- Loading blueprints -although a bit broken\n- sphere generator\n- mirror mode"); } System.Windows.Forms.FolderBrowserDialog fbD = new System.Windows.Forms.FolderBrowserDialog(); fbD.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); fbD.ShowDialog(); string scrap = fbD.SelectedPath; try { steamapps = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(scrap)); } catch { steamapps = ""; } ScrapData = scrap + "\\Data"; } } if (ScrapData == "") ScrapData = steamapps + @"\common\Scrap Mechanic\Data"; if (SurvivalData == "") SurvivalData = steamapps + @"\common\Scrap Mechanic\Survival"; if (steamapps != "") ModDatabase = steamapps + @"\workshop\content\387990"; Properties.Settings.Default.steamapps = steamapps; Properties.Settings.Default.Save(); return steamapps; } public static void LoadAllBlueprints() { string blueprintdir = User_ + "\\blueprints"; UserID = Convert.ToInt64(Path.GetFileName(User_).ToString().Substring(5)); LoadBpsIn(blueprintdir); if (Directory.Exists(steamapps + @"\workshop\content\387990")) LoadBpsIn(steamapps + @"\workshop\content\387990"); Thread updatebps = new Thread(new ThreadStart(() => { while(true) { if (Directory.GetLastWriteTime(blueprintdir) > DateTime.Now.AddSeconds(-2)) LoadBpsIn(blueprintdir); if (Directory.Exists(steamapps + @"\workshop\content\387990") && Directory.GetLastWriteTime(steamapps + @"\workshop\content\387990") > DateTime.Now.AddSeconds(-2)) LoadBpsIn(Database.steamapps + @"\workshop\content\387990"); Thread.Sleep(1500); } })); updatebps.IsBackground = true; updatebps.Start(); } public static void LoadBpsIn(string directory) { ImageToBitmapSourceConverter converter = new ImageToBitmapSourceConverter(); foreach (string blueprint in Directory.GetDirectories(directory)) { if (File.Exists(blueprint + @"\blueprint.json") /*&& File.Exists(blueprint + @"\icon.png") && File.Exists(blueprint + @"\description.json")*/) { if (!File.Exists(blueprint + @"\description.json")) { dynamic desc = new JObject(); desc.name = "unnamed blueprint"; desc.description = "has no name"; //create new description File.WriteAllText(blueprint + @"\description.json", desc.ToString()); } if (File.Exists(blueprint + @"\icon.png")) { Image image = Image.FromFile(blueprint + @"\icon.png"); if (!blueprints.ContainsKey(blueprint)) blueprints.Add(blueprint, (BitmapSource)converter.Convert((Image)image.Clone(),null,null,null)); else { if (!blueprints[blueprint].Equals((Image)image.Clone())) { //blueprints[blueprint].; blueprints[blueprint] = (BitmapSource)converter.Convert((Image)image.Clone(), null, null, null); } } image.Dispose(); } else { //load with 'missing icon' or sth Image image = Image.FromFile("missingicon.bmp"); if (!blueprints.ContainsKey(blueprint)) blueprints.Add(blueprint, (BitmapSource)converter.Convert((Image)image.Clone(), null, null, null)); else { if (!blueprints[blueprint].Equals((Image)image.Clone())) { //blueprints[blueprint].; blueprints[blueprint] = (BitmapSource)converter.Convert((Image)image.Clone(), null, null, null); } } image.Dispose(); } } else if(File.Exists(blueprint + @"\icon.png")) { //go over all files, if no .txt files or directories, remove folder bool dirs = false; foreach (string subdir in Directory.GetDirectories(blueprint)) { if (Directory.Exists(subdir)) dirs = true; } if(!dirs) { bool hasTxtFile = false; foreach (string subfile in Directory.GetFiles(blueprint)) { string ext = Path.GetExtension(subfile); if (ext == ".txt") hasTxtFile = true; } if (!hasTxtFile) Directory.Delete(blueprint, true); } } } } private static void LoadVanillaObjects() { string inventorydecpath = ScrapData + @"\Gui\Language\English\InventoryItemDescriptions.json"; JObject inventoryitemdesc = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(System.IO.File.ReadAllText(inventorydecpath)) as dynamic; //VANILLA BLOCKS: dynamic blockz = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>( System.IO.File.ReadAllText(ScrapData + @"\Objects\Database\ShapeSets\blocks.json")); foreach (dynamic prop in blockz) { foreach (dynamic part in blockz[prop.Name]) { string name = "unnamed shape " + part.uuid.ToString(); if (inventoryitemdesc[part.uuid.ToString()] != null) name = inventoryitemdesc[part.uuid.ToString()].title.ToString(); blocks.Add( part.uuid.ToString(), new Block(ScrapData, name, "vanilla", part,null) ); } } //VANILLA PARTS: string ScrapShapeSets = ScrapData + @"\Objects\Database\ShapeSets"; foreach (string file in System.IO.Directory.GetFiles(ScrapShapeSets)) { dynamic parts = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(System.IO.File.ReadAllText(file)); foreach (dynamic prop in parts) { foreach (dynamic part in parts[prop.Name]) { try { string name = "unnamed shape " + part.uuid.ToString(); if (inventoryitemdesc[part.uuid.ToString()] != null) name = inventoryitemdesc[part.uuid.ToString()].title.ToString(); if (part.renderable != null)//only adding parts here, modded shit not allowed blocks.Add( part.uuid.ToString(), new Part(ScrapData, name, "vanilla", part, null, true) ); } catch (Exception e) { Notifications.Add(new Notification( "unloadable file", new Task(() => { System.Windows.MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show(e.Message+"\n\nopen file?", "error in vanilla files!", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); if (messageBoxResult == MessageBoxResult.Yes) { System.Diagnostics.Process.Start(file); } }) )); } } } } } private static void LoadModObjects() { List<String> workshoppages = new List<string>(); if (ModDatabase != "") foreach (string folder in System.IO.Directory.GetDirectories(ModDatabase)) { //modded blocks: if (System.IO.Directory.Exists(folder + @"\Objects\Database\ShapeSets"))//its a mod, not a blueprint (workshop dir contains blueprints too) { dynamic inventoryitemdesc = new JObject(); try { inventoryitemdesc = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(System.IO.File.ReadAllText(folder + @"\Gui\Language\English\inventoryDescriptions.json")); if (inventoryitemdesc == null) inventoryitemdesc = new JObject(); } catch {//not parseable if (!workshoppages.Contains("http://steamcommunity.com/sharedfiles/filedetails/?id=" + System.IO.Path.GetFileName(folder))) workshoppages.Add("http://steamcommunity.com/sharedfiles/filedetails/?id=" + System.IO.Path.GetFileName(folder)); Notifications.Add(new Notification( "unloadable file", new Task(() => { System.Windows.MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("item desc not parseable, open location?", "unparseable file!", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); if (messageBoxResult == MessageBoxResult.Yes) { System.Diagnostics.Process.Start(folder +@"\Gui\Language\"); } }) )); } int conflictusemod = 0; //(1 use old, 2 use new foreach (string file in System.IO.Directory.GetFiles(folder + @"\Objects\Database\ShapeSets")) if (System.IO.Path.GetExtension(file).ToLower() == ".json") { dynamic parts = null; try { //try to parse the usual way string text = System.IO.File.ReadAllText(file); parts = Newtonsoft.Json.Linq.JObject.Parse(text); } catch (Exception e) {//not parseable, add to naughty list if (!workshoppages.Contains("http://steamcommunity.com/sharedfiles/filedetails/?id=" + System.IO.Path.GetFileName(folder))) workshoppages.Add("http://steamcommunity.com/sharedfiles/filedetails/?id=" + System.IO.Path.GetFileName(folder)); Notifications.Add(new Notification( "unparseable file", new Task(() => { System.Windows.MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("unparseable file found:\n" + file, "unparseable file!\nError:\n" + e.Message, System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); if (messageBoxResult == MessageBoxResult.Yes) { System.Diagnostics.Process.Start(file); } }) )); } dynamic moddesc = Newtonsoft.Json.Linq.JObject.Parse(System.IO.File.ReadAllText(folder + @"\description.json")); if (parts != null) foreach (dynamic prop in parts) { foreach (dynamic part in parts[prop.Name]) { try { if (!(part is JObject)) { continue; } if (moddesc.name != null) { if (conflictusemod == 0 && blocks.ContainsKey(part.uuid.ToString()) && blocks[part.uuid.ToString()].Path != folder) { conflictusemod = 1;//keep mod1 string uuid = part.uuid.ToString(); string mod1 = blocks[part.uuid.ToString()].Mod; string mod2 = moddesc.name; if (mod1.ToString() == "vanilla") { conflictusemod = 2;//overwrite, people have old installed mods in vanilla files! } else { MessageBoxResult messageBoxResult = MessageBox.Show ("\"" + mod1 + "\" is using some(or all) uuid's of mod \"" + mod2 + "\"\n\nOverwrite blocks from \"" + mod1 + "\" with the blocks from \"" + mod2 + "\" ?\n\n" + file, "Conflicting mods!!", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); if (messageBoxResult == MessageBoxResult.Yes) { conflictusemod = 2;//overwrite! } } //System.Diagnostics.Process.Start(blocks[part.uuid.ToString()].Modfolder.ToString()); //System.Diagnostics.Process.Start(folder); } if (conflictusemod != 1)//OVERWRITE if 2 , 0=no conflict { usedmods[moddesc.fileId.ToString()] = moddesc.name.ToString(); string name = "unnamed shape " + part.uuid.ToString(); if (inventoryitemdesc[part.uuid.ToString()] != null) name = inventoryitemdesc[part.uuid.ToString()].title.ToString(); if (part.renderable != null)//part { if(blocks.ContainsKey(part.uuid.ToString())) { //OVERWRITE blocks[part.uuid.ToString()] = new Part(folder, name, moddesc.name.ToString(), part, moddesc); } else blocks.Add( part.uuid.ToString(), new Part(folder, name, moddesc.name.ToString(), part, moddesc) ); } else //block! { if (blocks.ContainsKey(part.uuid.ToString())) { //OVERWRITE blocks[part.uuid.ToString()] = new Block(folder, name, moddesc.name.ToString(), part, moddesc); } else blocks.Add( part.uuid.ToString(), new Block(folder, name, moddesc.name.ToString(), part, moddesc) ); //part.dif asg nor } } } else { Notifications.Add(new Notification( "broken appdata mod", new Task(() => { MessageBox.Show("broken mod description!\nfolder: " + folder); }) )); } } catch { if(!workshoppages.Contains("http://steamcommunity.com/sharedfiles/filedetails/?id=" + System.IO.Path.GetFileName(folder))) workshoppages.Add("http://steamcommunity.com/sharedfiles/filedetails/?id=" + System.IO.Path.GetFileName(folder)); } } } } } } try //appdata mods { string appdatamods = User_ + "\\Mods"; foreach (string folder in System.IO.Directory.GetDirectories(appdatamods)) { if (System.IO.Directory.Exists(folder + @"\Objects\Database\ShapeSets")) { dynamic inventoryitemdesc = new JObject(); try { inventoryitemdesc = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(System.IO.File.ReadAllText(folder + @"\Gui\Language\English\inventoryDescriptions.json")); if (inventoryitemdesc == null) inventoryitemdesc = new JObject(); } catch (Exception e) { Notifications.Add(new Notification( "broken appdata mod", new Task(() => { MessageBox.Show(e.Message + "\n\n" + folder+ @"\Gui\Language\English\inventoryDescriptions.json", "broken appdata mod!", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); }) )); } foreach (string file in System.IO.Directory.GetFiles(folder + @"\Objects\Database\ShapeSets")) if (System.IO.Path.GetExtension(file).ToLower() == ".json") { dynamic parts = null; try { parts = Newtonsoft.Json.Linq.JObject.Parse(System.IO.File.ReadAllText(file)); } catch (Exception e) { Notifications.Add(new Notification( "broken appdata mod", new Task(() => { MessageBox.Show(e.Message + "\n\n" + file, "broken appdata mod!", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); }) )); } dynamic moddesc = Newtonsoft.Json.Linq.JObject.Parse(System.IO.File.ReadAllText(folder + @"\description.json")); if (parts != null) foreach (dynamic prop in parts) { foreach (dynamic part in parts[prop.Name]) { try { if (!(part is JObject)) { continue; } if (moddesc.name != null) { if (moddesc.fileId == null) { Random r = new Random();//fucking jank fix moddesc.fileId = r.Next().ToString(); } usedmods[moddesc.fileId.ToString()] = moddesc.name.ToString(); string name = "unnamed shape " + part.uuid.ToString(); if (inventoryitemdesc[part.uuid.ToString()] != null) name = inventoryitemdesc[part.uuid.ToString()].title.ToString(); if (part.renderable != null)//part { if (blocks.ContainsKey(part.uuid.ToString())) { blocks[part.uuid.ToString()] = new Part(folder,name, moddesc.name.ToString(),part, moddesc); } else blocks.Add( part.uuid.ToString(), new Part(folder, name, moddesc.name.ToString(), part, moddesc) ); } else //block! { if (blocks.ContainsKey(part.uuid.ToString())) { blocks[part.uuid.ToString()] = new Block(folder, name, moddesc.name.ToString(), part, moddesc); } else blocks.Add( part.uuid.ToString(), new Block(folder, name, moddesc.name.ToString(), part, moddesc) ); } } else { MessageBox.Show("broken mod description!\nFile: " + folder); //MessageBox.Show("you have a broken mod!\nFile: " + file,"", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); } } catch (Exception e) { MessageBox.Show(e.Message + "\n" + file, "\nSomething wrong with a self-made mod", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); } } } } } } } catch (Exception e) { MessageBox.Show(e.Message, "Error while loading appdata mods", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); } if (workshoppages.Count != 0) { Notifications.Add(new Notification( "unloadable mods --workshop pages", new Task(() => { System.Windows.MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Mods: " + usedmods.Count() + "\nBlocks loaded: " + blocks.Count() + "\n\nFound mods that weren't able to be loaded\nEither broken or made by a lazy modder\n\npls Remove or Unsub\n\nOpen Workshop pages?", "Found unloadable mods!", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); if (messageBoxResult == MessageBoxResult.Yes) { foreach (string page in workshoppages) { System.Diagnostics.Process.Start(page); } } }) )); } } } public abstract class Blockobject { public string Path { get; private set; }//path to mod public string Mod { get; private set; } = "";//modname public string Name { get; private set; } = "unnamed shape";//block name public int id { get; private set; }//mod id private Bitmap icon; public bool glass { get; protected set; } = false; public Blockobject(string path, string Name, string Modname, dynamic desc) { this.Path = path; this.Name = Name; this.Mod = Modname; if(desc != null) { this.id = desc.fileId; } } public Bitmap GetIcon(string uuid) { if (icon != null) return icon; if(File.Exists(this.Path + @"\Gui\IconMap.png") && File.Exists(this.Path + @"\Gui\IconMap.xml")) { Bitmap IconMap = new Bitmap(this.Path + @"\Gui\IconMap.png"); XmlDocument doc = new XmlDocument(); doc.LoadXml(File.ReadAllText(this.Path + @"\Gui\IconMap.xml")); string iconstring = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc).Replace("@", ""); dynamic icons = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(iconstring); string[] size = icons.MyGUI.Resource.Group.size.ToString().Split(' '); foreach (dynamic icon in icons.MyGUI.Resource.Group.Index) { if([email protected]() == uuid) { string[] point = icon.Frame.point.ToString().Split(' '); Bitmap bmp = IconMap.Clone(new System.Drawing.Rectangle(Convert.ToInt32(point[0]), Convert.ToInt32(point[1]), Convert.ToInt32(size[0]), Convert.ToInt32(size[1])), IconMap.PixelFormat); IconMap.Dispose(); this.icon = bmp; return bmp; } } } return null; } public abstract int GetWeight(dynamic bounds = null); public xyzpair BoundsByRotation(xyzpair bounds, int xaxis, int zaxis) { if (Math.Abs(xaxis) == 3) { if (Math.Abs(zaxis) == 2) { return new xyzpair(bounds.y, bounds.z, bounds.x); } else if (Math.Abs(zaxis) == 1) { return new xyzpair(bounds.z, bounds.y, bounds.x); } } if (Math.Abs(xaxis) == 2) { if (Math.Abs(zaxis) == 3) { return new xyzpair(bounds.y, bounds.x, bounds.z); } else if (Math.Abs(zaxis) == 1) { return new xyzpair(bounds.z, bounds.x, bounds.y); } } if (Math.Abs(xaxis) == 1) { if (Math.Abs(zaxis) == 2) { return new xyzpair(bounds.x, bounds.z, bounds.y); } } return bounds; } protected Model3D Render(double x, double y, double z, Geometry3D geometry3D, xyzpair bounds, string color, int xaxis, int zaxis) { //x => x - centerx; if (color.StartsWith("#")) color = color.Substring(1); System.Windows.Media.Color c = System.Windows.Media.Color.FromRgb(Convert.ToByte(color.Substring(0, 2), 16), Convert.ToByte(color.Substring(2, 2), 16), Convert.ToByte(color.Substring(4, 2), 16)); if (glass == true) c.A = 120; System.Windows.Media.Media3D.Material material = new DiffuseMaterial(new SolidColorBrush(c)); //for textures: prob need to switch to: https://www.nuget.org/packages/HelixToolkit.Wpf.SharpDX/ //https://github.com/helix-toolkit/helix-toolkit/issues/471 Model3D renderedblock = new GeometryModel3D { Geometry = geometry3D, Material = material }; #region Rotation and Translation renderedblock.Transform = new MatrixTransform3D(new Matrix3D()); Transform3DGroup baseLinkMove = new Transform3DGroup(); TranslateTransform3D baseLinkTranslate = new TranslateTransform3D(); RotateTransform3D baseLinkRotatex = new RotateTransform3D(); RotateTransform3D baseLinkRotatez = new RotateTransform3D(); bool xpos = xaxis > 0; bool zpos = zaxis > 0; switch (Math.Abs(xaxis)) { case 1: baseLinkRotatex.Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, 0, xpos ? 0 : 1), 180); baseLinkMove.Children.Add(baseLinkRotatex); switch (Math.Abs(zaxis)) { case 1: MessageBox.Show("Incorrect rotationset found !"); break; case 2: baseLinkRotatez.Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(zpos ? -1 : 1, 0, 0), 90); break; case 3: baseLinkRotatez.Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(zpos ? 0 : 1, 0, 0), 180); break; } baseLinkMove.Children.Add(baseLinkRotatez); break; case 2: baseLinkRotatex.Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, 0, xpos ? 1 : -1), 90); baseLinkMove.Children.Add(baseLinkRotatex); switch (Math.Abs(zaxis)) { case 1: baseLinkRotatez.Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, zpos ? 1 : -1, 0), 90); break; case 2: MessageBox.Show("Incorrect rotationset found !"); break; case 3: baseLinkRotatez.Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, zpos ? 0 : 1, 0), 180); break; } baseLinkMove.Children.Add(baseLinkRotatez); break; case 3: baseLinkRotatex.Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, xpos ? -1 : 1, 0), 90); baseLinkMove.Children.Add(baseLinkRotatex); switch (Math.Abs(zaxis)) { case 1: baseLinkRotatez.Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, 0, (zpos == xpos) ? 1 : 0), 180); break; case 2: baseLinkRotatez.Rotation = new AxisAngleRotation3D(new System.Windows.Media.Media3D.Vector3D(0, 0, (zpos == xpos) ? -1 : 1), 90); break; case 3: MessageBox.Show("Incorrect rotationset found !"); break; } baseLinkMove.Children.Add(baseLinkRotatez); break; } //rotations translate! baseLinkTranslate.OffsetX = x + (float)(bounds.x) / 2; baseLinkTranslate.OffsetY = y + (float)(bounds.y) / 2; baseLinkTranslate.OffsetZ = z + (float)(bounds.z) / 2; baseLinkMove.Children.Add(baseLinkTranslate); renderedblock.Transform = baseLinkMove; #endregion return renderedblock; } } public class Block : Blockobject { private dynamic block; //private static Dictionary<dynamic,Geometry3D> previousGeometries; private int weight = -1; public Block(string path, string Name, string Modname, JObject block, JObject desc) :base( path, Name, Modname, desc) { this.block = block; if (this.block != null && this.block.glass != null && this.block.glass == true) base.glass = true; } public override int GetWeight(dynamic bounds) { if (this.weight != -1) return this.weight; double density = 500; if (this.block.density != null) density = this.block.density; int weight = (int)(density * (int)bounds.x + density * (int)bounds.y + density * (int)bounds.z); return weight; } public Model3D Render(double x, double y, double z, dynamic bounds, string color, int xaxis, int zaxis) { var meshBuilder = new MeshBuilder(false, false); int bx = Convert.ToInt32(bounds.x); int by = Convert.ToInt32(bounds.y); int bz = Convert.ToInt32(bounds.z); meshBuilder.AddBox(new Point3D(0, 0, 0), bx, by, bz); Geometry3D geometry3D = meshBuilder.ToMesh(true); return base.Render(x, y, z, geometry3D, BoundsByRotation(new xyzpair(bx, by, bz), xaxis, zaxis), color, xaxis, zaxis); } } public class Part : Blockobject { public string uuid { get; private set; } private dynamic part; private Geometry3D geometry3D; private xyzpair bounds; private int weight = -1; public enum properties { unknown, noninteractive, spotlight, engine, thruster, steering, seat, timedjoint, lever, button, sensor, logic, timer, piston, simpleInteractive, bearing, spring, radio, horn, tone, scripted } private properties property = properties.unknown; public bool IsConnectable { get { return (GetProperty() != properties.noninteractive) && (this.property != properties.bearing) && (this.property != properties.spring); } private set { } } public properties GetProperty() { if (property == properties.unknown) { if (part.spotlight != null) this.property = properties.spotlight; else if (part.engine != null) this.property = properties.engine; else if (part.thruster != null) this.property = properties.thruster; else if (part.steering != null) this.property = properties.steering; else if (part.seat != null) this.property = properties.seat; else if (part.timedjoint != null) this.property = properties.timedjoint; else if (part.lever != null) this.property = properties.lever; else if (part.button != null) this.property = properties.button; else if (part.sensor != null) this.property = properties.sensor; else if (part.logic != null) this.property = properties.logic; else if (part.timer != null) this.property = properties.timer; else if (part.piston != null) this.property = properties.piston; else if (part.simpleInteractive != null) this.property = properties.simpleInteractive; else if (part.bearing != null) this.property = properties.bearing; else if (part.spring != null) this.property = properties.spring; else if (part.radio != null) this.property = properties.radio; else if (part.horn != null) this.property = properties.horn; else if (part.tone != null) this.property = properties.tone; else if (part.scripted != null) this.property = properties.scripted; else this.property = properties.noninteractive; } return property; } public Part(string path, string Name, string Modname, JObject part, JObject desc, bool prerender = false ) : base(path, Name, Modname, desc) { this.part = part; if (!(this.part.renderable is JObject)) { String render = this.part.renderable.ToString().Replace(@"/", @"\"); String renderablePath = render;// = this.Path + r.Substring(r.IndexOf('/')).Replace(@"/", @"\"); if (render.ToLower().StartsWith("$game_data")) { renderablePath = Database.ScrapData + render.Substring(10); } if (render.ToLower().StartsWith("$mod_data")) { renderablePath = base.Path + render.Substring(9); } if (render.ToLower().StartsWith("$survival_data")) { renderablePath = Database.SurvivalData + render.Substring(14); } if (render.ToLower().StartsWith("../data")) { renderablePath = base.Path + render.Substring(7); } String json = System.IO.File.ReadAllText(renderablePath); // FIX THE FUCKING SHIT JSON BY DEVS: String reverseJson = new string(json.Reverse().ToArray()); int curlyOpenBracketCount = reverseJson.Count<char>(f => f == '{'); int curlyCloseBracketCount = reverseJson.Count<char>(f => f == '}'); while (curlyCloseBracketCount > curlyOpenBracketCount) { reverseJson = reverseJson.Substring(reverseJson.IndexOf('}')+1); curlyOpenBracketCount = reverseJson.Count<char>(f => f == '{'); curlyCloseBracketCount = reverseJson.Count<char>(f => f == '}'); } int blockyOpenBracketCount = reverseJson.Count<char>(f => f == '['); int blockyCloseBracketCount = reverseJson.Count<char>(f => f == ']'); while (blockyCloseBracketCount > blockyOpenBracketCount) { reverseJson = reverseJson.Substring(reverseJson.IndexOf(']') + 1); blockyOpenBracketCount = reverseJson.Count<char>(f => f == '['); blockyCloseBracketCount = reverseJson.Count<char>(f => f == ']'); } json = new string(reverseJson.Reverse().ToArray()); dynamic renderable = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json) as dynamic; this.part.renderable = renderable; } this.uuid = this.part.uuid; if (prerender == true) { new Thread(new ThreadStart(() => { this.GetGeometry(); })).Start(); this.GetProperty(); this.GetBounds(); } } public xyzpair GetBounds() { if(this.bounds == null) this.bounds = xyzpair.getPartBounds(part); return this.bounds; } public override int GetWeight(dynamic bounds) { if (this.weight != -1) return this.weight; double density = 500; if (this.part.density != null) density = this.part.density; int weight = (int)(density * (int)bounds.x + density* (int)bounds.y + density * (int)bounds.z); return weight; } public dynamic GetBoundsDynamic() { this.GetBounds(); dynamic bounds = new JObject(); bounds.x = this.bounds.x; bounds.y = this.bounds.y; bounds.z = this.bounds.z; return bounds; } public Model3D Render(double x, double y, double z, string color, int xaxis,int zaxis) { return base.Render(x, y, z, GetGeometry(), BoundsByRotation(GetBounds(), xaxis,zaxis), color, xaxis, zaxis); } public Geometry3D GetGeometry() { if(geometry3D != null) return geometry3D; //if (part.renderable.lodList[0].subMeshList != null) // foreach (dynamic submesh in part.renderable.lodList[0].subMeshList) // if (submesh.material.ToString() == "Glass") // base.glass = true; //part.renderable.lodList[].subMeshList[].textureList[] //part.renderable.lodList[].subMeshMap.Shark.textureList[] string meshlocation = part.renderable.lodList[0].mesh.ToString(); this.geometry3D = LoadMesh(meshlocation); return geometry3D; } private Geometry3D LoadMesh(string meshlocation) { Geometry3D geometry = null; try { bool game = false; if (meshlocation.ToLower().StartsWith("$game_data")) { meshlocation = meshlocation.Substring(10); meshlocation = Database.ScrapData + meshlocation; game = true; } if (meshlocation.ToLower().StartsWith("$mod_data")) { meshlocation = meshlocation.Substring(9); meshlocation = base.Path + meshlocation; } if (meshlocation.ToLower().StartsWith("$survival_data")) { meshlocation = meshlocation.Substring(14); meshlocation = Database.SurvivalData + meshlocation; } if (meshlocation.ToLower().StartsWith("../data")) { meshlocation = meshlocation.Substring(7); meshlocation = base.Path + meshlocation; game = true; } string location = meshlocation; if (System.IO.Path.GetExtension(meshlocation) != ".obj") { string obj = System.IO.Path.GetDirectoryName(meshlocation) + "\\" + System.IO.Path.GetFileNameWithoutExtension(meshlocation) + ".obj"; if (File.Exists(obj)) location = obj;//loading obj is prefered string meshes = obj.Replace(System.IO.Path.GetDirectoryName(Path), "Meshes"); if (game == true) meshes = obj.Replace(System.IO.Path.GetDirectoryName(Database.ScrapData), "Meshes"); if (File.Exists(meshes)) { location = meshes;//if converted obj in install files exists, use it } } Scene a = new AssimpImporter().ImportFile(location); var meshBuilder = new MeshBuilder(false, false); foreach(Mesh m in a.Meshes) { foreach (Face face in m.Faces) { IList<Point3D> vertices = new List<Point3D>(); foreach (uint i in face.Indices) { vertices.Add(new Point3D(m.Vertices[i].X, m.Vertices[i].Y, m.Vertices[i].Z)); } meshBuilder.AddPolygon(vertices); vertices = new List<Point3D>(); } if (false) { try { var texturecoords = m.GetTextureCoords(0); meshBuilder.TextureCoordinates = new PointCollection(); foreach (Assimp.Vector3D vec in m.GetTextureCoords(0)) { meshBuilder.TextureCoordinates.Add(new System.Windows.Point(Convert.ToDouble(vec.X), Convert.ToDouble(vec.Y))); } } catch (Exception edd) { MessageBox.Show(edd.Message); } } } //meshBuilder.Normals = m.Normals; //meshBuilder.Tangents = m.Tangents; //meshBuilder.BiTangents = m.BiTangents; geometry = meshBuilder.ToMesh(true); } catch (Exception e) { bool devmode = false; if(devmode)//create meshes structure inside tool folder { string toolmesh = meshlocation.Replace(System.IO.Path.GetDirectoryName(Path), "Meshes"); System.IO.Directory.CreateDirectory(System.IO.Directory.GetParent(toolmesh).ToString()); if(!File.Exists(toolmesh)) File.Copy(meshlocation, toolmesh); } //failed to load .fbx/mesh file //construct geometry out of pointlist var meshBuilder = new MeshBuilder(false, false); if (part.box != null) { meshBuilder.AddBox(new Point3D(0, 0, 0),Convert.ToDouble(part.box.x), Convert.ToDouble(part.box.y), Convert.ToDouble(part.box.z)); return meshBuilder.ToMesh(true); } if (part.cylinder != null) { Point3D p1 = new Point3D(0, 0, 0); Point3D p2 = new Point3D(0, 0, 0); double margin = Convert.ToDouble(part.cylinder.margin); double depth = Convert.ToDouble(part.cylinder.depth); if (part.cylinder.axis.ToString().ToLower() == "x") { p1.X -= depth / 2; p2.X += depth / 2; } if (part.cylinder.axis.ToString().ToLower() == "y") { p1.Y -= depth / 2; p2.Y += depth / 2; } if (part.cylinder.axis.ToString().ToLower() == "z") { p1.Z -= depth / 2; p2.Z += depth / 2; } meshBuilder.AddCylinder(p1, p2, Convert.ToDouble(part.cylinder.diameter) * margin, (Convert.ToInt32(part.cylinder.diameter) + 5 ) * 2); return meshBuilder.ToMesh(true); } if(part.hull != null) { if(part.hull.pointList != null && part.hull.pointList.Count > 5) { List<Point3D> points = new List<Point3D>(); foreach(dynamic point in part.hull.pointList) { points.Add(new Point3D( Convert.ToDouble(point.x) * Convert.ToInt32(part.hull.x), Convert.ToDouble(point.y) * Convert.ToInt32(part.hull.y), Convert.ToDouble(point.z) * Convert.ToInt32(part.hull.z))); } meshBuilder.AddPolygon(points); return meshBuilder.ToMesh(true); } else { meshBuilder.AddBox(new Point3D(0, 0, 0), Convert.ToInt32(part.hull.x), Convert.ToInt32(part.hull.y), Convert.ToInt32(part.hull.z)); return meshBuilder.ToMesh(true); } } MessageBox.Show("error building mesh", "", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.OK, MessageBoxOptions.DefaultDesktopOnly); //shouldn't be able to get to this line. } return geometry; } } public class xyzpair { public int x; public int y; public int z; public xyzpair(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public static xyzpair getPartBounds(dynamic part) { dynamic bounds = getDynamicPartBounds(part); xyzpair b = new xyzpair(1,1,1); b.x = bounds.x; b.y = bounds.y; b.z = bounds.z; return b; } private static dynamic getDynamicPartBounds(dynamic part) { dynamic bounds = new JObject(); if (part.box != null) { return part.box; } if (part.hull != null) { bounds.x = part.hull.x; bounds.y = part.hull.y; bounds.z = part.hull.z; return bounds; } if (part.cylinder != null) { if (part.cylinder.axis.ToString().ToLower() == "x") { bounds.x = part.cylinder.depth; bounds.y = part.cylinder.diameter; bounds.z = part.cylinder.diameter; return bounds; } else if (part.cylinder.axis.ToString().ToLower() == "y") { bounds.x = part.cylinder.diameter; bounds.y = part.cylinder.depth; bounds.z = part.cylinder.diameter; return bounds; } else if (part.cylinder.axis.ToString().ToLower() == "z") { bounds.x = part.cylinder.diameter; bounds.y = part.cylinder.diameter; bounds.z = part.cylinder.depth; return bounds; } } bounds.X = 1; bounds.Y = 1; bounds.Z = 1; MessageBox.Show("no bounds\n\nImpossible senario. please report"); return bounds; } } [ValueConversion(typeof(Image), typeof(BitmapSource))] public class ImageToBitmapSourceConverter : IValueConverter { [DllImport("gdi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeleteObject(IntPtr value); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Image myImage = (Image)value; var bitmap = new Bitmap(myImage); IntPtr bmpPt = bitmap.GetHbitmap(); BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmpPt, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); //freeze bitmapSource and clear memory to avoid memory leaks bitmapSource.Freeze(); DeleteObject(bmpPt); return bitmapSource; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Shapes; using Newtonsoft.Json.Linq; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for Circle_generator.xaml /// </summary> public partial class Circle_generator : Window { private MainWindow mainwindow; public Circle_generator(MainWindow window) { this.mainwindow = window; InitializeComponent(); } private void Button_Help_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start("https://youtu.be/glLgQemUS2I?t=1479"); } private void Button_Create_Click(object sender, RoutedEventArgs e) { float X = Convert.ToInt32(TextBox_X.Text); float Y = Convert.ToInt32(TextBox_Y.Text); //float Z = Convert.ToInt32(TextBox_Z.Text); float t = 0.4f + (float)Convert.ToDouble(TextBox_thickness.Text); dynamic circle = new JObject(); HashSet<Point3D> points = new HashSet<Point3D>(); double precision = 0.95; double pp = 0; for (float x = -X; x < X; x++) for (float y = -Y; y < Y; y++) if ((Math.Pow(x / X, 2) + Math.Pow(y / Y, 2)) < precision && (Math.Pow((x ) / (X - t), 2) + Math.Pow((y ) / (Y - t), 2)) > (precision-pp)) { points.Add(new Point3D(x, y, 1)); } circle = BlueprintOptimizer.CreateBlueprintFromPoints(points); if (circle.bodies[0].childs.Count > 0) { string message = "++ An ellipse/circle with " + circle.bodies[0].childs.Count + " shapes has been generated!"; Random r = new Random(); string blueprintpath = Database.User_ + "\\Blueprints\\Generatedellipse-" + r.Next() + r.Next(); dynamic description = new JObject(); description.description = "generated ellipsoid"; description.name = "generated ellipse/circle" + r.Next(); description.type = "Blueprint"; description.version = 0; if (BP.Blueprintpath == null) {//no blueprint exists, initialize new one new BP(blueprintpath, circle, description); } else {//overwrite current blueprint BP.setblueprint(circle); BP.Description.description += message; } mainwindow.RenderBlueprint(); } else { MessageBox.Show("no circle has been generated"); } } private dynamic block(int x, int y, int z, dynamic bounds) { dynamic block = new JObject(); block.color = "5DB7E7"; block.pos = new JObject(); block.pos.x = x; block.pos.y = y; block.pos.z = z; block.bounds = new JObject(); block.bounds.x = bounds.x; block.bounds.y = bounds.y; block.bounds.z = bounds.z; block.shapeId = "a6c6ce30-dd47-4587-b475-085d55c6a3b4"; block.xaxis = 1; block.zaxis = 3; return block; } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox t = (TextBox)sender; try { if (Convert.ToDouble(t.Text) < 0 ){ t.Text = "0"; } } catch { t.Text = "0"; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for NotificationWindow.xaml /// </summary> public partial class NotificationWindow : Window { public NotificationWindow() { InitializeComponent(); fill_listbox(); listBox_notis.MouseDoubleClick += new MouseButtonEventHandler(Notification_Click); new Task(() => { try { int amountnotis = 0; while (true) { this.Dispatcher.Invoke((Action)(() => { if (amountnotis != Database.Notifications.Count) this.fill_listbox(); amountnotis = Database.Notifications.Count; if (amountnotis == 0) this.Close(); })); Thread.Sleep(2000); } } catch { } }).Start(); } private void fill_listbox() { listBox_notis.Items.Clear(); foreach (Notification notification in Database.Notifications) { listBox_notis.Items.Add(notification); } } private void Notification_Click(object sender, RoutedEventArgs e) { if(listBox_notis.SelectedIndex>-1) { Notification currentnoti = ((Notification)listBox_notis.SelectedItem); currentnoti.performTask(); Database.Notifications.Remove(((Notification)listBox_notis.SelectedItem)); fill_listbox();//refresh } } } public class Notification { public string description { get; private set; } private Task task; //public string tag{get; private set;} public void performTask() { try { if (task != null) task.Start(); } catch (Exception e) { MessageBox.Show(e.Message, "\nerror while showing notification"); } } public Notification(string description, Task task) { this.description = description; this.task = task; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Advanced_Blueprint_Tools { using System.Windows.Media; using System.Windows.Media.Media3D; using HelixToolkit.Wpf; using System.Threading; public class MainViewModel { /// <summary> /// Initializes a new instance of the <see cref="MainViewModel"/> class. /// </summary> public MainViewModel() { // Create a model group var modelGroup = new Model3DGroup(); // Create a mesh builder and add a box to it var meshBuilder = new MeshBuilder(false, false); meshBuilder.AddBox(new Point3D(0, 5, 5), 2, 2, 5); meshBuilder.AddBox(new Rect3D(0, 0, 1.2, 1, 5, 0.4)); MeshGeometry3D g = new MeshGeometry3D(); // Create a mesh from the builder (and freeze it) var mesh = meshBuilder.ToMesh(true); // Create some materials var greenMaterial = MaterialHelper.CreateMaterial(Colors.Green); var redMaterial = MaterialHelper.CreateMaterial(Colors.Red); var blueMaterial = MaterialHelper.CreateMaterial(Colors.Blue); var insideMaterial = MaterialHelper.CreateMaterial(Colors.Yellow); //The Importer to load .obj files ModelImporter importer = new ModelImporter(); //The Material (Color) that is applyed to the importet objects Material material = new DiffuseMaterial(new SolidColorBrush(Colors.White)); importer.DefaultMaterial = material; Model3D block = importer.Load(@"D:\Program Files (x86)\Steam\SteamApps\workshop\content\387990\877698157\Objects\Mesh\Seat.obj"); //modelGroup.Children.Add(block); // Add 3 models to the group (using the same mesh, that's why we had to freeze it) modelGroup.Children.Add(new GeometryModel3D { Geometry = mesh, Material = greenMaterial, BackMaterial = insideMaterial }); //modelGroup.Children.Add(new GeometryModel3D { Geometry = mesh, Transform = new TranslateTransform3D(-2, 0, 0), Material = redMaterial, BackMaterial = insideMaterial }); //modelGroup.Children.Add(new GeometryModel3D { Geometry = mesh, Transform = new TranslateTransform3D(2, 0, 0), Material = blueMaterial, BackMaterial = insideMaterial }); // Set the property, which will be bound to the Content property of the ModelVisual3D (see MainWindow.xaml) this.Model = modelGroup; } /// <summary> /// Gets or sets the model. /// </summary> /// <value>The model.</value> public Model3D Model { get; set; } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Threading; using System.Diagnostics; namespace Advanced_Blueprint_Tools { class Updater { public bool CheckForUpdates() //for current branch & version: 'properties.settings' { try { var request = (HttpWebRequest)WebRequest.Create("https://raw.githubusercontent.com/brentbatch/blueprinttool/master/version.json"); request.UserAgent = "VSTS-Get"; request.ContentType = "application/json"; request.Method = "GET"; WebResponse response = request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); var result = reader.ReadToEnd(); dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(result); int gotoversion = Convert.ToInt32(json.Public.version.ToString()); if (Properties.Settings.Default.branch == "Test") { gotoversion = Convert.ToInt32(json.Test.version.ToString()); } /* if (Properties.Settings.Default.version > gotoversion && Properties.Settings.Default.branch != "Test") {//going from high version to public branch(lower version) Database.Notifications.Add(new Notification("manual update required", new Task(() => { System.Windows.MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("going from Test version to public version requires a manual re-install\nYou'll need to remove the current version and install public version yourself\n\nOpen download link of 'public' branch in browser?", "Update", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); if (messageBoxResult == MessageBoxResult.Yes) { System.Diagnostics.Process.Start("https://github.com/brentbatch/blueprinttool/archive/master.zip");//public } //manual update }) )); return true; }*/ if (Properties.Settings.Default.version < gotoversion || (Properties.Settings.Default.version > gotoversion && Properties.Settings.Default.branch != "Test")) {//normal update Database.Notifications.Add(new Notification("Update Available!", new Task(() => { System.Windows.MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show("Found a new update for branch: "+ Properties.Settings.Default.branch +"\n\nDo you want to update to this version?\ncurrent:"+ Properties.Settings.Default.version+ "\nbranch version:"+gotoversion.ToString()+"\n\nWould you like to download this version?", "Update Available!", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk, MessageBoxResult.Yes, MessageBoxOptions.DefaultDesktopOnly); if (messageBoxResult == MessageBoxResult.Yes) { string root = Directory.GetDirectoryRoot("Meshes") + "bptools\\"; if (File.Exists(root + "update.zip")) File.Delete(root + "update.zip"); string applicationfiles = ""; if (!Directory.Exists(root)) Directory.CreateDirectory(root); if (Properties.Settings.Default.branch == "Test") { //System.Diagnostics.Process.Start("https://github.com/brentbatch/Blueprinttool_test/archive/master.zip"); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (WebClient webClient = new WebClient()) { webClient.DownloadFile("https://github.com/brentbatch/Blueprinttool_test/archive/master.zip", root+"update.zip"); } //create new desktop shortcuts applicationfiles = root + "Update\\Blueprinttool_test-master\\Application Files"; } catch (Exception e) { MessageBox.Show(e.Message); } } else {//public //System.Diagnostics.Process.Start("https://github.com/brentbatch/Blueprinttool/archive/master.zip"); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (WebClient webClient = new WebClient()) { webClient.DownloadFile("https://github.com/brentbatch/Blueprinttool/archive/master.zip", @"update.zip"); } applicationfiles = root + "Update\\Blueprinttool-master\\Application Files"; } catch (Exception e) { MessageBox.Show(e.Message); } } String ZipPath = root + @"update.zip"; String extractPath = root + @"Update"; string startPath = root + @"start"; //System.IO.Compression.ZipFile.CreateFromDirectory(startPath, ZipPath); string master = Path.GetDirectoryName(applicationfiles); if (File.Exists(master + "\\Advanced Blueprint Tools.application")) File.Delete(master + "\\Advanced Blueprint Tools.application"); if (File.Exists(master + "\\README.md")) File.Delete(master + "\\README.md"); if (File.Exists(master + "\\version.json")) File.Delete(master + "\\version.json"); if (File.Exists(master + "\\setup.exe")) File.Delete(master + "\\setup.exe"); try { System.IO.Compression.ZipFile.ExtractToDirectory(ZipPath, extractPath); } catch { } dynamic config = new JObject(); config.steamapps = Properties.Settings.Default.steamapps; config.times = Properties.Settings.Default.times; config.branch = Properties.Settings.Default.branch; config.wires = Properties.Settings.Default.wires; config.safemode = Properties.Settings.Default.safemode; config.colorwires = Properties.Settings.Default.colorwires; config.wirecolor = Properties.Settings.Default.wirecolor; config.blobcolor = Properties.Settings.Default.blobcolor; config.coloropacity = Properties.Settings.Default.coloropacity; DateTime lasthigh = new DateTime(1900, 1, 1); string findlastversionname = ""; foreach (string subdir in Directory.GetDirectories(applicationfiles)) //get user_numbers folder that is last used { DirectoryInfo fi1 = new DirectoryInfo(subdir); DateTime created = fi1.LastWriteTime; fi1 = new DirectoryInfo(subdir); if (created > lasthigh) { findlastversionname = subdir; lasthigh = created; } } File.WriteAllText(findlastversionname + "\\config", config.ToString()); object shDesktop = (object)"Desktop"; IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell(); string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\Advanced Blueprint Tools.lnk"; IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress); shortcut.Description = "Shortcut for blueprint tool "+gotoversion; shortcut.TargetPath = findlastversionname + "\\Advanced Blueprint Tools.exe"; shortcut.WorkingDirectory = findlastversionname; shortcut.Save(); Process.Start(shortcutAddress); Environment.Exit(0); } }) )); return true; } } catch { Database.Notifications.Add(new Notification("unable to check for updates",null)); } return false; } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media.Media3D; namespace Advanced_Blueprint_Tools { class BlueprintOptimizer { public static dynamic optimizeblueprint(dynamic blueprint) { dynamic optimizedblueprint = new JObject(); //code return blueprint; } public static dynamic CreateBlueprintFromPoints(HashSet<Point3D> pointlist) { Dictionary<Point3D, Bounds> mergex = new Dictionary<Point3D, Bounds>(); int i = 0; foreach(Point3D point in pointlist) if(!pointlist.Contains(new Point3D(point.X-1,point.Y, point.Z))) { while (pointlist.Contains(new Point3D(point.X + i, point.Y, point.Z))) { //pointlist.Remove(new Point3D(point.X + i, point.Y, point.Z)); if (!mergex.ContainsKey(point)) mergex.Add(point, new Bounds { x = 1, y = 1, z = 1 }); else mergex[point].x++; i++; } i = 0; } pointlist.Clear(); Dictionary<Point3D, Bounds> mergey = new Dictionary<Point3D, Bounds>(); foreach(Point3D point in mergex.Keys) if(!(mergex.ContainsKey(new Point3D(point.X, point.Y-1, point.Z)) && mergex[new Point3D(point.X, point.Y, point.Z)].x == mergex[new Point3D(point.X, point.Y - 1, point.Z)].x)) { while (mergex.ContainsKey(new Point3D(point.X, point.Y + i, point.Z)) && mergex[new Point3D(point.X, point.Y + i, point.Z)].x == mergex[point].x)//x bound need to be same to merge { //mergex.Remove(neighbourkey); if (!mergey.ContainsKey(point)) mergey.Add(point, mergex[point]); else mergey[point].y++; i++; } i = 0; } mergex.Clear(); Dictionary<Point3D, Bounds> mergez = new Dictionary<Point3D, Bounds>(); foreach (Point3D point in mergey.Keys) if (!(mergey.ContainsKey(new Point3D(point.X, point.Y , point.Z-1)) && mergey[new Point3D(point.X, point.Y, point.Z)].x == mergey[new Point3D(point.X, point.Y, point.Z - 1)].x && mergey[new Point3D(point.X, point.Y, point.Z)].y == mergey[new Point3D(point.X, point.Y, point.Z - 1)].y)) { while (mergey.ContainsKey(new Point3D(point.X, point.Y, point.Z + i)) && mergey[new Point3D(point.X, point.Y, point.Z + i)].x == mergey[point].x && mergey[new Point3D(point.X, point.Y, point.Z + i)].y == mergey[point].y) { //mergex.Remove(neighbourkey); if (!mergez.ContainsKey(point)) mergez.Add(point, mergey[point]); else mergez[point].z++; i++; } i = 0; } mergey.Clear(); dynamic blueprint = new JObject(); blueprint.version = 1; blueprint.bodies = new JArray(); blueprint.bodies.Add(new JObject()); blueprint.bodies[0].childs = new JArray(); int amountgenerated = 0; int negz = 1;//-1/1 foreach(var keypair in mergez) { dynamic child = new JObject(); child.color = "5DB7E7"; child.pos = new JObject(); child.pos.x = (int)Math.Floor(keypair.Key.X); child.pos.y = (int)Math.Floor(keypair.Key.Y); child.pos.z = (int)Math.Floor(keypair.Key.Z); child.bounds = new JObject(); child.bounds.x = keypair.Value.x; child.bounds.y = keypair.Value.y; child.bounds.z = keypair.Value.z; child.shapeId = "a6c6ce30-dd47-4587-b475-085d55c6a3b4"; child.xaxis = 1; child.zaxis = negz*3; blueprint.bodies[0].childs.Add(child); amountgenerated++; } return blueprint; } public static dynamic CreateBlueprintFromPointsAndColor(HashSet<Tuple<Point3D, string>> colorpoints) { Dictionary<Point3D, Bounds> mergex = new Dictionary<Point3D, Bounds>(); int i = 0; int j = 0; foreach (var point in colorpoints) if (!colorpoints.Contains(new Tuple<Point3D, string>( new Point3D(point.Item1.X - 1, point.Item1.Y, point.Item1.Z), point.Item2))) { while (colorpoints.Contains(new Tuple<Point3D, string>(new Point3D(point.Item1.X + i, point.Item1.Y, point.Item1.Z), point.Item2))) { //pointlist.Remove(new Point3D(point.X + i, point.Y, point.Z)); if (!mergex.ContainsKey(point.Item1)) mergex.Add(point.Item1, new Bounds { x = 1, y = 1, z = 1, color = point.Item2 }); else mergex[point.Item1].x++; i++; } i = 0; j++; } colorpoints.Clear(); Dictionary<Point3D, Bounds> mergey = new Dictionary<Point3D, Bounds>(); foreach (Point3D point in mergex.Keys) if (!(mergex.ContainsKey(new Point3D(point.X, point.Y - 1, point.Z)) && mergex[new Point3D(point.X, point.Y, point.Z)].x == mergex[new Point3D(point.X, point.Y - 1, point.Z)].x && mergex[new Point3D(point.X, point.Y, point.Z)].color == mergex[new Point3D(point.X, point.Y - 1, point.Z)].color)) { while (mergex.ContainsKey(new Point3D(point.X, point.Y + i, point.Z)) && mergex[new Point3D(point.X, point.Y + i, point.Z)].x == mergex[point].x && mergex[new Point3D(point.X, point.Y + i, point.Z)].color == mergex[point].color)//x bound need to be same to merge { //mergex.Remove(neighbourkey); if (!mergey.ContainsKey(point)) mergey.Add(point, mergex[point]); else mergey[point].y++; i++; } i = 0; } mergex.Clear(); Dictionary<Point3D, Bounds> mergez = new Dictionary<Point3D, Bounds>(); foreach (Point3D point in mergey.Keys) if (!(mergey.ContainsKey(new Point3D(point.X, point.Y, point.Z - 1)) && mergey[new Point3D(point.X, point.Y, point.Z)].x == mergey[new Point3D(point.X, point.Y, point.Z - 1)].x && mergey[new Point3D(point.X, point.Y, point.Z)].y == mergey[new Point3D(point.X, point.Y, point.Z - 1)].y && mergey[new Point3D(point.X, point.Y, point.Z)].color == mergey[new Point3D(point.X, point.Y, point.Z - 1)].color)) { while (mergey.ContainsKey(new Point3D(point.X, point.Y, point.Z + i)) && mergey[new Point3D(point.X, point.Y, point.Z + i)].x == mergey[point].x && mergey[new Point3D(point.X, point.Y, point.Z + i)].y == mergey[point].y && mergey[new Point3D(point.X, point.Y, point.Z + i)].color == mergey[point].color) { //mergex.Remove(neighbourkey); if (!mergez.ContainsKey(point)) mergez.Add(point, mergey[point]); else mergez[point].z++; i++; } i = 0; } mergey.Clear(); dynamic blueprint = new JObject(); blueprint.version = 1; blueprint.bodies = new JArray(); blueprint.bodies.Add(new JObject()); blueprint.bodies[0].childs = new JArray(); int amountgenerated = 0; int negz = 1;//-1/1 foreach (var keypair in mergez) { dynamic child = new JObject(); child.color = keypair.Value.color; child.pos = new JObject(); child.pos.x = (int)Math.Floor(keypair.Key.X); child.pos.y = (int)Math.Floor(keypair.Key.Y); child.pos.z = (int)Math.Floor(keypair.Key.Z); child.bounds = new JObject(); child.bounds.x = keypair.Value.x; child.bounds.y = keypair.Value.y; child.bounds.z = keypair.Value.z; child.shapeId = "a6c6ce30-dd47-4587-b475-085d55c6a3b4"; child.xaxis = 1; child.zaxis = negz * 3; blueprint.bodies[0].childs.Add(child); amountgenerated++; } return blueprint; } public class Bounds { public string color; public int y; public int z; public int x; } } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for required_mods.xaml /// </summary> public partial class required_mods : Window { private dynamic Mods; public required_mods(dynamic Mods) { this.Mods = Mods.mods; InitializeComponent(); foreach (dynamic mod in this.Mods) { listBox_mods.Items.Add(mod);//new mod(mod.name.ToString(), mod.author.ToString(), mod.url.ToString(), true) } listBox_mods.MouseDoubleClick += new MouseButtonEventHandler(Mod_Click); listBox_mods.SelectionChanged += new SelectionChangedEventHandler(Mod_Click); } private void Mod_Click(object sender, RoutedEventArgs e) { ListBox b = (ListBox)sender; dynamic mod = (b.SelectedItem); MessageBoxResult messageBoxResult = MessageBox.Show ("Name: "+mod.name+"\nAuthor: "+mod.author+"\nUrl: "+mod.url+"\n\nWould you like to go to this mod page?", "Selected Mod -provided by http://scrapmechanic.xesau.eu/uuidservice/", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk); if (messageBoxResult == MessageBoxResult.Yes) { System.Diagnostics.Process.Start(@"steam://openurl/"+mod.url); } } } public class mod { public string name; public string author; public string url; public Brush Background; public mod(string name, string author, string url, bool hasit) { this.name = name; this.author = author; this.url = url; if(hasit) { var bc = new BrushConverter(); this.Background = (Brush)bc.ConvertFrom("#5522ff22"); } else { var bc = new BrushConverter(); this.Background = (Brush)bc.ConvertFrom("#55ff2222"); } } } } <file_sep>using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Advanced_Blueprint_Tools { /// <summary> /// Interaction logic for Cuboid_Generator.xaml /// </summary> public partial class Cuboid_Generator : Window { MainWindow mainWindow; public Cuboid_Generator(MainWindow mainWindow) { this.mainWindow = mainWindow; InitializeComponent(); } private void Button_Help_Click(object sender, RoutedEventArgs e) { System.Diagnostics.Process.Start("https://youtu.be/glLgQemUS2I?t=1627"); } private void Button_Create_Click(object sender, RoutedEventArgs e) { int thickness = Convert.ToInt32(TextBox_thickness.Text); int sizeX = Convert.ToInt32(TextBox_X.Text); int sizeY = Convert.ToInt32(TextBox_Y.Text); int sizeZ = Convert.ToInt32(TextBox_Z.Text) - thickness; dynamic Cuboid = new JObject(); Cuboid.bodies = new JArray(); Cuboid.bodies.Add(new JObject()); Cuboid.bodies[0].childs = new JArray(); Cuboid.bodies[0].childs.Add(block(0, 0, 0, sizeX, sizeY, thickness)); Cuboid.bodies[0].childs.Add(block(0, 0, thickness, sizeX, thickness, sizeZ)); Cuboid.bodies[0].childs.Add(block(0, 0, thickness, thickness, sizeY, sizeZ)); Cuboid.bodies[0].childs.Add(block(sizeX - thickness, thickness, thickness, thickness, sizeY - thickness, sizeZ - thickness)); Cuboid.bodies[0].childs.Add(block(thickness, sizeY - thickness , thickness, sizeX - thickness, thickness, sizeZ - thickness)); Cuboid.bodies[0].childs.Add(block(thickness, thickness, sizeZ, sizeX - thickness, sizeY - thickness, thickness)); string message = "++ A Cuboid has been generated!"; Random r = new Random(); string blueprintdir = Database.User_ + "\\Blueprints" + "\\GeneratedCuboid-" + r.Next() + r.Next(); dynamic description = new JObject(); description.description = "generated cuboid"; description.name = "generated cuboid" + r.Next(); description.type = "Blueprint"; description.version = 0; if (BP.Blueprintpath == null) {//no blueprint exists, initialize new one new BP(blueprintdir, Cuboid, description); } else {//a blueprint exists, overwrite it BP.setblueprint(Cuboid); BP.Description.description += message; } mainWindow.RenderBlueprint(); } private dynamic block(int x, int y, int z, int bx, int by, int bz) { dynamic block = new JObject(); block.color = "5DB7E7"; block.pos = new JObject(); block.pos.x = x; block.pos.y = y; block.pos.z = z; block.bounds = new JObject(); block.bounds.x = bx; block.bounds.y = by; block.bounds.z = bz; block.shapeId = "a6c6ce30-dd47-4587-b475-085d55c6a3b4"; block.xaxis = 1; block.zaxis = 3; return block; } private void TextBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox t = (TextBox)sender; try { if (Convert.ToInt32(t.Text) >= 0) { } } catch { if (t.Text == "-") { t.Text = "-0"; t.Select(1, 1); } else { t.Text = "0"; t.Select(0, 1); } } } } }
2f858ade4d3e75934976abbe679c4519325dc8f1
[ "C#" ]
22
C#
brentbatch/Blueprint-tools-sourcecode
6e2bfd730839c3868c52eef9f3e0f45e3df4fbea
207b3a79a74896d634bb2f206254cbe37355d161
refs/heads/master
<file_sep>/** * @file lasttest.c * @author blackball <<EMAIL>> * @date Mon Oct 17 13:13:01 2011 * * @brief test lastdbio * * */ #include "lastdbio.h" #include <string.h> #include <stdio.h> void pack_double(struct db *database, double d[], int n) { int len = sizeof(double) * n; struct db_node *node = new_node(len); memcpy(node->data, d, len); dump(database, node); } // more consideration on unpack int unpack_double(struct db *database, double d[], int n, int idx) { int code = -1; int len = sizeof(double) * n; if (idx > -1) { struct db_node *node = undump(database, idx); if (node != NULL) { memcpy(d, node->data, len); code = 0; } } return code; } int main2(int argc, char *argv[]) { int magic = 123; struct db *database = createdb(magic, "lastest.d", sizeof(double)*5); double d[5] = {2,3,4,5,1}; double s[5] = {1,2,3,4,5}; pack_double(database, d, 5); pack_double(database, s, 5); writedb(database); return 0; } int main(int argc ,char *argv[]) { struct db * database = opendb("lastest.d"); double d[5]; if(unpack_double(database, d, 5, 1)) { printf("invalid index!\n"); } else for(int i = 0; i < 5; ++i) printf("%lf\n", d[i]); closedb(database); getchar(); return 0; } <file_sep>/** * @file _dbio.h * @author blackball <<EMAIL>> * @date Mon Oct 17 10:51:06 2011 * * @brief binary data io * */ #ifndef _MX_BINARY_IO_H_INCLUDED_ #define _MX_BINARY_IO_H_INCLUDED_ #include <stddef.h> #ifdef __cplusplus extern "C" { #endif struct db_header { int magic; // file identity int num; // number of nodes int len; // length of one node(fixed) int reserved; //reserved flag }; struct db_node { int len; struct db_node *next; void* data; }; struct db_node* new_node(int len); void free_node(struct db_node *n); #define DB_NAME_LEN 64 struct db { struct db_header hdr; // header of db char fname[DB_NAME_LEN];// file name of db struct db_node *head; // head of list struct db_node *tail; // tail of list struct db_node *curr; // current pointer, // only used for indexing }; struct db* createdb(int magic, const char *fname, int fixed_len); void writedb(struct db* d); void fast_writedb(struct db *d); struct db* opendb(const char *fname); struct db* fast_opendb(const char *fname); void closedb(struct db* d); void fast_closedb(struct db* d); void dump(struct db* d, struct db_node *n); struct db_node* undump(struct db *d, int idx); #ifdef __cplusplus } #endif #endif <file_sep>/** * @file example.cpp * @author blackball <<EMAIL>> * @date Mon Oct 17 18:17:04 2011 * * @brief test dbio * */ #include <stdio.h> #include <windows.h> #include "dbio.h" #include "galleryio.h" int test_pack(void) { int arr[10] = {1,2,3,4,5,4,3,2,1,0}; int len = sizeof(int) * 10; struct db *dbase = createdb(123, "data.db", len); if ( dbase == NULL ) { fprintf(stderr, "unknow error!\n"); return 0; } for(int i = 0; i < 1000000; ++i) if (0 != pack_arr(dbase, arr, len)) { fprintf(stderr, "unknow error!\n"); return 0; } writedb(dbase); return 0; } int test_fast_unpack(void) { int arr[10]; int len = sizeof(int)*10; struct db *dbase = fast_opendb("data.db"); if (dbase == NULL) { fprintf(stderr, "can not open database!\n"); return 0; } if (0 != unpack_arr(dbase, arr, len, -1)) { fprintf(stderr, "unknow error!\n"); } for(int i = 0; i < 10; ++i) printf("%d ", arr[i]); fast_closedb(dbase); return 0; } int test_unpack(void) { int arr[10]; int len = sizeof(int)*10; struct db *dbase = opendb("data.db"); if (dbase == NULL) { fprintf(stderr, "can not open database!\n"); return 0; } if (0 != unpack_arr(dbase, arr, len, 1000)) { fprintf(stderr, "unknow error!\n"); } for(int i = 0; i < 10; ++i) printf("%d ", arr[i]); closedb(dbase); return 0; } void test_gallery() { // Create a item GItem *items[5]; int j; for (j = 0; j < 5; ++j) items[j] = new_gitem(4800); int i = 0; for (j = 0; j < 5; ++j) for (i = 0; i < 4800; ++i) { items[j]->feature[i] = i + j; } items[0]->imgID = 0; items[0]->label = 0; items[1]->imgID = 1; items[1]->label = 0; items[2]->imgID = 2; items[2]->label = 0; items[3]->imgID = 3; items[3]->label = 1; items[4]->imgID = 4; items[4]->label = 1; // Create a person Person *person0 = new_person(3); person0->label = 0; person0->items[0] = items[0]; person0->items[1] = items[1]; person0->items[2] = items[2]; Person *person1 = new_person(2); person1->label = 1; person1->items[0] = items[3]; person1->items[1] = items[4]; // create a gallery Gallery *gallery = new_gallery(2); gallery->persons[0] = person0; gallery->persons[1] = person1; // create a database // in fact, its the content length of GItem int len = sizeof(int)*2 + sizeof(double)*4800; struct db* gdb = createdb(123, "gallery.db", len); if (!gdb) { fprintf(stderr, "can not create databse!\n"); return ; } create_gallerydb(gdb, gallery); writedb(gdb); free_gallery(gallery); } void test_load_gallery() { struct db* gdb = fast_opendb("gallery.db"); if (!gdb) { fprintf(stderr, "can not open gallery db!\n"); return ; } Gallery *gallery = open_gallery(gdb); if (!gallery) { fprintf(stderr, "can not construct gallery from your DB!\n"); fast_closedb(gdb); return ; } printf("%d\n%d\n", gallery->n, gallery->persons[0]->n); for (int i = 0; i < 80; ++i) { printf("%lf ", gallery->persons[1]->items[1]->feature[i]); } printf("\n"); close_gallery(gallery); fast_closedb(gdb); } int main(int argc, char *argv[]) { long t = GetTickCount(); //test_pack(); //test_gallery(); test_load_gallery(); //test_unpack(); //test_fast_unpack(); t = GetTickCount() - t; printf("%f", t/1000.); getchar(); return 0; } <file_sep>/** * @file dbio.h * @author blackball <<EMAIL>> * @date Mon Oct 17 16:05:47 2011 * * @brief user defined IO functions for database * operations. define your pack/unpack methods here. * */ #ifndef _MX_DB_IO_H_INCLUDED_ #define _MX_DB_IO_H_INCLUDED_ #include "_dbio.h" #ifdef __cplusplus extern "C" { #endif int pack_arr(struct db *dbase, void *data, int len); int unpack_arr(struct db *dbase, void *data, int len, int idx); #ifdef __cplusplus } #endif #endif <file_sep>/** * @file _dbio.cpp * @author blackball <<EMAIL>> * @date Mon Oct 17 16:30:20 2011 * * @brief implementation of binary data IO * * */ #include "_dbio.h" #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef __cplusplus extern "C" { #endif // hooks for future customizing typedef int (db_log_fnc)(const char *fmt, ... ); typedef void* (db_malloc_fnc)(size_t sz); typedef void* (db_realloc_fnc)(void *ptr, size_t sz); typedef void (db_free_fnc)(void *ptr); typedef void (db_exit_fnc)(int status); struct _db_hook { db_log_fnc *log; db_malloc_fnc *malloc; db_realloc_fnc *realloc; db_free_fnc *free; db_exit_fnc *exit; }; /** * default logging function, print warning,error msg * out default tp stderr. * * @param fmt format string * * @return 0 for now, nothing happend */ static int _default_log(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); return 0; } // customize by your needs struct _db_hook hooks = { _default_log, malloc, realloc, free, exit }; /** * check if the database header is valid * * @param dhr pointer to database header * * @return 0 if OK, else wrong */ static int _check_header(struct db_header* hdr) { int s = -1; if ((hdr->num > 0) && (hdr->len > 0) && (hdr->reserved == 0)) s = 0; return s; } /** * create databse * * @param magic a unique identity for database * @param fname file name of database file * @param fixed_len len of item in database * * @return a new db handle */ struct db* createdb(int magic, const char *fname, int fixed_len) { struct db *d = (struct db*)hooks.malloc(sizeof(struct db)); d->hdr.magic = magic; d->hdr.num = 0; d->hdr.len = fixed_len; d->hdr.reserved = 0; d->head = NULL; d->tail = NULL; d->curr = NULL; if (DB_NAME_LEN < strlen(fname)) { hooks.log("file name is too long! Use a part of it.\n"); } strncpy(d->fname, fname, DB_NAME_LEN - 1); return d; } /** * free database handle * * @param d database handle */ static void _free_db(struct db *d) { int n; struct db_node *curr, *next; if (d == NULL) return ; n = d->hdr.num; curr = d->head; int i = 0; for (; i < n; ++i) { if ( curr == NULL ) break; next = curr->next; free_node(curr); curr = next; } if ( i != n ) { hooks.log("unexpected error !\n"); return ; } free(d); d = NULL; } /** * write data base into disk * * @param d database handle */ void writedb(struct db *d) { FILE *f = NULL; if ((f = fopen(d->fname, "wb")) == NULL) { hooks.log("failed to open file %s!\n", d->fname); return ; } // simple safety check if(d) if ( _check_header(&(d->hdr))) { hooks.log("invalid databse!\n"); fclose(f); return ; } // first write header fwrite(&(d->hdr), sizeof(struct db_header), 1, f); // write content struct db_node *curr = d->head; int i = 0; int num = d->hdr.num; for(; i < num; ++i) { if (curr == NULL ) break; fwrite(curr->data, sizeof(char)*(d->hdr.len), 1, f); curr = curr->next; } if (i != num) { hooks.log("unexpected error happens!\n"); } fclose(f); _free_db(d); } /** * open an exist database with its name * * @param fname name of database * * @return opened database handle */ struct db* opendb(const char *fname) { FILE *f; struct db *d = NULL; if ((f = fopen(fname, "r")) == NULL) { hooks.log("can not open file %s!\n", fname); return NULL; } d = (struct db*)hooks.malloc(sizeof(struct db)); strncpy(d->fname, fname, DB_NAME_LEN-1); d->head = NULL; d->tail = NULL; d->curr = NULL; d->hdr.len = 0; d->hdr.magic = 0; d->hdr.num = 0; d->hdr.reserved = 0; // constuct database handle if (0 == fread(&(d->hdr), sizeof(struct db_header), 1, f)) { hooks.log("invalid database file!\n"); hooks.free(d); d = NULL; } if (d) if ( _check_header(&(d->hdr)) ) { hooks.log("invalid databse header!\n"); hooks.free(d); d = NULL; } if (d) { // construct node list int cnt = d->hdr.num; while(!feof(f) && cnt > 0) { struct db_node *n = new_node(d->hdr.len); fread(n->data, sizeof(char)*(d->hdr.len), 1, f); dump(d, n);d->hdr.num--; --cnt; } if (cnt != 0) { hooks.log("unexpected file end!\n"); hooks.free(d); d = NULL; } } fclose(f); return d; } /** * close database * * @param d */ void closedb(struct db *d) { _free_db(d); } /** * create a new node by specify its lenth * * @param len bytes in node's data domain * * @return new node with allocated memory */ struct db_node* new_node(int len) { struct db_node *n = (struct db_node*) hooks.malloc(sizeof(struct db_node)+ sizeof(char)*(len)); n->len = len; n->data =(void*)(n+1); return n; } /** * free node * * @param n a node */ void free_node(struct db_node* n) { hooks.free((void*)n); n = NULL; } /** * Macro to add new node at the tail of a list * * @param tail tail of list, tail = last node * @param add new node * */ #define _add_node(tail, add) \ do{ \ tail->next = add; \ tail = add; \ tail->next = NULL; \ }while(0) /** * insert a node into database * * @param d databse handle * @param n new node */ void dump(struct db* d, struct db_node *n) { if (!d || !n || (d->hdr.len != n->len)) { hooks.log("invalid database or node !\n"); return ; } // insert node into db if (d->head == NULL) // first node { d->head = n; d->tail = n; d->tail->next = NULL; } else _add_node(d->tail, n); d->hdr.num++; } /** * index and return the item specified * * @param d database * @param idx -1 for accessing one by * one, [0,1,..,num-1] for indexing * * @return pointer to the specified node */ struct db_node* undump(struct db *d, int idx) { struct db_node *node; if(idx == -1) { if (d->curr == NULL) d->curr = d->head; else { d->curr = d->curr->next; } node = d->curr; } else if( (idx >= 0) && (idx < d->hdr.num) ) { d->curr = d->head; int i = 0; for(; i < idx; ++i) { d->curr = d->curr->next; } node = d->curr; } else { hooks.log("invalid index!\n"); node = NULL; } return node; } /** * fast version of open database * * @param fname * * @return */ struct db* fast_opendb(const char* fname) { // get the header FILE *f; struct db *d = NULL; if ((f = fopen(fname, "r")) == NULL) { hooks.log("can not open file %s!\n", fname); return NULL; } d = (struct db*)hooks.malloc(sizeof(struct db)); strncpy(d->fname, fname, DB_NAME_LEN-1); d->head = NULL; d->tail = NULL; d->curr = NULL; d->hdr.len = 0; d->hdr.magic = 0; d->hdr.num = 0; d->hdr.reserved = 0; // constuct database handle if (0 == fread(&(d->hdr), sizeof(struct db_header), 1, f)) { hooks.log("invalid database file!\n"); hooks.free(d); d = NULL; } if (d) if ( _check_header(&(d->hdr)) ) { hooks.log("invalid databse header!\n"); hooks.free(d); d = NULL; } // because the len of every node is fixed, we could // read all nodes' data once, and link them to a list if (d) { int len_total = d->hdr.num * d->hdr.len; // for all nodes int node_total = d->hdr.num * sizeof(struct db_node); void *nodes = hooks.malloc(node_total); void *chunk = hooks.malloc(len_total); if (chunk == NULL || nodes == NULL) { hooks.log("insufficient memory!\n"); hooks.exit(-1); } // read all data at once fread(chunk, len_total, 1, f); // constuct database linked list int cnt = d->hdr.num; int len = d->hdr.len; // init every node struct db_node *curr = (struct db_node*)nodes; int i = 0; for(; i < cnt-1; ++i) { curr->len = len; curr->data = NULL; curr->next = (curr + 1); curr = curr->next; } d->head = (struct db_node*)nodes; d->tail = curr; curr->len = len; curr->data = NULL; curr->next = NULL; d->curr = NULL; curr = d->head; void *data_head = chunk; for(i = 0; i < cnt; ++i) { if (curr == NULL) break; curr->data = data_head; curr = curr->next; data_head = (unsigned char*)data_head + len; } curr = NULL; data_head = NULL; } return d; } /** * fast version of write the database * * @param d database handle */ void fast_writedb(struct db *d) { // when you create a new database, // you don't know the size of it, // so we can't write all stuffs once // what we could make it fast is, // not free the list, left it to OS FILE *f = NULL; if ((f = fopen(d->fname, "wb")) == NULL) { hooks.log("failed to open file %s!\n", d->fname); return ; } // simple safety check if(!d) if ( _check_header(&(d->hdr))) { hooks.log("invalid databse!\n"); fclose(f); return ; } // first write header fwrite(&(d->hdr), sizeof(struct db_header), 1, f); // write content struct db_node *curr = d->head; int i = 0; int num = d->hdr.num; for(; i < num; ++i) { if (curr == NULL ) break; fwrite(curr->data, sizeof(char)*(d->hdr.len), 1, f); curr = curr->next; } if (i != num) { hooks.log("unexpected error happens!\n"); } fclose(f); // no memory free here, leave it to OS } /** * fast version of close database * * @param d */ void fast_closedb(struct db *d) { // if you use fast_opendb(), // then you could use this fast close // version. hooks.free(d->head->data); hooks.free(d->head); } #ifdef __cplusplus } #endif <file_sep>/** * @file dbio.cpp * @author blackball <<EMAIL>> * @date Mon Oct 17 16:08:13 2011 * * @brief definitions of user defined pack/unpack methods * * */ #include "dbio.h" #include "_dbio.h" #include <string.h> #ifdef __cplusplus extern "C" { #endif /** * pack any type of array * * @param dbase database * @param data data chunk * @param len sizeof(type)*n * * @return error code, 0 means OK, -1 means failed */ int pack_arr(struct db *dbase, void *data, int len) { int code = -1; struct db_node *node = new_node(len); memcpy(node->data, data, len); // insert node into dbase dump(dbase, node); code = 0; return code; } /** * unpack a array data from database * * @param dbase database handle * @param data array * @param len sizeof(type)*n * @param idx -1 for continious, [0, len-1] for idx * * @return */ int unpack_arr(struct db* dbase, void *data, int len, int idx) { int code = -1; struct db_node *node = undump(dbase, idx); if (node != NULL) { memcpy(data,node->data,len); code = 0; } return code; } #ifdef __cplusplus } #endif
4221e150986411ebd2b1e143055c062aa05d9795
[ "C", "C++" ]
6
C++
blackball/dbio
73168086e0cb76e739d75f042a0294332d6a7cb8
a627df6313cd1490c3af52242c002b8ccb0591be
refs/heads/master
<repo_name>santiago1234/corrcodon<file_sep>/R/compute_correlations.R import::from(dplyr, "%>%") #' Computes the correlation of tile and codon enrichment #' #' \code{compute_correlations} returns the correlations of tile (rna expression) #' with codon enrichment for all the codons starting at \code{min_tile} #' #' This function computes the correlation (spearman or pearson) #' between the tile number (rna expression) and the codon enrichment value (codon usage #' transcriptome level) starting at \code{min_tile}. A positive correlation indicates that the #' codon is depleted at genes with low expression and enriched at genes with high expression #' and vice versa for a negative correlation, a correlation near zero may indicate #' that there is not an enrichment pattern for that particular codon. The \code{min_tile} value #' is \strong{important}, it indicates from where to start computing the correlation, #' this min tile value should be where we start having gene expression, (if we choose a tile #' value of 60 all the genes in tiles less than 60 will not be used in the computation), for instance #' if we have 100 tiles and we pick \code{min_tile} to be 1, the first tiles will be genes #' that are potentially no expressed and it will add noise to the resulting value. We shoul #' include a \code{min_tile} value where the genes start to get expressed (low expression but not abssent expression). #' @param enrichment A tibble, enrichment of each codon at each tile, this #' tibble is the output of the function \code{codon_enrichmen}. #' @param min_tile An integer, tile less than min_tile will not be used in the computation. #' @param corr_method A character string, either spearman or pearson #' @return A tibble with the correlation of each codon. #' @examples #' encode_rna_seq %>% #' subset_genes(hsapiens_codon_composition) %>% #' tile_expression(n = 100) %>% #' quantify_codons_tile(hsapiens_codon_composition) %>% #' codon_enrichment() -> enrichment #' compute_correlations(enrichment, 60) #' @note Correlations for the stop codons are misleading compute_correlations <- function(enrichment, min_tile, corr_method = "spearman") { if (!min_tile %in% enrichment$tile) { stop("wrong tile value, see ?compute_correlations") } correlation <- function(codon_) { enrichment %>% dplyr::filter(codon == codon_, tile >= min_tile) -> selected_cols cor(selected_cols$tile, selected_cols$enrichment, method = corr_method) -> correlation_result tibble::tibble(codon = codon_, correlation = correlation_result) } CODONS %>% purrr::map_df(correlation) } <file_sep>/R/data.R #' Example of expected data input for the functions in this packages #' #' This RNA quantification data sets comes from the encode project #' #' @format A tibble: 61,471 × 2 #' \describe{ #' \item{gene_id}{ensmble, gene ids} #' \item{gene_quantification, trancript quantifications TPMs} #' ... #' } #' @source \url{https://github.com/santiago1234/ccrnaec/tree/master/human-encode-analysis/data} "encode_rna_seq" #' H. Sapiens open reading frames codon composition #' #' This data set contains the codon composition of the human genes #' the longest transcript isoform #' #' @format A tibble: 19,673 × 67 #' \describe { #' \item{gene_id}{ensmble gene id} #' \item{cds_length}{coding sequence length in nucleotides} #' \item{codon}{the frequency of each codon in the cds} #' ... #'} #' @source \url{https://github.com/santiago1234/ccrnaec/tree/master/data} "hsapiens_codon_composition" #' Genetic Code #' #' the DNA codons #' #' @format A charcter vector of length 64 "CODONS" <file_sep>/tests/testthat/test_codon_enrichment.R # test the function codon_enrichment import::from(dplyr, "%>%") encode_rna_seq %>% subset_genes(hsapiens_codon_composition) %>% tile_expression(n = 10) %>% quantify_codons_tile(codon_composition = hsapiens_codon_composition) %>% codon_enrichment() -> results_to_test test_that("enrichment values add 1", { results_to_test %>% dplyr::group_by(tile) %>% dplyr::summarise(add_one = sum(enrichment)) %>% .[["add_one"]] -> ones tile <- results_to_test$tile %>% max expect_equal(sum(ones), tile) }) <file_sep>/R/corrcodon_pipeline.R import::from(dplyr, "%>%") #' Pipeline function to compute the codon enrichment correlation with gene expression #' @inheritParams subset_genes #' @return A tibble with the correlation values #' @examples #' subset_genes(encode_rna_seq, hsapiens_codon_composition) %>% corrcodon_pipeline(hsapiens_codon_composition) corrcodon_pipeline <- function(rna_experiment, codon_composition, tiles = 100, min_tile = 59) { message("running pipeline ...") if (any(!rna_experiment$gene_id %in% codon_composition$gene_id)) { warning("running function subset_genes ..., not all genes ids of rna experiment in codon composition file" ) } rna_experiment %>% subset_genes(codon_composition) %>% tile_expression(n = tiles) %>% quantify_codons_tile(codon_composition = codon_composition) %>% codon_enrichment() %>% compute_correlations(min_tile = min_tile, corr_method = "spearman") } <file_sep>/tests/testthat/test_tile_expression.R import::from(dplyr, "%>%") ## test the function subset_genes experiment_subset <- subset_genes(encode_rna_seq, hsapiens_codon_composition) test_that("gene ids functio output subset of codon_composition", { subset_ids <- experiment_subset$gene_id contained <- any(!subset_ids %in% hsapiens_codon_composition$gene_id) expect_false(contained) }) ## test the tile expression function tiles <- 20 f_out <- tile_expression(encode_rna_seq, n = tiles) test_that("added a new column to the data frame", { expect_equal(ncol(f_out), ncol(encode_rna_seq) + 1) expect_true("tile" %in% colnames(f_out)) }) test_that('ranges tiles', { expect_equal(min(f_out$tile), 1) expect_equal(max(f_out$tile), tiles) }) ## test the function expected behaviour ## sum gene_quantifications in tile i should always be less ## than sum ene_quantifications in tile i + 1 test_that( "expected behaviour", { for (i in 1:(tiles - 1)) { quanitfications_i <- f_out$gene_quantification[f_out$tile == i] quanitfications_i_plus_1 <- f_out$gene_quantification[f_out$tile == (i + 1)] expect_true(sum(quanitfications_i) <= sum(quanitfications_i_plus_1)) } } ) <file_sep>/R/tile_expression.R #' Gets the genes that are present in both files: codon composition & rna experiment #' #' \code{subset_genes} returns a subset of rna_experiment where all the ids are present in #' the codon composition file #' #' This is the first function to be run, if the returned file is empty we are not using the #' same gene ids in both tables, gene_ids from codon composition should match #' gene ids in rna_seq experiment #' #' @param rna_experiment A tibble with the gene quantifications (TPMs or RPKMS) #' in a collumn called gene_quantification #' @param codon_composition A tibble with with the codon composition, 66 columns, #' densities of each codon, cds_length & gene_id #' @return A tibble where all the gene ids in rna_exeriment and contained in gene #' ids codon composition #' @examples #' subset_genes(encode_rna_seq, hsapiens_codon_composition) subset_genes <- function(rna_experiment, codon_composition) { rna_experiment[rna_experiment$gene_id %in% codon_composition$gene_id, ] } #' Groups gene expression in tiles #' #' @param rna_experiment A tibble with the gene quantifications (TPMs or RPKMS) in a collumn called gene_quantification #' @param n An interger, number of tiles #' @return A tibble with a new column: tile tile_expression <- function(rna_experiment, n) { if (!"gene_quantification" %in% colnames(rna_experiment)) { stop( "not column called gene_quantification, provided a collumn with the genes quantification (TPMs or RPKMs)" ) } dplyr::mutate( rna_experiment, tile = dplyr::ntile(gene_quantification, n = n) ) } <file_sep>/tests/testthat.R library(testthat) library(corrcodon) test_check("corrcodon") <file_sep>/tests/testthat/test_count_codons_in_tiles.R import::from(dplyr, "%>%") ## test the functions in count_codons_in_tiles.R til <- 50 subset_genes(encode_rna_seq, hsapiens_codon_composition) %>% tile_expression(n = til) -> experiment # test tha function uses the apposite genes ------------------------------- test_that( "output the same genes that are in the tile", { message("testing function get_codon_expression_tile ...") test_f <- function(tile_number) { n_genes <- dplyr::filter(experiment, tile == tile_number) %>% .$gene_id get_codon_expression_tile( experiment, codon = "AAA", tile_value = tile_number, hsapiens_codon_composition ) %>% .$gene_id -> out_genes expect_false(any(!n_genes %in% out_genes)) } purrr::map( 1:til, test_f ) }) # test function quantify codons tile -------------------------------------- codon_quantification <- quantify_codons_tile(experiment,codon_composition = hsapiens_codon_composition) test_that( "outputs the correct number of codons", { # sum all codons test_f2 <- function(tile_number) { get_codon_expression_tile( experiment, codon = "AAA", tile_value = tile_number, hsapiens_codon_composition ) -> out_f (out_f$number_of_codons * out_f[["AAA"]]) %>% sum -> tc expect_true(dplyr::filter(codon_quantification, codon == "AAA", tile == tile_number)[["total_codons"]] == tc) } purrr::map( 1:til, test_f2 ) } ) <file_sep>/R/codon_enrichment.R import::from(dplyr, "%>%") #' Compute the enrichment of each codon at each tile #' #' \code{codon_enrichment} returns a table with the enrichment of each codon at #' each tile #' #' This function computes the enrichment of each codon in each tile, the enrichment #' is computed: \deqn{E_{codon} = \frac{codon_in_tile}{total_codons_in_tile}} #' @param codon_quantifications a tibble, the output of function \code{quantify_codons_tile} #' @return A tibble, with enrichment column added indicating the value of the enrichment #' of each particular codon in tile #' @examples #' encode_rna_seq %>% #' subset_genes(hsapiens_codon_composition) %>% #' tile_expression(n = 100) %>% #' quantify_codons_tile(hsapiens_codon_composition) %>% #' codon_enrichment() codon_enrichment <- function(codon_quantifications) { # compute the total number of codons in each tile codon_quantifications %>% dplyr::group_by(tile) %>% dplyr::summarise(total_in_tile = sum(total_codons)) -> total_tiles enrichment_tile <- function(tile_value) { # compute the total codons in the tile total_tiles %>% dplyr::filter(tile == tile_value) %>% .[["total_in_tile"]] -> tile_total # compute the codon enrichment in tile dplyr::filter(codon_quantifications, tile == tile_value) %>% dplyr::mutate(enrichment = total_codons / tile_total) } # apply the above function to all the tiles 1:max(codon_quantifications$tile) %>% purrr::map_df(.f = enrichment_tile) } <file_sep>/R/count_codons_in_tiles.R ## FUNCTIONS TO COUNT THE NUMBER OF CODONS IN EACH TILE ## import the pipe with the import package import::from(dplyr, "%>%") #' Joins the codon composition with the rna experiment #' #' \code{get_codon_expression_tile} generates the tibble with columns gene_id, #' number_of_codons, codon, gene_quantification for the tile #' #' This function combines the codon_composition file and the rna_experiment by #' selecting the genes in tile: tile_value and then reports the columns: #' gene_id, number_of_codons, codon, gene_quantification, Also the function #' calculates the number of codons per gene. #' @param rna_experiment_tiled The output of function \code{tile_expression} #' @param codon A string one of the codons #' @param tile_value The tile to subset the data, integer #' @param codon_composition A tibble with with the codon composition, 66 columns #' @examples #' tile_data <- encode_rna_seq %>% subset_genes(hsapiens_codon_composition) %>% tile_expression(n = 10) #' get_codon_expression_tile(tile_data, codon = "AAA", tile_value = 8, codon_composition = hsapiens_codon_composition) get_codon_expression_tile <- function(rna_experiment_tiled, codon, tile_value, codon_composition) { tile_x <- dplyr::filter(rna_experiment_tiled, tile == tile_value) codon_composition %>% dplyr::mutate( number_of_codons = cds_length / 3 ) %>% dplyr::select( gene_id, number_of_codons, get(codon) ) %>% dplyr::inner_join( dplyr::select(tile_x, gene_id, gene_quantification), by = "gene_id" ) } # codons_in_tile ---------------------------------------------------------- #' Computes the total number of codons in tile #' #' This function runs \code{get_codon_expression_tile} and computes the total number #' of codons in the tile: the sum of the codons of each gene in the tile #' #' @inheritParams get_codon_expression_tile #' @return A tibble: 1 × 3, codon, total_codons tile #' @examples #' tile_data <- encode_rna_seq %>% subset_genes(hsapiens_codon_composition) %>% tile_expression(n = 10) #' codons_in_tile(tile_data, codon = "AAA", tile_value = 8, codon_composition = hsapiens_codon_composition) #' @author <NAME> codons_in_tile <- function(rna_experiment_tiled, codon, tile_value, codon_composition) { get_codon_expression_tile(rna_experiment_tiled, codon, tile_value, codon_composition) %>% dplyr::mutate(num_codon = .$number_of_codons * .[[codon]]) -> codons_in_tile_per_gene dplyr::tibble( codon = codon, total_codons = sum(codons_in_tile_per_gene$num_codon), tile = tile_value ) } # quantify_codons_tile ---------------------------------------------------- #' Counts the codons in each tile #' #' This function runs \code{codons_in_tile} for all the codons and all tiles #' values. #' @param rna_experiment_tiled rna_experiment_tiled The output of function \code{tile_expression} #' @param codon_composition A tibble with with the codon composition, 66 columns #' @return A tibble with the number of codons in each tile per codon #' @examples #' subset_genes(encode_rna_seq, hsapiens_codon_composition) %>% #' tile_expression(n = 100) %>% #' quantify_codons_tile(hsapiens_codon_composition) quantify_codons_tile <- function(rna_experiment_tiled, codon_composition) { ## send warning if not all genes id of experiment are in codon_composition gene ids if(any(!rna_experiment_tiled$gene_id %in% codon_composition$gene_id)) { warning("not all ids of experiment in codon composition ids, you should run: subset_genes before this :/") } max_tile <- max(rna_experiment_tiled$tile) dplyr::tibble( codones = rep(CODONS, max_tile), tile = rep(1:max_tile, 64) %>% sort ) -> to_map ## parallel version parallel::mclapply( 1:nrow(to_map), FUN = function(index) codons_in_tile( rna_experiment_tiled, codon = to_map$codones[index], tile_value = to_map$tile[index], codon_composition ), mc.cores = 4 ) %>% dplyr::bind_rows() }
586d04a2a83a4c95ef76808fa07fde90c10016d6
[ "R" ]
10
R
santiago1234/corrcodon
8b6a67c2a3f59d448a74c85b0a1f683f4a0afe94
895f172bcc6423ee341828dbc8004dc1e7f5b22c
refs/heads/master
<file_sep>import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.io.PrintWriter; import java.nio.ByteBuffer; /** * The BlockChain class, contains a linked * data structure of blocks. * The Node class contains the block as well * as a reference to the next node. * The BlockChain itself keeps references to * the first and the last nodes. */ public class BlockChain { //fields------------------------------------------------------------ public Node first; public Node last; public static int blockNum = -1; //Node-------------------------------------------------------------- public static class Node { public Block value; public Node next; public Node(Block value, Node next) { this.value = value; this.next = next; } } //constructor------------------------------------------------------ public BlockChain(int initial) throws NoSuchAlgorithmException{ blockNum++; this.first = new Node(new Block(BlockChain.blockNum, initial, null), null); this.last = this.first; } //methods--------------------------------------------------------- public Block mine(int amount) throws NoSuchAlgorithmException { long nonce = -1; boolean nonceFound = false; while (!nonceFound) { nonce++; Hash hash = new Hash(Block.calculateHash(BlockChain.blockNum + 1, amount, this.last.value.getHash(), nonce)); if (hash.isValid()) { nonceFound = true; } } return new Block(BlockChain.blockNum + 1, amount, this.last.value.getHash(), nonce); } public int getSize() { return BlockChain.blockNum + 1; } public void append(Block blk) { Node node = new Node(blk, null); this.last.next = node; this.last = node; BlockChain.blockNum++; } public boolean removeLast() { if (this.getSize() < 2) { return false; } Node temp = this.first; while (temp.next.next != null) { temp = temp.next; } temp.next = null; this.last = temp; BlockChain.blockNum--; return true; } public Hash getHash() { return this.last.value.getHash(); } //Checks if hashes match up //if the hashes are valid, and //whether the total remains positive public boolean isValidBlockChain() { Node temp = this.first; int total = temp.value.getAmount(); Hash prevHash; Hash currentHash = temp.value.getHash(); if (!currentHash.isValid()) { return false; } while (temp.next != null) { temp = temp.next; total += temp.value.getAmount(); prevHash = currentHash; currentHash = temp.value.getHash(); if (total < 0 || !temp.value.getPrevHash().equals(prevHash) || !currentHash.isValid()) { return false; } } return true; } public void printBalances() { PrintWriter pen = new PrintWriter(System.out, true); Node temp = this.first; int total = temp.value.getAmount(); int initial = total; while (temp.next != null) { temp = temp.next; total += temp.value.getAmount(); } pen.println("Alice: " + total + " Bob: " + (initial - total)); } public String toString() { //Implement String retString = new String(); PrintWriter pen = new PrintWriter(System.out, true); Node temp = this.first; while (temp != null) { retString += '\n'; retString += temp.value.toString(); temp = temp.next; } return retString; } } <file_sep># BlockChain A simple BlockChain program that provides a simple loop for working with the BlockChain class. Acts pretty much like a normal BlockChain. Written by <NAME> and <NAME>
517f069b373f90494f288df3de55735f00c2e383
[ "Markdown", "Java" ]
2
Java
sve009/BlockChain
36c56016922d97eae89472fff791877bdf5850cd
e01a401bf71340bf972680badaee5ffc54c5da2c
refs/heads/main
<file_sep>import React, { useContext } from 'react'; import './ProfileComponent.scss'; import {DataContext} from '../../App'; import user from './Assests/user.png'; const ProfileComponent = () => { const [data, setData] = useContext(DataContext); console.log(data) return( <div className='profile-component'> <div className='greetings-text'> <div className='greetings'>Hello,</div> <div className='user-name'>{data.userName}!</div> <span className='additional-text'>Copy your bio link and paste it in your</span> </div> <div className='profile-image'> <img className='user-img' src={user} alt='User'/> </div> </div> ) } export default ProfileComponent;<file_sep>import React, { useContext, useEffect, useState } from "react"; import CardComponent from '../CardComponent/CardComponent'; import "./CardListComponent.scss"; import { DataContext } from '../../App'; import Decrease from './Assests/decrease.png'; import increase from './Assests/increase.png'; const CardListComponent = () => { const [Data, setData] = useContext(DataContext); const [CardData, setCardData] = useState([]) useEffect(() => { let tempCardJson = [ { title : 'Total Bookings', value : Data.totalBookings, }, { title : 'Pending Approval', value : Data.pendingApproval, color : '#f35162' }, { title : 'New Clients this month', value : Data.newClientsthismonth, img:increase }, { title : 'Returning Clients', value : Data.returningClients+'%', img:Decrease } ] setCardData(tempCardJson) }, [Data]) return( <div className='card-list-component'> <div className='card-list-title'>Quick Stats</div> { CardData.map((data,index) => { return( <CardComponent key={index} cardData={data}/> ) }) } </div> ) } export default CardListComponent;<file_sep>import React, { useContext } from 'react'; import BookingsComponent from '../BookingsComponent/BookingsComponent'; import { DataContext } from '../../App'; import './BookingListComponent.scss'; const BookingListComponent = () => { const [data, setData] = useContext(DataContext); return( <div className='bookings-list'> { data.bookings && data.bookings.length > 0 ? data.bookings.map((booking) => { return( <BookingsComponent data={booking} /> ) }) : '' } </div> ) } export default BookingListComponent<file_sep>import React from "react"; import './SideBarComponent.scss' import dashboardActive from './Assests/dashboard-active.png'; import graph from './Assests/graph.png'; import Logout from './Assests/logout.png'; const SideBarComponent = () => { return( <div className='sidebar-component'> <div className='sidebar-title'> <h1 className='title'>S</h1> </div> <div className='menu-icons'> <div className='active-dashboard=icon icons selected'> <img className='sidebar-icons selected' src={dashboardActive} /> </div> <div className='chart-icon'> <img className='sidebar-icons' src={graph} /> </div> </div> <div className='logout-icon'> <img className='logout-img' src={Logout} alt='logout' /> </div> </div> ) } export default SideBarComponent;<file_sep>import { useState, createContext, useEffect } from 'react'; import './App.css'; import BookingListComponent from './Components/BookingListComponent/BookingListComponent'; import SideBarComponent from './Components/SideBarComponent/SideBarComponent'; import SearchComponent from "./Components/SearchComponent/SearchComponent"; import ProfileComponent from "./Components/ProfileComponent/ProfileComponent"; import NotificationIcon from './Assests/Notifications.png' import RemainderComponent from './Components/RemainderComponent/RemainderComponent'; import CardListComponent from './Components/CardListComponent/CardListComponent'; import TabComponent from './Components/TabComponent/TabComponent'; export const DataContext = createContext( [ {}, () => {}] ); function App() { const [data, setData] = useState({}); useEffect(() => { fetch('https://raw.githubusercontent.com/arun6202/reactjs_assignment/main/data.json') .then(response => response.json()) .then(result => setData(result)) }, []) return ( <div className="App"> <div id='dashboard-page' className='dashboard-page'> <div className='side-bar'> <SideBarComponent /> </div> <DataContext.Provider value = {[data,setData]}> <div className='main-container'> <h1 className='heading'>Dashboard</h1> <span className='welcome-text'>Welcome Back!</span> <CardListComponent /> <TabComponent /> <BookingListComponent /> </div> <div className='right-container'> <div className='header'> <div className='search'> <SearchComponent /> </div> <div className='notifications'> <img className='notification-icon' src={NotificationIcon} alt='Notification Icon' /> </div> </div> <ProfileComponent /> <RemainderComponent /> </div> </DataContext.Provider> </div> </div> ); } export default App;
c20b006607d4694337fcc584860d10d01e6a2c7d
[ "JavaScript" ]
5
JavaScript
yogesh45/Bookings-dashboard
3b18df29c57a0fc7476954810cb7182707676b76
1d9c5ca9741a3c4dfbab03f9fd7735d4faa6c311
refs/heads/main
<file_sep>def sumaDigitos(numero): suma=0 while numero!=0: digito=numero%10 suma=suma+digito numero=numero//10 return suma num=int(input("Número a procesar: ")) while num!=0: print("Suma:",sumaDigitos(num)) num=int(input("Número a procesar: "))<file_sep>def validarDNI(dni): cantidad=0 while dni!=0: cantidad+=1 dni//=10 return cantidad==7 or cantidad==8<file_sep>'''Escribir una función que, dado un string, retorne la longitud de la última palabra. Se considera que las palabras están separadas por uno o más espacios. También podría haber espacios al principio o al final del string pasado por parámetro.''' def lenramiro(frase): if len(frase)==0: return 0 cantidad=0 for i in range(len(frase)): if frase[i]!=' ': cantidad+=1 else: if i<len(frase)-1 and frase[i+1]!=' ': cantidad=0 return cantidad print(len("ramiro")) <file_sep>def validar(email): caracterBuscado="@" emailValido=False for c in email: if c==caracterBuscado: return True return False direccion=input("Tu email: ") if validar(direccion): print("Dirección válida") else: print("Dirección inválida")<file_sep>def factorial(numero): f=1 if numero!=0: for i in range(1,numero+1): f=f*i return f cantidad=0 num=int(input("Número (-1 para cortar): ")) while num!=-1: print("Factorial:", factorial(num)) cantidad+=1 num=int(input("Número (-1 para cortar): ")) print("Se leyeron",cantidad,"números")<file_sep>def coordenadaZ(x,y): x=x+10 y=y+15 return x+y #programa principal x=int(input("Coordenada eje x: ")) y=int(input("Coordenada eje y: ")) for i in range(3): z=coordenadaZ(x,y) x=x+1 y=y+1 print(x," . ",y)<file_sep>def sumaDigitos(numero): suma=0 while numero!=0: digito=numero%10 suma=suma+digito numero=numero//10 return suma cantidad=0 mayor=-1 numero=int(input("Número positivo: ")) while numero>=0: suma=sumaDigitos(numero) if suma > mayor: mayor=suma n_mayorsuma=numero if suma < 10: cantidad+=1 numero=int(input("Número positivo: ")) print("Sumatoria de dígitos de",n_mayorsuma,":",mayor) print("Cantidad con sumatoria menor a 10:",cantidad)<file_sep>def frecuencia(numero,digito): cantidad=0 while numero!=0: ultDigito=numero%10 if ultDigito==digito: cantidad+=1 numero=numero//10 return cantidad num=int(input("Número: ")) un_digito=int(input("Dígito: ")) print("Frecuencia del dígito en el número:",frecuencia(num,un_digito))<file_sep>def primo(num): for i in range(2,num): if num%i==0: return False return True numero=int(input("Número: ")) if primo(numero): print("Es primo") else: print("No es primo")<file_sep>def maximo(x,y): if x>y: return x else: return y def minimo(x,y): if x<y: return x else: return y #programa principal x=int(input("Un número: ")) y=int(input("Otro número: ")) print(maximo(x-3, minimo(x+2, y-5)))<file_sep>def lenUltimaPalabra(cadena): longitud=len(cadena) if longitud==0: return 0 cantidad=0 for i in range(longitud): if cadena[i]!=' ': cantidad+=1 else: if cadena[i]==' ' and i<(longitud-1) and cadena[i+1]!=' ': cantidad=0 return cantidad def DNIvalido(dni): cantidad=0 while dni!=0: cantidad+=1 dni//=10 return cantidad==7 or cantidad==8 def primerosTresDigitos(numero): while numero >= 1000: numero = numero // 10 return numero def obtenerIdentificador(nombre, dni): nombre=nombre.strip() id=nombre[:nombre.find(" ")] id=id+str(lenUltimaPalabra(nombre)) id=id+str(primerosTresDigitos(dni)) return id #programa principal nombre=input("Nombre del socio: ") while nombre!="": dni=int(input("DNI del socio: ")) while (DNIvalido(dni)): print("Número inválido.") dni=int(input("DNI del socio: ")) print(obtenerIdentificador(nombre,dni)) nombre=input("Nombre del socio: ")<file_sep>def titulo(cadena): nueva="" inicioPalabra=True #indica el inicio de una palabra for caracter in cadena: if not caracter.isalpha(): nueva=nueva+caracter inicioPalabra=True else: if inicioPalabra: nueva=nueva+caracter.upper() inicioPalabra=False #ya no es el inicio de una palabra else: nueva=nueva+caracter.lower() return nueva<file_sep>def primo(num): for i in range(2,num): if num%i==0: return False return True def frecuencia(numero,digito): cantidad=0 while numero!=0: ultDigito=numero%10 if ultDigito==digito: cantidad+=1 numero=numero//10 return cantidad def factorial(numero): f=1 if numero!=0: for i in range(1,numero+1): f=f*i return f def sumaDigitos(numero): suma=0 while numero!=0: digito=numero%10 suma=suma+digito numero=numero//10 return suma mayor=0 numero=int(input("Número primo: ")) while primo(numero): print("Suma de los dígitos:",sumaDigitos(numero)) digito=int(input("Dígito: ")) print("El",digito,"aparece",frecuencia(numero,digito),"veces") if numero > mayor: mayor=numero numero=int(input("Número primo: ")) print("Factorial de",mayor,":",factorial(mayor))<file_sep>def sumaDigitos(numero): suma=0 while numero!=0: digito=numero%10 suma=suma+digito numero=numero//10 return suma sumatoria=0 num=int(input("Número a procesar: ")) while num!=0: print("Suma:",sumaDigitos(num)) sumatoria=sumatoria+num num=int(input("Número a procesar: ")) print("Sumatoria:", sumatoria) print("Dígitos:", sumaDigitos(sumatoria))
12caa6b4908259ac78a25f43401faac80f3e0fd3
[ "Python" ]
14
Python
Sarayin/Ejercicios-de-trabajo
bec23bfebfa65890a41b08e54deff11772e3e35d
b44fc91de5574754e1d950d7825b1d859cf41434
refs/heads/master
<repo_name>johnnyehl/ProyectoTesis<file_sep>/facilito/apps/facil/migrations/0001_initial.py # Generated by Django 2.0.5 on 2018-05-15 20:33 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Assistant', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('attended', models.BooleanField(default=False)), ('has_paid', models.BooleanField(default=False)), ('assistant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('slug', models.SlugField(editable=False)), ], ), migrations.CreateModel( name='Comments', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('content', models.TextField()), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='Event', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('name', models.CharField(max_length=200, unique=True)), ('slug', models.SlugField(editable=False)), ('summary', models.TextField(max_length=255)), ('content', models.TextField()), ('place', models.CharField(max_length=50)), ('start', models.DateTimeField()), ('finish', models.DateTimeField()), ('imagen', models.ImageField(upload_to='events')), ('is_free', models.BooleanField(default=True)), ('amount', models.DecimalField(decimal_places=2, default=0.0, max_digits=5)), ('views', models.PositiveIntegerField(blank=True, default=0, null=True)), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='facil.Category')), ('organizer', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='comments', name='event', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='facil.Event'), ), migrations.AddField( model_name='comments', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='assistant', name='event', field=models.ManyToManyField(to='facil.Event'), ), ] <file_sep>/facilito/apps/facil/apps.py from django.apps import AppConfig class FacilConfig(AppConfig): name = 'facil'
2074f8e7280ec9536fdc4dcc779fd2ea4020101b
[ "Python" ]
2
Python
johnnyehl/ProyectoTesis
c92e7eaa0d819292d42f775d41e124539e6fcc3c
294f58d93396d9bb0493e5416945e52f706cde67
refs/heads/master
<repo_name>minsuchoe/Day15_SceneManagement<file_sep>/Assets/GameManager.cs using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; //Scene 로딩시 필요 public class GameManager : MonoBehaviour { public static GameManager instance = null; public int level = 1; private void Awake() { if (instance == null) instance = this; else if (instance != null) Destroy(gameObject); DontDestroyOnLoad(gameObject); InitGame(); } private void InitGame() { } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.L)) SceneManager.LoadScene("Lobby"); if (Input.GetKeyDown(KeyCode.R)) SceneManager.LoadScene("Room"); if (Input.GetKeyDown(KeyCode.P)) SceneManager.LoadScene("Play"); } } <file_sep>/Assets/PlayerController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { void Start () { print("level : " + GameManager.instance.level); } }
63fa9deff7c9d0c4a8d7fdd7b60d1d1853a8b2c0
[ "C#" ]
2
C#
minsuchoe/Day15_SceneManagement
824dc2953a3c9cd542a87bfe9b0db3b57c93fbc9
d3e04ba685cbd86598bd1b3ed11e384d629d010d
refs/heads/master
<file_sep>from PyQt4.QtGui import QLineEdit, QApplication, QColor, QPalette, QSlider from PyQt4.QtCore import pyqtSignal, pyqtSlot, pyqtProperty, QState, QStateMachine, QPropertyAnimation from channel import PyDMChannel class PyDMSlider(QSlider): __pyqtSignals__ = ("send_value_signal(str)", "connected_signal()", "disconnected_signal()", "no_alarm_signal()", "minor_alarm_signal()", "major_alarm_signal()", "invalid_alarm_signal()") #Emitted when the user changes the value. send_value_signal = pyqtSignal(str) def __init__(self, channel=None, parent=None): super(PyDMSlider, self).__init__(parent) self._channel = channel self.valueChanged.connect(self.sendValue) self._des_max = None self._des_min = None self._step = '1' self._maxrange = '10' self._minrange = '-10' self.setupRange(self._step) #accounts for the fact that the silider only works with integer numbers def mapStepSize(self): pass def setupRange(self,step_size): upper_range_int = int((1/float(step_size))*float(self._maxrange)) lower_range_int = int((1/float(step_size))*float(self._minrange)) self.setMaximum(upper_range_int) self.setMinimum(lower_range_int) #step size property def getStep(self): return str(self._step) def setStep(self,value): self._step = str(value) step = pyqtProperty(str,fget=getStep,fset=setStep) #max range property def getMaxrange(self): return str(self._maxrange) def setMaxrange(self,value): self._maxrange = str(value) maxrange = pyqtProperty(str,fget=getMaxrange,fset=setMaxrange) #min range property def getMinrange(self): return str(self._minrange) def setMinrange(self,value): self._minrange = str(value) minrange = pyqtProperty(str,fget=getMinrange,fset=setMinrange) #overwrite wheel event to fire only when slider is in focus def wheelEvent(self,event): pass #set slider to new position #if the slider is not in focus, dont set slider to new position @pyqtSlot(str) def receiveValue(self, new_val): if not self.hasFocus(): self.setSliderPosition(int(float(new_val))) #send out new value to channel @pyqtSlot() def sendValue(self): if self.hasFocus(): val = str(float(self.value())*float(self._step)) self.send_value_signal.emit(val) #false = disconnected, true = connected @pyqtSlot(bool) def connectionStateChanged(self, connected): self.setEnabled(connected) if connected: self.setupRange(self._step) def getChannel(self): return str(self._channel) def setChannel(self, value): if self._channel != value: self._channel = str(value) def resetChannel(self): if self._channel != None: self._channel = None channel = pyqtProperty(str, getChannel, setChannel, resetChannel) def channels(self): return [PyDMChannel(address=self.channel, connection_slot=self.connectionStateChanged, value_slot=self.receiveValue, value_signal=self.send_value_signal)] <file_sep>from qtplugin_base import qtplugin_factory from checkbox import PyDMCheckbox PyDMCheckboxPlugin = qtplugin_factory(PyDMCheckbox) <file_sep># pydm: Python Display Manager pydm is a PyQt-based framework for building user interfaces for control systems. The goal is to provide a no-code, drag-and-drop system to make simple screens, as well as a straightforward python framework to build complex applications. # Prerequisites * Python 2.7 or 3.5 * Qt 4.8 or higher * PyQt 4.11 or higher If you'd like to use Qt Designer (drag-and-drop tool to build interfaces) you'll need to make sure you have the PyQt plugin for Designer installed. This usually happens automatically when you install PyQt. # Running the Examples There are various examples of some of the features of the display manager. To launch a particular display run 'python pydm.py <filename>'. There is a 'home' display in the examples directory with buttons to launch all the examples: run 'python pydm.py examples/home.ui' There isn't any documentation yet, hopefully looking at the examples can get you started. #Widget Designer Plugins pydm widgets are written in Python, and are loaded into Qt Designer via the PyQt Designer Plugin. If you want to use the pydm widgets in Qt Designer, add the pydm/widgets/ directory to your PYQTDESIGNERPATH environment variable. Eventually, this will happen automatically in some kind of setup script.<file_sep>from qtplugin_base import qtplugin_factory from timeplot import PyDMTimePlot PyDMTimePlotPlugin = qtplugin_factory(PyDMTimePlot) <file_sep>from qtplugin_base import qtplugin_factory from shell_command import PyDMShellCommand PyDMShellCommandPlugin = qtplugin_factory(PyDMShellCommand) <file_sep>from qtplugin_base import qtplugin_factory from line_edit import PyDMLineEdit PyDMLineEditPlugin = qtplugin_factory(PyDMLineEdit) <file_sep>from qtplugin_base import qtplugin_factory from related_display_button import PyDMRelatedDisplayButton PyDMRelatedDisplayButtonPlugin = qtplugin_factory(PyDMRelatedDisplayButton) <file_sep>from qtplugin_base import qtplugin_factory from label import PyDMLabel PyDMLabelPlugin = qtplugin_factory(PyDMLabel) <file_sep>pyqtgraph>=0.9.10 numpy>=1.11.0 scipy>=0.12.0 pyepics>=3.2.4 requests>=1.1.0 <file_sep>from .label import PyDMLabel from .pushbutton import PyDMPushButton from .image import PyDMImageView<file_sep>from qtplugin_base import qtplugin_factory from embedded_display import PyDMEmbeddedDisplay PyDMEmbeddedDisplayPlugin = qtplugin_factory(PyDMEmbeddedDisplay) <file_sep>from qtplugin_base import qtplugin_factory from waveformtable import PyDMWaveformTable PyDMWaveformTablePlugin = qtplugin_factory(PyDMWaveformTable) <file_sep>from qtplugin_base import qtplugin_factory from image import PyDMImageView PyDMImageViewPlugin = qtplugin_factory(PyDMImageView) <file_sep>from qtplugin_base import qtplugin_factory from slider import PyDMSlider PyDMSliderPlugin = qtplugin_factory(PyDMSlider) <file_sep>from PyQt4.QtGui import QPushButton from PyQt4.QtCore import pyqtSlot, pyqtProperty, QString import shlex, subprocess class PyDMShellCommand(QPushButton): def __init__(self, command=None, parent=None): super(PyDMShellCommand, self).__init__(parent) self._command = command self.process = None def getCommand(self): return QString.fromAscii(self._command) def setCommand(self, value): if self._command != value: self._command = str(value) def resetCommand(self): if self._command is not None: self._command = None def mouseReleaseEvent(self, mouse_event): self.execute_command() super(PyDMShellCommand, self).mouseReleaseEvent(mouse_event) @pyqtSlot() def execute_command(self): if self.process is None or self.process.poll() is not None: args = shlex.split(self._command) self.process = subprocess.Popen(args) else: print "Command already active." command = pyqtProperty("QString", getCommand, setCommand, resetCommand) <file_sep>from qtplugin_base import qtplugin_factory from indicator import PyDMIndicator PyDMIndicatorPlugin = qtplugin_factory(PyDMIndicator) <file_sep>#!/usr/bin/env python import sys from pydm import PyDMApplication if __name__ == "__main__": app = PyDMApplication(sys.argv) sys.exit(app.exec_())<file_sep>from qtplugin_base import qtplugin_factory from waveformplot import PyDMWaveformPlot PyDMWaveformPlotPlugin = qtplugin_factory(PyDMWaveformPlot) <file_sep>from qtplugin_base import qtplugin_factory from pushbutton import PyDMPushButton PyDMPushButtonPlugin = qtplugin_factory(PyDMPushButton)
42db92c4f74344a60312b5a5c5d3572a9c546dfc
[ "Markdown", "Python", "Text" ]
19
Python
Jus80687/pydm
ab70a8f61bfc21d7461652c21e478b526efe24f8
1a11133c443269c033163ad874da9dc2607e16ef
refs/heads/master
<file_sep>require_relative "../config/environment.rb" require 'active_support/inflector' require 'pry' class InteractiveRecord def initialize (hash = {}) hash.each do |key, value| self.send("#{key}=", value) end end def self.table_name self.to_s.downcase.pluralize end def self.column_names columns = [] info = DB[:conn].execute("PRAGMA table_info('#{table_name}')") info.each do |row| columns << row["name"] end columns end def self.find_by_name(name_to_find) query = "SELECT * FROM #{table_name} WHERE name = '#{name_to_find}'" find = DB[:conn].execute(query) end def table_name_for_insert self.class.table_name end def col_names_for_insert self.class.column_names.delete_if{|a| a == "id"}.join(", ") end def values_for_insert cols = self.class.column_names.delete_if{|a| a == "id"} vals = [] cols.each do |column| vals << "'#{self.send("#{column}")}'" unless send(column).nil? end vals.join(", ") end def save query = "INSERT INTO #{table_name_for_insert} (#{col_names_for_insert}) VALUES (#{values_for_insert});" DB[:conn].execute(query) @id = DB[:conn].execute("SELECT last_insert_rowid() FROM #{table_name_for_insert}")[0][0] end def self.find_by(hash) columns = self.column_names results = [] columns.each do |col| query = "SELECT * FROM #{table_name} WHERE #{col} = '#{hash.values[0]}'" results << DB[:conn].execute(query) unless DB[:conn].execute(query).size < 1 end results[0] end end
1a45a3dd8fda82761a1650afbbad91b8ad369115
[ "Ruby" ]
1
Ruby
jakebrady5/dynamic-orm-lab-v-000
306c571ca1502ba575d97d454ba1a845e9b74883
eeb7d28fbe6be715ed80b7ad80ba14ae99aa0be4
refs/heads/master
<file_sep>package com.example.movingcarapp import android.graphics.PointF import kotlin.math.acos import kotlin.math.sqrt class Triangle( private val a: PointF, private val b: PointF, private val c: PointF ) { private fun getAB(): Double { val dx = a.x - b.x val dy = (a.y - b.y).toDouble() return sqrt(dx * dx + dy * dy) } private fun getBC(): Double { val dx = b.x - c.x val dy = (b.y - c.y).toDouble() return sqrt(dx * dx + dy * dy) } private fun getAC(): Double { val dx = a.x - c.x val dy = (a.y - c.y).toDouble() return sqrt(dx * dx + dy * dy) } fun getAngle(): Float { return angle(getAC(), getBC(), getAB()).toFloat() } private fun angle(oppositeLeg: Double, adjacentLeg1: Double, adjacentLeg2: Double): Double { return Math.toDegrees( acos( (adjacentLeg1 * adjacentLeg1 + adjacentLeg2 * adjacentLeg2 - oppositeLeg * oppositeLeg) / 2 / adjacentLeg2 / adjacentLeg1 ) ) } } <file_sep>include ':app' rootProject.name='MovingCarApp' <file_sep>package com.example.movingcarapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.fragment.app.Fragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) showFragment() } private fun showFragment() { var fragment = getFragment() if (fragment == null) { fragment = RoadFragment.newInstance() supportFragmentManager.beginTransaction() .add(R.id.activity_main_fragment_container, fragment) .commit() } } private fun getFragment(): Fragment? { return supportFragmentManager.findFragmentById(R.id.activity_main_fragment_container) } } <file_sep>package com.example.movingcarapp import android.graphics.PointF import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.fragment.app.Fragment import kotlinx.android.synthetic.main.fragment_road.* import android.view.MotionEvent import android.view.animation.* class RoadFragment : Fragment() { companion object { fun newInstance() = RoadFragment() } private lateinit var car: ImageView private val rotateDuration = 500L private val translateDuration = 1500L var previousAngle = 0f override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_road, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) findViews() initListeners() } private fun findViews() { car = fragment_road_car } private fun initListeners() { view?.setOnTouchListener { _, event -> if (event.action == MotionEvent.ACTION_DOWN) { disableView(view) startMotion(event.x, event.y) true } else { false } } } private fun disableView(view: View?) { if (view == null) return view.isEnabled = false view.postDelayed({ view.isEnabled = true }, translateDuration + rotateDuration) } private fun startMotion(x: Float, y: Float) { val toDegrees = getToDegrees(x, y) car.animate() .rotationBy(toDegrees) .setDuration(rotateDuration) .withEndAction { car.animate().x(x).y(y) .setInterpolator(AccelerateDecelerateInterpolator()) .setDuration(translateDuration) .start() } .start() } private fun getToDegrees(x: Float, y: Float): Float { val startPoint = PointF(car.x, car.y) val endPoint = PointF(x, y) val thirdPointY = getThirdPointY(y) val thirdPoint = PointF(car.x, thirdPointY) val triangle = Triangle(thirdPoint, startPoint, endPoint) val angle = getAngle(x, triangle) previousAngle = getPreviousAngle(x, triangle) return angle } private fun getThirdPointY(y: Float): Float { return if (car.y > y) { y } else { car.y + (car.y - y) } } private fun getAngle(x: Float, triangle: Triangle): Float { val angle = when { car.x > x -> triangle.getAngle().unaryMinus() else -> triangle.getAngle() } return angle - previousAngle } private fun getPreviousAngle(x: Float, triangle: Triangle): Float { return if (car.x > x) { triangle.getAngle().unaryMinus() } else { triangle.getAngle() } } }
a0f6d2a4e5e694a6e3e3a511d1ea45105fa6662a
[ "Kotlin", "Gradle" ]
4
Kotlin
AmirVagapov/MovingCarApplication
cfc475485b6c8771be492067178378f0308193e1
117154126604a0c5b5520dff37fd12ee03597c2b
refs/heads/master
<repo_name>dumdumdablu/batch21<file_sep>/Java/src/HelloGuys.java public class HelloGuys { public static void main(String[] args) { System.out.println("Hello Guys"); } public void hello(){ System.out.println("Hello I am in hello method()."); System.out.println("Hello I am in second line. hello method"); } }
45d6df390989015b6fcf8eedf9d64ecf2ac92d8c
[ "Java" ]
1
Java
dumdumdablu/batch21
c94c04d697efbc9fea2d6898c9944beaa45f4fd1
b36690226b4ccd493a9b822ce313471e269e32e8
refs/heads/master
<repo_name>getheash/temperature-control-app<file_sep>/React_Apps/ReadMe.txt I have created this folder to store all the React apps that I create for testing purposes. <file_sep>/src/container.jsx import React, { Component } from "react"; class Container extends Component { state = { temp: 10, }; constructor(props) { super(props); this.handleTempIncrease = this.handleTempIncrease.bind(this); this.handleTempDecrease = this.handleTempDecrease.bind(this); } handleTempIncrease() { let newTemp = this.state.temp; if (newTemp < 30) { newTemp += 1; } this.setState({ temp: newTemp, }); } handleTempDecrease() { let newTemp = this.state.temp; if (newTemp > -5) { newTemp -= 1; } this.setState({ temp: newTemp, }); } render() { return ( <div className="app-container"> <div className="temperature-display-container"> <div className={this.getTempColor()}>{this.state.temp}°C</div> </div> <div className="button-container"> <button onClick={this.handleTempIncrease}>+</button> <button onClick={this.handleTempDecrease}>-</button> </div> </div> ); } getTempColor() { return this.state.temp >= 15 ? "temperature-display hot" : "temperature-display cold"; } } export default Container;
b3db4dece753fc3101eab3eb76cb8f92f518b581
[ "JavaScript", "Text" ]
2
Text
getheash/temperature-control-app
01ec21e34bbbd4068d9342190d1bcdba3e40c772
b27f281841ef1a818835bc4b506fba346164c7c5
refs/heads/master
<repo_name>charliemurgatroyd/webscrape<file_sep>/pyscrape.py print('in pyscrape file')
5bd149ea635fc1a0fc81e88dca31a1b247f9d139
[ "Python" ]
1
Python
charliemurgatroyd/webscrape
b9b36cfba39a51a3c79109bdd9c3ab016ec179a2
6360c20dba0bd1afd473ae34266429b53a778a5b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Collections; using System.Threading; using System.Diagnostics; /****** Available functions to call *********** string getAnnualizedGain(string symbol) string getExchange(string symbol) double getChange(string symbol) string getChangeInPercent(string symbol) double getStockYearHigh(string symbol) double getStockYearLow(string symbol) string getCompanyName(string symbol) double getLatestValue(string symbol) */ namespace stockme { class Program { static void Main(string[] args) { const int NUM_THREADS = 8; //reccomended 36 symbols per thread ArrayList arList = new ArrayList(); ArrayList qrResults; Stopwatch sw = new Stopwatch(); // (284 * 2) symbols is suggested for stress test. arList.Add("goog"); arList.Add("A"); arList.Add("AA"); arList.Add("AA-B"); arList.Add("HBI"); arList.Add("HCN"); arList.Add("HE"); arList.Add("HF"); //ThreadStockerWrapper(threads,function_name,stocknames_arraylist); ThreadStockWrapper Stocker = new ThreadStockWrapper(NUM_THREADS, "getLatestValue", arList); //see available functions above to call. sw.Start(); qrResults = Stocker.threadStockCall(); // returns back a QuerryResults ArrayList(); sw.Stop(); foreach (QueryResults qr in qrResults) { if (qr.isString) { Console.WriteLine(qr.sSymbol + " " + qr.sResult + " " + qr.sQuery); } else { //results have a double instead. Console.WriteLine(qr.sSymbol + " " + qr.dResult + " " + qr.sQuery); } } Console.WriteLine("Elapsed Miliseconds " + sw.ElapsedMilliseconds); } } /*begin Class QueryResults ***** brandon ****/ class QueryResults { private string symbol, str_result, query; private double dbl_result; private bool bIsStr; // is the result a string.. if false it is a double. public QueryResults(string s, double d, string r, string q, bool isStr) { sSymbol = s; dResult = d; sResult = r; sQuery = q; bIsStr = isStr; } public bool isString // if false the result is a double; { get { return bIsStr; } set { } } public string sSymbol { get { return symbol; } set { symbol = value; } } public double dResult { get { return dbl_result; } set { dbl_result = value; } } public string sResult { get { return str_result; } set { str_result = value; } } public string sQuery { get { return query; } set { query = value; } } } /*begin Class ThreadStockWrapper ***** brandon ****/ class ThreadStockWrapper { private int iThreads; private string sFunction; private ArrayList arStockSymbols; private ArrayList[] arThreadStorage, arResults; private StockDrone[] sdDrones; private Thread[] tThreads; public ThreadStockWrapper(int threads, string function, ArrayList stockSymbols) { iThreads = threads; sFunction = function; arStockSymbols = stockSymbols; arThreadStorage = new ArrayList[threads]; arResults = new ArrayList[threads]; sdDrones = new StockDrone[threads]; tThreads = new Thread[threads]; for (int i = 0; i < threads; i++) { arResults[i] = new ArrayList(); arThreadStorage[i] = new ArrayList(); } for (int i = 0; i < stockSymbols.Count; i++) { arThreadStorage[i % threads].Add(stockSymbols[i]); // distributing the load equally. } for (int i = 0; i < threads; i++) { sdDrones[i] = new StockDrone(arThreadStorage[i], arResults[i]); //prep each drone, storage of symbols, and results storage. tThreads[i] = new Thread(sdDrones[i].dispatchFunction); // assign each drone as a thread. } } public ArrayList threadStockCall() { ArrayList arTemp = new ArrayList(); for (int i = 0; i < iThreads; i++) // puts our drones to work. { tThreads[i].Start(sFunction); } int storageCount = iThreads; while (storageCount > 0) { for (int i = 0; i < iThreads; i++) { storageCount--; if(arResults[i].Count > 0) { arTemp.Add(arResults[i][0]); //allows results to be returned in the order in which they were recieved. arResults[i].RemoveAt(0); storageCount++; } } } return arTemp; } } /****Begin Class StockDrone *** Brandon ***/ public class StockDrone // drone class. this will be our worker bees { private static int iThreadCount = 0; private static object locker = new Object(); private ArrayList stockSymbols, results; public StockDrone(ArrayList s, ArrayList r) { stockSymbols = s; results = r; lock (locker) { iThreadCount++; } } public void dispatchFunction(object oFunction)//paramatized threads can only have objects as parameters { string sFunction = (string)oFunction; Stock stock = new Stock(); if (sFunction.Length >= 4) { char temp = sFunction.ToUpper().ElementAt(3); char temp2 = sFunction.ToUpper().ElementAt(sFunction.Length - 1); // public QueryResults(string s, double d, string r, string q, bool isString) switch (temp) //switch statments are faster than if and elses { case 'A': foreach (string s in stockSymbols) { results.Add(new QueryResults(s, 0.0, stock.getAnnualizedGain(s), "getAnnualizedGain", true)); } break; case 'C': if (temp2 == 'E') { temp2 = sFunction.ToUpper().ElementAt(sFunction.Length - 2); //getChange if (temp2 == 'G') { foreach (string s in stockSymbols) { results.Add(new QueryResults(s, stock.getChange(s), "", "getChange", false)); } } else { foreach (string s in stockSymbols) { results.Add(new QueryResults(s, 0.0, stock.getCompanyName(s), "getCompanyName", true)); } } } else if (temp2 == 'T') { // getChangeInPercent foreach (string s in stockSymbols) { results.Add(new QueryResults(s, 0.0, stock.getChangeInPercent(s), "getChangeInPercent", true)); } } break; case 'E': // getExchange foreach (string s in stockSymbols) { results.Add(new QueryResults(s, 0.0, stock.getExchange(s), "getExchange", true)); } break; case 'L': //getLatestValue foreach (string s in stockSymbols) { //false means the result is a double. results.Add(new QueryResults(s, stock.getLatestValue(s), "", "getLatestValue", false)); } break; case 'S': if (temp2 == 'H') { //getStockYearHigh foreach (string s in stockSymbols) { //false means the result is a double. results.Add(new QueryResults(s, stock.getStockYearHigh(s), "", "getStockYearHigh", false)); } } else if (temp2 == 'W') { //getStockYearLow foreach (string s in stockSymbols) { //false means the result is a double. results.Add(new QueryResults(s, stock.getStockYearLow(s), "", "getStockYearLow", false)); } } break; } } lock (locker) { iThreadCount--; } } public static int getThreadCount() { return iThreadCount; } } /*begin Class Stock ******** blake */ class Stock { // This doesn't work properly public string getAnnualizedGain(string symbol) { return getFromAPIquoute(symbol, "g3")[0]; } public string getExchange(string symbol) { return getFromAPIquoute(symbol, "x0")[0]; } public double getChange(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "c1")[0]); } public string getChangeInPercent(string symbol) { return getFromAPIquoute(symbol, "p2")[0]; } public double getStockYearHigh(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "k0")[0]); } public double getStockYearLow(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "j0")[0]); } // This method will return a string with the company name based on the symbol. public string getCompanyName(string symbol) { return getFromAPIquoute(symbol, "n")[0].Substring(1, getFromAPIquoute(symbol, "n")[0].Length - 4); } public double getLatestValue(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "l1")[0]); } // Stock Symbol // args listed here https://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty // returns an array of strings. Each arg is it's own element in the array. private string[] getFromAPIquoute(string symbol, string args) { string[] results = null; try { string temp = null; string yahooURL = @"http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=" + args; // Initialize a new WebRequest. HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL); // Get the response from the Internet resource. HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse(); // Read the body of the response from the server. StreamReader strm = new StreamReader(webresp.GetResponseStream(), Encoding.ASCII); temp = strm.ReadToEnd(); results = temp.Split(new Char[] { ',' }); strm.Close(); } catch { //some exception } return results; } public string getHistory(string symbol, DateTime from, DateTime to, char interval) { //string[] results = null; string temp = null; try { string yahooURL = @"http://ichart.yahoo.com/table.csv?s=" + symbol + "&a=" + (from.Month - 1).ToString() + "&b=" + (from.Day).ToString() + "&c=" + (from.Year).ToString() + "&d=" + (to.Month - 1).ToString() + "&e=" + (to.Day).ToString() + "&f=" + (to.Year).ToString() + "&g=" + interval.ToString() + "&ignore=.csv"; // Initialize a new WebRequest. HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL); // Get the response from the Internet resource. HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse(); // Read the body of the response from the server. StreamReader strm = new StreamReader(webresp.GetResponseStream(), Encoding.ASCII); temp = strm.ReadToEnd(); //results = temp.Split(new Char[] { ',' }); //results[0] = temp; strm.Close(); } catch { //some exception } return temp; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using FreeTradeWindowsForms; namespace FreeTradeWindowsForms.Models { public class User { Stock stock = new Stock(); public string Username { get; set; } public string Password { get; set; } /// <summary> /// Buying power available /// </summary> public double Cash { get; set; } /// <summary> /// Overall worth of cash and all investments /// </summary> public double Worth { get; set; } /// <summary> /// Total amount of cash used for investing - this only changes if more cash is borrowed, this will be the basis of all performance calculations /// </summary> public double borrowedCash { get; set; } /// <summary> /// // All companies that are currently being invested in. /// </summary> public List<Holding> Holdings { get; set; } public List<Transaction> Transactions { get; set; } public List<Company> WatchList { get; set; } /// <summary> /// This flag determines whether the user can trade when the market is closed /// </summary> public bool EnforceMarketClosure { get; set; } /// <summary> /// This value determines the fee that is charged for each transaction. /// </summary> public double transactionFee { get; set; } // Create a new user by setting the username, password, and how much cash they initially borrowed public User(string username, string password, double borrowedCash) { this.Username = username; this.Password = <PASSWORD>; this.borrowedCash = borrowedCash; this.Worth = borrowedCash; this.Cash = borrowedCash; this.EnforceMarketClosure = true; this.transactionFee = 0; Holdings = new List<Holding>(); Transactions = new List<Transaction>(); WatchList = new List<Company>(); } public User() { } /// <summary> /// Add more cash to use for investing. /// </summary> /// <param name="amount"></param> public bool AddCash(double amount) { if (amount > 0) { Cash += amount; borrowedCash += amount; return true; } return false; } /// <summary> /// Buy stocks /// </summary> /// <param name="companyName"></param> /// <param name="companySymbol"></param> /// <param name="currentSharePrice"></param> /// <param name="numOfShares"></param> /// <param name="time"></param> /// <returns></returns> public bool BuyStock(string companyName, string companySymbol, double currentSharePrice, int numOfShares, DateTime time) { if (!stock.IsOpenStockMarket() && EnforceMarketClosure) { MessageBox.Show("The market is closed."); return false; } if (numOfShares * currentSharePrice > Cash) { MessageBox.Show("You don't have enough money for that purchase. Dummy."); return false; } double transactionAmount = (numOfShares * currentSharePrice); // create a new holding if one doesn't already exist Holding holding = GetHolding(companySymbol); if (holding == null) { holding = new Holding(companySymbol); Holdings.Add(holding); holding.companyName = companyName; holding.currentSharePrice = currentSharePrice; } holding.numOfShares += numOfShares; holding.totalInvested += (transactionAmount); holding.worth += (transactionAmount); // Add to list of transactions Transactions.Add(new Transaction(companyName, companySymbol, currentSharePrice, numOfShares, time)); MessageBox.Show("You just purchased " + numOfShares + " shares of " + companyName + " stock at" + currentSharePrice.ToString("C2") + " per share."); Cash = Cash - transactionAmount; Cash = Cash - transactionFee; refresh(); return true; } /// <summary> /// Get a holding information /// </summary> /// <param name="companySymbol"></param> /// <returns></returns> public Holding GetHolding(string companySymbol) { for (int i = 0; i < Holdings.Count; i++) { if (Holdings[i].stockSymbol == companySymbol) { return Holdings[i]; } } return null; } /// <summary> /// Sell stocks /// </summary> /// <param name="companyName"></param> /// <param name="companySymbol"></param> /// <param name="currentSharePrice"></param> /// <param name="numOfShares"></param> /// <param name="time"></param> /// <returns></returns> public bool SellStock(string companyName, string companySymbol, double currentSharePrice, int numOfShares, DateTime time) { Holding holding = GetHolding(companySymbol); if (!stock.IsOpenStockMarket() && EnforceMarketClosure) { MessageBox.Show("The market is closed."); return false; } if (holding == null) return false; if (numOfShares > holding.numOfShares) { MessageBox.Show("You cannot sell more shares than you own, dummy..."); return false; } // Sale amount is subtracted from worth because worth is represents the overall worth of the stocks. double saleAmount = (numOfShares * currentSharePrice); holding.worth = holding.worth - saleAmount; Cash = Cash + saleAmount; Cash = Cash - transactionFee; // The effective price per share is the total amount of money invested divided by the number of shares being held. double effectivePricePerShare = (holding.totalInvested / holding.numOfShares); holding.totalInvested = holding.totalInvested - (effectivePricePerShare * numOfShares); holding.numOfShares = holding.numOfShares - numOfShares; refresh(); MessageBox.Show("You sold " + numOfShares.ToString() + " share(s) of " + companyName + " at " + currentSharePrice.ToString("C2") + " a share. Total sale amount: " + saleAmount.ToString("C2")); return true; } /// <summary> /// Add a company to the user's watchlist. /// </summary> /// <param name="company"></param> public void AddToWatchList(Company company) { if (!CompanyInWatchList(company)) { WatchList.Add(company); MessageBox.Show("Company added to watchlist."); } else { MessageBox.Show("Company already in watchlist."); } } public bool CompanyInWatchList(Company company) { foreach (Company watchListCompany in WatchList) { if (company.Symbol == watchListCompany.Symbol) { return true; } } return false; } /// <summary> /// Refresh user profile /// </summary> public void refresh() { // refresh everything in the user profile // refresh everything in each holding double tempWorth = 0; for (int i = 0; i < Holdings.Count; i++) { Holdings[i].Refresh(stock.getLatestValue(Holdings[i].stockSymbol)); tempWorth += Holdings[i].worth; } Worth = Cash + tempWorth; } /// <summary> /// Get a list of the top gainers /// </summary> /// <param name="count">How many holdings do you want in the list?</param> /// <param name="Gains">If true, returns top gainers, if false, top losers.</param> /// <returns></returns> public List<Holding> GetTopGainers(int count, bool gains) { refresh(); List<Holding> topGainers; if (gains) topGainers = Holdings.OrderByDescending(o => o.GetPerformance()).ToList(); else topGainers = Holdings.OrderBy(o => o.GetPerformance()).ToList(); if (count < Holdings.Count) { List<Holding> topGainersConstrained = new List<Holding>(); for (int i = 0; i < count; i++) topGainersConstrained.Add(topGainers[i]); return topGainersConstrained; } return topGainers; } private void AddTestDataToHoldings() { Holding holding = new Holding("AAPL"); holding.numOfShares = 5; holding.totalInvested = 80.00; Holdings.Add(holding); holding = new Holding("TSLA"); holding.numOfShares = 10; holding.totalInvested = 10000.00; Holdings.Add(holding); } public void GenerateReport(string filepath) { // Clear file if (File.Exists(filepath)) { File.WriteAllText(filepath, string.Empty); } StreamWriter file = new StreamWriter(filepath); refresh(); List<String> report = new List<string>(); report.Add("Auto Generated report for: " + Username); report.Add(DateTime.Now.ToShortDateString()); report.Add("------------------------------------------------"); report.Add(""); report.Add("Net Worth:\t" + Worth.ToString("C2")); report.Add("Cash on Hand:\t" + Cash.ToString("C2")); report.Add("Cash Borrowed:\t" + borrowedCash.ToString("C2")); report.Add("Num of Transactions: \t" + Transactions.Count.ToString()); report.Add(""); report.Add("Holdings"); report.Add("--------"); for (int i = 0; i < Holdings.Count; i++) { report.Add("\t" + (i + 1).ToString() + ". " + Holdings[i].companyName + " - " + Holdings[i].stockSymbol); report.Add("\t\tPerformance: " + Holdings[i].GetPerformance().ToString("P")); report.Add("\t\tNumber of Shares: " + Holdings[i].numOfShares); report.Add("\t\tWorth: " + Holdings[i].worth.ToString("C2")); report.Add("\t\tTotal Invested: " + Holdings[i].totalInvested.ToString("C2")); } for (int i = 0; i < report.Count; i ++) { file.WriteLine(report[i]); } file.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Windows.Forms; namespace FreeTradeWindowsForms { class Stock { // This doesn't work properly public string getAnnualizedGain(string symbol) { return getFromAPIquoute(symbol, "g3")[0]; } public string getExchange(string symbol) { return getFromAPIquoute(symbol, "x0")[0]; } public double getChange(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "c1")[0]); } public string getChangeInPercent(string symbol) { return getFromAPIquoute(symbol, "p2")[0]; } public double getStockYearHigh(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "k0")[0]); } public double getStockYearLow(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "j0")[0]); } // This method will return a string with the company name based on the symbol. public string getCompanyName(string symbol) { return getFromAPIquoute(symbol, "n")[0].Substring(1, getFromAPIquoute(symbol, "n")[0].Length - 4); } public double getLatestValue(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "l1")[0]); } // Stock Symbol // args listed here https://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty // returns an array of strings. Each arg is it's own element in the array. private string[] getFromAPIquoute(string symbol, string args) { string[] results = null; int count = 0; while (results == null && count < 3) { try { string temp = null; string yahooURL = @"http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=" + args; // Initialize a new WebRequest. HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL); // Get the response from the Internet resource. HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse(); // Read the body of the response from the server. StreamReader strm = new StreamReader(webresp.GetResponseStream(), Encoding.ASCII); temp = strm.ReadToEnd(); results = temp.Split(new Char[] { ',' }); strm.Close(); } catch { //some exception } count++; } if (count == 3) { MessageBox.Show("Can't seem to get ahold of Yahoo at the moment, maybe try again later?\nThe system will now exit."); results = new string[1] { "0" }; Environment.Exit(0); } return results; } public string getHistory(string symbol, DateTime from, DateTime to, char interval) { //string[] results = null; string temp = null; try { string yahooURL = @"http://ichart.yahoo.com/table.csv?s=" + symbol + "&a=" + (from.Month - 1).ToString() + "&b=" + (from.Day).ToString() + "&c=" + (from.Year).ToString() + "&d=" + (to.Month - 1).ToString() + "&e=" + (to.Day).ToString() + "&f=" + (to.Year).ToString() + "&g=" + interval.ToString() + "&ignore=.csv"; // Initialize a new WebRequest. HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL); // Get the response from the Internet resource. HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse(); // Read the body of the response from the server. StreamReader strm = new StreamReader(webresp.GetResponseStream(), Encoding.ASCII); temp = strm.ReadToEnd(); //results = temp.Split(new Char[] { ',' }); //results[0] = temp; strm.Close(); } catch { //some exception } return temp; } public bool IsOpenStockMarket() { TimeSpan _marketUpdateDelay = new TimeSpan(0, 15, 00); // market update delay TimeSpan _marketOpenTime = new TimeSpan(9, 30, 00); // market open time TimeSpan _marketCloseTime = new TimeSpan(16, 00, 00); // market close time DateTime dt = DateTime.Now; string nameOfTheDay = DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("en-GB")).ToLower(); if (nameOfTheDay == "sunday" || nameOfTheDay == "saturday") { return false; } // check if current time is between stock marker open and close hours if (dt.Hour > _marketOpenTime.Hours && dt.Hour < _marketCloseTime.Hours) return true; if (dt.Hour == _marketOpenTime.Hours && dt.Minute >= _marketOpenTime.Minutes + _marketUpdateDelay.Minutes) return true; if (dt.Hour == _marketCloseTime.Hours && dt.Minute <= _marketCloseTime.Minutes + _marketUpdateDelay.Minutes) return true; return false; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FreeTrade { public class Company { public string Symbol { get; set; } public string Name { get; set; } public string Sector { get; set; } public string Industry { get; set; } public string IPOyear { get; set; } public double StockPrice; public Company(String symbol, String name, String sector, String industry, String ipoYear, double stockPrice) { Symbol = symbol; Name = name; Sector = sector; Industry = industry; IPOyear = ipoYear; StockPrice = stockPrice; } public double getStockPrice() { Stock stock = new Stock(); return stock.getLatestValue(Symbol); } public override string ToString() { return Name + " - " + Symbol; } public bool Contains(string query) { query = query.ToLower(); return (Symbol.ToLower().Contains(query) || Name.ToLower().Contains(query) || Sector.ToLower().Contains(query) || Industry.ToLower().Contains(query) || IPOyear.ToLower().Contains(query)); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using FreeTradeWindowsForms.Controllers; using FreeTradeWindowsForms.Models; namespace FreeTradeWindowsForms { public partial class Settings : Form { User user; public Settings(User user) { InitializeComponent(); this.user = user; if (!user.EnforceMarketClosure) { marketCloseBox.Text = "No"; } settingsFeesBox.Text = user.transactionFee.ToString(); } public User getUser() { return user; } public string getCash() { return settingsCashBox.Text; } public string getFees() { return settingsFeesBox.Text; } public string getEnforcement() { return marketCloseBox.Text; } private void settingsSaveButton_Click(object sender, EventArgs e) { string message = ""; double temp = 0; //used in parsing and then assigned to revelent fields. if (settingsCashBox.Text.Length > 0 && double.TryParse(settingsCashBox.Text, out temp)) { if (user.AddCash(temp)) { } else message += "No money has been added since cash is zero."; } else { if(settingsCashBox.Text.Length > 0) message += "Invalid Entry in cash"; } //add fees here. if (settingsFeesBox.Text.Length >= 0 && double.TryParse(settingsFeesBox.Text, out temp) && temp >= 0) user.transactionFee= temp; else { if(message.Length > 0) message+=Environment.NewLine; if(settingsFeesBox.Text.Length > 0) message += "Invalid entry in fees"; else settingsFeesBox.Text = user.transactionFee.ToString(); } //set market enforcement if (getEnforcement().Equals("Yes")) { user.EnforceMarketClosure = true; } else { user.EnforceMarketClosure = false; } //close the settings window. this.Close(); if (message.Length > 0) MessageBox.Show(message); else MessageBox.Show("Settings changed."); } private void settingsFeesBox_TextChanged(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; namespace FreeTrade { class Stock { // This doesn't work properly public string getAnnualizedGain(string symbol) { return getFromAPIquoute(symbol, "g3")[0]; } public string getExchange(string symbol) { return getFromAPIquoute(symbol, "x0")[0]; } public double getChange(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "c1")[0]); } public string getChangeInPercent(string symbol) { return getFromAPIquoute(symbol, "p2")[0]; } public double getStockYearHigh(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "k0")[0]); } public double getStockYearLow(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "j0")[0]); } // This method will return a string with the company name based on the symbol. public string getCompanyName(string symbol) { return getFromAPIquoute(symbol, "n")[0].Substring(1, getFromAPIquoute(symbol, "n")[0].Length - 4); } public double getLatestValue(string symbol) { return Convert.ToDouble(getFromAPIquoute(symbol, "l1")[0]); } // Stock Symbol // args listed here https://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty // returns an array of strings. Each arg is it's own element in the array. private string[] getFromAPIquoute(string symbol, string args) { string[] results = null; try { string temp = null; string yahooURL = @"http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=" + args; // Initialize a new WebRequest. HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL); // Get the response from the Internet resource. HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse(); // Read the body of the response from the server. StreamReader strm = new StreamReader(webresp.GetResponseStream(), Encoding.ASCII); temp = strm.ReadToEnd(); results = temp.Split(new Char[] { ',' }); strm.Close(); } catch { //some exception } return results; } public string getHistory(string symbol, DateTime from, DateTime to, char interval) { //string[] results = null; string temp = null; try { string yahooURL = @"http://ichart.yahoo.com/table.csv?s=" + symbol + "&a=" + (from.Month - 1).ToString() + "&b=" + (from.Day).ToString() + "&c=" + (from.Year).ToString() + "&d=" + (to.Month - 1).ToString() + "&e=" + (to.Day).ToString() + "&f=" + (to.Year).ToString() + "&g=" + interval.ToString() + "&ignore=.csv"; // Initialize a new WebRequest. HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL); // Get the response from the Internet resource. HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse(); // Read the body of the response from the server. StreamReader strm = new StreamReader(webresp.GetResponseStream(), Encoding.ASCII); temp = strm.ReadToEnd(); //results = temp.Split(new Char[] { ',' }); //results[0] = temp; strm.Close(); } catch { //some exception } return temp; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FreeTradeWindowsForms { public partial class WhatIf : Form { public WhatIf() { InitializeComponent(); } private void whatButton_Click(object sender, EventArgs e) { try { DateTime from = fromPicker.Value; DateTime to = toPicker.Value; Stock stock = new Stock(); string[] splitResults = stock.getHistory(companySymbolBox.Text, from, from, 'm').Split(new Char[] { ',' }); double fromPrice = Convert.ToDouble(splitResults[7]); splitResults = stock.getHistory(companySymbolBox.Text, to, to, 'm').Split(new Char[] { ',' }); double toPrice = Convert.ToDouble(splitResults[7]); int numShares = Convert.ToInt32(purchasedSharesBox.Text); double profit = (toPrice - fromPrice) * numShares; if (profit >= 0) MessageBox.Show("You would have made " + profit.ToString("C2") + " had you bought " + numShares + " share(s) of " + companySymbolBox.Text + " in " + from.Year + " and then sold in " + to.Year + "\nFrom: " + fromPrice.ToString("C2") + "\nTo: " + toPrice.ToString("C2")); else MessageBox.Show("You would have lost " + profit.ToString("C2") + " had you bought " + numShares + " share(s) of " + companySymbolBox.Text + " in " + from.Year + " and then sold in " + to.Year + "\nFrom: " + fromPrice.ToString("C2") + "\nTo: " + toPrice.ToString("C2")); } catch { MessageBox.Show("Something is wrong with this."); } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FreeTradeWindowsForms { public partial class Login : Form { public Login() { InitializeComponent(); } private void loginButton_Click(object sender, EventArgs e) { this.Close(); } public string getUsername() { return usernameBox.Text; } public string getPassword() { return passBox.Text; } private void newUserButton_Click(object sender, EventArgs e) { NewUser newUser = new NewUser(); newUser.Show(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using FreeTrade.ViewModels; namespace FreeTrade.Views { /// <summary> /// Interaction logic for Trade.xaml /// </summary> public partial class Trade : UserControl { TradeViewModel viewModel = new TradeViewModel(); public Trade() { InitializeComponent(); this.DataContext = viewModel; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using FreeTradeWindowsForms.Controllers; namespace FreeTradeWindowsForms { public partial class NewUser : Form { public NewUser() { InitializeComponent(); } public string getUsername() { return newUserNameBox.Text; } public string getPassword() { return pass1Box.Text; } public string getPasswordVerification() { return pass2Box.Text; } public string getStartingCash() { return startCashBox.Text; } //protected override void OnFormClosing(FormClosingEventArgs e) //{ // base.OnFormClosing(e); // if (e.CloseReason == CloseReason.WindowsShutDown) return; // if (pass1Box.Text != pass2Box.Text) // { // // Confirm user wants to close // switch (MessageBox.Show(this, "Your passwords do not match.", "Incorrect Input", MessageBoxButtons.OK)) // { // case DialogResult.OK: // e.Cancel = true; // break; // default: // break; // } // } //} private void addUserButton_Click(object sender, EventArgs e) { double startingCash; bool test = double.TryParse(getStartingCash(), out startingCash); if (string.IsNullOrEmpty(getUsername()) || string.IsNullOrEmpty(getPassword()) || string.IsNullOrEmpty(getPasswordVerification()) || string.IsNullOrEmpty(getStartingCash()) || !double.TryParse(getStartingCash(), out startingCash) || pass1Box.Text != pass2Box.Text || startingCash < 0) { MessageBox.Show("Invalid information. Please try again."); return; } if (LoginController.isUser(getUsername())) MessageBox.Show("Username already exists."); else { LoginController.CreateNewUser(getUsername(), getPassword(), double.Parse(getStartingCash())); this.Close(); } } private void startCashBox_TextChanged(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using System.IO; namespace FreeTradeWindowsForms { public class Search { List<Company> stocks = new List<Company>(); public Search() { initialize(); } public List<string> getStocksList(string filename) { List<string> allStocks = new List<string>(); using (StreamReader r = new StreamReader(filename)) { string line; while ((line = r.ReadLine()) != null) { allStocks.Add(line); } } return allStocks; } public void initialize() { List<string> allStocks = new List<string>(); allStocks.AddRange(getStocksList(@"../../Stocks/nyse.csv")); allStocks.AddRange(getStocksList(@"../../Stocks/nasdaq.csv")); allStocks.AddRange(getStocksList(@"../../Stocks/amex.csv")); string[] lines = allStocks.ToArray(); String[] columns = null; Company theCompany = new Company(null, null, null, null, null, 0); foreach (String line in lines) { columns = line.Replace("\"", "").Split(','); theCompany.Name = columns[1]; theCompany.Symbol = columns[0]; theCompany.Sector = columns[6]; theCompany.Industry = columns[7]; theCompany.IPOyear = columns[5]; stocks.Add(theCompany); theCompany = new Company(null, null, null, null, null, 0); } } public List<Company> search(string query) { if (!String.IsNullOrEmpty(query)) { query = query.ToLower(); List<Company> results = new List<Company>(); results.AddRange(stocks.FindAll(x => x.Contains(query))); List<Company> result = new List<Company>(results); return result; } return null; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FreeTradeWindowsForms.Models { public class Holding { // TODO: add companyName and currentPrice /* * This class represents a company that a user is invested in. * * Properties: * numOfShares - the total number of shares invested in the company. * stockSymbol - the stock symbol of the company that is being held. * totalValue - value of all assets in company * worth - the amount of money the holding is worth at the current stock price. * */ public Holding(string stockSymbol) { this.stockSymbol = stockSymbol; this.companyName = ""; this.currentSharePrice = 0.0; this.numOfShares = 0; this.totalInvested = 0.0; this.worth = 0.0; this.performance = 0.0; } public Holding() { } public int numOfShares; public string stockSymbol; public string companyName; public double totalInvested; public double currentSharePrice; public double worth; public double performance; /// <summary> /// Get the percentage increase or decrease, don't forget to update the current share price manually before using this. /// </summary> public double GetPerformance() { return ((worth / totalInvested) - 1); } public void Refresh(double currentPrice) { this.currentSharePrice = currentPrice; worth = numOfShares * currentPrice; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using FreeTradeWindowsForms.Models; namespace FreeTradeWindowsForms.Controllers { static class LoginController { public static User Login(string username, string password) { //Construct the filepath string filepath = Directory.GetCurrentDirectory() + "\\" + username + ".txt"; // User already exists if (File.Exists(filepath)) { System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(User)); System.IO.StreamReader file = new System.IO.StreamReader(filepath); User user = new User(); user = (User)reader.Deserialize(file); file.Close(); if (user.Password == password) return user; else return null; } else { // User not found return null; } } public static bool isUser(string username) { string filepath = Directory.GetCurrentDirectory() + "\\" + username + ".txt"; if (File.Exists(filepath)) return true; else return false; } public static User CreateNewUser(string username, string password, double startingCash) { //Construct the filepath string filepath = Directory.GetCurrentDirectory() + "\\" + username + ".txt"; // User already exists if (File.Exists(filepath)) return null; User user = new User(username, password, startingCash); Logout(user); return user; } public static void Logout(User user) { // The following is just test code //User user = new User("Ted", "<PASSWORD>", <PASSWORD>); //user.Holdings.Add(new Holding("GOOG")); //DateTime newDate = new DateTime(); //user.WatchList.Add(new Company("test", "GOOG", "Something", "Something", "Something", 50.00)); //user.Transactions.Add(new Transaction("Test", "Test", 50.00, 50, DateTime.Now)); System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(User)); //Construct the filepath string filepath = Directory.GetCurrentDirectory() + "\\" + user.Username + ".txt"; // Clear the file if (File.Exists(filepath) ) { File.WriteAllText(filepath, string.Empty); } System.IO.StreamWriter file = new System.IO.StreamWriter( filepath); writer.Serialize(file, user); file.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FreeTrade { class Test { public void theTest(string[] args) { Stock stock = new Stock(); Console.WriteLine(stock.getLatestValue("sdfgsdfg").ToString()); Console.WriteLine(stock.getChangeInPercent("GOOG").ToString()); Console.WriteLine(stock.getChange("GOOG").ToString()); Console.WriteLine(stock.getExchange("GOOG").ToString()); Console.WriteLine(stock.getAnnualizedGain("GOOG").ToString()); DateTime from = new DateTime(2010, 1, 1); DateTime to = DateTime.Now; Console.WriteLine(stock.getHistory("GOOG", from, to, 'w').ToString()); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace transaction { class UserProfile { private List<CompanyStock> lCompanyStock; private List<StockTransaction> lStockTransaction; private string sName; private double dMoney; private double dPurchases; private double dSales; private double dChargedFees; private double dTransFee; List<CompanyStockInfo> GetCompnayList() { List<CompanyStockInfo> Temp = new List<CompanyStockInfo>(); foreach (CompanyStock cs in lCompanyStock) { Temp.Add(cs.GetDescriptor()); } return Temp; } List<StockTransactionInfo> GetTransactionList() { List<StockTransactionInfo> Temp = new List<StockTransactionInfo>(); foreach (StockTransaction st in lStockTransaction) { Temp.Add(st.GetDescriptor()); } return Temp; } public UserProfile() { sName = "default"; dMoney = 5000.0; dPurchases = 0.0; dSales = 0.0; dChargedFees = 0.0; dTransFee = 7.00; lCompanyStock = new List<CompanyStock>(); lStockTransaction = new List<StockTransaction>(); } public UserProfile(string name, double money, double transFee) { //setting up a new user if (!SetName(name)) { sName = "error"; } if (!SetMoney(money)) { dMoney = 0.0; } dPurchases = 0.0; dSales = 0.0; dChargedFees = 0.0; if (!SetTransActionFee(transFee)) { dTransFee = 2.00; } lCompanyStock = new List<CompanyStock>(); lStockTransaction = new List<StockTransaction>(); } public UserProfile(string name) { sName = name; lCompanyStock = new List<CompanyStock>(); lStockTransaction = new List<StockTransaction>(); ReadFromFile(); } public void WriteToFiles() { //5 fields/ string nl = Environment.NewLine; string temp = dMoney.ToString() + nl + dPurchases.ToString() + nl + dSales.ToString() + nl + dChargedFees.ToString() + nl + dTransFee.ToString(); System.IO.File.WriteAllText(sName + "UserProfile.txt", temp); System.IO.StreamWriter file = new System.IO.StreamWriter(sName + "CompanyStock.txt", true); foreach(CompanyStock cs in lCompanyStock) { //5 fields file.WriteLine(cs.GetName()); file.WriteLine(cs.GetSymbol()); file.WriteLine(cs.GetSpent().ToString()); file.WriteLine(cs.GetEarned().ToString()); file.WriteLine(cs.GetShares().ToString()); } file.Close(); file = new System.IO.StreamWriter(sName + "StockTransaction.txt", true); foreach(StockTransaction st in lStockTransaction) { //6 lines file.WriteLine(st.GetName()); file.WriteLine(st.GetSymbol()); file.WriteLine(st.GetPrice()); file.WriteLine(st.GetShares()); file.WriteLine(st.GetDate().ToString("MM dd yyyy HH mm ss fff")); file.WriteLine(st.GetSold().ToString()); } file.Close(); } private void ReadFromFile() // this is private for a really good reason. this function should only be used by constructor. { //Read Basic User Data In string[] lines = System.IO.File.ReadAllLines(sName + "UserProfile.txt"); dMoney = double.Parse(lines[0]); dPurchases = double.Parse(lines[1]); dSales = double.Parse(lines[2]); dChargedFees = double.Parse(lines[3]); dTransFee = double.Parse(lines[4]); lines = System.IO.File.ReadAllLines(sName + "CompanyStock.txt"); string tempName; string tempSymbol; double tempSpent; double tempEarned; double tempShares; for (int i = 0; i < lines.Length; i += 5) { tempName= lines[i]; tempSymbol = lines[i+1 ]; tempSpent = double.Parse(lines[i + 2]); tempEarned = double.Parse(lines[i + 3]); tempShares = double.Parse(lines[i + 4]); lCompanyStock.Add(new CompanyStock(tempName,tempSymbol,tempSpent,tempEarned,tempShares)); } lines = System.IO.File.ReadAllLines(sName + "StockTransaction.txt"); DateTime dt; bool tempSold; double tempPrice; string [] dtSpl; // Date Splitter; int month; int day; int year; int hour; int minute; int second; int millisecond; for (int i = 0; i < lines.Length; i += 6) { tempName = lines[i]; tempSymbol = lines[i + 1]; tempPrice = double.Parse(lines[i + 2]); tempShares = double.Parse(lines[i + 3]); dtSpl = lines[i + 4].Split(' '); tempSold = bool.Parse(lines[i + 5]); month = int.Parse(dtSpl[0]); day = int.Parse(dtSpl[1]); year = int.Parse(dtSpl[2]); hour = int.Parse(dtSpl[3]); minute = int.Parse(dtSpl[4]); second = int.Parse(dtSpl[5]); millisecond = int.Parse(dtSpl[6]); dt = new DateTime(year, month, day, hour, minute, second, millisecond); lStockTransaction.Add(new StockTransaction(tempName,tempSymbol,tempPrice,tempShares,dt,tempSold)); } } public string GetName() { return sName; } public bool SetName(string name) { if (name != null && name.Length > 0) { sName = name; return true; } return false; } public bool BuyStock(String name, string symbol, double price, double shares, DateTime dt) { if (shares * price > dMoney) return false; if (name == null || symbol == null) return false; dMoney -= ((shares * price) + dChargedFees); dChargedFees += dTransFee; dPurchases += (shares * price); bool found = false; lStockTransaction.Add(new StockTransaction(name, symbol, price, shares, dt, false)); for (int i = 0; i < lCompanyStock.Count && !found; i++) { if (lCompanyStock[i].GetName() == name && lCompanyStock[i].GetSymbol() == symbol) { double spentTemp = lCompanyStock[i].GetSpent(); double sharesTemp = lCompanyStock[i].GetShares(); found = true; lCompanyStock[i].SetShares(sharesTemp + shares); lCompanyStock[i].SetSpent(spentTemp + (price * shares)); } } if (!found) { lCompanyStock.Add(new CompanyStock(name, symbol, price * shares, 0, shares)); } return true; } public bool SellStock(String name, string symbol, double price, double shares, DateTime dt) { if (name == null || symbol == null) return false; bool found = false; for (int i = 0; i < lCompanyStock.Count && !found; i++) { if (lCompanyStock[i].GetName() == name && lCompanyStock[i].GetSymbol() == symbol) { double earnedTemp = lCompanyStock[i].GetEarned(); double sharesTemp = lCompanyStock[i].GetShares(); found = true; if (shares > sharesTemp) return false; dSales += (shares * price); lCompanyStock[i].SetEarned(earnedTemp+(shares*price)); lCompanyStock[i].SetShares(sharesTemp - shares); } } lStockTransaction.Add(new StockTransaction(name, symbol, price, shares, dt, true)); dMoney += ((shares * price) - dChargedFees); return true; } public double GetMoney() { return dMoney; } bool SetMoney(double money) { if (money >= 0.0) { dMoney = money; return true; } return false; } public double GetPurchases() { return dPurchases; } public bool SetPurchases(double pur) { if (pur >= 0) { dPurchases = 0.0; return true; } return false; } public double GetSales() { return dSales; } public bool SetSales(double sales) { if (sales >= 0) { dSales = sales; return true; } return false; } public double GetChargedFee() { return dTransFee; } public bool SetChargedFee(double charged) { if (charged >= 0.0) { dChargedFees = charged; return true; } return false; } public double GetTransActionFee() { return dTransFee; } public bool SetTransActionFee(double transFee) { if (transFee >= 0) { dTransFee = transFee; return true; } return false; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace transaction { struct StockTransactionInfo { public string Name; public string Symbol; public string Price; public string Shares; public string date; public string Sold; } public class StockTransaction { private string sName; private string sStockSymbol; private double dPrice; private double dShares; private DateTime dtDate; private bool bSold; public StockTransactionInfo GetDescriptor() { StockTransactionInfo Temp = new StockTransactionInfo(); Temp.Name = sName; Temp.Symbol = sStockSymbol; Temp.Price = dPrice.ToString(); Temp.Shares = dShares.ToString(); Temp.date = dtDate.ToString("MM/dd/yyyy hh:mm:ss.fff"); Temp.Sold = bSold.ToString(); return Temp; } public StockTransaction() { sName = "default"; sStockSymbol = "dt"; dPrice = 0.0; dShares = 0.0; dtDate = DateTime.Now; bSold = false; } public StockTransaction(string name, string symbol, double price, double shares, DateTime dt, bool sold) { if (!SetName(name))//if Error. { sName = "Invalid Name"; } if (!SetSymbol(symbol)) { sStockSymbol = "Invalid Symbol"; } if(!SetPrice(price)) { price = 0.0; } if(!SetShares(shares)) { dShares = 0.0; } if (!SetDate(dtDate)) { dtDate = DateTime.Now; } bSold = sold; } public string GetName() { return sName; } public bool SetName(string name) { if (name != null && name.Length > 0) { sName = name; return true; } return false; } public string GetSymbol() { return sStockSymbol; } public bool SetSymbol(string symbol) { if (symbol !=null && symbol.Length > 0) { sStockSymbol = symbol; return true; } return false; } public double GetPrice() { return dPrice; } public bool SetPrice(double price) { if (price >= 0.0) { dPrice = price; return true; } return false; } public double GetShares() { return dShares; } bool SetShares(double shares) { if (shares >= 0.0) { dShares = shares; return true; } return false; } public bool SetDate(DateTime dt) { if (dt == null) return false; //creating a deep copy int Month = dt.Month; int Day = dt.Day; int Year = dt.Year; int Hour = dt.Hour; int Minute = dt.Minute; int Second = dt.Second; int Millisecond = dt.Millisecond; //deep copy dont touch our guts. dtDate = new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond); return true; } public DateTime GetDate() { //deep copy so we don't play with the guts. int Month = dtDate.Month; int Day = dtDate.Day; int Year = dtDate.Year; int Hour = dtDate.Hour; int Minute = dtDate.Minute; int Second = dtDate.Second; int Millisecond = dtDate.Millisecond; return new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond); } public bool GetSold() { return bSold; } public void SetSold(bool s) { bSold = s; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FreeTradeWindowsForms.Models { public class Transaction { public string CompanyName { get; set; } public string StockSymbol { get; set; } public double SharePrice { get; set; } public int NumOfShares { get; set; } public DateTime date { get; set; } public Transaction() { } public Transaction(string companyName, string companySymbol, double sharePrice, int numOhShares, DateTime date) { this.CompanyName = companyName; this.StockSymbol = companySymbol; this.SharePrice = sharePrice; this.NumOfShares = numOhShares; this.date = date; } } } <file_sep>FreeTrade ========= This application allows you to practice buying and selling stocks. <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; using System.Collections.ObjectModel; using FreeTrade.Models; using FreeTrade.Helpers; namespace FreeTrade.ViewModels { class TradeViewModel : ViewModelBase { public Search searchHelper = new Search(); private string companyName; private string searchTerm; private Company selectedCompany; private bool isCompanySelected = false; public ObservableCollection<Company> companies; public TradeViewModel() { searchHelper.initialize(); companies = new ObservableCollection<Company>(); } #region PROPERTIES public string CompanyName { get { return companyName; } set { if (companyName != value) { companyName = value; RaisePropertyChanged("CompanyName"); } } } public string SearchTerm { get { return searchTerm; } set { if (searchTerm != value) { searchTerm = value; RaisePropertyChanged("SearchTerm"); } } } public ObservableCollection<Company> Companies { get { return companies; } set { if (companies != value) { companies = value; RaisePropertyChanged("Companies"); } } } public Company SelectedCompany { get { return selectedCompany; } set { if (selectedCompany != value) { selectedCompany = value; RaisePropertyChanged("SelectedCompany"); if (selectedCompany != null) { IsCompanySelected = true; RaisePropertyChanged("IsCompanySelected"); } else { IsCompanySelected = false; RaisePropertyChanged("IsCompanySelected"); } } } } public bool IsCompanySelected { get { return isCompanySelected; } set { if (isCompanySelected != value) { isCompanySelected = value; RaisePropertyChanged("IsCompanySelected"); } } } #endregion PROPERTIES #region METHODS public void Search() { Companies = searchHelper.search(searchTerm); } public bool CanSearch() { return true; } #endregion METHODS #region COMMANDS private ICommand searchCommand; public ICommand SearchCommand { get { if (searchCommand == null) { searchCommand = new RelayCommand( param => this.Search(), param => this.CanSearch() ); } return searchCommand; } } #endregion COMMANDS } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Timers; using System.Threading.Tasks; using System.Windows.Forms; using FreeTradeWindowsForms.Controllers; using FreeTradeWindowsForms.Models; using System.Threading; namespace FreeTradeWindowsForms { public partial class MainForm : Form { User user; List<Company> results = new List<Company>(); Thread refreshThread; System.Timers.Timer refreshTimer; public MainForm() { InitializeComponent(); showLogin(); updateMarketStatus(); initializeUser(); refreshThread = new Thread(refresh); refreshThread.Start(); refreshTimer = new System.Timers.Timer(30000); } public void refresh() { Thread.Sleep(30000); this.Invoke((MethodInvoker)delegate { if (mainTab.SelectedIndex == 0) { user.refresh(); updateOverview(); } }); refresh(); } public void updateMarketStatus() { Stock marketCheck = new Stock(); if (marketCheck.IsOpenStockMarket()) { marketStatus.Text = "Open"; marketStatus.ForeColor = System.Drawing.Color.Green; } else { marketStatus.Text = "Closed"; marketStatus.ForeColor = System.Drawing.Color.Red; } } public void showLogin() { Login login = new Login(); DialogResult result = login.ShowDialog(); if (result == DialogResult.Cancel) { Environment.Exit(0); return; } user = LoginController.Login(login.getUsername(), login.getPassword()); if (user == null) { MessageBox.Show("Invalid username or password."); showLogin(); } } public void initializeUser() { statusUserCash.Text = user.Cash.ToString("C2"); statusUsername.Text = user.Username; updateOverview(); } public void updateOverview() { LabelCashOverview.Text = user.Worth.ToString("C2"); updateWatchlistBox(); UpdateTopGainersListbox(); LabelOverallWorth.Text = user.Worth.ToString("C2"); double userTotalReturns = ((user.Worth / user.borrowedCash) - 1); LabelTotalReturns.Text = userTotalReturns.ToString("P"); if (userTotalReturns < 0) LabelTotalReturns.ForeColor = Color.Red; else LabelTotalReturns.ForeColor = Color.Green; LabelCashOverview.Text = user.Cash.ToString("C2"); } private void updateWatchlistBox() { ListBoxWatchlist.Items.Clear(); List<Company> comps = user.WatchList; comps.Reverse(); foreach (Company company in comps) { ListBoxWatchlist.Items.Add(String.Format("{0} - {1}", company.Name, company.getStockPrice().ToString("C2"))); } } private void UpdateTopGainersListbox() { ListBoxTop5Gains.Items.Clear(); ListBoxTop5Loss.Items.Clear(); List<Holding> topGainers = user.GetTopGainers(5, true); foreach (Holding holding in topGainers) ListBoxTop5Gains.Items.Add(String.Format("{0} | %{1}", holding.companyName, holding.GetPerformance().ToString("P"))); topGainers = user.GetTopGainers(5, false); foreach (Holding holding in topGainers) ListBoxTop5Loss.Items.Add(String.Format("{0} | %{1}", holding.companyName, holding.GetPerformance().ToString("P"))); } private void fileToolStripMenuItem_Click(object sender, EventArgs e) { } private void searchButton_Click(object sender, EventArgs e) { results = new List<Company>(); searchResults.Items.Clear(); string query = searchBox.Text; Search search = new Search(); results = search.search(query); if (results != null) { foreach (Company company in results) { searchResults.Items.Add(String.Format("{0} - {1}", company.Name, company.Symbol)); } } } private void searchResults_SelectedIndexChanged(object sender, EventArgs e) { Stock stock = new Stock(); int index = searchResults.SelectedIndex; if (index >= 0) { Company company = results[index]; tradeCompanyName.Text = company.Name; tradeSymbol.Text = company.Symbol; tradeStockPrice.Text = company.getStockPrice().ToString("C2"); tradeExchange.Text = stock.getExchange(company.Symbol); tradeIPO.Text = company.IPOyear; tradeIndustry.Text = company.Industry; tradeHigh.Text = stock.getStockYearHigh(company.Symbol).ToString("C2"); tradeLow.Text = stock.getStockYearLow(company.Symbol).ToString("C2"); List<Holding> holdings = user.Holdings; //loop through the purchased stocks. foreach (Holding holding in holdings) { if (holding.stockSymbol.Equals(company.Symbol)) { tradeCurrentSharesBox.Text = holding.numOfShares.ToString(); break; } else { tradeCurrentSharesBox.Text = "0"; } } } } private void searchEnter(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { searchButton_Click(null, null); e.Handled = true; } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { System.Windows.Forms.Application.Exit(); } private void buyButton_Click(object sender, EventArgs e) { int index = searchResults.SelectedIndex; if (index > -1) { Company company = results[index]; int numOfShares = 0; bool bParse = int.TryParse(tradeNumOfShares.Text, out numOfShares); DateTime now = DateTime.Now; // had to use short circuiting to make sure stocks were not bought with an ammount of zero. //rework of code?? if (bParse && numOfShares > 0 && user.BuyStock(company.Name, company.Symbol, company.getStockPrice(), numOfShares, now)) { statusUserCash.Text = user.Cash.ToString("C2"); if (string.IsNullOrEmpty(tradeCurrentSharesBox.Text)) { tradeCurrentSharesBox.Text = numOfShares.ToString(); } else tradeCurrentSharesBox.Text = (Convert.ToDouble(tradeCurrentSharesBox.Text) + numOfShares).ToString(); } else { if(numOfShares < 1) MessageBox.Show("Invalid Data in number of stocks."); } } else { MessageBox.Show("No company selected or field is empty!!!"); } } private void tradeNumOfShares_TextChanged(object sender, EventArgs e) { int index = searchResults.SelectedIndex; if (index > -1 && tradeNumOfShares.Text.Length>0) { Company company = results[index]; int numOfShares = 0; bool bParseSucces = false; bParseSucces = int.TryParse(tradeNumOfShares.Text, out numOfShares); if (bParseSucces) { transAmBox.Text = (company.getStockPrice() * numOfShares).ToString("C2"); } else { MessageBox.Show("Non-Numerial Entry in Number of Share", "Invalid Input"); tradeNumOfShares.Text = ""; } } else if (tradeNumOfShares.Text.Length == 0) { } else { MessageBox.Show("No company selected!!!!"); } } private void mainTab_SelectedIndexChanged(object sender, EventArgs e) { if (mainTab.SelectedIndex == 0) updateOverview(); if (mainTab.SelectedIndex == 1) fill_Portfolio(); if (mainTab.SelectedIndex == 2) clearTrade(); else clearTrade(); if (mainTab.SelectedIndex == 3) updatePerformance(); } public void clearTrade() { searchBox.Text = ""; tradeCurrentSharesBox.Text = ""; tradeCompanyName.Text = ""; tradeSymbol.Text = ""; tradeStockPrice.Text = ""; tradeExchange.Text = ""; tradeIPO.Text = ""; tradeIndustry.Text = ""; tradeHigh.Text = ""; tradeLow.Text = ""; tradeNumOfShares.Text = ""; transAmBox.Text = ""; } public void fill_Portfolio() { portDataGrid.Rows.Clear(); portDataGrid.Refresh(); portDataGrid.ColumnCount = 7; portDataGrid.Columns[0].Name = "Company Name"; portDataGrid.Columns[1].Name = "Company Symbol"; portDataGrid.Columns[2].Name = "Number of Shares"; portDataGrid.Columns[3].Name = "Current Price"; portDataGrid.Columns[4].Name = "Worth"; portDataGrid.Columns[5].Name = "Total Invested"; List<Holding> stocks = user.Holdings; //loop through the purchased stocks. foreach (Holding stock in stocks) { string[] row = new string[6]; row[0] = stock.companyName; row[1] = stock.stockSymbol; row[2] = stock.numOfShares.ToString(); row[3] = stock.currentSharePrice.ToString("C2"); row[4] = stock.worth.ToString("C2"); row[5] = stock.totalInvested.ToString("C2"); portDataGrid.Rows.Add(row); } } private void label9_Click(object sender, EventArgs e) { } private void tradeSellButton_Click(object sender, EventArgs e) { int index = searchResults.SelectedIndex; if (index > -1) { Company company = results[index]; int numOfShares = 0; bool bParse = int.TryParse(tradeNumOfShares.Text, out numOfShares); DateTime now = DateTime.Now; double price = company.getStockPrice(); //had to use short circuiting if (bParse && numOfShares > 0 && user.SellStock(company.Name, company.Symbol, price, numOfShares, now)) { tradeCurrentSharesBox.Text = (Convert.ToDouble(tradeCurrentSharesBox.Text) - numOfShares).ToString(); } else MessageBox.Show("Error in Number of stocks."); statusUserCash.Text = user.Cash.ToString("C2"); } else { MessageBox.Show("No company selected!!!"); } } private void watchButton_Click(object sender, EventArgs e) { int index = searchResults.SelectedIndex; if (index > -1) { Company company = results[index]; user.AddToWatchList(company); } else { MessageBox.Show("No company selected."); } } private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { } private void preferencesToolStripMenuItem_Click(object sender, EventArgs e) { Settings settings = new Settings(user); settings.ShowDialog(); user=settings.getUser(); statusUserCash.Text = user.Cash.ToString("C2"); } protected override void OnFormClosing(FormClosingEventArgs e) { refreshThread.Abort(); base.OnFormClosing(e); LoginController.Logout(user); if (e.CloseReason == CloseReason.WindowsShutDown) return; } public void updatePerformance() { performanceHoldingsBox.Items.Clear(); List<Holding> holdings = user.Holdings; //loop through the purchased stocks. foreach (Holding holding in holdings) { performanceHoldingsBox.Items.Add(String.Format("{0} | {1} | {2}", holding.companyName, holding.currentSharePrice.ToString("C2"), holding.GetPerformance().ToString("P"))); } //load initial graph. updatePerformanceGraph("", ""); } public void updatePerformanceGraph(string symbol, string timePeriod) { performancePic.Load("http://chart.finance.yahoo.com/z?s=" + symbol + "&t="+timePeriod); } private void performanceHoldingsBox_SelectedIndexChanged(object sender, EventArgs e) { updatePerformanceGraph(getHoldingBoxString(), getTimeBoxString()); } private string getHoldingBoxString() { int i = performanceHoldingsBox.SelectedIndex; if (i < 0) return ""; List<Holding> holdings = user.Holdings; return holdings[i].stockSymbol; } private void performanceTimeBox_SelectedIndexChanged(object sender, EventArgs e) { updatePerformanceGraph(getHoldingBoxString(), getTimeBoxString()); } private string getTimeBoxString() { int i = performanceTimeBox.SelectedIndex; if (i == 0) return "1d"; else if (i == 1) return "5d"; else if (i == 2) return "3m"; else if (i == 3) return "6m"; else if (i == 4) return "1y"; else if (i == 5) return "2y"; else if (i == 6) return "5y"; else if (i == 7) return "my"; else return ""; } private void whatIfToolStripMenuItem_Click(object sender, EventArgs e) { WhatIf whatIf = new WhatIf(); whatIf.Show(); } private void ButtonWatchlistDelete_Click(object sender, EventArgs e) { user.WatchList.RemoveAt(ListBoxWatchlist.SelectedIndex); ListBoxWatchlist.Items.RemoveAt(ListBoxWatchlist.SelectedIndex); } private void toolStripMenuItem1_Click(object sender, EventArgs e) { SaveFileDialog fileDialog = new SaveFileDialog(); fileDialog.DefaultExt = "*.ftr"; DialogResult result = fileDialog.ShowDialog(); if (result == DialogResult.OK) user.GenerateReport(fileDialog.FileName); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace transaction { struct CompanyStockInfo { public string Name; public string Symbol; public string Spent; public string Earned; public string Shares; } class CompanyStock { String sName; string sSymbol; double dSpent; double dEarned; double dShares; public CompanyStockInfo GetDescriptor() { CompanyStockInfo Temp = new CompanyStockInfo(); Temp.Name = sName; Temp.Symbol = sSymbol; Temp.Spent = dSpent.ToString(); Temp.Earned = dEarned.ToString(); return Temp; } public CompanyStock() { sName = "default"; sSymbol = "dt"; dSpent = 0; dEarned = 0; dShares = 0; } public CompanyStock(string name, string symbol, double spent, double earned, double shares) { if(!SetName(name)) // bad name entered { sName = "Error"; } if(!SetSymbol(symbol)) { sSymbol = "err"; } if(!SetSpent(spent)) { dSpent = 0.0; } if(!SetEarned(earned)) // again an error by the user. { dEarned = 0.0; } if(!SetShares(shares)) { dShares = 0.0; } } public string GetName() { return sName; } public bool SetName(string name) { if (name != null && name.Length > 0) { sName = name; return true; } return false; } public string GetSymbol() { return sSymbol; } public bool SetSymbol(string symbol) { if (symbol != null && symbol.Length > 0) { sSymbol = symbol; return true; } return false; } public double GetSpent() { return dSpent; } public bool SetSpent(double spent) { if (spent >= 0.0) { dSpent = spent; return true; } return false; } public double GetEarned() { return dEarned; } public bool SetEarned(double earned) { if (earned >= 0.0) { dEarned = earned; return true; } return false; } public double GetShares() { return dShares; } public bool SetShares(double shares) { if (shares >= 0.0) { dShares = shares; return true; } return false; } } }
0301df7fbcd292b77dcb182f21c633590488f488
[ "Markdown", "C#" ]
21
C#
bpeterman/FreeTrade
ae2638047a57acc3771b122fc05f6fa5a3757e57
40ed9fdd0ec6d27534d9b5f8622d2c8160290172
refs/heads/master
<repo_name>dnhsoft/docker-php<file_sep>/5.3/docker-compose.yml web: image: chudo1 ports: - "8000:80" <file_sep>/README.md # docker-php Few older PHP versions <file_sep>/5.3/Dockerfile FROM debian:6 RUN echo "deb http://packages.dotdeb.org squeeze all" >> /etc/apt/sources.list RUN echo "deb-src http://packages.dotdeb.org squeeze all" >> /etc/apt/sources.list RUN apt-get update && apt-get install -y \ wget RUN wget http://www.dotdeb.org/dotdeb.gpg RUN apt-key add dotdeb.gpg RUN apt-get update && apt-get install -y \ supervisor \ apache2 \ php5 \ libapache2-mod-php5 \ php5-mysql \ php5-curl \ php5-gd \ php5-idn \ php-pear \ php5-imap \ php5-mcrypt \ php5-memcache \ php5-mhash \ php5-ming \ php5-ps \ php5-pspell \ php5-recode \ php5-snmp \ php5-sqlite \ php5-tidy \ php5-xmlrpc \ php5-xsl \ php5-json EXPOSE 80 COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf CMD ["/usr/bin/supervisord"] <file_sep>/5.6/update-sources.sh #!/bin/bash THIS_DIR=$(dirname "$(readlink -f "$0")")"" rm -rf $THIS_DIR/apache cd $THIS_DIR/../../php-official/5.6 git pull origin master cp -R ./apache $THIS_DIR cd $THIS_DIR echo "Adding ftp and zip modules..." sed -i "s/--with-openssl/--with-openssl --enable-opcache --enable-ftp --enable-zip/g" ./apache/Dockerfile <file_sep>/7.2/setup-php.sh #!/bin/bash INI_DIR="/usr/local/etc/php/conf.d" DNH_INI_FILE="$INI_DIR/dnh-custom.ini" rm -f $DNH_INI_FILE echo "upload_max_filesize=$PHP_UPLOAD_MAX_FILESIZE" >> $DNH_INI_FILE echo "post_max_size=$PHP_POST_MAX_FILESIZE" >> $DNH_INI_FILE echo "memory_limit=$PHP_MEMORY_LIMIT" >> $DNH_INI_FILE echo "max_execution_time=$PHP_MAX_EXECUTION_TIME" >> $DNH_INI_FILE echo "session.cookie_secure=$PHP_SESSION_COOKIE_SECURE" >> $DNH_INI_FILE OPCACHE_INI_FILE="$INI_DIR/opcache-custom.ini" rm -f $OPCACHE_INI_FILE if [ "$PHP_OPCACHE_ENABLE" == "1" ]; then echo "zend_extension=opcache.so" >> $OPCACHE_INI_FILE echo "opcache.enable=1" >> $OPCACHE_INI_FILE echo "opcache.memory_consumption=$PHP_OPCACHE_MEMORY_CONSUMPTION" >> $OPCACHE_INI_FILE echo "opcache.interned_strings_buffer=$PHP_OPCACHE_INTERNED_STRINGS_BUFFER" >> $OPCACHE_INI_FILE echo "opcache.max_accelerated_files=$PHP_OPCACHE_ACCELERATED_FILES" >> $OPCACHE_INI_FILE echo "opcache.revalidate_freq=$PHP_OPCACHE_REVALIDATE_FREQ" >> $OPCACHE_INI_FILE echo "opcache.fast_shutdown=$PHP_OPCACHE_FAST_SHUTDOWN" >> $OPCACHE_INI_FILE fi APC_INI_FILE="$INI_DIR/apcu.ini" rm -f $APC_INI_FILE if [ $PHP_APCU_ENABLE == '1' ]; then echo 'extension=apcu.so' > $APC_INI_FILE fi <file_sep>/5.2/Dockerfile FROM debian:6 RUN echo "deb http://archive.debian.org/debian lenny main contrib non-free" >> /etc/apt/sources.list RUN apt-get update && apt-get install -y \ wget RUN wget http://www.dotdeb.org/dotdeb.gpg RUN apt-key add dotdeb.gpg COPY lenny.conf /etc/apt/preferences.d/lenny COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf RUN apt-get update && apt-get install -y \ supervisor \ apache2 \ mysql-client \ libapache2-mod-php5 \ php5-common \ php5-curl \ php5-gd \ php5-mcrypt \ php5-mysql \ php5-cli \ php5-mhash \ php5-xsl \ php5-imap \ php5-xmlrpc \ php5-sqlite \ php5-json EXPOSE 80 CMD ["/usr/bin/supervisord"]
57a4e1ef171f624791a0f1e144e361dcb73a03bf
[ "Markdown", "YAML", "Dockerfile", "Shell" ]
6
YAML
dnhsoft/docker-php
6540808bdad4d56866476a40351870f4648c49e7
54693338ed382644eb182d7b7936674ea8d8c12a
refs/heads/main
<file_sep># trio5 Virus <file_sep>#!/bin/bash clear sleep1 echo -e "╔════•ೋೋ•════╗" echo -e " Author : TC" echo -e " YT :TRIO CHANNEL" echo -e "╚════•ೋೋ•════╝" read -p "Masukan No Target : " nomor; while [[ true ]]; do echo -e "Mencoba Mengirim Virus Ke Nomor $nomor" done
e4eb09c5af8ea3a4943bce397136f0427e2e521b
[ "Markdown", "Shell" ]
2
Markdown
TrioChannel/trio5
863bdc49789e2df79ce4fb741e0815a90d0b0fa2
c63bc0ad3a2a51012ddc92416f30d8243e025ef7
refs/heads/master
<repo_name>liting68/planbook<file_sep>/weixin.php <?php require_once 'weixin/lib/config.php'; require_once 'weixin/wechat.php'; //define your token $wechat = WeChat::getInstance(); //$wechatObj->valid(); //$wechatObj->setToken(); //$wechatObj->sendCustomMsg("hello","o9ZPks_8ZpcQXBndQqjuUpt-E9tg"); //$wechat->responseMsg(); ?><file_sep>/App/Model/Qe.php <?php FLEA::loadClass('FLEA_Db_TableDataGateway'); class Model_Qe extends FLEA_Db_TableDataGateway { var $tableName = 'qe'; var $primaryKey = 'id'; function addTimes($qeid){ $times=$this->find(array('id'=>$qeid),'','times'); $this->updateField(array('id'=>$qeid), 'times', $times['times']*1+1); } } ?><file_sep>/App/Service/pdf/font/unifont/msyh.mtx.php <?php $name='MicrosoftYaHei'; $type='TTF'; $desc=array ( 'Ascent' => 1058, 'Descent' => -262, 'CapHeight' => 756, 'Flags' => 4, 'FontBBox' => '[-158 -255 1270 1036]', 'ItalicAngle' => 0, 'StemV' => 87, 'MissingWidth' => 697, ); $up=-87; $ut=58; $ttffile='/Library/WebServer/Documents/qa/App/Service/pdf/font/unifont/msyh.ttf'; $originalsize=15043584; $fontkey='microsoftyahei'; ?><file_sep>/App/Model/QsAnswerDetail.php <?php FLEA::loadClass('FLEA_Db_TableDataGateway'); class Model_QsAnswerDetail extends FLEA_Db_TableDataGateway { var $tableName = 'qs_answer_detail'; var $primaryKey = 'id'; } ?><file_sep>/App/Model/QeCon.php <?php FLEA::loadClass('FLEA_Db_TableDataGateway'); class Model_QeCon extends FLEA_Db_TableDataGateway { var $tableName = 'qecon'; var $primaryKey = 'id'; } ?><file_sep>/App/Class/Common.php <?php if (! function_exists ( 'mb_substr' )) { function mb_substr($str, $start, $len = '', $encoding = "UTF-8") { $limit = strlen ( $str ); for($s = 0; $start > 0; -- $start) { // found the real start if ($s >= $limit) break; if ($str [$s] <= "\x7F") ++ $s; else { ++ $s; // skip length while ( $str [$s] >= "\x80" && $str [$s] <= "\xBF" ) ++ $s; } } if ($len == '') return substr ( $str, $s ); else for($e = $s; $len > 0; -- $len) { //found the real end if ($e >= $limit) break; if ($str [$e] <= "\x7F") ++ $e; else { ++ $e; //skip length while ( $str [$e] >= "\x80" && $str [$e] <= "\xBF" && $e < $limit ) ++ $e; } } return substr ( $str, $s, $e - $s ); } } /** * Project: 公共函数 * Author: libin * Date: 2008年10月13日 * File: common.php * Version: 1.0 */ class Class_Common extends FLEA_Controller_Action { var $_admin; /** * Enter description here... * */ function __construct() { $this->_admin = & get_singleton ( "Model_Admin" ); } /** * Open, parse, and return the file content. * @author libin 2008-09-13 * @param string string the php file name * * @return string */ function include_fetch($file, $var = array()) { extract ( $var ); // Extract the vars to local namespace ob_start (); // Start output buffering include ($file); // Include the file $contents = ob_get_contents (); // Get the contents of the buffer ob_end_clean (); // End buffering and discard return $contents; // Return the contents } /** *调用包含函数 * @author libin 2008-09-13 * @param unknown_type $function * @param unknown_type $params * @return unknown */ function include_fetch_function($function, $params = array()) { ob_start (); call_user_func_array ( $function, $params ); $contents = ob_get_contents (); ob_end_clean (); return $contents; } /** * 显示模板页面 * @author libin 2008-09-13 * @param unknown_type $parm */ function show($parm = array()) { $smarty = & $this->_getView (); foreach ( $parm as $key => $value ) { $smarty->assign ( $key, $value ); } if (@$parm ['title'] == "") { $parm ['title'] = DEFAUT_TITLE; } $smarty->register_modifier ( "substr", array ("Class_Common", "m_substr" ) ); $smarty->register_modifier ( "formatdate", array ("Class_Common", "formatdate" ) ); $smarty->register_modifier ( "formatmoney", array ("Class_Common", "formatmoney" ) ); if (isset ( $_SESSION ['loginuserid'] ) && $_SESSION ['loginuserid'] != "") { $loginuserinfo = $this->_admin->findByField ( "id", $_SESSION ['loginuserid'] ); $smarty->assign ( 'loginuserinfo', @$loginuserinfo ); $smarty->assign ( 'loginuserid', @$_SESSION ['loginuserid'] ); } else { $loginuserinfo = array (); } $smarty->display ( 'main.tpl' ); } function article($parm = array()){ $smarty = & $this->_getView (); foreach ( $parm as $key => $value ) { $smarty->assign ( $key, $value ); } $smarty->display ( 'article.tpl' ); } /** * 后台管理 * * @param unknown_type $parm * @param unknown_type $admin_flag */ function manage($parm = array(), $admin_flag = "") { $smarty = & $this->_getView (); foreach ( $parm as $key => $value ) { $smarty->assign ( $key, $value ); } if (@$parm ['title'] == "") { $parm ['title'] = DEFAUT_TITLE; } $smarty->register_modifier ( "substr", array ("Class_Common", "m_substr" ) ); $smarty->register_modifier ( "formatdate", array ("Class_Common", "formatdate" ) ); $smarty->register_modifier ( "formatmoney", array ("Class_Common", "formatmoney" ) ); if (isset ( $_SESSION ['loginuserid'] ) && $_SESSION ['loginuserid'] != "") { $loginuserinfo = $this->_user->findByField ( "id", $_SESSION ['loginuserid'] ); } else { $loginuserinfo = array (); } $smarty->assign ( 'loginuserinfo', @$loginuserinfo ); $smarty->assign ( 'loginuserid', @$_SESSION ['loginuserid'] ); $smarty->display ( 'admin/main.tpl' ); } /** * 不带模板的页面显示 * @author libin 2008-09-13 * @param unknown_type $page * @param unknown_type $parm */ function display($page, $parm = array()) { $smarty = & $this->_getView (); foreach ( $parm as $key => $value ) { $smarty->assign ( $key, $value ); } $smarty->register_modifier ( "substr", array ("Com_Common", "m_substr" ) ); $smarty->display ( $page ); } /** * * Enter description here ... * @param unknown_type $date */ function formatdate($date) { $date = str_replace ( "-", "/", $date ); return $date; } /** * * 格式化金额 * @param unknown_type $date */ function formatmoney($date) { $date = number_format ( $date ); return $date; } /** * word cut * @author libin 2008-09-13 * @param unknown_type $word * @param unknown_type $num * @return unknown */ function word_explode($word, $num) { $str = wordwrap ( $word, $num, "|", 1 ); $str = explode ( "|", $str ); $str = $str [0]; return $str; } /** *字截取 * * @param unknown_type $word * @param unknown_type $startw * @param unknown_type $length * @return unknown */ function m_substr($word, $start, $length, $more = "") { $word = htmlspecialchars_decode ( $word ); $word = str_replace ( "&acute;", "'", $word ); $str = mb_substr ( $word, $start, $length, "UTF-8" ); if (strlen ( $word ) > strlen ( $str )) { $str = $str . $more; } return $str; } /** * * 检查用户角色信息 * @param unknown_type $userid * @param unknown_type $role */ function checkUser($userid, $role = "") { $userinfo = $this->_user->findByField ( "id", $userid ); if (! is_array ( $role )) { $role = explode ( ",", $role ); } $flag = false; if (count ( $userinfo ) > 0 && is_array ( $userinfo )) { foreach ( $role as $v ) { if ($v == $userinfo ['role']) { $flag = true; } } } if ($flag) { return true; } else { $url = url ( "Default", "Login" ); redirect ( $url ); } } /** * * 过滤参数 * @return undefine * @author libin * @property created at 2012-10-29 * @property updated at 2012-10-29 * @example */ function filter($value) { if(is_array($value)){ foreach ($value as $k=>$v){ if(is_array($v)){ foreach ($v as $kk=>$vv){ $v[$kk]=htmlspecialchars ( $vv); } $value[$k]=$v; }else{ $value[$k]=htmlspecialchars ( $v); } } }else{ $value = htmlspecialchars ( $value); } return $value; } /** * 由长连接生成短链接操作 * * 算法描述:使用6个字符来表示短链接,我们使用ASCII字符中的'a'-'z','0'-'9','A'-'Z',共计62个字符做为集合。 * 每个字符有62种状态,六个字符就可以表示62^6(56800235584),那么如何得到这六个字符, * 具体描述如下: * 1. 对传入的长URL+设置key值 进行Md5,得到一个32位的字符串(32 字符十六进制数),即16的32次方; * 2. 将这32位分成四份,每一份8个字符,将其视作16进制串与0x3fffffff(30位1)与操作, 即超过30位的忽略处理; * 3. 这30位分成6段, 每5个一组,算出其整数值,然后映射到我们准备的62个字符中, 依次进行获得一个6位的短链接地址。 * * @author flyer0126 * @since 2012/07/13 */ function shortUrl( $long_url ){ $key = 'tongji2014'; $base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 利用md5算法方式生成hash值 $hex = hash('md5', $long_url.$key); $hexLen = strlen($hex); $subHexLen = $hexLen / 8; $output = array(); for( $i = 0; $i < $subHexLen; $i++ ) { // 将这32位分成四份,每一份8个字符,将其视作16进制串与0x3fffffff(30位1)与操作 $subHex = substr($hex, $i*8, 8); $idx = 0x3FFFFFFF & (1 * ('0x' . $subHex)); // 这30位分成6段, 每5个一组,算出其整数值,然后映射到我们准备的62个字符 $out = ''; for( $j = 0; $j < 6; $j++ ) { $val = 0x0000003D & $idx; $out .= $base32[$val]; $idx = $idx >> 5; } $output[$i] = $out; } return $output[0]; } function generateQRfromGoogle($chl,$Height ='150',$widht='150',$EC_level='L',$margin='0'){ $chl = urlencode($chl); return '<img src="http://1192.168.127.12/chart?chs='.$widht.'x'.$Height.'&cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$chl.'" alt="QR code" height="'.$Height.'" widht="'.$widht.'"/>'; } function downloadQRpngfromGoogle($chl,$Height ='150',$widht='150',$EC_level='L',$margin='0'){ $chl = urlencode($chl); return 'http://172.16.31.10/chart?chs='.$widht.'x'.$Height.'&cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$chl; } /** * 时间差计算 *time2Units(time()-strtotime($date)) * @param Timestamp $time 时间差 * @return String Time Elapsed * @author <NAME> * @copyright http://phparch.cn (Professional PHP Architecture) */ function time2Units ($time) { $year = floor($time / 60 / 60 / 24 / 365); $time -= $year * 60 * 60 * 24 * 365; $month = floor($time / 60 / 60 / 24 / 30); $time -= $month * 60 * 60 * 24 * 30; $week = floor($time / 60 / 60 / 24 / 7); $time -= $week * 60 * 60 * 24 * 7; $day = floor($time / 60 / 60 / 24); $time -= $day * 60 * 60 * 24; $hour = floor($time / 60 / 60); $time -= $hour * 60 * 60; $minute = floor($time / 60); $time -= $minute * 60; $second = $time; $elapse = '刚刚'; $unitArr = array('年前' =>'year', '个月前'=>'month', '周前'=>'week', '天前'=>'day', '小时前'=>'hour', '分钟前'=>'minute', '秒前'=>'second' ); foreach ( $unitArr as $cn => $u ) { if ( $year > 0 ) {//大于一年显示年月日 $elapse = date('Y/m/d',time()-$time); break; } else if ( $$u > 0 ) { $elapse = $$u . $cn; break; } } return $elapse; } } ?><file_sep>/resource/js/analysis.js $(function () { $('div[id^=container]').each(function(i){ var title='';//$('#quetitle'+i).val(); var anscount=$('#anscount'+i).val(); var subtitle='答卷人数:'+anscount; if($('#quetype'+i).val()==1){ var option=createOption(i,title,subtitle,anscount,'pie'); }else if($('#quetype'+i).val()==2){ var option=createOption(i,title,subtitle,anscount,'bar'); }else if($('#quetype'+i).val()==3){ var option=createOption(i,title,subtitle,anscount,'bar'); } $(this).highcharts(option); }); }); //构造option i第几个,标题,副标题,图形类型 function createOption(i,title,subtitle,anscount,type){ var option = (type=='pie') ? getPieOption() : getBarOption(); option.title.text=title; option.subtitle.text=subtitle; option.chart.type=type; var optdata=new Array(); $('.options'+i).each(function(opi){ var opttitle=$(this).text().toString(); var optcount=$('.counts'+i).eq(opi).text().toString()*1; if(type=='pie'){ optcount = optcount/anscount*100; optdata[opi]=[opttitle, optcount]; }else if(type=='bar'){ option.xAxis.categories[opi]=opttitle; optdata[opi]=optcount; } }); option.series[0]={ name: '选中人数', data: optdata }; return option; } //饼形图 function getPieOption(){ var option={ chart: { plotBackgroundColor: null, plotBorderWidth: null,//null, plotShadow: false }, colors:['#22b5c3', '#a3be57', '#ff9c9c', '#48cfef', '#25bf6e', '#ea5f35', '#7e85e0', '#f2bd7c', '#bbbbba', '#7257a2'], title: { text: '选项标题', style:{ fontFamily:'Microsoft YaHei' } }, subtitle: { text: '副标题', style:{ fontFamily:'Microsoft YaHei' } }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '{point.name}: {point.percentage:.1f} %', style: { fontFamily:'Microsoft YaHei', fontSize:'8px' } } } }, series: [{}] }; return option; } //条形图 function getBarOption(){ var option={ chart: { type: 'bar' }, title: { text: '选项标题' }, subtitle: { text: '副标题' }, xAxis: { categories: [], title: { text: null } }, yAxis: { min: 0, title: { text: '', style:{fontFamily:'Microsoft YaHei'} } }, tooltip: { style:{ color:'#888888', fontFamily:'Microsoft YaHei' }, formatter: function() { return this.y.toFixed(2)+'%'; } }, plotOptions: { bar: { dataLabels: { enabled: true } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -40, y: 100, floating: true, borderWidth: 1, backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'), shadow: true }, credits: { enabled: false }, series: [{}] }; return option; }<file_sep>/resource/js/list.js $(function(){ $('a.delBtn').click(function(){ if(confirm('确定删除吗?')){ window.location=$(this).attr('href'); } return false; }); $('a.pubBtn').click(function(){ if(confirm('确定发布吗?')){ window.location=$(this).attr('href'); } return false; }); $('a.overBtn').click(function(){ if(confirm('确定结束这个问卷吗?')){ window.location=$(this).attr('href'); } return false; }); $('a.recover').click(function(){ if(confirm('确定恢复这个问卷吗?')){ window.location=$(this).attr('href'); } return false; }); });<file_sep>/App/Model/Questionnaire.php <?php FLEA::loadClass('FLEA_Db_TableDataGateway'); class Model_Questionnaire extends FLEA_Db_TableDataGateway { var $tableName = 'questionnaire'; var $primaryKey = 'id'; } ?><file_sep>/App/Model/QsAbstract.php <?php FLEA::loadClass('FLEA_Db_TableDataGateway'); class Model_QsAbstract extends FLEA_Db_TableDataGateway { var $tableName = 'qs_abstract'; var $primaryKey = 'id'; } ?><file_sep>/App/Model/QsAnswer.php <?php FLEA::loadClass('FLEA_Db_TableDataGateway'); class Model_QsAnswer extends FLEA_Db_TableDataGateway { var $tableName = 'qs_answer'; var $primaryKey = 'id'; function getMaxNumGoupByQid($qnnaid){ $ans=$this->find(array('qs_id'=>$qnnaid),'id desc'); return !isset($ans['id'])?1:($ans['num']*1+1); } } ?><file_sep>/App/Controller/As.php <?php class Controller_As extends FLEA_Controller_Action { /** * * Enter description here ... * @var Class_Common */ var $_common; var $_admin; var $_adminid; var $_qs; var $_qe; var $_op; var $_qs_answer; var $_qs_answer_detail; var $_qs_abstract; var $_qepath; var $_qecon; function __construct() { $this->_common = get_singleton ( "Class_Common" ); $this->_admin = get_singleton ( "Model_Admin" ); $this->_qs = get_singleton ( "Model_Qs" ); $this->_qe = get_singleton ( "Model_Qe" ); $this->_op = get_singleton ( "Model_Op" ); $this->_qs_answer = get_singleton ( "Model_QsAnswer" ); $this->_qs_answer_detail = get_singleton ( "Model_QsAnswerDetail" ); $this->_qs_abstract = get_singleton ( "Model_QsAbstract" ); $this->_qepath=get_singleton ( "Model_QePath" ); $this->_qecon=get_singleton ( "Model_QeCon" ); } //短链接跳转 function actionQrcode() { $short = isset ( $_GET ['short'] ) ? $this->_common->filter($_GET ['short']) : ''; $questionnaire=$this->_qs->find(array('short'=>$short),'id desc'); if(@$questionnaire['status']=='1'){ $url=url('As','Index',array('qid'=>$questionnaire['id'])); redirect($url); return ; } if($questionnaire['status']=='0'){ echo '<h1>调查问卷还没发布</h1>'; }elseif($questionnaire['status']=='2'){ echo '<h1>调查问卷已经结束</h1>'; }else{ echo '<h1>找不到相关问卷,请联系管理员</h1>'; } } //回答问卷 function actionIndex(){ $qsid = isset ( $_GET ['qid'] ) ? $this->_common->filter($_GET ['qid']) : ''; $questionnaire=$this->_qs->findByField('id',$qsid); $abstract=$this->_qs_abstract->findAll(array('qs_id'=>$qsid),'id asc'); $qepath=$this->_qepath->findAll(array('qs_id'=>$qsid,'step'=>0));//第一组随机问题 $tmparr=array(); foreach ($qepath as $qk=>$p){ $tmparr[$qk]=$p['probability']; } $pk=$this->get_rand($tmparr); $question=$this->_qe->findByField('id',$qepath[$pk]['qe_id']); $question['option']=$this->_op->findAll(array('qe_id'=>$question['id']),'id asc'); //获取答题路径及条件,供js判断 $path=$this->_qepath->findAll(array('qs_id'=>$qsid,' step > 0 and qe_id <> '.$question['id']),'step asc,id asc'); $qesall=$qes=$qe=array(); $step=''; foreach ($path as $p){ if($step!=$p['step']&&($p['flag_over']==2||$p['step']==$questionnaire['step_num']) ){//默认随机问题排除触发结束 if(count($qe)>0){$qes[]=$qe;} $qe=array(); } $ques=$this->_qe->findByField('id',$p['qe_id']); $ques['option']=$this->_op->findAll(array('qe_id'=>$ques['id']),"id"); $p['question']=$ques; $qe[]=$p;//结构化路径 $step=$p['step']; $qesall[]=$p;//所有问题 } if(count($qe)>0){$qes[]=$qe;}//结构化路径 $qecon=$this->_qecon->findAll(array('qs_id'=>$qsid)); $qes=$this->restructure($qes);//重构内容按概率出题 //print_r($qes);//exit(); $signinfo=$this->_admin->findByField('adm_name','admin'); $this->_common->display('as/answer.tpl',array ('questionnaire'=>$questionnaire,'abstract'=>$abstract,'question'=>$question,'qesall'=>$qesall,'qes'=>$qes,'qecon'=>$qecon,'signinfo'=>$signinfo) ); } //问题结果重构 function restructure($list){ $newlist=array(); foreach ($list as $k => $d){ $arr=array(); foreach ($d as $qk=>$q){ $arr[$qk]=$q['probability']; } $tk=$this->get_rand($arr); $repeatFlag=0; foreach ($newlist as $n){ if($n['qe_id']==$d[$tk]['qe_id']){ $repeatFlag=1; } } $newlist[$k]=$d[$tk]; } if($repeatFlag){ return $this->restructure($list); }else{ return $newlist; } } //根据概率获取结果 function get_rand($proArr) { $result = ''; //概率数组的总概率精度 $proSum = array_sum($proArr); //概率数组循环 foreach ($proArr as $key => $proCur) { $randNum = mt_rand(1, $proSum); if ($randNum <= $proCur) { $result = $key; break; } else { $proSum -= $proCur; } } unset ($proArr); return $result; } //提交问卷 function actionSubmit(){ $data = $this->_common->filter($_POST); $act = isset ( $data ['act'] ) ? $data ['act'] : ''; $qnnaid = isset ( $data ['questionnaire_unit'] ) ? $data ['questionnaire_unit'] : ''; if($act=='submit'&&!empty($qnnaid)){ $questionnaire=$this->_qs->findByField('id',$qnnaid); if($questionnaire['status']=='0'){ $ref=$_SERVER['HTTP_REFERER']; echo '<h1>调查问卷还没发布,您不能答题<br><a href="'.$ref.'" >返回</a><'; return ; } if($questionnaire['status']=='2'){ $ref=$_SERVER['HTTP_REFERER']; echo '<h1>调查问卷已结束,您不能答题<br><a href="'.$ref.'" >返回</a>'; return ; } $passtime=''; $time=$data['time']; //$d = intval($time/86400); $h = round(($time%86400)/3600); $m = round(($time%3600)/60); $s = round(($time%60)); $passtime.=$h>0?$h.'时':''; $passtime.=$m>0?$m.'分':''; $passtime.=$s.'秒'; //回答信息 $answer=array('qs_id'=>$qnnaid,'pass_time'=>$passtime,'num'=>$this->_qs_answer->getMaxNumGoupByQid($qnnaid),'ip'=>$_SERVER['REMOTE_ADDR']); $ansid=$this->_qs_answer->create($answer); $quesnum=$data['quesnum']; for($i=0;$i<$quesnum;$i++){ $asoption=$data['check'.$i]; if(is_array($asoption)){//多选 foreach ($asoption as $aopt){ $asdetial=array('qs_answer_id'=>$ansid,'qs_id'=>$qnnaid,'qe_id'=>$data['questionid'.$i],'op_id'=>$aopt,'qs_answer_content'=>$data['anscontent'.$aopt]); $this->_qs_answer_detail->create($asdetial); } }else{ $asdetial=array('qs_answer_id'=>$ansid,'qs_id'=>$qnnaid,'qe_id'=>$data['questionid'.$i],'op_id'=>$asoption,'qs_answer_content'=>$data['anscontent'.$asoption]); $this->_qs_answer_detail->create($asdetial); } $this->_qe->addTimes($data['questionid'.$i]);//添加答题次数 } $url=url('As','Complete'); redirect($url); } } //完成问卷 function actionComplete(){ $signinfo=$this->_admin->findByField('adm_name','admin'); $this->_common->display('as/complete.tpl',array('msg'=>'感谢您的提交!','signinfo'=>$signinfo)); } function actionPreview(){ $config = FLEA::getAppInf ( 'dbDSN' ); $prefix = $config ['prefix']; $aid = isset ( $_GET ['qid'] ) ? $this->_common->filter($_GET['qid']) : ''; $answer=$this->_qs_answer->findByField('id',$aid); if(empty($answer['id'])){ echo '答题内容不存在,可能已被删除'; return; } $questionnaire=$this->_qs->findByField('id',$answer['qs_id']); $abstract=$this->_qs_abstract->findAll(array('qs_id'=>$aid)); $detailsql="select qe.* from ".$prefix."qe qe left join ".$prefix."qs_answer_detail ad on qe.id=ad.qe_id where ad.qs_answer_id=".$aid." group by qe.id"; $question=$this->_qe->findBySql($detailsql); foreach ($question as $k=>$q){ //查找答题选项 $sql="select opt.content,ad.qs_answer_content as answer_content from ".$prefix."qs_answer_detail ad left join ".$prefix."op opt on ad.op_id=opt.id where ad.qs_answer_id=$aid and ad.qe_id=".$q['id']; $o=$this->_qs_answer_detail->findBySql($sql); $contentstr=array(); $answerstr=array(); foreach ($o as $oo){ $contentstr[]=$oo['content']; $answerstr[]=$oo['answer_content']; } $contentstr=implode(',', $contentstr); $answerstr=implode(',', $answerstr); $answer_content=''; if($q['type']=='1'||$q['type']=='2'){ $answer_content=$contentstr; }else{ $contentstr=explode("@text", $contentstr); $answerstr=explode(",", $answerstr); foreach ($contentstr as $ck=>$c){ $answer_content.=$c.$answerstr[$ck]; } } $question[$k]['answer']=$answer_content; } $this->_common->display('as/preview.tpl',array('answer'=>$answer,'questionnaire'=>$questionnaire,'question'=>$question,'abstract'=>$abstract)); } function actionAnalysis(){ $config = FLEA::getAppInf ( 'dbDSN' ); $prefix = $config ['prefix']; $qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid']) : ''; $questionnaire=$this->_qs->findByField('id',$qnnaid); $question=$this->_qe->findBySql("select qe.*,path.qs_id from ".$prefix."qe qe left join ".$prefix."qepath path on path.qe_id = qe.id where path.qs_id=$qnnaid"); foreach ($question as $k=>$q){ $options=$this->_op->findAll(array('qe_id'=>$q['id'])); foreach ($options as $opk=>$op){ $options[$opk]['count']=$this->_qs_answer_detail->findCount(array('qs_id'=>$qnnaid,'qe_id'=>$q['id'],'op_id'=>$op['id'])); } $question[$k]['option']=$options; } $questionnaire['anscount']=$this->_qs_answer->findCount(array('qs_id'=>$qnnaid)); //查看答卷详情 $pageparm = array ('qnnaid'=>$qnnaid);//9删除 $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 50; $title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : ''; $conditions=array('qs_id'=>$qnnaid); if(!empty($title)){ $conditions[]="title like '%$title%'"; $pageparm['title']=$title; } $total=$this->_qs_answer->findCount($conditions); $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "As", "Analysis"); $pages->_parm = $pageparm; $page = $pages->analysisPage (); $start = ($page_no - 1) * $page_size; $answerlist=$this->_qs_answer->findAll($conditions,"id desc limit $start,$page_size"); foreach ($answerlist as $k=>$v){ $anses=array(); foreach ($question as $qk=>$q){ $sql="select op.content,ad.qs_answer_content as answer_content from ".$prefix."qs_answer_detail ad left join ".$prefix."op op on op.id=ad.op_id where ad.qe_id=".$q['id']." and ad.qs_answer_id=".$v['id']; $o=$this->_qs_answer_detail->findBySql($sql); $content=array(); $answer=array(); foreach ($o as $oo){ $content[]=$oo['content']; $answer[]=$oo['answer_content']; } $content=implode(',', $content); $answer=implode(',', $answer); $answer_content=''; if($q['type']=='1'||$q['type']=='2'){ $answer_content=$content; }else{ $content=explode("@text", $content); $answer=explode(",", $answer); foreach ($content as $ck=>$c){ $c.=@$answer[$ck]; $answer_content.=$c; } } $anses[]=array('content'=>$answer_content,'qetype'=>$q['type']); } $answerlist[$k]['answer']=$anses; } $this->_common->display('as/analysis.tpl', array ('questionnaire'=>$questionnaire,'question'=>$question,'answerlist'=>$answerlist,'page'=>$page,'pageparm'=>$pageparm) ); } } <file_sep>/result.php <?php require_once 'const.php'; header("Location:".SITEHOST.'/index.php?controller=Answer&action=Analysis&qnnaid='.$_GET['qnnaid']);<file_sep>/resource/js/qsadd.js $(function(){ //添加图文摘要 $('#addAbstract').click(function(){ var num=$('#abstractnum').val(); ++num; $('#addAbsTr').before('<tr><td style="text-align:center;"><input name="abstract'+num+'[title]" type="text" value="摘要'+num+'" style="width:50px;" /></td><td><textarea name="abstract'+num+'[content]" style="width:700px;height:150px;"></textarea></td></tr>'+ '<tr><td style="text-align:center;">图片'+num+'</td><td><input name="abstractimg'+num+'" type="file" style="width:700px;"></td></tr>'+ '<tr><td style="text-align:center;">图片信息'+num+'</td><td><textarea name="abstract'+num+'[imginfo]" value="" style="width:700px;height:50px;"></textarea></td></tr>'); $('#abstractnum').val(num); }); //选中路径 $('.tk_lm').live('click',function(){ //当前第几步路径 $('.selectedstep').val($('.tk_lm').index($(this))); $('.tk_lm').removeClass('tk_lmon'); $(this).addClass('tk_lmon'); }); //添加问题到路径中 $('.tk_rm1 li').click(function(){ var step=$('.selectedstep').val(); var no=$(this).find('.no').val(); var qeid=$(this).find('.qeid').val(); var qetitle=$(this).find('.qetitle').val(); //添加路径隐藏属性 $('.tk_lmon ul').append($(this).clone().addClass('tooltip').attr('title',qetitle).html('<span>R</span><p>'+no+'</p><input type="hidden" name="step[]" class="step" value="'+step+'" /><input type="hidden" name="qeid[]" class="qeid" value="'+qeid+'" /><input type="hidden" name="probability[]" class="probability" value="1" /><input type="hidden" value="2" class="hascon" name="hascon[]" /><input type="hidden" value="1" class="aslimit" name="aslimit[]" /><input type="hidden" value="2" class="flag_over" name="flag_over[]" /><input type="hidden" class="qetitle" value="'+qetitle+'" />')); $('.tooltip').tooltipster(); }); //移除问题 $('#removeQe').click(function(){ if(confirm('是否移除?')){ $('.tk_lm ul li.selected').remove(); $('.tck_box').hide(); } }); //查看详细 $('.tk_lm ul li').live('click',function(){ $('.tk_lm ul li').removeClass('selected'); $(this).addClass('selected'); var url=$('#getOpsByQeUrl').val(); var qeid=$(this).find('.qeid').val(); var step=$(this).find('.step').val(); var probability=$(this).find('.probability').val(); var aslimit=$(this).find('.aslimit').val(); var flag_over=$(this).find('.flag_over').val(); var beftk=step; var beftklmqe=$('.tk_lm:lt('+beftk+')').find('li'); $.ajax({ type:'post', url:url, data:{'qeid':qeid}, dataType:'json', success:function(res){ //问题详情 $('#tc_qeTitle').text('').html('<font color="red">'+res.no+'</font>&nbsp;'+res.title); $('#tc_ulops').html(''); for(i in res.op){ $('#tc_ulops').append('<li>'+res.op[i].content+'</li>'); } $('.qeBeforeCon').html(''); $('.qeProbability').val(probability); $('.qeAslimit').val(aslimit); if(flag_over==1){ $('.qeFlagOver').eq(0).removeAttr('checked'); $('.qeFlagOver').eq(1).attr('checked','checked'); }else{ $('.qeFlagOver').eq(0).attr('checked','checked'); $('.qeFlagOver').eq(1).removeAttr('checked'); } //前置条件 if(step==0){ $('.qeBeforeCon').text('无'); $('#addCondition').attr('disabled','disabled'); }else{ $('#addCondition').removeAttr('disabled'); var strda=''; $('.tk_lmon li.selected input[name^=consprevqe]').each(function(i){ strda+='qe[]='+$(this).val()+'&op[]='+$('.tk_lmon li.selected input[name^=consprevop]').eq(i).val()+'&'; }); if(strda!=''){//原先有条件的情况 var getconurl=$('#getBeforeConUrl').val(); //填充条件 $.ajax({ type:'post', url:getconurl, data:strda, dataType:'json', success:function(res){ var str=''; for(i in res){ str+='<select class="questionCondition">'; str+='<option value="">请选择</option>'; beftklmqe.each(function(tkli){ var sected=(res[i].qeid==$(this).find('.qeid').val())?'selected':''; str+='<option '+sected+' value="'+$(this).find('.qeid').val()+'">'+$(this).find('p').text()+'('+$(this).find('.qetitle').val()+')</option>' }) var opstr=''; var inputattr='type="checkbox" '; if(res[i].qetype=='2'){ inputattr='type="checkbox" '; } for(opk in res[i].ops){ sected=''; for(s in res[i].opids){ if(res[i].opids[s]==res[i].ops[opk].id){ sected='checked'; } } opstr+='<li><label><input class="selectop" '+sected+' '+inputattr+' name="radiocon'+i+'" value="'+res[i].ops[opk].id+'">'+res[i].ops[opk].content+'</label></li>'; } str+='</select><br><div class="dxt"><ul class="optionCondition">'+opstr+'</ul></div><br>'+'<div class="cls"></div>'; } $('.qeBeforeCon').html(str); } }); }else{//默认无值的情况 var str='<select class="questionCondition">'; str+='<option value="">请选择</option>'; beftklmqe.each(function(tkli){ str+='<option value="'+$(this).find('.qeid').val()+'">'+$(this).find('p').text()+'('+$(this).find('.qetitle').val()+')</option>' }) str+='</select><br><div class="dxt"><ul class="optionCondition"></ul></div><br>'; $('.qeBeforeCon').html(str+'<div class="cls"></div>'); } } $('.tck_box').show(); } }) }); //条件 $('.questionCondition').live('change',function(){ var url=$('#getOpsByQeUrl').val(); var index=$('.questionCondition').index($(this)); var options=$('.optionCondition').eq(index); var qeid=$(this).val(); $.ajax({ type:'post', url:url, data:{'qeid':qeid}, dataType:'json', success:function(res){ options.html(''); var inputattr='type="checkbox" name="radiocon'+index+'"'; if(res.type=='2'){ inputattr='type="checkbox" name="radiocon'+index+'"'; } for(i in res.op){ options.append('<li><label><input class="selectop" '+inputattr+' value="'+res.op[i].id+'">'+res.op[i].content+'</label></li>'); } } }) }); //添加条件 $('#addCondition').click(function(){ var ops=$('.questionCondition').last().clone().html();//前一个问题选项 var str='<select class="questionCondition">'; str+=ops; str+='</select><br><div class="dxt"><ul class="optionCondition"></ul></div><br>'; $('.qeBeforeCon').append(str+'<div class="cls"></div>'); }); //确认条件 $('#subCondition').click(function(){ //问题出现概率 $('.tk_lmon li.selected input.probability').val($('.qeProbability').val()); $('.tk_lmon li.selected input.aslimit').val($('.qeAslimit').val()); $('.tk_lmon li.selected input.flag_over').val($('.qeFlagOver:checked').val()); $('.tk_lmon li.selected input[name^=consprevqe]').remove(); $('.tk_lmon li.selected input[name^=consprevop]').remove(); $('.tk_lmon li.selected input[name^=consqeid]').remove(); $('.tk_lmon li.selected input[name^=constep]').remove(); $('.questionCondition').each(function(i){ var qeid=$(this).val(); $('.optionCondition').eq(i).find('input:checked').each(function(oi){ $('.tk_lmon li.selected').append('<input type="hidden" name="consprevqe[]" value="'+qeid+'" /><input type="hidden" name="consprevop[]" value="'+$(this).val()+'" /><input type="hidden" name="consqeid[]" value="'+$('.tk_lmon li.selected input.qeid').val()+'" /><input type="hidden" name="constep[]" value="'+$('.tk_lmon li.selected input.step').val()+'" />'); }); }); if($('.optionCondition li').length>0){//有前置条件 $('.tk_lmon li.selected input.hascon').val(1); $('.tk_lmon li.selected span').text('C'); }else{//无前置条件 $('.tk_lmon li.selected input.hascon').val(2); $('.tk_lmon li.selected span').text('R'); } $('.tck_box').hide(); }); //鼠标滚动 $(window).scroll(function(){ // if($(window).scrollTop() > $('.tk_l').offset().top){ // $('.tk_l').css('margin-top',($(window).scrollTop()-$('.tk_l').offset().top)+'px'); // } }); //弹出框 $('body').append($('.tck_box')); $('#tck_close').click(function(){ $('.tck_box').hide(); $('.tk_lm ul li').removeClass('selected'); }); //鼠标hover效果 // $('li[class^=icon]').hover(function(){ // //alert($(this).find('.qetitle').val()) // },function(){ // // }); $('.tooltip').tooltipster(); //添加路径框 $('#addpath').click(function(){ $(this).prev().removeClass('wx'); $(this).before('<div class="tk_lm wx"><ul></ul><div class="cls"></div></div>'); }); //查找题库 $('.searchCategory').change(function(){ var cid=$(this).val(); if(cid==''){ $(this).parent().next().find('li').show(); return; } $(this).parent().next().find('li').each(function(){ if($(this).find('.qecate').val()==cid){ $(this).show(); }else{ $(this).hide(); } }); }); $('.searchQeBtn').click(function(){ var key=$(this).prev().val(); if(key==''){ $(this).parent().next().find('li').show(); return; } $(this).parent().next().find('li').each(function(){ var str=$(this).find('.qetitle').val(); if(str.indexOf(key)!=-1){ $(this).show(); }else{ $(this).hide(); } }); }); $('.searchAll').click(function(){ $(this).parent().next().find('li').show(); //$(this).parent().find('.searchTitle').val(''); }); }); function checkFrom(){ var flag=true; var title=$('#qs_title').val(); var status=$('#questionnaire_status').val(); var msg=''; if($.trim(title)==''){ msg+='请填写问卷标题\n'; flag=false; } if($.trim(status)=='1'){ msg+='问卷已发布不可编辑\n'; flag=false; } if($.trim(status)=='2'){ msg+='问卷已结束不可编辑\n'; flag=false; } if(!flag){ alert(msg); } return flag; }<file_sep>/App/Controller/Questionnaire.php <?php require_once SERVERROOT. DS . 'App' . DS . 'Class' .DS.'phpqrcode.php'; require_once SERVERROOT. DS . 'weixin' . DS . 'wechat.php'; class Controller_Questionnaire extends FLEA_Controller_Action { /** * * Enter description here ... * @var Class_Common */ var $_common; var $_admin; var $_adminid; var $_questionnaire; var $_question; var $_option; var $_answer; var $_abstract; function __construct() { $this->_common = get_singleton ( "Class_Common" ); $this->_admin = get_singleton ( "Model_Admin" ); $this->_questionnaire = get_singleton ( "Model_Questionnaire" ); $this->_question = get_singleton ( "Model_Question" ); $this->_option = get_singleton ( "Model_Option" ); $this->_answer = get_singleton ( "Model_Answer" ); $this->_abstract = get_singleton ( "Model_Abstract" ); $this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : ""; if(empty($_SESSION ['loginuserid'])){ $url=url("Default","Login"); redirect($url); } } //问卷列表 function actionIndex() { $pageparm = array ('status != 9 and status != 2');//9删除 $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 20; $title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : ''; $conditions=array('status != 9 and status != 2'); if(!empty($title)){ $conditions[]="title like '%$title%'"; $pageparm['title']=$title; } $total=$this->_questionnaire->findCount($conditions); $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "Questionnaire", "Index" ); $pages->_parm = $pageparm; $page = $pages->page (); $start = ($page_no - 1) * $page_size; $list=$this->_questionnaire->findAll($conditions,"id desc limit $start,$page_size"); foreach ($list as $k=>$d){ $list[$k]['num']=$this->_answer->findCount(array('questionnaire_id'=>$d['id'])); $list[$k]['updated']=$this->_common->time2Units(time()-strtotime($d['updated'])); } $this->_common->show ( array ('main' => 'questionnaire/list.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) ); } //完成的问卷列表 function actionFinshed(){ $pageparm = array ('status = 2');//9删除 $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 20; $title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : ''; $conditions=array('status = 2'); if(!empty($title)){ $conditions[]="title like '%$title%'"; $pageparm['title']=$title; } $total=$this->_questionnaire->findCount($conditions); $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "Questionnaire", "Finshed" ); $pages->_parm = $pageparm; $page = $pages->page (); $start = ($page_no - 1) * $page_size; $list=$this->_questionnaire->findAll($conditions,"id desc limit $start,$page_size"); foreach ($list as $k=>$d){ $list[$k]['num']=$this->_answer->findCount(array('questionnaire_id'=>$d['id'])); } $this->_common->show ( array ('main' => 'questionnaire/list.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) ); } //问卷新增 function actionAdd(){ $act=isset ( $_POST ['act'] ) ? $_POST ['act'] : ''; if($act=='add'){ $data=$this->_common->filter($_POST['data']); $data['author']=htmlspecialchars_decode($data['author']); //问卷设置 $data['over_num']=intval($data['over_num']); if(empty($data['over_num'])){ unset($data['over_num']); } if(empty($data['over_date'])){ unset($data['over_date']); } //短连接及二维码 $shoturl=url('Answer','Index',array('time'=>time())); $shoturl=$this->_common->shortUrl($shoturl); $data['short']=$shoturl; $data['qrcode']=$this->createQr($shoturl); $data['created']=date("Y-m-d H:i:s"); //创建问卷 $questionnaire_id=$this->_questionnaire->create($data); //创建摘要 $Upload= & get_singleton ( "Service_UpLoad" ); $folder="resource/upload/abstract/"; if (! file_exists ( $folder )) { mkdir ( $folder, 0777 ); } $Upload->setDir($folder.date("Ymd")."/"); $absnum=$_POST['abstractnum']; for ($i=0;$i<$absnum;$i++){ $abstract=array(); $numi=($i+1); $Upload->setPrefixName($i); $img=$Upload->upload('abstractimg'.$numi); if($img['status']==1){ $file_path=$img['file_path']; } $abstract['questionnaire_id']=$questionnaire_id; $abstract['title']=$_POST['abstract'.$numi]['title']; $abstract['content']=$_POST['abstract'.$numi]['content']; $abstract['imginfo']=$_POST['abstract'.$numi]['imginfo']; $abstract['img']=$file_path; $this->_abstract->create($abstract); } //创建答题选项 $questionnum=$this->_common->filter($_POST['questionnum']); for($i=0;$i<$questionnum;$i++){ //创建问题 if(isset($_POST['question'.$i])){ $question=$this->_common->filter($_POST['question'.$i]); $question['questionnaire_id']=$questionnaire_id; $question['num']=($i+1); $question_id=$this->_question->create($question); foreach($question['content'] as $c){ //创建选项 if(!empty($c)){ $option=array('content'=>$c,'questionnaire_id'=>$questionnaire_id,'question_id'=>$question_id); $this->_option->create($option); } } } } $url=url('Questionnaire','Index'); redirect($url); } $this->_common->show ( array ('main' => 'questionnaire/add.tpl') ); } //问卷编辑 function actionEdit(){ $qnnaid=isset ( $_GET ['qnnaid'] ) ? $_GET ['qnnaid'] : ''; $act=isset ( $_POST ['act'] ) ? $_POST ['act'] : ''; $msg=''; if($act=='edit'){ $data=$this->_common->filter($_POST['data']); $data['author']=htmlspecialchars_decode($data['author']); //问卷设置 $data['over_num']=intval($data['over_num']); if(empty($data['over_num'])){ unset($data['over_num']); } if(empty($data['over_date'])){ unset($data['over_date']); } //清除旧二维码 if(file_exists ( $data['qrcode'] )){ unlink($data['qrcode']); } //短连接及二维码 $shoturl=url('Answer','Index',array('time'=>time())); $shoturl=$this->_common->shortUrl($shoturl); $data['short']=$shoturl; $data['qrcode']=$this->createQr($shoturl); //创建问卷 $questionnaire_id=$data['id']; $this->_questionnaire->update($data); //清除摘要和选项 $this->_abstract->removeByConditions(array('questionnaire_id'=>$questionnaire_id)); $this->_question->removeByConditions(array('questionnaire_id'=>$questionnaire_id)); $this->_option->removeByConditions(array('questionnaire_id'=>$questionnaire_id)); //创建摘要 $Upload= & get_singleton ( "Service_UpLoad" ); $folder="resource/upload/abstract/"; if (! file_exists ( $folder )) { mkdir ( $folder, 0777 ); } $Upload->setDir($folder.date("Ymd")."/"); $absnum=$_POST['abstractnum']; for ($i=0;$i<$absnum;$i++){ $abstract=array(); $numi=($i+1); $Upload->setPrefixName($i); $img=$Upload->upload('abstractimg'.$numi); $oldimg=$_POST['abstract'.$numi]['img']; if($img['status']==1){//如果有上传图片则更新 $file_path=$img['file_path']; if(file_exists($oldimg)){ unlink($oldimg); } }else{ $file_path=$oldimg; } $abstract['questionnaire_id']=$questionnaire_id; $abstract['title']=$_POST['abstract'.$numi]['title']; $abstract['content']=$_POST['abstract'.$numi]['content']; $abstract['imginfo']=$_POST['abstract'.$numi]['imginfo']; $abstract['img']=$file_path; $this->_abstract->create($abstract); } //创建答题选项 $questionnum=$this->_common->filter($_POST['questionnum']); for($i=0;$i<$questionnum;$i++){ //创建问题 if(isset($_POST['question'.$i])){ $question=$this->_common->filter($_POST['question'.$i]); $question['questionnaire_id']=$questionnaire_id; $question['num']=($i+1); $question_id=$this->_question->create($question); foreach($question['content'] as $c){ //创建选项 if(!empty($c)){ $option=array('content'=>$c,'questionnaire_id'=>$questionnaire_id,'question_id'=>$question_id); $this->_option->create($option); } } } } $msg='问卷更新成功!'; } $questionnaire=$this->_questionnaire->findByField('id',$qnnaid); $abstract=$this->_abstract->findAll(array('questionnaire_id'=>$qnnaid),'id asc'); $question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num,id desc'); foreach ($question as $k=>$q){ $question[$k]['option']=$this->_option->findAll(array('question_id'=>$q['id']),'id asc'); } $this->_common->show ( array ('main' => 'questionnaire/edit.tpl','questionnaire'=>$questionnaire,'abstract'=>$abstract,'question'=>$question,'msg'=>$msg) ); } //被删除的问卷列表 function actionDeList() { $pageparm = array ('status = 9');//9删除 $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 20; $title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : ''; $conditions=array('status = 9'); if(!empty($title)){ $conditions[]="title like '%$title%'"; $pageparm['title']=$title; } $total=$this->_questionnaire->findCount($conditions); $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "Questionnaire", "DeList" ); $pages->_parm = $pageparm; $page = $pages->page (); $start = ($page_no - 1) * $page_size; $list=$this->_questionnaire->findAll($conditions,"id desc limit $start,$page_size"); foreach ($list as $k=>$d){ $list[$k]['num']=$this->_answer->findCount(array('questionnaire_id'=>$d['id'])); $list[$k]['updated']=$this->_common->time2Units(time()-strtotime($d['updated'])); } $this->_common->show ( array ('main' => 'questionnaire/delist.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) ); } //再次发布 function actionRePublic(){ $qnnaid=isset ( $_GET ['qnnaid'] ) ? $_GET ['qnnaid'] : ''; $questionnaire=$this->_questionnaire->findByField('id',$qnnaid); if(is_array($questionnaire)){ $abstract=$this->_abstract->findAll(array('questionnaire_id'=>$qnnaid),'id asc'); $question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num,id desc'); unset($questionnaire['id']); //短连接及二维码 $shoturl=url('Answer','Index',array('time'=>time())); $shoturl=$this->_common->shortUrl($shoturl); $questionnaire['short']=$shoturl; $questionnaire['qrcode']=$this->createQr($shoturl); $questionnaire['status']=0; $questionnaire['created']=date("Y-m-d H:i:s"); $newqnnaid=$this->_questionnaire->create($questionnaire); foreach ($abstract as $ab){ unset($ab['id']); $ab['questionnaire_id']=$newqnnaid; $this->_abstract->create($ab); } foreach ($question as $q){ $options=$this->_option->findAll(array('question_id'=>$q['id']),'id asc'); unset($q['id']); $q['questionnaire_id']=$newqnnaid; $newqid=$this->_question->create($q); foreach ($options as $op){ unset($op['id']); $op['question_id']=$newqid; $op['questionnaire_id']=$newqnnaid; $this->_option->create($op); } } } $url=url('Questionnaire','Index'); redirect($url); } function actionDel(){//删除status9 $id=$this->_common->filter($_GET['id']); $eve=array('id'=>$id,'status'=>9); $this->_questionnaire->update($eve); redirect($_SERVER['HTTP_REFERER']); } function actionPublic(){ //发布status1 $id=$this->_common->filter($_GET['id']); $eve=array('id'=>$id,'status'=>1); $this->_questionnaire->update($eve); redirect($_SERVER['HTTP_REFERER']); } function actionEnd(){//结束status2 $id=$this->_common->filter($_GET['id']); $eve=array('id'=>$id,'status'=>2); $this->_questionnaire->update($eve); $msg=SITEHOST.'/result.php?qnnaid='.$id; $wechatObj = WeChat::getInstance(); $wechatObj->sendCustomMsg('分析结果是 '.$msg,"o9ZPks_8ZpcQXBndQqjuUpt-E9tg"); redirect($_SERVER['HTTP_REFERER']); } function actionRecover(){//恢复被删除的问卷 $id=$this->_common->filter($_GET['id']); $eve=array('id'=>$id,'status'=>0); $this->_questionnaire->update($eve); redirect($_SERVER['HTTP_REFERER']); } function createQr($shoturl){ $qrfile='resource/upload/'.$shoturl.'.png'; $qrurl=SITEHOST.url('Answer','Qrcode',array('short'=>$shoturl)); QRcode::png($qrurl,$qrfile,0,7,1);//生成二维码 //file_put_contents($qrfile , file_get_contents($this->_common->downloadQRpngfromGoogle($qrurl,300,300)));//生成本地图片 return $qrfile; } } <file_sep>/resource/js/add.js $(function(){ //添加图文摘要 $('#addAbstract').click(function(){ var num=$('#abstractnum').val(); ++num; $('#addAbsTr').before('<tr><td style="text-align:center;"><input name="abstract'+num+'[title]" type="text" value="摘要'+num+'" style="width:50px;padding:0;" /></td><td><textarea name="abstract'+num+'[content]" style="width:700px;height:150px;"></textarea></td></tr>'+ '<tr><td style="text-align:center;">图片'+num+'</td><td><input name="abstractimg'+num+'" type="file" style="width:700px;"></td></tr>'+ '<tr><td style="text-align:center;">图片信息'+num+'</td><td><textarea name="abstract'+num+'[imginfo]" value="" style="width:700px;height:50px;"></textarea></td></tr>'); $('#abstractnum').val(num); }); //添加选项 $('#addSingle').click(function(){ var num=$('#questionnum').val(); $('#addtr').before('<tr class="qtr"><td class="qn" style="text-align:center;"></td><td>'+ '<input type="text" name="question'+num+'[title]" value="" style="width:300px;" /><a style="float:right;" href="#" class="delQuestion">删除</a></td></tr>'+ '<tr class="atr"><td style="text-align:center;">单选题<input type="hidden" name="question'+num+'[type]" value="1" /><br>'+ '<input type="button" class="mvDown" value="下移" /><input type="button" class="mvUp" value="上移" /></td>'+ '<td><input type="radio" name="question'+num+'">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+ '<br/><input type="radio" name="question'+num+'">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+ '<a href="#" class="addOption">添加选项+</a></td></tr>'); $('#questionnum').val((num*1+1)); resetQ(); }); $('#addMultiple').click(function(){ var num=$('#questionnum').val(); $('#addtr').before('<tr class="qtr"><td class="qn" style="text-align:center;"></td><td>'+ '<input type="text" name="question'+num+'[title]" value="" style="width:300px;" /><a style="float:right;" href="#" class="delQuestion">删除</a></td></tr>'+ '<tr class="atr"><td style="text-align:center;">多选题<input type="hidden" name="question'+num+'[type]" value="2" /><br>'+ '<input type="button" class="mvDown" value="下移" /><input type="button" class="mvUp" value="上移" /></td>'+ '<td><input type="checkbox">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+ '<br/><input type="checkbox">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+ '<a href="#" class="addOption">添加选项+</a></td></tr>'); $('#questionnum').val((num*1+1)); resetQ(); }); $('#addOpenness').click(function(){ var num=$('#questionnum').val(); $('#addtr').before('<tr class="qtr"><td class="qn" style="text-align:center;"></td><td>'+ '<input type="text" name="question'+num+'[title]" value="" style="width:300px;" /><a style="float:right;" href="#" class="delQuestion">删除</a></td></tr>'+ '<tr class="atr"><td style="text-align:center;">开放性问题<input type="hidden" name="question'+num+'[type]" value="3" /><br>'+ '<input type="button" class="mvDown" value="下移" /><input type="button" class="mvUp" value="上移" /></td>'+ '<td>(需要答题者填写文字的部分请用特殊符号"@text"代替,如:我认为@text)<br/>'+ '<input type="radio" name="question'+num+'">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+ '<br/><input type="radio" name="question'+num+'">&nbsp;<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" />'+ '<a href="#" class="addOption">添加选项+</a></td></tr>'); $('#questionnum').val((num*1+1)); resetQ(); }); $('#addFill').click(function(){ var num=$('#questionnum').val(); $('#addtr').before('<tr class="qtr"><td class="qn" style="text-align:center;"></td><td>'+ '<input type="text" name="question'+num+'[title]" value="" style="width:300px;" /><a style="float:right;" href="#" class="delQuestion">删除</a></td></tr>'+ '<tr class="atr"><td style="text-align:center;">填空题<input type="hidden" name="question'+num+'[type]" value="4" /><br>'+ '<input type="button" class="mvDown" value="下移" /><input type="button" class="mvUp" value="上移" /></td>'+ '<td>(需要答题者填写文字的部分请用特殊符号"@text"代替,如:姓名是@text)<br/>'+ '<input type="text" name="question'+num+'[content][]" value="" style="width:240px;" /></td></tr>'); $('#questionnum').val((num*1+1)); resetQ(); }); $('.delQuestion').live('click',function(){ if(confirm('是否删除问题')){ $(this).parent().parent().next().remove(); $(this).parent().parent().remove(); resetQ(); } return false; }); $('.addOption').live('click',function(){ var optcheck=$(this).prev().prev().clone().removeAttr('checked'); var opt=$(this).prev().clone().val(''); $(this).before('<br/>'); $(this).before(optcheck); $(this).before('&nbsp;'); $(this).before(opt); return false; }); //下移 $('input.mvDown').live('click',function(){ var thisaobj=$(this).parent().parent(); var thisqobj=thisaobj.prev(); var index=$('tr.atr').index(thisaobj); if((index+1)<=$('tr.atr').length){ $('tr.atr').eq(index+1).after(thisqobj); thisqobj.after(thisaobj); resetQ(); } }); //上移 $('input.mvUp').live('click',function(){ var thisaobj=$(this).parent().parent(); var thisqobj=thisaobj.prev(); var index=$('tr.atr').index(thisaobj); if((index-1)>=0){ $('tr.qtr').eq(index-1).before(thisaobj); thisaobj.before(thisqobj); resetQ(); } }); }); //重新初始化问题序号 function initQuestionNum(){ $('tr.qtr').each(function(i){ $(this).find('input').each(function(){ if($(this).attr('name')){ var strname=$(this).attr('name')+''; strname = strname.replace(/question\d+/g,'question'+i); $(this).attr('name',strname+''); } }); $(this).next().find('input').each(function(){ if($(this).attr('name')){ var strname=$(this).attr('name')+''; strname = strname.replace(/question\d+/g,'question'+i); $(this).attr('name',strname+''); } }); }); } //重置Q序号 function resetQ(){ $('.qn').each(function(i){ $(this).html('Q'+(i+1)); }); initQuestionNum(); } function checkFrom(){ var flag=true; var title=$('#questionnaire_title').val(); var status=$('#questionnaire_status').val(); var msg=''; if($.trim(title)==''){ msg+='请填写问卷标题\n'; flag=false; } if($.trim(status)=='1'){ msg+='问卷已发布不可编辑\n'; flag=false; } if($.trim(status)=='2'){ msg+='问卷已结束不可编辑\n'; flag=false; } if(!flag){ alert(msg); } return flag; }<file_sep>/App/Model/Category.php <?php FLEA::loadClass('FLEA_Db_TableDataGateway'); class Model_Category extends FLEA_Db_TableDataGateway { var $tableName = 'category'; var $primaryKey = 'id'; } ?><file_sep>/resource/js/as.js $(function(){ setInterval(function(){$('#time').val($('#time').val()*1+1)},1000); $('#submit').click(function(){ if($('#questionnaire_status').val()!=1){ if($('#questionnaire_status').val()==2){ alert('调查问卷已结束,您不能答题'); }else{ alert('调查问卷还没发布,您不能答题'); } return false; }else{ return true; } }); $('.anstext').live('blur',function(){ var qeobj=$(this).parent().parent(); var type=qeobj.find('.qetype').val(); if(type==3){ var i=qeobj.find('.anstext').index($(this)); qeobj.find('input[name^=anscontent]').eq(i).val($(this).val()); } if(type==4){ var str=''; qeobj.find('.anstext').each(function(i){ str+=$(this).val()+','; }); qeobj.find('input[name^=anscontent]').val(str.slice(0,-1)); } }); $('#copyQurl').click(function(){ //window.clipboardData.setData("Text等等", '需要复制的信息'); //alert('复制成功'); return false; }); //判断概率出下一题 $('.ansqe label').live('click',function(){ //选中高亮切换 if(!$(this).find('input:eq(0)').attr('checked')){ //最多选择几项 var numlimit=$(this).parent().find('.aslimit').val(); if($(this).find('input:eq(0)').attr('type')=='checkbox'&&$(this).parent().find('input:checked').length>=numlimit){ alert('本题最多选择'+numlimit+'项答案'); return false; } //勾选 if($(this).find('input:eq(0)').attr('type')=='radio'){ $(this).parent().find('label').css('background-color','#fff'); } $(this).find('input:eq(0)').attr('checked','checked');//勾选 $(this).css('background-color','#d5eaff'); }else{ //取消 $(this).find('input:eq(0)').removeAttr('checked','checked');//勾选 $(this).css('background-color','#fff'); } //如果是触发结束题则不出新的题 if($(this).parent().find('.flag_over').val()==1){ return false; } //移除后面答题内容 var index=$('.question_list').index($(this).parent().parent()); $('.question_list:gt('+index+')').remove(); var questionid=$(this).parent().prev().find('input[name^=questionid]').val(); var optionlist=$(this).parent().find('input:checked');//var optionid=$(this).find('input').val(); var selectqeid=''; var selectqeidarr=new Array(); //找符合前置条件的问题 var i=0; $('.qecon li').each(function(){ var qecon_prevqe_id=$(this).find('.qecon_prevqe_id').val(); var qecon_prevop_id=$(this).find('.qecon_prevop_id').val(); var qecon_qe_id=$(this).find('.qecon_qe_id').val(); optionlist.each(function(){ if(qecon_prevqe_id==questionid && qecon_prevop_id==$(this).val()){ selectqeidarr[i]=qecon_qe_id; i++; } }); }); var ind=Math.floor(Math.random()*selectqeidarr.length); selectqeid=selectqeidarr[ind]?selectqeidarr[ind]:''; //如果没有符合前置条件的问题则随机下一轮,按概率出 if(selectqeid==''){ var step=$('.ansqe').length; var qeli=$('#qepath .step').eq(step-1).find('li');//某个路径的li var maxnum=0; qeli.each(function(){ maxnum+=$(this).find('.probability').val()*1; }); var tnum=Math.floor(Math.random()*maxnum+1); qeli.each(function(){ var probability=$(this).find('.probability').val()*1; if(tnum<=probability){ selectqeid=$(this).find('.qeid').val(); return false; }else{ maxnum-=probability; tnum=Math.floor(Math.random()*maxnum+1); } }); } if(selectqeid!=''){ var leng=$('.question_list').length; var selectqe=$('li#qestion_id'+selectqeid).length>0?$('li#qestion_id'+selectqeid):$('li#questall_id'+selectqeid).eq(0);//先通过前置条件找,如果没有则在所有路径问题中找到问题 var qetitle=selectqe.find('.qetitle').val(); var qetype=selectqe.find('.qetype').val(); var aslimit=selectqe.find('.aslimit').val();//答题限制 var flag_over=selectqe.find('.flag_over').val();//1触发结束,2无 var qefile=(selectqe.find('.qefile').val()!='')?'<br><img src="'+selectqe.find('.qefile').val()+'">':''; var str='<div class="wj_m question_list">'+ '<p>Q'+(leng+1)+'. '+qetitle+qefile+ '<input type="hidden" name="questionid'+leng+'" value="'+selectqeid+'" />'+ '</p> <div class="wj_mm ansqe">'+ '<input class="qetype" type="hidden" value="'+qetype+'" /><input class="aslimit" type="hidden" value="'+aslimit+'" /><input class="flag_over" type="hidden" value="'+flag_over+'" />'; selectqe.find('.opid').each(function(i){ var opid=$(this).val(); var opcontent=selectqe.find('.opcontent').eq(i).val(); str+='<label>'; if(qetype == 1){ str+='<input type="radio" name="check'+leng+'" value="'+opid+'">'; }else if(qetype == 2){ str+='<input type="checkbox" name="check'+leng+'[]" value="'+opid+'">'; }else if(qetype == 3){ str+='<input type="radio" name="check'+leng+'" value="'+opid+'">'; }else if(qetype == 4){ str+='<input type="hidden" name="check'+leng+'" value="'+opid+'">'; } opcontent=opcontent.replace(/@text/g,'<br><input type="text" class="anstext" value="" style="font-size:16px;width:80%;height:30px;" /><br>') str+=opcontent+'<input type="hidden" name="anscontent'+opid+'" value="" /></label>'; }); str+='</div></div>'; $(this).parent().parent().after(str);//新加题目 if(flag_over==1){ $('#quesnum').val($('.question_list').length); $('#submit').val('答题结束并提交'); }else{ $('#submit').val('中止答题并提交'); } }else{ $('#quesnum').val($('.question_list').length); $('#submit').val('答题结束并提交'); } return false; }); }); <file_sep>/App/Controller/ResultAnalysis_bak_20150316.php <?php FLEA::loadFile ('App/Service/pdf/tfpdf.php'); FLEA::loadFile ( "Service/PHPExcel/IOFactory.php" ); class Controller_ResultAnalysis extends FLEA_Controller_Action { /** * * Enter description here ... * @var Class_Common */ var $_common; var $_admin; var $_adminid; var $_questionnaire; var $_question; var $_option; var $_answer; var $_answer_detail; function __construct() { $this->_common = get_singleton ( "Class_Common" ); $this->_admin = get_singleton ( "Model_Admin" ); $this->_questionnaire = get_singleton ( "Model_Questionnaire" ); $this->_question = get_singleton ( "Model_Question" ); $this->_option = get_singleton ( "Model_Option" ); $this->_answer = get_singleton ( "Model_Answer" ); $this->_answer_detail = get_singleton ( "Model_AnswerDetail" ); $this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : ""; if(empty($_SESSION ['loginuserid'])){ $url=url("Default","Login"); redirect($url); } } //分析统计图 function actionAnalysis(){ $qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid']) : ''; if(empty($qnnaid)){ $url=url('Questionnaire','Index'); redirect($url); return; } $questionnaire=$this->_questionnaire->findByField('id',$qnnaid); $question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num asc,id desc'); foreach ($question as $k=>$q){ $options=$this->_option->findAll(array('question_id'=>$q['id'])); foreach ($options as $opk=>$op){ $options[$opk]['count']=$this->_answer_detail->findCount(array('questionnaire_id'=>$qnnaid,'question_id'=>$q['id'],'option_id'=>$op['id'])); } $question[$k]['option']=$options; } $questionnaire['anscount']=$this->_answer->findCount(array('questionnaire_id'=>$qnnaid)); $this->_common->show ( array ('main' => 'analysis/analysis.tpl','questionnaire'=>$questionnaire,'question'=>$question) ); } //答题列表 function actionList() { $qnnaid=isset ( $_GET ['qnnaid'] ) ? $this->_common->filter($_GET ['qnnaid']) : ''; if(empty($qnnaid)){ $url=url('Questionnaire','Index'); redirect($url); return; } $pageparm = array ('qnnaid'=>$qnnaid);//9删除 $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 20; $title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : ''; $conditions=array('questionnaire_id'=>$qnnaid); if(!empty($title)){ $conditions[]="title like '%$title%'"; $pageparm['title']=$title; } $total=$this->_answer->findCount($conditions); $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "ResultAnalysis", "List"); $pages->_parm = $pageparm; $page = $pages->page (); $start = ($page_no - 1) * $page_size; $list=$this->_answer->findAll($conditions,"id desc limit $start,$page_size"); $questionnaire=$this->_questionnaire->findByField('id',$qnnaid); $this->_common->show ( array ('main' => 'analysis/answer_list.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm,'questionnaire'=>$questionnaire) ); } function actionDelAnswer(){ $id=isset ( $_GET ['id'] ) ? $this->_common->filter($_GET ['id']) : ''; if(empty($id)){ $url=url('Questionnaire','Index'); redirect($url); return; } $this->_answer->removeByConditions(array('id'=>$id)); $this->_answer_detail->removeByConditions(array('answer_id'=>$id)); redirect($_SERVER['HTTP_REFERER']); } //pdf打印 function actionQuestionarePdf(){ $config = FLEA::getAppInf ( 'dbDSN' ); $prefix = $config ['prefix']; $qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid']) : ''; $questionnaire=$this->_questionnaire->findByField('id',$qnnaid); $question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num asc,id asc'); //查看答卷详情 $conditions=array('questionnaire_id'=>$qnnaid); $answerlist=$this->_answer->findAll($conditions,"id desc"); if(!is_array($answerlist)||count($answerlist)<=0){ echo '暂无答题数据'; return false; } $pdf = new tFPDF (); $pdf->isfooter = false; $pdf->bMargin = 0; $pdf->AutoPageBreak = false; $pdf->AddFont ( 'MicrosoftYaHei', '', 'msyh.ttf', true ); $pdf->Open (); foreach ($answerlist as $k=>$v){ $pdf->AddPage (); $pdf->SetTextColor ( 0, 0, 0 ); $x=$y=0; $y += 10; $pdf->SetXY ( $x, $y ); $pdf->SetFont ( 'MicrosoftYaHei', '', 12 ); $pdf->SetFontSize(15); $sw=$pdf->GetStringWidth($questionnaire['title']); $pdf->MultiCell(210, 8, $questionnaire['title'],0,'C'); //$pdf->Cell ( 210,12, $questionnaire['title'], 0, 0, 'C', 0); $y += (ceil($sw/210))*8+5; $pdf->SetXY ( $x, $y ); $pdf->SetFontSize(10); $pdf->Cell ( 210,12, '答题序号:'.$v['num'].' 用 户 IP:'.$v['ip'].' 答题时长:'.$v['pass_time'].' 答题时间:'.$v['created'], 0, 0, 'C', 0); $y += 12; $pdf->SetXY ( $x+5, $y ); $pdf->SetFillColor(60,156,207); $pdf->Cell ( 200,0.5, '', 0, 0, 'C', 1);//蓝线 foreach ($question as $qk=>$q){ //查下问题答案详情 $sql="select op.content,ad.answer_content from ".$prefix."answer_detail ad left join ".$prefix."option op on op.id=ad.option_id where ad.question_id=".$q['id']." and ad.answer_id=".$v['id']; $o=$this->_answer_detail->findBySql($sql); $content=array(); $answer=array(); foreach ($o as $oo){ $content[]=$oo['content']; $answer[]=$oo['answer_content']; } $content=implode(',', $content); $answer=implode(',', $answer); $answer_content=''; if($q['type']=='1'||$q['type']=='2'){ $answer_content=$content; }else{ $content=explode("@text", $content); $answer=explode(",", $answer); foreach ($content as $ck=>$c){ $answer_content.=$c.$answer[$ck]; } } $y+=5; $pdf->SetXY($x+5,$y); $pdf->Cell(8,10,'Q'.($qk+1).'.', 0, 0, 'L', 0); $pdf->SetX($x+12); $pdf->MultiCell(192, 10, $q['title']); $sw=$pdf->GetStringWidth($q['title']); $y+=ceil($sw/192)>0?ceil($sw/192)*10:10; $pdf->SetX($x+5,$y); $pdf->Cell(10,10,'回答:', 0, 0, 'L', 0); $pdf->SetX($x+15); $pdf->MultiCell(190, 10, $answer_content); $sw=$pdf->GetStringWidth($answer_content); $y+=ceil($sw/190)>0?ceil($sw/190)*10:10; } $pdf->SetXY ( $x+5, 260 ); $pdf->Cell ( 200,0.5, '', 0, 0, 'C', 1); $pdf->SetXY ( $x+10, 260 ); $pdf->Cell ( 210,12, '关注"Planbook"微信账号,了解更多内容', 0, 0, 'L', 0); $path = "resource/images/planbook.jpg"; $pdf->Image ( $path, 160, 262, 30, 30 ); } $pdf->Output (); } //导出Excel function actionQuestionareExc(){ $config = FLEA::getAppInf ( 'dbDSN' ); $prefix = $config ['prefix']; $qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid']) : ''; $questionnaire=$this->_questionnaire->findByField('id',$qnnaid); $question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num asc,id asc'); $conditions=array('questionnaire_id'=>$qnnaid); $answerlist=$this->_answer->findAll($conditions,"id desc "); // 设置基本属性 $objPHPExcel = new PHPExcel(); // 创建多个工作薄 $sheet1 = $objPHPExcel->createSheet(); // 设置第一个工作簿为活动工作簿 $objPHPExcel->setActiveSheetIndex(0); // 设置活动工作簿名称 $objPHPExcel->getActiveSheet()->setTitle('统计数据'); // 设置默认字体和大小 $objPHPExcel->getDefaultStyle()->getFont()->setName('宋体'); $objPHPExcel->getDefaultStyle()->getFont()->setSize(10); // 给特定单元格中写入内容 $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0,1, '答题序号'); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1,1, '答题时间'); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2,1, '答题时长'); $i=3; foreach ($question as $q){ $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($i,1, $q['title']); ++$i; } $r=2; foreach ($answerlist as $v){ $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0,$r, $v['num']); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1,$r, $v['created']); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2,$r, $v['pass_time']); $i=3; foreach ($question as $q){ //查找答题选项 $sql="select op.content,ad.answer_content from ".$prefix."answer_detail ad left join ".$prefix."option op on op.id=ad.option_id where ad.question_id=".$q['id']." and ad.answer_id=".$v['id']; $o=$this->_answer_detail->findBySql($sql); $contentstr=array(); $answerstr=array(); foreach ($o as $oo){ $contentstr[]=$oo['content']; $answerstr[]=$oo['answer_content']; } $contentstr=implode(',', $contentstr); $answerstr=implode(',', $answerstr); $answer_content=''; if($q['type']=='1'||$q['type']=='2'){ $answer_content=$contentstr; }else{ $contentstr=explode("@text", $contentstr); $answerstr=explode(",", $answerstr); foreach ($contentstr as $ck=>$c){ $answer_content.=$c.@$answerstr[$ck]; } } //用户答案 $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($i,$r, $answer_content); ++$i; } ++$r; } $FileName = '答题统计表'.date('YmdHis').".xls"; // 输出EXCEL文件名 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); header("Pragma: public"); header("Expires: 0"); header("Cache-Control:must-revalidate, post-check=0, pre-check=0"); header("Content-Type:application/force-download"); header("Content-Type: application/vnd.ms-excel;"); header("Content-Type:application/octet-stream"); header("Content-Type:application/download"); header("Content-Disposition:attachment;filename=".$FileName); header("Content-Transfer-Encoding:binary"); $objWriter->save("php://output"); } } <file_sep>/App/Controller/Answer.php <?php class Controller_Answer extends FLEA_Controller_Action { /** * * Enter description here ... * @var Class_Common */ var $_common; var $_admin; var $_adminid; var $_questionnaire; var $_question; var $_option; var $_answer; var $_answer_detail; var $_abstract; function __construct() { $this->_common = get_singleton ( "Class_Common" ); $this->_admin = get_singleton ( "Model_Admin" ); $this->_questionnaire = get_singleton ( "Model_Questionnaire" ); $this->_question = get_singleton ( "Model_Question" ); $this->_option = get_singleton ( "Model_Option" ); $this->_answer = get_singleton ( "Model_Answer" ); $this->_answer_detail = get_singleton ( "Model_AnswerDetail" ); $this->_abstract = get_singleton ( "Model_Abstract" ); } //短链接跳转 function actionQrcode() { $short = isset ( $_GET ['short'] ) ? $this->_common->filter($_GET ['short']) : ''; $questionnaire=$this->_questionnaire->find(array('short'=>$short),'id desc'); if(@$questionnaire['status']=='1'){ $url=url('Answer','Index',array('qid'=>$questionnaire['id'])); redirect($url); return ; } if($questionnaire['status']=='0'){ echo '<h1>调查问卷还没发布</h1>'; }elseif($questionnaire['status']=='2'){ echo '<h1>调查问卷已经结束</h1>'; }else{ echo '<h1>找不到相关问卷,请联系管理员</h1>'; } } //回答问卷 function actionIndex(){ $qid = isset ( $_GET ['qid'] ) ? $this->_common->filter($_GET ['qid']) : ''; $questionnaire=$this->_questionnaire->findByField('id',$qid); $abstract=$this->_abstract->findAll(array('questionnaire_id'=>$qid),'id asc'); $question=$this->_question->findAll(array('questionnaire_id'=>$qid),'num,id asc'); foreach ($question as $k=>$q){ $question[$k]['option']=$this->_option->findAll(array('question_id'=>$q['id']),'id asc'); } $signinfo=$this->_admin->findByField('adm_name','admin'); $this->_common->display('qa/qa.tpl',array ('questionnaire'=>$questionnaire,'question'=>$question,'abstract'=>$abstract,'signinfo'=>$signinfo) ); } //提交问卷 function actionSubmit(){ $data = $this->_common->filter($_POST); $act = isset ( $data ['act'] ) ? $data ['act'] : ''; $qnnaid = isset ( $data ['questionnaire_unit'] ) ? $data ['questionnaire_unit'] : ''; if($act=='submit'&&!empty($qnnaid)){ $questionnaire=$this->_questionnaire->findByField('id',$qnnaid); if($questionnaire['status']=='0'){ $ref=$_SERVER['HTTP_REFERER']; echo '<h1>调查问卷还没发布,您不能答题<br><a href="'.$ref.'" >返回</a><'; return ; } if($questionnaire['status']=='2'){ $ref=$_SERVER['HTTP_REFERER']; echo '<h1>调查问卷已结束,您不能答题<br><a href="'.$ref.'" >返回</a>'; return ; } $passtime=''; $time=$data['time']; //$d = intval($time/86400); $h = round(($time%86400)/3600); $m = round(($time%3600)/60); $s = round(($time%60)); $passtime.=$h>0?$h.'时':''; $passtime.=$m>0?$m.'分':''; $passtime.=$s.'秒'; //回答信息 $answer=array('questionnaire_id'=>$qnnaid,'pass_time'=>$passtime,'num'=>$this->_answer->getMaxNumGoupByQid($qnnaid),'ip'=>$_SERVER['REMOTE_ADDR']); $ansid=$this->_answer->create($answer); $quesnum=$this->_question->findCount(array('questionnaire_id'=>$qnnaid)); for($i=0;$i<$quesnum;$i++){ $asoption=$data['check'.$i]; if(is_array($asoption)){ foreach ($asoption as $aopt){ $asdetial=array('answer_id'=>$ansid,'questionnaire_id'=>$qnnaid,'question_id'=>$data['questionid'.$i],'option_id'=>$aopt,'answer_content'=>$data['anscontent'.$aopt]); $this->_answer_detail->create($asdetial); } }else{ $asdetial=array('answer_id'=>$ansid,'questionnaire_id'=>$qnnaid,'question_id'=>$data['questionid'.$i],'option_id'=>$asoption,'answer_content'=>$data['anscontent'.$asoption]); $this->_answer_detail->create($asdetial); } } $url=url('Answer','Complete'); redirect($url); } } //完成问卷 function actionComplete(){ $signinfo=$this->_admin->findByField('adm_name','admin'); $this->_common->display('qa/complete.tpl',array('msg'=>'感谢您的提交!','signinfo'=>$signinfo)); } function actionPreview(){ $config = FLEA::getAppInf ( 'dbDSN' ); $prefix = $config ['prefix']; $qid = isset ( $_GET ['qid'] ) ? $this->_common->filter($_GET['qid']) : ''; $answer=$this->_answer->findByField('id',$qid); if(empty($answer['id'])){ echo '答题内容不存在,可能已被删除'; return; } $questionnaire=$this->_questionnaire->findByField('id',$answer['questionnaire_id']); $abstract=$this->_abstract->findAll(array('questionnaire_id'=>$qid)); $question=$this->_question->findAll(array('questionnaire_id'=>$answer['questionnaire_id']),'num asc,id desc'); foreach ($question as $k=>$q){ //查找答题选项 $sql="select op.content,ad.answer_content from ".$prefix."answer_detail ad left join ".$prefix."option op on op.id=ad.option_id where ad.question_id=".$q['id']." and ad.answer_id=".$qid; $o=$this->_answer_detail->findBySql($sql); $contentstr=array(); $answerstr=array(); foreach ($o as $oo){ $contentstr[]=$oo['content']; $answerstr[]=$oo['answer_content']; } $contentstr=implode(',', $contentstr); $answerstr=implode(',', $answerstr); $answer_content=''; if($q['type']=='1'||$q['type']=='2'){ $answer_content=$contentstr; }else{ $contentstr=explode("@text", $contentstr); $answerstr=explode(",", $answerstr); foreach ($contentstr as $ck=>$c){ $answer_content.=$c.$answerstr[$ck]; } } $question[$k]['answer']=$answer_content; } $this->_common->display('qa/preview.tpl',array('answer'=>$answer,'questionnaire'=>$questionnaire,'question'=>$question,'abstract'=>$abstract)); } function actionAnalysis(){ $config = FLEA::getAppInf ( 'dbDSN' ); $prefix = $config ['prefix']; $qnnaid = isset ( $_GET ['qnnaid'] ) ?$this->_common->filter($_GET ['qnnaid']) : ''; $questionnaire=$this->_questionnaire->findByField('id',$qnnaid); $question=$this->_question->findAll(array('questionnaire_id'=>$qnnaid),'num asc,id asc'); foreach ($question as $k=>$q){ $options=$this->_option->findAll(array('question_id'=>$q['id'])); foreach ($options as $opk=>$op){ $options[$opk]['count']=$this->_answer_detail->findCount(array('questionnaire_id'=>$qnnaid,'question_id'=>$q['id'],'option_id'=>$op['id'])); } $question[$k]['option']=$options; } $questionnaire['anscount']=$this->_answer->findCount(array('questionnaire_id'=>$qnnaid)); //查看答卷详情 $pageparm = array ('qnnaid'=>$qnnaid);//9删除 $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 50; $title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : ''; $conditions=array('questionnaire_id'=>$qnnaid); if(!empty($title)){ $conditions[]="title like '%$title%'"; $pageparm['title']=$title; } $total=$this->_answer->findCount($conditions); $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "Answer", "Analysis"); $pages->_parm = $pageparm; $page = $pages->analysisPage (); $start = ($page_no - 1) * $page_size; $answerlist=$this->_answer->findAll($conditions,"id desc limit $start,$page_size"); foreach ($answerlist as $k=>$v){ $anses=array(); foreach ($question as $qk=>$q){ $sql="select op.content,ad.answer_content from ".$prefix."answer_detail ad left join ".$prefix."option op on op.id=ad.option_id where ad.question_id=".$q['id']." and ad.answer_id=".$v['id']; $o=$this->_answer_detail->findBySql($sql); $content=array(); $answer=array(); foreach ($o as $oo){ $content[]=$oo['content']; $answer[]=$oo['answer_content']; } $content=implode(',', $content); $answer=implode(',', $answer); $answer_content=''; if($q['type']=='1'||$q['type']=='2'){ $answer_content=$content; }else{ $content=explode("@text", $content); $answer=explode(",", $answer); foreach ($content as $ck=>$c){ $c.=@$answer[$ck]; $answer_content.=$c; } } $anses[]=array('content'=>$answer_content,'qetype'=>$q['type']); } $answerlist[$k]['answer']=$anses; } $this->_common->display('qa/analysis.tpl', array ('questionnaire'=>$questionnaire,'question'=>$question,'answerlist'=>$answerlist,'page'=>$page,'pageparm'=>$pageparm) ); } } <file_sep>/App/Controller/Qe.php <?php class Controller_Qe extends FLEA_Controller_Action { /** * * Enter description here ... * @var Class_Common */ var $_common; var $_admin; var $_adminid; var $_qs; var $_qe; var $_op; var $_group; var $_category; function __construct() { $this->_common = get_singleton ( "Class_Common" ); $this->_admin = get_singleton ( "Model_Admin" ); $this->_group = get_singleton ( "Model_Group" ); $this->_category = get_singleton ( "Model_Category" ); $this->_qs = get_singleton ( "Model_Qs" ); $this->_qe = get_singleton ( "Model_Qe" ); $this->_op = get_singleton ( "Model_Op" ); $this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : ""; if(empty($_SESSION ['loginuserid'])){ $url=url("Default","Login"); redirect($url); } } //题库分组 function actionGroup(){ $act=isset($_POST['act'])?$this->_common->filter($_POST['act']):''; $msg=''; if(!empty($act)){ $ids=$_POST['ids']; $name=$_POST['name']; foreach ($name as $k=>$n){ if(!empty($n)){ if(!empty($ids[$k])){ $g=array('id'=>$ids[$k],'name'=>$n); $this->_group->update($g); }else{ $g=array('name'=>$n); $this->_group->create($g); } } } $msg='分组更新成功'; } $groups=$this->_group->findAll(); $this->_common->show ( array ('main' => 'qe/group.tpl','groups'=>$groups,'msg'=>$msg) ); } //删除分组 function actionDelGroup(){ $id=$this->_common->filter($_GET['id']); $count=$this->_qe->findCount(array('group_id'=>$id)); if($count>0){ echo '<script>alert("此分组中有题库,不可删除");window.location="'.$_SERVER['HTTP_REFERER'].'"</script>'; }else{ $this->_group->removeByPkv($id); redirect($_SERVER['HTTP_REFERER']); } } //题库分类 function actionCategory(){ $act=isset($_POST['act'])?$this->_common->filter($_POST['act']):''; $msg=''; if(!empty($act)){ $ids=$_POST['ids']; $name=$_POST['name']; foreach ($name as $k=>$n){ if(!empty($n)){ if(!empty($ids[$k])){ $g=array('id'=>$ids[$k],'name'=>$n); $this->_category->update($g); }else{ $g=array('name'=>$n); $this->_category->create($g); } } } $msg='分类更新成功'; } $category=$this->_category->findAll(); $this->_common->show ( array ('main' => 'qe/category.tpl','category'=>$category,'msg'=>$msg) ); } //删除分类 function actionDelCategory(){ $id=$this->_common->filter($_GET['id']); $count=$this->_qe->findCount(array('category_id'=>$id)); if($count>0){ echo '<script>alert("此类型中有题库,不可删除");window.location="'.$_SERVER['HTTP_REFERER'].'"</script>'; }else{ $this->_category->removeByPkv($id); redirect($_SERVER['HTTP_REFERER']); } } //题库新增 function actionQeAdd(){ $act=isset ( $_POST ['act'] ) ? $_POST ['act'] : ''; if($act=='add'){ //创建题库 $qe=$this->_common->filter($_POST['qe']); //判断类型为空 if(empty($qe['category_id'])){unset($qe['category_id']);} $Upload= & get_singleton ( "Service_UpLoad" ); $folder="resource/upload/qeimg/"; if (! file_exists ( $folder )) { mkdir ( $folder, 0777 ); } $Upload->setDir($folder.date("Ymd")."/"); $img=$Upload->upload('file'); if($img['status']==1){ $file_path=$img['file_path']; $qe['file']=$file_path; } $qe_id=$this->_qe->create($qe); //创建答题选项 $i=$qe['type']; if(isset($_POST['op'.$i])){ $op=$this->_common->filter($_POST['op'.$i]); foreach($op['content'] as $c){ //创建选项 if(!empty($c)){ $option=array('content'=>$c,'qe_id'=>$qe_id); $this->_op->create($option); } } } $url=url('Qe','QeList'); redirect($url); } $group=$this->_group->findAll(array(),"id"); $category=$this->_category->findAll(array(),"id"); $this->_common->show ( array ('main' => 'qe/qeadd.tpl','category'=>$category,'group'=>$group) ); } //题库编辑 function actionQeEdit(){ $act=isset ( $_POST ['act'] ) ? $_POST ['act'] : ''; $id=isset ( $_GET ['qeid'] ) ? $this->_common->filter($_GET ['qeid']) : ''; $msg=''; if($act=='edit'){ //创建题库 $qe=$this->_common->filter($_POST['qe']); //判断类型为空 if(empty($qe['category_id'])){unset($qe['category_id']);} $qe_id=$qe['id']; $Upload= & get_singleton ( "Service_UpLoad" ); $folder="resource/upload/qeimg/"; if (! file_exists ( $folder )) { mkdir ( $folder, 0777 ); } $Upload->setDir($folder.date("Ymd")."/"); $img=$Upload->upload('file'); if($img['status']==1){ $file_path=$img['file_path']; $qe['file']=$file_path; } $this->_qe->update($qe); //创建答题选项 $i=$qe['type']; if(isset($_POST['op'.$i])){ $this->_op->removeByConditions(array('qe_id'=>$qe_id)); $op=$this->_common->filter($_POST['op'.$i]); foreach($op['content'] as $c){ //创建选项 if(!empty($c)){ $option=array('content'=>$c,'qe_id'=>$qe_id); $this->_op->create($option); } } } $msg='修改成功!'; } $qe=$this->_qe->findByField('id',$id); $ops=$this->_op->findAll(array('qe_id'=>$id),"id asc"); $group=$this->_group->findAll(array(),"id asc"); $category=$this->_category->findAll(array(),"id"); $this->_common->show ( array ('main' => 'qe/qeedit.tpl','category'=>$category,'group'=>$group,'qe'=>$qe,'ops'=>$ops,'msg'=>$msg) ); } //题库列表 function actionQeList(){ $config = FLEA::getAppInf ( 'dbDSN' ); $prefix = $config ['prefix']; $keyword = isset ( $_GET ['keyword'] ) ? $this->_common->filter($_GET ['keyword']) : ''; $group_id = isset ( $_GET ['group'] ) ? $this->_common->filter($_GET ['group']) : ''; $category_id = isset ( $_GET ['category'] ) ? $this->_common->filter($_GET ['category']) : ''; $conditions=''; $pageparm=array(); if(!empty($keyword)){ $conditions=" and title like '%".addslashes($keyword)."%'"; $pageparm['keyword']=$keyword; } if(!empty($group_id)){ $conditions.=" and group_id =".addslashes($group_id); $pageparm['group']=$group_id; } if(!empty($category_id)){ $conditions.=" and category_id =".addslashes($category_id); $pageparm['category']=$category_id; } $sql="select qe.*,gp.name group_name from ".$prefix."qe qe left join ".$prefix."group gp on qe.group_id=gp.id where 1=1 "; $sql.=$conditions; $total=$this->_qe->findBySql("select count(*) as num from ($sql) s "); $total=$total[0]['num']; $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 20; $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "Qe", "QeList"); $pages->_parm = $pageparm; $page = $pages->page (); $start = ($page_no - 1) * $page_size; $list=$this->_qe->findBySql($sql." order by qe.id desc limit $start,$page_size"); foreach ($list as $k=>$v){ $ops=$this->_op->findAll(array('qe_id'=>$v['id']),'id asc'); $list[$k]['ops']=$ops; } $group=$this->_group->findAll(array(),"id"); $category=$this->_category->findAll(array(),"id"); $this->_common->show ( array ('main' => 'qe/qelist.tpl','list'=>$list,'pageparm'=>$pageparm,'group'=>$group,'category'=>$category,'page'=>$page) ); } //题库附件 function actionQeFile(){ $config = FLEA::getAppInf ( 'dbDSN' ); $prefix = $config ['prefix']; $keyword = isset ( $_GET ['keyword'] ) ? $this->_common->filter($_GET ['keyword']) : ''; $conditions=''; if(!empty($keyword)){ $conditions="and title like '%".addslashes($keyword)."%'"; $pageparm['keyword']=$keyword; } $sql="select qe.*,gp.name group_name from ".$prefix."qe qe left join ".$prefix."group gp on qe.group_id=gp.id where qe.file is not null and qe.file<>'' "; $sql.=$conditions; $total=$this->_qe->findBySql("select count(*) as num from ($sql) s "); $total=$total[0]['num']; $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 20; $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "Qe", "QeList"); $pages->_parm = $pageparm; $page = $pages->page (); $start = ($page_no - 1) * $page_size; $list=$this->_qe->findBySql($sql."order by qe.id desc limit $start,$page_size"); foreach ($list as $k=>$v){ $ops=$this->_op->findAll(array('qe_id'=>$v['id']),'id asc'); $list[$k]['ops']=$ops; $total=$this->_qe->findBySql("select count(a.id) as num from ".$prefix."qs_answer a left join ".$prefix."qs qs on a.qs_id=qs.id left join ".$prefix."qepath path on path.qs_id=qs.id where path.qe_id=".$v['id']); $total=@$total[0]['num']*1; $list[$k]['rate']=round($v['times']/$total*100,2); } $this->_common->show ( array ('main' => 'qe/qefiles.tpl','list'=>$list,'pageparm'=>$pageparm,'page'=>$page) ); } //删除题库 function actionQeDel(){ $id=$this->_common->filter($_GET['id']); $this->_op->removeByConditions(array('qe_id'=>$id)); $this->_qe->removeByPkv($id); redirect($_SERVER['HTTP_REFERER']); } //删除题库附件 function actionQeDelFile(){ $id=$this->_common->filter($_GET['qeid']); $qe=$this->_qe->findByField('id',$id); if(!empty($qe['file'])){ unlink($qe['file']); } $qe['file']=''; $this->_qe->update($qe); redirect($_SERVER['HTTP_REFERER']); } } <file_sep>/App/Controller/Qs.php <?php require_once SERVERROOT. DS . 'App' . DS . 'Class' .DS.'phpqrcode.php'; require_once SERVERROOT. DS . 'weixin' . DS . 'wechat.php'; class Controller_Qs extends FLEA_Controller_Action { /** * * Enter description here ... * @var Class_Common */ var $_common; var $_admin; var $_adminid; var $_qs; var $_qe; var $_op; var $_qs_answer; var $_qs_abstract; var $_group; var $_category; var $_qepath; var $_qecon; function __construct() { $this->_common = get_singleton ( "Class_Common" ); $this->_admin = get_singleton ( "Model_Admin" ); $this->_group = get_singleton ( "Model_Group" ); $this->_category = get_singleton ( "Model_Category" ); $this->_qs = get_singleton ( "Model_Qs" ); $this->_qe = get_singleton ( "Model_Qe" ); $this->_op = get_singleton ( "Model_Op" ); $this->_qs_answer = get_singleton ( "Model_QsAnswer" ); $this->_qs_abstract = get_singleton ( "Model_QsAbstract" ); $this->_qepath=get_singleton ( "Model_QePath" ); $this->_qecon=get_singleton ( "Model_QeCon" ); $this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : ""; if(empty($_SESSION ['loginuserid'])){ $url=url("Default","Login"); redirect($url); } } //问卷添加 function actionAdd(){ $act=isset ( $_POST ['act'] ) ? $_POST ['act'] : ''; if($act=='add'){ //问卷设置 $data=$this->_common->filter($_POST['data']); $data['over_num']=intval($data['over_num']); if(empty($data['over_num'])){ unset($data['over_num']); } if(empty($data['over_date'])){ unset($data['over_date']); } //短连接及二维码 $shoturl=url('As','Index',array('time'=>time())); $shoturl=$this->_common->shortUrl($shoturl); $data['short']=$shoturl; $data['qrcode']=$this->createQr($shoturl); $data['created']=date("Y-m-d H:i:s"); //创建问卷 $qs_id=$this->_qs->create($data); //创建摘要 $Upload= & get_singleton ( "Service_UpLoad" ); $folder="resource/upload/abstract/"; if (! file_exists ( $folder )) { mkdir ( $folder, 0777 ); } $Upload->setDir($folder.date("Ymd")."/"); $absnum=$_POST['abstractnum']; for ($i=0;$i<$absnum;$i++){ $abstract=array(); $numi=($i+1); $Upload->setPrefixName($i); $img=$Upload->upload('abstractimg'.$numi); if($img['status']==1){ $file_path=$img['file_path']; } $abstract['qs_id']=$qs_id; $abstract['title']=$_POST['abstract'.$numi]['title']; $abstract['content']=$_POST['abstract'.$numi]['content']; $abstract['imginfo']=$_POST['abstract'.$numi]['imginfo']; $abstract['img']=$file_path; $this->_qs_abstract->create($abstract); } //创建答题选项 $step=$this->_common->filter($_POST['step']); $qeids=$this->_common->filter($_POST['qeid']); $probability=$this->_common->filter($_POST['probability']); $hascon=$this->_common->filter($_POST['hascon']); $aslimit=$this->_common->filter($_POST['aslimit']); $flag_over=$this->_common->filter($_POST['flag_over']); $num=1; $csp=$step[0]; foreach ($step as $sk=>$sp){ $prov=($probability[$sk]=='')?1:$probability[$sk]; $qepath=array('qs_id'=>$qs_id,'step'=>$sp,'qe_id'=>$qeids[$sk],'num'=>$num,'probability'=>$prov,'hascon'=>$hascon[$sk],'aslimit'=>$aslimit[$sk],'flag_over'=>$flag_over[$sk]); if($csp!=$sp){ $num=1; }else{ ++$num; } $csp=$sp; $this->_qepath->create($qepath); } $stepnumupdate=array('id'=>$qs_id,'step_num'=>$csp); $this->_qs->update($stepnumupdate);//更新最大步骤数 $prevqe=$this->_common->filter($_POST['consprevqe']); $prevop=$this->_common->filter($_POST['consprevop']); $consqeid=$this->_common->filter($_POST['consqeid']); $constep=$this->_common->filter($_POST['constep']); foreach ($prevqe as $pk=>$qid){ $qecon=array('qs_id'=>$qs_id,'prevqe_id'=>$qid,'prevop_id'=>empty($prevop[$pk])?null:$prevop[$pk],'qe_id'=>$consqeid[$pk],'step'=>$constep[$pk]); $this->_qecon->create($qecon); } $url=url('Qs','List'); redirect($url); } $gps=$groups=$this->_group->findAll(array(),"id asc",null,array("id","name")); foreach ($groups as $kg=>$g){ $groups[$kg]['qes']=$this->_qe->findAll(array('group_id'=>$g['id'])); } $category=$this->_category->findAll(array(),"id"); $this->_common->show ( array ('main' => 'qs/qsadd.tpl','groups'=>$groups,'category'=>$category,'gps'=>$gps) ); } //专业问卷调查列表 function actionList() { $pageparm = array ('status != 9 and status != 2');//9删除 $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 20; $title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : ''; $conditions=array('status != 9 and status != 2'); if(!empty($title)){ $conditions[]="title like '%$title%'"; $pageparm['title']=$title; } $total=$this->_qs->findCount($conditions); $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "Qs", "List" ); $pages->_parm = $pageparm; $page = $pages->page (); $start = ($page_no - 1) * $page_size; $list=$this->_qs->findAll($conditions,"id desc limit $start,$page_size"); foreach ($list as $k=>$d){ $list[$k]['num']=$this->_qs_answer->findCount(array('qs_id'=>$d['id'])); } $this->_common->show ( array ('main' => 'qs/qslist.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) ); } //被删除的问卷列表 function actionDeList() { $pageparm = array ('status = 9');//9删除 $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 20; $title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : ''; $conditions=array('status = 9'); if(!empty($title)){ $conditions[]="title like '%$title%'"; $pageparm['title']=$title; } $total=$this->_qs->findCount($conditions); $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "Qs", "DeList" ); $pages->_parm = $pageparm; $page = $pages->page (); $start = ($page_no - 1) * $page_size; $list=$this->_qs->findAll($conditions,"id desc limit $start,$page_size"); foreach ($list as $k=>$d){ $list[$k]['num']=$this->_qs_answer->findCount(array('qs_id'=>$d['id'])); } $this->_common->show ( array ('main' => 'qs/deqslist.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) ); } //完成的问卷列表 function actionFinshed(){ $pageparm = array ('status = 2');//9删除 $page_no = isset ( $_GET ['page_no'] ) ? $_GET ['page_no'] : 1; $page_size = 20; $title = isset ( $_GET ['title'] ) ? $this->_common->filter($_GET ['title']) : ''; $conditions=array('status = 2'); if(!empty($title)){ $conditions[]="title like '%$title%'"; $pageparm['title']=$title; } $total=$this->_qs->findCount($conditions); $pages = & get_singleton ( "Service_Page" ); $pages->_page_no = $page_no; $pages->_page_num = $page_size; $pages->_total = $total; $pages->_url = url ( "Qs", "Finshed" ); $pages->_parm = $pageparm; $page = $pages->page (); $start = ($page_no - 1) * $page_size; $list=$this->_qs->findAll($conditions,"id desc limit $start,$page_size"); foreach ($list as $k=>$d){ $list[$k]['num']=$this->_qs_answer->findCount(array('qs_id'=>$d['id'])); $list[$k]['updated']=$this->_common->time2Units(time()-strtotime($d['updated'])); } $this->_common->show ( array ('main' => 'qs/qslist.tpl','list'=>$list,'page'=>$page,'pageparm'=>$pageparm) ); } //专业问卷编辑 function actionEdit(){ $qnnaid=isset ( $_GET ['qnnaid'] ) ? $_GET ['qnnaid'] : ''; $act=isset ( $_POST ['act'] ) ? $_POST ['act'] : ''; $msg=''; if($act=='edit'){ $data=$this->_common->filter($_POST['data']); $data['author']=htmlspecialchars_decode($data['author']); //问卷设置 if(empty($data['over_num'])){ unset($data['over_num']); } if(empty($data['over_date'])){ unset($data['over_date']); } //清除旧二维码 if(file_exists ( $data['qrcode'] )){ unlink($data['qrcode']); } //短连接及二维码 $shoturl=url('As','Index',array('time'=>time())); $shoturl=$this->_common->shortUrl($shoturl); $data['short']=$shoturl; $data['qrcode']=$this->createQr($shoturl); //创建问卷 $qs_id=$data['id']; $this->_qs->update($data); //清除摘要和选项 $this->_qs_abstract->removeByConditions(array('qs_id'=>$qs_id)); //创建摘要 $Upload= & get_singleton ( "Service_UpLoad" ); $folder="resource/upload/abstract/"; if (! file_exists ( $folder )) { mkdir ( $folder, 0777 ); } $Upload->setDir($folder.date("Ymd")."/"); $absnum=$_POST['abstractnum']; for ($i=0;$i<$absnum;$i++){ $abstract=array(); $numi=($i+1); $Upload->setPrefixName($i); $img=$Upload->upload('abstractimg'.$numi); $oldimg=$_POST['abstract'.$numi]['img']; if($img['status']==1){//如果有上传图片则更新 $file_path=$img['file_path']; if(file_exists($oldimg)){ unlink($oldimg); } }else{ $file_path=$oldimg; } $abstract['qs_id']=$qs_id; $abstract['title']=$_POST['abstract'.$numi]['title']; $abstract['content']=$_POST['abstract'.$numi]['content']; $abstract['imginfo']=$_POST['abstract'.$numi]['imginfo']; $abstract['img']=$file_path; $this->_qs_abstract->create($abstract); } $this->_qepath->removeByConditions(array('qs_id'=>$qs_id)); $this->_qecon->removeByConditions(array('qs_id'=>$qs_id)); //创建答题选项 $step=$this->_common->filter($_POST['step']); $qeids=$this->_common->filter($_POST['qeid']); $probability=$this->_common->filter($_POST['probability']); $hascon=$this->_common->filter($_POST['hascon']); $aslimit=$this->_common->filter($_POST['aslimit']); $flag_over=$this->_common->filter($_POST['flag_over']); $num=1; $csp=$step[0]; foreach ($step as $sk=>$sp){ $prov=($probability[$sk]=='')?1:$probability[$sk]; $qepath=array('qs_id'=>$qs_id,'step'=>$sp,'qe_id'=>$qeids[$sk],'num'=>$num,'probability'=>$prov,'hascon'=>$hascon[$sk],'aslimit'=>$aslimit[$sk],'flag_over'=>$flag_over[$sk]); if($csp!=$sp){ $num=1; }else{ ++$num; } $csp=$sp; $this->_qepath->create($qepath); } $stepnumupdate=array('id'=>$qs_id,'step_num'=>$csp); $this->_qs->update($stepnumupdate);//更新最大步骤数 $prevqe=$this->_common->filter($_POST['consprevqe']); $prevop=$this->_common->filter($_POST['consprevop']); $consqeid=$this->_common->filter($_POST['consqeid']); $constep=$this->_common->filter($_POST['constep']); foreach ($prevqe as $pk=>$qid){ $qecon=array('qs_id'=>$qs_id,'prevqe_id'=>$qid,'prevop_id'=>empty($prevop[$pk])?null:$prevop[$pk],'qe_id'=>$consqeid[$pk],'step'=>$constep[$pk]); $this->_qecon->create($qecon); } $msg="更新成功!"; } $gps=$groups=$this->_group->findAll(array(),"id asc",null,array("id","name")); foreach ($groups as $kg=>$g){ $groups[$kg]['qes']=$this->_qe->findAll(array('group_id'=>$g['id'])); } $questionnaire=$this->_qs->findByField('id',$qnnaid); $abstract=$this->_qs_abstract->findAll(array('qs_id'=>$qnnaid),'id asc'); $path=$this->_qepath->findAll(array('qs_id'=>$qnnaid),'step asc,id asc'); $qes=$qe=array(); $step=''; foreach ($path as $p){ if($step!=$p['step']){ if(count($qe)>0){$qes[]=$qe;} $qe=array(); } $question=$this->_qe->findByField('id',$p['qe_id']); $p['question']=$question; $p['qecon']=$this->_qecon->findAll(array('step'=>$p['step'],'qs_id'=>$qnnaid,'qe_id'=>$p['qe_id'])); $qe[]=$p; $step=$p['step']; } if(count($qe)>0){$qes[]=$qe;} $category=$this->_category->findAll(array(),"id"); $this->_common->show ( array ('main' => 'qs/qsedit.tpl','questionnaire'=>$questionnaire,'abstract'=>$abstract,'msg'=>$msg,'groups'=>$groups,'category'=>$category,'gps'=>$gps,'path'=>$path,'qes'=>$qes) ); } //再次发布 function actionRePublic(){ $qnnaid=isset ( $_GET ['qnnaid'] ) ? $_GET ['qnnaid'] : ''; $questionnaire=$this->_qs->findByField('id',$qnnaid); if(is_array($questionnaire)){ $abstract=$this->_qs_abstract->findAll(array('qs_id'=>$qnnaid),'id asc'); $qepath=$this->_qepath->findAll(array('qs_id'=>$qnnaid),'id'); $qecon=$this->_qecon->findAll(array('qs_id'=>$qnnaid),'id'); unset($questionnaire['id']); //短连接及二维码 $shoturl=url('As','Index',array('time'=>time())); $shoturl=$this->_common->shortUrl($shoturl); $questionnaire['short']=$shoturl; $questionnaire['qrcode']=$this->createQr($shoturl); $questionnaire['status']=0; $questionnaire['created']=date("Y-m-d H:i:s"); $newqnnaid=$this->_qs->create($questionnaire); foreach ($abstract as $ab){ unset($ab['id']); $ab['qs_id']=$newqnnaid; $this->_qs_abstract->create($ab); } foreach ($qepath as $q){ unset($q['id']); $q['qs_id']=$newqnnaid; $this->_qepath->create($q); } foreach ($qecon as $q){ unset($q['id']); $q['qs_id']=$newqnnaid; $this->_qecon->create($q); } } $url=url('Qs','List'); redirect($url); } //删除status9 function actionDel(){ $id=$this->_common->filter($_GET['id']); $eve=array('id'=>$id,'status'=>9); $this->_qs->update($eve); redirect($_SERVER['HTTP_REFERER']); } //发布status1 function actionPublic(){ $id=$this->_common->filter($_GET['id']); $eve=array('id'=>$id,'status'=>1); $this->_qs->update($eve); redirect($_SERVER['HTTP_REFERER']); } //结束status2 function actionEnd(){ $id=$this->_common->filter($_GET['id']); $eve=array('id'=>$id,'status'=>2); $this->_qs->update($eve); $msg=SITEHOST.'/result.php?qnnaid='.$id; $wechatObj = WeChat::getInstance(); $wechatObj->sendCustomMsg('分析结果是 '.$msg,"o9ZPks_8ZpcQXBndQqjuUpt-E9tg"); redirect($_SERVER['HTTP_REFERER']); } //ajax获取问题选项 function actionGetOpsByQe(){ $qeid=$this->_common->filter($_POST['qeid']); $qe=$this->_qe->findByField('id',$qeid); $op=$this->_op->findAll(array('qe_id'=>$qeid),'id asc'); $qe['op']=$op; echo json_encode($qe); } //ajax根据分组获取问题 function actionGetQeByGroup(){ $gid=$this->_common->filter($_POST['gid']); $qes=$this->_qe->findAll(array('group_id'=>$gid)); echo json_encode($qes); } //ajax获取前置条件 function actionGetBeforeCon(){ $qe=$this->_common->filter($_POST['qe']); $op=$this->_common->filter($_POST['op']); $curqeid=''; $data=array(); $qandop=array(); foreach ($qe as $k=>$q){ $qes=$this->_qe->findByField('id',$q); if($q!=$curqeid&&!empty($qandop)){ $qandop['ops']=$this->_op->findAll(array('qe_id'=>$qandop['qeid']),'id asc'); $data[]=$qandop; $qandop=array(); } $qandop['qeid']=$q; $qandop['qetype']=$qes['type']; $qandop['opids'][]=$op[$k]; $curqeid=$q; } if(!empty($qandop)){ $qandop['ops']=$this->_op->findAll(array('qe_id'=>$qandop['qeid']),'id asc'); $data[]=$qandop; } echo json_encode($data); } function createQr($shoturl){ $qrfile='resource/upload/'.$shoturl.'.png'; $qrurl=SITEHOST.url('As','Qrcode',array('short'=>$shoturl)); QRcode::png($qrurl,$qrfile,0,10,1);//生成二维码 //file_put_contents($qrfile , file_get_contents($this->_common->downloadQRpngfromGoogle($qrurl,300,300)));//生成本地图片 return $qrfile; } } <file_sep>/const.php <?php define ('DEFAUT_TITLE',"调查问卷管理后台"); define('SERVERROOT',dirname(__FILE__) ); $httpsflag=isset($_SERVER['HTTPS'])?$_SERVER['HTTPS']:""; if(empty($httpsflag)){ $urlprefix="http://"; }else{ $urlprefix="http://"; } define('SITE',$urlprefix.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'],0,strrpos ($_SERVER['PHP_SELF'],'/')+1)); //define('SITEHOST','http://www.planinbook.com:8021'); define('SITEHOST','http://192.168.11.100'); ?><file_sep>/App/Controller/Admin.php <?php class Controller_Admin extends FLEA_Controller_Action { /** * * Enter description here ... * @var Class_Common */ var $_common; var $_admin; var $_adminid; var $_questionnaire; var $_question; var $_option; var $_answer; function __construct() { $this->_common = get_singleton ( "Class_Common" ); $this->_admin = get_singleton ( "Model_Admin" ); $this->_questionnaire = get_singleton ( "Model_Questionnaire" ); $this->_question = get_singleton ( "Model_Question" ); $this->_option = get_singleton ( "Model_Option" ); $this->_answer = get_singleton ( "Model_Answer" ); $this->_adminid = isset ( $_SESSION ['loginuserid'] ) ? $_SESSION ['loginuserid'] : ""; if(empty($_SESSION ['loginuserid'])){ $url=url("Default","Login"); redirect($url); } } //问卷列表 function actionChangePass() { $msg=''; $act=isset($_POST['act'])?$this->_common->filter($_POST['act']):''; if($act=='update'){ $data=$this->_common->filter($_POST); $old_pass=$data['old_pass']; $new_pass=$data['new_pass']; $confirm_pass=$data['confirm_pass']; if(empty($old_pass)||empty($new_pass)||empty($confirm_pass)){ $msg='请输入正确内容'; }elseif($new_pass!=$confirm_pass){ $msg='新密码确认内容不一致'; }else{ $adm=$this->_admin->findByField('id',$this->_adminid); if(md5($old_pass)!=$adm['adm_password']){ $msg='原始密码不正确'; }else{ $adm['adm_password']=md5($new_pass); $this->_admin->update($adm); $msg='密码更新成功'; } } } $this->_common->show ( array ('main' => 'admin/change_pass.tpl','msg'=>$msg) ); } //管理问卷公共信息 function actionCommonInfo(){ $msg=''; $act=isset($_POST['act'])?$this->_common->filter($_POST['act']):''; if($act=='update'){ $admin = $this->_admin->findByField('id',$this->_adminid); $data=$this->_common->filter($_POST); $info['id']=$this->_adminid; $info['complete_msg']=$data['complete_msg']; $info['sign_text']=$data['sign_text']; //签名图片 $Upload= & get_singleton ( "Service_UpLoad" ); $folder="resource/upload/signimg/"; if (! file_exists ( $folder )) { mkdir ( $folder, 0777 ); } $Upload->setDir($folder.$admin['adm_name']."/"); $oldimg=$admin['sign_img']; $img=$Upload->upload('file'); if($img['status']==1){//如果有上传图片则更新 $info['sign_img']=$img['file_path']; if(file_exists($oldimg)){ unlink($oldimg); } }else{ $info['sign_img']=$oldimg; } $this->_admin->update($info); $msg='更新成功'; } $info=$this->_admin->findByField('id',$this->_adminid); $this->_common->show ( array ('main' => 'admin/common_info.tpl','msg'=>$msg,'admin'=>$info) ); } }<file_sep>/resource/js/qa.js $(function(){ setInterval(function(){$('#time').val($('#time').val()*1+1)},1000); $('#submit').click(function(){ if($('#questionnaire_status').val()!=1){ if($('#questionnaire_status').val()==2){ alert('调查问卷已结束,您不能答题'); }else{ alert('调查问卷还没发布,您不能答题'); } return false; }else{ return true; } }); $('.anstext').blur(function(){ var qeobj=$(this).parent().parent(); var type=qeobj.find('.qetype').val(); if(type==3){ var i=qeobj.find('.anstext').index($(this)); qeobj.find('input[name^=anscontent]').eq(i).val($(this).val()); } if(type==4){ var str=''; qeobj.find('.anstext').each(function(i){ str+=$(this).val()+','; }); qeobj.find('input[name^=anscontent]').val(str.slice(0,-1)); } }); //选中高亮切换 $('input[type=radio],input[type=checkbox]').change(function(){ $('input[type=radio],input[type=checkbox]').each(function(i){ if($(this).attr('checked')){ $(this).parent().css('background-color','#d5eaff'); }else{ $(this).parent().css('background-color','#fff'); } }); }); $('#copyQurl').click(function(){ //window.clipboardData.setData("Text等等", '需要复制的信息'); //alert('复制成功'); return false; }); });
2608a92cea460e1de17447f5ab0df4cdb7265aa6
[ "JavaScript", "PHP" ]
25
PHP
liting68/planbook
74ca445b6b0f85b3f3edb2f83bd41c213b94057e
68e4ec80a37cf38b69b10c5f88cf5320e4a05ded
refs/heads/master
<file_sep># Parallel requests 'Parallel requests' is a simple HTML/CSS/JavaScript application using recent pictures feed from Flickr API. By default the (on application loading) number of pictures retrieved from Flickr API is 100 and number of parallel requests is 5. The user can change two value by selecting values from the dropdown menus on the right side of the screen. On the right side there is a active(parallel) request counter. The dropdowns are are disabled whe active request counter is biiger then 0 the requests. The application is uploaded to https://gt-parallel-requests.herokuapp.com/ ## Installation You can download or clone the application files from Github - https://github.com/cologneto/parallel-requests. Once downloaded you can simply run the index.html file into your browser. ## Usage To add the Parallel Requests module into your own project you can include parallelRequest.js from /js directory in this project. To use it just call - ParallelRequests.create(maximumNumberOfPictures, numberOfParallelRequests, wrapSelector) where maximumNumberOfPictures argument must be of data type 'number' smaller then 500, null or undefined, numberOfParallelRequests argument - must be of data type 'number' smaller then 500, null or undefined and wrapSelector must be of type 'string' or null or undefined and you must include element with class or id attribute into body. If there is no selector passed the pictures will be appended to the html documents body. Examples ParallelRequests.create(100, 5, '.wrapper'); You can call it without arguments - ParallelRequests.create() or ParallelRequests.create(100, 5) or ParallelRequests.create(100) or ParallelRequests.create(null, 5, ''); <file_sep>var ParallelRequests = (function(){ var maxPicturesRequests; var requestsCounter = 0; var parallelRequests; var photosArray; var wrapperSelector; // This application using Flickr rest API for retrieving the recent uploaded pictures function getAllPicturesLinks(url) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (this.readyState == 4 ){ if(this.status == 200){ photosArray = this.response.photos.photo; requestsCounter = parallelRequests; for (var i = 0; i < parallelRequests; i++) { getSinglePicture(photosArray[i]); } } } } xhr.open('GET', url); xhr.responseType = 'json'; xhr.send(); } // append picture to body function appendPictureToContainer(pic) { var img = document.createElement('img'); var wrapper = document.querySelector(wrapperSelector); img.src = pic; wrapper.appendChild(img); } // make a single get request for a picture function getSinglePicture(pic, con) { var pictureUrl = 'https://farm'+pic.farm+'.staticflickr.com/'+pic.server+'/'+pic.id+'_'+pic.secret+'.jpg' // setting the timeout setTimeout(function () { // // getting image as 'blob' var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if (this.readyState == 4 && this.status == 200){ // var url = window.URL || window.webkitURL; appendPictureToContainer(url.createObjectURL(this.response)); if(requestsCounter < maxPicturesRequests) { getSinglePicture(photosArray[requestsCounter]); requestsCounter++; } else { return false; } } }; xhr.open('GET', pictureUrl); xhr.responseType = 'blob'; xhr.send(); }, 1); } function create(maxPicReq, parReqCount, wrapSelector) { maxPicturesRequests = maxPicReq || 100; parallelRequests = parReqCount || 5; wrapperSelector = wrapSelector || 'body'; // Flickr URL for retrieving recently added pictures (maxPictureRequests <= 500 - API ) var url = 'https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&' + 'api_key=<KEY>&' + 'per_page=' + maxPicturesRequests + '&format=json&nojsoncallback=1'; getAllPicturesLinks(url); } return { create: create } })();
9d3c49c5c8baf69dc4746c09bbf65fff4083a048
[ "Markdown", "JavaScript" ]
2
Markdown
cologneto/parallel-requests
911046b4b983e55b2a13cbef0e78ee6553a47db1
d13c339ba25f43cb4c4c695d9e6767628698ac71
HEAD
<file_sep>var LevelData = { levelList:[ '0-1', '0-2', '0-3' ], currentLevel: 0 }; var Load = function () {}; Load.prototype.preload = function () { this.game.load.image('sheetmap', 'asset/img/sheet.png'); this.game.load.spritesheet('sheet', 'asset/img/sheet.png', 16, 16); // crisp pixel upscaling this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; this.game.scale.refresh(); this.game.scale.pageAlignHorizontally = true; this.game.scale.pageAlignVertically = true; this.game.stage.smoothed = false; // enable crisp rendering this.game.renderer.renderSession.roundPixels = true; Phaser.Canvas.setImageRenderingCrisp(this.game.canvas) PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST; //for WebGL this.game.input.gamepad.start(); }; Load.prototype.create = function () { this.game.state.start('Gameplay', true, false, LevelData.levelList[LevelData.currentLevel]); }; var Gameplay = function () { this.player = null; this.playerRunSpeed = 100; this.map = null; }; Gameplay.prototype.init = function (levelName) { this.levelName = levelName; }; Gameplay.prototype.preload = function () { this.game.load.tilemap(this.levelName, 'asset/map/' + this.levelName + '.json', undefined, Phaser.Tilemap.TILED_JSON); }; Gameplay.prototype.create = function () { this.game.physics.arcade.gravity.y = 550; this.map = this.game.add.tilemap(this.levelName); this.map.addTilesetImage('terrain', 'sheetmap', 16, 16); this.background = this.map.createLayer('background'); this.foreground = this.map.createLayer('foreground'); this.foreground.resizeWorld(); this.map.setCollisionBetween(0, 256, true, this.foreground); var playerPost = { x: 32, y: 32 }; this.goal = null; if (this.map.objects.gameplay) { this.map.objects.gameplay.forEach(function (obj) { if (obj.name === 'Player') { playerPost.x = obj.x + 16; playerPost.y = obj.y + 16; } if (obj.name === 'Goal') { this.goal = this.game.add.sprite(obj.x, obj.y, 'sheet', 61); this.game.physics.enable(this.goal, Phaser.Physics.ARCADE); this.goal.animations.add('spin', [61, 62], 8, true); this.goal.animations.play('spin'); this.goal.body.allowGravity = false; } }, this); } this.player = this.game.add.sprite(playerPost.x, playerPost.y, 'sheet', 0); this.player.animations.add('runRight', [32, 33], 8, true); this.player.animations.add('runLeft', [48, 49], 8, true); this.player.animations.add('holdRight', [34, 35], 8, true); this.player.animations.add('holdLeft', [50, 51], 8, true); this.player.anchor.set(0.5, 0.5); this.game.physics.enable(this.player, Phaser.Physics.ARCADE); this.player.body.maxVelocity.y = 150; this.player.body.setSize(8, 16); this.player.facingRight = true; this.player.tilegraphic = this.game.add.sprite(0, -24, 'sheet', 8); this.player.tilegraphic.anchor.set(0.5, 0); this.player.tilegraphic.renderable = false; this.player.addChild(this.player.tilegraphic); this.grabKey = this.game.input.keyboard.addKey(Phaser.KeyCode.C); this.grabKey.onDown.add(function () { var tl = this.map.getTile(~~(this.player.x / 16) + (this.player.facingRight ? 1 : -1), ~~(this.player.y / 16) + (this.game.input.keyboard.isDown(Phaser.KeyCode.DOWN) ? 1 : (this.game.input.keyboard.isDown(Phaser.KeyCode.UP) ? -1 : 0)), this.foreground); if (tl !== null && this.player.tilegraphic.renderable === false && (tl.index === 9 || tl.index === 10 || tl.index === 25 || tl.index === 26)) { this.player.tilegraphic.renderable = true; this.player.tilegraphic.frame = tl.index - 1; this.map.removeTile(~~(this.player.x / 16) + (this.player.facingRight ? 1 : -1), ~~(this.player.y / 16) + (this.game.input.keyboard.isDown(Phaser.KeyCode.DOWN) ? 1 : (this.game.input.keyboard.isDown(Phaser.KeyCode.UP) ? -1 : 0)), this.foreground); } else if (tl === null && this.player.tilegraphic.renderable === true) { this.player.tilegraphic.renderable = false; this.map.putTile(this.player.tilegraphic.frame + 1, ~~(this.player.x / 16) + (this.player.facingRight ? 1 : -1), ~~(this.player.y / 16) + (this.game.input.keyboard.isDown(Phaser.KeyCode.DOWN) ? 1 : (this.game.input.keyboard.isDown(Phaser.KeyCode.UP) ? -1 : 0)) , this.foreground); } }, this); }; Gameplay.prototype.update = function () { this.game.physics.arcade.collide(this.player, this.foreground); this.game.physics.arcade.overlap(this.player, this.goal, function () {}, function () { LevelData.currentLevel = (LevelData.currentLevel + 1) % LevelData.levelList.length; this.game.state.start('Gameplay', true, false, LevelData.levelList[LevelData.currentLevel]); return false; }, this); // poll keyboard keys if (this.game.input.keyboard.isDown(Phaser.KeyCode.RIGHT)) { this.player.body.velocity.x = this.playerRunSpeed; this.player.facingRight = true; } else if (this.game.input.keyboard.isDown(Phaser.KeyCode.LEFT)) { this.player.body.velocity.x = -1 * this.playerRunSpeed; this.player.facingRight = false; } else { this.player.body.velocity.x = 0; } // update animations this.player.animations.play(this.player.facingRight ? (this.player.tilegraphic.renderable ? 'holdRight' : 'runRight') : (this.player.tilegraphic.renderable ? 'holdLeft' : 'runLeft')); if (this.game.input.keyboard.isDown(Phaser.KeyCode.X) && this.player.body.blocked.down) { this.player.body.velocity.y = -200; } }; Gameplay.prototype.shutdown = function () { this.game.cache.removeTilemap(this.levelName); }; var main = function () { var game = new Phaser.Game(256, 224); game.state.add('Load', Load, false); game.state.add('Gameplay', Gameplay, false); game.state.start('Load'); };
71ab006d932935a3906d6e46c168016f3df8902b
[ "JavaScript" ]
1
JavaScript
danbolt/quirk
8461234c8ab32d05a96889bc6f512718a194dd30
68c4b4645d555d9ef0c39eb6e9a48e1747b539bf
refs/heads/master
<repo_name>syncfusion/xamarin-demos<file_sep>/Forms/XlsIO/XlsIO/Samples/ImportHtmlTable/ImportHtmlTablePage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using Xamarin.Forms; using System.Reflection; using System.IO; using SampleBrowser.Core; namespace SampleBrowser.XlsIO { /// <summary> /// This class is used to import HTML table to worksheet. /// </summary> public partial class ImportHtmlTablePage : SampleView { public ImportHtmlTablePage() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP)) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnGetInputTemplate.HorizontalOptions = LayoutOptions.Start; this.btnGetInputTemplate.VerticalOptions = LayoutOptions.Center; this.btnGetInputTemplate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGetInputTemplate.VerticalOptions = LayoutOptions.Center; } } private void BtnGetInputTemplate_Clicked(object sender, System.EventArgs e) { Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream inputStream = null; string fileName = "ImportHTMLTable.html"; string contentType = "text/html"; #if COMMONSB inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ImportHTMLTable.html"); #else inputStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ImportHTMLTable.html"); #endif MemoryStream htmlStream = new MemoryStream(); inputStream.CopyTo(htmlStream); htmlStream.Position = 0; if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save(fileName, contentType, htmlStream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save(fileName, contentType, htmlStream); } } private void BtnGenerate_Clicked(object sender, System.EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; #if COMMONSB Stream stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ImportHTMLTable.html"); #else Stream stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ImportHTMLTable.html"); #endif IWorkbook workbook = application.Workbooks.Create(1); workbook.Version = ExcelVersion.Excel2016; IWorksheet worksheet = workbook.Worksheets[0]; MemoryStream outputStream = new MemoryStream(); string fileName = "ImportHTMLTable.xlsx"; string contentType = "application/msexcel"; worksheet.ImportHtmlTable(stream, 1, 1); worksheet.UsedRange.AutofitColumns(); worksheet.UsedRange.AutofitRows(); workbook.SaveAs(outputStream); outputStream.Position = 0; if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save(fileName, contentType, outputStream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save(fileName, contentType, outputStream); } } } }<file_sep>/Android/SampleBrowser/Samples/Schedule/ScheduleCustomHeader.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Widget; using Android.Views; using Android.Content; using Android.Graphics; using Android.App; using Android.OS; using System.Collections.ObjectModel; using System.Reflection.Emit; using Android.Media; using Android.Util; namespace SampleBrowser { public class ScheduleCustomHeader : IDisposable { public Context Context { get; set; } public TextView MonthText { get; set; } private LinearLayout mainLayout, leftmainLayout, mainheaderLayout; private LinearLayout optionLinearlayout, monthTextlayout, plusLinearlayout, calendarLinearlayout; private DisplayMetrics density; public TableLayout HeaderLayout { get; set; } public ScheduleCustomHeader(Context context) { Context = context; HeaderLayout = new TableLayout(context); density = Context.Resources.DisplayMetrics; HeaderLayout.SetBackgroundColor(Color.Argb(255, 214, 214, 214)); HeaderLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, density.HeightPixels / 14); AddHeaderViews(); } internal ImageView ScheduleOption { get; set; } internal ImageView SchedulePlus { get; set; } internal ImageView ScheduleCalendar { get; set; } private void AddHeaderViews() { mainLayout = new LinearLayout(Context); int mainLayoutWidth = 0; if (density.Density > 2) { mainLayoutWidth = (int)(density.WidthPixels / 1.3); } else { mainLayoutWidth = (int)(density.WidthPixels / 1.4); } mainLayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(mainLayoutWidth, density.HeightPixels / 14)); mainLayout.Orientation = Android.Widget.Orientation.Horizontal; leftmainLayout = new LinearLayout(Context); leftmainLayout.SetGravity(GravityFlags.Right); leftmainLayout.Orientation = Android.Widget.Orientation.Horizontal; mainheaderLayout = new LinearLayout(Context); mainheaderLayout.Orientation = Android.Widget.Orientation.Horizontal; optionLinearlayout = new LinearLayout(Context); optionLinearlayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(100, density.HeightPixels / 14)); ScheduleOption = new ImageView(Context); ScheduleOption.SetBackgroundResource(Resource.Drawable.scheduleOption); optionLinearlayout.AddView(ScheduleOption); mainLayout.AddView(optionLinearlayout); monthTextlayout = new LinearLayout(Context); monthTextlayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(density.WidthPixels / 2, density.HeightPixels / 14)); MonthText = new TextView(Context); MonthText.SetTextColor(Color.Black); if (IsTabletDevice(Context)) { monthTextlayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(density.WidthPixels / 2, density.HeightPixels / 14)); monthTextlayout.SetGravity(GravityFlags.Center); MonthText.SetPadding(10, 20, 0, 0); } if (density.Density > 2) { MonthText.SetPadding(10, 20, 0, 0); } MonthText.Gravity = GravityFlags.Fill; MonthText.SetMinimumHeight(80); MonthText.SetTypeface(Typeface.DefaultBold, TypefaceStyle.Bold); MonthText.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); MonthText.TextSize = 20; MonthText.Text = "August 2016"; monthTextlayout.AddView(MonthText); mainLayout.AddView(monthTextlayout); plusLinearlayout = new LinearLayout(Context); if (density.Density > 2) { plusLinearlayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(120, density.HeightPixels / 13)); } else if (density.Density < 2 && density.WidthPixels < 600) { plusLinearlayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(70, density.HeightPixels / 13)); } else { plusLinearlayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(90, density.HeightPixels / 13)); } SchedulePlus = new ImageView(Context); SchedulePlus.SetBackgroundResource(Resource.Drawable.schedulePlus); plusLinearlayout.AddView(SchedulePlus); leftmainLayout.AddView(plusLinearlayout); calendarLinearlayout = new LinearLayout(Context); if (density.Density > 2) { calendarLinearlayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(120, density.HeightPixels / 13)); } else if (density.Density < 2 && density.WidthPixels < 600) { calendarLinearlayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(70, density.HeightPixels / 13)); } else { calendarLinearlayout.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams(90, density.HeightPixels / 13)); } ScheduleCalendar = new ImageView(Context); ScheduleCalendar.SetBackgroundResource(Resource.Drawable.scheduleCalendar); calendarLinearlayout.AddView(ScheduleCalendar); leftmainLayout.AddView(calendarLinearlayout); leftmainLayout.SetGravity(GravityFlags.Left); mainheaderLayout.AddView(mainLayout); mainheaderLayout.AddView(leftmainLayout); HeaderLayout.AddView(mainheaderLayout); } public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = Java.Lang.Math.Sqrt(Math.Pow(screenWidth, 2) + Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } public void Dispose() { if (mainLayout != null) { mainLayout.Dispose(); mainLayout = null; } if (leftmainLayout != null) { leftmainLayout.Dispose(); leftmainLayout = null; } if (mainheaderLayout != null) { mainheaderLayout.Dispose(); mainheaderLayout = null; } if (optionLinearlayout != null) { optionLinearlayout.Dispose(); optionLinearlayout = null; } if (monthTextlayout != null) { monthTextlayout.Dispose(); monthTextlayout = null; } if (plusLinearlayout != null) { plusLinearlayout.Dispose(); plusLinearlayout = null; } if (calendarLinearlayout != null) { calendarLinearlayout.Dispose(); calendarLinearlayout = null; } } } } <file_sep>/Forms/Chart/Chart/Samples/LogarithmicAxis/LogarithmicAxisViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class LogarithmicAxisViewModel { public ObservableCollection<ChartDataModel> LogarithmicData { get; set; } public LogarithmicAxisViewModel() { LogarithmicData = new ObservableCollection<ChartDataModel> { new ChartDataModel("1995", 80 ), new ChartDataModel("1996", 200 ), new ChartDataModel("1997", 400 ), new ChartDataModel("1998", 600 ), new ChartDataModel("1999", 700 ), new ChartDataModel("2000", 1400 ), new ChartDataModel("2001", 2000 ), new ChartDataModel("2002", 4000 ), new ChartDataModel("2003", 6000 ), new ChartDataModel("2004", 8000 ), new ChartDataModel("2005", 11000) }; } } } <file_sep>/Forms/PdfViewer/PdfViewer.UWP/Renderer/AlertViewUWP.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.SfPdfViewer.UWP; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel.Core; using Windows.UI.Core; using Windows.UI.Popups; using Xamarin.Forms; [assembly: Dependency(typeof(AlertViewUWP))] namespace SampleBrowser.SfPdfViewer.UWP { class AlertViewUWP : IAlertView { public void Show(string description) { CoreApplication.MainView?.CoreWindow?.Dispatcher?.RunAsync(CoreDispatcherPriority.Normal, async () => { MessageDialog msg = new MessageDialog(description); await msg.ShowAsync(); }); } } } <file_sep>/Android/SampleBrowser/Samples/PDF/GettingStartedPDF.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.Pdf; using Syncfusion.Pdf.Interactive; using System.IO; using Syncfusion.Pdf.Graphics; using Syncfusion.Drawing; using System.Reflection; namespace SampleBrowser { public partial class GettingStartedPDF : SamplePage { private Context m_context; PdfDocument doc; PdfPage page; Syncfusion.Drawing.Color gray = Syncfusion.Drawing.Color.FromArgb(255, 77, 77, 77); Syncfusion.Drawing.Color black = Syncfusion.Drawing.Color.FromArgb(255, 0, 0, 0); Syncfusion.Drawing.Color white = Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255); Syncfusion.Drawing.Color violet = Syncfusion.Drawing.Color.FromArgb(255, 151, 108, 174); public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to create a simple PDF document with text and images."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate PDF"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { doc = new PdfDocument(); doc.PageSettings.Margins.All = 0; page = doc.Pages.Add(); PdfGraphics g = page.Graphics; PdfFont headerFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 35); PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16); g.DrawRectangle(new PdfSolidBrush(gray), new RectangleF(0, 0, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height)); g.DrawRectangle(new PdfSolidBrush(black), new RectangleF(0, 0, page.Graphics.ClientSize.Width, 130)); g.DrawRectangle(new PdfSolidBrush(white), new RectangleF(0, 400, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height - 450)); g.DrawString("Syncfusion", headerFont, new PdfSolidBrush(violet), new PointF(10, 20)); g.DrawRectangle(new PdfSolidBrush(violet), new RectangleF(10, 63, 155, 35)); g.DrawString("File Formats", subHeadingFont, new PdfSolidBrush(black), new PointF(45, 70)); PdfLayoutResult result = HeaderPoints("Optimized for usage in a server environment where spread and low memory usage in critical.", 15); result = HeaderPoints("Proven, reliable platform thousands of users over the past 10 years.", result.Bounds.Bottom + 15); result = HeaderPoints("Microsoft Excel, Word, Presentation, PDF and PDF Viewer.", result.Bounds.Bottom + 15); result = HeaderPoints("Why start from scratch? Rely on our dependable solution frameworks.", result.Bounds.Bottom + 15); result = BodyContent("Deployment-ready framework tailored to your needs.", result.Bounds.Bottom + 45); result = BodyContent("Enable your applications to read and write file formats documents easily.", result.Bounds.Bottom + 25); result = BodyContent("Solutions available for web, desktop, and mobile applications.", result.Bounds.Bottom + 25); result = BodyContent("Backed by our end-to-end product maintenance infrastructure.", result.Bounds.Bottom + 25); result = BodyContent("The quickest path from concept to delivery.", result.Bounds.Bottom + 25); PdfPen redPen = new PdfPen(PdfBrushes.Red, 2); g.DrawLine(redPen, new PointF(40, result.Bounds.Bottom + 92), new PointF(40, result.Bounds.Bottom + 145)); float headerBulletsXposition = 40; PdfTextElement txtElement = new PdfTextElement("The Experts"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 90, 450, 200)); PdfPen violetPen = new PdfPen(PdfBrushes.Violet, 2); g.DrawLine(violetPen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 92), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 145)); txtElement = new PdfTextElement("Accurate Estimates"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 90, 450, 200)); txtElement = new PdfTextElement("A substantial number of .NET reporting applications use our frameworks."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200)); txtElement = new PdfTextElement("Given our expertise, you can expect estimates to be accurate."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200)); PdfPen greenPen = new PdfPen(PdfBrushes.Green, 2); g.DrawLine(greenPen, new PointF(40, result.Bounds.Bottom + 32), new PointF(40, result.Bounds.Bottom + 85)); txtElement = new PdfTextElement("No-Hassle Licensing"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 30, 450, 200)); PdfPen bluePen = new PdfPen(PdfBrushes.Blue, 2); g.DrawLine(bluePen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 32), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 85)); txtElement = new PdfTextElement("About Syncfusion"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 30, 450, 200)); txtElement = new PdfTextElement("No royalties, run time, or server deployment fees means no surprises."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200)); txtElement = new PdfTextElement("Syncfusion offers over 1,000 components and frameworks for mobile, web, and desktop development."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200)); Stream imgStream = typeof(GettingStartedPDF).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Xamarin_bannerEdit.jpg"); g.DrawImage(PdfImage.FromStream(imgStream), 180, 630, 280, 150); g.DrawString("All trademarks mentioned belong to their owners.", new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic), PdfBrushes.White, new PointF(10, g.ClientSize.Height - 30)); PdfTextWebLink linkAnnot = new PdfTextWebLink(); linkAnnot.Url = "http://www.syncfusion.com"; linkAnnot.Text = "www.syncfusion.com"; linkAnnot.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic); linkAnnot.Brush = PdfBrushes.White; linkAnnot.DrawTextWebLink(page, new PointF(g.ClientSize.Width - 100, g.ClientSize.Height - 30)); MemoryStream stream = new MemoryStream(); doc.Save(stream); doc.Close(true); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("GettingStarted.pdf", "application/pdf", stream, m_context); } } private PdfLayoutResult BodyContent(string text, float yPosition) { float headerBulletsXposition = 35; PdfTextElement txtElement = new PdfTextElement("3"); txtElement.Font = new PdfStandardFont(PdfFontFamily.ZapfDingbats, 16); txtElement.Brush = new PdfSolidBrush(violet); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; txtElement.Draw(page, new RectangleF(headerBulletsXposition, yPosition, 320, 100)); txtElement = new PdfTextElement(text); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 17); txtElement.Brush = new PdfSolidBrush(white); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; PdfLayoutResult result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 25, yPosition, 450, 130)); return result; } private PdfLayoutResult HeaderPoints(string text, float yPosition) { float headerBulletsXposition = 220; PdfTextElement txtElement = new PdfTextElement("l"); txtElement.Font = new PdfStandardFont(PdfFontFamily.ZapfDingbats, 10); txtElement.Brush = new PdfSolidBrush(violet); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; txtElement.Draw(page, new RectangleF(headerBulletsXposition, yPosition, 300, 100)); txtElement = new PdfTextElement(text); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11); txtElement.Brush = new PdfSolidBrush(white); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; PdfLayoutResult result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 20, yPosition, 320, 100)); return result; } } }<file_sep>/Android/SampleBrowser/Samples/SfMaskedEdit/SfMaskedEditText_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Syncfusion.Android.MaskedEdit; using System; using System.Globalization; namespace SampleBrowser { public class SfMaskedEditText_Mobile { #region Fields SfMaskedEdit sfToAccount, sfDesc, amountMask, emailMask, phoneMask; TextView erroToAccount, errotextAmount, errotextEmail, errotextPhone; Context context; LinearLayout propertylayout; InputValidationMode validationMask; CultureInfo currentCulute; /// <summary> /// Contain the close button visibility details /// </summary> ClearButtonVisibilityMode clearButtonVisibility; bool hidePrompt; char currentPrompt; AlertDialog.Builder resultsDialog; SfMaskedEditProperties maskProperties; #endregion public SfMaskedEditText_Mobile() { maskProperties = new SfMaskedEditProperties(this); } #region Properties internal InputValidationMode ValidationMask { get { return validationMask; } set { validationMask = value; } } internal char CurrentPrompt { get { return currentPrompt; } set { currentPrompt = value; } } internal CultureInfo CurrentCulture { get { return currentCulute; } set { currentCulute = value; } } /// <summary> /// Gets or Set the close button visibility. /// </summary> internal ClearButtonVisibilityMode ClearButtonVisibility { get { return clearButtonVisibility; } set { clearButtonVisibility = value; } } internal bool HidePrompt { get { return hidePrompt; } set { hidePrompt = value; } } #endregion public View GetSampleContent(Context con) { ScrollView scroll = new ScrollView(con); bool isTablet = SfMaskedEditText.IsTabletDevice(con); LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(12, 12, 12, 12); TextView headLabel = new TextView(con); headLabel.TextSize = 30; headLabel.SetTextColor(Color.ParseColor("#262626")); headLabel.Typeface = Typeface.DefaultBold; headLabel.Text = "Funds Transfer"; linear.AddView(headLabel); TextView fundTransferLabelSpacing = new TextView(con); fundTransferLabelSpacing.SetHeight(40); linear.AddView(fundTransferLabelSpacing); TextView textToAccount = new TextView(con); textToAccount.SetTextColor(Color.ParseColor("#6d6d72")); textToAccount.TextSize = 16; textToAccount.Typeface = Typeface.Default; textToAccount.Text = "To Account"; textToAccount.SetPadding(0, 0, 0, 10); linear.AddView(textToAccount); sfToAccount = new SfMaskedEdit(con); sfToAccount.Mask = "0000 0000 0000 0000"; sfToAccount.Gravity = GravityFlags.Start; sfToAccount.ValidationMode = InputValidationMode.KeyPress; sfToAccount.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfToAccount.Hint = "1234 1234 1234 1234"; sfToAccount.SetHintTextColor(Color.LightGray); linear.AddView(sfToAccount); erroToAccount = new TextView(con); erroToAccount.SetTextColor(Color.Red); erroToAccount.TextSize = 12; erroToAccount.Typeface = Typeface.Default; linear.AddView(erroToAccount); TextView textDesc = new TextView(con); textDesc.Text = "Description"; textDesc.Typeface = Typeface.Default; textDesc.SetPadding(0, 30, 0, 10); textDesc.TextSize = 16; linear.AddView(textDesc); sfDesc = new SfMaskedEdit(con); sfDesc.Mask = ""; sfDesc.Gravity = GravityFlags.Start; sfDesc.ValidationMode = InputValidationMode.KeyPress; sfDesc.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfDesc.Hint = "Enter description"; sfDesc.SetHintTextColor(Color.LightGray); linear.AddView(sfDesc); TextView textAmount = new TextView(con); textAmount.Text = "Amount"; textAmount.Typeface = Typeface.Default; textAmount.SetPadding(0, 30, 0, 10); textAmount.TextSize = 16; linear.AddView(textAmount); amountMask = new SfMaskedEdit(con); amountMask.Mask = "$ 0,000.00"; amountMask.Gravity = GravityFlags.Start; amountMask.ValidationMode = InputValidationMode.KeyPress; amountMask.ValueMaskFormat = MaskFormat.IncludePromptAndLiterals; amountMask.Hint = "$ 3,874.00"; amountMask.SetHintTextColor(Color.LightGray); linear.AddView(amountMask); errotextAmount = new TextView(con); errotextAmount.SetTextColor(Color.Red); errotextAmount.TextSize = 12; errotextAmount.Typeface = Typeface.Default; linear.AddView(errotextAmount); TextView textEmail = new TextView(con); textEmail.Text = "Email ID"; textEmail.Typeface = Typeface.Default; textEmail.SetPadding(0, 30, 0, 10); textEmail.TextSize = 16; linear.AddView(textEmail); emailMask = new SfMaskedEdit(con); emailMask.Mask = @"\w+@\w+\.\w+"; emailMask.MaskType = MaskType.RegEx; emailMask.Gravity = GravityFlags.Start; emailMask.ValidationMode = InputValidationMode.KeyPress; emailMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; emailMask.Hint = "<EMAIL>"; emailMask.SetHintTextColor(Color.LightGray); linear.AddView(emailMask); errotextEmail = new TextView(con); errotextEmail.SetTextColor(Color.Red); errotextEmail.TextSize = 12; errotextEmail.Typeface = Typeface.Default; linear.AddView(errotextEmail); TextView textPhone = new TextView(con); textPhone.Text = "Mobile Number "; textPhone.Typeface = Typeface.Default; textPhone.SetPadding(0, 30, 0, 10); textPhone.TextSize = 16; linear.AddView(textPhone); phoneMask = new SfMaskedEdit(con); phoneMask.Mask = "+1 000 000 0000"; phoneMask.Gravity = GravityFlags.Start; phoneMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; phoneMask.ValidationMode = InputValidationMode.KeyPress; phoneMask.Hint = "+1 323 339 3392"; phoneMask.SetHintTextColor(Color.LightGray); linear.AddView(phoneMask); errotextPhone = new TextView(con); errotextPhone.SetTextColor(Color.Red); errotextPhone.TextSize = 12; errotextPhone.Typeface = Typeface.Default; linear.AddView(errotextPhone); TextView searchButtonSpacing = new TextView(con); searchButtonSpacing.SetHeight(30); Button searchButton = new Button(con); searchButton.SetWidth(ActionBar.LayoutParams.MatchParent); searchButton.SetHeight(40); searchButton.Text = "TRANSFER MONEY"; searchButton.SetTextColor(Color.White); searchButton.SetBackgroundColor(Color.Gray); searchButton.Click += (object sender, EventArgs e) => { if (string.IsNullOrEmpty(sfToAccount.Text) || string.IsNullOrEmpty(sfDesc.Text) || string.IsNullOrEmpty(amountMask.Text) || string.IsNullOrEmpty(emailMask.Text) || string.IsNullOrEmpty(phoneMask.Text)) { resultsDialog.SetMessage("Please fill all the required data!"); } else if((sfToAccount.HasError || sfDesc.HasError || amountMask.HasError || emailMask.HasError || phoneMask.HasError)) { resultsDialog.SetMessage("Please enter valid details"); } else { resultsDialog.SetMessage(string.Format("Amount of {0} has been transferred successfully!", amountMask.Value)); sfToAccount.Value = string.Empty; sfDesc.Value = string.Empty; amountMask.Value = string.Empty; emailMask.Value = string.Empty; phoneMask.Value = string.Empty; } resultsDialog.Create().Show(); }; linear.AddView(searchButtonSpacing); linear.AddView(searchButton); sfToAccount.ValueChanged += SfToAccount_ValueChanged; sfToAccount.MaskInputRejected += SfToAccount_MaskInputRejected; amountMask.ValueChanged += AmountMask_ValueChanged; amountMask.MaskInputRejected += AmountMask_MaskInputRejected; emailMask.ValueChanged += EmailMask_ValueChanged; emailMask.MaskInputRejected += EmailMask_MaskInputRejected; phoneMask.ValueChanged += PhoneMask_ValueChanged; phoneMask.MaskInputRejected += PhoneMask_MaskInputRejected; //results dialog resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetTitle("Status"); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); scroll.AddView(linear); return scroll; } private void PhoneMask_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { errotextPhone.Text = GetRejectionHintText(e.RejectionHint); } private void PhoneMask_ValueChanged(object sender, ValueChangedEventArgs e) { errotextPhone.Text = ""; } private void EmailMask_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { errotextEmail.Text = GetRejectionHintText(e.RejectionHint); } private void EmailMask_ValueChanged(object sender, ValueChangedEventArgs e) { errotextEmail.Text = ""; } private void AmountMask_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { errotextAmount.Text = GetRejectionHintText(e.RejectionHint); } private void AmountMask_ValueChanged(object sender, ValueChangedEventArgs e) { errotextAmount.Text = ""; } private void SfToAccount_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { erroToAccount.Text = GetRejectionHintText(e.RejectionHint); } private void SfToAccount_ValueChanged(object sender, ValueChangedEventArgs e) { erroToAccount.Text = ""; } private string GetRejectionHintText(MaskedTextResultHint hint) { string hintText = string.Empty; switch (hint) { case MaskedTextResultHint.AlphanumericCharacterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.DigitExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.LetterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.SignedDigitExpected: hintText = "Invalid character!"; break; //case MaskedTextResultHint.UnavailableEditPosition: // hintText = "Invalid typed character!"; // break; } return hintText; } public View GetPropertyWindowLayout(Context context1) { bool isTablet = SfMaskedEditText.IsTabletDevice(context1); LinearLayout gridLinearLayout = null; context = context1; if (isTablet) { gridLinearLayout = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Vertical }; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent); layoutParams.TopMargin = 25; gridLinearLayout.LayoutParameters = layoutParams; gridLinearLayout.SetBackgroundResource(Resource.Drawable.LinearLayout_Border); } propertylayout = new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; maskProperties.ValidationLayout(context, propertylayout, true); maskProperties.CultureLayout(context, propertylayout, true); maskProperties.CloseButtonVisibilityLayout(context, propertylayout, true); maskProperties.HideLayout(context, propertylayout, true); maskProperties.PromptLayout(context, propertylayout, true); if (isTablet) { gridLinearLayout.AddView(propertylayout); return gridLinearLayout; } else return propertylayout; } public void OnApplyChanges() { sfToAccount.HidePromptOnLeave = hidePrompt; sfToAccount.ValidationMode = validationMask; sfToAccount.PromptChar = currentPrompt; sfToAccount.Culture = currentCulute; sfToAccount.ClearButtonVisibility = clearButtonVisibility; sfDesc.HidePromptOnLeave = hidePrompt; sfDesc.ValidationMode = validationMask; sfDesc.PromptChar = currentPrompt; sfDesc.Culture = currentCulute; sfDesc.ClearButtonVisibility = clearButtonVisibility; amountMask.HidePromptOnLeave = hidePrompt; amountMask.ValidationMode = validationMask; amountMask.Culture = currentCulute; amountMask.PromptChar = currentPrompt; amountMask.ClearButtonVisibility = clearButtonVisibility; emailMask.HidePromptOnLeave = hidePrompt; emailMask.ValidationMode = validationMask; emailMask.PromptChar = currentPrompt; emailMask.Culture = currentCulute; emailMask.ClearButtonVisibility = clearButtonVisibility; phoneMask.HidePromptOnLeave = hidePrompt; phoneMask.ValidationMode = validationMask; phoneMask.PromptChar = currentPrompt; phoneMask.ClearButtonVisibility = clearButtonVisibility; phoneMask.Culture = currentCulute; } } }<file_sep>/iOS/SampleBrowser/Samples/DataGrid/Model/ProductRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class ProductRepository { public ProductRepository () { } #region private variables private Random random = new Random (); #endregion #region GetOrderDetails public ObservableCollection<Products> GetProductDetails(int count) { ObservableCollection<Products> productDetails = new ObservableCollection<Products>(); for (int i = 1; i <= count; i++) { var ord = new Products () { SupplierID = i, ProductID = ProductID [random.Next (15)], ProductName = ProductNames [random.Next (15)], Quantity = random.Next (1, 20), UnitPrice = random.Next (30, 200), UnitsInStock = random.Next (3, 12), }; ord.Discount = ord.Quantity + "%"; productDetails.Add (ord); } return productDetails; } #endregion #region MainGrid DataSource string[] ProductNames = new string[] { "Mutton", "Syrup", "Crab Meat", "Pierrot", "Tigers", "Chai", "Chang", "Chartreuse", "Cajun", "Gumb", "Chocolate", "Blaye", "Gravad lax", "Filo Mix", "Geitost", "Flotemysost", "Ikura", "Longlife Tofu", "Maxilaku", "Mishi", "<NAME>", "Coffee", "Konbu", "<NAME>", "Pavlova", "Cabrales" }; int[] ProductID = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; #endregion } } <file_sep>/Android/SampleBrowser/Samples/PullToRefresh/ListView/Inbox.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public class Mail { #region Properties public string Sender { get; set; } public string Subject { get; set; } public string Details { get; set; } public Color BackgroundColor { get; set; } #endregion } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Model/CellTemplateModelRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CellTemplateModelRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class Use for store the Item values /// </summary> public class CellTemplateModelRepository { /// <summary> /// Initializes a new instance of the CellTemplateModelRepository class. /// </summary> public CellTemplateModelRepository() { } /// <summary> /// Used to generates the Items source. /// </summary> /// <returns>returns generates items</returns> public List<CellTemplateModel> GetEmployeeDetails() { List<CellTemplateModel> employeeDetails = new List<CellTemplateModel>(); var assembly = Assembly.GetAssembly(this.GetType()); employeeDetails.Add(new CellTemplateModel() { Name = "Nancy", Designation = "Sales Representative", DateOfBirth = new DateTime(1948, 8, 12), About = "Education includes a BA in psychology from Colorado State University in 1970. Nancy is a member of Toastmasters International.", Country = "USA", EmployeeID = 4563, Telephone = "(206) 555 -9857", Image = "People_Circle1.png", }); employeeDetails.Add(new CellTemplateModel() { Name = "Andrea", Designation = "Vice President", DateOfBirth = new DateTime(1952, 2, 19), About = "Andrea received her Ph.D. in international marketing in 1981. She joined the company as a sales representative in March 1993.", Country = "USA", EmployeeID = 4362, Telephone = "(206) 555 -9482", Image = "People_Circle2.png", }); employeeDetails.Add(new CellTemplateModel() { Name = "Janet", Designation = "Sales Representative", DateOfBirth = new DateTime(1963, 8, 30), Country = "USA", EmployeeID = 4134, About = "Janet has a BS degree in chemistry from Boston College (1984). Janet was hired as a sales associate in 1991 and promoted to sales representative in February 1992.", Telephone = "(206) 555 -9356", Image = "People_Circle3.png", }); employeeDetails.Add(new CellTemplateModel() { Name = "Margaret", Designation = "Sales Representative", DateOfBirth = new DateTime(1937, 9, 19), Country = "USA", EmployeeID = 4834, About = "Margaret holds a BA in English literature from Concordia College (1958). She was assigned to the London office temporarily 1992.", Telephone = "(206) 555 -4766", Image = "People_Circle16.png" }); employeeDetails.Add(new CellTemplateModel() { Name = "Steven", Designation = "Sales Manager", DateOfBirth = new DateTime(1955, 4, 3), Country = "USA", EmployeeID = 4267, About = "<NAME> graduated with a BSC degree in 1976. He spent 6 months in an orientation program at the Seattle office and then returned to London.", Telephone = "(206) 555 -4567", Image = "People_Circle8.png" }); employeeDetails.Add(new CellTemplateModel() { Name = "Michale", Designation = "Sales Representative", DateOfBirth = new DateTime(1963, 7, 2), Country = "USA", EmployeeID = 4553, About = "Michale is a graduate of Sussex University (MA, economics, 1983). She has also taken the course Multi-Cultural Selling for the Sales Professional.", Telephone = "(206) 555 -7777", Image = "People_Circle12.png" }); employeeDetails.Add(new CellTemplateModel() { Name = "Robert", Designation = "Sales Representative", DateOfBirth = new DateTime(1960, 5, 27), Country = "USA", EmployeeID = 4423, About = "<NAME> completing his degree in English at the University of Michigan in 1992. After completing a course, he was transferred to the London office in March 1993.", Telephone = "(206) 555 -7856", Image = "People_Circle14.png" }); employeeDetails.Add(new CellTemplateModel() { Name = "Laura", Designation = "Inside Sales Coordinator", DateOfBirth = new DateTime(1958, 9, 1), Country = "Seattle", EmployeeID = 4265, About = "Laura received a BA in psychology from the University of Washington. She has also completed a course in business French.", Telephone = "(206) 555 -1189", Image = "People_Circle9.png" }); employeeDetails.Add(new CellTemplateModel() { Name = "Anne", Designation = "Sales Representative", DateOfBirth = new DateTime(1966, 1, 27), Country = "USA", EmployeeID = 3563, About = "Anne has a BA degree in English from St. Lawrence College. She has also completed a course in business French.", Telephone = "(206) 555 -7856", Image = "People_Circle10.png" }); return employeeDetails; } } } <file_sep>/Android/SampleBrowser/Samples/PullToRefresh/ListView/ListViewInPullToRefresh.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Syncfusion.SfPullToRefresh; using System.Collections.ObjectModel; using System.Threading.Tasks; namespace SampleBrowser { public class ListViewInPullToRefresh : SamplePage { SfPullToRefresh pullToRefresh; ListView listView; CustomBaseAdapter adapter; InboxRepositiory repository; public ListViewInPullToRefresh() { } public override View GetSampleContent(Context context) { pullToRefresh = new SfPullToRefresh(context); pullToRefresh.TransitionType = TransitionType.Push; pullToRefresh.Refreshing += Pull_Refreshing; listView = new ListView(context); repository = new InboxRepositiory(); adapter = new CustomBaseAdapter((Activity)context, repository.InboxItems); listView.Adapter = adapter; pullToRefresh.PullableContent = listView; return pullToRefresh; } private async void Pull_Refreshing(object sender, RefreshingEventArgs e) { await Task.Delay(3000); repository.RefreshItemSource(); adapter.NotifyDataSetChanged(); e.Refreshed = true; } public override View GetPropertyWindowLayout(Context context) { FrameLayout propertyLayout = new FrameLayout(context); LinearLayout container = new LinearLayout(context); container.Orientation = Orientation.Vertical; container.SetBackgroundColor(Color.White); container.SetPadding(15, 15, 15, 20); TextView transitiontype = new TextView(context); transitiontype.Text = "Tranisition Type"; transitiontype.TextSize = 20; transitiontype.SetPadding(0, 0, 0, 10); transitiontype.SetTextColor(Color.Black); Spinner transitionTypeSpinner = new Spinner(context, SpinnerMode.Dialog); transitionTypeSpinner.SetMinimumHeight(60); transitionTypeSpinner.SetBackgroundColor(Color.Gray); transitionTypeSpinner.DropDownWidth = 600; transitionTypeSpinner.SetPadding(10, 10, 0, 10); transitionTypeSpinner.SetGravity(GravityFlags.CenterHorizontal); container.AddView(transitiontype); container.AddView(transitionTypeSpinner); List<String> list = new List<String>(); list.Add("SlideOnTop"); list.Add("Push"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, list); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); transitionTypeSpinner.Adapter = dataAdapter; transitionTypeSpinner.ItemSelected += transitionTypeSpinner_ItemSelected; if (pullToRefresh.TransitionType == TransitionType.SlideOnTop) transitionTypeSpinner.SetSelection(0); else transitionTypeSpinner.SetSelection(1); propertyLayout.AddView(container); return propertyLayout; } void transitionTypeSpinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; String selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); if (pullToRefresh != null) { if (selectedItem.Equals("SlideOnTop")) { pullToRefresh.TransitionType = TransitionType.SlideOnTop; pullToRefresh.RefreshContentThreshold = 0; } else if (selectedItem.Equals("Push")) { pullToRefresh.TransitionType = TransitionType.Push; pullToRefresh.RefreshContentThreshold = 25; } } } public override void Destroy() { pullToRefresh.Refreshing -= Pull_Refreshing; pullToRefresh.Dispose(); pullToRefresh = null; } } }<file_sep>/Forms/TreeView/TreeView/Samples/AutoFitContent/Helper/Converters.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.TreeView.Engine; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return "Just now"; TimeSpan timeSpan = DateTime.Now.Subtract((DateTime)value); if (timeSpan.Days == 0) { if (timeSpan.Hours == 0) { if (timeSpan.Minutes < 5) return "Just now"; else return timeSpan.Minutes + " mins before"; } else return timeSpan.Hours + " hour" + ((timeSpan.Hours == 1) ? "" : "s") + " ago"; } else return timeSpan.Days + " day" + ((timeSpan.Days == 1) ? "" : "s") + " ago"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [Preserve(AllMembers = true)] public class RepliesTextConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var isExpand= (bool)value; return (isExpand ? "Hide " : "View "); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [Preserve(AllMembers = true)] public class RepliesCountConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var replies = (ObservableCollection<Reply>)value; return " " + (replies.Count > 0 ? replies.Count : 0) + " replies"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Calculate/CalcQuickCalculation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using CoreGraphics; using System.Collections.ObjectModel; using CoreAnimation; using SampleBrowser; using Foundation; using Syncfusion.Calculate; namespace SampleBrowser { public partial class CalcQuickCalculation : SampleView { #region Fields CalcQuickView calcQuickView; #endregion #region Constructor public CalcQuickCalculation () { calcQuickView = new CalcQuickView (); this.AddSubview (calcQuickView); } #endregion #region Methods public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } protected override void Dispose (bool disposing) { calcQuickView.Dispose (); base.Dispose (disposing); } #endregion } public class CalcQuickView : UIScrollView { #region Fields CalcQuickBase calcQuickBase; UITextField editTextA; UITextField editTextB; UITextField editTextC; UILabel titleLabel; UILabel expressionTitle; UILabel descripLabel; UILabel expression1; UILabel expression2; UILabel expression3; UILabel result1; UILabel result2; UILabel result3; UILabel textA; UILabel textB; UILabel textC; CALayer layer1; CALayer layer2; CALayer layer3; UIButton calculateButton; NSObject showNotification; NSObject hideNotification; #endregion #region Constructor public CalcQuickView () { InitializeCalcQuick (); CreateCalcQuickDesign (); RegisterForKeyboardNotifications (); } #endregion #region Methods public override void LayoutSubviews () { this.ContentSize = new CGSize (Frame.Width, 550); var width = Frame.Width - 20; var height = Frame.Height; titleLabel.Frame = new CGRect (5, 15, width, 25); descripLabel.Frame = new CGRect (5, 45, width, 30); textA.Frame = new CGRect (5, 70, width / 2 , 40); editTextA.Frame = new CGRect ((width / 2) + 5, 70, width / 2, 40); textB.Frame = new CGRect (5, 110, width / 2 , 40); editTextB.Frame = new CGRect ((width / 2) + 5, 110, width / 2, 40); textC.Frame = new CGRect (5, 150, width / 2 , 40); editTextC.Frame = new CGRect ((width / 2) + 5, 150, width / 2, 40); calculateButton.Frame = new CGRect (5, 200, width, 30); expressionTitle.Frame = new CGRect (5, 240, width, 30); expression1.Frame = new CGRect (5, 270, width / 2, 40); result1.Frame = new CGRect ((width / 2) + 5, 270, width / 2, 40); layer1.Frame = new CGRect (result1.Bounds.Left, result1.Bounds.Bottom - 5, result1.Bounds.Right, 1); expression2.Frame = new CGRect (5, 310, width / 2, 40); result2.Frame = new CGRect ((width / 2) + 5, 310, width / 2, 40); layer2.Frame = new CGRect (result2.Bounds.Left, result2.Bounds.Bottom - 5, result2.Bounds.Right, 1); expression3.Frame = new CGRect (5, 350, width / 2, 40); result3.Frame = new CGRect ((width / 2) + 5, 350, width / 2, 40); layer3.Frame = new CGRect (result3.Bounds.Left, result3.Bounds.Bottom - 5, result3.Bounds.Right, 1); base.LayoutSubviews (); } private void CreateCalcQuickDesign() { #region Header titleLabel = new UILabel(); titleLabel.Text = "CalcQuick Calculation"; titleLabel.Font = UIFont.FromName ("Helvetica-Bold", 25f); titleLabel.TextAlignment = UITextAlignment.Center; descripLabel = new UILabel(); descripLabel.Text = "This sample demonstrates the calculation via keys and expressions using CalcQuick."; descripLabel.Lines = 0; descripLabel.LineBreakMode = UILineBreakMode.WordWrap; descripLabel.Font = UIFont.FromName ("Helvetica", 12f); #endregion #region Arguments and Result textA = CreateLabel ("Key A"); textB = CreateLabel ("Key B"); textC = CreateLabel ("Key C"); expression1 = CreateLabel ("Sum([A],[B],[C])"); expression2 = CreateLabel ("PI()*([A]^2)"); expression3 = CreateLabel ("Concatenate([A],[B],[C])"); layer1 = new CALayer() { BorderWidth = 1 , BorderColor = UIColor.Black.CGColor}; layer2 = new CALayer() { BorderWidth = 1 , BorderColor = UIColor.Black.CGColor}; layer3 = new CALayer() { BorderWidth = 1 , BorderColor = UIColor.Black.CGColor}; result1 = CreateLabel (calcQuickBase["Exp1"]); result1.Layer.AddSublayer(layer1); result2 = CreateLabel (calcQuickBase["Exp2"]); result2.Layer.AddSublayer(layer2); result3 = CreateLabel (calcQuickBase["Exp3"]); result3.Layer.AddSublayer(layer3); editTextA = CreateTextField (calcQuickBase["A"]); editTextB = CreateTextField (calcQuickBase["B"]); editTextC = CreateTextField (calcQuickBase["C"]); expressionTitle = new UILabel(); expressionTitle.Text = "CalcQuick Calculation"; expressionTitle.Font = UIFont.FromName ("Helvetica-Bold", 18f); #endregion #region Compute calculateButton = new UIButton(); calculateButton.SetTitle("Compute", UIControlState.Normal); calculateButton.Layer.BorderWidth = 1; calculateButton.Layer.CornerRadius = 4; calculateButton.SetTitleColor(UIColor.Black,UIControlState.Highlighted); calculateButton.BackgroundColor = UIColor.LightGray; calculateButton.TouchUpInside += CalculateButton_TouchUpInside; #endregion AddSubview (titleLabel); AddSubview (descripLabel); AddSubview (textA); AddSubview (textB); AddSubview (textC); AddSubview (editTextA); AddSubview (editTextB); AddSubview (editTextC); AddSubview (calculateButton); AddSubview (expressionTitle); AddSubview (expression1); AddSubview (expression2); AddSubview (expression3); AddSubview (result1); AddSubview (result2); AddSubview (result3); } private void InitializeCalcQuick() { calcQuickBase = new CalcQuickBase(); calcQuickBase.Engine.UseNoAmpersandQuotes = true; calcQuickBase["A"] = "25"; calcQuickBase["B"] = "50"; calcQuickBase["C"] = "10"; calcQuickBase["Exp1"] = "=Sum([A],[B],[C])"; calcQuickBase["Exp2"] = "=PI()*([A]^2)"; calcQuickBase["Exp3"] = "=Concatenate([A],[B],[C])"; } private void CalculateButton_TouchUpInside (object sender, EventArgs e) { this.EndEditing(true); calcQuickBase["A"] = editTextA.Text; calcQuickBase["B"] = editTextB.Text; calcQuickBase["C"] = editTextC.Text; calcQuickBase.SetDirty(); result1.Text = calcQuickBase["Exp1"]; result2.Text = calcQuickBase["Exp2"]; result3.Text = calcQuickBase["Exp3"]; } private UILabel CreateLabel(string text) { return new UILabel () { Text = text, Font = UIFont.FromName ("Helvetica", 14f) }; } private UITextField CreateTextField(string text) { var textField = new UITextField () { Text = text, Font = UIFont.FromName ("Helvetica", 14f) }; textField.ResignFirstResponder (); return textField; } public override void TouchesBegan(NSSet touches, UIEvent evt) { this.EndEditing(true); } protected virtual void RegisterForKeyboardNotifications() { hideNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, OnKeyboardNotification); showNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, OnKeyboardNotification); } private void OnKeyboardNotification (NSNotification notification) { var visible = notification.Name == UIKeyboard.WillShowNotification; var keyboardFrame = visible ? UIKeyboard.FrameEndFromNotification(notification) : UIKeyboard.FrameBeginFromNotification(notification); if (visible) this.SetContentOffset (new CGPoint (this.Frame.Left, (this.Frame.Height - keyboardFrame.Height) / 2), false); else this.SetContentOffset (new CGPoint (this.Frame.Left, this.Frame.Top), false); } protected override void Dispose (bool disposing) { if (calcQuickBase != null) { calcQuickBase.Dispose (); calcQuickBase = null; } NSNotificationCenter.DefaultCenter.RemoveObserver(showNotification); NSNotificationCenter.DefaultCenter.RemoveObserver(hideNotification); base.Dispose (disposing); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Filtering.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Widget; using Android.Graphics; using Android.Views; using System.Globalization; namespace SampleBrowser { public class Filtering:SamplePage { SfDataGrid sfGrid; FilteringViewModel viewModel; SearchView filterText; Spinner conditionDropdown; Spinner columnDropdown; ArrayAdapter condtionAdapter; GridLayout gridlayout; TextView conditionTextView; TextView columnTextView; public override Android.Views.View GetSampleContent (Android.Content.Context context) { LinearLayout linear = new LinearLayout(context); linear.Orientation = Orientation.Vertical; sfGrid = new SfDataGrid (context); sfGrid.SelectionMode = SelectionMode.Single; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; viewModel = new FilteringViewModel (context); viewModel.SetRowstoGenerate (100); sfGrid.GridStyle.AlternatingRowColor = Color.Rgb (206, 206, 206); this.sfGrid.AutoGeneratingColumn += GridAutoGenerateColumn; sfGrid.ItemsSource = (viewModel.BookInfo); filterText = new SearchView(context); filterText.SetQueryHint( "Enter the Text to filter"); filterText.QueryTextChange += OnFilterTextChanged; viewModel.filtertextchanged = OnFilterChanged; linear.AddView(filterText); linear.AddView(sfGrid); return linear; } public override View GetPropertyWindowLayout (Android.Content.Context context) { gridlayout = new GridLayout (context); gridlayout.RowCount = 2; gridlayout.ColumnCount = 2; conditionTextView = new TextView (context); conditionTextView.Text = "Select the Condition to filter"; columnTextView = new TextView (context); columnTextView.Text = "Select the Column to filter"; columnDropdown = new Spinner(context, SpinnerMode.Dialog); var columnAdapter = ArrayAdapter.CreateFromResource (context, Resource.Array.column_array, Android.Resource.Layout.SimpleSpinnerItem); columnAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem); columnDropdown.Adapter = columnAdapter; conditionDropdown = new Spinner (context, SpinnerMode.Dialog); condtionAdapter = new ArrayAdapter (context, Android.Resource.Layout.SimpleSpinnerItem); condtionAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem); conditionDropdown.Adapter = condtionAdapter; columnDropdown.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> (OnColumnSelected); conditionDropdown.ItemSelected += OnConditionSelected; gridlayout.LayoutParameters = new LinearLayout.LayoutParams (LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent); gridlayout.AddView (columnTextView); gridlayout.AddView (columnDropdown); gridlayout.AddView (conditionTextView); gridlayout.AddView (conditionDropdown); return gridlayout; } private void OnColumnSelected (object sender, AdapterView.ItemSelectedEventArgs e) { Spinner newSpinner = (Spinner)sender; viewModel.SelectedColumn = newSpinner.GetItemAtPosition (e.Position).ToString (); if (viewModel.SelectedColumn == "All Columns") { conditionDropdown.Visibility = ViewStates.Gone; conditionTextView.Visibility = ViewStates.Gone; } else { conditionDropdown.Visibility = ViewStates.Visible; conditionTextView.Visibility = ViewStates.Visible; foreach (var prop in typeof(BookInfo).GetProperties()) { if (prop.Name == viewModel.SelectedColumn) { var type = prop.GetType (); if (prop.PropertyType == typeof(Java.Lang.String)) { condtionAdapter.Clear (); condtionAdapter.Add ("Equals"); condtionAdapter.Add ("Contains"); if (this.viewModel.SelectedCondition == "Equals") this.viewModel.SelectedCondition = "Equals"; else this.viewModel.SelectedCondition = "Contains"; } else { condtionAdapter.Clear (); condtionAdapter.Add ("Equals"); condtionAdapter.Add ("NotEquals"); if (this.viewModel.SelectedCondition == "Equals") this.viewModel.SelectedCondition = "Equals"; else this.viewModel.SelectedCondition = "NotEquals"; } } } } if (filterText.Query != "") this.OnFilterChanged (); } void OnFilterChanged () { if (sfGrid.View != null) { this.sfGrid.View.Filter = viewModel.FilerRecords; this.sfGrid.View.RefreshFilter (); } } void OnFilterTextChanged(object sender, SearchView.QueryTextChangeEventArgs e) { viewModel.FilterText = (sender as SearchView).Query.ToString(); } void GridAutoGenerateColumn (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "Last Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "BookID") { e.Column.HeaderText = "Book ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "BookName") { e.Column.HeaderText = "Book Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Price") { e.Column.TextAlignment = GravityFlags.Center; e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); } else if (e.Column.MappingName == "Country") { e.Column.TextAlignment = GravityFlags.CenterVertical; } } private void OnConditionSelected (object sender, AdapterView.ItemSelectedEventArgs e) { Spinner newSpinner = (Spinner)sender; viewModel.SelectedCondition = newSpinner.GetItemAtPosition (e.Position).ToString (); if (filterText.Query != "") this.OnFilterChanged (); } public override void Destroy () { sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumn; sfGrid.Dispose (); conditionDropdown = null; columnDropdown = null; filterText = null; columnTextView = null; conditionTextView = null; sfGrid = null; viewModel = null; condtionAdapter = null; gridlayout.RemoveAllViews(); gridlayout = null; } } } <file_sep>/Forms/DataForm/DataForm/Samples/GettingStarted/Helpers/SfDataFormGettingStartedBehavior.cs #region Copyright // <copyright file="SfDataFormGettingStartedBehavior.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Syncfusion.XForms.DataForm; using Xamarin.Forms; using Xamarin.Forms.Internals; /// <summary> /// Represents the behavior of the data form getting started sample. /// </summary> public class SfDataFormGettingStartedBehavior : Behavior<Syncfusion.XForms.DataForm.SfDataForm> { /// <summary> /// DataForm control to edit the data fields of any data object /// </summary> private Syncfusion.XForms.DataForm.SfDataForm dataForm; /// <summary> /// Attaches to the superclass and then calls the OnAttachedTo method on this object. /// </summary> /// <param name="bindable">The bindable object to which the behavior was attached.</param> protected override void OnAttachedTo(Syncfusion.XForms.DataForm.SfDataForm bindable) { this.dataForm = bindable; this.dataForm.AutoGeneratingDataFormItem += this.OnAutoGeneratingDataFormItem; this.dataForm.BindingContextChanged += this.OnBindingContextChanged; base.OnAttachedTo(bindable); } /// <summary> /// Calls the OnDetachingFrom method and then detaches from the superclass. /// </summary> /// <param name="bindable">The bindable object from which the behavior was detached.</param> protected override void OnDetachingFrom(Syncfusion.XForms.DataForm.SfDataForm bindable) { base.OnDetachingFrom(bindable); this.dataForm.AutoGeneratingDataFormItem -= this.OnAutoGeneratingDataFormItem; (this.dataForm.DataObject as INotifyPropertyChanged).PropertyChanged -= this.OnPropertyChanged; this.dataForm.BindingContextChanged -= this.OnBindingContextChanged; this.dataForm = null; } /// <summary> /// Occurs when binding context of the data form is changed. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Event arguments of binding context.</param> private void OnBindingContextChanged(object sender, EventArgs e) { (this.dataForm.DataObject as INotifyPropertyChanged).PropertyChanged += this.OnPropertyChanged; } /// <summary> /// Occurs during the auto generation of the data form item. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Data form item event arguments.</param> private void OnAutoGeneratingDataFormItem(object sender, AutoGeneratingDataFormItemEventArgs e) { if (e.DataFormItem != null) { if (e.DataFormItem.Name.Equals("HasErrors")) { e.Cancel = true; } else if (e.DataFormItem.Name.Equals("AccountNumber") || e.DataFormItem.Name.Equals("AccountNumber1")) { (e.DataFormItem as DataFormTextItem).KeyBoard = Keyboard.Numeric; } else if (e.DataFormItem.Name.Equals("Email")) { (e.DataFormItem as DataFormTextItem).KeyBoard = Keyboard.Email; } else if (e.DataFormItem.Name.Equals("Agree")) { e.DataFormItem.LayoutOptions = LayoutType.Default; (e.DataFormItem as DataFormCheckBoxItem).IsThreeState = false; (e.DataFormItem as DataFormCheckBoxItem).Text = "I agree to the Terms & Conditions"; } if (!e.DataFormItem.Name.Equals("AccountType")) { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { ReserveSpaceForAssistiveLabels = true }; } } } /// <summary> /// Occurs when propery value is changed. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Property changed event arguments.</param> private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName.Equals("AccountNumber")) { var value = (string)sender.GetType().GetProperty("AccountNumber1").GetValue(sender); if (!string.IsNullOrEmpty(value)) { this.dataForm.Validate("AccountNumber1"); } } else if (e.PropertyName.Equals("AccountNumber1")) { var value = (string)sender.GetType().GetProperty("AccountNumber").GetValue(sender); if (!string.IsNullOrEmpty(value)) { this.dataForm.Validate("AccountNumber"); } } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/ProductInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Foundation; namespace SampleBrowser { public class ProductInfo : NotificationObject { #region Private Members private int productID; private string productModel; private int userRating; private string product; private bool availability; private double price; private int shippingDays; private string productType; #endregion #region Properties [Preserve] public int ProductID { get { return this.productID; } set { this.productID = value; this.RaisePropertyChanged ("ProductID"); } } [Preserve] public string Product { get { return this.product; } set { this.product = value; this.RaisePropertyChanged ("Product"); } } [Preserve] public int UserRating { get { return this.userRating; } set { this.userRating = value; this.RaisePropertyChanged ("UserRating"); } } [Preserve] public string ProductModel { get { return this.productModel; } set { this.productModel = value; this.RaisePropertyChanged ("ProductModel"); } } [Preserve] public double Price { get { return this.price; } set { this.price = value; this.RaisePropertyChanged ("Price"); } } [Preserve] public int ShippingDays { get { return this.shippingDays; } set { this.shippingDays = value; this.RaisePropertyChanged ("ShippingDays"); } } [Preserve] public bool Availability { get { return this.availability; } set { this.availability = value; this.RaisePropertyChanged ("Availability"); } } [Preserve] public string ProductType { get { return this.productType; } set { this.productType = value; this.RaisePropertyChanged ("ProductType"); } } #endregion } } <file_sep>/Forms/ListView/ListView/Helper/BehaviorBase.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Xamarin.Forms; namespace SampleBrowser.SfListView { public class BehaviorBase<T> : Behavior<T> where T : BindableObject { public T AssociatedObject { get; private set; } protected override void OnAttachedTo (T bindable) { base.OnAttachedTo (bindable); AssociatedObject = bindable; if (bindable.BindingContext != null) { BindingContext = bindable.BindingContext; } bindable.BindingContextChanged += OnBindingContextChanged; } protected override void OnDetachingFrom (T bindable) { base.OnDetachingFrom (bindable); bindable.BindingContextChanged -= OnBindingContextChanged; AssociatedObject = null; } void OnBindingContextChanged (object sender, EventArgs e) { OnBindingContextChanged (); } protected override void OnBindingContextChanged () { base.OnBindingContextChanged (); BindingContext = AssociatedObject.BindingContext; } } } <file_sep>/Forms/DataGrid/DataGrid.iOS/MailService.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "MailService.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Foundation; using MessageUI; using SampleBrowser.SfDataGrid; using SampleBrowser.SfDataGrid.iOS; using UIKit; using Xamarin.Forms; [assembly: Dependency(typeof(MailService))] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed.")] namespace SampleBrowser.SfDataGrid.iOS { /// <summary> /// A dependency service used to open the required application. /// </summary> public class MailService : IMailService { /// <summary> /// Initializes a new instance of the MailService class. /// </summary> public MailService() { } /// <summary> /// Use this method to compose mail /// </summary> /// <param name="fileName">string type of parameter fileName</param> /// <param name="recipients">string type of parameter recipients</param> /// <param name="subject">string type of parameter subject</param> /// <param name="messagebody">string type of parameter message body</param> /// <param name="stream">MemoryStream type parameter stream</param> public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream stream) { if (MFMailComposeViewController.CanSendMail) { var mailer = new MFMailComposeViewController(); mailer.SetMessageBody(messagebody ?? string.Empty, false); mailer.SetSubject(subject ?? subject); mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { }); string exception = string.Empty; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filePath = Path.Combine(path, fileName); try { FileStream fileStream = File.Open(filePath, FileMode.Create); stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { exception = e.ToString(); } mailer.AddAttachmentData(NSData.FromFile(filePath), this.GetMimeType(fileName), Path.GetFileName(fileName)); UIViewController vc = UIApplication.SharedApplication.KeyWindow.RootViewController; while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } vc.PresentViewController(mailer, true, null); } } /// <summary> /// This method return the application type /// </summary> /// <param name="filename">indicates file name as string type</param> /// <returns>returns the Image type</returns> private string GetMimeType(string filename) { if (string.IsNullOrEmpty(filename)) { return null; } var extension = Path.GetExtension(filename.ToLowerInvariant()); switch (extension) { case "png": return "image/png"; case "doc": return "application/msword"; case "pdf": return "application/pdf"; case "jpeg": case "jpg": return "image/jpeg"; case "zip": case "docx": case "xlsx": case "pptx": return "application/zip"; case "htm": case "html": return "text/html"; } return "application/octet-stream"; } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/Vertical Chart.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Threading.Tasks; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class VerticalChart : SampleView { SFChart chart ; ChartViewModel dataModel; bool isDispose = false; public VerticalChart () { chart = new SFChart (); chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; SFDateTimeAxis xAxis = new SFDateTimeAxis (); NSDateFormatter formatter = new NSDateFormatter (); formatter.DateFormat = new NSString ("mm:ss"); xAxis.LabelStyle.LabelFormatter = formatter; xAxis.Title.Text = new NSString ("Time (s)"); xAxis.ShowMajorGridLines = false; chart.PrimaryAxis = xAxis; SFNumericalAxis yAxis = new SFNumericalAxis (); yAxis.Minimum = new NSNumber(-10); yAxis.Maximum = new NSNumber (10); yAxis.Interval = new NSNumber (10); yAxis.Title.Text = new NSString ("Velocity(m/s)"); yAxis.ShowMajorGridLines = false; chart.SecondaryAxis = yAxis; chart.Title.Text = new NSString ("Seismograph analysis of country"); chart.Title.Font = UIFont.FromName ("Helvetica neue",15); dataModel = new ChartViewModel(); SFFastLineSeries series = new SFFastLineSeries(); series.LegendIcon = SFChartLegendIcon.Circle; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; series.Label = "Indonesia"; series.ItemsSource = dataModel.verticalData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.IsTransposed = true; series.EnableAnimation = true; chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.Series.Add(series); this.AddSubview(chart); UpdateData (); } async void UpdateData() { await Task.Delay(50); if (!isDispose) { ChartDataModel datapoint = dataModel.dataPointWithTimeInterval(0.13); (chart.Series[0].ItemsSource as ObservableCollection<ChartDataModel>).Add(new ChartDataModel(datapoint.XValue, datapoint.YValue)); if (dataModel.verticalCount < 340) UpdateData(); } } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } protected override void Dispose(bool disposing) { isDispose = disposing; base.Dispose(disposing); } } } <file_sep>/Forms/Switch/Switch/Samples/GettingStartedSample/View/TokenItem.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfSwitch { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class TokenItem : ContentView { #region Memebers private String name; private String icon; private Color color; #endregion #region Properties /// <summary> /// get or set the visiblity of the text to segment control which get enabled and disabled from the list view /// </summary> public String Name { get { return name; } set { name = value; raisepropertyChanged("Name"); } } /// <summary> /// get or set the icons /// </summary> public String Icon { get { return icon; } set { icon = value; raisepropertyChanged("Icon"); } } /// <summary> /// get or set the color to segment control which get enabled and disabled from the list view /// </summary> public Color Color { get { return color; } set { color = value; raisepropertyChanged("Color"); } } #endregion #region Constructor /// <summary> /// Constructor of the token items used on the list view /// </summary> /// <param name="iconFont"></param> /// <param name="textValue"></param> /// <param name="textColor"></param> public TokenItem(AppModel model) { InitializeComponent(); this.BindingContext = this; Name = model.Name; Icon = model.Icon; Color = model.IconColor; } #endregion #region PropertyChanged public event PropertyChangedEventHandler propertyChanged; private void raisepropertyChanged(string property) { if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(property)); } } #endregion } }<file_sep>/iOS/SampleBrowser/Samples/DataGrid/TemplateColumnCell/StockCell.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using System.IO; using System.Reflection; namespace SampleBrowser { public class StockCell : GridCell { UIImageView imageView; UILabel stocktext; public StockCell () { imageView = new UIImageView (); stocktext = new UILabel (); stocktext.Font = UIFont.SystemFontOfSize (20); this.Add (stocktext); this.CanRendererUnload = false; this.AddSubview (imageView); } public MemoryStream LoadResource (String name) { MemoryStream aMem = new MemoryStream (); var assm = Assembly.GetExecutingAssembly (); var path = String.Format ("SampleBrowser.Resources.Images.{0}",name); var aStream = assm.GetManifestResourceStream (path); aStream.CopyTo (aMem); return aMem; } protected override void UnLoad () { this.RemoveFromSuperview (); } public override void Draw (CoreGraphics.CGRect rect) { this.stocktext.Font = DataColumn.GridColumn.RecordFont; this.stocktext.TextColor = DataColumn.Renderer.DataGrid.GridStyle.GetRecordForegroundColor (); this.stocktext.TextAlignment = UITextAlignment.Right; base.Draw (rect); } public override void LayoutSubviews () { base.LayoutSubviews (); if (Convert.ToDouble (DataColumn.CellValue) < 0.05) { imageView.Image = ImageHelper.ToUIImage (new ImageMapStream (LoadResource ("RedDown.png").ToArray ())); } else { imageView.Image = ImageHelper.ToUIImage (new ImageMapStream (LoadResource ("GreenUp.png").ToArray ())); } this.stocktext.Frame = new CoreGraphics.CGRect (35, this.Bounds.Top, 65, this.Bounds.Height); this.imageView.Frame = new CoreGraphics.CGRect (20, 10, 17, this.Bounds.Height - 20); this.stocktext.Font = DataColumn.GridColumn.RecordFont; this.stocktext.TextAlignment = UITextAlignment.Right; this.stocktext.Text = DataColumn.CellValue.ToString (); } protected override void Dispose (bool disposing) { if (this.imageView != null && stocktext != null) { imageView.Dispose (); imageView = null; stocktext.Dispose (); stocktext = null; } base.Dispose (disposing); } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Styles/Dark.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Graphics; namespace SampleBrowser { public class Dark : DataGridStyle { public Dark () { } public override Color GetHeaderBackgroundColor () { return Color.ParseColor("#212121"); } public override Color GetHeaderForegroundColor () { return Color.ParseColor("#FFFFFF"); } public override Color GetRecordForegroundColor () { return Color.ParseColor("#FFFFFF"); } public override Color GetAlternatingRowBackgroundColor() { return Color.ParseColor("#2E2E2E"); } public override Color GetRecordBackgroundColor() { return Color.ParseColor("#2B2b2B"); } public override Color GetSelectionBackgroundColor () { return Color.ParseColor("#555555"); } public override Color GetSelectionForegroundColor () { return Color.ParseColor("#FFFFFF"); } public override Color GetCaptionSummaryRowBackgroundColor () { return Color.Rgb (02, 02, 02); } public override Color GetCaptionSummaryRowForegroundColor () { return Color.Rgb (255, 255, 255); } public override Color GetBorderColor () { return Color.Rgb (81, 83, 82); } public override int GetHeaderSortIndicatorDown () { return Resource.Drawable.SortingDown; } public override int GetHeaderSortIndicatorUp () { return Resource.Drawable.SortingUp; } public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Horizontal; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/AutoComplete/MultiSelection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Foundation; using UIKit; using CoreGraphics; using Syncfusion.SfAutoComplete.iOS; using System.Collections.Generic; namespace SampleBrowser { public class MultiSelection : SampleView { UILabel email, attach, send, ToLabel, ccLabel, bcclabel, interestLabel, cultureLabel, allowNullLabel; UIView redpanel; SfAutoComplete toAutoComplete; SfAutoComplete ccAutoComplete; SfAutoComplete bccAutoComplete; UITextField messageBox; public UIView option = new UIView(); private readonly IList<string> cultureList = new List<string>(); public MultiSelection() { //ToAutoComplete toAutoComplete = new SfAutoComplete(); toAutoComplete.MultiSelectMode = MultiSelectMode.Token; toAutoComplete.TokensWrapMode = TokensWrapMode.Wrap; toAutoComplete.DataSource = new ContactsInfoCollection().GetContactDetails(); toAutoComplete.DisplayMemberPath = (NSString)"ContactName"; toAutoComplete.ImageMemberPath = "ContactImage"; this.AddSubview(toAutoComplete); //CCAutoComplete ccAutoComplete = new SfAutoComplete(); ccAutoComplete.MultiSelectMode = MultiSelectMode.Token; ccAutoComplete.TokensWrapMode = TokensWrapMode.Wrap; ccAutoComplete.DataSource = new ContactsInfoCollection().GetContactDetails(); ccAutoComplete.DisplayMemberPath = (NSString)"ContactName"; ccAutoComplete.ImageMemberPath = "ContactImage"; this.AddSubview(ccAutoComplete); //BCCAutoComplete bccAutoComplete = new SfAutoComplete(); bccAutoComplete.MultiSelectMode = MultiSelectMode.Token; bccAutoComplete.TokensWrapMode = TokensWrapMode.Wrap; bccAutoComplete.DataSource = new ContactsInfoCollection().GetContactDetails(); bccAutoComplete.DisplayMemberPath = (NSString)"ContactName"; bccAutoComplete.ImageMemberPath = "ContactImage"; this.AddSubview(bccAutoComplete); //MessageBox messageBox = new UITextField(); messageBox.Text = "Send from my smart phone"; this.AddSubview(messageBox); mainPageDesign(); } public void mainPageDesign() { redpanel = new UIView(); redpanel.BackgroundColor = UIColor.Red; this.AddSubview(redpanel); //emaill email = new UILabel(); email.TextColor = UIColor.White; email.BackgroundColor = UIColor.Clear; email.Text = @"Email - Compose"; email.TextAlignment = UITextAlignment.Left; email.Font = UIFont.FromName("Helvetica", 16f); redpanel.AddSubview(email); //attachl attach = new UILabel(); attach.TextColor = UIColor.White; attach.BackgroundColor = UIColor.Clear; attach.Text = @"Attach"; attach.TextAlignment = UITextAlignment.Left; attach.Font = UIFont.FromName("Helvetica", 16f); redpanel.AddSubview(attach); //sendl send = new UILabel(); send.TextColor = UIColor.White; send.BackgroundColor = UIColor.Clear; send.Text = @"Send"; send.TextAlignment = UITextAlignment.Left; send.Font = UIFont.FromName("Helvetica", 16f); redpanel.AddSubview(send); //ToLabell ToLabel = new UILabel(); ToLabel.TextColor = UIColor.Black; ToLabel.BackgroundColor = UIColor.Clear; ToLabel.Text = @"To"; ToLabel.TextAlignment = UITextAlignment.Left; ToLabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(ToLabel); //ccLabell ccLabel = new UILabel(); ccLabel.TextColor = UIColor.Black; ccLabel.BackgroundColor = UIColor.Clear; ccLabel.Text = @"Cc"; ccLabel.TextAlignment = UITextAlignment.Left; ccLabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(ccLabel); //bcclabell bcclabel = new UILabel(); bcclabel.TextColor = UIColor.Black; bcclabel.BackgroundColor = UIColor.Clear; bcclabel.Text = @"Bcc"; bcclabel.TextAlignment = UITextAlignment.Left; bcclabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(bcclabel); this.BackgroundColor = UIColor.White; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; redpanel.Frame = new CGRect(0, 0, view.Frame.Width, 50); toAutoComplete.Frame = new CGRect(50, 60, view.Frame.Width - 60, 30); ccAutoComplete.Frame = new CGRect(50, 110, view.Frame.Width - 60, 30); bccAutoComplete.Frame = new CGRect(50, 160, view.Frame.Width - 60, 30); messageBox.Frame = new CGRect(10, 210, view.Frame.Width - 60, 30); email.Frame = new CGRect(15, 10, 180, 40); attach.Frame = new CGRect(this.Frame.Size.Width - 120, 10, 60, 40); send.Frame = new CGRect(this.Frame.Size.Width - 60, 10, 50, 40); ToLabel.Frame = new CGRect(15, 60, 60, 30); ccLabel.Frame = new CGRect(15, 110, this.Frame.Size.Width - 20, 30); bcclabel.Frame = new CGRect(15, 160, this.Frame.Size.Width - 20, 30); } } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/Swiping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using CoreGraphics; using UIKit; using System.Threading.Tasks; using Foundation; namespace SampleBrowser { public class Swiping:SampleView { #region Fields SfDataGrid SfGrid; SwipingViewModel viewModel; DetailView detailView; UILabel col1; UILabel col2; UILabel col3; UILabel col4; UITextField orderIDText; UITextField customerIDText; UITextField employeeIDText; UITextField nameText; UIButton save; UIButton cancel; private bool IsUndoClicked{ get; set; } private int swipedRowindex; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public Swiping () { save = new UIButton (); save.SetTitle ("Save", UIControlState.Normal); save.BackgroundColor = UIColor.DarkGray; save.Font = UIFont.FromName("Helvetica-Bold", 12f); save.TouchDown += Save_TouchDown; cancel = new UIButton (); cancel.SetTitle ("Cancel", UIControlState.Normal); cancel.TouchDown += Cancel_TouchDown; cancel.BackgroundColor = UIColor.DarkGray; cancel.Font = UIFont.FromName("Helvetica-Bold", 12f); col1 = new UILabel(); col1.Text="Order ID"; col2 = new UILabel(); col2.Text="Customer ID"; col3 = new UILabel(); col3.Text="Employee ID"; col4 = new UILabel(); col4.Text="Name"; orderIDText = new UITextField (); orderIDText.AllowsEditingTextAttributes = true; orderIDText.ShouldReturn += (textField) => { orderIDText.ResignFirstResponder(); return true; }; customerIDText = new UITextField (); customerIDText.ShouldReturn += (textField) => { customerIDText.ResignFirstResponder(); return true; }; employeeIDText = new UITextField (); employeeIDText.ShouldReturn += (textField) => { employeeIDText.ResignFirstResponder(); return true; }; nameText = new UITextField (); nameText.ShouldReturn += (textField) => { nameText.ResignFirstResponder(); return true; }; orderIDText.Hidden = true; customerIDText.Hidden = true; employeeIDText.Hidden = true; nameText.Hidden = true; col1.Hidden = true; col2.Hidden = true; col3.Hidden = true; col4.Hidden = true; save.Hidden = true; cancel.Hidden = true; this.detailView = new DetailView (); this.detailView.Hidden = true; this.SfGrid = new SfDataGrid (); this.viewModel = new SwipingViewModel (); this.SfGrid.ItemsSource = viewModel.OrdersInfo; this.SfGrid.AutoGenerateColumns = false; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.ColumnSizer = ColumnSizer.Star; UIButton leftSwipeViewText = new UIButton (); leftSwipeViewText.SetTitle("Edit", UIControlState.Normal); leftSwipeViewText.SetTitleColor(UIColor.White, UIControlState.Normal); leftSwipeViewText.VerticalAlignment = UIControlContentVerticalAlignment.Center; leftSwipeViewText.BackgroundColor = UIColor.FromRGB(0,158,218); leftSwipeViewText.TouchUpInside += LeftSwipeViewButton_TouchUpInside; leftSwipeViewText.Frame = new CGRect(56, 0, 60, 45); UIButton leftSwipeViewButton = new UIButton (); leftSwipeViewButton.SetImage (UIImage.FromFile("Images/Edit.png"),UIControlState.Normal); leftSwipeViewButton.BackgroundColor = UIColor.FromRGB(0, 158, 218); leftSwipeViewButton.TouchUpInside += LeftSwipeViewButton_TouchUpInside; leftSwipeViewButton.Frame = new CGRect(16, 10, 24, 24); CustomSwipeView leftSwipeView = new CustomSwipeView (); leftSwipeView.AddSubview (leftSwipeViewButton); leftSwipeView.AddSubview(leftSwipeViewText); leftSwipeView.Frame = new CGRect(0, 0, 120, 44); leftSwipeView.BackgroundColor = UIColor.FromRGB(0, 158, 218); UIButton rightSwipeViewText = new UIButton (); rightSwipeViewText.SetTitle ("Delete", UIControlState.Normal); rightSwipeViewText.SetTitleColor(UIColor.White, UIControlState.Normal); rightSwipeViewText.VerticalAlignment = UIControlContentVerticalAlignment.Center; rightSwipeViewText.BackgroundColor = UIColor.FromRGB(220, 89, 95); rightSwipeViewText.TouchUpInside += RightSwipeViewButton_TouchUpInside; rightSwipeViewText.Frame = new CGRect(56, 0, 60, 45); UIButton rightSwipeViewButton = new UIButton (); rightSwipeViewButton.SetImage (UIImage.FromFile("Images/Delete.png"),UIControlState.Normal); rightSwipeViewButton.BackgroundColor = UIColor.FromRGB(220, 89, 95); rightSwipeViewButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; rightSwipeViewButton.TouchUpInside += RightSwipeViewButton_TouchUpInside; rightSwipeViewButton.Frame = new CGRect(16, 10, 24, 24); CustomSwipeView rightSwipeView = new CustomSwipeView (); rightSwipeView.AddSubview (rightSwipeViewButton); rightSwipeView.AddSubview(rightSwipeViewText); rightSwipeView.Frame = new CGRect(0, 0, 120, 44); rightSwipeView.BackgroundColor = UIColor.FromRGB(220, 89, 95); this.SfGrid.AllowSwiping = true; this.SfGrid.LeftSwipeView = leftSwipeView; this.SfGrid.RightSwipeView = rightSwipeView; this.SfGrid.SwipeEnded += SfGrid_SwipeEnded; this.SfGrid.SwipeStarted += SfGrid_SwipeStarted; this.SfGrid.GridTapped += SfGrid_GridTapped; this.SfGrid.GridLongPressed += SfGrid_GridLongPressed; GridTextColumn CustomerID = new GridTextColumn(); CustomerID.MappingName = "CustomerID"; CustomerID.HeaderText = "Customer ID"; GridTextColumn OrderID = new GridTextColumn(); OrderID.MappingName = "OrderID"; OrderID.HeaderText = "Order ID"; GridTextColumn EmployeeID = new GridTextColumn(); EmployeeID.MappingName = "EmployeeID"; EmployeeID.HeaderText = "Employee ID"; GridTextColumn Name = new GridTextColumn(); Name.MappingName = "FirstName"; Name.HeaderText = "Name"; this.SfGrid.Columns.Add(OrderID); this.SfGrid.Columns.Add(CustomerID); this.SfGrid.Columns.Add(EmployeeID); this.SfGrid.Columns.Add(Name); this.AddSubview (SfGrid); this.AddSubview (detailView); this.AddSubview (col1); this.AddSubview (col2); this.AddSubview (col3); this.AddSubview (col4); this.AddSubview (orderIDText); this.AddSubview (customerIDText); this.AddSubview (employeeIDText); this.AddSubview (nameText); this.AddSubview (save); this.AddSubview (cancel); } private void SfGrid_GridLongPressed(object sender, GridLongPressedEventArgs e) { this.CloseEditWindow(); } private void SfGrid_GridTapped(object sender, GridTappedEventArgs e) { this.CloseEditWindow(); } void Cancel_TouchDown(object sender, EventArgs e) { CloseEditWindow(); } private void CloseEditWindow() { hideOptionViews(); initializeTextFields(); } void Save_TouchDown (object sender, EventArgs e) { commitValues (); hideOptionViews (); } private void commitValues () { if (swipedRowindex > 0) { var swipedRowData = this.viewModel.OrdersInfo [this.swipedRowindex - 1]; swipedRowData.OrderID = this.orderIDText.Text; swipedRowData.CustomerID = this.customerIDText.Text; swipedRowData.EmployeeID = this.employeeIDText.Text; swipedRowData.FirstName = this.nameText.Text; } } private void hideOptionViews() { this.detailView.Hidden = true; this.col1.Hidden = true; this.col2.Hidden = true; this.col3.Hidden = true; this.col4.Hidden = true; this.orderIDText.Hidden = true; this.customerIDText.Hidden = true; this.employeeIDText.Hidden = true; this.nameText.Hidden = true; this.save.Hidden = true; this.cancel.Hidden = true; } private void initializeTextFields() { if (swipedRowindex > 0) { var swipedRowData = this.viewModel.OrdersInfo [this.swipedRowindex - 1]; orderIDText.Text = swipedRowData.OrderID; this.customerIDText.Text = swipedRowData.CustomerID; this.employeeIDText.Text = swipedRowData.EmployeeID; this.nameText.Text = swipedRowData.FirstName; } } void LeftSwipeViewButton_TouchUpInside(object sender, EventArgs e) { this.detailView.Hidden = false; this.col1.Hidden = false; this.col2.Hidden = false; this.col3.Hidden = false; this.col4.Hidden = false; this.orderIDText.Hidden = false; this.customerIDText.Hidden = false; this.employeeIDText.Hidden = false; this.nameText.Hidden = false; this.save.Hidden = false; this.cancel.Hidden= false; } void RightSwipeViewButton_TouchUpInside(object sender, EventArgs e) { viewModel.OrdersInfo.RemoveAt(swipedRowindex - 1); } public override void LayoutSubviews () { this.SfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); detailView.Frame = new CGRect (10, this.SfGrid.Frame.Top + 100, SfGrid.Frame.Width - 20, 200); col1.Frame = new CGRect (detailView.Frame.Right * 0.15, detailView.Frame.Top + 20, detailView.Frame.Right /2, 20); col2.Frame = new CGRect (detailView.Frame.Right * 0.15, col1.Frame.Bottom + 10, detailView.Frame.Right /2, 20); col3.Frame = new CGRect (detailView.Frame.Right * 0.15, col2.Frame.Bottom + 10, detailView.Frame.Right /2, 20); col4.Frame = new CGRect (detailView.Frame.Right * 0.15, col3.Frame.Bottom + 10, detailView.Frame.Right /2, 20); orderIDText.Frame= new CGRect( col1.Frame.Right,detailView.Frame.Top+ 20,detailView.Frame.Right,20); customerIDText.Frame= new CGRect( col2.Frame.Right,orderIDText.Frame.Bottom +10,detailView.Frame.Right,20); employeeIDText.Frame= new CGRect( col3.Frame.Right,customerIDText.Frame.Bottom +10,detailView.Frame.Right,20); nameText.Frame= new CGRect( col4.Frame.Right,employeeIDText.Frame.Bottom +10,detailView.Frame.Right,20); save.Frame = new CGRect (detailView.Frame.Right / 4, nameText.Frame.Bottom + 20, 50, 20); cancel.Frame = new CGRect (save.Frame.Right +10, nameText.Frame.Bottom + 20, 80, 20); base.LayoutSubviews (); } void SfGrid_SwipeStarted (object sender, SwipeStartedEventArgs e) { SfGrid.MaxSwipeOffset = 120; } private void SfGrid_SwipeEnded (object sender, SwipeEndedEventArgs e) { swipedRowindex = e.RowIndex; initializeTextFields (); } protected override void Dispose(bool disposing) { if (disposing) { if (save != null) { save.TouchDown -= Save_TouchDown; } if (cancel != null) { cancel.TouchDown -= Cancel_TouchDown; } if (SfGrid != null) { SfGrid.SwipeEnded -= SfGrid_SwipeEnded; SfGrid.SwipeStarted -= SfGrid_SwipeStarted; SfGrid.GridTapped -= SfGrid_GridTapped; SfGrid.GridLongPressed -= SfGrid_GridLongPressed; SfGrid.Dispose(); } col1 = null; col2 = null; col3 = null; col4 = null; orderIDText = null; customerIDText = null; employeeIDText = null; nameText = null; save = null; cancel = null; viewModel = null; detailView = null; SfGrid = null; } base.Dispose(disposing); } } public class DetailView : UIView { public DetailView () { this.BackgroundColor = UIColor.LightGray; } } public class CustomSwipeView : UIView { public override bool Hidden { get { return base.Hidden; } set { base.Hidden = value; } } public CustomSwipeView() { } public override void LayoutSubviews() { var childWidth = this.Frame.Width / 3; } } } <file_sep>/Android/SampleBrowser/Samples/DataSource/DataSourceSorting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.DataSource; using Android.Graphics; namespace SampleBrowser { public class DataSourceSorting : SamplePage, IDisposable { #region Fields private DataSource dataSource; private ContatsViewModel viewModel; private ListView listView; private Spinner groupDropdown; private GridLayout gridlayout; private TextView groupTextView; private SearchView filterText; #endregion #region Override public override Android.Views.View GetSampleContent(Android.Content.Context context) { LinearLayout linear = new LinearLayout(context) { Orientation = Orientation.Vertical }; listView = new ListView(context); listView.FastScrollEnabled = true; viewModel = new ContatsViewModel(); dataSource = new DataSource(); dataSource.Source = viewModel.ContactsList; dataSource.LiveDataUpdateMode = LiveDataUpdateMode.AllowDataShaping; dataSource.SortDescriptors.Add(new SortDescriptor("ContactName", Syncfusion.DataSource.ListSortDirection.Ascending)); listView.Adapter = new ContactsAdapter(dataSource, context); filterText = new SearchView(context); filterText.SetIconifiedByDefault(false); filterText.SetPadding(0, 0, 0, (int)(10 * context.Resources.DisplayMetrics.Density)); filterText.SetQueryHint("Search contact"); filterText.QueryTextChange += OnFilterTextChanged; linear.AddView(new LinearLayout(context) { Focusable = true, FocusableInTouchMode = true }, 0, 0); linear.AddView(filterText); linear.AddView(listView); return linear; } public override View GetPropertyWindowLayout(Context context) { gridlayout = new GridLayout(context); gridlayout.SetPadding(20, 20, 20, 20); gridlayout.RowCount = 2; gridlayout.ColumnCount = 2; groupTextView = new TextView(context); groupTextView.Text = "Sort by"; groupDropdown = new Spinner(context, SpinnerMode.Dialog); var groupAdapter = new ArrayAdapter(context, Android.Resource.Layout.SimpleSpinnerItem); groupAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); groupAdapter.Add("Ascending"); groupAdapter.Add("Descending"); groupDropdown.Adapter = groupAdapter; groupDropdown.ItemSelected += GroupDropdown_ItemSelected; gridlayout.AddView(groupTextView, LinearLayout.LayoutParams.WrapContent, (int)(30 * context.Resources.DisplayMetrics.Density)); gridlayout.AddView(groupDropdown); return gridlayout; } private void GroupDropdown_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { var spinner = sender as Spinner; var direction = spinner.GetItemAtPosition(e.Position).ToString(); dataSource.BeginInit(); dataSource.SortDescriptors.Clear(); dataSource.SortDescriptors.Add(new SortDescriptor() { PropertyName = "ContactName", Direction = direction == "Ascending" ? Syncfusion.DataSource.ListSortDirection.Ascending : Syncfusion.DataSource.ListSortDirection.Descending }); dataSource.EndInit(); (this.listView.Adapter as ContactsAdapter).NotifyDataSetChanged(); } private void OnFilterTextChanged(object sender, SearchView.QueryTextChangeEventArgs e) { if (dataSource != null) { this.dataSource.Filter = FilterContacts; this.dataSource.RefreshFilter(); } } private bool FilterContacts(object obj) { var contacts = obj as Contacts; if (contacts.ContactName.ToLower().Contains(filterText.Query.ToLower()) || contacts.ContactNumber.ToLower().Contains(filterText.Query.ToLower())) { return true; } else { return false; } } public void Dispose() { if (dataSource != null) { dataSource.Dispose(); dataSource = null; } if (gridlayout != null) { gridlayout.Dispose(); gridlayout = null; } if (groupDropdown != null) { groupDropdown.Dispose(); groupDropdown = null; } if (groupTextView != null) { groupTextView.Dispose(); groupTextView = null; } if (listView != null) { listView.Dispose(); listView = null; } if (filterText != null) { filterText.Dispose(); filterText = null; } } #endregion } }<file_sep>/iOS/SampleBrowser/Resources/Samples/ImageEditor/ImageEditorCustomization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfImageEditor.iOS; using Foundation; using UIKit; using CoreGraphics; using System.Drawing; using Photos; using System.IO; namespace SampleBrowser { public class ImageEditorCustomization : SampleView { bool isReset, isUndo, isRedo, isRect, isText, isPath = false; UIView RightView; UIView overView; UIView topView; SfImageEditor sfImageEditor; Object settings; UITextField textView; UIViewController presentController; public ImageEditorCustomization() { } public override void LayoutSubviews() { base.LayoutSubviews(); presentController = GetVisibleViewController(); UIView mainView = new UIView(); mainView.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); mainView.BackgroundColor = UIColor.Clear; sfImageEditor = new SfImageEditor(new CGRect(mainView.Frame.X, mainView.Frame.Y, mainView.Frame.Width, mainView.Frame.Height)); sfImageEditor.Image = UIImage.FromBundle("Images/ImageEditor/Customize.jpg"); sfImageEditor.BackgroundColor = UIColor.Black; sfImageEditor.ToolBarSettings.IsVisible = false; //settings = new Object(); sfImageEditor.ItemSelected += (object sender, ItemSelectedEventArgs e) => { RightView.Alpha = 1; settings = e.Settings; }; mainView.AddSubview(sfImageEditor); /*--------------------------------------------------*/ //TopView topView = new UIView(); topView.Frame = new CGRect(0, 15, Frame.Width, 25); topView.Alpha = 0; UIButton reset = new UIButton(new CGRect(0, 0, Frame.Width / 6, 25)); reset.BackgroundColor = UIColor.Clear; reset.SetImage(UIImage.FromBundle("Images/ImageEditor/reset_customization.png"), UIControlState.Normal); reset.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; reset.TouchUpInside += Reset_TouchUpInside; topView.AddSubview(reset); UIButton redo = new UIButton(new CGRect(Frame.Width / 6, 0, Frame.Width / 6, 25)); redo.BackgroundColor = UIColor.Clear; redo.SetImage(UIImage.FromBundle("Images/ImageEditor/redo_customization.png"), UIControlState.Normal); redo.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; redo.TouchUpInside += Redo_TouchUpInside; redo.Alpha = 0; topView.AddSubview(redo); UIButton undo = new UIButton(new CGRect(2 * (Frame.Width / 6), 0, Frame.Width / 6, 25)); undo.BackgroundColor = UIColor.Clear; undo.SetImage(UIImage.FromBundle("Images/ImageEditor/undo_customization.png"), UIControlState.Normal); undo.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; undo.TouchUpInside += Undo_TouchUpInside; topView.AddSubview(undo); UIButton rect = new UIButton(new CGRect(3 * (Frame.Width / 6), 0, Frame.Width / 6, 25)); rect.BackgroundColor = UIColor.Clear; rect.SetImage(UIImage.FromBundle("Images/ImageEditor/rect_customization.png"), UIControlState.Normal); rect.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; rect.TouchUpInside += Rect_TouchUpInside; topView.AddSubview(rect); UIButton text = new UIButton(new CGRect(4 * (Frame.Width / 6), 0, Frame.Width / 6, 25)); text.BackgroundColor = UIColor.Clear; text.SetImage(UIImage.FromBundle("Images/ImageEditor/text_customization.png"), UIControlState.Normal); text.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; text.TouchUpInside += Text_TouchUpInside; topView.AddSubview(text); UIButton path = new UIButton(new CGRect(5 * (Frame.Width / 6), 0, Frame.Width / 6, 25)); path.BackgroundColor = UIColor.Clear; path.SetImage(UIImage.FromBundle("Images/ImageEditor/pen_customization.png"), UIControlState.Normal); path.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; path.TouchUpInside += Path_TouchUpInside; topView.AddSubview(path); mainView.AddSubview(topView); /*----------------------------------------------------------*/ //BottomView UIView bottomView = new UIView(); bottomView.Frame = new CGRect(10, Frame.Height - 50, Frame.Width, 30); bottomView.BackgroundColor = UIColor.Clear; textView = new UITextField(new CGRect(20, 0, Frame.Width - 100, 30)); textView.Layer.CornerRadius = 10.0f; textView.Layer.BorderColor = UIColor.White.CGColor; textView.Layer.BorderWidth = 2; textView.TextColor = UIColor.White; textView.Placeholder = "Enter a Caption"; textView.Enabled = true; textView.ResignFirstResponder(); textView.MultipleTouchEnabled = true; bottomView.AddSubview(textView); UIButton share = new UIButton(new CGRect(Frame.Width - 70, 0, 50, 30)); share.BackgroundColor = UIColor.Clear; share.SetImage(UIImage.FromBundle("Images/ImageEditor/share_customization.png"), UIControlState.Normal); share.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; share.TouchUpInside += Share_TouchUpInside; bottomView.AddSubview(share); mainView.AddSubview(bottomView); /*--------------------------------------------------*/ //RightView RightView = new UIView(); RightView.Frame = new CGRect(Frame.Width - 50, 20, 30, Frame.Height ); RightView.BackgroundColor = UIColor.Clear; //Color Collection UIColor[] array = new UIColor[10]{ UIColor.FromRGB(68,114,196) ,UIColor.FromRGB(237,125,49) ,UIColor.FromRGB(255,192,0) ,UIColor.FromRGB(112,173,71) ,UIColor.FromRGB(91,155,213) ,UIColor.FromRGB(193,193,193) ,UIColor.FromRGB(111,111,226) ,UIColor.FromRGB(226,105,174) ,UIColor.FromRGB(158,72,14) ,UIColor.FromRGB(153,115,0) }; int y = (int)(this.Frame.Height / 2)-175; for (int i = 0; i < 10; i++) { UIButton colorButton = new UIButton(); colorButton.Frame = new CGRect(3, y + 5, 25, 25); colorButton.Layer.CornerRadius = 10; y = y + 30; colorButton.BackgroundColor = array[i]; colorButton.TouchUpInside += ColorButton_TouchUpInside; RightView.Add(colorButton); } mainView.AddSubview(RightView); RightView.Alpha = 0; overView = new UIView(); overView.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); overView.BackgroundColor = UIColor.Clear; overView.Alpha = 1f; UITapGestureRecognizer tapped = new UITapGestureRecognizer(TapCarrierLabel); overView.AddGestureRecognizer(tapped); AddSubview(mainView); AddSubview(overView); } public void TapCarrierLabel(UITapGestureRecognizer uitgr) { overView.Alpha = 0; topView.Alpha = 1; } void Path_TouchUpInside(object sender, EventArgs e) { isPath = true; isReset = false; isUndo = false; isRedo = false; isRect = false; isText = false; if (RightView.Alpha == 0) RightView.Alpha = 1; else RightView.Alpha = 0; } void Text_TouchUpInside(object sender, EventArgs e) { settings = null; isPath = false; isReset = false; isUndo = false; isRedo = false; isRect = false; isText = true; if (RightView.Alpha == 0) RightView.Alpha = 1; else RightView.Alpha = 0; sfImageEditor.AddText("Text",new TextSettings()); } void Rect_TouchUpInside(object sender, EventArgs e) { settings = null; isPath = false; isReset = false; isUndo = false; isRedo = false; isRect = true; isText = false; if (RightView.Alpha == 0) RightView.Alpha = 1; else RightView.Alpha = 0; sfImageEditor.AddShape(ShapeType.Rectangle,new PenSettings()); } void Redo_TouchUpInside(object sender, EventArgs e) { isPath = false; isReset = false; isUndo = false; isRedo = true; isRect = false; isText = false; RightView.Alpha = 0; sfImageEditor.Redo(); } void Undo_TouchUpInside(object sender, EventArgs e) { isPath = false; isReset = false; isUndo = true; isRedo = false; isRect = false; isText = false; RightView.Alpha = 0; sfImageEditor.Undo(); } void Reset_TouchUpInside(object sender, EventArgs e) { isPath = false; isReset = true; isUndo = false; isRedo = false; isRect = false; isText = false; RightView.Alpha = 0; sfImageEditor.Reset(); overView.Alpha = 1; topView.Alpha = 0; } void Share_TouchUpInside(object sender, EventArgs e) { sfImageEditor.Save(); sfImageEditor.ImageSaved += SfImageEditor_ImageSaved; } void ColorButton_TouchUpInside(object sender, EventArgs e) { var colorSelected = (sender as UIButton).BackgroundColor; if (isPath) { sfImageEditor.AddShape(ShapeType.Path, new PenSettings() { Color = colorSelected }); } if (settings is TextSettings) { (settings as TextSettings).Color = colorSelected; } if (settings is PenSettings) { (settings as PenSettings).Color = colorSelected; //sfImageEditor.AddShape(ShapeType.Rectangle, new PenSettings() { Color = colorSelected, StrokeWidth = 5 }); } RightView.Alpha = 0; } void SfImageEditor_ImageSaved(object sender, ImageSavedEventArgs e) { string[] str = e.Location.Split('/'); PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null); PHAsset asset = assetResult.firstObject as PHAsset; Stream stream = null; PHImageManager.DefaultManager.RequestImageData(asset, null, async (data, dataUti, orientation, info) => { UIImage newImage = new UIImage(data); var items = new NSObject[] { newImage }; var activityController = new UIActivityViewController(items, null); NSString[] excludedActivityTypes = null; if (excludedActivityTypes != null && excludedActivityTypes.Length > 0) activityController.ExcludedActivityTypes = excludedActivityTypes; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { if (activityController.PopoverPresentationController != null) { activityController.PopoverPresentationController.SourceView = presentController.View; } } await presentController.PresentViewControllerAsync(activityController, true); }); } internal static UIViewController GetVisibleViewController() { var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController; if (rootController.PresentedViewController == null) return rootController; if (rootController.PresentedViewController is UINavigationController) { return ((UINavigationController)rootController.PresentedViewController).TopViewController; } if (rootController.PresentedViewController is UITabBarController) { return ((UITabBarController)rootController.PresentedViewController).SelectedViewController; } return rootController.PresentedViewController; } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/StepArea.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class StepArea : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Electricity-Production"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.ColorModel.ColorPalette = ChartColorPalette.Natural; chart.Legend.Visibility = Visibility.Visible; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.ToggleSeriesVisibility = true; NumericalAxis categoryaxis = new NumericalAxis(); categoryaxis.MajorTickStyle.TickSize = 8; categoryaxis.ShowMajorGridLines = false; categoryaxis.Interval = 2; categoryaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Title.Text = "Production (Billion as kWh)"; numericalaxis.Minimum = 0; numericalaxis.Maximum = 600; numericalaxis.Interval = 100; numericalaxis.LabelStyle.LabelFormat = "#'B'"; numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.StrokeWidth = 0; chart.SecondaryAxis = numericalaxis; StepAreaSeries stepAreaSeries1 = new StepAreaSeries(); stepAreaSeries1.ItemsSource = MainPage.GetStepAreaData1(); stepAreaSeries1.XBindingPath = "XValue"; stepAreaSeries1.YBindingPath = "YValue"; stepAreaSeries1.Label = "Renewable"; stepAreaSeries1.EnableAnimation = true; stepAreaSeries1.LegendIcon = ChartLegendIcon.Rectangle; StepAreaSeries stepAreaSeries2 = new StepAreaSeries(); stepAreaSeries2.ItemsSource = MainPage.GetStepAreaData2(); stepAreaSeries2.XBindingPath = "XValue"; stepAreaSeries2.YBindingPath = "YValue"; stepAreaSeries2.Label = "Non-Renewable"; stepAreaSeries2.EnableAnimation = true; stepAreaSeries2.LegendIcon = ChartLegendIcon.Rectangle; chart.Series.Add(stepAreaSeries1); chart.Series.Add(stepAreaSeries2); return chart; } } }<file_sep>/Forms/RangeSlider/RangeSlider/Samples/RangeSlider/RangeSlider_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfRangeSlider.XForms; using Xamarin.Forms; namespace SampleBrowser.SfRangeSlider { public partial class RangeSlider_Default : SampleView { ObservableCollection<Syncfusion.SfRangeSlider.XForms.Items> customCollection { get; set; } public RangeSlider_Default() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP) { layoutRoot.HorizontalOptions = LayoutOptions.Center; layoutRoot.WidthRequest = 500; } customCollection = new ObservableCollection<Syncfusion.SfRangeSlider.XForms.Items>(); customCollection.Add(new Syncfusion.SfRangeSlider.XForms.Items() { Label = "Min", Value = 0}); customCollection.Add(new Syncfusion.SfRangeSlider.XForms.Items() { Label = "Max",Value= 10 }); rangeslider4.CustomLabels = customCollection; rangeslider5.ShowValueLabel = true; rangeslider5.LabelFormat = " {0:c}"; rangeslider5.Culture = new System.Globalization.CultureInfo("en-US"); if (App.Current.MainPage!= null && App.Current.MainPage.Visual == VisualMarker.Material) { this.SetMaterialValues(rangeslider1); this.SetMaterialValues(rangeslider2); this.SetMaterialValues(rangeslider3, true); this.SetMaterialValues(rangeslider4); this.SetMaterialValues(rangeslider5); } } public View getContent() { return this.Content; } /// <summary> /// Set the color values for material /// </summary> /// <param name="rangeSlider"></param> private void SetMaterialValues(Syncfusion.SfRangeSlider.XForms.SfRangeSlider rangeSlider, bool isTick = false) { if (Device.RuntimePlatform != Device.UWP) { rangeSlider.LabelColor = Color.FromRgba(0, 0, 0, 200); if (isTick) { rangeSlider.TickPlacement = TickPlacement.Inline; } } } } } <file_sep>/Forms/Carousel/Carousel/Converter/Converters.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfCarousel { #region converter /// <summary> /// Text to proper conveter. /// </summary> public class TextToProperConveter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value.ToString().Replace("-WF", ""); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } /// <summary> /// Font icon converter. /// </summary> public class FontIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string path = parameter.ToString(); if (Device.RuntimePlatform == "Android") { return path; } else if (Device.RuntimePlatform == "iOS") { string fontname = path.Substring(path.IndexOf('#') + 1, path.Length - 1 - path.IndexOf('#')); return fontname; } else { #if COMMONSB return "/Assets/Fonts/" + path; #else if (Core.SampleBrowser.IsIndividualSB) { return "/Assets/Fonts/"+path; } else { return $"ms-appx:///SampleBrowser.SfCarousel.UWP/Assets/Fonts/"+path; } #endif } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class UnWantedTextRemove : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string text = value.ToString(); if(text.Contains("-")) { string temp = text.Substring(0, text.IndexOf('-')); return temp; } return text; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } #endregion } <file_sep>/Forms/CircularGauge/CircularGauge/Samples/DirectionCompass/DirectionCompass.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Xamarin.Forms.Internals; namespace SampleBrowser.SfCircularGauge { [Preserve(AllMembers = true)] public partial class DirectionCompass : SampleView { public DirectionCompass() { InitializeComponent(); needlePointerColorPicker.SelectedIndex = 0; needlePointerColorPicker.SelectedIndexChanged += NeedlePointerColorPicker_SelectedIndexChanged; #region Conditions if (Device.Idiom == TargetIdiom.Tablet || Device.Idiom == TargetIdiom.Desktop) { pointer1.Thickness = 50; pointer2.Thickness = 50; scale.LabelOffset = 0.81; } #endregion Conditions } private void NeedlePointerColorPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (needlePointerColorPicker.SelectedIndex) { case 0: viewModel.NeedlePointerColor = Color.FromHex("#f03e3e"); break; case 1: viewModel.NeedlePointerColor = Color.FromHex("#4472c4"); break; case 2: viewModel.NeedlePointerColor = Color.FromHex("#ed7d31"); break; } } private void scale_LabelCreated(object sender, Syncfusion.SfGauge.XForms.LabelCreatedEventArgs args) { switch ((string)args.LabelContent) { case "0": args.LabelContent = "N"; break; case "2": args.LabelContent = "NE"; break; case "4": args.LabelContent = "E"; break; case "6": args.LabelContent = "SE"; break; case "8": args.LabelContent = "S"; break; case "10": args.LabelContent = "SW"; break; case "12": args.LabelContent = "W"; break; case "14": args.LabelContent = "NW"; break; } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/SplineArea.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class SplineArea : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Inflation Rate in Percentage"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.Visibility = Visibility.Visible; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.ToggleSeriesVisibility = true; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; NumericalAxis primaryAxis = new NumericalAxis(); primaryAxis.ShowMajorGridLines = false; primaryAxis.Interval = 2; primaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; chart.PrimaryAxis = primaryAxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Minimum = 0; numericalaxis.Maximum = 4; numericalaxis.Interval = 1; numericalaxis.MajorTickStyle.TickSize = 0; numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.LabelStyle.LabelFormat = "#'% '"; chart.SecondaryAxis = numericalaxis; var areaSeries1 = new SplineAreaSeries { Label = "US", Alpha = 0.5f, EnableAnimation = true, ItemsSource = MainPage.GetSplineAreaData1(), XBindingPath = "XValue", YBindingPath = "YValue", LegendIcon = ChartLegendIcon.SeriesType }; var areaSeries2 = new SplineAreaSeries { Alpha = 0.5f, Label = "France", EnableAnimation = true, ItemsSource = MainPage.GetSplineAreaData2(), XBindingPath = "XValue", YBindingPath = "YValue", LegendIcon = ChartLegendIcon.SeriesType }; var areaSeries3 = new SplineAreaSeries { Alpha = 0.5f, Label = "Germany", EnableAnimation = true, ItemsSource = MainPage.GetSplineAreaData3(), XBindingPath = "XValue", YBindingPath = "YValue", LegendIcon = ChartLegendIcon.SeriesType }; chart.Series.Add(areaSeries1); chart.Series.Add(areaSeries2); chart.Series.Add(areaSeries3); areaSeries1.TooltipEnabled = true; areaSeries2.TooltipEnabled = true; areaSeries3.TooltipEnabled = true; areaSeries1.EnableAnimation = true; areaSeries2.EnableAnimation = true; areaSeries3.EnableAnimation = true; return chart; } } }<file_sep>/Forms/RangeNavigator/RangeNavigator/Samples/SimpleRangeNavigator/RangeNavViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using Syncfusion.SfChart.XForms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfRangeNavigator { [Preserve(AllMembers = true)] public class RangeNavViewModel { public ObservableCollection<ChartDataPoint> DateTimeRangeData { get; set; } public RangeNavViewModel() { DateTimeRangeData = new ObservableCollection<ChartDataPoint> { new ChartDataPoint(new DateTime(2015, 01, 1), 14), new ChartDataPoint(new DateTime(2015, 02, 1), 54), new ChartDataPoint(new DateTime(2015, 03, 1), 23), new ChartDataPoint(new DateTime(2015, 04, 1), 53), new ChartDataPoint(new DateTime(2015, 05, 1), 25), new ChartDataPoint(new DateTime(2015, 06, 1), 32), new ChartDataPoint(new DateTime(2015, 07, 1), 78), new ChartDataPoint(new DateTime(2015, 08, 1), 100), new ChartDataPoint(new DateTime(2015, 09, 1), 55), new ChartDataPoint(new DateTime(2015, 10, 1), 38), new ChartDataPoint(new DateTime(2015, 11, 1), 27), new ChartDataPoint(new DateTime(2015, 12, 1), 56), new ChartDataPoint(new DateTime(2015, 12, 31), 35) }; } } }<file_sep>/Android/SampleBrowser/Samples/SfPicker/GettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Com.Syncfusion.SfPicker; namespace SampleBrowser { public class SfPickerDemo : SamplePage { SfPicker sfpicker; TextView eventLog; Spinner showHeaderSpinner, showColumnHeaderSpinner; int width; Context context1; TextView showHeaderText, showColumnHeaderText, headerText; EditText headerTextView; ArrayAdapter<String> dataAdapter; public SfPickerDemo() { } public override View GetSampleContent(Context con) { float height = con.Resources.DisplayMetrics.HeightPixels; ; LinearLayout layout = new LinearLayout(con); Typeface tf = Typeface.CreateFromAsset(con.Assets, "Segoe_MDL2_Assets.ttf"); layout.Orientation = Android.Widget.Orientation.Vertical; sfpicker = new SfPicker(con); sfpicker.ShowHeader = true; List<String> source = new List<string>(); source.Add("Yellow"); source.Add("Green"); source.Add("Orange"); source.Add("Lime"); source.Add("LightBlue"); source.Add("Pink"); source.Add("SkyBlue"); source.Add("White"); source.Add("Red"); source.Add("Aqua"); sfpicker.ItemsSource = source; sfpicker.LayoutParameters = new ViewGroup.LayoutParams(Android.Views.ViewGroup.LayoutParams.MatchParent, (int)(height * 0.60)); sfpicker.PickerMode = PickerMode.Default; sfpicker.ShowFooter = false; sfpicker.ShowColumnHeader = false; sfpicker.UnSelectedItemTextColor = Color.Black; sfpicker.SelectedIndex = 7; float density = con.Resources.DisplayMetrics.Density; eventLog = new TextView(con); eventLog.LayoutParameters = new ViewGroup.LayoutParams(800, 400); layout.SetGravity(GravityFlags.CenterHorizontal); layout.AddView(sfpicker); string headerText1 = "PICK A COLOR"; sfpicker.ShowHeader = true; sfpicker.HeaderText = headerText1; sfpicker.BorderColor = Color.Red; TextView textview = new TextView(con); textview.Text = "Event Log"; textview.Typeface = tf; textview.SetTextColor(Color.Black); textview.TextSize = 20; if (density > 2) textview.SetPadding(20, 0, 0, 20); else textview.SetPadding(10, 0, 0, 10); layout.AddView(textview); var scrollviewer = new ScrollView(con); var textFrame = new LinearLayout(con); textFrame.Orientation = Android.Widget.Orientation.Vertical; scrollviewer.AddView(textFrame); scrollviewer.VerticalScrollBarEnabled = true; FrameLayout bottomFrame = new FrameLayout(con); bottomFrame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(height * 0.40)); bottomFrame.SetBackgroundColor(Color.Silver); bottomFrame.AddView(scrollviewer); bottomFrame.SetPadding(10, 0, 10, 0); layout.AddView(bottomFrame); sfpicker.ColumnHeaderText = "COLOR"; sfpicker.OnSelectionChanged += (sender, e) => { eventLog = new TextView(con); eventLog.SetTextColor(Color.Black); if (textFrame.ChildCount == 6) textFrame.RemoveViewAt(0); textFrame.AddView(eventLog); eventLog.Text = (e.NewValue).ToString() + " " + "has been Selected"; Color color = PickerHelper.GetColor(e.NewValue.ToString()); sfpicker.SetBackgroundColor(color); sfpicker.Background.Alpha = 128; scrollviewer.ScrollTo(0, textFrame.Bottom); }; return layout; } public override View GetPropertyWindowLayout(Android.Content.Context context) { context1 = context; width = (context.Resources.DisplayMetrics.WidthPixels) / 2; showHeaderLayout(); showColumnHeaderLayout(); HeaderTextLayout(); /****************** **propertylayout** ******************/ //Separator LinearLayout.LayoutParams separatorLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); separatorLayoutParams.SetMargins(0, 20, 0, 0); SeparatorView separate = new SeparatorView(context1, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; propertylayout.AddView(showHeaderText); propertylayout.AddView(showHeaderSpinner); propertylayout.SetPadding(10, 10, 10, 40); propertylayout.AddView(showColumnHeaderText); propertylayout.AddView(showColumnHeaderSpinner); propertylayout.AddView(headerText); propertylayout.AddView(headerTextView); showHeaderText.SetPadding(0, 0, 0, 40); showHeaderSpinner.SetPadding(0, 0, 0, 50); showColumnHeaderText.SetPadding(0, 40, 0, 40); showColumnHeaderSpinner.SetPadding(0, 0, 0, 50); headerText.SetPadding(0, 40, 0, 40); headerTextView.SetPadding(0, 0, 0, 50); return propertylayout; } private void showHeaderLayout() { showHeaderText = new TextView(context1); showHeaderText.TextSize = 20; showHeaderText.Text = "Show Header"; showHeaderSpinner = new Spinner(context1, SpinnerMode.Dialog); //View Mode List List<String> showHeaderList = new List<String>(); showHeaderList.Add("False"); showHeaderList.Add("True"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context1, Android.Resource.Layout.SimpleSpinnerItem, showHeaderList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); showHeaderSpinner.Adapter = dataAdapter; //Mode Spinner Item Selected Listener showHeaderSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("True")) { sfpicker.ShowHeader = true; } if (selectedItem.Equals("False")) { sfpicker.ShowHeader = false; } }; } private void showColumnHeaderLayout() { showColumnHeaderText = new TextView(context1); showColumnHeaderText.TextSize = 20; showColumnHeaderText.Text = "Show Column Header"; showColumnHeaderSpinner = new Spinner(context1, SpinnerMode.Dialog); //View Mode List List<String> showColumnHeaderList = new List<String>(); showColumnHeaderList.Add("False"); showColumnHeaderList.Add("True"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context1, Android.Resource.Layout.SimpleSpinnerItem, showColumnHeaderList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); showColumnHeaderSpinner.Adapter = dataAdapter; //Mode Spinner Item Selected Listener showColumnHeaderSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("True")) { sfpicker.ShowColumnHeader = true; } if (selectedItem.Equals("False")) { sfpicker.ShowColumnHeader = false; } }; } private void HeaderTextLayout() { headerText = new TextView(context1); headerText.TextSize = 20; headerText.Text = "Header Text"; headerTextView = new EditText(context1); headerTextView.TextSize = 18; headerTextView.Text = "PICK A COLOR"; headerTextView.TextChanged += (sender, e) => { sfpicker.HeaderText = e.Text.ToString(); }; } } public static class PickerHelper { static Dictionary<string, Color> colors = new Dictionary<string, Color>(); public static Color GetColor(object color) { colors.Clear(); colors.Add("Yellow", Color.Yellow); colors.Add("Green", Color.Green); colors.Add("Orange", Color.Orange); colors.Add("Lime", Color.Lime); colors.Add("LightBlue", Color.LightBlue); colors.Add("Pink", Color.Pink); colors.Add("SkyBlue", Color.SkyBlue); colors.Add("White", Color.White); colors.Add("Red", Color.Red); colors.Add("Aqua", Color.Aqua); return colors[color.ToString()]; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/AppointmentEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using nuint = System.Int32; using System.Drawing; #endif namespace SampleBrowser { public class AppointmentEditor : SampleView { SFSchedule schedule; static UIView editor; static UIButton button_cancel; static UIButton button_save; static UITextView label_subject; static UITextView label_location; static UILabel label_starts; static UILabel label_ends; static UIButton button_startDate; static UIButton button_endDate; static UIDatePicker picker_startDate; static UIDatePicker picker_endDate; static UIButton done_button; static ScheduleAppointment selectedAppointment; static int indexOfAppointment; //UITapGestureRecognizer tapGesture; public AppointmentEditor() { schedule = new SFSchedule(); editor = new UIView(); schedule.CellTapped += Schedule_ScheduleTapped; schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; schedule.Appointments = CreateAppointments(); createEditor(); this.AddSubview(schedule); schedule.Hidden = false; editor.Hidden = true; this.AddSubview(editor); // control = this; } private void Schedule_ScheduleTapped(object sender, CellTappedEventArgs e) { editor.Hidden = false; schedule.Hidden = true; indexOfAppointment = -1; if (e.ScheduleAppointment != null) { for (nuint i = 0; i < schedule.Appointments.Count; i++) { if (schedule.Appointments.GetItem<ScheduleAppointment>(i) == e.ScheduleAppointment) { indexOfAppointment = int.Parse(i.ToString()); break; } } selectedAppointment = (e.ScheduleAppointment); label_subject.Text = selectedAppointment.Subject; label_location.Text = selectedAppointment.Location; String _sDate = DateTime.Parse((selectedAppointment.StartTime.ToString())).ToString(); button_startDate.SetTitle(_sDate, UIControlState.Normal); picker_startDate.SetDate(selectedAppointment.StartTime, true); String _eDate = DateTime.Parse((selectedAppointment.EndTime.ToString())).ToString(); button_endDate.SetTitle(_eDate, UIControlState.Normal); picker_endDate.SetDate(selectedAppointment.EndTime, true); editor.EndEditing(true); } else { List<UIColor> colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); label_subject.Text = "Subject"; label_location.Text = "Location"; String _sDate = DateTime.Parse((e.Date.ToString())).ToString(); picker_startDate.SetDate(e.Date, true); button_startDate.SetTitle(_sDate, UIControlState.Normal); String _eDate = DateTime.Parse((e.Date.AddSeconds(3600).ToString())).ToString(); picker_endDate.SetDate(e.Date.AddSeconds(3600), true); button_endDate.SetTitle(_eDate, UIControlState.Normal); } } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = new CGRect(Frame.X, 0, Frame.Width, Frame.Height); } nfloat yMargin = nfloat.Parse((this.Frame.Height * 0.1).ToString()); nfloat xMargin = nfloat.Parse((this.Frame.Width * 0.1).ToString()); nfloat elementWidth = nfloat.Parse((this.Frame.Width - (xMargin * 2)).ToString()); button_cancel.Frame = new CGRect(20, yMargin, 200, 30); button_save.Frame = new CGRect((this.Frame.Width) - 220, yMargin, 200, 30); label_subject.Frame = new CGRect(xMargin, yMargin * 2, elementWidth, 30); label_location.Frame = new CGRect(xMargin, yMargin * 3, elementWidth, 30); label_starts.Frame = new CGRect(xMargin, yMargin * 4, elementWidth, 30); button_startDate.Frame = new CGRect(xMargin, yMargin * 5, elementWidth, 30); label_ends.Frame = new CGRect(xMargin, yMargin * 6, elementWidth, 30); button_endDate.Frame = new CGRect(xMargin, yMargin * 7, elementWidth, 30); picker_startDate.Frame = new CGRect(xMargin, yMargin * 4, elementWidth, 200); picker_endDate.Frame = new CGRect(xMargin, yMargin * 4, elementWidth, 200); done_button.Frame = new CGRect(xMargin, yMargin * 4, elementWidth, 30); base.LayoutSubviews(); } private void createEditor() { button_cancel = new UIButton(); button_save = new UIButton(); label_subject = new UITextView(); label_location = new UITextView(); label_ends = new UILabel(); label_starts = new UILabel(); button_startDate = new UIButton(); button_endDate = new UIButton(); picker_startDate = new UIDatePicker(); picker_endDate = new UIDatePicker(); done_button = new UIButton(); //cancel button button_cancel.SetTitle("Cancel", UIControlState.Normal); button_cancel.SetTitleColor(UIColor.Blue, UIControlState.Normal); button_cancel.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_cancel.TouchUpInside += (object sender, EventArgs e) => { editor.Hidden = true; schedule.Hidden = false; editor.EndEditing(true); }; //save button button_save.SetTitle("Save", UIControlState.Normal); button_save.SetTitleColor(UIColor.Blue, UIControlState.Normal); button_save.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_save.TouchUpInside += (object sender, EventArgs e) => { if (indexOfAppointment != -1) { schedule.Appointments.GetItem<ScheduleAppointment>(nuint.Parse(indexOfAppointment.ToString())).Subject = (NSString)label_subject.Text; schedule.Appointments.GetItem<ScheduleAppointment>(nuint.Parse(indexOfAppointment.ToString())).Location = (NSString)label_location.Text; schedule.Appointments.GetItem<ScheduleAppointment>(nuint.Parse(indexOfAppointment.ToString())).StartTime = picker_startDate.Date; schedule.Appointments.GetItem<ScheduleAppointment>(nuint.Parse(indexOfAppointment.ToString())).EndTime = picker_endDate.Date; } else { ScheduleAppointment appointment = new ScheduleAppointment(); appointment.Subject = (NSString)label_subject.Text; appointment.Location = (NSString)label_location.Text; appointment.StartTime = picker_startDate.Date; appointment.EndTime = picker_endDate.Date; appointment.AppointmentBackground = UIColor.FromRGB(0xA2, 0xC1, 0x39); schedule.Appointments.Add(appointment); } editor.Hidden = true; schedule.Hidden = false; schedule.ReloadData(); editor.EndEditing(true); }; //subject label label_subject.TextColor = UIColor.Black; label_subject.TextAlignment = UITextAlignment.Left; label_subject.Layer.CornerRadius = 8; label_subject.Layer.BorderWidth = 2; label_subject.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //location label label_location.TextColor = UIColor.Black; label_location.TextAlignment = UITextAlignment.Left; label_location.Layer.CornerRadius = 8; label_location.Layer.BorderWidth = 2; label_location.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //starts time label_starts.Text = "Start Time :"; label_starts.TextColor = UIColor.Black; button_startDate.SetTitle("Start time", UIControlState.Normal); button_startDate.SetTitleColor(UIColor.Blue, UIControlState.Normal); button_startDate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_startDate.TouchUpInside += (object sender, EventArgs e) => { picker_startDate.Hidden = false; done_button.Hidden = false; label_ends.Hidden = true; button_endDate.Hidden = true; button_startDate.Hidden = true; label_starts.Hidden = true; editor.EndEditing(true); }; //end time label_ends.Text = "End Time :"; label_ends.TextColor = UIColor.Black; //end date button_endDate.SetTitle("End time", UIControlState.Normal); button_endDate.SetTitleColor(UIColor.Blue, UIControlState.Normal); button_endDate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_endDate.TouchUpInside += (object sender, EventArgs e) => { picker_endDate.Hidden = false; done_button.Hidden = false; label_ends.Hidden = true; button_endDate.Hidden = true; button_startDate.Hidden = true; label_starts.Hidden = true; editor.EndEditing(true); }; //date and time pickers picker_startDate.Hidden = true; picker_endDate.Hidden = true; //done button done_button.SetTitle("Done", UIControlState.Normal); done_button.SetTitleColor(UIColor.Blue, UIControlState.Normal); done_button.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; done_button.TouchUpInside += (object sender, EventArgs e) => { picker_startDate.Hidden = true; picker_endDate.Hidden = true; done_button.Hidden = true; label_ends.Hidden = false; button_endDate.Hidden = false; button_startDate.Hidden = false; label_starts.Hidden = false; String _sDate = DateTime.Parse((picker_startDate.Date.ToString())).ToString(); button_startDate.SetTitle(_sDate, UIControlState.Normal); String _eDate = DateTime.Parse((picker_endDate.Date.ToString())).ToString(); button_endDate.SetTitle(_eDate, UIControlState.Normal); editor.EndEditing(true); }; button_cancel.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 10, 100, 30); button_save.Frame = new CGRect(100, this.Frame.Y + 10, 300, 30); label_subject.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 50, 300, 30); label_location.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 90, 300, 30); label_starts.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 140, 300, 30); button_startDate.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, 300, 30); label_ends.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 220, 300, 30); button_endDate.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 260, 300, 30); picker_startDate.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, 300, 30); picker_endDate.Frame = new CGRect(100, this.Frame.Y + 180, 300, 30); picker_endDate.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, 300, 30); done_button.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, 300, 30); done_button.Hidden = true; editor.Add(button_cancel); editor.Add(button_save); editor.Add(label_subject); editor.Add(label_location); editor.Add(label_starts); editor.Add(button_startDate); editor.Add(label_ends); editor.Add(button_endDate); editor.Add(picker_endDate); editor.Add(picker_startDate); editor.Add(done_button); } NSMutableArray CreateAppointments() { NSDate today = new NSDate(); setColors(); setSubjects(); NSMutableArray appCollection = new NSMutableArray(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)subjectCollection[i]; appointment.AppointmentBackground = colorCollection[i]; appCollection.Add(appointment); } return appCollection; } List<String> subjectCollection; private void setSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); } // adding colors collection List<UIColor> colorCollection; private void setColors() { colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0xF0, 0x96, 0x09)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Trackball.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Com.Syncfusion.Navigationdrawer; using System; using System.Collections.Generic; namespace SampleBrowser { [Activity(Label = "Trackball")] public class Trackball : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Average sales for person"; chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; DateTimeAxis primaryAxis = new DateTimeAxis(); primaryAxis.PlotOffset = 5; primaryAxis.AxisLineOffset = 5; primaryAxis.ShowMajorGridLines = false; primaryAxis.Interval = 1; primaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; primaryAxis.EdgeLabelsVisibilityMode = EdgeLabelsVisibilityMode.Visible; primaryAxis.LabelStyle.LabelFormat = "yyyy"; chart.PrimaryAxis = primaryAxis; chart.PrimaryAxis.ShowMajorGridLines = false; chart.SecondaryAxis = new NumericalAxis { }; chart.SecondaryAxis.MajorTickStyle.TickSize = 0; chart.SecondaryAxis.LineStyle.StrokeWidth = 0; (chart.SecondaryAxis as NumericalAxis).Maximum = 80; (chart.SecondaryAxis as NumericalAxis).Minimum = 10; (chart.SecondaryAxis as NumericalAxis).Interval = 10; chart.SecondaryAxis.Title.Text = "Revenue"; chart.SecondaryAxis.LabelStyle.LabelFormat = "#'M '"; var series = new LineSeries { ItemsSource = MainPage.GetSeriesData1(), XBindingPath = "Date", YBindingPath = "YValue", Label = "John", Color = Color.ParseColor("#00BDAE"), StrokeWidth= 3 }; series.DataMarker.MarkerStrokeColor = Color.ParseColor("#00BDAE"); series.DataMarker.ShowMarker = true; series.DataMarker.MarkerColor = Color.White; series.DataMarker.MarkerStrokeWidth = 2; series.DataMarker.MarkerWidth = 6; series.DataMarker.MarkerHeight = 6; chart.Series.Add(series); series = new LineSeries { ItemsSource = MainPage.GetSeriesData2(), XBindingPath = "Date", YBindingPath = "YValue", Color = Color.ParseColor("#404041"), Label = "Andrew", StrokeWidth = 3 }; series.DataMarker.MarkerStrokeColor = Color.ParseColor("#404041"); series.DataMarker.ShowMarker = true; series.DataMarker.MarkerColor = Color.White; series.DataMarker.MarkerStrokeWidth = 2; series.DataMarker.MarkerWidth = 6; series.DataMarker.MarkerHeight = 6; chart.Series.Add(series); series = new LineSeries { ItemsSource = MainPage.GetSeriesData3(), XBindingPath = "Date", YBindingPath = "YValue", Color = Color.ParseColor("#357CD2"), Label = "Thomas", StrokeWidth = 3 }; series.DataMarker.MarkerStrokeColor = Color.ParseColor("#357CD2"); series.DataMarker.ShowMarker = true; series.DataMarker.MarkerColor = Color.White; series.DataMarker.MarkerStrokeWidth = 2; series.DataMarker.MarkerWidth = 6; series.DataMarker.MarkerHeight = 6; chart.Series.Add(series); chart.Behaviors.Add(new ChartTrackballBehavior()); var label = new TextView(context); label.SetPadding(5, 5, 5, 5); label.Text = "Press and hold to enable trackball."; var layout = new LinearLayout(context){ Orientation = Android.Widget.Orientation.Vertical }; var layoutLabel = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Horizontal, LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent) }; layoutLabel.SetHorizontalGravity(GravityFlags.CenterHorizontal); layoutLabel.AddView(label); layout.AddView(layoutLabel); layout.AddView(chart); return layout; } public override View GetPropertyWindowLayout(Android.Content.Context context) { /** * Property Window * */ int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; LinearLayout propertylayout = new LinearLayout(context); //= new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams( width * 2, 5); layoutParams1.SetMargins(0, 20, 0, 0); TextView labelDisplayMode = new TextView(context); labelDisplayMode.TextSize = 20; labelDisplayMode.Text = "LabelDisplay Mode"; Spinner selectLabelMode = new Spinner(context,SpinnerMode.Dialog); List<String> adapter = new List<String>() { "FloatAllPoints", "NearestPoint", "GroupAllPoints" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); ChartTrackballBehavior trackballBehavior = (chart.Behaviors[0] as ChartTrackballBehavior); if (selectedItem.Equals("NearestPoint")) { trackballBehavior.LabelDisplayMode = TrackballLabelDisplayMode.NearestPoint; } else if (selectedItem.Equals("FloatAllPoints")) { trackballBehavior.LabelDisplayMode = TrackballLabelDisplayMode.FloatAllPoints; } else if (selectedItem.Equals("GroupAllPoints")) { trackballBehavior.LabelDisplayMode = TrackballLabelDisplayMode.GroupAllPoints; } }; propertylayout.AddView(labelDisplayMode); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); propertylayout.AddView(separate, layoutParams1); propertylayout.AddView(selectLabelMode); return propertylayout; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/RenderingDynamicData.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Syncfusion.SfDataGrid; using CoreGraphics; namespace SampleBrowser { public class RenderingDynamicData:SampleView { #region Fields SfDataGrid SfGrid; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public RenderingDynamicData () { this.SfGrid = new SfDataGrid (); this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.ItemsSource = new StocksViewModel ().Stocks; if (Utility.IsIpad) this.SfGrid.ColumnSizer = ColumnSizer.Star; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.GridStyle.AlternatingRowColor = UIColor.FromRGB (219, 219, 219); this.AddSubview (SfGrid); } void GridAutoGenerateColumns (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "LastTrade") { e.Column.HeaderText = "Last Trade"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "Change") { e.Column.TextAlignment = UITextAlignment.Right; } else if (e.Column.MappingName == "PreviousClose") { e.Column.HeaderText = "Previous Close"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "Open") { e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "Account") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; e.Column.Format = "C"; } else if (e.Column.MappingName == "Symbol") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "Volume") { e.Column.TextAlignment = UITextAlignment.Center; } else if(e.Column.MappingName == "StockChange") { e.Column.UserCellType = typeof(StockCell); e.Column.AllowSorting = false; } } public override void LayoutSubviews () { this.SfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews (); } protected override void Dispose(bool disposing) { SfGrid.Dispose(); base.Dispose(disposing); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataForm/ContactForm.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using Syncfusion.iOS.DataForm; using CoreGraphics; namespace SampleBrowser { public class ContactForm : SampleView { #region Fields SfDataForm dataForm; UITableView tableView; UIButton button; DataFormController dataFormController; #endregion UIView uIView; public ContactForm() { dataForm = new SfDataForm(); dataForm.LayoutManager = new DataFormLayoutManagerExt(dataForm); tableView = new UITableView(); tableView.RowHeight = 50; tableView.SeparatorColor = UIColor.Clear; dataFormController = new DataFormController(dataForm, tableView); tableView.Source = new ContactTableSource(dataFormController, new ListViewGroupingViewModel().ContactsInfo); this.AddSubview(tableView); button = new UIButton(); uIView = new UIView(); uIView.AddSubview(button); uIView.BackgroundColor = UIColor.FromRGB(242.0f / 255.0f, 242.0f / 255.0f, 242.0f / 255.0f); button.SetTitle("Add", UIControlState.Normal); button.SetTitleColor(this.TintColor, UIControlState.Normal); button.TouchDown += Button_TouchDown; this.AddSubview(this.tableView); this.AddSubview(uIView); } private void Button_TouchDown(object sender, EventArgs e) { var navigationController = UIApplication.SharedApplication.KeyWindow.RootViewController as UINavigationController; dataFormController.refreshLayout = false; dataFormController.UpDateDataFormView(new ContactInfo(), true); dataFormController.UpdateView(); navigationController.PushViewController(dataFormController, false); } public override void LayoutSubviews() { button.Frame = new CGRect(this.Frame.Width - 100, 0, 100, 50); uIView.Frame = (new CGRect(0, 0, this.Frame.Width, 50)); this.tableView.Frame = new CGRect(0, uIView.Bounds.Height, this.Frame.Width, this.Frame.Height - 50); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }<file_sep>/Forms/ImageEditor/ImageEditor/Samples/ProfileEditor/ProfileEditor.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Reflection; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfImageEditor { public partial class ProfileEditor : SampleView { public ProfileEditor() { InitializeComponent(); } private void Button_Clicked(object sender, EventArgs e) { Navigation.PushAsync(new ProfileEditPage(ViewModel)); } } public class ProfileEditorViewModel : INotifyPropertyChanged { public ProfileEditorViewModel() { Assembly assembly = typeof(ImageSerializeModel).GetTypeInfo().Assembly; #if COMMONSB ProfilePicture = ImageSource.FromResource("SampleBrowser.Icons.Profile.png", assembly); #else ProfilePicture = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.Profile.png", assembly); #endif Details = new List<ProfileModel>(); Details.Add(new ProfileModel() { Icon = "\ue72a", Field = "Name", Content = "<NAME>" }); Details.Add(new ProfileModel() { Icon = "\ue725", Field = "Email", Content = "<EMAIL>" }); Details.Add(new ProfileModel() { Icon = "\ue766", Field = "Phone", Content = "+1-123-456-7890" }); Details.Add(new ProfileModel() { Icon = "\ue757", Field = "Address", Content = "Avenue 2nd street, NW SY" }); } private ImageSource profilePicture; public event PropertyChangedEventHandler PropertyChanged; public ImageSource ProfilePicture { get { return profilePicture; } set { profilePicture = value; RaisePropertyChanged("ProfilePicture"); } } private byte[] byteArray; public byte[] ByteArray { get { return byteArray; } set { byteArray = value; ProfilePicture = ImageSource.FromStream(() => new MemoryStream(value)); } } public List<ProfileModel> Details { get; set; } void RaisePropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public class ProfileModel { public string Icon { get; set; } public string Field { get; set; } public string Content { get; set; } } } <file_sep>/iOS/SampleBrowser/Samples/Chart/ChartAnnotation.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using CoreAnimation; #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using CoreGraphics; using Foundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.CoreGraphics; using MonoTouch.UIKit; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class ChartAnnotation : SampleView { public ChartAnnotation() { SFChart chart = new SFChart(); chart.PrimaryAxis = new SFNumericalAxis() { Minimum = new NSNumber(0), Maximum = new NSNumber(4), ShowMajorGridLines = false }; chart.SecondaryAxis = new SFNumericalAxis() { Minimum = new NSNumber(20), Maximum = new NSNumber(70), ShowMajorGridLines = false, }; VerticalLineAnnotation VerticalLineAnnotation = new VerticalLineAnnotation(); VerticalLineAnnotation.X1 = 2; VerticalLineAnnotation.LineCap = ChartLineCap.Arrow; VerticalLineAnnotation.Text = "Vertical Line"; VerticalLineAnnotation.ShowAxisLabel = true; HorizontalLineAnnotation horizontalLineAnnotation = new HorizontalLineAnnotation(); horizontalLineAnnotation.Y1 = 45; horizontalLineAnnotation.LineCap = ChartLineCap.Arrow; horizontalLineAnnotation.Text = "Horizontal Line"; horizontalLineAnnotation.ShowAxisLabel = true; LineAnnotation lineAnnotation = new LineAnnotation(); lineAnnotation.X1 = 2.5; lineAnnotation.X2 = 3.5; lineAnnotation.Y1 = 52; lineAnnotation.Y2 = 63; lineAnnotation.LineCap = ChartLineCap.Arrow; lineAnnotation.Text = "Line"; RectangleAnnotation rectangleAnnotation = new RectangleAnnotation(); rectangleAnnotation.Text = "Rectangle"; rectangleAnnotation.X1 = 0.5; rectangleAnnotation.X2 = 1.5; rectangleAnnotation.Y1 = 25; rectangleAnnotation.Y2 = 35; EllipseAnnotation ellipseAnnotation = new EllipseAnnotation(); ellipseAnnotation.Text = "Ellipse"; ellipseAnnotation.X1 = 2.5; ellipseAnnotation.X2 = 3.5; ellipseAnnotation.Y1 = 25; ellipseAnnotation.Y2 = 35; TextAnnotation textAnnotation = new TextAnnotation(); textAnnotation.X1 = 1; textAnnotation.Y1 = 57.5; textAnnotation.Text = "Text Annotation"; chart.Annotations.Add(VerticalLineAnnotation); chart.Annotations.Add(horizontalLineAnnotation); chart.Annotations.Add(lineAnnotation); chart.Annotations.Add(rectangleAnnotation); chart.Annotations.Add(ellipseAnnotation); chart.Annotations.Add(textAnnotation); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } } <file_sep>/Forms/BadgeView/BadgeView/Samples/Customization/Customization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "BadgeCustomization.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfBadgeView { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.BadgeView; using Syncfusion.XForms.Buttons; using Xamarin.Forms; using Xamarin.Forms.Xaml; /// <summary> /// Badge Customization class. /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public partial class Customization : SampleView { private bool isUpdate = false; /// <summary> /// Initializes a new instance of the <see cref="BadgeCustomization" /> class. /// </summary> public Customization() { this.InitializeComponent(); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { this.textBadgeIcon.IsVisible = false; this.textBadgeType.IsVisible = false; this.textBadgeIconGrid.IsVisible = true; this.textBadgeTypeGrid.IsVisible = true; this.badgeTypePicker.SelectedIndex = 6; this.badgeIconPicker.SelectedIndex = 3; this.badgeIconCard.HorizontalOptions = LayoutOptions.Start; this.badgeTypeCard.HorizontalOptions = LayoutOptions.Start; } if (Device.RuntimePlatform == Device.WPF) { badgeSetting.Offset = new Point(-8, -8); this.badgeIconPicker.HeightRequest = 25; this.badgeTypePicker.HeightRequest = 25; } else { badgeSetting.Offset = new Point(-10, -10); } this.badgeIcon.SelectedIndex = 3; this.badgeType.SelectedIndex = 6; isUpdate = true; DynamicUpdate(); } /// <summary> /// Dynamic update for badge text animation /// </summary> private async void DynamicUpdate() { double badgeText = 10; while (isUpdate && this.badge1 != null) { badgeText += 1; this.badge1.BadgeText = badgeText.ToString(); await Task.Delay(2000); } } public override void OnDisappearing() { base.OnDisappearing(); isUpdate = false; } /// <summary> /// This method is called when picker collection changed /// </summary> /// <param name="sender">Gets the sender</param> /// <param name="e">Gets the event args</param> private void Picker1_SelectedIndexChanged(object sender, EventArgs e) { if (this.badge != null && this.badge.BadgeSettings != null) { var picker = sender as Picker; switch (picker.SelectedIndex) { case 0: { viewModel.BadgeIcon = BadgeIcon.None; } break; case 1: { viewModel.BadgeIcon = BadgeIcon.Busy; this.badge2.BadgeSettings.BadgeType = BadgeType.Error; } break; case 2: { viewModel.BadgeIcon = BadgeIcon.Add; this.badge2.BadgeSettings.BadgeType = BadgeType.Success; } break; case 3: { viewModel.BadgeIcon = BadgeIcon.Available; this.badge2.BadgeSettings.BadgeType = BadgeType.Success; } break; case 4: { viewModel.BadgeIcon = BadgeIcon.Prohibit1; this.badge2.BadgeSettings.BadgeType = BadgeType.Error; } break; case 5: { viewModel.BadgeIcon = BadgeIcon.Prohibit2; this.badge2.BadgeSettings.BadgeType = BadgeType.Error; } break; case 6: { viewModel.BadgeIcon = BadgeIcon.Away; this.badge2.BadgeSettings.BadgeType = BadgeType.Warning; } break; case 7: { viewModel.BadgeIcon = BadgeIcon.Delete; this.badge2.BadgeSettings.BadgeType = BadgeType.Error; } break; case 8: { viewModel.BadgeIcon = BadgeIcon.Dot; this.badge2.BadgeSettings.BadgeType = BadgeType.Error; } break; } } } /// <summary> /// This method is called when picker selection changed /// </summary> /// <param name="sender">Gets the sender </param> /// <param name="e">Gets the eventArgs</param> private void Picker2_SelectedIndexChanged(object sender, EventArgs e) { if (this.badge != null && this.badge.BadgeSettings != null) { var picker = sender as Picker; TextColorSegment.IsEnabled = false; switch (picker.SelectedIndex) { case 0: viewModel.BadgeType = BadgeType.Primary; TextColorSegment.Opacity = 0.3; break; case 1: viewModel.BadgeType = BadgeType.Secondary; TextColorSegment.Opacity = 0.3; break; case 2: viewModel.BadgeType = BadgeType.Light; TextColorSegment.Opacity = 0.3; break; case 3: viewModel.BadgeType = BadgeType.Dark; TextColorSegment.Opacity = 0.3; break; case 4: viewModel.BadgeType = BadgeType.Success; TextColorSegment.Opacity = 0.3; break; case 5: viewModel.BadgeType = BadgeType.Warning; TextColorSegment.Opacity = 0.3; break; case 6: viewModel.BadgeType = BadgeType.Error; TextColorSegment.Opacity = 0.3; break; case 7: viewModel.BadgeType = BadgeType.Info; TextColorSegment.Opacity = 0.3; break; case 8: { viewModel.BadgeType = BadgeType.None; TextColorSegment.IsEnabled = true; TextColorSegment.Opacity = 1; } break; } } } } #region Color to chip converter public class ColorToChipConverter : IValueConverter { #region Member SfChip selectedChip = null; #endregion #region Convert public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { ObservableCollection<SfChip> colorChips = new ObservableCollection<SfChip>(); foreach (var item in value as ObservableCollection<Color>) { var colorChip = new SfChip() { BackgroundColor = (Color)item, ShowSelectionIndicator = false, SelectionIndicatorColor = Color.LightGray, BorderColor = Color.Transparent, BorderWidth = 0, CornerRadius = 18, WidthRequest = 35, HeightRequest = 35, Margin = 10, }; colorChip.Clicked += ColorChip_Clicked; colorChips.Add(colorChip); } return colorChips; } #endregion #region Event private void ColorChip_Clicked(object sender, EventArgs e) { if (selectedChip != null) { selectedChip.ShowSelectionIndicator = false; selectedChip.BorderColor = Color.Transparent; selectedChip.BorderWidth = 0; } selectedChip = (sender as SfChip); selectedChip.ShowSelectionIndicator = true; selectedChip.BorderColor = Color.LightGray; selectedChip.BorderWidth = 3; ((selectedChip.Parent as StackLayout).BindingContext as CustomizationViewModel).BackgroundColor = selectedChip.BackgroundColor; } #endregion #region Convert Back public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } #endregion } #endregion }<file_sep>/Forms/DataGrid/DataGrid/Samples/DataGridStyles/DataGridStylesBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DataGridStylesBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the DataGridStyles samples /// </summary> public class DataGridStylesBehaviors : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private StylesViewModel viewModel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt stylePicker; /// <summary> /// Used to change a GridStyle based on selected Index /// </summary> /// <param name="sender">OnStyleChanged event sender</param> /// <param name="e">EventArgs e</param> public void OnStyleChanged(object sender, EventArgs e) { if (this.stylePicker.SelectedIndex == 0) { this.dataGrid.GridStyle = new Dark(); } else if (this.stylePicker.SelectedIndex == 1) { this.dataGrid.GridStyle = new Blue(); } else if (this.stylePicker.SelectedIndex == 2) { this.dataGrid.GridStyle = new Red(); } else if (this.stylePicker.SelectedIndex == 3) { this.dataGrid.GridStyle = new Green(); } else if (this.stylePicker.SelectedIndex == 4) { this.dataGrid.GridStyle = new Purple(); } } /// <summary> /// Fired when DataGrid View is created /// </summary> /// <param name="sender">GridViewCreated event sender</param> /// <param name="e">GridViewCreatedEventArgs e</param> public void GridViewCreated(object sender, GridViewCreatedEventArgs e) { this.dataGrid.SelectedItem = this.viewModel.OrdersInfo[3]; } /// <summary> /// You can override this method to subscribe to Associated Object events and initialize properties. /// </summary> /// <param name="bindAble">A sample View type of parameter bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.dataGrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.viewModel = new StylesViewModel(); bindAble.BindingContext = this.viewModel; this.dataGrid.ItemsSource = this.viewModel.OrdersInfo; this.dataGrid.GridViewCreated += this.GridViewCreated; this.stylePicker = bindAble.FindByName<PickerExt>("StylePicker"); this.stylePicker.Items.Add("Dark"); this.stylePicker.Items.Add("Blue"); this.stylePicker.Items.Add("Red"); this.stylePicker.Items.Add("Green"); this.stylePicker.Items.Add("Purple"); this.stylePicker.SelectedIndex = 1; this.stylePicker.SelectedIndexChanged += this.OnStyleChanged; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">A sampleView type of parameter bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.dataGrid.GridViewCreated -= this.GridViewCreated; this.stylePicker.SelectedIndexChanged -= this.OnStyleChanged; this.dataGrid = null; this.stylePicker = null; base.OnDetachingFrom(bindAble); } } } <file_sep>/Forms/Calendar/Calendar.Android/MainActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content.PM; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser.SfCalendar.Droid { /// <summary> /// Main Activity /// </summary> [Activity(Label = "SampleBrowser.SfCalendar", Icon = "@drawable/AppIcon", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { /// <summary> /// statusBa and navigation bar Height /// </summary> private double statusBarHeight, navigationBarheight; /// <summary> /// Initializes a new instance of the <see cref="OnCreate" /> class /// </summary> /// <param name="bundle">bundle param </param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "SA1126:prefix to indicate the intended method call", Justification = "Not mark member as static")] protected override void OnCreate(Bundle bundle) { int navigationResID = Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (navigationResID > 0) { this.navigationBarheight = Resources.GetDimensionPixelSize(navigationResID) / Resources.DisplayMetrics.Density; } int statusResID = Resources.GetIdentifier("status_bar_height", "dimen", "android"); if (statusResID > 0) { this.statusBarHeight = Resources.GetDimensionPixelSize(statusResID) / Resources.DisplayMetrics.Density; } TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); SampleBrowser.Core.Droid.CoreSampleBrowser.Init(this.Resources, null); this.LoadApplication(new App()); } } }<file_sep>/Android/SampleBrowser/Samples/PopupLayout/Popup Customizations/Adapter/MovieAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.Android.PopupLayout; using Android.Graphics; using Android.Content.Res; using System.Threading.Tasks; using static Android.Views.View; using Android.Util; namespace SampleBrowser { public class MovieAdapter : BaseAdapter<TableItem> { List<TableItem> items; Activity context; FrameLayout mainView; int count = 0; public MovieAdapter(Activity context, List<TableItem> items,FrameLayout view) : base() { this.context = context; this.items = items; this.mainView = view; } public override long GetItemId(int position) { return position; } public override TableItem this[int position] { get { return items[position]; } } public override int Count { get { return items.Count; } } public override View GetView(int position, View convertView, ViewGroup parent) { var item = items[position]; View view = convertView; view = context.LayoutInflater.Inflate(Resource.Layout.CustomListView, null); count++; return CreateMovieTile(view as LinearLayout, item); } private LinearLayout CreateMovieTile (LinearLayout view,TableItem item) { var density = Resources.System.DisplayMetrics.Density; ImageView img = new ImageView(context); img.SetPadding(16,16,12 ,16); img.SetImageResource(item.ImageResourceId); if (MainActivity.IsTablet) view.AddView(img, (int)(125 * density), (int)(142 * density)); else view.AddView(img, (int)(103 * density), (int)(117 * density)); LinearLayout linear = new LinearLayout(context); linear.Orientation = Android.Widget.Orientation.Vertical; TextView t1 = new TextView(context); t1.Text = item.Heading; t1.SetTextColor(Color.ParseColor("#000000")); t1.SetTextSize(ComplexUnitType.Dip, 16); if (MainActivity.IsTablet) t1.SetPadding((int)(12 * density), (int)(12 * density), 0, (int)(8 * density)); else t1.SetPadding((int)(12 * density), 0, 0, (int)(8 * density)); TextView t2 = new TextView(context); t2.SetTextColor(Color.Argb(54,00,00,00)); t2.Text = item.SubHeading; t2.SetTextSize(ComplexUnitType.Dip, 12); t2.SetPadding((int)(12 * density), 0, 0, (int)(10 * density)); LinearLayout certificateLayout = new LinearLayout(context); certificateLayout.Orientation = Android.Widget.Orientation.Horizontal; certificateLayout.SetPadding(0, 20, 0, 0); TextView t3 = new TextView(context); t3.Text = "2D"; t3.SetX((int)(12 * density)); t3.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; t3.SetTextColor(Color.Argb(54, 00, 00, 00)); t3.SetTextSize(ComplexUnitType.Dip, 10); t3.SetBackgroundResource(Resource.Layout.BorderLayout); TextView t4 = new TextView(context); t4.Text = "3D"; t4.SetTextColor(Color.Argb(54, 00, 00, 00)); t4.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; t4.SetX((int)(22 * density)); t4.SetTextSize(ComplexUnitType.Dip, 10); t4.SetBackgroundResource(Resource.Layout.BorderLayout); if (item.Heading == "AA-Team" || item.Heading == "Configuring 2" || item.Heading == "Inside Us 2" || item.Heading == "Clash Of The Titans") { TextView t5 = new TextView(context); t5.Text = "UA"; t5.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; t5.SetTextColor(Color.Argb(54, 00, 00, 00)); t5.SetX((int)(32 * density)); t5.SetTextSize(ComplexUnitType.Dip, 10); t5.SetBackgroundResource(Resource.Layout.BorderLayout); certificateLayout.AddView(t3, (int)(30 * density), (int)(20 * density)); certificateLayout.AddView(t4, (int)(30 * density), (int)(20 * density)); certificateLayout.AddView(t5, (int)(30 * density), (int)(20 * density)); } else { certificateLayout.AddView(t3, (int)(30 * density), (int)(20 * density)); certificateLayout.AddView(t4, (int)(30 * density), (int)(20 * density)); } linear.AddView(t1); linear.AddView(t2); linear.AddView(certificateLayout); if (MainActivity.IsTablet) view.AddView(linear, (int)(Resources.System.DisplayMetrics.WidthPixels - (195 * density)), ViewGroup.LayoutParams.MatchParent); else view.AddView(linear, (int)(Resources.System.DisplayMetrics.WidthPixels - (183 * density)), ViewGroup.LayoutParams.MatchParent); Button bookButton = new Button(context); bookButton.SetTextColor(Color.White); bookButton.SetTextSize(ComplexUnitType.Dip, 14); bookButton.Gravity = GravityFlags.Center; bookButton.SetY((int)(43 *density)); if (MainActivity.IsTablet) bookButton.SetPadding(0, 0, (int)(12 * density), 0); else bookButton.SetPadding((int)(12 * density), 0, (int)(12 * density), 0); bookButton.SetText("Book", TextView.BufferType.Normal); bookButton.SetBackgroundColor(Color.ParseColor("#007CEE")); bookButton.Click += BookButton_Click; if (MainActivity.IsTablet) view.AddView(bookButton, (int)(65 * density), (int)(30 * density)); else view.AddView(bookButton, (int)(60 * density), (int)(30 * density)); return view; } private void BookButton_Click(object sender, EventArgs e) { var child = this.mainView.GetChildAt(0); this.mainView.RemoveAllViews(); if (child.Id == 1) { this.mainView.AddView(PopupCustomizations.secondPage, ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); } var backbutton = ((((context as AllControlsSamplePage).SettingsButton.Parent as RelativeLayout).GetChildAt(1) as LinearLayout).GetChildAt(0) as RelativeLayout).GetChildAt(0); backbutton.Click += backbutton_Click; } private void backbutton_Click(object sender, EventArgs e) { if (this.mainView != null && this.mainView.ChildCount > 0) { var child = this.mainView.GetChildAt(0); if (child != null && child.Id == 2) { this.mainView.RemoveView(child); if (PopupCustomizations.movieList.Parent == null) { this.mainView.AddView(PopupCustomizations.movieList); } } } } } public class TableItem { public string Heading { get; set; } public string SubHeading { get; set; } public int ImageResourceId { get; set; } public string Timing1 { get; set; } public string Timing2 { get; set; } } } <file_sep>/Forms/XlsIO/XlsIO/Samples/FiltersPage/FiltersPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Collections.ObjectModel; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XlsIO; using Xamarin.Forms; namespace SampleBrowser.XlsIO { /// <summary> /// This class is used to filter data within a range of Excel worksheet. /// </summary> public partial class FiltersPage : SampleView { public FiltersPage() { InitializeComponent(); this.picker.Items.Add("Custom Filter"); this.picker.Items.Add("Text Filter"); this.picker.Items.Add("DateTime Filter"); this.picker.Items.Add("Dynamic Filter"); this.picker.Items.Add("Color Filter"); this.picker.Items.Add("Icon Filter"); this.picker.Items.Add("Advanced Filter"); this.Advanced.Items.Add("Filter In Place"); this.Advanced.Items.Add("Filter Copy"); this.picker.SelectedIndex = 0; this.Advanced.SelectedIndex = 0; this.ColorFilterType.Items.Add("Font Color"); this.ColorFilterType.Items.Add("Cell Color"); this.ColorsList.Items.Add("Red"); this.ColorsList.Items.Add("Blue"); this.ColorsList.Items.Add("Green"); this.ColorsList.Items.Add("Yellow"); this.ColorsList.Items.Add("Empty"); this.IconSetList.Items.Add("ThreeSymbols"); this.IconSetList.Items.Add("FourRating"); this.IconSetList.Items.Add("FiveArrows"); this.IconIdList.Items.Add("1"); this.IconIdList.Items.Add("2"); this.IconIdList.Items.Add("3"); this.IconIdList.Items.Add("NoIcon"); this.IconIdList.SelectedIndex = 0; this.ColorsList.SelectedIndex = 0; this.ColorFilterType.SelectedIndex = 0; this.IconSetList.SelectedIndex = 0; if (Device.Idiom != TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP)) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGetInputTemplate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnGetInputTemplate.VerticalOptions = LayoutOptions.Center; this.btnGetInputTemplate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; this.Content_3.FontSize = 13.5; this.Label1.FontSize = 13.5; this.Label2.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGetInputTemplate.VerticalOptions = LayoutOptions.Center; } } internal void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; // Initializing Workbook Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = null; int filterType = this.picker.SelectedIndex; #if COMMONSB if (filterType == 6) fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.AdvancedFilterData.xlsx"); else if (filterType == 5) fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.IconFilterData.xlsx"); else if (filterType == 4) fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.FilterData_Color.xlsx"); else fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.FilterData.xlsx"); #else if (filterType == 6) { fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.AdvancedFilterData.xlsx"); } else if (filterType == 5) { fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.IconFilterData.xlsx"); } else if (filterType == 4) { fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.FilterData_Color.xlsx"); } else { fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.FilterData.xlsx"); } #endif IWorkbook workbook = application.Workbooks.Open(fileStream); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; if (filterType != 6) { sheet.AutoFilters.FilterRange = sheet.Range[1, 1, 49, 3]; } switch (filterType) { case 0: IAutoFilter filter1 = sheet.AutoFilters[0]; filter1.IsAnd = false; filter1.FirstCondition.ConditionOperator = ExcelFilterCondition.Equal; filter1.FirstCondition.DataType = ExcelFilterDataType.String; filter1.FirstCondition.String = "Owner"; filter1.SecondCondition.ConditionOperator = ExcelFilterCondition.Equal; filter1.SecondCondition.DataType = ExcelFilterDataType.String; filter1.SecondCondition.String = "Sales Representative"; break; case 1: IAutoFilter filter2 = sheet.AutoFilters[0]; filter2.AddTextFilter(new string[] { "Owner", "Sales Representative", "Sales Associate" }); break; case 2: IAutoFilter filter3 = sheet.AutoFilters[1]; filter3.AddDateFilter(new DateTime(2004, 9, 1, 1, 0, 0, 0), DateTimeGroupingType.month); filter3.AddDateFilter(new DateTime(2011, 1, 1, 1, 0, 0, 0), DateTimeGroupingType.year); break; case 3: IAutoFilter filter4 = sheet.AutoFilters[1]; filter4.AddDynamicFilter(DynamicFilterType.Quarter1); break; case 4: // ColorFilter sheet.AutoFilters.FilterRange = sheet["A1:C49"]; Syncfusion.Drawing.Color color = Syncfusion.Drawing.Color.Empty; switch (ColorsList.SelectedIndex) { case 0: color = Syncfusion.Drawing.Color.Red; break; case 1: color = Syncfusion.Drawing.Color.Blue; break; case 2: color = Syncfusion.Drawing.Color.Green; break; case 3: color = Syncfusion.Drawing.Color.Yellow; break; case 4: color = Syncfusion.Drawing.Color.Empty; break; } if (ColorFilterType.SelectedIndex == 0) { IAutoFilter filter = sheet.AutoFilters[2]; filter.AddColorFilter(color, ExcelColorFilterType.FontColor); } else { IAutoFilter filter = sheet.AutoFilters[0]; filter.AddColorFilter(color, ExcelColorFilterType.CellColor); } break; case 5: sheet.AutoFilters.FilterRange = sheet["A4:D44"]; ExcelIconSetType iconSet = ExcelIconSetType.FiveArrows; int filterIndex = 0; int iconId = 0; switch (IconSetList.SelectedIndex) { case 0: filterIndex = 3; iconSet = ExcelIconSetType.ThreeSymbols; break; case 1: filterIndex = 1; iconSet = ExcelIconSetType.FourRating; break; case 2: filterIndex = 2; iconSet = ExcelIconSetType.FiveArrows; break; } switch (IconIdList.SelectedIndex) { case 0: iconId = 0; break; case 1: iconId = 1; break; case 2: iconId = 2; break; case 3: if (IconSetList.SelectedIndex == 0) { iconSet = (ExcelIconSetType)(-1); } else { iconId = 3; } break; case 4: if (IconSetList.SelectedIndex == 1) { iconSet = (ExcelIconSetType)(-1); } else { iconId = 4; } break; case 5: iconSet = (ExcelIconSetType)(-1); break; } IAutoFilter filter5 = sheet.AutoFilters[filterIndex]; filter5.AddIconFilter(iconSet, iconId); break; case 6: // AdvancedFilter IRange filterRange = sheet.Range["A8:G51"]; IRange criteriaRange = sheet.Range["A2:B5"]; if (Advanced.SelectedIndex == 0) { sheet.AdvancedFilter(ExcelFilterAction.FilterInPlace, filterRange, criteriaRange, null, Switch1.IsToggled); } else { IRange range = sheet.Range["I7:O7"]; range.Merge(); range.Text = "FilterCopy"; range.CellStyle.Font.RGBColor = Syncfusion.Drawing.Color.FromArgb(0, 112, 192); range.HorizontalAlignment = ExcelHAlign.HAlignCenter; range.CellStyle.Font.Bold = true; IRange copyRange = sheet.Range["I8"]; sheet.AdvancedFilter(ExcelFilterAction.FilterCopy, filterRange, criteriaRange, copyRange, Switch1.IsToggled); } break; } workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Filters.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("Filters.xlsx", "application/msexcel", stream); } } internal void OnButtonClicked1(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; // Initializing Workbook Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = null; int filterType = this.picker.SelectedIndex; #if COMMONSB if (filterType == 6) fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.AdvancedFilterData.xlsx"); else if (filterType == 5) fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.IconFilterData.xlsx"); else if (filterType == 4) fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.FilterData_Color.xlsx"); else fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.FilterData.xlsx"); #else if (filterType == 6) { fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.AdvancedFilterData.xlsx"); } else if (filterType == 5) { fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.IconFilterData.xlsx"); } else if (filterType == 4) { fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.FilterData_Color.xlsx"); } else { fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.FilterData.xlsx"); } #endif IWorkbook workbook = application.Workbooks.Open(fileStream); workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.xlsx", "application/msexcel", stream); } } internal void OnItemSelected(object sender, EventArgs e) { if (this.picker.SelectedIndex == 6) { this.DynamicGrid.IsVisible = true; this.ColorFilterGrid.IsVisible = false; this.IconFilterGrid.IsVisible = false; } else if (this.picker.SelectedIndex == 5) { this.DynamicGrid.IsVisible = false; this.ColorFilterGrid.IsVisible = false; this.IconFilterGrid.IsVisible = true; } else if (this.picker.SelectedIndex == 4) { this.DynamicGrid.IsVisible = false; this.ColorFilterGrid.IsVisible = true; this.IconFilterGrid.IsVisible = false; } else { this.DynamicGrid.IsVisible = false; this.ColorFilterGrid.IsVisible = false; this.IconFilterGrid.IsVisible = false; } } internal void IconSetChanged(object sender, EventArgs e) { if (IconSetList.SelectedIndex == 0) { this.IconIdList.Items.Clear(); this.IconIdList.Items.Add("RedCrossSymbol"); this.IconIdList.Items.Add("YellowExclamationSymbol"); this.IconIdList.Items.Add("GreenCheckSymbol"); this.IconIdList.Items.Add("NoIcon"); } else if (IconSetList.SelectedIndex == 1) { this.IconIdList.Items.Clear(); this.IconIdList.Items.Add("SignalWithOneFillBar"); this.IconIdList.Items.Add("SignalWithTwoFillBars"); this.IconIdList.Items.Add("SignalWithThreeFillBars"); this.IconIdList.Items.Add("SignalWithFourFillBars"); this.IconIdList.Items.Add("NoIcon"); } else { this.IconIdList.Items.Clear(); this.IconIdList.Items.Add("RedDownArrow"); this.IconIdList.Items.Add("YellowDownInclineArrow"); this.IconIdList.Items.Add("YellowSideArrow"); this.IconIdList.Items.Add("YellowUpInclineArrow"); this.IconIdList.Items.Add("GreenUpArrow"); this.IconIdList.Items.Add("NoIcon"); } this.IconIdList.SelectedIndex = 0; } } public class IconList { public string IconName { get; set; } public string Icon { get; set; } } }<file_sep>/Forms/PdfViewer/PdfViewer.iOS/Renderer/CustomEntryRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Xamarin.Forms.Platform.iOS; using Xamarin.Forms; using UIKit; using SampleBrowser.SfPdfViewer; using SampleBrowser.SfPdfViewer.iOS; [assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))] namespace SampleBrowser.SfPdfViewer.iOS { public class CustomEntryRenderer : EntryRenderer { Syncfusion.SfPdfViewer.XForms.SfPdfViewer pdfViewerControl; UIAlertView alertView; IUIAlertViewDelegate alertViewDelegate; UITextField textField; bool isInitialized = false; protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); } protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if ((sender as CustomEntry) != null) { if (e.PropertyName == "IsFocused") { if ((sender as CustomEntry) != null && (sender as CustomEntry).IsFocused) Control.PerformSelector(new ObjCRuntime.Selector("selectAll"), null, 0.0f); } if (!isInitialized && (sender as CustomEntry).IsPageNumberEntry) { textField = new UITextField(); SetNativeControl(textField); pdfViewerControl = (sender as CustomEntry).PdfViewer; textField.TextAlignment = UITextAlignment.Center; textField.TextColor = new UIColor(0f, 0.46f, 1f, 1f); textField.Layer.BorderColor = new CoreGraphics.CGColor(0, 0, 0, 0.4f); textField.Layer.BorderWidth = 1; textField.Layer.CornerRadius = 2; textField.TintColor = new UIColor(255f, 255f, 255f, 0); textField.EditingDidBegin += TextField_EditingDidBegin; isInitialized = true; } } } void TextField_EditingDidBegin(object sender, EventArgs e) { (sender as UITextField).ResignFirstResponder(); alertViewDelegate = new AlertViewDelegate(pdfViewerControl); alertView = new UIAlertView("Go To Page", "Enter Page Number (1 - " + pdfViewerControl.PageCount.ToString() + ")", alertViewDelegate, "Cancel", "Okay"); alertView.BackgroundColor = UIColor.White; alertView.Layer.BorderWidth = 1; alertView.Layer.BorderColor = new CoreGraphics.CGColor(0.2f, 0.2f); alertView.Layer.CornerRadius = 10; alertView.AlertViewStyle = UIAlertViewStyle.PlainTextInput; (alertView.GetTextField(0) as UITextField).KeyboardType = UIKeyboardType.NumberPad; (alertView.GetTextField(0) as UITextField).BecomeFirstResponder(); (alertView.GetTextField(0) as UITextField).ShouldReturn += (textField) => { int pageNum = 0; if (int.TryParse(alertView.GetTextField(0).Text, out pageNum) && pageNum > 0 && pageNum <= pdfViewerControl.PageCount) { pdfViewerControl.PageNumber = pageNum; return true; } else if (alertView.GetTextField(0).Text != "") return true; else return false; }; alertView.Show(); } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/PopupCustomizations/TicketBooking.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "TicketBooking.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using Xamarin.Forms; using Xamarin.Forms.Xaml; [XamlCompilation(XamlCompilationOptions.Compile)] /// <summary> /// A ContentPage that contains the TicketBooking sample. /// </summary> public partial class TicketBooking : ContentPage { /// <summary> /// Initializes a new instance of the TicketBooking class. /// </summary> public TicketBooking() { this.InitializeComponent(); } /// <summary> /// You can override this method while View was disappear from window /// </summary> protected override void OnDisappearing() { base.OnDisappearing(); if (this.termsAndConditionPopup != null) { this.termsAndConditionPopup.Dispose(); this.termsAndConditionPopup = null; } if (this.informationDialog != null) { this.informationDialog.Dispose(); this.informationDialog = null; } if (this.ticketBookingPopup != null) { this.ticketBookingPopup.Dispose(); this.ticketBookingPopup = null; } if (this.confirmationDialog != null) { this.confirmationDialog.Dispose(); this.confirmationDialog = null; } if (this.seconddataGrid != null) { this.seconddataGrid.Dispose(); this.seconddataGrid = null; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Maps/BubbleVisualization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfBusyIndicator.iOS; using System; using Syncfusion.SfMaps.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using CoreGraphics; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGPoint= System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class BubbleVisualization : SampleView { internal SFBusyIndicator busyindicator; UIView view; UILabel label; public override void LayoutSubviews() { view.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); ; SetNeedsDisplay(); } public BubbleVisualization() { SFMap maps = new SFMap(); view = new UIView(); view.Frame = new CGRect(0, 0, 300, 400); busyindicator = new SFBusyIndicator(); busyindicator.ViewBoxWidth = 75; busyindicator.ViewBoxHeight = 75; busyindicator.Foreground = UIColor.FromRGB(0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; view.AddSubview(busyindicator); label = new UILabel(); label.TextAlignment = UITextAlignment.Center; label.Text = "Top 40 Population Countries With Bubbles"; label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(0, 0, 400, 40); label.TextColor = UIColor.Black; view.AddSubview(label); NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(0.3), delegate { maps.Frame = new CGRect(Frame.Location.X, 60, Frame.Size.Width - 6, Frame.Size.Height - 60); view.AddSubview(maps); }); SFShapeFileLayer layer = new SFShapeFileLayer(); layer.Uri = (NSString)NSBundle.MainBundle.PathForResource("world1", "shp"); layer.ShapeIDPath = (NSString)"Country"; layer.ShapeIDTableField = (NSString)"NAME"; layer.ShowMapItems = true; layer.DataSource = GetDataSource(); SFShapeSetting shapeSettings = new SFShapeSetting(); shapeSettings.Fill = UIColor.LightGray; layer.ShapeSettings = shapeSettings; SFBubbleMarkerSetting marker = new SFBubbleMarkerSetting(); marker.ValuePath = (NSString)"Population"; marker.ColorValuePath = (NSString)"Population"; ObservableCollection<SFMapColorMapping> colorMappings = new ObservableCollection<SFMapColorMapping>(); SFRangeColorMapping rangeColorMapping1 = new SFRangeColorMapping(); rangeColorMapping1.To = 1400000000; rangeColorMapping1.From = 325000000; rangeColorMapping1.LegendLabel = (NSString)"Above 4%"; rangeColorMapping1.Color = UIColor.FromRGB(46, 118, 159); colorMappings.Add(rangeColorMapping1); SFRangeColorMapping rangeColorMapping2 = new SFRangeColorMapping(); rangeColorMapping2.To = 325000000; rangeColorMapping2.From = 180000000; rangeColorMapping2.LegendLabel = (NSString)"4% - 2%"; rangeColorMapping2.Color = UIColor.FromRGB(216, 68, 68); colorMappings.Add(rangeColorMapping2); SFRangeColorMapping rangeColorMapping3 = new SFRangeColorMapping(); rangeColorMapping3.To = 180000000; rangeColorMapping3.From = 100000000; rangeColorMapping3.LegendLabel = (NSString)"2% - 1%"; rangeColorMapping3.Color = UIColor.FromRGB(129, 111, 40); colorMappings.Add(rangeColorMapping3); SFRangeColorMapping rangeColorMapping4 = new SFRangeColorMapping(); rangeColorMapping4.To = 100000000; rangeColorMapping4.From = 5000000; rangeColorMapping4.LegendLabel = (NSString)"Below 1%"; rangeColorMapping4.Color = UIColor.FromRGB(127, 56, 160); colorMappings.Add(rangeColorMapping4); marker.ColorMappings = colorMappings; layer.BubbleMarkerSetting = marker; SFMapLegendSettings mapLegendSettings = new SFMapLegendSettings(); mapLegendSettings.ShowLegend = true; mapLegendSettings.LegendType = LegendType.Bubbles; mapLegendSettings.IconSize = new CGSize(15, 15); mapLegendSettings.Position = new CGPoint(50, 5); mapLegendSettings.TextSize = 15; layer.LegendSettings = mapLegendSettings; maps.Layers.Add(layer); AddSubview(view); maps.Delegate = new MapsBubbleDelegate(this); } NSMutableArray GetDataSource() { NSMutableArray array = new NSMutableArray(); array.Add(getDictionary("China", 1393730000, 18.2)); array.Add(getDictionary("India", 1336180000, 17.5)); array.Add(getDictionary("United States", 327726000, 4.29)); array.Add(getDictionary("Indonesia", 265015300, 3.47)); array.Add(getDictionary("Pakistan", 209503000, 2.78)); array.Add(getDictionary("Brazil", 201795000, 2.74)); array.Add(getDictionary("Nigeria", 197306006, 2.53)); array.Add(getDictionary("Bangladesh", 165086000, 2.16)); array.Add(getDictionary("Russia", 146877088, 1.92)); array.Add(getDictionary("Japan", 126490000, 1.66)); array.Add(getDictionary("Mexico", 124737789, 1.63)); array.Add(getDictionary("Ethiopia", 107534882, 1.41)); array.Add(getDictionary("Philippines", 106375000, 1.39)); array.Add(getDictionary("Egypt", 97459100, 1.27)); array.Add(getDictionary("Vietnam", 94660000, 1.24)); array.Add(getDictionary("Germany", 82740900, 1.08)); array.Add(getDictionary("Iran", 81737800, 1.07)); array.Add(getDictionary("Turkey", 80810525, 1.06)); array.Add(getDictionary("Thailand", 69183173, 0.91)); array.Add(getDictionary("France", 67297000, 0.88)); array.Add(getDictionary("United Kingdom", 66040229, 0.86)); array.Add(getDictionary("Italy", 60436469, 0.79)); array.Add(getDictionary("South Africa", 57725600, 0.76)); array.Add(getDictionary("Colombia", 49918600, 0.65)); array.Add(getDictionary("Spain", 46659302, 0.61)); array.Add(getDictionary("Argentina", 44494502, 0.58)); array.Add(getDictionary("Poland", 38433600, 0.5)); array.Add(getDictionary("Canada", 37206700, 0.48)); array.Add(getDictionary("Saudi Arabia", 33413660, 0.44)); array.Add(getDictionary("Malaysia", 32647000, 0.42)); array.Add(getDictionary("Nepal", 29218867, 0.38)); array.Add(getDictionary("Australia", 25015400, 0.32)); array.Add(getDictionary("Kazakhstan", 18253300, 0.24)); array.Add(getDictionary("Cambodia", 16069921, 0.21)); array.Add(getDictionary("Belgium", 11414214, 0.15)); array.Add(getDictionary("Greece", 10768193, 0.14)); array.Add(getDictionary("Sweden", 10171524, 0.13)); array.Add(getDictionary("Somalia", 15181925, 0.12)); array.Add(getDictionary("Austria", 8830487, 0.12)); array.Add(getDictionary("Bulgaria", 7050034, 0.092)); return array; } NSDictionary getDictionary(string name, double population, double percent) { NSString name1 = (NSString)name; object[] objects = new object[3]; object[] keys = new object[3]; keys.SetValue("Country", 0); keys.SetValue("Population", 1); keys.SetValue("Percent", 2); objects.SetValue(name1, 0); objects.SetValue(population, 1); objects.SetValue(percent, 2); return NSDictionary.FromObjectsAndKeys(objects, keys); } } public class MapsBubbleDelegate : SFMapsDelegate { public MapsBubbleDelegate(BubbleVisualization bubble) { sample = bubble; } BubbleVisualization sample; public override void DidLoad(SFMap map) { if (sample.busyindicator != null) { sample.busyindicator.RemoveFromSuperview(); sample.busyindicator = null; } } } } <file_sep>/Forms/Chart/Chart/Samples/Trackball/Trackball.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.XForms; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfChart { public partial class Trackball : SampleView { public Trackball() { InitializeComponent(); var data = new TrackballViewModel(); labelDisplayMode.SelectedIndex = 1; labelDisplayMode.SelectedIndexChanged += labelDisplayMode_SelectedIndexChanged; trackballTouchMode.SelectedIndex = 0; trackballTouchMode.SelectedIndexChanged += trackballTouchMode_SelectedIndexChanged; if(Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { secondaryAxisLabelStyle.LabelFormat = "0'M '"; } else { secondaryAxisLabelStyle.LabelFormat = "#'M '"; } if (Device.RuntimePlatform == Device.macOS || Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { chart.Legend.OverflowMode = ChartLegendOverflowMode.Scroll; label.IsVisible = false; } } void labelDisplayMode_SelectedIndexChanged(object sender, EventArgs e) { switch (labelDisplayMode.SelectedIndex) { case 0: chartTrackball.LabelDisplayMode = TrackballLabelDisplayMode.NearestPoint; break; case 1: chartTrackball.LabelDisplayMode = TrackballLabelDisplayMode.FloatAllPoints; break; } } void trackballTouchMode_SelectedIndexChanged(object sender, EventArgs e) { switch (trackballTouchMode.SelectedIndex) { case 0: chartTrackball.ActivationMode = ChartTrackballActivationMode.LongPress; break; case 1: chartTrackball.ActivationMode = ChartTrackballActivationMode.TouchMove; break; case 2: chartTrackball.ActivationMode = ChartTrackballActivationMode.None; break; } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if ((Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS)) { if (height > 0 && width > 0) { if (height > width) { chart.Legend.DockPosition = LegendPlacement.Top; } else { chart.Legend.DockPosition = LegendPlacement.Right; } } } } } public class StringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value.ToString() + "%"; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string Value = value.ToString(); int result; if (int.TryParse(Value, out result)) return result; return value; } } }<file_sep>/Forms/BadgeView/BadgeView/Samples/Notification/Notification.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Notification.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfBadgeView { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; /// <summary> /// Getting Started class /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public partial class Notification : SampleView { private bool isUpdate = false; #region Constructor /// <summary> /// Initializes a new instance of the <see cref="Notification" /> class. /// </summary> public Notification() { this.InitializeComponent(); statusBadge.BadgeSettings.Offset = new Point(-5, 5); switch (Device.RuntimePlatform) { case Device.iOS: { callsBadge.BadgeSettings.TextPadding = new Thickness(3); callsBadge.BadgeSettings.Offset = new Point(0, 2); } break; case Device.Android: { callsBadge.BadgeSettings.Offset = new Point(0, 2); } break; case Device.UWP: { callsBadge.BadgeSettings.Offset = new Point(-2, 0); callsBadge.BadgeSettings.TextPadding = new Thickness(3); chatBadge.BadgeSettings.Offset = new Point(0, 3); } break; case Device.WPF: { fontIconLabel2.VerticalOptions = LayoutOptions.End; fontIconLabel2.HorizontalOptions = LayoutOptions.Center; fontIconLabel4.VerticalOptions = LayoutOptions.End; fontIconLabel4.HorizontalOptions = LayoutOptions.Center; } break; } isUpdate = true; DynamicUpdate(); } #endregion private async void DynamicUpdate() { double badgeText = 1; while (isUpdate && this.chatBadge != null) { badgeText += 1; this.chatBadge.BadgeText = badgeText.ToString(); await Task.Delay(2000); } } public override void OnDisappearing() { base.OnDisappearing(); isUpdate = false; } } }<file_sep>/Forms/Chart/Chart/Samples/WaterfallChart/WaterFallSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfChart { public class WaterfallSeriesViewModel { public ObservableCollection<ChartDataModel> RevenueDetails { get; set; } public WaterfallSeriesViewModel() { RevenueDetails = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sales", 165), new ChartDataModel("Staff", -47), new ChartDataModel("Balance", 58, true), new ChartDataModel("Others", 15), new ChartDataModel("Tax", -20), new ChartDataModel("Profit", 45, true) }; if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { RevenueDetails.Add(new ChartDataModel("Inventory", -10)); RevenueDetails.Add(new ChartDataModel("Marketing", -25)); RevenueDetails.Add(new ChartDataModel("Net Income", 25, true)); } } } }<file_sep>/iOS/SampleBrowser/Samples/DataGrid/Exporting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Foundation; using QuickLook; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.SfDataGrid; using Syncfusion.SfDataGrid.Exporting; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Reflection; using UIKit; namespace SampleBrowser { public class Exporting : SampleView { #region Fields SfDataGrid SfGrid; UIButton exportPdf; UIButton exportExcel; CustomView excelView; CustomView pdfView; UIButton exportPDfImage; UIButton exportExcelImage; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public Exporting() { this.SfGrid = new SfDataGrid(); this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.ItemsSource = new ExportingViewModel().OrdersInfo; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; exportPDfImage = new UIButton(); exportPDfImage.SetImage(UIImage.FromFile("Images/pdfexport.png"), UIControlState.Normal); exportPDfImage.TouchDown += ExportToPdf; exportPdf = new UIButton(UIButtonType.RoundedRect); exportPdf.SetTitleColor (UIColor.Black, UIControlState.Normal); exportPdf.SetTitle("Export To Pdf",UIControlState.Normal); exportPdf.Font = UIFont.SystemFontOfSize(11); exportPdf.TouchDown += ExportToPdf; exportExcelImage = new UIButton(); exportExcelImage.SetImage(UIImage.FromFile("Images/excelexport.png"), UIControlState.Normal); exportExcelImage.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; exportExcelImage.TouchDown += ExportToExcel; exportExcel = new UIButton(UIButtonType.RoundedRect); exportExcel.Font = UIFont.SystemFontOfSize(11); exportExcel.SetTitle("Export To Excel", UIControlState.Normal); exportExcel.SetTitleColor(UIColor.Black, UIControlState.Normal); exportExcel.TouchDown += ExportToExcel; UIButton b = new UIButton(); b.Font = UIFont.SystemFontOfSize(5); excelView = new CustomView(); excelView.AddSubviews((exportExcelImage)); excelView.AddSubviews((exportExcel)); pdfView = new CustomView(); pdfView.AddSubviews(exportPDfImage); pdfView.AddSubviews(exportPdf); this.AddSubview(excelView); this.AddSubview(pdfView); this.AddSubview(this.SfGrid); } private void ExportToExcel(object sender, EventArgs e) { DataGridExcelExportingController excelExport = new DataGridExcelExportingController(); var excelEngine = excelExport.ExportToExcel(this.SfGrid , new DataGridExcelExportingOption() {ExportRowHeight = false,ExportColumnWidth = false , DefaultColumnWidth = 100, DefaultRowHeight = 60}); var workbook = excelEngine.Excel.Workbooks[0]; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); Save("DataGrid.xlsx", "application/msexcel", stream); } private void ExportToPdf(object sender, EventArgs e) { DataGridPdfExportingController pdfExport = new DataGridPdfExportingController(); MemoryStream stream = new MemoryStream(); pdfExport.HeaderAndFooterExporting += pdfExport_HeaderAndFooterExporting; var doc = pdfExport.ExportToPdf(this.SfGrid); doc.Save(stream); doc.Close(true); Save("DataGrid.pdf", "application/pdf", stream); } private void pdfExport_HeaderAndFooterExporting(object sender, PdfHeaderFooterEventArgs e) { var width = e.PdfPage.GetClientSize().Width; PdfPageTemplateElement header = new PdfPageTemplateElement(width, 60); var assmbely = Assembly.GetExecutingAssembly(); var imagestream = assmbely.GetManifestResourceStream("SampleBrowser.Resources.Images.SyncfusionLogo.jpg"); PdfImage pdfImage = PdfImage.FromStream(imagestream); header.Graphics.DrawImage(pdfImage, new RectangleF(0, 0, width, 50)); e.PdfDocumentTemplate.Top = header; } private void Save(string filename, string contentType, MemoryStream stream) { string exception = string.Empty; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filePath = Path.Combine(path, filename); try { FileStream fileStream = File.Open(filePath, FileMode.Create); stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { exception = e.ToString(); } if (contentType == "application/html" || exception != string.Empty) return; UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (currentController.PresentedViewController != null) currentController = currentController.PresentedViewController; UIView currentView = currentController.View; QLPreviewController qlPreview = new QLPreviewController(); QLPreviewItem item = new QLPreviewItemBundles(filename, filePath); qlPreview.DataSource = new PreviewControllersDS(item); currentController.PresentViewController((UIViewController)qlPreview, true, (Action)null); } void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo("en-US"); e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Index") { e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "Last Name"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 10; } else if (e.Column.MappingName == "ShippingDate") { e.Column.HeaderText = "Shipping Date"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; e.Column.Format = "d"; } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } } public override void LayoutSubviews() { this.pdfView.Frame = new CGRect((this.Frame.Left + 5), 10, ((this.Frame.Right / 2)- 30), 50); this.excelView.Frame = new CGRect(pdfView.Frame.Right, 10, ((this.Frame.Right / 2) - 30), 50); this.SfGrid.Frame = new CGRect(0, 70, this.Frame.Width, this.Frame.Height - 70); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { if (disposing) { if (exportPDfImage != null) { exportPDfImage.TouchDown -= ExportToPdf; exportPDfImage = null; } if (exportPdf != null) { exportPdf.TouchDown -= ExportToPdf; exportPdf = null; } if (exportExcelImage != null) { exportExcelImage.TouchDown -= ExportToExcel; exportExcelImage = null; } if (exportExcel != null) { exportExcel.TouchDown -= ExportToExcel; exportExcel = null; } if (SfGrid != null) { SfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; SfGrid.Dispose(); } excelView = null; pdfView = null; SfGrid = null; } base.Dispose(disposing); } } public class QLPreviewItemBundles : QLPreviewItem { string _fileName, _filePath; public QLPreviewItemBundles(string fileName, string filePath) { _fileName = fileName; _filePath = filePath; } public override string ItemTitle { get { return _fileName; } } public override NSUrl ItemUrl { get { var documents = NSBundle.MainBundle.BundlePath; var lib = Path.Combine(documents, _filePath); var url = NSUrl.FromFilename(lib); return url; } } } public class PreviewControllersDS : QLPreviewControllerDataSource { private QLPreviewItem _item; public PreviewControllersDS(QLPreviewItem item) { _item = item; } public override nint PreviewItemCount(QLPreviewController controller) { return (nint)1; } public override IQLPreviewItem GetPreviewItem(QLPreviewController controller, nint index) { return _item; } } public class CustomView : UIView { public CustomView() : base() { this.Layer.BorderColor = UIColor.Gray.CGColor; this.Layer.BorderWidth = 1; } public override void LayoutSubviews() { base.LayoutSubviews(); this.Subviews[0].Frame = new CGRect(0, 10, 30, 26); this.Subviews[1].Frame = new CGRect(30, 10, 85, 30); } } } <file_sep>/Forms/PDF/readme.md PDF is a .NET class library used to create, read, and write PDF. This library is used in Windows Forms, WPF, Silverlight, ASP.NET and ASP.NET MVC, WinRT, Windows Phone, Windows store universal, and Xamarin applications without the dependency of Adobe Acrobat. PDF creates files from version 1.5 and later, and supports PDF version 1.4 and later. This is viewed by using Adobe Reader 7.x or later versions. The following samples are available for PDF to demonstrate the functionalities of each feature: | Sample | Description | | ------ | ----------- | | [Getting Started PDF](PDF/Samples/GettingStartedPDF) | Demonstrates how to create a simple PDF document with text and images. | | [Stamping](PDF/Samples/Stamping) | Demonstrates how to stamp or watermark an existing PDF document. | | [Table Features](PDF/Samples/TableFeatures) | Demonstrates how to create borderless tables in a PDF document. | | [Booklet](PDF/Samples/Booklet) | Demonstrates how to create a booklet from an existing PDF document. | | [Barcode](PDF/Samples/Barcode) | Demonstrates how to create various barcode in a PDF document. | | [Email Attachment](PDF/Samples/MailAttachment) | Demonstrates how to send a filled PDF form as an email attachment. | | [Digital Signature](PDF/Samples/DigitalSiganture) | Demonstrates how to digitally sign PDF document using a .pfx certificate. | | [Image Insertion](PDF/Samples/ImageInsertion) | Demonstrates how to insert images in a PDF document. | | [Encryption](PDF/Samples/Encryption) | Demonstrates how to create a secure PDF document. | | [RTL Text](PDF/Samples/RTLSupport) | Demonstrates drawing right-to-left language text in the PDF document. |<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/CategoryAxis.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif using System.Drawing; namespace SampleBrowser { public class CategoryAxis : SampleView { public CategoryAxis () { SFChart chart = new SFChart (); chart.Title.Text = new NSString("Sales Comparison"); SFCategoryAxis categoryAxis = new SFCategoryAxis (); categoryAxis.LabelPlacement = SFChartLabelPlacement.BetweenTicks; chart.PrimaryAxis = categoryAxis; chart.PrimaryAxis.Interval = new NSNumber(1); chart.PrimaryAxis.Title.Text = new NSString ("Sales Across Products"); chart.SecondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis.Title.Text = new NSString ("Sales Amount in Millions (USD)"); chart.SecondaryAxis.Minimum = new NSNumber(0); chart.SecondaryAxis.Maximum = new NSNumber(100); chart.SecondaryAxis.Interval = new NSNumber(10); NSNumberFormatter numberFormatter = new NSNumberFormatter (); numberFormatter.NumberStyle = NSNumberFormatterStyle.Currency; numberFormatter.MinimumFractionDigits = 0; chart.SecondaryAxis.LabelStyle.LabelFormatter = numberFormatter; ChartViewModel dataModel = new ChartViewModel (); SFLineSeries series = new SFLineSeries(); series.ItemsSource = dataModel.CategoryData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.EnableAnimation = true; chart.Series.Add(series); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } }<file_sep>/Android/SampleBrowser/Samples/AutoComplete/TokensSample/AutoCompleteContactsInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.Linq; namespace SampleBrowser { public class AutoCompleteContactsInfo { public string ContactName { get; set; } public string ContactNumber { get; set; } public string ContactType { get; set; } public string ContactImage { get; set; } } public class AutoCompleteContactsInfoRepository { #region Fields private Random random = new Random(); #endregion #region Constructor public AutoCompleteContactsInfoRepository() { } #endregion #region Get Contacts Details public ObservableCollection<AutoCompleteContactsInfo> GetContactDetails() { ObservableCollection<AutoCompleteContactsInfo> customerDetails = new ObservableCollection<AutoCompleteContactsInfo>(); for (int i = 0; i < CustomerNames2.Count(); i++) { var details = new AutoCompleteContactsInfo() { ContactType = contactType[random.Next(0, 5)], ContactName = CustomerNames2[i], ContactNumber = CustomerNames2[i].Replace(" ", "") + "@outlook.com", ContactImage = "b" + (i % 14) + ".png", }; customerDetails.Add(details); if (i < 23) { details = new AutoCompleteContactsInfo() { ContactType = contactType[random.Next(0, 5)], ContactName = CustomerNames1[i], ContactNumber = CustomerNames1[i].Replace(" ", "") + "@outlook.com", ContactImage = "a" + (i % 6) + ".png", }; customerDetails.Add(details); } } return customerDetails; } #endregion #region Contacts Information string[] contactType = new string[] { "Available.png", "Offline.png", "Away.png", "Busy.png", "DND.png" }; string[] CustomerNames1 = new string[] { "Kyle", "Gina", "Michael", "Oscar", "William", "Bill", "Daniel", "Frank", "Howard", "Jack", "Holly", "Steve", "Vince", "Zeke", "Aiden", "Jackson", "Mason", "Liam", "Jacob", "Jayden", "Ethan", "Alexander", "Sebastian", }; string[] CustomerNames2 = new string[] { "Clara", "Irene", "Ellie", "Gabriella", "Nora", "Lucy", "Arianna", "Sarah", "Kaylee", "Adriana", "Finley", "Daleyza", "Leila", "Mckenna", "Jacqueline", "Brynn", "Sawyer", "Rosalie", "Maci", "Miranda", "Talia", "Shelby", "Haven", "Yaretzi", "Zariah", "Karla", "Cassandra", "Pearl", "Irene", "Zelda", "Wren", "Yamileth", "Belen", "Briley", "Jada", "Jaden" }; #endregion } } <file_sep>/iOS/SampleBrowser/Samples/Schedule/Timetable.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Foundation; using Syncfusion.SfSchedule.iOS; using UIKit; using System.Collections.ObjectModel; namespace SampleBrowser { public class Timetable : SampleView { private static SFSchedule schedule; private List<NSString> subjectCollection; private List<NSDate> startTimeCollection; private List<NSDate> endTimeCollection; private ObservableCollection<ScheduleAppointment> appointmentCollection = new ObservableCollection<ScheduleAppointment>(); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Timetable() { schedule = new SFSchedule(); schedule.ScheduleView = SFScheduleView.SFScheduleViewDay; schedule.TimeIntervalHeight = -1; schedule.VisibleDatesChanged += Schedule_VisibleDatesChanged; InitializeAppointmentComponents(); var dayViewSettings = new DayViewSettings(); dayViewSettings.StartHour = 9; dayViewSettings.EndHour = 16; schedule.DayViewSettings = dayViewSettings; dayViewSettings.NonAccessibleBlockCollection = CreateNonAccescibleBlock(); schedule.DayViewSettings = dayViewSettings; this.AddSubview(schedule); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = new CGRect(Frame.X, 0, Frame.Width, Frame.Height); } base.LayoutSubviews(); } private NSMutableArray CreateNonAccescibleBlock() { var nonAccessibleBlocks = new NonAccessibleBlock(); var nonAccessibleBlocksCollection = new NSMutableArray(); nonAccessibleBlocks.StartHour = 12; nonAccessibleBlocks.EndHour = 13; nonAccessibleBlocks.Text = (NSString)"LUNCH"; nonAccessibleBlocksCollection.Add(nonAccessibleBlocks); return nonAccessibleBlocksCollection; } private void InitializeAppointmentComponents() { SetSubjects(); SetStartTime(); SetEndTime(); } private void SetSubjects() { subjectCollection = new List<NSString>(); subjectCollection.Add((NSString)"Wellness"); subjectCollection.Add((NSString)"Language Arts"); subjectCollection.Add((NSString)"Mathematics"); subjectCollection.Add((NSString)"Social Studies"); subjectCollection.Add((NSString)"Physical Education"); subjectCollection.Add((NSString)"Geography"); } private void SetStartTime() { startTimeCollection = new List<NSDate>(); NSCalendar calendar = NSCalendar.CurrentCalendar; NSDate today = new NSDate(); NSDateComponents startDateComponents = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); startDateComponents.Hour = 9; startDateComponents.Minute = 1; startDateComponents.Second = 0; NSDateComponents startDateComponents1 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); startDateComponents1.Hour = 10; startDateComponents1.Minute = 1; startDateComponents1.Second = 0; NSDateComponents startDateComponents2 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); startDateComponents2.Hour = 11; startDateComponents2.Minute = 11; startDateComponents2.Second = 0; NSDateComponents startDateComponents3 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); startDateComponents3.Hour = 13; startDateComponents3.Minute = 1; startDateComponents3.Second = 0; NSDateComponents startDateComponents4 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); startDateComponents4.Hour = 14; startDateComponents4.Minute = 1; startDateComponents4.Second = 0; NSDateComponents startDateComponents5 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); startDateComponents5.Hour = 15; startDateComponents5.Minute = 11; startDateComponents5.Second = 0; startTimeCollection.Add(calendar.DateFromComponents(startDateComponents)); startTimeCollection.Add(calendar.DateFromComponents(startDateComponents1)); startTimeCollection.Add(calendar.DateFromComponents(startDateComponents2)); startTimeCollection.Add(calendar.DateFromComponents(startDateComponents3)); startTimeCollection.Add(calendar.DateFromComponents(startDateComponents4)); startTimeCollection.Add(calendar.DateFromComponents(startDateComponents5)); } private void SetEndTime() { endTimeCollection = new List<NSDate>(); NSCalendar calendar = NSCalendar.CurrentCalendar; NSDate today = new NSDate(); NSDateComponents endDateComponents = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); endDateComponents.Hour = 10; endDateComponents.Minute = 0; endDateComponents.Second = 0; NSDateComponents endDateComponents1 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); endDateComponents1.Hour = 11; endDateComponents1.Minute = 0; endDateComponents1.Second = 0; NSDateComponents endDateComponents2 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); endDateComponents2.Hour = 12; endDateComponents2.Minute = 0; endDateComponents2.Second = 0; NSDateComponents endDateComponents3 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); endDateComponents3.Hour = 14; endDateComponents3.Minute = 0; endDateComponents3.Second = 0; NSDateComponents endDateComponents4 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); endDateComponents4.Hour = 15; endDateComponents4.Minute = 0; endDateComponents4.Second = 0; NSDateComponents endDateComponents5 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); endDateComponents5.Hour = 16; endDateComponents5.Minute = 0; endDateComponents5.Second = 0; endTimeCollection.Add(calendar.DateFromComponents(endDateComponents)); endTimeCollection.Add(calendar.DateFromComponents(endDateComponents1)); endTimeCollection.Add(calendar.DateFromComponents(endDateComponents2)); endTimeCollection.Add(calendar.DateFromComponents(endDateComponents3)); endTimeCollection.Add(calendar.DateFromComponents(endDateComponents4)); endTimeCollection.Add(calendar.DateFromComponents(endDateComponents5)); } private UIColor GetColors(NSString subject) { if (subject == "Wellness") { return UIColor.FromRGB(162, 193, 57); } else if (subject == "Language Arts") { return UIColor.FromRGB(216, 0, 115); } else if (subject == "Mathematics") { return UIColor.FromRGB(230, 1113, 284); } else if (subject == "Social Studies") { return UIColor.FromRGB(27, 161, 226); } else if (subject == "Physical Education") { return UIColor.FromRGB(0, 171, 169); } else { return UIColor.FromRGB(511, 153, 51); } } private string GetStaff(NSString subject) { if (subject == "Wellness") { return "Mr. Jamison"; } else if (subject == "Language Arts") { return "Ms. Casey"; } else if (subject == "Mathematics") { return "Mr. Percorino"; } else if (subject == "Social Studies") { return "Ms. Gawade"; } else if (subject == "Physical Education") { return "Mr. Shilling"; } else { return "Mr. <NAME>"; } } private NSDate GetDate(NSDate visibleDate, NSDate startTimeDate) { NSCalendar calendar = NSCalendar.CurrentCalendar; NSDate today1 = new NSDate(); NSDateComponents visibleDateCompoents = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, visibleDate); NSDateComponents startDateCompoents = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, startTimeDate); visibleDateCompoents.Hour = startDateCompoents.Hour; visibleDateCompoents.Minute = startDateCompoents.Minute; visibleDateCompoents.Second = startDateCompoents.Second; return calendar.DateFromComponents(visibleDateCompoents); } private NSDate GetBreakDate(NSDate visibleDate, int hour, int mins, int secs) { NSCalendar calendar = NSCalendar.CurrentCalendar; NSDate today1 = new NSDate(); NSDateComponents visibleDateCompoents = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, visibleDate); visibleDateCompoents.Hour = hour; visibleDateCompoents.Minute = mins; visibleDateCompoents.Second = secs; return calendar.DateFromComponents(visibleDateCompoents); } private int GetDayOfWeek(NSDate visibleDate) { NSCalendar calendar = NSCalendar.CurrentCalendar; NSDate today1 = new NSDate(); NSDateComponents visibleDateCompoents = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Weekday, visibleDate); return (int)visibleDateCompoents.Weekday; } private int GetStartDateHour(NSDate startTimeDate) { NSCalendar calendar = NSCalendar.CurrentCalendar; NSDateComponents startDateCompoents = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, startTimeDate); return (int)startDateCompoents.Hour; } private int GetEndDateHour(NSDate endTimeDate) { NSCalendar calendar = NSCalendar.CurrentCalendar; NSDateComponents endDateComponents = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, endTimeDate); return (int)endDateComponents.Hour; } private void Schedule_VisibleDatesChanged(object sender, VisibleDatesChangedEventArgs e) { var visibleDates = e.VisibleDates; var randomNumber = new Random(); var startDate = NSDate.Now; var endDate = NSDate.Now; appointmentCollection = new ObservableCollection<ScheduleAppointment>(); for (nuint i = 0; i < visibleDates.Count; i++) { if (GetDayOfWeek(visibleDates.GetItem<NSDate>(i)) == 1 || GetDayOfWeek(visibleDates.GetItem<NSDate>(i)) == 7) { schedule.DayViewSettings.NonAccessibleBlockCollection = null; } else { schedule.DayViewSettings.NonAccessibleBlockCollection = CreateNonAccescibleBlock(); } if (GetDayOfWeek(visibleDates.GetItem<NSDate>(i)) == 1 || GetDayOfWeek(visibleDates.GetItem<NSDate>(i)) == 7) { continue; } for (int j = 0; j < startTimeCollection.Count; j++) { startDate = GetDate(visibleDates.GetItem<NSDate>(i), startTimeCollection[j]); endDate = GetDate(visibleDates.GetItem<NSDate>(i), endTimeCollection[j]); var subject = subjectCollection[randomNumber.Next(subjectCollection.Count)]; appointmentCollection.Add(new ScheduleAppointment() { StartTime = startDate, EndTime = endDate, Subject = (NSString)(subject + " (" + GetStartDateHour(startDate).ToString() + ":00 - " + GetEndDateHour(endDate).ToString() + ":00" + ") \n\n" + GetStaff(subject)), AppointmentBackground = GetColors(subject), }); } // Break Timings startDate = GetBreakDate(visibleDates.GetItem<NSDate>(i), 11, 01, 0); endDate = GetBreakDate(visibleDates.GetItem<NSDate>(i), 11, 10, 0); appointmentCollection.Add(new ScheduleAppointment() { StartTime = startDate, EndTime = endDate, AppointmentBackground = UIColor.LightGray }); startDate = GetBreakDate(visibleDates.GetItem<NSDate>(i), 15, 01, 0); endDate = GetBreakDate(visibleDates.GetItem<NSDate>(i), 15, 10, 0); appointmentCollection.Add(new ScheduleAppointment() { StartTime = startDate, EndTime = endDate, AppointmentBackground = UIColor.LightGray }); } schedule.ItemsSource = appointmentCollection; } protected override void Dispose(bool disposing) { if (schedule != null) { schedule.Dispose(); } if (appointmentCollection != null) { appointmentCollection.Clear(); } if (startTimeCollection != null) { startTimeCollection.Clear(); } if (endTimeCollection != null) { endTimeCollection.Clear(); } if (subjectCollection != null) { subjectCollection.Clear(); } schedule = null; appointmentCollection = null; endTimeCollection = null; startTimeCollection = null; subjectCollection = null; } } } <file_sep>/Forms/ImageEditor/ImageEditor/Samples/CustomViewSample/CustomViewSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfImageEditor.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfImageEditor { public partial class CustomViewSample : SampleView { CustomViewViewModel viewModel; CustomViewModel model; double height = 0, width = 0; public CustomViewSample() { viewModel = new CustomViewViewModel(); model = new CustomViewModel(); this.BindingContext = new ImageListModel(viewModel); InitializeComponent(); } void ImageTapped(object sender, System.EventArgs e) { LoadFromStream((sender as Image).Source, viewModel, model); } void LoadFromStream(ImageSource source, CustomViewViewModel viewModel, CustomViewModel model) { if (Device.RuntimePlatform.ToLower() == "ios") { Navigation.PushAsync(new NavigationPage(new CustomViewHomePage(source, viewModel))); } else if (Device.RuntimePlatform.ToLower() == "uwp") { Navigation.PushAsync(new CustomViewHomePage(source, viewModel)); } else { Navigation.PushModalAsync(new CustomViewHomePage(source, viewModel)); } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.RuntimePlatform.ToLower() == "uwp" && Device.Idiom == TargetIdiom.Desktop) { imageGrid.RowDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 70, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(2, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Clear(); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); } else if ((width != this.width || height != this.height) && (width > -1 || height > -1)) { this.width = width; this.height = height; if (width < height) { imageGrid.RowDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 70, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.6, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Clear(); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); } else { imageGrid.RowDefinitions.Clear(); mainGrid.ColumnDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 10, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1.5, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0.5, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0.5, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0.5, GridUnitType.Star) }); } } } } public class ImageListModel { public ImageSource Image1 { get; set; } public ImageSource Image2 { get; set; } public ImageSource Image3 { get; set; } public ImageListModel(CustomViewViewModel viewmodel) { Image1 = viewmodel.ImageList[0].Image; Image2 = viewmodel.ImageList[1].Image; Image3 = viewmodel.ImageList[2].Image; } } public class CustomViewViewModel { public ObservableCollection<CustomViewModel> ImageList { get; set; } public CustomViewViewModel() { Assembly assembly = typeof(CustomViewHomePage).GetTypeInfo().Assembly; ImageList = new ObservableCollection<CustomViewModel> { #if COMMONSB new CustomViewModel { Image=ImageSource.FromResource("SampleBrowser.Icons.EditorBuilding1.png",assembly),ImageName="Nature1"} , new CustomViewModel { Image=ImageSource.FromResource("SampleBrowser.Icons.EditorBuilding2.png",assembly),ImageName="Nature2"} , new CustomViewModel { Image=ImageSource.FromResource("SampleBrowser.Icons.EditorTablet.png",assembly),ImageName="Nature3"} , #else new CustomViewModel { Image=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorBuilding1.png",assembly),ImageName="Nature1"} , new CustomViewModel { Image=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorBuilding2.png",assembly),ImageName="Nature2"} , new CustomViewModel { Image=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorTablet.png",assembly),ImageName="Nature3"} , #endif }; } } public class CustomViewModel { public ImageSource Image { get; set; } public string ImageName { get; set; } } }<file_sep>/Forms/Chart/Chart/Samples/TechnicalIndicator/TechnicalIndicatorViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using Syncfusion.SfChart.XForms; namespace SampleBrowser.SfChart { public class TechnicalIndicatorViewModel { public ObservableCollection<ChartDataPoint> TechnicalIndicatorData { get; set; } public TechnicalIndicatorViewModel() { DateTime calendar = new DateTime(2000, 1, 1); TechnicalIndicatorData = new ObservableCollection<ChartDataPoint> { new ChartDataPoint(calendar.AddMonths(1), 65.75, 67.27, 65.75, 65.98, 7938200), new ChartDataPoint(calendar.AddMonths(2), 65.98, 65.70, 65.04, 65.11, 10185300), new ChartDataPoint(calendar.AddMonths(3), 65.11, 65.05, 64.26, 64.97, 10835800), new ChartDataPoint(calendar.AddMonths(4), 64.97, 65.16, 64.09, 64.29, 9613400), new ChartDataPoint(calendar.AddMonths(5), 64.29, 62.73, 61.85, 62.44, 17175000), new ChartDataPoint(calendar.AddMonths(6), 62.44, 62.02, 61.29, 61.47, 18040600), new ChartDataPoint(calendar.AddMonths(7), 61.47, 62.75, 61.55, 61.59, 13456300), new ChartDataPoint(calendar.AddMonths(8), 61.59, 64.78, 62.22, 64.64, 8045100), new ChartDataPoint(calendar.AddMonths(9), 64.64, 64.50, 63.03, 63.28, 8608900), new ChartDataPoint(calendar.AddMonths(10), 63.28, 63.70, 62.70, 63.59, 15025500), new ChartDataPoint(calendar.AddMonths(11), 63.59, 64.45, 63.26, 63.61, 10065800), new ChartDataPoint(calendar.AddMonths(12), 63.61, 64.56, 63.81, 64.52, 6178200), new ChartDataPoint(calendar.AddMonths(13), 64.52, 64.84, 63.66, 63.91, 5478500), new ChartDataPoint(calendar.AddMonths(14), 63.91, 65.30, 64.50, 65.22, 7964300), new ChartDataPoint(calendar.AddMonths(15), 65.22, 65.36, 64.46, 65.06, 5679300), new ChartDataPoint(calendar.AddMonths(16), 65.06, 64.54, 63.56, 63.65, 10758300), new ChartDataPoint(calendar.AddMonths(17), 63.65, 64.03, 63.33, 63.73, 5665900), new ChartDataPoint(calendar.AddMonths(18), 63.73, 63.40, 62.80, 62.83, 5833000), new ChartDataPoint(calendar.AddMonths(19), 62.83, 63.75, 62.96, 63.60, 3500800), new ChartDataPoint(calendar.AddMonths(20), 63.6, 63.64, 62.51, 63.51, 5044700), new ChartDataPoint(calendar.AddMonths(21), 63.51, 64.03, 63.53, 63.76, 4871300), new ChartDataPoint(calendar.AddMonths(22), 63.76, 63.77, 63.01, 63.65, 7040400), new ChartDataPoint(calendar.AddMonths(23), 63.65, 63.95, 63.58, 63.79, 4727800), new ChartDataPoint(calendar.AddMonths(24), 63.79, 63.47, 62.92, 63.25, 6334900), new ChartDataPoint(calendar.AddMonths(25), 63.25, 63.96, 63.21, 63.48, 6823200), new ChartDataPoint(calendar.AddMonths(26), 63.48, 63.63, 62.55, 63.50, 9718400), new ChartDataPoint(calendar.AddMonths(27), 63.5, 63.25, 62.82, 62.90, 2827000), new ChartDataPoint(calendar.AddMonths(28), 62.9, 62.34, 62.05, 62.18, 4942700), new ChartDataPoint(calendar.AddMonths(29), 62.18, 62.86, 61.94, 62.81, 4582800), new ChartDataPoint(calendar.AddMonths(30), 62.81, 63.06, 62.44, 62.83, 12423900), new ChartDataPoint(calendar.AddMonths(31), 62.83, 63.16, 62.66, 63.09, 4940500), new ChartDataPoint(calendar.AddMonths(32), 63.09, 62.89, 62.43, 62.66, 6132300), new ChartDataPoint(calendar.AddMonths(33), 62.66, 62.39, 61.90, 62.25, 6263800), new ChartDataPoint(calendar.AddMonths(34), 62.25, 61.69, 60.97, 61.50, 5008300), new ChartDataPoint(calendar.AddMonths(35), 61.5, 61.87, 61.18, 61.79, 6662500), new ChartDataPoint(calendar.AddMonths(36), 61.79, 63.41, 62.72, 63.16, 5254000), new ChartDataPoint(calendar.AddMonths(37), 63.16, 64.40, 63.65, 63.89, 5356600), new ChartDataPoint(calendar.AddMonths(38), 63.89, 63.45, 61.60, 61.87, 5052600), new ChartDataPoint(calendar.AddMonths(39), 61.87, 62.35, 61.30, 61.54, 6266700), new ChartDataPoint(calendar.AddMonths(40), 61.54, 61.49, 60.33, 61.06, 6190800), new ChartDataPoint(calendar.AddMonths(41), 61.06, 60.78, 59.84, 60.09, 6452300), new ChartDataPoint(calendar.AddMonths(42), 60.09, 59.62, 58.62, 58.80, 5954000), new ChartDataPoint(calendar.AddMonths(43), 58.8, 59.60, 58.89, 59.53, 6250000), new ChartDataPoint(calendar.AddMonths(44), 59.53, 60.96, 59.42, 60.68, 5307300), new ChartDataPoint(calendar.AddMonths(45), 60.68, 61.12, 60.65, 60.73, 6192900), new ChartDataPoint(calendar.AddMonths(46), 60.73, 61.19, 60.62, 61.19, 6355600), new ChartDataPoint(calendar.AddMonths(47), 61.19, 61.07, 60.54, 60.97, 2946300), new ChartDataPoint(calendar.AddMonths(48), 60.97, 61.05, 59.65, 59.75, 2257600), new ChartDataPoint(calendar.AddMonths(49), 59.75, 60.58, 55.99, 59.93, 2872000), new ChartDataPoint(calendar.AddMonths(50), 59.93, 60.12, 59.26, 59.73, 2737500), new ChartDataPoint(calendar.AddMonths(51), 59.73, 60.11, 59.35, 59.57, 2589700), new ChartDataPoint(calendar.AddMonths(52), 59.57, 60.40, 59.60, 60.10, 7315800), new ChartDataPoint(calendar.AddMonths(53), 60.1, 60.31, 59.76, 60.28, 6883900), new ChartDataPoint(calendar.AddMonths(54), 60.28, 61.68, 60.50, 61.50, 5570700), new ChartDataPoint(calendar.AddMonths(55), 61.5, 62.72, 61.64, 62.26, 5976000), new ChartDataPoint(calendar.AddMonths(56), 62.26, 64.08, 63.10, 63.70, 3641400), new ChartDataPoint(calendar.AddMonths(57), 63.7, 64.60, 63.99, 64.39, 6711600), new ChartDataPoint(calendar.AddMonths(58), 64.39, 64.45, 63.92, 64.25, 6427000), new ChartDataPoint(calendar.AddMonths(59), 64.25, 65.40, 64.66, 64.70, 5863200), new ChartDataPoint(calendar.AddMonths(60), 64.7, 65.86, 65.32, 65.75, 4711400), new ChartDataPoint(calendar.AddMonths(61), 65.75, 65.22, 64.63, 64.75, 5930600), new ChartDataPoint(calendar.AddMonths(62), 64.75, 65.39, 64.76, 65.04, 5602700), new ChartDataPoint(calendar.AddMonths(63), 65.04, 65.30, 64.78, 65.18, 7487300), new ChartDataPoint(calendar.AddMonths(64), 65.18, 65.09, 64.42, 65.09, 9085400), new ChartDataPoint(calendar.AddMonths(65), 65.09, 65.64, 65.20, 65.25, 6455300), new ChartDataPoint(calendar.AddMonths(66), 65.25, 65.59, 64.74, 64.84, 6135500), new ChartDataPoint(calendar.AddMonths(67), 64.84, 65.84, 65.42, 65.82, 5846400), new ChartDataPoint(calendar.AddMonths(68), 65.82, 66.75, 65.85, 66.00, 6681200), new ChartDataPoint(calendar.AddMonths(69), 66, 67.41, 66.17, 67.41, 8780000), new ChartDataPoint(calendar.AddMonths(70), 67.41, 68.61, 68.06, 68.41, 10780900), new ChartDataPoint(calendar.AddMonths(71), 68.41, 68.91, 68.42, 68.76, 2336450), new ChartDataPoint(calendar.AddMonths(72), 68.76, 69.58, 68.86, 69.01, 11902000), new ChartDataPoint(calendar.AddMonths(73), 69.01, 69.14, 68.74, 68.94, 7513300), new ChartDataPoint(calendar.AddMonths(74), 68.94, 68.73, 68.06, 68.65, 12074800), new ChartDataPoint(calendar.AddMonths(75), 68.65, 68.79, 68.19, 68.67, 8785400), new ChartDataPoint(calendar.AddMonths(76), 68.67, 69.75, 68.68, 68.74, 11373200), new ChartDataPoint(calendar.AddMonths(77), 68.74, 68.82, 67.71, 67.76, 12378300), new ChartDataPoint(calendar.AddMonths(78), 67.76, 69.05, 68.43, 69.00, 8458700), new ChartDataPoint(calendar.AddMonths(79), 69, 68.39, 67.77, 68.02, 10779200), new ChartDataPoint(calendar.AddMonths(80), 68.02, 67.94, 67.22, 67.72, 9665400), new ChartDataPoint(calendar.AddMonths(81), 67.72, 68.15, 67.32, 67.32, 12258400), new ChartDataPoint(calendar.AddMonths(82), 67.32, 67.95, 67.13, 67.32, 7563600), new ChartDataPoint(calendar.AddMonths(83), 67.32, 68.00, 67.16, 67.96, 5509900), new ChartDataPoint(calendar.AddMonths(84), 67.96, 68.89, 68.34, 68.61, 12135500), new ChartDataPoint(calendar.AddMonths(85), 68.61, 69.47, 68.30, 68.51, 8462000), new ChartDataPoint(calendar.AddMonths(86), 68.51, 68.69, 68.21, 68.62, 2011950), new ChartDataPoint(calendar.AddMonths(87), 68.62, 68.39, 65.80, 68.37, 8536800), new ChartDataPoint(calendar.AddMonths(88), 68.37, 67.75, 65.00, 62.00, 7624900), new ChartDataPoint(calendar.AddMonths(89), 67.62, 67.04, 65.04, 67.00, 13694600), new ChartDataPoint(calendar.AddMonths(90), 66, 66.83, 65.02, 67.60, 8911200), new ChartDataPoint(calendar.AddMonths(91), 66.6, 66.98, 65.44, 66.73, 6679600), new ChartDataPoint(calendar.AddMonths(92), 66.73, 66.84, 65.10, 66.11, 6451900), new ChartDataPoint(calendar.AddMonths(93), 66.11, 66.59, 65.69, 66.38, 6739100), new ChartDataPoint(calendar.AddMonths(94), 66.38, 67.98, 66.51, 67.67, 2103260), new ChartDataPoint(calendar.AddMonths(95), 67.67, 69.21, 68.59, 68.90, 10551800), new ChartDataPoint(calendar.AddMonths(96), 68.9, 69.96, 69.27, 69.44, 5261100), new ChartDataPoint(calendar.AddMonths(97), 69.44, 69.01, 68.14, 68.18, 5905400), new ChartDataPoint(calendar.AddMonths(98), 68.18, 68.93, 68.08, 68.14, 10283600), new ChartDataPoint(calendar.AddMonths(99), 68.14, 68.60, 66.92, 67.25, 5006800), new ChartDataPoint(calendar.AddMonths(100), 67.25, 67.77, 67.23, 67.77, 4110000) }; } } }<file_sep>/Forms/DataSource/DataSource/Samples/DataSourceSorting/DataSourceSorting.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Xamarin.Forms; using Syncfusion.DataSource; using SampleBrowser.Core; using Xamarin.Forms.Internals; namespace SampleBrowser.DataSource { [Preserve(AllMembers = true)] public partial class DataSourceSorting : SampleView { ContatsViewModel viewModel; Syncfusion.DataSource.DataSource sfDataSource; public DataSourceSorting() { InitializeComponent(); viewModel = new ContatsViewModel(); sfDataSource = new Syncfusion.DataSource.DataSource(); sfDataSource.Source = viewModel.ContactsList; sfDataSource.BeginInit(); sfDataSource.SortDescriptors.Add(new SortDescriptor("ContactName")); sfDataSource.EndInit(); listView.ItemsSource = sfDataSource.DisplayItems; optionList.SelectedIndex = 0; } private void OnFilterTextChanged(object sender, TextChangedEventArgs e) { if (sfDataSource != null) { this.sfDataSource.Filter = FilterContacts; this.sfDataSource.RefreshFilter(); } } private bool FilterContacts(object obj) { var contacts = obj as Contacts; if (filterText.Text == null || contacts.ContactName.ToLower().Contains(filterText.Text.ToLower()) || contacts.ContactNumber.ToLower().Contains(filterText.Text.ToLower())) return true; else return false; } private void OnSortDirectionChanged(object sender, EventArgs e) { Picker newPicker = (Picker)sender; var direction = newPicker.Items[newPicker.SelectedIndex]; sfDataSource.BeginInit(); sfDataSource.SortDescriptors.Clear(); sfDataSource.SortDescriptors.Add(new SortDescriptor() { PropertyName = "ContactName", Direction = direction == "Ascending" ? Syncfusion.DataSource.ListSortDirection.Ascending : Syncfusion.DataSource.ListSortDirection.Descending }); sfDataSource.EndInit(); } } }<file_sep>/iOS/SampleBrowser/Samples/Rating/Rating_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfRating.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Rating_Tablet: SampleView { UILabel precisionLabel,toolTipLabel,itemCountLabel; UILabel movieRateLabel,walkLabel,timeLabel,descriptionLabel,rateLabel,valueLabel,propertiesLabel; UITextView itemCountTextfield; UIImageView image1; UIView customView; UIScrollView subView; UIButton showPropertyButton,closeButton; UIButton precisionButton = new UIButton (); UIButton toolTipButton = new UIButton (); UIButton doneButton=new UIButton(); UIView contentView = new UIView (); UIView controlView = new UIView (); PickerModel model,model1; UIPickerView precisionPicker, toolTipPicker; private string selectedType; private UIView activeview; // Controller that activated the keyboard private float scroll_amount = 0.0f; // amount to scroll private float bottom = 0.0f; // bottom point private float offset = 10.0f; // extra offset private bool moveViewUp = false; SfRating rating2,rating1; private readonly IList<string> precisionList = new List<string> { "Standard", "Half", "Exact" }; private readonly IList<string> toottipplace = new List<string> { "TopLeft", "BottomRight", "None" }; void Rating_ValueChanged(object sender, ValueChangedEventArgs e) { UpdateText(); } public Rating_Tablet() { //Rating 1 rating1 = new SfRating (); rating1.ItemCount=5; rating1.Precision= SFRatingPrecision.Standard; rating1.TooltipPlacement= SFRatingTooltipPlacement.None; rating1.ItemSize=30; rating1.Value = 3; rating1.ItemSpacing = 30; rating1.ValueChanged += Rating_ValueChanged; //RatingSettings SfRatingSettings ratingSetting = new SfRatingSettings (); ratingSetting.RatedFill = UIColor.FromRGB (251,209,10); ratingSetting.RatedStroke = UIColor.FromRGB (251,209,10); //Rating 2 rating2 = new SfRating(); rating2.ItemCount=5; rating2.RatingSettings = ratingSetting; rating2.Precision = SFRatingPrecision.Half; rating2.TooltipPlacement= SFRatingTooltipPlacement.None; rating2.ItemSize=10; rating2.Readonly=true; rating2.Value=(nfloat)3.5; rating2.ItemSpacing = 5; mainPageDesign(); autoHide(); loadOptionView(); } public void autoHide() { NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, KeyBoardUpNotification); NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, KeyBoardDownNotification); } private void KeyBoardUpNotification(NSNotification notification) { propertiesLabel.Hidden = true; closeButton.Hidden = true; // get the keyboard size var r = UIKeyboard.BoundsFromNotification(notification); // Find what opened the keyboard foreach (UIView view in this.contentView.Subviews) { if (view.IsFirstResponder) activeview = view; } // Bottom of the controller = initial position + height + offset bottom = ((float)(activeview.Frame.Y + activeview.Frame.Height + offset)); // Calculate how far we need to scroll scroll_amount = ((float)(r.Height - (contentView.Frame.Size.Height - bottom))); // Perform the scrolling if (scroll_amount > 0) { moveViewUp = true; ScrollTheView(moveViewUp); } else { moveViewUp = false; } } private void KeyBoardDownNotification(NSNotification notification) { propertiesLabel.Hidden = false; closeButton.Hidden = false; if (moveViewUp) { ScrollTheView(false); } } private void ScrollTheView(bool move) { // scroll the view up or down UIView.BeginAnimations(string.Empty, System.IntPtr.Zero); UIView.SetAnimationDuration(0.1); var frame = contentView.Frame; if (move) { frame.Y -= scroll_amount; } else { frame.Y += scroll_amount; scroll_amount = 0; } contentView.Frame = frame; UIView.CommitAnimations(); } public void mainPageDesign() { customView = new UIView(); customView.BackgroundColor = UIColor.FromRGB(165, 165, 165); //Image image1 = new UIImageView(); image1.Image = UIImage.FromBundle("Images/walk.png"); //PrecisionLabell precisionLabel = new UILabel(); precisionLabel.Text = "Precision"; precisionLabel.Font = UIFont.FromName("Helvetica", 14f); precisionLabel.TextColor = UIColor.Black; precisionLabel.TextAlignment = UITextAlignment.Left; //ToolTipLabell toolTipLabel = new UILabel(); toolTipLabel.Text = "ToolTip Placement"; toolTipLabel.Font = UIFont.FromName("Helvetica", 14f); toolTipLabel.TextColor = UIColor.Black; toolTipLabel.TextAlignment = UITextAlignment.Left; //ItemCountLabell itemCountLabel = new UILabel(); itemCountLabel.Text = "Item Count"; itemCountLabel.Font = UIFont.FromName("Helvetica", 14f); itemCountLabel.TextColor = UIColor.Black; itemCountLabel.TextAlignment = UITextAlignment.Left; //MovieRateLabell movieRateLabel = new UILabel(); movieRateLabel.Text = "Movie Rating"; movieRateLabel.TextColor = UIColor.Black; movieRateLabel.TextAlignment = UITextAlignment.Left; movieRateLabel.Font = UIFont.FromName("Helvetica", 22f); //WalkLabell walkLabel = new UILabel(); walkLabel.Text = "The Walk (2015)"; walkLabel.TextColor = UIColor.Black; walkLabel.TextAlignment = UITextAlignment.Left; walkLabel.Font = UIFont.FromName("Helvetica", 18f); //TimeLabell timeLabel = new UILabel(); timeLabel.Text = "PG | 2 h 20 min"; timeLabel.TextColor = UIColor.Black; timeLabel.TextAlignment = UITextAlignment.Left; timeLabel.Font = UIFont.FromName("Helvetica", 12f); //DescriptionLabell descriptionLabel = new UILabel(); descriptionLabel.Text = "In 1974, high-wire artist <NAME> recruits a team of people to help him realize his dream: to walk the immense void between the world Trade Centre towers."; descriptionLabel.TextColor = UIColor.Black; descriptionLabel.TextAlignment = UITextAlignment.Left; descriptionLabel.Font = UIFont.FromName("Helvetica", 14f); descriptionLabel.LineBreakMode = UILineBreakMode.WordWrap; descriptionLabel.Lines = 0; //RateLabell rateLabel = new UILabel(); rateLabel.Text = "Rate"; rateLabel.TextColor = UIColor.Black; rateLabel.TextAlignment = UITextAlignment.Left; rateLabel.Font = UIFont.FromName("Helvetica", 18f); //ValueLabell valueLabel = new UILabel(); valueLabel.TextColor = UIColor.Black; valueLabel.TextAlignment = UITextAlignment.Left; valueLabel.Font = UIFont.FromName("Helvetica", 14f); UpdateText(); } public void loadOptionView() { //PrecisionButton precisionButton = new UIButton(); precisionButton.SetTitle("Standard", UIControlState.Normal); precisionButton.Font = UIFont.FromName("Helvetica", 14f); precisionButton.SetTitleColor(UIColor.Black, UIControlState.Normal); precisionButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; precisionButton.Layer.CornerRadius = 8; precisionButton.Layer.BorderWidth = 2; precisionButton.TouchUpInside += ShowPicker1; precisionButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //TooltipButton toolTipButton = new UIButton(); toolTipButton.SetTitle("None", UIControlState.Normal); toolTipButton.Font = UIFont.FromName("Helvetica", 14f); toolTipButton.SetTitleColor(UIColor.Black, UIControlState.Normal); toolTipButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; toolTipButton.Layer.CornerRadius = 8; toolTipButton.Layer.BorderWidth = 2; toolTipButton.TouchUpInside += ShowPicker2; toolTipButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //DoneButton doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.Font = UIFont.FromName("Helvetica", 14f); doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); //Picker precisionPicker = new UIPickerView(); toolTipPicker = new UIPickerView(); model = new PickerModel(precisionList); precisionPicker.Model = model; model1 = new PickerModel(toottipplace); toolTipPicker.Model = model1; model.PickerChanged += SelectedIndexChanged; model1.PickerChanged += SelectedIndexChanged1; precisionPicker.ShowSelectionIndicator = true; precisionPicker.Hidden = true; toolTipPicker.Hidden = true; precisionPicker.BackgroundColor = UIColor.Gray; toolTipPicker.BackgroundColor = UIColor.Gray; toolTipPicker.ShowSelectionIndicator = true; //ItemCountTextField itemCountTextfield = new UITextView(); itemCountTextfield.TextAlignment = UITextAlignment.Center; itemCountTextfield.Layer.BorderColor = UIColor.Black.CGColor; itemCountTextfield.BackgroundColor = UIColor.FromRGB(246, 246, 246); itemCountTextfield.KeyboardType = UIKeyboardType.NumberPad; itemCountTextfield.Text = "5"; itemCountTextfield.Font = UIFont.FromName("Helvetica", 14f); itemCountTextfield.Changed += (object sender, EventArgs e) => { if (itemCountTextfield.Text.Length > 0) { rating1.ItemCount = int.Parse(itemCountTextfield.Text); } else { rating1.ItemCount = 5; } UpdateText(); }; //adding to controlView controlView.AddSubview(rating1); controlView.AddSubview(rating2); controlView.AddSubview(movieRateLabel); controlView.AddSubview(walkLabel); controlView.AddSubview(timeLabel); controlView.AddSubview(descriptionLabel); controlView.AddSubview(rateLabel); controlView.AddSubview(valueLabel); controlView.AddSubview(image1); controlView.AddSubview(itemCountTextfield); this.AddSubview(controlView); //Adding to content view contentView.AddSubview(precisionLabel); contentView.AddSubview(toolTipLabel); contentView.AddSubview(precisionButton); contentView.AddSubview(itemCountLabel); contentView.AddSubview(toolTipButton); contentView.AddSubview(precisionPicker); contentView.AddSubview(toolTipPicker); contentView.AddSubview(doneButton); contentView.AddSubview(itemCountTextfield); contentView.BackgroundColor = UIColor.FromRGB(240, 240, 240); //PropertyLabel propertiesLabel = new UILabel(); propertiesLabel.Text = " OPTIONS"; //ShowpropertyButton showPropertyButton = new UIButton(); showPropertyButton.Hidden = true; showPropertyButton.SetTitle("OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = false; showPropertyButton.Hidden = true; }; this.AddSubview(showPropertyButton); //CloseButton closeButton = new UIButton(); closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; }; //AddingGesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer(() => { subView.Hidden = true; showPropertyButton.Hidden = false; } ); propertiesLabel.UserInteractionEnabled = true; propertiesLabel.AddGestureRecognizer(tapgesture); //Adding to subvieww subView = new UIScrollView(); subView.ContentSize = new CGSize(Frame.Width, 350); subView.AddSubview(contentView); subView.AddSubview(propertiesLabel); subView.AddSubview(closeButton); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); this.AddSubview(subView); } private void UpdateText() { nint tempIntValue = (nint)rating1.Value; nfloat tempFloatValue = rating1.Value; nfloat differencevalue = tempFloatValue - tempIntValue; if(differencevalue == 0) valueLabel.Text = "Rating : "+tempIntValue+" / "+rating1.ItemCount; else valueLabel.Text = "Rating : "+ Math.Round (tempFloatValue,1)+" / "+rating1.ItemCount; } public void SetValue(nfloat value) { UpdateText (); } void ShowPicker1 (object sender, EventArgs e) { doneButton.Hidden = false; precisionPicker.Hidden = false; itemCountLabel.Hidden = itemCountLabel.Hidden = true; itemCountTextfield.Hidden = true;; itemCountTextfield.Hidden = true; toolTipPicker.Hidden = true; } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; toolTipPicker.Hidden = true; itemCountLabel.Hidden = false; itemCountTextfield.Hidden = false; precisionPicker.Hidden = true; } void ShowPicker2 (object sender, EventArgs e) { doneButton.Hidden = false; precisionPicker.Hidden = true; toolTipPicker.Hidden = false; itemCountLabel.Hidden = true; itemCountTextfield.Hidden = true; } private void SelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; precisionButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Standard") { rating1.Precision = SFRatingPrecision.Standard; } else if (selectedType == "Half") { rating1.Precision = SFRatingPrecision.Half; } else if (selectedType == "Exact") { rating1.Precision = SFRatingPrecision.Exact; } } public override void TouchesBegan (NSSet touches, UIEvent evt){ this.EndEditing (true); } private void SelectedIndexChanged1(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; toolTipButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "TopLeft") { rating1.TooltipPlacement = SFRatingTooltipPlacement.TopLeft; } else if (selectedType == "BottomRight") { rating1.TooltipPlacement = SFRatingTooltipPlacement.BottomRight; } else if (selectedType == "None") { rating1.TooltipPlacement = SFRatingTooltipPlacement.None; } } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; subView.Frame = new CGRect (0, view.Frame.Size.Height -view.Frame.Size.Height/3, view.Frame.Size.Width, view.Frame.Size.Height/3); controlView.Frame=new CGRect(100,40,this.Frame.Size.Width-200,this.Frame.Size.Height-40); contentView.Frame=new CGRect(0,40,subView.Frame.Size.Width,subView.Frame.Size.Height); customView.Frame = new CGRect (10, 220,view.Frame.Width-20, 1); rating1.Frame = new CGRect (10,355,270,50); rating2.Frame = new CGRect (295,60,200,20); movieRateLabel.Frame = new CGRect(10, 0, 200, 30); walkLabel.Frame = new CGRect (220,30,160,30); timeLabel.Frame = new CGRect (220,51,80,30); descriptionLabel.Frame = new CGRect (220, 10, 400, 200); rateLabel.Frame = new CGRect (10,315,200,30); valueLabel.Frame = new CGRect (10,405,200,30); image1.Frame = new CGRect (10, 30, 200, 255); precisionLabel.Frame = new CGRect (100,40, contentView.Frame.Size.Width-210, 30); toolTipLabel.Frame = new CGRect (100, 90, contentView.Frame.Size.Width-220, 30); itemCountLabel.Frame = new CGRect (100, 140,contentView.Frame.Size.Width-210 , 30); precisionButton.Frame=new CGRect (350, 40, contentView.Frame.Size.Width - 520, 30); toolTipButton.Frame=new CGRect (350, 90, contentView.Frame.Size.Width - 520, 30); itemCountTextfield.Frame = new CGRect (350, 140, contentView.Frame.Size.Width - 520, 30); precisionPicker.Frame = new CGRect (100,0, contentView.Frame.Size.Width-200,200); toolTipPicker.Frame = new CGRect (100,0 , contentView.Frame.Size.Width-200 , 200); doneButton.Frame = new CGRect (100,0 , contentView.Frame.Size.Width-200, 30); showPropertyButton.Frame = new CGRect (0, this.Frame.Size.Height - 25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect (this.Frame.Size.Width - 30, 5, 20, 30); propertiesLabel.Frame = new CGRect (10, 5, this.Frame.Width, 30); } base.LayoutSubviews (); } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/Helpers/CustomView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Util; namespace SampleBrowser { public class RowDragDropTemplate : LinearLayout { #region Fields Paint paint; Label label1; Label label2; Label label3; Label label4; Label label5; #endregion #region Constructor public RowDragDropTemplate(Context context) : base(context) { this.SetWillNotDraw(false); paint = new Paint(PaintFlags.AntiAlias); paint.SetStyle(Paint.Style.Stroke); this.Orientation = Orientation.Horizontal; paint.Color = Color.Black; label1 = new Label(context) { Gravity = GravityFlags.Center }; label2 = new Label(context) { Gravity = GravityFlags.Center }; label3 = new Label(context) { Gravity = GravityFlags.Center }; label4 = new Label(context) { Gravity = GravityFlags.Center, IsLastLabel = true }; label5 = new Label(context) { Gravity = GravityFlags.Center, IsLastLabel = true }; this.AddView(label1); this.AddView(label2); this.AddView(label3); this.AddView(label4); //this.AddView(label5); } public RowDragDropTemplate(Context context, IAttributeSet attrs) : base(context, attrs) { } public RowDragDropTemplate(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { } public RowDragDropTemplate(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes) { } protected RowDragDropTemplate(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } #endregion #region Methods protected override void OnDraw(Canvas canvas) { canvas.DrawRect(0, 0, this.Width, this.Height, paint); base.OnDraw(canvas); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { UpdateLabelWidthAndHeight(); base.OnLayout(changed, l, t, r, b); this.label1.Layout(0, 0, this.Width / 4, this.Height); this.label2.Layout(label1.Right, 0, (this.Width / 4) * 2, this.Height); this.label3.Layout(label2.Right, 0, (this.Width / 4) * 3, this.Height); this.label4.Layout(label3.Right, 0, (this.Width / 4) * 4, this.Height); // this.label5.Layout(label4.Right, 0, (this.Width / 4) * 5, this.Height); } internal void UpdateRow(object rowData) { var orderInfo = rowData as OrderInfo; label1.Text = orderInfo.OrderID; label2.Text = orderInfo.EmployeeID; label3.Text = orderInfo.CustomerID; label4.Text = orderInfo.FirstName; //label5.Text = orderInfo.LastName; } internal void UpdateLabelWidthAndHeight() { label1.SetWidth(this.Width / 4); label2.SetWidth(this.Width / 4); label3.SetWidth(this.Width / 4); label4.SetWidth(this.Width / 4); //label5.SetWidth(this.Width / 5); label1.SetHeight(this.Height); label2.SetHeight(this.Height); label3.SetHeight(this.Height); label4.SetHeight(this.Height); //label5.SetHeight(this.Height); } #endregion } public class Label : TextView { public bool IsLastLabel { get; set; } public Label(Context context) : base(context) { this.SetWillNotDraw(false); } public Label(Context context, IAttributeSet attrs) : base(context, attrs) { } public Label(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { } public Label(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes) { } protected Label(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } protected override void OnDraw(Canvas canvas) { if (!IsLastLabel) canvas.DrawLine(this.Width - this.Resources.DisplayMetrics.Density / 2, 0, this.Width - this.Resources.DisplayMetrics.Density / 2, this.Height, new Android.Graphics.Paint() { Color = Color.Black }); base.OnDraw(canvas); } } }<file_sep>/Forms/Chart/Chart/Samples/PyramidChart/PyramidSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class PyramidSeriesViewModel { public ObservableCollection<ChartDataModel> PyramidData { get; set; } public PyramidSeriesViewModel() { PyramidData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sweet Treats", 120), new ChartDataModel("Milk, Youghnut, Cheese", 435), new ChartDataModel("Vegetables", 470), new ChartDataModel("Meat, Poultry, Fish", 475), new ChartDataModel("Fruits", 520), new ChartDataModel("Bread, Rice, Pasta", 930), }; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/CustomerInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CustomerInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Syncfusion.Data; using Xamarin.Forms; /// <summary> /// A class for comparing CustomerInfo Objects /// </summary> public class CustomerInfo : IComparer<object>, ISortDirection { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int namX; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int namY; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] //// Get or Set the SortDirection value private Syncfusion.Data.ListSortDirection sortDirection; /// <summary> /// Gets or sets the value of SortDirection /// </summary> public Syncfusion.Data.ListSortDirection SortDirection { get { return this.sortDirection; } set { this.sortDirection = value; } } /// <summary> /// Used to compare the x and y value /// </summary> /// <param name="x">object type of comparer x value</param> /// <param name="y">object type of comparer y value</param> /// <returns>sort description</returns> public int Compare(object x, object y) { //// For Customers Type data //// else if => For Group type Data if (x.GetType() == typeof(CustomerDetails)) { //// Calculating the length of CustomerName if the object type is Customers this.namX = ((CustomerDetails)x).FirstName.Length; this.namY = ((CustomerDetails)y).FirstName.Length; } else if (x.GetType() == typeof(Group)) { //// Calculating the group key length this.namX = ((Group)x).Key.ToString().Length; this.namY = ((Group)y).Key.ToString().Length; } else { this.namX = x.ToString().Length; this.namY = y.ToString().Length; } //// Objects are compared and return the SortDirection if (this.namX.CompareTo(this.namY) > 0) { return this.SortDirection == Syncfusion.Data.ListSortDirection.Ascending ? 1 : -1; } else if (this.namX.CompareTo(this.namY) == -1) { return this.SortDirection == Syncfusion.Data.ListSortDirection.Ascending ? -1 : 1; } else { return 0; } } } } <file_sep>/Forms/ListView/ListView/Samples/GettingStarted/Model/ShoppingInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewShoppingCategoryInfo : INotifyPropertyChanged { #region Fields private string categoryName; private string categoryDesc; private string categoryImage; #endregion #region Constructor public ListViewShoppingCategoryInfo() { } #endregion #region Properties public string CategoryName { get { return categoryName; } set { categoryName = value; OnPropertyChanged("CategoryName"); } } public string CategoryDescription { get { return categoryDesc; } set { categoryDesc = value; OnPropertyChanged("CategoryDescription"); } } public string CategoryImage { get { return categoryImage; } set { categoryImage = value; OnPropertyChanged("CategoryImage"); } } #endregion #region Interface Member public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Forms/Sparkline/Sparkline/Samples/Sparkline/Sparkline_Phone.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfSparkline.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSparkline { [Preserve(AllMembers = true)] public partial class Sparkline_Phone : SampleView { SfAreaSparkline area; SfLineSparkline line; SfColumnSparkline column; SfWinLossSparkline winLoss; Label columnLabel, areaLabel, lineLabel, winLossLabel; public Sparkline_Phone() { InitializeComponent(); var dataModel = new SparkViewModel(); stack.BindingContext = dataModel; area = new SfAreaSparkline { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; area.ItemsSource = dataModel.Datas; area.YBindingPath = "Performance"; areaLabel = new Label { Text = "Area", FontSize = 14, HorizontalOptions = LayoutOptions.Center, FontAttributes = FontAttributes.Bold }; stack.Children.Add(area); stack.Children.Add(areaLabel); line = new SfLineSparkline { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; line.ItemsSource = dataModel.Datas; line.YBindingPath = "Performance"; lineLabel = new Label { Text = "Line", FontSize = 14, HorizontalOptions = LayoutOptions.Center, FontAttributes = FontAttributes.Bold }; stack.Children.Add(line); stack.Children.Add(lineLabel); column = new SfColumnSparkline { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; column.ItemsSource = dataModel.ColumnDatas; column.YBindingPath = "YearPerformance"; columnLabel = new Label { Text = "Column", FontSize = 14, HorizontalOptions = LayoutOptions.Center, FontAttributes = FontAttributes.Bold }; stack.Children.Add(column); stack.Children.Add(columnLabel); winLoss = new SfWinLossSparkline { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; winLoss.ItemsSource = dataModel.ColumnDatas; winLoss.YBindingPath = "YearPerformance"; winLossLabel = new Label { Text = "Win/Loss", FontSize = 14, HorizontalOptions = LayoutOptions.Center, FontAttributes = FontAttributes.Bold }; stack.Children.Add(winLoss); stack.Children.Add(winLossLabel); if (Device.RuntimePlatform == Device.iOS) stack.SizeChanged += Layout_SizeChanged; else { area.Margin = new Thickness(0, 5, 0, 5); line.Margin = new Thickness(0, 5, 0, 5); column.Margin = new Thickness(0, 5, 0, 5); winLoss.Margin = new Thickness(0, 5, 0, 5); } } public View getContent() { return Content; } public View getPropertyView() { return this.PropertyView; } protected void Layout_SizeChanged(object sender, System.EventArgs e) { var size = areaLabel.Bounds.Height; var labelHeight = size * 4; double controlPadding = 6; var height = stack.Height - (labelHeight + (controlPadding * 8)); var width = stack.Width; MeasureSparkline(width, height); } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); MeasureSparkline(width, height); } private void MeasureSparkline(double width, double height) { if (height > 0 && width > 0) { area.HeightRequest = 0.20 * height; line.HeightRequest = 0.20 * height; column.HeightRequest = 0.20 * height; winLoss.HeightRequest = 0.20 * height; lineLabel.HeightRequest = 0.05 * height; areaLabel.HeightRequest = 0.05 * height; columnLabel.HeightRequest = 0.05 * height; winLossLabel.HeightRequest = 0.05 * height; area.WidthRequest = width; line.WidthRequest = width; column.WidthRequest = width; winLoss.WidthRequest = width; } } } }<file_sep>/Forms/Picker/Picker/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfPicker.XForms; using Xamarin.Forms; namespace SampleBrowser.SfPicker { public partial class Themes : SampleView { public Themes() { InitializeComponent(); this.picker.BindingContext = new PickerViewModel(); } } public class ColorName { public string Name { get; set; } } public class PickerViewModel { private ObservableCollection<object> sportsCollection = new ObservableCollection<object>(); private ObservableCollection<object> selectedItemCollection = new ObservableCollection<object>(); public ObservableCollection<object> Items { get { return sportsCollection; } set { if (sportsCollection != value) { sportsCollection = value; } } } public ObservableCollection<object> SelectedItem { get { return selectedItemCollection; } set { if (selectedItemCollection != value) { selectedItemCollection = value; } } } public PickerViewModel() { ObservableCollection<object> sportsCollection = new ObservableCollection<object>(); sportsCollection.Add("Cricket"); sportsCollection.Add("Volley Ball"); sportsCollection.Add("Hockey"); sportsCollection.Add("Foot Ball"); sportsCollection.Add("Basket Ball"); sportsCollection.Add("Golf"); sportsCollection.Add("Badminton"); sportsCollection.Add("Tennis"); Items = sportsCollection; ObservableCollection<object> selectedItemCollection = new ObservableCollection<object>(); selectedItemCollection.Add("Cricket"); SelectedItem = selectedItemCollection; } } } <file_sep>/Forms/ListView/ListView/Samples/Orientation/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Syncfusion.ListView.XForms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewOrientationViewModel { #region Fields private ObservableCollection<PizzaInfo> pizzaInfo; private ObservableCollection<PizzaInfo> pizzaInfo1; #endregion #region Constructor public ListViewOrientationViewModel() { GenerateSource(); } #endregion #region Properties public ObservableCollection<PizzaInfo> PizzaInfo { get { return pizzaInfo; } set { this.pizzaInfo = value; } } public ObservableCollection<PizzaInfo> PizzaInfo1 { get { return pizzaInfo1; } set { this.pizzaInfo1 = value; } } #endregion #region Generate Source private void GenerateSource() { PizzaInfoRepository pizzainfo = new PizzaInfoRepository(); pizzaInfo = pizzainfo.GetPizzaInfo(); pizzaInfo1 = pizzainfo.GetPizzaInfo1(); } #endregion } } <file_sep>/Forms/Calculate/Calculate/Samples/CalcQuick/CalcQuickViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Calculate; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms.Internals; namespace SampleBrowser.Calculate { [Preserve(AllMembers = true)] public class CalcQuickViewModel : INotifyPropertyChanged { #region Fields private string textA; private string textB; private string textC; private string result1; private string result2; private string result3; private ICommand compute; #endregion #region Properties public string TextA { get { return textA; } set { textA = value; OnPropertyChanged("TextA"); } } public string TextB { get { return textB; } set { textB = value; OnPropertyChanged("TextB"); } } public string TextC { get { return textC; } set { textC = value; OnPropertyChanged("TextC"); } } public string Result1 { get { return result1; } set { result1 = value; OnPropertyChanged("Result1"); } } public string Result2 { get { return result2; } set { result2 = value; OnPropertyChanged("Result2"); } } public string Result3 { get { return result3; } set { result3 = value; OnPropertyChanged("Result3"); } } public ICommand ComputeCommand { get { if (compute == null) compute = new CalcQuickCommand(this); return compute; } set { compute = value; } } internal CalcQuickBase calcQuickBase { get; set; } #endregion #region Constructor public CalcQuickViewModel() { InitializeCalcQuick(); TextA = calcQuickBase["A"]; TextB = calcQuickBase["B"]; TextC = calcQuickBase["C"]; Result1 = calcQuickBase["Exp1"]; Result2 = calcQuickBase["Exp2"]; Result3 = calcQuickBase["Exp3"]; } #endregion private void InitializeCalcQuick() { calcQuickBase = new CalcQuickBase(); calcQuickBase.Engine.UseNoAmpersandQuotes = true; calcQuickBase["A"] = "25"; calcQuickBase["B"] = "50"; calcQuickBase["C"] = "10"; calcQuickBase["Exp1"] = "=Sum([A],[B],[C])"; calcQuickBase["Exp2"] = "=PI()*([A]^2)"; calcQuickBase["Exp3"] = "=Concatenate([A],[B],[C])"; } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion #region Dispose internal void Dispose() { calcQuickBase.Dispose(); calcQuickBase = null; } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Calculate/Helper/FunctionsLibraryViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using UIKit; namespace SampleBrowser { public class FunctionsLibraryViewModel : UIPickerViewModel { List<string> functions; UITextField formulaEdit; UITextField pickerTextView; FunctionsLibraryView libraryView; public FunctionsLibraryViewModel(UITextField textFeild, UITextField pickerView, FunctionsLibraryView _libraryView) { functions = new List<string>(); formulaEdit = textFeild; pickerTextView = pickerView; libraryView = _libraryView; functions = GetFunctions(); } private List<string> GetFunctions() { List<string> functions = new List<string>(); foreach (string item in libraryView.Engine.LibraryFunctions.Keys) functions.Add(item); functions.Sort(); functions.RemoveAt(0); functions.RemoveAt(0); functions.RemoveAt(0); functions.Remove("ACCRINTM"); functions.Remove("AVERAGEIFS"); functions.Remove("BETA.DIST"); functions.Remove("BIGMUL"); functions.Remove("IMAGINARYDIFFERENCE"); functions.Remove("IMPRODUCT"); functions.Remove("IMSUB"); functions.Remove("F.INV.RT"); functions.Remove("HYPGEOM.DIST"); functions.Remove("IMCONJUGATE"); functions.Remove("MIRR"); functions.Remove("FORMULATEXT"); functions.Remove("GROWTH"); functions.Remove("IRR"); functions.Remove("MDETERN"); functions.Remove("MMULT"); functions.Remove("NORM.INV"); functions.Remove("PROPER"); functions.Remove("REPLACEB"); functions.Remove("UNICODE"); functions.Remove("XIRR"); return functions; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return functions.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return functions[(int)row]; } public override void Selected(UIPickerView pickerView, nint row, nint component) { string item = functions[(int)row]; pickerTextView.Text = item; libraryView.EndEditing(true); FunctionsHelper.GetFunction(item, formulaEdit); } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { return new UILabel() { Text = functions[(int)row], Font = UIFont.FromName("Helvetica", 14f) }; } } }<file_sep>/Forms/Button/Button/Samples/CustomizationSample/CustomizationSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.Buttons; using System.Collections.ObjectModel; using Xamarin.Forms; namespace SampleBrowser.SfButton { #region Customization Sample Class public partial class CustomizationSample : SampleView { #region Constructor ViewModel viewModel; public CustomizationSample() { InitializeComponent(); viewModel = new ViewModel(); this.TextColorSegment.ItemsSource = viewModel.PrimaryColors; this.BackgroundColorSegment.ItemsSource = viewModel.PrimaryColors; this.BorderColorSegment.ItemsSource = viewModel.PrimaryColors; this.BindingContext = viewModel; if(Device.RuntimePlatform == Device.UWP) { shadow.IsVisible = false; } } void Handle_SelectionChanged(object sender, Syncfusion.XForms.Buttons.SelectionChangedEventArgs e) { if ((sender as Syncfusion.XForms.Buttons.SfSegmentedControl) == TextColorSegment) { viewModel.TextColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; this.TextColorSegment.SelectionTextColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; } else if ((sender as Syncfusion.XForms.Buttons.SfSegmentedControl) == BackgroundColorSegment) { viewModel.BackgroundColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; this.BackgroundColorSegment.SelectionTextColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; } else if ((sender as Syncfusion.XForms.Buttons.SfSegmentedControl) == BorderColorSegment) { viewModel.BorderColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; this.BorderColorSegment.SelectionTextColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; } } #endregion } #endregion }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/TechnicalIndicators.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using System.Collections.Generic; #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; #endif namespace SampleBrowser { public class TechnicalIndicators : SampleView { SFChart chart; SFSMAIndicator indicator; NSMutableArray indicatorCollection; UIPickerView indicatorTypePicker; UIButton doneButton; UIButton indicatorTypeTextButton; public TechnicalIndicators() { indicatorTypePicker = new UIPickerView(); indicatorTypeTextButton = new UIButton(); doneButton = new UIButton(); indicator = new SFSMAIndicator(); indicator.SeriesName = new NSString("Hi-Low"); indicator.XBindingPath = "XValue"; indicator.High = "High"; indicator.Low = "Low"; indicator.Open = "Open"; indicator.Close = "Close"; SFNumericalAxis axis = new SFNumericalAxis(); axis.OpposedPosition = true; axis.ShowMajorGridLines = false; indicator.YAxis = axis; indicatorCollection = new NSMutableArray(); indicatorCollection.Add(indicator); chart = new SFChart(); chart.Title.Text = new NSString("StockDetails"); chart.Title.TextAlignment = UITextAlignment.Center; SFDateTimeAxis datetime = new SFDateTimeAxis(); datetime.MaximumLabels = 6; datetime.LabelsIntersectAction = SFChartAxisLabelsIntersectAction.Hide; chart.PrimaryAxis = datetime; datetime.Title.Text = new NSString("Date"); chart.SecondaryAxis = new SFNumericalAxis(); SFChartTrackballBehavior behavior = new SFChartTrackballBehavior(); chart.AddChartBehavior(behavior); chart.TechnicalIndicators.Add(indicator); ChartViewModel dataModel = new ChartViewModel(); SFOHLCSeries series = new SFOHLCSeries(); series.ItemsSource = dataModel.TechnicalIndicatorData; series.XBindingPath = "XValue"; series.High = "High"; series.Low = "Low"; series.Open = "Open"; series.Close = "Close"; series.EnableTooltip = true; series.LineWidth = 1; series.SeriesName = new NSString("Hi-Low"); series.ColorModel.Palette = SFChartColorPalette.Natural; chart.Series.Add(series); this.AddSubview(chart); indicatorTypeTextButton.SetTitle("SMA indicator", UIControlState.Normal); indicatorTypeTextButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; indicatorTypeTextButton.SetTitleColor(UIColor.Black, UIControlState.Normal); indicatorTypeTextButton.TouchUpInside += delegate { indicatorTypePicker.Hidden = false; doneButton.Hidden = false; this.BecomeFirstResponder(); }; indicatorTypeTextButton.BackgroundColor = UIColor.Clear; indicatorTypeTextButton.Layer.BorderWidth = 2.0f; indicatorTypeTextButton.Layer.BorderColor = UIColor.FromRGB(240.0f / 255.0f, 240.0f / 255.0f, 240.0f / 255.0f).CGColor; indicatorTypeTextButton.Layer.CornerRadius = 8.0f; this.AddSubview(indicatorTypeTextButton); indicatorTypePicker.ShowSelectionIndicator = true; indicatorTypePicker.Hidden = true; indicatorTypePicker.Model = new StatusPickerViewModel(chart, indicatorTypeTextButton, indicator, indicatorCollection); indicatorTypePicker.BackgroundColor = UIColor.FromRGB(240f / 255.0f, 240f / 255.0f, 240f / 255.0f); indicatorTypePicker.SelectedRowInComponent(0); this.AddSubview(indicatorTypePicker); doneButton.SetTitle("Done" + "\t", UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.TouchUpInside += delegate { indicatorTypePicker.Hidden = true; doneButton.Hidden = true; this.BecomeFirstResponder(); }; doneButton.BackgroundColor = UIColor.FromRGB(240f / 255.0f, 240f / 255.0f, 240f / 255.0f); doneButton.Hidden = true; this.AddSubview(doneButton); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } public override void LayoutSubviews() { base.LayoutSubviews(); chart.Frame = new CGRect(this.Bounds.X, this.Bounds.Y + 40, this.Bounds.Width, this.Bounds.Height - 40); indicatorTypeTextButton.Frame = new CGRect(10, Bounds.Y, Frame.Size.Width - 20, 40); if (Utility.IsIpad) { doneButton.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 253, Frame.Size.Width, 35); indicatorTypePicker.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 260, Frame.Size.Width, 260); } else { doneButton.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 143, Frame.Size.Width, 35); indicatorTypePicker.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 150, Frame.Size.Width, 150); } } } public class StatusPickerViewModel : UIPickerViewModel { UIButton indicatorTypeTextButton; SFChart chart; SFTechnicalIndicator indicator; NSMutableArray indicatorCollection; public StatusPickerViewModel(SFChart chart1, UIButton indicatorButton, SFTechnicalIndicator indicator1, NSMutableArray collection) { indicatorTypeTextButton = indicatorButton; chart = chart1; indicator = indicator1; indicatorCollection = collection; } private readonly IList<string> colors = new List<string> { "AD Indicator", "ATR Indicator", "BB Indicator", "EMA Indicator", "MACD Indicator", "Momentum Indicator", "RSI Indicator", "SMA Indicator", "Stochastic Indicator", "TMA Indicator" }; public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return (nint)colors.Count; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return colors[(int)row]; } public override void Selected(UIPickerView pickerView, nint row, nint component) { indicatorTypeTextButton.SetTitle(colors[(int)row], UIControlState.Normal); indicatorCollection.RemoveAllObjects(); chart.TechnicalIndicators.RemoveAt(0); if (row == 0) indicator = new SFADIndicator(); else if (row == 1) indicator = new SFATRIndicator(); else if (row == 2) indicator = new SFBBIndicator(); else if (row == 3) indicator = new SFEMAIndicator(); else if (row == 4) indicator = new SFMACDIndicator(); else if (row == 5) indicator = new SFMomentumIndicator(); else if (row == 6) indicator = new SFRSIIndicator(); else if (row == 7) indicator = new SFSMAIndicator(); else if (row == 8) indicator = new SFStochasticIndicator(); else if (row == 9) indicator = new SFTMAIndicator(); indicator.SeriesName = new NSString("Hi-Low"); indicator.XBindingPath = "XValue"; indicator.High = "High"; indicator.Low = "Low"; indicator.Open = "Open"; indicator.Close = "Close"; SFNumericalAxis axis = new SFNumericalAxis(); axis.OpposedPosition = true; axis.ShowMajorGridLines = false; indicator.YAxis = axis; indicatorCollection = new NSMutableArray(); indicatorCollection.Add(indicator); chart.TechnicalIndicators.Add(indicator); } } } <file_sep>/Forms/DataGrid/DataGrid.UWP/MainPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "MainPage.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1649:FileHeaderFileNameDocumentationMustMatchTypeName", Justification = "Reviewed.")] namespace SampleBrowser.SfDataGrid.UWP { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; /// <summary> /// This is the main entry point of the application while launching in UWP platform. /// </summary> public sealed partial class MainPage { /// <summary> /// Initializes a new instance of the MainPage class. /// </summary> public MainPage() { this.InitializeComponent(); LoadApplication(new SampleBrowser.SfDataGrid.App()); } } } <file_sep>/Forms/Carousel/Carousel/Samples/Carousel_View/Carousel_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Xamarin.Forms; using Syncfusion.SfCarousel.XForms; using System.Collections.ObjectModel; using SampleBrowser.Core; namespace SampleBrowser.SfCarousel { /// <summary> /// Carousel default. /// </summary> public partial class Carousel_Default : SampleView { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.SfCarousel.Carousel_Default"/> class. /// </summary> public Carousel_Default() { InitializeComponent(); viewmodePicker.SelectedIndex = 0; carousel.BindingContext = new CarouselViewModel(); DeviceChanges(); } #endregion #region device changes /// <summary> /// Devices the changes. /// </summary> private void DeviceChanges() { if (Device.RuntimePlatform == Device.iOS) { carousel.ItemHeight = 200; carousel.ItemWidth = 150; optionLayout.Padding = new Thickness(0, 0, 10, 0); } if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { carousel.ItemHeight = (int)Core.SampleBrowser.ScreenHeight / 2; carousel.ItemWidth = (int)Core.SampleBrowser.ScreenWidth / 2; carousel.HeightRequest = 400; carousel.WidthRequest = 800; carouselLayout.Padding = new Thickness(0, 40, 0, 0); } if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { carousel.SelectedItemOffset = 160; carousel.HeightRequest = 600; carousel.WidthRequest = 800; carousel.HorizontalOptions = LayoutOptions.CenterAndExpand; carouselLayout.Padding = new Thickness(0, 80, 0, 0); } if (Device.RuntimePlatform == Device.UWP) { carousel.ScaleOffset = 0.5f; } if (Device.RuntimePlatform == Device.Android) { carousel.ItemHeight = Convert.ToInt32(250); carousel.ItemWidth = Convert.ToInt32(180); carouselLayout.Padding = new Thickness(0, 60, 0, 0); carousel.ScaleOffset = (float)0.70; } } #endregion #region Options /// <summary> /// Offsets the value changed. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void OffsetValueChanged(object sender, Syncfusion.SfNumericUpDown.XForms.ValueEventArgs e) { Decimal temp = Convert.ToDecimal(offset.Value); float offsetvalue = (float)temp; carousel.Offset = offsetvalue; } /// <summary> /// Handles the value event handler. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void HandleValueEventHandler(object sender, Syncfusion.SfNumericUpDown.XForms.ValueEventArgs e) { Decimal tempvalue = Convert.ToDecimal(scale.Value); float scalevalue = (float)tempvalue; if (scalevalue <= 1) { carousel.ScaleOffset = scalevalue; } else { carousel.ScaleOffset = 1.0f; } } /// <summary> /// Handles the value event handler1. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void HandleValueEventHandler1(object sender, Syncfusion.SfNumericUpDown.XForms.ValueEventArgs e) { Decimal temp = Convert.ToDecimal(rotateangle.Value); int rotationangle = (int)temp; if (rotationangle > 0 && rotationangle <= 360) { carousel.RotationAngle = rotationangle; } else { carousel.RotationAngle = 45; } } /// <summary> /// Viewmodes the picker selected index changed. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void viewmodePicker_SelectedIndexChanged(object sender, EventArgs e) { switch (viewmodePicker.SelectedIndex) { case 0: carousel.ViewMode = ViewMode.Default; break; case 1: carousel.ViewMode = ViewMode.Linear; break; } } #endregion #region SampleBrowser view /// <summary> /// Gets the content. /// </summary> /// <returns>The content.</returns> public View getContent() { return this.Content; } #endregion #region Property view /// <summary> /// Gets the property. /// </summary> /// <returns>The property.</returns> public View getProperty() { return this.PropertyView; } #endregion } } <file_sep>/Forms/XlsIO/XlsIO.iOS/PreviewControllerDS.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="PreviewControllerDS.cs" company=" Syncfusion Inc."> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> #endregion namespace SampleBrowser.XlsIO.IOS { using System; using QuickLook; /// <summary> /// This class used the specialized view for previewing an item using DataSource. /// </summary> public class PreviewControllerDS : QLPreviewControllerDataSource { /// <summary> /// Contains the value of <see cref="QLPreviewItem"/> class. /// </summary> private QLPreviewItem item; /// <summary> /// Initializes a new instance of the <see cref="PreviewControllerDS" /> class. /// </summary> /// <param name="ql_Item">The value of item parameter from <see cref="QLPreviewItem"/> class.</param> public PreviewControllerDS(QLPreviewItem ql_Item) { this.item = ql_Item; } /// <summary> /// Override the PreviewItemCount method with <see cref="nint"/>. /// </summary> /// <param name="controller">The value of controller parameter from <see cref="QLPreviewController"/> class.</param> /// <returns>return the value 1.</returns> public override nint PreviewItemCount(QLPreviewController controller) { return (nint)1; } /// <summary> /// Override the GetPreviewItem method with <see cref="IQLPreviewItem"/> interface. /// </summary> /// <param name="controller">The value of controller parameter from <see cref="QLPreviewController"/> class.</param> /// <param name="index">The value of an index.</param> /// <returns>return the _item field.</returns> public override IQLPreviewItem GetPreviewItem(QLPreviewController controller, nint index) { return this.item; } } }<file_sep>/Forms/Chart/Chart/Samples/SplineRangeAreaChart/SplineRangeAreaSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser.SfChart { public class SplineRangeAreaSeriesViewModel { public ObservableCollection<Person> SplineRangeAreaData { get; set; } public ObservableCollection<Person> SplineRangeAreaData1 { get; set; } public SplineRangeAreaSeriesViewModel() { SplineRangeAreaData = new ObservableCollection<Person> { new Person("Jan", 45, 32), new Person("Feb", 48, 34), new Person("Mar", 46, 32), new Person("Apr", 48, 36), new Person("May", 46, 32), new Person("Jun", 49, 34) }; SplineRangeAreaData1 = new ObservableCollection<Person> { new Person("Jan", 30, 18), new Person("Feb", 24, 12), new Person("Mar", 29, 15), new Person("Apr", 24, 10), new Person("May", 30, 18), new Person("Jun", 24, 10) }; } public class Person { public string Name { get; set; } public double High { get; set; } public double Low { get; set; } public Person(string name, double high, double low) { Name = name; High = high; Low = low; } } } } <file_sep>/Forms/RadioButton/readme.md The radio button is a selection control that allows users to select one option from a set. The two states of radio button are checked and unchecked. | Sample | Description | | ------ | ----------- | | [Online payment mode](RadioButton/Samples/RadioButton) |This sample demonstrates how to select the payment transfer mode using radio buttons group.|<file_sep>/Forms/Calendar/Calendar/Samples/CalendarCustomization/ViewModel/CalendarCustomizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.ComponentModel; using Syncfusion.SfCalendar.XForms; using Xamarin.Forms; namespace SampleBrowser.SfCalendar { public class CalendarCustomizationViewModel : INotifyPropertyChanged { Random random = new Random(); public bool IsCurrentMonth { get; set; } public string Title { get; set; } public string Temperature { get; set; } public string Wind { get; set; } public string Humidity { get; set; } public DateTime Date { get; set; } private double celcius; public double Celcius { get { return celcius; } set { celcius = value; OnPropertyChanged("Celcius"); } } private string image; public event PropertyChangedEventHandler PropertyChanged; public string Image { get { return image; } set { image = value; OnPropertyChanged("Image"); } } public CalendarCustomizationViewModel(bool iscurrentmonth, DateTime date) { IsCurrentMonth = iscurrentmonth; this.Date = date; this.Title = " "; this.Temperature = " "; this.Wind = " "; this.Humidity = " "; if (IsCurrentMonth) { UpdateCelcius(); } } private void UpdateCelcius() { if (this.Date.Day % 5 == 0) { this.Celcius = 50; } else if (this.Date.Day % 3 == 0) { this.Celcius = 80; } else { this.Celcius = 120; } if (Celcius > 10 && Celcius < 60) { this.Image = "RainyWeather.png"; } else if (Celcius > 60 && Celcius < 100) { this.Image = "CloudSunny.png"; } else { this.Image = "Sunny.png"; } } private void OnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/PullToRefreshView/PullToRefreshViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PullToRefreshViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A ViewModel for PullToRefresh sample. /// </summary> public class PullToRefreshViewModel : INotifyPropertyChanged { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private readonly Random randomNumber = new Random(); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private readonly string[] selectedtemperatures = { "Humid", "Rainy", "Cloudy", "Wind", "Warm" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private readonly string[] temperatures = { "Humid", "Rainy", "Cloudy", "WindUnselected", "Warm" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private WeatherData data; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<WeatherData> selectedData; /// <summary> /// Initializes a new instance of the PullToRefreshViewModel class. /// </summary> public PullToRefreshViewModel() { this.SelectedData = this.GetWeatherData(); this.Data = this.SelectedData[0]; } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the value of Selected Data and notifies user when collection value gets changed. /// </summary> public ObservableCollection<WeatherData> SelectedData { get { return this.selectedData; } set { this.selectedData = value; this.RaisePropertyChanged("SelectedData"); } } /// <summary> /// Gets or sets the value of Data and notifies user when collection value gets changed. /// </summary> public WeatherData Data { get { return this.data; } set { this.data = value; this.RaisePropertyChanged("Data"); } } /// <summary> /// Generates weather data values /// </summary> /// <returns>data value</returns> private ObservableCollection<WeatherData> GetWeatherData() { DateTime now = DateTime.Now; ObservableCollection<WeatherData> array = new ObservableCollection<WeatherData>(); for (int i = 0; i < 7; i++) { WeatherData data = this.GetData(now.AddDays(i)); data.Type = this.temperatures[i % this.temperatures.Length] + ".png"; data.SelectedType = this.selectedtemperatures[i % this.temperatures.Length] + "Selected.png"; array.Add(data); } return array; } /// <summary> /// Generates date time /// </summary> /// <param name="date">Date Time value parameter named date</param> /// <returns>date time value</returns> private WeatherData GetData(DateTime date) { string month; DateTime now = DateTime.Now; month = string.Empty + now.DayOfWeek + ", " + string.Empty + now.ToString("MMMM") + " " + now.Date.Day; return new WeatherData(date.ToString("dddd"), month, this.randomNumber.Next(20, 50), string.Empty, string.Empty); } #region INotifyPropertyChanged /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name represent propertyName</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/iOS/SampleBrowser/Controllers/SampleView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using UIKit; namespace SampleBrowser { public class SampleView : UIView { #region ctor public SampleView() { } #endregion #region properties public UIView OptionView { get; set; } public static CGSize PopoverSize { get { return new CGSize(320.0, 400.0); } } public UINavigationController NavigationController { get; set; } #endregion #region methods public virtual void OnOptionsViewClosed() { } public virtual void ViewWillAppear() { } public virtual void ViewWillDisappear() { } #endregion } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Grouping/GroupingBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GroupingBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Grouping samples /// </summary> public class GroupingBehaviors : Behavior<Syncfusion.SfDataGrid.XForms.SfDataGrid> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">DataGrid type of parameter bindAble</param> protected override void OnAttachedTo(Syncfusion.SfDataGrid.XForms.SfDataGrid bindAble) { this.dataGrid = bindAble; if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Desktop) { this.dataGrid.Columns.ForEach(column => column.MaximumWidth = 500); } this.dataGrid.CellRenderers.Remove("CaptionSummary"); this.dataGrid.CellRenderers.Add("CaptionSummary", new GroupCaptionRenderer()); this.dataGrid.CellRenderers.Remove("TableSummary"); this.dataGrid.CellRenderers.Add("TableSummary", new TableSummaryRenderer()); base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">DataGrid type of parameter bindAble</param> protected override void OnDetachingFrom(Syncfusion.SfDataGrid.XForms.SfDataGrid bindAble) { this.dataGrid.Columns.ForEach(column => column.MaximumWidth = 500); this.dataGrid = null; base.OnDetachingFrom(bindAble); } } } <file_sep>/Forms/ListView/ListView/Samples/Selection/Helper/Behaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DataSource; using Syncfusion.ListView.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.Core; using Xamarin.Forms.Internals; using SelectionMode = Syncfusion.ListView.XForms.SelectionMode; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] #region SelectionBehavior public class SfListViewSelectionBehavior : Behavior<SampleView> { #region Fields private Syncfusion.ListView.XForms.SfListView ListView; private Grid selectionCancelImageParent; private Grid selectionEditImageParent; private ListViewSelectionViewModel SelectionViewModel; private Grid headerGrid; #endregion #region Overrides protected override void OnAttachedTo(SampleView bindable) { ListView = bindable.FindByName<Syncfusion.ListView.XForms.SfListView>("listView"); ListView.ItemHolding += ListView_ItemHolding; ListView.SelectionChanged += ListView_SelectionChanged; if (Device.RuntimePlatform == Device.UWP) ListView.FocusBorderThickness = new Thickness(1, 1, 1, 2); SelectionViewModel = new ListViewSelectionViewModel(); ListView.BindingContext = SelectionViewModel; ListView.ItemsSource = SelectionViewModel.MusicInfo; headerGrid = bindable.FindByName<Grid>("headerGrid"); headerGrid.BindingContext = SelectionViewModel; selectionCancelImageParent = bindable.FindByName<Grid>("cancelImageParent"); var selectionCancelImageTapped = new TapGestureRecognizer() { Command=new Command(selectionCancelImageTapped_Tapped) } ; selectionCancelImageParent.GestureRecognizers.Add(selectionCancelImageTapped); selectionEditImageParent = bindable.FindByName<Grid>("editImageParent"); var selectionEditImageTapped = new TapGestureRecognizer() { Command = new Command(SelectionEditImageTapped_Tapped) }; selectionEditImageParent.GestureRecognizers.Add(selectionEditImageTapped); base.OnAttachedTo(bindable); } protected override void OnDetachingFrom(SampleView bindable) { ListView.ItemHolding -= ListView_ItemHolding; ListView.SelectionChanged -= ListView_SelectionChanged; ListView = null; selectionCancelImageParent = null; selectionEditImageParent = null; SelectionViewModel = null; headerGrid = null; base.OnDetachingFrom(bindable); } #endregion #region Events private void ListView_SelectionChanged(object sender, ItemSelectionChangedEventArgs e) { if (ListView.SelectionMode == SelectionMode.Multiple) { SelectionViewModel.HeaderInfo = ListView.SelectedItems.Count + " selected"; for (int i = 0; i < e.AddedItems.Count; i++) { var item = e.AddedItems[i]; (item as Musiqnfo).IsSelected = true; } for (int i = 0; i < e.RemovedItems.Count; i++) { var item = e.RemovedItems[i]; (item as Musiqnfo).IsSelected = false; } } } private void SelectionEditImageTapped_Tapped() { UpdateSelectionTempate(); } private void selectionCancelImageTapped_Tapped() { for (int i = 0; i < ListView.SelectedItems.Count; i++) { var item = ListView.SelectedItems[i] as Musiqnfo; item.IsSelected = false; } this.ListView.SelectedItems.Clear(); UpdateSelectionTempate(); } private void ListView_ItemHolding(object sender, ItemHoldingEventArgs e) { if (ListView.SelectionMode != SelectionMode.Multiple) UpdateSelectionTempate(); } #endregion #region Methods public void UpdateSelectionTempate() { if (ListView.SelectedItems.Count > 0 || selectionEditImageParent.IsVisible) { ListView.SelectionMode = SelectionMode.Multiple; ListView.SelectionBackgroundColor = Color.Transparent; ListView.SelectedItems.Clear(); SelectionViewModel.HeaderInfo = ListView.SelectedItems.Count + " selected"; SelectionViewModel.TitleInfo = ""; SelectionViewModel.IsVisible = true; selectionEditImageParent.IsVisible = false; } else { ListView.SelectionMode = SelectionMode.Single; ListView.SelectionBackgroundColor = Color.FromRgb(228, 228, 228); SelectionViewModel.HeaderInfo = ""; SelectionViewModel.TitleInfo = "Music Library"; SelectionViewModel.IsVisible = false; selectionEditImageParent.IsVisible = true; } } #endregion } #endregion } <file_sep>/Forms/DataSource/DataSource/Samples/DataSourceGrouping/Model/Contacts.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Xamarin.Forms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using Xamarin.Forms.Internals; namespace SampleBrowser.DataSource { [Preserve(AllMembers = true)] public class Contacts : INotifyPropertyChanged { private string contactName; private string contactNumber; private string displayString; private Color color; public Contacts(string name, string number) { contactName = name; contactNumber = number; displayString = name[0].ToString(); } public string ContactName { get { return contactName; } set { if (contactName != value) { contactName = value; this.RaisedOnPropertyChanged("ContactName"); } } } public string ContactNumber { get { return contactNumber; } set { if (contactNumber != value) { contactNumber = value; this.RaisedOnPropertyChanged("ContactNumber"); } } } public string DisplayString { get { return displayString; } set { if (displayString != value) { displayString = value; this.RaisedOnPropertyChanged("DisplayString"); } } } public Color ContactColor { get { return color; } set { if (color != value) { color = value; this.RaisedOnPropertyChanged("ContactColor"); } } } public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/Category.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif using System.Drawing; namespace SampleBrowser { public class CategoryAxis : SampleView { public CategoryAxis () { SFChart chart = new SFChart (); chart.Title.Text = new NSString("Internet Users - 2016"); SFCategoryAxis categoryAxis = new SFCategoryAxis (); categoryAxis.LabelPlacement = SFChartLabelPlacement.BetweenTicks; categoryAxis.ShowMajorGridLines = false; chart.PrimaryAxis = categoryAxis; chart.PrimaryAxis.Interval = new NSNumber(1); chart.PrimaryAxis.Title.Text = new NSString ("Country"); chart.PrimaryAxis.LabelStyle.WrappedLabelAlignment = ChartAxisLabelAlignment.Center; chart.PrimaryAxis.LabelStyle.MaxWidth = 35; chart.PrimaryAxis.LabelStyle.Color = UIColor.Black; chart.SecondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis.Minimum = new NSNumber(0); chart.SecondaryAxis.Maximum = new NSNumber(75); chart.SecondaryAxis.Interval = new NSNumber(10); chart.SecondaryAxis.Visible = false; chart.SecondaryAxis.ShowMajorGridLines = false; chart.SecondaryAxis.ShowMinorGridLines = false; chart.Delegate = new DataMarkerFormatter(); ChartViewModel dataModel = new ChartViewModel (); SFColumnSeries series = new SFColumnSeries(); series.ItemsSource = dataModel.CategoryData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.EnableAnimation = true; series.ColorModel.Palette = SFChartColorPalette.Natural; series.DataMarker.ShowLabel = true; series.DataMarker.LabelStyle.LabelPosition = SFChartDataMarkerLabelPosition.Outer; series.DataMarker.LabelStyle.Font = UIFont.SystemFontOfSize(12f); chart.Series.Add(series); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } class DataMarkerFormatter : SFChartDelegate { public override NSString GetFormattedDataMarkerLabel(SFChart chart, NSString label, nint index) { String formattedLabel = label + "M"; label = new NSString(formattedLabel); return label; } } } }<file_sep>/Android/SampleBrowser/Samples/Maps/Models/PopulationMarker.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Com.Syncfusion.Maps; using Android.Graphics; using Android.Views; using Android.Widget; namespace SampleBrowser { public class PopulationMarker : MapMarker { public PopulationMarker (Android.Content.Context con) { context = con; } Android.Content.Context context; public string Name { get; set; } public string Population { get; set; } } public class MarkerAdapter : Com.Syncfusion.Maps.MapsAdapter { Android.Content.Context context; public MarkerAdapter(Android.Content.Context con) { context = con; } public override View GetMarkerView(MapMarker marker, PointF point) { LinearLayout layout = new LinearLayout(context); ImageView imageView = new ImageView(context); imageView.SetImageResource(Resource.Drawable.pin); float density = context.Resources.DisplayMetrics.Density; int layoutWidth = (int)(15 * density); int layoutHeight = (int)(40 * density); int imageHeight = (int)(20 * density); var layoutParams = new LinearLayout.LayoutParams(layoutWidth , layoutHeight); layout.Orientation = Orientation.Vertical; layout.SetMinimumHeight(layoutHeight); layout.SetMinimumWidth(layoutWidth); layout.LayoutParameters = layoutParams; var imageViewParams = new LinearLayout.LayoutParams(layoutWidth, imageHeight); imageView.LayoutParameters = imageViewParams; imageView.SetMinimumHeight(imageHeight); imageView.SetMinimumWidth(layoutWidth); layout.AddView(imageView); return layout; } } }<file_sep>/Android/SampleBrowser/Samples/Maps/ColorMappings.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Com.Syncfusion.Maps; using Org.Json; using System.Collections.Generic; using Android.Graphics; using Android.Widget; using Android.OS; using Com.Syncfusion.Sfbusyindicator; using Com.Syncfusion.Sfbusyindicator.Enums; using Android.Content; using Android.Views; namespace SampleBrowser { public class ColorMappings : SamplePage { SfMaps maps; Handler handler; public override Android.Views.View GetSampleContent (Android.Content.Context context) { handler = new Handler(); LinearLayout layout = new LinearLayout(context); TextView textView = new TextView(context); textView.TextSize = 16; textView.SetPadding(10, 20, 0, 0); textView.SetHeight(90); textView.Text = "Primary Agricultural Activity of USA"; layout.AddView(textView); textView.Gravity = Android.Views.GravityFlags.Top; layout.Orientation = Orientation.Vertical; maps = new SfMaps (context); ShapeFileLayer layer = new ShapeFileLayer(); layer.Uri ="usa_state.shp"; layer.ShapeIdTableField ="STATE_NAME"; layer.ShapeIdPath ="Name"; layer.DataSource = GetDataSource (); layer.ShapeSettings.ShapeColorValuePath = "Type"; layer.ShapeSettings.ShapeFill = Color.ParseColor("#A9D9F7"); SetColorMapping(layer.ShapeSettings); LayerCustomTooltipSetting layerCustomTooltip = new LayerCustomTooltipSetting(context); layerCustomTooltip.ShowTooltip = true; layer.TooltipSettings = layerCustomTooltip; layer.LegendSetting = new LegendSetting (){ ShowLegend = true, ItemMargin = 0 }; maps.Layers.Add (layer); SfBusyIndicator sfBusyIndicator = new SfBusyIndicator(context); sfBusyIndicator.IsBusy = true; sfBusyIndicator.AnimationType = AnimationTypes.SlicedCircle; sfBusyIndicator.ViewBoxWidth = 50; sfBusyIndicator.ViewBoxHeight = 50; sfBusyIndicator.TextColor = Color.ParseColor("#779772"); layout.AddView(sfBusyIndicator); Java.Lang.Runnable run = new Java.Lang.Runnable(() => { layout.RemoveView(sfBusyIndicator); layout.AddView(maps); }); handler.PostDelayed(run, 100); return layout; } JSONArray GetDataSource() { JSONArray array = new JSONArray (); array.Put(getJsonObject("Alabama", "Vegetables", 9 )); array.Put(getJsonObject( "Alaska", "Vegetables", 3 )); array.Put(getJsonObject( "Arizona", "Rice", 11 )); array.Put(getJsonObject( "Arkansas", "Vegetables", 6 )); array.Put(getJsonObject( "California", "Rice", 55 )); array.Put(getJsonObject( "Colorado", "Rice", 9 )); array.Put(getJsonObject( "Connecticut", "Grains", 7 )); array.Put(getJsonObject( "Delaware", "Grains", 3 )); array.Put(getJsonObject( "District of Columbia", "Grains", 3 )); array.Put(getJsonObject( "Florida", "Rice", 29 )); array.Put(getJsonObject( "Georgia", "Rice", 16 )); array.Put(getJsonObject( "Hawaii", "Grains", 4 )); array.Put(getJsonObject( "Idaho", "Grains", 4 )); array.Put(getJsonObject( "Illinois", "Vegetables", 20 )); array.Put(getJsonObject( "Indiana", "Grains", 11 )); array.Put(getJsonObject( "Iowa", "Vegetables", 6 )); array.Put(getJsonObject( "Kansas", "Rice", 6 )); array.Put(getJsonObject( "Kentucky", "Grains", 8 )); array.Put(getJsonObject( "Louisiana", "Rice", 8 )); array.Put(getJsonObject( "Maine", "Grains", 4 )); array.Put(getJsonObject( "Maryland", "Grains", 10 )); array.Put(getJsonObject( "Massachusetts", "Grains", 11 )); array.Put(getJsonObject( "Michigan", "Grains", 16 )); array.Put(getJsonObject( "Minnesota", "Wheat", 10 )); array.Put(getJsonObject( "Mississippi", "Vegetables", 6 )); array.Put(getJsonObject( "Missouri", "Vegetables", 10 )); array.Put(getJsonObject( "Montana", "Grains", 3 )); array.Put(getJsonObject( "Nebraska", "Rice", 5 )); array.Put(getJsonObject( "Nevada", "Wheat", 6 )); array.Put(getJsonObject( "New Hampshire", "Grains", 4 )); array.Put(getJsonObject( "New Jersey", "Vegetables", 14 )); array.Put(getJsonObject( "New Mexico", "Rice", 5 )); array.Put(getJsonObject( "New York", "Vegetables", 29 )); array.Put(getJsonObject( "North Carolina", "Rice", 15 )); array.Put(getJsonObject( "North Dakota", "Grains", 3 )); array.Put(getJsonObject( "Ohio", "Vegetables", 18 )); array.Put(getJsonObject( "Oklahoma", "Rice", 7 )); array.Put(getJsonObject( "Oregon", "Wheat", 7 )); array.Put(getJsonObject( "Pennsylvania", "Vegetables", 20 )); array.Put(getJsonObject( "Rhode Island", "Grains", 4 )); array.Put(getJsonObject( "South Carolina", "Rice", 9 )); array.Put(getJsonObject( "South Dakota", "Grains", 3 )); array.Put(getJsonObject( "Tennessee", "Vegetables", 11 )); array.Put(getJsonObject( "Texas", "Vegetables", 38 )); array.Put(getJsonObject( "Utah", "Rice", 6 )); array.Put(getJsonObject( "Vermont", "Grains", 3 )); array.Put(getJsonObject( "Virginia", "Rice", 13 )); array.Put(getJsonObject( "Washington", "Vegetables", 12 )); array.Put(getJsonObject( "West Virginia", "Grains", 5 )); array.Put(getJsonObject( "Wisconsin", "Grains", 10 )); array.Put(getJsonObject( "Wyoming", "Wheat", 3 )); return array; } JSONObject getJsonObject(String name,String type,double count) { JSONObject obj= new JSONObject(); obj.Put ("Name", name); obj.Put ("Type", type); return obj; } void SetColorMapping(ShapeSetting setting) { List<ColorMapping> colorMappings= new List<ColorMapping>(); EqualColorMapping colorMapping2= new EqualColorMapping(); colorMapping2.Value= "Rice"; colorMapping2.LegendLabel= "Rice"; colorMapping2.Color =Color.ParseColor("#FD8C48"); colorMappings.Add(colorMapping2); EqualColorMapping colorMapping3= new EqualColorMapping(); colorMapping3.Value= "Wheat"; colorMapping3.LegendLabel= "Wheat"; colorMapping3.Color =Color.ParseColor("#E54D42"); colorMappings.Add(colorMapping3); EqualColorMapping colorMapping4= new EqualColorMapping(); colorMapping4.Value= "Grains"; colorMapping4.LegendLabel= "Grains"; colorMapping4.Color =Color.ParseColor("#3A99D9"); colorMappings.Add(colorMapping4); EqualColorMapping colorMapping1= new EqualColorMapping(); colorMapping1.Value= "Vegetables"; colorMapping1.LegendLabel= "Vegetables"; colorMapping1.Color =Color.ParseColor("#29BB9C"); colorMappings.Add(colorMapping1); setting.ColorMapping = colorMappings; } } public class LayerCustomTooltipSetting : TooltipSetting { Context context; public LayerCustomTooltipSetting(Context con) { context = con; } public override View GetView(object shapeData) { LinearLayout layout = new LinearLayout(context); LinearLayout.LayoutParams linearlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layout.Orientation = Orientation.Vertical; layout.LayoutParameters = linearlayoutParams; layout.SetGravity(GravityFlags.Center); TextView topLabel = new TextView(context); topLabel.Text = ((JSONObject)shapeData).GetString("Name"); topLabel.TextSize = 12; topLabel.SetTextColor(Color.ParseColor("#FFFFFF")); topLabel.Gravity = GravityFlags.CenterHorizontal; TextView bottoLabel = new TextView(context); bottoLabel.Text = ((JSONObject)shapeData).GetString("Type"); bottoLabel.TextSize = 12; bottoLabel.SetTextColor(Color.ParseColor("#FFFFFF")); bottoLabel.Gravity = GravityFlags.CenterHorizontal; layout.AddView(topLabel); layout.AddView(bottoLabel); return layout; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/NumericTextBox/NumericTextBox_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfNumericTextBox.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class NumericTextBox_Mobile : SampleView { UIPickerView culturePicker; UILabel titleLabel, descriptionLabel, formulaLabel, principalLabel, interestRateLabel, termLabel, interestLabel, cultureLabel,allowNullLabel; UISwitch allowSwitch; UIButton cultureDoneButton,cultureButton; private string cultureSelectedType; SFNumericTextBox principalNumericTextBox; SFNumericTextBox interestRateNumericTextBox; SFNumericTextBox periodNumericTextBox; SFNumericTextBox outputNumericTextBox; public UIView option = new UIView (); private readonly IList<string> cultureList = new List<string> (); public void optionView() { this.option.AddSubview(allowNullLabel); this.option.AddSubview(allowSwitch); this.option.AddSubview(cultureLabel); this.option.AddSubview (cultureDoneButton); this.option.AddSubview(culturePicker); this.option.AddSubview (cultureButton); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; this.OptionView.Frame = view.Frame; this.option.Frame = new CGRect (0, 70, Frame.Width, Frame.Height); principalNumericTextBox.Frame = new CGRect(200, 120, view.Frame.Width-220, 40); interestRateNumericTextBox.Frame = new CGRect(200, 180, view.Frame.Width-220, 40); periodNumericTextBox.Frame = new CGRect(200, 240, view.Frame.Width-220, 40); outputNumericTextBox.Frame = new CGRect(200, 300, view.Frame.Width-220, 40); titleLabel.Frame =new CGRect(15, 0, this.Frame.Size.Width-20, 50); descriptionLabel.Frame = new CGRect(15, 35, this.Frame.Size.Width-20, 50); formulaLabel.Frame = new CGRect(15, 60, this.Frame.Size.Width-20, 50); principalLabel.Frame = new CGRect(15, 120, this.Frame.Size.Width-20, 50); interestRateLabel.Frame = new CGRect(15, 180, this.Frame.Size.Width-20, 50); termLabel.Frame = new CGRect(15, 240, this.Frame.Size.Width-20, 50); interestLabel.Frame = new CGRect(15, 300, this.Frame.Size.Width-20, 50); cultureLabel.Frame=new CGRect(15, 40, this.Frame.Size.Width-20, 40); cultureButton.Frame=new CGRect(10,80, this.Frame.Size.Width-20, 40); allowNullLabel.Frame=new CGRect(15, 140, this.Frame.Size.Width-20, 40); allowSwitch.Frame=new CGRect(250,140, this.Frame.Size.Width-20, 40); culturePicker.Frame=new CGRect(0,this.Frame.Size.Height/4+20, this.Frame.Size.Width,this.Frame.Size.Height/3); cultureDoneButton.Frame=new CGRect(0, this.Frame.Size.Height/4-20, this.Frame.Size.Width, 40); } this.optionView (); base.LayoutSubviews (); } static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public NumericTextBox_Mobile () { this.OptionView = new UIView (); //cultureList this.cultureList.Add ((NSString)"United States"); this.cultureList.Add ((NSString)"United Kingdom"); this.cultureList.Add ((NSString)"Japan"); this.cultureList.Add ((NSString)"France"); this.cultureList.Add ((NSString)"Italy"); //principalNumericTextBox principalNumericTextBox= new SFNumericTextBox(); principalNumericTextBox.Watermark = "Enter Principal"; principalNumericTextBox.AllowNull = true; principalNumericTextBox.MaximumNumberDecimalDigits = 2; principalNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; principalNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnLostFocus; principalNumericTextBox.FormatString = "c"; principalNumericTextBox.Value = 1000; principalNumericTextBox.CultureInfo = new NSLocale ("en_US"); principalNumericTextBox.NumericTextBoxDelegate = new NumericTextBoxMobileDelegate(); this.AddSubview(principalNumericTextBox); //interestRateNumericTextBox interestRateNumericTextBox= new SFNumericTextBox(); interestRateNumericTextBox.Watermark = "Enter RI"; interestRateNumericTextBox.AllowNull = true; interestRateNumericTextBox.MaximumNumberDecimalDigits = 0; interestRateNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; interestRateNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnLostFocus; interestRateNumericTextBox.FormatString = @"p"; interestRateNumericTextBox.Value = 1f; interestRateNumericTextBox.CultureInfo = new NSLocale ("en_US"); interestRateNumericTextBox.NumericTextBoxDelegate = new NumericTextBoxMobileDelegate(); this.AddSubview(interestRateNumericTextBox); //periodNumericTextBox periodNumericTextBox= new SFNumericTextBox(); periodNumericTextBox.Watermark = @"Enter Years"; periodNumericTextBox.AllowNull = true; periodNumericTextBox.MaximumNumberDecimalDigits = 0; periodNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; periodNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnLostFocus; periodNumericTextBox.FormatString = @"years"; periodNumericTextBox.Value = 20; periodNumericTextBox.CultureInfo = new NSLocale ("en_US"); periodNumericTextBox.NumericTextBoxDelegate = new NumericTextBoxMobileDelegate(); this.AddSubview(periodNumericTextBox); //outputNumericTextBox outputNumericTextBox= new SFNumericTextBox(); outputNumericTextBox.Watermark = @"Enter a number"; outputNumericTextBox.AllowNull = true; outputNumericTextBox.MaximumNumberDecimalDigits = 0; outputNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; outputNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnLostFocus; outputNumericTextBox.FormatString = @"c"; outputNumericTextBox.Value = 2000; outputNumericTextBox.Enabled = false; outputNumericTextBox.TextColor = UIColor.Gray; outputNumericTextBox.CultureInfo = new NSLocale ("en_US"); outputNumericTextBox.NumericTextBoxDelegate = new NumericTextBoxMobileDelegate(); this.AddSubview(outputNumericTextBox); mainPageDesign(); } public void mainPageDesign() { //titleLabell titleLabel = new UILabel(); titleLabel.TextColor = UIColor.Black; titleLabel.BackgroundColor = UIColor.Clear; titleLabel.Text = @"Simple Interest Calculator"; titleLabel.TextAlignment = UITextAlignment.Left; titleLabel.Font = UIFont.FromName("Helvetica", 20f); this.AddSubview(titleLabel); //descriptionLabell descriptionLabel = new UILabel(); descriptionLabel.TextColor = UIColor.Black; descriptionLabel.BackgroundColor = UIColor.Clear; descriptionLabel.Text = @"The formula for finding simple interest is:"; descriptionLabel.TextAlignment = UITextAlignment.Left; descriptionLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(descriptionLabel); //formulaLabell formulaLabel = new UILabel(); formulaLabel.TextColor = UIColor.Black; formulaLabel.BackgroundColor = UIColor.Clear; formulaLabel.Text = @"Interest = Principal * Rate * Time"; formulaLabel.TextAlignment = UITextAlignment.Left; formulaLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(formulaLabel); //principalLabell principalLabel = new UILabel(); principalLabel.TextColor = UIColor.Black; principalLabel.BackgroundColor = UIColor.Clear; principalLabel.Text = @"Principal"; principalLabel.TextAlignment = UITextAlignment.Left; principalLabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(principalLabel); //interestRateLabell interestRateLabel = new UILabel(); interestRateLabel.TextColor = UIColor.Black; interestRateLabel.BackgroundColor = UIColor.Clear; interestRateLabel.Text = @"Interest Rate"; interestRateLabel.TextAlignment = UITextAlignment.Left; interestRateLabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(interestRateLabel); //termLabell termLabel = new UILabel(); termLabel.TextColor = UIColor.Black; termLabel.BackgroundColor = UIColor.Clear; termLabel.Text = @"Term"; termLabel.TextAlignment = UITextAlignment.Left; termLabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(termLabel); //interestLabell interestLabel = new UILabel(); interestLabel.TextColor = UIColor.Black; interestLabel.BackgroundColor = UIColor.Clear; interestLabel.Text = @"Interest"; interestLabel.TextAlignment = UITextAlignment.Left; interestLabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(interestLabel); //allowNullLabell allowNullLabel = new UILabel(); allowNullLabel.TextColor = UIColor.Black; allowNullLabel.BackgroundColor = UIColor.Clear; allowNullLabel.Text = @"Allow Null"; allowNullLabel.TextAlignment = UITextAlignment.Left; allowNullLabel.Font = UIFont.FromName("Helvetica", 16f); //allowSwitchh allowSwitch = new UISwitch(); allowSwitch.ValueChanged += allowNullToggleChanged; allowSwitch.On = true; //cultureLabell cultureLabel = new UILabel(); cultureLabel.TextColor = UIColor.Black; cultureLabel.BackgroundColor = UIColor.Clear; cultureLabel.Text = @"Culture"; cultureLabel.TextAlignment = UITextAlignment.Left; cultureLabel.Font = UIFont.FromName("Helvetica", 16f); // this.OptionView.AddSubview(cultureLabel); //cultureButtonn cultureButton = new UIButton(); cultureButton.SetTitle("United States", UIControlState.Normal); cultureButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; cultureButton.BackgroundColor = UIColor.Clear; cultureButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureButton.Hidden = false; cultureButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; cultureButton.Layer.BorderWidth = 4; cultureButton.Layer.CornerRadius = 8; cultureButton.TouchUpInside += ShowCulturePicker; //culturePickerr PickerModel culturePickermodel = new PickerModel(this.cultureList); culturePickermodel.PickerChanged += (sender, e) => { this.cultureSelectedType = e.SelectedValue; cultureButton.SetTitle(cultureSelectedType, UIControlState.Normal); if (cultureSelectedType == "United States") { principalNumericTextBox.CultureInfo = new NSLocale("en_US"); interestRateNumericTextBox.CultureInfo = new NSLocale("en_US"); periodNumericTextBox.CultureInfo = new NSLocale("en_US"); outputNumericTextBox.CultureInfo = new NSLocale("en_US"); } else if (cultureSelectedType == "United Kingdom") { principalNumericTextBox.CultureInfo = new NSLocale("en_UK"); interestRateNumericTextBox.CultureInfo = new NSLocale("en_UK"); periodNumericTextBox.CultureInfo = new NSLocale("en_UK"); outputNumericTextBox.CultureInfo = new NSLocale("en_UK"); } else if (cultureSelectedType == "Japan") { principalNumericTextBox.CultureInfo = new NSLocale("jp_JP"); interestRateNumericTextBox.CultureInfo = new NSLocale("jp_JP"); periodNumericTextBox.CultureInfo = new NSLocale("jp_JP"); outputNumericTextBox.CultureInfo = new NSLocale("jp_JP"); } else if (cultureSelectedType == "France") { principalNumericTextBox.CultureInfo = new NSLocale("fr_FR"); interestRateNumericTextBox.CultureInfo = new NSLocale("fr_FR"); periodNumericTextBox.CultureInfo = new NSLocale("fr_FR"); outputNumericTextBox.CultureInfo = new NSLocale("fr_FR"); } else if (cultureSelectedType == "Italy") { principalNumericTextBox.CultureInfo = new NSLocale("it_IT"); interestRateNumericTextBox.CultureInfo = new NSLocale("it_IT"); periodNumericTextBox.CultureInfo = new NSLocale("it_IT"); outputNumericTextBox.CultureInfo = new NSLocale("it_IT"); } }; culturePicker = new UIPickerView(); culturePicker.ShowSelectionIndicator = true; culturePicker.Hidden = true; culturePicker.Model = culturePickermodel; culturePicker.BackgroundColor = UIColor.White; //cultureDoneButtonn cultureDoneButton = new UIButton(); cultureDoneButton.SetTitle("Done\t", UIControlState.Normal); cultureDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; cultureDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); cultureDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureDoneButton.Hidden = true; cultureDoneButton.TouchUpInside += HideCulturePicker; this.BackgroundColor = UIColor.White; } public void SetValue() { outputNumericTextBox.Value = principalNumericTextBox.Value * interestRateNumericTextBox.Value * periodNumericTextBox.Value; } void ShowCulturePicker (object sender, EventArgs e) { cultureDoneButton.Hidden = false; culturePicker.Hidden = false; this.BecomeFirstResponder (); } void HideCulturePicker (object sender, EventArgs e) { cultureDoneButton.Hidden = true; culturePicker.Hidden = true; this.BecomeFirstResponder (); } private void allowNullToggleChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { principalNumericTextBox.AllowNull = true; interestRateNumericTextBox.AllowNull = true; periodNumericTextBox.AllowNull = true; outputNumericTextBox.AllowNull = true; } else { principalNumericTextBox.AllowNull = false; interestRateNumericTextBox.AllowNull = false; periodNumericTextBox.AllowNull = false; outputNumericTextBox.AllowNull = false; } } public override void TouchesBegan (NSSet touches, UIEvent evt){ this.EndEditing (true); } } public class NumericTextBoxMobileDelegate:SFNumericTextBoxDelegate { public override void ValueChange (SFNumericTextBox SFNumericTextBox, nfloat value) { (SFNumericTextBox.Superview as NumericTextBox_Mobile).SetValue (); } } } <file_sep>/Forms/TextInputLayout/TextInputLayout/Samples/PaymentView/PaymentViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; using System.Windows.Input; using Xamarin.Forms; namespace SampleBrowser.SfTextInputLayout { public class PaymentViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private Color backgroundColor; public Color BackgroundColor { get { return backgroundColor; } set { backgroundColor = value; NotifyPropertyChanged(); } } private Color focusedColor; public Color FocusedColor { get { return focusedColor; } set { focusedColor = value; NotifyPropertyChanged(); } } private ObservableCollection<Color> colors; public ObservableCollection<Color> Colors { get { return colors; } set { colors = value; } } private bool enableHintAlwaysFloated; public bool EnableHintAlwaysFloated { get { return enableHintAlwaysFloated; } set { enableHintAlwaysFloated = value; NotifyPropertyChanged(); } } private double cornerRadius = 4; public double CornerRadius { get { return cornerRadius; } set { cornerRadius = Math.Round(value); NotifyPropertyChanged(); } } private string name; public string Name { get { return name; } set { name = value; NotifyPropertyChanged(); } } private double amount; public double Amount { get { return amount; } set { amount = value; NotifyPropertyChanged(); } } private string expiredMonth; public string ExpiredMonth { get { return expiredMonth; } set { expiredMonth = value; IsMonthEmpty = false; NotifyPropertyChanged(); } } private string expiredYear; public string ExpiredYear { get { return expiredYear; } set { expiredYear = value; IsYearEmpty = false; NotifyPropertyChanged(); } } private string cVVNumber; public string CVVNumber { get { return cVVNumber; } set { var maxCharLength = 3; if (value.Length > maxCharLength) { cVVNumber = value.Substring(0, maxCharLength); } else { cVVNumber = value; } HasError = false; NotifyPropertyChanged(); } } private List<string> month; public List<string> Month { get { return month; } set { month = value; NotifyPropertyChanged(); } } private List<string> year; public List<string> Year { get { return year; } set { year = value; NotifyPropertyChanged(); } } private bool hasError; public bool HasError { get { return hasError; } set { hasError = value; NotifyPropertyChanged(); } } private bool isMonthEmpty; public bool IsMonthEmpty { get { return isMonthEmpty; } set { isMonthEmpty = value; NotifyPropertyChanged(); } } private bool isYearEmpty; public bool IsYearEmpty { get { return isYearEmpty; } set { isYearEmpty = value; NotifyPropertyChanged(); } } private object cardNumber; public object CardNumber { get { return cardNumber; } set { cardNumber = value; NotifyPropertyChanged(); } } public ICommand PaymentCommand { get; private set; } public PaymentViewModel() { PaymentCommand = new Command<string>(PaymentButtonClicked); colors = new ObservableCollection<Color> { Color.FromUint(0x0A000000), Color.FromHex("#b5cdf4"), Color.FromHex("#fcc7ee") }; Month = new List<string>(); for(int i = 1; i<=12; i++) { if(i <= 9) { Month.Add("0" + i); } else { Month.Add(i.ToString()); } } Year = new List<string>(); for(int i=19; i<=40; i++) { Year.Add(i.ToString()); } } private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// This method will be called whenever payment button is clicked. /// </summary> /// <param name="obj">The object</param> private void PaymentButtonClicked(object obj) { var card = CardNumber as string; if (string.IsNullOrEmpty(CVVNumber) || CVVNumber.Length != 3) { HasError = true; } if(string.IsNullOrEmpty(ExpiredMonth)) { IsMonthEmpty = true; } if(string.IsNullOrEmpty(ExpiredYear)) { IsYearEmpty = true; } if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(card) || string.IsNullOrEmpty(CVVNumber) || string.IsNullOrEmpty(ExpiredMonth) || string.IsNullOrEmpty(ExpiredYear)) { Application.Current.MainPage.DisplayAlert("Alert", "Please fill all the fields", "Ok"); } else { Application.Current.MainPage.DisplayAlert("Success", "Payment done successfully", "Ok"); } } } } <file_sep>/Forms/ComboBox/ComboBox/Samples/GettingStartedSample/ContactsInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfComboBox { [Preserve(AllMembers = true)] public class ContactsInfoRepository { #region Constructor public ContactsInfoRepository() { } #endregion #region Get Size Details public ObservableCollection<string> GetSizeDetails() { ObservableCollection<string> SizeDetails = new ObservableCollection<string>(); for (int i = 0; i < Size.Count(); i++) { SizeDetails.Add(Size[i]); } return SizeDetails; } #endregion #region Get Resolution Details public ObservableCollection<string> GetResolutionDetails() { ObservableCollection<string> ResolutionDetails = new ObservableCollection<string>(); for (int i = 0; i < Resolution.Count(); i++) { ResolutionDetails.Add(Resolution[i] ); } return ResolutionDetails; } #endregion #region Get Orientation Details public ObservableCollection<string> GetOrientationDetails() { ObservableCollection<string> OrinetationDetails = new ObservableCollection<string>(); for (int i = 0; i < Orientation.Count(); i++) { OrinetationDetails.Add(Orientation[i]); } return OrinetationDetails; } #endregion #region Contacts Information string[] Size = new string[] { "100%", "125%", "150% (Recommended)", "175%", }; string[] Resolution = new string[] { "1920 x 1080 (Recommended)", "1680 x 1050", "1600 x 900", "1440 x 900", "1400 x 1050", "1366 x 768", "1360 x 768", "1280 x 1024", "1280 x 960", "1280 x 720", "854 x 480", "800 x 480", "480 X 640", "480 x 320", "432 x 240", "360 X 640", "320 x 240", }; string[] Orientation = new string[] { "Landscape", "Portrait", "Landscape (flipped)", "Portrait (flipped)", }; #endregion } } <file_sep>/Forms/PdfViewer/PdfViewer.iOS/Renderer/SfFontButtonRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Xamarin.Forms.Platform.iOS; using Xamarin.Forms; using UIKit; using SampleBrowser.SfPdfViewer; using SampleBrowser.SfPdfViewer.iOS; [assembly: ExportRenderer(typeof(SfFontButton), typeof(SfFontButtonRenderer))] namespace SampleBrowser.SfPdfViewer.iOS { public class SfFontButtonRenderer : ButtonRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Button> e) { base.OnElementChanged(e); double? fontSize = e.NewElement?.FontSize; if(fontSize==null || e.NewElement.FontFamily==null) { return; } UIFont font = UIFont.FromName(e.NewElement.FontFamily, (int)fontSize); Control.Font = font; } protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName.Equals("Text")) { Label label = sender as Label; UIFont font = UIFont.FromName("Final_PDFViewer_IOS_FontUpdate", 50); if ((Element as SfFontButton).ButtonName == "viewModeButton") Control.Font = UIFont.FromName(Element.FontFamily, Control.Font.PointSize); else if ((Element as SfFontButton).ButtonName == "popupIconSelector") return; else if ((Element as SfFontButton).ButtonName == "renameBookmarkButton") return; else if ((Element as SfFontButton).ButtonName == "deleteBookmarkButton") return; else Control.Font = font; Control.Font.WithSize(35); } } } }<file_sep>/Android/SampleBrowser/Samples/Maps/DataMarkers.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Com.Syncfusion.Maps; using Com.Syncfusion.Sfbusyindicator; using Com.Syncfusion.Sfbusyindicator.Enums; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Content; using Android.Views; namespace SampleBrowser { public class DataMarkers : SamplePage { public DataMarkers () { } Handler handler; Android.Content.Context sampleContext; public override Android.Views.View GetSampleContent (Android.Content.Context context) { sampleContext = context; LinearLayout layout= new LinearLayout(context); layout.Orientation = Orientation.Vertical; TextView textView= new TextView(context); textView.TextSize = 16; textView.SetPadding(10,20,0,0); textView.SetHeight(90); handler = new Handler(); textView.Text ="Top Population Countries"; layout.AddView(textView); textView.Gravity = Android.Views.GravityFlags.Top; SfMaps maps = new SfMaps (context); ShapeFileLayer layer = new ShapeFileLayer (); layer.Uri= "world1.shp"; SfBusyIndicator sfBusyIndicator = new SfBusyIndicator(context); sfBusyIndicator.IsBusy = true; sfBusyIndicator.AnimationType = AnimationTypes.SlicedCircle; sfBusyIndicator.ViewBoxWidth = 50; sfBusyIndicator.ViewBoxHeight = 50; sfBusyIndicator.TextColor = Color.ParseColor("#779772"); layout.AddView(sfBusyIndicator); Java.Lang.Runnable run = new Java.Lang.Runnable(() => { layout.RemoveView(sfBusyIndicator); layout.AddView(maps); }); handler.PostDelayed(run,100); PopulationMarker usa= new PopulationMarker(context); usa.Latitude =38.8833; usa.Longitude=-77.0167; usa.Name= "United States"; usa.Population ="321,174,000"; layer.Markers.Add(usa); PopulationMarker brazil= new PopulationMarker(context); brazil.Latitude=-15.7833; brazil.Longitude=-47.8667; brazil.Name = "Brazil"; brazil.Population= "204,436,000"; layer.Markers.Add(brazil); PopulationMarker india= new PopulationMarker(context); india.Latitude=21.0000; india.Longitude=78.0000; india.Name= "India"; india.Population ="1,272,470,000"; layer.Markers.Add(india); PopulationMarker china= new PopulationMarker(context); china.Latitude=35.0000; china.Longitude=103.0000; china.Name = "China"; china.Population = "1,370,320,000"; layer.Markers.Add(china); PopulationMarker indonesia= new PopulationMarker(context); indonesia.Latitude=-6.1750; indonesia.Longitude=106.8283; indonesia.Name="Indonesia"; indonesia.Population="255,461,700"; layer.Markers.Add(indonesia); maps.Adapter = new MarkerAdapter(context); MarkerCustomTooltipSetting tooltipSetting = new MarkerCustomTooltipSetting(context); tooltipSetting.ShowTooltip = true; layer.MarkerSetting.TooltipSettings = tooltipSetting; maps.Layers.Add (layer); return layout; } } public class MarkerCustomTooltipSetting : TooltipSetting { Context context; public MarkerCustomTooltipSetting(Context con) { context = con; } public override View GetView(object shapeData) { LinearLayout layout = new LinearLayout(context); LinearLayout.LayoutParams linearlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layout.Orientation = Orientation.Vertical; layout.LayoutParameters = linearlayoutParams; layout.SetGravity(GravityFlags.CenterHorizontal); TextView topLabel = new TextView(context); topLabel.Text = (shapeData as PopulationMarker).Name.ToString(); topLabel.TextSize = 12; topLabel.SetTextColor(Color.ParseColor("#FFFFFF")); topLabel.Gravity = GravityFlags.CenterHorizontal; TextView bottoLabel = new TextView(context); bottoLabel.Text = (shapeData as PopulationMarker).Population.ToString(); bottoLabel.TextSize = 12; bottoLabel.SetTextColor(Color.ParseColor("#FFFFFF")); bottoLabel.Gravity = GravityFlags.CenterHorizontal; layout.AddView(topLabel); layout.AddView(bottoLabel); return layout; } } } <file_sep>/Forms/XlsIO/XlsIO.Droid/MainActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="MainActivity.cs" company=" Syncfusion Inc."> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> #endregion namespace SampleBrowser.XlsIO.Droid { using System; using System.Diagnostics.CodeAnalysis; using Android.App; using Android.Content.PM; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; /// <summary> /// This class used to load the application for android. /// </summary> [Activity(Label = "SampleBrowser XlsIO", MainLauncher = false, Icon = "@drawable/AppIcon", Theme = "@style/MainTheme", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Justification = "Reviewed.")] /// <summary> /// override the method OnCreate with <see cref="Bundle"/> class. /// </summary> /// <param name="bundle">The value from <see cref="Bundle"/> class.</param> protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); Core.Droid.CoreSampleBrowser.Init(Resources, this); LoadApplication(new App()); } } }<file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/ActivityIndicator.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Drawing; using CoreGraphics; using Foundation; using UIKit; namespace SampleBrowser { [Register("ActivityIndicator")] public class ActivityIndicator : UIView { UILabel m_messageLabel; UIActivityIndicatorView activityIndicator; internal UILabel MessageLabel { get { return m_messageLabel; } set { m_messageLabel = value; } } public ActivityIndicator(CGRect frame): base(frame) { m_messageLabel = new UILabel(); Frame = frame; BackgroundColor = UIColor.FromRGBA(0, 0, 0, 0.3f); activityIndicator.Color = UIColor.Blue; Layer.CornerRadius = 20; Layer.BorderWidth = 10; } public ActivityIndicator() { m_messageLabel = new UILabel(); activityIndicator = new UIActivityIndicatorView(); BackgroundColor = UIColor.FromRGBA(0, 0, 0, 0.3f); activityIndicator.Color = UIColor.Blue; activityIndicator.Frame = new CGRect(this.Frame.X, this.Frame.Y+10, 100,50); m_messageLabel.Frame= new CGRect(this.Frame.X + 60, this.Frame.Y , 200, 75); } public void SetMessage(string message) { m_messageLabel.TextColor = UIColor.White; m_messageLabel.Text = message; } public void StartAnimating() { this.AddSubview(m_messageLabel); this.AddSubview(activityIndicator); activityIndicator.StartAnimating(); } public void StopAnimating() { activityIndicator.StopAnimating(); this.RemoveFromSuperview(); } public bool IsAnimating { get { if(activityIndicator!=null) return activityIndicator.IsAnimating; return false; } } } }<file_sep>/Forms/Button/readme.md The Essential Xamarin SfButton control allows you to perform an action by clicking on it and displaying both text and images. | Sample | Description | | ------ | ----------- | | [Getting Started](Button/Samples/GettingStartedSample) | This sample demonstrates the basic properties of SfButtonControl in Xamarin Forms application| | [Customizaion](Button/Samples/CustomizationSample) | This sample demonstrates the different types of button customization in Xamarin Forms application | | [Toggle Button](Button/Samples/ToggleButtonSample) | This sample demonstrates the toggle state of SfButton in Xamarin Forms application |<file_sep>/Forms/ImageEditor/ImageEditor/Samples/Serialization/Serialization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using SampleBrowser.Core; using Syncfusion.ListView.XForms; using Xamarin.Forms; namespace SampleBrowser.SfImageEditor { public partial class Serialization : SampleView { SerializationViewModel model; SerializationModel SelectedItem; Assembly assembly = typeof(ImageSerializeModel).GetTypeInfo().Assembly; double height = 0, width = 0; public Serialization() { InitializeComponent(); model = new SerializationViewModel(); listView.BindingContext = model; listView.ItemsSource = model.ModelList; deleteImage.Source = new FontImageSource() { Glyph = "\ue735", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.FromHex("#616161") }; } void Handle_Tapped(object sender, System.EventArgs e) { var items = listView.SelectedItems.ToList(); foreach (SerializationModel item in items) { (item as SerializationModel).SelectedImageVisibility = "false"; if (model.ModelList.Contains(item)) model.ModelList.Remove(item); } ClearItems(); } void ClearItems() { for (int i = 1; i < model.ModelList.Count; i++) { model.ModelList[i].SelectedImageVisibility = "false"; model.ModelList[i].SelectedItemThickness = new Thickness(0, 0, 0, 0); } listView.SelectedItems.Clear(); deleteImage.IsVisible = false; listView.SelectionChanged -= ListView_SelectionChanged; } void Handle_ItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e) { SelectedItem = e.ItemData as SerializationModel; //if (SelectedItem.ImageName == "CreateNew") //{ var item = SelectedItem; if (SelectedItem.SelectedImageVisibility == "false") { SelectedItem.SelectedImageVisibility = "false"; if (Device.RuntimePlatform.ToLower() == "ios") { Navigation.PushAsync(new NavigationPage(new SerializationContentPage(item, listView, model))); } else if (Device.RuntimePlatform.ToLower() == "uwp") { Navigation.PushAsync(new SerializationContentPage(item, listView, model)); } else { Navigation.PushModalAsync(new SerializationContentPage(item, listView, model)); } ClearItems(); } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.RuntimePlatform.ToLower() == "uwp") return; if ((width != this.width || height != this.height) && (width > -1 || height > -1)) { this.width = width; this.height = height; if (width < height) { imageGrid.RowDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 70, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.8, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); } else { imageGrid.RowDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 10, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); } } } void Handle_ItemHolding(object sender, Syncfusion.ListView.XForms.ItemHoldingEventArgs e) { if (listView.SelectedItems.Count > 0) { listView.SelectedItems.Clear(); } for (int i = 1; i < model.ModelList.Count; i++) { model.ModelList[i].SelectedImageVisibility = "true"; model.ModelList[i].SelectionImage = new FontImageSource() { Glyph = "\ue718", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.LightGray }; } listView.SelectionChanged += ListView_SelectionChanged; deleteImage.IsVisible = true; } private void ListView_SelectionChanged(object sender, ItemSelectionChangedEventArgs e) { deleteImage.IsVisible = true; for (int i = 0; i < e.AddedItems.Count; i++) { var item = e.AddedItems[i]; if ((item as SerializationModel).ImageName == "CreateNew") { listView.SelectedItems.Remove(item); } else { (item as SerializationModel).SelectedImageVisibility = "true"; (item as SerializationModel).SelectionImage = new FontImageSource() { Glyph = "\ue748", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.FromHex("#065DC7") }; (item as SerializationModel).SelectedItemThickness = new Thickness(15, 15, 15, 15); } } for (int i = 0; i < e.RemovedItems.Count; i++) { var item = e.RemovedItems[i]; (item as SerializationModel).SelectedImageVisibility = "true"; (item as SerializationModel).SelectionImage = new FontImageSource() { Glyph = "\ue718", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.LightGray }; (item as SerializationModel).SelectedItemThickness = new Thickness(0, 0, 0, 0); } } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/DragAndDrop.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.SfDataGrid; using System.Globalization; using Android.Util; using Android.Graphics; namespace SampleBrowser { public class DragAndDrop : SamplePage { #region Fields SfDataGrid sfGrid; DragAndDropViewModel viewModel; #endregion #region Override Methods public override View GetSampleContent(Context context) { sfGrid = new SfDataGrid(context); viewModel = new DragAndDropViewModel(); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = viewModel.OrdersInfo; sfGrid.SelectionMode = SelectionMode.Single; sfGrid.AllowDraggingColumn = true; sfGrid.AllowDraggingRow = true; sfGrid.RowDragDropTemplate = new RowDragDropTemplate(context); sfGrid.QueryRowDragging += QueryRowDragging; sfGrid.ColumnSizer = ColumnSizer.Star; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; return sfGrid; } public override void Destroy() { sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; sfGrid.Dispose(); sfGrid = null; viewModel = null; } #endregion #region Callbacks void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } //else if (e.Column.MappingName == "LastName") //{ // e.Column.HeaderText = "Last Name"; // e.Column.TextAlignment = GravityFlags.CenterVertical; //} else e.Cancel = true; } private void QueryRowDragging(object sender, QueryRowDraggingEventArgs e) { if (e.Reason == QueryRowDraggingReason.DragStarted) { (sfGrid.RowDragDropTemplate as RowDragDropTemplate).UpdateRow(e.RowData); } } #endregion } }<file_sep>/Forms/XlsIO/XlsIO.iOS/SaveIOS.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="SaveIOS.cs" company=" Syncfusion Inc."> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Foundation; using QuickLook; using SampleBrowser.Core; using SampleBrowser.XlsIO.IOS; using UIKit; using Xamarin.Forms; [assembly: Dependency(typeof(SaveIOS))] namespace SampleBrowser.XlsIO.IOS { /// <summary> /// This class is used to save option for IOS. /// </summary> public class SaveIOS : ISave { /// <summary> /// This method used to provide save option for IOS. /// </summary> /// <param name="filename">Name of the output file</param> /// <param name="contentType">Content type of the output file</param> /// <param name="stream">Input file of MemoryStream</param> public void Save(string filename, string contentType, MemoryStream stream) { string exception = string.Empty; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filePath = Path.Combine(path, filename); try { FileStream fileStream = File.Open(filePath, FileMode.Create); stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { exception = e.ToString(); } finally { if (contentType != "application/html") { stream.Dispose(); } } if (contentType == "application/html" || exception != string.Empty) { return; } UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (currentController.PresentedViewController != null) { currentController = currentController.PresentedViewController; } UIView currentView = currentController.View; QLPreviewController preview = new QLPreviewController(); QLPreviewItem item = new QLPreviewItemBundle(filename, filePath); preview.DataSource = new PreviewControllerDS(item); // UIViewController uiView = currentView as UIViewController; currentController.PresentViewController((UIViewController)preview, true, (Action)null); } } }<file_sep>/Forms/Calculate/Calculate/Samples/FunctionsLibrary/FunctionsLibraryViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Calculate; using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.Calculate { [Preserve(AllMembers = true)] public class FunctionsLibraryViewModel : INotifyPropertyChanged { #region Fields public string txtA1; public string txtA2; public string txtA3; public string txtA4; public string txtA5; public string txtB1; public string txtB2; public string txtB3; public string txtB4; public string txtB5; public string txtC1; public string txtC2; public string txtC3; public string txtC4; public string txtC5; public string txtGen; public string txtResult; private ICommand compute; internal List<string> LibraryFunctions; internal CalcEngine Engine; internal CalcData _CalcData; #endregion #region Constructor public FunctionsLibraryViewModel() { txtA1 = "32"; txtA2 = "12"; txtA3 = "88"; txtA4 = "73"; txtA5 = "63"; txtB1 = "50"; txtB2 = "24"; txtB3 = "-22"; txtB4 = "91"; txtB5 = "29"; txtC1 = "10"; txtC2 = "90"; txtC3 = "37"; txtC4 = "21"; txtC5 = "44"; txtGen = string.Empty; txtResult = string.Empty; LibraryFunctions = new List<string>(); InitializeEngine(); } #endregion #region Properties public string TxtA1 { get { return txtA1; } set { txtA1 = value; OnPropertyChanged("TxtA1"); } } public string TxtA2 { get { return txtA2; } set { txtA2 = value; OnPropertyChanged("TxtA2"); } } public string TxtA3 { get { return txtA3; } set { txtA3 = value; OnPropertyChanged("TxtA3"); } } public string TxtA4 { get { return txtA4; } set { txtA4 = value; OnPropertyChanged("TxtA4"); } } public string TxtA5 { get { return txtA5; } set { txtA5 = value; OnPropertyChanged("TxtA5"); } } public string TxtB1 { get { return txtB1; } set { txtB1 = value; OnPropertyChanged("TxtB1"); } } public string TxtB2 { get { return txtB2; } set { txtB2 = value; OnPropertyChanged("TxtB2"); } } public string TxtB3 { get { return txtB3; } set { txtB3 = value; OnPropertyChanged("TxtB3"); } } public string TxtB4 { get { return txtB4; } set { txtB4 = value; OnPropertyChanged("TxtB4"); } } public string TxtB5 { get { return txtB5; } set { txtB5 = value; OnPropertyChanged("TxtB5"); } } public string TxtC1 { get { return txtC1; } set { txtC1 = value; OnPropertyChanged("TxtC1"); } } public string TxtC2 { get { return txtC2; } set { txtC2 = value; OnPropertyChanged("TxtC2"); } } public string TxtC3 { get { return txtC3; } set { txtC3 = value; OnPropertyChanged("TxtC3"); } } public string TxtC4 { get { return txtC4; } set { txtC4 = value; OnPropertyChanged("TxtC4"); } } public string TxtC5 { get { return txtC5; } set { txtC5 = value; OnPropertyChanged("TxtC5"); } } public string TxtGen { get { return txtGen; } set { txtGen = value; OnPropertyChanged("TxtGen"); } } public string TxtResult { get { return txtResult; } set { txtResult = value; OnPropertyChanged("TxtResult"); } } public ICommand ComputeCommand { get { if (compute == null) compute = new ComputeCommand(this); return compute; } set { compute = value; } } #endregion #region Methods internal void InitializePicker(Picker picker) { foreach (string item in Engine.LibraryFunctions.Keys) LibraryFunctions.Add(item); LibraryFunctions.Sort(); LibraryFunctions.RemoveAt(0); LibraryFunctions.RemoveAt(0); LibraryFunctions.RemoveAt(0); LibraryFunctions.Remove("ACCRINTM"); LibraryFunctions.Remove("AVERAGEIFS"); LibraryFunctions.Remove("BETA.DIST"); LibraryFunctions.Remove("BIGMUL"); LibraryFunctions.Remove("IMAGINARYDIFFERENCE"); LibraryFunctions.Remove("IMPRODUCT"); LibraryFunctions.Remove("IMSUB"); LibraryFunctions.Remove("F.INV.RT"); LibraryFunctions.Remove("HYPGEOM.DIST"); LibraryFunctions.Remove("IMCONJUGATE"); LibraryFunctions.Remove("MIRR"); LibraryFunctions.Remove("FORMULATEXT"); LibraryFunctions.Remove("GROWTH"); LibraryFunctions.Remove("IRR"); LibraryFunctions.Remove("MDETERN"); LibraryFunctions.Remove("MMULT"); LibraryFunctions.Remove("NORM.INV"); LibraryFunctions.Remove("PROPER"); LibraryFunctions.Remove("REPLACEB"); LibraryFunctions.Remove("UNICODE"); LibraryFunctions.Remove("XIRR"); foreach (string item in LibraryFunctions) picker.Items.Add(item); picker.SelectedIndex = 0; } private void InitializeEngine() { _CalcData = new CalcData(); Engine = new CalcEngine(_CalcData); Engine.UseNoAmpersandQuotes = true; int i = CalcEngine.CreateSheetFamilyID(); Engine.RegisterGridAsSheet("CalcData" + i.ToString(), _CalcData, i); } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion #region Dispose internal void Dispose() { _CalcData = null; Engine.Dispose(); Engine = null; } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/TreeView/ViewModel/FileManagerViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using UIKit; namespace SampleBrowser { public class FileManagerViewModel { public ObservableCollection<FileManager> Folders { get; set; } public FileManagerViewModel() { GenerateFiles(); } private void GenerateFiles() { var doc = new FileManager() { FileName = "Documents", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_folder.png") }; var download = new FileManager() { FileName = "Downloads", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_folder.png") }; var mp3 = new FileManager() { FileName = "Music", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_folder.png") }; var pics = new FileManager() { FileName = "Pictures", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_folder.png") }; var videos = new FileManager() { FileName = "Videos", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_folder.png") }; var polution = new FileManager() { FileName = "Environmental Pollution.docx", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_word.png") }; var globalWarming = new FileManager() { FileName = "Global Warming.ppt", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_ppt.png") }; var sanitation = new FileManager() { FileName = "Sanitation.docx", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_word.png") }; var socialnetwork = new FileManager() { FileName = "Social Network.pdf", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_pdf.png") }; var youthempower = new FileManager() { FileName = "Youth Empowerment.pdf", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_pdf.png") }; var game = new FileManager() { FileName = "Game.exe", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_exe.png") }; var tutorials = new FileManager() { FileName = "Tutorials.zip", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_zip.png") }; var typescript = new FileManager() { FileName = "TypeScript.7z", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_zip.png") }; var uiguide = new FileManager() { FileName = "UI-Guide.pdf", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_pdf.png") }; var song = new FileManager() { FileName = "Gouttes", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_mp3.png") }; var camera = new FileManager() { FileName = "Camera Roll", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_folder.png") }; var stone = new FileManager() { FileName = "Stone.jpg", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_png.png") }; var wind = new FileManager() { FileName = "Wind.jpg", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_png.png") }; var img0 = new FileManager() { FileName = "WIN_20160726_094117.JPG", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_img0.png") }; var img1 = new FileManager() { FileName = "WIN_20160726_094118.JPG", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_img1.png") }; var video0 = new FileManager() { FileName = "Nature.mp4", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_video.png") }; var video1 = new FileManager() { FileName = "Wild.mpeg", ImageIcon = UIImage.FromBundle("Images/TreeView/treeview_video.png") }; doc.SubFolder = new ObservableCollection<FileManager> { polution, globalWarming, sanitation, socialnetwork, youthempower }; download.SubFolder = new ObservableCollection<FileManager> { game, tutorials, typescript, uiguide }; mp3.SubFolder = new ObservableCollection<FileManager> { song }; pics.SubFolder = new ObservableCollection<FileManager> { camera, stone, wind }; camera.SubFolder = new ObservableCollection<FileManager> { img0, img1 }; videos.SubFolder = new ObservableCollection<FileManager> { video0, video1 }; this.Folders = new ObservableCollection<FileManager>(); Folders.Add(doc); Folders.Add(download); Folders.Add(mp3); Folders.Add(pics); Folders.Add(videos); } } }<file_sep>/Android/SampleBrowser/Samples/Carousel/readme.md The `SfCarousel` provides rich visual navigation experience of image data. Also has efficient customization support and interactive navigation features. The following samples are available for carousel control to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](Carousel.cs)| It showcases the built-in animations on carousel items and customization of spacing between the selected and unselected items.| |[LoadMore](LoadMore_Mobile.cs)|It demonstrates the behavior of `LoadMore` feature in carousel. Initially items of specified count are loaded in carousel and the remaining items are loaded after tapping the load more button.| <file_sep>/Forms/Carousel/Carousel/SampleViewClass/Carousel_View.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfCarousel { /// <summary> /// Carousel. /// </summary> public class Carousel_View: SampleView { #region Constructor public Carousel_View() { #region device if (Device.Idiom == TargetIdiom.Phone || Device.RuntimePlatform == Device.UWP) { Carousel_Default busy = new Carousel_Default(); this.Content = busy.getContent(); this.PropertyView = busy.getProperty(); } #endregion #region tablet else if (Device.Idiom == TargetIdiom.Tablet) { Carousel_Tablet busyTab = new Carousel_Tablet(); this.Content = busyTab.getContent(); this.PropertyView = busyTab.getPropertyView(); } #endregion } #endregion } }<file_sep>/Forms/DataGrid/DataGrid.macOS/Main.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Main.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1649:FileHeaderFileNameDocumentationMustMatchTypeName", Justification = "Reviewed.")] namespace SampleBrowser.SfDataGrid.MacOS { using System.Diagnostics.CodeAnalysis; using AppKit; /// <summary> /// This is the main entry point of the application. /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1400:AccessModifierMustBeDeclared", Justification = "Reviewed.")] static class MainClass { /// <summary> /// This is the main entry point of the application. /// </summary> /// <param name="args">Main method parameter as string type of args</param> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1400:AccessModifierMustBeDeclared", Justification = "Reviewed.")] static void Main(string[] args) { NSApplication.Init(); NSApplication.Main(args); } } } <file_sep>/Forms/Chat/Chat/Samples/ViewModel/LoadMoreViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GettingStartedViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfChat { using Syncfusion.ListView.XForms; using Syncfusion.XForms.Chat; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// ViewModel for Load More sample. /// </summary> public class LoadMoreViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// Chat conversation message collection. /// </summary> private ObservableCollection<object> messages; /// <summary> /// Author assinging temporary array. /// </summary> private int[] authorArray; /// <summary> /// current user of chat. /// </summary> private Author currentUser; /// <summary> /// message conversation set. /// </summary> private List<string> messageList; /// <summary> /// visible of the Badgeview. /// </summary> private bool isVisible = false; /// <summary> /// bool value for chat IsBusy. /// </summary> private bool isBusy = false; /// <summary> /// bool value indicate chat in Bottom. /// </summary> private bool isBottom; /// <summary> /// bool value indicate load more command execution. /// </summary> private bool loadMoreCommandExecute; /// <summary> /// Field for load more behavior property. /// </summary private LoadMoreOption loadMoreBehavior = LoadMoreOption.Manual; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="GettingStartedViewModel"/> class. /// </summary> public LoadMoreViewModel() { this.Messages = new ObservableCollection<object>(); this.InitializeAuthors(); this.InitializeMessageList(); this.authorArray = new int[] { 0, 1, 2, 1, 0, 1, 0, 2, 1, 0, 0, 2, 0, 1, 0, 2, 1, 0, 2, 1, 0, 2, 1, 0, 2, 1, 0, 2, 0, 1, 0, 2, 0, 2, 1, 0, 2, 0, 2, 1, 2, 0, 0, 2, 0, 1, 0, 2, 0, 1, 0, 1, 0, 2, 0, 0, 1, 2, 0, 1 }; this.MapAuthorToMessage(); this.CurrentUser = this.AuthorsCollection[0]; LoadMoreCommand = new Command<object>(LoadMoreItems, CanLoadMoreItems); this.InitConvo(); } #endregion #region Public Properties /// <summary> /// Gets or sets the LoadMoreBehavior of SfChat. /// </summary> public LoadMoreOption LoadMoreBehavior { get { return this.loadMoreBehavior; } set { this.loadMoreBehavior = value; RaisePropertyChanged("LoadMoreBehavior"); } } /// <summary> /// Gets or sets the group message conversation. /// </summary> public ObservableCollection<object> Messages { get { return this.messages; } set { this.messages = value; RaisePropertyChanged("Messages"); } } /// <summary> /// Gets or sets the current author. /// </summary> public Author CurrentUser { get { return this.currentUser; } set { this.currentUser = value; RaisePropertyChanged("CurrentUser"); } } /// <summary> /// Gets or sets the load more command. /// </summary> public ICommand LoadMoreCommand { get; set; } /// <summary> /// Gets or sets the IsBusy. /// </summary> public bool IsBusy { get { return this.isBusy; } set { this.isBusy = value; RaisePropertyChanged("IsBusy"); } } /// <summary> /// Gets or sets the IsBottom to inidicate the chat reach bottom or not. /// </summary> public bool IsBottom { get { return this.isBottom; } set { this.isBottom = value; RaisePropertyChanged("IsBottom"); } } /// <summary> /// Gets or sets the LoadMoreCommand to inidicate load more command execute or not. /// </summary> public bool LoadMoreCommandExecute { get { return this.loadMoreCommandExecute; } set { this.loadMoreCommandExecute = value; RaisePropertyChanged("LoadMoreCommandExecute"); } } /// <summary> /// Gets or sets the IsVisible to inidicate the visible of badgeview or not. /// </summary> public bool IsVisible { get { return this.isVisible; } set { this.isVisible = value; RaisePropertyChanged("IsVisible"); } } #endregion #region Internal Properties /// <summary> /// Gets a sets the value indicates GettingStarted view managed resource are disposed or not. /// </summary> internal bool IsDisposed { get; set; } /// <summary> /// Chat conversation authors collection. /// </summary> internal ObservableCollection<Author> AuthorsCollection { get; set; } /// <summary> /// Dictionary that holds the message and its respective author. /// </summary> internal Dictionary<int, Author> AuthorMessageDataBase { get; set; } #endregion #region Property Changed /// <summary> /// Property changed handler. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Occurs when property is changed. /// </summary> /// <param name="propName">changed property name</param> public void RaisePropertyChanged(string propName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } #endregion #region Private Methods #region Init /// <summary> /// Initializes the message collection for group conversation. /// </summary> private void InitializeMessageList() { this.messageList = new List<string> { "Good morning.", "Good morning.", "Morning.", "Is this all of us?", "Yes, Tammy has a couple of vid conferences, so I’m going to email her a summary when we’re done.", "Ok.", "Did everyone get the email with Jamie’s registry link?", "Yes. The link worked.", "There’s some cute stuff on there. You wanted to go in together on one of the more expensive things?", "Yeah. Did you see that stroller? I was looking at it.", "Here 👇", "Oh, yeah. I saw that. It’s very cool that it turns into a car seat.", "It has really good reviews, so I assume they did a lot of research before picking it.", "They want the teal version, right?", "That’s what comes up when I click the registry link, so I assume so.", "“Lake Blue”.", "Looks teal to me.", "It’s better than just plain black, in any case.", "True.", "How many of us are pooling for it?", "Tammy is a probably. Neal gave me a max of $30, and Son just said sure. I think he just doesn’t want to shop for baby things. So at least 5, probably 6.", "😂 That’s so Son.", "So that puts us at between $26 and $31 per person, before tax. That’s not too bad.", "Yeah. I mean, I’m sure Jamie would love toys and books, but I figure there should be at least something from her list at the shower.", "I’m ok with it.", "Yeah, me, too.", "Great. I’ll just send an email to Tammy for when she gets out of her calls.", "Do you have Prime?", "Yes! Although I think I’d get free shipping at that price point, anyway.", "It’s nice that it’s on sale, too.", "Yeah, that’s why I want to get it ordered today. Also so I have time to inspect it a bit, make sure it works.", "Are we wrapping it at all?", "I have this giant bow in my closet I can put on it. I don’t even remember where it came from. It’s purple.", "Gender-neutral. Yay.", "They know the gender, though, right?", "Yes. It’s a girl. Jamie’s not big on surprises. She likes purple, though.", "That works, then.", "Do you want to do our own cards?", "You know Son won’t get one.", "We can just tell them who the stroller’s from.", "Yeah. We should keep a list at the party of who gave what anyway.", "I think that’s customary. For thank you cards.", "So yes, we’ll all do our own cards.", "Is the party in the conference room or the break room?", "Conference room. Mae has it booked for us.", "That’s good. Cleaner and easier to hide gifts in.", "Easier to decorate without getting in people’s way, too.", "You don’t want people spilling their lunches all over the tablecloth?", "That would be bad.", "😂 😂 😂", "I think Mae’s going to do the decorating in the morning. Aisha authorized a small budget for balloons and stuff.", "Tell her to let us know if she needs any help. I should have some downtime around 10:30.", "Ok, thanks. I will.", "Ack. I wish I could help, but I’ve got vid calls myself scheduled all that morning.", "No problem. I think there’ll be plenty of people.", "I’ll email everyone when Tammy gets back to me about the gift.", "Ok, that sounds good.", "Yes. I’ll see you two later.", "Thanks for meeting with me. Bye.", "Bye 👋 👋 👋" }; } /// <summary> /// Initializes the author collection. /// </summary> private void InitializeAuthors() { this.AuthorsCollection = new ObservableCollection<Author>(); this.AuthorsCollection.Add(new Author() { Name = "Nancy", Avatar = "People_Circle16.png" }); this.AuthorsCollection.Add(new Author() { Name = "Andrea", Avatar = "People_Circle2.png" }); this.AuthorsCollection.Add(new Author() { Name = "Harrison", Avatar = "People_Circle14.png" }); this.AuthorsCollection.Add(new Author() { Name = "Margaret", Avatar = "People_Circle7.png" }); this.AuthorsCollection.Add(new Author() { Name = "Steven", Avatar = "People_Circle5.png" }); this.AuthorsCollection.Add(new Author() { Name = "Michale", Avatar = "People_Circle23.png" }); } /// <summary> /// Initializes the conversation and adds messages. /// </summary> private void InitConvo() { if (this.IsDisposed) { return; } for (int i = messageList.Count - 8; i < messageList.Count; i++) { this.Messages.Add(this.CreateMessage(this.messageList[i], this.AuthorMessageDataBase[i])); } } /// <summary> /// Initializes which message belongs to which author. /// </summary> private void MapAuthorToMessage() { this.AuthorMessageDataBase = new Dictionary<int, Author>(); for (int i = 0; i < this.messageList.Count; i++) { this.AuthorMessageDataBase.Add(i, this.AuthorsCollection[this.authorArray[i]]); } } #endregion /// <summary> /// Creating message to based on the given string. /// </summary> /// <param name="text">The text of the new message.</param> /// <param name="auth">The author of the new message.</param> /// <returns>The <see cref="TextMessage"/> created with the given string.</returns> private TextMessage CreateMessage(string text, Author auth) { if (text.Contains("Here 👇")) { return new HyperlinkMessage() { DateTime = DateTime.Now, Author = auth, Text = text, Url = "https://www.amazon.com/Safety-1st-Smooth-OnBoard-Monument/dp/B01JRY00CW/ref=sr_1_6?dchild=1&keywords=stroller&qid=1592569167&refinements=p_72%3A2661618011&rnid=2661617011&sr=8-6&th=1" }; } return new TextMessage() { DateTime = DateTime.Now, Author = auth, Text = text, }; } /// <summary> /// Action Raised when the load more command. /// </summary> private bool CanLoadMoreItems(object obj) { if (this.Messages.Count >= this.messageList.Count) { IsBusy = false; return false; } return true; } /// <summary> /// Action raised when the load more command is executed. /// </summary> private async void LoadMoreItems(object obj) { try { LoadMoreCommandExecute = true; IsBusy = true; await Task.Delay(3000); LoadMoreMessages(); } catch { } finally { IsBusy = false; LoadMoreCommandExecute = false; if ((this.LoadMoreBehavior == LoadMoreOption.Auto || this.LoadMoreBehavior == LoadMoreOption.AutoOnScroll) && this.messageList.Count == this.Messages.Count) { this.LoadMoreBehavior = LoadMoreOption.None; } } } /// <summary> /// Adds the older messages to <see cref="SfChat"/>'s message collection. /// </summary> /// <param name="index">index of message collection.</param> /// <param name="count">count of the message to be added.</param> private void LoadMoreMessages() { for (int i = 1; i <= 10 ; i++) { if (this.messageList.Count != this.Messages.Count) { this.Messages.Insert(0, this.CreateMessage(messageList[this.messageList.Count - this.Messages.Count - 1], AuthorMessageDataBase[this.messageList.Count - this.Messages.Count - 1])); } } } #endregion } } <file_sep>/Forms/BadgeView/BadgeView/Samples/Customization/CustomizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CustomizationViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfBadgeView { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Text; using Syncfusion.XForms.BadgeView; using Syncfusion.XForms.Buttons; using Xamarin.Forms; using Xamarin.Forms.Internals; /// <summary> /// Customization View Model class. /// </summary> [Preserve(AllMembers = true)] [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1027:TabsMustNotBeUsed", Justification = "Reviewed.")] [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] public class CustomizationViewModel : INotifyPropertyChanged { #region Fields private BadgeIcon badgeIcon; private BadgeType badgeType; private Color backgroundColor = Color.FromHex("#F25B8E"); #endregion #region Event /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Properties #region BadgeIcon /// <summary> /// Gets or sets the badge icon /// </summary> public BadgeIcon BadgeIcon { get { return this.badgeIcon; } set { this.badgeIcon = value; if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs("BadgeIcon")); } } } #endregion BadgeIcon #region BadgeType /// <summary> /// Gets or sets the badge type /// </summary> public BadgeType BadgeType { get { return this.badgeType; } set { this.badgeType = value; if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs("BadgeType")); } } } #endregion BadgeType /// <summary> /// Gets or sets the background color of button. /// </summary> /// <value>The background color of button</value> public Color BackgroundColor { get { return backgroundColor; } set { backgroundColor = value; if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs("BackgroundColor")); } } } public ObservableCollection<Color> Colors { get; set; } #endregion Properties #region Constructor /// <summary> /// Initializes a new instance of the <see cref="T:button.buttonViewModel"/> class. /// </summary> public CustomizationViewModel() { this.Colors = new ObservableCollection<Color>(); Colors.Add(Color.FromHex("#F25B8E")); Colors.Add(Color.FromHex("#EE80F0")); Colors.Add(Color.FromHex("#F0A043")); Colors.Add(Color.FromHex("#7C7FF1")); Colors.Add(Color.FromHex("#5BBBDD")); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Schedule/Recurrence.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Com.Syncfusion.Schedule; using Com.Syncfusion.Schedule.Enums; using Android.Views; using Android.Widget; using Java.Util; using System.Collections.Generic; using Android.Graphics; using Java.Text; namespace SampleBrowser { public class Recurrence : SamplePage, IDisposable { public Recurrence() { } private SfSchedule sfschedule; public override View GetSampleContent(Context con) { sfschedule = new SfSchedule(con); sfschedule.ScheduleView = ScheduleView.MonthView; sfschedule.FirstDayOfWeek = 1; GetAppointments(); sfschedule.ItemsSource = appointmentCollection; MonthViewSettings monthViewSettings = new MonthViewSettings(); monthViewSettings.ShowAppointmentsInline = true; sfschedule.MonthViewSettings = monthViewSettings; sfschedule.EnableNavigation = true; return sfschedule; } private ScheduleAppointmentCollection appointmentCollection; //Creating appointments for ScheduleAppointmentCollection public void GetAppointments() { appointmentCollection = new ScheduleAppointmentCollection(); //Recurrence Appointment 1 ScheduleAppointment appointment1 = new ScheduleAppointment(); Calendar currentDate = Calendar.Instance; Calendar startTime = (Calendar)currentDate.Clone(); Calendar endTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth), 4, 0, 0); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth), 6, 0, 0); appointment1.StartTime = startTime; appointment1.EndTime = endTime; appointment1.Color = Color.ParseColor("#FF1BA1E2"); appointment1.Subject = "Occurs once in every two days"; RecurrenceProperties recurrenceProp1 = new RecurrenceProperties(); recurrenceProp1.RecurrenceType = RecurrenceType.Daily; recurrenceProp1.Interval = 2; recurrenceProp1.RecurrenceRange = RecurrenceRange.Count; recurrenceProp1.RecurrenceCount = 10; appointment1.RecurrenceRule = ScheduleHelper.RRuleGenerator(recurrenceProp1, appointment1.StartTime, appointment1.EndTime); appointmentCollection.Add(appointment1); //Recurrence Appointment 2 ScheduleAppointment scheduleAppointment1 = new ScheduleAppointment(); Calendar currentDate1 = Calendar.Instance; Calendar startTime1 = (Calendar)currentDate1.Clone(); Calendar endTime1 = (Calendar)currentDate1.Clone(); startTime1.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth), 10, 0, 0); endTime1.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth), 12, 0, 0); scheduleAppointment1.StartTime = startTime1; scheduleAppointment1.EndTime = endTime1; scheduleAppointment1.Color = Color.ParseColor("#FFD80073"); scheduleAppointment1.Subject = "Occurs every Monday"; RecurrenceProperties recurrenceProperties1 = new RecurrenceProperties(); recurrenceProperties1.RecurrenceType = RecurrenceType.Weekly; recurrenceProperties1.RecurrenceRange = RecurrenceRange.Count; recurrenceProperties1.Interval = 1; recurrenceProperties1.WeekDays = WeekDays.Monday; recurrenceProperties1.RecurrenceCount = 10; scheduleAppointment1.RecurrenceRule = ScheduleHelper.RRuleGenerator(recurrenceProperties1, scheduleAppointment1.StartTime, scheduleAppointment1.EndTime); appointmentCollection.Add(scheduleAppointment1); } public void OnNothingSelected(object sender, AdapterView.ItemSelectedEventArgs e) { sfschedule.ScheduleView = ScheduleView.WeekView; } public void Dispose() { if (sfschedule != null) { sfschedule.Dispose(); sfschedule = null; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/SplineRangeArea.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using Foundation; namespace SampleBrowser { public class SplineRangeArea : SampleView { public SplineRangeArea() { SFChart chart = new SFChart(); chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.Title.Text = new NSString("Product Price Comparison"); SFCategoryAxis primary = new SFCategoryAxis(); primary.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; primary.ShowMajorGridLines = false; chart.PrimaryAxis = primary; chart.SecondaryAxis = new SFNumericalAxis(); chart.SecondaryAxis.ShowMajorGridLines = false; chart.SecondaryAxis.ShowMinorGridLines = false; chart.SecondaryAxis.Minimum = new NSNumber(5); chart.SecondaryAxis.Maximum = new NSNumber(55); chart.SecondaryAxis.Interval = new NSNumber(5); ChartViewModel dataModel = new ChartViewModel(); SFSplineRangeAreaSeries series1 = new SFSplineRangeAreaSeries(); series1.ItemsSource = dataModel.RangeAreaData; series1.XBindingPath = "XValue"; series1.High = "High"; series1.Low = "Low"; series1.EnableTooltip = true; series1.Label = "Product A"; series1.EnableAnimation = true; chart.Series.Add(series1); SFSplineRangeAreaSeries series2 = new SFSplineRangeAreaSeries(); series2.ItemsSource = dataModel.RangeAreaData1; series2.XBindingPath = "XValue"; series2.High = "High"; series2.Low = "Low"; series2.EnableTooltip = true; series2.Label = "Product B"; chart.Legend.IconHeight = 14; series2.EnableAnimation = true; chart.Series.Add(series2); chart.Legend.Visible = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; chart.AddChartBehavior(new SFChartZoomPanBehavior()); chart.PrimaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/ProductInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ProductInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties and notifies clients that a property value has changed. /// </summary> public class ProductInfo : Employee { #region Private Members [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int productID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string productModel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int userRating; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string product; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private bool availability; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double price; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int shippingDays; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string productType; #endregion #region Properties /// <summary> /// Gets or sets the value of ProductID and notifies user when value gets changed /// </summary> public int ProductID { get { return this.productID; } set { this.productID = value; this.RaisePropertyChanged("ProductID"); } } /// <summary> /// Gets or sets the value of Product and notifies user when value gets changed /// </summary> public string Product { get { return this.product; } set { this.product = value; this.RaisePropertyChanged("Product"); } } /// <summary> /// Gets or sets the value of UserRating and notifies user when value gets changed /// </summary> public int UserRating { get { return this.userRating; } set { this.userRating = value; this.RaisePropertyChanged("UserRating"); } } /// <summary> /// Gets or sets the value of ProductModel and notifies user when value gets changed /// </summary> public string ProductModel { get { return this.productModel; } set { this.productModel = value; this.RaisePropertyChanged("ProductModel"); } } /// <summary> /// Gets or sets the value of Price and notifies user when value gets changed /// </summary> public double Price { get { return this.price; } set { this.price = value; this.RaisePropertyChanged("Price"); } } /// <summary> /// Gets or sets the value of ShippingDays and notifies user when value gets changed /// </summary> public int ShippingDays { get { return this.shippingDays; } set { this.shippingDays = value; this.RaisePropertyChanged("ShippingDays"); } } /// <summary> /// Gets or sets a value indicating whether Availability has true or false value and notifies user when value gets changed /// </summary> public bool Availability { get { return this.availability; } set { this.availability = value; this.RaisePropertyChanged("Availability"); } } /// <summary> /// Gets or sets the value of ProductType and notifies user when value gets changed /// </summary> public string ProductType { get { return this.productType; } set { this.productType = value; this.RaisePropertyChanged("ProductType"); } } #endregion } }<file_sep>/Android/SampleBrowser/Samples/ImageEditor/Serialization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Syncfusion.SfImageEditor.Android; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Content; using Android.Content.PM; using Android.Graphics.Drawables; using Android.Views; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; using Android.Content.Res; using System.Text; using Android.Util; using Java.Lang; using System.ComponentModel; using System.Collections.ObjectModel; using Android.Views.InputMethods; namespace SampleBrowser { public class Serialization : SamplePage { internal static Activity Activity { get; set; } View view { get; set; } public static Bitmap Image { get; set; } Context con { get; set; } public static Stream ImageStream { get; set; } public static Item SelectedItem { get; set; } public static GridView gridview { get; set; } ImageView notSelected { get; set; } public static List<Item> mSelectedItems; ImageButton deleteButton { get; set; } public static bool isLongPressEnabled { get; set; } public static bool isDeleted { get; set; } public override Android.Views.View GetSampleContent(Android.Content.Context context) { mSelectedItems = new List<Item>(); con = context; isLongPressEnabled = false; isDeleted = false; Activity = con as Activity; LayoutInflater layoutInflater = LayoutInflater.From(context); view = layoutInflater.Inflate(Resource.Layout.SerializationFirstPage, null); gridview = view.FindViewById<GridView>(Resource.Id.gridview); var deviceDensity = (int)context.Resources.DisplayMetrics.Density; if (IsTabletDevice(context)) { gridview.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 650 * deviceDensity); gridview.NumColumns = 3; } else if(deviceDensity>=3 && deviceDensity<4 && !IsTabletDevice(context)) { gridview.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 310 * deviceDensity); } else if(deviceDensity < 3 && !IsTabletDevice(context)) { gridview.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 400 * deviceDensity); } deleteButton = view.FindViewById<ImageButton>(Resource.Id.editordelete); deleteButton.Click+= DeleteButton_Click; gridview.Adapter = new ImageAdapter(Activity); deleteButton.Visibility = ViewStates.Invisible; gridview.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) { isDeleted = false; SelectedItem = (gridview.Adapter as ImageAdapter).mItems[args.Position]; if (!SelectedItem.IsLongPressedEnabled) { isLongPressEnabled = false; Activity = con as Activity; Activity?.StartActivity(typeof(SerializationActivity)); if (SelectedItem.ImageName != "Create New") { ImageStream = SelectedItem.Strm; SelectedItem.IsItemChecked = false; SelectedItem.IsLongPressedEnabled = false; } } else if(!SelectedItem.IsItemChecked) { SelectedItem.IsItemChecked = true; mSelectedItems.Add(SelectedItem); } else if(SelectedItem.IsItemChecked) { SelectedItem.IsItemChecked = false; if(mSelectedItems.Count>0) mSelectedItems.Remove(SelectedItem); } (gridview.Adapter as ImageAdapter).NotifyDataSetChanged(); }; gridview.ItemLongClick+= (object sender, AdapterView.ItemLongClickEventArgs e) => { deleteButton.Visibility = ViewStates.Visible; SelectedItem = (gridview.Adapter as ImageAdapter).mItems[e.Position]; if (SelectedItem.ImageName != "CreateNew") { SelectedItem.IsLongPressedEnabled = true; isLongPressEnabled = true; isDeleted = false; (gridview.Adapter as ImageAdapter).NotifyDataSetChanged(); } }; return view; } public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = System.Math.Sqrt(System.Math.Pow(screenWidth, 2) + System.Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } void DeleteButton_Click(object sender, EventArgs e) { for (int i = 0; i < mSelectedItems.Count; i++) { if ((gridview.Adapter as ImageAdapter).mItems.Contains(mSelectedItems[i])) { (gridview.Adapter as ImageAdapter).mItems.Remove(mSelectedItems[i]); } } (gridview.Adapter as ImageAdapter).NotifyDataSetChanged(); isDeleted = true; deleteButton.Visibility = ViewStates.Invisible; } } [Activity(Label = "SfImageEditor", ScreenOrientation = ScreenOrientation.Portrait, Icon = "@drawable/icon")] public class SerializationActivity : Activity { SfImageEditor editor; View view { get; set; } EditText entry; string name=""; LinearLayout popipView; FrameLayout overView; InputMethodManager imm; int height = 500; protected override void OnCreate(Bundle savedInstanceState) { LayoutInflater layoutInflater = LayoutInflater.From(this); view = layoutInflater.Inflate(Resource.Layout.editorSavePopup, null); popipView = view.FindViewById<LinearLayout>(Resource.Id.editorPopUp); var deviceDensity = (int)this.Resources.DisplayMetrics.Density; popipView.Visibility = ViewStates.Invisible; var SaveButton = view.FindViewById<Button>(Resource.Id.Savebutton); var CancelButton = view.FindViewById<Button>(Resource.Id.Cancelbutton); entry = view.FindViewById<EditText>(Resource.Id.editTextDialogUserInput); SaveButton.Click += SaveButton_Click; CancelButton.Click += CancelButton_Click; imm= (InputMethodManager)GetSystemService(Context.InputMethodService); if (IsTabletDevice(this)) { height = 150; } else height = 200*deviceDensity; var Params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent - 100, height, GravityFlags.CenterHorizontal); Params.SetMargins(0, 300, 0, 0); popipView.LayoutParameters = Params; FrameLayout mainLayout = new FrameLayout(this); var tParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent, GravityFlags.Fill); mainLayout.SetBackgroundColor(Color.Transparent); editor = new SfImageEditor(this); RunTimer(); editor.ImageSaving+= Editor_ImageSaving; base.OnCreate(savedInstanceState); editor.SetToolbarItemVisibility("save", false); HeaderToolbarItem item1 = new HeaderToolbarItem(); item1.Text = "Save"; editor.SetBackgroundColor(Color.White); editor.ToolbarSettings.ToolbarItems.Add(item1); editor.ToolbarSettings.ToolbarItemSelected += (sender, e) => { if (e.ToolbarItem is HeaderToolbarItem) { var text = (e.ToolbarItem as HeaderToolbarItem).Text; if (text == "Save") { if (Serialization.SelectedItem.Name == "CreateNew") { overView.Visibility = ViewStates.Visible; popipView.Visibility = ViewStates.Visible; } else editor.Save(); } } }; overView = new FrameLayout(this); var overViewParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent, GravityFlags.Fill); overView.LayoutParameters = overViewParams; overView.Alpha = 0.5f; overView.Visibility = ViewStates.Invisible; overView.SetBackgroundColor(Color.Black); mainLayout.AddView(editor); mainLayout.AddView(overView); mainLayout.AddView(popipView); SetContentView(mainLayout); } public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = System.Math.Sqrt(System.Math.Pow(screenWidth, 2) + System.Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } void SaveButton_Click(object sender, EventArgs e) { name = entry.Text; editor.Save(); popipView.Visibility = ViewStates.Invisible; overView.Visibility = ViewStates.Invisible; entry.Text=""; this.imm?.HideSoftInputFromWindow(this.entry.WindowToken, HideSoftInputFlags.None); } void CancelButton_Click(object sender, EventArgs e) { popipView.Visibility = ViewStates.Invisible; overView.Visibility = ViewStates.Invisible; entry.Text = ""; this.imm?.HideSoftInputFromWindow(this.entry.WindowToken, HideSoftInputFlags.None); } void Editor_ImageSaving(object sender, ImageSavingEventArgs e) { var serializedStream = editor.SaveEdits(); var mStream = e.Stream; mStream.Position = 0; Bitmap bitmap = BitmapFactory.DecodeStream(mStream); var bitMap = bitmap; if (Serialization.SelectedItem.Name != "CreateNew") { Serialization.SelectedItem.Strm = serializedStream; Serialization.SelectedItem.BitMap = bitmap; } else { (Serialization.gridview.Adapter as ImageAdapter).mItems.Add(new Item { Name = name != "" ? name : ValidateName(), BitMap = bitMap, Strm = serializedStream, IsLongPressedEnabled = false, IsItemChecked = false, }); } (Serialization.gridview.Adapter as ImageAdapter).NotifyDataSetChanged(); } string ValidateName() { string Name = "NewItem"; int j = 1; for (int i = 0; i < (Serialization.gridview.Adapter as ImageAdapter).mItems.Count; i++) { if ((Serialization.gridview.Adapter as ImageAdapter).mItems[i].Name == Name) { Name = "NewItem " + j; j++; } } return Name; } async void RunTimer() { await DelayActionAsync(500, LoadStreamToEditor); } public async Task DelayActionAsync(int delay, Action action) { await Task.Delay(delay); action(); } void LoadStreamToEditor() { editor.LoadEdits(Serialization.ImageStream); } } public class Item : INotifyPropertyChanged { public string Name { get; set; } public ImageButton Image { get; set; } private int _resource; public int Resource { get { return _resource; } set { _resource = value; RaisePropertyChanged("Resource"); } } private bool _isLongPressedEnabled; public bool IsLongPressedEnabled { get { return _isLongPressedEnabled; } set { _isLongPressedEnabled = value; RaisePropertyChanged("IsLongPressedEnabled"); } } private bool _isItemChecked; public bool IsItemChecked { get { return _isItemChecked; } set { _isItemChecked = value; RaisePropertyChanged("IsItemChecked"); } } private bool _isDeleted; public bool ISDeleted { get { return _isDeleted; } set { _isDeleted = value; RaisePropertyChanged("ISDeleted"); } } private Bitmap _bitMap; public Bitmap BitMap { get { return _bitMap; } set { _bitMap = value; RaisePropertyChanged("BitMap"); } } private string _imageName; public string ImageName { get { return _imageName; } set { _imageName = value; RaisePropertyChanged("ImageName"); } } private Stream _stream = null; public Stream Strm { get { return _stream; } set { _stream = value; RaisePropertyChanged("Strm"); } } private string _imagestream; public string Imagestream { get { return _imagestream; } set { _imagestream = value; RaisePropertyChanged("Imagestream"); } } public event PropertyChangedEventHandler PropertyChanged; void RaisePropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public class SquareImageView : ImageView { public SquareImageView(Context context, IAttributeSet atrs) : base(context, atrs) { } public SquareImageView(Context context, IAttributeSet atrs, int defStyle) : base(context, atrs, defStyle) { } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure(widthMeasureSpec, heightMeasureSpec); SetMeasuredDimension(MeasuredWidth, MeasuredHeight); } } public class ImageAdapter : BaseAdapter { private Activity curvedActivity; public List<Item> mItems; AssetManager assets; string content; View v; public ImageAdapter(Activity curvedActivity) { assets = curvedActivity.Assets; this.curvedActivity = curvedActivity; mItems = new List<Item>(); mItems.Add(new Item { Name = "CreateNew", Resource = Resource.Drawable.CreateNew,ImageName="CreateNew",Strm=null,Imagestream = "Ban1.txt",BitMap= BitmapFactory.DecodeResource(curvedActivity.Resources,Resource.Drawable.CreateNew),IsLongPressedEnabled=false,IsItemChecked=false,ISDeleted=false}); mItems.Add(new Item { Name = "Chart", Resource = Resource.Drawable.ChartImage, ImageName = "Chart", Strm = null, Imagestream = "Chart.txt", BitMap = BitmapFactory.DecodeResource(curvedActivity.Resources, Resource.Drawable.ChartImage), IsLongPressedEnabled = false,IsItemChecked = false,ISDeleted = false}); mItems.Add(new Item { Name = "Venn Diagram", Resource = Resource.Drawable.VennImage,ImageName = "Venn",Strm=null,Imagestream = "Venn.txt", BitMap = BitmapFactory.DecodeResource(curvedActivity.Resources, Resource.Drawable.VennImage),IsLongPressedEnabled = false, IsItemChecked = false,ISDeleted = false}); mItems.Add(new Item { Name = "Freehand", Resource = Resource.Drawable.Freehand, ImageName = "Freehand", Strm = null, Imagestream = "FreeHand.txt", BitMap = BitmapFactory.DecodeResource(curvedActivity.Resources, Resource.Drawable.Freehand), IsLongPressedEnabled = false, IsItemChecked = false, ISDeleted = false }); for (int i = 0; i < mItems.Count;i++) { if (i != 0) { using (StreamReader sr = new StreamReader(assets.Open(mItems[i].Imagestream))) { content = sr.ReadToEnd(); byte[] byteArray = Encoding.ASCII.GetBytes(content); MemoryStream stream = new MemoryStream(byteArray); mItems[i].Strm = stream; } } } } public override int Count => mItems.Count; public override Java.Lang.Object GetItem(int position) { return null; } public override long GetItemId(int position) { return 0; } public override View GetView(int position, View convertView, ViewGroup parent) { v = convertView; if (v == null) { v = curvedActivity.LayoutInflater.Inflate(Resource.Layout.SerializationGriditem, null); } if (mItems[position].ImageName == "CreateNew") { v.SetBackgroundColor(Color.ParseColor("#065DC7")); v.FindViewById<ImageView>(Resource.Id.picture).SetImageBitmap(mItems[position].BitMap); v.FindViewById<TextView>(Resource.Id.text).Text = mItems[position].Name; v.FindViewById<TextView>(Resource.Id.createNew).Visibility = ViewStates.Visible; v.FindViewById<TextView>(Resource.Id.text).Visibility = ViewStates.Invisible; v.FindViewById<ImageView>(Resource.Id.itemSelected).Visibility = ViewStates.Invisible; v.FindViewById<ImageView>(Resource.Id.picture).SetScaleType(ImageView.ScaleType.Center); } else { v.SetBackgroundColor(Color.ParseColor("#ffffff")); v.FindViewById<ImageView>(Resource.Id.picture).Alpha = 1f; v.FindViewById<ImageView>(Resource.Id.picture).SetScaleType(ImageView.ScaleType.FitXy); v.FindViewById<ImageView>(Resource.Id.picture).SetImageBitmap(mItems[position].BitMap); v.FindViewById<TextView>(Resource.Id.text).Text = mItems[position].Name; v.FindViewById<TextView>(Resource.Id.createNew).Visibility = ViewStates.Invisible; v.FindViewById<TextView>(Resource.Id.text).Visibility = ViewStates.Visible; v.FindViewById<ImageView>(Resource.Id.itemSelected).Visibility = ViewStates.Invisible; } if (Serialization.isLongPressEnabled && mItems[position].ImageName != "CreateNew" && !Serialization.isDeleted) { v.SetBackgroundColor(Color.ParseColor("#ffffff")); mItems[position].IsLongPressedEnabled = true; v.FindViewById<ImageView>(Resource.Id.itemSelected).Visibility = ViewStates.Visible; } if (mItems[position].IsLongPressedEnabled && mItems[position].IsItemChecked && mItems[position].ImageName != "CreateNew" && ! Serialization.isDeleted) { v.SetBackgroundColor(Color.ParseColor("#ffffff")); v.FindViewById<ImageView>(Resource.Id.picture).Alpha = 0.5f; v.FindViewById<ImageView>(Resource.Id.itemSelected).Visibility = ViewStates.Visible; v.FindViewById<ImageView>(Resource.Id.itemSelected).SetImageResource(Resource.Drawable.Selected); } if (mItems[position].IsLongPressedEnabled && !mItems[position].IsItemChecked && mItems[position].ImageName != "CreateNew" && ! Serialization.isDeleted) { v.SetBackgroundColor(Color.ParseColor("#ffffff")); v.FindViewById<ImageView>(Resource.Id.picture).Alpha = 1f; v.FindViewById<ImageView>(Resource.Id.itemSelected).Visibility = ViewStates.Visible; v.FindViewById<ImageView>(Resource.Id.itemSelected).SetImageResource(Resource.Drawable.NotSelected); } if(Serialization.isDeleted) { v.FindViewById<ImageView>(Resource.Id.picture).Alpha = 1f; mItems[position].IsLongPressedEnabled = false; v.FindViewById<ImageView>(Resource.Id.itemSelected).Visibility = ViewStates.Invisible; } return v; } } } <file_sep>/Android/SampleBrowser/Samples/XlsIO/FiltersPage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public partial class FiltersPage : SamplePage { private Context m_context; private Spinner spinner; private LinearLayout advancedLinear1; private LinearLayout advancedLinear2; private LinearLayout advancedLinear3; private LinearLayout advancedLinear4; private LinearLayout advancedLinear5; private LinearLayout advancedLinear6; private LinearLayout linear; private Spinner spinner1; private Spinner spinner2; private Spinner spinner3; private Spinner spinner4; private Spinner spinner5; private Switch switch1; private Button button1; public override View GetSampleContent (Context con) { int numerHeight = getDimensionPixelSize(con, Resource.Dimension.numeric_txt_ht); int width = con.Resources.DisplayMetrics.WidthPixels - 40; linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to filter data within a range of Excel worksheet."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; LinearLayout subLinear = new LinearLayout(con); subLinear.Orientation = Orientation.Horizontal; TextView space2 = new TextView (con); space2.TextSize = 17; space2.TextAlignment = TextAlignment.Center; space2.Text = "Filter Type"; space2.SetTextColor(Color.ParseColor("#262626")); space2.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); subLinear.AddView (space2); string[] list = { "Custom Filter", "Text Filter", "DateTime Filter", "Dynamic Filter", "Color Filter", "Icon Filter", "Advanced Filter" }; ArrayAdapter<String> array = new ArrayAdapter<String>(con,Android.Resource.Layout.SimpleSpinnerItem , list); spinner = new Spinner (con); spinner.Adapter = array; spinner.SetSelection (1); subLinear.AddView (spinner); linear.AddView(subLinear); advancedLinear1 = new LinearLayout(con); advancedLinear1.Orientation = Orientation.Horizontal; TextView space3 = new TextView(con); space3.TextSize = 17; space3.TextAlignment = TextAlignment.Center; space3.Text = "Filter Action"; space3.SetTextColor(Color.ParseColor("#262626")); space3.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear1.AddView(space3); string[] list1 = new string[] { "Filter In Place", "Filter Copy" }; ArrayAdapter array1 = new ArrayAdapter(con, Android.Resource.Layout.SimpleSpinnerItem, list1); spinner1 = new Spinner(con); spinner1.Adapter = array1; spinner1.SetSelection(1); advancedLinear1.AddView(spinner1); advancedLinear2 = new LinearLayout(con); advancedLinear2.Orientation = Orientation.Horizontal; TextView space4 = new TextView(con); space4.TextSize = 17; space4.TextAlignment = TextAlignment.Center; space4.Text = "Unique Records"; space4.SetTextColor(Color.ParseColor("#262626")); space4.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear2.AddView(space4); linear.AddView(advancedLinear1); linear.AddView(advancedLinear2); switch1 = new Switch(con); switch1.Checked = false; advancedLinear2.AddView(switch1); advancedLinear3 = new LinearLayout(con); advancedLinear3.Orientation = Orientation.Horizontal; TextView space5 = new TextView(con); space5.TextSize = 17; space5.TextAlignment = TextAlignment.Center; space5.Text = "Color Filter Type"; space5.SetTextColor(Color.ParseColor("#262626")); space5.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear3.AddView(space5); string[] list2 = new string[] { "Font Color", "Cell Color" }; ArrayAdapter array2 = new ArrayAdapter(con, Android.Resource.Layout.SimpleSpinnerItem, list2); spinner2 = new Spinner(con); spinner2.Adapter = array2; spinner2.SetSelection(0); advancedLinear3.AddView(spinner2); advancedLinear4 = new LinearLayout(con); advancedLinear4.Orientation = Orientation.Horizontal; TextView space6 = new TextView(con); space6.TextSize = 17; space6.TextAlignment = TextAlignment.Center; space6.Text = "Color"; space6.SetTextColor(Color.ParseColor("#262626")); space6.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear4.AddView(space6); string[] list3 = new string[] { "Red", "Blue", "Green", "Yellow", "Empty" }; ArrayAdapter array3 = new ArrayAdapter(con, Android.Resource.Layout.SimpleSpinnerItem, list3); spinner3 = new Spinner(con); spinner3.Adapter = array3; spinner3.SetSelection(0); advancedLinear4.AddView(spinner3); advancedLinear5 = new LinearLayout(con); advancedLinear5.Orientation = Orientation.Horizontal; TextView space7 = new TextView(con); space7.TextSize = 17; space7.TextAlignment = TextAlignment.Center; space7.Text = "IconSet Type"; space7.SetTextColor(Color.ParseColor("#262626")); space7.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear5.AddView(space7); string[] list4 = new string[] { "ThreeSymbols", "FourRating", "FiveArrows"}; ArrayAdapter array4 = new ArrayAdapter(con, Android.Resource.Layout.SimpleSpinnerItem, list4); spinner4 = new Spinner(con); spinner4.Adapter = array4; spinner4.SetSelection(0); advancedLinear5.AddView(spinner4); advancedLinear6 = new LinearLayout(con); advancedLinear6.Orientation = Orientation.Horizontal; TextView space8 = new TextView(con); space8.TextSize = 17; space8.TextAlignment = TextAlignment.Center; space8.Text = "Icon ID"; space8.SetTextColor(Color.ParseColor("#262626")); space8.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear6.AddView(space8); string[] list5 = new string[] { "RedCrossSymbol", "YellowExclamationSymbol", "GreenCheckSymbol", "NoIcon" }; ArrayAdapter array5 = new ArrayAdapter(con, Android.Resource.Layout.SimpleSpinnerItem, list5); spinner5 = new Spinner(con); spinner5.Adapter = array5; spinner5.SetSelection(0); advancedLinear6.AddView(spinner5); string[] iconsList2 = new string[] { "SignalWithOneFillBar", "SignalWithTwoFillBars", "SignalWithThreeFillBars", "SignalWithFourFillBars", "NoIcon" }; string[] iconsList3 = new string[] { "RedDownArrow", "YellowDownInclineArrow", "YellowSideArrow", "YellowUpInclineArrow", "GreenUpArrow", "NoIcon" }; Button button = new Button(con); button.Text = "Input Template"; button.Click += OnButtonClicked1; linear.AddView(button); button1 = new Button (con); button1.Text = "Generate Excel"; button1.Click += OnButtonClicked; linear.AddView (button1); spinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = array.GetItem(e.Position); if (selectedItem.Equals("Advanced Filter")) { linear.RemoveView(button1); linear.RemoveView(button); linear.AddView(advancedLinear1); linear.AddView(advancedLinear2); linear.AddView(button); linear.AddView(button1); linear.RemoveView(advancedLinear3); linear.RemoveView(advancedLinear4); linear.RemoveView(advancedLinear5); linear.RemoveView(advancedLinear6); } else if(selectedItem.Equals("Icon Filter")) { linear.RemoveView(button); linear.RemoveView(button1); linear.RemoveView(advancedLinear1); linear.RemoveView(advancedLinear2); linear.RemoveView(advancedLinear3); linear.RemoveView(advancedLinear4); linear.AddView(advancedLinear5); linear.AddView(advancedLinear6); linear.AddView(button); linear.AddView(button1); } else if(selectedItem.Equals("Color Filter")) { linear.RemoveView(button); linear.RemoveView(button1); linear.RemoveView(advancedLinear1); linear.RemoveView(advancedLinear2); linear.RemoveView(advancedLinear5); linear.RemoveView(advancedLinear6); linear.AddView(advancedLinear3); linear.AddView(advancedLinear4); linear.AddView(button); linear.AddView(button1); } else { linear.RemoveView(advancedLinear1); linear.RemoveView(advancedLinear2); linear.RemoveView(advancedLinear3); linear.RemoveView(advancedLinear4); linear.RemoveView(advancedLinear5); linear.RemoveView(advancedLinear6); } }; spinner4.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { if (spinner4.SelectedItemPosition == 0) spinner5.Adapter = new ArrayAdapter(con, Android.Resource.Layout.SimpleSpinnerItem, list5); else if (spinner4.SelectedItemPosition == 1) spinner5.Adapter = new ArrayAdapter(con, Android.Resource.Layout.SimpleSpinnerItem, iconsList2); else if (spinner4.SelectedItemPosition == 2) spinner5.Adapter = new ArrayAdapter(con, Android.Resource.Layout.SimpleSpinnerItem, iconsList3); }; return linear; } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; int index = spinner.SelectedItemPosition; #region Initializing Workbook string resourcePath = ""; if (index == 6) resourcePath = "SampleBrowser.Samples.XlsIO.Template.AdvancedFilterData.xlsx"; else if (index == 5) resourcePath = "SampleBrowser.Samples.XlsIO.Template.IconFilterData.xlsx"; else if (index == 4) resourcePath = "SampleBrowser.Samples.XlsIO.Template.FilterData_Color.xlsx"; else resourcePath = "SampleBrowser.Samples.XlsIO.Template.FilterData.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly (); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; sheet["A60"].Activate(); #endregion if (index!=6) sheet.AutoFilters.FilterRange = sheet.Range[1, 1, 49, 3]; string fileName = ""; switch(index) { case 0: fileName = "CustomFilter.xlsx"; IAutoFilter filter1 = sheet.AutoFilters[0]; filter1.IsAnd = false; filter1.FirstCondition.ConditionOperator = ExcelFilterCondition.Equal; filter1.FirstCondition.DataType = ExcelFilterDataType.String; filter1.FirstCondition.String = "Owner"; filter1.SecondCondition.ConditionOperator = ExcelFilterCondition.Equal; filter1.SecondCondition.DataType = ExcelFilterDataType.String; filter1.SecondCondition.String = "Sales Representative"; break; case 1: fileName = "TextFilter.xlsx"; IAutoFilter filter2 = sheet.AutoFilters[0]; filter2.AddTextFilter(new string[] { "Owner", "Sales Representative", "Sales Associate" }); break; case 2: fileName = "DateTimeFilter.xlsx"; IAutoFilter filter3 = sheet.AutoFilters[1]; filter3.AddDateFilter(new DateTime(2004, 9, 1, 1, 0, 0, 0), DateTimeGroupingType.month); filter3.AddDateFilter(new DateTime(2011, 1, 1, 1, 0, 0, 0), DateTimeGroupingType.year); break; case 3: fileName = "DynamicFilter.xlsx"; IAutoFilter filter4 = sheet.AutoFilters[1]; filter4.AddDynamicFilter(DynamicFilterType.Quarter1); break; case 4: fileName = "Color Filter.xlsx"; #region ColorFilter sheet.AutoFilters.FilterRange = sheet["A1:C49"]; Syncfusion.Drawing.Color color = Syncfusion.Drawing.Color.Empty; switch (spinner3.SelectedItemPosition) { case 0: color = Syncfusion.Drawing.Color.Red; break; case 1: color = Syncfusion.Drawing.Color.Blue; break; case 2: color = Syncfusion.Drawing.Color.Green; break; case 3: color = Syncfusion.Drawing.Color.Yellow; break; case 4: color = Syncfusion.Drawing.Color.Empty; break; } if(spinner2.SelectedItemPosition == 0) { IAutoFilter filter = sheet.AutoFilters[2]; filter.AddColorFilter(color, ExcelColorFilterType.FontColor); } else { IAutoFilter filter = sheet.AutoFilters[0]; filter.AddColorFilter(color, ExcelColorFilterType.CellColor); } #endregion break; case 5: fileName = "IconFilter.xlsx"; #region IconFilter sheet.AutoFilters.FilterRange = sheet["A4:D44"]; ExcelIconSetType iconSet = ExcelIconSetType.FiveArrows; int filterIndex = 0; int iconId = 0; switch(spinner4.SelectedItemPosition) { case 0: filterIndex = 3; iconSet = ExcelIconSetType.ThreeSymbols; break; case 1: filterIndex = 1; iconSet = ExcelIconSetType.FourRating; break; case 2: filterIndex = 2; iconSet = ExcelIconSetType.FiveArrows; break; } switch (spinner5.SelectedItemPosition) { case 0: iconId = 0; break; case 1: iconId = 1; break; case 2: iconId = 2; break; case 3: if (spinner4.SelectedItemPosition == 0) iconSet = (ExcelIconSetType)(-1); else iconId = 3; break; case 4: if (spinner4.SelectedItemPosition == 1) iconSet = (ExcelIconSetType)(-1); else iconId = 4; break; case 5: iconSet = (ExcelIconSetType)(-1); break; } IAutoFilter filter5 = sheet.AutoFilters[filterIndex]; filter5.AddIconFilter(iconSet, iconId); #endregion break; case 6: #region AdvancedFilter fileName = "AdvancedFilter.xlsx"; IRange filterRange = sheet.Range["A8:G51"]; IRange criteriaRange = sheet.Range["A2:B5"]; if (spinner1.SelectedItemPosition == 0) { sheet.AdvancedFilter(ExcelFilterAction.FilterInPlace, filterRange, criteriaRange, null, switch1.Checked); } else { IRange range = sheet.Range["I7:O7"]; range.Merge(); range.Text = "FilterCopy"; range.CellStyle.Font.RGBColor = Syncfusion.Drawing.Color.FromArgb(0, 112, 192); range.HorizontalAlignment = ExcelHAlign.HAlignCenter; range.CellStyle.Font.Bold = true; IRange copyRange = sheet.Range["I8"]; sheet.AdvancedFilter(ExcelFilterAction.FilterCopy, filterRange, criteriaRange, copyRange, switch1.Checked); } #endregion break; } workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save (fileName, "application/msexcel", stream, m_context); } } void OnButtonClicked1(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; int index = spinner.SelectedItemPosition; string resourcePath = ""; if (index == 6) resourcePath = "SampleBrowser.Samples.XlsIO.Template.AdvancedFilterData.xlsx"; else if (index == 5) resourcePath = "SampleBrowser.Samples.XlsIO.Template.IconFilterData.xlsx"; else if (index == 4) resourcePath = "SampleBrowser.Samples.XlsIO.Template.FilterData_Color.xlsx"; else resourcePath = "SampleBrowser.Samples.XlsIO.Template.FilterData.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); IWorksheet sheet = workbook.Worksheets[0]; workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("Input Template.xlsx", "application/msexcel", stream, m_context); } } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } } } <file_sep>/Forms/Chat/Chat/Samples/GettingStarted/GettingStartedBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.BadgeView; using Syncfusion.XForms.Chat; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfChat { /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the getting started sample. /// </summary public class GettingStartedBehavior : Behavior<SampleView> { #region Fields /// <summary> /// flight booking view model. /// </summary> private GettingStartedViewModel viewModel; /// <summary> /// flight booking view model. /// </summary> private int unReadMessageCount; /// <summary> /// sfChat control instance. /// </summary> private Syncfusion.XForms.Chat.SfChat sfChat; /// <summary> /// sfBadgeView control instance. /// </summary> private Syncfusion.XForms.BadgeView.SfBadgeView sfBadgeView; /// <summary> /// sfBadgeView badge settings instance. /// </summary> private Syncfusion.XForms.BadgeView.BadgeSetting badgeSetting; /// <summary> /// The page that hosts the load more sameple. /// </summary> private SampleView sampleView; /// <summary> /// Tap gesture for the badge view. /// </summary> private TapGestureRecognizer tap; #endregion protected override void OnAttachedTo(SampleView bindable) { base.OnAttachedTo(bindable); tap = new TapGestureRecognizer(); tap.Tapped += ScrollToBottom; this.sampleView = bindable; this.sfChat = bindable.FindByName<Syncfusion.XForms.Chat.SfChat>("sfChat"); this.viewModel = bindable.FindByName<GettingStartedViewModel>("viewModel"); this.sfBadgeView = bindable.FindByName<Syncfusion.XForms.BadgeView.SfBadgeView>("ScrollDown"); this.sfBadgeView.GestureRecognizers.Add(tap); this.viewModel.Messages.CollectionChanged += MessageCollectionChanged; this.sfChat.Scrolled += ChatScrolled; badgeSetting = new Syncfusion.XForms.BadgeView.BadgeSetting(); badgeSetting.BadgeType = Syncfusion.XForms.BadgeView.BadgeType.Primary; badgeSetting.BadgeAnimation = Syncfusion.XForms.BadgeView.BadgeAnimation.None; badgeSetting.BadgePosition = Syncfusion.XForms.BadgeView.BadgePosition.TopLeft; if (Device.RuntimePlatform == "Android") { badgeSetting.Offset = new Point(-1, 1); } else if (Device.RuntimePlatform == "UWP") { badgeSetting.Offset = new Point(-7, -10); } else badgeSetting.Offset = new Point(0, -1); sfBadgeView.WidthRequest = 60; badgeSetting.FontSize = 10; sfBadgeView.BadgeSettings = badgeSetting; } /// <summary> /// Raised when the chat scrolled. /// </summary> /// <param name="sender">The object as sender.</param> /// <param name="e">ChatScrolledEventArgs as e.</param> private void ChatScrolled(object sender, ChatScrolledEventArgs e) { sfChat.CanAutoScrollToBottom = e.IsBottomReached; viewModel.IsBadgeViewVisible = !e.IsBottomReached; if (e.IsBottomReached) { sfBadgeView.BadgeText = string.Empty; this.unReadMessageCount = 0; } } /// <summary> /// Raised when the image button tapped. /// </summary> /// <param name="sender">The object as sender.</param> /// <param name="e">EventArgs as e.</param> private void ScrollToBottom(object sender, EventArgs e) { this.viewModel.IsBadgeViewVisible = false; this.sfChat.ScrollToMessage(sfChat.Messages[sfChat.Messages.Count - 1]); } /// <summary> /// Raised when the viewmodel message collection changed. /// </summary> /// <param name="sender">The object as sender.</param> /// <param name="e">NotifyCollectionChangedEventArgs as e.</param> private void MessageCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach (var chatItem in e.NewItems) { if ((chatItem as TextMessage) != null && viewModel.IsBadgeViewVisible) { this.unReadMessageCount++; sfBadgeView.BadgeText = this.unReadMessageCount.ToString(); } } } } /// <summary> /// Clears the instances used in this sample. /// </summary> private void Dispose() { this.sfChat.Scrolled -= ChatScrolled; if (this.sfChat != null) { this.sfChat.Dispose(); this.sfChat = null; } if (this.viewModel != null) { this.viewModel = null; } } /// <summary> /// Method will be called when the view is detached from window /// </summary> /// <param name="bindable">SampleView type of bindAble parameter</param> protected override void OnDetachingFrom(BindableObject bindable) { this.Dispose(); this.tap.Tapped -= ScrollToBottom; this.tap = null; base.OnDetachingFrom(bindable); } } } <file_sep>/Android/SampleBrowser/Samples/NavigationDrawer/NavigationDrawer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Android.Util; #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Com.Syncfusion.Navigationdrawer; namespace SampleBrowser { [Activity(Label = "NavigationDrawer")] public class NavigationDrawer : SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ LinearLayout inboxLayout, mail1, mail2, mail3, mail4, mail9, mail10, mail11,mail18, mail19, mail20; LinearLayout secondaryDrawerLayout, Item1, Item2, Item3, Item4, Item5, Item6, Item7; LinearLayout ItemLayout1, ItemLayout2, ItemLayout3, ItemLayout4, ItemLayout5, ItemLayout6, ItemLayout7; LinearLayout.LayoutParams layoutParams5, layoutParams,layoutParamsSecondaryDrawer; SeparatorView separatorView1, separatorView2, separatorView3, separatorView4, separatorView5, separatorView6, separatorView7; SeparatorView labelSeparator4, labelSeparator3, labelSeparator5; SeparatorView labelSeparator6, labelSeparator7, labelSeparator8, labelSeparator9,labelSeparator18, labelSeparator19, labelSeparator20; LinearLayout outboxlayout, mail12, mail13, mail14, mail15, mail16, mail17; LinearLayout mail5, mail6, profilelayout, linear2; SeparatorView labelSeparator10, labelSeparator11, labelSeparator12, labelSeparator13; SeparatorView labelSeparator14, labelSeparator15, labelSeparator16, labelSeparator17; Button iconbutton,iconbutton1; ListView viewItem; SfNavigationDrawer slideDrawer; DrawerSettings drawerSettings; LinearLayout propertylayout; ArrayAdapter<String> dataAdapter, dataAdapter1, arrayAdapter, dataAdapter2, dataAdapter3; Spinner positionSpinner,positionSpinner1, animationSpinner, animationSpinner1; Position sliderposition = Position.Left,sliderposition1 = Position.Right; Transition sliderTransition = Transition.SlideOnTop,sliderTransition1 = Transition.SlideOnTop; Context context; int height, width; double actionBarHeight; TextView profileContentLabel; FrameLayout ContentFrame; ScrollView textScroller,textScroller1, textScroller2; public override void OnApplyChanges() { base.OnApplyChanges(); slideDrawer.Position = sliderposition; slideDrawer.Transition = sliderTransition; slideDrawer.SecondaryDrawerSettings.Position = sliderposition1; slideDrawer.SecondaryDrawerSettings.Transition = sliderTransition1; } public override View GetPropertyWindowLayout(Context context) { int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; layoutParams = new LinearLayout.LayoutParams(width * 2, 3); layoutParams.SetMargins(0, 20, 0, 0); positionLabelLayout(); AnimationLayout(); return propertylayout; } private void positionLabelLayout() { //cultureLabel TextView cultureLabel = new TextView(context); cultureLabel.TextSize = 20; cultureLabel.Text = "Default Drawer Position"; TextView cultureLabel1 = new TextView(context); cultureLabel1.TextSize = 20; cultureLabel1.Text = " Secondary Drawer Position"; //positionlist List<String> positionlist = new List<String>(); positionlist.Add("Left"); positionlist.Add("Right"); positionlist.Add("Top"); positionlist.Add("Bottom"); List<String> positionlist1 = new List<String>(); positionlist1.Add("Left"); positionlist1.Add("Right"); positionlist1.Add("Top"); positionlist1.Add("Bottom"); //dataAdapter dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, positionlist); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); dataAdapter2 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, positionlist1); dataAdapter2.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //positionSpinner positionSpinner = new Spinner(context,SpinnerMode.Dialog); positionSpinner.SetGravity(GravityFlags.Left); positionSpinner.Adapter = dataAdapter; positionSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Left")) { sliderposition = Position.Left; } if (selectedItem.Equals("Right")) { sliderposition = Position.Right; } if (selectedItem.Equals("Top")) { sliderposition = Position.Top; } if (selectedItem.Equals("Bottom")) { sliderposition = Position.Bottom; } }; positionSpinner1 = new Spinner(context, SpinnerMode.Dialog); positionSpinner1.SetGravity(GravityFlags.Left); positionSpinner1.Adapter = dataAdapter2; positionSpinner1.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter2.GetItem(e.Position); if (selectedItem.Equals("Left")) { sliderposition1 = Position.Left; } if (selectedItem.Equals("Right")) { sliderposition1 = Position.Right; } if (selectedItem.Equals("Top")) { sliderposition1 = Position.Top; } if (selectedItem.Equals("Bottom")) { sliderposition1 = Position.Bottom; } }; propertylayout.AddView(cultureLabel); propertylayout.AddView(positionSpinner); propertylayout.AddView(cultureLabel1); propertylayout.AddView(positionSpinner1); //labelSeparator SeparatorView labelSeparator = new SeparatorView(context, width * 2); labelSeparator.separatorColor = Color.LightGray; labelSeparator.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); //propertylayout.AddView(labelSeparator, layoutParams); } private void AnimationLayout() { //cultureLabel1 TextView cultureLabel1 = new TextView(context); cultureLabel1.TextSize = 20; cultureLabel1.Text = "Default Drawer Animations"; //cultureLabel2 TextView cultureLabel2 = new TextView(context); cultureLabel2.TextSize = 20; cultureLabel2.Text = "Secondary Drawer Animations"; //transitionlist List<String> transitionlist = new List<String>(); transitionlist.Add("SlideOnTop"); transitionlist.Add("Reveal"); transitionlist.Add("Push"); //transitionlist List<String> transitionlist1 = new List<String>(); transitionlist1.Add("SlideOnTop"); transitionlist1.Add("Reveal"); transitionlist1.Add("Push"); //dataAdapter1 dataAdapter1 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, transitionlist); dataAdapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); ; dataAdapter3 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, transitionlist1); dataAdapter3.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); ; //animationSpinner animationSpinner = new Spinner(context,SpinnerMode.Dialog); animationSpinner.SetGravity(GravityFlags.Left); animationSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter1.GetItem(e.Position); if (selectedItem.Equals("SlideOnTop")) { sliderTransition = Transition.SlideOnTop; } if (selectedItem.Equals("Reveal")) { sliderTransition = Transition.Reveal; } if (selectedItem.Equals("Push")) { sliderTransition = Transition.Push; } }; animationSpinner1 = new Spinner(context, SpinnerMode.Dialog); animationSpinner1.SetGravity(GravityFlags.Left); animationSpinner1.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter3.GetItem(e.Position); if (selectedItem.Equals("SlideOnTop")) { sliderTransition1 = Transition.SlideOnTop; } if (selectedItem.Equals("Reveal")) { sliderTransition1 = Transition.Reveal; } if (selectedItem.Equals("Push")) { sliderTransition1 = Transition.Push; } }; TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); animationSpinner.Adapter = dataAdapter1; animationSpinner1.Adapter = dataAdapter3; propertylayout.AddView(cultureLabel1); propertylayout.AddView(animationSpinner); propertylayout.AddView(cultureLabel2); propertylayout.AddView(animationSpinner1); //labelSeparator1 SeparatorView labelSeparator1 = new SeparatorView(context, width * 2); labelSeparator1.separatorColor = Color.LightGray; labelSeparator1.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); //propertylayout.AddView(labelSeparator1, layoutParams); propertylayout.SetPadding(5, 0, 5, 0); } public override View GetSampleContent(Context context1) { context = context1; IconButtonLayout(); HomeContentLayout(); MainContentLayout(); ProfileContentLayout(); InboxContentLayout(); SecondaryDrawerLayout(); OutBoxLayout(); ClickListenerLayout(); return slideDrawer; } private void IconButtonLayout() { //iconbutton iconbutton = new Button(context); iconbutton.SetBackgroundResource(Resource.Drawable.burgericon); FrameLayout.LayoutParams btlayoutParams = new FrameLayout.LayoutParams(getDimensionPixelSize(context, Resource.Dimension.nav_drawer_btn_wt), getDimensionPixelSize(context, Resource.Dimension.nav_drawer_btn_ht), GravityFlags.Center); iconbutton.LayoutParameters = btlayoutParams; iconbutton.SetPadding(10, 0, 0, 0); if (context.Resources.DisplayMetrics.Density > 1.5) { iconbutton.SetX(10); } iconbutton.Gravity = GravityFlags.CenterVertical; iconbutton1 = new Button(context); Typeface tf = Typeface.CreateFromAsset(context.Assets, "Segoe_MDL2_Assets.ttf"); iconbutton1.Text = "\uE823"; iconbutton1.Typeface = tf; iconbutton1.SetTextColor(Color.White); iconbutton1.SetBackgroundColor(Color.Rgb(47, 173, 227)); FrameLayout.LayoutParams btlayoutParams1 = new FrameLayout.LayoutParams(getDimensionPixelSize(context, Resource.Dimension.nav_drawer_btn_wt), getDimensionPixelSize(context, Resource.Dimension.nav_drawer_btn_ht), GravityFlags.Center); iconbutton1.LayoutParameters = btlayoutParams1; iconbutton1.SetPadding(10, 0, 0, 0); if (context.Resources.DisplayMetrics.Density > 1.5) { iconbutton1.SetX(10); } iconbutton1.Gravity = GravityFlags.CenterVertical; } private void HomeContentLayout() { //HomeLabel profileContentLabel = new TextView(context); profileContentLabel.TextSize = 20; profileContentLabel.Text = "Home"; profileContentLabel.SetTextColor(Color.White); profileContentLabel.Gravity = GravityFlags.Center; //linearLayout LinearLayout linearLayout = new LinearLayout(context); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams((int)(context.Resources.DisplayMetrics.WidthPixels - (68 * context.Resources.DisplayMetrics.Density)), getDimensionPixelSize(context, Resource.Dimension.nav_drawer_header_ht), GravityFlags.Center); layoutParams.SetMargins(10, 0, 0, 0); linearLayout.SetPadding(10, 0, 0, 0); linearLayout.AddView(iconbutton); linearLayout.AddView(profileContentLabel, layoutParams); linearLayout.AddView(iconbutton1); linearLayout.SetBackgroundColor(Color.Rgb(47, 173, 227)); TypedValue tv = new TypedValue(); if (context.Theme.ResolveAttribute(Android.Resource.Attribute.ActionBarSize, tv, true)) { actionBarHeight = TypedValue.ComplexToDimensionPixelSize(tv.Data, context.Resources.DisplayMetrics); } height = Convert.ToInt32(context.Resources.DisplayMetrics.HeightPixels - actionBarHeight); width = context.Resources.DisplayMetrics.WidthPixels; //linear2 linear2 = new LinearLayout(context); linear2.Orientation = Orientation.Vertical; linear2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); FrameLayout.LayoutParams layout2 = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); linear2.AddView(linearLayout, layout2); } private void MainContentLayout() { //textScroller textScroller = new ScrollView(context); textScroller.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); //textView TextView textView = new TextView(context); textView.Text = "\n \t Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus. Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet. Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula. Lorem tortor neque, purus taciti quis id. Elementum integer orci accumsan minim phasellus vel."; textView.TextSize = 16; textView.SetPadding(20, 0, 20, 0); textScroller.AddView(textView); ContentFrame = new FrameLayout(context); ContentFrame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); ContentFrame.SetBackgroundColor(Color.White); ContentFrame.AddView(textScroller); textScroller.SetBackgroundColor(Color.White); linear2.AddView(ContentFrame); //contentLayout LinearLayout contentLayout = new LinearLayout(context); RoundedImageView roundedImg = new RoundedImageView(context, getDimensionPixelSize(context, Resource.Dimension.nav_drawer_imd_size), getDimensionPixelSize(context, Resource.Dimension.nav_drawer_imd_size)); roundedImg.SetPadding(0, 10, 0, 10); roundedImg.SetImageResource(Resource.Drawable.user); LinearLayout.LayoutParams layparams8 = new LinearLayout.LayoutParams(getDimensionPixelSize(context, Resource.Dimension.nav_drawer_imd_size), getDimensionPixelSize(context, Resource.Dimension.nav_drawer_imd_size)); layparams8.Gravity = GravityFlags.Center; roundedImg.LayoutParameters = new ViewGroup.LayoutParams(getDimensionPixelSize(context, Resource.Dimension.nav_drawer_imd_size), getDimensionPixelSize(context, Resource.Dimension.nav_drawer_imd_size)); //userNameLabel1 TextView userNameLabel1 = new TextView(context); userNameLabel1.Text = "<NAME>"; userNameLabel1.Gravity = GravityFlags.Center; userNameLabel1.TextSize = 17; userNameLabel1.SetTextColor(Color.White); userNameLabel1.SetPadding(0, 20, 0, 0); userNameLabel1.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); //headerLayout LinearLayout headerLayout = new LinearLayout(context); headerLayout.Orientation = Orientation.Vertical; headerLayout.SetBackgroundColor(Color.Rgb(47, 173, 227)); headerLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, getDimensionPixelSize(context, Resource.Dimension.nav_drawer_slider_ht)); headerLayout.SetGravity(GravityFlags.Center); headerLayout.AddView(roundedImg, layparams8); headerLayout.AddView(userNameLabel1); LinearLayout.LayoutParams layparams2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(height * 0.15)); layparams2.Gravity = GravityFlags.Center; contentLayout.AddView(headerLayout); LinearLayout.LayoutParams layparams5 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (2)); contentLayout.AddView(new SeparatorView(context, width) { separatorColor = Color.LightGray }, layparams5); contentLayout.SetBackgroundColor(Color.White); linear2.SetBackgroundColor(Color.White); //slideDrawer slideDrawer = new Com.Syncfusion.Navigationdrawer.SfNavigationDrawer(context); slideDrawer.ContentView = linear2; slideDrawer.DrawerWidth = (float)(200); slideDrawer.DrawerHeight = (float)(300); slideDrawer.Transition = Transition.SlideOnTop; slideDrawer.TouchThreshold = 90; slideDrawer.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); viewItem = new ListView(context); viewItem.VerticalScrollBarEnabled = true; iconbutton.Click += (object sender, EventArgs e) => { slideDrawer.ToggleDrawer(); }; iconbutton1.Click += (object sender, EventArgs e) => { slideDrawer.ToggleSecondaryDrawer(); }; //positionlist List<String> positionlist = new List<String>(); positionlist.Add("Home"); positionlist.Add("Profile"); positionlist.Add("Inbox"); positionlist.Add("Outbox"); positionlist.Add("Sent Items"); positionlist.Add("Trash"); arrayAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleListItem1, positionlist); viewItem.Adapter = arrayAdapter; viewItem.SetBackgroundColor(Color.White); viewItem.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); contentLayout.AddView(viewItem); contentLayout.Orientation = Orientation.Vertical; //frameLayout FrameLayout frameLayout = new FrameLayout(context); frameLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); frameLayout.SetBackgroundColor(Color.White); frameLayout.AddView(contentLayout); slideDrawer.DrawerContentView = frameLayout; } private void ProfileContentLayout() { //profilelayout profilelayout = new LinearLayout(context); profilelayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); profilelayout.Orientation = Orientation.Vertical; LinearLayout linearLayout2 = new LinearLayout(context); linearLayout2.SetGravity(GravityFlags.Center); linearLayout2.SetPadding(0, 30, 0, 30); linearLayout2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); RoundedImageView roundedImg1 = new RoundedImageView(context, getDimensionPixelSize(context, Resource.Dimension.nav_drawer_prof_ht), getDimensionPixelSize(context, Resource.Dimension.nav_drawer_prof_ht)); roundedImg1.LayoutParameters = new ViewGroup.LayoutParams(getDimensionPixelSize(context, Resource.Dimension.nav_drawer_prof_ht), getDimensionPixelSize(context, Resource.Dimension.nav_drawer_prof_ht)); roundedImg1.SetImageResource(Resource.Drawable.user); LinearLayout txtlayout = new LinearLayout(context); txtlayout.SetPadding(40, 0, 0, 0); txtlayout.Orientation = Orientation.Vertical; //userNameLabel2 TextView userNameLabel2 = new TextView(context); userNameLabel2.TextSize = 20; userNameLabel2.Text = "JamesPollock"; userNameLabel2.SetTextColor(Color.Black); //userAgeLabel TextView userAgeLabel = new TextView(context); userAgeLabel.Text = "Age 30"; userAgeLabel.TextSize = 13; userAgeLabel.SetTextColor(Color.Black); //txtlayout txtlayout.AddView(userNameLabel2); txtlayout.AddView(userAgeLabel); linearLayout2.AddView(roundedImg1); linearLayout2.AddView(txtlayout); linearLayout2.SetBackgroundColor(Color.White); profilelayout.AddView(linearLayout2); profilelayout.Orientation = Orientation.Vertical; //separatorparams FrameLayout.LayoutParams separatorparams = new FrameLayout.LayoutParams(width, 2, GravityFlags.Center); SeparatorView labelSeparator2 = new SeparatorView(context, width); labelSeparator2.separatorColor = Color.LightGray; labelSeparator2.SetPadding(20, 0, 20, 20); profilelayout.AddView(labelSeparator2, separatorparams); //profiledescriptionLabel TextView profiledescriptionLabel = new TextView(context); profiledescriptionLabel.TextSize = 16; profiledescriptionLabel.SetPadding(20, 0, 20, 0); profiledescriptionLabel.SetBackgroundColor(Color.White); profiledescriptionLabel.Text = "\n" + "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.\n" + "\n" + "\n" + "when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.\n" + "\n" + "\n" + "<NAME>"; profilelayout.AddView(profiledescriptionLabel); profilelayout.SetBackgroundColor(Color.White); } private void InboxContentLayout() { LinearLayout ContentLayout = new LinearLayout(context); ContentLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); TextView date = new TextView(context); date.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); date.Text = "Jan 17"; date.Typeface = Typeface.DefaultBold; date.SetTextColor(Color.ParseColor("#006BCD")); date.Gravity = GravityFlags.End; //inboxLayout inboxLayout = new LinearLayout(context); inboxLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); inboxLayout.SetBackgroundColor(Color.White); inboxLayout.Orientation = Orientation.Vertical; mail1 = new LinearLayout(context); //userNameLabel3 TextView userNameLabel3 = new TextView(context); userNameLabel3.Text = "John"; userNameLabel3.Typeface = Typeface.DefaultBold; userNameLabel3.TextSize = 15; userNameLabel3.Gravity = GravityFlags.Start; TextView updateLabel1 = new TextView(context); updateLabel1.Text = "Goto Meeting"; updateLabel1.Typeface = Typeface.DefaultBold; updateLabel1.SetTextColor(Color.ParseColor("#006BCD")); updateLabel1.TextSize = 13; TextView messageLabel1 = new TextView(context); messageLabel1.Text = "Join meeting to discuss about daily status,workflow,pending work and improve process"; TextView spaceText1 = new TextView(context); spaceText1.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text1 = new TextView(context); Text1.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); //labelSeparator3 labelSeparator3 = new SeparatorView(context, width * 2); labelSeparator3.separatorColor = Color.LightGray; labelSeparator3.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); //layoutParams5 layoutParams5 = new LinearLayout.LayoutParams(width * 2, 3); layoutParams5.SetMargins(0, 10, 15, 0); messageLabel1.TextSize = 12; ContentLayout.AddView(userNameLabel3); ContentLayout.AddView(date); mail1.AddView(ContentLayout); mail1.AddView(spaceText1); mail1.AddView(updateLabel1); mail1.AddView(Text1); mail1.AddView(messageLabel1); //mail2 LinearLayout ContentLayout1 = new LinearLayout(context); ContentLayout1.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); TextView date1 = new TextView(context); date1.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); date1.Text = "Jan 8"; date1.Typeface = Typeface.DefaultBold; date1.SetTextColor(Color.ParseColor("#006BCD")); date1.Gravity = GravityFlags.End; mail2 = new LinearLayout(context); TextView userNameLabel4 = new TextView(context); userNameLabel4.Text = "Caster"; userNameLabel4.Typeface = Typeface.DefaultBold; userNameLabel4.TextSize = 15; TextView updateLabel2 = new TextView(context); updateLabel2.Text = "FW:Status Update"; updateLabel2.Typeface = Typeface.DefaultBold; updateLabel2.SetTextColor(Color.ParseColor("#006BCD")); updateLabel2.TextSize = 13; TextView messageLabel2 = new TextView(context); messageLabel2.Text = "Hi, Please find the today's status"; messageLabel2.TextSize = 12; TextView spaceText2 = new TextView(context); spaceText2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text2 = new TextView(context); Text2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); ContentLayout1.AddView(userNameLabel4); ContentLayout1.AddView(date1); mail2.AddView(ContentLayout1); mail2.AddView(spaceText2); mail2.AddView(updateLabel2); mail2.AddView(Text2); mail2.AddView(messageLabel2); labelSeparator4 = new SeparatorView(context, width * 2); labelSeparator4.separatorColor = Color.LightGray; labelSeparator4.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //mail3 LinearLayout ContentLayout2 = new LinearLayout(context); ContentLayout2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); TextView date2 = new TextView(context); date2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); date2.Text = "Mar 9"; date2.Typeface = Typeface.DefaultBold; date2.SetTextColor(Color.ParseColor("#006BCD")); date2.Gravity = GravityFlags.End; mail3 = new LinearLayout(context); TextView userNameLabel5 = new TextView(context); userNameLabel5.Text = "Joey"; userNameLabel5.Typeface = Typeface.DefaultBold; userNameLabel5.TextSize = 15; TextView updateLabel3 = new TextView(context); updateLabel3.Text = "Greetings! Congrats"; updateLabel3.Typeface = Typeface.DefaultBold; updateLabel3.SetTextColor(Color.ParseColor("#006BCD")); updateLabel3.TextSize = 13; TextView messageLabel3 = new TextView(context); messageLabel3.Text = "Hi, Congrats you have won the raffle"; messageLabel3.TextSize = 12; TextView spaceText3 = new TextView(context); spaceText3.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text3 = new TextView(context); Text3.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); ContentLayout2.AddView(userNameLabel5); ContentLayout2.AddView(date2); mail3.AddView(ContentLayout2); mail3.AddView(spaceText3); mail3.AddView(updateLabel3); mail3.AddView(Text3); mail3.AddView(messageLabel3); labelSeparator5 = new SeparatorView(context, width * 2); labelSeparator5.separatorColor = Color.LightGray; labelSeparator5.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //mail4 LinearLayout ContentLayout3 = new LinearLayout(context); ContentLayout3.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); TextView date3 = new TextView(context); date3.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); date3.Text = "Apr 10"; date3.Typeface = Typeface.DefaultBold; date3.SetTextColor(Color.ParseColor("#006BCD")); date3.Gravity = GravityFlags.End; mail4 = new LinearLayout(context); TextView userNameLabel6 = new TextView(context); userNameLabel6.Text = "Xavier"; userNameLabel6.Typeface = Typeface.DefaultBold; userNameLabel6.TextSize = 15; TextView updateLabel4 = new TextView(context); updateLabel4.Text = "Report Monitor"; updateLabel4.Typeface = Typeface.DefaultBold; updateLabel4.SetTextColor(Color.ParseColor("#006BCD")); updateLabel4.TextSize = 13; TextView messageLabel4 = new TextView(context); messageLabel4.Text = "Do not reply, Please find the attachment. Attachment have the full details of monitor report with timing"; messageLabel4.TextSize = 12; TextView spaceText4 = new TextView(context); spaceText4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text4 = new TextView(context); Text4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); ContentLayout3.AddView(userNameLabel6); ContentLayout3.AddView(date3); mail4.AddView(ContentLayout3); mail4.AddView(spaceText4); mail4.AddView(updateLabel4); mail4.AddView(Text4); mail4.AddView(messageLabel4); labelSeparator6 = new SeparatorView(context, width * 2); labelSeparator6.separatorColor = Color.LightGray; labelSeparator6.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //mail9 LinearLayout ContentLayout4 = new LinearLayout(context); ContentLayout4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); TextView date4 = new TextView(context); date4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); date4.Text = "May 11"; date4.Typeface = Typeface.DefaultBold; date4.SetTextColor(Color.ParseColor("#006BCD")); date4.Gravity = GravityFlags.End; mail9 = new LinearLayout(context); TextView userNameLabel7 = new TextView(context); userNameLabel7.Text = "Gonzalez"; userNameLabel7.Typeface = Typeface.DefaultBold; userNameLabel7.TextSize = 15; TextView updateLabel5 = new TextView(context); updateLabel5.Text = "News Letter"; updateLabel5.Typeface = Typeface.DefaultBold; updateLabel5.SetTextColor(Color.ParseColor("#006BCD")); updateLabel5.TextSize = 13; TextView messageLabel5 = new TextView(context); messageLabel5.Text = "Hi, Please find the attached news letter"; messageLabel5.TextSize = 12; TextView spaceText5 = new TextView(context); spaceText5.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text5 = new TextView(context); Text5.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); ContentLayout4.AddView(userNameLabel7); ContentLayout4.AddView(date4); mail9.AddView(ContentLayout4); mail9.AddView(spaceText5); mail9.AddView(updateLabel5); mail9.AddView(Text5); mail9.AddView(messageLabel5); labelSeparator7 = new SeparatorView(context, width * 2); labelSeparator7.separatorColor = Color.LightGray; labelSeparator7.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //mail10 LinearLayout ContentLayout5 = new LinearLayout(context); ContentLayout5.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); TextView date5 = new TextView(context); date5.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); date5.Text = "May 12"; date5.Typeface = Typeface.DefaultBold; date5.SetTextColor(Color.ParseColor("#006BCD")); date5.Gravity = GravityFlags.End; mail10 = new LinearLayout(context); TextView userNameLabel8 = new TextView(context); userNameLabel8.Text = "Rodriguez"; userNameLabel8.Typeface = Typeface.DefaultBold; userNameLabel8.TextSize = 15; TextView updateLabel6 = new TextView(context); updateLabel6.Text = "Conference about Latest Technology"; updateLabel6.Typeface = Typeface.DefaultBold; updateLabel6.SetTextColor(Color.ParseColor("#006BCD")); updateLabel6.TextSize = 13; TextView messageLabel6 = new TextView(context); messageLabel6.Text = "Hi,We are scheduled a conference meeting"; messageLabel6.TextSize = 12; TextView spaceText6 = new TextView(context); spaceText6.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text6 = new TextView(context); Text6.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); ContentLayout5.AddView(userNameLabel8); ContentLayout5.AddView(date5); mail10.AddView(ContentLayout5); mail10.AddView(spaceText6); mail10.AddView(updateLabel6); mail10.AddView(Text6); mail10.AddView(messageLabel6); labelSeparator8 = new SeparatorView(context, width * 2); labelSeparator8.separatorColor = Color.LightGray; labelSeparator8.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //mail11 LinearLayout ContentLayout6 = new LinearLayout(context); ContentLayout6.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); TextView date6 = new TextView(context); date6.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); date6.Text = "May 13"; date6.Typeface = Typeface.DefaultBold; date6.SetTextColor(Color.ParseColor("#006BCD")); date6.Gravity = GravityFlags.End; mail11 = new LinearLayout(context); TextView userNameLabel9 = new TextView(context); userNameLabel9.Text = "Ruben"; userNameLabel9.TextSize = 15; userNameLabel9.Typeface = Typeface.DefaultBold; TextView updateLabel7 = new TextView(context); updateLabel7.Text = "RE:Status Update"; updateLabel7.SetTextColor(Color.ParseColor("#006BCD")); updateLabel7.Typeface = Typeface.DefaultBold; updateLabel7.TextSize = 13; TextView messageLabel7 = new TextView(context); messageLabel7.Text = "Thanks for the status report"; messageLabel7.TextSize = 12; TextView spaceText7 = new TextView(context); spaceText7.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text7 = new TextView(context); Text7.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); ContentLayout6.AddView(userNameLabel9); ContentLayout6.AddView(date6); mail11.AddView(ContentLayout6); mail11.AddView(spaceText7); mail11.AddView(updateLabel7); mail11.AddView(Text7); mail11.AddView(messageLabel7); labelSeparator9 = new SeparatorView(context, width * 2); labelSeparator9.separatorColor = Color.LightGray; labelSeparator9.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //mail18 mail18 = new LinearLayout(context); TextView userNameLabel18 = new TextView(context); userNameLabel18.Text = "Frank"; userNameLabel18.TextSize = 15; TextView updateLabel18 = new TextView(context); updateLabel18.Text = "Monthly Reports Documents"; updateLabel18.TextSize = 13; TextView messageLabel18 = new TextView(context); messageLabel18.Text = "Hi,All documents are reviewed"; messageLabel18.TextSize = 12; TextView spaceText18 = new TextView(context); spaceText18.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text18 = new TextView(context); Text18.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); mail18.AddView(userNameLabel18); mail18.AddView(spaceText18); mail18.AddView(updateLabel18); mail18.AddView(Text18); mail18.AddView(messageLabel18); labelSeparator18 = new SeparatorView(context, width * 2); labelSeparator18.separatorColor = Color.LightGray; labelSeparator18.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //mail19 mail19 = new LinearLayout(context); TextView userNameLabel19 = new TextView(context); userNameLabel19.Text = "Michael"; userNameLabel19.TextSize = 15; TextView updateLabel19 = new TextView(context); updateLabel19.Text = "Metting Confirmation"; updateLabel19.TextSize = 13; TextView messageLabel19 = new TextView(context); messageLabel19.Text = "Thanks for scheduling the metting"; messageLabel19.TextSize = 12; TextView spaceText19 = new TextView(context); spaceText19.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text19 = new TextView(context); Text19.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); mail19.AddView(userNameLabel19); mail19.AddView(spaceText19); mail19.AddView(updateLabel19); mail19.AddView(Text19); mail19.AddView(messageLabel19); labelSeparator19 = new SeparatorView(context, width * 2); labelSeparator19.separatorColor = Color.LightGray; labelSeparator19.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //mail20 mail20 = new LinearLayout(context); TextView userNameLabel20 = new TextView(context); userNameLabel20.Text = "Robin"; userNameLabel20.TextSize = 15; TextView updateLabel20 = new TextView(context); updateLabel20.Text = "Success! Report Automation"; updateLabel20.TextSize = 13; TextView messageLabel20 = new TextView(context); messageLabel20.Text = "Do not reply, Automation result will update soon"; messageLabel20.TextSize = 12; TextView spaceText20 = new TextView(context); spaceText20.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); TextView Text20 = new TextView(context); Text20.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 20); mail20.AddView(userNameLabel20); mail20.AddView(spaceText20); mail20.AddView(updateLabel20); mail20.AddView(Text20); mail20.AddView(messageLabel20); labelSeparator20 = new SeparatorView(context, width * 2); labelSeparator20.separatorColor = Color.LightGray; labelSeparator20.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //mail Orientation mail1.Orientation = Orientation.Vertical; mail2.Orientation = Orientation.Vertical; mail3.Orientation = Orientation.Vertical; mail4.Orientation = Orientation.Vertical; mail9.Orientation = Orientation.Vertical; mail10.Orientation = Orientation.Vertical; mail11.Orientation = Orientation.Vertical; mail18.Orientation = Orientation.Vertical; mail19.Orientation = Orientation.Vertical; mail20.Orientation = Orientation.Vertical; //mail LayoutParameters mail1.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail1.SetPadding(20, 10, 10, 5); mail2.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail2.SetPadding(20, 10, 10, 5); mail3.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail3.SetPadding(20, 10, 10, 5); mail4.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail4.SetPadding(20, 10, 10, 5); mail9.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail9.SetPadding(20, 10, 10, 5); mail10.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail10.SetPadding(20, 10, 10, 5); mail11.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail11.SetPadding(20, 10, 10, 5); mail18.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail18.SetPadding(20, 10, 10, 5); mail19.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail19.SetPadding(20, 10, 10, 5); mail20.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail20.SetPadding(20, 10, 10, 5); //inboxview inboxLayout.SetPadding(20, 0, 20, 20); inboxLayout.AddView(mail1); inboxLayout.AddView(labelSeparator3, layoutParams5); inboxLayout.AddView(mail2); inboxLayout.AddView(labelSeparator4, layoutParams5); inboxLayout.AddView(mail3); inboxLayout.AddView(labelSeparator5, layoutParams5); inboxLayout.AddView(mail4); inboxLayout.AddView(labelSeparator6, layoutParams5); inboxLayout.AddView(mail9); inboxLayout.AddView(labelSeparator7, layoutParams5); inboxLayout.AddView(mail10); inboxLayout.AddView(labelSeparator9, layoutParams5); inboxLayout.AddView(mail11); inboxLayout.AddView(labelSeparator8, layoutParams5); inboxLayout.AddView(mail18); inboxLayout.AddView(labelSeparator18, layoutParams5); inboxLayout.AddView(mail19); inboxLayout.AddView(labelSeparator19, layoutParams5); inboxLayout.AddView(mail20); inboxLayout.AddView(labelSeparator20, layoutParams5); } private void SecondaryDrawerLayout() { //textScroller textScroller1 = new ScrollView(context); textScroller1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); TextView headerView = new TextView(context); headerView.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); headerView.SetBackgroundColor(Color.Rgb(47, 173, 227)); headerView.SetPadding(20, 0, 0, 0); headerView.Text = "Notifications"; headerView.TextSize = 20; headerView.Gravity = GravityFlags.CenterVertical; headerView.SetTextColor(Color.White); //slideDrawer drawerSettings = new DrawerSettings(); drawerSettings.DrawerWidth = (float)(230); drawerSettings.DrawerHeight = (float)(250); drawerSettings.DrawerHeaderHeight = 40; drawerSettings.Transition = Transition.SlideOnTop; drawerSettings.Position = Position.Right; drawerSettings.EnableSwipeGesture = true; drawerSettings.TouchThreshold = 90; drawerSettings.DrawerHeaderView = headerView; //ItemLAyout ItemLayout1 = new LinearLayout(context); ItemLayout1.Orientation = Orientation.Horizontal; ItemLayout2 = new LinearLayout(context); ItemLayout2.Orientation = Orientation.Horizontal; ItemLayout3 = new LinearLayout(context); ItemLayout3.Orientation = Orientation.Horizontal; ItemLayout4 = new LinearLayout(context); ItemLayout4.Orientation = Orientation.Horizontal; ItemLayout5 = new LinearLayout(context); ItemLayout5.Orientation = Orientation.Horizontal; ItemLayout6 = new LinearLayout(context); ItemLayout6.Orientation = Orientation.Horizontal; ItemLayout7 = new LinearLayout(context); ItemLayout7.Orientation = Orientation.Horizontal; //secondaryDrawerLayout secondaryDrawerLayout = new LinearLayout(context); secondaryDrawerLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); secondaryDrawerLayout.SetBackgroundColor(Color.White); secondaryDrawerLayout.Orientation = Orientation.Vertical; //layoutParamsSecondaryDrawer layoutParamsSecondaryDrawer = new LinearLayout.LayoutParams(width * 2, 3); layoutParamsSecondaryDrawer.SetMargins(0, 10, 15, 0); //ItemImage ImageView imag1 = new ImageView(context); imag1.LayoutParameters = new ViewGroup.LayoutParams(120, 120); imag1.SetPadding(0, 20, 0, 0); imag1.SetImageResource(Resource.Drawable.a5); ImageView imag2 = new ImageView(context); imag2.LayoutParameters = new ViewGroup.LayoutParams(120, 120); imag2.SetPadding(0, 20, 0, 0); imag2.SetImageResource(Resource.Drawable.a0); ImageView imag3 = new ImageView(context); imag3.LayoutParameters = new ViewGroup.LayoutParams(120, 120); imag3.SetPadding(0, 20, 0, 0); imag3.SetImageResource(Resource.Drawable.a1); ImageView imag4 = new ImageView(context); imag4.LayoutParameters = new ViewGroup.LayoutParams(120, 120); imag4.SetPadding(0, 20, 0, 0); //LinearLayout.LayoutParams layparams8 = new LinearLayout.LayoutParams(30,30); imag4.SetImageResource(Resource.Drawable.a2); ImageView imag5 = new ImageView(context); imag5.LayoutParameters = new ViewGroup.LayoutParams(120, 120); imag5.SetPadding(0, 20, 0, 0); imag5.SetImageResource(Resource.Drawable.a3); ImageView imag6 = new ImageView(context); imag6.LayoutParameters = new ViewGroup.LayoutParams(120, 120); imag6.SetPadding(0, 20, 0, 0); imag6.SetImageResource(Resource.Drawable.a4); ImageView imag7 = new ImageView(context); imag7.LayoutParameters = new ViewGroup.LayoutParams(120, 120); imag7.SetPadding(0, 20, 0, 0); imag7.SetImageResource(Resource.Drawable.user); //Item1 Item1 = new LinearLayout(context); Item1.Orientation = Orientation.Vertical; Item1.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); Item1.SetPadding(20, 10, 10, 5); //John TextView userNameLabel1 = new TextView(context); userNameLabel1.Text = "John"; userNameLabel1.Typeface = Typeface.DefaultBold; userNameLabel1.TextSize = 15; TextView spaceText = new TextView(context); spaceText.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 3); TextView Text1 = new TextView(context); Text1.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 4); TextView messageLabel1 = new TextView(context); messageLabel1.SetTextColor(Color.Rgb(0, 107, 205)); messageLabel1.Text = "Goto Meeting"; messageLabel1.Typeface = Typeface.DefaultBold; TextView description1 = new TextView(context); description1.TextSize = 12; description1.Text = "Join meeting to discuss about daily status, workflow, pending work and improve process"; Item1.AddView(userNameLabel1); Item1.AddView(spaceText); Item1.AddView(messageLabel1); Item1.AddView(Text1); Item1.AddView(description1); //separatorView separatorView1 = new SeparatorView(context, width * 2); separatorView1.separatorColor = Color.LightGray; separatorView1.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); ItemLayout1.AddView(imag1); ItemLayout1.AddView(Item1); //Item2 Item2 = new LinearLayout(context); Item2.Orientation = Orientation.Vertical; Item2.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); Item2.SetPadding(20, 10, 10, 5); //Caster TextView userNameLabel2 = new TextView(context); userNameLabel2.Text = "Caster"; userNameLabel2.Typeface = Typeface.DefaultBold; userNameLabel2.TextSize = 15; TextView spaceText2 = new TextView(context); spaceText2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 3); TextView Text2 = new TextView(context); Text2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 4); TextView messageLabel2 = new TextView(context); messageLabel2.SetTextColor(Color.Rgb(0, 107, 205)); messageLabel2.Text = "FW:Status Update"; messageLabel2.Typeface = Typeface.DefaultBold; TextView description2 = new TextView(context); description2.TextSize = 12; description2.Text = "Hi, Please find the today's status"; Item2.AddView(userNameLabel2); Item2.AddView(spaceText2); Item2.AddView(messageLabel2); Item1.AddView(Text2); Item2.AddView(description2); //separatorView separatorView2 = new SeparatorView(context, width * 2); separatorView2.separatorColor = Color.LightGray; separatorView2.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); ItemLayout2.AddView(imag2); ItemLayout2.AddView(Item2); //Item3 Item3 = new LinearLayout(context); Item3.Orientation = Orientation.Vertical; Item3.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); Item3.SetPadding(20, 10, 10, 5); //Joey TextView userNameLabel3 = new TextView(context); userNameLabel3.Text = "Joey"; userNameLabel3.Typeface = Typeface.DefaultBold; userNameLabel3.TextSize = 15; TextView spaceText3 = new TextView(context); spaceText3.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 3); TextView Text3 = new TextView(context); Text3.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 4); TextView messageLabel3 = new TextView(context); messageLabel3.SetTextColor(Color.Rgb(0, 107, 205)); messageLabel3.Text = "Greetings! Congrats"; messageLabel3.Typeface = Typeface.DefaultBold; TextView description3 = new TextView(context); description3.TextSize = 12; description3.Text = "Hi, Congrats you have won the raffle"; Item3.AddView(userNameLabel3); Item3.AddView(spaceText3); Item3.AddView(messageLabel3); Item3.AddView(Text3); Item3.AddView(description3); //separatorView separatorView3 = new SeparatorView(context, width * 2); separatorView3.separatorColor = Color.LightGray; separatorView3.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); ItemLayout3.AddView(imag3); ItemLayout3.AddView(Item3); //Item4 Item4 = new LinearLayout(context); Item4.Orientation = Orientation.Vertical; Item4.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); Item4.SetPadding(20, 10, 10, 5); //Xavier TextView userNameLabel4 = new TextView(context); userNameLabel4.Text = "Xavier"; userNameLabel4.Typeface = Typeface.DefaultBold; userNameLabel4.TextSize = 15; TextView spaceText4 = new TextView(context); spaceText4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 3); TextView Text4 = new TextView(context); Text4.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 4); TextView messageLabel4 = new TextView(context); messageLabel4.SetTextColor(Color.Rgb(0, 107, 205)); messageLabel4.Text = "Report Monitor"; messageLabel4.Typeface = Typeface.DefaultBold; TextView description4 = new TextView(context); description4.TextSize = 12; description4.Text = "Do not reply, Please find the attachment. Attachment have the full details of monitor report with timing"; Item4.AddView(userNameLabel4); Item4.AddView(spaceText4); Item4.AddView(messageLabel4); Item4.AddView(Text4); Item4.AddView(description4); //separatorView separatorView4 = new SeparatorView(context, width * 2); separatorView4.separatorColor = Color.LightGray; separatorView4.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); ItemLayout4.AddView(imag4); ItemLayout4.AddView(Item4); //Item5 Item5 = new LinearLayout(context); Item5.Orientation = Orientation.Vertical; Item5.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); Item5.SetPadding(20, 10, 10, 5); //Gonzalez TextView userNameLabel5 = new TextView(context); userNameLabel5.Text = "Gonzalez"; userNameLabel5.Typeface = Typeface.DefaultBold; userNameLabel5.TextSize = 15; TextView spaceText5 = new TextView(context); spaceText5.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 3); TextView Text5 = new TextView(context); Text5.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 4); TextView messageLabel5 = new TextView(context); messageLabel5.SetTextColor(Color.Rgb(0, 107, 205)); messageLabel5.Text = "News Letter"; messageLabel5.Typeface = Typeface.DefaultBold; TextView description5 = new TextView(context); description5.TextSize = 12; description5.Text = "Hi, Please find the attached news letter"; Item5.AddView(userNameLabel5); Item5.AddView(spaceText5); Item5.AddView(messageLabel5); Item5.AddView(Text5); Item5.AddView(description5); //separatorView separatorView5 = new SeparatorView(context, width * 2); separatorView5.separatorColor = Color.LightGray; separatorView5.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); ItemLayout5.AddView(imag5); ItemLayout5.AddView(Item5); //Item6 Item6 = new LinearLayout(context); Item6.Orientation = Orientation.Vertical; Item6.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); Item6.SetPadding(20, 10, 10, 5); //Rodriguez TextView userNameLabel6 = new TextView(context); userNameLabel6.Text = "Rodriguez"; userNameLabel6.Typeface = Typeface.DefaultBold; userNameLabel6.TextSize = 15; TextView spaceText6 = new TextView(context); spaceText6.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 3); TextView Text6 = new TextView(context); Text6.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 4); TextView messageLabel6 = new TextView(context); messageLabel6.SetTextColor(Color.Rgb(0, 107, 205)); messageLabel6.Text = "Conference about Latest Technology"; messageLabel6.Typeface = Typeface.DefaultBold; TextView description6 = new TextView(context); description6.TextSize = 12; description6.Text = "Hi,We are scheduled a conference meeting"; Item6.AddView(userNameLabel6); Item6.AddView(spaceText6); Item6.AddView(messageLabel6); Item6.AddView(Text6); Item6.AddView(description6); //separatorView separatorView6 = new SeparatorView(context, width * 2); separatorView6.separatorColor = Color.LightGray; separatorView6.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); ItemLayout6.AddView(imag6); ItemLayout6.AddView(Item6); //Item7 Item7 = new LinearLayout(context); Item7.Orientation = Orientation.Vertical; Item7.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); Item7.SetPadding(20, 10, 10, 5); //Ruben TextView userNameLabel7 = new TextView(context); userNameLabel7.Text = "Ruben"; userNameLabel7.Typeface = Typeface.DefaultBold; userNameLabel7.TextSize = 15; TextView spaceText7 = new TextView(context); spaceText7.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 3); TextView Text7 = new TextView(context); Text7.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 4); TextView messageLabel7 = new TextView(context); messageLabel7.SetTextColor(Color.Rgb(0, 107, 205)); messageLabel7.Text = "RE:Status Update"; messageLabel7.Typeface = Typeface.DefaultBold; TextView description7 = new TextView(context); description7.TextSize = 12; description7.Text = "Thanks for the status report"; Item7.AddView(userNameLabel7); Item7.AddView(spaceText7); Item7.AddView(messageLabel7); Item7.AddView(description7); Item7.AddView(Text7); //separatorView separatorView7 = new SeparatorView(context, width * 2); separatorView7.separatorColor = Color.LightGray; separatorView7.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); ItemLayout7.AddView(imag7); ItemLayout7.AddView(Item7); //secondaryDrawerLayout secondaryDrawerLayout.SetPadding(20, 0, 20, 20); secondaryDrawerLayout.AddView(ItemLayout1); secondaryDrawerLayout.AddView(separatorView1, layoutParamsSecondaryDrawer); secondaryDrawerLayout.AddView(ItemLayout2); secondaryDrawerLayout.AddView(separatorView2, layoutParamsSecondaryDrawer); secondaryDrawerLayout.AddView(ItemLayout3); secondaryDrawerLayout.AddView(separatorView3, layoutParamsSecondaryDrawer); secondaryDrawerLayout.AddView(ItemLayout4); secondaryDrawerLayout.AddView(separatorView4, layoutParamsSecondaryDrawer); secondaryDrawerLayout.AddView(ItemLayout5); secondaryDrawerLayout.AddView(separatorView5, layoutParamsSecondaryDrawer); secondaryDrawerLayout.AddView(ItemLayout6); secondaryDrawerLayout.AddView(separatorView6, layoutParamsSecondaryDrawer); secondaryDrawerLayout.AddView(ItemLayout7); secondaryDrawerLayout.AddView(separatorView7, layoutParamsSecondaryDrawer); textScroller1.AddView(secondaryDrawerLayout); drawerSettings.DrawerContentView = textScroller1; slideDrawer.SecondaryDrawerSettings = drawerSettings; } private void OutBoxLayout() { //outboxlayout outboxlayout = new LinearLayout(context); outboxlayout.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent)); outboxlayout.SetBackgroundColor(Color.White); outboxlayout.Orientation = (Orientation.Vertical); //mail5 mail5 = new LinearLayout(context); TextView userNameLabel10 = new TextView(context); userNameLabel10.Text = "Ruben"; userNameLabel10.TextSize = 20; TextView updateLabel8 = new TextView(context); updateLabel8.Text = "Update on Timeline"; updateLabel8.SetTextColor(Color.ParseColor("#1CAEE4")); updateLabel8.TextSize = 16; TextView messageLabel8 = new TextView(context); messageLabel8.Text = "Hi Ruben, see you at 6PM"; labelSeparator10 = new SeparatorView(context, width * 2); labelSeparator10.separatorColor = Color.LightGray; labelSeparator10.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); messageLabel8.TextSize = 13; mail5.AddView(userNameLabel10); mail5.AddView(messageLabel8); //mail6 mail6 = new LinearLayout(context); TextView userNameLabel11 = new TextView(context); userNameLabel11.Text = "Rodriguez"; userNameLabel11.TextSize = 20; TextView updateLabel9 = new TextView(context); updateLabel9.Text = "Update on Timeline"; updateLabel9.SetTextColor(Color.ParseColor("#1CAEE4")); updateLabel9.TextSize = 16; TextView messageLabel9 = new TextView(context); messageLabel9.Text = "Hi Rodriguez, see you at 4PM"; messageLabel9.TextSize = 13; mail6.AddView(userNameLabel11); mail6.AddView(messageLabel9); //mail12 mail12 = new LinearLayout(context); TextView userNameLabel12 = new TextView(context); userNameLabel12.Text = "Gonzalez"; userNameLabel12.TextSize = 20; TextView updateLabel10 = new TextView(context); updateLabel10.Text = "Update on Timeline"; updateLabel10.SetTextColor(Color.ParseColor("#1CAEE4")); updateLabel10.TextSize = 16; TextView messageLabel10 = new TextView(context); messageLabel10.Text = "Hi Gonzalez, see you at 3PM"; mail12.AddView(userNameLabel12); mail12.AddView(messageLabel10); labelSeparator11 = new SeparatorView(context, width * 2); labelSeparator11.separatorColor = Color.LightGray; labelSeparator11.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); mail12.Orientation = Orientation.Vertical; mail12.Orientation = (Orientation.Vertical); mail5.Orientation = Orientation.Vertical; mail6.Orientation = Orientation.Vertical; //mail13 mail13 = new LinearLayout(context); TextView userNameLabel13 = new TextView(context); userNameLabel13.Text = "Xavier"; userNameLabel13.TextSize = 20; TextView updateLabel11 = new TextView(context); updateLabel11.Text = "Update on Timeline"; updateLabel11.SetTextColor(Color.ParseColor("#1CAEE4")); updateLabel11.TextSize = 16; TextView messageLabel11 = new TextView(context); messageLabel11.Text = "Hi Xavier, see you at 2PM"; labelSeparator12 = new SeparatorView(context, width * 2); labelSeparator12.separatorColor = Color.LightGray; labelSeparator12.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); mail13.AddView(userNameLabel13); mail13.AddView(messageLabel11); mail13.Orientation = (Orientation.Vertical); mail13.Orientation = (Orientation.Vertical); //mail14 mail14 = new LinearLayout(context); TextView userNameLabel14 = new TextView(context); userNameLabel14.Text = "Joey"; userNameLabel14.TextSize = 20; TextView updateLabel12 = new TextView(context); updateLabel12.Text = "Update on Timeline"; updateLabel12.SetTextColor(Color.ParseColor("#1CAEE4")); updateLabel12.TextSize = 16; TextView messageLabel12 = new TextView(context); messageLabel12.Text = "Hi Joey, see you at 1PM"; labelSeparator13 = new SeparatorView(context, width * 2); labelSeparator13.separatorColor = Color.LightGray; labelSeparator13.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); mail14.AddView(userNameLabel14); mail14.AddView(messageLabel12); mail14.Orientation = (Orientation.Vertical); mail14.Orientation = (Orientation.Vertical); //mail15 mail15 = new LinearLayout(context); TextView userNameLabel15 = new TextView(context); userNameLabel15.Text = "Joey"; userNameLabel15.TextSize = 20; TextView updateLabel13 = new TextView(context); updateLabel13.Text = "Update on Timeline"; updateLabel13.SetTextColor(Color.ParseColor("#1CAEE4")); updateLabel13.TextSize = 16; TextView messageLabel13 = new TextView(context); messageLabel13.Text = "Hi Joey, see you at 1PM"; labelSeparator14 = new SeparatorView(context, width * 2); labelSeparator14.separatorColor = Color.LightGray; labelSeparator14.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); mail15.AddView(userNameLabel15); mail15.AddView(messageLabel13); mail15.Orientation = (Orientation.Vertical); mail15.Orientation = (Orientation.Vertical); //mail16 mail16 = new LinearLayout(context); TextView userNameLabel16 = new TextView(context); userNameLabel16.Text = ("Caster"); userNameLabel16.TextSize = (20); TextView updateLabel14 = new TextView(context); updateLabel14.Text = ("Update on Timeline"); updateLabel14.SetTextColor(Color.ParseColor("#1CAEE4")); updateLabel14.TextSize = (16); TextView messageLabel14 = new TextView(context); messageLabel14.Text = ("Hi Caster, see you at 11PM"); labelSeparator15 = new SeparatorView(context, width * 2); labelSeparator15.separatorColor = Color.LightGray; labelSeparator15.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); mail16.AddView(userNameLabel16); mail16.AddView(messageLabel14); mail16.Orientation = (Orientation.Vertical); mail16.Orientation = (Orientation.Vertical); //mail17 mail17 = new LinearLayout(context); TextView userNameLabel17 = new TextView(context); userNameLabel17.Text = "john"; userNameLabel17.TextSize = 20; TextView updateLabel15 = new TextView(context); updateLabel15.Text = ("Update on Timeline"); updateLabel15.SetTextColor(Color.ParseColor("#1CAEE4")); updateLabel15.TextSize = (16); TextView messageLabel15 = new TextView(context); messageLabel15.Text = ("Hi John, see you at 10AM"); labelSeparator16 = new SeparatorView(context, width * 2); labelSeparator16.separatorColor = Color.LightGray; labelSeparator16.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); mail17.AddView(userNameLabel17); mail17.AddView(messageLabel15); mail17.Orientation = (Orientation.Vertical); mail17.Orientation = (Orientation.Vertical); //mail LayoutParameters mail6.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail6.SetPadding(20, 10, 10, 10); mail5.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail5.SetPadding(20, 10, 10, 5); mail12.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail12.SetPadding(20, 10, 10, 5); mail13.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail13.SetPadding(20, 10, 10, 5); mail14.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail14.SetPadding(20, 10, 10, 5); mail15.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail15.SetPadding(20, 10, 10, 5); mail16.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail16.SetPadding(20, 10, 10, 5); mail17.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent)); mail17.SetPadding(20, 10, 10, 5); labelSeparator17 = new SeparatorView(context, width * 2); labelSeparator17.separatorColor = Color.LightGray; labelSeparator17.LayoutParameters = (new ViewGroup.LayoutParams(width * 2, 3)); //outboxView outboxlayout.SetPadding(20, 0, 20, 20); outboxlayout.AddView(mail5); outboxlayout.AddView(labelSeparator17, layoutParams5); outboxlayout.AddView(mail6); outboxlayout.AddView(labelSeparator10, layoutParams5); outboxlayout.AddView(mail12); outboxlayout.AddView(labelSeparator11, layoutParams5); outboxlayout.AddView(mail13); outboxlayout.AddView(labelSeparator12, layoutParams5); outboxlayout.AddView(mail15); outboxlayout.AddView(labelSeparator14, layoutParams5); outboxlayout.AddView(mail16); outboxlayout.AddView(labelSeparator15, layoutParams5); outboxlayout.AddView(mail17); outboxlayout.AddView(labelSeparator16, layoutParams5); } private void ClickListenerLayout() { //textScroller textScroller2 = new ScrollView(context); textScroller2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); //Item click Listener viewItem.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => { String selectedItem = arrayAdapter.GetItem(e.Position); if (selectedItem.Equals("Home")) { ContentFrame.RemoveAllViews(); ContentFrame.AddView(textScroller); profileContentLabel.Text = "Home"; } if (selectedItem.Equals("Profile")) { ContentFrame.RemoveAllViews(); ContentFrame.AddView(profilelayout); profileContentLabel.Text = "Profile"; } if (selectedItem.Equals("Inbox")) { ContentFrame.RemoveAllViews(); inboxLayout.RemoveAllViews(); textScroller2.RemoveAllViews(); inboxLayout.SetPadding(20, 0, 20, 20); inboxLayout.AddView(mail1); inboxLayout.AddView(labelSeparator3, layoutParams5); inboxLayout.AddView(mail2); inboxLayout.AddView(labelSeparator4, layoutParams5); inboxLayout.AddView(mail3); inboxLayout.AddView(labelSeparator5, layoutParams5); inboxLayout.AddView(mail4); inboxLayout.AddView(labelSeparator6, layoutParams5); inboxLayout.AddView(mail9); inboxLayout.AddView(labelSeparator7, layoutParams5); inboxLayout.AddView(mail10); inboxLayout.AddView(labelSeparator9, layoutParams5); inboxLayout.AddView(mail11); inboxLayout.AddView(labelSeparator8, layoutParams5); inboxLayout.AddView(mail18); inboxLayout.AddView(labelSeparator18, layoutParams5); inboxLayout.AddView(mail19); inboxLayout.AddView(labelSeparator19, layoutParams5); inboxLayout.AddView(mail20); inboxLayout.AddView(labelSeparator20, layoutParams5); textScroller2.AddView(inboxLayout); ContentFrame.AddView(textScroller2); profileContentLabel.Text = "Inbox"; } if (selectedItem.Equals("Outbox")) { ContentFrame.RemoveAllViews(); outboxlayout.RemoveAllViews(); outboxlayout.SetPadding(20, 0, 20, 20); outboxlayout.AddView(mail5); outboxlayout.AddView(labelSeparator17, layoutParams5); outboxlayout.AddView(mail6); outboxlayout.AddView(labelSeparator10, layoutParams5); outboxlayout.AddView(mail12); outboxlayout.AddView(labelSeparator11, layoutParams5); outboxlayout.AddView(mail13); outboxlayout.AddView(labelSeparator12, layoutParams5); outboxlayout.AddView(mail15); outboxlayout.AddView(labelSeparator14, layoutParams5); outboxlayout.AddView(mail16); outboxlayout.AddView(labelSeparator15, layoutParams5); outboxlayout.AddView(mail17); outboxlayout.AddView(labelSeparator16, layoutParams5); ContentFrame.AddView(outboxlayout); profileContentLabel.Text = "Outbox"; } if (selectedItem.Equals("Sent Items")) { ContentFrame.RemoveAllViews(); inboxLayout.RemoveAllViews(); inboxLayout.SetPadding(20, 0, 20, 20); textScroller2.RemoveAllViews(); inboxLayout.AddView(mail10); inboxLayout.AddView(labelSeparator4, layoutParams5); inboxLayout.AddView(mail9); inboxLayout.AddView(labelSeparator5, layoutParams5); inboxLayout.AddView(mail4); inboxLayout.AddView(labelSeparator6, layoutParams5); inboxLayout.AddView(mail3); inboxLayout.AddView(labelSeparator8, layoutParams5); inboxLayout.AddView(mail11); inboxLayout.AddView(labelSeparator3, layoutParams5); inboxLayout.AddView(mail1); inboxLayout.AddView(labelSeparator7, layoutParams5); inboxLayout.AddView(mail2); inboxLayout.AddView(labelSeparator9, layoutParams5); textScroller2.AddView(inboxLayout); ContentFrame.AddView(textScroller2); profileContentLabel.Text = "Sent Items"; } if (selectedItem.Equals("Trash")) { ContentFrame.RemoveAllViews(); outboxlayout.RemoveAllViews(); outboxlayout.SetPadding(20, 0, 20, 20); outboxlayout.AddView(mail13); outboxlayout.AddView(labelSeparator12, layoutParams5); outboxlayout.AddView(mail5); outboxlayout.AddView(labelSeparator17, layoutParams5); outboxlayout.AddView(mail12); outboxlayout.AddView(labelSeparator11, layoutParams5); outboxlayout.AddView(mail15); outboxlayout.AddView(labelSeparator14, layoutParams5); outboxlayout.AddView(mail17); outboxlayout.AddView(labelSeparator16, layoutParams5); outboxlayout.AddView(mail16); outboxlayout.AddView(labelSeparator15, layoutParams5); outboxlayout.AddView(mail6); outboxlayout.AddView(labelSeparator10, layoutParams5); ContentFrame.AddView(outboxlayout); profileContentLabel.Text = "Trash"; } slideDrawer.ToggleDrawer(); }; } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/AutoComplete/Engine.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; namespace SampleBrowser { public class ToleratingTyposHelper { public ToleratingTyposHelper() { soundexTerms.Add("aeiouhyw"); soundexTerms.Add("bfpv"); soundexTerms.Add("cgikqsxz"); soundexTerms.Add("dt"); soundexTerms.Add("l"); soundexTerms.Add("mn"); soundexTerms.Add("r"); } List<string> soundexTerms = new List<string>(); /// <summary> /// Based on Soundex Algorithmn and DL Distance Algorithmn /// </summary> /// <returns>The matching.</returns> /// <param name="value1">Value1.</param> /// <param name="value2">Value2.</param> public int IsMatching(string value1, string value2) { var val1 = ProcessOnSoundexAlgorithmn(value1); var val2 = ProcessOnSoundexAlgorithmn(value2); return CalcualteDistance(val1, val2); } public int GetMinValue(int[] value) { int minValue = 0; foreach (var item in value) { if (item < minValue) minValue = item; } return minValue; } public int GetDamerauLevenshteinDistance(string source, string target) { var bounds = new { Height = source.Length + 1, Width = target.Length + 1 }; int[,] matrix = new int[bounds.Height, bounds.Width]; for (int height = 0; height < bounds.Height; height++) { matrix[height, 0] = height; }; for (int width = 0; width < bounds.Width; width++) { matrix[0, width] = width; }; for (int height = 1; height < bounds.Height; height++) { for (int width = 1; width < bounds.Width; width++) { int cost = (source[height - 1] == target[width - 1]) ? 0 : 1; int insertion = matrix[height, width - 1] + 1; int deletion = matrix[height - 1, width] + 1; int substitution = matrix[height - 1, width - 1] + cost; int distance = Math.Min(insertion, Math.Min(deletion, substitution)); if (height > 1 && width > 1 && source[height - 1] == target[width - 2] && source[height - 2] == target[width - 1]) { distance = Math.Min(distance, matrix[height - 2, width - 2] + cost); } matrix[height, width] = distance; } } return matrix[bounds.Height - 1, bounds.Width - 1]; } /// <summary> /// DL Algorithmn Implementation /// </summary> /// <returns>The distance.</returns> /// <param name="value1">Value1.</param> /// <param name="value2">Value2.</param> public int CalcualteDistance(string value1, string value2) { int lengthValue1 = value1.Length; int lengthValue2 = value2.Length; var matrix = new int[lengthValue1 + 1, lengthValue2 + 1]; for (int i = 0; i <= lengthValue1; i++) matrix[i, 0] = i; for (int j = 0; j <= lengthValue2; j++) matrix[0, j] = j; for (int i = 1; i <= lengthValue1; i++) { for (int j = 1; j <= lengthValue2; j++) { int cost = value2[j - 1] == value1[i - 1] ? 0 : 1; var vals = new int[] { matrix[i - 1, j] + 1, matrix[i, j - 1] + 1, matrix[i - 1, j - 1] + cost }; matrix[i, j] = GetMinValue(vals); if (i > 1 && j > 1 && value1[i - 1] == value2[j - 2] && value1[i - 2] == value2[j - 1]) matrix[i, j] = Math.Min(matrix[i, j], matrix[i - 2, j - 2] + cost); } } return matrix[lengthValue1, lengthValue2]; } /// <summary> /// Soundex Algorithmn Implementation /// </summary> /// <returns>The on soundex algorithmn.</returns> /// <param name="value1">Value1.</param> /// <param name="moreAccuracy">If set to <c>true</c> more accuracy.</param> public string ProcessOnSoundexAlgorithmn(string value1, bool moreAccuracy = true) { string stringValue = string.Empty; foreach (var item in value1.ToLower()) { for (int i = 0; i < soundexTerms.Count; i++) { if (soundexTerms[i].Contains(item.ToString())) { stringValue += i.ToString(); continue; } } } if (stringValue.Length > 0) { if (moreAccuracy) { stringValue = stringValue.Insert(0, value1[0].ToString()); stringValue = stringValue.Replace("0", ""); } } return stringValue; } } } <file_sep>/Forms/Shimmer/Shimmer/Samples/ShimmerCustomization/Customization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.Border; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfShimmer { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Customization : SampleView { public Customization() { InitializeComponent(); picker.SelectedIndex = 4; waveDirectionPicker.SelectedIndex = 0; var colors = new List<Color> { Color.FromHex("#EBEBEB"), Color.FromHex("#E7E7F9"), Color.FromHex("#E1EFFF"), Color.FromHex("#F4E2EE"), Color.FromHex("#F6F6DB"), }; var viewCollection = new ObservableCollection<View>(); foreach (var color in colors) { var grid = new Grid(); var border = new Syncfusion.XForms.Border.SfBorder { Margin = new Thickness(3), HorizontalOptions = LayoutOptions.Center, CornerRadius = 22, BorderWidth = 0, Content = new BoxView { Color = color } }; grid.Children.Add(border); viewCollection.Add(grid); } shimmerColorSegmentedControl.ItemsSource = viewCollection; } private void OnPickerSelectedIndexChanged(object sender, EventArgs e) { shimmer.Type = (Syncfusion.XForms.Shimmer.ShimmerTypes)(sender as Picker).SelectedIndex; } private void OnShimmerColorSelectionChanged(object sender, Syncfusion.XForms.Buttons.SelectionChangedEventArgs e) { viewModel.ShimmerColor = viewModel.ShimmerColors[e.Index]; shimmerColorSegmentedControl.SelectionTextColor = viewModel.ShimmerColors[e.Index]; viewModel.WaveColor = viewModel.WaveColors[e.Index]; } private void OnWaveDirectionPickerSelectedIndexChanged(object sender, EventArgs e) { shimmer.WaveDirection = (Syncfusion.XForms.Shimmer.WaveDirection)(sender as Picker).SelectedIndex; } } }<file_sep>/Forms/DocIO/DocIO/Samples/TrackChanges/TrackChanges.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using SampleBrowser.Core; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.DocIO; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using Syncfusion.OfficeChart; using Syncfusion.Drawing; namespace SampleBrowser.DocIO { public partial class TrackChanges : SampleView { public TrackChanges() { InitializeComponent(); this.acceptAll.IsChecked = true; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Description.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate1.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate1.BackgroundColor = Xamarin.Forms.Color.Gray; this.btnGenerate2.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate2.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Description.FontSize = 13.5; } this.Description.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate1.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate2.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; } } void OnButtonClicked1(object sender, EventArgs e) { Assembly assembly = typeof(TrackChanges).GetTypeInfo().Assembly; #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif Stream inputStream = assembly.GetManifestResourceStream(rootPath + "TrackChangesTemplate.docx"); MemoryStream stream = new MemoryStream(); inputStream.CopyTo(stream); inputStream.Dispose(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("TrackChangesTemplate.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("TrackChangesTemplate.docx", "application/msword", stream); } void OnButtonClicked2(object sender, EventArgs e) { Assembly assembly = typeof(TrackChanges).GetTypeInfo().Assembly; WordDocument document = new WordDocument(); #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif // Open an existing template document. Stream inputStream = assembly.GetManifestResourceStream(rootPath + "TrackChangesTemplate.docx"); document.Open(inputStream, FormatType.Docx); inputStream.Dispose(); if (rejectAll != null && (bool)rejectAll.IsChecked) document.Revisions.RejectAll(); else document.Revisions.AcceptAll(); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Docx); document.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Track Changes.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("Track Changes.docx", "application/msword", stream); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/PullToRefresh/BaseView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Foundation; using UIKit; namespace SampleBrowser { public class BaseView : UIView { public BaseView(CGRect frame) : base(frame) { Frame = frame; DrawView(); } UILabel label; UIImageView image; internal WeatherModel model; internal WeatherView selectedView; UILabel label1; void DrawView() { label = new UILabel(new CGRect(0, Frame.Height - 130, Frame.Width, 40)); label.TextColor = UIColor.White; label.Font = UIFont.SystemFontOfSize(40); label.TextAlignment = UITextAlignment.Center; image = new UIImageView(); image.Frame = new CGRect((Frame.Width / 2) - 70, -25, 150, 100); AddSubview(label); AddSubview(image); label1 = new UILabel(new CGRect(0, Frame.Height - 70, Frame.Width, 30)); label1.TextColor = UIColor.White; label1.Font = UIFont.SystemFontOfSize(14); label1.TextAlignment = UITextAlignment.Center; AddSubview(label1); } internal void updateBaseView() { UIFont arialFont = UIFont.SystemFontOfSize(45); NSDictionary arialDict = NSDictionary.FromObjectAndKey(arialFont, UIStringAttributeKey.Font); NSMutableAttributedString aAttrString = new NSMutableAttributedString(model.Temp, arialDict); NSMutableAttributedString aAttrString1 = new NSMutableAttributedString("°/", arialDict); aAttrString.Append(aAttrString1); UIFont VerdanaFont = UIFont.SystemFontOfSize(30); NSString tel = (NSString)"12"; NSDictionary verdanaDict = NSDictionary.FromObjectAndKey(VerdanaFont, UIStringAttributeKey.Font); NSMutableAttributedString vAttrString = new NSMutableAttributedString(tel, verdanaDict); aAttrString.Append(vAttrString); label.AttributedText = aAttrString; image.Image = new UIImage(model.Type); label1.Text = model.Date; //selectedView.unSelectView(); } } } <file_sep>/Forms/DocIO/DocIO/Samples/TableOfContents/TableOfContents.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using SampleBrowser.Core; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.DocIO; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using Syncfusion.OfficeChart; using Syncfusion.Drawing; namespace SampleBrowser.DocIO { public partial class TableOfContents : SampleView { public TableOfContents() { InitializeComponent(); this.docxButton.IsChecked = true; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.btnGenerate.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Description.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Description.FontSize = 13.5; } this.Description.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { WordDocument doc = new WordDocument(); doc.EnsureMinimal(); WParagraph para = doc.LastParagraph; para.AppendText("Essential DocIO - Table of Contents"); para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; para.ApplyStyle(BuiltinStyle.Heading4); para = doc.LastSection.AddParagraph() as WParagraph; para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; para.ApplyStyle(BuiltinStyle.Heading4); para = doc.LastSection.AddParagraph() as WParagraph; //Insert TOC TableOfContent toc = para.AppendTOC(1, 3); para.ApplyStyle(BuiltinStyle.Heading4); //Apply built-in paragraph formatting WSection section = doc.LastSection; #region Default Styles WParagraph newPara = section.AddParagraph() as WParagraph; newPara = section.AddParagraph() as WParagraph; newPara.AppendBreak(BreakType.PageBreak); WTextRange text = newPara.AppendText("Document with Default styles") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading1); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading1 of built in style. This sample demonstrates the TOC insertion in a word document. Note that DocIO can only insert TOC field in a word document. It can not refresh or create TOC field. MS Word refreshes the TOC field after insertion. Please update the field or press F9 key to refresh the TOC."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Section1") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading2); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Paragraph1") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading3); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Paragraph2") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading3); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph."); section.AddParagraph(); section = doc.AddSection() as WSection; section.BreakCode = SectionBreakCode.NewPage; newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Section2") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading2); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Paragraph1") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading3); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Paragraph2") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading3); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph."); #endregion toc.IncludePageNumbers = true; toc.RightAlignPageNumbers = true; toc.UseHyperlinks = true; toc.LowerHeadingLevel = 1; toc.UpperHeadingLevel = 3; toc.UseOutlineLevels = true; //Updates the table of contents. doc.UpdateTableOfContents(); string filename = ""; string contenttype = ""; MemoryStream outputStream = new MemoryStream(); if (pdfButton != null && (bool)pdfButton.IsChecked) { filename = "Table Of Contents.pdf"; contenttype = "application/pdf"; DocIORenderer renderer = new DocIORenderer(); PdfDocument pdfDoc = renderer.ConvertToPDF(doc); pdfDoc.Save(outputStream); pdfDoc.Close(); } else { filename = "Table Of Contents.docx"; contenttype = "application/msword"; doc.Save(outputStream, FormatType.Docx); } doc.Close(); if (Device.RuntimePlatform == Device.UWP) DependencyService.Get<ISaveWindowsPhone>() .Save(filename, contenttype, outputStream); else DependencyService.Get<ISave>().Save(filename, contenttype, outputStream); } } } <file_sep>/Android/SampleBrowser/Samples/PDFViewer/GettingStartedPDFViewer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.SfPdfViewer.Android; using System.IO; using System.Reflection; using Android.Views.InputMethods; using System.Diagnostics; using static Android.Views.ViewGroup; using Android.Graphics; namespace SampleBrowser { [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] public class PdfViewerDemo : SamplePage { SfPdfViewer pdfViewerControl; LinearLayout mainView; public override View GetSampleContent(Context context) { LayoutInflater layoutInflater = LayoutInflater.From(context); mainView = (LinearLayout)layoutInflater.Inflate(Resource.Layout.PDFViewer, null); pdfViewerControl = (SfPdfViewer)mainView.FindViewById(Resource.Id.pdfviewercontrol); Stream docStream = typeof(PdfViewerDemo).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDFViewer.Assets.GIS Succinctly.pdf"); pdfViewerControl.LoadDocument(docStream); pdfViewerControl.DocumentSaveInitiated += PdfViewerControl_DocumentSaveInitiated; pdfViewerControl.PreserveSignaturePadOrientation = true; return mainView; } private void PdfViewerControl_DocumentSaveInitiated(object sender, DocumentSaveInitiatedEventArgs args) { MemoryStream stream = args.SavedStream as MemoryStream; string root = null; string fileName = "sample.pdf"; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); Java.IO.File directory = new Java.IO.File(root + "/Syncfusion"); directory.Mkdir(); Java.IO.File file = new Java.IO.File(directory, fileName); if (file.Exists()) file.Delete(); Java.IO.FileOutputStream outputStream = new Java.IO.FileOutputStream(file); outputStream.Write(stream.ToArray()); outputStream.Flush(); outputStream.Close(); AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainView.Context); alertDialog.SetTitle("Save"); alertDialog.SetMessage("The modified document is saved in the below location. " + "\n" + file.Path); alertDialog.SetPositiveButton("OK", (senderAlert, e) => { }); Dialog dialog = alertDialog.Create(); dialog.Show(); } public override void Destroy() { pdfViewerControl.Unload(); GC.Collect(); GC.WaitForPendingFinalizers(); base.Destroy(); } } }<file_sep>/Forms/ListView/ListView/Samples/LoadMore/Model/ProductRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ProductRepository { internal string[] Names = new string[] { "Apple", "Banana", "Papaya", "Lime", "Pomegranate", "Orange", "Watermelon", "Apricot", "Grapes", "Cherry", "Avacado", "Dragon", "Guava", "Mango", "Lemon", "Blueberry", "Jackfruit", "Kiwi", "Peach", "Pineapple", "Strawberry", "Raspberry" }; internal string[] FruitNames = new string[] { "Apple", "Banana", "Papaya", "Lime", "Pomegranate", "Orange", "Watermelon", "Apricot", "Grapes", "Cherry", "Avacado", "Dragon", "Guava", "Mango", "Lemon", "Blueberry", "Jackfruit", "Kiwi", "Peach", "Pineapple", "Strawberry", "Raspberry" }; internal string[] Weights = new string[] { "1 lb", "1.5 lb", "1 lb", "1 lb", "1 lb", "1 lb", "2 lb", "2 lb", "1 lb", "1.5 lb", "1 lb", "2 lb", "1 lb", "1 lb", "1.5 lb", "1 lb", "1 lb", "1.5 lb", "1 lb", "1.5 lb", "1 lb", "1 lb" }; internal double[] Prices = new double[] { 2.47, 1.40, 1.48, 2.28, 10.47, 1.00, 3.98, 14.99, 1.50, 7.48, 26.20, 22.66, 1.47, 7.10, 7.40, 6.00, 7.27, 7.33, 9.99, 2.00, 13.99, 16.99 }; } } <file_sep>/Android/SampleBrowser/Samples/AutoComplete/Countrylist.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; namespace SampleBrowser { public class Countrylist { List<String> countryList = new List<String>(); public Countrylist () { //countryList countryList.Add ("Afghanistan"); countryList.Add ("Akrotiri"); countryList.Add ("Albania"); countryList.Add ("Algeria"); countryList.Add ("American Samoa"); countryList.Add ("Andorra"); countryList.Add ("Angola"); countryList.Add ("Anguilla"); countryList.Add ("Antarctica"); countryList.Add ("Antigua and Barbuda"); countryList.Add ("Argentina"); countryList.Add ("Armenia"); countryList.Add ("Aruba"); countryList.Add ("Ashmore and Cartier Islands"); countryList.Add ("Australia"); countryList.Add ("Austria"); countryList.Add ("Azerbaijan"); countryList.Add ("Bahamas, The"); countryList.Add ("Bahrain"); countryList.Add ("Bangladesh"); countryList.Add ("Barbados"); countryList.Add ("Bassas da India"); countryList.Add ("Belarus"); countryList.Add ("Belgium"); countryList.Add ("Belize"); countryList.Add ("Benin"); countryList.Add ("Bermuda"); countryList.Add ("Bhutan"); countryList.Add ("Bolivia"); countryList.Add ("Bosnia and Herzegovina"); countryList.Add ("Botswana"); countryList.Add ("Bouvet Island"); countryList.Add ("Brazil"); countryList.Add ("British Indian Ocean Territory"); countryList.Add ("British Virgin Islands"); countryList.Add ("Brunei"); countryList.Add ("Bulgaria"); countryList.Add ("Burkina Faso"); countryList.Add ("Burma"); countryList.Add ("Burundi"); countryList.Add ("Cambodia"); countryList.Add ("Cameroon"); countryList.Add ("Canada"); countryList.Add ("Cape Verde"); countryList.Add ("Cayman Islands"); countryList.Add ("Central African Republic"); countryList.Add ("Chad"); countryList.Add ("Chile"); countryList.Add ("China"); countryList.Add ("Christmas Island"); countryList.Add ("Clipperton Island"); countryList.Add ("Cocos (Keeling) Islands"); countryList.Add ("Colombia"); countryList.Add ("Comoros"); countryList.Add ("Congo, Democratic Republic of the"); countryList.Add ("Congo, Republic of the"); countryList.Add ("Cook Islands"); countryList.Add ("Coral Sea Islands"); countryList.Add ("Costa Rica"); countryList.Add ("Cote d'Ivoire"); countryList.Add ("Croatia"); countryList.Add ("Cuba"); countryList.Add ("Cyprus"); countryList.Add ("Czech Republic"); countryList.Add ("Denmark"); countryList.Add ("Dhekelia"); countryList.Add ("Djibouti"); countryList.Add ("Dominica"); countryList.Add ("Dominican Republic"); countryList.Add ("Ecuador"); countryList.Add ("Egypt"); countryList.Add ("El Salvador"); countryList.Add ("Equatorial Guinea"); countryList.Add ("Eritrea"); countryList.Add ("Estonia"); countryList.Add ("Ethiopia"); countryList.Add ("Europa Island"); countryList.Add ("Falkland Islands (Islas Malvinas)"); countryList.Add ("Faroe Islands"); countryList.Add ("Fiji"); countryList.Add ("Finland"); countryList.Add ("France"); countryList.Add ("French Guiana"); countryList.Add ("French Polynesia"); countryList.Add ("French Southern and Antarctic Lands"); countryList.Add ("Gabon"); countryList.Add ("Gambia, The"); countryList.Add ("Gaza Strip"); countryList.Add ("Georgia"); countryList.Add ("Germany"); countryList.Add ("Ghana"); countryList.Add ("Gibraltar"); countryList.Add ("Glorioso Islands"); countryList.Add ("Greece"); countryList.Add ("Greenland"); countryList.Add ("Grenada"); countryList.Add ("Guadeloupe"); countryList.Add ("Guam"); countryList.Add ("Guatemala"); countryList.Add ("Guernsey"); countryList.Add ("Guinea"); countryList.Add ("Guinea-Bissau"); countryList.Add ("Guyana"); countryList.Add ("Haiti"); countryList.Add ("Heard Island and McDonald Islands"); countryList.Add ("Holy See (Vatican City)"); countryList.Add ("Honduras"); countryList.Add ("Hong Kong"); countryList.Add ("Hungary"); countryList.Add ("Iceland"); countryList.Add ("India"); countryList.Add ("Indonesia"); countryList.Add ("Iran"); countryList.Add ("Iraq"); countryList.Add ("Ireland"); countryList.Add ("Isle of Man"); countryList.Add ("Israel"); countryList.Add ("Italy"); countryList.Add ("Jamaica"); countryList.Add ("Jan Mayen"); countryList.Add ("Japan"); countryList.Add ("Jersey"); countryList.Add ("Jordan"); countryList.Add ("Juan de Nova Island"); countryList.Add ("Kazakhstan"); countryList.Add ("Kenya"); countryList.Add ("Kiribati"); countryList.Add ("Korea, North"); countryList.Add ("Korea, South"); countryList.Add ("Kuwait"); countryList.Add ("Kyrgyzstan"); countryList.Add ("Laos"); countryList.Add ("Latvia"); countryList.Add ("Lebanon"); countryList.Add ("Lesotho"); countryList.Add ("Liberia"); countryList.Add ("Libya"); countryList.Add ("Liechtenstein"); countryList.Add ("Lithuania"); countryList.Add ("Luxembourg"); countryList.Add ("Macau"); countryList.Add ("Macedonia"); countryList.Add ("Madagascar"); countryList.Add ("Malawi"); countryList.Add ("Malaysia"); countryList.Add ("Maldives"); countryList.Add ("Mali"); countryList.Add ("Malta"); countryList.Add ("Marshall Islands"); countryList.Add ("Martinique"); countryList.Add ("Mauritania"); countryList.Add ("Mauritius"); countryList.Add ("Mayotte"); countryList.Add ("Mexico"); countryList.Add ("Micronesia, Federated States of"); countryList.Add ("Moldova"); countryList.Add ("Monaco"); countryList.Add ("Mongolia"); countryList.Add ("Montserrat"); countryList.Add ("Morocco"); countryList.Add ("Mozambique"); countryList.Add ("Namibia"); countryList.Add ("Nauru"); countryList.Add ("Navassa Island"); countryList.Add ("Nepal"); countryList.Add ("Netherlands"); countryList.Add ("Netherlands Antilles"); countryList.Add ("New Caledonia"); countryList.Add ("New Zealand"); countryList.Add ("Nicaragua"); countryList.Add ("Niger"); countryList.Add ("Nigeria"); countryList.Add ("Niue"); countryList.Add ("Norfolk Island"); countryList.Add ("Northern Mariana Islands"); countryList.Add ("Norway"); countryList.Add ("Oman"); countryList.Add ("Pakistan"); countryList.Add ("Palau"); countryList.Add ("Panama"); countryList.Add ("Papua New Guinea"); countryList.Add ("Paracel Islands"); countryList.Add ("Paraguay"); countryList.Add ("Peru"); countryList.Add ("Philippines"); countryList.Add ("Pitcairn Islands"); countryList.Add ("Poland"); countryList.Add ("Portugal"); countryList.Add ("Puerto Rico"); countryList.Add ("Qatar"); countryList.Add ("Reunion"); countryList.Add ("Romania"); countryList.Add ("Russia"); countryList.Add ("Rwanda"); countryList.Add ("Saint Helena"); countryList.Add ("Saint Kitts and Nevis"); countryList.Add ("Saint Lucia"); countryList.Add ("Saint Pierre and Miquelon"); countryList.Add ("Saint Vincent and the Grenadines"); countryList.Add ("Samoa"); countryList.Add ("San Marino"); countryList.Add ("Sao Tome and Principe"); countryList.Add ("Saudi Arabia"); countryList.Add ("Senegal"); countryList.Add ("Serbia and Montenegro"); countryList.Add ("Seychelles"); countryList.Add ("Sierra Leone"); countryList.Add ("Singapore"); countryList.Add ("Slovakia"); countryList.Add ("Slovenia"); countryList.Add ("Solomon Islands"); countryList.Add ("Somalia"); countryList.Add ("South Africa"); countryList.Add ("South Georgia and the South Sandwich Islands"); countryList.Add ("Spain"); countryList.Add ("Spratly Islands"); countryList.Add ("Sri Lanka"); countryList.Add ("Sudan"); countryList.Add ("Suriname"); countryList.Add ("Svalbard"); countryList.Add ("Swaziland"); countryList.Add ("Sweden"); countryList.Add ("Switzerland"); countryList.Add ("Syria"); countryList.Add ("Taiwan"); countryList.Add ("Tajikistan"); countryList.Add ("Tanzania"); countryList.Add ("Thailand"); countryList.Add ("Timor-Leste"); countryList.Add ("Togo"); countryList.Add ("Tokelau"); countryList.Add ("Tonga"); countryList.Add ("Trinidad and Tobago"); countryList.Add ("Tromelin Island"); countryList.Add ("Tunisia"); countryList.Add ("Turkey"); countryList.Add ("Turkmenistan"); countryList.Add ("Turks and Caicos Islands"); countryList.Add ("Tuvalu"); countryList.Add ("Uganda"); countryList.Add ("Ukraine"); countryList.Add ("United Arab Emirates"); countryList.Add ("United Kingdom"); countryList.Add ("United States"); countryList.Add ("Uruguay"); countryList.Add ("Uzbekistan"); countryList.Add ("Vanuatu"); countryList.Add ("Venezuela"); countryList.Add ("Vietnam"); countryList.Add ("Virgin Islands"); countryList.Add ("Wake Island"); countryList.Add ("Wallis and Futuna"); countryList.Add ("West Bank"); countryList.Add ("Western Sahara"); countryList.Add ("Yemen"); countryList.Add ("Zambia"); countryList.Add ("Zimbabwe"); } public List<String> Country { get { return countryList; } } } } <file_sep>/Android/SampleBrowser/Samples/Maps/TicketBooking.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.Graphics; using Android.Views; using Android.Widget; using Com.Syncfusion.Maps; using Org.Json; namespace SampleBrowser { public class TicketBooking : SamplePage { GridLayout gridlayout; View view; LinearLayout linearLayoutChild; Button ClearSelection; TextView SelectedLabel, SelectedLabelCount; SfMaps maps; public override Android.Views.View GetSampleContent(Android.Content.Context context) { LayoutInflater layoutInflater = LayoutInflater.From(context); view = layoutInflater.Inflate(Resource.Layout.TicketBooking, null); gridlayout = (GridLayout)view; maps = new SfMaps(context); ShapeFileLayer layer = new ShapeFileLayer(); layer.ShowItems = true; layer.EnableSelection = true; layer.Uri = "Custom.shp"; layer.DataSource = GetDataSource(); layer.SelectionMode = SelectionMode.Multiple; layer.ShapeSettings.SelectedShapeColor = Color.Rgb(98, 170, 95); layer.GeometryType = GeometryType.Points; layer.ShapeSelected += (object sender, ShapeFileLayer.ShapeSelectedEventArgs e) => { JSONObject data = (JSONObject)e.P0; if (data != null) { UpdateSelection(); } }; layer.SelectedItems.CollectionChanged += SelectedItems_CollectionChanged; layer.ShapeSettings.ShapeStrokeThickess = 2; SetColorMapping(layer.ShapeSettings); layer.ShapeSettings.ShapeColorValuePath = "SeatNumber"; layer.ShapeIdTableField = "seatno"; layer.ShapeIdPath = "SeatNumber"; maps.Layers.Add(layer); maps.SetPadding(10, 0, 0, 0); linearLayoutChild = (LinearLayout)view.FindViewById(Resource.Id.linear); ClearSelection = (Button)view.FindViewById(Resource.Id.ClearSelection); ClearSelection.Click += (object sender, EventArgs e) => { if ((maps.Layers[0] as ShapeFileLayer).SelectedItems.Count != 0) { (maps.Layers[0] as ShapeFileLayer).SelectedItems.Clear(); SelectedLabel.Text = ""; SelectedLabelCount.Text = "" + (maps.Layers[0] as ShapeFileLayer).SelectedItems.Count; //ClearSelection.Visibility = ViewStates.Invisible; ClearSelection.Alpha = 0.5f; ClearSelection.Enabled = false; } }; SelectedLabel = (TextView)view.FindViewById(Resource.Id.SelectedLabel); SelectedLabelCount=(TextView)view.FindViewById(Resource.Id.SelectedLabelCount); linearLayoutChild.AddView(maps); return gridlayout; } private void SelectedItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove) { UpdateSelection(); } } void UpdateSelection() { string selected = ""; string selectedSeat = ""; if ((maps.Layers[0] as ShapeFileLayer).SelectedItems.Count == 0) { SelectedLabel.Text = "" + selected; SelectedLabelCount.Text = "" + (maps.Layers[0] as ShapeFileLayer).SelectedItems.Count; //ClearSelection.Visibility = ViewStates.Invisible; ClearSelection.Alpha = 0.5f; ClearSelection.Enabled = false; } else { for (int i = 0; i < (maps.Layers[0] as ShapeFileLayer).SelectedItems.Count; i++) { JSONObject item = (JSONObject)(maps.Layers[0] as ShapeFileLayer).SelectedItems[i]; object SeatNo = item.Get("SeatNumber"); selectedSeat = SeatNo.ToString(); if (selectedSeat == "1" || selectedSeat == "2" || selectedSeat == "8" || selectedSeat == "9") { (maps.Layers[0] as ShapeFileLayer).SelectedItems.Remove(item); } else { if ((maps.Layers[0] as ShapeFileLayer).SelectedItems.Count <= 1) selected += ("S" + selectedSeat); else if (i == (maps.Layers[0] as ShapeFileLayer).SelectedItems.Count - 1) selected += ("S" + selectedSeat); else selected += ("S" + selectedSeat + ", "); } } // ClearSelection.Visibility = ViewStates.Visible; ClearSelection.Alpha = 1f; ClearSelection.Enabled = true; SelectedLabel.Text = selected; SelectedLabelCount.Text = "" + (maps.Layers[0] as ShapeFileLayer).SelectedItems.Count; } } JSONArray GetDataSource() { JSONArray array = new JSONArray(); for (int i = 1; i < 22; i++) { array.Put(getJsonObject(""+i)); } return array; } JSONObject getJsonObject(String Seatnumber) { JSONObject obj = new JSONObject(); obj.Put("SeatNumber", Seatnumber); return obj; } void SetColorMapping(ShapeSetting setting) { List<ColorMapping> colorMappings = new List<ColorMapping>(); EqualColorMapping colorMapping2 = new EqualColorMapping(); colorMapping2.Value = "1"; colorMapping2.Color = Color.ParseColor("#FFA500"); colorMappings.Add(colorMapping2); EqualColorMapping colorMapping3 = new EqualColorMapping(); colorMapping3.Value = "2"; colorMapping3.Color = Color.ParseColor("#FFA500"); colorMappings.Add(colorMapping3); EqualColorMapping colorMapping4 = new EqualColorMapping(); colorMapping4.Value = "8"; colorMapping4.Color = Color.ParseColor("#FFA500"); colorMappings.Add(colorMapping4); EqualColorMapping colorMapping1 = new EqualColorMapping(); colorMapping1.Value = "9"; colorMapping1.Color = Color.ParseColor("#FFA500"); colorMappings.Add(colorMapping1); setting.ColorMapping = colorMappings; } } } <file_sep>/iOS/SampleBrowser/Samples/Chart/DateTimeAxis.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Foundation; using Syncfusion.SfChart.iOS; using UIKit; namespace SampleBrowser { public class DateTimeAxis : SampleView { int month = int.MaxValue; public DateTimeAxis() { SFChart chart = new SFChart(); chart.Title.Text = (NSString)"Food Production - 2017"; chart.PrimaryAxis = new SFDateTimeAxis() { ZoomFactor = 0.1f, ZoomPosition = 0.6f, EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift }; chart.PrimaryAxis.LabelCreated += (sender, e) => { var date = DateTime.Parse(e.AxisLabel.LabelContent.ToString()); NSDateFormatter formatter = new NSDateFormatter(); if (date.Month != month) { SFAxisLabelStyle labelStyle = new SFAxisLabelStyle(); formatter.DateFormat = new NSString("MMM-dd"); labelStyle.LabelFormatter = formatter; labelStyle.Font = UIFont.FromName("Helvetica-Bold", 9); e.AxisLabel.LabelStyle = labelStyle; month = date.Month; } else { SFAxisLabelStyle labelStyle = new SFAxisLabelStyle(); formatter.DateFormat = new NSString("dd"); labelStyle.LabelFormatter = formatter; e.AxisLabel.LabelStyle = labelStyle; } }; chart.PrimaryAxis.Title.Text = (NSString)"Production Across Years"; chart.SecondaryAxis = new SFNumericalAxis(); chart.SecondaryAxis.Title.Text = (NSString)"Growth (In Metric Tons)"; ChartViewModel dataModel = new ChartViewModel(); SFFastLineSeries series = new SFFastLineSeries(); series.ColorModel.Palette = SFChartColorPalette.Natural; series.ItemsSource = dataModel.DateTimeAxisData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; chart.Series.Add(series); SFChartZoomPanBehavior zoomPan = new SFChartZoomPanBehavior(); zoomPan.EnableSelectionZooming = false; zoomPan.ZoomMode = SFChartZoomMode.X; chart.Behaviors.Add(zoomPan); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } } <file_sep>/Forms/PDF/PDF/Samples/Redaction/Redaction.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Pdf; using System; using System.IO; using Xamarin.Forms; using System.Reflection; using SampleBrowser.Core; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Redaction; namespace SampleBrowser.PDF { public partial class Redaction : SampleView { public Redaction() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } private void ButtonView_Click(object sender, EventArgs e) { #if COMMONSB Stream documentStream = typeof(RemoveImage).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.RedactionTemplate.pdf"); #else Stream documentStream = typeof(RemoveImage).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.RedactionTemplate.pdf"); #endif MemoryStream stream = new MemoryStream(); documentStream.CopyTo(stream); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("RedactionTemplate.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("RedactionTemplate.pdf", "application/pdf", stream); } void OnButtonClicked(object sender, EventArgs e) { //Load Tiff image to stream. #if COMMONSB Stream documentStream = typeof(Redaction).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.RedactionTemplate.pdf"); #else Stream documentStream = typeof(Redaction).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.RedactionTemplate.pdf"); #endif //Load the PDF document from stream. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream); PdfLoadedPage lpage = loadedDocument.Pages[0] as PdfLoadedPage; //Create PDF redaction for the page to redact text PdfRedaction textRedaction = new PdfRedaction(new Syncfusion.Drawing.RectangleF(477f, 154f, 62.709f, 16.802f), Syncfusion.Drawing.Color.Black); PdfRedaction textRedaction2 = new PdfRedaction(new Syncfusion.Drawing.RectangleF(70, 240, 65.709f, 16.802f), Syncfusion.Drawing.Color.Black); PdfRedaction imageRedaction = new PdfRedaction(new Syncfusion.Drawing.RectangleF(52.14447f, 712.1465f, 126.10835f, 81.45297f), Syncfusion.Drawing.Color.Black); lpage.AddRedaction(textRedaction); lpage.AddRedaction(textRedaction2); lpage.AddRedaction(imageRedaction); loadedDocument.Redact(); MemoryStream stream = new MemoryStream(); //Saves the PDF to the memory stream. loadedDocument.Save(stream); loadedDocument.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Redaction.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("Redaction.pdf", "application/pdf", stream); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/FrozenRow/FrozenRowBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "FrozenRowBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.GridCommon.ScrollAxis; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the FrozenRow samples /// </summary> public class FrozenRowBehavior : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private RelativeLayout relativeLayout; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">A sampleView type of parameter bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.dataGrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.relativeLayout = bindAble.FindByName<RelativeLayout>("relative"); this.dataGrid.GridLoaded += this.DataGrid_GridLoaded; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">A sampleView type of bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.dataGrid.GridLoaded -= this.DataGrid_GridLoaded; this.dataGrid = null; this.relativeLayout = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Fired when DataGrid is loaded /// </summary> /// <param name="sender">DataGrid_GridLoaded event sender</param> /// <param name="e">GridLoadedEventArgs of e</param> private void DataGrid_GridLoaded(object sender, GridLoadedEventArgs e) { var point = this.dataGrid.RowColumnIndexToPoint(new RowColumnIndex(this.dataGrid.FrozenRowsCount, 0)); BoxView boxView = new BoxView(); boxView.HeightRequest = 1.0; boxView.BackgroundColor = Color.FromHex("#757575"); boxView.Opacity = 100; this.relativeLayout.Children.Add(boxView, Constraint.Constant(point.X), Constraint.Constant(point.Y + this.dataGrid.RowHeight), widthConstraint: Constraint.RelativeToParent((parent) => { return parent.Width; })); } } } <file_sep>/Forms/PDF/PDF/Samples/Conformance/Conformance.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Xamarin.Forms; using System.IO; using SampleBrowser.Core; using System.Reflection; using Syncfusion.Pdf.Interactive; namespace SampleBrowser.PDF { public partial class Conformance : SampleView { public Conformance() { InitializeComponent(); this.comformance.Items.Add("PDF/A-1a"); this.comformance.Items.Add("PDF/A-1b"); this.comformance.Items.Add("PDF/A-2a"); this.comformance.Items.Add("PDF/A-2b"); this.comformance.Items.Add("PDF/A-2u"); this.comformance.Items.Add("PDF/A-3a"); this.comformance.Items.Add("PDF/A-3b"); this.comformance.Items.Add("PDF/A-3u"); this.comformance.SelectedIndex = 0; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { PdfDocument document = null; if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-1a") { //Create a new PDF document document = new PdfDocument(PdfConformanceLevel.Pdf_A1A); } else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-1b") { document = new PdfDocument(PdfConformanceLevel.Pdf_A1B); } else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-2a") { document = new PdfDocument(PdfConformanceLevel.Pdf_A2A); } else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-2b") { document = new PdfDocument(PdfConformanceLevel.Pdf_A2B); } else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-2u") { document = new PdfDocument(PdfConformanceLevel.Pdf_A2U); } else { if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-3a") { document = new PdfDocument(PdfConformanceLevel.Pdf_A3A); } else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-3b") { document = new PdfDocument(PdfConformanceLevel.Pdf_A3B); } else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-3u") { document = new PdfDocument(PdfConformanceLevel.Pdf_A3U); } #if COMMONSB Stream imgStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Products.xml"); #else Stream imgStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Products.xml"); #endif PdfAttachment attachment = new PdfAttachment("PDF_A.xml",imgStream); attachment.Relationship = PdfAttachmentRelationship.Alternative; attachment.ModificationDate = DateTime.Now; attachment.Description = "PDF_A"; attachment.MimeType = "application/xml"; document.Attachments.Add(attachment); } //Add a page PdfPage page = document.Pages.Add(); //Create font #if COMMONSB Stream arialFontStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.arial.ttf"); Stream imageStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.AdventureCycle.jpg"); #else Stream arialFontStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.arial.ttf"); Stream imageStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.AdventureCycle.jpg"); #endif PdfFont font = new PdfTrueTypeFont(arialFontStream, 14); //Create PDF graphics for the page. PdfGraphics graphics = page.Graphics; //Load the image from the disk. PdfImage img = PdfImage.FromStream(imageStream); //Draw the image in the specified location and size. graphics.DrawImage(img, new RectangleF(150, 30, 200, 100)); PdfTextElement textElement = new PdfTextElement("Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based," + " is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, " + "European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional" + " sales teams are located throughout their market base.") { Font = font }; PdfLayoutResult layoutResult = textElement.Draw(page, new RectangleF(0, 150, page.GetClientSize().Width, page.GetClientSize().Height)); MemoryStream stream = new MemoryStream(); //Save the PDF document. document.Save(stream); //Close the PDF document. document.Close(); stream.Position = 0; if ( Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("PDF_A.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("PDF_A.pdf", "application/pdf", stream); } } } <file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/DropDownMenuItem.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; namespace SampleBrowser { /// <summary> /// Drop down list item. /// </summary> public class DropDownMenuItem{ /// <summary> /// Gets or sets the display text. /// </summary> /// <value>The display text.</value> public string DisplayText { get; set; } /// <summary> /// Gets or sets the item. /// </summary> public bool IsSelected { get; set; } } } <file_sep>/Forms/PDF/PDF/Samples/OpenTypeFont/OpenTypeFont.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Xamarin.Forms; using System.IO; using SampleBrowser.Core; using System.Reflection; namespace SampleBrowser.PDF { public partial class OpenTypeFont : SampleView { public OpenTypeFont() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { //Create a new PDF document PdfDocument document = new PdfDocument(); //Add a page PdfPage page = document.Pages.Add(); //Create font #if COMMONSB Stream fontStream = typeof(OpenTypeFont).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.NotoSerif-Black.otf"); #else Stream fontStream = typeof(OpenTypeFont).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.NotoSerif-Black.otf"); #endif PdfFont font = new PdfTrueTypeFont(fontStream, 14); //Text to draw string text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; //Create a brush PdfBrush brush = new PdfSolidBrush(new PdfColor(0, 0, 0)); PdfPen pen = new PdfPen(new PdfColor(0,0,0)); SizeF clipBounds = page.Graphics.ClientSize; RectangleF rect = new RectangleF(0, 0, clipBounds.Width, clipBounds.Height); //Draw text. page.Graphics.DrawString(text, font, brush, rect); MemoryStream stream = new MemoryStream(); //Save the PDF document. document.Save(stream); //Close the PDF document. document.Close(); stream.Position = 0; if ( Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("OpenTypeFont.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("OpenTypeFont.pdf", "application/pdf", stream); } } } <file_sep>/Android/SampleBrowser/Properties/AssemblyInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("SampleBrowser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Syncfusion Inc.")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Copyright © 2001-2023 Syncfusion Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.0")] [assembly: ComVisible(false)]<file_sep>/Forms/Rotator/Rotator/Samples/Rotator/Rotator_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Xamarin.Forms; using Syncfusion.SfRotator.XForms; using SampleBrowser.Core; namespace SampleBrowser.SfRotator { public partial class Rotator_Default : SampleView { void Handle_ClickedAdd(object sender, System.EventArgs e) { totalCart++; TotalCart.Text = "(" + totalCart.ToString() + ")"; } int totalCart = 0; void Handle_ClickedBuy(object sender, System.EventArgs e) { //App.Current.MainPage.DisplayAlert("Order Details", "Order has been placed successfully", "OK"); } void Handle_Clicked(object sender, System.EventArgs e) { mButton.BackgroundColor = sButton.BackgroundColor = xButton.BackgroundColor = xLButton.BackgroundColor = Color.White; mButton.TextColor = sButton.TextColor = xButton.TextColor = xLButton.TextColor = Color.Black; (sender as Button).BackgroundColor = Color.FromHex("#f1852a"); (sender as Button).TextColor = Color.White; } double width; public Rotator_Default() { InitializeComponent(); width = Core.SampleBrowser.ScreenWidth; sfRotator.BindingContext = new RotatorViewModel(); SettingsWindow(); sfRotator.SelectedIndex = 1; ratingImage.Margin = new Thickness(10, 0, 2, 0); if (Device.RuntimePlatform == Device.UWP) { List<SfRotatorItem> rotatoritems = new List<SfRotatorItem>(); rotatoritems.Add(new SfRotatorItem() { Image = ImagePathConverter.GetImageSource("SampleBrowser.SfRotator.Duck0.png") }); rotatoritems.Add(new SfRotatorItem() { Image = ImagePathConverter.GetImageSource("SampleBrowser.SfRotator.Duck1.png") }); rotatoritems.Add(new SfRotatorItem() { Image = ImagePathConverter.GetImageSource("SampleBrowser.SfRotator.Duck2.png") }); rotatoritems.Add(new SfRotatorItem() { Image = ImagePathConverter.GetImageSource("SampleBrowser.SfRotator.Duck3.png") }); rotatoritems.Add(new SfRotatorItem() { Image = ImagePathConverter.GetImageSource("SampleBrowser.SfRotator.Duck4.png") }); rotatoritems.Add(new SfRotatorItem() { Image = ImagePathConverter.GetImageSource("SampleBrowser.SfRotator.Duck5.png") }); sfRotator.ItemsSource = null; sfRotator.ItemsSource = rotatoritems; mButton.FontSize = 22; xLButton.FontSize = 22; sButton.FontSize = 22; xButton.FontSize = 22; if (Device.Idiom != TargetIdiom.Phone) { maingrid.HorizontalOptions = LayoutOptions.Center; grid.HorizontalOptions = LayoutOptions.Start; grid.Margin = new Thickness(10); header.HorizontalOptions = LayoutOptions.Start; header.Margin = new Thickness(10,0,10,0); header.WidthRequest = 550; grid.WidthRequest = 550; controlsize.Height = 315; sfRotator.HeightRequest = 250; } else { controlsize.Height = 270; sfRotator.HeightRequest = 270; sfRotator.WidthRequest = 260; } } else if(Device.RuntimePlatform == Device.Android) { root.HorizontalOptions = LayoutOptions.Center; } if (Device.RuntimePlatform == Device.iOS) sfRotator.NavigationStripPosition = NavigationStripPosition.Bottom; sfRotator.HeightRequest = sfRotator.WidthRequest; mButton.BackgroundColor = sButton.BackgroundColor = xButton.BackgroundColor = xLButton.BackgroundColor = Color.White; mButton.TextColor = sButton.TextColor = xButton.TextColor = xLButton.TextColor = Color.Black; } private void SettingsWindow() { directionPicker.Items.Add("BottomToTop"); directionPicker.Items.Add("Horizontal"); directionPicker.Items.Add("LeftToRight"); directionPicker.Items.Add("RightToLeft"); directionPicker.Items.Add("TopToBottom"); directionPicker.Items.Add("Vertical"); directionPicker.SelectedIndex = 1; directionPicker.SelectedIndexChanged += picker1_SelectedIndexChanged; tabPicker.Items.Add("Bottom"); tabPicker.Items.Add("Top"); tabPicker.Items.Add("Left"); tabPicker.Items.Add("Right"); tabPicker.SelectedIndex = 3; modePicker.Items.Add("Dots"); modePicker.Items.Add("Thumbnail"); modePicker.SelectedIndex = 1; tabPicker.SelectedIndexChanged += picker2_SelectedIndexChanged; modePicker.SelectedIndexChanged += picker3_SelectedIndexChanged; toggleButton.Toggled += toggleStateChanged; if (Device.RuntimePlatform == Device.Android) { mButton.FontSize = 15; sButton.FontSize = 15; xButton.FontSize = 15; xLButton.FontSize = 15; } else if (Device.RuntimePlatform == Device.iOS) { sfRotator.WidthRequest = width; // sfRotator.HeightRequest = App.ScreenWidth; emptyLabel.WidthRequest = 200; } if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { emptyLabel.WidthRequest = 150; directionPicker.HeightRequest = 90; tabPicker.HeightRequest = 90; directionLabel.Text = " " + "Tick Placement"; directionLabel.HeightRequest = 22; tabLabel.Text = " " + "Label Placement"; tabLabel.HeightRequest = 22; modeLabel.Text = " " + "Label Placement"; modeLabel.HeightRequest = 22; emptyLabel.Text = " " + "Label"; emptyLabel.HeightRequest = 22; } } void picker1_SelectedIndexChanged(object sender, EventArgs e) { switch (directionPicker.SelectedIndex) { case 0: { sfRotator.NavigationDirection = NavigationDirection.BottomToTop; break; } case 1: { sfRotator.NavigationDirection = NavigationDirection.Horizontal; break; } case 2: { sfRotator.NavigationDirection = NavigationDirection.LeftToRight; break; } case 3: { sfRotator.NavigationDirection = NavigationDirection.RightToLeft; break; } case 4: { sfRotator.NavigationDirection = NavigationDirection.TopToBottom; break; } case 5: { sfRotator.NavigationDirection = NavigationDirection.Vertical; break; } } } void picker2_SelectedIndexChanged(object sender, EventArgs e) { switch (tabPicker.SelectedIndex) { case 0: { sfRotator.NavigationStripPosition = NavigationStripPosition.Bottom; break; } case 1: { sfRotator.NavigationStripPosition = NavigationStripPosition.Top; break; } case 2: { sfRotator.NavigationStripPosition = NavigationStripPosition.Left; break; } case 3: { sfRotator.NavigationStripPosition = NavigationStripPosition.Right; break; } } } void picker3_SelectedIndexChanged(object sender, EventArgs e) { switch (modePicker.SelectedIndex) { case 0: { sfRotator.NavigationStripMode = NavigationStripMode.Dots; break; } case 1: { sfRotator.NavigationStripMode = NavigationStripMode.Thumbnail; break; } } } void toggleStateChanged(object sender, ToggledEventArgs e) { sfRotator.EnableAutoPlay = e.Value; } public View getContent() { return this.Content; } public View getPropertyView() { return this.PropertyView; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/EmployeeInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "EmployeeInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws.// </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties and notifies clients that a property value has changed. /// </summary> public class EmployeeInfo : INotifyPropertyChanged { #region private variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int salary; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int employeeID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string name; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string title; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string company; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int age; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double bonus; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private bool isavaialble; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string doj; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string imagename; #endregion /// <summary> /// Initializes a new instance of the EmployeeInfo class. /// </summary> public EmployeeInfo() { } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the value of EmployeeID and notifies user when value gets changed /// </summary> public int EmployeeID { get { return this.employeeID; } set { this.employeeID = value; this.RaisePropertyChanged("EmployeeID"); } } /// <summary> /// Gets or sets the value of Name and notifies user when value gets changed /// </summary> public string Name { get { return this.name; } set { this.name = value; this.RaisePropertyChanged("Name"); } } /// <summary> /// Gets or sets the value of Age and notifies user when value gets changed /// </summary> public int Age { get { return this.age; } set { this.age = value; } } /// <summary> /// Gets or sets the value of Title and notifies user when value gets changed /// </summary> public string Title { get { return this.title; } set { this.title = value; this.RaisePropertyChanged("Title"); } } /// <summary> /// Gets or sets the value of Salary and notifies user when value gets changed /// </summary> public int Salary { get { return this.salary; } set { this.salary = value; this.RaisePropertyChanged("Salary"); } } /// <summary> /// Gets or sets the value of Company and notifies user when value gets changed /// </summary> public string Company { get { return this.company; } set { this.company = value; this.RaisePropertyChanged("Company"); } } /// <summary> /// Gets or sets the value of Bonus and notifies user when value gets changed /// </summary> public double Bonus { get { return this.bonus; } set { this.bonus = value; this.RaisePropertyChanged("Bonus"); } } /// <summary> /// Gets or sets a value indicating whether IsAvailable is true or false and notifies user when value gets changed /// </summary> public bool IsAvailable { get { return this.isavaialble; } set { this.isavaialble = value; this.RaisePropertyChanged("IsAvailable"); } } /// <summary> /// Gets or sets the value of DOJ and notifies user when value gets changed /// </summary> public string DOJ { get { return this.doj; } set { this.doj = value; this.RaisePropertyChanged("ShippingDate"); } } /// <summary> /// Gets or sets the value of ImageName and notifies user when value gets changed /// </summary> public string ImageName { get { return this.imagename; } set { this.imagename = value; this.RaisePropertyChanged("ImageName"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type of parameter name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } } <file_sep>/Forms/Cards/Cards/Samples/CardLayout/CardData.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; using Xamarin.Forms; namespace SampleBrowser.Cards { public class CardData : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string description; public string Description { get { return description; } set { description = value; OnPropertyChanged(); } } private string imagePath; public string ImagePath { get { return imagePath; } set { imagePath = value; OnPropertyChanged(); } } private string name; public string Name { get { return name; } set { name = value; OnPropertyChanged(); } } private double price; public double Price { get { return price; } set { price = value; OnPropertyChanged(); } } private string offer; public string Offer { get { return offer; } set { offer = value; OnPropertyChanged(); } } private string rating; public string Rating { get { return rating; } set { rating = value; OnPropertyChanged(); } } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/Forms/PdfViewer/PdfViewer/Samples/Helper/BookMarkHelperDesktop.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Pdf.Interactive; using Syncfusion.Pdf.Parsing; using Syncfusion.XForms.TabView; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfPdfViewer { internal class BookMarkPane : Grid { Grid bookmarkTitle = new Grid(); AbsoluteLayout absoluteLayoutContainer = new AbsoluteLayout(); Label bookmarkTitleText = new Label() { Text = "Bookmarks", FontSize = 16 }; ListView bookmarkView = new ListView(); ListView customBookmarkView = new ListView(); Syncfusion.SfPdfViewer.XForms.SfPdfViewer pdfViewer; StackLayout bookPane; IList<ContentBookmark> listViewItemsSource; ObservableCollection<BookmarkContextMenu> ContextMenuList = new ObservableCollection<BookmarkContextMenu>(); List<PdfBookmark> navigationQueue = new List<PdfBookmark>(); internal PdfLoadedDocument bookmarkLoadedDocument; Syncfusion.XForms.TabView.SfTabView tabView = new Syncfusion.XForms.TabView.SfTabView(); private Grid tabviewHeader_Content; private Grid tabviewHeader_Bookmark; internal Frame AddBookmarkButton; internal Label AddBookmarkLabel; internal Frame contextOptionsFrame; StackLayout contextOptions; internal Frame toastMessageFrame; internal Label messageLabel; double CustomBookmarkView_ScrollY; internal int selectedCustomBookmarkIndex; PDFViewerCustomToolbar_Desktop PDFViewerCustomToolbar_Desktop; internal Grid NobookmarksLabel { get; set; } internal Grid CustomNobookmarksLabel { get; set; } internal BookMarkPane(PDFViewerCustomToolbar_Desktop toolbar_Desktop) { pdfViewer = toolbar_Desktop.pdfViewer; bookPane = toolbar_Desktop.basePane; bookmarkLoadedDocument = toolbar_Desktop.bookmarkLoadedDocument; listViewItemsSource = toolbar_Desktop.ListViewItemsSource; this.PDFViewerCustomToolbar_Desktop = toolbar_Desktop; CreateToolBar(); } private void CreateToolBar() { bookmarkTitle = new Grid(); bookmarkTitle.HeightRequest = 40; bookmarkTitle.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); bookmarkTitle.ColumnDefinitions.Add(new ColumnDefinition() { Width = 32 }); bookmarkTitle.RowDefinitions.Add(new RowDefinition() { Height = 38 }); bookmarkTitle.RowDefinitions.Add(new RowDefinition() { Height = 2 }); bookmarkTitle.VerticalOptions = LayoutOptions.Start; Frame frame3 = new Frame() { BackgroundColor = Color.FromHex("#E0E0E0") }; Grid.SetColumnSpan(frame3, 2); Grid.SetRow(frame3, 1); bookmarkTitle.Children.Add(frame3); bookmarkTitle.RowSpacing = 10; bookmarkTitleText.HorizontalOptions = LayoutOptions.Start; bookmarkTitleText.VerticalOptions = LayoutOptions.Center; bookmarkTitleText.Margin = new Thickness(10, 10, 0, 0); bookmarkTitleText.FontSize = 15; bookmarkTitleText.TextColor = Color.FromHex("#000000"); bookmarkTitleText.FontFamily = "SegoeUI"; bookmarkTitleText.FontAttributes = FontAttributes.Bold; bookmarkTitle.Children.Add(bookmarkTitleText); Button closeButton = new Button() { WidthRequest = 30, HeightRequest = 30 }; closeButton.Text = "\uE701"; closeButton.FontFamily = "ms-appx:///Syncfusion.SfPdfViewer.XForms.UWP/Final_PDFViewer_UWP_FontUpdate.ttf#Final_PDFViewer_UWP_FontUpdate"; closeButton.FontSize = 12; closeButton.TextColor = Color.FromHex("#000000"); closeButton.BackgroundColor = Color.Transparent; closeButton.HorizontalOptions = LayoutOptions.End; closeButton.VerticalOptions = LayoutOptions.End; closeButton.Clicked += CloseButton_Clicked; Grid.SetColumn(closeButton, 1); Grid.SetRow(closeButton, 0); Grid.SetColumn(bookmarkTitleText, 0); Grid.SetRow(bookmarkTitleText, 0); bookmarkTitle.Children.Add(closeButton); Grid.SetRow(bookmarkTitle, 0); bookPane.Children.Add(bookmarkTitle); NobookmarksLabel = new Grid(); Label label = new Label() { Text = "No Bookmarks", FontSize = 15, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }; NobookmarksLabel.Children.Add(label); CustomNobookmarksLabel = new Grid(); Label customLabel = new Label() { Text = "No Bookmarks", FontSize = 15, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }; CustomNobookmarksLabel.Children.Add(customLabel); Grid.SetRow(absoluteLayoutContainer, 1); bookmarkView.HorizontalOptions = LayoutOptions.StartAndExpand; bookmarkView.VerticalOptions = LayoutOptions.StartAndExpand; bookmarkView.Margin = new Thickness(0, 3, 0, 0); bookmarkView.ItemsSource = listViewItemsSource; bookmarkView.ItemTapped += BookmarkView_ItemTapped; bookmarkView.ItemTemplate = new DataTemplate(() => { ViewCell viewCell = new ViewCell(); Grid view = new Grid(); Grid viewChild = new Grid(); viewChild.SetBinding(Grid.MarginProperty, "MarginForDesktop"); view.HeightRequest = 40; viewChild.ColumnDefinitions.Add(new ColumnDefinition() { Width = 40 }); viewChild.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); viewChild.ColumnDefinitions.Add(new ColumnDefinition() { Width = 40 }); Label bookmarkTitle = new Label(); bookmarkTitle.HorizontalOptions = LayoutOptions.StartAndExpand; bookmarkTitle.LineBreakMode = LineBreakMode.TailTruncation; bookmarkTitle.VerticalOptions = LayoutOptions.Center; bookmarkTitle.SetBinding(Label.TextProperty, "Title"); bookmarkTitle.FontFamily = "SegoeUI"; bookmarkTitle.FontSize = 13; Grid.SetColumn(bookmarkTitle, 1); Grid.SetRow(bookmarkTitle, 0); viewChild.Children.Add(bookmarkTitle); Button backToParentButton = new Button() { Text = FontMappingHelper.BookmarkBackward, TextColor = Color.FromHex("8A000000"), BackgroundColor = Color.Transparent }; backToParentButton.FontFamily = FontMappingHelper.BookmarkFont; backToParentButton.FontSize = 24; backToParentButton.Clicked += BackToParentButton_Clicked; backToParentButton.HorizontalOptions = LayoutOptions.Start; backToParentButton.VerticalOptions = LayoutOptions.Start; Grid.SetRow(backToParentButton, 0); Grid.SetColumn(backToParentButton, 0); viewChild.Children.Add(backToParentButton); backToParentButton.SetBinding(IsVisibleProperty, "IsBackToParentButtonVisible"); Button expandButton = new Button() { Text = FontMappingHelper.BookmarkForward, TextColor = Color.FromHex("8A000000"), BackgroundColor = Color.Transparent }; expandButton.SetBinding(SfFontButton.CommandParameterProperty, "."); expandButton.FontFamily = FontMappingHelper.BookmarkFont; expandButton.FontSize = 24; expandButton.Clicked += BookmarkExpand_Clicked; expandButton.HorizontalOptions = LayoutOptions.End; expandButton.VerticalOptions = LayoutOptions.End; Grid.SetRow(expandButton, 0); Grid.SetColumn(expandButton, 2); viewChild.Children.Add(expandButton); expandButton.SetBinding(IsVisibleProperty, "IsExpandButtonVisible"); view.Children.Add(viewChild); viewCell.View = view; return viewCell; }); customBookmarkView.HorizontalOptions = LayoutOptions.Center; customBookmarkView.VerticalOptions = LayoutOptions.Start; customBookmarkView.ItemsSource = pdfViewer.CustomBookmarks; customBookmarkView.Scrolled += CustomBookmarkView_Scrolled; customBookmarkView.ItemTapped += CustomBookmarkView_ItemTapped; customBookmarkView.ItemTemplate = new DataTemplate(() => { ViewCell viewCell = new ViewCell(); Grid view = new Grid(); Grid viewChild = new Grid(); viewChild.SetBinding(Grid.MarginProperty, "MarginForDesktop"); view.HeightRequest = 40; viewChild.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); viewChild.ColumnDefinitions.Add(new ColumnDefinition() { Width = 32 }); Label bookmarkLabel = new Label() { TextColor = Color.FromHex("#000000") }; bookmarkLabel.Margin = new Thickness(12, 8, 0, 9); bookmarkLabel.LineBreakMode = LineBreakMode.TailTruncation; bookmarkLabel.VerticalOptions = LayoutOptions.Center; bookmarkLabel.SetBinding(Label.TextProperty, "Name"); bookmarkLabel.FontFamily = "SegoeUI"; bookmarkLabel.FontSize = 12; Grid.SetColumn(bookmarkLabel, 0); SfFontButton popUpMenuButton = new SfFontButton() { Text="\uE711", HeightRequest=30, WidthRequest=30}; popUpMenuButton.FontFamily = FontMappingHelper.FontFamily; popUpMenuButton.BackgroundColor = Color.Transparent; popUpMenuButton.TextColor = Color.FromHex("#000000"); popUpMenuButton.HorizontalOptions = LayoutOptions.Center; popUpMenuButton.VerticalOptions = LayoutOptions.Center; popUpMenuButton.Clicked += PopUpMenuButton_Clicked; popUpMenuButton.Margin = new Thickness(0, 10, 12, 10); Grid.SetColumn(popUpMenuButton, 1); viewChild.Children.Add(bookmarkLabel); viewChild.Children.Add(popUpMenuButton); view.Children.Add(viewChild); viewCell.View = view; return viewCell; }); tabviewHeader_Content = new Grid(); Label Bookmark_DefaultHeader = new Label(); Bookmark_DefaultHeader.WidthRequest = 40; Bookmark_DefaultHeader.FontFamily = FontMappingHelper.CustomBookmarkFont; Bookmark_DefaultHeader.Text = FontMappingHelper.Bookmark_Default; Bookmark_DefaultHeader.TextColor = Color.FromHex("#007CEE"); Bookmark_DefaultHeader.FontSize = 25; Bookmark_DefaultHeader.HorizontalOptions = LayoutOptions.Center; Bookmark_DefaultHeader.VerticalOptions = LayoutOptions.Center; Bookmark_DefaultHeader.HorizontalTextAlignment = TextAlignment.Center; Bookmark_DefaultHeader.VerticalTextAlignment = TextAlignment.Center; tabviewHeader_Content.Children.Add(Bookmark_DefaultHeader); tabviewHeader_Bookmark = new Grid(); Label Bookmark_CustomHeader = new Label(); Bookmark_CustomHeader.WidthRequest = 40; Bookmark_CustomHeader.FontFamily = FontMappingHelper.CustomBookmarkFont; Bookmark_CustomHeader.Text = FontMappingHelper.Bookmark_Custom; Bookmark_CustomHeader.FontSize = 20; Bookmark_CustomHeader.HorizontalOptions = LayoutOptions.Center; Bookmark_CustomHeader.VerticalOptions = LayoutOptions.Center; Bookmark_CustomHeader.HorizontalTextAlignment = TextAlignment.Center; Bookmark_CustomHeader.VerticalTextAlignment = TextAlignment.Center; tabviewHeader_Bookmark.Children.Add(Bookmark_CustomHeader); var tabItems = new TabItemCollection { new SfTabItem() { HorizontalOptions = LayoutOptions.CenterAndExpand, VerticalOptions = LayoutOptions.CenterAndExpand, Content = bookmarkView, HeaderContent=tabviewHeader_Content }, new SfTabItem() { HorizontalOptions = LayoutOptions.CenterAndExpand, VerticalOptions = LayoutOptions.CenterAndExpand, Content = customBookmarkView, HeaderContent=tabviewHeader_Bookmark }, }; tabView.TabHeight = 32; tabView.TabWidth = 140; tabView.Items = tabItems; tabView.SelectionChanged += TabView_SelectionChanged; AbsoluteLayout.SetLayoutFlags(tabView, AbsoluteLayoutFlags.All); AbsoluteLayout.SetLayoutBounds(tabView, new Rectangle(0, 0, 1, 1)); absoluteLayoutContainer.Children.Add(tabView); toastMessageFrame = new Frame() { IsVisible = false, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.End, CornerRadius = 4, HeightRequest = 32, WidthRequest = 129, BackgroundColor = Color.FromHex("#353535"), Padding = 0, Margin = new Thickness(0, 0, 0, 13) }; messageLabel = new Label() { BackgroundColor = Color.Transparent, HeightRequest = 20, Margin = new Thickness(0, 5, 0, 5), TextColor = Color.FromHex("#FFFFFF"), FontSize = 14, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center }; toastMessageFrame.Content = messageLabel; AddBookmarkLabel = new Label() { TextColor = Color.White, FontSize = 24, BackgroundColor = Color.Transparent, VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }; AddBookmarkButton = new Frame() { BackgroundColor = Color.FromHex("#007CEE"), Content = AddBookmarkLabel, HasShadow = false, Padding = 0 }; TapGestureRecognizer addGesture = new TapGestureRecognizer(); addGesture.Tapped += AddBookmarkButton_Clicked; AddBookmarkLabel.FontFamily = FontMappingHelper.CustomBookmarkFont; AddBookmarkLabel.Text = FontMappingHelper.Bookmark_Add; AddBookmarkButton.GestureRecognizers.Add(addGesture); AddBookmarkButton.CornerRadius = 34; AddBookmarkButton.HeightRequest = 68; AddBookmarkButton.WidthRequest = 68; VisualStateGroupList visualStateGroupList = new VisualStateGroupList(); VisualStateGroup commonStateGroup = new VisualStateGroup(); VisualState EnabledState = new VisualState() { Name = "Normal" }; EnabledState.Setters.Add(new Setter { Property = Button.BackgroundColorProperty, Value = Color.FromHex("#007CEE") }); VisualState DisabledState = new VisualState() { Name = "Disabled" }; DisabledState.Setters.Add(new Setter { Property = Button.BackgroundColorProperty, Value = Color.FromHex("#7BB9F2") }); AddBookmarkButton.Margin = new Thickness(0, 0, 26, 26); AbsoluteLayout.SetLayoutFlags(AddBookmarkButton, AbsoluteLayoutFlags.PositionProportional); AbsoluteLayout.SetLayoutBounds(AddBookmarkButton, new Rect(1, 1, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)); commonStateGroup.States.Add(EnabledState); commonStateGroup.States.Add(DisabledState); visualStateGroupList.Add(commonStateGroup); VisualStateManager.SetVisualStateGroups(AddBookmarkButton, visualStateGroupList); absoluteLayoutContainer.Children.Add(AddBookmarkButton); contextOptionsFrame = new Frame() { BorderColor = Color.FromHex("#D5D5D5"), IsVisible = false, Padding = 0, HasShadow = false, Margin = new Thickness(0, 0, 22, 0), CornerRadius = 4, HeightRequest = 88, WidthRequest = 149, BackgroundColor = Color.FromHex("#F6F6F6") }; contextOptionsFrame.SetBinding(Frame.IsVisibleProperty,"IsContextMenuVisible"); ListView ContextMenuListView = new ListView() { VerticalScrollBarVisibility = ScrollBarVisibility.Never }; ContextMenuListView.RowHeight = 40; ContextMenuListView.ItemsSource = ContextMenuList; ContextMenuListView.ItemTapped += ContextMenuListView_ItemTapped; ContextMenuList.Add(new BookmarkContextMenu(FontMappingHelper.RenameBookmark,"Rename")); ContextMenuList.Add(new BookmarkContextMenu(FontMappingHelper.DeleteBookmark, "Delete")); ContextMenuListView.ItemTemplate = new DataTemplate(() => { ViewCell viewCell = new ViewCell(); StackLayout stack = new StackLayout() { Orientation = StackOrientation.Horizontal }; Label Label = new Label() { TextColor = Color.FromHex("#000000") }; Label.VerticalOptions = LayoutOptions.Center; Label.HorizontalOptions = LayoutOptions.Center; Label.VerticalTextAlignment = TextAlignment.Center; Label.VerticalTextAlignment = TextAlignment.Center; Label.SetBinding(Label.TextProperty, "LabelText"); Label.FontFamily = "SegoeUI"; Label.FontSize = 12; Label Button = new Label() {WidthRequest=40, HorizontalTextAlignment=TextAlignment.Center, VerticalTextAlignment=TextAlignment.Center}; Button.FontFamily = FontMappingHelper.CustomBookmarkFont; Button.BackgroundColor = Color.Transparent; Button.TextColor = Color.FromHex("#000000"); Button.HorizontalOptions = LayoutOptions.Center; Button.VerticalOptions = LayoutOptions.Center; Button.SetBinding(Label.TextProperty, "IconText"); stack.Children.Add(Button); stack.Children.Add(Label); viewCell.View = stack; return viewCell; }); contextOptions = new StackLayout() { Orientation = StackOrientation.Vertical, BackgroundColor = Color.FromHex("#F6F6F6") , Margin= new Thickness(0,4,0,4) }; contextOptions.HeightRequest = 80; contextOptions.WidthRequest = 149; AbsoluteLayout.SetLayoutFlags(contextOptionsFrame, AbsoluteLayoutFlags.PositionProportional); AbsoluteLayout.SetLayoutBounds(contextOptionsFrame, new Rect(1, 0, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)); contextOptions.Children.Add(ContextMenuListView); contextOptionsFrame.Content = contextOptions; absoluteLayoutContainer.Children.Add(contextOptionsFrame); var hideComtextMenuTapGestureRecognizer = new TapGestureRecognizer(); customBookmarkView.GestureRecognizers.Add(hideComtextMenuTapGestureRecognizer); hideComtextMenuTapGestureRecognizer.Tapped += (sender, args) => { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; }; pdfViewer.CustomBookmarks.CollectionChanged += CustomBookmarks_CollectionChanged; BackgroundColor = Color.FromHex("#F6F6F6"); bookPane.WidthRequest = 280; bookPane.Children.Add(absoluteLayoutContainer); bookPane.Children.Add(this); } private void CustomBookmarks_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { UpdateCustomBookmarkView(); } internal void UpdateBookmarkContent() { if (absoluteLayoutContainer.Parent == null) { Children.Add(absoluteLayoutContainer); } if (bookmarkLoadedDocument.Bookmarks != null && bookmarkLoadedDocument.Bookmarks.Count == 0) { tabView.Items[0].Content = NobookmarksLabel; } else if (bookmarkLoadedDocument.Bookmarks.Count > 0) { tabView.Items[0].Content = bookmarkView; } } internal void UpdateCustomBookmarkView() { if (absoluteLayoutContainer.Parent == null) { Children.Add(absoluteLayoutContainer); } if (pdfViewer.CustomBookmarks.Count == 0) { tabView.Items[1].Content = CustomNobookmarksLabel; AddBookmarkButton.IsEnabled = true; } else if (pdfViewer.CustomBookmarks.Count != 0) { tabView.Items[1].Content = customBookmarkView; } } private void ContextMenuListView_ItemTapped(object sender, ItemTappedEventArgs e) { (sender as ListView).SelectedItem = null; if (e.ItemIndex == 0) { OnRenameOptions(sender); } else if (e.ItemIndex == 1) { OnDeleteOptions(sender); } } private void TabView_SelectionChanged(object sender, Syncfusion.XForms.TabView.SelectionChangedEventArgs e) { if ((BindingContext as PdfViewerViewModel).IsContextMenuVisible == true) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; } foreach (var item in tabView.Items) { if (e.Index == tabView.Items.IndexOf(item)) ((item.HeaderContent as Grid).Children[0] as Label).TextColor = Color.FromHex("#007CEE"); else ((item.HeaderContent as Grid).Children[0] as Label).TextColor = Color.Black; ; } } private void OnRenameOptions(object obj) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; PDFViewerCustomToolbar_Desktop.ToggleBookmarkPopup(); PDFViewerCustomToolbar_Desktop.BookmarkPopup.IsVisible = true; PDFViewerCustomToolbar_Desktop.BookmarkPopup.EditEntry.Text = pdfViewer.CustomBookmarks[this.selectedCustomBookmarkIndex].Name; PDFViewerCustomToolbar_Desktop.BookmarkPopup.EditEntry.Focus(); } private async void OnDeleteOptions(object obj) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; this.messageLabel.Text = pdfViewer.CustomBookmarks[selectedCustomBookmarkIndex].Name + "- Deleted"; if (pdfViewer.PageNumber == pdfViewer.CustomBookmarks[selectedCustomBookmarkIndex].PageNumber) { AddBookmarkButton.InputTransparent = false; AddBookmarkButton.BackgroundColor = Color.FromHex("#007CEE"); AddBookmarkLabel.Opacity = 1; } pdfViewer.CustomBookmarks.RemoveAt(selectedCustomBookmarkIndex); if (pdfViewer.CustomBookmarks.Count == 0) { AddBookmarkButton.InputTransparent = false; AddBookmarkButton.BackgroundColor = Color.FromHex("#007CEE"); AddBookmarkLabel.Opacity = 1; UpdateCustomBookmarkView(); } toastMessageFrame.IsVisible = true; PDFViewerCustomToolbar_Desktop.PositionToastMessage(); await toastMessageFrame.FadeTo(1, 1000); await toastMessageFrame.FadeTo(0, 1000); } private void CustomBookmarkView_ItemTapped(object sender, ItemTappedEventArgs e) { pdfViewer.GoToBookmark(e.Item as Syncfusion.SfPdfViewer.XForms.CustomBookmark); } private void CustomBookmarkView_Scrolled(object sender, ScrolledEventArgs e) { this.CustomBookmarkView_ScrollY = e.ScrollY; } private async void AddBookmarkButton_Clicked(object sender, EventArgs e) { if ((BindingContext as PdfViewerViewModel).IsContextMenuVisible == true) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; } tabView.SelectedIndex = 1; pdfViewer.CustomBookmarks.Add(new Syncfusion.SfPdfViewer.XForms.CustomBookmark("Page " + pdfViewer.PageNumber, pdfViewer.PageNumber)); AddBookmarkButton.InputTransparent = true; AddBookmarkButton.BackgroundColor = Color.FromHex("#7BB9F2"); AddBookmarkLabel.Opacity = 0.7; PDFViewerCustomToolbar_Desktop.PositionToastMessage(); this.messageLabel.Text = pdfViewer.CustomBookmarks.Last().Name + "- Added"; toastMessageFrame.IsVisible = true; await toastMessageFrame.FadeTo(1, 1000); await toastMessageFrame.FadeTo(0, 1000); } private void PopUpMenuButton_Clicked(object sender, EventArgs e) { this.selectedCustomBookmarkIndex = pdfViewer.CustomBookmarks.IndexOf((Syncfusion.SfPdfViewer.XForms.CustomBookmark)(sender as Button).BindingContext); var YOffset= (selectedCustomBookmarkIndex * 40) + (40 * 0.5) - this.CustomBookmarkView_ScrollY + tabView.TabHeight; if (YOffset > absoluteLayoutContainer.Height - contextOptionsFrame.Height - 20) { YOffset = absoluteLayoutContainer.Height - contextOptionsFrame.Height - 20; } contextOptionsFrame.TranslationY = YOffset; if ((BindingContext as PdfViewerViewModel).IsContextMenuVisible==true) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; } else { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = true; } } private void BackToParentButton_Clicked(object sender, EventArgs e) { try { if (listViewItemsSource != null && listViewItemsSource.Count > 0) { for (int i = listViewItemsSource.Count - 1; i >= 0; i--) { listViewItemsSource.RemoveAt(i); } } } catch (Exception) { } if (navigationQueue.Count < 2) { for (int i = 0; i < bookmarkLoadedDocument.Bookmarks.Count; i++) listViewItemsSource.Add(new ContentBookmark(bookmarkLoadedDocument.Bookmarks[i], false)); if (navigationQueue.Count != 0) navigationQueue.RemoveAt(navigationQueue.Count - 1); } else { PdfBookmark parentBookmark = navigationQueue[navigationQueue.Count - 2]; navigationQueue.RemoveAt(navigationQueue.Count - 2); UpdateBookmarkList(parentBookmark); } } internal void PopulateInitialBookmarkList() { if (listViewItemsSource != null && listViewItemsSource.Count != 0) { try { for (int i = listViewItemsSource.Count - 1; i >= 0; i--) listViewItemsSource.RemoveAt(i); } catch (Exception) { } } if (bookmarkLoadedDocument != null) { PdfBookmarkBase bookmarkBase = bookmarkLoadedDocument.Bookmarks; for (int i = 0; i < bookmarkBase.Count; i++) listViewItemsSource.Add(new ContentBookmark(bookmarkBase[i], false)); } if (navigationQueue.Count != 0) { try { for (int i = navigationQueue.Count - 1; i >= 0; i--) navigationQueue.RemoveAt(i); } catch (Exception) { } } } private void BookmarkExpand_Clicked(object sender, EventArgs e) { PdfBookmark bookmark = ((sender as Button).CommandParameter as ContentBookmark).Bookmark; navigationQueue.Add(bookmark); UpdateBookmarkList(bookmark); } private void BookmarkView_ItemTapped(object sender, ItemTappedEventArgs e) { if (e.Item != null) pdfViewer.GoToBookmark((e.Item as ContentBookmark).Bookmark); } internal void UpdateBookmarkList(PdfBookmark bookmark) { if (listViewItemsSource != null && listViewItemsSource.Count > 0) { for (int i = listViewItemsSource.Count - 1; i >= 0; i--) listViewItemsSource.RemoveAt(i); } listViewItemsSource.Add(new ContentBookmark(bookmark, true)); for (int i = 0; i < bookmark.Count; i++) listViewItemsSource.Add(new ContentBookmark(bookmark[i], false)); } private void CloseButton_Clicked(object sender, EventArgs e) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; if (BindingContext as PdfViewerViewModel != null) (BindingContext as PdfViewerViewModel).IsBookMarkVisible = false; this.WidthRequest = 0; } } internal class BookmarkContextMenu { internal BookmarkContextMenu(string iconText,string labelText) { IconText=iconText; LabelText=labelText; } public string IconText { get; private set; } public string LabelText { get; private set; } } } <file_sep>/Forms/ImageEditor/ImageEditor/Samples/BannerCreator/ImageEditorToolbarPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfImageEditor.XForms; using Xamarin.Forms; namespace SampleBrowser.SfImageEditor { public partial class ImageEditorToolbarPage : ContentPage { bool isCropped; void Done_Clicked(object sender, System.EventArgs e) { imageEditor.Crop(); // cancelToolBar.IsVisible = false; } void Cancel_Clicked(object sender, System.EventArgs e) { imageEditor.ToggleCropping(); // cancelToolBar.IsVisible = false; } Model data; ImageSource scr = null; ViewModel ViewModelMain; string location = ""; public ImageEditorToolbarPage(ImageSource imagesource, ViewModel viewModel, Model model) { data = model; ViewModelMain = viewModel; this.BindingContext = ViewModelMain; scr = imagesource; InitializeComponent(); imageEditor.Source = imagesource; // imageEditor.SetToolbarItemVisibility("Cancel,Ok", false); imageEditor.ToolbarSettings.ToolbarItems.Clear(); imageEditor.EnableZooming = false; Assembly assembly = typeof(ImageSerializeModel).GetTypeInfo().Assembly; FooterToolbarItem banner = new FooterToolbarItem() { Text = "Banner Types", SubItems = new System.Collections.ObjectModel.ObservableCollection<Syncfusion.SfImageEditor.XForms.ToolbarItem>() { #if COMMONSB new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="Facebook Post",Icon=ImageSource.FromResource("SampleBrowser.Icons.fivetofour.png",assembly)}, new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="Facebook Cover",Icon=ImageSource.FromResource("SampleBrowser.Icons.fourtothree.png",assembly)}, new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="Twitter Cover",Icon=ImageSource.FromResource("SampleBrowser.Icons.fivetofour.png",assembly)}, new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="Twitter Post",Icon=ImageSource.FromResource("SampleBrowser.Icons.fourtothree.png",assembly)}, new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="YouTubeChannel Cover",Icon=ImageSource.FromResource("SampleBrowser.Icons.fivetofour.png",assembly)}, #else new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="Facebook Post",Icon=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.fivetofour.png",assembly)}, new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="Facebook Cover",Icon=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.fourtothree.png",assembly)}, new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="Twitter Cover",Icon=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.fivetofour.png",assembly)}, new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="Twitter Post",Icon=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.fourtothree.png",assembly)}, new Syncfusion.SfImageEditor.XForms.ToolbarItem(){Text="YouTubeChannel Cover",Icon=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.fivetofour.png",assembly)}, #endif }, }; HeaderToolbarItem item2 = new HeaderToolbarItem(); item2.Name = "Share"; item2.IconHeight = 30; item2.Icon = new FontImageSource() { Glyph = "\ue751", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.Black }; imageEditor.ToolbarSettings.ToolbarItems.Add(item2); imageEditor.ToolbarSettings.ToolbarItems.Add(banner); imageEditor.ToolbarSettings.ToolbarItemSelected += (sender, e) => { var selected = (e.ToolbarItem as Syncfusion.SfImageEditor.XForms.ToolbarItem); if (selected != null) { if (selected.Name == "Share") Share(); else if (selected.Text == "Facebook Post" || selected.Text=="Banner Types") imageEditor.ToggleCropping(1200, 900); else if (selected.Text == "Facebook Cover") imageEditor.ToggleCropping(851, 315); else if (selected.Text == "Twitter Cover") imageEditor.ToggleCropping(1500, 500); else if (selected.Text == "Twitter Post") imageEditor.ToggleCropping(1024, 512); else if (selected.Text == "YouTubeChannel Cover") imageEditor.ToggleCropping(2560, 1440); } }; } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if ((width > height && isCropped) || (width < height && isCropped)) { // cancelToolBar.IsVisible = false; isCropped = false; } } public async Task DelayActionAsync(int delay, Action action) { await Task.Delay(delay); action(); } async void Share() { imageEditor.Save(); imageEditor.ImageSaving += (sender, args) => { }; imageEditor.ImageSaved += (sender, args) => { location = args.Location; }; await DelayActionAsync(2500, Sharing); } void Sharing() { var temp = location; var filePath = DependencyService.Get<IFileStore>().GetFilePath(); var share = DependencyService.Get<IShare>(); share.Show("Title", "Message", temp); } } } <file_sep>/Forms/TimePicker/TimePicker/ViewModel/TimePickerAlarmObject.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; namespace SampleBrowser.SfTimePicker { #region TimePickerAlarmObject class /// <summary> /// /// </summary> public class TimePickerAlarmObject : INotifyPropertyChanged { #region Members /// <summary> /// Update based on selected time /// </summary> private TimeSpan timeValue; /// <summary> /// Indicates switch is ON/OFF /// </summary> private bool isOn; /// <summary> /// TimeDiffernce field /// </summary> private TimeSpan? timeDifference; #endregion #region Properties /// <summary> /// Update based on Picker Selected Time /// </summary> public TimeSpan TimeValue { get { return timeValue; } set { timeValue = value; CalculateTimeDifference(IsOn); this.NotifyPropertyChanged(); } } /// <summary> /// To indicate whether the Switch is ON/OFF /// </summary> public bool IsOn { get { return isOn; } set { isOn = value; CalculateTimeDifference(isOn); this.NotifyPropertyChanged(); } } /// <summary> /// Time difference based on selected time /// </summary> public TimeSpan? TimeDifference { get { return timeDifference; } set { timeDifference = value; this.NotifyPropertyChanged(); } } #endregion #region NotifyPropertyChanged /// <summary> /// Property changed event handler. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Notify when the property is changed /// </summary> /// <param name="propertyName"></param> private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Calculate the time difference /// </summary> /// <param name="switchOn"></param> private void CalculateTimeDifference(bool switchOn) { if (switchOn) { DateTime dateTimeValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0); dateTimeValue = dateTimeValue.AddTicks(this.TimeValue.Ticks); if (dateTimeValue <= DateTime.Now) { dateTimeValue = dateTimeValue.AddDays(1); } DateTime dateTime = DateTime.Now; dateTime = dateTime.AddSeconds(-dateTime.Second); this.TimeDifference = dateTime.Subtract(dateTimeValue); } else this.TimeDifference = null; } #endregion } #endregion } <file_sep>/Android/SampleBrowser/Samples/TreeView/TreeTemplate.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Android.TreeView; using Syncfusion.TreeView.Engine; using System; namespace SampleBrowser { public class TreeTemplate : SamplePage, IDisposable { private SfTreeView treeView; private MailFolderViewModel viewModel; public override Android.Views.View GetSampleContent(Android.Content.Context context) { treeView = new SfTreeView(context, null); viewModel = new MailFolderViewModel(); treeView.FullRowSelect = true; treeView.Indentation = 20; treeView.ExpanderWidth = 40; treeView.ItemHeight = 40; treeView.AutoExpandMode = AutoExpandMode.AllNodesExpanded; treeView.ChildPropertyName = "SubFolder"; treeView.ItemsSource = viewModel.Folders; treeView.Adapter = new TemplateAdapter(); return treeView; } public void Dispose() { if (treeView != null) { treeView.Dispose(); treeView = null; } } } }<file_sep>/Forms/Schedule/Schedule/Samples/DayViewConfigurations/Behaviors/DayViewConfigurationBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Day View Configuration Behavior class /// </summary> public class DayViewConfigurationBehavior : Behavior<SampleView> { /// <summary> /// schedule initialization /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule schedule; /// <summary> /// start time slider /// </summary> private Slider startTimeSlider; /// <summary> /// time label switch. /// </summary> private Switch showTimeLabel; /// <summary> /// end time slider /// </summary> private Slider endTimeSlider; /// <summary> /// view picker /// </summary> private Picker viewPicker; /// <summary> /// date picker /// </summary> private DatePicker datePicker; /// <summary> /// end hour label /// </summary> private Label endHourLabel; /// <summary> /// start hour label /// </summary> private Label startHourLabel; #region OnAttached /// <summary> /// Method for converter /// </summary> /// <param name="input">input value</param> /// <returns>return the double value</returns> public string Converter(double input) { string final; double h = (int)input; double m = input - h; string ampm = " "; if (m == 59) { h = h + 1; m = 0; } if (h == 12) { ampm = "PM"; } else if (h == 24) { h = 12; ampm = "AM"; } else if (h > 12) { h = h - 12; ampm = "PM"; } else if (h < 12) { ampm = "AM"; } m = TimeSpan.FromMinutes(m).Seconds; if (m == 0) { var time = TimeSpan.FromMinutes(m); final = h.ToString() + ":" + m.ToString() + "0 " + ampm; } else if (m == 1 || m == 2 || m == 3 || m == 4 || m == 5 || m == 6 || m == 7 || m == 8 || m == 9) { var time = TimeSpan.FromMinutes(m); final = h.ToString() + ":0" + m.ToString() + " " + ampm; } else { final = h.ToString() + ":" + m.ToString() + " " + ampm; } return final; } #region SetScheduleView /// <summary> ///method for selecting schedule view /// </summary> /// <param name="sender">return the object</param> internal void SetScheduleView(object sender) { switch ((sender as Picker).SelectedIndex) { case 0: this.schedule.ScheduleView = ScheduleView.DayView; break; case 1: this.schedule.ScheduleView = ScheduleView.WeekView; break; case 2: this.schedule.ScheduleView = ScheduleView.WorkWeekView; break; } } #endregion #region DatePickerGoToDate /// <summary> /// method for move to date /// </summary> /// <param name="date">date value</param> internal void DatePickerGoToDate(DateTime date) { this.schedule.MoveToDate = date; } #endregion #region OnDetachingFrom /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(SampleView bindable) { this.startTimeSlider.ValueChanged -= this.StartTimeSlider_ValueChanged; this.endTimeSlider.ValueChanged -= this.EndTimeSlider_ValueChanged; this.viewPicker.SelectedIndexChanged -= this.ViewPicker_SelectedIndexChanged; this.datePicker.DateSelected -= this.DatePicker_DateSelected; this.showTimeLabel.Toggled -= this.ShowTimeLabel_Toggled; this.schedule = null; this.startTimeSlider = null; this.endTimeSlider = null; this.viewPicker = null; this.datePicker = null; this.showTimeLabel = null; } #endregion /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">binadable value</param> protected override void OnAttachedTo(SampleView bindable) { this.schedule = (bindable.Content as Grid).Children[0] as Syncfusion.SfSchedule.XForms.SfSchedule; if (Device.RuntimePlatform == Device.Android) { this.schedule.ViewHeaderStyle.DateFontSize = 24; } this.startTimeSlider = bindable.FindByName<Slider>("startTimeSlider"); this.endTimeSlider = bindable.FindByName<Slider>("endTimeSlider"); this.viewPicker = bindable.FindByName<Picker>("viewPicker"); this.datePicker = bindable.FindByName<DatePicker>("datePicker"); this.startHourLabel = bindable.FindByName<Label>("startHourLabel"); this.endHourLabel = bindable.FindByName<Label>("endHourLabel"); this.showTimeLabel = bindable.FindByName<Switch>("timeLabelWidth"); this.viewPicker.SelectedIndex = 0; this.startTimeSlider.ValueChanged += this.StartTimeSlider_ValueChanged; this.endTimeSlider.ValueChanged += this.EndTimeSlider_ValueChanged; this.viewPicker.SelectedIndexChanged += this.ViewPicker_SelectedIndexChanged; this.datePicker.DateSelected += this.DatePicker_DateSelected; this.showTimeLabel.Toggled += this.ShowTimeLabel_Toggled; this.SetNonAccessibleBlocks(); } private void ShowTimeLabel_Toggled(object sender, ToggledEventArgs e) { if ((sender as Switch).IsToggled) { if (Device.RuntimePlatform == "UWP" || Device.RuntimePlatform == "WPF") { this.schedule.DayViewSettings.TimeRulerSize = 52; this.schedule.WeekViewSettings.TimeRulerSize = 52; this.schedule.WorkWeekViewSettings.TimeRulerSize = 52; } else { this.schedule.DayViewSettings.TimeRulerSize = -1; this.schedule.WeekViewSettings.TimeRulerSize = -1; this.schedule.WorkWeekViewSettings.TimeRulerSize = -1; } } else { this.schedule.DayViewSettings.TimeRulerSize = 0; this.schedule.WeekViewSettings.TimeRulerSize = 0; this.schedule.WorkWeekViewSettings.TimeRulerSize = 0; } } #endregion #region DatePicker_DateSelected /// <summary> /// Method for date selection /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Date Changed Event Args</param> private void DatePicker_DateSelected(object sender, DateChangedEventArgs e) { this.DatePickerGoToDate(e.NewDate); } #endregion #region ViewPicker_SelectedIndexChanged /// <summary> /// Method for schedule view selection /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void ViewPicker_SelectedIndexChanged(object sender, EventArgs e) { this.SetScheduleView(sender); } #endregion #region EndTimeSlider_ValueChanged /// <summary> /// Method for end time selection /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Value Changed Event Args</param> private void EndTimeSlider_ValueChanged(object sender, ValueChangedEventArgs e) { if (e.NewValue >= this.startTimeSlider.Value) { (this.schedule.BindingContext as ConfigurationViewModel).EndHour = e.NewValue; this.endHourLabel.Text = "Change the work hour end time:" + this.Converter(e.NewValue); } else { this.endTimeSlider.Value = this.startTimeSlider.Value; this.endHourLabel.Text = "Change the work hour end time:" + this.Converter(this.startTimeSlider.Value); } } #endregion #region StartTimeSlider_ValueChanged /// <summary> /// method for start time value changed. /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Value Changed Event Args</param> private void StartTimeSlider_ValueChanged(object sender, ValueChangedEventArgs e) { if (e.NewValue <= this.endTimeSlider.Value) { (this.schedule.BindingContext as ConfigurationViewModel).WorkStartHour = e.NewValue; this.startHourLabel.Text = "Change the work hour start time:" + this.Converter(e.NewValue); } else { this.startTimeSlider.Value = this.endTimeSlider.Value; this.startHourLabel.Text = "Change the work hour start time:" + this.Converter(this.endTimeSlider.Value); } } #endregion #region SetNonAccessibleBlocks /// <summary> /// method for non accessible blocks /// </summary> private void SetNonAccessibleBlocks() { if (Device.RuntimePlatform == "Android" || Device.RuntimePlatform == "iOS") { NonAccessibleBlocksCollection nonAccessibleBlocks = new NonAccessibleBlocksCollection(); var nonAccessibleBlock = new NonAccessibleBlock(); nonAccessibleBlock.StartTime = 13; nonAccessibleBlock.EndTime = 14; nonAccessibleBlock.Text = "Lunch time"; nonAccessibleBlocks.Add(nonAccessibleBlock); this.schedule.DayViewSettings.NonAccessibleBlocks = nonAccessibleBlocks; this.schedule.WeekViewSettings.NonAccessibleBlocks = nonAccessibleBlocks; this.schedule.WorkWeekViewSettings.NonAccessibleBlocks = nonAccessibleBlocks; } } #endregion } }<file_sep>/Forms/DigitalGauge/DigitalGauge/Samples/DigitalGauge_Tablet/DigitalGauge_Tablet.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfGauge.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfDigitalGauge { [Preserve(AllMembers = true)] //[XamlCompilation(XamlCompilationOptions.Compile)] public partial class DigitalGauge_Tablet : SampleView { public void EnableTimer() { this.DateTime = DateTime.Now; Device.StartTimer(TimeSpan.FromSeconds(1), () => { this.DateTime = DateTime.Now; return true; }); } DateTime dateTime = new DateTime(); public DateTime DateTime { set { if (dateTime != value) { string dateTimeValue = DateTime.Now.ToString("HH mm ss"); segmentSevenGauge.Value = dateTimeValue; segmentFourteenGauge.Value = dateTimeValue; segmentSixteenGauge.Value = dateTimeValue; segmentMatrixGauge.Value = dateTimeValue; } } get { return dateTime; } } public DigitalGauge_Tablet() { InitializeComponent(); string dateTimeValue = DateTime.Now.ToString("HH mm ss"); //Setting value segmentSevenGauge.Value = dateTimeValue; segmentFourteenGauge.Value = dateTimeValue; segmentSixteenGauge.Value = dateTimeValue; segmentMatrixGauge.Value = dateTimeValue; //Background color segmentSevenGauge.BackgroundColor = Color.FromRgb(235, 235, 235); segmentFourteenGauge.BackgroundColor = Color.FromRgb(235, 235, 235); segmentSixteenGauge.BackgroundColor = Color.FromRgb(235, 235, 235); segmentMatrixGauge.BackgroundColor = Color.FromRgb(235, 235, 235); //Character StrokeColorr segmentSevenGauge.CharacterStrokeColor = Color.FromRgb(20, 108, 237); segmentSixteenGauge.CharacterStrokeColor = Color.FromRgb(219, 153, 7); segmentMatrixGauge.CharacterStrokeColor = Color.FromRgb(249, 66, 53); segmentFourteenGauge.CharacterStrokeColor = Color.FromRgb(2, 186, 94); //Disabled SegmentColor segmentFourteenGauge.DisabledSegmentColor = Color.FromRgb(2, 186, 94); segmentSixteenGauge.DisabledSegmentColor = Color.FromRgb(219, 153, 7); segmentSevenGauge.DisabledSegmentColor = Color.FromRgb(20, 60, 106); segmentMatrixGauge.DisabledSegmentColor = Color.FromRgb(249, 66, 53); deviceSetting(); } public void deviceSetting() { if (Device.RuntimePlatform == Device.iOS) { //segmentSevenGauge segmentSevenGauge.HeightRequest = 100; segmentFourteenGauge.HeightRequest = 100; segmentSixteenGauge.HeightRequest = 100; segmentMatrixGauge.HeightRequest = 100; //segmentSevenGauge segmentSevenGauge.CharacterHeight = 100; segmentFourteenGauge.CharacterHeight = 100; segmentSixteenGauge.CharacterHeight = 100; segmentMatrixGauge.CharacterHeight = 100; //segmentSevenGaugee segmentSevenGauge.CharacterWidth = 50; segmentFourteenGauge.CharacterWidth = 50; segmentSixteenGauge.CharacterWidth = 50; segmentMatrixGauge.CharacterWidth = 50; //segmentSevenGaugee segmentSevenGauge.WidthRequest = (8 * segmentSevenGauge.CharacterWidth) + (7 * segmentSevenGauge.CharacterSpacing); segmentFourteenGauge.WidthRequest = (8 * segmentFourteenGauge.CharacterWidth) + (7 * segmentFourteenGauge.CharacterSpacing); segmentSixteenGauge.WidthRequest = (8 * segmentSixteenGauge.CharacterWidth) + (7 * segmentSixteenGauge.CharacterSpacing); segmentMatrixGauge.WidthRequest = (9 * segmentMatrixGauge.CharacterWidth) + (7 * segmentMatrixGauge.CharacterSpacing); segmentSevenGauge.HorizontalOptions = LayoutOptions.Center; segmentFourteenGauge.HorizontalOptions = LayoutOptions.Center; segmentSixteenGauge.HorizontalOptions = LayoutOptions.Center; segmentMatrixGauge.HorizontalOptions = LayoutOptions.Center; } EnableTimer(); if (Device.RuntimePlatform == Device.Android) { segmentSevenGauge.HeightRequest = segmentSevenGauge.CharacterHeight + segmentSevenGauge.CharacterHeight / 6; segmentFourteenGauge.HeightRequest = segmentFourteenGauge.CharacterHeight + segmentFourteenGauge.CharacterHeight / 6; segmentSixteenGauge.HeightRequest = segmentSixteenGauge.CharacterHeight + segmentSixteenGauge.CharacterHeight / 6; segmentMatrixGauge.HeightRequest = segmentMatrixGauge.CharacterHeight + segmentMatrixGauge.CharacterHeight / 6; } if (Device.RuntimePlatform == Device.UWP) { segmentSevenGauge.HeightRequest = 65; segmentFourteenGauge.HeightRequest = 65; segmentSixteenGauge.HeightRequest = 65; segmentMatrixGauge.HeightRequest = 65; segmentSevenGauge.CharacterHeight = 65; segmentSevenGauge.CharacterWidth = 20; segmentSevenGauge.SegmentStrokeWidth = 3; segmentFourteenGauge.CharacterHeight = 65; segmentFourteenGauge.CharacterWidth = 20; segmentFourteenGauge.SegmentStrokeWidth = 3; segmentSixteenGauge.CharacterHeight = 65; segmentSixteenGauge.CharacterWidth = 20; segmentSixteenGauge.SegmentStrokeWidth = 3; segmentMatrixGauge.CharacterHeight = 65; segmentMatrixGauge.CharacterWidth = 20; segmentMatrixGauge.SegmentStrokeWidth = 3; segmentSevenGauge.WidthRequest = 350; segmentFourteenGauge.WidthRequest = 350; segmentSixteenGauge.WidthRequest = 350; segmentMatrixGauge.WidthRequest = 350; sevenSegment.WidthRequest = 350; fourteenSegment.WidthRequest = 350; sixteenSegment.WidthRequest = 350; matrixSegment.WidthRequest = 350; segmentSevenGauge.HorizontalOptions = LayoutOptions.Center; segmentFourteenGauge.HorizontalOptions = LayoutOptions.Center; segmentSixteenGauge.HorizontalOptions = LayoutOptions.Center; segmentMatrixGauge.HorizontalOptions = LayoutOptions.Center; sevenSegment.HorizontalTextAlignment = TextAlignment.Center; fourteenSegment.HorizontalTextAlignment = TextAlignment.Center; sixteenSegment.HorizontalTextAlignment = TextAlignment.Center; matrixSegment.HorizontalTextAlignment = TextAlignment.Center; sixteenSegment.FontSize = 20; matrixSegment.FontSize = 20; sevenSegment.FontSize = 20; fourteenSegment.FontSize = 20; } } public View getContent() { return this.Content; } } } <file_sep>/Forms/Kanban/Kanban/Samples/KanbanCustomizationSample/KanbanCustomViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfKanban.XForms; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using SampleBrowser.Core; namespace SampleBrowser.SfKanban { [Preserve(AllMembers = true)] public class KanbanCustomViewModel { public ObservableCollection<CustomKanbanModel> Cards { get; set; } public int LastOrderID { get; set; } public KanbanCustomViewModel() { LastOrderID = 16365; Cards = new ObservableCollection<CustomKanbanModel>(); Cards.Add( new CustomKanbanModel() { ID = 1, Title = "Margherita", ImageURL = "margherita.png", Category = "Menu", Rating = 4, Description = "The classic. Fresh tomatoes, garlic, olive oil, and basil. For pizza purists and minimalists only.", Tags = new string[] { "Cheese" } } ); Cards.Add( new CustomKanbanModel() { ID = 2, Title = "Double Cheese", ImageURL = "doublecheesemargherita.png", Category = "Menu", Rating = 5, Description = "The minimalist classic with a double helping of cheese", Tags = new string[] { "Cheese" } } ); Cards.Add( new CustomKanbanModel() { ID = 3, Title = "Bucolic Pie", ImageURL = "bucolicpie.png", Category = "Menu", Rating = 4.5f, Description = "The pizza you daydream about to escape city life. Onions, peppers, and tomatoes.", Tags = new string[] { "Onions", "Capsicum" } } ); Cards.Add( new CustomKanbanModel() { ID = 4, Title = "Bumper Crop", Rating = 3.25f, ImageURL = "bumpercrop.png", Category = "Menu", Description = "Can’t get enough veggies? Eat this. Carrots, mushrooms, potatoes, and way more", Tags = new string[] { "Tomato", "Mushroom" } } ); Cards.Add( new CustomKanbanModel() { ID = 5, Title = "Spice of Life", ImageURL = "SpiceOfLife.png", Category = "Menu", Rating = 4.75f, Description = "Thrill-seeking, heat-seeking pizza people only. It’s hot. Trust us.", Tags = new string[] { "Corn", "Gherkins" } } ); Cards.Add( new CustomKanbanModel() { ID = 6, Title = "Very Nicoise", ImageURL = "VeryNicoise.png", Category = "Menu", Rating = 3.75f, Description = "Anchovies, Dijon vinaigrette, shallots, red peppers, and potatoes.", Tags = new string[] { "Red pepper", "Capsicum" } } ); Cards.Add( new CustomKanbanModel() { ID = 7, Title = "Salad Daze", ImageURL = "SaladDaze.png", Category = "Menu", Rating = 5, Description = "Pretty much salad on a pizza. Broccoli, olives, cherry tomatoes, red onion.", Tags = new string[] { "Onions", "Jalapeno" } } ); Cards.Add( new CustomKanbanModel() { ID = 4, Title = "Bumper Crop", ImageURL = "bumpercrop.png", Category = "Ready to Serve", OrderID = "Order ID - #16362", Description = "Can’t get enough veggies? Eat this. Carrots, mushrooms, potatoes, and way more", Tags = new string[] { "Tomato", "Mushroom" } } ); Cards.Add( new CustomKanbanModel() { ID = 5, Title = "Spice of Life", ImageURL = "SpiceOfLife.png", Category = "Ready to Serve", OrderID = "Order ID - #16363", Description = "Thrill-seeking, heat-seeking pizza people only. It’s hot. Trust us.", Tags = new string[] { "Corn", "Gherkins" } } ); Cards.Add( new CustomKanbanModel() { ID = 3, Title = "Bucolic Pie", ImageURL = "bucolicpie.png", Category = "Door Delivery", OrderID = "Order ID - #16361", Description = "The pizza you daydream about to escape city life. Onions, peppers, and tomatoes.", Tags = new string[] { "Onions", "Capsicum" } } ); Cards.Add( new CustomKanbanModel() { ID = 6, Title = "Very Nicoise", ImageURL = "VeryNicoise.png", Category = "Dining", OrderID = "Order ID - #16364", AnimationDuration = 60000, Description = "Anchovies, Dijon vinaigrette, shallots, red peppers, and potatoes.", Tags = new string[] { "Red pepper", "Capsicum" } } ); Cards.Add( new CustomKanbanModel() { ID = 2, Title = "Double Cheese", ImageURL = "doublecheesemargherita.png", Category = "Delivery", OrderID = "Order ID - #16365", AnimationDuration = 60000, Description = "The minimalist classic with a double helping of cheese", Tags = new string[] { "Cheese" } } ); } } public class CustomKanbanModel : KanbanModel { public float Rating { get; set; } public string OrderID { get; set; } public int AnimationDuration { get; set; } } } <file_sep>/Forms/PopupLayout/PopupLayout.UWP/MainPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "MainPage.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout.UWP { using Syncfusion.ListView.XForms.UWP; using Syncfusion.SfDataGrid.XForms.UWP; using Syncfusion.SfRotator.XForms.UWP; using Syncfusion.XForms.UWP.PopupLayout; /// <summary> /// This is the main entry point of the application while launching in UWP platform. /// </summary> public sealed partial class MainPage { /// <summary> /// Initializes a new instance of the MainPage class. /// </summary> public MainPage() { this.InitializeComponent(); SfPopupLayoutRenderer.Init(); SfDataGridRenderer.Init(); SfListViewRenderer.Init(); SfRotatorRenderer.Init(); this.LoadApplication(new SfPopupLayout.App()); } } }<file_sep>/Forms/Barcode/readme.md Barcode provides a perfect approach to encode texts by using the supported symbol types that comprises one dimensional and two dimensional barcodes. The basic structure of a barcode consists of one or more data characters, optionally one or two check characters, a start pattern as well as a stop pattern. The following samples are available for Barcode control to demonstrate the functionalities of each feature: | Sample | Description | | ------ | ----------- | | [QR Barcode](Barcode/Samples/QRCode) | QR Code is a two dimensional symbology that is used in automotive industry. | | [DataMatrix Barcode](Barcode/Samples/DataMatrix) | DataMatrix symbology is widely used in printed media such as labels and letters. | | [CodaBar Barcode](Barcode/Samples/Codabar) | Codabar is a discrete numeric symbology that is used in libraries and information processing applications. |<file_sep>/Forms/DataGrid/DataGrid/Samples/SwipeDelete/SwipeDelete.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SwipeDelete.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; /// <summary> /// A sampleView that contains the SwipeDelete sample. /// </summary> public partial class SwipeDelete : SampleView { #region Field [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int swipedRowindex; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ContentView leftTemplateView; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ContentView rightTemplateView; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private bool isSuspend; #endregion #region Constructor /// <summary> /// Initializes a new instance of the SwipeDelete class. /// </summary> public SwipeDelete() { this.InitializeComponent(); } #endregion #region Property /// <summary> /// Gets or sets a value indicating whether FilterText has true or false value. /// </summary> public bool IsUndoClicked { get; set; } #endregion #region Private Methods /// <summary> /// Triggers while DataGrid Property was changed /// </summary> /// <param name="sender">DataGrid_PropertyChanged event sender </param> /// <param name="e">DataGrid_PropertyChanged args e</param> private void DataGrid_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "Width") { dataGrid.MaxSwipeOffset = dataGrid.Width; } } /// <summary> /// Triggers while DataGrid swiping was started /// </summary> /// <param name="sender">DataGrid_SwipeStarted event sender </param> /// <param name="e">DataGrid_SwipeStarted args e</param> private void DataGrid_SwipeStarted(object sender, Syncfusion.SfDataGrid.XForms.SwipeStartedEventArgs e) { if (this.isSuspend) { e.Cancel = true; } } /// <summary> /// Triggers while DataGrid swiping was ended /// </summary> /// <param name="sender">DataGrid_SwipeEnded event sender </param> /// <param name="e">DataGrid_SwipeEnded args e</param> private void DataGrid_SwipeEnded(object sender, Syncfusion.SfDataGrid.XForms.SwipeEndedEventArgs e) { this.swipedRowindex = e.RowIndex; if (Math.Abs(e.SwipeOffset) >= dataGrid.Width) { if (e.SwipeOffset > 0) { this.leftTemplateView.Content.IsVisible = true; } else { this.rightTemplateView.Content.IsVisible = true; } this.DoDeleting(); } } /// <summary> /// Used this method to remove the record rows while delete was presses /// </summary> private async void DoDeleting() { this.isSuspend = true; await Task.Delay(2000); if (this.leftTemplateView.Content.IsVisible) { this.leftTemplateView.Content.IsVisible = false; } else if (this.rightTemplateView.Content.IsVisible) { this.rightTemplateView.Content.IsVisible = false; } if (!this.IsUndoClicked) { this.viewModel.OrdersInfo.RemoveAt(this.swipedRowindex - 1); } else { var removedData = viewModel.OrdersInfo[this.swipedRowindex - 1]; var isSelected = dataGrid.SelectedItems.Contains(removedData); viewModel.OrdersInfo.Remove(removedData); viewModel.OrdersInfo.Insert(this.swipedRowindex - 1, removedData); if (isSelected) { dataGrid.SelectedItems.Add(removedData); } this.IsUndoClicked = false; } this.isSuspend = false; } /// <summary> /// Tigers while Label binding context was changed /// </summary> /// <param name="sender">Label_BindingContextChanged sender</param> /// <param name="e">Label_BindingContextChanged event args e</param> private void Label_BindingContextChanged(object sender, EventArgs e) { var label = sender as Label; if (label.GestureRecognizers.Count == 0) { label.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Undo) }); } } /// <summary> /// Tigers while right template binding context was changed /// </summary> /// <param name="sender">RightTemplate_BindingContextChanged sender</param> /// <param name="e">RightTemplate_BindingContextChanged event args e</param> private void RightTemplate_BindingContextChanged(object sender, EventArgs e) { this.rightTemplateView = sender as ContentView; } /// <summary> /// Tigers while Left template binding context was changed /// </summary> /// <param name="sender">RightTemplate_BindingContextChanged sender</param> /// <param name="e">RightTemplate_BindingContextChanged event args e</param> private void LeftTemplate_BindingContextChanged(object sender, EventArgs e) { this.leftTemplateView = sender as ContentView; } /// <summary> /// Used this method for undo operation while label was touched /// </summary> private void Undo() { this.IsUndoClicked = true; } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/DataMarkerCustomization/DataMarkerCustomizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class DataMarkerCustomizationViewModel { public ObservableCollection<ChartDataModel> DataMarkerData1 { get; set; } public ObservableCollection<ChartDataModel> DataMarkerData2 { get; set; } public DataMarkerCustomizationViewModel() { DataMarkerData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2013", 1110), new ChartDataModel("2014", 1130), new ChartDataModel("2015", 1153), new ChartDataModel("2016", 1175), }; DataMarkerData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2013", 1070), new ChartDataModel("2014", 1105), new ChartDataModel("2015", 1138), new ChartDataModel("2016", 1155), }; } } }<file_sep>/iOS/SampleBrowser/Samples/Schedule/ScheduleView/ScheduleEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using CoreGraphics; using Foundation; using Syncfusion.SfSchedule.iOS; using UIKit; namespace SampleBrowser { public class ScheduleEditor { private SFSchedule schedule; private ScheduleViews scheduleViews; public ScheduleEditor(SFSchedule sfSchedule, ScheduleViews scheduleView) { this.schedule = sfSchedule; this.scheduleViews = scheduleView; Editor = new UIView(); Editor.BackgroundColor = UIColor.White; } internal UIView Editor { get; set; } internal UIButton ButtonCancel { get; set; } internal UIButton ButtonSave { get; set; } internal UIButton DoneButton { get; set; } internal UIButton TimezoneButton { get; set; } internal UIButton DoneButton1 { get; set; } internal UIButton ButtonStartDate { get; set; } internal UIButton ButtonEndDate { get; set; } internal UIButton StartTimeZoneButton { get; set; } internal UIButton EndTimeZoneButton { get; set; } internal UITextView LabelSubject { get; set; } internal UITextView LabelLocation { get; set; } internal UILabel LabelStarts { get; set; } internal UILabel LabelEnds { get; set; } internal UILabel StartTimeZoneLabel { get; set; } internal UILabel EndTimeZoneLabel { get; set; } internal UILabel AllDaylabel { get; set; } internal UILabel TimezoneLabel { get; set; } internal UISwitch AllDaySwitch { get; set; } internal UIPickerView StartTimeZonePicker { get; set; } internal UIPickerView EndTimeZonePicker { get; set; } internal UIPickerView TimeZonePicker { get; set; } internal UIDatePicker PickerStartDate { get; set; } internal UIDatePicker PickerEndDate { get; set; } internal UIScrollView ScrollView { get; set; } internal void CreateOptionWindow() { if (TimezoneButton == null) { TimezoneButton = new UIButton(); TimezoneButton.Layer.BorderWidth = 2; TimezoneButton.Layer.CornerRadius = 4; TimezoneButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; TimezoneButton.SetTitle("Default", UIControlState.Normal); TimezoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); } if (TimezoneLabel == null) { TimezoneLabel = new UILabel(); TimezoneLabel.Text = "Time Zone"; TimezoneLabel.TextColor = UIColor.Black; } if (TimeZonePicker == null) { TimeZonePicker = new UIPickerView(); TimeZonePicker.Hidden = true; } if (DoneButton1 == null) { DoneButton1 = new UIButton(); DoneButton1.Hidden = true; DoneButton1.SetTitleColor(UIColor.Black, UIControlState.Normal); DoneButton1.SetTitle("Done\t", UIControlState.Normal); DoneButton1.BackgroundColor = UIColor.LightGray; DoneButton1.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; } TimezoneButton.TouchUpInside += (object sender, EventArgs e) => { TimeZonePicker.Hidden = false; DoneButton1.Hidden = false; }; DoneButton1.TouchUpInside += (object sender, EventArgs e) => { TimeZonePicker.Hidden = true; DoneButton1.Hidden = true; }; SchedulePickerModel model = new SchedulePickerModel(TimeZoneCollection.TimeZoneList); model.PickerChanged += (sender, e) => { if (e.SelectedValue != "Default") { schedule.TimeZone = e.SelectedValue; } TimezoneButton.SetTitle(e.SelectedValue, UIControlState.Normal); }; TimeZonePicker.Model = model; TimeZonePicker.ShowSelectionIndicator = true; if (Utility.IsIPad) { TimezoneLabel.Frame = new CGRect(0, 0, 320, 30); TimezoneButton.Frame = new CGRect(0, TimezoneLabel.Frame.Bottom, 320, 30); DoneButton1.Frame = new CGRect(0, TimezoneButton.Frame.Bottom, 320, 30); TimeZonePicker.Frame = new CGRect(0, DoneButton1.Frame.Bottom, 320, 200); } } internal void CreateEditor() { ButtonCancel = new UIButton(); ButtonSave = new UIButton(); LabelSubject = new UITextView(); LabelLocation = new UITextView(); LabelEnds = new UILabel(); LabelStarts = new UILabel(); ButtonStartDate = new UIButton(); ButtonEndDate = new UIButton(); StartTimeZoneLabel = new UILabel(); EndTimeZoneLabel = new UILabel(); StartTimeZoneButton = new UIButton(); EndTimeZoneButton = new UIButton(); PickerStartDate = new UIDatePicker(); PickerEndDate = new UIDatePicker(); DoneButton = new UIButton(); ScrollView = new UIScrollView(); StartTimeZonePicker = new UIPickerView(); EndTimeZonePicker = new UIPickerView(); AllDaySwitch = new UISwitch(); AllDaylabel = new UILabel(); ScrollView.BackgroundColor = UIColor.White; LabelSubject.Font = UIFont.SystemFontOfSize(14); LabelLocation.Font = UIFont.SystemFontOfSize(14); LabelStarts.Font = UIFont.SystemFontOfSize(15); LabelEnds.Font = UIFont.SystemFontOfSize(15); StartTimeZoneLabel.Font = UIFont.SystemFontOfSize(15); EndTimeZoneLabel.Font = UIFont.SystemFontOfSize(15); AllDaylabel.Font = UIFont.SystemFontOfSize(15); StartTimeZoneButton.Font = UIFont.SystemFontOfSize(15); EndTimeZoneButton.Font = UIFont.SystemFontOfSize(15); ButtonStartDate.Font = UIFont.SystemFontOfSize(15); ButtonEndDate.Font = UIFont.SystemFontOfSize(15); ButtonCancel.BackgroundColor = UIColor.FromRGB(229, 229, 229); ButtonCancel.Font = UIFont.SystemFontOfSize(15); ButtonSave.Font = UIFont.SystemFontOfSize(15); ButtonSave.BackgroundColor = UIColor.FromRGB(33, 150, 243); ButtonCancel.Layer.CornerRadius = 6; ButtonSave.Layer.CornerRadius = 6; ButtonStartDate.Layer.CornerRadius = 6; ButtonEndDate.Layer.CornerRadius = 6; StartTimeZoneLabel.Text = "Start Time Zone"; StartTimeZoneLabel.TextColor = UIColor.Black; EndTimeZoneLabel.Text = "End Time Zone"; EndTimeZoneLabel.TextColor = UIColor.Black; AllDaylabel.Text = "All Day"; AllDaylabel.TextColor = UIColor.Black; AllDaySwitch.On = false; AllDaySwitch.OnTintColor = UIColor.FromRGB(33, 150, 243); AllDaySwitch.ValueChanged += AllDaySwitch_ValueChanged; StartTimeZoneButton.SetTitle("Default", UIControlState.Normal); StartTimeZoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); StartTimeZoneButton.Layer.BorderWidth = 2; StartTimeZoneButton.Layer.CornerRadius = 4; StartTimeZoneButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; StartTimeZoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; StartTimeZoneButton.TouchUpInside += (object sender, EventArgs e) => { StartTimeZonePicker.Hidden = false; DoneButton.Hidden = false; AllDaylabel.Hidden = true; AllDaySwitch.Hidden = true; ButtonCancel.Hidden = true; ButtonSave.Hidden = true; EndTimeZoneLabel.Hidden = true; EndTimeZoneButton.Hidden = true; Editor.EndEditing(true); }; EndTimeZoneButton.SetTitle("Default", UIControlState.Normal); EndTimeZoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); EndTimeZoneButton.Layer.BorderWidth = 2; EndTimeZoneButton.Layer.CornerRadius = 4; EndTimeZoneButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; EndTimeZoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; EndTimeZoneButton.TouchUpInside += (object sender, EventArgs e) => { EndTimeZonePicker.Hidden = false; DoneButton.Hidden = false; AllDaylabel.Hidden = true; AllDaySwitch.Hidden = true; ButtonCancel.Hidden = true; ButtonSave.Hidden = true; EndTimeZoneLabel.Hidden = true; EndTimeZoneButton.Hidden = true; Editor.EndEditing(true); }; //cancel button ButtonCancel.SetTitle("Cancel", UIControlState.Normal); ButtonCancel.SetTitleColor(UIColor.FromRGB(59, 59, 59), UIControlState.Normal); ButtonCancel.TouchUpInside += (object sender, EventArgs e) => { Editor.Hidden = true; schedule.Hidden = false; Editor.EndEditing(true); scheduleViews.HeaderView.Hidden = false; }; //save button ButtonSave.SetTitle("Save", UIControlState.Normal); ButtonSave.SetTitleColor(UIColor.White, UIControlState.Normal); ButtonSave.TouchUpInside += (object sender, EventArgs e) => { scheduleViews.HeaderView.Hidden = false; if (scheduleViews.IndexOfAppointment != -1) { (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.IndexOfAppointment.ToString())].Subject = (NSString)LabelSubject.Text; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.IndexOfAppointment.ToString())].Location = (NSString)LabelLocation.Text; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.IndexOfAppointment.ToString())].StartTime = PickerStartDate.Date; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.IndexOfAppointment.ToString())].EndTime = PickerEndDate.Date; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.IndexOfAppointment.ToString())].IsAllDay = AllDaySwitch.On; } else { ScheduleAppointment appointment = new ScheduleAppointment(); appointment.Subject = (NSString)LabelSubject.Text; appointment.Location = (NSString)LabelLocation.Text; appointment.StartTime = PickerStartDate.Date; appointment.EndTime = PickerEndDate.Date; appointment.AppointmentBackground = UIColor.FromRGB(0xA2, 0xC1, 0x39); appointment.IsAllDay = AllDaySwitch.On; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>).Add(appointment); } Editor.Hidden = true; schedule.Hidden = false; schedule.ReloadData(); Editor.EndEditing(true); }; //subject label LabelSubject.TextColor = UIColor.Black; LabelSubject.TextAlignment = UITextAlignment.Left; LabelSubject.Layer.CornerRadius = 8; LabelSubject.Layer.BorderWidth = 2; LabelSubject.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //location label LabelLocation.TextColor = UIColor.Black; LabelLocation.TextAlignment = UITextAlignment.Left; LabelLocation.Layer.CornerRadius = 8; LabelLocation.Layer.BorderWidth = 2; LabelLocation.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //starts time LabelStarts.Text = "Start Time"; LabelStarts.TextColor = UIColor.Black; ButtonStartDate.SetTitle("Start time", UIControlState.Normal); ButtonStartDate.Layer.BorderWidth = 2; ButtonStartDate.Layer.CornerRadius = 4; ButtonStartDate.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; ButtonStartDate.SetTitleColor(UIColor.Black, UIControlState.Normal); ButtonStartDate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; ButtonStartDate.TouchUpInside += (object sender, EventArgs e) => { PickerStartDate.Hidden = false; DoneButton.Hidden = false; AllDaylabel.Hidden = true; AllDaySwitch.Hidden = true; ButtonCancel.Hidden = true; ButtonSave.Hidden = true; EndTimeZoneLabel.Hidden = true; EndTimeZoneButton.Hidden = true; Editor.EndEditing(true); }; //end time LabelEnds.Text = "End Time"; LabelEnds.TextColor = UIColor.Black; //end date ButtonEndDate.SetTitle("End time", UIControlState.Normal); ButtonEndDate.SetTitleColor(UIColor.Black, UIControlState.Normal); ButtonEndDate.Layer.BorderWidth = 2; ButtonEndDate.Layer.CornerRadius = 4; ButtonEndDate.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; ButtonEndDate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; ButtonEndDate.TouchUpInside += (object sender, EventArgs e) => { PickerEndDate.Hidden = false; DoneButton.Hidden = false; AllDaylabel.Hidden = true; AllDaySwitch.Hidden = true; ButtonCancel.Hidden = true; ButtonSave.Hidden = true; EndTimeZoneLabel.Hidden = true; EndTimeZoneButton.Hidden = true; Editor.EndEditing(true); }; //date and time pickers PickerStartDate.Hidden = true; PickerEndDate.Hidden = true; StartTimeZonePicker.Hidden = true; EndTimeZonePicker.Hidden = true; DoneButton.Hidden = true; //done button DoneButton.SetTitle("Done", UIControlState.Normal); DoneButton.SetTitleColor(UIColor.Blue, UIControlState.Normal); DoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; DoneButton.TouchUpInside += (object sender, EventArgs e) => { PickerStartDate.Hidden = true; PickerEndDate.Hidden = true; StartTimeZonePicker.Hidden = true; EndTimeZonePicker.Hidden = true; DoneButton.Hidden = true; LabelEnds.Hidden = false; ButtonEndDate.Hidden = false; ButtonStartDate.Hidden = false; LabelStarts.Hidden = false; EndTimeZoneLabel.Hidden = false; StartTimeZoneLabel.Hidden = false; AllDaylabel.Hidden = false; AllDaySwitch.Hidden = false; StartTimeZoneButton.Hidden = false; EndTimeZoneButton.Hidden = false; ButtonCancel.Hidden = false; ButtonSave.Hidden = false; String _sDate = DateTime.Parse(PickerStartDate.Date.ToString()).ToString(); ButtonStartDate.SetTitle(_sDate, UIControlState.Normal); String _eDate = DateTime.Parse(PickerEndDate.Date.ToString()).ToString(); ButtonEndDate.SetTitle(_eDate, UIControlState.Normal); Editor.EndEditing(true); }; SchedulePickerModel model = new SchedulePickerModel(TimeZoneCollection.TimeZoneList); model.PickerChanged += (sender, e) => { if (e.SelectedValue != "Default" && scheduleViews.SelectedAppointment != null) { scheduleViews.SelectedAppointment.StartTimeZone = e.SelectedValue; } StartTimeZoneButton.SetTitle(e.SelectedValue, UIControlState.Normal); }; SchedulePickerModel model2 = new SchedulePickerModel(TimeZoneCollection.TimeZoneList); model2.PickerChanged += (sender, e) => { if (e.SelectedValue != "Default" && scheduleViews.SelectedAppointment != null) { scheduleViews.SelectedAppointment.EndTimeZone = e.SelectedValue; } EndTimeZoneButton.SetTitle(e.SelectedValue, UIControlState.Normal); }; StartTimeZonePicker.Model = model; EndTimeZonePicker.Model = model2; StartTimeZonePicker.ShowSelectionIndicator = true; EndTimeZonePicker.ShowSelectionIndicator = true; ScrollView.Add(LabelSubject); ScrollView.Add(LabelLocation); ScrollView.Add(LabelStarts); ScrollView.Add(ButtonStartDate); ScrollView.Add(StartTimeZoneLabel); ScrollView.Add(StartTimeZoneButton); ScrollView.Add(LabelEnds); ScrollView.Add(ButtonEndDate); ScrollView.Add(EndTimeZoneLabel); ScrollView.Add(EndTimeZoneButton); ScrollView.Add(StartTimeZonePicker); ScrollView.Add(EndTimeZonePicker); ScrollView.Add(PickerEndDate); ScrollView.Add(PickerStartDate); ScrollView.Add(DoneButton); ScrollView.Add(AllDaylabel); ScrollView.Add(AllDaySwitch); ScrollView.Add(ButtonCancel); ScrollView.Add(ButtonSave); Editor.Add(ScrollView); } internal void EditorFrameUpdate() { var childHeight = 30; if (Utility.IsIPad) { childHeight = 40; } var padding = 20; LabelSubject.Frame = new CGRect(ScrollView.Frame.X, ScrollView.Frame.Y, ScrollView.Frame.Size.Width - padding, childHeight); LabelLocation.Frame = new CGRect(ScrollView.Frame.X, LabelSubject.Frame.Bottom + 10, ScrollView.Frame.Size.Width - padding, childHeight); LabelStarts.Frame = new CGRect(ScrollView.Frame.X, LabelLocation.Frame.Bottom, ScrollView.Frame.Size.Width - padding, childHeight); ButtonStartDate.Frame = new CGRect(ScrollView.Frame.X, LabelStarts.Frame.Bottom, ScrollView.Frame.Size.Width - padding, childHeight); StartTimeZoneLabel.Frame = new CGRect(ScrollView.Frame.X, ButtonStartDate.Frame.Bottom, ScrollView.Frame.Size.Width - padding, childHeight); StartTimeZoneButton.Frame = new CGRect(ScrollView.Frame.X, StartTimeZoneLabel.Frame.Bottom, ScrollView.Frame.Size.Width - padding, childHeight); LabelEnds.Frame = new CGRect(ScrollView.Frame.X, StartTimeZoneButton.Frame.Bottom, ScrollView.Frame.Size.Width - padding, childHeight); ButtonEndDate.Frame = new CGRect(ScrollView.Frame.X, LabelEnds.Frame.Bottom, ScrollView.Frame.Size.Width - padding, childHeight); EndTimeZoneLabel.Frame = new CGRect(ScrollView.Frame.X, ButtonEndDate.Frame.Bottom, ScrollView.Frame.Size.Width - padding, childHeight); EndTimeZoneButton.Frame = new CGRect(ScrollView.Frame.X, EndTimeZoneLabel.Frame.Bottom, ScrollView.Frame.Size.Width - padding, childHeight); AllDaylabel.Frame = new CGRect(ScrollView.Frame.X, EndTimeZoneButton.Frame.Bottom + 10, (ScrollView.Frame.Size.Width / 2) - padding, childHeight); AllDaySwitch.Frame = new CGRect(AllDaylabel.Frame.Right, EndTimeZoneButton.Frame.Bottom + 10, (ScrollView.Frame.Size.Width / 2) - padding, childHeight); ButtonCancel.Frame = new CGRect(ScrollView.Frame.X, AllDaySwitch.Frame.Bottom + 10, (ScrollView.Frame.Size.Width / 2) - padding, childHeight); ButtonSave.Frame = new CGRect(ButtonCancel.Frame.Right + 10, AllDaySwitch.Frame.Bottom + 10, (ScrollView.Frame.Size.Width / 2) - padding, childHeight); PickerStartDate.Frame = new CGRect(ScrollView.Frame.X, ButtonEndDate.Frame.Bottom, ScrollView.Frame.Size.Width - padding, 200); PickerEndDate.Frame = new CGRect(ScrollView.Frame.X, ButtonEndDate.Frame.Bottom, ScrollView.Frame.Size.Width - padding, 200); StartTimeZonePicker.Frame = new CGRect(ScrollView.Frame.X, ButtonEndDate.Frame.Bottom, ScrollView.Frame.Size.Width - padding, 200); EndTimeZonePicker.Frame = new CGRect(ScrollView.Frame.X, ButtonEndDate.Frame.Bottom, ScrollView.Frame.Size.Width - padding, 200); DoneButton.Frame = new CGRect(ScrollView.Frame.X, ButtonEndDate.Frame.Bottom, ScrollView.Frame.Size.Width - padding, childHeight); ScrollView.ContentSize = new CGSize(ScrollView.Frame.Size.Width - padding, ButtonCancel.Frame.Bottom); } internal void Disablechild() { StartTimeZoneButton.UserInteractionEnabled = false; StartTimeZoneButton.SetTitleColor(UIColor.Gray, UIControlState.Normal); EndTimeZoneButton.UserInteractionEnabled = false; EndTimeZoneButton.SetTitleColor(UIColor.Gray, UIControlState.Normal); } internal void EnableChild() { StartTimeZoneButton.UserInteractionEnabled = true; StartTimeZoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); EndTimeZoneButton.UserInteractionEnabled = true; EndTimeZoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); } private void AllDaySwitch_ValueChanged(object sender, EventArgs e) { if ((sender as UISwitch).On) { this.Disablechild(); } else { this.EnableChild(); } if (scheduleViews.SelectedAppointment != null) { scheduleViews.SelectedAppointment.IsAllDay = (sender as UISwitch).On; } } } }<file_sep>/Forms/DataForm/DataForm/Samples/ContactForm/Helpers/FloatingActionButtonImage.cs #region Copyright // <copyright file="FloatingActionButtonImage.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using SampleBrowser.Core; using Xamarin.Forms; /// <summary> /// View that holds floating action button image /// </summary> public class FloatingActionButtonImage : Image { /// <summary> /// Command property is a bindable property to allow the property binding on BindableObject. /// </summary> public static readonly BindableProperty CommandProperty = BindableProperty.Create("Command", typeof(ICommand), typeof(FloatingActionButtonImage), null); /// <summary> /// Command parameter property is a bindable property to allow the property binding on BindableObject. /// </summary> public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create("CommandParameter", typeof(object), typeof(FloatingActionButtonImage), null); /// <summary> /// Initializes a new instance of the <see cref="FloatingActionButtonImage"/> class. /// </summary> public FloatingActionButtonImage() { this.Initialize(); } /// <summary> /// Represents the method that will handle item tap. /// </summary> public event EventHandler ItemTapped = (e, a) => { }; /// <summary> /// Gets or sets the command property value of the command to execute an action. /// </summary> public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { this.SetValue(CommandProperty, value); } } /// <summary> /// Gets or sets the parameter value of the command. /// </summary> public object CommandParameter { get { return this.GetValue(CommandParameterProperty); } set { this.SetValue(CommandParameterProperty, value); } } /// <summary> /// Gets the value of the command after transition. /// </summary> private ICommand TransitionCommand { get { return new Command(async () => { AnchorX = 0.48; AnchorY = 0.48; await this.ScaleTo(0.8, 50, Easing.Linear); await Task.Delay(100); await this.ScaleTo(1, 50, Easing.Linear); Command?.Execute(CommandParameter); ItemTapped(this, EventArgs.Empty); }); } } /// <summary> /// Initializes and sets the initial value for the floating action button image. /// </summary> public void Initialize() { this.VerticalOptions = LayoutOptions.EndAndExpand; this.WidthRequest = 40; this.HeightRequest = 40; this.Source = "Add.png"; this.HorizontalOptions = LayoutOptions.EndAndExpand; GestureRecognizers.Add(new TapGestureRecognizer { Command = this.TransitionCommand }); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Axis/StripLines.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class StripLines : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Weather Report"; chart.Title.TextSize = 15; NumericalStripLine numericalStripLines1 = new NumericalStripLine(); numericalStripLines1.Start = 10; numericalStripLines1.Width = 10; numericalStripLines1.Text = "Low Temperature"; numericalStripLines1.LabelStyle.TextSize = 12; numericalStripLines1.FillColor = Color.ParseColor("#f9d423"); NumericalStripLine numericalStripLines2 = new NumericalStripLine(); numericalStripLines2.Start = 20; numericalStripLines2.Width = 10; numericalStripLines2.Text = "Average Temperature"; numericalStripLines2.LabelStyle.TextSize = 12; numericalStripLines2.FillColor = Color.ParseColor("#fc902a"); NumericalStripLine numericalStripLines3 = new NumericalStripLine(); numericalStripLines3.Start = 30; numericalStripLines3.Width = 10; numericalStripLines3.Text = "High Temperature"; numericalStripLines3.LabelStyle.TextSize = 12; numericalStripLines3.FillColor = Color.ParseColor("#ff512f"); NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Minimum = 10; numericalAxis.Maximum = 40; numericalAxis.LabelStyle.LabelFormat = "##.##°C"; numericalAxis.StripLines.Add(numericalStripLines1); numericalAxis.StripLines.Add(numericalStripLines2); numericalAxis.StripLines.Add(numericalStripLines3); chart.PrimaryAxis = new CategoryAxis(); (chart.PrimaryAxis as CategoryAxis).LabelPlacement = LabelPlacement.BetweenTicks; chart.SecondaryAxis = numericalAxis; var lineSeries = new LineSeries { StrokeWidth = 2, ItemsSource = MainPage.GetStripLineData(), XBindingPath = "XValue", YBindingPath = "YValue", Color = Color.White }; chart.Series.Add(lineSeries); ChartTooltipBehavior toolTip = new ChartTooltipBehavior(); toolTip.TextColor = Color.Black; chart.Behaviors.Add(toolTip); lineSeries.DataMarker.ShowLabel = false; lineSeries.DataMarker.ShowMarker = true; lineSeries.DataMarker.MarkerWidth = 10; lineSeries.DataMarker.MarkerHeight = 10; lineSeries.DataMarker.MarkerColor = Color.ParseColor("#666666"); lineSeries.DataMarker.MarkerStrokeColor = Color.ParseColor("#ffffff"); lineSeries.DataMarker.MarkerStrokeWidth = 4; lineSeries.TooltipEnabled = true; return chart; } } }<file_sep>/iOS/SampleBrowser/Samples/DataSource/ViewModel/DataSourceGettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Diagnostics; using System.Collections.ObjectModel; namespace SampleBrowser { public class DataSourceGettingStartedViewModel : INotifyPropertyChanged { #region Constructor public DataSourceGettingStartedViewModel() { } #endregion #region Filtering #region Fields private string filtertext = ""; private string selectedcolumn = "All Columns"; private string selectedcondition = "Equals"; internal delegate void FilterChanged (); internal FilterChanged filtertextchanged; #endregion #region Property public string FilterText { get{ return filtertext; } set { filtertext = value; OnFilterTextChanged (); RaisePropertyChanged ("FilterText"); } } public string SelectedCondition { get { return selectedcondition; } set { selectedcondition = value; } } public string SelectedColumn { get { return selectedcolumn; } set { selectedcolumn = value; } } #endregion #region Private Methods private void OnFilterTextChanged () { filtertextchanged (); } private bool MakeStringFilter (BookDetails o, string option, string condition) { var value = o.GetType ().GetProperty (option); var exactValue = value.GetValue (o, null); exactValue = exactValue.ToString ().ToLower (); string text = FilterText.ToLower (); var methods = typeof(string).GetMethods (); if (methods.Count () != 0) { if (condition == "Contains") { var methodInfo = methods.FirstOrDefault (method => method.Name == condition); bool result1 = (bool)methodInfo.Invoke (exactValue, new object[] { text }); return result1; } else if (exactValue.ToString () == text.ToString ()) { bool result1 = String.Equals (exactValue.ToString (), text.ToString ()); if (condition == "Equals") return result1; else if (condition == "NotEquals") return false; } else if (condition == "NotEquals") { return true; } return false; } else return false; } private bool MakeNumericFilter (BookDetails o, string option, string condition) { var value = o.GetType ().GetProperty (option); var exactValue = value.GetValue (o, null); double res; bool checkNumeric = double.TryParse (exactValue.ToString (), out res); if (checkNumeric) { switch (condition) { case "Equals": try { if (exactValue.ToString () == FilterText) { if (Convert.ToDouble (exactValue) == (Convert.ToDouble (FilterText))) return true; } } catch (Exception e) { Console.WriteLine (e); Debug.WriteLine("Invalid input"); } break; case "NotEquals": try { if (Convert.ToDouble (FilterText) != Convert.ToDouble (exactValue)) return true; } catch (Exception e) { Console.WriteLine (e); Debug.WriteLine("Invalid input"); return true; } break; } } return false; } #endregion #region Public Methods public bool FilerRecords (object o) { double res; bool checkNumeric = double.TryParse (FilterText, out res); var item = o as BookDetails; if (item != null && FilterText.Equals ("")) { return true; } else { if (item != null) { if (checkNumeric && !SelectedColumn.Equals ("All Columns")) { bool result = MakeNumericFilter (item, SelectedColumn, SelectedCondition); return result; } else if (SelectedColumn.Equals ("All Columns")) { if (item.BookName.ToLower ().Contains (FilterText.ToLower ()) || item.Price.ToString ().ToLower ().Contains (FilterText.ToLower ()) || item.BookID.ToString ().ToLower ().Contains (FilterText.ToLower ())|| item.CustomerName.ToString ().ToLower ().Contains (FilterText.ToLower ())) return true; return false; } else { bool result = MakeStringFilter (item, SelectedColumn, SelectedCondition); return result; } } } return false; } #endregion #endregion #region ItemsSource private ObservableCollection<BookDetails> bookInfo; public ObservableCollection<BookDetails> BookInfo { get { return bookInfo; } set { this.bookInfo = value; } } #endregion #region ItemSource Generator public void SetRowstoGenerate (int count) { BookDetailsRepository bookrepository = new BookDetailsRepository (); bookInfo = bookrepository.GetBookDetails (count); } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged (string propertyName) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (propertyName)); } #endregion } }<file_sep>/Forms/Presentation/Presentation/Samples/Slides/Slides.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using System.Xml; using System.Xml.Linq; using SampleBrowser.Core; namespace SampleBrowser.Presentation { public partial class Slides : SampleView { public Slides() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Slides.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Slides.pptx"; #endif Assembly assembly = typeof(Slides).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a existing PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); #region Slide1 ISlide slide1 = presentation.Slides[0]; IShape shape1 = slide1.Shapes[0] as IShape; shape1.Left = 108; shape1.Top = 139.68; shape1.Width = 743.04; shape1.Height = 144; ITextBody textFrame1 = shape1.TextBody; IParagraphs paragraphs1 = textFrame1.Paragraphs; IParagraph paragraph1 = paragraphs1.Add(); paragraphs1[0].IndentLevelNumber = 0; AddParagraphData(paragraph1, "ESSENTIAL PRESENTATION", "Calibri", 48,true); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center; slide1.Shapes.RemoveAt(1); #endregion #region Slide2 ISlide slide2 = presentation.Slides.Add(SlideLayoutType.SectionHeader); shape1 = slide2.Shapes[0] as IShape; shape1.Left = 55; shape1.Top = 23; shape1.Width = 573; shape1.Height = 71; textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe paragraphs1 = textFrame1.Paragraphs; paragraph1 = paragraphs1.Add(); AddParagraphData(paragraph1, "Slide with simple text", "Calibri", 40, false); paragraphs1[0].HorizontalAlignment = HorizontalAlignmentType.Left; IShape shape2 = slide2.Shapes[1] as IShape; shape2.Left = 87; shape2.Top = 119; shape2.Width = 725; shape2.Height = 355; ITextBody textFrame2 = shape2.TextBody; //Instance to hold paragraphs in textframe IParagraphs paragraphs2 = textFrame2.Paragraphs; //Add paragrpah text IParagraph paragraph_1 = paragraphs2.Add(); AddParagraphData(paragraph_1, "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.", "Calibri", 15, false); IParagraph paragraph_2 = paragraphs2.Add(); AddParagraphData(paragraph_2, "In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group.", "Calibri", 15, false); #endregion #region Slide3 slide2 = presentation.Slides.Add(SlideLayoutType.TwoContent); shape1 = slide2.Shapes[0] as IShape; shape1.Left = 26; shape1.Top = 37; shape1.Width = 815; shape1.Height = 76; //Adds textframe in shape textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe paragraphs1 = textFrame1.Paragraphs; paragraphs1.Add(); paragraph1 = paragraphs1[0]; AddParagraphData(paragraph1, "Slide with Image", "Calibri", 44, false); //Adds shape in slide shape2 = slide2.Shapes[1] as IShape; shape2.Left = 578; shape2.Top = 141; shape2.Width = 316; shape2.Height = 326; textFrame2 = shape2.TextBody; //Instance to hold paragraphs in textframe paragraphs2 = textFrame2.Paragraphs; IParagraph paragraph2 = paragraphs2.Add(); AddParagraphData(paragraph2, "The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases.", "Calibri", 16, false); IParagraph paragraph3 = paragraphs2.Add(); AddParagraphData(paragraph3, "Using Northwind, you can become familiar with how a relational database is structured and how the database objects work together to help you enter, store, manipulate, and print your data.", "Calibri", 16, false); IParagraph paragraph4 = paragraphs2.Add(); // AddParagraphData(paragraph4, ref textpart1, "While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.", "Calibri", 16); IShape shape3 = (IShape)slide2.Shapes[2]; slide2.Shapes.RemoveAt(2); //Adds picture in the shape resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.tablet.jpg"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.tablet.jpg"; #endif assembly = typeof(Slides).GetTypeInfo().Assembly; fileStream = assembly.GetManifestResourceStream(resourcePath); slide2.Shapes.AddPicture(fileStream, 58, 141, 477, 318); fileStream.Dispose(); #endregion #region Slide4 ISlide slide4 = presentation.Slides.Add(SlideLayoutType.TwoContent); shape1 = slide4.Shapes[0] as IShape; shape1.Left = 37; shape1.Top = 24; shape1.Width = 815; shape1.Height = 76; textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe paragraphs1 = textFrame1.Paragraphs; paragraphs1.Add(); paragraph1 = paragraphs1[0]; AddParagraphData(paragraph1, "Slide with Table", "Calibri", 44, false); shape2 = slide4.Shapes[1] as IShape; slide4.Shapes.Remove(shape2); ITable table = (ITable)slide4.Shapes.AddTable(6, 6, 58, 154, 823, 273); table.Rows[0].Height = 61.2; table.Rows[1].Height = 30; table.Rows[2].Height = 61; table.Rows[3].Height = 61; table.Rows[4].Height = 61; table.Rows[5].Height = 61; table.HasBandedRows = true; table.HasHeaderRow = true; table.HasBandedColumns = false; table.BuiltInStyle = BuiltInTableStyle.MediumStyle2Accent1; ICell cell1 = table.Rows[0].Cells[0]; textFrame2 = cell1.TextBody; paragraph2 = textFrame2.Paragraphs.Add(); paragraph2.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart2 = paragraph2.AddTextPart(); textPart2.Text = "ID"; ICell cell2 = table.Rows[0].Cells[1]; ITextBody textFrame3 = cell2.TextBody; paragraph3 = textFrame3.Paragraphs.Add(); paragraph3.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart3 = paragraph3.AddTextPart(); textPart3.Text = "Company Name"; ICell cell3 = table.Rows[0].Cells[2]; ITextBody textFrame4 = cell3.TextBody; paragraph4 = textFrame4.Paragraphs.Add(); paragraph4.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart4 = paragraph4.AddTextPart(); textPart4.Text = "<NAME>"; ICell cell4 = table.Rows[0].Cells[3]; ITextBody textFrame5 = cell4.TextBody; IParagraph paragraph5 = textFrame5.Paragraphs.Add(); paragraph5.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart5 = paragraph5.AddTextPart(); textPart5.Text = "Address"; ICell cell5 = table.Rows[0].Cells[4]; ITextBody textFrame6 = cell5.TextBody; IParagraph paragraph6 = textFrame6.Paragraphs.Add(); paragraph6.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart6 = paragraph6.AddTextPart(); textPart6.Text = "City"; ICell cell6 = table.Rows[0].Cells[5]; ITextBody textFrame7 = cell6.TextBody; IParagraph paragraph7 = textFrame7.Paragraphs.Add(); paragraph7.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart7 = paragraph7.AddTextPart(); textPart7.Text = "Country"; //Add data in table AddTableData(cell1, table, textFrame1, paragraph1); slide4.Shapes.RemoveAt(1); #endregion MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("SlidesSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("SlidesSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } void AddTableData(ICell cell1, ITable table, ITextBody textFrame1, IParagraph paragraph1) { Dictionary<string, Dictionary<string, string>> products = LoadXMLData(); int count = 0; for (int i = 1; i <= 5; i++) { for (int j = 0; j <= 5; j++) { cell1 = table.Rows[i].Cells[j]; textFrame1 = cell1.TextBody; paragraph1 = textFrame1.Paragraphs.Add(); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textpart1 = paragraph1.AddTextPart(); textpart1.Text = products.Values.ToList()[0].Values.ToList()[count]; count++; } } } void AddParagraphData(IParagraph paragraph, string text, string fontname, int fontsize, bool isBolt) { ITextPart textpart = paragraph.AddTextPart(); paragraph.HorizontalAlignment = HorizontalAlignmentType.Left; textpart.Text = text; textpart.Font.FontName = fontname; textpart.Font.FontSize = fontsize; textpart.Font.Color = ColorObject.Black; textpart.Font.Bold = isBolt; } private Dictionary<string, Dictionary<string, string>> LoadXMLData() { XDocument productXml; Dictionary<string, Dictionary<string, string>> Products = new Dictionary<string, Dictionary<string, string>>(); Assembly assembly = typeof(Slides).GetTypeInfo().Assembly; Stream productXMLStream = null; #if COMMONSB productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.Presentation.Samples.Templates.SlideTableData.xml"); #else productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Presentation.Samples.Templates.SlideTableData.xml"); #endif productXml = XDocument.Load(productXMLStream); IEnumerable<XElement> productElements = from product in productXml.Descendants("Product") select product; string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; string month; foreach (XElement productElement in productElements) { Dictionary<string, string> Month_Value = new Dictionary<string, string>(); foreach (XElement child in productElement.Descendants()) { var childElements = productElement.Element(child.Name); if (childElements != null) { string value = childElements.Value; string elementName = child.Name.ToString(); switch (elementName) { case "Cell": foreach (XElement mo in child.Descendants()) { month = mo.Name.LocalName; foreach (XElement val in mo.Descendants()) { Month_Value.Add(month, val.Value); } } break; case "ProductName": productName = value; break; } } } Products.Add(productName, Month_Value); } return Products; } } } <file_sep>/Forms/Calendar/Calendar.iOS/AppDelegate.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using Foundation; using SampleBrowser.Core.iOS; using UIKit; #region Generated Code namespace SampleBrowser.SfCalendar.iOS #endregion { /// <summary> /// The UIApplicationDelegate for the application. This class is responsible for launching the /// User Interface of the application, as well as listening (and optionally responding) to /// application events from iOS. /// </summary> [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { /// <summary> /// status Bar and navigation bar Height /// </summary> private double statusBarHeight, navigationBarHeight; /// <summary> /// This method is invoked when the application has loaded and is ready to run. In this /// method you should instantiate the window, load the UI into it and then make the window /// visible. /// You have 17 seconds to return from this method, or iOS will terminate your application. /// </summary> /// <param name="app">app param</param> /// <param name="options">options param</param> /// <returns>Finished Launching</returns> public override bool FinishedLaunching(UIApplication app, NSDictionary options) { this.statusBarHeight = app.StatusBarFrame.Size.Height; this.navigationBarHeight = new CustomNavigationPageRenderer().NavigationBar.Frame.Height; global::Xamarin.Forms.Forms.Init(); Syncfusion.SfCalendar.XForms.iOS.SfCalendarRenderer.Init(); Syncfusion.ListView.XForms.iOS.SfListViewRenderer.Init(); SampleBrowser.Core.iOS.CoreSampleBrowser.Init(UIScreen.MainScreen.Bounds, app.StatusBarFrame.Size.Height); this.LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }<file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/OptionsView/Options.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using Syncfusion.SfPullToRefresh; using CoreGraphics; using Syncfusion.SfDataGrid; namespace SampleBrowser { public class Options : UIView { UILabel transtionMode; UISwitch transtion; public Options(SfPullToRefresh pullToRefresh) { transtionMode = new UILabel(); transtionMode.Text = "Transition: Push / SlideOnTop"; transtion = new UISwitch(); transtion.On = pullToRefresh.TransitionType == TransitionType.SlideOnTop ? true : false; transtion.ValueChanged += (sender, e) => { pullToRefresh.TransitionType = transtion.On ? TransitionType.SlideOnTop : TransitionType.Push; if (pullToRefresh.PullableContent.GetType() != typeof(SfDataGrid)) pullToRefresh.RefreshContentThreshold = transtion.On ? 0 : 17; else pullToRefresh.PullingThreshold = transtion.On ? 90 : 120; }; this.AddSubview(transtionMode); this.AddSubview(transtion); } public override void LayoutSubviews() { base.LayoutSubviews(); transtionMode.Frame = new CGRect(10, 10, 3 * this.Frame.Width / 4, 50); transtion.Frame = new CGRect(3 * this.Frame.Width / 4, 20, 30, 10); } } }<file_sep>/iOS/SampleBrowser/Samples/DataSource/Helper/ContactCell.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreAnimation; using System; using System.Collections.Generic; using System.Text; using UIKit; namespace SampleBrowser { public class ContactCell : UITableViewCell { #region Field private UILabel Label1; private UILabel Label2; private UILabel Label3; #endregion #region Constructor public ContactCell() { this.AutosizesSubviews = false; Label1 = CreateLabel(Label1); Label1.TextColor = UIColor.White; Label1.TextAlignment = UITextAlignment.Center; Label1.Font = UIFont.BoldSystemFontOfSize(20); Label1.Layer.MasksToBounds = false; Label1.Layer.BorderColor = UIColor.White.CGColor; Label1.Layer.BorderWidth = 0; Label1.ClipsToBounds = true; Label1.Frame = new CoreGraphics.CGRect(0, 0, 70, 70); Label2 = CreateLabel(Label2); Label2.Font = UIFont.FromName("Helvetica Neue", 15); Label3 = CreateLabel(Label3); Label3.TextColor = UIColor.LightGray; SelectionStyle = UITableViewCellSelectionStyle.Blue; this.AddSubviews(new UIView[] {Label1, Label2, Label3 }); this.LayoutMargins = new UIEdgeInsets(10, 10, 10, 10); this.Layer.AddSublayer(new CALayer()); } #endregion #region Private Method private UILabel CreateLabel(UILabel label) { label = new UILabel(); label.TextColor = UIColor.Black; label.TextAlignment = UITextAlignment.Left; label.LineBreakMode = UILineBreakMode.CharacterWrap; label.Font = UIFont.FromName("Helvetica Neue", 11); return label; } Random r = new Random(); public void UpdateValue(object obj) { var contact = obj as Contacts; Label1.Text = contact.ContactName[0].ToString(); Label2.Text = contact.ContactName; Label3.Text = contact.ContactNumber; Label1.BackgroundColor = contact.ContactColor; } #endregion #region override public override void LayoutSubviews() { this.Layer.Frame = this.Frame; this.Layer.Sublayers[0].BackgroundColor = UIColor.LightGray.CGColor; this.Layer.Sublayers[0].Frame = new CoreGraphics.CGRect(0, 0, this.Frame.Width, 0.5); Label1.Frame = new CoreGraphics.CGRect(10, 10, 50, this.Frame.Height - 20); var radius = (float)Math.Min(Label1.Frame.Width, Label1.Frame.Height); Label1.Layer.CornerRadius = (radius / 2); nfloat y = 0; foreach (var subview in this.Subviews) { if (subview is UILabel && !(subview == Label1)) { subview.Frame = new CoreGraphics.CGRect(Label1.Frame.Right + 20, y + 10, (this.Frame.Width - 20 - Label1.Frame.Right), (this.Frame.Height - 20) / 3); y += subview.Frame.Height; } } } #endregion } } <file_sep>/Forms/DataSource/DataSource/Samples/DataSourceGettingStarted/DataSourceGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using System.Reflection; using Syncfusion.DataSource; using SampleBrowser.Core; using Xamarin.Forms.Internals; namespace SampleBrowser.DataSource { [Preserve(AllMembers = true)] public partial class DataSourceGettingStarted : SampleView { DataSourceGettingStartedViewModel viewModel; Syncfusion.DataSource.DataSource sfDataSource; public DataSourceGettingStarted() { InitializeComponent(); viewModel = new DataSourceGettingStartedViewModel(); sfDataSource = new Syncfusion.DataSource.DataSource(); viewModel.DataSource = sfDataSource; sfDataSource.Source = viewModel.BookInfo as IEnumerable<BookDetails>; sfDataSource.BeginInit(); viewModel.filtertextchanged = OnFilterChanged; sfDataSource.SortDescriptors.Add(new SortDescriptor() { Direction = ListSortDirection.Descending, PropertyName = "BookID", }); sfDataSource.EndInit(); listView.ItemsSource = sfDataSource.DisplayItems; ColumnsList.SelectedIndex = 0; } #region CallBacks void OnColumnsSelectionChanged(object sender, EventArgs e) { Picker newPicker = (Picker)sender; viewModel.SelectedColumn = newPicker.Items[newPicker.SelectedIndex]; if (viewModel.SelectedColumn == "All Columns") { viewModel.SelectedCondition = "Contains"; OptionsList.IsVisible = false; this.OnFilterChanged(); } else { OptionsList.IsVisible = true; var prop = typeof(BookDetails).GetRuntimeProperty(viewModel.SelectedColumn); if (prop.Name == viewModel.SelectedColumn) { if (prop.PropertyType == typeof(string)) { OptionsList.Items.Clear(); OptionsList.Items.Add("Contains"); OptionsList.Items.Add("Equals"); OptionsList.Items.Add("NotEquals"); if (this.viewModel.SelectedCondition == "Equals") OptionsList.SelectedIndex = 1; else if (this.viewModel.SelectedCondition == "NotEquals") OptionsList.SelectedIndex = 2; else OptionsList.SelectedIndex = 0; } else { OptionsList.Items.Clear(); OptionsList.Items.Add("Equals"); OptionsList.Items.Add("NotEquals"); if (this.viewModel.SelectedCondition == "Equals") OptionsList.SelectedIndex = 0; else OptionsList.SelectedIndex = 1; } } } } void OnFilterOptionsChanged(object sender, EventArgs e) { Picker newPicker = (Picker)sender; if (newPicker.SelectedIndex >= 0) { viewModel.SelectedCondition = newPicker.Items[newPicker.SelectedIndex]; if (viewModel.FilterText != null) this.OnFilterChanged(); } } void OnFilterTextChanged(object sender, TextChangedEventArgs e) { if (e.NewTextValue == null) viewModel.FilterText = ""; else viewModel.FilterText = e.NewTextValue; } void OnFilterChanged() { if (sfDataSource != null) { this.sfDataSource.Filter = viewModel.FilerRecords; this.sfDataSource.RefreshFilter(); } } #endregion } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/RenderingDynamicData.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Graphics; using Android.Views; namespace SampleBrowser { public class RenderingDynamicData:SamplePage { SfDataGrid sfGrid; public override Android.Views.View GetSampleContent (Android.Content.Context context) { sfGrid = new SfDataGrid (context); GridTextColumn product = new GridTextColumn(); product.MappingName = "Product"; product.HeaderTextMargin = new Thickness(8, 0, 0, 0); product.TextMargin = new Thickness(8, 0, 0, 0); sfGrid.Columns.Add(product); GridTextColumn stockColumn = new GridTextColumn (); stockColumn.UserCellType = typeof(StockCell); stockColumn.LoadUIView = true; stockColumn.MappingName = "StockChange"; stockColumn.HeaderText = "Stock"; stockColumn.AllowSorting = false; stockColumn.HeaderTextMargin = new Thickness(8, 0, 0, 0); stockColumn.TextMargin = new Thickness(8, 0, 0, 0); sfGrid.SelectionMode = SelectionMode.Single; sfGrid.Columns.Add (stockColumn); sfGrid.GridStyle.AlternatingRowColor = Color.Rgb (206, 206, 206); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = new RenderingDynamicDataViewModel ().Stocks; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; return sfGrid; } void GridAutoGenerateColumns (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "LastTrade") { e.Column.HeaderText = "Last Trade"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "Change") { e.Column.TextAlignment = GravityFlags.Right; } else if (e.Column.MappingName == "PreviousClose") { e.Column.HeaderText = "Previous Close"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "Open") { e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "Account") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Symbol") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Volume") { e.Column.TextAlignment = GravityFlags.Center; } } public override void Destroy () { this.sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; sfGrid.Dispose (); sfGrid = null; } } } <file_sep>/Forms/Maps/Maps/Samples/ColorMappings/ColorMappings.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfMaps.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] //[XamlCompilation(XamlCompilationOptions.Compile)] public partial class ColorMappings : SampleView { public ColorMappings() { InitializeComponent(); var shapeLayer = this.Map.Layers[0] as ShapeFileLayer; shapeLayer.TooltipSettings.TooltipTemplate = grid.Resources["toolTipTemplate"] as DataTemplate; grid.SizeChanged += Grid_SizeChanged; } private void Grid_SizeChanged(object sender, EventArgs e) { if (Map.Bounds.Width > Map.Bounds.Height) { (this.Map.Layers[0] as ShapeFileLayer).LegendSettings.LegendPosition = new Point(55, 85); (this.Map.Layers[0] as ShapeFileLayer).LegendSettings.HorizontalAlignment = HorizontalAlignment.Start; } else { (this.Map.Layers[0] as ShapeFileLayer).LegendSettings.LegendPosition = new Point(50, 5); (this.Map.Layers[0] as ShapeFileLayer).LegendSettings.HorizontalAlignment = HorizontalAlignment.Center; } } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/GettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GettingStartedViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for GettingStarted sample. /// </summary> public class GettingStartedViewModel : INotifyPropertyChanged { #region Fields [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<GettingStartedModel> data; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private List<string> stockSymbols = new List<string>(); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] location = new string[] { "East", "West", "Central", }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] teamName = new string[] { "Cavaliers", "Clippers", "DenverNuggets", "DetroitPistons", "GoldenState", "Hornets", "LosAngeles", "Mavericks", "Memphis", "Miami", "Milwakke", "NewYork", "Orlando", "Thunder", }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int[] wins = new int[] { 93, 82, 76, 77, 52, 84, 82, 81, 70, 65, 97, 77, 72, 68, 66 }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int[] losses = new int[] { 58, 67, 72, 73, 98, 66, 68, 69, 81, 85, 54, 74, 78, 82, 85, }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double[] pct = new double[] { .616, .550, .514, .513, .347, .560, .547, .540, .464, .433, .642, .510, .480, .453, .437 }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double[] gb = new double[] { 0, 10, 15.5, 15.5, 40.5, 0, 2, 3, 14.5, 19, 0, 20, 24.5, 28.5, 31, }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] l10 = new string[] { "6-4", "4-6", "4-6", "5-5", "2-8", "5-5", "6-4", "9-1", "4-6", "4-6", "6-4", "3-7", "5-5", "4-6", "7-3" }; #endregion #region Constructor /// <summary> /// Initializes a new instance of the GettingStartedViewModel class. /// </summary> public GettingStartedViewModel() { this.data = new ObservableCollection<GettingStartedModel>(); this.AddRows(14); } #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets the Data. /// </summary> /// <value>The Data.</value> public ObservableCollection<GettingStartedModel> Data { get { return this.data; } } #region updating code /// <summary> /// Adds the rows. /// </summary> /// <param name="count">The given count.</param> private void AddRows(int count) { for (int i = 1; i < count; i++) { this.data.Add(this.GetTeamDetail(i)); } } /// <summary> /// Get the Employee details. /// </summary> /// <param name="i">record index</param> /// <returns>team details</returns> private GettingStartedModel GetTeamDetail(int i) { return new GettingStartedModel() { Team = this.teamName[i], PCT = this.pct[i], GB = this.gb[i], Wins = this.wins[i], Losses = this.losses[i], Image = this.teamName[i] == "Thunder" ? this.teamName[i] + "_Logo.png" : this.teamName[i] + ".png", Location = this.location[i % 3] }; } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type of name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Bubble.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Bubble : SampleView { public Bubble () { SFChart chart = new SFChart (); chart.Title.Text = new NSString ("World Countries Details"); SFNumericalAxis primaryAxis = new SFNumericalAxis (); chart.PrimaryAxis = primaryAxis; primaryAxis.Minimum = new NSNumber (50); primaryAxis.Maximum = new NSNumber (110); primaryAxis.Interval = new NSNumber (10); primaryAxis.ShowMinorGridLines = false; primaryAxis.ShowMajorGridLines = false; chart.PrimaryAxis.Title.Text = new NSString ("Literacy Rate"); chart.SecondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis.Title.Text = new NSString ("GDP Growth Rate"); chart.SecondaryAxis.Minimum = new NSNumber (-2); chart.SecondaryAxis.Maximum = new NSNumber (16); chart.SecondaryAxis.ShowMinorGridLines = false; chart.SecondaryAxis.ShowMajorGridLines = false; ChartViewModel dataModel = new ChartViewModel (); SFBubbleSeries series = new SFBubbleSeries(); series.EnableTooltip = true; series.Alpha = 0.6f; series.ItemsSource = dataModel.BubbleData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.Size = "Size"; series.MaximumRadius = 20; series.MinimumRadius = 5; series.ColorModel.Palette = SFChartColorPalette.Natural; series.EnableAnimation = true; chart.Series.Add(series); chart.AddChartBehavior(new SFChartZoomPanBehavior()); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } }<file_sep>/Android/SampleBrowser/Samples/TabView/readme.md The `SfTabView` control provides a simple and intuitive interface for tab navigation in your mobile application that allows users to explore and switch among different views. The following sample is available for tab view to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](TabViewGettingStarted.cs)|It demonstrates customization of Tab view's header, positioning items and handling overflown tabs.| <file_sep>/Android/SampleBrowser/Samples/Chart/Axis/Logarithmic.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class Logarithmic : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Product X Growth [1995-2005]"; chart.Title.TextSize = 15; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis categoryAxis = new CategoryAxis(); categoryAxis.AxisLineOffset = 10; categoryAxis.PlotOffset = 10; categoryAxis.Title.Text = "Year"; chart.PrimaryAxis = categoryAxis; chart.PrimaryAxis.Interval = 2; chart.PrimaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; LogarithmicAxis logAxis = new LogarithmicAxis(); logAxis.ShowMinorGridLines = true; logAxis.MinorTicksPerInterval = 5; logAxis.Title.Text = "Profit"; logAxis.LabelStyle.LabelFormat = "$##.##"; chart.SecondaryAxis = logAxis; LineSeries lineSeries = new LineSeries(); lineSeries.EnableAnimation = true; lineSeries.ItemsSource = MainPage.GetLogarithmicData(); lineSeries.XBindingPath = "XValue"; lineSeries.YBindingPath = "YValue"; lineSeries.DataMarker.ShowLabel = false; lineSeries.DataMarker.ShowMarker = true; lineSeries.DataMarker.MarkerHeight = 10; lineSeries.DataMarker.MarkerWidth = 10; lineSeries.DataMarker.MarkerStrokeWidth = 2; lineSeries.DataMarker.MarkerStrokeColor = Color.ParseColor("#00bdae"); lineSeries.DataMarker.MarkerColor = Color.White; chart.Series.Add(lineSeries); lineSeries.TooltipEnabled = true; return chart; } } }<file_sep>/Forms/ListView/ListView/Samples/Selection/Model/MusiqInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class MusiqInfoRepository { #region Constructor public MusiqInfoRepository() { } #endregion #region Properties internal ObservableCollection<Musiqnfo> GetMusiqInfo() { var random = new Random(); var musiqInfo = new ObservableCollection<Musiqnfo>(); for (int i = 0; i < SongsNames.Count(); i++) { var info = new Musiqnfo() { SongTitle = SongsNames[i], SongAuther = SongAuthers[i], SongSize = random.Next(50, 600).ToString() + "." + random.Next(1, 10) / 2 + "KB", }; musiqInfo.Add(info); } return musiqInfo; } #endregion #region SongInfo string[] SongsNames = new string[] { "Adventure of a lifetime", "Blue moon of Kentucky", "I don't care if tomorrow never comes", "You are the first, my last, my everything", "Words don't come easy to me", "Everybody's free to wear sunscreen", "Before the next teardrop falls", "You've lost that lovin' feeling", "Underneath your clothes", "Try to remember", "The hanging tree", "Somewhere over the rainbow", "Return to innocence", "I say a little prayer for you", "I believe I can fly", "House every weekend", "Heal the world", "Green green grass of home", "God only knows", "Five hundred miles", "Earth song", "Down to the river to pray", "Come away with me", "Boulevard of broken dreams", "Heart is a drum", "I'm so lonesome I could cry", }; string[] SongAuthers = new string[] { "Coldplay", "<NAME>", "<NAME> & <NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "Righteous Brothers", "Shakira", "<NAME>", "<NAME> ft. <NAME>", "<NAME>", "Enigma", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "The Beach Boys", "The Brothers Four", "<NAME>", "<NAME>", "<NAME>", "Green Day", "Beck", "<NAME>", }; #endregion } } <file_sep>/Forms/TimePicker/readme.md The `SfPicker` allows user to pick an item from a list of items that can be customized with custom view. The following samples are available for picker control to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](Picker/Samples/PickerGettingStarted)|It demonstrates the selection functionality on picker items.| |[Dialog](Picker/Samples/PopupPicker)| It demonstrates the dialog mode in picker control.| |[Date/Time](Picker/Samples/DateTimePicker)| It demonstrates the data binding support with the most popular data sources. The picker control automatically generates its columns based on data source structure. | |[Cascading](Picker/Samples/Cascading)| It demonstrates the usage of multiple collections in a row. A column’s data source depends on the selection in another column. Countries and cities are the data sources, the items in cities column is populated based on selected country.| <file_sep>/Android/SampleBrowser/Samples/Schedule/ScheduleViewOptionLayout.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Widget; using Android.Views; using Android.Content; using Android.Graphics; using Android.App; using Android.OS; using System.Collections.ObjectModel; using System.Reflection.Emit; using Android.Media; using Com.Syncfusion.Schedule; using Com.Syncfusion.Schedule.Enums; using Android.Util; namespace SampleBrowser { public class ScheduleViewOptionLayout : IDisposable { private Context con; private LinearLayout mainLayout, borderLayout; private SfSchedule sfSchedule; public FrameLayout OptionLayout { get; set; } public ScheduleViewOptionLayout(Context context, SfSchedule schedule) { con = context; sfSchedule = schedule; Density = con.Resources.DisplayMetrics; OptionLayout = new FrameLayout(context); OptionLayout.SetBackgroundColor(Color.White); OptionLayout.LayoutParameters = new ViewGroup.LayoutParams(Density.WidthPixels / 3, Density.HeightPixels / 3); borderLayout = new LinearLayout(context); borderLayout.SetBackgroundColor(Color.LightGray); borderLayout.SetPadding(1, 1, 1, 1); borderLayout.LayoutParameters = new ViewGroup.LayoutParams(Density.WidthPixels / 3, Density.HeightPixels / 3); AddHeaderViews(); } internal DisplayMetrics Density { get; set; } internal TextView Day { get; set; } internal TextView Week { get; set; } internal TextView Workweek { get; set; } internal TextView Month { get; set; } private void AddHeaderViews() { mainLayout = new LinearLayout(con); mainLayout.SetBackgroundColor(Color.White); mainLayout.LayoutParameters = new ViewGroup.LayoutParams(Density.WidthPixels / 3, Density.HeightPixels / 3); mainLayout.Orientation = Android.Widget.Orientation.Vertical; Day = new TextView(con); Day.Text = "Day"; Day.TextSize = 20; Day.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, (Density.HeightPixels / 3) / 4); //Where 20 as a textsize Day.SetPadding(10, (Day.LayoutParameters.Height / 2) - 20, 0, 0); Week = new TextView(con); Week.Text = "Week"; Week.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, (Density.HeightPixels / 3) / 4); Week.TextSize = 20; //Where 20 as a textsize Week.SetPadding(10, (Week.LayoutParameters.Height / 2) - 20, 0, 0); Workweek = new TextView(con); Workweek.Text = "Workweek"; Workweek.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, (Density.HeightPixels / 3) / 4); Workweek.TextSize = 20; //Where 20 as a textsize Workweek.SetPadding(10, (Workweek.LayoutParameters.Height / 2) - 20, 0, 0); Month = new TextView(con); Month.Text = "Month"; Month.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, (Density.HeightPixels / 3) / 4); Month.TextSize = 20; //Where 20 as a textsize Month.SetPadding(10, (Month.LayoutParameters.Height / 2) - 20, 0, 0); View divider1 = new View(con); divider1.SetBackgroundColor(Color.LightGray); divider1.LayoutParameters = new ViewGroup.LayoutParams(Density.WidthPixels / 3, 2); View divider2 = new View(con); divider2.SetBackgroundColor(Color.LightGray); divider2.LayoutParameters = new ViewGroup.LayoutParams(Density.WidthPixels / 3, 2); View divider3 = new View(con); divider3.SetBackgroundColor(Color.LightGray); divider3.LayoutParameters = new ViewGroup.LayoutParams(Density.WidthPixels / 3, 2); mainLayout.AddView(Day); mainLayout.AddView(divider1); mainLayout.AddView(Week); mainLayout.AddView(divider2); mainLayout.AddView(Workweek); mainLayout.AddView(divider3); mainLayout.AddView(Month); borderLayout.AddView(mainLayout); OptionLayout.AddView(borderLayout); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void Day_Click(object sender, EventArgs e) { sfSchedule.ScheduleView = ScheduleView.DayView; } public void Dispose() { if (sfSchedule!= null) { sfSchedule.Dispose(); sfSchedule = null; } if (mainLayout != null) { mainLayout.Dispose(); mainLayout = null; } if (borderLayout != null) { borderLayout.Dispose(); borderLayout = null; } } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/SfImage.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SfImage.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; /// <summary> /// A custom Image View that holds an image. /// </summary> public class SfImage : Syncfusion.SfDataGrid.XForms.SfImageView { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed.")] /// <summary> /// Initializes a new instance of the SfImage class. /// </summary> public SfImage() { } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/ProgressBar/Circular.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; using CoreGraphics; using Syncfusion.iOS.ProgressBar; using UIKit; namespace SampleBrowser { public class Circular : SampleView { UIScrollView scrollView; SfCircularProgressBar CircularDeterminate; SfCircularProgressBar CircularInDeterminate; SfCircularProgressBar CircularCustomContent; SfCircularProgressBar CircularVideoPlayer; SfCircularProgressBar CircularTrackOutside; SfCircularProgressBar CircularFilledIndicator; SfCircularProgressBar CircularTrackInside; SfCircularProgressBar CircularThinTrackStyle; SfCircularProgressBar CircularSegment; SfCircularProgressBar CircularSegmentPadding; SfCircularProgressBar CircularSegmentFillStyle; SfCircularProgressBar CircularAngleCustomization; UILabel CircularDeterminateLabel; UILabel CircularCustomContentLabel; UILabel CircularRadiusCustomizationLabel; UILabel CircularSegmentLabel; UILabel CircularAngleCustomizationLabel; UIView CustContentLayout; UIButton pauseButton, playButton; bool isDispose = false; private UILabel GetLabel(string text) { return new UILabel() { Text = text, Font = UIFont.FromName("HelveticaNeue", 11f), TextAlignment = UITextAlignment.Left }; } private UILabel GetLabel(double content) { string custContent = content + "%"; return new UILabel() { Frame = new CGRect(0, 0, 40, 20), Text = custContent, Font = UIFont.FromName("HelveticaNeue", 11f), TextAlignment = UITextAlignment.Center, TextColor = UIColor.FromRGB(0, 124, 238) }; } public Circular() { scrollView = new UIScrollView(); this.AddSubview(scrollView); CircularDeterminateLabel = this.GetLabel("Detminate and indeterminate"); CircularDeterminate = new SfCircularProgressBar { Progress = 75 }; CircularInDeterminate = new SfCircularProgressBar { IsIndeterminate = true }; scrollView.AddSubview(CircularDeterminateLabel); scrollView.AddSubview(CircularDeterminate); scrollView.AddSubview(CircularInDeterminate); CircularCustomContentLabel = this.GetLabel("Custom content"); CircularCustomContent = new SfCircularProgressBar() { Progress = 75, AnimationDuration = 1, }; this.SetCustomContentProgress(); this.CircularVideoPlayer = new SfCircularProgressBar() { Progress = 100, TrackInnerRadius = 0f, IndicatorOuterRadius = 0.7f, IndicatorInnerRadius = 0.65f, AnimationDuration = 2000, }; this.CircularVideoPlayer.ValueChanged += this.ProgressBar_ValueChanged100; scrollView.AddSubview(this.CircularCustomContentLabel); scrollView.AddSubview(this.CircularCustomContent); scrollView.AddSubview(this.CircularVideoPlayer); UIView customView = new UIView(); customView.Frame = new CGRect(0, 40, 100, 80); playButton = new UIButton(); playButton.Hidden = true; playButton.Frame = new CGRect(0, 23, 100, 33); playButton.SetImage(UIImage.FromFile("SfProgressPlay.png"), UIControlState.Normal); playButton.BackgroundColor = UIColor.Clear; pauseButton = new UIButton(); pauseButton.Frame = new CGRect(0, 23, 100, 33); pauseButton.BackgroundColor = UIColor.Clear; pauseButton.SetImage(UIImage.FromFile("SfProgressPause.png"), UIControlState.Normal); customView.AddSubview(playButton); customView.AddSubview(pauseButton); playButton.TouchUpInside += (sender, e) => { this.CircularVideoPlayer.Progress = 100; this.pauseButton.Hidden = false; this.playButton.Hidden = true; }; pauseButton.TouchUpInside += (sender, e) => { this.CircularVideoPlayer.Progress = (double)GetInternalPropertyValue(typeof(ProgressBarBase), this.CircularVideoPlayer, "ActualProgress"); this.playButton.Hidden = false; this.pauseButton.Hidden = true; }; this.CircularVideoPlayer.Content = customView; this.CircularRadiusCustomizationLabel = this.GetLabel("Radius customization"); this.CircularTrackOutside = new SfCircularProgressBar() { Progress = 100, IndicatorOuterRadius = 0.7f, IndicatorInnerRadius = 0.65f, ShowProgressValue = false, AnimationDuration = 2000, }; this.CircularTrackOutside.ValueChanged += this.ProgressBar_ValueChanged100; this.CircularFilledIndicator = new SfCircularProgressBar() { Progress = 100, IndicatorOuterRadius = 0.7f, IndicatorInnerRadius = 0f, ShowProgressValue = false, AnimationDuration = 2000, }; this.CircularFilledIndicator.ValueChanged += this.ProgressBar_ValueChanged100; CircularTrackInside = new SfCircularProgressBar() { TrackOuterRadius = 0.7f, TrackInnerRadius = 0f, ShowProgressValue = true, AnimationDuration = 1, }; this.SetTrackInsideStyleProgress(); this.CircularThinTrackStyle = new SfCircularProgressBar() { Progress = 100, IndicatorOuterRadius = 0.75f, IndicatorInnerRadius = 0.6f, TrackOuterRadius = 0.7f, TrackInnerRadius = 0.65f, AnimationDuration = 2000, ShowProgressValue = false, }; this.CircularThinTrackStyle.ValueChanged += this.ProgressBar_ValueChanged100; scrollView.AddSubview(CircularRadiusCustomizationLabel); scrollView.AddSubview(CircularTrackOutside); scrollView.AddSubview(CircularFilledIndicator); scrollView.AddSubview(CircularTrackInside); scrollView.AddSubview(CircularThinTrackStyle); this.CircularSegmentLabel = this.GetLabel("Segment"); this.CircularSegment = new SfCircularProgressBar() { Progress = 75, ShowProgressValue = false, SegmentCount = 4, AnimationDuration = 2000, }; this.CircularSegment.ValueChanged += this.ProgressBar_ValueChanged75; this.CircularSegmentPadding = new SfCircularProgressBar() { Progress = 75, ShowProgressValue = false, TrackInnerRadius = 0.6f, IndicatorInnerRadius = 0.65f, IndicatorOuterRadius = 0.7f, AnimationDuration = 2000, SegmentCount = 4 }; this.CircularSegmentPadding.ValueChanged += this.ProgressBar_ValueChanged75; CircularSegmentFillStyle = new SfCircularProgressBar() { ShowProgressValue = false, SegmentCount = 20, AnimationDuration = 1, }; this.SetSegmentedFillingStyleProgress(); scrollView.AddSubview(CircularSegmentLabel); scrollView.AddSubview(CircularSegment); scrollView.AddSubview(CircularSegmentPadding); scrollView.AddSubview(CircularSegmentFillStyle); this.CircularAngleCustomizationLabel = this.GetLabel("Angle customization"); this.CircularAngleCustomization = new SfCircularProgressBar() { Progress = 100, StartAngle = 130, EndAngle = 410, AnimationDuration = 2000, ShowProgressValue = false }; this.CircularAngleCustomization.ValueChanged += this.ProgressBar_ValueChanged100; scrollView.AddSubview(CircularAngleCustomizationLabel); scrollView.AddSubview(CircularAngleCustomization); } public override void LayoutSubviews() { base.LayoutSubviews(); nfloat X = 20; nfloat Y = 40; nfloat margin = 10; nfloat height = this.scrollView.Frame.Size.Height / 6; nfloat width = this.scrollView.Frame.Size.Width - 40; nfloat columnWidth = (this.scrollView.Frame.Size.Width - 40) / 3; scrollView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); CircularDeterminateLabel.Frame = new CGRect(X, Y, width, 15); Y = Y + CircularDeterminateLabel.Frame.Size.Height + margin; CircularDeterminate.Frame = new CGRect(X, Y, columnWidth, height); CircularInDeterminate.Frame = new CGRect(X + columnWidth + margin, Y, columnWidth, height); Y = Y + CircularDeterminate.Frame.Size.Height + margin; CircularCustomContentLabel.Frame = new CGRect(X, Y, width, 15); Y = Y + CircularCustomContentLabel.Frame.Size.Height + margin; CircularCustomContent.Frame = new CGRect(X, Y, columnWidth, height); CircularVideoPlayer.Frame = new CGRect(X + columnWidth + margin, Y, columnWidth, height); Y = Y + CircularCustomContent.Frame.Size.Height + margin; CircularRadiusCustomizationLabel.Frame = new CGRect(X, Y, width, 15); Y = Y + CircularRadiusCustomizationLabel.Frame.Size.Height + margin; CircularTrackOutside.Frame = new CGRect(X, Y, columnWidth, height); CircularFilledIndicator.Frame = new CGRect(X + columnWidth + margin, Y, columnWidth, height); CircularTrackInside.Frame = new CGRect(X + columnWidth * 2 + margin, Y, columnWidth, height); Y = Y + CircularTrackOutside.Frame.Size.Height + margin; CircularThinTrackStyle.Frame = new CGRect(X, Y, columnWidth, height); Y = Y + CircularThinTrackStyle.Frame.Size.Height + margin; CircularSegmentLabel.Frame = new CGRect(X, Y, width, 15); Y = Y + CircularSegmentLabel.Frame.Size.Height + margin; CircularSegment.Frame = new CGRect(X, Y, columnWidth, height); CircularSegmentPadding.Frame = new CGRect(X + columnWidth + margin, Y, columnWidth, height); CircularSegmentFillStyle.Frame = new CGRect(X + columnWidth * 2 + margin, Y, columnWidth, height); Y = Y + CircularSegment.Frame.Size.Height + margin; CircularAngleCustomizationLabel.Frame = new CGRect(X, Y, width, 15); Y = Y + CircularAngleCustomizationLabel.Frame.Size.Height + margin; CircularAngleCustomization.Frame = new CGRect(X, Y, columnWidth, height); scrollView.ContentSize = new CGSize(this.Frame.Size.Width, Y + CircularAngleCustomization.Frame.Size.Height); } private void ProgressBar_ValueChanged100(object sender, ProgressValueEventArgs e) { SfCircularProgressBar progressbar = sender as SfCircularProgressBar; if (e.Progress.Equals(100)) { progressbar.AnimationDuration = 1; progressbar.Progress = 0; } if (e.Progress.Equals(0)) { progressbar.AnimationDuration = 2000; progressbar.Progress = 100; } } private void ProgressBar_ValueChanged75(object sender, ProgressValueEventArgs e) { SfCircularProgressBar progressbar = sender as SfCircularProgressBar; if (e.Progress.Equals(75)) { progressbar.AnimationDuration = 1; progressbar.Progress = 0; } if (e.Progress.Equals(0)) { progressbar.AnimationDuration = 2000; progressbar.Progress = 75; } } private async Task SetCustomContentProgress() { if (!isDispose) { double progress = 0; while (progress < 75) { this.CircularCustomContent.Progress = progress += 1; this.CustContentLayout = new UIView(); this.CustContentLayout.Frame = new CGRect(0, 0, 100, 80); string custContent = progress + "%"; UILabel progressLabel = new UILabel() { Frame = new CGRect(this.CustContentLayout.Center.X - 20, 25, 40, 20), Text = custContent, Font = UIFont.FromName("HelveticaNeue", 11f), TextAlignment = UITextAlignment.Center, TextColor = UIColor.FromRGB(0, 124, 238) }; this.CustContentLayout.AddSubview(progressLabel); UILabel textView = new UILabel() { Frame = new CGRect(this.CustContentLayout.Center.X - 20, this.CustContentLayout.Center.Y, 40, 20), Text = "used", TextAlignment = UITextAlignment.Center, Font = UIFont.FromName("HelveticaNeue", 10f), TextColor = UIColor.FromRGB(0, 124, 238), }; this.CustContentLayout.Center = this.CircularCustomContent.Center; this.CustContentLayout.AddSubview(textView); this.CircularCustomContent.Content = this.CustContentLayout; await Task.Delay(50); } } } private async Task SetSegmentedFillingStyleProgress() { if (!isDispose) { double progress = 0; this.CircularSegmentFillStyle.Progress = 0; await Task.Delay(1000); while (progress < 100) { this.CircularSegmentFillStyle.Progress = progress += 5; await Task.Delay(1000); } await this.SetSegmentedFillingStyleProgress(); } } private async void SetTrackInsideStyleProgress() { if (!isDispose) { double progress = 0; while (progress < 100) { this.CircularTrackInside.Progress = progress += 1; this.CircularTrackInside.Content = this.GetLabel((int)progress); if (this.Handle != System.IntPtr.Zero) CircularTrackInside.AddSubview(this.CircularTrackInside.Content); await Task.Delay(500); } this.CircularTrackInside.Progress = 0; this.SetTrackInsideStyleProgress(); } } protected override void Dispose(bool disposing) { isDispose = disposing; base.Dispose(disposing); } public static object GetInternalPropertyValue(Type type, object obj, string name) { var properties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance); return properties.Where(propertyInfo => propertyInfo.Name.Equals(name)) .Select(propertyInfo => propertyInfo.GetValue(obj)) .FirstOrDefault(); } } }<file_sep>/Forms/DataSource/DataSource/Samples/Helper/CustomView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Syncfusion.DataSource.Extensions; using Syncfusion.DataSource; using Xamarin.Forms.Internals; namespace SampleBrowser.DataSource { [Preserve(AllMembers = true)] public class CustomListView : ListView { public CustomListView() { this.BackgroundColor = Color.White; } protected override void SetupContent(Cell content, int index) { var viewCell = content as ViewCell; if ((this.ItemsSource as DisplayItems)[index] is GroupResult) { viewCell.View = new Header() { WidthRequest = this.Width }; } else if (viewCell.View is Header) { viewCell.View = this.ItemTemplate.CreateContent() as View; } base.SetupContent(viewCell, index); } } [Preserve(AllMembers = true)] public class Header : ContentView { Label label; public Header() { this.BackgroundColor = Color.FromHex("#D9D9D9"); this.Padding = new Thickness(10, 0, 0, 0); label = new Label(); label.TextColor = Color.Black; label.FontSize = 18; label.VerticalTextAlignment = TextAlignment.Center; label.HorizontalOptions = LayoutOptions.Start; label.VerticalOptions = LayoutOptions.Center; label.FontAttributes = FontAttributes.Bold; label.HeightRequest = 30; this.Content = label; } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); } protected override void OnBindingContextChanged() { if ((this.BindingContext is GroupResult)) { var groupresult = this.BindingContext as GroupResult; label.Text += groupresult.Key.ToString(); } base.OnBindingContextChanged(); } } [Preserve(AllMembers = true)] public class Row : StackLayout { protected override void OnSizeAllocated(double width, double height) { foreach (var child in this.Children) { child.WidthRequest = this.Width / 4; child.HeightRequest = 50; } base.OnSizeAllocated(width, height); } } [Preserve(AllMembers = true)] public class CustomGrid : Grid { protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); } protected override void LayoutChildren(double x, double y, double width, double height) { base.LayoutChildren(x, y, width, height); } } [Preserve(AllMembers = true)] public class DisplayLabel : Label { public DisplayLabel() { if(Device.RuntimePlatform == Device.UWP) { this.FontSize = 30; } else if(Device.RuntimePlatform == Device.Android) { if (Device.Idiom == TargetIdiom.Phone) this.FontSize = 30; else this.FontSize = 32; } else { if (Device.Idiom == TargetIdiom.Phone) this.FontSize = 30; else this.FontSize = 32; } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(50, 50); } protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint) { return new SizeRequest(new Size(50, 50)); } } [Preserve(AllMembers = true)] public class ContentLabel : Label { public ContentLabel() { if (Device.RuntimePlatform == Device.UWP) { this.FontSize = 16; this.HeightRequest = 20; } else if (Device.RuntimePlatform == Device.Android) { if (Device.Idiom == TargetIdiom.Phone) this.FontSize = 16; else this.FontSize = 18; this.HeightRequest = 20; } else { if (Device.Idiom == TargetIdiom.Phone) this.FontSize = 16; else this.FontSize = 18; this.HeightRequest = 20; } } } } <file_sep>/Forms/ImageEditor/ImageEditor.iOS/Renderers/CustomRenderers.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using CoreGraphics; using Foundation; using SampleBrowser.SfImageEditor.iOS.Renderers; using CustomControls = SampleBrowser.SfImageEditor.CustomControls; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using System.IO; using System.Threading.Tasks; [assembly:ExportRenderer(typeof(CustomControls.CustomEditor), typeof(CustomEditorRenderer))] namespace SampleBrowser.SfImageEditor.iOS.Renderers { public class CustomEditorRenderer : EditorRenderer { UITextView replacingControl; protected override void OnElementChanged(ElementChangedEventArgs<Editor> e) { base.OnElementChanged(e); if (Control != null) { var element = e.NewElement as CustomControls.CustomEditor; replacingControl = new UITextView(Control.Bounds); replacingControl.Layer.BorderColor = Color.Gray.ToCGColor(); replacingControl.Layer.CornerRadius = 20; replacingControl.Layer.BorderWidth = 3; replacingControl.TextContainerInset = new UIEdgeInsets(15, 20, 0, 20); if (element == null) return; replacingControl.Text = element.WatermarkText; replacingControl.TextAlignment = UITextAlignment.Center; replacingControl.ClearsOnInsertion = false; if (replacingControl.Text == element.WatermarkText) { replacingControl.TextColor = UIColor.LightGray; replacingControl.ClearsOnInsertion = true; } else{ replacingControl.TextColor = UIColor.Black; } replacingControl.Changed += (sender, ev) => { replacingControl.TextColor = UIColor.Black; }; replacingControl.ResignFirstResponder(); this.SetNativeControl(replacingControl); } } protected override void Dispose(bool disposing) { if(disposing && replacingControl!=null) { replacingControl = null; } } } }<file_sep>/Android/SampleBrowser/Samples/DataForm/Model/ContactsInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Collections.ObjectModel; namespace SampleBrowser { public class ContactsInfoRepository { #region Fields private Random random = new Random(); #endregion #region Constructor public ContactsInfoRepository() { } #endregion #region Get Contacts Details public ObservableCollection<ContactsInfo> GetContactDetails(int count) { ObservableCollection<ContactsInfo> customerDetails = new ObservableCollection<ContactsInfo>(); for (int i = 0; i < 10; i++) { var details = new ContactsInfo() { ContactType = ContactsInfo.ContactsType.Business, ContactNumber = random.Next(100000, 400000).ToString(), ContactName = customerNames[i], }; customerDetails.Add(details); } customerDetails[0].ContactImage = Resource.Drawable.Contact0; customerDetails[1].ContactImage = Resource.Drawable.Contact1; customerDetails[2].ContactImage = Resource.Drawable.Contact2; customerDetails[3].ContactImage = Resource.Drawable.Contact3; customerDetails[4].ContactImage = Resource.Drawable.Contact4; customerDetails[5].ContactImage = Resource.Drawable.Contact5; customerDetails[6].ContactImage = Resource.Drawable.Contact6; customerDetails[7].ContactImage = Resource.Drawable.Contact7; customerDetails[8].ContactImage = Resource.Drawable.Contact8; customerDetails[9].ContactImage = Resource.Drawable.Contact9; return customerDetails; } #endregion #region Contacts Information [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] private string[] contactType = new string[] { "HOME", "WORK", "MOBILE", "OTHER", "BUSINESS" }; private string[] customerNames = new string[] { "Liz", "Ralph", "Oscar", "Torrey", "Gina", "Irene", "Katie", "Fiona", "Kyle", "Michael", "William", "Bill", }; #endregion } }<file_sep>/Forms/Picker/Picker.UWP/CustomEntryRenderer.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Windows.UI; using Windows.UI.Xaml.Media; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; using SampleBrowser.SfPicker; using SampleBrowser.UWP; [assembly: ExportRenderer(typeof(CustomPickerEntry), typeof(CustomPickerEntryRenderer))] namespace SampleBrowser.UWP { public class CustomPickerEntryRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (e.NewElement == null) return; Control.IsReadOnly = true; Control.BorderBrush = new Windows.UI.Xaml.Media.SolidColorBrush(Colors.LightGray); Control.VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center; Control.VerticalContentAlignment = Windows.UI.Xaml.VerticalAlignment.Center; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Presentation/TablesPresentation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Presentation; using System.Collections.Generic; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using Syncfusion.Calculate; using System.Xml; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class TablesPresentation : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UILabel label2; UIButton button; public TablesPresentation() { label2 = new UILabel(); label1 = new UILabel(); label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to create a table with specified number of rows and columns using Presentation library."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (0, 10,frameRect.Location.X + frameRect.Size.Width , 120); } else { label.Frame = new CGRect (frameRect.Location.X, 10, frameRect.Size.Width , 120); } this.AddSubview (label); label2.Frame = frameRect; label2.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label2.Text = "Please click the Generate Presentation button to save and view the generated PowerPoint Presentation."; label2.Font = UIFont.SystemFontOfSize(15); label2.Lines = 0; label2.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label2.Font = UIFont.SystemFontOfSize(18); label2.Frame = new CGRect (0, 190, frameRect.Location.X + frameRect.Size.Width , 50); } else { label2.Frame = new CGRect (frameRect.Location.X, 190, frameRect.Size.Width , 50); } this.AddSubview (label2); button.SetTitle("Generate Presentation",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect (0, 290, frameRect.Location.X + frameRect.Size.Width , 10); } else { button.Frame = new CGRect (frameRect.Location.X, 260, frameRect.Size.Width , 10); } this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { //Stream to save the created PowerPoint presnetation MemoryStream stream = new MemoryStream(); //Creates a new instance of the presentation. using (IPresentation presentation = Syncfusion.Presentation.Presentation.Create()) { #region Slide1 //To add a slide to PowerPoint presentation ISlide slide = presentation.Slides.Add(SlideLayoutType.TitleOnly); //To set the table title in a slide SetTableTitle(slide); //To get the table data from an XML file Dictionary<string, Dictionary<string, string>> products = LoadXMLData(); int columnCount = products.Keys.Count + 1; int rowCount = products[products.Keys.ToArray()[0]].Count + 1; //To add a new table in slide. ITable table = slide.Shapes.AddTable(rowCount, columnCount, 61.92, 95.76, 856.8, 378.72); //To set the style for the table. table.BuiltInStyle = BuiltInTableStyle.MediumStyle2Accent6; //To set category title SetCategoryTitle(table); //Iterates and sets the values to the table cells. for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++) { IRow row = table.Rows[rowIndex]; Dictionary<string, string> months = products[products.Keys.ToArray()[0]]; string[] monthName = months.Keys.ToArray(); for (int cellIndex = 0; cellIndex < row.Cells.Count - 1; cellIndex++) { months = products[products.Keys.ToArray()[cellIndex]]; AddHeaderRowAndColumn(row, cellIndex, products.Keys.ToArray(), rowIndex, monthName); AddCellContent(row, rowIndex, monthName, months, cellIndex); } } #endregion //Save the presentation instance to the memory stream. presentation.Save(stream); } stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("TablesPresentation.pptx", "application/mspowerpoint", stream); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } #region HelperMethods /// <summary> /// Loads the xml content to fill the table cells in the presentation. /// </summary> /// <returns></returns> private Dictionary<string, Dictionary<string, string>> LoadXMLData() { Dictionary<string, Dictionary<string, string>> Products = new Dictionary<string, Dictionary<string, string>>(); Assembly assembly = Assembly.GetExecutingAssembly(); Stream productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.Presentation.Templates.TableData.xml"); XmlReader reader = XmlReader.Create(productXMLStream); string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; string month; while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Products": Dictionary<string, string> Month_Value = new Dictionary<string, string>(); while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Product": while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Month": while (reader.Read()) { month = reader.Name; if (reader.IsStartElement()) { month = reader.Name; while (reader.Read()) { if (reader.IsStartElement()) { if (reader.Name == "Value") { reader.Read(); reader.MoveToContent(); Month_Value.Add(month, reader.Value); } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == month) { break; } } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Month") { break; } } break; case "ProductName": reader.Read(); reader.MoveToContent(); productName = reader.Value; break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Product") { break; } } break; } Products.Add(productName, Month_Value); Month_Value = new Dictionary<string, string>(); } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Products") break; } break; } } } return Products; } /// <summary> /// Sets the table title. /// </summary> /// <param name="slide">Represents the slide instance of the presentation.</param> private void SetTableTitle(ISlide slide) { IShape shape = slide.Shapes[0] as IShape; shape.Left = 84.24; shape.Top = 0; shape.Width = 792; shape.Height = 126.72; ITextBody textFrame = shape.TextBody; IParagraphs paragraphs = textFrame.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; //Instance to hold textparts in paragraph. ITextParts textParts = paragraph.TextParts; textParts.Add(); ITextPart textPart = textParts[0]; textPart.Text = "Target "; IFont font = textPart.Font; font.FontName = "Arial"; font.FontSize = 28; font.Bold = true; font.CapsType = TextCapsType.All; textParts.Add(); //Creates a textpart and assigns value to it. textPart = textParts[1]; textPart.Text = "Vs "; font = textPart.Font; font.FontName = "Arial"; font.FontSize = 18; textParts.Add(); //Creates a textpart and assigns value to it. textPart = textParts[2]; textPart.Text = "PERFORMANCE"; font = textPart.Font; font.FontName = "Arial"; font.FontSize = 28; font.Bold = true; } /// <summary> /// Adds the cell content to the table. /// </summary> /// <param name="row">Represents the instance of row.</param> /// <param name="rowIndex">Represents the row index.</param> /// <param name="monthName">Represnets the array of month name.</param> /// <param name="months">Represnets the dictionary of months and its values.</param> /// <param name="cellIndex">Represents the cell index.</param> private void AddCellContent(IRow row, int rowIndex, string[] monthName, Dictionary<string, string> months, int cellIndex) { if (rowIndex == 0) return; ICell cell = row.Cells[cellIndex + 1]; //Instance to hold paragraphs in cell. IParagraphs paragraphs = cell.TextBody.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Left; ITextParts textParts = paragraph.TextParts; textParts.Add(); //Creates a textpart and assigns value to it. ITextPart textPart = textParts[0]; textPart.Text = months[monthName[rowIndex - 1]]; IFont font = textPart.Font; font.FontName = "Arial"; font.FontSize = 14; } /// <summary> /// Adds the content for the row and column for the table. /// </summary> /// <param name="row">Represents the particular row.</param> /// <param name="cellIndex">Represents the index of the cell.</param> /// <param name="cellContent">Represents the cell content.</param> /// <param name="rowIndex">Represents the index of the row.</param> /// <param name="monthName">Represents the content of monthname for the table.</param> private void AddHeaderRowAndColumn(IRow row, int cellIndex, string[] cellContent, int rowIndex, string[] monthName) { //To set text alignment type inside cell ICell cell = null; if (rowIndex == 0) cell = row.Cells[cellIndex + 1]; else cell = row.Cells[0]; cell.TextBody.VerticalAlignment = VerticalAlignmentType.Middle; //To add a paragraph inside cell IParagraphs paragraphs = cell.TextBody.Paragraphs; if (paragraphs.Count == 0) paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; ITextParts textParts = paragraph.TextParts; if (textParts.Count == 0) textParts.Add(); //Creates a textpart and assigns value to it. ITextPart textPart = textParts[0]; if (rowIndex == 0) textPart.Text = cellContent[cellIndex]; else textPart.Text = monthName[rowIndex - 1]; IFont font = textPart.Font; font.FontName = "Arial"; font.FontSize = 14; font.Bold = true; } /// <summary> /// Sets the title for the category in the table. /// </summary> /// <param name="table">Instance to access the table from the presentation.</param> void SetCategoryTitle(ITable table) { //Instance to hold rows in the table table.Rows[0].Height = 81.44; //To set text alignment type inside cell //ICell cell11 = ; table.Rows[0].Cells[0].TextBody.VerticalAlignment = VerticalAlignmentType.Middle; //To add a paragraph inside cell IParagraphs paragraphs = table.Rows[0].Cells[0].TextBody.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; ITextParts textParts = paragraph.TextParts; textParts.Add(); //Creates a textpart and assigns value to it. ITextPart textPart = textParts[0]; textPart.Text = "Month"; IFont font = textPart.Font; font.FontName = "Arial"; font.FontSize = 14; font.Bold = true; } #endregion HelperMethods } }<file_sep>/Forms/DataForm/DataForm/Samples/DynamicFormPage/Helper/SourceProviderExt.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.DataForm; using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace SampleBrowser.SfDataForm { /// <summary> /// Represents the source of the dataFormItem whose name is given. /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public class SourceProviderExt:SourceProvider { public override IList GetSource(string sourceName) { var list = new List<string>(); if (sourceName == "Team") { list.Add("Marketing"); list.Add("Maintenance"); list.Add("Accounts"); } else if(sourceName == "Country" || sourceName == "EcommerceCountry" || sourceName == "OrganizationCountry") { list.Add("Afghanistan"); list.Add("Akrotiri"); list.Add("Albania"); list.Add("Algeria"); list.Add("American Samoa"); list.Add("Andorra"); list.Add("Angola"); list.Add("Anguilla"); list.Add("Antarctica"); list.Add("Antigua and Barbuda"); list.Add("Argentina"); list.Add("Armenia"); list.Add("Aruba"); list.Add("Ashmore and Cartier Islands"); list.Add("Australia"); list.Add("Austria"); list.Add("Azerbaijan"); list.Add("Bahamas, The"); list.Add("Bahrain"); list.Add("Bangladesh"); list.Add("Barbados"); list.Add("Bassas da India"); list.Add("Belarus"); list.Add("Belgium"); list.Add("Belize"); list.Add("Benin"); list.Add("Bermuda"); list.Add("Bhutan"); list.Add("Bolivia"); list.Add("Bosnia and Herzegovina"); list.Add("Botswana"); list.Add("Bouvet Island"); list.Add("Brazil"); list.Add("British Indian Ocean Territory"); list.Add("British Virgin Islands"); list.Add("Brunei"); list.Add("Bulgaria"); list.Add("Burkina Faso"); list.Add("Burma"); list.Add("Burundi"); list.Add("Cambodia"); list.Add("Cameroon"); list.Add("Canada"); list.Add("Cape Verde"); list.Add("Cayman Islands"); list.Add("Central African Republic"); list.Add("Chad"); list.Add("Chile"); list.Add("China"); list.Add("Christmas Island"); list.Add("Clipperton Island"); list.Add("Cocos (Keeling) Islands"); list.Add("Colombia"); list.Add("Comoros"); list.Add("Congo"); list.Add("Congo, Republic of the"); list.Add("Cook Islands"); list.Add("Coral Sea Islands"); list.Add("Costa Rica"); list.Add("Cote d'Ivoire"); list.Add("Croatia"); list.Add("Cuba"); list.Add("Cyprus"); list.Add("Czech Republic"); list.Add("Denmark"); list.Add("Dhekelia"); list.Add("Djibouti"); list.Add("Dominica"); list.Add("Dominican Republic"); list.Add("Ecuador"); list.Add("Egypt"); list.Add("El Salvador"); list.Add("Equatorial Guinea"); list.Add("Eritrea"); list.Add("Estonia"); list.Add("Ethiopia"); list.Add("Europa Island"); list.Add("Falkland Islands"); list.Add("Faroe Islands"); list.Add("Fiji"); list.Add("Finland"); list.Add("France"); list.Add("French Guiana"); list.Add("French Polynesia"); list.Add("French Southern and Antarctic Lands"); list.Add("Gabon"); list.Add("The Gambia"); list.Add("Gaza Strip"); list.Add("Georgia"); list.Add("Germany"); list.Add("Ghana"); list.Add("Gibraltar"); list.Add("Glorioso Islands"); list.Add("Greece"); list.Add("Greenland"); list.Add("Grenada"); list.Add("Guadeloupe"); list.Add("Guam"); list.Add("Guatemala"); list.Add("Guernsey"); list.Add("Guinea"); list.Add("Guinea-Bissau"); list.Add("Guyana"); list.Add("Haiti"); list.Add("Heard Island and McDonald Islands"); list.Add("Holy See"); list.Add("Honduras"); list.Add("Hong Kong"); list.Add("Hungary"); list.Add("Iceland"); list.Add("India"); list.Add("Indonesia"); list.Add("Iran"); list.Add("Iraq"); list.Add("Ireland"); list.Add("Isle of Man"); list.Add("Israel"); list.Add("Italy"); list.Add("Jamaica"); list.Add("<NAME>"); list.Add("Japan"); list.Add("Jersey"); list.Add("Jordan"); list.Add("Juan de Nova Island"); list.Add("Kazakhstan"); list.Add("Kenya"); list.Add("Kiribati"); list.Add("Korea, North"); list.Add("Korea, South"); list.Add("Kuwait"); list.Add("Kyrgyzstan"); list.Add("Laos"); list.Add("Latvia"); list.Add("Lebanon"); list.Add("Lesotho"); list.Add("Liberia"); list.Add("Libya"); list.Add("Liechtenstein"); list.Add("Lithuania"); list.Add("Luxembourg"); list.Add("Macau"); list.Add("Macedonia"); list.Add("Madagascar"); list.Add("Malawi"); list.Add("Malaysia"); list.Add("Maldives"); list.Add("Mali"); list.Add("Malta"); list.Add("Marshall Islands"); list.Add("Martinique"); list.Add("Mauritania"); list.Add("Mauritius"); list.Add("Mayotte"); list.Add("Mexico"); list.Add("Micronesia"); list.Add("Moldova"); list.Add("Monaco"); list.Add("Mongolia"); list.Add("Montserrat"); list.Add("Morocco"); list.Add("Mozambique"); list.Add("Namibia"); list.Add("Nauru"); list.Add("Navassa Island"); list.Add("Nepal"); list.Add("Netherlands"); list.Add("Netherlands Antilles"); list.Add("New Caledonia"); list.Add("New Zealand"); list.Add("Nicaragua"); list.Add("Niger"); list.Add("Nigeria"); list.Add("Niue"); list.Add("Norfolk Island"); list.Add("Northern Mariana Islands"); list.Add("Norway"); list.Add("Oman"); list.Add("Pakistan"); list.Add("Palau"); list.Add("Panama"); list.Add("Papua New Guinea"); list.Add("Paracel Islands"); list.Add("Paraguay"); list.Add("Peru"); list.Add("Philippines"); list.Add("Pitcairn Islands"); list.Add("Poland"); list.Add("Portugal"); list.Add("Puerto Rico"); list.Add("Qatar"); list.Add("Reunion"); list.Add("Romania"); list.Add("Russia"); list.Add("Rwanda"); list.Add("<NAME>"); list.Add("<NAME> and Nevis"); list.Add("<NAME>"); list.Add("<NAME> and Miquelon"); list.Add("<NAME>"); list.Add("Samoa"); list.Add("San Marino"); list.Add("Sao Tome and Principe"); list.Add("Saudi Arabia"); list.Add("Senegal"); list.Add("Serbia and Montenegro"); list.Add("Seychelles"); list.Add("Sierra Leone"); list.Add("Singapore"); list.Add("Slovakia"); list.Add("Slovenia"); list.Add("Solomon Islands"); list.Add("Somalia"); list.Add("South Africa"); list.Add("South Georgia"); list.Add("Spain"); list.Add("Spratly Islands"); list.Add("Sri Lanka"); list.Add("Sudan"); list.Add("Suriname"); list.Add("Svalbard"); list.Add("Swaziland"); list.Add("Sweden"); list.Add("Switzerland"); list.Add("Syria"); list.Add("Taiwan"); list.Add("Tajikistan"); list.Add("Tanzania"); list.Add("Thailand"); list.Add("Timor-Leste"); list.Add("Togo"); list.Add("Tokelau"); list.Add("Tonga"); list.Add("Trinidad and Tobago"); list.Add("Tromelin Island"); list.Add("Tunisia"); list.Add("Turkey"); list.Add("Turkmenistan"); list.Add("Turks and Caicos Islands"); list.Add("Tuvalu"); list.Add("Uganda"); list.Add("Ukraine"); list.Add("United Arab Emirates"); list.Add("United Kingdom"); list.Add("United States"); list.Add("Uruguay"); list.Add("Uzbekistan"); list.Add("Vanuatu"); list.Add("Venezuela"); list.Add("Vietnam"); list.Add("Virgin Islands"); list.Add("Wake Island"); list.Add("Wallis and Futuna"); list.Add("West Bank"); list.Add("Western Sahara"); list.Add("Yemen"); list.Add("Zambia"); list.Add("Zimbabwe"); } return list; } } } <file_sep>/Android/SampleBrowser/Samples/DocIO/FormFillingAndProtection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public partial class FormFillingAndProtection: SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to fill data and protect the content controls in an existing Word document."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); //Creates an empty Word document instance. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.ContentControlTemplate.docx"); //Opens template document. document.Open(inputStream, FormatType.Word2013); IWTextRange textRange; //Gets table from the template document. IWTable table = document.LastSection.Tables[0]; WTableRow row = table.Rows[1]; #region Inserting content controls #region Calendar content control IWParagraph cellPara = row.Cells[0].Paragraphs[0]; //Accesses the date picker content control. IInlineContentControl inlineControl = (cellPara.ChildEntities[2] as IInlineContentControl); textRange = inlineControl.ParagraphItems[0] as WTextRange; //Sets today's date to display. textRange.Text = DateTime.Now.ToShortDateString(); textRange.CharacterFormat.FontSize = 14; //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; #endregion #region Plain text content controls table = document.LastSection.Tables[1]; row = table.Rows[0]; cellPara = row.Cells[0].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; textRange = inlineControl.ParagraphItems[0] as WTextRange; //Sets text in plain text content control. textRange.Text = "Northwind Analytics"; textRange.CharacterFormat.FontSize = 14; cellPara = row.Cells[1].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; textRange = inlineControl.ParagraphItems[0] as WTextRange; //Sets text in plain text content control. textRange.Text = "Northwind"; textRange.CharacterFormat.FontSize = 14; row = table.Rows[1]; cellPara = row.Cells[0].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; //Sets text in plain text content control. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = "10"; textRange.CharacterFormat.FontSize = 14; cellPara = row.Cells[1].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; //Sets text in plain text content control. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = "<NAME>"; textRange.CharacterFormat.FontSize = 14; #endregion #region CheckBox Content control row = table.Rows[2]; cellPara = row.Cells[0].LastParagraph; //Inserts checkbox content control. inlineControl = cellPara.AppendInlineContentControl(ContentControlType.CheckBox); inlineControl.ContentControlProperties.LockContents = true; //Sets checkbox as checked state. inlineControl.ContentControlProperties.IsChecked = true; textRange = cellPara.AppendText("C#, "); textRange.CharacterFormat.FontSize = 14; //Inserts checkbox content control. inlineControl = cellPara.AppendInlineContentControl(ContentControlType.CheckBox); inlineControl.ContentControlProperties.LockContents = true; //Sets checkbox as checked state. inlineControl.ContentControlProperties.IsChecked = true; textRange = cellPara.AppendText("VB"); textRange.CharacterFormat.FontSize = 14; #endregion #region Drop down list content control cellPara = row.Cells[1].LastParagraph; //Accesses the dropdown list content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); inlineControl.ContentControlProperties.LockContents = true; //Sets default option to display. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = "ASP.NET"; textRange.CharacterFormat.FontSize = 14; inlineControl.ParagraphItems.Add(textRange); //Adds items to the dropdown list. ContentControlListItem item; item = new ContentControlListItem(); item.DisplayText = "ASP.NET MVC"; item.Value = "2"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); item = new ContentControlListItem(); item.DisplayText = "Windows Forms"; item.Value = "3"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); item = new ContentControlListItem(); item.DisplayText = "WPF"; item.Value = "4"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); item = new ContentControlListItem(); item.DisplayText = "Xamarin"; item.Value = "5"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); #endregion #region Calendar content control row = table.Rows[3]; cellPara = row.Cells[0].LastParagraph; //Accesses the date picker content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); inlineControl.ContentControlProperties.LockContents = true; //Sets default date to display. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = DateTime.Now.AddDays(-5).ToShortDateString(); textRange.CharacterFormat.FontSize = 14; cellPara = row.Cells[1].LastParagraph; //Inserts date picker content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); inlineControl.ContentControlProperties.LockContents = true; //Sets default date to display. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = DateTime.Now.AddDays(10).ToShortDateString(); textRange.CharacterFormat.FontSize = 14; #endregion #endregion #region Block content control //Accesses the block content control. BlockContentControl blockContentControl = ((document.ChildEntities[0] as WSection).Body.ChildEntities[2] as BlockContentControl); //Protects the block content control blockContentControl.ContentControlProperties.LockContents = true; #endregion MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("FormFillingAndProtection.docx", "application/msword", stream, m_context); } } } } <file_sep>/Forms/XlsIO/XlsIO/Samples/ExcelToJSON/ExcelToJSON.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using System.Reflection; using SampleBrowser.Core; using Syncfusion.XlsIO; using Syncfusion.Pdf; using Syncfusion.XlsIORenderer; using Xamarin.Forms; using LayoutOptions = Xamarin.Forms.LayoutOptions; namespace SampleBrowser.XlsIO { /// <summary> /// This class is the conversion of a Excel document to PDF. /// </summary> public partial class ExcelToJSON : SampleView { public ExcelToJSON() { InitializeComponent(); this.picker.Items.Add("Workbook"); this.picker.Items.Add("Worksheet"); this.picker.Items.Add("Range"); this.picker.SelectedIndex = 0; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInput.HorizontalOptions = LayoutOptions.Start; this.btnInput.VerticalOptions = LayoutOptions.Center; this.btnInput.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } internal void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; Stream stream = GetFileStream("ExcelToJSON.xlsx"); IWorkbook workbook = application.Workbooks.Open(stream); IWorksheet sheet = workbook.Worksheets[0]; IRange range = sheet.Range["A2:B10"]; bool isShema = this.IsSchema.IsChecked.Value; MemoryStream memoryStream = new MemoryStream(); if (this.picker.SelectedIndex == 0) workbook.SaveAsJson(memoryStream, isShema); else if (this.picker.SelectedIndex == 1) workbook.SaveAsJson(memoryStream, sheet, isShema); else if (this.picker.SelectedIndex == 2) workbook.SaveAsJson(memoryStream, range, isShema); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("ExcelToJSON.json", "application/json", memoryStream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("ExcelToJSON.json", "application/json", memoryStream); } } internal Stream GetFileStream(string fileName) { Stream stream = null; #if COMMONSB stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template."+ fileName); #else stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template." + fileName); #endif return stream; } internal void OnInputButtonClicked(object sender, EventArgs e) { //Load Input Template to memory stream. Stream file = GetFileStream("ExcelToJSON.xlsx"); ; file.Position = 0; MemoryStream stream = new MemoryStream(); file.CopyTo(stream); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.xlsx", "application/msexcel", stream); } } } }<file_sep>/Android/SampleBrowser/Samples/PopupLayout/Onboard Helps/PopupGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Views; using System.Globalization; using Syncfusion.Android.PopupLayout; using Android.Widget; using Android.Views.Animations; using Android; using System.Reflection; using System.Linq; using Android.Graphics; using Android.Animation; using Java.Util; using System.Threading.Tasks; using Android.Content; using Android.Graphics.Drawables; using Android.Text.Method; using Android.Runtime; using Android.Text; namespace SampleBrowser { public class PopupGettingStarted : SamplePage { int clickCount = 0; RelativeLayout mainView; SfDataGrid sfGrid; SfPopupLayout sfPopUp; SwipingViewModel viewModel; Context cont; float density; View backgroundView; ImageView imageView; Animation anim; TextView nextButton; SwipeView leftSwipeView; LinearLayout deleteView; private int swipedRowindex; CheckBox allowsorting; CheckBox allowResizing; CheckBox allowEditing; CheckBox allowRowDragAndDrop; System.Drawing.Point popupLayoutpoint; bool pageExited = false; public override Android.Views.View GetSampleContent(Android.Content.Context context) { mainView = new RelativeLayout(context); cont = context; density = cont.Resources.DisplayMetrics.Density; CreatePopup(); CreateDataGrid(); mainView.AddView(sfGrid); AddBackgroundView(); CreateNextButton(); sfPopUp.Content = mainView; return sfPopUp; } private void CreateNextButton() { if (mainView.IndexOfChild(nextButton) == -1) { nextButton = new TextView(cont); nextButton.SetTypeface(Typeface.Default, TypefaceStyle.Bold); nextButton.TextSize = 20; nextButton.Gravity = GravityFlags.CenterVertical; nextButton.SetTextColor(Color.White); nextButton.Click += BackgroundView_Click; if (MainActivity.IsTablet) nextButton.SetX((cont.Resources.DisplayMetrics.WidthPixels / 10) * 8); else nextButton.SetX((cont.Resources.DisplayMetrics.WidthPixels / 10) * 7); nextButton.SetY((cont.Resources.DisplayMetrics.HeightPixels / 10) * 7); mainView.AddView(nextButton, (int)(100 * density), (int)(50 * density)); } if (clickCount == 4) nextButton.Text = "Ok.Got it !"; else nextButton.Text = "Next"; } private void CreateDataGrid() { deleteView = new LinearLayout(cont); deleteView.TextAlignment = TextAlignment.Center; deleteView.Orientation = Android.Widget.Orientation.Horizontal; deleteView.Click += swipeViewImage_Click; ImageView deleteImage = new ImageView(cont); deleteImage.SetImageResource(Resource.Drawable.Delete); deleteImage.SetBackgroundColor(Color.ParseColor("#EF5350")); TextView delete = new TextView(cont); delete.Text = "DELETE"; delete.Gravity = GravityFlags.Center; delete.TextAlignment = TextAlignment.Center; delete.SetTextColor(Color.White); delete.SetBackgroundColor(Color.ParseColor("#EF5350")); viewModel = new SwipingViewModel(); viewModel.SetRowstoGenerate(100); sfGrid = new SfDataGrid(cont); sfGrid.ViewDetachedFromWindow += SfGrid_ViewDetachedFromWindow; sfGrid.AutoGenerateColumns = false; sfGrid.ItemsSource = (viewModel.OrdersInfo); sfGrid.AllowSwiping = true; sfGrid.AllowSorting = true; sfGrid.AllowResizingColumn = true; sfGrid.AllowDraggingRow = true; sfGrid.AllowEditing = true; sfGrid.ColumnSizer = ColumnSizer.Star; sfGrid.SelectionMode = SelectionMode.Single; sfGrid.NavigationMode = NavigationMode.Cell; sfGrid.EditTapAction = TapAction.OnDoubleTap; sfGrid.GridLoaded += SfGrid_GridLoaded; sfGrid.SwipeEnded += SfGrid_SwipeEnded; sfGrid.RowHeight = 60; int width = cont.Resources.DisplayMetrics.WidthPixels; sfGrid.MaxSwipeOffset = (int)(120 * density); leftSwipeView = new SwipeView(cont); deleteView.AddView(deleteImage, (int)(30 * density), (int)sfGrid.RowHeight); deleteView.AddView(delete, sfGrid.MaxSwipeOffset - 30, (int)sfGrid.RowHeight); leftSwipeView.AddView(deleteView, sfGrid.MaxSwipeOffset, (int)sfGrid.RowHeight); sfGrid.LeftSwipeView = leftSwipeView; GridTextColumn CustomerID = new GridTextColumn(); CustomerID.MappingName = "CustomerID"; CustomerID.HeaderText = "Customer ID"; GridTextColumn OrderID = new GridTextColumn(); OrderID.MappingName = "OrderID"; OrderID.HeaderText = "Order ID"; OrderID.TextMargin = new Thickness(16, 0, 0, 0); OrderID.HeaderTextMargin = new Thickness(16, 0, 0, 0); GridTextColumn EmployeeID = new GridTextColumn(); EmployeeID.MappingName = "EmployeeID"; EmployeeID.HeaderText = "Employee ID"; GridTextColumn Name = new GridTextColumn(); Name.MappingName = "FirstName"; Name.HeaderText = "Name"; sfGrid.Columns.Add(OrderID); sfGrid.Columns.Add(CustomerID); sfGrid.Columns.Add(EmployeeID); sfGrid.Columns.Add(Name); sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; } private void SfGrid_ViewDetachedFromWindow(object sender, View.ViewDetachedFromWindowEventArgs e) { pageExited = true; sfPopUp.Opened -= SfPopUp_PopupOpened; sfPopUp.Closed -= SfPopUp_PopupClosed; sfPopUp.PopupView.ClearAnimation(); sfPopUp.Dispose(); sfPopUp = null; } private void SfGrid_GridLoaded(object sender, GridLoadedEventArgs e) { if (MainActivity.IsTablet) sfPopUp.Show((int)(cont.Resources.DisplayMetrics.WidthPixels / density - 50), 0); else sfPopUp.Show((int)(cont.Resources.DisplayMetrics.WidthPixels / density - 25), 0); } private void CreatePopup() { sfPopUp = new SfPopupLayout(cont); sfPopUp.PopupView.AnimationMode = AnimationMode.Fade; sfPopUp.PopupView.AnimationDuration = 50; sfPopUp.PopupView.PopupStyle.BorderThickness = 0; sfPopUp.PopupView.PopupStyle.BorderColor = Color.Transparent; sfPopUp.PopupView.ShowFooter = false; sfPopUp.PopupView.ShowHeader = false; sfPopUp.Opened += SfPopUp_PopupOpened; sfPopUp.Closed += SfPopUp_PopupClosed; sfPopUp.SetBackgroundColor(Color.Transparent); sfPopUp.PopupView.SetBackgroundColor(Color.Transparent); sfPopUp.StaysOpen = true; sfPopUp.PopupView.WidthRequest = 250; sfPopUp.PopupView.HeightRequest = 100; ImageView img = new ImageView(cont); img.SetImageResource(Resource.Drawable.Popup_InfoNotification); img.SetScaleType(ImageView.ScaleType.FitEnd); sfPopUp.PopupView.ContentView = img; } private void SfPopUp_PopupClosed(object sender, EventArgs e) { if (clickCount == 5) { mainView.RemoveView(backgroundView); mainView.RemoveView(nextButton); } } private void SfPopUp_PopupOpened(object sender, EventArgs e) { sfPopUp.PopupView.AnimationMode = AnimationMode.None; try { if (clickCount == 0) { anim = new TranslateAnimation(sfPopUp.GetX(), sfPopUp.GetX(), sfPopUp.GetY(), sfPopUp.GetY() + 30); anim.Duration = 500; //You can manage the time of the blink with this parameter anim.RepeatMode = RepeatMode.Reverse; anim.RepeatCount = int.MaxValue; sfPopUp.PopupView.StartAnimation(anim); } else if (clickCount == 1) { sfPopUp.PopupView.ClearAnimation(); anim = new TranslateAnimation(popupLayoutpoint.X, popupLayoutpoint.X + (50 * density), popupLayoutpoint.Y, popupLayoutpoint.Y); anim.Duration = 2000; //You can manage the time of the blink with this parameter anim.RepeatMode = RepeatMode.Restart; anim.RepeatCount = int.MaxValue; sfPopUp.PopupView.StartAnimation(anim); } else if (clickCount == 2) { sfPopUp.PopupView.ClearAnimation(); anim = new AlphaAnimation(0.0f, 1.0f); anim.Duration = 250; anim.RepeatCount = 1; //You can manage the time of the blink with this parameter anim.RepeatMode = RepeatMode.Restart; sfPopUp.PopupView.StartAnimation(anim); anim.AnimationEnd += async (s, ev) => { await Task.Delay(1000); if(!pageExited) sfPopUp.PopupView.StartAnimation(anim); }; } else if (clickCount == 3) { sfPopUp.PopupView.ClearAnimation(); anim = null; anim = new TranslateAnimation(popupLayoutpoint.X / density, (popupLayoutpoint.X / density) + 50 * density, popupLayoutpoint.Y / density, popupLayoutpoint.Y / density); anim.Duration = 2000; anim.RepeatCount = int.MaxValue; //You can manage the time of the blink with this parameter anim.RepeatMode = RepeatMode.Restart; sfPopUp.PopupView.StartAnimation(anim); } else if (clickCount == 4) { DrawArc test; sfPopUp.PopupView.ClearAnimation(); anim = null; var handSymbol = (sfPopUp.PopupView.ContentView as RelativeLayout).GetChildAt(1); if (MainActivity.IsTablet) test = new DrawArc(2000, 1, -10, 1, 150, 1, -100); else test = new DrawArc(2000, 1, -50, 1, 350, 1, -300); test.RepeatCount = int.MaxValue; //You can manage the time of the blink with this parameter test.RepeatMode = RepeatMode.Restart; handSymbol.StartAnimation(test); } } catch { } } private void AddBackgroundView() { if (mainView.IndexOfChild(backgroundView) == -1) { backgroundView = new View(cont); backgroundView.SetBackgroundColor(Color.Black); backgroundView.Alpha = 0.8f; backgroundView.Click += BackgroundView_Click; this.mainView.AddView(backgroundView, ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); } } private void BackgroundView_Click(object sender, EventArgs e) { clickCount++; sfPopUp.IsOpen = false; if (imageView == null) { imageView = new ImageView(cont); } if (clickCount == 1) { LinearLayout linear = new LinearLayout(cont); linear.Orientation = Orientation.Horizontal; ImageView img = new ImageView(cont); img.SetImageResource(Resource.Drawable.Popup_ResizingIllustration); linear.AddView(img, (int)(150 * density), ViewGroup.LayoutParams.MatchParent); linear.AddView(new View(cont)); sfPopUp.PopupView.HeightRequest = 150; sfPopUp.PopupView.WidthRequest = 250; sfPopUp.PopupView.ContentView = linear; sfPopUp.PopupView.AnimationMode = AnimationMode.Fade; popupLayoutpoint = this.sfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(0, 1)); sfPopUp.Show(popupLayoutpoint.X, popupLayoutpoint.Y); sfPopUp.StaysOpen = true; img = null; linear = null; } else if (clickCount == 2) { imageView.SetImageResource(Resource.Drawable.Popup_EditIllustration); sfPopUp.PopupView.ContentView = imageView; var point = this.sfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(3, 3)); sfPopUp.PopupView.AnimationMode = AnimationMode.Fade; sfPopUp.Show((int)(point.X / density), (int)(point.Y / density)); sfPopUp.StaysOpen = true; } else if (clickCount == 3) { LinearLayout linear = new LinearLayout(cont); linear.Orientation = Orientation.Horizontal; ImageView img = new ImageView(cont); img.SetBackgroundColor(Color.Transparent); img.SetImageResource(Resource.Drawable.Popup_SwipeIllustration); linear.AddView(img, (int)(250 * density), ViewGroup.LayoutParams.MatchParent); linear.AddView(new View(cont)); sfPopUp.PopupView.HeightRequest = 150; sfPopUp.PopupView.WidthRequest = 350; sfPopUp.PopupView.ContentView = linear; popupLayoutpoint = this.sfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(3, 0)); sfPopUp.PopupView.AnimationMode = AnimationMode.Fade; sfPopUp.Show((int)(popupLayoutpoint.X / density), (int)(popupLayoutpoint.Y / density)); img = null; linear = null; } else if (clickCount == 4) { RelativeLayout linear = new RelativeLayout(cont); ImageView img = new ImageView(cont); img.SetBackgroundColor(Color.Transparent); img.SetImageResource(Resource.Drawable.Popup_DragAndDropIllustration); ImageView img2 = new ImageView(cont); img2.SetBackgroundColor(Color.Transparent); img2.SetImageResource(Resource.Drawable.Popup_HandSymbol); linear.AddView(img, (int)(250 * density), ViewGroup.LayoutParams.MatchParent); linear.AddView(img2, (int)(50 * density), ViewGroup.LayoutParams.MatchParent); linear.AddView(new View(cont)); if (MainActivity.IsTablet) sfPopUp.PopupView.HeightRequest = 200; else sfPopUp.PopupView.HeightRequest = 150; sfPopUp.PopupView.WidthRequest = 350; sfPopUp.PopupView.ContentView = linear; popupLayoutpoint = this.sfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(3, 0)); sfPopUp.PopupView.AnimationMode = AnimationMode.Fade; sfPopUp.Show((int)(popupLayoutpoint.X / density), (int)(popupLayoutpoint.Y / density)); img = null; img2 = null; linear = null; } } public override View GetPropertyWindowLayout(Android.Content.Context context) { LinearLayout linear = new LinearLayout(context); linear.Orientation = Orientation.Vertical; allowsorting = new CheckBox(context); allowResizing = new CheckBox(context); allowEditing = new CheckBox(context); allowRowDragAndDrop = new CheckBox(context); allowsorting.Text = "Allow Sorting"; allowResizing.Text = "Allow Resizing"; allowEditing.Text = "Allow Editing"; allowRowDragAndDrop.Text = "Allow RowDragAndDrop"; allowsorting.Checked = true; allowResizing.Checked = true; allowEditing.Checked = true; allowRowDragAndDrop.Checked = true; allowsorting.CheckedChange += OnAllowSortingChanged; allowResizing.CheckedChange += OnAllowResizingChanged; allowEditing.CheckedChange += OnAllowEditingChanged; allowRowDragAndDrop.CheckedChange += OnAllowRowDragAndDropChanged; linear.AddView(allowsorting); linear.AddView(allowResizing); linear.AddView(allowEditing); linear.AddView(allowRowDragAndDrop); return linear; } void OnAllowRowDragAndDropChanged(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) sfGrid.AllowDraggingRow = true; else sfGrid.AllowDraggingRow = false; } void OnAllowSortingChanged(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) sfGrid.AllowSorting = true; else sfGrid.AllowSorting = false; } void OnAllowResizingChanged(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) sfGrid.AllowResizingColumn = true; else sfGrid.AllowResizingColumn = false; } void OnAllowEditingChanged(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) sfGrid.AllowEditing = true; else sfGrid.AllowEditing = false; } void GridGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (MainActivity.IsTablet) e.Column.MaximumWidth = 300; else e.Column.MaximumWidth = 150; if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.ColumnSizer = ColumnSizer.None; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo("en-US"); e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.ColumnSizer = ColumnSizer.None; e.Column.TextAlignment = GravityFlags.CenterVertical; } else e.Cancel = true; } public override void Destroy() { sfGrid.AutoGeneratingColumn -= GridGenerateColumns; allowsorting.CheckedChange -= OnAllowSortingChanged; allowResizing.CheckedChange -= OnAllowResizingChanged; allowEditing.CheckedChange -= OnAllowEditingChanged; allowRowDragAndDrop.CheckedChange -= OnAllowRowDragAndDropChanged; imageView = null; anim = null; backgroundView = null; viewModel = null; allowEditing = null; allowResizing = null; allowRowDragAndDrop = null; allowsorting = null; sfGrid.Dispose(); sfGrid = null; } private void SfGrid_SwipeEnded(object sender, SwipeEndedEventArgs e) { swipedRowindex = e.RowIndex; } void swipeViewImage_Click(object sender, EventArgs e) { viewModel.OrdersInfo.RemoveAt(swipedRowindex - 1); } } public class DrawArc : Animation { private float displacementY; private Point start; private Point end; private Point middle; private float fromXValue; private float toXValue; private float y; private int startXType; private int endXType; private int yType; public DrawArc(long duration, int fromXType, float fromXValue, int toXType, float toXValue, int yType, float yValue) { this.Duration = duration; this.fromXValue = fromXValue; this.toXValue = toXValue; y = yValue; startXType = fromXType; endXType = toXType; this.yType = yType; } private long CalculatePoints(float interpolatedTime, float p0, float p1, float p2) { return (long)Math.Round((Math.Pow((1 - interpolatedTime), 2) * p0) + (2 * (1 - interpolatedTime) * interpolatedTime * p1) + (Math.Pow(interpolatedTime, 2) * p2)); } protected override void ApplyTransformation(float interpolatedTime, Transformation t) { float displacementX = CalculatePoints(interpolatedTime, start.X, middle.X, end.X); if (MainActivity.IsTablet) displacementY = CalculatePoints(interpolatedTime, start.Y, middle.Y, end.Y - 50); else displacementY = CalculatePoints(interpolatedTime, start.Y, middle.Y, end.Y + 50); t.Matrix.SetTranslate(displacementX - 50, displacementY); } public override void Initialize(int width, int height, int parentWidth, int parentHeight) { base.Initialize(width, height, parentWidth, parentHeight); float startX = ResolveSize(Dimension.Absolute, fromXValue, width, parentWidth); float endX = ResolveSize(Dimension.Absolute, toXValue, width, parentWidth); float middleY = ResolveSize(Dimension.Absolute, y, width, parentWidth); float middleX = startX + ((endX - startX) / 2); start = new Point((int)startX, 0); end = new Point((int)endX, 100); middle = new Point((int)middleX, (int)middleY); } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/PopupCustomizations/PopupCustomizationsBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PopupCustomizationsBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.PopupLayout; using Xamarin.Forms; /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the SeatSelection samples /// </summary> public class PopupCustomizationsBehavior : Behavior<SampleView> { /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">Label type of parameter bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { base.OnAttachedTo(bindAble); (bindAble.Resources["BookingNotification"] as SfPopupLayout).Show(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/CircularGauge/MultipleScales.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfGauge.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using System.Drawing; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class MultipleScales : SampleView { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } UISlider slider; UIView option = new UIView(); SFCircularGauge gauge; SFCircularScale scale1; SFCircularScale scale2; public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } if (Utility.IsIpad) { gauge.Frame = new CGRect(50, 50, (float)this.Frame.Width - 100, (float)this.Frame.Height - 100); } else { gauge.Frame = new CGRect(10, 10, (float)this.Frame.Width - 20, (float)this.Frame.Height - 20); } base.LayoutSubviews(); } public MultipleScales() { gauge = new SFCircularGauge(); scale1 = new SFCircularScale(); scale1.StartValue = 0; scale1.EndValue = 240; scale1.Interval = 20; scale1.MinorTicksPerInterval = 1; scale1.ScaleStartOffset = 0.7f; scale1.ScaleEndOffSet = 0.69f; scale1.LabelOffset = 0.88f; scale1.LabelColor = UIColor.FromRGB(198, 46, 10); scale1.RimColor = UIColor.FromRGB(198, 46, 10); SFTickSettings major = new SFTickSettings(); major.StartOffset = 0.7f; major.EndOffset = 0.77f; major.Width = 2; major.Color = UIColor.FromRGB(198, 46, 10); SFTickSettings minor = new SFTickSettings(); minor.StartOffset = 0.7f; minor.EndOffset = 0.77f; minor.Width = 2; minor.Color = UIColor.FromRGB(198, 46, 10); scale1.MajorTickSettings = major; scale1.MinorTickSettings = minor; SFMarkerPointer pointer1 = new SFMarkerPointer(); pointer1.Value = 120; pointer1.Color = UIColor.FromRGB(198, 46, 10); pointer1.Offset = 0.69f; pointer1.MarkerShape = MarkerShape.InvertedTriangle; pointer1.EnableAnimation = false; scale1.Pointers.Add(pointer1); gauge.Scales.Add(scale1); scale2 = new SFCircularScale(); scale2.StartValue = 0; scale2.EndValue = 160; scale2.Interval = 40; scale2.MinorTicksPerInterval = 1; scale2.RimColor = UIColor.FromRGB(51, 51, 51); scale2.LabelOffset = 0.45f; scale2.LabelColor = UIColor.FromRGB(51, 51, 51); scale2.ScaleStartOffset = 0.65f; scale2.ScaleEndOffSet = 0.64f; SFTickSettings major1 = new SFTickSettings(); major1.StartOffset = 0.64f; major1.EndOffset = 0.57f; major1.Width = 2; major1.Color = UIColor.FromRGB(51, 51, 51); scale2.MajorTickSettings = major1; SFTickSettings minor1 = new SFTickSettings(); minor1.StartOffset = 0.64f; minor1.EndOffset = 0.59f; minor1.Width = 2; minor1.Color = UIColor.FromRGB(51, 51, 51); scale2.MinorTickSettings = minor1; SFMarkerPointer pointer2 = new SFMarkerPointer(); pointer2.Value = 80; pointer2.Color = UIColor.FromRGB(51, 51, 51); pointer2.Offset = 0.65f; pointer2.MarkerShape = MarkerShape.Triangle; pointer2.EnableAnimation = false; scale2.Pointers.Add(pointer2); gauge.Scales.Add(scale2); this.AddSubview(gauge); CreateOptionView(); this.OptionView = option; } private void CreateOptionView() { UILabel text = new UILabel(); text.Text = "Scale1"; text.TextAlignment = UITextAlignment.Left; text.TextColor = UIColor.Black; text.Frame = new CGRect(10, 10, 320, 20); text.Font = UIFont.FromName("Helvetica", 14f); UILabel text1 = new UILabel(); text1.Text = "StartAngle"; text1.TextAlignment = UITextAlignment.Left; text1.TextColor = UIColor.Black; text1.Frame = new CGRect(10, 35, 320, 20); text1.Font = UIFont.FromName("Helvetica", 14f); slider = new UISlider(); slider.Frame = new CGRect(5, 60, 320, 20); slider.MinValue = 0f; slider.MaxValue = 360f; slider.Value = 40f; slider.ValueChanged += (object sender, EventArgs e) => { scale1.StartAngle = slider.Value; }; UILabel text2 = new UILabel(); text2.Text = "SweepAngle"; text2.TextAlignment = UITextAlignment.Left; text2.TextColor = UIColor.Black; text2.Frame = new CGRect(10, 85, 320, 20); text2.Font = UIFont.FromName("Helvetica", 14f); UISlider slider1 = new UISlider(); slider1.Frame = new CGRect(5, 110, 320, 20); slider1.MinValue = 0f; slider1.MaxValue = 360f; slider1.Value = 320f; slider1.ValueChanged += (object sender, EventArgs e) => { scale1.SweepAngle = slider1.Value; }; UILabel text3 = new UILabel(); text3.Text = "Scale2"; text3.TextAlignment = UITextAlignment.Left; text3.TextColor = UIColor.Black; text3.Frame = new CGRect(10, 135, 320, 20); text3.Font = UIFont.FromName("Helvetica", 14f); UILabel text4 = new UILabel(); text4.Text = "StartAngle"; text4.TextAlignment = UITextAlignment.Left; text4.TextColor = UIColor.Black; text4.Frame = new CGRect(10, 160, 320, 20); text4.Font = UIFont.FromName("Helvetica", 14f); UISlider slider2 = new UISlider(); slider2.Frame = new CGRect(5, 185, 320, 20); slider2.MinValue = 0f; slider2.MaxValue = 360f; slider2.Value = 40f; slider2.ValueChanged += (object sender, EventArgs e) => { scale2.StartAngle = slider2.Value; }; UILabel text5 = new UILabel(); text5.Text = "SweepAngle"; text5.TextAlignment = UITextAlignment.Left; text5.TextColor = UIColor.Black; text5.Frame = new CGRect(10, 210, 320, 20); text5.Font = UIFont.FromName("Helvetica", 14f); UISlider slider3 = new UISlider(); slider3.Frame = new CGRect(5, 235, 320, 20); slider3.MinValue = 0f; slider3.MaxValue = 360f; slider3.Value = 320f; slider3.ValueChanged += (object sender, EventArgs e) => { scale2.SweepAngle = slider3.Value; }; this.option.AddSubview(text); this.option.AddSubview(text1); this.option.AddSubview(slider); this.option.AddSubview(text2); this.option.AddSubview(slider1); this.option.AddSubview(text3); this.option.AddSubview(text4); this.option.AddSubview(slider2); this.option.AddSubview(text5); this.option.AddSubview(slider3); } protected override void Dispose(bool disposing) { //gauge.Scales[0].Pointers.Clear(); //gauge.Scales[1].Pointers.Clear(); //gauge.Scales.Clear(); //gauge.Dispose(); base.Dispose(disposing); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/StripLines.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using nfloat = System.Single; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class StripLines : SampleView { public StripLines () { SFChart chart = new SFChart (); chart.Title.Text = new NSString ("Weather Report"); SFCategoryAxis primaryAxis = new SFCategoryAxis (); primaryAxis.LabelPlacement = SFChartLabelPlacement.BetweenTicks; chart.PrimaryAxis = primaryAxis; chart.PrimaryAxis.Title.Text = new NSString ("Months"); SFNumericalAxis numeric = new SFNumericalAxis (); numeric.Minimum = NSObject.FromObject(10); numeric.Maximum = NSObject.FromObject(40); numeric.Title.Text = new NSString ("Temperature in Celsius"); SFChartNumericalStripLine strip1 = new SFChartNumericalStripLine (); strip1.Start = 10; strip1.Width = 10; strip1.Text = new NSString("Low Temperature"); strip1.BackgroundColor = UIColor.FromRGBA((nfloat)249/255,(nfloat)212/255,(nfloat)35/255,(nfloat)1.0); numeric.AddStripLine (strip1); SFChartNumericalStripLine strip2 = new SFChartNumericalStripLine (); strip2.Start = 20; strip2.Width = 10; strip2.Text = new NSString("Average Temperature"); strip2.BackgroundColor = UIColor.FromRGBA((nfloat)252/255,(nfloat)144/255,(nfloat)42/255,(nfloat)1.0); numeric.AddStripLine (strip2); SFChartNumericalStripLine strip3 = new SFChartNumericalStripLine (); strip3.Start = 30; strip3.Width = 10; strip3.Text = new NSString("High Temperature"); strip3.BackgroundColor = UIColor.FromRGBA((nfloat)254/255,(nfloat)81/255,(nfloat)47/255,(nfloat)1.0); numeric.AddStripLine (strip3); chart.SecondaryAxis = numeric; ChartViewModel dataModel = new ChartViewModel (); SFLineSeries series = new SFLineSeries(); series.LineWidth = 2; series.Color = UIColor.White; series.ItemsSource = dataModel.StripLineData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.DataMarker.ShowLabel = false; series.DataMarker.ShowMarker = true; series.DataMarker.MarkerWidth = 10; series.DataMarker.MarkerHeight = 10; series.DataMarker.MarkerColor = UIColor.FromRGBA((nfloat)102/255, (nfloat)102/255, (nfloat)102/255, (nfloat)1.0); series.DataMarker.MarkerBorderColor = UIColor.FromRGBA((nfloat)255, (nfloat)255, (nfloat)255, (nfloat)1.0); ; series.DataMarker.MarkerBorderWidth = 4; chart.Series.Add(series); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } }<file_sep>/Forms/XlsIO/XlsIO.Droid/SaveAndroid.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="SaveAndroid.cs" company=" Syncfusion Inc."> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> #endregion using System; using System.IO; using System.Threading.Tasks; using Android.Content; using AndroidX.Core.Content; using Java.IO; using SampleBrowser.Core; using SampleBrowser.XlsIO; using SampleBrowser.XlsIO.Droid; using Xamarin.Forms; [assembly: Dependency(typeof(SaveAndroid))] namespace SampleBrowser.XlsIO.Droid { /// <summary> /// This method used to save the files. /// </summary> internal class SaveAndroid : ISave { /// <summary> /// Save method used to save the files using <see cref="MemoryStream"/> class. /// </summary> /// <param name="fileName">Name of the output file.</param> /// <param name="contentType">Content type of the output file.</param> /// <param name="stream">The file in the form of <see cref="MemoryStream"/> class.</param> public void Save(string fileName, string contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.App.Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath; } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } finally { if (contentType != "application/html") { stream.Dispose(); } } if (file.Exists() && contentType != "application/html") { Android.Net.Uri path = Android.Net.Uri.FromFile(file); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); path = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file); if (mimeType == "application/json") mimeType = "text/html"; intent.SetDataAndType(path, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); Android.App.Application.Context.StartActivity(intent); } } } }<file_sep>/Forms/Backdrop/Backdrop/Samples/Backdrop/BackdropViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Backdrop; using Syncfusion.XForms.Buttons; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.Reflection; using System; using System.Diagnostics.CodeAnalysis; namespace SampleBrowser.SfBackdrop { [Preserve(AllMembers = true)] public class BackdropViewModel : INotifyPropertyChanged { #region fields private ObservableCollection<BackdropModel> frontViewData; private double leftcornerRadius; private double rightcornerRadius; private double currentRadius; private bool isBackLayerRevealed; public event PropertyChangedEventHandler PropertyChanged; #endregion #region public properties public ObservableCollection<BackdropModel> FrontViewData { get { return frontViewData; } set { frontViewData = value; RaisePropetyChanged("FrontViewData"); } } public double LeftCornerRadius { get { return leftcornerRadius; } set { leftcornerRadius = value; RaisePropetyChanged("LeftCornerRadius"); if (value > 0) { this.currentRadius = value; } } } public double RightCornerRadius { get { return rightcornerRadius; } set { rightcornerRadius = value; RaisePropetyChanged("RightCornerRadius"); if (value > 0) { this.currentRadius = value; } } } public bool IsBackLayerRevealed { get { return isBackLayerRevealed; } set { isBackLayerRevealed = value; RaisePropetyChanged("IsBackLayerRevealed"); } } public ICommand EdgeShapeCommand { get; set; } public ICommand CornerTyeCommand { get; set; } public ICommand ExpandModeCommand { get; set; } public ICommand CornerRadiusCommand { get; set; } #endregion #region Constructor public BackdropViewModel() { FrontViewData = new ObservableCollection<BackdropModel>() { new BackdropModel(){ ImageSource = "Brownie.jpg"}, new BackdropModel(){ ImageSource = "Cupcake.jpg" }, new BackdropModel(){ ImageSource = "Cake.jpg" }, new BackdropModel(){ ImageSource = "Icecake.jpg"}, new BackdropModel(){ ImageSource = "Cookie.jpg"}, new BackdropModel(){ ImageSource = "Biscuits.jpg"}, }; var cornerRadius = 16; LeftCornerRadius = cornerRadius; RightCornerRadius = cornerRadius; EdgeShapeCommand = new Command(EdgeShapeChanged); CornerTyeCommand = new Command(CornerTyeChanged); ExpandModeCommand = new Command(ExpandModeChanged); CornerRadiusCommand = new Command(CornerRadiusChanged); } #endregion #region private methods private void RaisePropetyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } private void EdgeShapeChanged(object attachedObject) { var list = attachedObject as List<object>; Syncfusion.XForms.Buttons.SelectionChangedEventArgs selectionChangedEventArgs = list[0] as Syncfusion.XForms.Buttons.SelectionChangedEventArgs; var frontLayer = (list[1] as SfBackdropPage)?.FrontLayer; if (selectionChangedEventArgs == null || frontLayer == null) { return; } var selectedIndex = selectionChangedEventArgs.Index; if (selectedIndex > -1) { frontLayer.EdgeShape = selectedIndex == 0 ? EdgeShape.Curve : EdgeShape.Flat; } } private void CornerTyeChanged(object attachedObject) { var list = attachedObject as List<object>; Syncfusion.XForms.Buttons.SelectionChangedEventArgs selectionChangedEventArgs = list[0] as Syncfusion.XForms.Buttons.SelectionChangedEventArgs; if (selectionChangedEventArgs == null) { return; } var selectedIndex = selectionChangedEventArgs.Index; switch (selectedIndex) { case 0: this.LeftCornerRadius = this.currentRadius; this.RightCornerRadius = this.currentRadius; break; case 1: this.LeftCornerRadius = this.currentRadius; this.RightCornerRadius = 0; break; case 2: this.LeftCornerRadius = 0; this.RightCornerRadius = this.currentRadius; break; } } private void ExpandModeChanged(object attachedObject) { var list = attachedObject as List<object>; Syncfusion.XForms.Buttons.SelectionChangedEventArgs selectionChangedEventArgs = list[0] as Syncfusion.XForms.Buttons.SelectionChangedEventArgs; var backdrop = list[1] as SfBackdropPage; if (selectionChangedEventArgs == null || backdrop == null) { return; } var selectedIndex = selectionChangedEventArgs.Index; switch (selectedIndex) { case 0: backdrop.BackLayerRevealOption = RevealOption.Auto; break; case 1: backdrop.BackLayerRevealOption = RevealOption.Fill; break; } } private void CornerRadiusChanged(object attachedObject) { ValueChangedEventArgs eventArgs = attachedObject as ValueChangedEventArgs; if (eventArgs == null) { return; } var value = eventArgs.NewValue; if (this.LeftCornerRadius == 0 && this.RightCornerRadius > 0) { this.RightCornerRadius = value; } else if (this.LeftCornerRadius > 0 && this.RightCornerRadius == 0) { this.LeftCornerRadius = value; } else { this.LeftCornerRadius = value; this.RightCornerRadius = value; } } #endregion } }<file_sep>/Android/SampleBrowser/Samples/XlsIO/ImportXMLPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public partial class ImportXMLPage : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to import XML data into Excel workbook."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Excel"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook //A new workbook is created.[Equivalent to creating a new workbook in MS Excel] //The new workbook will have 1 worksheets IWorkbook workbook = application.Workbooks.Create(1); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; Assembly assembly = Assembly.GetExecutingAssembly (); Stream fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.customers.xml"); // Import the XML contents to worksheet XlsIOExtensions exten = new XlsIOExtensions(); exten.ImportXML(fileStream, sheet, 1, 1, true); // Apply style for header IStyle headerStyle = sheet[1, 1, 1, sheet.UsedRange.LastColumn].CellStyle; headerStyle.Font.Bold = true; headerStyle.Font.Color = ExcelKnownColors.Brown; headerStyle.Font.Size = 10; // Resize columns sheet.Columns[0].ColumnWidth = 11; sheet.Columns[1].ColumnWidth = 30.5; sheet.Columns[2].ColumnWidth = 20; sheet.Columns[3].ColumnWidth = 25.6; sheet.Columns[6].ColumnWidth = 10.5; sheet.Columns[4].ColumnWidth = 40; sheet.Columns[5].ColumnWidth = 25.5; sheet.Columns[7].ColumnWidth = 9.6; sheet.Columns[8].ColumnWidth = 15; sheet.Columns[9].ColumnWidth = 15; #endregion #region Saving workbook and disposing objects workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("ImportXML.xlsx", "application/msexcel", stream, m_context); } #endregion } } } <file_sep>/Android/SampleBrowser/Samples/DataForm/ContactForm.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.Android.DataForm; using Android.Graphics; using Android.Views.InputMethods; namespace SampleBrowser { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] public class ContactForm : SamplePage { private bool refreshLayout = false; private RelativeLayout linearLayout; private ListView listView; private SfDataForm dataForm; private bool isReadOnly = true; private TextView editButton; private ImageButton addButton; private TextView contactLabel; private Button refreshButton; private View dataFormView; private Context context; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "contactList")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "_contactList", Justification = "Used Locals")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "titleRelativeLayout", Justification = "Used Locals")] public override View GetSampleContent(Context context) { this.context = context; //// Get our button from the layout resource, //// and attach an event to it var view = LayoutInflater.From(context).Inflate(Resource.Layout.ContactsLayout, null); linearLayout = view.FindViewById<RelativeLayout>(Resource.Id.linearLayout); listView = linearLayout.FindViewById<ListView>(Resource.Id.listView); var contactList = new ListViewGroupingViewModel().ContactsInfo; listView.ChoiceMode = ChoiceMode.Single; listView.Divider = null; listView.DividerHeight = 0; listView.ItemClick += OnItemSelect; listView.Adapter = new ListViewCustomAdapter(context as Activity); dataFormView = LayoutInflater.From(context).Inflate(Resource.Layout.DataFormLayout, null); var titleRelativeLayout = dataFormView.FindViewById<RelativeLayout>(Resource.Id.titleRelativeLayout); var backButton = dataFormView.FindViewById<TextView>(Resource.Id.back); backButton.SetBackgroundColor(Color.Transparent); backButton.Click += OnBack; contactLabel = dataFormView.FindViewById<TextView>(Resource.Id.label); editButton = dataFormView.FindViewById<TextView>(Resource.Id.right); editButton.SetBackgroundColor(Color.Transparent); editButton.Click += OnEditAndDone; // SfDataForm settings dataForm = new SfDataForm(context); dataForm.ColumnCount = 2; dataForm.LayoutManager = new DataFormLayoutManagerExt(dataForm); dataForm.AutoGeneratingDataFormItem += DataForm_AutoGeneratingDataFormItem; var dataFormLinearLayout = dataFormView.FindViewById<LinearLayout>(Resource.Id.dataFormLinearLayout); dataFormLinearLayout.AddView(dataForm); refreshButton = dataFormView.FindViewById<Button>(Resource.Id.moreFields); refreshButton.Text = "More Fields"; refreshButton.SetBackgroundColor(Color.Transparent); refreshButton.SetTextColor(Color.Blue); refreshButton.Click += RefreshButton_Click; addButton = linearLayout.FindViewById<ImageButton>(Resource.Id.add); addButton.SetImageResource(Resource.Drawable.AddContact); addButton.SetBackgroundColor(Color.Transparent); addButton.Click += OnAdd; linearLayout.AddView(dataFormView, WindowManagerLayoutParams.MatchParent, WindowManagerLayoutParams.MatchParent); dataFormView.Visibility = ViewStates.Gone; return linearLayout; } /// <summary> /// Raised to refresh the layout to show the fields that were canceled. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RefreshButton_Click(object sender, EventArgs e) { refreshLayout = true; HideKeyboard(context as Activity); dataForm.RefreshLayout(); refreshButton.Visibility = ViewStates.Gone; } /// <summary> /// Hide key board when refresh layout. /// </summary> /// <param name="activity"></param> public static void HideKeyboard(Activity activity) { InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); ////Find the currently focused view, so we can grab the correct window token from it. View view = activity.CurrentFocus; ////If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = new View(activity); } imm.HideSoftInputFromWindow(view.WindowToken, 0); } /// <summary> /// Raised to add the item to list view through data form if the form is valid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnAdd(object sender, EventArgs e) { contactLabel.Text = "Add Contact"; refreshButton.Visibility = ViewStates.Visible; dataFormView.Visibility = ViewStates.Visible; // Setting data object for DataForm and update the read only property. var item = new ContactsInfo(); if (item.ContactImage == 0) { item.ContactImage = Resource.Drawable.ContactName; } refreshLayout = false; dataForm.DataObject = item; isReadOnly = true; UpdateDataFormView(false); linearLayout.GetChildAt(0).Visibility = ViewStates.Gone; linearLayout.GetChildAt(1).Visibility = ViewStates.Gone; } /// <summary> /// Raised to update the data form view which will update the read only and edit bar caption. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnEditAndDone(object sender, EventArgs e) { UpdateDataFormView(); } /// <summary> /// Raise to invisible the data form layout. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnBack(object sender, EventArgs e) { contactLabel.Text = "Edit Contact"; dataFormView.Visibility = ViewStates.Gone; listView.Visibility = ViewStates.Visible; addButton.Visibility = ViewStates.Visible; } /// <summary> /// Updates read only property and /// </summary> private void UpdateDataFormView(bool commit = true) { var item = dataForm.DataObject as ContactsInfo; var index = (listView.Adapter as ListViewCustomAdapter).ContactList.IndexOf(item); if (isReadOnly) { isReadOnly = false; dataForm.IsReadOnly = false; editButton.Text = "Done"; } else { isReadOnly = true; if (commit) { var isValid = dataForm.Validate(); if (!isValid) { return; } dataForm.Commit(); } dataForm.IsReadOnly = true; if (index != -1) { editButton.Text = "Edit"; (listView.Adapter as ListViewCustomAdapter).ContactList[index] = item; (listView.Adapter as ListViewCustomAdapter).NotifyDataSetChanged(); } else { dataForm.DataObject = item; (listView.Adapter as ListViewCustomAdapter).ContactList.Add(item); HideKeyboard(this.context as Activity); contactLabel.Text = "Edit Contact"; dataFormView.Visibility = ViewStates.Gone; listView.Visibility = ViewStates.Visible; addButton.Visibility = ViewStates.Visible; } } } /// <summary> /// Raised to set read only property and cancel the some properties. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DataForm_AutoGeneratingDataFormItem(object sender, AutoGeneratingDataFormItemEventArgs e) { if (e.DataFormItem != null) { if (!refreshLayout) { if (e.DataFormItem.Name.Equals("MiddleName") || e.DataFormItem.Name.Equals("LastName")) { e.Cancel = true; } } if (e.DataFormItem.Name.Equals("ContactNumber")) { (e.DataFormItem as DataFormTextItem).InputType = Android.Text.InputTypes.ClassNumber; } else if (e.DataFormItem.Name.Equals("Email")) { (e.DataFormItem as DataFormTextItem).InputType = Android.Text.InputTypes.TextVariationEmailAddress; } } if (e.DataFormGroupItem != null) { e.DataFormGroupItem.AllowExpandCollapse = false; } } /// <summary> /// Event raised to show the data form with selected item. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnItemSelect(object sender, AdapterView.ItemClickEventArgs e) { refreshLayout = false; dataFormView.Visibility = ViewStates.Visible; refreshButton.Visibility = ViewStates.Visible; var item = (listView.Adapter as ListViewCustomAdapter).ContactList[e.Position]; if (item == dataForm.DataObject) { dataForm.DataObject = null; } dataForm.DataObject = item; isReadOnly = false; UpdateDataFormView(false); linearLayout.GetChildAt(0).Visibility = ViewStates.Gone; linearLayout.GetChildAt(1).Visibility = ViewStates.Gone; } public override void Destroy() { listView.Dispose(); listView = null; dataForm.AutoGeneratingDataFormItem -= DataForm_AutoGeneratingDataFormItem; dataForm.Dispose(); dataForm = null; } } }<file_sep>/Forms/MaskedEdit/readme.md The masked text box is an advanced version of the entry control that restricts input to certain types of characters, texts, and numbers using a masked pattern. This control is used to create a template for providing information such as telephone numbers, IP addresses, product IDs, and so on. | Sample | Description | | ------ | ----------- | | [Money transfer](MaskedEdit/Samples/MaskedEdit) |This sample demonstrates different masked values input to restrict users to provide only valid payment transaction details in the Xamarin Forms application. Users can change the culture, prompt character, hide prompt on leave, and validation mode properties in the option page.|<file_sep>/Forms/Chat/Chat/Samples/ViewModel/GettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GettingStartedViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfChat { using Syncfusion.XForms.Chat; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for GettingStarted sample. /// </summary> public class GettingStartedViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// Backing field for the IsBadgeViewVisibleProperty. /// </summary> private bool isBadgeViewVisible = false; /// <summary> /// Chat conversation message collection. /// </summary> private ObservableCollection<object> messages; /// <summary> /// Author assinging temporary array. /// </summary> private int[] authorArray; /// <summary> /// current user of chat. /// </summary> private Author currentUser; /// <summary> /// message conversation set. /// </summary> private List<string> messageList; /// <summary> /// Indicates the typing indicator visibility. /// </summary> private bool showTypingIndicator; /// <summary> /// Chat typing indicator. /// </summary> private ChatTypingIndicator typingIndicator; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="GettingStartedViewModel"/> class. /// </summary> public GettingStartedViewModel() { this.Messages = new ObservableCollection<object>(); this.TypingIndicator = new ChatTypingIndicator(); this.InitializeAuthors(); this.InitializeMessageList(); this.authorArray = new int[] { 0, 1, 2, 2, 0, 3, 4, 0, 3, 0, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 5, 1 }; this.MapAuthorToMessage(); this.CurrentUser = this.AuthorsCollection[0]; this.InitConvo(); } #endregion #region Public Properties /// <summary> /// Gets or sets the Chat typing indicator value. /// </summary> public ChatTypingIndicator TypingIndicator { get { return this.typingIndicator; } private set { this.typingIndicator = value; RaisePropertyChanged("TypingIndicator"); } } /// <summary> /// Gets or sets the value indicating whether the typing indicator is visible or not. /// </summary> public bool ShowTypingIndicator { get { return this.showTypingIndicator; } private set { this.showTypingIndicator = value; RaisePropertyChanged("ShowTypingIndicator"); } } /// <summary> /// Gets or sets a value indicating whether the badge view is visible or not. /// </summary> public bool IsBadgeViewVisible { get { return this.isBadgeViewVisible; } set { this.isBadgeViewVisible = value; RaisePropertyChanged("IsBadgeViewVisible"); } } /// <summary> /// Gets or sets the group message conversation. /// </summary> public ObservableCollection<object> Messages { get { return this.messages; } set { this.messages = value; RaisePropertyChanged("Messages"); } } /// <summary> /// Gets or sets the current author. /// </summary> public Author CurrentUser { get { return this.currentUser; } set { this.currentUser = value; RaisePropertyChanged("CurrentUser"); } } #endregion #region Internal Properties /// <summary> /// Gets a sets the value indicates GettingStarted view managed resource are disposed or not. /// </summary> internal bool IsDisposed { get; set; } /// <summary> /// Chat conversation authors collection. /// </summary> internal ObservableCollection<Author> AuthorsCollection { get; set; } /// <summary> /// Dictionary that holds the message and its respective author. /// </summary> internal Dictionary<int, Author> AuthorMessageDataBase { get; set; } #endregion #region Property Changed /// <summary> /// Property changed handler. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Occurs when property is changed. /// </summary> /// <param name="propName">changed property name</param> public void RaisePropertyChanged(string propName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } #endregion #region Private Methods #region Init /// <summary> /// Initializes the message collection for group conversation. /// </summary> private void InitializeMessageList() { this.messageList = new List<string> { "Hi guys, good morning! I'm very delighted to share with you the news that our team is going to launch a new mobile application.", "Oh! That's great.", "That is good news.", "Are we going to develop the app natively or hybrid?", "We should develop this app in Xamarin, since it provides native experience and performance.", "I haven't heard of Xamarin. What's Xamarin?", "Xamarin.Forms is a new library that lets you build native UIs for iOS, Android, and Windows Phone from one shared C# codebase.", "You can check out this link to get started with Xamarin.", "That's great! I will look into it.", "Yes, please do. It saves a lot of development time from what I've heard. We may have to dig deeper to know more.", "What kind of application is it and when are we going to launch?", "A kind of Emergency Broadcast App.", "Can you please elaborate?", "The app will help users broadcast emergency messages to friends and family from their phones with location data during emergency situations.", "Can we extend this idea and broadcast the data all the time? It will be better if we provide options to broadcast to selected people based on timing or profiles.", "That's a great idea. We can consider that in our requirement.", "Do we have a layout design for the new app?", "We will have a dedicated design engineer to design the layout once the requirement is finalized.", "Is this app going to be supported in wearable technology, too?", "No, not yet. We are going to develop the mobile version first. Support for wearable watches can be considered for the next version, though.", "Are we going to recruit a new team? Otherwise, will we migrate our existing engineers?", "Since our current project is going to be complete by the end of next month, we can move the required resources from there to the development of this app. I will all the details by the end of next week.", "Wow! That's great.", "Cool. Cheers", }; } /// <summary> /// Initializes the author collection. /// </summary> private void InitializeAuthors() { this.AuthorsCollection = new ObservableCollection<Author>(); this.AuthorsCollection.Add(new Author() { Name = "Nancy", Avatar = "People_Circle16.png" }); this.AuthorsCollection.Add(new Author() { Name = "Andrea", Avatar = "People_Circle2.png" }); this.AuthorsCollection.Add(new Author() { Name = "Harrison", Avatar = "People_Circle14.png" }); this.AuthorsCollection.Add(new Author() { Name = "Margaret", Avatar = "People_Circle7.png" }); this.AuthorsCollection.Add(new Author() { Name = "Steven", Avatar = "People_Circle5.png" }); this.AuthorsCollection.Add(new Author() { Name = "Michale", Avatar = "People_Circle23.png" }); } /// <summary> /// Initializes the conversation and adds messages. /// </summary> private async void InitConvo() { if (this.IsDisposed) { return; } this.Messages.Add(this.CreateMessage(this.messageList[0], this.AuthorMessageDataBase[0])); for (int i = 1; i < this.messageList.Count; i++) { AuthorStartedTyping(this.AuthorMessageDataBase[i]); if (AuthorMessageDataBase[i] == AuthorsCollection[0]) { await Task.Delay(3000).ConfigureAwait(true); } else { await Task.Delay(2000).ConfigureAwait(true); } if (this.IsDisposed) { return; } this.ShowTypingIndicator = false; this.Messages.Add(this.CreateMessage(this.messageList[i], this.AuthorMessageDataBase[i])); await Task.Delay(1000).ConfigureAwait(true); if (this.IsDisposed) { return; } } await Task.Delay(1000).ConfigureAwait(true); InitConvo(); } /// <summary> /// Initializes which message belongs to which author. /// </summary> private void MapAuthorToMessage() { this.AuthorMessageDataBase = new Dictionary<int, Author>(); for (int i = 0; i < this.messageList.Count; i++) { this.AuthorMessageDataBase.Add(i, this.AuthorsCollection[this.authorArray[i]]); } } #endregion /// <summary> /// Creating message to based on the given string. /// </summary> /// <param name="text">The text of the new message.</param> /// <param name="auth">The author of the new message.</param> /// <returns>The <see cref="TextMessage"/> created with the given string.</returns> private TextMessage CreateMessage(string text, Author auth) { if (text.Contains("get started with Xamarin")) { return new HyperlinkMessage() { DateTime = DateTime.Now, Author = auth, Text = text, Url = "https://docs.microsoft.com/en-us/xamarin/get-started/" }; } return new TextMessage() { DateTime = DateTime.Now, Author = auth, Text = text, }; } /// <summary> /// Updates the typing indicator based on the current typing author. /// </summary> private void AuthorStartedTyping(Author auth) { if (auth != this.CurrentUser) { this.TypingIndicator.Authors.Clear(); if (auth.Name == "Margaret") { this.TypingIndicator.Authors.Add(auth); this.TypingIndicator.Authors.Add(this.AuthorsCollection[4]); this.TypingIndicator.Text = auth.Name + " and " + this.AuthorsCollection[4].Name + " are typing ..."; } else { this.TypingIndicator.Authors.Add(auth); this.TypingIndicator.Text = auth.Name + " is typing ..."; } this.TypingIndicator.AvatarViewType = Syncfusion.XForms.Chat.AvatarViewType.Image; this.ShowTypingIndicator = true; } } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/NumericAxis/NumericAxisViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class NumericAxisViewModel { public ObservableCollection<ChartDataModel> NumericData { get; set; } public ObservableCollection<ChartDataModel> NumericData1 { get; set; } public NumericAxisViewModel() { NumericData = new ObservableCollection<ChartDataModel> { new ChartDataModel(16, 2 ), new ChartDataModel(17, 14), new ChartDataModel(18, 7 ), new ChartDataModel(19, 7 ), new ChartDataModel(20, 10), }; NumericData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(16, 7 ), new ChartDataModel(17, 7 ), new ChartDataModel(18, 11), new ChartDataModel(19, 8 ), new ChartDataModel(20, 24), }; } } } <file_sep>/Forms/ListView/ListView/Samples/Paging/Model/PagingProduct.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class PagingProduct : INotifyPropertyChanged { public string Name { get; set; } public string Ratings { get; set; } public string Image { get; set; } public string Weight { get; set; } public double Price { get; set; } public string Offer { get; set; } public double ReviewValue { get; set; } private void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/ViewModel/GettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GettingStartedViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.ComponentModel; using System.Reflection; using SampleBrowser.Core; using Syncfusion.XForms.PopupLayout; using Xamarin.Forms; /// <summary> /// A ViewModel for GettingStarted sample. /// </summary> public class GettingStartedViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// Backing filed for SmallFontSwitch property. /// </summary> private bool smallFontSwitch; /// <summary> /// Backing filed for NormalFontSwitch property. /// </summary> private bool normalFontSwitch; /// <summary> /// Backing filed for LargeFontSwitch property. /// </summary> private bool largeFontSwitch; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="GettingStartedViewModel" /> class. /// </summary> public GettingStartedViewModel() { this.OpenAlertDialog = new Command<SfPopupLayout>(this.DisplayAlert); this.OpenAlertWithTitleDialog = new Command<SfPopupLayout>(this.DisplayAlertWithTitle); this.OpenSimpleDialog = new Command<SfPopupLayout>(this.DisplaySimpleDialog); this.OpenConfirmationDialog = new Command<SfPopupLayout>(this.DisplayConfirmationDialog); this.OpenModalDialog = new Command<SfPopupLayout>(this.DisplayModalDialog); this.OpenRelativeDialog = new Command<SfPopupLayout>(this.DisplayDialogRelativeToView); this.OpenFullScreenDialog = new Command<SfPopupLayout>(this.DisplayFullScreenDialog); this.OpenBlurDialog = new Command<SfPopupLayout>(this.DisplayBlurBackgroundDialog); this.SetBindingImageSource(); } #endregion #region Events /// <summary> /// Event that triggers when the property is changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Properties /// <summary> /// Gets or sets the command for opening the AlertDialog popup. /// </summary> public Command<SfPopupLayout> OpenAlertDialog { get; set; } /// <summary> /// Gets or sets the command for opening the AlertDialog popup with title. /// </summary> public Command<SfPopupLayout> OpenAlertWithTitleDialog { get; set; } /// <summary> /// Gets or sets the command for opening the simple dialog. /// </summary> public Command<SfPopupLayout> OpenSimpleDialog { get; set; } /// <summary> /// Gets or sets the command for opening the confirmation dialog. /// </summary> public Command<SfPopupLayout> OpenConfirmationDialog { get; set; } /// <summary> /// Gets or sets the command for opening the Modal window popup. /// </summary> public Command<SfPopupLayout> OpenModalDialog { get; set; } /// <summary> /// Gets or sets the command for opening the popup relative to a view. /// </summary> public Command<SfPopupLayout> OpenRelativeDialog { get; set; } /// <summary> /// Gets or sets the command for opening the full screen popup. /// </summary> public Command<SfPopupLayout> OpenFullScreenDialog { get; set; } /// <summary> /// Gets or sets the command for opening the blur background popup. /// </summary> public Command<SfPopupLayout> OpenBlurDialog { get; set; } /// <summary> /// Gets or sets a value indicating whether the SmallFont is enabled. /// </summary> public bool SmallFontSwitch { get { return this.smallFontSwitch; } set { this.smallFontSwitch = value; if (value) { this.SelectSmallFontSize(); } this.RaisePropertyChanged("SmallFontSwitch"); } } /// <summary> /// Gets or sets a value indicating whether the NormalFont is enabled. /// </summary> public bool NormalFontSwitch { get { return this.normalFontSwitch; } set { this.normalFontSwitch = value; if (value) { this.SelectNormaFontSize(); } this.RaisePropertyChanged("NormalFontSwitch"); } } /// <summary> /// Gets or sets a value indicating whether the LargeFont is enabled. /// </summary> public bool LargeFontSwitch { get { return this.largeFontSwitch; } set { this.largeFontSwitch = value; if (value) { this.SelectLargeFontSize(); } this.RaisePropertyChanged("LargeFontSwitch"); } } #endregion #region Private Methods /// <summary> /// Displays the popup as the alert. /// </summary> /// <param name="popupLayout">Popup to be displayed.</param> private void DisplayAlert(SfPopupLayout popupLayout) { popupLayout.OverlayMode = OverlayMode.Transparent; popupLayout.Show(); } /// <summary> /// Displays the popup as the dialog with title. /// </summary> /// <param name="popupLayout">Popup to be displayed.</param> private void DisplayAlertWithTitle(SfPopupLayout popupLayout) { popupLayout.Show(); } /// <summary> /// Displays the popup as the simple dialog. /// </summary> /// <param name="popupLayout">Popup to be displayed.</param> private void DisplaySimpleDialog(SfPopupLayout popupLayout) { popupLayout.Show(); } /// <summary> /// Displays the popup as the confirmation dialog. /// </summary> /// <param name="popupLayout">Popup to be displayed.</param> private void DisplayConfirmationDialog(SfPopupLayout popupLayout) { popupLayout.Show(); } /// <summary> /// Displays the popup as the modal window. /// </summary> /// <param name="popupLayout">Popup to be displayed.</param> private void DisplayModalDialog(SfPopupLayout popupLayout) { popupLayout.Show(); } /// <summary> /// Displays the dialog relative to the view. /// </summary> /// <param name="popupLayout">Popup to be displayed.</param> private void DisplayDialogRelativeToView(SfPopupLayout popupLayout) { popupLayout.Show(); } /// <summary> /// Displays the full screen popup. /// </summary> /// <param name="popupLayout">Popup to be displayed.</param> private void DisplayFullScreenDialog(SfPopupLayout popupLayout) { popupLayout.PopupView.IsFullScreen = true; popupLayout.Show(true); } /// <summary> /// Displays the blur background popup. /// </summary> /// <param name="popupLayout">Popup to be displayed.</param> private void DisplayBlurBackgroundDialog(SfPopupLayout popupLayout) { popupLayout.OverlayMode = OverlayMode.Blur; popupLayout.Show(); } /// <summary> /// Sets the ImageSource for the Images. /// </summary> private void SetBindingImageSource() { } /// <summary> /// Selects the small font size. /// </summary> private void SelectSmallFontSize() { this.NormalFontSwitch = false; this.LargeFontSwitch = false; } /// <summary> /// Selects the normal font size. /// </summary> private void SelectNormaFontSize() { this.LargeFontSwitch = false; this.SmallFontSwitch = false; } /// <summary> /// Selects the large font size. /// </summary> private void SelectLargeFontSize() { this.SmallFontSwitch = false; this.NormalFontSwitch = false; } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Forms/PdfViewer/PdfViewer/Samples/SinglePageView/SinglePageView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfPdfViewer.XForms; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.IO; namespace SampleBrowser.SfPdfViewer { [Preserve(AllMembers = true)] public partial class SinglePageView : SampleView { string currentDocument = "Xamarin Forms Succinctly"; public SinglePageView() { InitializeComponent(); pdfViewerControl.DocumentSaveInitiated += PdfViewerControl_DocumentSaved; (BindingContext as GettingStartedViewModel).DocumentName = currentDocument; } public override void OnAppearing() { string filePath = string.Empty; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif (BindingContext as GettingStartedViewModel).PageByPageDocumentStream = (typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath+"Assets." + currentDocument + ".pdf")); } public override void OnDisappearing() { if (Device.RuntimePlatform == Device.Android) { pdfViewerControl.Unload(); GC.Collect(); GC.WaitForPendingFinalizers(); } } private void PdfViewerControl_DocumentSaved(object sender, DocumentSaveInitiatedEventArgs args) { string filePath = DependencyService.Get<ISave>().Save(args.SaveStream as MemoryStream); string message = "The PDF has been saved to " + filePath; DependencyService.Get<IAlertView>().Show(message); } } } <file_sep>/iOS/SampleBrowser/CopyFilesFromCommon.sh #!/bin/sh # Define directories. ProjectPath=$(PWD) ESPath="${ProjectPath%/*}" mkdir $ProjectPath/Samples/DocIO/Templates mkdir $ProjectPath/Samples/PDFViewer/Assets mkdir $ProjectPath/Samples/PDF/Assets mkdir $ProjectPath/Samples/Presentation/Templates mkdir $ProjectPath/Samples/XlsIO/Template cp $ESPath/essentialstudio-common/Data/DocIO/BkmkDocumentPart_Template.docx $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Data/DocIO/Bookmark_Template.docx $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Data/DocIO/Excel_Template.xlsx $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Data/DocIO/Products.xml $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Data/DocIO/Employees.xml $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/DocIO/Letter Formatting.docx" $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/DocIO/ContentControlTemplate.docx" $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/DocIO/Doc to HTML.doc" $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/DocIO/WordtoPDF.docx" $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/DocIO/CreateEquation.docx" $ProjectPath/Samples/DocIO/Templates/ cp -R "$ESPath/essentialstudio-common/Data/DocIO/Doc to HTML.doc" $ProjectPath/Samples/DocIO/Templates/WordtoHTML.doc cp "$ESPath/essentialstudio-common/Data/DocIO/Template.doc" $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/DocIO/EmployeesReportDemo.doc" $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/DocIO/Template_Letter.doc" $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/DocIO/Security Settings.docx" $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/DocIO/TrackChangesTemplate.docx" $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Images/DocIO/AdventureCycle.jpg $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Images/DocIO/Mountain-200.jpg $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Images/DocIO/Mountain-300.jpg $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Images/DocIO/Northwind.png $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Images/DocIO/Road-550-W.jpg $ProjectPath/Samples/DocIO/Templates/ cp $ESPath/essentialstudio-common/Images/DocIO/SampleImage.png $ProjectPath/Samples/DocIO/Templates/ cp "$ESPath/essentialstudio-common/Data/PDF/GIS Succinctly.pdf" $ProjectPath/Samples/PDFViewer/Assets/ cp "$ESPath/essentialstudio-common/Data/PDF/F# Succinctly.pdf" $ProjectPath/Samples/PDFViewer/Assets/ cp "$ESPath/essentialstudio-common/Data/PDF/HTTP Succinctly.pdf" $ProjectPath/Samples/PDFViewer/Assets/ cp "$ESPath/essentialstudio-common/Data/PDF/Xamarin Forms Succinctly.pdf" $ProjectPath/Samples/PDFViewer/Assets/ cp "$ESPath/essentialstudio-common/Data/PDF/FormFillingDocument.pdf" $ProjectPath/Samples/PDFViewer/Assets/ cp "$ESPath/essentialstudio-common/Data/PDF/Encrypted Document.pdf" $ProjectPath/Samples/PDFViewer/Assets/ cp "$ESPath/essentialstudio-common/Data/PDF/JavaScript Succinctly.pdf" $ProjectPath/Samples/PDFViewer/Assets/ cp "$ESPath/essentialstudio-common/Data/PDF/Product Catalog.pdf" $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/PDF/SalesOrderDetail.pdf $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/PDF/Products.xml $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/PDF/Report.xml $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/PDF/InvoiceProductList.xml $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Images/PDF/Xamarin_bannerEdit.jpg $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Images/PDF/Xamarin_JPEG.jpg $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Images/PDF/Xamarin_PNG.png $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/PDF/PDF.pfx $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/PDF/SignedDocument.pdf $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/PDF/arial.ttf $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/PDF/arabic.txt $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/PDF/NotoSerif-Black.otf $ProjectPath/Samples/PDF/Assets/ cp "$ESPath/essentialstudio-common/Data/PDF/JavaScript Succinctly.pdf" $ProjectPath/Samples/PDF/Assets/ cp $ESPath/essentialstudio-common/Data/Presentation/HelloWorld.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/Images.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/NewCharts.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/Slides.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Images/Presentation/tablet.jpg $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/Products.xml $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/TableData.xml $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/SlideTableData.xml $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/ShapeWithAnimation.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/Animation.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/Transition.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/Template.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/HeaderFooter.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/OleTemplate.docx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/OlePicture.png $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/Presentation/EmbeddedOleObject.pptx $ProjectPath/Samples/Presentation/Templates/ cp $ESPath/essentialstudio-common/Data/XlsIO/FilterData.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/IconFilterData.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/FilterData_Color.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/ReplaceOptions.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/AdvancedFilterData.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/ChartData.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/CLRObjects.xml $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/customers.xml $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/ExcelToPDF.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/ExcelToJSON.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/ExportSales.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/ExportData.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/ExportData.xml $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/ExpenseReport.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/NorthwindTemplate.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/InvoiceTemplate.xlsx $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/bahnschrift.ttf $ProjectPath/Samples/XlsIO/Template/ cp $ESPath/essentialstudio-common/Data/XlsIO/georgiab.ttf $ProjectPath/Samples/XlsIO/Template/ <file_sep>/Forms/AutoComplete/readme.md The `SfAutoComplete` control filters and provides suggestion to choose from a list based on the typed text. Suggestions are provided as text appended to the original text or displayed in a drop-down list. The following samples are available for AutoComplete to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](AutoComplete/Samples/AutoComplete)|It demonstrates the basic functionalities of autocomplete, the filtering pattern, customizing dropdown height and providing delay to display the dropdown list.| |[Multiple Selection](AutoComplete/Samples/MultiSelect)| It demonstrates the feature of multi selection in AutoComplete. Here, multi selection in token representation has been demonstrated.| |[Tolerating Typos](AutoComplete/Samples/ToleratingTypos)|It shows the custom filtering ability to get suggestions even if the typed text has typographical errors.| |[Avoiding PopUp](AutoComplete/Samples/CustomSearchPage)| It populates the filtered in a list view instead of showing a drop down list.| |[Diacritics Sense](AutoComplete/Samples/Delimiter)|It demonstrates the ability to sense diacritics in languages and providing filtered list.| |[Perfomance](AutoComplete/Samples/Performance)|It demonstrates the performance of autocomplete with more than 10000 items.| |[Header Customization](AutoComplete/Samples/HeaderFooterSample)|It demonstrates the customization support provided for header and footer in drop down view.|<file_sep>/Forms/Chart/Chart/Samples/LiveUpdate/LiveUpdate.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class LiveUpdate : SampleView { LiveUpdateViewModel viewModel; public LiveUpdate() { InitializeComponent(); viewModel = Chart.BindingContext as LiveUpdateViewModel; viewModel.UpdateLiveData(); (Chart.SecondaryAxis as NumericalAxis).Maximum = 1.5; (Chart.SecondaryAxis as NumericalAxis).Minimum = -1.5; viewModel.StartTimer(); } public override void OnAppearing() { if (viewModel != null) viewModel.StartTimer(); base.OnAppearing(); } public override void OnDisappearing() { if (viewModel != null) viewModel.StopTimer(); } } }<file_sep>/Forms/DatePicker/DatePicker/ViewModel/DatePickerTaskObjectViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Pickers; using Syncfusion.XForms.PopupLayout; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; namespace SampleBrowser.SfDatePicker { #region DatePickerTaskObjectViewModel class /// <summary> /// DatePickerTaskObjectViewModel class /// </summary> public class DatePickerTaskObjectViewModel : INotifyPropertyChanged { #region Members /// <summary> /// Tasks collections /// </summary> private ObservableCollection<DatePickerTaskObject> tasks = new ObservableCollection<DatePickerTaskObject>(); /// <summary> /// SelectedItem value /// </summary> private DatePickerTaskObject selectedItem; /// <summary> /// To check whether the Picker is Open or not. /// </summary> private bool isPickerOpen; /// <summary> /// To check whether the xamarin picker is Open or not. /// </summary> private bool isOpen; /// <summary> /// isOkClicked /// </summary> private bool isOkClicked; /// <summary> /// selectedDate /// </summary> private DateTime selectedDate = DateTime.Now; /// <summary> /// Text value /// </summary> private string text; /// <summary> /// Default header text value /// </summary> private string headertext = "Date Picker"; /// <summary> /// show Column Header /// </summary> private bool showColumnHeader = true; /// <summary> /// showHeader /// </summary> private bool showHeader = true; /// <summary> /// selected DateFormat /// </summary> private DateFormat selectedDateFormat; /// <summary> /// Picker selected item field /// </summary> private string pickerSelectedItem; #endregion #region Properties /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public DateFormat SelectedDateFormat { get { return selectedDateFormat; } set { selectedDateFormat = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the picker selection /// </summary> public string PickerSelectedItem { get { return this.pickerSelectedItem; } set { this.pickerSelectedItem = value; this.PickerSelectionChanged(); this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public bool ShowColumnHeader { get { return showColumnHeader; } set { showColumnHeader = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public bool ShowHeader { get { return showHeader; } set { showHeader = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public ObservableCollection<DatePickerTaskObject> Tasks { get { return tasks; } set { tasks = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public ObservableCollection<string> DateFormatcollections { get { return dateFormatcollections; } set { dateFormatcollections = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public string DateFormat { get { return dateFormat; } set { dateFormat = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public DatePickerTaskObject SelectedItem { get { return selectedItem; } set { selectedItem = value; if(value !=null) { this.SelectedDate = value.DateValue; this.IsPickerOpen = true; } this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public DateTime SelectedDate { get { return selectedDate; } set { selectedDate = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public bool IsPickerOpen { get { return isPickerOpen; } set { isPickerOpen = value; if (!value) this.SelectedItem = null; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public bool IsOpen { get { return isOpen; } set { isOpen = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public bool IsOkClicked { get { return isOkClicked; } set { isOkClicked = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public string Text { get { return text; } set { text = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedDateFormat /// </summary> public string HeaderText { get { return headertext; } set { headertext = value; this.NotifyPropertyChanged(); } } #endregion #region Command /// <summary> /// Add command value /// </summary> private ICommand addCommand; /// <summary> /// AddCommand Command /// </summary> public ICommand AddCommand { get { return addCommand; } set { addCommand = value; } } /// <summary> /// ok command /// </summary> private ICommand okCommand; /// <summary> /// Gets or set the value for the Ok command /// </summary> public ICommand OKCommand { get { return okCommand; } set { okCommand = value; } } /// <summary> /// Cancel command /// </summary> private ICommand cancelCommand; /// <summary> /// Gets or sets the value for the Cancel command /// </summary> public ICommand CancelCommand { get { return cancelCommand; } set { cancelCommand = value; } } /// <summary> /// Accept Command /// </summary> private ICommand acceptCommand; /// <summary> /// Gets or sets the value for the AcceptCommand /// </summary> public ICommand AcceptCommand { get { return acceptCommand; } set { acceptCommand = value; } } /// <summary> /// decline command /// </summary> private ICommand declineCommand; /// <summary> /// Gets or sets the value for the date format collections /// </summary> private ObservableCollection<string> dateFormatcollections; /// <summary> /// dated formart /// </summary> private string dateFormat; /// <summary> /// Gets or sets the value for the Decline command /// </summary> public ICommand DeclineCommand { get { return declineCommand; } set { declineCommand = value; } } #endregion #region Constructor /// <summary> /// DatePickerTaskObjectViewModel /// </summary> public DatePickerTaskObjectViewModel() { this.GetDefaultTasks(); this.AddCommand = new Command(AddNewTask); this.OKCommand = new Command(AddItems); this.CancelCommand = new Command(Cancel); this.AcceptCommand = new Command(Accept); this.DeclineCommand = new Command(Decline); } #endregion #region NotifyPropertyChanged /// <summary> /// PropertyChanged /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// NotifyPropertyChanged /// </summary> /// <param name="propertyName"></param> private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Methods /// <summary> /// GetDefaultTasks /// </summary> public void GetDefaultTasks() { this.Tasks.Add(new DatePickerTaskObject() { Description = "Get quote from travel agent", DateValue = DateTime.Now }); this.Tasks.Add(new DatePickerTaskObject() { Description = "Book flight ticket", DateValue = DateTime.Now.AddDays(2) }); this.Tasks.Add(new DatePickerTaskObject() { Description = "Buy travel guide book", DateValue= DateTime.Now }); this.Tasks.Add(new DatePickerTaskObject() { Description = "Register for sky diving", DateValue = DateTime.Now.AddDays(9) }); this.DateFormatcollections = new ObservableCollection<string>() { "ddMMMyyyy", "ddMMyyyy", "MMddyyyy", "Mdyyyy", "yyyyMMdd", "ddMM", "MMyyyy", "MMMyyyy", }; this.PickerSelectedItem = DateFormatcollections[2]; } /// <summary> /// AddNewTask /// </summary> public void AddNewTask() { Text = ""; IsOpen = true; } /// <summary> /// AddItems /// </summary> public void AddItems() { this.SetTaskValue(); IsOpen = false; } /// <summary> /// Cancel /// </summary> public void Cancel() { IsOpen = false; } /// <summary> /// Accept /// </summary> public void Accept() { IsOkClicked = true; if (this.SelectedItem != null && this.SelectedDate != null) { this.SelectedItem.DateValue = this.SelectedDate; } } /// <summary> /// Decline /// </summary> public void Decline() { IsOkClicked = false; } /// <summary> /// SetTaskValue /// </summary> public void SetTaskValue() { if(string.IsNullOrEmpty(Text)) { Text = "New Appointment"; } this.Tasks.Add(new DatePickerTaskObject() { DateValue = this.SelectedDate,Description=Text}); } /// <summary> /// Pick the selection /// </summary> private void PickerSelectionChanged() { switch (PickerSelectedItem) { case "ddMMMyyyy": SelectedDateFormat = Syncfusion.XForms.Pickers.DateFormat.dd_MMM_yyyy; break; case "ddMMyyyy": SelectedDateFormat = Syncfusion.XForms.Pickers.DateFormat.dd_MM_yyyy; break; case "MMddyyyy": SelectedDateFormat = Syncfusion.XForms.Pickers.DateFormat.MM_dd_yyyy; break; case "Mdyyyy": SelectedDateFormat = Syncfusion.XForms.Pickers.DateFormat.M_d_yyyy; break; case "yyyyMMdd": SelectedDateFormat = Syncfusion.XForms.Pickers.DateFormat.yyyy_MM_dd; break; case "ddMM": SelectedDateFormat = Syncfusion.XForms.Pickers.DateFormat.dd_MM; break; case "MMyyyy": SelectedDateFormat = Syncfusion.XForms.Pickers.DateFormat.MM_yyyy; break; case "MMMyyyy": SelectedDateFormat = Syncfusion.XForms.Pickers.DateFormat.MMM_yyyy; break; } } #endregion } #endregion #region DatePickerDateToTextConverter class /// <summary> /// DatePickerDateToTextConverter /// </summary> public class DatePickerDateToTextConverter : IValueConverter { /// <summary> /// Convert method /// </summary> /// <param name="value"> object value</param> /// <param name="targetType">target type</param> /// <param name="parameter">parameter value</param> /// <param name="culture">culture </param> /// <returns>return string</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (((DateTime)value).ToShortDateString() == DateTime.Now.ToShortDateString()) { return "Due today"; } else return ((DateTime)value).ToString("d"); } /// <summary> /// Convert Back method /// </summary> /// <param name="value"> object value</param> /// <param name="targetType">target type</param> /// <param name="parameter">parameter value</param> /// <param name="culture">culture </param> /// <returns>null</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if ((string)value == "Due today") { return DateTime.Now; } else { DateTime oDate = DateTime.Parse((string)value); return oDate; } } } #endregion #region DatePickerBoolToColor class /// <summary> /// DatePickerBoolToColor /// </summary> public class DatePickerBoolToColor : IValueConverter { /// <summary> /// Convert method /// </summary> /// <param name="value"> object value</param> /// <param name="targetType">target type</param> /// <param name="parameter">parameter value</param> /// <param name="culture">culture </param> /// <returns>return clolor</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return Color.Accent; else return Color.Gray; } /// <summary> /// Convert back method /// </summary> /// <param name="value"> object value</param> /// <param name="targetType">target type</param> /// <param name="parameter">parameter value</param> /// <param name="culture">culture </param> /// <returns>null</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } #endregion #region DatePickerTextToColor class /// <summary> /// DatePickerTextToColor class /// </summary> public class DatePickerTextToColor : IValueConverter { /// <summary> /// Convert method /// </summary> /// <param name="value"> object value</param> /// <param name="targetType">target type</param> /// <param name="parameter">parameter value</param> /// <param name="culture">culture </param> /// <returns>return color</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (((DateTime)value).ToShortDateString() == DateTime.Now.ToShortDateString()) { return Color.Accent; } else { return Color.Default; } } /// <summary> /// Convert Back method /// </summary> /// <param name="value"> object value</param> /// <param name="targetType">target type</param> /// <param name="parameter">parameter value</param> /// <param name="culture">culture </param> /// <returns>null</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } #endregion } <file_sep>/iOS/SampleBrowser/Samples/Schedule/README.md ## SfSchedule The Schedule control is used to schedule and manage appointments through an intuitive user interface, thus allows you to plan and manage the events or appointments in an efficient way. | Sample | Description | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| | Getting Started | Showcases a simple schedule with data source displayed in day, workweek, week, and month views. | | Schedule View | Showcases the date navigation support with appointment editing such as start time, end time, subject, time zone, and more. | | Recurrence | Showcases the recurring appointments. | | Time table | Showcases the working hours with blocking timeslots. | | Agenda View | This sample showcases the agenda view support of schedule where specific date’s appointments can be viewed below the month view. | | Drag and Drop | Showcases the capability of rescheduling appointment through drag-and-drop operations. | | Customization | Showcases the capability of appointment customization using custom view.| | Configuration | Showcases the separation of working and non-working hours with different colors with blocking timeslots in day, week, and workweek views. It shows the blackout of a particular date and week number support in month view. | | Localization | Showcases the localization support of schedule. | <file_sep>/iOS/SampleBrowser/Samples/TabView/TabViewGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using CoreGraphics; using Syncfusion.iOS.TabView; using UIKit; namespace SampleBrowser { public class TabViewGettingStarted : SampleView { bool isControlLoaded = false; UILabel headerLabel; TemplateView templateView; SfTabView tabView; UIScrollView tabContentView; TabViewOptionsPage optionsPage; List<OrderDetails> FurnitureList = new List<OrderDetails>(); List<OrderDetails> ToysList = new List<OrderDetails>(); List<OrderDetails> ClothingList = new List<OrderDetails>(); List<OrderDetails> ShoesList = new List<OrderDetails>(); List<OrderDetails> FruitsList = new List<OrderDetails>(); public TabViewGettingStarted() { BackgroundColor = UIColor.FromRGB(48, 146, 246); InitializeOrderDetails(); optionsPage = new TabViewOptionsPage(); this.OptionView = optionsPage; } public override void LayoutSubviews() { if (!isControlLoaded) { isControlLoaded = true; InitializeHeaderLabel(); InitializeTabView(); this.optionsPage.sftabView = tabView; this.optionsPage.Frame = this.Frame; } base.LayoutSubviews(); } void InitializeHeaderLabel() { headerLabel = new UILabel(); headerLabel.Frame = new CGRect(0, 0, this.Frame.Width, 50); headerLabel.BackgroundColor = UIColor.FromRGB(48, 146, 246); headerLabel.TextColor = UIColor.White; headerLabel.Text = " Shopping Cart"; // Add(headerLabel); } UIView InitializeTabContent(string tabName,int count) { tabContentView = new UIScrollView(); tabContentView.BackgroundColor = UIColor.FromRGB(232,235,240); var height = 0; switch(tabName) { case "Furniture": for (int i = 0;i<count;i++) { var view = InitializeTemplateView(FurnitureList[i].Image, FurnitureList[i].Title, FurnitureList[i].Price, FurnitureList[i].Offer, FurnitureList[i].Rating, FurnitureList[i].Description); view.Frame = new CGRect(5, 5 + (i * 175), this.Frame.Width - 10, 170); tabContentView.Add(view); height = (int)(view.Frame.Y + view.Frame.Height); } break; case "Toys": for (int i = 0; i < count; i++) { var view = InitializeTemplateView(ToysList[i].Image, ToysList[i].Title, ToysList[i].Price, ToysList[i].Offer, ToysList[i].Rating, ToysList[i].Description); view.Frame = new CGRect(5, 5 + (i * 175), this.Frame.Width - 10, 170); tabContentView.Add(view); height = (int)(view.Frame.Y + view.Frame.Height); } break; case "Clothing": for (int i = 0; i < count; i++) { var view = InitializeTemplateView(ClothingList[i].Image, ClothingList[i].Title, ClothingList[i].Price, ClothingList[i].Offer, ClothingList[i].Rating, ClothingList[i].Description); view.Frame = new CGRect(5, 5 + (i * 175), this.Frame.Width - 10, 170); tabContentView.Add(view); height = (int)(view.Frame.Y + view.Frame.Height); } break; case "Shoes": for (int i = 0; i < count; i++) { var view = InitializeTemplateView(ShoesList[i].Image, ShoesList[i].Title, ShoesList[i].Price, ShoesList[i].Offer, ShoesList[i].Rating, ShoesList[i].Description); view.Frame = new CGRect(5, 5 + (i * 175), this.Frame.Width - 10, 170); tabContentView.Add(view); height = (int)(view.Frame.Y + view.Frame.Height); } break; case "Fruits": for (int i = 0; i < count; i++) { var view = InitializeTemplateView(FruitsList[i].Image, FruitsList[i].Title, FruitsList[i].Price, FruitsList[i].Offer, FruitsList[i].Rating, FruitsList[i].Description); view.Frame = new CGRect(5, 5 + (i * 175), this.Frame.Width - 10, 170); tabContentView.Add(view); height = (int)(view.Frame.Y + view.Frame.Height); } break; } tabContentView.ContentSize = new CGSize(this.Frame.Width, height); return tabContentView; } UIView InitializeTemplateView(string image, string title, string price, string offer, string rating,string description) { templateView = new TemplateView(); templateView.UpdateContent(image, title, price, offer, rating, description); return templateView; } void InitializeTabView() { TabItemCollection collection = new TabItemCollection(); tabView = new SfTabView(); tabView.TabHeaderBackgroundColor = UIColor.Clear; tabView.BackgroundColor = UIColor.FromRGB(48, 146, 246);//UIColor.White;//UIColor.FromRGB(48, 146, 246); tabView.TabHeaderBackgroundColor = UIColor.FromRGB(48, 146, 246);//UIColor.White;//UIColor.FromRGB(48, 146, 246); tabView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); SfTabItem furnitureTab = new SfTabItem(); furnitureTab.Title = "Furniture"; furnitureTab.IconFont = "A"; furnitureTab.Content = InitializeTabContent("Furniture", 5); furnitureTab.TitleFontColor = UIColor.White; furnitureTab.FontIconFontColor = UIColor.White; furnitureTab.SelectionColor = UIColor.White; furnitureTab.FontIconFont = UIFont.FromName("TabIcons", 20); collection.Add(furnitureTab); SfTabItem clothingTab = new SfTabItem(); clothingTab.IconFont = "C"; clothingTab.Title = "Clothing"; clothingTab.Content = InitializeTabContent("Clothing", 5); clothingTab.TitleFontColor = UIColor.White; clothingTab.FontIconFontColor = UIColor.White; clothingTab.SelectionColor = UIColor.White; clothingTab.FontIconFont = UIFont.FromName("TabIcons", 20); collection.Add(clothingTab); SfTabItem shoesTab = new SfTabItem(); shoesTab.IconFont = "F"; shoesTab.Title = "Shoes"; shoesTab.Content = InitializeTabContent("Shoes", 5); shoesTab.TitleFontColor = UIColor.White; shoesTab.FontIconFontColor = UIColor.White; shoesTab.SelectionColor = UIColor.White; shoesTab.FontIconFont = UIFont.FromName("TabIcons", 20); collection.Add(shoesTab); SfTabItem fruitsTab = new SfTabItem(); fruitsTab.IconFont = "H"; fruitsTab.Title = "Fruits"; fruitsTab.Content = InitializeTabContent("Fruits", 5); fruitsTab.TitleFontColor = UIColor.White; fruitsTab.FontIconFontColor = UIColor.White; fruitsTab.SelectionColor = UIColor.White; fruitsTab.FontIconFont = UIFont.FromName("TabIcons", 20); collection.Add(fruitsTab); SfTabItem toysTab = new SfTabItem(); toysTab.Title = "Toys"; toysTab.IconFont = "K"; toysTab.Content = InitializeTabContent("Toys", 5); toysTab.TitleFontColor = UIColor.White; toysTab.FontIconFontColor = UIColor.White; toysTab.SelectionColor = UIColor.White; toysTab.FontIconFont = UIFont.FromName("TabIcons", 20); collection.Add(toysTab); tabView.Items = collection; Add(tabView); tabView.SelectionIndicatorSettings.Color = UIColor.White; tabView.TabHeight = 60; if((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { tabView.TabWidth = 150; } } void InitializeOrderDetails() { FurnitureList.Add(new OrderDetails("Images/TabView/sofa2.png", "Leather Black Sofa", "$99.50", "5%", "3.9","Warrenty coverred upto 5 years.Its specialty is its bookcase headboard which serves as an easy access to users.Bring a new member into your family.Delivered in non - assembled pieces.")); FurnitureList.Add(new OrderDetails("Images/TabView/hall.png", "Wooden Standing Drawer", "$299.40", "1%", "4.1","This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials.")); FurnitureList.Add(new OrderDetails("Images/TabView/sofa.png", "Semi Fabric Sofa", "$149.90", "10%", "4.4","Engineered wood is created by binding or glueing together at least three thin boards of wood.As a result, your engineered wood furniture will be stable and climate - resistant.")); FurnitureList.Add(new OrderDetails("Images/TabView/chair.png", "Dinning Chair", "$129.40", "15%", "3.7","Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy.")); FurnitureList.Add(new OrderDetails("Images/TabView/hall2.png", "Fabric White Sofa", "$199.50", "20%", "4.5","Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight.")); ToysList.Add(new OrderDetails("Images/TabView/friends.png", "Warriors", "$9.50", "5%", "4.7","Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant.")); ToysList.Add(new OrderDetails("Images/TabView/robot.png", "Robots", "$7.97", "15%", "4.2","Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy.")); ToysList.Add(new OrderDetails("Images/TabView/minion.png", "Minion collections", "$4.55", "20%", "3.5","Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight.")); ToysList.Add(new OrderDetails("Images/TabView/train.png", "Train simulation", "$5.97", "15%", "3.9","High quality material has been used. Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces.")); ToysList.Add(new OrderDetails("Images/TabView/van.png", "Icecream Van", "$18.47", "10%", "4.1","This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials.")); ClothingList.Add(new OrderDetails("Images/TabView/whiteshirt.png", "Long Sleeve Cotton Shirt", "$25.11", "5%", "4.9","Warrenty coverred upto 5 years.Its specialty is its bookcase headboard which serves as an easy access to users.Bring a new member into your family.Delivered in non - assembled pieces.")); ClothingList.Add(new OrderDetails("Images/TabView/shirt.png", "<NAME>", "$20.21", "10%", "4.1","This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials.")); ClothingList.Add(new OrderDetails("Images/TabView/tshirt.png", "Short Sleeve T-Shirt", "$11.29", "10%", "4.5","Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant.")); ClothingList.Add(new OrderDetails("Images/TabView/redcoat.png", "Casual Shirt Semi-Fit", "$35.75", "10%", "4.3","Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy.")); ClothingList.Add(new OrderDetails("Images/TabView/silvercoat.png", "Classic Slim Fit Suit ", "$74.32", "20%", "4.1","Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces.")); // ClothingList.Add(new OrderDetails("Images/TabView/redcoat.jpeg", "Party Suit - Red", "$59.11", "30%", "4.4")); ShoesList.Add(new OrderDetails("Images/TabView/canvas.png", "Lightweight Shoes", "$12.44", "15%", "3.9","This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials.")); ShoesList.Add(new OrderDetails("Images/TabView/graycanvas.png", "Trendy Grey Shoes", "$16.37", "20%", "3.7","Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant.")); ShoesList.Add(new OrderDetails("Images/TabView/boots.png", "Classic Formal Shoes", "$29.45", "35%", "4.3","Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy.")); ShoesList.Add(new OrderDetails("Images/TabView/blackshoe.png", "White Sporty Shoes", "$29.97", "10%", "4.1","Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight.")); ShoesList.Add(new OrderDetails("Images/TabView/leather.png", "Trendy Brown Shoes", "$43.11", "5%", "4.5","High quality material has been used. Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces.")); FruitsList.Add(new OrderDetails("Images/TabView/orange.png", "Orange", "$0.49", "0.5%", "3.9","Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant.")); FruitsList.Add(new OrderDetails("Images/TabView/blueberry.png", "Blueberries (Imported)", "$1.25", "0.25%", "4.7","Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy.")); FruitsList.Add(new OrderDetails("Images/TabView/apple.png", "Apple", "$1.45", "5%", "4.1","Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight.")); FruitsList.Add(new OrderDetails("Images/TabView/strawberry.png", "Strawberry", "$0.91", "2%", "4.2","High quality material has been used. Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces.")); FruitsList.Add(new OrderDetails("Images/TabView/banana.png","Banana","$2.23","4%","4.5","This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials.")); } } } <file_sep>/Forms/Chart/Chart/Samples/AxisCrossing/AxisCrossingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class SalesModel { public double YValue { get; set; } public double Size { get; set; } public string XValue { get; set; } } public class AxisCrossingViewModel { public ObservableCollection<SalesModel> Data { get; set; } public AxisCrossingViewModel() { Data = new ObservableCollection<SalesModel>() { new SalesModel { XValue = "2000", YValue = 70 }, new SalesModel { XValue = "2001", YValue = 50 }, new SalesModel { XValue = "2002", YValue = -30}, new SalesModel { XValue = "2003", YValue = -70}, new SalesModel { XValue = "2004", YValue = 40 }, new SalesModel { XValue = "2005", YValue = 80 }, new SalesModel { XValue = "2006", YValue = -70}, new SalesModel { XValue = "2007", YValue = 30 }, new SalesModel { XValue = "2008", YValue = 80 }, new SalesModel { XValue = "2009", YValue = -30}, new SalesModel { XValue = "2010", YValue = -80}, new SalesModel { XValue = "2011", YValue = 40 }, new SalesModel { XValue = "2012", YValue = -50}, new SalesModel { XValue = "2013", YValue = -10}, new SalesModel { XValue = "2014", YValue = -80}, new SalesModel { XValue = "2015", YValue = 40 }, new SalesModel { XValue = "2016", YValue = -50} }; } } } <file_sep>/Forms/SegmentedControl/SegmentedControl/Samples/SegmentViewGettingStarted/ViewModel/GettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using System.ComponentModel; using Syncfusion.XForms.Buttons; using Xamarin.Forms; namespace SampleBrowser.SegmentedControl { public class GettingStartedViewModel :INotifyPropertyChanged { private string fontIconText; public string FontIconText { get { return fontIconText; } set { fontIconText = value; OnPropertyChanged("FontIconText"); } } private ObservableCollection<SfSegmentItem> sizeCollection = new ObservableCollection<SfSegmentItem>(); /// <summary> /// Item collectio for Different size of shirt /// </summary> public ObservableCollection<SfSegmentItem> SizeCollection { get { return sizeCollection; } set { sizeCollection = value; } } private ObservableCollection<SfSegmentItem> clothTypeCollection = new ObservableCollection<SfSegmentItem>(); /// <summary> /// Item collection for types of cloth /// </summary> public ObservableCollection<SfSegmentItem> ClothTypeCollection { get { return clothTypeCollection; } set { clothTypeCollection = value; } } /// <summary> /// Item collection for different colors of shirt to be selected. /// </summary> public ObservableCollection<SfSegmentItem> PrimaryColors { get; set; } public GettingStartedViewModel() { ClothTypeCollection = new ObservableCollection<SfSegmentItem>() { new SfSegmentItem() { Text = "Formals", FontColor = Color.Black }, new SfSegmentItem() { Text = "Casuals", FontColor = Color.Black }, new SfSegmentItem() { Text = "Trendy", FontColor = Color.Black } }; SizeCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "A", Text="XS",FontColor=Color.FromHex("#3F3F3F") }, new SfSegmentItem(){IconFont = "A", Text="S",FontColor=Color.FromHex("#3F3F3F")}, new SfSegmentItem(){IconFont = "A", Text="M",FontColor=Color.FromHex("#3F3F3F")}, new SfSegmentItem(){IconFont = "A", Text="L",FontColor=Color.FromHex("#3F3F3F")}, new SfSegmentItem(){IconFont = "A", Text="XL",FontColor=Color.FromHex("#3F3F3F")}, }; var fontFamily = "Segmented.ttf"; var colorfontFamily = "SegmentIcon.ttf"; if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB fontFamily = "/Assets/Fonts/Segmented.ttf#Segmented"; #else if (Core.SampleBrowser.IsIndividualSB) { fontFamily = "/Assets/Fonts/Segmented.ttf#Segmented"; } else { fontFamily = $"ms-appx:///SampleBrowser.SfSegmentedControl.UWP/Assets/Fonts/Segmented.ttf#Segmented"; } #endif } else if (Device.RuntimePlatform == Device.iOS) { fontFamily = "segment2"; } else if (Device.RuntimePlatform == Device.WPF) { fontFamily = "/Assets/Fonts/Segmented.ttf#Segmented"; } if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB colorfontFamily = "/Assets/Fonts/SegmentIcon.ttf#segment2"; #else if (Core.SampleBrowser.IsIndividualSB) { colorfontFamily = "/Assets/Fonts/SegmentIcon.ttf#segment2"; } else { colorfontFamily = $"ms-appx:///SampleBrowser.SfSegmentedControl.UWP/Assets/Fonts/SegmentIcon.ttf#segment2"; } #endif } else if (Device.RuntimePlatform == Device.iOS) { colorfontFamily = "segment2"; } else if(Device.RuntimePlatform == Device.WPF) { colorfontFamily = "/Assets/Fonts/SegmentIcon.ttf#segment2"; } var SegoeFontFamily = "Segoe_MDL2_Assets.ttf"; if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB SegoeFontFamily = "/Assets/Fonts/Segoe_MDL2_Assets.ttf#Segoe MDL2 Assets"; #else if (Core.SampleBrowser.IsIndividualSB) { SegoeFontFamily = "/Assets/Fonts/Segoe_MDL2_Assets.ttf#Segoe MDL2 Assets"; } else { SegoeFontFamily = $"ms-appx:///SampleBrowser.SfSegmentedControl.UWP/Assets/Fonts/Segoe_MDL2_Assets.ttf#Segoe MDL2 Assets"; } #endif } else if (Device.RuntimePlatform == Device.iOS) { SegoeFontFamily = "Segoe MDL2 Assets"; } else if(Device.RuntimePlatform == Device.WPF) { SegoeFontFamily = "/Assets/Fonts/Segoe_MDL2_Assets.ttf#Segoe MDL2 Assets"; } PrimaryColors = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#32318E"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#2F7DC0"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#953376"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#B33F3F"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#F1973F"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#C9D656"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#008D7F"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, }; } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/Android/SampleBrowser/Common/Model/SampleModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.Generic; namespace SampleBrowser { public class SampleModel : Java.Lang.Object, Java.IO.ISerializable { #region ctor public SampleModel() { Type = string.Empty; } #endregion #region properties public string Name { get; set; } public string Type { get; set; } public string Title { get; set; } public string ImageId { get; set; } public string Description { get; set; } #endregion } public class ControlModel : SampleModel { #region ctor public ControlModel() { Features = new List<SampleModel>(); Samples = new List<SampleModel>(); } #endregion #region properties public List<SampleModel> Features { get; set; } public List<SampleModel> Samples { get; set; } #endregion } }<file_sep>/Android/SampleBrowser/Samples/AutoComplete/AutoComplete_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Android.Views.InputMethods; using Android.Util; #endregion using System; using Com.Syncfusion.Autocomplete; using Android.Widget; using Android.Views; using System.Runtime.Remoting.Contexts; using Android.Graphics; using System.Collections.ObjectModel; using System.Collections.Generic; using Android.App; using Android.Content; using SampleBrowser; namespace SampleBrowser { public class AutoComplete_Mobile { /********************************* **Local Variable Inizialisation** *********************************/ int minimum = 1, popupdelay = 100, maximum = 150, jobNumber = 0, width; TextView jobSearchLabel, countryLabel, jobFieldLabel, experienceLabel, jobSearchLabelSpacing; TextView countryLabelSpacing, countryAutoCompleteSpacing, jobFieldLabelSpacing, jobFieldAutoCompleteSpacing; TextView experienceLabelSpacing, experienceSpinnerSpacing, searchButtonSpacing; EditText minPrefixCharacterText, maxDropDownHeightText, popUpDelayText; Spinner suggestionModeSpinner, autoCompleteModeSpinner, experienceSpinner; LinearLayout propertylayout, minPrefixCharaterStack, maxDropDownHeightStack, popUpDelayStack; ArrayAdapter<String> suggestionModeDataAdapter, autoCompleteModeDataAdapter; SfAutoComplete countryNameAutoComplete, jobFieldAutoComplete; SuggestionMode suggestionModes = SuggestionMode.StartsWith; AutoCompleteMode autoCompleteMode = AutoCompleteMode.Suggest; List<String> Title = new List<String>(); List<String> Experience = new List<String>(); AlertDialog.Builder resultsDialog; Button searchButton; Android.Content.Context context; public View GetPropertyLayout(Android.Content.Context context1) { context = context1; width = context.Resources.DisplayMetrics.WidthPixels / 2; propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; SuggestionModeLayout(); AutoCompleteModeLayout(); MinimumPrefixCharacterLayout(); MaximumDropDownLayout(); PopUpDelayLayout(); ScrollView scroll = new ScrollView(context1); scroll.AddView(propertylayout); return scroll; } private void SuggestionModeLayout() { /***************** **SuggestionMode** ******************/ TextView suggestionModeLabel = new TextView(context); suggestionModeLabel.Text = "Suggestion Mode"; suggestionModeLabel.TextSize = 20; suggestionModeLabel.Gravity = GravityFlags.Left; //SpaceText TextView spacingText = new TextView(context); propertylayout.AddView(spacingText); suggestionModeSpinner = new Spinner(context,SpinnerMode.Dialog); propertylayout.AddView(suggestionModeLabel); propertylayout.AddView(suggestionModeSpinner); //SuggestionList List<String> suggestionModeList = new List<String>(); suggestionModeList.Add("StartsWith"); suggestionModeList.Add("StartsWithCaseSensitive"); suggestionModeList.Add("Contains"); suggestionModeList.Add("ContainsWithCaseSensitive"); suggestionModeList.Add("EndsWith"); suggestionModeList.Add("EndsWithCaseSensitive"); suggestionModeList.Add("Equals"); suggestionModeList.Add("EqualsWithCaseSensitive"); suggestionModeDataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, suggestionModeList); suggestionModeDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); suggestionModeSpinner.Adapter = suggestionModeDataAdapter; //suggestionModeSpinner ItemSelected Listener suggestionModeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = suggestionModeDataAdapter.GetItem(e.Position); if (selectedItem.Equals("StartsWith")) { suggestionModes = SuggestionMode.StartsWith; } else if (selectedItem.Equals("StartsWithCaseSensitive")) { suggestionModes = SuggestionMode.StartsWithCaseSensitive; } else if (selectedItem.Equals("Contains")) { suggestionModes = SuggestionMode.Contains; } else if (selectedItem.Equals("ContainsWithCaseSensitive")) { suggestionModes = SuggestionMode.ContainsWithCaseSensitive; } else if (selectedItem.Equals("EndsWith")) { suggestionModes = SuggestionMode.EndsWith; } else if (selectedItem.Equals("EndsWithCaseSensitive")) { suggestionModes = SuggestionMode.EndsWithCaseSensitive; } else if (selectedItem.Equals("Equals")) { suggestionModes = SuggestionMode.Equals; } else if (selectedItem.Equals("EqualsWithCaseSensitive")) { suggestionModes = SuggestionMode.EqualsWithCaseSensitive; } }; //Separator SeparatorView suggestionModeSeparate = new SeparatorView(context, width * 2); suggestionModeSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams suggestionModeLayoutParam = new LinearLayout.LayoutParams(width * 2, 5); suggestionModeLayoutParam.SetMargins(0, 20, 0, 0); // propertylayout.AddView(suggestionModeSeparate, suggestionModeLayoutParam); } private void AutoCompleteModeLayout() { /******************* **AutoCompleteMode** ********************/ TextView autoCompleteModeLabel = new TextView(context); autoCompleteModeLabel.Text = "AutoComplete Mode"; autoCompleteModeLabel.TextSize = 20; autoCompleteModeLabel.Gravity = GravityFlags.Left; //SpaceTExt TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); autoCompleteModeSpinner = new Spinner(context,SpinnerMode.Dialog); propertylayout.AddView(autoCompleteModeLabel); propertylayout.AddView(autoCompleteModeSpinner); //AutoCompleteModeList List<String> autoCompleteModeList = new List<String>(); autoCompleteModeList.Add("Suggest"); autoCompleteModeList.Add("SuggestAppend"); autoCompleteModeList.Add("Append"); autoCompleteModeDataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, autoCompleteModeList); autoCompleteModeDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); autoCompleteModeSpinner.Adapter = autoCompleteModeDataAdapter; //autoCompleteModeSpinner ItemSelected Listener autoCompleteModeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = autoCompleteModeDataAdapter.GetItem(e.Position); if (selectedItem.Equals("Suggest")) { autoCompleteMode = AutoCompleteMode.Suggest; } else if (selectedItem.Equals("SuggestAppend")) { autoCompleteMode = AutoCompleteMode.SuggestAppend; } else if (selectedItem.Equals("Append")) { autoCompleteMode = AutoCompleteMode.Append; } }; //Separator SeparatorView separate1 = new SeparatorView(context, width * 2); separate1.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams autoCompleteModeLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); autoCompleteModeLayoutParams.SetMargins(0, 20, 0, 0); propertylayout.SetPadding(5, 0, 5, 0); //autoCompleteModeSeparator SeparatorView autoCompleteModeSeparate = new SeparatorView(context, width * 2); autoCompleteModeSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); //propertylayout.AddView(autoCompleteModeSeparate, autoCompleteModeLayoutParams); } private void MinimumPrefixCharacterLayout() { /************************ **Min Prefix Character** ************************/ TextView minPrefixCharaterLabel = new TextView(context); minPrefixCharaterLabel.Text = "Min Prefix Character"; minPrefixCharaterLabel.TextSize = 20; //MinPrefixCharacterText minPrefixCharacterText = new EditText(context); minPrefixCharacterText.Text = "1"; minPrefixCharacterText.TextSize = 16; minPrefixCharacterText.SetWidth(50); minPrefixCharacterText.InputType = Android.Text.InputTypes.ClassPhone; minPrefixCharacterText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { try { if (minPrefixCharacterText.Text.Length > 0) minimum = Convert.ToInt32(e.Text.ToString()); else minimum = 1; } catch { } }; //MinPrefixCharaterTextLayoutParams LinearLayout.LayoutParams minPrefixCharaterTextLayoutParams = new LinearLayout.LayoutParams( width - 10, ViewGroup.LayoutParams.WrapContent); minPrefixCharaterTextLayoutParams.SetMargins(-10, 10, 0, 0); LinearLayout.LayoutParams minPrefixCharaterLabelLayoutParams = new LinearLayout.LayoutParams( width - 10, ViewGroup.LayoutParams.WrapContent); minPrefixCharaterLabelLayoutParams.SetMargins(0, 10, 0, 0); TextView spacingText = new TextView(context); propertylayout.AddView(spacingText); //MinPrefixCharaterStack minPrefixCharaterStack = new LinearLayout(context); minPrefixCharaterStack.AddView(minPrefixCharaterLabel, minPrefixCharaterLabelLayoutParams); minPrefixCharaterStack.AddView(minPrefixCharacterText, minPrefixCharaterTextLayoutParams); minPrefixCharaterStack.Orientation = Orientation.Horizontal; propertylayout.AddView(minPrefixCharaterStack); //MinPrefixCharaterSeparate SeparatorView minPrefixCharaterSeparate = new SeparatorView(context, width * 2); minPrefixCharaterSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams minPrefixCharaterLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); minPrefixCharaterLayoutParams.SetMargins(0, 20, 0, 0); // propertylayout.AddView(minPrefixCharaterSeparate, minPrefixCharaterLayoutParams); } private void MaximumDropDownLayout() { /*********************** **max DropDown height** ***********************/ TextView maxDropDownHeightLabel = new TextView(context); maxDropDownHeightLabel.Text = "Max DropDown Height"; maxDropDownHeightLabel.TextSize = 20; //MaxDropDownHeightText maxDropDownHeightText = new EditText(context); maxDropDownHeightText.Text = "200"; maxDropDownHeightText.TextSize = 16; maxDropDownHeightText.SetWidth(50); maxDropDownHeightText.InputType = Android.Text.InputTypes.ClassPhone; maxDropDownHeightText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { try { if (maxDropDownHeightText.Text.Length > 0) maximum = Convert.ToInt32(e.Text.ToString()); else maximum = 150; } catch{ } }; //MaxDropDownHeightTextLayoutParams LinearLayout.LayoutParams maxDropDownHeightTextLayoutParams = new LinearLayout.LayoutParams( width - 10, ViewGroup.LayoutParams.WrapContent); maxDropDownHeightTextLayoutParams.SetMargins(-10, 10, 0, 0); LinearLayout.LayoutParams maxDropDownHeightLabelLayoutParams = new LinearLayout.LayoutParams( width - 10, ViewGroup.LayoutParams.WrapContent); maxDropDownHeightLabelLayoutParams.SetMargins(0, 10, 0, 0); TextView spacingText = new TextView(context); propertylayout.AddView(spacingText); //MaxDropDownHeightStack maxDropDownHeightStack = new LinearLayout(context); maxDropDownHeightStack.AddView(maxDropDownHeightLabel, maxDropDownHeightLabelLayoutParams); maxDropDownHeightStack.AddView(maxDropDownHeightText, maxDropDownHeightTextLayoutParams); maxDropDownHeightStack.Orientation = Orientation.Horizontal; propertylayout.AddView(maxDropDownHeightStack); //MaxDropDownHeightSeparate SeparatorView maxDropDownHeightSeparate = new SeparatorView(context, width * 2); maxDropDownHeightSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams maxDropDownHeightLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); maxDropDownHeightLayoutParams.SetMargins(0, 20, 0, 0); // propertylayout.AddView(maxDropDownHeightSeparate, maxDropDownHeightLayoutParams); } private void PopUpDelayLayout() { /*************** **Popup Delay** ***************/ TextView popUpDelayLabel = new TextView(context); popUpDelayLabel.Text = "PopUp Delay"; popUpDelayLabel.TextSize = 20; //PopUpDelayText popUpDelayText = new EditText(context); popUpDelayText.Text = "100"; popUpDelayText.TextSize = 16; popUpDelayText.InputType = Android.Text.InputTypes.ClassPhone; popUpDelayText.SetWidth(50); //popUpDelayText TextChanged Listener popUpDelayText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { try { if (popUpDelayText.Text.Length > 0) popupdelay = Convert.ToInt32(e.Text.ToString()); else popupdelay = 100; } catch { } }; LinearLayout.LayoutParams popUpDelayTextLayoutParams = new LinearLayout.LayoutParams( width - 10, ViewGroup.LayoutParams.WrapContent); popUpDelayTextLayoutParams.SetMargins(-10, 10, 0, 0); LinearLayout.LayoutParams popUpDelayLabelLayoutParams = new LinearLayout.LayoutParams( width - 10, ViewGroup.LayoutParams.WrapContent); popUpDelayLabelLayoutParams.SetMargins(0, 10, 0, 0); TextView spacingText = new TextView(context); propertylayout.AddView(spacingText); //PopUpDelayStack popUpDelayStack = new LinearLayout(context); popUpDelayStack.AddView(popUpDelayLabel, popUpDelayLabelLayoutParams); popUpDelayStack.AddView(popUpDelayText, popUpDelayTextLayoutParams); popUpDelayStack.Orientation = Orientation.Horizontal; propertylayout.AddView(popUpDelayStack); //PopUpDelaySeparate SeparatorView popUpDelaySeparate = new SeparatorView(context, width * 2); popUpDelaySeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams popUpDelayLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); popUpDelayLayoutParams.SetMargins(0, 20, 0, 0); // propertylayout.AddView(popUpDelaySeparate, popUpDelayLayoutParams); } public View GetSampleContent(Android.Content.Context con) { SamplePageContents(con); //countryNameAutoComplete countryNameAutoComplete = new SfAutoComplete(con); ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleListItem1, new Countrylist().Country); countryNameAutoComplete.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 50); countryNameAutoComplete.AutoCompleteSource = (countryAdapter); countryNameAutoComplete.SuggestionMode = SuggestionMode.StartsWith; countryNameAutoComplete.MaximumDropDownHeight = 150; countryNameAutoComplete.Watermark = "Enter a country name"; countryNameAutoComplete.GetAutoEditText().SetTextSize(ComplexUnitType.Sp, 20); countryNameAutoComplete.TextHighlightMode = OccurrenceMode.FirstOccurrence; countryNameAutoComplete.HighlightedTextColor = Color.Blue; //jobFieldAutoComplete jobFieldAutoComplete = new SfAutoComplete(con); ArrayAdapter<String> titleAdapter = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleListItem1, Title); jobFieldAutoComplete.AutoCompleteSource = (titleAdapter); jobFieldAutoComplete.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 50); jobFieldAutoComplete.SuggestionMode = SuggestionMode.Contains; jobFieldAutoComplete.MaximumDropDownHeight = 150; jobFieldAutoComplete.Watermark = "Starts with ’S’, ‘M’ or ‘B’"; jobFieldAutoComplete.GetAutoEditText().SetTextSize(ComplexUnitType.Sp, 20); jobFieldAutoComplete.TextHighlightMode = OccurrenceMode.FirstOccurrence; jobFieldAutoComplete.HighlightedTextColor = Color.Blue; //main view LinearLayout mainView = GetView(con); return mainView; } private LinearLayout GetView(Android.Content.Context con) { //mainLayout LinearLayout mainLayout = new LinearLayout(con); mainLayout.SetPadding(20, 20, 20, 30); mainLayout.SetBackgroundColor(Color.Rgb(236, 236, 236)); mainLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); mainLayout.Orientation = Orientation.Vertical; mainLayout.AddView(jobSearchLabel); mainLayout.AddView(jobSearchLabelSpacing); mainLayout.AddView(countryLabel); mainLayout.AddView(countryLabelSpacing); mainLayout.AddView(countryNameAutoComplete); mainLayout.AddView(countryAutoCompleteSpacing); mainLayout.AddView(jobFieldLabel); mainLayout.AddView(jobFieldLabelSpacing); mainLayout.AddView(jobFieldAutoComplete); mainLayout.AddView(jobFieldAutoCompleteSpacing); mainLayout.AddView(experienceLabel); mainLayout.AddView(experienceLabelSpacing); mainLayout.AddView(experienceSpinner); mainLayout.AddView(experienceSpinnerSpacing); mainLayout.AddView(searchButtonSpacing); mainLayout.AddView(searchButton); mainLayout.Touch += (object sender, View.TouchEventArgs e) => { Rect outRect = new Rect(); countryNameAutoComplete.GetGlobalVisibleRect(outRect); jobFieldAutoComplete.GetGlobalVisibleRect(outRect); if (!outRect.Contains((int)e.Event.RawX, (int)e.Event.RawY)) { countryNameAutoComplete.ClearFocus(); jobFieldAutoComplete.ClearFocus(); } hideSoftKeyboard((Activity)con); }; return mainLayout; } private void SamplePageContents(Android.Content.Context con) { //Title list Title.Add("Software"); Title.Add("Banking"); Title.Add("Media"); Title.Add("Medical"); //jobSearchLabel jobSearchLabel = new TextView(con); jobSearchLabel.Text = "Job Search"; jobSearchLabel.TextSize = 30; jobSearchLabel.Typeface = Typeface.DefaultBold; //jobSearchLabelSpacing jobSearchLabelSpacing = new TextView(con); jobSearchLabelSpacing.SetHeight(40); //countryLabel countryLabel = new TextView(con); countryLabel.Text = "Country"; countryLabel.TextSize = 16; //countryLabelSpacing countryLabelSpacing = new TextView(con); countryLabelSpacing.SetHeight(10); //countryAutoCompleteSpacing countryAutoCompleteSpacing = new TextView(con); countryAutoCompleteSpacing.SetHeight(30); //jobFieldLabel jobFieldLabel = new TextView(con); jobFieldLabel.Text = "Job Field"; jobFieldLabel.TextSize = 16; //jobFieldLabelSpacing jobFieldLabelSpacing = new TextView(con); jobFieldLabelSpacing.SetHeight(10); //jobFieldAutoCompleteSpacing jobFieldAutoCompleteSpacing = new TextView(con); jobFieldAutoCompleteSpacing.SetHeight(30); //experienceLabel experienceLabel = new TextView(con); experienceLabel.Text = "Experience"; experienceLabel.TextSize = 16; //experienceLabelSpacing experienceLabelSpacing = new TextView(con); experienceLabelSpacing.SetHeight(10); //Experience list Experience.Add("1"); Experience.Add("2"); //searchButton searchButton = new Button(con); searchButton.SetWidth(ActionBar.LayoutParams.MatchParent); searchButton.SetHeight(40); searchButton.Text = "Search"; searchButton.SetTextColor(Color.White); searchButton.SetBackgroundColor(Color.Gray); searchButton.Click += (object sender, EventArgs e) => { GetResult(); resultsDialog.SetMessage(jobNumber + " Jobs Found"); resultsDialog.Create().Show(); }; //searchButtonSpacing searchButtonSpacing = new TextView(con); searchButtonSpacing.SetHeight(30); //experience Spinner experienceSpinner = new Spinner(con,SpinnerMode.Dialog); experienceSpinner.DropDownWidth = 500; experienceSpinner.SetBackgroundColor(Color.Gray); ArrayAdapter<String> experienceDataAdapter = new ArrayAdapter<String> (con, Android.Resource.Layout.SimpleSpinnerItem, Experience); experienceDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); experienceSpinner.Adapter = experienceDataAdapter; //experienceSpinnerSpacing experienceSpinnerSpacing = new TextView(con); experienceSpinnerSpacing.SetHeight(30); //results dialog resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetTitle("Results"); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); } public void GetResult() { jobNumber = 0; if (countryNameAutoComplete.Text.ToString().Equals("") || jobFieldAutoComplete.Text.ToString().Equals("")) { } else { Random r = new Random(); jobNumber = r.Next(5, 60); } } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); inputMethodManager.HideSoftInputFromWindow(activity.CurrentFocus.WindowToken, 0); } public void ApplyChanges() { countryNameAutoComplete.SuggestionMode = suggestionModes; countryNameAutoComplete.AutoCompleteMode = autoCompleteMode; countryNameAutoComplete.MinimumPrefixCharacters = minimum; countryNameAutoComplete.PopUpDelay = popupdelay; countryNameAutoComplete.MaximumDropDownHeight = maximum; jobFieldAutoComplete.SuggestionMode = suggestionModes; jobFieldAutoComplete.AutoCompleteMode = autoCompleteMode; jobFieldAutoComplete.MinimumPrefixCharacters = minimum; jobFieldAutoComplete.PopUpDelay = popupdelay; jobFieldAutoComplete.MaximumDropDownHeight = maximum; } } }<file_sep>/Android/SampleBrowser/Samples/XlsIO/ImportNestedCollectionPage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using System.ComponentModel; using System.Xml.Serialization; namespace SampleBrowser { public partial class ImportNestedCollectionPage : SamplePage { private Context m_context; private Spinner spinner; private LinearLayout advancedLinear1; private LinearLayout advancedLinear2; RadioGroup radioGroup; RadioButton expandButton; RadioButton collapseButton; EditText editText; private LinearLayout linear; private Switch switch1; private Button button1; public override View GetSampleContent (Context con) { int numerHeight = getDimensionPixelSize(con, Resource.Dimension.numeric_txt_ht); int width = con.Resources.DisplayMetrics.WidthPixels - 40; linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); linear.DividerPadding = 0; TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to import data from nested collection with layout and group options."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; LinearLayout subLinear = new LinearLayout(con); subLinear.Orientation = Orientation.Horizontal; TextView space2 = new TextView (con); space2.TextSize = 17; space2.TextAlignment = TextAlignment.Center; space2.Text = "Layout Options"; space2.SetTextColor(Color.ParseColor("#262626")); space2.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); subLinear.AddView (space2); string[] list = { "Default", "Merge", "Repeat" }; ArrayAdapter<String> array = new ArrayAdapter<String>(con,Android.Resource.Layout.SimpleSpinnerItem , list); spinner = new Spinner (con); spinner.Adapter = array; spinner.SetSelection (0); subLinear.AddView (spinner); linear.AddView(subLinear); advancedLinear1 = new LinearLayout(con); advancedLinear1.Orientation = Orientation.Horizontal; TextView space4 = new TextView(con); space4.TextSize = 17; space4.TextAlignment = TextAlignment.Center; space4.Text = "Apply Group"; space4.SetTextColor(Color.ParseColor("#262626")); space4.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear1.AddView(space4); switch1 = new Switch(con); switch1.Checked = false; advancedLinear1.AddView(switch1); linear.AddView(advancedLinear1); LinearLayout advancedLinear3 = new LinearLayout(con); advancedLinear3.Orientation = Orientation.Horizontal; TextView space6 = new TextView(con); space6.TextSize = 17; space6.TextAlignment = TextAlignment.Center; space6.Text = ""; space6.SetTextColor(Color.ParseColor("#262626")); space6.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear3.AddView(space6); advancedLinear2 = new LinearLayout(con); advancedLinear2.Orientation = Orientation.Vertical; TextView space5 = new TextView(con); space5.TextSize = 17; space5.TextAlignment = TextAlignment.Center; space5.Text = "Options"; space5.SetTextColor(Color.ParseColor("#262626")); space5.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight - 90); advancedLinear2.AddView(space5); radioGroup = new RadioGroup(con); radioGroup.TextAlignment = TextAlignment.Center; radioGroup.Orientation = Orientation.Vertical; expandButton = new RadioButton(con); expandButton.Text = "Expand"; radioGroup.AddView(expandButton); collapseButton = new RadioButton(con); collapseButton.Text = "Collapse at Level"; radioGroup.AddView(collapseButton); advancedLinear2.AddView(radioGroup); editText = new EditText(con); editText.TextSize = 17; editText.TextAlignment = TextAlignment.Center; editText.Text = "1"; editText.SetTextColor(Color.ParseColor("#262626")); advancedLinear3.AddView(advancedLinear2); button1 = new Button (con); button1.Text = "Generate Excel"; button1.Click += OnButtonClicked; linear.AddView(button1); expandButton.Checked = true; switch1.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { if (switch1.Checked) { linear.RemoveView(button1); linear.AddView(advancedLinear3); linear.AddView(button1); } else { linear.RemoveView(advancedLinear3); } }; collapseButton.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { if (collapseButton.Checked) { linear.RemoveView(button1); linear.RemoveView(advancedLinear3); advancedLinear3.RemoveView(advancedLinear2); advancedLinear2.AddView(editText); advancedLinear3.AddView(advancedLinear2); linear.AddView(advancedLinear3); linear.AddView(button1); } else { linear.RemoveView(button1); linear.RemoveView(advancedLinear3); advancedLinear3.RemoveView(advancedLinear2); advancedLinear2.RemoveView(editText); advancedLinear3.AddView(advancedLinear2); linear.AddView(advancedLinear3); linear.AddView(button1); } }; return linear; } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; IWorkbook workbook = excelEngine.Excel.Workbooks.Create(1); IWorksheet worksheet = workbook.Worksheets[0]; IList<Brands> list = GetVehicleDetails(); ExcelImportDataOptions importDataOptions = new ExcelImportDataOptions(); importDataOptions.FirstRow = 4; if (spinner.SelectedItemPosition == 0) importDataOptions.NestedDataLayoutOptions = ExcelNestedDataLayoutOptions.Default; else if (spinner.SelectedItemPosition == 1) importDataOptions.NestedDataLayoutOptions = ExcelNestedDataLayoutOptions.Merge; else if (spinner.SelectedItemPosition == 2) importDataOptions.NestedDataLayoutOptions = ExcelNestedDataLayoutOptions.Repeat; if (switch1.Checked) { if (expandButton.Checked) { importDataOptions.NestedDataGroupOptions = ExcelNestedDataGroupOptions.Expand; } else if (collapseButton.Checked) { importDataOptions.NestedDataGroupOptions = ExcelNestedDataGroupOptions.Collapse; if (editText.Text != string.Empty) { importDataOptions.CollapseLevel = int.Parse(editText.Text); } } } worksheet.ImportData(list, importDataOptions); #region Define Styles IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle"); IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle"); pageHeader.Font.FontName = "Calibri"; pageHeader.Font.Size = 16; pageHeader.Font.Bold = true; pageHeader.Color = Syncfusion.Drawing.Color.FromArgb(0, 146, 208, 80); pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Font.Bold = true; tableHeader.Font.FontName = "Calibri"; tableHeader.Color = Syncfusion.Drawing.Color.FromArgb(0, 146, 208, 80); #endregion #region Apply Styles // Apply style for header worksheet["A1:C2"].Merge(); worksheet["A1"].Text = "Automobile Brands in the US"; worksheet["A1"].CellStyle = pageHeader; worksheet["A4:C4"].CellStyle = tableHeader; worksheet["A1:C1"].CellStyle.Font.Bold = true; worksheet.UsedRange.AutofitColumns(); #endregion MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("ImportData.xlsx", "application/msexcel", stream, m_context); } } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } #region Helper Methods private IList<Brands> GetVehicleDetails() { XmlSerializer deserializer = new XmlSerializer(typeof(BrandObjects)); string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExportData.xml"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); TextReader textReader = new StreamReader(fileStream); BrandObjects brands = (BrandObjects)deserializer.Deserialize(textReader); List<Brands> list = new List<Brands>(); string brandName = brands.BrandObject[0].BrandName; string vehicleType = brands.BrandObject[0].VahicleType; string modelName = brands.BrandObject[0].ModelName; Brands brand = new Brands(brandName); brand.VehicleTypes = new List<VehicleTypes>(); VehicleTypes vehicle = new VehicleTypes(vehicleType); vehicle.Models = new List<ModelObject>(); ModelObject model = new ModelObject(modelName); brand.VehicleTypes.Add(vehicle); list.Add(brand); foreach (BrandObject brandObj in brands.BrandObject) { if (brandName == brandObj.BrandName) { if (vehicleType == brandObj.VahicleType) { vehicle.Models.Add(new ModelObject(brandObj.ModelName)); continue; } else { vehicle = new VehicleTypes(brandObj.VahicleType); vehicle.Models = new List<ModelObject>(); vehicle.Models.Add(new ModelObject(brandObj.ModelName)); brand.VehicleTypes.Add(vehicle); vehicleType = brandObj.VahicleType; } continue; } else { brand = new Brands(brandObj.BrandName); vehicle = new VehicleTypes(brandObj.VahicleType); vehicle.Models = new List<ModelObject>(); vehicle.Models.Add(new ModelObject(brandObj.ModelName)); brand.VehicleTypes = new List<VehicleTypes>(); brand.VehicleTypes.Add(vehicle); vehicleType = brandObj.VahicleType; list.Add(brand); brandName = brandObj.BrandName; } } textReader.Close(); return list; } #endregion } #region Helper Class [XmlRootAttribute("BrandObjects")] public class BrandObjects { [XmlElement("BrandObject")] public BrandObject[] BrandObject { get; set; } } public class BrandObject { public string BrandName { get; set; } public string VahicleType { get; set; } public string ModelName { get; set; } } //[Serializable] public class Brands { private string m_brandName; [DisplayNameAttribute("Brand")] public string BrandName { get { return m_brandName; } set { m_brandName = value; } } private IList<VehicleTypes> m_vehicles; public IList<VehicleTypes> VehicleTypes { get { return m_vehicles; } set { m_vehicles = value; } } public Brands(string brandName) { m_brandName = brandName; } } public class VehicleTypes { private string m_vehicle; [DisplayNameAttribute("Vehicle Type")] public string Vehicle { get { return m_vehicle; } set { m_vehicle = value; } } private IList<ModelObject> m_models; public IList<ModelObject> Models { get { return m_models; } set { m_models = value; } } public VehicleTypes(string vehicle) { m_vehicle = vehicle; } } #endregion } <file_sep>/iOS/SampleBrowser/Samples/RadialMenu/CustomDrawing.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Drawing; using CoreGraphics; using UIKit; namespace SampleBrowser { public class LinePath { public int LineWidth { get; set; } public UIColor PenColor { get; set; } public UIBezierPath Path { get; set; } } public class CustomDrawing : UIView { List<LinePath> linePathCollection; UIColor penColor; // clear the canvas public void Clear() { path.Dispose(); linePathCollection.Clear(); path = new UIBezierPath(); canTouchDraw = false; SetNeedsDisplay(); } public CustomDrawing() { linePathCollection = new List<LinePath>(); this.Frame = new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height); path = new UIBezierPath(); this.PenColor = UIColor.Black; this.lineWidth = 8; this.BackgroundColor = UIColor.White; } public event EventHandler<EventArgs> Tapped; internal virtual void OnTapped(EventArgs args) { if (this.Tapped != null) this.Tapped(this, args); } private CGPoint touchLocation; private CGPoint prevTouchLocation; private bool canTouchDraw; private int lineWidth; UIBezierPath path; public int LineWidth { get { return lineWidth; } set { lineWidth = value; } } public UIColor PenColor { get { return penColor; } set { penColor = value; } } public override void TouchesBegan(Foundation.NSSet touches, UIEvent evt) { this.OnTapped(new EventArgs()); base.TouchesBegan(touches, evt); path = new UIBezierPath(); UITouch touch = touches.AnyObject as UITouch; this.canTouchDraw = true; this.touchLocation = touch.LocationInView(this); this.prevTouchLocation = touch.PreviousLocationInView(this); this.SetNeedsDisplay(); } public override void TouchesMoved(Foundation.NSSet touches, UIEvent evt) { base.TouchesMoved(touches, evt); UITouch touch = touches.AnyObject as UITouch; this.touchLocation = touch.LocationInView(this); this.prevTouchLocation = touch.PreviousLocationInView(this); this.SetNeedsDisplay(); } public override void TouchesEnded(Foundation.NSSet touches, UIEvent evt) { base.TouchesEnded(touches, evt); linePathCollection.Add(new LinePath() { PenColor = penColor, Path = path, LineWidth = lineWidth }); path.ClosePath(); } public override void Draw(CGRect rect) { //base.Draw(rect); if (this.canTouchDraw) { for (int i = 0; i < linePathCollection.Count; i++) { LinePath lPath = linePathCollection[i]; lPath.PenColor.SetStroke(); lPath.Path.LineWidth = lPath.LineWidth; lPath.Path.LineJoinStyle = CGLineJoin.Round; lPath.Path.LineCapStyle = CGLineCap.Round; lPath.Path.Stroke(); } penColor.SetStroke(); path.LineWidth = lineWidth; path.LineJoinStyle = CGLineJoin.Round; path.LineCapStyle = CGLineCap.Round; path.MoveTo(this.prevTouchLocation); path.AddLineTo(this.touchLocation); path.Stroke(); } } } } <file_sep>/Forms/Chart/Chart/Samples/Legend/LegendViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Xamarin.Forms; namespace SampleBrowser.SfChart { public class LegendViewModel { List<Color> colors; private List<Color> GetPieColors() { if (colors == null) { colors = new List<Color>(10) { Color.FromRgba(0, 189, 174, 255), Color.FromRgba(64, 64, 65, 255), Color.FromRgba(53, 124, 210, 255), Color.FromRgba(229, 101, 144, 255), Color.FromRgba(248, 184, 131, 255), Color.FromRgba(112, 173, 71, 255), Color.FromRgba(221, 138, 189, 255), Color.FromRgba(127, 132, 232, 255), Color.FromRgba(123, 180, 235, 255), Color.FromRgba(234, 122, 87, 255) }; } return colors; } public ObservableCollection<Model> Data { get; set; } int previousExplodeIndex = -1; int explodeIndex = 5; public int ExplodeIndex { get { return explodeIndex; } set { explodeIndex = value; if (previousExplodeIndex != -1) { Data[previousExplodeIndex].IsExploded = false; Data[previousExplodeIndex].LegendBackgroundColor = Color.Transparent; } if (explodeIndex != -1) { Data[explodeIndex].IsExploded = true; Data[explodeIndex].LegendBackgroundColor = GetPieColors()[explodeIndex].MultiplyAlpha(0.4); } previousExplodeIndex = explodeIndex; } } public LegendViewModel() { Data = new ObservableCollection<Model> { new Model("Labour", 28), new Model("Legal", 10), new Model("Production", 20), new Model("License", 15), new Model("Facilities", 23), new Model("Taxes", 17), new Model("Insurance", 12) }; } } public class Model : INotifyPropertyChanged { Color legendBackgroundColor; public Color LegendBackgroundColor { get { return legendBackgroundColor; } set { legendBackgroundColor = value; OnPropertyChanged("LegendBackgroundColor"); } } public string Name { get; set; } public double Value { get; set; } bool isExploded; public bool IsExploded { get { return isExploded; } set { isExploded = value; OnPropertyChanged("IsExploded"); } } public Model(String name, double value) { Name = name; Value = value; } void OnPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } public event PropertyChangedEventHandler PropertyChanged; } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/StockData.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; namespace SampleBrowser { public class StockData : INotifyPropertyChanged { #region Private Members private string symbol; private string account; private double lastTrade; private double stockChange; private double previousClose; private double open; private long volume; private string product; #endregion /// <summary> /// Gets or sets the Product. /// </summary> /// <value>The Product.</value> public string Product { get { return product; } set { product = value; RaisePropertyChanged("Product"); } } /// <summary> /// Gets or sets the stock change. /// </summary> /// <value>The stock change.</value> public double StockChange { get { return stockChange; } set { stockChange = value; RaisePropertyChanged ("StockChange"); } } /// <summary> /// Gets or sets the open. /// </summary> /// <value>The open.</value> public double Open { get { return open; } set { open = value; RaisePropertyChanged ("Open"); } } /// <summary> /// Gets or sets the last trade. /// </summary> /// <value>The last trade.</value> public double LastTrade { get { return lastTrade; } set { lastTrade = value; RaisePropertyChanged ("LastTrade"); } } /// <summary> /// Gets or sets the previous close. /// </summary> /// <value>The previous close.</value> public double PreviousClose { get { return previousClose; } set { previousClose = value; RaisePropertyChanged ("PreviousClose"); } } /// <summary> /// Gets or sets the symbol. /// </summary> /// <value>The symbol.</value> public string Symbol { get { return symbol; } set { symbol = value; RaisePropertyChanged ("Symbol"); } } /// <summary> /// Gets or sets the account. /// </summary> /// <value>The account.</value> public string Account { get { return account; } set { account = value; RaisePropertyChanged ("Account"); } } /// <summary> /// Gets or sets the volume. /// </summary> /// <value>The volume.</value> public long Volume { get { return volume; } set { volume = value; RaisePropertyChanged ("Volume"); } } /// <summary> /// Initializes the on. /// </summary> /// <param name="other">The other.</param> public void InitializeOn (StockData other) { this.Symbol = other.Symbol; this.LastTrade = other.LastTrade; this.StockChange = other.StockChange; this.PreviousClose = other.PreviousClose; this.Open = other.Open; this.Volume = other.Volume; this.Product = other.Product; } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged (string propertyName) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (propertyName)); } #endregion } } <file_sep>/Forms/ImageEditor/ImageEditor.Android/Renderers/CustomRenderers.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics.Drawables; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using CustomControls = SampleBrowser.SfImageEditor.CustomControls; using Xamarin.Forms; using Syncfusion.SfImageEditor.XForms; using Xamarin.Forms.Platform.Android; using Syncfusion.SfImageEditor.XForms.Droid; using SampleBrowser.SfImageEditor.Droid.Renderers; using Android.Support.V4.App; using Android; using Android.Content.PM; using System.Threading.Tasks; using System.IO; #if COMMONSB using Resource = SampleBrowser.Droid.Resource; #endif [assembly:ExportRenderer(typeof(CustomControls.CustomEditor), typeof(SampleBrowser.SfImageEditor.Droid.Renderers.CustomEditorRenderer))] [assembly:ExportRenderer(typeof(CustomControls.RoundedColorButton), typeof(SampleBrowser.SfImageEditor.Droid.Renderers.ColorButtonRenderer))] [assembly: ExportRenderer(typeof(CustomControls.CustomButton), typeof(SampleBrowser.SfImageEditor.Droid.Renderers.CustomButtonRenderer))] [assembly: Dependency(typeof(CustomImageView))] [assembly: ExportRenderer(typeof(CustomControls.CustomImageView),typeof(SampleBrowser.SfImageEditor.Droid.Renderers.CustomImageViewRenderer))] [assembly: ExportRenderer(typeof(SampleBrowser.SfImageEditor.CustomImageEditor), typeof(SampleBrowser.SfImageEditor.Droid.Renderers.CustomViewEditorRenderer))] namespace SampleBrowser.SfImageEditor.Droid.Renderers { public class CustomEditorRenderer : EditorRenderer { public CustomEditorRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Editor> e) { base.OnElementChanged(e); if (Control != null) { var element = (CustomControls.CustomEditor)e.NewElement; Control.Hint = element.WatermarkText; Control.Gravity = GravityFlags.Center; Control.SetHintTextColor(Color.White.ToAndroid()); GradientDrawable gd = new GradientDrawable(); float density = (float)Context.Resources.DisplayMetrics.Density; gd.SetCornerRadius(15 * density); gd.SetStroke(2, Color.LightGray.ToAndroid()); this.Control.SetBackground(gd); } } } public class ColorButtonRenderer : ButtonRenderer { public ColorButtonRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e) { base.OnElementChanged(e); if (Control != null) { var element = (CustomControls.RoundedColorButton)e.NewElement; GradientDrawable gd = new GradientDrawable(); gd.SetCornerRadius(30); gd.SetColor(element.BackgroundColor.ToAndroid()); this.Control.SetBackground(gd); } } } public class CustomButtonRenderer : ButtonRenderer { public CustomButtonRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e) { base.OnElementChanged(e); if (Control != null) { var element = (CustomControls.CustomButton)e.NewElement; GradientDrawable gd = new GradientDrawable(); gd.SetCornerRadius(0); gd.SetColor(element.BackgroundColor.ToAndroid()); this.Control.SetBackground(gd); } } } public class CustomImageViewRenderer:ImageRenderer { private static int PERMISSION_REQUEST_CODE = 200; string permission = Manifest.Permission.ReadExternalStorage; string writePermission = Manifest.Permission.WriteExternalStorage; static bool permissionEnabled = false; public CustomImageViewRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Image> e) { base.OnElementChanged(e); if (!permissionEnabled) { EnableReadWritePermission(); permissionEnabled = true; } } public void EnableReadWritePermission() { if (ActivityCompat.CheckSelfPermission(this.Context, permission) != Permission.Granted && ActivityCompat.CheckSelfPermission(this.Context, writePermission) != Permission.Granted) { ActivityCompat.RequestPermissions(this.Context as Activity, new String[] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage }, PERMISSION_REQUEST_CODE); } } } public class CustomViewEditorRenderer : SfImageEditorRenderer { internal static Context NativeContext; public CustomViewEditorRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Syncfusion.SfImageEditor.XForms.SfImageEditor> e) { base.OnElementChanged(e); NativeContext = this.Context; } } public class CustomImageView : ICustomViewDependencyService { public Context CustomContext { get; set; } public object GetCustomView(string imageName, object context) { ImageView view = new ImageView(CustomViewEditorRenderer.NativeContext); view.LayoutParameters = new ViewGroup.LayoutParams(200, 200); if (imageName == "Typogy1") view.SetImageResource(Resource.Drawable.Typogy1); else if (imageName == "Typogy2") view.SetImageResource(Resource.Drawable.Typogy2); else if (imageName == "Typogy3") view.SetImageResource(Resource.Drawable.Typogy3); else if (imageName == "Typogy4") view.SetImageResource(Resource.Drawable.Typogy4); else if (imageName == "Typogy5") view.SetImageResource(Resource.Drawable.Typogy5); else if (imageName == "Typogy6") view.SetImageResource(Resource.Drawable.Typogy6); return view; } public Task<Stream> GetImageSource(string uri) { return null; } } }<file_sep>/Forms/Maps/Maps/Samples/Drilldown/DrilldownViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace SampleBrowser.SfMaps { public class DrilldownViewModel { public DrilldownViewModel() { DataSource = new ObservableCollection<DrilldownModel>(); DataSource.Add(new DrilldownModel("Afghanistan", "Asia")); DataSource.Add(new DrilldownModel("Angola", "Africa")); DataSource.Add(new DrilldownModel("Albania", "Europe")); DataSource.Add(new DrilldownModel("United Arab Emirates", "Asia")); DataSource.Add(new DrilldownModel("Argentina", "South America")); DataSource.Add(new DrilldownModel("Armenia", "Asia")); DataSource.Add(new DrilldownModel("French Southern and Antarctic Lands", "Seven seas (open ocean)")); DataSource.Add(new DrilldownModel("Australia", "Australia")); DataSource.Add(new DrilldownModel("Austria", "Europe")); DataSource.Add(new DrilldownModel("Azerbaijan", "Asia")); DataSource.Add(new DrilldownModel("Burundi", "Africa")); DataSource.Add(new DrilldownModel("Belgium", "Europe")); DataSource.Add(new DrilldownModel("Benin", "Africa")); DataSource.Add(new DrilldownModel("Burkina Faso", "Africa")); DataSource.Add(new DrilldownModel("Bangladesh", "Asia")); DataSource.Add(new DrilldownModel("Bulgaria", "Europe")); DataSource.Add(new DrilldownModel("The Bahamas", "North America")); DataSource.Add(new DrilldownModel("Bosnia and Herzegovina", "Europe")); DataSource.Add(new DrilldownModel("Belarus", "Europe")); DataSource.Add(new DrilldownModel("Belize", "North America")); DataSource.Add(new DrilldownModel("Bolivia", "South America")); DataSource.Add(new DrilldownModel("Brazil", "South America")); DataSource.Add(new DrilldownModel("Brunei", "Asia")); DataSource.Add(new DrilldownModel("Bhutan", "Asia")); DataSource.Add(new DrilldownModel("Botswana", "Africa")); DataSource.Add(new DrilldownModel("Central African Republic", "Africa")); DataSource.Add(new DrilldownModel("Canada", "North America")); DataSource.Add(new DrilldownModel("Switzerland", "Europe")); DataSource.Add(new DrilldownModel("Chile", "South America")); DataSource.Add(new DrilldownModel("China", "Asia")); DataSource.Add(new DrilldownModel("Ivory Coast", "Africa")); DataSource.Add(new DrilldownModel("Cameroon", "Africa")); DataSource.Add(new DrilldownModel("Democratic Republic of the Congo", "Africa")); DataSource.Add(new DrilldownModel("Republic of Congo", "Africa")); DataSource.Add(new DrilldownModel("Colombia", "South America")); DataSource.Add(new DrilldownModel("Costa Rica", "North America")); DataSource.Add(new DrilldownModel("Cuba", "North America")); DataSource.Add(new DrilldownModel("Northern Cyprus", "Asia")); DataSource.Add(new DrilldownModel("Cyprus", "Asia")); DataSource.Add(new DrilldownModel("Czech Republic", "Europe")); DataSource.Add(new DrilldownModel("Germany", "Europe")); DataSource.Add(new DrilldownModel("Djibouti", "Africa")); DataSource.Add(new DrilldownModel("Denmark", "Europe")); DataSource.Add(new DrilldownModel("Dominican Republic", "North America")); DataSource.Add(new DrilldownModel("Algeria", "Africa")); DataSource.Add(new DrilldownModel("Ecuador", "South America")); DataSource.Add(new DrilldownModel("Egypt", "Africa")); DataSource.Add(new DrilldownModel("Eritrea", "Africa")); DataSource.Add(new DrilldownModel("Spain", "Europe")); DataSource.Add(new DrilldownModel("Estonia", "Europe")); DataSource.Add(new DrilldownModel("Ethiopia", "Africa")); DataSource.Add(new DrilldownModel("Finland", "Europe")); DataSource.Add(new DrilldownModel("Fiji", "Australia")); DataSource.Add(new DrilldownModel("Falkland Islands", "South America")); DataSource.Add(new DrilldownModel("France", "Europe")); DataSource.Add(new DrilldownModel("Gabon", "Africa")); DataSource.Add(new DrilldownModel("United Kingdom", "Europe")); DataSource.Add(new DrilldownModel("Georgia", "Asia")); DataSource.Add(new DrilldownModel("Ghana", "Africa")); DataSource.Add(new DrilldownModel("Guinea", "Africa")); DataSource.Add(new DrilldownModel("Gambia", "Africa")); DataSource.Add(new DrilldownModel("Guinea Bissau", "Africa")); DataSource.Add(new DrilldownModel("Equatorial Guinea", "Africa")); DataSource.Add(new DrilldownModel("Greece", "Europe")); DataSource.Add(new DrilldownModel("Greenland", "North America")); DataSource.Add(new DrilldownModel("Guatemala", "North America")); DataSource.Add(new DrilldownModel("Guyana", "South America")); DataSource.Add(new DrilldownModel("Honduras", "North America")); DataSource.Add(new DrilldownModel("Croatia", "Europe")); DataSource.Add(new DrilldownModel("Haiti", "North America")); DataSource.Add(new DrilldownModel("Hungary", "Europe")); DataSource.Add(new DrilldownModel("Indonesia", "Asia")); DataSource.Add(new DrilldownModel("India", "Asia")); DataSource.Add(new DrilldownModel("Ireland", "Europe")); DataSource.Add(new DrilldownModel("Iran", "Asia")); DataSource.Add(new DrilldownModel("Iraq", "Asia")); DataSource.Add(new DrilldownModel("Iceland", "Europe")); DataSource.Add(new DrilldownModel("Israel", "Asia")); DataSource.Add(new DrilldownModel("Italy", "Europe")); DataSource.Add(new DrilldownModel("Jamaica", "North America")); DataSource.Add(new DrilldownModel("Jordan", "Asia")); DataSource.Add(new DrilldownModel("Japan", "Asia")); DataSource.Add(new DrilldownModel("Kazakhstan", "Asia")); DataSource.Add(new DrilldownModel("Kenya", "Africa")); DataSource.Add(new DrilldownModel("Kyrgyzstan", "Asia")); DataSource.Add(new DrilldownModel("Cambodia", "Asia")); DataSource.Add(new DrilldownModel("South Korea", "Asia")); DataSource.Add(new DrilldownModel("Kosovo", "Europe")); DataSource.Add(new DrilldownModel("Kuwait", "Asia")); DataSource.Add(new DrilldownModel("Laos", "Asia")); DataSource.Add(new DrilldownModel("Lebanon", "Asia")); DataSource.Add(new DrilldownModel("Liberia", "Africa")); DataSource.Add(new DrilldownModel("Libya", "Africa")); DataSource.Add(new DrilldownModel("Sri Lanka", "Asia")); DataSource.Add(new DrilldownModel("Lesotho", "Africa")); DataSource.Add(new DrilldownModel("Lithuania", "Europe")); DataSource.Add(new DrilldownModel("Luxembourg", "Europe")); DataSource.Add(new DrilldownModel("Latvia", "Europe")); DataSource.Add(new DrilldownModel("Morocco", "Africa")); DataSource.Add(new DrilldownModel("Moldova", "Europe")); DataSource.Add(new DrilldownModel("Madagascar", "Africa")); DataSource.Add(new DrilldownModel("Mexico", "North America")); DataSource.Add(new DrilldownModel("Macedonia", "Europe")); DataSource.Add(new DrilldownModel("Mali", "Africa")); DataSource.Add(new DrilldownModel("Myanmar", "Asia")); DataSource.Add(new DrilldownModel("Montenegro", "Europe")); DataSource.Add(new DrilldownModel("Mongolia", "Asia")); DataSource.Add(new DrilldownModel("Mozambique", "Africa")); DataSource.Add(new DrilldownModel("Mauritania", "Africa")); DataSource.Add(new DrilldownModel("Malawi", "Africa")); DataSource.Add(new DrilldownModel("Malaysia", "Asia")); DataSource.Add(new DrilldownModel("Namibia", "Africa")); DataSource.Add(new DrilldownModel("New Caledonia", "Australia")); DataSource.Add(new DrilldownModel("Niger", "Africa")); DataSource.Add(new DrilldownModel("Nigeria", "Africa")); DataSource.Add(new DrilldownModel("Nicaragua", "North America")); DataSource.Add(new DrilldownModel("Netherlands", "Europe")); DataSource.Add(new DrilldownModel("Norway", "Europe")); DataSource.Add(new DrilldownModel("Nepal", "Asia")); DataSource.Add(new DrilldownModel("New Zealand", "Australia")); DataSource.Add(new DrilldownModel("Oman", "Asia")); DataSource.Add(new DrilldownModel("Pakistan", "Asia")); DataSource.Add(new DrilldownModel("Panama", "North America")); DataSource.Add(new DrilldownModel("Peru", "South America")); DataSource.Add(new DrilldownModel("Philippines", "Asia")); DataSource.Add(new DrilldownModel("Papua New Guinea", "Australia")); DataSource.Add(new DrilldownModel("Poland", "Europe")); DataSource.Add(new DrilldownModel("Puerto Rico", "North America")); DataSource.Add(new DrilldownModel("North Korea", "Asia")); DataSource.Add(new DrilldownModel("Portugal", "Europe")); DataSource.Add(new DrilldownModel("Paraguay", "South America")); DataSource.Add(new DrilldownModel("Palestine", "Asia")); DataSource.Add(new DrilldownModel("Qatar", "Asia")); DataSource.Add(new DrilldownModel("Romania", "Europe")); DataSource.Add(new DrilldownModel("Russia", "Asia")); DataSource.Add(new DrilldownModel("Rwanda", "Africa")); DataSource.Add(new DrilldownModel("Western Sahara", "Africa")); DataSource.Add(new DrilldownModel("Saudi Arabia", "Asia")); DataSource.Add(new DrilldownModel("Sudan", "Africa")); DataSource.Add(new DrilldownModel("South Sudan", "Africa")); DataSource.Add(new DrilldownModel("Senegal", "Africa")); DataSource.Add(new DrilldownModel("Solomon Islands", "Australia")); DataSource.Add(new DrilldownModel("Sierra Leone", "Africa")); DataSource.Add(new DrilldownModel("El Salvador", "North America")); DataSource.Add(new DrilldownModel("Somaliland", "Africa")); DataSource.Add(new DrilldownModel("Somalia", "Africa")); DataSource.Add(new DrilldownModel("Republic of Serbia", "Europe")); DataSource.Add(new DrilldownModel("Suriname", "South America")); DataSource.Add(new DrilldownModel("Slovakia", "Europe")); DataSource.Add(new DrilldownModel("Slovenia", "Europe")); DataSource.Add(new DrilldownModel("Sweden", "Europe")); DataSource.Add(new DrilldownModel("Swaziland", "Africa")); DataSource.Add(new DrilldownModel("Syria", "Asia")); DataSource.Add(new DrilldownModel("Chad", "Africa")); DataSource.Add(new DrilldownModel("Togo", "Africa")); DataSource.Add(new DrilldownModel("Thailand", "Asia")); DataSource.Add(new DrilldownModel("Tajikistan", "Asia")); DataSource.Add(new DrilldownModel("Turkmenistan", "Asia")); DataSource.Add(new DrilldownModel("East Timor", "Asia")); DataSource.Add(new DrilldownModel("Trinidad and Tobago", "North America")); DataSource.Add(new DrilldownModel("Tunisia", "Africa")); DataSource.Add(new DrilldownModel("Turkey", "Asia")); DataSource.Add(new DrilldownModel("Taiwan", "Asia")); DataSource.Add(new DrilldownModel("United Republic of Tanzania", "Africa")); DataSource.Add(new DrilldownModel("Uganda", "Africa")); DataSource.Add(new DrilldownModel("Ukraine", "Europe")); DataSource.Add(new DrilldownModel("Uruguay", "South America")); DataSource.Add(new DrilldownModel("United States of America", "North America")); DataSource.Add(new DrilldownModel("Uzbekistan", "Asia")); DataSource.Add(new DrilldownModel("Venezuela", "South America")); DataSource.Add(new DrilldownModel("Vietnam", "Asia")); DataSource.Add(new DrilldownModel("Vanuatu", "Australia")); DataSource.Add(new DrilldownModel("Yemen", "Asia")); DataSource.Add(new DrilldownModel("South Africa", "Africa")); DataSource.Add(new DrilldownModel("Zambia", "Africa")); DataSource.Add(new DrilldownModel("Zimbabwe", "Africa")); } public ObservableCollection<DrilldownModel> DataSource { get; set; } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Model/EmployeeDetails.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; namespace SampleBrowser { public class EmployeeDetails { public EmployeeDetails () { } #region private variables private List<string> EmployeeDates; private Random random = new Random (); #endregion #region GetEmployeeDetails public List<EmployeeInfo> GetEmployeeDetails (int count) { this.EmployeeDates = GetDateBetween (2000, 2014, count); List<EmployeeInfo> employeeDetails = new List<EmployeeInfo> (); for (int i = 1; i <= count; i++) { var ord = new EmployeeInfo () { EmployeeID = EmployeeID [random.Next (15)], Name = Customers [random.Next (15)], Age = Age [random.Next (10)], Company = Company [random.Next (10)], Title = Title [random.Next (10)], Salary = Salary [random.Next (13)], Bonus = Bonus [random.Next (7)], IsAvailable = ((i % random.Next (1, 10) > 5) ? true : false), DOJ = this.EmployeeDates [i - 1], ImageName = getImageName (random.Next (0, 2)), }; employeeDetails.Add (ord); } return employeeDetails; } #endregion private string getImageName (int index) { if (index == 0) return ("GIRL" + random.Next (1, 24) + ".png"); else return ("GUY" + random.Next (1, 24) + ".png"); } private List<string> GetDateBetween (int startYear, int endYear, int count) { List<string> date = new List<string> (); Random d = new Random (1); Random m = new Random (2); Random y = new Random (startYear); for (int i = 0; i < count; i++) { int year = y.Next (startYear, endYear); int month = m.Next (3, 13); int day = d.Next (1, 31); date.Add ((new DateTime (year, month, day)).ToString ()); } return date; } int[] EmployeeID = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; int[] Salary = new int[] { 256787, 34455, 445545, 234567, 78434555, 93455, 3456674, 34567457, 23424, 655676, 2252459, 34368, 125436, 90558, 648489, 5537383 }; string[] Company = new string[] { "ABC", "XYZ", "XXX", "YYY", "ZZZ", "ZXY", "KKK", "BCD", "XZY", "FDG", "BCA", "UTS", "KFI", "XXX", }; string[] Title = new string[] { "Manager ", "Recruiter", "Security", "Supervisor", "Admin", "Admin", "Assistant", "President", "Designer", "Manager", "Marketing", "Stocker", "Clerk" }; string[] Customers = new string[] { "Kyle", "Gina", "Irene", "Katie", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Brenda", "Danielle", "Fiona", "Howard", "Jack", "Larry", "Holly", "Jennifer", "Liz", "Pete", "Steve", "Vince", "Zeke" }; int[] Age = new int[] { 21, 34, 45, 21, 23, 25, 43, 32, 22, 44, 25, 47, 35, 37, 41 }; double[] Bonus = new double[] { 0.2, 0.3, 0.4, 0.1, 0.12, 0.13, 0.15, 0.18, 0.14, 0.6, 0.7 }; } } <file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/SalesInfoViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SalesInfoViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for SalesInfo class. /// </summary> public class SalesInfoViewModel : INotifyPropertyChanged { #region Field [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<SalesByDate> dailySalesDetails = null; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<object> selectedItems; #endregion #region Constructor /// <summary> /// Initializes a new instance of the SalesInfoViewModel class. /// </summary> public SalesInfoViewModel() { var salesInfoRepository = new SalesInfoRepository(); this.dailySalesDetails = salesInfoRepository.GetSalesDetailsByDay(60); this.SelectedItems = new ObservableCollection<object>(); this.SelectedItems.Add(this.DailySalesDetails[3]); } #endregion #region Event /// <summary> /// Event that is fired when the property in this class is changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region ItemsSource /// <summary> /// Gets or sets the value of DailySalesDetails /// </summary> public ObservableCollection<SalesByDate> DailySalesDetails { get { return this.dailySalesDetails; } set { this.dailySalesDetails = value; } } /// <summary> /// Gets or sets the value of SelectedItems /// </summary> public ObservableCollection<object> SelectedItems { get { return this.selectedItems; } set { this.selectedItems = value; this.RaisePropertyChnaged("SelectedItems"); } } /// <summary> /// Method that is called when the property in this class is changed. /// </summary> /// <param name="name">Property name</param> public void RaisePropertyChnaged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } } <file_sep>/Forms/DocIO/DocIO/Samples/BuiltInStyle/BuiltInStyle.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using SampleBrowser.Core; using Syncfusion.DocIO.DLS; using System; using System.IO; using Xamarin.Forms; namespace SampleBrowser.DocIO { public partial class BuiltInStyle : SampleView { public BuiltInStyle() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { //if (!SampleBrowser.DocIO.App.isUWP) //{ // this.Content_1.FontSize = 18.5; //} //else //{ this.Content_1.FontSize = 13.5; //} this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { // Creating a new document. WordDocument document = new WordDocument(); WSection section = document.AddSection() as WSection; //Set Margin of the section section.PageSetup.Margins.All = 72; WParagraph para = section.AddParagraph() as WParagraph; section.AddColumn(100, 100); section.AddColumn(100, 100); section.MakeColumnsEqual(); #region Built-in styles # region List Style //List //para = section.AddParagraph() as WParagraph; para.AppendText("This para is written with style List").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.List); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //List5 style para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style List5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.List5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region ListNumber Style //List Number style para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListNumber").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListNumber); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //List Number5 style para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListNumber5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListNumber5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region TOA Heading Style //TOA Heading para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style TOA Heading").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ToaHeading); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion para = section.AddParagraph() as WParagraph; section.BreakCode = SectionBreakCode.NewColumn; # region ListBullet Style //ListBullet para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListBullet").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListBullet); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //ListBullet5 para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListBullet5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListBullet5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region List Continue Style //ListContinue para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListContinue").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListContinue); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //ListContinue5 para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListContinue5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListContinue5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region HTMLSample Style //HtmlSample para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style HtmlSample").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.HtmlSample); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion section = document.AddSection() as WSection; section.BreakCode = SectionBreakCode.NoBreak; # region Document Map Style //Docuemnt Map para = section.AddParagraph() as WParagraph; para.AppendText("This para is written with style DocumentMap\n").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.DocumentMap); IWTextRange textrange = para.AppendText("Google Chrome\n"); textrange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; textrange = para.AppendText("Mozilla Firefox\n"); textrange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; textrange = para.AppendText("Internet Explorer"); textrange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; #endregion # region Heading Styles //Heading Styles para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading1); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading2); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading3); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading4); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading5); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading6); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading7); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading8); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading9); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); # endregion #endregion Built-in styles #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("WordDocument_BuiltInStyles.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("WordDocument_BuiltInStyles.docx", "application/msword", stream); #endregion } } } <file_sep>/Android/SampleBrowser/Samples/Calendar/InlineEvents.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Calendar; using Com.Syncfusion.Calendar.Enums; using Java.Util; using Android.Graphics; namespace SampleBrowser { public class InlineEvents : SamplePage, IDisposable { /********************************* **Local Variable Inizialisation** *********************************/ private List<Calendar> startTimeCollection, endTimeCollection; private List<String> subjectCollection, colorCollection; private CalendarEventCollection appointmentCollection; private FrameLayout mainView; private SfCalendar calendar; public override View GetSampleContent(Context context) { /************ **Calendar** ************/ calendar = new SfCalendar(context); calendar.ViewMode = ViewMode.MonthView; calendar.ShowEventsInline = true; GetAppointments(); calendar.DataSource = appointmentCollection; calendar.HeaderHeight = 100; //Month View Settings MonthViewLabelSetting labelSettings = new MonthViewLabelSetting(); labelSettings.DateLabelSize = 14; MonthViewSettings monthViewSettings = new MonthViewSettings(); monthViewSettings.MonthViewLabelSetting = labelSettings; monthViewSettings.SelectedDayTextColor = Color.Black; monthViewSettings.TodayTextColor = Color.ParseColor("#1B79D6"); monthViewSettings.InlineBackgroundColor = Color.ParseColor("#E4E8ED"); monthViewSettings.WeekDayBackgroundColor = Color.ParseColor("#F7F7F7"); calendar.MonthViewSettings = monthViewSettings; //Main View mainView = new FrameLayout(context); mainView.AddView(calendar); return mainView; } /*********************************************************** **Creating appointments for ScheduleAppointmentCollection** ***********************************************************/ private void GetAppointments() { appointmentCollection = new CalendarEventCollection(); SetColors(); SetSubjects(); SetStartTime(); SetEndTime(); for (int i = 0; i < 15; i++) { CalendarInlineEvent appointment = new CalendarInlineEvent(); appointment.Color = Color.ParseColor(colorCollection[i]); appointment.Subject = subjectCollection[i]; appointment.StartTime = startTimeCollection[i]; appointment.EndTime = endTimeCollection[i]; appointmentCollection.Add(appointment); } } /****************************** **Adding Subjects Collection** ******************************/ private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); } /**************************** **Adding Colors Collection** ****************************/ private void SetColors() { colorCollection = new List<String>(); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FF339933"); colorCollection.Add("#FF00ABA9"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF339933"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF00ABA9"); } /******************************* **Adding StartTime Collection** *******************************/ private void SetStartTime() { startTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; for (int i = 0; i < 5; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, 3, 0, 0); startTimeCollection.Add(startTime); } for (int i = 0; i < 5; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, 11, 0, 0); startTimeCollection.Add(startTime); } for (int i = 10; i < 20; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, 17, 0, 0); startTimeCollection.Add(startTime); } } /***************************** **Adding EndTime Collection** *****************************/ private void SetEndTime() { endTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; for (int i = 0; i < 5; i++) { Calendar endTime = (Calendar)currentDate.Clone(); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, 5, 0, 0); endTimeCollection.Add(endTime); } for (int i = 0; i < 5; i++) { Calendar endTime = (Calendar)currentDate.Clone(); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, 12, 0, 0); endTimeCollection.Add(endTime); } for (int i = 10; i < 20; i++) { Calendar endTime = (Calendar)currentDate.Clone(); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, 18, 0, 0); endTimeCollection.Add(endTime); } } public void Dispose() { if (calendar != null) { calendar.Dispose(); calendar = null; } if (mainView != null) { mainView.Dispose(); mainView = null; } } } }<file_sep>/Forms/DataForm/DataForm/Samples/DynamicFormPage/Model/OrganizationForm.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.DataForm; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Text; using Xamarin.Forms.Internals; using System.ComponentModel.DataAnnotations; namespace SampleBrowser.SfDataForm { /// <summary> /// Represents the Organization information of the data form dynamicforms sample. /// </summary> [Preserve(AllMembers = true)] public class OrganizationForm : INotifyPropertyChanged { #region Fields /// <summary> /// Represents the name of the organization form information. /// </summary> private string organizationName; /// <summary> /// Represents the first address line of the organization form information. /// </summary> private string addressline1; /// <summary> /// Represents the second address line of the organization form information. /// </summary> private string addressline2; /// <summary> /// Represents the country of the organization form information. /// </summary> private string organizationCountry; /// <summary> /// Represents the city of the organization form information. /// </summary> private string organizationCity; /// <summary> /// Represents the zip of the organization form information. /// </summary> private string zip; /// <summary> /// Represents the code of the organization form information. /// </summary> private string code; /// <summary> /// Represents the phone of the organization form information. /// </summary> private string phone; /// <summary> /// Represents the contact email of the organization form information. /// </summary> private string contactemail; #endregion public OrganizationForm() { } /// <summary> /// Represents the method that will handle when a property is changed on a component. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the organization name field. /// </summary> [Display(ShortName = "Organization name")] public string OrganizationName { get { return this.organizationName; } set { this.organizationName = value; this.RaisePropertyChanged("OrganizationName"); } } /// <summary> /// Gets or sets the first address line field. /// </summary> [Display(ShortName = "Address line 1")] [DataType(DataType.MultilineText)] public string AddressLine1 { get { return this.addressline1; } set { this.addressline1 = value; this.RaisePropertyChanged("AddressLine1"); } } /// <summary> /// Gets or sets the second address line field. /// </summary> [Display(ShortName = "Address line 2")] [DataType(DataType.MultilineText)] public string AddressLine2 { get { return this.addressline2; } set { this.addressline2 = value; this.RaisePropertyChanged("AddressLine2"); } } /// <summary> /// Gets or sets the city field. /// </summary> [DisplayOptions(ColumnSpan = 2)] [Display(ShortName = "City")] public string OrganizationCity { get { return this.organizationCity; } set { this.organizationCity = value; this.RaisePropertyChanged("OrganizationCity"); } } /// <summary> /// Gets or sets the zip field. /// </summary> [DisplayOptions(ColumnSpan = 2)] [DataType(DataType.PhoneNumber)] public string Zip { get { return this.zip; } set { this.zip = value; this.RaisePropertyChanged("Zip"); } } /// <summary> /// Gets or sets the country field. /// </summary> [Display(ShortName = "Country")] public string OrganizationCountry { get { return this.organizationCountry; } set { this.organizationCountry = value; this.RaisePropertyChanged("OrganizationCountry"); } } /// <summary> /// Gets or sets the code field. /// </summary> [DisplayOptions(ColumnSpan = 2)] [DataType(DataType.PhoneNumber)] public string Code { get { return this.code; } set { this.code = value; this.RaisePropertyChanged("Code"); } } /// <summary> /// Gets or sets the phone field. /// </summary> [DisplayOptions(ColumnSpan = 2)] [Display(ShortName = "Phone")] [DataType(DataType.PhoneNumber)] public string Phone { get { return this.phone; } set { this.phone = value; this.RaisePropertyChanged("Phone"); } } /// <summary> /// Gets or sets the contact email field. /// </summary> [Display(ShortName = "Contact email")] public string ContactEmail { get { return this.contactemail; } set { this.contactemail = value; this.RaisePropertyChanged("ContactEmail"); } } #endregion /// <summary> /// Occurs when propery value is changed. /// </summary> /// <param name="propName">Property name</param> private void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Paging.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.SfDataGrid; using Syncfusion.SfDataGrid.DataPager; using System.Globalization; namespace SampleBrowser { public class Paging:SamplePage { SfDataGrid sfGrid; PagingViewModel viewModel; SfDataPager sfDataPager; public override Android.Views.View GetSampleContent(Android.Content.Context context) { sfDataPager = new SfDataPager(context); sfGrid = new SfDataGrid(context); sfGrid.SelectionMode = SelectionMode.Single; viewModel = new PagingViewModel(); sfDataPager.PageSize = 15; sfDataPager.Source = viewModel.OrdersInfo; sfDataPager.NumericButtonCount = 20; sfGrid.AutoGeneratingColumn += GridGenerateColumns; sfGrid.ItemsSource = sfDataPager.PagedSource; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; linearLayout.AddView(sfDataPager, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)SfDataGridHelpers.ConvertDpToPixels(this.sfGrid, 75))); linearLayout.AddView(sfGrid); return linearLayout; } void GridGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo("en-US"); e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "Last Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ShippingDate") { e.Column.HeaderText = "Shipping Date"; e.Column.Format = "d"; } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextAlignment = GravityFlags.CenterVertical; } } public override void Destroy() { sfGrid.AutoGeneratingColumn -= GridGenerateColumns; sfGrid.Dispose(); sfGrid = null; viewModel = null; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/PullToRefresh/WeatherModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Foundation; namespace SampleBrowser { public class WeatherModel { public WeatherModel(NSString date,NSString type, NSString temp,NSString day) { Date = date; Day = day; Type = type; Temp = temp; } internal NSString Date; internal NSString Day; internal NSString Type; internal NSString Temp; } } <file_sep>/Android/SampleBrowser/Samples/Presentation/PPTXToPDF.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.PresentationRenderer; using Syncfusion.Pdf; namespace SampleBrowser { public partial class PPTXToPDF : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to convert a PowerPoint presentation to PDF."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Input Template"; button1.Click += OnInpTemplateButtonClicked; linear.AddView(button1); Button button2 = new Button(con); button2.Text = "Convert"; button2.Click += OnButtonClicked; linear.AddView(button2); return linear; } void OnInpTemplateButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Template.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); fileStream.Dispose(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("InputTemplate.pptx", "application/powerpoint", stream, m_context); } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Template.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a existing PowerPoint Presentation. IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Convert the PowerPoint document to PDF document. PdfDocument pdfDocument = PresentationToPdfConverter.Convert(presentation); MemoryStream pdfStream = new MemoryStream(); //Save the converted PDF document into MemoryStream. pdfDocument.Save(pdfStream); pdfStream.Position = 0; //Close the PDF document. pdfDocument.Close(true); //Close the PowerPoint Presentation. presentation.Close(); if (pdfStream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("PPTXToPDF.pdf", "application/pdf", pdfStream, m_context); } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/ZoomingAndPanning.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Android.Graphics; namespace SampleBrowser { public class ZoomingandPanning : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "Height vs Weight"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.ColorModel.ColorPalette = ChartColorPalette.Natural; NumericalAxis primariyAxis = new NumericalAxis(); primariyAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; primariyAxis.ShowMajorGridLines = false; primariyAxis.Minimum = 100; primariyAxis.Maximum = 220; primariyAxis.Interval = 20; primariyAxis.Title.Text = "Height in Inches"; chart.PrimaryAxis = primariyAxis; NumericalAxis secondaryAxis = new NumericalAxis(); secondaryAxis.ShowMajorGridLines = false; secondaryAxis.Minimum = 50; secondaryAxis.Maximum = 80; secondaryAxis.Interval = 5; secondaryAxis.Title.Text = "Weight in Pounds"; chart.SecondaryAxis = secondaryAxis; ScatterSeries scatter = new ScatterSeries(); scatter.Alpha = 0.7f; scatter.ScatterWidth = 12; scatter.ScatterHeight = 12; scatter.ItemsSource = MainPage.GetScatterMaleData(); scatter.XBindingPath = "XValue"; scatter.YBindingPath = "YValue"; scatter.Label = "Male"; scatter.LegendIcon = ChartLegendIcon.SeriesType; scatter.EnableAnimation = true; ScatterSeries scatter1 = new ScatterSeries(); scatter1.Alpha = 0.7f; scatter1.ScatterWidth = 12; scatter1.ScatterHeight = 12; scatter1.ShapeType = ChartScatterShapeType.Diamond; scatter1.ItemsSource = MainPage.GetScatterFemaleData(); scatter1.XBindingPath = "XValue"; scatter1.YBindingPath = "YValue"; scatter1.Label = "Female"; scatter1.LegendIcon = ChartLegendIcon.SeriesType; scatter1.EnableAnimation = true; chart.Series.Add(scatter); chart.Series.Add(scatter1); chart.Behaviors.Add(new ChartZoomPanBehavior { SelectionZoomingEnabled = true, SelectionRectStrokeWidth = 1 }); var label = new TextView(context); label.SetPadding(5, 5, 5, 5); label.Text = "Pinch to zoom or double tap and drag to select a region to zoom in."; var layout = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Vertical }; var layoutLabel = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Horizontal, LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent) }; layoutLabel.SetHorizontalGravity(GravityFlags.CenterHorizontal); layoutLabel.AddView(label); layout.AddView(layoutLabel); layout.AddView(chart); return layout; } public override void OnApplyChanges() { base.OnApplyChanges(); } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/Polar.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Com.Syncfusion.Navigationdrawer; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class Polar : SamplePage { SfChart chart; List<String> polarAngleMode; NumericalAxis secondaryAxis; PolarSeries polarSeries1; PolarSeries polarSeries2; PolarSeries polarSeries3; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Average Sales Comparison"; chart.Title.TextSize = 15; chart.Legend.Visibility = Visibility.Visible; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.ToggleSeriesVisibility = true; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; chart.PrimaryAxis = new CategoryAxis(); secondaryAxis = new NumericalAxis(); secondaryAxis.LabelStyle.LabelFormat = "#'M'"; chart.SecondaryAxis = secondaryAxis; polarSeries1 = new PolarSeries(); polarSeries1.TooltipEnabled = true; polarSeries1.EnableAnimation = true; polarSeries1.StrokeWidth = 3; polarSeries1.PathEffect = new DashPathEffect(new float[] { 4, 6 }, 0); polarSeries1.Label = "Product A"; polarSeries1.Closed = true; polarSeries1.DrawType = PolarChartDrawType.Area; polarSeries1.Alpha = 0.5f; polarSeries1.ItemsSource = MainPage.GetPolarData1(); polarSeries1.XBindingPath = "XValue"; polarSeries1.YBindingPath = "YValue"; chart.Series.Add(polarSeries1); polarSeries2 = new PolarSeries(); polarSeries2.TooltipEnabled = true; polarSeries2.EnableAnimation = true; polarSeries2.StrokeWidth = 3; polarSeries2.PathEffect = new DashPathEffect(new float[] { 4, 6 }, 0); polarSeries2.Label = "Product B"; polarSeries2.Closed = true; polarSeries2.DrawType = PolarChartDrawType.Area; polarSeries2.Alpha = 0.5f; polarSeries2.ItemsSource = MainPage.GetPolarData2(); polarSeries2.XBindingPath = "XValue"; polarSeries2.YBindingPath = "YValue"; chart.Series.Add(polarSeries2); polarSeries3 = new PolarSeries(); polarSeries3.XBindingPath = "XValue"; polarSeries3.YBindingPath = "YValue"; polarSeries3.EnableAnimation = true; polarSeries3.StrokeWidth = 3; polarSeries3.PathEffect = new DashPathEffect(new float[] { 4, 6 }, 0); polarSeries3.TooltipEnabled = true; polarSeries3.Label = "Product C"; polarSeries3.Closed = true; polarSeries3.DrawType = PolarChartDrawType.Area; polarSeries3.Alpha = 0.5f; polarSeries3.ItemsSource = MainPage.GetPolarData3(); chart.Series.Add(polarSeries3); return chart; } private void SelectLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = polarAngleMode[e.Position]; if (selectedItem.Equals("Rotate 0")) { secondaryAxis.PolarAngle = ChartPolarAngle.Rotate0; } else if (selectedItem.Equals("Rotate 90")) { secondaryAxis.PolarAngle = ChartPolarAngle.Rotate90; } else if (selectedItem.Equals("Rotate 180")) { secondaryAxis.PolarAngle = ChartPolarAngle.Rotate180; } else if (selectedItem.Equals("Rotate 270")) { secondaryAxis.PolarAngle = ChartPolarAngle.Rotate270; } } public override View GetPropertyWindowLayout(Android.Content.Context context) { /** * Property Window * */ int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; LinearLayout propertylayout = new LinearLayout(context); //= new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams( width * 2, 5); layoutParams1.SetMargins(0, 20, 0, 0); TextView drawType = new TextView(context); drawType.TextSize = 20; drawType.Text = "Draw Type"; drawType.SetPadding(5, 20, 0, 20); TextView polarAngle = new TextView(context); polarAngle.TextSize = 20; polarAngle.Text = "Angle"; polarAngle.SetPadding(5, 20, 0, 20); Spinner selectLabelMode = new Spinner(context, SpinnerMode.Dialog); polarAngleMode = new List<String>() { "Rotate 0", "Rotate 90", "Rotate 180", "Rotate 270" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, polarAngleMode); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += SelectLabelMode_ItemSelected; Spinner selectDrawType = new Spinner(context, SpinnerMode.Dialog); List<String> adapter = new List<String>() { "Area", "Line"}; ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectDrawType.Adapter = dataAdapter1; selectDrawType.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter1.GetItem(e.Position); if (selectedItem.Equals("Area")) { polarSeries1.DrawType = PolarChartDrawType.Area; polarSeries2.DrawType = PolarChartDrawType.Area; polarSeries3.DrawType = PolarChartDrawType.Area; } else if (selectedItem.Equals("Line")) { polarSeries1.DrawType = PolarChartDrawType.Line; polarSeries2.DrawType = PolarChartDrawType.Line; polarSeries3.DrawType = PolarChartDrawType.Line; } }; SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); propertylayout.AddView(drawType); propertylayout.AddView(selectDrawType); propertylayout.AddView(polarAngle); propertylayout.AddView(selectLabelMode); propertylayout.AddView(separate, layoutParams1); return propertylayout; } } }<file_sep>/Android/SampleBrowser/Samples/TabView/TabViewGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; namespace SampleBrowser { internal class TabViewGettingStarted : SamplePage { Spinner DisplayModeSpinner, TabPositionSpinner, SelectionIndicatorSpinner; Context context1; TextView ModeText, PositionText, SelectionIndicatorText; ArrayAdapter<String> dataAdapter,dataAdapter1; private TabControl tabControl; public override View GetSampleContent(Context context) { tabControl = new TabControl(context); return tabControl; } public override View GetPropertyWindowLayout(Context context) { context1 = context; DisplayModeLayout(); TabPositionLayout(); SelectionIndicatorLayout(); LinearLayout propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; //if(IsTabletDevice(context)) //{ ModeText.SetPadding(0,0,0,40); DisplayModeSpinner.SetPadding(0,0,0,50); PositionText.SetPadding(0, 40, 0, 40); TabPositionSpinner.SetPadding(0, 0, 0, 50); SelectionIndicatorText.SetPadding(0, 40, 0, 40); SelectionIndicatorSpinner.SetPadding(0, 0, 0, 50); // } propertylayout.AddView(ModeText); propertylayout.AddView(DisplayModeSpinner); propertylayout.SetPadding(10, 10, 10, 40); propertylayout.AddView(PositionText); propertylayout.AddView(TabPositionSpinner); propertylayout.SetPadding(10, 10, 10, 40); propertylayout.AddView(SelectionIndicatorText); propertylayout.AddView(SelectionIndicatorSpinner); return propertylayout; } public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = Math.Sqrt(Math.Pow(screenWidth, 2) + Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } private void TabPositionLayout() { PositionText = new TextView(context1); PositionText.TextSize = 20; PositionText.Text = "Tab Position"; TabPositionSpinner = new Spinner(context1, SpinnerMode.Dialog); List<String> TabPostionList = new List<String>(); TabPostionList.Add("Top"); TabPostionList.Add("Bottom"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context1, Android.Resource.Layout.SimpleSpinnerItem, TabPostionList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); TabPositionSpinner.Adapter = dataAdapter; //Mode Spinner Item Selected Listener TabPositionSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Top")) { tabControl.TabHeaderPosition = Syncfusion.Android.TabView.TabHeaderPosition.Top; } if (selectedItem.Equals("Bottom")) { tabControl.TabHeaderPosition = Syncfusion.Android.TabView.TabHeaderPosition.Bottom; } }; } private void SelectionIndicatorLayout() { SelectionIndicatorText = new TextView(context1); SelectionIndicatorText.TextSize = 20; SelectionIndicatorText.Text = "SelectionIndicator Position"; SelectionIndicatorSpinner = new Spinner(context1, SpinnerMode.Dialog); List<String> SelectionIndicatorList = new List<String>(); SelectionIndicatorList.Add("Top"); SelectionIndicatorList.Add("Bottom"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context1, Android.Resource.Layout.SimpleSpinnerItem, SelectionIndicatorList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); SelectionIndicatorSpinner.Adapter = dataAdapter; //Mode Spinner Item Selected Listener SelectionIndicatorSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Top")) { tabControl.SelectionIndicatorSettings.Position = Syncfusion.Android.TabView.SelectionIndicatorPosition.Top; } if (selectedItem.Equals("Bottom")) { tabControl.SelectionIndicatorSettings.Position = Syncfusion.Android.TabView.SelectionIndicatorPosition.Bottom; } }; } private void DisplayModeLayout() { ModeText = new TextView(context1); ModeText.TextSize = 20; ModeText.Text = "Display Mode"; DisplayModeSpinner = new Spinner(context1, SpinnerMode.Dialog); //View Mode List List<String> DisplayModeList = new List<String>(); DisplayModeList.Add("Text"); DisplayModeList.Add("Image"); DisplayModeList.Add("NoHeader"); DisplayModeList.Add("ImageWithText"); //Data Adapter dataAdapter1 = new ArrayAdapter<String>(context1, Android.Resource.Layout.SimpleSpinnerItem, DisplayModeList); dataAdapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); DisplayModeSpinner.Adapter = dataAdapter1; //Mode Spinner Item Selected Listener DisplayModeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter1.GetItem(e.Position); if (selectedItem.Equals("Text")) { tabControl.DisplayMode = Syncfusion.Android.TabView.TabDisplayMode.Text; } if (selectedItem.Equals("Image")) { tabControl.DisplayMode = Syncfusion.Android.TabView.TabDisplayMode.Image; } if (selectedItem.Equals("NoHeader")) { tabControl.DisplayMode = Syncfusion.Android.TabView.TabDisplayMode.NoHeader; } if (selectedItem.Equals("ImageWithText")) { tabControl.DisplayMode = Syncfusion.Android.TabView.TabDisplayMode.ImageWithText; } }; } public override void OnApplyChanges() { base.OnApplyChanges(); tabControl.ApplyChanges(); } } }<file_sep>/iOS/SampleBrowser/Samples/Presentation/CreateAnimationPresentation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Presentation; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class CreateAnimationPresentation : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; public CreateAnimationPresentation() { label1 = new UILabel(); label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to create a animation in PowerPoint presentation."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width , 50); } else { label.Frame = new CGRect (frameRect.Location.X, 5, frameRect.Size.Width , 70); } this.AddSubview (label); button.SetTitle("Generate Presentation",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect (0, 65, frameRect.Location.X + frameRect.Size.Width , 10); } else { button.Frame = new CGRect (frameRect.Location.X, 70, frameRect.Size.Width , 10); } this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Animation.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Presentation.Open(fileStream); //Modify the existing animation CreateAnimationWithShape(presentation); MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("CreateAnimationSample.pptx", "application/mspowerpoint", stream); } } # region Create Animation private void CreateAnimationWithShape(IPresentation presentation) { //Get the slide from the presentation ISlide slide = presentation.Slides[0]; //Access the animation sequence to create effects ISequence sequence = slide.Timeline.MainSequence; //Add motion path effect to the shape IEffect line1 = sequence.AddEffect(slide.Shapes[8] as IShape, EffectType.PathUp, EffectSubtype.None, EffectTriggerType.OnClick); IMotionEffect motionEffect = line1.Behaviors[0] as IMotionEffect; motionEffect.Timing.Duration = 1f; IMotionPath motionPath = motionEffect.Path; motionPath[1].Points[0].X = 0.00365f; motionPath[1].Points[0].Y = -0.27431f; //Add motion path effect to the shape IEffect line2 = sequence.AddEffect(slide.Shapes[3] as IShape, EffectType.PathDown, EffectSubtype.None, EffectTriggerType.WithPrevious); motionEffect = line2.Behaviors[0] as IMotionEffect; motionEffect.Timing.Duration = 0.75f; motionPath = motionEffect.Path; motionPath[1].Points[0].X = 0.00234f; motionPath[1].Points[0].Y = 0.43449f; //Add wipe effect to the shape IEffect wipe1 = sequence.AddEffect(slide.Shapes[1] as IShape, EffectType.Wipe, EffectSubtype.None, EffectTriggerType.AfterPrevious); wipe1.Behaviors[1].Timing.Duration = 1f; //Add fly effect to the shape IEffect fly1 = sequence.AddEffect(slide.Shapes[5] as IShape, EffectType.Fly, EffectSubtype.Left, EffectTriggerType.AfterPrevious); fly1.Behaviors[1].Timing.Duration = 0.70f; fly1.Behaviors[2].Timing.Duration = 0.70f; ////Add wipe effect to the shape IEffect wipe2 = sequence.AddEffect(slide.Shapes[2] as IShape, EffectType.Wipe, EffectSubtype.None, EffectTriggerType.AfterPrevious); wipe2.Behaviors[1].Timing.Duration = 1f; ////Add fly effect to the shape IEffect fly2 = sequence.AddEffect(slide.Shapes[4] as IShape, EffectType.Fly, EffectSubtype.Right, EffectTriggerType.AfterPrevious); fly2.Behaviors[1].Timing.Duration = 0.70f; fly2.Behaviors[2].Timing.Duration = 0.70f; IEffect fly3 = sequence.AddEffect(slide.Shapes[6] as IShape, EffectType.Fly, EffectSubtype.Top, EffectTriggerType.AfterPrevious); fly3.Behaviors[1].Timing.Duration = 1.50f; fly3.Behaviors[2].Timing.Duration = 1.50f; ////Add flay effect to the shape IEffect fly4 = sequence.AddEffect(slide.Shapes[7] as IShape, EffectType.Fly, EffectSubtype.Left, EffectTriggerType.AfterPrevious); fly4.Behaviors[1].Timing.Duration = 0.50f; fly4.Behaviors[2].Timing.Duration = 0.50f; } #endregion public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/ViewModel/FilterOptionsTableSource.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; using UIKit; namespace SampleBrowser { public class FilterOptionsTableSource : UITableViewSource { public List<string> tableItems; string cellIdentifier = "TableCell"; string[] keys = new string[] { }; public string selecteditem = null; public FilterOptionsTableSource(List<string> items) { tableItems = items; keys = new string[] { "Filter Condition Type" }; } public override nint RowsInSection(UITableView tableview, nint section) { return tableItems.Count; } public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier); // if there are no cells to reuse, create a new one if (cell == null) cell = new UITableViewCell(UITableViewCellStyle.Subtitle, cellIdentifier); cell.TextLabel.Text = tableItems[indexPath.Row]; cell.SelectionStyle = UITableViewCellSelectionStyle.Blue; return cell; } public override void WillDisplay(UITableView tableView, UITableViewCell cell, Foundation.NSIndexPath indexPath) { if (cell.Selected) { cell.BackgroundColor = UIColor.Red; } } public override nint NumberOfSections(UITableView tableView) { return keys.Length; } public override void RowSelected(UITableView tableView, Foundation.NSIndexPath indexPath) { selecteditem = tableItems[indexPath.Row]; } public override string TitleForHeader(UITableView tableView, nint section) { return keys[section]; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/GettingStartedModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GettingStartedModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties and notifies clients that a property value has changed. /// </summary> public class GettingStartedModel : INotifyPropertyChanged { #region Private Members [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string team; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string location; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int wins; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int losses; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string image; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double pct; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double gb; #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public properties /// <summary> /// Gets or sets the Team. /// </summary> /// <value>The Team.</value> public string Team { get { return this.team; } set { this.team = value; this.RaisePropertyChanged("Team"); } } /// <summary> /// Gets or sets the PCT. /// </summary> /// <value>The PCT.</value> public double PCT { get { return this.pct; } set { this.pct = value; this.RaisePropertyChanged("PCT"); } } /// <summary> /// Gets or sets the GB. /// </summary> /// <value>The GB.</value> public double GB { get { return this.gb; } set { this.gb = value; this.RaisePropertyChanged("GB"); } } /// <summary> /// Gets or sets the Wins. /// </summary> /// <value>The Wins.</value> public int Wins { get { return this.wins; } set { this.wins = value; this.RaisePropertyChanged("Wins"); } } /// <summary> /// Gets or sets the Losses. /// </summary> /// <value>The Losses.</value> public int Losses { get { return this.losses; } set { this.losses = value; this.RaisePropertyChanged("Losses"); } } /// <summary> /// Gets or sets the team image source. /// </summary> /// <value>The image source for team.</value> public string Image { get { return this.image; } set { this.image = value; this.RaisePropertyChanged("Image"); } } /// <summary> /// Gets or sets the Location. /// </summary> /// <value>The Location.</value> public string Location { get { return this.location; } set { this.location = value; this.RaisePropertyChanged("Location"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="propertyName">string type of parameter propertyName</param> public void RaisePropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } }<file_sep>/iOS/SampleBrowser/Resources/Samples/RangeSlider/RangeSliderGettingStarted_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfRangeSlider.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class RangeSliderGettingStarted_Tablet : SampleView { SFRangeSlider rangeSlider1,rangeSlider2; UILabel departureLabel,arrivalLabel,ticksLabel,placementLabel,timeLabel1,showLabel,snapsToLabel,timeLabel2,timeLabel3; UIButton positionbutton = new UIButton (); UIButton positionbutton1 = new UIButton (); UIButton doneButton=new UIButton(); UIButton closeButton=new UIButton(); UIButton showPropertyButton=new UIButton(); UILabel propertiesLabel=new UILabel(); UILabel headingLabel=new UILabel(); UIView subView=new UIView(); UIView contentView = new UIView (); UIView controlView = new UIView (); UIPickerView positionPicker1, positionPicker2; UISwitch labelswitch, labelswitch1; private string selectedType; private readonly IList<string> TAlignment = new List<string> { "BottomRight", "TopLeft", "Inline", "Outside", "None" }; private readonly IList<string> LAlignment = new List<string> { "BottomRight", "TopLeft" }; public RangeSliderGettingStarted_Tablet() { //RangeSlider 1 rangeSlider1 = new SFRangeSlider(); rangeSlider1.Maximum = 12; rangeSlider1.Minimum = 0; rangeSlider1.RangeStart = 0; rangeSlider1.RangeEnd = 12; rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementBottomRight; rangeSlider1.TickFrequency = 2; rangeSlider1.ToolTipPlacement = SFToolTipPlacement.SFToolTipPlacementTopLeft; rangeSlider1.ValuePlacement = SFValuePlacement.SFValuePlacementBottomRight; rangeSlider1.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeSlider1.KnobColor = UIColor.White; rangeSlider1.TrackSelectionColor = UIColor.FromRGB (65, 115, 185); rangeSlider1.TrackColor = UIColor.FromRGB (182, 182, 182); rangeSlider1.Delegate = new RangeSliderTabletDelegate(); //RangeSlider 2 rangeSlider2 = new SFRangeSlider(); rangeSlider2.Frame = new CGRect (10, 100, this.Frame.Size.Width, this.Frame.Size.Height); rangeSlider2.Maximum = 12; rangeSlider2.Minimum = 0; rangeSlider2.RangeStart = 0; rangeSlider2.RangeEnd = 12; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementBottomRight; rangeSlider2.TickFrequency = 2; rangeSlider2.ValuePlacement = SFValuePlacement.SFValuePlacementBottomRight; rangeSlider2.ToolTipPlacement = SFToolTipPlacement.SFToolTipPlacementTopLeft; rangeSlider2.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeSlider2.KnobColor = UIColor.White; rangeSlider2.TrackSelectionColor = UIColor.FromRGB (65, 115, 185); rangeSlider2.TrackColor = UIColor.FromRGB (182, 182, 182); rangeSlider2.Delegate = new RangeSliderTabletDelegate(); controlView.AddSubview (rangeSlider1); controlView.AddSubview (rangeSlider2); this.AddSubview (controlView); mainPageDesign(); loadOptionView(); } public void mainPageDesign() { //headingLabel headingLabel.Text = "RangeSlider"; headingLabel.Font = UIFont.FromName("Helvetica", 20f); //departureLabel departureLabel = new UILabel(); departureLabel.Text = "Departure"; departureLabel.TextColor = UIColor.Black; departureLabel.TextAlignment = UITextAlignment.Left; departureLabel.Font = UIFont.FromName("Helvetica", 18f); //tickLabel ticksLabel = new UILabel(); ticksLabel.Text = "Tick Placement"; ticksLabel.Font = UIFont.FromName("Helvetica", 14f); ticksLabel.TextColor = UIColor.Black; ticksLabel.TextAlignment = UITextAlignment.Left; //PlacementLabel placementLabel = new UILabel(); placementLabel.Text = "Label Placement"; placementLabel.Font = UIFont.FromName("Helvetica", 14f); placementLabel.TextColor = UIColor.Black; placementLabel.TextAlignment = UITextAlignment.Left; //TimeLabel 1 timeLabel1 = new UILabel(); timeLabel1.Text = "(in Hours)"; timeLabel1.TextColor = UIColor.Gray; timeLabel1.TextAlignment = UITextAlignment.Left; timeLabel1.Font = UIFont.FromName("Helvetica", 14f); //TimeLabel 2 timeLabel2 = new UILabel(); timeLabel2.Text = "(in Hours)"; timeLabel2.TextColor = UIColor.Gray; timeLabel2.TextAlignment = UITextAlignment.Left; timeLabel2.Font = UIFont.FromName("Helvetica", 14f); //SnapsToLabel snapsToLabel = new UILabel(); snapsToLabel.Text = "Snap To Tick"; snapsToLabel.Font = UIFont.FromName("Helvetica", 14f); snapsToLabel.TextColor = UIColor.Black; snapsToLabel.TextAlignment = UITextAlignment.Left; //TimeLabel 2 timeLabel2 = new UILabel(); timeLabel2.Text = "Time: 12 AM - 12 PM"; timeLabel2.TextColor = UIColor.Gray; timeLabel2.TextAlignment = UITextAlignment.Left; timeLabel2.Font = UIFont.FromName("Helvetica", 14f); //TimleLabel 3 timeLabel3 = new UILabel(); timeLabel3.Text = "Time: 12 AM - 12 PM"; timeLabel3.TextColor = UIColor.Gray; timeLabel3.TextAlignment = UITextAlignment.Left; timeLabel3.Font = UIFont.FromName("Helvetica", 14f); //PositionButtton positionbutton = new UIButton(); positionbutton.SetTitle("BottomRight", UIControlState.Normal); positionbutton.Font = UIFont.FromName("Helvetica", 14f); positionbutton.SetTitleColor(UIColor.Black, UIControlState.Normal); positionbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; positionbutton.Layer.CornerRadius = 8; positionbutton.Layer.BorderWidth = 2; positionbutton.TouchUpInside += ShowPicker1; positionbutton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //PositionButton 1 positionbutton1 = new UIButton(); positionbutton1.SetTitle("BottomRight", UIControlState.Normal); positionbutton1.Font = UIFont.FromName("Helvetica", 14f); positionbutton1.SetTitleColor(UIColor.Black, UIControlState.Normal); positionbutton1.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; positionbutton1.Layer.CornerRadius = 8; positionbutton1.Layer.BorderWidth = 2; positionbutton1.TouchUpInside += ShowPicker2; positionbutton1.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //DoneButton doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.Font = UIFont.FromName("Helvetica", 14f); doneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); //ShowLabel showLabel = new UILabel(); showLabel.Text = "Show Label"; showLabel.Font = UIFont.FromName("Helvetica", 14f); showLabel.TextColor = UIColor.Black; showLabel.TextAlignment = UITextAlignment.Left; //LabelSwitch labelswitch = new UISwitch(); labelswitch.On = true; labelswitch.OnTintColor = UIColor.FromRGB(50, 150, 221); labelswitch.ValueChanged += toggleChanged; //LabelSwitch 1 labelswitch1 = new UISwitch(); labelswitch1.OnTintColor = UIColor.FromRGB(50, 150, 221); labelswitch1.On = false; labelswitch1.ValueChanged += toggleChanged1; //ArrivalLabel arrivalLabel = new UILabel(); arrivalLabel.Text = "Arrival"; arrivalLabel.TextColor = UIColor.Black; arrivalLabel.TextAlignment = UITextAlignment.Left; arrivalLabel.Font = UIFont.FromName("Helvetica", 18f); //PositionPicker 1 positionPicker1 = new UIPickerView(); PickerModel model = new PickerModel(TAlignment); model.PickerChanged += SelectedIndexChanged; positionPicker1.Model = model; positionPicker1.ShowSelectionIndicator = true; positionPicker1.Hidden = true; positionPicker1.BackgroundColor = UIColor.Gray; //PositionPicker 2 positionPicker2 = new UIPickerView(); PickerModel model1 = new PickerModel(LAlignment); model1.PickerChanged += SelectedIndexChanged1; positionPicker2.Model = model1; positionPicker2.ShowSelectionIndicator = true; positionPicker2.BackgroundColor = UIColor.Gray; positionPicker2.Hidden = true; //Adding to control view controlView.AddSubview(departureLabel); controlView.AddSubview(arrivalLabel); controlView.AddSubview(timeLabel1); controlView.AddSubview(timeLabel2); controlView.AddSubview(timeLabel2); controlView.AddSubview(timeLabel3); } public void loadOptionView() { //Adding to contentView propertiesLabel.Text = "OPTIONS"; contentView.AddSubview(ticksLabel); contentView.AddSubview(positionbutton); contentView.AddSubview(placementLabel); contentView.AddSubview(positionbutton1); contentView.AddSubview(positionPicker1); contentView.AddSubview(positionPicker2); contentView.AddSubview(doneButton); contentView.AddSubview(showLabel); contentView.AddSubview(labelswitch); contentView.AddSubview(snapsToLabel); contentView.AddSubview(labelswitch1); //Adding to SubView subView.AddSubview(contentView); contentView.BackgroundColor = UIColor.FromRGB(240, 240, 240); subView.AddSubview(closeButton); subView.AddSubview(propertiesLabel); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); this.AddSubview(subView); //ShowPropertyButton showPropertyButton.Hidden = true; showPropertyButton.SetTitle("OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = false; showPropertyButton.Hidden = true; }; this.AddSubview(showPropertyButton); //closeButton closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; }; //AddingGesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer(() => { subView.Hidden = true; showPropertyButton.Hidden = false; } ); propertiesLabel.UserInteractionEnabled = true; propertiesLabel.AddGestureRecognizer(tapgesture); } public void SetValue(SFRangeSlider r,nfloat start, nfloat end) { if (r == rangeSlider1) { if (Math.Round (start) < 1) { if (Math.Round (end) == 12) timeLabel2.Text = "Time: 12 AM - " + Math.Round (end) + " PM"; else timeLabel2.Text = "Time: 12 AM - " + Math.Round (end) + " AM"; } else { if (Math.Round (end) == 12) timeLabel2.Text = "Time: " + Math.Round (start) + " AM - " + Math.Round (end) + " PM"; else timeLabel2.Text = "Time: " + Math.Round (start) + " AM - " + Math.Round (end) + " AM"; } if (Math.Round (start) == Math.Round (end)) { if (Math.Round (start) < 1) timeLabel2.Text = "Time: 12 AM"; else if (Math.Round (start) == 12) timeLabel2.Text = "Time: 12 PM"; else timeLabel2.Text = "Time: " + Math.Round (start) + " AM"; } } else if(r==rangeSlider2){ if (Math.Round (start) < 1) { if (Math.Round (end) == 12) timeLabel3.Text = "Time: 12 AM - " + Math.Round (end) + " PM"; else timeLabel3.Text = "Time: 12 AM - " + Math.Round (end) + " AM"; } else { if (Math.Round (end) == 12) timeLabel3.Text = "Time: " + Math.Round (start) + " AM - " + Math.Round (end) + " PM"; else timeLabel3.Text = "Time: " + Math.Round (start) + " AM - " + Math.Round (end) + " AM"; } if (Math.Round (start) == Math.Round (end)) { if (Math.Round (start) < 1) timeLabel3.Text = "Time: 12 AM"; else if (Math.Round (start) == 12) timeLabel3.Text = "Time: 12 PM"; else timeLabel3.Text = "Time: " + Math.Round (start) + " AM"; } } } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; subView.Frame = new CGRect (0,view.Frame.Size.Height-view.Frame.Size.Height/3, view.Frame.Size.Width, view.Frame.Size.Height/3); controlView.Frame=new CGRect(100,40,this.Frame.Size.Width-200,this.Frame.Size.Height-40); contentView.Frame=new CGRect(0,40,subView.Frame.Size.Width,subView.Frame.Size.Height-20); headingLabel.Frame = new CGRect (10, 10, 120, 30); departureLabel.Frame = new CGRect (this.Frame.X + 10, 45,85, 30); arrivalLabel.Frame = new CGRect (this.Frame.X + 10,210, 80, 30); timeLabel1.Frame = new CGRect (this.Frame.X + 95, 45, this.Frame.Size.Width-20, 30); timeLabel2.Frame = new CGRect (this.Frame.X + 65, 210, 85, 30); timeLabel2.Frame = new CGRect (this.Frame.X + 10, 75,150, 30); timeLabel3.Frame = new CGRect (this.Frame.X + 10,240, 150, 30); rangeSlider1.Frame = new CGRect (2, 105, controlView.Frame.Size.Width - 4, 100); rangeSlider2.Frame = new CGRect (2, 265, controlView.Frame.Size.Width - 4, 100); ticksLabel.Frame = new CGRect (110, 50, contentView.Frame.Size.Width - 220, 30); positionbutton.Frame=new CGRect(350, 50, contentView.Frame.Size.Width - 520, 30); placementLabel.Frame = new CGRect (110, 90, contentView.Frame.Size.Width - 220, 30); positionbutton1.Frame=new CGRect(350, 90, contentView.Frame.Size.Width - 520, 30); positionPicker1.Frame = new CGRect (100, 20, contentView.Frame.Size.Width-200, 200); positionPicker2.Frame = new CGRect (100, 20, contentView.Frame.Size.Width-200 , 200); showLabel.Frame = new CGRect (110, 130, contentView.Frame.Size.Width - 220, 30); labelswitch.Frame = new CGRect (350, 130, labelswitch.Frame.Width-200, 30); snapsToLabel.Frame = new CGRect (110, 170, contentView.Frame.Size.Width - 220, 30); labelswitch1.Frame = new CGRect (350, 170, labelswitch.Frame.Width-200, 30); doneButton.Frame = new CGRect (100, 20, contentView.Frame.Size.Width-200, 30); showPropertyButton.Frame = new CGRect (0, this.Frame.Size.Height-25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect (this.Frame.Size.Width - 30, 5, 20, 30); propertiesLabel.Frame = new CGRect (10, 5, this.Frame.Width, 30); } base.LayoutSubviews (); } void ShowPicker1 (object sender, EventArgs e) { doneButton.Hidden = false; positionPicker1.Hidden = false; positionPicker2.Hidden = true; positionbutton.Hidden = true; placementLabel.Hidden = true; positionbutton1.Hidden = true; ticksLabel.Hidden = true; labelswitch.Hidden = true; showLabel.Hidden = true; snapsToLabel.Hidden = true; labelswitch1.Hidden = true; } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; positionPicker2.Hidden = true; positionPicker1.Hidden = true; positionbutton.Hidden = false; placementLabel.Hidden = false; positionbutton1.Hidden = false; labelswitch.Hidden = false; showLabel.Hidden = false; ticksLabel.Hidden = false; snapsToLabel.Hidden = false; labelswitch1.Hidden = false; } void ShowPicker2 (object sender, EventArgs e) { doneButton.Hidden = false; positionPicker1.Hidden = true; positionPicker2.Hidden = false; positionbutton.Hidden = true; placementLabel.Hidden = true; positionbutton1.Hidden = true; ticksLabel.Hidden = true; labelswitch.Hidden = true; showLabel.Hidden = true; snapsToLabel.Hidden = true; labelswitch1.Hidden = true; } private void SelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; positionbutton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "TopLeft") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementTopLeft; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementTopLeft; } else if (selectedType == "BottomRight") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementBottomRight; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementBottomRight; } else if (selectedType == "Inline") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementInline; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementInline; } else if (selectedType == "Outside") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementOutSide; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementOutSide; } else if (selectedType == "None") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementNone; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementNone; } } private void SelectedIndexChanged1(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; positionbutton1.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "TopLeft") { rangeSlider1.ValuePlacement = SFValuePlacement.SFValuePlacementTopLeft; rangeSlider2.ValuePlacement = SFValuePlacement.SFValuePlacementTopLeft; } else if (selectedType == "BottomRight") { rangeSlider1.ValuePlacement = SFValuePlacement.SFValuePlacementBottomRight; rangeSlider2.ValuePlacement = SFValuePlacement.SFValuePlacementBottomRight; } } private void toggleChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { rangeSlider1.ShowValueLabel = true; rangeSlider2.ShowValueLabel = true; } else { rangeSlider1.ShowValueLabel = false; rangeSlider2.ShowValueLabel = false; } } private void toggleChanged1(object sender, EventArgs e) { if (((UISwitch)sender).On) { rangeSlider1.SnapsTo = SFSnapsTo.SFSnapsToTicks; rangeSlider2.SnapsTo = SFSnapsTo.SFSnapsToTicks; } else { rangeSlider1.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeSlider2.SnapsTo = SFSnapsTo.SFSnapsToNone; } } public class RangeSliderTabletDelegate:SFRangeSliderDelegate { public override void RangeValueChange (SFRangeSlider SFRangeSlider, nfloat start, nfloat end) { (SFRangeSlider.Superview.Superview as RangeSliderGettingStarted_Tablet).SetValue (SFRangeSlider, start, end); } } } }<file_sep>/iOS/SampleBrowser/Samples/TreeMap/readme.md The tree map control provides a simple and effective way to visualize flat or hierarchical data as clustered rectangles with a specific, weighted attribute determining the size of each rectangle. This control has highly customizable features such as displaying hierarchical and flat-level data, legends, different layouts, and color mapping. The following samples are available for tree map to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Getting Started](GettingStarted.cs)| The tree map control provides a simple and effective way to visualize flat or hierarchical data as clustered rectangles. This sample explains a basic tree map control with color mapping and legend support. | | [Hierarchical](Hierarchical.cs)| This sample shows how to add hierarchical data in a tree map. | <file_sep>/Android/SampleBrowser/Samples/Schedule/Configuration.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Android.Views; using Android.Widget; using Com.Syncfusion.Sfrangeslider; using System.Collections.Generic; using Java.Util; using Android.Graphics; using Java.Text; using Android.App; using Android.OS; using Com.Syncfusion.Schedule; using Com.Syncfusion.Schedule.Enums; using System.Collections.ObjectModel; namespace SampleBrowser { public class Configuration : SamplePage, IDisposable { public Configuration() { } private SfSchedule sfschedule; private FrameLayout propertylayout; private MonthViewSettings monthsettings; private bool isInitialLoad = false; public override View GetSampleContent(Context context) { sfschedule = new SfSchedule(context); weekViewSetting = new WeekViewSettings(); monthsettings = new MonthViewSettings(); propertylayout = new FrameLayout(context); isInitialLoad = true; propertylayout = SetOptionPage(context); GetAppointments(); sfschedule.ItemsSource = appointmentCollection; sfschedule.ScheduleView = ScheduleView.WeekView; sfschedule.DayViewSettings.NonAccessibleBlocks = SetNonAccessibleBlocks(); sfschedule.WeekViewSettings.NonAccessibleBlocks = SetNonAccessibleBlocks(); sfschedule.WorkWeekViewSettings.NonAccessibleBlocks = SetNonAccessibleBlocks(); monthsettings.BlackoutDates = SetBlackoutDates(); monthsettings.ShowWeekNumber = true; sfschedule.MonthViewSettings = monthsettings; sfschedule.LayoutParameters = new FrameLayout.LayoutParams( LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); LinearLayout layout = new LinearLayout(context); layout.Orientation = Android.Widget.Orientation.Vertical; layout.AddView(sfschedule); return layout; } private List<String> subjectCollection; private List<String> colorCollection; private List<Calendar> startTimeCollection; private List<Calendar> endTimeCollection; private ScheduleAppointmentCollection appointmentCollection; //Creating appointments for ScheduleAppointmentCollection public void GetAppointments() { appointmentCollection = new ScheduleAppointmentCollection(); SetColors(); RandomNumbers(); SetSubjects(); SetStartTime(); SetEndTime(); for (int i = 0; i < 10; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[i]); scheduleAppointment.Subject = subjectCollection[i]; scheduleAppointment.StartTime = startTimeCollection[i]; scheduleAppointment.EndTime = endTimeCollection[i]; appointmentCollection.Add(scheduleAppointment); } } private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); } private void SetColors() { colorCollection = new List<String>(); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FF339933"); colorCollection.Add("#FF00ABA9"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF339933"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF00ABA9"); } private List<Int32> randomNums; private void RandomNumbers() { randomNums = new List<Int32>(); Java.Util.Random rand = new Java.Util.Random(); for (int i = 0; i < 10; i++) { int randomNum = rand.NextInt((15 - 9) + 1) + 9; randomNums.Add(randomNum); } } private void SetStartTime() { Calendar currentDate = Calendar.Instance; startTimeCollection = new List<Calendar>(); int count = 0; for (int i = -5; i < 5; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count], 0, 0); startTimeCollection.Add(startTime); count++; } } private void SetEndTime() { Calendar currentDate = Calendar.Instance; endTimeCollection = new List<Calendar>(); int count = 0; for (int i = -5; i < 5; i++) { Calendar endTime = (Calendar)currentDate.Clone(); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count] + 1, 0, 0); endTimeCollection.Add(endTime); count++; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private ObservableCollection<Calendar> SetBlackoutDates() { ObservableCollection<Calendar> black_dates = new ObservableCollection<Calendar>(); Calendar currentDate = Calendar.Instance; Calendar firstDate = (Calendar)currentDate.Clone(); firstDate.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), 21); black_dates.Add(firstDate); Calendar secondDate = (Calendar)currentDate.Clone(); secondDate.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), 22); black_dates.Add(secondDate); Calendar thirdDate = (Calendar)currentDate.Clone(); thirdDate.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), 23); black_dates.Add(thirdDate); return black_dates; } private NonAccessibleBlocksCollection SetNonAccessibleBlocks() { NonAccessibleBlocksCollection nonAccessibleBlocksCollection = new NonAccessibleBlocksCollection(); NonAccessibleBlock lunch = new NonAccessibleBlock(); lunch.StartTime = 13; lunch.EndTime = 14; lunch.Text = "Lunch Break"; nonAccessibleBlocksCollection.Add(lunch); nonAccessibleBlocks = nonAccessibleBlocksCollection; return nonAccessibleBlocks; } private WeekViewSettings weekViewSetting; private SfRangeSlider workHourRangeSlider; private CheckBox showWeekNumber; private TextView workingHoursTxtBlock; private CheckBox showNonAccessibleBlockcheckBox; private CheckBox showBlackoutDates; private LinearLayout monthViewLayout, otherviewsLayout; private NonAccessibleBlocksCollection nonAccessibleBlocks; public override View GetPropertyWindowLayout(Context context) { return propertylayout; } private FrameLayout SetOptionPage(Context context) { FrameLayout propertyLayout = new FrameLayout(context); LinearLayout layout = new LinearLayout(context); layout.Orientation = Android.Widget.Orientation.Vertical; layout.SetBackgroundColor(Color.White); layout.SetPadding(15, 15, 15, 20); monthViewLayout = new LinearLayout(context); monthViewLayout.Orientation = Android.Widget.Orientation.Vertical; monthViewLayout.SetBackgroundColor(Color.White); monthViewLayout.SetPadding(15, 15, 15, 20); otherviewsLayout = new LinearLayout(context); otherviewsLayout.Orientation = Android.Widget.Orientation.Vertical; otherviewsLayout.SetBackgroundColor(Color.White); otherviewsLayout.SetPadding(15, 15, 15, 20); //Schedule Type TextView scheduleType_txtBlock = new TextView(context); scheduleType_txtBlock.Text = "Select the Schedule Type"; scheduleType_txtBlock.TextSize = 20; scheduleType_txtBlock.SetPadding(0, 0, 0, 10); scheduleType_txtBlock.SetTextColor(Color.Black); Spinner typeSpinner = new Spinner(context, SpinnerMode.Dialog); typeSpinner.SetMinimumHeight(60); typeSpinner.SetBackgroundColor(Color.Gray); typeSpinner.DropDownWidth = 600; typeSpinner.SetPadding(10, 10, 0, 10); typeSpinner.SetGravity(GravityFlags.CenterHorizontal); layout.AddView(scheduleType_txtBlock); layout.AddView(typeSpinner); List<String> list = new List<String>(); list.Add("Week View"); list.Add("Day View"); list.Add("Work Week View"); list.Add("Month View"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, list); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); typeSpinner.Adapter = dataAdapter; typeSpinner.ItemSelected += SType_spinner_ItemSelected; View divider1 = new View(context); divider1.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 2); divider1.SetBackgroundColor(Color.Gray); otherviewsLayout.AddView(divider1); //Working Hours Duration workingHoursTxtBlock = new TextView(context); workingHoursTxtBlock.SetPadding(0, 20, 0, 0); workingHoursTxtBlock.Text = "Working Hours Duration"; workingHoursTxtBlock.TextSize = 20; workingHoursTxtBlock.SetTextColor(Color.Black); workHourRangeSlider = new SfRangeSlider(context); workHourRangeSlider.SetPadding(0, 0, 0, 30); workHourRangeSlider.Minimum = 0; workHourRangeSlider.Maximum = 24; workHourRangeSlider.TickFrequency = 2; workHourRangeSlider.StepFrequency = 1; workHourRangeSlider.RangeStart = weekViewSetting.WorkStartHour; workHourRangeSlider.RangeEnd = weekViewSetting.WorkEndHour; workHourRangeSlider.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 100); workHourRangeSlider.RangeChanged += WorkHour_rangeSlider_RangeChanged; workHourRangeSlider.ShowRange = true; workHourRangeSlider.ValuePlacement = ValuePlacement.TopLeft; workHourRangeSlider.ToolTipPlacement = ToolTipPlacement.None; workHourRangeSlider.TickPlacement = TickPlacement.None; workHourRangeSlider.ShowValueLabel = true; workHourRangeSlider.SnapsTo = SnapsTo.StepValues; if (context.Resources.DisplayMetrics.Density < 2) { workHourRangeSlider.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 150); } else if (context.Resources.DisplayMetrics.Density == 2) { workHourRangeSlider.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 200); } else { workHourRangeSlider.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 250); } otherviewsLayout.AddView(workingHoursTxtBlock); otherviewsLayout.AddView(workHourRangeSlider); View divider2 = new View(context); divider2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 2); divider2.SetBackgroundColor(Color.Gray); otherviewsLayout.AddView(divider2); showNonAccessibleBlockcheckBox = new CheckBox(context); showNonAccessibleBlockcheckBox.SetPadding(0, 10, 0, 10); showNonAccessibleBlockcheckBox.Text = "Show Non-Accessible Blocks"; showNonAccessibleBlockcheckBox.TextSize = 20; showNonAccessibleBlockcheckBox.SetTextColor(Color.Black); showNonAccessibleBlockcheckBox.Checked = true; showNonAccessibleBlockcheckBox.CheckedChange += Show_Non_Accessible_Block_checkBox_CheckedChange; otherviewsLayout.AddView(showNonAccessibleBlockcheckBox); View monthlayoutDivider = new View(context); monthlayoutDivider.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 2); monthlayoutDivider.SetBackgroundColor(Color.Gray); monthViewLayout.AddView(monthlayoutDivider); //Show black out dates showBlackoutDates = new CheckBox(context); showBlackoutDates.SetPadding(0, 10, 0, 10); showBlackoutDates.Text = "Show Blackout days"; showBlackoutDates.TextSize = 20; showBlackoutDates.Checked = true; showBlackoutDates.SetTextColor(Color.Black); showBlackoutDates.CheckedChange += Show_Blackout_Dates_CheckedChange; monthViewLayout.AddView(showBlackoutDates); //Show week number showWeekNumber = new CheckBox(context); showWeekNumber.SetPadding(0, 10, 0, 10); showWeekNumber.Text = "Show Week number"; showWeekNumber.TextSize = 20; showWeekNumber.Checked = true; showWeekNumber.SetTextColor(Color.Black); showWeekNumber.CheckedChange += Show_week_number_CheckedChange; monthViewLayout.AddView(showWeekNumber); View monthLayoutdivider2 = new View(context); monthLayoutdivider2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 2); monthLayoutdivider2.SetBackgroundColor(Color.Gray); monthViewLayout.AddView(monthLayoutdivider2); View divider5 = new View(context); divider5.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 2); divider5.SetBackgroundColor(Color.Gray); otherviewsLayout.AddView(divider5); FrameLayout collapsedLayouts = new FrameLayout(context); collapsedLayouts.AddView(otherviewsLayout); collapsedLayouts.AddView(monthViewLayout); layout.AddView(collapsedLayouts); if (sfschedule.ScheduleView != ScheduleView.MonthView) { monthViewLayout.Visibility = ViewStates.Invisible; } propertyLayout.AddView(layout); return propertyLayout; } private void SType_spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; String selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); if (sfschedule != null) { monthViewLayout.Visibility = ViewStates.Invisible; otherviewsLayout.Visibility = ViewStates.Visible; if (selectedItem.Equals("Day View")) { sfschedule.ScheduleView = ScheduleView.DayView; } else if (selectedItem.Equals("Week View")) { sfschedule.ScheduleView = ScheduleView.WeekView; sfschedule.EnableNavigation = true; } else if (selectedItem.Equals("Work Week View")) { sfschedule.ScheduleView = ScheduleView.WorkWeekView; } else if (selectedItem.Equals("Month View")) { monthViewLayout.Visibility = ViewStates.Visible; otherviewsLayout.Visibility = ViewStates.Invisible; sfschedule.ScheduleView = ScheduleView.MonthView; } } } // void RangeChanged(Object o, double v, double v1) private void WorkHour_rangeSlider_RangeChanged(object sender, RangeChangedEventArgs e) { sfschedule.DayViewSettings.WorkStartHour = e.RangeStart; sfschedule.DayViewSettings.WorkEndHour = e.RangeEnd; sfschedule.WeekViewSettings.WorkStartHour = e.RangeStart; sfschedule.WeekViewSettings.WorkEndHour = e.RangeEnd; sfschedule.WorkWeekViewSettings.WorkStartHour = e.RangeStart; sfschedule.WorkWeekViewSettings.WorkEndHour = e.RangeEnd; } //void onCheckedChanged(CompoundButton buttonView, bool isChecked) private void Show_Non_Accessible_Block_checkBox_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { sfschedule.DayViewSettings.NonAccessibleBlocks.Add(SetNonAccessibleBlocks()[0]); sfschedule.WeekViewSettings.NonAccessibleBlocks.Add(SetNonAccessibleBlocks()[0]); sfschedule.WorkWeekViewSettings.NonAccessibleBlocks.Add(SetNonAccessibleBlocks()[0]); } else { sfschedule.DayViewSettings.NonAccessibleBlocks.Clear(); sfschedule.WeekViewSettings.NonAccessibleBlocks.Clear(); sfschedule.WorkWeekViewSettings.NonAccessibleBlocks.Clear(); } } // void onCheckedChanged(CompoundButton buttonView, boolean isChecked) private void Show_Blackout_Dates_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { if (!isInitialLoad) { sfschedule.MonthViewSettings.BlackoutDates = SetBlackoutDates(); isInitialLoad = false; } } else { sfschedule.MonthViewSettings.BlackoutDates.Clear(); } isInitialLoad = false; } //void onCheckedChanged(CompoundButton buttonView, boolean isChecked) private void Show_week_number_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { if (sfschedule != null) { sfschedule.MonthViewSettings.ShowWeekNumber = true; } } else { sfschedule.MonthViewSettings.ShowWeekNumber = false; } } public override void OnApplyChanges() { base.OnApplyChanges(); } public void Dispose() { if (sfschedule != null) { sfschedule.Dispose(); sfschedule = null; } if (propertylayout != null) { propertylayout.Dispose(); propertylayout = null; } if (monthViewLayout != null) { monthViewLayout.Dispose(); monthViewLayout = null; } if (otherviewsLayout != null) { otherviewsLayout.Dispose(); otherviewsLayout = null; } if (workHourRangeSlider != null) { workHourRangeSlider.RangeChanged -= WorkHour_rangeSlider_RangeChanged; workHourRangeSlider.Dispose(); workHourRangeSlider = null; } if (showWeekNumber != null) { showWeekNumber.CheckedChange -= Show_week_number_CheckedChange; showWeekNumber.Dispose(); showWeekNumber = null; } if (workingHoursTxtBlock != null) { workingHoursTxtBlock.Dispose(); workingHoursTxtBlock = null; } if (showNonAccessibleBlockcheckBox != null) { showNonAccessibleBlockcheckBox.CheckedChange -= Show_Non_Accessible_Block_checkBox_CheckedChange; showNonAccessibleBlockcheckBox.Dispose(); showNonAccessibleBlockcheckBox = null; } if (showBlackoutDates != null) { showBlackoutDates.CheckedChange -= Show_Blackout_Dates_CheckedChange; showBlackoutDates.Dispose(); showBlackoutDates = null; } if (monthViewLayout != null) { monthViewLayout.Dispose(); monthViewLayout = null; } } } } <file_sep>/Forms/RangeSlider/RangeSlider/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Syncfusion.SfRangeSlider.XForms; using Xamarin.Forms; namespace SampleBrowser.SfRangeSlider { public partial class Themes : SampleView { public Themes() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP) { layoutRoot.HorizontalOptions = LayoutOptions.Start; layoutRoot.WidthRequest = 500; } RangeChangeEvent(); if (App.Current.MainPage != null) { if (App.Current.MainPage.Visual == VisualMarker.Material) { sfRangeSlider1.ToolTipTextColor = Color.White; sfRangeSlider2.ToolTipTextColor = Color.White; this.SetMaterialValues(sfRangeSlider1); this.SetMaterialValues(sfRangeSlider2); } } } void toggleStateChanged(object sender, ToggledEventArgs e) { sfRangeSlider1.ShowValueLabel = e.Value; sfRangeSlider2.ShowValueLabel = e.Value; } void toggleStateChanged1(object sender, ToggledEventArgs e) { if (e.Value) { sfRangeSlider1.SnapsTo = SnapsTo.Ticks; sfRangeSlider2.SnapsTo = SnapsTo.Ticks; } else { sfRangeSlider1.SnapsTo = SnapsTo.None; sfRangeSlider2.SnapsTo = SnapsTo.None; } } void RangeChangeEvent() { sfRangeSlider1.RangeChanging += (object sender, RangeEventArgs e) => { if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { if (Math.Round(e.Start) < 1) { if (Math.Round(e.End) == 12) timeLabel3.Text = "12 AM - " + Math.Round(e.End) + " PM"; else timeLabel3.Text = "12 AM - " + Math.Round(e.End) + " AM"; } else { if (Math.Round(e.End) == 12) timeLabel3.Text = Math.Round(e.Start) + " AM - " + Math.Round(e.End) + " PM"; else timeLabel3.Text = Math.Round(e.Start) + " AM - " + Math.Round(e.End) + " AM"; } if (Math.Round(e.Start) == Math.Round(e.End)) { if (Math.Round(e.Start) < 1) timeLabel3.Text = "12 AM"; else if (Math.Round(e.Start) == 12) timeLabel3.Text = "12 PM"; else timeLabel3.Text = Math.Round(e.Start) + " AM"; } } if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { if (Math.Round(sfRangeSlider1.RangeStart) < 1) { if (Math.Round(sfRangeSlider1.RangeEnd) == 12) timeLabel3.Text = "12 AM - " + Math.Round(sfRangeSlider1.RangeEnd) + " PM"; else timeLabel3.Text = "12 AM - " + Math.Round(sfRangeSlider1.RangeEnd) + " AM"; } else { if (Math.Round(sfRangeSlider1.RangeEnd) == 12) timeLabel3.Text = Math.Round(sfRangeSlider1.RangeStart) + " AM - " + Math.Round(sfRangeSlider1.RangeEnd) + " PM"; else timeLabel3.Text = Math.Round(sfRangeSlider1.RangeStart) + " AM - " + Math.Round(sfRangeSlider1.RangeEnd) + " AM"; } if (Math.Round(sfRangeSlider1.RangeStart) == Math.Round(sfRangeSlider1.RangeEnd)) { if (Math.Round(sfRangeSlider1.RangeStart) < 1) timeLabel3.Text = "12 AM"; else if (Math.Round(sfRangeSlider1.RangeStart) == 12) timeLabel3.Text = "12 PM"; else timeLabel3.Text = Math.Round(sfRangeSlider1.RangeStart) + " AM"; } } }; sfRangeSlider2.RangeChanging += (object sender, RangeEventArgs e) => { if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { if (Math.Round(e.Start) < 1) { if (Math.Round(e.End) == 12) timeLabel4.Text = "12 AM - " + Math.Round(e.End) + " PM"; else timeLabel4.Text = "12 AM - " + Math.Round(e.End) + " AM"; } else { if (Math.Round(e.End) == 12) timeLabel4.Text = Math.Round(e.Start) + " AM - " + Math.Round(e.End) + " PM"; else timeLabel4.Text = Math.Round(e.Start) + " AM - " + Math.Round(e.End) + " AM"; } if (Math.Round(e.Start) == Math.Round(e.End)) { if (Math.Round(e.Start) < 1) timeLabel4.Text = "12 AM"; else if (Math.Round(e.Start) == 12) timeLabel4.Text = "12 PM"; else timeLabel4.Text = Math.Round(e.Start) + " AM"; } } if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { if (Math.Round(sfRangeSlider2.RangeStart) < 1) { if (Math.Round(sfRangeSlider2.RangeEnd) == 12) timeLabel4.Text = "12 AM - " + Math.Round(sfRangeSlider2.RangeEnd) + " PM"; else timeLabel4.Text = "12 AM - " + Math.Round(sfRangeSlider2.RangeEnd) + " AM"; } else { if (Math.Round(sfRangeSlider2.RangeEnd) == 12) timeLabel4.Text = Math.Round(sfRangeSlider2.RangeStart) + " AM - " + Math.Round(sfRangeSlider2.RangeEnd) + " PM"; else timeLabel4.Text = Math.Round(sfRangeSlider2.RangeStart) + " AM - " + Math.Round(sfRangeSlider2.RangeEnd) + " AM"; } if (Math.Round(sfRangeSlider2.RangeStart) == Math.Round(sfRangeSlider2.RangeEnd)) { if (Math.Round(sfRangeSlider2.RangeStart) < 1) timeLabel4.Text = "12 AM"; else if (Math.Round(sfRangeSlider2.RangeStart) == 12) timeLabel4.Text = "12 PM"; else timeLabel4.Text = Math.Round(sfRangeSlider2.RangeStart) + " AM"; } } }; } /// <summary> /// Set the color values for material /// </summary> /// <param name="rangeSlider"></param> private void SetMaterialValues(Syncfusion.SfRangeSlider.XForms.SfRangeSlider rangeSlider) { if (Device.RuntimePlatform != Device.UWP) { rangeSlider.LabelColor = Color.FromRgba(0, 0, 0, 200); rangeSlider.TickPlacement = TickPlacement.Inline; } } } }<file_sep>/Forms/Picker/Picker/Samples/Cascading/Cascading.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using Xamarin.Forms; namespace SampleBrowser.SfPicker { public partial class Cascading : SampleView { Random r = new Random(); ObservableCollection<object> column1Source = new ObservableCollection<object>(); ObservableCollection<object> Source { get; set; } ObservableCollection<object> Source2 { get; set; } Dictionary<string, string> flags = new Dictionary<string, string>(); public string str = ""; private bool isPickerClosed = true; public Cascading() { InitializeComponent(); frompicker.Parent = tempGrid; topicker.Parent = tempGrid; arrivepicker.Parent = tempGrid; departpicker.Parent = tempGrid; submit.Clicked += Submit_Clicked; flags.Add("UK", "uk.png"); flags.Add("USA", "usa.png"); flags.Add("UAE", "uae.png"); flags.Add("India", "india.png"); flags.Add("Germany","germany.png"); ObservableCollection<object> column2Source = new ObservableCollection<object>(); column1Source.Add("UK"); column1Source.Add("USA"); column1Source.Add("India"); column1Source.Add("UAE"); column1Source.Add("Germany"); column2Source = GetCity("India"); Source = new ObservableCollection<object>(); Source2 = new ObservableCollection<object>(); Source.Add(column1Source); Source.Add(column2Source); Source2.Add(column1Source); Source2.Add(GetCity2("USA")); frompicker.SelectionChanged += Picker_SelectionChanged; frompicker.ItemsSource = Source; frompicker.Opened += Frompicker_OnPopUpOpened; frompicker.OnColumnLoaded += Frompicker_OnColumnLoaded; if (Device.RuntimePlatform != Device.Android) frompicker.OnPickerItemLoaded += Frompicker_OnPickerItemLoaded; frompicker.ShowColumnHeader = true; ObservableCollection<string> columnHeaderCollection = new ObservableCollection<string>(); if (Device.RuntimePlatform == Device.Android) { columnHeaderCollection.Add("COUNTRY"); columnHeaderCollection.Add("CITY"); frompicker.PickerWidth = 300; topicker.PickerWidth=300; departpicker.PickerWidth = 350; arrivepicker.PickerWidth = 350; departpicker.ColumnHeaderFontSize = 12; arrivepicker.ColumnHeaderFontSize = 12; btn1.WidthRequest = 30; btn2.WidthRequest = 30; btn3.WidthRequest = 30; btn4.WidthRequest = 30; } else { columnHeaderCollection.Add("Country"); columnHeaderCollection.Add("City"); } frompicker.ColumnHeaderText = columnHeaderCollection; frompicker.OkButtonClicked += Frompicker_OkButtonClicked; frompicker.CancelButtonClicked += Frompicker_CancelButtonClicked; frompicker.Closing += Frompicker_Closing; topicker.SelectionChanged += Picker_SelectionChanged1; topicker.ItemsSource = Source2; topicker.ShowColumnHeader = true; topicker.ColumnHeaderText = columnHeaderCollection; topicker.CancelButtonClicked += Topicker_CancelButtonClicked; topicker.OkButtonClicked += Topicker_OkButtonClicked; topicker.Opened += Topicker_OnPopUpOpened; topicker.Closing += Topicker_Closing; topicker.OnColumnLoaded += Topicker_OnColumnLoaded; if (Device.RuntimePlatform != Device.Android) topicker.OnPickerItemLoaded += Topicker_OnPickerItemLoaded; frompicker.Parent = tempGrid; topicker.Parent = tempGrid; departpicker.OnColumnLoaded += Departpicker_OnColumnLoaded; departpicker.Closing += Departpicker_Closing; departpicker.OkButtonClicked += Departpicker_OkButtonClicked; departpicker.CancelButtonClicked += Departpicker_CancelButtonClicked; arrivepicker.OnColumnLoaded += Arrivepicker_OnColumnLoaded; arrivepicker.Closing += Arrivepicker_Closing; arrivepicker.OkButtonClicked += Arrivepicker_OkButtonClicked; arrivepicker.CancelButtonClicked += Arrivepicker_CancelButtonClicked; str = DateTime.Now.Day.ToString(); if (str.Length == 1) { str = "0" + str; } startdate.Text = DateTime.Now.Year.ToString() + " " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3) + " " + str + " " + DateTime.Now.ToString("hh") + ":" + DateTime.Now.ToString("mm"); enddate.Text = DateTime.Now.Year.ToString() + " " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3) + " " + str + " " + " " + DateTime.Now.ToString("hh") + ":" + DateTime.Now.ToString("mm"); todaycollection.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month)); if (DateTime.Now.Date.Day < 10) todaycollection.Add("0" + DateTime.Now.Date.Day); else todaycollection.Add(DateTime.Now.Date.Day.ToString()); todaycollection.Add(DateTime.Now.Date.Year.ToString()); todaycollection.Add(DateTime.Now.ToString("hh")); todaycollection.Add(DateTime.Now.ToString("mm")); fromPlace.Focused += FromPlace_Focused; toplace.Focused += Toplace_Focused; startdate.Focused += Startdate_Focused; enddate.Focused += Enddate_Focused; fromPlace.Text = "Chennai, India"; toplace.Text = "Boston, USA"; this.BindingContext = new CascadingViewModel(); if (Device.RuntimePlatform == Device.Android) { submit.BackgroundColor = Color.FromHex("#009688"); submit.TextColor = Color.White; submit.Text = "SEARCH"; frompicker.HeaderText = "FROM"; topicker.HeaderText = "TO"; arrivepicker.ColumnHeaderFontSize = 12; departpicker.ColumnHeaderFontSize = 12; arrivepicker.HeaderText = "SELECT A DATE & TIME"; departpicker.HeaderText = "SELECT A DATE & TIME"; submit.FontFamily = "sans-serif-medium"; submit.WidthRequest = 130; submit.HeightRequest = 40; } if (Device.RuntimePlatform == Device.iOS) { frompicker.SelectedItemFontSize = 25; topicker.SelectedItemFontSize = 25; departpicker.SelectedItemFontSize = 25; arrivepicker.SelectedItemFontSize = 25; //frame.OutlineColor = Color.White; submit.WidthRequest = 250; submit.HeightRequest = 25; submit.BorderWidth = 1; arrivepicker.HeaderText = "Select a Date & Time"; departpicker.HeaderText = "Select a Date & Time"; fromLayout.HeightRequest = 30; toLayout.HeightRequest = 30; departLayout.HeightRequest = 30; arrivelayout.HeightRequest = 30; fromlabel.TextColor = Color.FromRgba(0, 0, 0, 0.5); tolabel.TextColor = Color.FromRgba(0, 0, 0, 0.5); departlabel.TextColor = Color.FromRgba(0, 0, 0, 0.5); arrivelabel.TextColor = Color.FromRgba(0, 0, 0, 0.5); fromlabel.FontFamily = "HelveticaNeue-Thin"; tolabel.FontFamily = "HelveticaNeue-Thin"; fromPlace.FontFamily = "HelveticaNeue-Thin"; toplace.FontFamily = "HelveticaNeue-Thin"; frompicker.SelectedItemFontFamily = "HelveticaNeue-Thin"; frompicker.UnSelectedItemFontFamily = "HelveticaNeue-Thin"; topicker.SelectedItemFontFamily = "HelveticaNeue-Thin"; topicker.UnSelectedItemFontFamily = "HelveticaNeue-Thin"; departpicker.SelectedItemFontFamily = "HelveticaNeue-Thin"; departpicker.UnSelectedItemFontFamily = "HelveticaNeue-Thin"; arrivepicker.SelectedItemFontFamily = "HelveticaNeue-Thin"; arrivepicker.UnSelectedItemFontFamily = "HelveticaNeue-Thin"; departlabel.FontFamily = "HelveticaNeue-Thin"; startdate.FontFamily = "HelveticaNeue-Thin"; arrivelabel.FontFamily = "HelveticaNeue-Thin"; enddate.FontFamily = "HelveticaNeue-Thin"; submit.FontFamily = "HelveticaNeue-Thin"; submit.BorderColor = Color.FromHex("#cdcdcd"); submit.FontSize = 14; submit.FontAttributes = FontAttributes.Italic; frompicker.PickerWidth = 300; topicker.PickerWidth = 300; arrivepicker.PickerWidth = 360; departpicker.PickerWidth = 360; } else if (Device.RuntimePlatform == Device.UWP) { if (Device.Idiom != TargetIdiom.Phone) { innerGrid.HorizontalOptions = LayoutOptions.Start; innerGrid.WidthRequest = 500; innerGrid.VerticalOptions = LayoutOptions.Start; } topicker.HeaderText = "TO"; frompicker.HeaderText = "FROM"; departpicker.HeaderText = "SELECT A DATE & TIME"; arrivepicker.HeaderText = "SELECT A DATE & TIME"; startdate.IsEnabled = true; startdate.HeightRequest = 40; arrivepicker.HeaderText = "PICK A DATE TIME"; departpicker.HeaderText = "PICK A DATE TIME"; enddate.IsEnabled = true; enddate.HeightRequest = 40; fromPlace.IsEnabled = true; fromPlace.HeightRequest = 40; toplace.IsEnabled = true; toplace.HeightRequest = 40; fromPlace.VerticalOptions = LayoutOptions.Center; toplace.VerticalOptions = LayoutOptions.Center; startdate.FontSize = 15; startdate.VerticalOptions = LayoutOptions.Center; enddate.FontSize = 15; enddate.VerticalOptions = LayoutOptions.Center; frompicker.PickerWidth = 300; topicker.PickerWidth = 300; departpicker.PickerWidth = 310; arrivepicker.PickerWidth = 310; submit.HorizontalOptions = LayoutOptions.Start; submit.HeightRequest = 40; submit.Margin = new Thickness(0, 15, 0, 0); if (Device.Idiom == TargetIdiom.Phone) { fromPlace.WidthRequest = 220; toplace.WidthRequest = 220; startdate.WidthRequest = 220; enddate.WidthRequest = 220; submit.WidthRequest = 270; } else submit.WidthRequest = 300; submit.BackgroundColor = Color.FromHex("#cdcdcd"); submit.TextColor = Color.Black; interlabel.Margin = new Thickness(10, 0, 0, 0); interlabel.FontAttributes = FontAttributes.Bold; fromlabel.TextColor = Color.Gray; tolabel.TextColor = Color.Gray; departlabel.TextColor = Color.Gray; arrivelabel.TextColor = Color.Gray; journeylabel.FontAttributes = FontAttributes.Bold; } var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += (s, e) => { if (Device.RuntimePlatform == Device.Android && Device.RuntimePlatform == Device.iOS) departpicker.IsOpen = true; }; startdate.GestureRecognizers.Add(tapGestureRecognizer); var tapGestureRecognizer2 = new TapGestureRecognizer(); tapGestureRecognizer2.Tapped += (s, e) => { if (Device.RuntimePlatform == Device.Android && Device.RuntimePlatform == Device.iOS) arrivepicker.IsOpen = true; }; enddate.GestureRecognizers.Add(tapGestureRecognizer2); var tapGestureRecognizer3 = new TapGestureRecognizer(); tapGestureRecognizer3.Tapped += (s, e) => { if (Device.RuntimePlatform == Device.Android && Device.RuntimePlatform == Device.iOS) frompicker.IsOpen = true; }; fromPlace.GestureRecognizers.Add(tapGestureRecognizer); var tapGestureRecognizer4 = new TapGestureRecognizer(); tapGestureRecognizer4.Tapped += (s, e) => { if (Device.RuntimePlatform == Device.Android && Device.RuntimePlatform == Device.iOS) topicker.IsOpen = true; }; toplace.GestureRecognizers.Add(tapGestureRecognizer2); if (Device.RuntimePlatform == Device.Android) { frompicker.BackgroundColor = Color.White; topicker.BackgroundColor = Color.White; } } private void Departpicker_CancelButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { isPickerClosed = false; departpicker.IsOpen = false; } private void Departpicker_OkButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { isPickerClosed = false; departpicker.IsOpen = false; } private void Arrivepicker_CancelButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { isPickerClosed = false; arrivepicker.IsOpen = false; } private void Arrivepicker_OkButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { isPickerClosed = false; arrivepicker.IsOpen = false; } private void Arrivepicker_Closing(object sender, Syncfusion.XForms.Core.CancelEventArgs e) { e.Cancel = isPickerClosed; } private void Departpicker_Closing(object sender, Syncfusion.XForms.Core.CancelEventArgs e) { e.Cancel = isPickerClosed; } private void Topicker_Closing(object sender, Syncfusion.XForms.Core.CancelEventArgs e) { e.Cancel = isPickerClosed; } private void Frompicker_Closing(object sender, Syncfusion.XForms.Core.CancelEventArgs e) { e.Cancel = isPickerClosed; } private void Enddate_Focused(object sender, FocusEventArgs e) { enddate.Unfocus(); arrivepicker.IsOpen = true; } private void Startdate_Focused(object sender, FocusEventArgs e) { startdate.Unfocus(); departpicker.IsOpen = true; } private void Toplace_Focused(object sender, FocusEventArgs e) { toplace.Unfocus(); topicker.IsOpen = true; } private void FromPlace_Focused(object sender, FocusEventArgs e) { fromPlace.Unfocus(); frompicker.IsOpen = true; } private void Topicker_OnColumnLoaded(object sender, Syncfusion.SfPicker.XForms.ColumnLoadedEventArgs e) { if (Device.RuntimePlatform != Device.Android) { if (e.Column == 0) { e.ColumnWidth = 150; } } } private void Topicker_OnPickerItemLoaded(object sender, Syncfusion.SfPicker.XForms.PickerViewEventArgs e) { if (e.Column == 0 && Device.RuntimePlatform != Device.Android) { Country c = new Country() { Name = e.Item.ToString() }; c.Flag = flags[e.Item.ToString()]; e.View = new Itemview(c); } } private void Submit_Clicked(object sender, EventArgs e) { int index = r.Next(0, 50); Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Results", "\n" + index + " Flights are available on that time to depart from " + fromPlace.Text.ToString(), "Ok"); } private void Frompicker_OnColumnLoaded(object sender, Syncfusion.SfPicker.XForms.ColumnLoadedEventArgs e) { if (Device.RuntimePlatform != Device.Android) { if (e.Column == 0) { e.ColumnWidth = 150; } } } private void Frompicker_OnPickerItemLoaded(object sender, Syncfusion.SfPicker.XForms.PickerViewEventArgs e) { if (e.Column == 0 && Device.RuntimePlatform != Device.Android) { Country c = new Country() { Name = e.Item.ToString() }; c.Flag = flags[e.Item.ToString()]; e.View = new Itemview(c); } } void Topicker_OnPopUpOpened(object sender, EventArgs e) { CascadingViewModel viewmodel = this.BindingContext as CascadingViewModel; ObservableCollection<object> arrivePlace = new ObservableCollection<object>(); String[] arraivePlaceArray = toplace.Text.Split(','); string country = arraivePlaceArray[1].Substring(1); arrivePlace.Add(country); arrivePlace.Add(arraivePlaceArray[0]); viewmodel.ArrivePlace = arrivePlace; } void Arrivepicker_OnColumnLoaded(object sender, Syncfusion.SfPicker.XForms.ColumnLoadedEventArgs e) { if (Device.RuntimePlatform == Device.UWP) { if (e.Column == 0) e.ColumnWidth = 80; if (e.Column == 1) e.ColumnWidth = 80; if (e.Column == 2) e.ColumnWidth = 50; } } void Departpicker_OnColumnLoaded(object sender, Syncfusion.SfPicker.XForms.ColumnLoadedEventArgs e) { if (Device.RuntimePlatform == Device.UWP) { if (e.Column == 0) e.ColumnWidth = 80; if (e.Column == 1) e.ColumnWidth = 80; if (e.Column == 2) e.ColumnWidth = 50; } } void Frompicker_OnPopUpOpened(object sender, EventArgs e) { CascadingViewModel viewmodel = this.BindingContext as CascadingViewModel; ObservableCollection<object> departPlace = new ObservableCollection<object>(); String[] departPlaceArray = fromPlace.Text.Split(','); string country = departPlaceArray[1].Substring(1); departPlace.Add(country); departPlace.Add(departPlaceArray[0]); viewmodel.FromPlace = departPlace; } void Topicker_OkButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { if (e.NewValue != null) { ObservableCollection<object> source = e.NewValue as ObservableCollection<object>; toplace.Text = source[1].ToString() + ", " + source[0].ToString(); } isPickerClosed = false; topicker.IsOpen = false; } void Topicker_CancelButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { CascadingViewModel viewmodel = this.BindingContext as CascadingViewModel; ObservableCollection<object> arrivePlace = new ObservableCollection<object>(); String[] arraivePlaceArray = toplace.Text.Split(','); string country = arraivePlaceArray[1].Substring(1); arrivePlace.Add(country); arrivePlace.Add(arraivePlaceArray[0]); viewmodel.ArrivePlace = arrivePlace; isPickerClosed = false; topicker.IsOpen = false; } void Handle_CancelButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { (this.BindingContext as CascadingViewModel).StartDate = GetCollectionfromstring(startdate.Text); } void Frompicker_CancelButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { CascadingViewModel viewmodel = this.BindingContext as CascadingViewModel; ObservableCollection<object> departPlace = new ObservableCollection<object>(); String[] departPlaceArray = fromPlace.Text.Split(','); string country = departPlaceArray[1].Substring(1); departPlace.Add(country); departPlace.Add(departPlaceArray[0]); viewmodel.FromPlace = departPlace; isPickerClosed = false; frompicker.IsOpen = false; } void Frompicker_OkButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { if (e.NewValue != null) { ObservableCollection<object> source = e.NewValue as ObservableCollection<object>; fromPlace.Text = source[1].ToString() + ", " + source[0].ToString(); } isPickerClosed = false; } void Handle_OkButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { if ((e.NewValue as IList).Count > 0) { startdate.Text = GetStringfromCollection(GetCollectionfromList(e.NewValue as IList)); (this.BindingContext as CascadingViewModel).StartDate = GetCollectionfromList(e.NewValue as IList); } } ObservableCollection<object> GetCollectionfromList(IList dates) { ObservableCollection<object> items = new ObservableCollection<object>(); foreach (var item in dates) { items.Add(item); } return items; } string GetStringfromCollection(ICollection collection) { string dates = string.Empty; int i = 0; foreach (var item in collection) { i++; dates += item; if (i == 4) dates += ":"; else dates += " "; } return dates; } ObservableCollection<object> todaycollection = new ObservableCollection<object>(); ObservableCollection<object> GetCollectionfromstring(string text) { if (!string.IsNullOrEmpty(text)) { text = text.Replace(':', ' '); var str = text.Split(' ').Where(s => !string.IsNullOrEmpty(s)); ObservableCollection<object> items = new ObservableCollection<object>(); foreach (var item in str) { items.Add(item); } return items; } return todaycollection; } void Handle_CancelButtonClicked1(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { (this.BindingContext as CascadingViewModel).EndDate = GetCollectionfromstring(startdate.Text); } void Handle_OkButtonClicked1(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { if ((e.NewValue as IList).Count > 0) { enddate.Text = GetStringfromCollection(GetCollectionfromList(e.NewValue as IList)); (this.BindingContext as CascadingViewModel).EndDate = GetCollectionfromList(e.NewValue as IList); //enddate.Text = GetStringfromCollection((this.BindingContext as ViewModel).StartDate); } } private void Enddate_OnPopUpClosed(object sender, EventArgs e) { if (string.IsNullOrEmpty(enddate.Text)) { (this.BindingContext as CascadingViewModel).EndDate = todaycollection; } else { (this.BindingContext as CascadingViewModel).EndDate = GetCollectionfromstring(enddate.Text); } } private void Startdate_OnPopUpClosed(object sender, EventArgs e) { if (string.IsNullOrEmpty(startdate.Text)) { (this.BindingContext as CascadingViewModel).StartDate = todaycollection; } else { (this.BindingContext as CascadingViewModel).StartDate = GetCollectionfromstring(startdate.Text); } } string currentData = "India", currentData2 = "UK"; public ObservableCollection<object> GetCity(string sdata) { currentData = sdata; ObservableCollection<object> selectedCountries = new ObservableCollection<object>(); if (sdata == "UK") { selectedCountries.Add("London"); selectedCountries.Add("Manchester"); selectedCountries.Add("Cambridge"); selectedCountries.Add("Edinburgh"); selectedCountries.Add("Glasgow"); selectedCountries.Add("Birmingham"); } else if (sdata == "USA") { selectedCountries.Add("New York"); selectedCountries.Add("Seattle"); selectedCountries.Add("Wasington"); selectedCountries.Add("Chicago"); selectedCountries.Add("Boston"); selectedCountries.Add("Los Angles"); } else if (sdata == "UAE") { selectedCountries.Add("Dubai"); selectedCountries.Add("Abu Dhabi"); selectedCountries.Add("Fujairah"); selectedCountries.Add("Sharjah"); selectedCountries.Add("Ajman"); selectedCountries.Add("AL Ain"); } else if (sdata == "India") { selectedCountries.Add("Mumbai"); selectedCountries.Add("Bengaluru"); selectedCountries.Add("Chennai"); selectedCountries.Add("Pune"); selectedCountries.Add("Jaipur"); selectedCountries.Add("Delhi"); } else { selectedCountries.Add("Berlin"); selectedCountries.Add("Munich"); selectedCountries.Add("Frankfurt"); selectedCountries.Add("Hamburg"); selectedCountries.Add("Cologne"); selectedCountries.Add("Bonn"); } return selectedCountries; } public ObservableCollection<object> GetCity2(string sdata) { currentData2 = sdata; ObservableCollection<object> selectedCountries = new ObservableCollection<object>(); if (sdata == "UK") { selectedCountries.Add("London"); selectedCountries.Add("Manchester"); selectedCountries.Add("Cambridge"); selectedCountries.Add("Edinburgh"); selectedCountries.Add("Glasgow"); selectedCountries.Add("Birmingham"); } else if (sdata == "USA") { selectedCountries.Add("New York"); selectedCountries.Add("San Francisco"); selectedCountries.Add("Wasington"); selectedCountries.Add("Chicago"); selectedCountries.Add("Boston"); selectedCountries.Add("Los Angles"); } else if (sdata == "UAE") { selectedCountries.Add("Dubai"); selectedCountries.Add("Abu Dhabi"); selectedCountries.Add("Fujairah"); selectedCountries.Add("Sharjah"); selectedCountries.Add("Ajman"); selectedCountries.Add("AL Ain"); } else if (sdata == "India") { selectedCountries.Add("Mumbai"); selectedCountries.Add("Chennai"); selectedCountries.Add("Bengaluru"); selectedCountries.Add("Pune"); selectedCountries.Add("Jaipur"); selectedCountries.Add("Delhi"); } else { selectedCountries.Add("Berlin"); selectedCountries.Add("Munich"); selectedCountries.Add("Frankfurt"); selectedCountries.Add("Hamburg"); selectedCountries.Add("Cologne"); selectedCountries.Add("Bonn"); } return selectedCountries; } void Picker_SelectionChanged(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { if (e.NewValue != null && e.NewValue is ObservableCollection<object> && (e.NewValue as ObservableCollection<object>).Count > 0) { if ((e.NewValue as ObservableCollection<object>)[0].ToString() != currentData) { //ObservableCollection<object> source = new ObservableCollection<object>(); ObservableCollection<object> columnSource2 = GetCity((e.NewValue as ObservableCollection<object>)[0].ToString()); //source.Add(column1Source); Source.RemoveAt(1); Source.Add(GetCity((e.NewValue as ObservableCollection<object>)[0].ToString())); //frompicker.ItemsSource = source; ObservableCollection<object> fromplaceCollection = new ObservableCollection<object>(); fromplaceCollection.Add((e.NewValue as ObservableCollection<object>)[0]); fromplaceCollection.Add(columnSource2[0]); (this.BindingContext as CascadingViewModel).FromPlace = fromplaceCollection; } } } private void Button_Click_2(object sender, EventArgs e) { topicker.IsOpen = true; isPickerClosed = true; } private void Button_Click_3(object sender, EventArgs e) { frompicker.IsOpen = true; isPickerClosed = true; } private void Button_Click_4(object sender, EventArgs e) { departpicker.IsOpen = true; isPickerClosed = true; } private void Button_Click_5(object sender, EventArgs e) { arrivepicker.IsOpen = true; isPickerClosed = true; } void Picker_SelectionChanged1(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { if (e.NewValue != null && e.NewValue is ObservableCollection<object> && (e.NewValue as ObservableCollection<object>).Count > 0) { if ((e.NewValue as ObservableCollection<object>)[0].ToString() != currentData2) { //ObservableCollection<object> source = new ObservableCollection<object>(); ObservableCollection<object> columnSource2 = GetCity2((e.NewValue as ObservableCollection<object>)[0].ToString()); //source.Add(column1Source); Source2.RemoveAt(1); Source2.Add(GetCity2((e.NewValue as ObservableCollection<object>)[0].ToString())); //topicker.ItemsSource = source; ObservableCollection<object> toplaceCollection = new ObservableCollection<object>(); toplaceCollection.Add((e.NewValue as ObservableCollection<object>)[0]); toplaceCollection.Add(columnSource2[0]); (this.BindingContext as CascadingViewModel).ArrivePlace = toplaceCollection; } } } } public class CascadingViewModel : INotifyPropertyChanged { private ObservableCollection<object> _startdate; public ObservableCollection<object> StartDate { get { return _startdate; } set { _startdate = value; RaisePropertyChanged("StartDate"); } } private ObservableCollection<object> _enddate; public ObservableCollection<object> EndDate { get { return _enddate; } set { _enddate = value; RaisePropertyChanged("EndDate"); } } private ObservableCollection<object> _fromPlace; public ObservableCollection<object> FromPlace { get { return _fromPlace; } set { _fromPlace = value; RaisePropertyChanged("FromPlace"); } } public ObservableCollection<object> ArrivePlace { get { return _endPlace; } set { _endPlace = value; RaisePropertyChanged("ArrivePlace"); } } private ObservableCollection<object> _endPlace; void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; public CascadingViewModel() { ObservableCollection<object> todaycollection = new ObservableCollection<object>(); //Select today dates todaycollection.Add(DateTime.Now.Date.Year.ToString()); todaycollection.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3)); if (DateTime.Now.Date.Day < 10) todaycollection.Add("0" + DateTime.Now.Date.Day); else todaycollection.Add(DateTime.Now.Date.Day.ToString()); todaycollection.Add(DateTime.Now.ToString("hh")); todaycollection.Add(DateTime.Now.ToString("mm")); ObservableCollection<object> initialDepartPlace = new ObservableCollection<object>(); initialDepartPlace.Add("India"); initialDepartPlace.Add("Chennai"); FromPlace = initialDepartPlace; ObservableCollection<object> initialArrivePlace = new ObservableCollection<object>(); initialArrivePlace.Add("USA"); initialArrivePlace.Add("Boston"); ArrivePlace = initialArrivePlace; this.StartDate = todaycollection; this.EndDate = todaycollection; } } } <file_sep>/Forms/Schedule/Schedule/Samples/DragDrop/ViewModel/DragDropViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Drag and Drop View Model class /// </summary> [Preserve(AllMembers = true)] public class DragDropViewModel : INotifyPropertyChanged { #region Properties /// <summary> /// team management /// </summary> private List<string> teamManagement; /// <summary> /// all day team management /// </summary> private List<string> allDayTeamManagement; /// <summary> /// color collection /// </summary> private List<Color> colorCollection; /// <summary> /// start time collection /// </summary> private List<DateTime> startTimeCollection; /// <summary> /// end time collection /// </summary> private List<DateTime> endTimeCollection; /// <summary> /// work start hour value /// </summary> private double workStartHour = 8; /// <summary> /// end hour value /// </summary> private double endHour = 16; /// <summary> /// random numbers /// </summary> ////creating random number collection private List<int> randomNums = new List<int>(); #endregion Properties #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DragDropViewModel" /> class. /// </summary> public DragDropViewModel() { this.Appointments = new ScheduleAppointmentCollection(); this.CreateRandomNumbersCollection(); this.CreateStartTimeCollection(); this.CreateEndTimeCollection(); this.CreateSubjectCollection(); this.CreateColorCollection(); this.IntializeAppoitments(10); } #endregion Constructor /// <summary> /// Property changed event handler /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets work start hour /// </summary> public double WorkStartHour { get { return this.workStartHour; } set { this.workStartHour = value; this.RaiseOnPropertyChanged("WorkStartHour"); } } /// <summary> /// Gets or sets end hour /// </summary> public double EndHour { get { return this.endHour; } set { this.endHour = value; this.RaiseOnPropertyChanged("EndHour"); } } /// <summary> /// Gets or sets appointments /// </summary> public ScheduleAppointmentCollection Appointments { get; set; } #region Methods #region InitializeAppointments /// <summary> /// initialize the appointments /// </summary> /// <param name="count">count value</param> private void IntializeAppoitments(int count) { for (int i = 0; i < count; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = this.colorCollection[i]; scheduleAppointment.Subject = this.teamManagement[i]; scheduleAppointment.StartTime = this.startTimeCollection[i]; scheduleAppointment.EndTime = this.endTimeCollection[i]; this.Appointments.Add(scheduleAppointment); } int allDayCount = 0; //// AllDay Appointment for (int i = 0; i < count; i++) { ScheduleAppointment allDayAppointment = new ScheduleAppointment(); allDayAppointment.Color = this.colorCollection[allDayCount]; allDayAppointment.Subject = this.allDayTeamManagement[allDayCount]; allDayAppointment.StartTime = this.startTimeCollection[i]; allDayAppointment.EndTime = this.endTimeCollection[i]; allDayAppointment.IsAllDay = true; this.Appointments.Add(allDayAppointment); allDayCount = allDayCount + 1; i = i + 1; } } #endregion InitializeAppointments #region SubjectCollection /// <summary> /// subject collection /// </summary> //// creating subject collection private void CreateSubjectCollection() { this.teamManagement = new List<string>(); this.teamManagement.Add("General Meeting"); this.teamManagement.Add("Plan Execution"); this.teamManagement.Add("Project Plan"); this.teamManagement.Add("Consulting"); this.teamManagement.Add("Performance Check"); this.teamManagement.Add("General Meeting"); this.teamManagement.Add("Plan Execution"); this.teamManagement.Add("Project Plan"); this.teamManagement.Add("Consulting"); this.teamManagement.Add("Performance Check"); this.allDayTeamManagement = new List<string>(); this.allDayTeamManagement.Add("Review"); this.allDayTeamManagement.Add("Meeting"); this.allDayTeamManagement.Add("Discussion"); this.allDayTeamManagement.Add("Retrospective"); this.allDayTeamManagement.Add("Outing"); } #endregion SubjectCollection #region creating color collection /// <summary> /// color collection /// </summary> ////creating color collection private void CreateColorCollection() { this.colorCollection = new List<Color>(); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FFF09609")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); } #endregion creating color collection #region CreateRandomNumbersCollection /// <summary> /// method for random number collection /// </summary> private void CreateRandomNumbersCollection() { this.randomNums = new List<int>(); Random rand = new Random(); for (int i = 0; i < 10; i++) { int random = rand.Next(9, 15); this.randomNums.Add(random); } } #endregion CreateRandomNumbersCollection #region CreateStartTimeCollection /// <summary> /// start time collection /// </summary> //// creating StartTime collection private void CreateStartTimeCollection() { this.startTimeCollection = new List<DateTime>(); DateTime currentDate = DateTime.Now; int count = 0; for (int i = -5; i < 5; i++) { DateTime startTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, this.randomNums[count], 0, 0); DateTime startDateTime = startTime.AddDays(i); this.startTimeCollection.Add(startDateTime); count++; } } #endregion CreateStartTimeCollection #region CreateEndTimeCollection /// <summary> /// end time collection /// </summary> //// creating EndTime collection private void CreateEndTimeCollection() { this.endTimeCollection = new List<DateTime>(); DateTime currentDate = DateTime.Now; int count = 0; for (int i = -5; i < 5; i++) { DateTime endTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, this.randomNums[count] + 1, 0, 0); DateTime endDateTime = endTime.AddDays(i); this.endTimeCollection.Add(endDateTime); count++; } } #endregion CreateEndTimeCollection #endregion Methods /// <summary> /// Invoke method when property changed /// </summary> /// <param name="propertyName">proper name</param> private void RaiseOnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/SampleControl.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; #endif namespace SampleBrowser { public class SampleControl : SampleView { public SampleControl () { } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Frame; } base.LayoutSubviews (); } } } <file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/UICollectionView Helper/CollectionViewSource.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using System.Collections.ObjectModel; namespace SampleBrowser { public class CollectionViewSource : UICollectionViewDataSource { private ObservableCollection<Mail> items; public InboxRepositiory repository; public CollectionViewSource() : base() { repository = new InboxRepositiory(); items = repository.InboxItems; } public override nint GetItemsCount(UICollectionView collectionView, nint section) { return items.Count; } public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { var cell = collectionView.DequeueReusableCell(CollectionViewCell.CellID, indexPath) as CollectionViewCell; Mail mail = items[indexPath.Row]; cell.UpdateRow(mail); cell.BackgroundColor = UIColor.White; return cell; } } }<file_sep>/Android/SampleBrowser/Samples/RangeSlider/GettingStarted_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Com.Syncfusion.Sfrangeslider; using Android.Widget; using Android.Views; using Android.Graphics; using SampleBrowser; using droid = Android.Widget.Orientation; using System.Collections.Generic; using System; using Android.Util; namespace SampleBrowser { //[con(Label = "Getting Started")] public class GettingStarted_Tab : SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ SfRangeSlider range, range2; public static TickPlacement tickplacement = TickPlacement.BottomRight; public static ValuePlacement valueplacement = ValuePlacement.BottomRight; public static bool showlabel = true; public static SnapsTo snapsto = SnapsTo.None; string fromvalue, toValue, fromValue1, toValue1; public static int rangeHeight; Button propertyButton; LinearLayout propertylayout, linearLayout; FrameLayout propertyFrameLayout, buttomButtonLayout; double actionBarHeight, navigationBarHeight, totalHeight; TextView arrivalLabel; Context con,context; Spinner tickSpinner, labelSpinner; ArrayAdapter<String> labelAdapter, dataAdapter; int tickPosition = 0, labelPosition = 0; bool showLabelPosition = true, snaptsToPosition = false; int totalWidth; public override View GetSampleContent(Context con1) { con = con1; InitialMethod(); DepatureLayout(); //rangeSlider range = new SfRangeSlider(con); range.Minimum = 0; range.Maximum = 12; range.TickFrequency = 2; range.ShowValueLabel = true; range.StepFrequency = 6; range.DirectionReversed = false; range.ValuePlacement = Com.Syncfusion.Sfrangeslider.ValuePlacement.BottomRight; range.RangeEnd = 12; range.RangeStart = 0; range.TickPlacement = Com.Syncfusion.Sfrangeslider.TickPlacement.BottomRight; range.ShowRange = true; range.SnapsTo = Com.Syncfusion.Sfrangeslider.SnapsTo.None; range.Orientation = Com.Syncfusion.Sfrangeslider.Orientation.Horizontal; range.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, rangeHeight); TimeLabelLayout(); linearLayout.AddView(range); ArrivalLabelLayout(); //rangeSlider range2 = new SfRangeSlider(con); range2.Minimum = 0; range2.Maximum = 12; range2.TickFrequency = 2; range2.ShowValueLabel = true; range2.StepFrequency = 6; range2.DirectionReversed = false; range2.ValuePlacement = Com.Syncfusion.Sfrangeslider.ValuePlacement.BottomRight; range2.RangeEnd = 12; range2.RangeStart = 0; range2.TickPlacement = Com.Syncfusion.Sfrangeslider.TickPlacement.BottomRight; range2.ShowRange = true; range2.SnapsTo = Com.Syncfusion.Sfrangeslider.SnapsTo.None; range2.Orientation = Com.Syncfusion.Sfrangeslider.Orientation.Horizontal; range2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, rangeHeight); TimeLableLayout2(); FinalLayout(); return frame; } FrameLayout frame; private void InitialMethod() { frame = new FrameLayout(con); totalHeight = con.Resources.DisplayMetrics.HeightPixels; TypedValue tv = new TypedValue(); if (con.Theme.ResolveAttribute(Android.Resource.Attribute.ActionBarSize, tv, true)) { actionBarHeight = TypedValue.ComplexToDimensionPixelSize(tv.Data, con.Resources.DisplayMetrics); } navigationBarHeight = getNavigationBarHeight(con); totalHeight = totalHeight - navigationBarHeight - actionBarHeight; //linearLayout linearLayout = new LinearLayout(con); linearLayout.SetPadding(20, 20, 20, 30); linearLayout.SetBackgroundColor(Color.White); linearLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.6), GravityFlags.Top | GravityFlags.CenterHorizontal); linearLayout.Orientation = Android.Widget.Orientation.Vertical; rangeHeight = getDimensionPixelSize(con, Resource.Dimension.range_ht); } TextView departureLabel; private void DepatureLayout() { //departureLabel departureLabel = new TextView(con); departureLabel.TextSize = 20; departureLabel.Text = " " + "Departure"; departureLabel.SetTextColor(Color.Black); } private void TimeLabelLayout() { //depstack LinearLayout depstack = new LinearLayout(con); depstack.Orientation = Android.Widget.Orientation.Horizontal; depstack.AddView(departureLabel); TextView timeLabel = new TextView(con); timeLabel.TextSize = 13; timeLabel.Text = " " + "(in Hours)"; timeLabel.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent); timeLabel.SetTextColor(Color.ParseColor("#939394")); timeLabel.Gravity = GravityFlags.Center; depstack.AddView(timeLabel); //snapsToLabel TextView snapsToLabel = new TextView(con); snapsToLabel.SetHeight(50); linearLayout.AddView(snapsToLabel); linearLayout.AddView(depstack); TextView timeLabel1 = new TextView(con); TextView textView12 = new TextView(con); linearLayout.AddView(textView12); linearLayout.AddView(timeLabel1); //timeLabel timeLabel1.TextSize = 13; fromValue1 = "12"; toValue1 = Math.Round(range.RangeEnd).ToString(); timeLabel1.SetTextColor(Color.ParseColor("#939394")); timeLabel1.Text = " " + "Time: " + fromValue1 + "AM " + " - " + toValue1 + " PM"; timeLabel1.Gravity = GravityFlags.Left; range.RangeChanged += (object sender, RangeChangedEventArgs e) => { String pMeridian = "AM", pMeridian1 = "AM"; if (Math.Round(e.RangeStart).ToString() == "0") { fromValue1 = "12"; pMeridian1 = "AM"; } else fromValue1 = Convert.ToString(Math.Round(e.RangeStart)); if (e.RangeEnd <= 12) toValue1 = Convert.ToString(Math.Round(e.RangeEnd)); if (Math.Round(e.RangeEnd).ToString() == "12") pMeridian = "PM"; if (Math.Round(e.RangeEnd).ToString() == "12") pMeridian = "PM"; if (Convert.ToString(Math.Round(e.RangeStart)).Equals(Convert.ToString(Math.Round(e.RangeEnd)))) { if (Math.Round(e.RangeStart).ToString() == "0") timeLabel1.Text = " " + "Time: " + fromValue1 + " " + pMeridian1; else if (Math.Round(e.RangeEnd).ToString() == "12") timeLabel1.Text = " " + "Time: " + toValue1 + " " + pMeridian; else timeLabel1.Text = " " + "Time: " + fromValue1 + " " + pMeridian1; } else timeLabel1.Text = " " + "Time: " + fromValue1 + " " + pMeridian1 + " - " + toValue1 + " " + pMeridian; }; } private void ArrivalLabelLayout() { //showLabel TextView showLabel = new TextView(con); showLabel.SetHeight(70); linearLayout.AddView(showLabel); arrivalLabel = new TextView(con); arrivalLabel.TextSize = 20; arrivalLabel.Text = " " + "Arrival"; arrivalLabel.SetTextColor(Color.Black); } private void TimeLableLayout2() { //timeLabel TextView timeLabel2 = new TextView(con); timeLabel2.TextSize = 13; timeLabel2.Text = " " + "(in Hours)"; timeLabel2.Gravity = GravityFlags.Center; timeLabel2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent); timeLabel2.SetTextColor(Color.ParseColor("#939394")); //AdjLabel TextView adjLabel8 = new TextView(con); adjLabel8.SetHeight(50); LinearLayout arrivestack = new LinearLayout(con); arrivestack.Orientation = Android.Widget.Orientation.Horizontal; arrivestack.AddView(arrivalLabel); arrivestack.AddView(timeLabel2); linearLayout.AddView(adjLabel8); linearLayout.AddView(arrivestack); TextView adjLabel9 = new TextView(con); linearLayout.AddView(adjLabel9); TextView timeLabel3 = new TextView(con); linearLayout.AddView(timeLabel3); linearLayout.AddView(range2); //timeLabel timeLabel3.TextSize = 13; timeLabel3.SetTextColor(Color.ParseColor("#939394")); fromvalue = "12"; toValue = Math.Round(range2.RangeEnd).ToString(); timeLabel3.Text = " " + "Time: " + fromvalue + "AM " + " - " + toValue + " PM"; timeLabel3.Gravity = GravityFlags.Left; range2.RangeChanged += (object sender, RangeChangedEventArgs e) => { String pMeridian = "AM", pMeridian1 = "AM"; if (Math.Round(e.RangeStart).ToString() == "0") { fromvalue = "12"; pMeridian1 = "AM"; } else fromvalue = Convert.ToString(Math.Round(e.RangeStart)); if (e.RangeEnd <= 12) toValue = Convert.ToString(Math.Round(e.RangeEnd)); if (Math.Round(e.RangeEnd).ToString() == "12") pMeridian = "PM"; if (Convert.ToString(Math.Round(e.RangeStart)).Equals(Convert.ToString(Math.Round(e.RangeEnd)))) { if (Math.Round(e.RangeStart).ToString() == "0") timeLabel3.Text = " " + "Time: " + fromvalue + " " + pMeridian1; else if (Math.Round(e.RangeEnd).ToString() == "12") timeLabel3.Text = " " + "Time: " + toValue + " " + pMeridian; else timeLabel3.Text = " " + "Time: " + fromvalue + " " + pMeridian1; } else timeLabel3.Text = " " + "Time: " + fromvalue + " " + pMeridian1 + " - " + toValue + " " + pMeridian; }; } private void FinalLayout() { //frame frame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); frame.SetBackgroundColor(Color.White); frame.SetPadding(10, 10, 10, 10); //scrollView1 ScrollView scrollView1 = new ScrollView(con); scrollView1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.7), GravityFlags.Top | GravityFlags.CenterHorizontal); scrollView1.AddView(linearLayout); frame.AddView(scrollView1); //buttomButtonLayout buttomButtonLayout = new FrameLayout(con); buttomButtonLayout.SetBackgroundColor(Color.Transparent); buttomButtonLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1), GravityFlags.Bottom | GravityFlags.CenterHorizontal); //propertyButton propertyButton = new Button(con); propertyButton.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Bottom | GravityFlags.CenterHorizontal); propertyButton.Text = "OPTIONS"; propertyButton.Gravity = GravityFlags.Start; //propertyFrameLayout propertyFrameLayout = new FrameLayout(con); propertyFrameLayout.SetBackgroundColor(Color.Rgb(240, 240, 240)); propertyFrameLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.3), GravityFlags.CenterHorizontal); propertyFrameLayout.AddView(GetPropertyLayout(con)); propertyButton.Click += (object sender, EventArgs e) => { buttomButtonLayout.RemoveAllViews(); propertyFrameLayout.RemoveAllViews(); propertyFrameLayout.AddView(GetPropertyLayout(con)); }; //scrollView ScrollView scrollView = new ScrollView(con); scrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.3), GravityFlags.Bottom | GravityFlags.CenterHorizontal); scrollView.AddView(propertyFrameLayout); frame.AddView(scrollView); frame.AddView(buttomButtonLayout); frame.FocusableInTouchMode = true; } public View GetPropertyLayout(Android.Content.Context context1) { context = context1; totalWidth = (context.Resources.DisplayMetrics.WidthPixels); OptionLayout(); TickPlacementLayout(); LabelPlacementLayout(); ShowLabelLayout(); SnapsToTicksLayout(); return propertylayout; } FrameLayout topProperty; LinearLayout proprtyOptionsLayout; private void OptionLayout() { //propertylayout propertylayout = new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; showlabel = showLabelPosition; snapsto = SnapsTo.None; //propertyLabel TextView propertyLabel = new TextView(context); propertyLabel.SetTextColor(Color.ParseColor("#282828")); propertyLabel.Gravity = GravityFlags.CenterVertical; propertyLabel.TextSize = 18; propertyLabel.SetPadding(0, 10, 0, 10); propertyLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.Left | GravityFlags.CenterHorizontal); propertyLabel.Text = " " + "OPTIONS"; //closeLabel TextView closeLabel = new TextView(context); closeLabel.SetBackgroundColor(Color.Transparent); closeLabel.Gravity = GravityFlags.CenterVertical; closeLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLabel.SetBackgroundResource(Resource.Drawable.sfclosebutton); //closeLayout FrameLayout closeLayout = new FrameLayout(context); closeLayout.SetBackgroundColor(Color.Transparent); closeLayout.SetPadding(0, 10, 0, 10); closeLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLayout.AddView(closeLabel); //topProperty topProperty = new FrameLayout(context); topProperty.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); topProperty.SetBackgroundColor(Color.Rgb(230, 230, 230)); topProperty.AddView(propertyLabel); topProperty.AddView(closeLayout); topProperty.Touch += (object sendar, View.TouchEventArgs e) => { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); }; proprtyOptionsLayout = new LinearLayout(context); proprtyOptionsLayout.Orientation = Android.Widget.Orientation.Vertical; //spaceText TextView spaceText1 = new TextView(context); spaceText1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText1); } private void TickPlacementLayout() { //TickPlacement TextView placementLabel = new TextView(context); placementLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); placementLabel.Text = "Tick Placement"; placementLabel.TextSize = 15; placementLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); placementLabel.SetTextColor(Color.Black); placementLabel.Gravity = GravityFlags.Left; //positionList List<String> positionList = new List<String>(); positionList.Add("BottomRight"); positionList.Add("TopLeft"); positionList.Add("Outside"); positionList.Add("Inline"); positionList.Add("None"); dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, positionList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //tickSpinner tickSpinner = new Spinner(context,SpinnerMode.Dialog); tickSpinner.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); tickSpinner.SetPadding(0, 0, 0, 0); tickSpinner.Adapter = dataAdapter; tickSpinner.SetSelection(tickPosition); tickSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); tickPosition = e.Position; if (selectedItem.Equals("BottomRight")) { tickplacement = TickPlacement.BottomRight; } else if (selectedItem.Equals("TopLeft")) { tickplacement = TickPlacement.TopLeft; } else if (selectedItem.Equals("Inline")) { tickplacement = TickPlacement.Inline; } else if (selectedItem.Equals("Outside")) { tickplacement = TickPlacement.Outside; } else if (selectedItem.Equals("None")) { tickplacement = TickPlacement.None; } ApplyChanges(); }; //tickPlacementLayout LinearLayout tickPlacementLayout = new LinearLayout(context); tickPlacementLayout.Orientation = Android.Widget.Orientation.Horizontal; tickPlacementLayout.AddView(placementLabel); tickPlacementLayout.AddView(tickSpinner); proprtyOptionsLayout.AddView(tickPlacementLayout); //spaceText TextView spaceText2 = new TextView(context); spaceText2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText2); } private void LabelPlacementLayout() { //Label Placement TextView departureLabel = new TextView(context); departureLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); departureLabel.Text = "Label Placement"; departureLabel.TextSize = 15; departureLabel.SetTextColor(Color.Black); //labelList List<String> labelList = new List<String>(); labelList.Add("BottomRight"); labelList.Add("TopLeft"); //labelSpinner labelSpinner = new Spinner(context,SpinnerMode.Dialog); labelSpinner.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); labelSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); labelPosition = e.Position; if (selectedItem.Equals("TopLeft")) { valueplacement = ValuePlacement.TopLeft; } else if (selectedItem.Equals("BottomRight")) { valueplacement = ValuePlacement.BottomRight; } ApplyChanges(); }; //labelAdapter labelAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, labelList); labelAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); labelSpinner.Adapter = labelAdapter; labelSpinner.SetSelection(labelPosition); labelSpinner.SetPadding(0, 0, 0, 0); //labelPlacementLayout LinearLayout labelPlacementLayout = new LinearLayout(context); labelPlacementLayout.Orientation = Android.Widget.Orientation.Horizontal; labelPlacementLayout.AddView(departureLabel); labelPlacementLayout.AddView(labelSpinner); proprtyOptionsLayout.AddView(labelPlacementLayout); //spaceText TextView spaceText3 = new TextView(context); spaceText3.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText3); } private void ShowLabelLayout() { //Show Label TextView showLabel = new TextView(context); showLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); showLabel.Text = "Show Label"; showLabel.TextSize = 15; //checkBox Switch checkBox = new Switch(context); checkBox.Checked = showLabelPosition; checkBox.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { if (e.IsChecked) showlabel = true; else showlabel = false; showLabelPosition = showlabel; ApplyChanges(); }; //spaceText TextView spaceText8 = new TextView(context); spaceText8.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); //showLabelLayout LinearLayout showLabelLayout = new LinearLayout(context); showLabelLayout.Orientation = Android.Widget.Orientation.Horizontal; showLabelLayout.AddView(showLabel); showLabelLayout.AddView(checkBox); showLabelLayout.AddView(spaceText8); proprtyOptionsLayout.AddView(showLabelLayout); //spaceText TextView spaceText4 = new TextView(context); spaceText4.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText4); } private void SnapsToTicksLayout() { //snapsToTicks TextView snapsToLabel = new TextView(context); snapsToLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); snapsToLabel.Text = "Snaps To Tick"; snapsToLabel.TextSize = 15; //checkBox Switch checkBox2 = new Switch(context); checkBox2.Checked = snaptsToPosition; checkBox2.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { if (e.IsChecked) snapsto = SnapsTo.Ticks; else snapsto = SnapsTo.None; snaptsToPosition = e.IsChecked; ApplyChanges(); }; //spaceText TextView spaceText7 = new TextView(context); spaceText7.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); //snapsToLabelLayout LinearLayout snapsToLabelLayout = new LinearLayout(context); snapsToLabelLayout.Orientation = Android.Widget.Orientation.Horizontal; snapsToLabelLayout.AddView(snapsToLabel); snapsToLabelLayout.AddView(checkBox2); snapsToLabelLayout.AddView(spaceText7); proprtyOptionsLayout.AddView(snapsToLabelLayout); //spaceText TextView spaceText5 = new TextView(context); spaceText5.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); //proprtyOptionsLayout.AddView(spaceText5); TextView spaceLabel = new TextView(context); spaceLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent); //layout1 LinearLayout layout1 = new LinearLayout(context); layout1.Orientation = Android.Widget.Orientation.Horizontal; layout1.AddView(spaceLabel); layout1.AddView(proprtyOptionsLayout); //propertylayout propertylayout.AddView(topProperty); propertylayout.AddView(layout1); } public static int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } public void ApplyChanges() { range2.TickPlacement = tickplacement; range.TickPlacement = tickplacement; range2.ValuePlacement = valueplacement; range.ValuePlacement = valueplacement; range2.ShowValueLabel = showlabel; range.ShowValueLabel = showlabel; range2.SnapsTo = snapsto; range.SnapsTo = snapsto; } private int getStatusBarHeight(Android.Content.Context con) { int barHeight = 0; int resourceId = con.Resources.GetIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { barHeight = con.Resources.GetDimensionPixelSize(resourceId); } return barHeight; } private int getNavigationBarHeight(Android.Content.Context con) { int navBarHeight = 0; int resourceId = con.Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navBarHeight = con.Resources.GetDimensionPixelSize(resourceId); } return navBarHeight; } } }<file_sep>/iOS/SampleBrowser/Samples/DocIO/XMLMapping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class XMLMapping : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton button; public XMLMapping() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to map custom XML part to content controls in the Word document."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 60); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 60); } this.AddSubview(label); button.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(5, 80, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 80, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Employees.xml"); // Create a new document. WordDocument document = new WordDocument(); //Add a section & a paragraph in the empty document. document.EnsureMinimal(); //Loads XML file into the customXML part of the Word document. CustomXMLPart docIOxmlPart = new CustomXMLPart(document); docIOxmlPart.Load(inputStream); //Insert content controls and maps Employees details to it. InsertAndMapEmployees(document, "EmployeesList", docIOxmlPart); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("XMLMapping.docx", "application/msword", stream); } } #region Helper Methods /// <summary> /// Insert and Maps CustomXMLPart to content control based on XPath. /// </summary> /// <param name="paragraph">Paragraph instance to append content control.</param> /// <param name="XPath">XPath of the CustomXMLNode to be mapped</param> /// <param name="custXMLPart">CustomXMLPart of the CustomXMLNode</param> private void MapCustomXMLPart(IWParagraph paragraph, string XPath, CustomXMLPart custXMLPart) { IInlineContentControl contentControl = paragraph.AppendInlineContentControl(ContentControlType.Text); contentControl.ContentControlProperties.XmlMapping.SetMapping(XPath, string.Empty, custXMLPart); } /// <summary> /// Inserts content control and maps the employees details to it. /// </summary> /// <param name="document">Word document instance.</param> /// <param name="xmlRootPath">Custom XML root Xpath.</param> /// <param name="docIOxmlPart">CustomXMLPart instance.</param> private void InsertAndMapEmployees(WordDocument document, string xmlRootPath, CustomXMLPart docIOxmlPart) { //Retrieving CustomXMLNode from xmlRootPath. CustomXMLNode parentNode = docIOxmlPart.SelectSingleNode(xmlRootPath); int empIndex = 1; foreach (CustomXMLNode employeeNode in parentNode.ChildNodes) { if (employeeNode.HasChildNodes()) { //Adds new paragraph to the section IWParagraph paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.BackColor = Syncfusion.Drawing.Color.Gray; IWTextRange textrange = paragraph.AppendText("Employee"); textrange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; textrange.CharacterFormat.Bold = true; textrange.CharacterFormat.FontSize = 14; //Insert content controls and maps Employee details to it. InsertAndMapEmployee(document, employeeNode, xmlRootPath, docIOxmlPart, empIndex); } empIndex++; } } /// <summary> /// Inserts content control and maps the employee details to it. /// </summary> /// <param name="document">Word document instance.</param> /// <param name="employeesNode">CustomXMLNode of employee.</param> /// <param name="rootXmlPath">Custom XML root Xpath.</param> /// <param name="docIOxmlPart">CustomXMLPart instance.</param> /// <param name="empIndex">Current employee index.</param> private void InsertAndMapEmployee(WordDocument document, CustomXMLNode employeesNode, string rootXmlPath, CustomXMLPart docIOxmlPart, int empIndex) { //Column names of Employee element. string[] employeesDetails = { "FirstName", "LastName", "Employee ID", "Extension", "Address", "City", "Country" }; int empChildIndex = 0; int customerIndex = 1; // Append current empolyee XPath with root XPath. string empPath = "/" + rootXmlPath + "/Employees[" + empIndex + "]/"; // Iterating child elements of Employee foreach (CustomXMLNode employeeChild in employeesNode.ChildNodes) { IWParagraph paragraph = document.LastParagraph; if (employeeChild.HasChildNodes()) { //Insert a content controls and maps Customer details to it. InsertAndMapCustomer(document, employeeChild, docIOxmlPart, empPath, customerIndex); customerIndex++; } else { if (empChildIndex != 1) { //Insert a content controls and maps Employee details other than Customer details to it. paragraph = document.LastSection.AddParagraph(); if (empChildIndex == 0) paragraph.AppendText("Name: "); else paragraph.AppendText(employeesDetails[empChildIndex] + ": "); } else paragraph.AppendText(" "); MapCustomXMLPart(paragraph, empPath + employeesDetails[empChildIndex].Replace(" ",""), docIOxmlPart); } empChildIndex++; } } /// <summary> /// Insert a content controls and maps Customer details to it. /// </summary> /// <param name="document">Word document instance.</param> /// <param name="customerNode">CustomXMLNode of customer.</param> /// <param name="docIOxmlPart">CustomXMLPart instance.</param> /// <param name="empPath">Current employee index.</param> /// <param name="custIndex">Current customer index.</param> private void InsertAndMapCustomer(WordDocument document, CustomXMLNode customerNode, CustomXMLPart docIOxmlPart, string empPath, int custIndex) { //Column names of Customer element. string[] customersDetails = { "Customer ID", "Employee ID", "Company Name", "Contact Name", "City", "Country" }; document.LastSection.AddParagraph(); //Adds new paragraph to the section IWParagraph paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.BackColor = Syncfusion.Drawing.Color.Green; paragraph.ParagraphFormat.LeftIndent = 72; IWTextRange textrange = paragraph.AppendText("Customers"); textrange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; textrange.CharacterFormat.Bold = true; textrange.CharacterFormat.FontSize = 14; int orderIndex = 1; int custChild = 0; bool isFirstOrder = true; string customerXpath = empPath + "Customers[" + custIndex + "]/"; foreach (CustomXMLNode customerChild in customerNode.ChildNodes) { if (customerChild.HasChildNodes()) { //Insert a content controls and maps Orders details to it. InsertAndMapOrders(document, customerChild, docIOxmlPart, customerXpath, orderIndex, isFirstOrder); document.LastSection.AddParagraph(); isFirstOrder = false; orderIndex++; } else { //Insert a content controls and maps Customer details other than Order details to it. paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.LeftIndent = 72; paragraph.AppendText(customersDetails[custChild] + ": "); MapCustomXMLPart(paragraph, customerXpath + customersDetails[custChild].Replace(" ", ""), docIOxmlPart); } custChild++; } } /// <summary> /// Insert a content controls and maps Orders details to it. /// </summary> /// <param name="document">Word document instance.</param> /// <param name="orderNode">CustomXMLNode of order.</param> /// <param name="docIOxmlPart">CustomXMLPart instance.</param> /// <param name="custPath">Current customer index</param> /// <param name="orderIndex">Current order index</param> /// <param name="isFirst">Indicates whether it is the first order of the customer.</param> private void InsertAndMapOrders(WordDocument document, CustomXMLNode orderNode, CustomXMLPart docIOxmlPart, string custPath, int orderIndex, bool isFirst) { //Column names of order element. string[] ordersDetails = { "Order ID", "Customer ID", "Order Date", "Shipped Date", "Required Date" }; IWParagraph paragraph = null; IWTextRange textrange = null; if (isFirst) { document.LastSection.AddParagraph(); //Adds new paragraph to the section paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.BackColor = Syncfusion.Drawing.Color.Red; paragraph.ParagraphFormat.LeftIndent = 128; textrange = paragraph.AppendText("Orders"); textrange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; textrange.CharacterFormat.Bold = true; textrange.CharacterFormat.FontSize = 14; } int orderChildIndex = 0; string customerXpath = custPath + "Orders[" + orderIndex + "]/"; foreach (CustomXMLNode orderChild in orderNode.ChildNodes) { //Adds new paragraph to the section paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.LeftIndent = 128; paragraph.AppendText(ordersDetails[orderChildIndex] + ": "); MapCustomXMLPart(paragraph, customerXpath + "/" + ordersDetails[orderChildIndex].Replace(" ", ""), docIOxmlPart); orderChildIndex++; } } # endregion public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Frame; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Android/SampleBrowser/Samples/RangeSlider/GettingStarted_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Com.Syncfusion.Sfrangeslider; using Android.Widget; using Android.Views; using Android.Graphics; using SampleBrowser; using droid = Android.Widget.Orientation; using System.Collections.Generic; using System; namespace SampleBrowser { //[con(Label = "Getting Started")] public class GettingStarted_Mobile { /********************************* **Local Variable Inizialisation** *********************************/ SfRangeSlider range, range2; public static TickPlacement tickplacement = TickPlacement.BottomRight; public static ValuePlacement valueplacement = ValuePlacement.BottomRight; public static bool showlabel = true; public static SnapsTo snapsto = SnapsTo.None; string fromvalue, toValue, fromValue1, toValue1; public static int rangeHeight; LinearLayout linearLayout; TextView departureLabel; Context con,context; TextView arrivalLabel, snapsToLabel; Spinner tickSpinner, labelSpinner; LinearLayout propertylayout, stackView3, stackView4; ArrayAdapter<String> labelAdapter, dataAdapter; int width; public View GetSampleContent(Context con1) { con = con1; linearLayout = new LinearLayout(con); linearLayout.SetPadding(20, 20, 20, 30); linearLayout.SetBackgroundColor(Color.Rgb(236, 235, 242)); linearLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); linearLayout.Orientation = Android.Widget.Orientation.Vertical; rangeHeight = getDimensionPixelSize(con, Resource.Dimension.range_ht); DepatureLayout(); //RangeSlider range = new SfRangeSlider(con); range.Minimum = 0; range.Maximum = 12; range.TickFrequency = 2; range.ShowValueLabel = true; range.StepFrequency = 6; range.DirectionReversed = false; range.ValuePlacement =Com.Syncfusion.Sfrangeslider.ValuePlacement.BottomRight; range.RangeEnd = 12; range.RangeStart = 0; range.TickPlacement = Com.Syncfusion.Sfrangeslider.TickPlacement.BottomRight; range.ShowRange = true; range.SnapsTo = Com.Syncfusion.Sfrangeslider.SnapsTo.None; range.Orientation = Com.Syncfusion.Sfrangeslider.Orientation.Horizontal; range.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, rangeHeight); TimeLabelLayout(); linearLayout.AddView(range); ArrivalLabelLayout(); //rangeSlider range2 = new SfRangeSlider(con); range2.Minimum = 0; range2.Maximum = 12; range2.TickFrequency = 2; range2.ShowValueLabel = true; range2.StepFrequency = 6; range2.DirectionReversed = false; range2.ValuePlacement = Com.Syncfusion.Sfrangeslider.ValuePlacement.BottomRight; range2.RangeEnd = 12; range2.RangeStart = 0; range2.TickPlacement = Com.Syncfusion.Sfrangeslider.TickPlacement.BottomRight; range2.ShowRange = true; range2.SnapsTo = Com.Syncfusion.Sfrangeslider.SnapsTo.None; range2.Orientation = Com.Syncfusion.Sfrangeslider.Orientation.Horizontal; range2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, rangeHeight); TimeLableLayout2(); return linearLayout; } private void DepatureLayout() { //departureLabel departureLabel = new TextView(con); departureLabel.TextSize = 20; departureLabel.Text = " " + "Departure"; departureLabel.SetTextColor(Color.Black); } private void TimeLabelLayout() { //depstack LinearLayout depstack = new LinearLayout(con); depstack.Orientation = Android.Widget.Orientation.Horizontal; depstack.AddView(departureLabel); TextView timeLabel = new TextView(con); timeLabel.TextSize = 13; timeLabel.Text = " " + "(in Hours)"; timeLabel.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent); timeLabel.SetTextColor(Color.ParseColor("#939394")); timeLabel.Gravity = GravityFlags.Center; depstack.AddView(timeLabel); //snapsToLabel TextView snapsToLabel = new TextView(con); snapsToLabel.SetHeight(50); //linearLayout.AddView(snapsToLabel); linearLayout.AddView(depstack); TextView timeLabel1 = new TextView(con); TextView textView12 = new TextView(con); linearLayout.AddView(textView12); linearLayout.AddView(timeLabel1); //timeLabel1 timeLabel1.TextSize = 13; fromValue1 = "12"; toValue1 = Math.Round(range.RangeEnd).ToString(); timeLabel1.SetTextColor(Color.ParseColor("#939394")); timeLabel1.Text = " " + "Time: " + fromValue1 + "AM " + " - " + toValue1 + " PM"; timeLabel1.Gravity = GravityFlags.Left; range.RangeChanged += (object sender, RangeChangedEventArgs e) => { String pMeridian = "AM", pMeridian1 = "AM"; if (Math.Round(e.RangeStart).ToString() == "0") { fromValue1 = "12"; pMeridian1 = "AM"; } else fromValue1 = Convert.ToString(Math.Round(e.RangeStart)); if (e.RangeEnd <= 12) toValue1 = Convert.ToString(Math.Round(e.RangeEnd)); if (Math.Round(e.RangeEnd).ToString() == "12") pMeridian = "PM"; if (Math.Round(e.RangeEnd).ToString() == "12") pMeridian = "PM"; if (Convert.ToString(Math.Round(e.RangeStart)).Equals(Convert.ToString(Math.Round(e.RangeEnd)))) { if (Math.Round(e.RangeStart).ToString() == "0") timeLabel1.Text = " " + "Time: " + fromValue1 + " " + pMeridian1; else if (Math.Round(e.RangeEnd).ToString() == "12") timeLabel1.Text = " " + "Time: " + toValue1 + " " + pMeridian; else timeLabel1.Text = " " + "Time: " + fromValue1 + " " + pMeridian1; } else timeLabel1.Text = " " + "Time: " + fromValue1 + " " + pMeridian1 + " - " + toValue1 + " " + pMeridian; }; } private void ArrivalLabelLayout() { //showLabel TextView showLabel = new TextView(con); // showLabel.SetHeight(30); linearLayout.AddView(showLabel); arrivalLabel = new TextView(con); arrivalLabel.TextSize = 20; arrivalLabel.Text = " " + "Arrival"; arrivalLabel.SetTextColor(Color.Black); } private void TimeLableLayout2() { //timeLabel TextView timeLabel2 = new TextView(con); timeLabel2.TextSize = 13; timeLabel2.Text = " " + "(in Hours)"; timeLabel2.Gravity = GravityFlags.Center; timeLabel2.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent); timeLabel2.SetTextColor(Color.ParseColor("#939394")); //AdjLabel TextView adjLabel8 = new TextView(con); adjLabel8.SetHeight(50); LinearLayout arrivestack = new LinearLayout(con); arrivestack.Orientation = Android.Widget.Orientation.Horizontal; arrivestack.AddView(arrivalLabel); arrivestack.AddView(timeLabel2); //linearLayout linearLayout.AddView(adjLabel8); linearLayout.AddView(arrivestack); TextView adjLabel9 = new TextView(con); linearLayout.AddView(adjLabel9); TextView timeLabel3 = new TextView(con); linearLayout.AddView(timeLabel3); linearLayout.AddView(range2); //timeLabel timeLabel3.TextSize = 13; timeLabel3.SetTextColor(Color.ParseColor("#939394")); fromvalue = "12"; toValue = Math.Round(range2.RangeEnd).ToString(); timeLabel3.Text = " " + "Time: " + fromvalue + "AM " + " - " + toValue + " PM"; timeLabel3.Gravity = GravityFlags.Left; range2.RangeChanged += (object sender, RangeChangedEventArgs e) => { String pMeridian = "AM", pMeridian1 = "AM"; if (Math.Round(e.RangeStart).ToString() == "0") { fromvalue = "12"; pMeridian1 = "AM"; } else fromvalue = Convert.ToString(Math.Round(e.RangeStart)); if (e.RangeEnd <= 12) toValue = Convert.ToString(Math.Round(e.RangeEnd)); if (Math.Round(e.RangeEnd).ToString() == "12") pMeridian = "PM"; if (Convert.ToString(Math.Round(e.RangeStart)).Equals(Convert.ToString(Math.Round(e.RangeEnd)))) { if (Math.Round(e.RangeStart).ToString() == "0") timeLabel3.Text = " " + "Time: " + fromvalue + " " + pMeridian1; else if (Math.Round(e.RangeEnd).ToString() == "12") timeLabel3.Text = " " + "Time: " + toValue + " " + pMeridian; else timeLabel3.Text = " " + "Time: " + fromvalue + " " + pMeridian1; } else timeLabel3.Text = " " + "Time: " + fromvalue + " " + pMeridian1 + " - " + toValue + " " + pMeridian; }; } public View GetPropertyWindowLayout(Android.Content.Context context1) { context = context1; width = context.Resources.DisplayMetrics.WidthPixels / 2; TickPlacementLayout(); LabelPlacementLayout(); ShowLabelLayout(); SnapsToLayout(); return propertylayout; } private void TickPlacementLayout() { propertylayout = new LinearLayout(context); propertylayout.Orientation = droid.Vertical; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width * 2, 5); layoutParams.SetMargins(0, 5, 0, 0); //TICK PLACEMENT TextView placementLabel = new TextView(context); placementLabel.Text = " " + "Tick Placement"; placementLabel.TextSize = 20; placementLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); placementLabel.SetTextColor(Color.Black); placementLabel.Gravity = GravityFlags.Left; TextView adjLabel2 = new TextView(context); adjLabel2.SetHeight(14); propertylayout.AddView(adjLabel2); //tickSpinner tickSpinner = new Spinner(context,SpinnerMode.Dialog); tickSpinner.SetPadding(0, 0, 0, 0); propertylayout.AddView(placementLabel); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); //propertylayout.AddView(separate, layoutParams); TextView adjLabel3 = new TextView(context); adjLabel3.SetHeight(20); //propertylayout.AddView(adjLabel3); propertylayout.AddView(tickSpinner); TextView adjLabel4 = new TextView(context); propertylayout.AddView(adjLabel4); //positionList List<String> positionList = new List<String>(); positionList.Add("BottomRight"); positionList.Add("TopLeft"); positionList.Add("Outside"); positionList.Add("Inline"); positionList.Add("None"); //dataAdapter dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, positionList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //tickSpinner tickSpinner.Adapter = dataAdapter; tickSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("BottomRight")) { tickplacement = TickPlacement.BottomRight; } else if (selectedItem.Equals("TopLeft")) { tickplacement = TickPlacement.TopLeft; } else if (selectedItem.Equals("Inline")) { tickplacement = TickPlacement.Inline; } else if (selectedItem.Equals("Outside")) { tickplacement = TickPlacement.Outside; } else if (selectedItem.Equals("None")) { tickplacement = TickPlacement.None; } }; } private void LabelPlacementLayout() { //LABEL PLACEMENT TextView departureLabel = new TextView(context); departureLabel.Text = " " + "Label Placement"; departureLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); departureLabel.Gravity = GravityFlags.Left; departureLabel.TextSize = 20; departureLabel.SetTextColor(Color.Black); List<String> labelList = new List<String>(); labelList.Add("BottomRight"); labelList.Add("TopLeft"); //labelSpinner labelSpinner = new Spinner(context,SpinnerMode.Dialog); labelSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("TopLeft")) { valueplacement = ValuePlacement.TopLeft; } else if (selectedItem.Equals("BottomRight")) { valueplacement = ValuePlacement.BottomRight; } }; //labelAdapter labelAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, labelList); labelAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); labelSpinner.Adapter = labelAdapter; labelSpinner.SetPadding(0, 0, 0, 0); LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(width * 2, 7); layoutParams2.SetMargins(0, 5, 0, 0); propertylayout.AddView(departureLabel); //separate2 SeparatorView separate2 = new SeparatorView(context, width * 2); separate2.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 7); // propertylayout.AddView(separate2, layoutParams2); //snapsToLabel snapsToLabel = new TextView(context); snapsToLabel.SetHeight(20); //propertylayout.AddView(snapsToLabel); propertylayout.AddView(labelSpinner); propertylayout.SetPadding(15, 0, 15, 0); TextView adjLabel12 = new TextView(context); adjLabel12.SetHeight(20); propertylayout.AddView(adjLabel12); } private void ShowLabelLayout() { //showLabel TextView showLabel = new TextView(context); showLabel.Text = " " + "Show Label"; showLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); showLabel.Gravity = GravityFlags.Center; showLabel.TextSize = 20; //checkBox Switch checkBox = new Switch(context); checkBox.Checked = true; checkBox.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { if (e.IsChecked) showlabel = true; else showlabel = false; }; //layoutParams LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams3.SetMargins(0, 10, 0, 0); LinearLayout.LayoutParams layoutParams4 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, 55); layoutParams4.SetMargins(0, 10, 0, 0); TextView textSpacing1 = new TextView(context); propertylayout.AddView(textSpacing1); //stackView stackView3 = new LinearLayout(context); stackView3.AddView(showLabel); stackView3.AddView(checkBox, layoutParams3); stackView3.Orientation = droid.Horizontal; propertylayout.AddView(stackView3); SeparatorView separate3 = new SeparatorView(context, width * 2); separate3.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams layoutParams7 = new LinearLayout.LayoutParams(width * 2, 5); layoutParams7.SetMargins(0, 30, 0, 0); //propertylayout.AddView(separate3, layoutParams7); } private void SnapsToLayout() { //SnapsToTicks snapsToLabel = new TextView(context); snapsToLabel.Text = " " + "Snaps To Tick"; snapsToLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); snapsToLabel.Gravity = GravityFlags.Center; snapsToLabel.TextSize = 20; //SnapsToTicks CheckBox Switch checkBox2 = new Switch(context); checkBox2.Checked = false; checkBox2.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { if (e.IsChecked) snapsto = SnapsTo.Ticks; else snapsto = SnapsTo.None; }; //layoutParams LinearLayout.LayoutParams layoutParams5 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams5.SetMargins(0, 20, 0, 0); LinearLayout.LayoutParams layoutParams6 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, 55); layoutParams6.SetMargins(0, 20, 0, 0); TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //stackView stackView4 = new LinearLayout(context); stackView4.AddView(snapsToLabel); stackView4.AddView(checkBox2, layoutParams5); stackView4.Orientation = droid.Horizontal; propertylayout.AddView(stackView4); SeparatorView separate4 = new SeparatorView(context, width * 2); separate4.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams layoutParams8 = new LinearLayout.LayoutParams(width * 2, 5); layoutParams8.SetMargins(0, 30, 0, 0); // propertylayout.AddView(separate4, layoutParams8); TextView textSpacing1 = new TextView(context); propertylayout.AddView(textSpacing1); } public static int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } public void OnApplyChanges() { range2.TickPlacement = tickplacement; range.TickPlacement = tickplacement; range2.ValuePlacement = valueplacement; range.ValuePlacement = valueplacement; range2.ShowValueLabel = showlabel; range.ShowValueLabel = showlabel; range2.SnapsTo = snapsto; range.SnapsTo = snapsto; } } }<file_sep>/Forms/DataGrid/DataGrid.iOS/DataGridDependencyService.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DataGridDependencyService.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using SampleBrowser.SfDataGrid.iOS; using UIKit; using Xamarin.Forms; [assembly: Dependency(typeof(DataGridDependencyService))] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed.")] namespace SampleBrowser.SfDataGrid.iOS { /// <summary> /// A dependency Service for DataGrid Samples. /// </summary> internal class DataGridDependencyService : IDataGridDependencyService { /// <summary> /// Used to get the device orientation in IOS platform /// </summary> /// <returns>Current device Orientation in IOS devices</returns> public string GetOrientation() { return UIDevice.CurrentDevice.Orientation.ToString(); } } }<file_sep>/Forms/Chips/Chips/Samples/GettingStarted/GettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.Buttons; using Xamarin.Forms; namespace SampleBrowser.Chips { /// <summary> /// Demonstrates the basic UI customization of SfChip control. /// </summary> public partial class GettingStarted : SampleView { #region GettingStarted constructor ChipViewModel viewModel; /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.Chips.GettingStarted"/> class. /// </summary> public GettingStarted() { viewModel = new ChipViewModel(); this.BindingContext = viewModel; InitializeComponent(); } /// <summary> /// Handles the selection changed. /// </summary> /// <param name="sender">Sender as TabView.</param> /// <param name="e">E as SelectionChangedEventArgs.</param> void Handle_SelectionChanged(object sender, Syncfusion.XForms.Buttons.SelectionChangedEventArgs e) { if ((sender as SfSegmentedControl) == TextColorSegment) { viewModel.TextColor = viewModel.PrimaryTextColors[e.Index].FontIconFontColor; this.TextColorSegment.SelectionTextColor = viewModel.PrimaryTextColors[e.Index].FontIconFontColor; } else if ((sender as SfSegmentedControl) == BackgroundColorSegment) { viewModel.BackgroundColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; this.BackgroundColorSegment.SelectionTextColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; } else if ((sender as SfSegmentedControl) == BorderColorSegment) { viewModel.BorderColorProperty = viewModel.PrimaryColors[e.Index].FontIconFontColor; this.BorderColorSegment.SelectionTextColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; } } #endregion } }<file_sep>/Android/SampleBrowser/Samples/XlsIO/FormulasPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using COLOR = Syncfusion.Drawing.Color; namespace SampleBrowser { public partial class FormulasPage : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates calculating cell values using formulas. "; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Excel"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { #region Workbook Initialize ExcelEngine engine = new ExcelEngine(); IApplication application = engine.Excel; application.DefaultVersion = ExcelVersion.Excel2016; IWorkbook workbook = application.Workbooks.Create(1); IWorksheet sheet = workbook.Worksheets[0]; sheet.EnableSheetCalculations(); sheet["A40"].Activate(); #endregion #region Worksheet Data sheet.Name = "Inventory"; sheet.IsGridLinesVisible = false; sheet["A1"].Text = "INVENTORY LIST"; sheet["A3"].Text = "TOTAL INVENTORY VALUE"; sheet["D3"].Text = "TOTAL ITEMS"; sheet["F3"].Text = "BIN COUNT"; sheet["A6"].Text = "ID"; sheet["B6"].Text = "Name"; sheet["C6"].Text = "Bin #"; sheet["D6"].Text = "Unit Price"; sheet["E6"].Text = "Quantity in Stock"; sheet["F6"].Text = "Inventory Value"; sheet["A7"].Text = "IN001"; sheet["B7"].Text = "Item 1"; sheet["C7"].Text = "T340"; sheet["D7"].Number = 51; sheet["E7:E26"].Number = 25; sheet["A8"].Text = "IN002"; sheet["B8"].Text = "Item 2"; sheet["C8"].Text = "T5780"; sheet["D8"].Number = 93; sheet["A9"].Text = "IN003"; sheet["B9"].Text = "Item 3"; sheet["C9"].Text = "T340"; sheet["D9"].Number = 57; sheet["A10"].Text = "IN004"; sheet["B10"].Text = "Item 4"; sheet["C10"].Text = "T908"; sheet["D10"].Number = 19; sheet["A11"].Text = "IN005"; sheet["B11"].Text = "Item 5"; sheet["C11"].Text = "T9845"; sheet["D11"].Number = 75; sheet["A12"].Text = "IN006"; sheet["B12"].Text = "Item 6"; sheet["C12"].Text = "T540"; sheet["D12"].Number = 11; sheet["A13"].Text = "IN007"; sheet["B13"].Text = "Item 7"; sheet["C13"].Text = "T5780"; sheet["D13"].Number = 56; sheet["A14"].Text = "IN008"; sheet["B14"].Text = "Item 8"; sheet["C14"].Text = "T340"; sheet["D14"].Number = 38; sheet["A15"].Text = "IN009"; sheet["B15"].Text = "Item 9"; sheet["C15"].Text = "T908"; sheet["D15"].Number = 59; sheet["A16"].Text = "IN010"; sheet["B16"].Text = "Item 10"; sheet["C16"].Text = "T9845"; sheet["D16"].Number = 50; sheet["A17"].Text = "IN011"; sheet["B17"].Text = "Item 11"; sheet["C17"].Text = "T306"; sheet["D17"].Number = 59; sheet["A18"].Text = "IN012"; sheet["B18"].Text = "Item 12"; sheet["C18"].Text = "T5780"; sheet["D18"].Number = 18; sheet["A19"].Text = "IN013"; sheet["B19"].Text = "Item 13"; sheet["C19"].Text = "T306"; sheet["D19"].Number = 26; sheet["A20"].Text = "IN014"; sheet["B20"].Text = "Item 14"; sheet["C20"].Text = "T908"; sheet["D20"].Number = 42; sheet["A21"].Text = "IN015"; sheet["B21"].Text = "Item 15"; sheet["C21"].Text = "T9845"; sheet["D21"].Number = 32; sheet["A22"].Text = "IN016"; sheet["B22"].Text = "Item 16"; sheet["C22"].Text = "T415"; sheet["D22"].Number = 90; sheet["A23"].Text = "IN017"; sheet["B23"].Text = "Item 17"; sheet["C23"].Text = "T5780"; sheet["D23"].Number = 12; sheet["A24"].Text = "IN018"; sheet["B24"].Text = "Item 18"; sheet["C24"].Text = "T340"; sheet["D24"].Number = 82; sheet["A25"].Text = "IN019"; sheet["B25"].Text = "Item 19"; sheet["C25"].Text = "T908"; sheet["D25"].Number = 16; sheet["A26"].Text = "IN020"; sheet["B26"].Text = "Item 20"; sheet["C26"].Text = "T9845"; sheet["D26"].Number = 11; sheet["A27"].Text = "Total"; #endregion #region Formatting sheet.Range["A1:F1"].Merge(); sheet.Range["A4:B4"].Merge(); sheet["A1"].CellStyle.Font.Bold = true; sheet["A1"].CellStyle.Font.FontName = "Calibri"; sheet["A1"].CellStyle.Font.Size = 18; sheet.Range["A1:F1"].CellStyle.IncludeBorder = true; sheet.Range["A1:F1"].CellStyle.Borders[ExcelBordersIndex.EdgeBottom].ColorRGB = COLOR.FromArgb(0, 204, 153); sheet.Range["A1:F1"].CellStyle.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Medium; sheet["A3:F3"].CellStyle.Font.Bold = true; sheet["A3:F3"].CellStyle.Font.FontName = "Calibri"; sheet["A3:F3"].CellStyle.Font.Size = 9; sheet["A4:F4"].CellStyle.Font.Bold = true; sheet["A4:F4"].CellStyle.Font.FontName = "Calibri"; sheet["A4:F4"].CellStyle.Font.Size = 14; sheet["A4:F4"].CellStyle.Font.RGBColor = COLOR.FromArgb(0, 204, 153); sheet["A4"].HorizontalAlignment = ExcelHAlign.HAlignCenter; sheet["A4"].NumberFormat = "_($* #,##0.00_)"; sheet["A6:F6"].CellStyle.Font.FontName = "Calibri"; sheet["A6:F6"].CellStyle.Font.Size = 11; sheet["A6:F6"].CellStyle.Font.Bold = true; sheet["A6:F6"].CellStyle.Font.RGBColor = COLOR.FromArgb(255, 255, 255); sheet["A6:F6"].WrapText = true; sheet["A6:F6"].VerticalAlignment = ExcelVAlign.VAlignTop; sheet.Range["A6:F6"].CellStyle.Color = COLOR.FromArgb(0, 204, 153); sheet["A6:F27"].CellStyle.Font.FontName = "Calibri"; sheet["A6:F27"].CellStyle.Font.Size = 11; sheet["D7:F27"].NumberFormat = "_($* #,##0.00_)"; sheet["D4:F4"].HorizontalAlignment = ExcelHAlign.HAlignLeft; sheet["A27:F27"].CellStyle.Font.FontName = "Calibri"; sheet["A27:F27"].CellStyle.Font.Size = 11; sheet["A27:F27"].CellStyle.Font.Bold = true; sheet.Range["A7:27"].CellStyle.IncludeBorder = true; sheet.Range["A7:F27"].CellStyle.Borders.ColorRGB = COLOR.FromArgb(112, 173, 71); sheet.Range["A7:F27"].CellStyle.Borders.LineStyle = ExcelLineStyle.Thin; sheet.Range["A7:F27"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine = false; sheet.Range["A7:F27"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false; sheet["A26:F26"].CellStyle.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Double; sheet.Range["A1:F1"].RowHeight = 24; sheet["A2"].RowHeight = 7.18; sheet["A3"].RowHeight = 23.5; sheet["A4"].RowHeight = 19.5; sheet["A5"].RowHeight = 6.8; sheet["A6"].RowHeight = 41.3; sheet["A1:B1"].ColumnWidth = 7.18; sheet["C1"].ColumnWidth = 6.91; sheet["D1"].ColumnWidth = 9.55; sheet["E1"].ColumnWidth = 8.91; sheet["F1"].ColumnWidth = 11.18; #endregion #region Formula sheet["D4"].Formula = "=COUNT(D7:D26)"; sheet["F4"].Formula = "=SUMPRODUCT(1/COUNTIF(C7:C26,C7:C26))"; for (int i = 7; i < 27; i++) sheet["F" + i].Formula = "=D" + i + "*E" + i; sheet["D27"].Formula = "SUM(D7:D26)"; sheet["E27"].Formula = "SUM(E7:E26)"; sheet["F27"].Formula = "SUM(F7:F26)"; sheet["A4"].Formula = "=F27"; #endregion workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); engine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("Formulas.xlsx", "application/msexcel", stream, m_context); } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/OHLC.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; namespace SampleBrowser { public class OHLC : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Financial Analysis"; chart.Title.TextSize = 15; DateTimeAxis dateTimeAxis = new DateTimeAxis(); dateTimeAxis.LabelStyle.LabelFormat = "MM/dd/yyyy"; dateTimeAxis.LabelRotationAngle = -45; dateTimeAxis.Title.Text = "Date"; chart.PrimaryAxis = dateTimeAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Title.Text = "Price in Dollar"; numericalAxis.Minimum = 0; numericalAxis.Maximum = 250; numericalAxis.Interval = 50; numericalAxis.LabelStyle.LabelFormat = "$##.##"; chart.SecondaryAxis = numericalAxis; chart.Series.Add(new HiLoOpenCloseSeries { StrokeWidth = 5, ItemsSource = MainPage.GetOhlcData(), XBindingPath = "XValue", Open = "Open", Close = "Close", High = "High", Low = "Low", TooltipEnabled = true, EnableAnimation = true, }); return chart; } } }<file_sep>/Forms/Chart/Chart/Samples/Tooltip/TooltipViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser.SfChart { class TooltipViewModel { public ObservableCollection<ChartDataModel> LineData1 { get; set; } public ObservableCollection<ChartDataModel> LineData2 { get; set; } public TooltipViewModel() { LineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2005, 60), new ChartDataModel(2006, 42), new ChartDataModel(2007, 62), new ChartDataModel(2008, 82), new ChartDataModel(2009, 84), new ChartDataModel(2010, 98), new ChartDataModel(2011, 85) }; LineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2005, 30), new ChartDataModel(2006, 12), new ChartDataModel(2007, 32), new ChartDataModel(2008, 52), new ChartDataModel(2009, 54), new ChartDataModel(2010, 68), new ChartDataModel(2011, 55) }; } } }<file_sep>/Android/SampleBrowser/Samples/PDFViewer/CustomToolBarGettingStartedPDFViewer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.SfPdfViewer.Android; using System.IO; using System.Reflection; using Android.Views.InputMethods; using System.Diagnostics; using static Android.Views.ViewGroup; using Android.Graphics; using Com.Syncfusion.Sfrangeslider; using Syncfusion.Pdf.Parsing; using Android.Util; using Android.Graphics.Drawables; using Syncfusion.Android.PopupLayout; using Android.Text.Method; using Android.Content.Res; using Syncfusion.Pdf; namespace SampleBrowser { [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] public class CustomToolBarPdfViewerDemo : SamplePage { internal SfPdfViewer pdfViewerControl; string selectedText = ""; EditText pageNumberEntry; TextView pageCountText; LinearLayout mainView; internal FrameLayout m_topToolbars; internal LinearLayout m_bottomToolbars; LinearLayout toolBarGrid; GridLayout bottomtoolBarGrid; LinearLayout annotationBarGrid; GridLayout annotationBackGrid; GridLayout searchBarGrid; LinearLayout annotationColorBarGrid; EditText searchView; Button searchButton; Button bookmarkButton; Button viewModeButton; Button stampButton; Button backButton; Button clearSearchButton; Context pdfViewerContext; Button selectionButton; string backupDocumentName = string.Empty; Button annotationModeButton; Button highlightModeButton; Button underlineModeButton; Button strikeoutModeButton; Button annotationBackButton; Button annotationColorButton; internal bool m_isAnnotationModeSelected; internal bool isLoadedDocument = false; Button cyancolorButton; Button yellowcolorButton; Button greencolorButton; Button magentacolorButton; Button whitecolorButton; Button blackcolorButton; Button removeButton; Button undoButton; Button redoButton; Button saveButton; TextMarkupAnnotation annotation; FrameLayout annotationToolBar; Button annotationButton; internal Color fontColor; float textSize = 27; float viewModeTextSize = 22; FrameLayout annotationsToolbar; LinearLayout annotationsGrid; Button TextMarkupAnnotationButton; Button ShapeAnnotationButton; Button InkAnnotationButton; FrameLayout inkannotationtoolbar; GridLayout inkannotationgrid; Button inkundobutton; Button inkredobutton; Button inkannotationbackbutton; FrameLayout inkannotationbottomtoolbar; GridLayout inkannotationbottomgrid; Button inkannotationThicknessButton; Button inkAnnotationColorButton; FrameLayout inkannotationthicknessToolbar; GridLayout inkannotationthicknessGrid; LinearLayout lineView1; FrameLayout annotationbottomcolortoolbar; Button opacityButton; Button inkBackButton; Button inkButton; internal int currentColorPosition; FrameLayout inkannotationbottomopacitytoolbar; ImageButton lineFive1; ImageButton lineFour1; ImageButton lineOne1; LinearLayout linesLayout1; ImageButton lineThree1; ImageButton lineTwo1; private ImageButton lineOneContainer1; private ImageButton lineTwoContainer1; private ImageButton lineThreeContainer1; private ImageButton lineFourContainer1; private ImageButton lineFiveContainer1; SeekBar seekbar1; InkAnnotation inkannot; HandwrittenSignature signature; bool m_opacityChanged; Button textmarkupannotationBackButton; Button inkremovebutton; TextView endprogressLabel; bool m_thicknessChanged; FrameLayout m_shapeAnnoationToolbar; internal LinearLayout m_rangeSliderView; private TextView m_rangeSliderText; internal Com.Syncfusion.Sfrangeslider.SfRangeSlider m_rangeSlider; private string fontValue; internal BookmarkToolbar bookmarkToolbar; internal StampSelectionView stampSelectionView; internal bool isBookmarkVisible; MainViewLayoutListener layoutListener; internal FrameLayout bookmarkToolbarParentLayout; private Button signaturePadButton; internal PopupWindow popup; internal bool disableToolbar; internal bool enableToolbar; internal Stream PdfStream = null; internal SfPopupLayout initialPopup; internal TextView titleText; internal EditText editText; internal LinearLayout footerLinear; internal LinearLayout headerLinear; internal int i = 0; internal Button acceptButton; internal Button declineButton; internal TextView errorView; internal ScreenSize screenSize; public override View GetSampleContent(Context context) { m_context = context; layoutListener = new MainViewLayoutListener(); fontColor = new Color(0, 118, 255); font = Typeface.CreateFromAsset(context.Assets, "PDFViewer_Android.ttf"); fontSizeFont = Typeface.CreateFromAsset(context.Assets, "Font size Font.ttf"); bookmarkFont = Typeface.CreateFromAsset(context.Assets, "PdfViewer_FONT.ttf"); viewModeFont = Typeface.CreateFromAsset(context.Assets, "Android Page icons.ttf"); stampFont = Typeface.CreateFromAsset(context.Assets, "Font Text edit stamp.ttf"); signatureFont = Typeface.CreateFromAsset(context.Assets, "Signature_PDFViewer_FONT.ttf"); LayoutInflater layoutInflater = LayoutInflater.From(context); pdfViewerContext = context; mainView = (LinearLayout)layoutInflater.Inflate(Resource.Layout.CustomToolbarPDFViewer, null); //The FrameLayout on which the bookmark toolbar will be added for tablet. bookmarkToolbarParentLayout = (FrameLayout)mainView.FindViewById<FrameLayout>(Resource.Id.bookmarkParent); mainView.AddOnLayoutChangeListener(layoutListener); m_topToolbars = (FrameLayout)mainView.FindViewById(Resource.Id.top); m_bottomToolbars = (LinearLayout)mainView.FindViewById(Resource.Id.bottom); pageNumberEntry = (EditText)mainView.FindViewById(Resource.Id.pagenumberentry1); pageNumberEntry.KeyPress += PageNumberEntry_KeyPress; pageCountText = (TextView)mainView.FindViewById(Resource.Id.pagecounttext1); searchButton = mainView.FindViewById<Button>(Resource.Id.searchButton); searchButton.Typeface = font; bookmarkButton = mainView.FindViewById<Button>(Resource.Id.bookmarkbutton); bookmarkButton.Typeface = bookmarkFont; bookmarkButton.TextSize = textSize; bookmarkButton.SetTextColor(fontColor); bookmarkButton.Click += BookmarkButton_Click; viewModeButton = mainView.FindViewById<Button>(Resource.Id.viewmodebutton); viewModeButton.Typeface = viewModeFont; viewModeButton.TextSize = viewModeTextSize; viewModeButton.SetTextColor(fontColor); viewModeButton.Click += ViewModeButton_Click; stampButton = mainView.FindViewById<Button>(Resource.Id.stampButton); stampButton.Typeface = stampFont; stampButton.TextSize = textSize; stampButton.SetTextColor(fontColor); stampButton.Click += StampButton_Click; searchButton.SetTextColor(fontColor); searchButton.TextSize = textSize; searchButton.Click += SearchButton_Click; saveButton = mainView.FindViewById<Button>(Resource.Id.savebutton); saveButton.Typeface = font; saveButton.TextSize = textSize; saveButton.SetTextColor(fontColor); saveButton.Click += SaveButton_Click; undoButton = mainView.FindViewById<Button>(Resource.Id.undobutton); undoButton.Typeface = font; undoButton.TextSize = textSize; undoButton.SetTextColor(Color.Gray); undoButton.Click += UndoButton_Click; redoButton = mainView.FindViewById<Button>(Resource.Id.redobutton); redoButton.SetTextColor(Color.Gray); redoButton.Typeface = font; redoButton.TextSize = textSize; redoButton.Click += RedoButton_Click; removeButton = mainView.FindViewById<Button>(Resource.Id.removebutton); removeButton.Typeface = font; removeButton.SetTextColor(fontColor); removeButton.TextSize = textSize; removeButton.Click += RemoveButton_Click; annotationModeButton = (Button)mainView.FindViewById(Resource.Id.annotationbutton); annotationModeButton.Typeface = font; annotationModeButton.SetTextColor(fontColor); annotationModeButton.TextSize = textSize; annotationModeButton.Click += AnnotationModeButton_Click; pdfViewerControl = (SfPdfViewer)mainView.FindViewById(Resource.Id.pdfviewercontrol); pdfViewerControl.DocumentLoaded += PdfViewerControl_DocumentLoaded; pdfViewerControl.PageChanged += PdfViewerControl_PageChanged; backupDocumentName = "F# Succinctly"; Stream docStream = typeof(PdfViewerDemo).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDFViewer.Assets." + backupDocumentName + ".pdf"); annotationToolBar = mainView.FindViewById<FrameLayout>(Resource.Id.annotationtoolbar); annotationToolBar.Visibility = ViewStates.Gone; toolBarGrid = mainView.FindViewById<LinearLayout>(Resource.Id.toolbarGrid); toolBarGrid.Visibility = ViewStates.Visible; bottomtoolBarGrid = mainView.FindViewById<GridLayout>(Resource.Id.bottomtoolbarGrid); bottomtoolBarGrid.Visibility = ViewStates.Visible; searchBarGrid = mainView.FindViewById<GridLayout>(Resource.Id.searchGrid); searchBarGrid.Visibility = ViewStates.Invisible; annotationBarGrid = mainView.FindViewById<LinearLayout>(Resource.Id.annotationgrid); annotationBarGrid.Visibility = ViewStates.Invisible; m_shapeAnnoationToolbar = mainView.FindViewById<FrameLayout>(Resource.Id.shapeannotationtoolbar); m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; shapeAnnotationBarGrid = mainView.FindViewById<LinearLayout>(Resource.Id.shapeannotationgrid); shapeAnnotationBarGrid.Visibility = ViewStates.Invisible; shapeAnnotationBarGrid.Visibility = ViewStates.Invisible; annotationBackGrid = mainView.FindViewById<GridLayout>(Resource.Id.annotationbackgrid); annotationBackGrid.Visibility = ViewStates.Invisible; annotationColorBarGrid = mainView.FindViewById<LinearLayout>(Resource.Id.selectedannotationcolorchangedGrid); annotationColorBarGrid.Visibility = ViewStates.Invisible; backButton = mainView.FindViewById<Button>(Resource.Id.backButton); backButton.Typeface = font; backButton.SetTextColor(fontColor); backButton.TextSize = textSize; highlightModeButton = (Button)mainView.FindViewById(Resource.Id.highlightbtn); highlightModeButton.Typeface = font; highlightModeButton.SetTextColor(fontColor); highlightModeButton.TextSize = textSize; highlightModeButton.Click += HighlightModeButton_Click; underlineModeButton = (Button)mainView.FindViewById(Resource.Id.underlinebtn); underlineModeButton.Typeface = font; underlineModeButton.SetTextColor(fontColor); underlineModeButton.TextSize = textSize; underlineModeButton.Click += UnderlineModeButton_Click; strikeoutModeButton = (Button)mainView.FindViewById(Resource.Id.strikeoutbutton); strikeoutModeButton.Typeface = font; strikeoutModeButton.SetTextColor(fontColor); strikeoutModeButton.TextSize = textSize; strikeoutModeButton.Click += StrikeoutModeButton_Click; annotationBackButton = (Button)mainView.FindViewById(Resource.Id.annotationbackbutton); annotationBackButton.Typeface = font; annotationBackButton.SetTextColor(fontColor); annotationBackButton.TextSize = textSize; annotationBackButton.Click += AnnotationBackButton_Click; annotationColorButton = (Button)mainView.FindViewById(Resource.Id.annotationcolorbutton); annotationColorButton.Click += AnnotationColorButton_Click; annotationButton = (Button)mainView.FindViewById(Resource.Id.annotationbtn); annotationButton.Typeface = font; annotationButton.SetTextColor(fontColor); annotationButton.TextSize = textSize; cyancolorButton = (Button)mainView.FindViewById(Resource.Id.cyanbutton); cyancolorButton.Click += CyancolorButton_Click; yellowcolorButton = (Button)mainView.FindViewById(Resource.Id.yellowbutton); yellowcolorButton.Click += YellowcolorButton_Click; greencolorButton = (Button)mainView.FindViewById(Resource.Id.greenbutton); greencolorButton.Click += GreencolorButton_Click; magentacolorButton = (Button)mainView.FindViewById(Resource.Id.magentabutton); magentacolorButton.Click += MagentacolorButton_Click; whitecolorButton = (Button)mainView.FindViewById(Resource.Id.whitebutton); whitecolorButton.Click += WhitecolorButton_Click; blackcolorButton = (Button)mainView.FindViewById(Resource.Id.blackbutton); blackcolorButton.Click += BlackcolorButton_Click; backButton.Click += BackButton_Click; searchView = mainView.FindViewById<EditText>(Resource.Id.search); searchView.SetHintTextColor(Android.Graphics.Color.Rgb(189, 189, 189)); searchView.Hint = "Search text"; searchView.FocusableInTouchMode = true; searchView.TextSize = 18; searchView.SetTextColor(Android.Graphics.Color.Rgb(103, 103, 103)); searchView.TextAlignment = TextAlignment.Center; searchView.KeyPress += SearchView_KeyPress; searchView.TextChanged += SearchView_TextChanged; selectionButton = mainView.FindViewById<Button>(Resource.Id.selectDocumentButton); selectionButton.Typeface = font; selectionButton.SetTextColor(fontColor); selectionButton.TextSize = textSize; selectionButton.Click += SelectionButton_Click; clearSearchButton = mainView.FindViewById<Button>(Resource.Id.clearSearchResult); clearSearchButton.Typeface = font; clearSearchButton.SetTextColor(fontColor); clearSearchButton.TextSize = textSize; clearSearchButton.Click += ClearSearchButton_Click; annotationsGrid = (LinearLayout)mainView.FindViewById(Resource.Id.annotationsgrid); annotationsGrid.Visibility = ViewStates.Gone; annotationsToolbar = (FrameLayout)mainView.FindViewById(Resource.Id.annotationstoolbar); annotationsToolbar.Visibility = ViewStates.Gone; TextMarkupAnnotationButton = (Button)mainView.FindViewById(Resource.Id.textmarkupannotationButton); TextMarkupAnnotationButton.Typeface = font; TextMarkupAnnotationButton.SetTextColor(fontColor); TextMarkupAnnotationButton.TextSize = textSize; TextMarkupAnnotationButton.Click += TextMarkupAnnotationButton_Click; ShapeAnnotationButton = (Button)mainView.FindViewById(Resource.Id.shapeannotationButton); ShapeAnnotationButton.Typeface = font; ShapeAnnotationButton.SetTextColor(fontColor); ShapeAnnotationButton.TextSize = textSize; ShapeAnnotationButton.Click += ShapeAnnotationButton_Click; InkAnnotationButton = (Button)mainView.FindViewById(Resource.Id.inkannotationButton); InkAnnotationButton.Typeface = font; InkAnnotationButton.SetTextColor(fontColor); InkAnnotationButton.TextSize = textSize; InkAnnotationButton.Click += InkAnnotationButton_Click; TextAnnotationButton = (Button)mainView.FindViewById(Resource.Id.editannotationButton); TextAnnotationButton.Typeface = font; TextAnnotationButton.SetTextColor(fontColor); TextAnnotationButton.Text = "\uE71f"; TextAnnotationButton.TextSize = textSize; TextAnnotationButton.Click += TextAnnotationButton_Click; signaturePadButton = (Button)mainView.FindViewById(Resource.Id.signButton); signaturePadButton.Typeface = signatureFont; signaturePadButton.SetTextColor(fontColor); signaturePadButton.TextSize = textSize; signaturePadButton.Click += SignaturePadButton_Click; shapeannotationBackButton = (Button)mainView.FindViewById(Resource.Id.shapeannotationBackButton); shapeannotationBackButton.Typeface = font; shapeannotationBackButton.SetTextColor(fontColor); shapeannotationBackButton.TextSize = textSize; shapeannotationBackButton.Click += ShapeannotationBackButton_Click; rectangleModeButton = (Button)mainView.FindViewById(Resource.Id.rectanglebtn); rectangleModeButton.Typeface = font; rectangleModeButton.SetTextColor(fontColor); rectangleModeButton.TextSize = textSize; rectangleModeButton.Click += RectangleModeButton_Click; circleModeButton = (Button)mainView.FindViewById(Resource.Id.circlebtn); circleModeButton.Typeface = font; circleModeButton.SetTextColor(fontColor); circleModeButton.TextSize = textSize; circleModeButton.Click += CircleModeButton_Click; lineModeButton = (Button)mainView.FindViewById(Resource.Id.linebutton); lineModeButton.Typeface = font; lineModeButton.SetTextColor(fontColor); lineModeButton.TextSize = textSize; lineModeButton.Click += LineModeButton_Click; arrowModeButton = (Button)mainView.FindViewById(Resource.Id.arrowbutton); arrowModeButton.Typeface = font; arrowModeButton.SetTextColor(fontColor); arrowModeButton.TextSize = textSize; arrowModeButton.Click += ArrowModeButton_Click; inkannotationgrid = (GridLayout)mainView.FindViewById(Resource.Id.inkannotationgrid); inkannotationgrid.Visibility = ViewStates.Gone; inkannotationtoolbar = (FrameLayout)mainView.FindViewById(Resource.Id.inkannotationtoolbar); inkannotationtoolbar.Visibility = ViewStates.Gone; inkundobutton = (Button)mainView.FindViewById(Resource.Id.inkundobutton1); inkundobutton.Typeface = font; inkundobutton.TextSize = textSize; inkundobutton.SetTextColor(Color.Gray); inkundobutton.Click += Inkundobutton_Click; inkredobutton = (Button)mainView.FindViewById(Resource.Id.inkredobutton1); inkredobutton.Typeface = font; inkredobutton.TextSize = textSize; inkredobutton.SetTextColor(Color.Gray); inkredobutton.Click += Inkredobutton_Click; inkannotationbackbutton = (Button)mainView.FindViewById(Resource.Id.inkannotationbackbutton); inkannotationbackbutton.Typeface = font; inkannotationbackbutton.SetTextColor(fontColor); inkannotationbackbutton.TextSize = textSize; inkannotationbackbutton.Click += Inkannotationbackbutton_Click; inkannotationbottomgrid = (GridLayout)mainView.FindViewById(Resource.Id.inkannotationbottomgrid); inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar = (FrameLayout)mainView.FindViewById(Resource.Id.inkannotationbottomtoolbar); inkannotationbottomtoolbar.Visibility = ViewStates.Gone; inkannotationThicknessButton = (Button)mainView.FindViewById(Resource.Id.inkannotationThicknessButton); inkannotationThicknessButton.Typeface = font; inkannotationThicknessButton.TextSize = textSize; inkannotationThicknessButton.Click += InkannotationThicknessButton_Click; inkAnnotationColorButton = (Button)mainView.FindViewById(Resource.Id.inkAnnotationColorButton); inkAnnotationColorButton.Click += InkAnnotationColorButton_Click; inkannotationthicknessToolbar = (FrameLayout)mainView.FindViewById(Resource.Id.inkannotationthicknessToolbar); inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid = (GridLayout)mainView.FindViewById(Resource.Id.inkannotationthicknessGrid); inkannotationthicknessGrid.Visibility = ViewStates.Gone; lineView1 = (LinearLayout)mainView.FindViewById(Resource.Id.lines1); lineView1.Visibility = ViewStates.Gone; annotationbottomcolortoolbar = (FrameLayout)mainView.FindViewById(Resource.Id.annotationbottomcolortoolbar); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; opacityButton = (Button)mainView.FindViewById(Resource.Id.opacitybtn); opacityButton.Visibility = ViewStates.Gone; opacityButton.Typeface = font; opacityButton.TextSize = textSize; opacityButton.Click += OpacityButton_Click; inkannotationbottomopacitytoolbar = (FrameLayout)mainView.FindViewById(Resource.Id.inkannotationbottomopacitytoolbar); inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkBackButton = (Button)mainView.FindViewById(Resource.Id.inkBackButton); inkBackButton.Visibility = ViewStates.Gone; inkBackButton.Typeface = font; inkBackButton.SetTextColor(fontColor); inkBackButton.TextSize = textSize; inkBackButton.Click += InkBackButton_Click; inkButton = (Button)mainView.FindViewById(Resource.Id.inkButton); inkButton.Visibility = ViewStates.Gone; inkButton.Typeface = font; inkButton.SetTextColor(fontColor); inkButton.TextSize = textSize; textmarkupannotationBackButton = (Button)mainView.FindViewById(Resource.Id.textmarkupannotationBackButton); textmarkupannotationBackButton.Typeface = font; textmarkupannotationBackButton.SetTextColor(fontColor); textmarkupannotationBackButton.TextSize = textSize; textmarkupannotationBackButton.Click += TextmarkupannotationBackButton_Click; inkremovebutton = (Button)mainView.FindViewById(Resource.Id.inkremovebutton); inkremovebutton.Typeface = font; inkremovebutton.Visibility = ViewStates.Gone; inkremovebutton.SetTextColor(fontColor); inkremovebutton.TextSize = textSize; inkremovebutton.Click += Inkremovebutton_Click; m_editTextAnntationButton=(Button)mainView.FindViewById(Resource.Id.edittextannotationButton); m_editTextAnntationButton.Typeface = font; m_editTextAnntationButton.Visibility = ViewStates.Gone; m_editTextAnntationButton.SetTextColor(fontColor); m_editTextAnntationButton.TextSize = textSize; m_editTextAnntationButton.Click += M_editTextAnntationButton_Click; linesLayout1 = (LinearLayout)mainView.FindViewById(Resource.Id.lines1); m_rangeandThicknessFrame = (FrameLayout)mainView.FindViewById(Resource.Id.thicknessrange); m_rangeSliderView = (LinearLayout)mainView.FindViewById(Resource.Id.rangeslider); linesLayoutGrid = (LinearLayout)mainView.FindViewById(Resource.Id.linesGrid); linesLayout1.Visibility = ViewStates.Gone; lineOneContainer1 = (ImageButton)mainView.FindViewById(Resource.Id.lineonecontainer1); lineOneContainer1.Tag = 0; lineOne1 = (ImageButton)mainView.FindViewById(Resource.Id.lineone1); lineOne1.Tag = 0; lineOne1.Click += ThickLinesClick; lineOneContainer1.Click += ThickContainerClick; lineTwoContainer1 = (ImageButton)mainView.FindViewById(Resource.Id.linetwocontainer1); lineTwoContainer1.Tag = 1; lineTwo1 = (ImageButton)mainView.FindViewById(Resource.Id.linetwo1); lineTwo1.Tag = 1; lineTwo1.Click += ThickLinesClick; lineTwoContainer1.Click += ThickLinesClick; lineThreeContainer1 = (ImageButton)mainView.FindViewById(Resource.Id.linethreecontainer1); lineThreeContainer1.Tag = 2; lineThree1 = (ImageButton)mainView.FindViewById(Resource.Id.linethree1); lineThree1.Tag = 2; lineThree1.Click += ThickLinesClick; lineThreeContainer1.Click += ThickContainerClick; lineFourContainer1 = (ImageButton)mainView.FindViewById(Resource.Id.linefourcontainer1); lineFourContainer1.Tag = 3; lineFour1 = (ImageButton)mainView.FindViewById(Resource.Id.linefour1); lineFour1.Tag = 3; lineFour1.Click += ThickLinesClick; lineFourContainer1.Click += ThickContainerClick; lineFiveContainer1 = (ImageButton)mainView.FindViewById(Resource.Id.linefivecontainer1); lineFiveContainer1.Tag = 4; lineFive1 = (ImageButton)mainView.FindViewById(Resource.Id.linefive1); lineFive1.Tag = 4; lineFive1.Click += ThickLinesClick; lineFiveContainer1.Click += ThickContainerClick; InitialializeRangeSlider(); seekbar1 = (SeekBar)mainView.FindViewById(Resource.Id.seekbar1); seekbar1.StopTrackingTouch += Seekbar_StopTrackingTouch; seekbar1.ProgressChanged += Seekbar_ProgressChanged; endprogressLabel = (TextView)mainView.FindViewById(Resource.Id.endprogress); pdfViewerControl.Toolbar.Enabled = false; pdfViewerControl.IsPasswordViewEnabled = false; pdfViewerControl.PreserveSignaturePadOrientation = true; pdfViewerControl.FreeTextAnnotationAdded += PdfViewerControl_FreeTextAnnotationAdded; pdfViewerControl.FreeTextAnnotationSelected += PdfViewerControl_FreeTextAnnotationSelected; pdfViewerControl.FreeTextAnnotationDeselected += PdfViewerControl_FreeTextAnnotationDeselected; pdfViewerControl.ShapeAnnotationSelected += PdfViewerControl_ShapeAnnotationSelected; pdfViewerControl.ShapeAnnotationDeselected += PdfViewerControl_ShapeAnnotationDeselected; pdfViewerControl.InkDeselected += PdfViewerControl_InkDeselected; ; pdfViewerControl.InkSelected += PdfViewerControl_InkSelected; pdfViewerControl.CanUndoInkModified += PdfViewerControl_CanUndoInkModified; pdfViewerControl.CanRedoInkModified += PdfViewerControl_CanRedoInkModified; pdfViewerControl.TextMarkupSelected += PdfViewerControl_TextMarkupSelected; pdfViewerControl.TextMarkupDeselected += PdfViewerControl_TextMarkupDeselected; pdfViewerControl.StampAnnotationSelected += PdfViewerControl_StampAnnotationSelected; pdfViewerControl.StampAnnotationDeselected += PdfViewerControl_StampAnnotationDeselected; pdfViewerControl.CanRedoModified += PdfViewerControl_CanRedoModified; pdfViewerControl.CanUndoModified += PdfViewerControl_CanUndoModified; pdfViewerControl.FreeTextPopupAppearing += PdfViewerControl_FreeTextPopupAppearing; pdfViewerControl.FreeTextPopupDisappeared += PdfViewerControl_FreeTextPopupDisappeared; pdfViewerControl.PasswordErrorOccurred += PdfViewerControl_PasswordErrorOccurred; TextSelectionMenuItem item = new TextSelectionMenuItem(); item.Text = "Search in browser"; item.Id = "find"; pdfViewerControl.TextSelectionSettings.MenuOptions.Items.Add(item); pdfViewerControl.TextSelectionCompleted += PdfViewerControl_TextSelectionCompleted; ; pdfViewerControl.TextSelectionSettings.MenuOptions.TextSelectionMenuItemClicked += MenuOptions_TextSelectionMenuItemClicked; bookmarkToolbar = new BookmarkToolbar(m_context, this); bookmarkToolbar.bookmarkLoadedDocument = new PdfLoadedDocument(docStream); //Populate the ListView with the bookmark elements bookmarkToolbar.PopulateInitialBookmarkList(); bookmarkToolbar.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); docStream.Position = 0; pdfViewerControl.LoadDocument(docStream); layoutListener.sampleView = this; screenSize = GetScreenSize(); return mainView; } private async void MenuOptions_TextSelectionMenuItemClicked(object sender, EventArgs e) { if ((sender as TextSelectionMenuItem).Id == "find") { String escapedQuery = Java.Net.URLEncoder.Encode(this.selectedText, "UTF-8"); var uri = Android.Net.Uri.Parse($"https://www.google.com/search?q={escapedQuery}"); var intent = new Intent(Intent.ActionView, uri); m_context.StartActivity(intent); } } private void PdfViewerControl_TextSelectionCompleted(object sender, TextSelectionCompletedEventArgs args) { this.selectedText = args.SelectedText; } private void PdfViewerControl_PasswordErrorOccurred(object sender, PasswordErrorOccurredEventArgs e) { if (i == 0) { DisplayInitialPopup(); InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(this.editText.WindowToken, HideSoftInputFlags.None); i++; } else { DisplayInitialPopup(); errorView.Visibility = ViewStates.Visible; } isLoadedDocument = false; } private void ViewModeButton_Click(object sender, EventArgs e) { if (pdfViewerControl.PageViewMode == PageViewMode.Continuous) { pdfViewerControl.PageViewMode = PageViewMode.PageByPage; viewModeButton.Text = m_context.Resources.GetText(Resource.String.pdfviewer_icon_pagebypageviewmode); } else { pdfViewerControl.PageViewMode = PageViewMode.Continuous; viewModeButton.Text = m_context.Resources.GetText(Resource.String.pdfviewer_icon_continuousviewmode); } } private void PdfViewerControl_StampAnnotationDeselected(object sender, StampAnnotationDeselectedEventArgs args) { annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorButton.Visibility = ViewStates.Visible; annotationButton.Visibility = ViewStates.Gone; annotationBackButton.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; m_selectedStampAnnotation = null; } private void PdfViewerControl_StampAnnotationSelected(object sender, StampAnnotationSelectedEventArgs args) { m_shapeAnnot = null; inkannot = null; signature = null; m_freeTextAnnot = null; annotation = null; m_selectedStampAnnotation = sender as StampAnnotation; annotationToolBar.Visibility = ViewStates.Visible; annotationBackGrid.Visibility = ViewStates.Visible; removeButton.Visibility = ViewStates.Visible; annotationButton.Visibility = ViewStates.Gone; annotationBackButton.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; annotationColorButton.Visibility = ViewStates.Invisible; } private void StampButton_Click(object sender, EventArgs e) { if (stampSelectionView == null) stampSelectionView = new StampSelectionView(this.m_context, this); if(!IsDeviceTablet) mainView.AddView(stampSelectionView); else { Android.Util.Size screenSize = new Android.Util.Size(m_context.Resources.DisplayMetrics.WidthPixels, m_context.Resources.DisplayMetrics.HeightPixels); popup = new PopupWindow(stampSelectionView, screenSize.Width, screenSize.Height); Color color = Color.Black; color.A = (byte)100; popup.SetBackgroundDrawable(new ColorDrawable(color)); popup.ShowAtLocation(mainView, GravityFlags.Center, 0, 0); } stampSelectionView.isShowing = true; m_topToolbars.Visibility = ViewStates.Invisible; m_bottomToolbars.Visibility = ViewStates.Invisible; } private void SignaturePadButton_Click(object sender, EventArgs e) { pdfViewerControl.AnnotationMode = AnnotationMode.HandwrittenSignature; } //Returns a value which indicates whether the current device is a tablet. internal bool IsDeviceTablet { get { DisplayMetrics m_displayMetrics = new DisplayMetrics(); ((Activity)m_context).WindowManager.DefaultDisplay.GetMetrics(m_displayMetrics); double dispWidth = m_displayMetrics.WidthPixels / (double)m_displayMetrics.DensityDpi; double dispHeight = m_displayMetrics.HeightPixels / (double)m_displayMetrics.DensityDpi; return (Math.Sqrt(Math.Pow(dispWidth, 2) + Math.Pow(dispHeight, 2)) >= 7.0); } } //Expands the bookmark toolbar internal void ExpandBookmarkToolbar() { if (!isBookmarkVisible) { if (IsDeviceTablet) this.bookmarkToolbarParentLayout.AddView(bookmarkToolbar); else { this.mainView.AddView(bookmarkToolbar); bookmarkToolbar.listAdapter.NotifyDataSetChanged(); m_topToolbars.Visibility = ViewStates.Invisible; m_bottomToolbars.Visibility = ViewStates.Invisible; } } isBookmarkVisible = true; } //Collapses the bookmark toolbar. internal void CollapseBookmarkToolbar() { if (isBookmarkVisible) { if (IsDeviceTablet) this.bookmarkToolbarParentLayout.RemoveView(bookmarkToolbar); else { this.mainView.RemoveView(bookmarkToolbar); m_topToolbars.Visibility = ViewStates.Visible; m_bottomToolbars.Visibility = ViewStates.Visible; } } isBookmarkVisible = false; } private void BookmarkButton_Click(object sender, EventArgs e) { if (isBookmarkVisible) CollapseBookmarkToolbar(); else { ExpandBookmarkToolbar(); annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; } } private void PdfViewerControl_FreeTextPopupDisappeared(object sender, FreeTextPopupDisappearedEventArgs args) { if (m_topToolbars != null) m_topToolbars.Visibility = ViewStates.Visible; if (m_bottomToolbars != null) m_bottomToolbars.Visibility = ViewStates.Visible; if (pdfViewerControl.AnnotationMode==AnnotationMode.FreeText) { if(toolBarGrid!=null) toolBarGrid.Visibility = ViewStates.Visible; if(annotationsToolbar!=null) annotationsToolbar.Visibility = ViewStates.Visible; if (bottomtoolBarGrid != null) bottomtoolBarGrid.Visibility = ViewStates.Visible; } else { if (toolBarGrid != null) toolBarGrid.Visibility = ViewStates.Visible; if (bottomtoolBarGrid!=null) bottomtoolBarGrid.Visibility = ViewStates.Visible; } } private void PdfViewerControl_FreeTextPopupAppearing(object sender, FreeTextPopupAppearingEventArgs args) { InvisibleToolbars(); } private void InvisibleToolbars() { //if(linesLayout1!=null) //linesLayout1.Visibility = ViewStates.Gone; //if(inkannotationtoolbar!=null) //inkannotationtoolbar.Visibility = ViewStates.Gone; //if (toolBarGrid != null) // toolBarGrid.Visibility = ViewStates.Gone; //if (searchBarGrid != null) // searchBarGrid.Visibility = ViewStates.Gone; if (m_topToolbars != null) m_topToolbars.Visibility = ViewStates.Gone; if (m_bottomToolbars != null) m_bottomToolbars.Visibility = ViewStates.Gone; } private void M_editTextAnntationButton_Click(object sender, EventArgs e) { pdfViewerControl.EditFreeTextAnnotation(); } private void PdfViewerControl_FreeTextAnnotationAdded(object sender, FreeTextAnnotationAddedEventArgs args) { linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; shapeAnnotationBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Visible; annotationsGrid.Visibility = ViewStates.Visible; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Invisible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; m_rangeSliderView.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; } private void ShapeannotationBackButton_Click(object sender, EventArgs e) { inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Visible; annotationsGrid.Visibility = ViewStates.Visible; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Invisible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; } private void InitialializeRangeSlider() { m_rangeSliderView.Orientation = Android.Widget.Orientation.Vertical; m_rangeSliderView.SetBackgroundColor(Color.ParseColor("#F6F6F6")); m_rangeSliderText = new TextView(m_context); m_rangeSliderText.Gravity = GravityFlags.Center | GravityFlags.CenterVertical; m_rangeSliderText.TextSize = 12; m_rangeSliderText.SetBackgroundColor(Color.ParseColor("#E9E9E9")); m_rangeSliderText.SetTextColor(Color.Black); LayoutParams m_rangeSliderTextParam = new LayoutParams(LayoutParams.MatchParent, LayoutParams.WrapContent); m_rangeSliderText.LayoutParameters = m_rangeSliderTextParam; LayoutParams m_rangeSliderParam = new LayoutParams(LayoutParams.MatchParent, LayoutParams.WrapContent); m_rangeSlider = new Com.Syncfusion.Sfrangeslider.SfRangeSlider(m_context); m_rangeSlider.SetBackgroundColor(Color.ParseColor("#E9E9E9")); fontValue = 12.ToString(); m_rangeSlider.ShowValueLabel = false; m_rangeSlider.Minimum = 6; m_rangeSlider.Maximum = 22; m_rangeSlider.LayoutParameters = m_rangeSliderParam; m_rangeSlider.TickFrequency = 2; m_rangeSlider.StepFrequency = 2; m_rangeSlider.SnapsTo = Com.Syncfusion.Sfrangeslider.SnapsTo.Ticks; m_rangeSlider.ShowRange = false; m_rangeSlider.KnobColor = Color.ParseColor("#0076FF"); m_rangeSlider.TrackSelectionColor = Color.ParseColor("#0076FF"); m_rangeSlider.TickPlacement = Com.Syncfusion.Sfrangeslider.TickPlacement.Inline; m_rangeSlider.ToolTipPlacement = Com.Syncfusion.Sfrangeslider.ToolTipPlacement.None; m_rangeSlider.ValueChanged += m_rangeSlider_ValueChanged; m_rangeSliderText.Text = "Font: " + fontValue + " pt"; m_rangeSliderView.AddView(m_rangeSliderText); m_rangeSliderView.AddView(m_rangeSlider); } private void m_rangeSlider_ValueChanged(object sender, Com.Syncfusion.Sfrangeslider.ValueChangedEventArgs e) { var value = (int)e.Value; fontValue = value.ToString(); m_rangeSliderText.Text = "Font: " + fontValue + " pt"; if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) pdfViewerControl.AnnotationSettings.FreeText.TextSize = (float)e.Value; if (m_freeTextAnnot != null) ((FreeTextAnnotation)m_freeTextAnnot).Settings.TextSize = (float)e.Value; } private void TextAnnotationButton_Click(object sender, EventArgs e) { var m_color = pdfViewerControl.AnnotationSettings.FreeText.TextColor; m_color.A = (byte)255; inkAnnotationColorButton.SetBackgroundColor(m_color); pdfViewerControl.AnnotationMode = AnnotationMode.FreeText; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Invisible; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Visible; inkannotationgrid.Visibility = ViewStates.Visible; inkannotationbottomgrid.Visibility = ViewStates.Visible; inkannotationbottomtoolbar.Visibility = ViewStates.Visible; inkundobutton.Visibility = ViewStates.Invisible; inkredobutton.Visibility = ViewStates.Invisible; inkButton.Text = "\uE71f"; inkButton.Visibility = ViewStates.Visible; inkBackButton.Visibility = ViewStates.Visible; inkremovebutton.Visibility = ViewStates.Gone; inkannotationThicknessButton.Typeface = fontSizeFont; inkannotationThicknessButton.Text = "\uE700"; var m_colorbuttonbackground = pdfViewerControl.AnnotationSettings.FreeText.TextColor; m_colorbuttonbackground.A = (byte)255; inkannotationThicknessButton.SetTextColor(m_colorbuttonbackground); opacityButton.Visibility = ViewStates.Invisible; } private void ArrowModeButton_Click(object sender, EventArgs e) { inkAnnotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor); pdfViewerControl.AnnotationMode = AnnotationMode.Arrow; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Invisible; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Visible; inkannotationgrid.Visibility = ViewStates.Visible; inkannotationbottomgrid.Visibility = ViewStates.Visible; inkannotationbottomtoolbar.Visibility = ViewStates.Visible; inkundobutton.Visibility = ViewStates.Invisible; inkredobutton.Visibility = ViewStates.Invisible; inkButton.Text = "\uE701"; inkButton.Visibility = ViewStates.Visible; inkBackButton.Visibility = ViewStates.Visible; inkremovebutton.Visibility = ViewStates.Gone; inkannotationThicknessButton.Typeface = font; inkannotationThicknessButton.Text = "\uE722"; var m_color = pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor; m_color.A = (byte)255; inkannotationThicknessButton.SetTextColor(m_color); opacityButton.Visibility = ViewStates.Visible; } private void LineModeButton_Click(object sender, EventArgs e) { var m_colorbuttonbackground = pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor; m_colorbuttonbackground.A = (byte)255; inkAnnotationColorButton.SetBackgroundColor(m_colorbuttonbackground); pdfViewerControl.AnnotationMode = AnnotationMode.Line; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Invisible; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Visible; inkannotationgrid.Visibility = ViewStates.Visible; inkannotationbottomgrid.Visibility = ViewStates.Visible; inkannotationbottomtoolbar.Visibility = ViewStates.Visible; inkundobutton.Visibility = ViewStates.Invisible; inkredobutton.Visibility = ViewStates.Invisible; inkButton.Text = "\uE703"; inkButton.Visibility = ViewStates.Visible; inkBackButton.Visibility = ViewStates.Visible; inkremovebutton.Visibility = ViewStates.Gone; inkannotationThicknessButton.Typeface = font; inkannotationThicknessButton.Text = "\uE722"; var m_color = pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor; m_color.A = (byte)255; inkannotationThicknessButton.SetTextColor(m_color); opacityButton.Visibility = ViewStates.Visible; } private void CircleModeButton_Click(object sender, EventArgs e) { var m_colorbuttonbackground = pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor; m_colorbuttonbackground.A = 255; inkAnnotationColorButton.SetBackgroundColor(m_colorbuttonbackground); pdfViewerControl.AnnotationMode = AnnotationMode.Circle; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Invisible; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Visible; inkannotationgrid.Visibility = ViewStates.Visible; inkannotationbottomgrid.Visibility = ViewStates.Visible; inkannotationbottomtoolbar.Visibility = ViewStates.Visible; inkundobutton.Visibility = ViewStates.Invisible; inkredobutton.Visibility = ViewStates.Invisible; inkButton.Text = "\uE714"; inkButton.Visibility = ViewStates.Visible; inkBackButton.Visibility = ViewStates.Visible; inkremovebutton.Visibility = ViewStates.Gone; inkannotationThicknessButton.Typeface = font; inkannotationThicknessButton.Text = "\uE722"; var m_color = pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor; m_color.A = (byte)255; inkannotationThicknessButton.SetTextColor(pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor); opacityButton.Visibility = ViewStates.Visible; } private void RectangleModeButton_Click(object sender, EventArgs e) { var m_colorbuttonbackground = pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor; m_colorbuttonbackground.A = (byte)255; inkAnnotationColorButton.SetBackgroundColor(m_colorbuttonbackground); pdfViewerControl.AnnotationMode = AnnotationMode.Rectangle; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Invisible; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Visible; inkannotationgrid.Visibility = ViewStates.Visible; inkannotationbottomgrid.Visibility = ViewStates.Visible; inkannotationbottomtoolbar.Visibility = ViewStates.Visible; inkundobutton.Visibility = ViewStates.Invisible; inkredobutton.Visibility = ViewStates.Invisible; inkButton.Text = "\uE710"; inkButton.Visibility = ViewStates.Visible; inkBackButton.Visibility = ViewStates.Visible; inkremovebutton.Visibility = ViewStates.Gone; inkannotationThicknessButton.Typeface = font; inkannotationThicknessButton.Text = "\uE722"; var m_color = pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor; m_color.A = (byte)255; inkannotationThicknessButton.SetTextColor(m_color); opacityButton.Visibility = ViewStates.Visible; } private void ShapeAnnotationButton_Click(object sender, EventArgs e) { annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Visible; shapeAnnotationBarGrid.Visibility = ViewStates.Visible; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Gone; } private bool ThicknessChanged { get { return m_thicknessChanged; } set { m_thicknessChanged = value; } } private void Seekbar_StopTrackingTouch(object sender, SeekBar.StopTrackingTouchEventArgs e) { double val = Math.Round((double)e.SeekBar.Progress / 100, 2); decimal dec = (decimal)val; if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { pdfViewerControl.AnnotationSettings.Ink.Opacity = (float)(dec); } if(pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.Opacity = (float)(dec); if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.Opacity = (float)(dec); if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.Opacity = (float)(dec); if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.Opacity = (float)(dec); if (pdfViewerControl.AnnotationMode == AnnotationMode.None && inkannot != null) { inkannot.Settings.Opacity = (float)(dec); } else if(pdfViewerControl.AnnotationMode == AnnotationMode.None && m_shapeAnnot != null) { m_shapeAnnot.Settings.Opacity = (float)(dec); } else if(pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature && signature != null) { signature.Settings.Opacity = (float)dec; } endprogressLabel.Text = string.Format("{0}%", (double)e.SeekBar.Progress); } private void ThickContainerClick(object sender, EventArgs e) { currentColorPosition = (int)((ImageButton)sender).Tag; Set(); } private void ThickLinesClick(object sender, EventArgs e) { currentColorPosition = (int)((ImageButton)sender).Tag; Set(); } internal void Set() { SetThickness(currentColorPosition); } private void SetThickness(int position) { switch (position) { case 0: if (inkannot != null) { inkannot.Settings.Thickness = 1; } else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Thickness = 1; else if (signature != null) signature.Settings.Thickness = 1; else if (pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) pdfViewerControl.AnnotationSettings.HandwrittenSignature.Thickness = 1; SetShapeThickness(2); lineView1.Visibility = ViewStates.Invisible; linesLayout1.Visibility = ViewStates.Gone; ThicknessChanged = false; break; case 1: if (inkannot != null) { inkannot.Settings.Thickness = 2; } else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Thickness = 2; else if (signature != null) signature.Settings.Thickness = 2; else if (pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) pdfViewerControl.AnnotationSettings.HandwrittenSignature.Thickness = 2; SetShapeThickness(4); lineView1.Visibility = ViewStates.Invisible; linesLayout1.Visibility = ViewStates.Gone; ThicknessChanged = false; break; case 2: if (inkannot != null) { inkannot.Settings.Thickness = 5; } else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Thickness = 5; else if (signature != null) signature.Settings.Thickness = 5; else if (pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) pdfViewerControl.AnnotationSettings.HandwrittenSignature.Thickness = 5; SetShapeThickness(6); lineView1.Visibility = ViewStates.Invisible; linesLayout1.Visibility = ViewStates.Gone; ThicknessChanged = false; break; case 3: if (inkannot != null) { inkannot.Settings.Thickness = 7; } else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Thickness = 7; else if (signature != null) signature.Settings.Thickness = 7; else if (pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) pdfViewerControl.AnnotationSettings.HandwrittenSignature.Thickness = 7; SetShapeThickness(8); lineView1.Visibility = ViewStates.Invisible; linesLayout1.Visibility = ViewStates.Gone; ThicknessChanged = false; break; case 4: if (inkannot != null) { inkannot.Settings.Thickness = 10; } else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Thickness = 10; else if (signature != null) signature.Settings.Thickness = 10; else if (pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) pdfViewerControl.AnnotationSettings.HandwrittenSignature.Thickness = 10; SetShapeThickness(10); lineView1.Visibility = ViewStates.Invisible; linesLayout1.Visibility = ViewStates.Gone; ThicknessChanged = false; break; } } private void SetShapeThickness(int thickness) { if (m_shapeAnnot != null) { m_shapeAnnot.Settings.Thickness = thickness; } else if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.Thickness = thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.Thickness = thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.Thickness = thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.Thickness = thickness; } private void Inkremovebutton_Click(object sender, EventArgs e) { m_editTextAnntationButton.Visibility = ViewStates.Gone; inkannot = (sender as InkAnnotation); if(inkannot!=null) pdfViewerControl.RemoveAnnotation(inkannot); if(m_shapeAnnot!=null) pdfViewerControl.RemoveAnnotation(m_shapeAnnot); if (m_freeTextAnnot != null) pdfViewerControl.RemoveAnnotation(m_freeTextAnnot); inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkButton.Visibility = ViewStates.Gone; inkBackButton.Visibility = ViewStates.Gone; inkremovebutton.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; pdfViewerControl.RemoveAnnotation(annotation); IsAnnotationModeSelected = false; m_shapeAnnot = null; m_freeTextAnnot = null; inkannot = null; signature = null; } private void TextmarkupannotationBackButton_Click(object sender, EventArgs e) { inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Visible; annotationsGrid.Visibility = ViewStates.Visible; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Invisible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; } private bool OpacityChanged { get { return m_opacityChanged; } set { m_opacityChanged = value; } } private void PdfViewerControl_InkSelected(object sender, InkSelectedEventArgs args) { m_shapeAnnot = null; m_freeTextAnnot = null; annotation = null; Color color; if (!args.IsSignature) { inkannot = (sender as InkAnnotation); color = new Color((byte)inkannot.Settings.Color.R, (byte)inkannot.Settings.Color.G, (byte)inkannot.Settings.Color.B, (byte)255); } else { signature = (sender as HandwrittenSignature); color = new Color((byte)signature.Settings.Color.R, (byte)signature.Settings.Color.G, (byte)signature.Settings.Color.B, (byte)255); } inkAnnotationColorButton.SetBackgroundColor(color); inkannotationThicknessButton.SetTextColor(color); linesLayout1.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Invisible; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Invisible; inkannotationgrid.Visibility = ViewStates.Invisible; inkannotationbottomgrid.Visibility = ViewStates.Visible; inkannotationbottomtoolbar.Visibility = ViewStates.Visible; inkButton.Text = "\uE71d"; inkannotationThicknessButton.Typeface = font; inkannotationThicknessButton.Text = "\uE722"; inkButton.Visibility = ViewStates.Visible; inkBackButton.Visibility = ViewStates.Gone; inkremovebutton.Visibility = ViewStates.Visible; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; opacityButton.Visibility = ViewStates.Visible; if (!args.IsSignature) seekbar1.Progress = (int)(inkannot.Settings.Opacity * 100); else seekbar1.Progress = (int)(signature.Settings.Opacity * 100); m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; } private void PdfViewerControl_InkDeselected(object sender, InkDeselectedEventArgs args) { inkannot = null; signature = null; inkannotationtoolbar.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; inkButton.Visibility = ViewStates.Gone; inkBackButton.Visibility = ViewStates.Gone; inkremovebutton.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; toolBarGrid.Visibility = ViewStates.Visible; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; } private void PdfViewerControl_ShapeAnnotationDeselected(object sender, ShapeAnnotationDeselectedEventArgs args) { m_shapeAnnot = null; inkannotationtoolbar.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; inkButton.Visibility = ViewStates.Gone; inkBackButton.Visibility = ViewStates.Gone; inkremovebutton.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; toolBarGrid.Visibility = ViewStates.Visible; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; } private void PdfViewerControl_ShapeAnnotationSelected(object sender, ShapeAnnotationSelectedEventArgs args) { m_freeTextAnnot = null; inkannot = null; signature = null; annotation = null; m_shapeAnnot = (sender as ShapeAnnotation); Color color = new Color((byte)m_shapeAnnot.Settings.StrokeColor.R, (byte)m_shapeAnnot.Settings.StrokeColor.G, (byte)m_shapeAnnot.Settings.StrokeColor.B, (byte)255); inkAnnotationColorButton.SetBackgroundColor(color); inkannotationThicknessButton.SetTextColor(color); linesLayout1.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Invisible; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Invisible; inkannotationgrid.Visibility = ViewStates.Invisible; inkannotationbottomgrid.Visibility = ViewStates.Visible; inkannotationbottomtoolbar.Visibility = ViewStates.Visible; inkannotationThicknessButton.Typeface = font; inkannotationThicknessButton.Text = "\uE722"; SetSelectedAnnotationButton(args); inkButton.Visibility = ViewStates.Visible; inkBackButton.Visibility = ViewStates.Gone; inkremovebutton.Visibility = ViewStates.Visible; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; seekbar1.Progress = (int)(m_shapeAnnot.Settings.Opacity * 100); m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; } private void PdfViewerControl_FreeTextAnnotationDeselected(object sender, FreeTextAnnotationDeselectedEventArgs args) { m_freeTextAnnot = null; inkannotationtoolbar.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; inkButton.Visibility = ViewStates.Gone; inkBackButton.Visibility = ViewStates.Gone; inkremovebutton.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; toolBarGrid.Visibility = ViewStates.Visible; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; m_editTextAnntationButton.Visibility = ViewStates.Gone; } private void PdfViewerControl_FreeTextAnnotationSelected(object sender, FreeTextAnnotationSelectedEventArgs args) { m_shapeAnnot = null; signature = null; inkannot = null; signature = null; annotation = null; m_freeTextAnnot = (sender as FreeTextAnnotation); Color color = new Color((byte)m_freeTextAnnot.Settings.TextColor.R, (byte)m_freeTextAnnot.Settings.TextColor.G, (byte)m_freeTextAnnot.Settings.TextColor.B, (byte)255); inkAnnotationColorButton.SetBackgroundColor(color); inkannotationThicknessButton.SetTextColor(color); linesLayout1.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Invisible; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Invisible; inkannotationgrid.Visibility = ViewStates.Invisible; inkannotationbottomgrid.Visibility = ViewStates.Visible; inkannotationbottomtoolbar.Visibility = ViewStates.Visible; inkannotationThicknessButton.Typeface = fontSizeFont; inkannotationThicknessButton.Text = "\uE700"; inkButton.Text = "\uE71f"; inkButton.Visibility = ViewStates.Visible; inkBackButton.Visibility = ViewStates.Gone; inkremovebutton.Visibility = ViewStates.Visible; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; m_editTextAnntationButton.Visibility = ViewStates.Visible; } private void SetSelectedAnnotationButton(ShapeAnnotationSelectedEventArgs args) { if (args.AnnotationType == AnnotationMode.Rectangle) inkButton.Text = "\uE710"; else if (args.AnnotationType == AnnotationMode.Circle) inkButton.Text = "\uE714"; else if (args.AnnotationType == AnnotationMode.Line) inkButton.Text = "\uE703"; else if (args.AnnotationType == AnnotationMode.Arrow) inkButton.Text = "\uE701"; } private void PdfViewerControl_CanRedoInkModified(object sender, CanRedoInkModifiedEventArgs args) { if (args.CanRedoInk) { inkredobutton.SetTextColor(fontColor); } else { inkredobutton.SetTextColor(Color.Gray); } } private void PdfViewerControl_CanUndoInkModified(object sender, CanUndoInkModifiedEventArgs args) { if (args.CanUndoInk) { inkundobutton.SetTextColor(fontColor); } else { inkundobutton.SetTextColor(Color.Gray); } } private void Seekbar_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { endprogressLabel.Text = string.Format("{0}%", (e.Progress)); } private void InkBackButton_Click(object sender, EventArgs e) { inkannotationtoolbar.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Visible; annotationsGrid.Visibility = ViewStates.Visible; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Invisible; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle || pdfViewerControl.AnnotationMode == AnnotationMode.Circle || pdfViewerControl.AnnotationMode == AnnotationMode.Arrow || pdfViewerControl.AnnotationMode == AnnotationMode.Line) { m_shapeAnnoationToolbar.Visibility = ViewStates.Visible; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; } if (pdfViewerControl.AnnotationMode==AnnotationMode.Ink) pdfViewerControl.EndInkSession(false); pdfViewerControl.AnnotationMode = AnnotationMode.None; if(!pdfViewerControl.CanUndo) undoButton.SetTextColor(Color.Gray); pdfViewerControl.SelectionMode = SelectionMode.None; } private void OpacityButton_Click(object sender, EventArgs e) { if (!OpacityChanged) { if(pdfViewerControl.AnnotationMode==AnnotationMode.Ink) seekbar1.Progress = ((int)(pdfViewerControl.AnnotationSettings.Ink.Opacity * 100)); if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) seekbar1.Progress = ((int)(pdfViewerControl.AnnotationSettings.Rectangle.Settings.Opacity * 100)); if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) seekbar1.Progress = ((int)(pdfViewerControl.AnnotationSettings.Circle.Settings.Opacity * 100)); if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) seekbar1.Progress = ((int)(pdfViewerControl.AnnotationSettings.Line.Settings.Opacity * 100)); if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) seekbar1.Progress = ((int)(pdfViewerControl.AnnotationSettings.Arrow.Settings.Opacity * 100)); inkannotationbottomopacitytoolbar.Visibility = ViewStates.Visible; OpacityChanged = true; } else { OpacityChanged = false; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; } } private void InkAnnotationColorButton_Click(object sender, EventArgs e) { if (annotationbottomcolortoolbar.Visibility == ViewStates.Visible) { OpacityChanged = false; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; opacityButton.Visibility = ViewStates.Gone; return; } inkannotationthicknessToolbar.Visibility = ViewStates.Gone; opacityButton.Visibility = ViewStates.Visible; if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { Color color = pdfViewerControl.AnnotationSettings.Ink.Color; color.A = (byte)(255); opacityButton.SetTextColor(color); } SetColorFreeTextAnnotation(); SetColorRectangleAnnotation(); SetColorCircleAnnotation(); SetColorLineAnnotation(); SetColorArrowAnnotation(); if (pdfViewerControl.AnnotationMode == AnnotationMode.None && inkannot != null) { Color color = inkannot.Settings.Color; color.A = (byte)(255); opacityButton.SetTextColor(color); } else if(pdfViewerControl.AnnotationMode == AnnotationMode.None && signature != null) { Color color = signature.Settings.Color; color.A = (byte)255; opacityButton.SetTextColor(color); } annotationbottomcolortoolbar.Visibility = ViewStates.Visible; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Visible; lineView1.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; } private void SetColorFreeTextAnnotation() { if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { opacityButton.Visibility = ViewStates.Gone; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_freeTextAnnot != null) { opacityButton.Visibility = ViewStates.Gone; } } private void SetColorArrowAnnotation() { if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { Color color = pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor; color.A = (byte)(255); opacityButton.SetTextColor(color); } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_shapeAnnot != null) { Color color = m_shapeAnnot.Settings.StrokeColor; color.A = (byte)(255); opacityButton.SetTextColor(color); } } private void SetColorLineAnnotation() { if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) { Color color = pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor; color.A = (byte)(255); opacityButton.SetTextColor(color); } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_shapeAnnot != null) { Color color = m_shapeAnnot.Settings.StrokeColor; color.A = (byte)(255); opacityButton.SetTextColor(color); } } private void SetColorCircleAnnotation() { if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { Color color = pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor; color.A = (byte)(255); opacityButton.SetTextColor(color); } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_shapeAnnot != null) { Color color = m_shapeAnnot.Settings.StrokeColor; color.A = (byte)(255); opacityButton.SetTextColor(color); } } private void SetColorRectangleAnnotation() { if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { Color color = pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor; color.A = (byte)( 255); opacityButton.SetTextColor(color); } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_shapeAnnot != null) { Color color = m_shapeAnnot.Settings.StrokeColor; color.A = (byte)(255); opacityButton.SetTextColor(color); } } private void InkannotationThicknessButton_Click(object sender, EventArgs e) { if(ThicknessChanged) { lineView1.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; ThicknessChanged = false; return; } if (annotationbottomcolortoolbar.Visibility == ViewStates.Visible) { OpacityChanged = false; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; opacityButton.Visibility = ViewStates.Gone; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { lineView1.Visibility = ViewStates.Visible; linesLayoutGrid.Visibility = ViewStates.Visible; m_rangeandThicknessFrame.Visibility = ViewStates.Visible; m_rangeSliderView.Visibility = ViewStates.Invisible; var m_color = pdfViewerControl.AnnotationSettings.Ink.Color; m_color.A = (byte)255; lineOne1.SetBackgroundColor(m_color); lineTwo1.SetBackgroundColor(m_color); lineThree1.SetBackgroundColor(m_color); lineFour1.SetBackgroundColor(m_color); lineFive1.SetBackgroundColor(m_color); ThicknessChanged = true; } SetThicknessRectangleAnnotation(); SetThicknessCircleAnnotation(); SetThicknessLineAnnotation(); SetThicknessArrowAnnotation(); if(pdfViewerControl.AnnotationMode == AnnotationMode.FreeText||m_freeTextAnnot!=null) { lineView1.Visibility = ViewStates.Visible; linesLayoutGrid.Visibility = ViewStates.Invisible; m_rangeandThicknessFrame.Visibility = ViewStates.Visible; m_rangeSliderView.Visibility = ViewStates.Visible; } if (inkannot != null) { lineView1.Visibility = ViewStates.Visible; linesLayoutGrid.Visibility = ViewStates.Visible; m_rangeandThicknessFrame.Visibility = ViewStates.Visible; m_rangeSliderView.Visibility = ViewStates.Invisible; var m_color = inkannot.Settings.Color; m_color.A = (byte)255; lineOne1.SetBackgroundColor(m_color); lineTwo1.SetBackgroundColor(m_color); lineThree1.SetBackgroundColor(m_color); lineFour1.SetBackgroundColor(m_color); lineFive1.SetBackgroundColor(m_color); ThicknessChanged = true; } if (signature != null) { lineView1.Visibility = ViewStates.Visible; linesLayoutGrid.Visibility = ViewStates.Visible; m_rangeandThicknessFrame.Visibility = ViewStates.Visible; m_rangeSliderView.Visibility = ViewStates.Invisible; var m_color = signature.Settings.Color; m_color.A = (byte)255; lineOne1.SetBackgroundColor(m_color); lineTwo1.SetBackgroundColor(m_color); lineThree1.SetBackgroundColor(m_color); lineFour1.SetBackgroundColor(m_color); lineFive1.SetBackgroundColor(m_color); ThicknessChanged = true; } if (m_shapeAnnot!=null) { lineView1.Visibility = ViewStates.Visible; linesLayoutGrid.Visibility = ViewStates.Visible; m_rangeandThicknessFrame.Visibility = ViewStates.Visible; m_rangeSliderView.Visibility = ViewStates.Invisible; var m_color = m_shapeAnnot.Settings.StrokeColor; m_color.A = (byte)255; lineOne1.SetBackgroundColor(m_color); lineTwo1.SetBackgroundColor(m_color); lineThree1.SetBackgroundColor(m_color); lineFour1.SetBackgroundColor(m_color); lineFive1.SetBackgroundColor(m_color); ThicknessChanged = true; } lineView1.Visibility = ViewStates.Visible; linesLayout1.Visibility = ViewStates.Visible; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; } private void SetThicknessArrowAnnotation() { if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { linesLayoutGrid.Visibility = ViewStates.Visible; m_rangeandThicknessFrame.Visibility = ViewStates.Visible; m_rangeSliderView.Visibility = ViewStates.Invisible; var m_color = pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor; m_color.A = 255; lineOne1.SetBackgroundColor(m_color); lineTwo1.SetBackgroundColor(m_color); lineThree1.SetBackgroundColor(m_color); lineFour1.SetBackgroundColor(m_color); lineFive1.SetBackgroundColor(m_color); ThicknessChanged = true; } } private void SetThicknessLineAnnotation() { if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) { linesLayoutGrid.Visibility = ViewStates.Visible; m_rangeandThicknessFrame.Visibility = ViewStates.Visible; m_rangeSliderView.Visibility = ViewStates.Invisible; var m_color = pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor; m_color.A = (byte)255; lineOne1.SetBackgroundColor(m_color); lineTwo1.SetBackgroundColor(m_color); lineThree1.SetBackgroundColor(m_color); lineFour1.SetBackgroundColor(m_color); lineFive1.SetBackgroundColor(m_color); ThicknessChanged = true; } } private void SetThicknessCircleAnnotation() { if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { linesLayoutGrid.Visibility = ViewStates.Visible; m_rangeandThicknessFrame.Visibility = ViewStates.Visible; m_rangeSliderView.Visibility = ViewStates.Invisible; var m_color = pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor; m_color.A = 255; lineOne1.SetBackgroundColor(m_color); lineTwo1.SetBackgroundColor(m_color); lineThree1.SetBackgroundColor(m_color); lineFour1.SetBackgroundColor(m_color); lineFive1.SetBackgroundColor(m_color); ThicknessChanged = true; } } private void SetThicknessRectangleAnnotation() { if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { linesLayoutGrid.Visibility = ViewStates.Visible; m_rangeandThicknessFrame.Visibility = ViewStates.Visible; m_rangeSliderView.Visibility = ViewStates.Invisible; var m_color = pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor; m_color.A = (byte)255; lineOne1.SetBackgroundColor(m_color); lineTwo1.SetBackgroundColor(m_color); lineThree1.SetBackgroundColor(m_color); lineFour1.SetBackgroundColor(m_color); lineFive1.SetBackgroundColor(m_color); ThicknessChanged = true; } } private void Inkannotationbackbutton_Click(object sender, EventArgs e) { linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; shapeAnnotationBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Invisible; toolBarGrid.Visibility = ViewStates.Visible; if(pdfViewerControl.AnnotationMode==AnnotationMode.Ink) pdfViewerControl.EndInkSession(true); pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; } private void Inkredobutton_Click(object sender, EventArgs e) { pdfViewerControl.RedoInk(); } private void Inkundobutton_Click(object sender, EventArgs e) { pdfViewerControl.UndoInk(); } private void AnnotationsBackButton_Click(object sender, EventArgs e) { annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; pdfViewerControl.SelectionMode = SelectionMode.None; IsAnnotationModeSelected = false; } private void InkAnnotationButton_Click(object sender, EventArgs e) { var m_colorbuttonbackground = pdfViewerControl.AnnotationSettings.Ink.Color; m_colorbuttonbackground.A = (byte)255; inkAnnotationColorButton.SetBackgroundColor(m_colorbuttonbackground); pdfViewerControl.AnnotationMode = AnnotationMode.Ink; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Invisible; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Visible; inkannotationgrid.Visibility = ViewStates.Visible; inkannotationbottomgrid.Visibility = ViewStates.Visible; inkannotationbottomtoolbar.Visibility = ViewStates.Visible; inkredobutton.Visibility = ViewStates.Visible; inkundobutton.Visibility = ViewStates.Visible; inkButton.Text = "\uE71d"; inkButton.Visibility = ViewStates.Visible; inkBackButton.Visibility = ViewStates.Visible; inkremovebutton.Visibility = ViewStates.Gone; inkannotationThicknessButton.Typeface = font; inkannotationThicknessButton.Text = "\uE722"; var m_color = pdfViewerControl.AnnotationSettings.Ink.Color; m_color.A = (byte)255; inkannotationThicknessButton.SetTextColor(m_color); opacityButton.Visibility = ViewStates.Visible; } private void TextMarkupAnnotationButton_Click(object sender, EventArgs e) { annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; shapeAnnotationBarGrid.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Visible; annotationBarGrid.Visibility = ViewStates.Visible; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Gone; } private bool IsAnnotationModeSelected { get { return m_isAnnotationModeSelected; } set { m_isAnnotationModeSelected = value; } } #region DocumentSelectionMenu private void SelectionButton_Click(object sender, EventArgs e) { if (searchBarGrid.Visibility == ViewStates.Visible) { InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(mainView.WindowToken, HideSoftInputFlags.None); } PopupMenu popup = new PopupMenu(pdfViewerContext, selectionButton); popup.Inflate(Resource.Drawable.popup_menu_pdfViewer); popup.MenuItemClick += Popup_MenuItemClick; popup.Show(); } private void Popup_MenuItemClick(object sender, PopupMenu.MenuItemClickEventArgs e) { bookmarkToolbar.ClearBookmark(); //Collapse the bookmark toolbar when a new PDF is selected CollapseBookmarkToolbar(); string documentName = e.Item.TitleFormatted.ToString(); if (documentName != backupDocumentName || disableToolbar) { pdfViewerControl.Unload(); DisableToolbar(); backupDocumentName = documentName; Stream docStream = typeof(PdfViewerDemo).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDFViewer.Assets." + documentName + ".pdf"); try { bookmarkToolbar.bookmarkLoadedDocument = new PdfLoadedDocument(docStream, ""); } catch (PdfException) { DisplayInitialPopup(); i++; return; } bookmarkToolbar.PopulateInitialBookmarkList(); pdfViewerControl.LoadDocument(docStream); } if (isLoadedDocument) EnableToolbar(); } private void EnableToolbar() { enableToolbar = true; if (!saveButton.Enabled) saveButton.Enabled = true; if (!bookmarkButton.Enabled) bookmarkButton.Enabled = true; if (!searchButton.Enabled) searchButton.Enabled = true; if (!pageNumberEntry.Enabled) pageNumberEntry.Enabled = true; if (!annotationModeButton.Enabled) annotationModeButton.Enabled = true; if (!viewModeButton.Enabled) viewModeButton.Enabled = true; pdfViewerControl.EnableScrollHead = true; saveButton.SetTextColor(fontColor); bookmarkButton.SetTextColor(fontColor); searchButton.SetTextColor(fontColor); pageNumberEntry.SetTextColor(fontColor); annotationModeButton.SetTextColor(fontColor); viewModeButton.SetTextColor(fontColor); pageCountText.SetTextColor(fontColor); } private void DisableToolbar() { disableToolbar = true; if (saveButton.Enabled) saveButton.Enabled = false; if (bookmarkButton.Enabled) bookmarkButton.Enabled = false; if (searchButton.Enabled) searchButton.Enabled = false; if (pageNumberEntry.Enabled) pageNumberEntry.Enabled = false; if (annotationModeButton.Enabled) annotationModeButton.Enabled = false; if (viewModeButton.Enabled) viewModeButton.Enabled = false; pdfViewerControl.EnableScrollHead = false; saveButton.SetTextColor(Color.Gray); bookmarkButton.SetTextColor(Color.Gray); searchButton.SetTextColor(Color.Gray); pageNumberEntry.SetTextColor(Color.Gray); annotationModeButton.SetTextColor(Color.Gray); viewModeButton.SetTextColor(Color.Gray); pageCountText.SetTextColor(Color.Gray); pageCountText.Text = "0"; pageNumberEntry.Text = "0"; } private void PdfViewerControl_DocumentLoaded1(object sender, EventArgs e) { initialPopup.Dismiss(); errorView.Visibility = ViewStates.Invisible; InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(mainView.WindowToken, HideSoftInputFlags.None); } #region Password Protected public PasswordTransformationMethod TransformationMethod { get; private set; } private void DisplayInitialPopup() { #region Popup Properties initialPopup = new SfPopupLayout(mainView.Context); initialPopup.PopupView.WidthRequest = 400; initialPopup.PopupView.HeightRequest = 230; headerLinear = new LinearLayout(mainView.Context); LinearLayout linear = new LinearLayout(mainView.Context); editText = new EditText(mainView.Context); if (IsTablet(mainView.Context)) { headerLinear.SetPadding(20, 10, 0, 0); linear.SetPadding(20, 20, 20, 0); editText.Layout(0, 70, 0, 0); initialPopup.PopupView.WidthRequest = 430 * mainView.Context.Resources.DisplayMetrics.Density; initialPopup.PopupView.HeightRequest = 230 * mainView.Context.Resources.DisplayMetrics.Density; } else { headerLinear.SetPadding(40, 40, 0, 0); linear.SetPadding(40, 20, 40, 0); editText.Layout(-20, 60, 0, 0); if (screenSize == ScreenSize.Small || screenSize == ScreenSize.Normal) { editText.SetHeight(100); editText.SetPadding(0, 20, 0, 0); initialPopup.PopupView.WidthRequest = 140 * mainView.Context.Resources.DisplayMetrics.Density; initialPopup.PopupView.HeightRequest = 85 * mainView.Context.Resources.DisplayMetrics.Density; } else if (screenSize == ScreenSize.Large || screenSize == ScreenSize.XLarge) { editText.SetHeight(150); editText.SetPadding(-5, 20, 0, 0); initialPopup.PopupView.WidthRequest = 140 * mainView.Context.Resources.DisplayMetrics.Density; initialPopup.PopupView.HeightRequest = 80 * mainView.Context.Resources.DisplayMetrics.Density; } } initialPopup.PopupView.ShowFooter = true; initialPopup.PopupView.ShowCloseButton = true; initialPopup.PopupView.HeaderTitle = "Password Protected"; initialPopup.PopupView.AcceptButtonText = "OK"; initialPopup.PopupView.DeclineButtonText = "CANCEL"; initialPopup.Closed += InitialPopup_Closed; initialPopup.PopupView.PopupStyle.HeaderTextSize = (int)(10 * mainView.Context.Resources.DisplayMetrics.Density); initialPopup.StaysOpen = true; #endregion initialPopup.PopupView.HeaderView = headerLinear; titleText = new TextView(mainView.Context); titleText.Text = "Password Protected"; titleText.SetTextSize(ComplexUnitType.Dip, 20); titleText.SetTextColor(Color.Black); titleText.Typeface = Typeface.DefaultBold; headerLinear.AddView(titleText); linear.Orientation = Android.Widget.Orientation.Vertical; TextView messageView = new TextView(mainView.Context); messageView.Text = "Enter the password to open this PDF File."; messageView.SetTextColor(Color.Black); messageView.SetTextSize(ComplexUnitType.Dip, 17); messageView.Typeface = Typeface.Default; linear.AddView(messageView); editText.TransformationMethod = Android.Text.Method.PasswordTransformationMethod.Instance; editText.Hint = "Password: <PASSWORD>"; editText.SetTextSize(ComplexUnitType.Dip, 15); //LinearLayout.LayoutParams ip=new LinearLayout.LayoutParams MarginLayoutParams parameter = new MarginLayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent); parameter.SetMargins(-5, 20, 0, 10); editText.LayoutParameters = parameter; if (IsDeviceTablet) editText.SetPadding(10, 0, 0, 0); else editText.SetPadding(10, 0, 0, 0); editText.TextChanged += EditText_TextChanged; editText.FocusChange += EditText_FocusChange; editText.KeyPress+= AcceptButton_Click; editText.SetWidth(10); linear.AddView(editText); errorView = new TextView(mainView.Context); errorView.Text = "Invalid Password!"; errorView.SetTextColor(Color.Red); if(IsTablet(mainView.Context)) { errorView.SetPadding(0, -5, 0, 0); parameter.SetMargins(0,-10,0,0); errorView.LayoutParameters = parameter; } else errorView.SetPadding(0, -15, 0, 0); errorView.SetBackgroundColor(Color.White); errorView.SetTextSize(ComplexUnitType.Dip, 17); errorView.Visibility = ViewStates.Invisible; errorView.Typeface = Typeface.Default; linear.AddView(errorView); initialPopup.PopupView.ContentView = linear; footerLinear = new LinearLayout(mainView.Context); declineButton = new Button(mainView.Context); declineButton.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); declineButton.Text = "CANCEL"; declineButton.SetTextSize(ComplexUnitType.Dip, 15); declineButton.SetBackgroundColor(Color.Transparent); declineButton.Click += DeclineButton_Click; footerLinear.AddView(declineButton); declineButton.Gravity = GravityFlags.End; footerLinear.SetHorizontalGravity(GravityFlags.Right); acceptButton = new Button(mainView.Context); acceptButton.SetWidth(0); acceptButton.Text = "OK"; acceptButton.Enabled = false; acceptButton.SetTextSize(ComplexUnitType.Dip, 15); acceptButton.SetForegroundGravity(GravityFlags.End); acceptButton.SetBackgroundColor(Color.Transparent); acceptButton.Gravity = GravityFlags.Center; acceptButton.Click += AcceptButton_Click; footerLinear.AddView(acceptButton); initialPopup.PopupView.FooterView = footerLinear; initialPopup.PopupView.PopupStyle.CornerRadius = 0; initialPopup.Show(); } private void EditText_FocusChange(object sender, View.FocusChangeEventArgs e) { editText.RequestFocus(); InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(editText.WindowToken, HideSoftInputFlags.ImplicitOnly); } private void InitialPopup_Closed(object sender, EventArgs e) { if (!isLoadedDocument) { DisableToolbar(); } } public ScreenSize GetScreenSize() { if ((mainView.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeNormal) return ScreenSize.Normal; else if ((mainView.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeLarge) return ScreenSize.Large; else if ((mainView.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeSmall) return ScreenSize.Small; else if ((mainView.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeXlarge) return ScreenSize.Small; return ScreenSize.Normal; } public static bool IsTablet(Context context) { Display display = ((Activity)context).WindowManager.DefaultDisplay; DisplayMetrics displayMetrics = new DisplayMetrics(); display.GetMetrics(displayMetrics); var wInches = displayMetrics.WidthPixels / (double)displayMetrics.DensityDpi; var hInches = displayMetrics.HeightPixels / (double)displayMetrics.DensityDpi; double screenDiagonal = Math.Sqrt(Math.Pow(wInches, 2) + Math.Pow(hInches, 2)); return (screenDiagonal >= 7.0); } private void EditText_TextChanged(object sender, Android.Text.TextChangedEventArgs e) { if (editText.Text != "") { acceptButton.Enabled = true; acceptButton.SetTextColor(Color.Rgb(0, 118, 255)); } else { acceptButton.Enabled = false; acceptButton.SetTextColor(Color.Gray); } } private void DeclineButton_Click(object sender, System.EventArgs e) { initialPopup.Dismiss(); pdfViewerControl.Unload(); DisableToolbar(); InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(mainView.WindowToken, HideSoftInputFlags.None); } private void AcceptButton_Click(object sender, System.EventArgs e) { initialPopup.Dismiss(); Stream docStream = typeof(PdfViewerDemo).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDFViewer.Assets." + backupDocumentName + ".pdf"); pdfViewerControl.LoadDocument(docStream, editText.Text); if (isLoadedDocument) { EnableToolbar(); InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(mainView.WindowToken, HideSoftInputFlags.None); } } public enum ScreenSize { Small = 0, Normal, Large, XLarge } #endregion #endregion #region TextSearch private void SearchView_TextChanged(object sender, Android.Text.TextChangedEventArgs e) { if (searchView.Text != string.Empty) { clearSearchButton.Visibility = ViewStates.Visible; } else { clearSearchButton.Visibility = ViewStates.Invisible; } } private void ClearSearchButton_Click(object sender, EventArgs e) { pdfViewerControl.CancelSearch(); searchView.Text = ""; clearSearchButton.Visibility = ViewStates.Invisible; InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.ShowSoftInput(searchView, ShowFlags.Implicit); } private void SearchView_KeyPress(object sender, View.KeyEventArgs e) { var editText = sender as EditText; if (e.KeyCode == Keycode.Enter) { if (!string.IsNullOrWhiteSpace(editText.Text) && !string.IsNullOrEmpty(editText.Text)) { searchText = editText.Text; pdfViewerControl.SearchText(searchText); } InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(mainView.WindowToken, HideSoftInputFlags.None); } if (e.KeyCode == Keycode.Del) { if (editText.Length() > 0) { editText.Text = editText.Text.Remove(editText.Length() - 1, 1); editText.SetSelection(editText.Text.Length); } else pdfViewerControl.CancelSearch(); } pdfViewerControl.SelectionMode = SelectionMode.None; } private void BackButton_Click(object sender, EventArgs e) { if (searchBarGrid.Visibility == ViewStates.Visible) { searchBarGrid.Visibility = ViewStates.Invisible; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.CancelSearch(); searchView.Text = ""; clearSearchButton.Visibility = ViewStates.Invisible; InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(mainView.WindowToken, HideSoftInputFlags.None); } } private void SearchButton_Click(object sender, EventArgs e) { CollapseBookmarkToolbar(); annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; if (toolBarGrid.Visibility == ViewStates.Visible) { toolBarGrid.Visibility = ViewStates.Invisible; searchBarGrid.Visibility = ViewStates.Visible; searchView.RequestFocus(); clearSearchButton.Visibility = ViewStates.Invisible; InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.ShowSoftInput(searchView, ShowFlags.Implicit); } } string searchText = string.Empty; private Button TextAnnotationButton; private LinearLayout shapeAnnotationBarGrid; private Button rectangleModeButton; private Button circleModeButton; private Button lineModeButton; private Button arrowModeButton; private Button shapeannotationBackButton; private Typeface fontSizeFont; internal Typeface font, viewModeFont; internal Typeface bookmarkFont, stampFont; private ShapeAnnotation m_shapeAnnot; private FreeTextAnnotation m_freeTextAnnot; private StampAnnotation m_selectedStampAnnotation; private Context m_context; private LinearLayout linesLayoutGrid; private FrameLayout m_rangeandThicknessFrame; private Button m_editTextAnntationButton; internal Typeface signatureFont; #endregion private void PdfViewerControl_PageChanged(object sender, PageChangedEventArgs args) { pageNumberEntry.Text = args.NewPageNumber.ToString(); } private void PdfViewerControl_DocumentLoaded(object sender, EventArgs args) { isLoadedDocument = true; pageNumberEntry.Text = pdfViewerControl.PageNumber.ToString(); pageCountText.Text = pdfViewerControl.PageCount.ToString(); if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.EndInkSession(false); inkremovebutton.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; pdfViewerControl.AnnotationMode = AnnotationMode.None; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; //if(initialPopup!=null) //initialPopup.Dismiss(); EnableToolbar(); } private void PageNumberEntry_KeyPress(object sender, View.KeyEventArgs e) { e.Handled = false; if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter) { int pageNumber = 0; if (int.TryParse((pageNumberEntry.Text), out pageNumber)) { if ((pageNumber > 0) && (pageNumber <= pdfViewerControl.PageCount)) pdfViewerControl.GoToPage(pageNumber); else { DisplayAlertDialog(); pageNumberEntry.Text = pdfViewerControl.PageNumber.ToString(); } } pageNumberEntry.ClearFocus(); InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(mainView.WindowToken, HideSoftInputFlags.None); } } void DisplayAlertDialog() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainView.Context); alertDialog.SetTitle("Error"); alertDialog.SetMessage("Please enter the valid page number"); alertDialog.SetPositiveButton("OK", (senderAlert, args) => { }); Dialog dialog = alertDialog.Create(); dialog.Show(); } private void AnnotationBackButton_Click(object sender, EventArgs e) { annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; } private void StrikeoutModeButton_Click(object sender, EventArgs e) { annotationBackGrid.Visibility = ViewStates.Visible; annotationButton.Text = "\uE711"; removeButton.Visibility = ViewStates.Gone; annotationBackButton.Visibility = ViewStates.Visible; annotationButton.Visibility = ViewStates.Visible; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color); pdfViewerControl.AnnotationMode = AnnotationMode.Strikethrough; } private void UnderlineModeButton_Click(object sender, EventArgs e) { annotationBackGrid.Visibility = ViewStates.Visible; removeButton.Visibility = ViewStates.Gone; annotationBackButton.Visibility = ViewStates.Visible; annotationButton.Visibility = ViewStates.Visible; annotationButton.Text = "\uE70d"; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color); pdfViewerControl.AnnotationMode = AnnotationMode.Underline; } private void HighlightModeButton_Click(object sender, EventArgs e) { annotationBackGrid.Visibility = ViewStates.Visible; annotationButton.Visibility = ViewStates.Visible; annotationButton.Text = "\uE715"; annotationBackButton.Visibility = ViewStates.Visible; removeButton.Visibility = ViewStates.Gone; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color); pdfViewerControl.AnnotationMode = AnnotationMode.Highlight; } private void AnnotationModeButton_Click(object sender, EventArgs e) { CollapseBookmarkToolbar(); pdfViewerControl.SelectionMode = SelectionMode.None; if (!pdfViewerControl.CanUndo) undoButton.SetTextColor(Color.Gray); if (!IsAnnotationModeSelected) { if (searchBarGrid.Visibility == ViewStates.Visible) { InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(mainView.WindowToken, HideSoftInputFlags.None); } if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.EndInkSession(false); m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Visible; annotationsGrid.Visibility = ViewStates.Visible; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; searchBarGrid.Visibility = ViewStates.Gone; IsAnnotationModeSelected = true; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkremovebutton.Visibility = ViewStates.Gone; pdfViewerControl.AnnotationMode = AnnotationMode.None; } else { if (searchBarGrid.Visibility == ViewStates.Visible) { InputMethodManager inputMethodManager = (InputMethodManager)mainView.Context.GetSystemService(Context.InputMethodService); inputMethodManager.HideSoftInputFromWindow(mainView.WindowToken, HideSoftInputFlags.None); } if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.EndInkSession(false); inkremovebutton.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; pdfViewerControl.AnnotationMode = AnnotationMode.None; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; pdfViewerControl.AnnotationMode = AnnotationMode.None; } } private void AnnotationColorButton_Click(object sender, EventArgs e) { annotationbottomcolortoolbar.Visibility = ViewStates.Visible; annotationColorBarGrid.Visibility = ViewStates.Visible; annotationToolBar.Visibility = ViewStates.Visible; annotationBackGrid.Visibility = ViewStates.Visible; } private void BlackcolorButton_Click(object sender, EventArgs e) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) { pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Android.Graphics.Color.Black; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) { pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Android.Graphics.Color.Black; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) { pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Android.Graphics.Color.Black; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && inkannot != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Black); inkannot.Settings.Color = Android.Graphics.Color.Black; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Black); inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && signature != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Black); signature.Settings.Color = Android.Graphics.Color.Black; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Black); inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && annotation != null) { annotationColorButton.SetBackgroundColor(Android.Graphics.Color.Black); annotation.Settings.Color = Android.Graphics.Color.Black; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Black); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Black); pdfViewerControl.AnnotationSettings.Ink.Color = Android.Graphics.Color.Black; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Black); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Black); pdfViewerControl.AnnotationSettings.HandwrittenSignature.Color = Android.Graphics.Color.Black; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Black); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } SetGreenRectangleAnnotation(Android.Graphics.Color.Black); SetGreenCircleAnnotation(Android.Graphics.Color.Black); SetGreenLineAnnotation(Android.Graphics.Color.Black); SetGreenArrowAnnotation(Android.Graphics.Color.Black); SetGreenFreeTextAnnotation(Android.Graphics.Color.Black); annotationBackGrid.Visibility = ViewStates.Visible; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; } private void WhitecolorButton_Click(object sender, EventArgs e) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) { pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Android.Graphics.Color.White; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) { pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Android.Graphics.Color.White; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) { pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Android.Graphics.Color.White; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && annotation != null) { annotationColorButton.SetBackgroundColor(Android.Graphics.Color.White); annotation.Settings.Color = Android.Graphics.Color.White; annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && inkannot != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.White); inkannot.Settings.Color = Android.Graphics.Color.White; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.White); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.White); pdfViewerControl.AnnotationSettings.Ink.Color = Android.Graphics.Color.White; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.White); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && signature != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.White); signature.Settings.Color = Android.Graphics.Color.White; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.White); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.White); pdfViewerControl.AnnotationSettings.HandwrittenSignature.Color = Android.Graphics.Color.White; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.White); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } SetGreenRectangleAnnotation(Android.Graphics.Color.White); SetGreenCircleAnnotation(Android.Graphics.Color.White); SetGreenLineAnnotation(Android.Graphics.Color.White); SetGreenArrowAnnotation(Android.Graphics.Color.White); SetGreenFreeTextAnnotation(Android.Graphics.Color.White); annotationBackGrid.Visibility = ViewStates.Visible; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; } private void MagentacolorButton_Click(object sender, EventArgs e) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) { pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Android.Graphics.Color.Magenta; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) { pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Android.Graphics.Color.Magenta; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) { pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Android.Graphics.Color.Magenta; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && annotation != null) { annotationToolBar.Visibility = ViewStates.Visible; annotationColorButton.SetBackgroundColor(Android.Graphics.Color.Magenta); annotation.Settings.Color = Android.Graphics.Color.Magenta; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && inkannot != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Magenta); inkannot.Settings.Color = Android.Graphics.Color.Magenta; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Magenta); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Magenta); pdfViewerControl.AnnotationSettings.Ink.Color = Android.Graphics.Color.Magenta; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Magenta); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && signature != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Magenta); signature.Settings.Color = Android.Graphics.Color.Magenta; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Magenta); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Magenta); pdfViewerControl.AnnotationSettings.HandwrittenSignature.Color = Android.Graphics.Color.Magenta; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Magenta); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } SetGreenRectangleAnnotation(Android.Graphics.Color.Magenta); SetGreenCircleAnnotation(Android.Graphics.Color.Magenta); SetGreenLineAnnotation(Android.Graphics.Color.Magenta); SetGreenArrowAnnotation(Android.Graphics.Color.Magenta); SetGreenFreeTextAnnotation(Android.Graphics.Color.Magenta); annotationBackGrid.Visibility = ViewStates.Visible; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; } private void GreencolorButton_Click(object sender, EventArgs e) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) { pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Android.Graphics.Color.Green; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) { pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Android.Graphics.Color.Green; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) { pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Android.Graphics.Color.Green; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && annotation != null) { annotationColorButton.SetBackgroundColor(Android.Graphics.Color.Green); annotation.Settings.Color = Android.Graphics.Color.Green; annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && inkannot != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Green); inkannot.Settings.Color = Android.Graphics.Color.Green; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Green); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Green); pdfViewerControl.AnnotationSettings.Ink.Color = Android.Graphics.Color.Green; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Green); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && signature != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Green); signature.Settings.Color = Android.Graphics.Color.Green; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Green); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Green); pdfViewerControl.AnnotationSettings.HandwrittenSignature.Color = Android.Graphics.Color.Green; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Green); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } SetGreenRectangleAnnotation(Android.Graphics.Color.Green); SetGreenCircleAnnotation(Android.Graphics.Color.Green); SetGreenLineAnnotation(Android.Graphics.Color.Green); SetGreenArrowAnnotation(Android.Graphics.Color.Green); SetGreenFreeTextAnnotation(Android.Graphics.Color.Green); annotationBackGrid.Visibility = ViewStates.Visible; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; } private void SetGreenFreeTextAnnotation(Color color) { if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { inkAnnotationColorButton.SetBackgroundColor(color); pdfViewerControl.AnnotationSettings.FreeText.TextColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_freeTextAnnot != null) { inkAnnotationColorButton.SetBackgroundColor(color); m_freeTextAnnot.Settings.TextColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } } private void SetGreenArrowAnnotation(Color color) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { inkAnnotationColorButton.SetBackgroundColor(color); pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_shapeAnnot != null) { inkAnnotationColorButton.SetBackgroundColor(color); m_shapeAnnot.Settings.StrokeColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } } private void SetGreenLineAnnotation(Color color) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) { inkAnnotationColorButton.SetBackgroundColor(color); pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_shapeAnnot != null) { inkAnnotationColorButton.SetBackgroundColor(color); m_shapeAnnot.Settings.StrokeColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } } private void SetGreenCircleAnnotation(Color color) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { inkAnnotationColorButton.SetBackgroundColor(color); pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_shapeAnnot != null) { inkAnnotationColorButton.SetBackgroundColor(color); m_shapeAnnot.Settings.StrokeColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } } private void SetGreenRectangleAnnotation(Color color) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { inkAnnotationColorButton.SetBackgroundColor(color); pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && m_shapeAnnot != null) { inkAnnotationColorButton.SetBackgroundColor(color); m_shapeAnnot.Settings.StrokeColor = color; inkannotationThicknessButton.SetTextColor(color); annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } } private void YellowcolorButton_Click(object sender, EventArgs e) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) { pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Android.Graphics.Color.Yellow; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) { pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Android.Graphics.Color.Yellow; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) { pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Android.Graphics.Color.Yellow; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && inkannot != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Yellow); inkannot.Settings.Color = Android.Graphics.Color.Yellow; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Yellow); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Yellow); pdfViewerControl.AnnotationSettings.Ink.Color = Android.Graphics.Color.Yellow; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Yellow); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && annotation != null) { annotationColorButton.SetBackgroundColor(Android.Graphics.Color.Yellow); annotation.Settings.Color = Android.Graphics.Color.Yellow; annotationToolBar.Visibility = ViewStates.Visible; } SetGreenRectangleAnnotation(Android.Graphics.Color.Yellow); SetGreenCircleAnnotation(Android.Graphics.Color.Yellow); SetGreenLineAnnotation(Android.Graphics.Color.Yellow); SetGreenArrowAnnotation(Android.Graphics.Color.Yellow); SetGreenFreeTextAnnotation(Android.Graphics.Color.Yellow); annotationBackGrid.Visibility = ViewStates.Visible; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; } private void CyancolorButton_Click(object sender, EventArgs e) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) { pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Android.Graphics.Color.Cyan; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) { pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Android.Graphics.Color.Cyan; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) { pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Android.Graphics.Color.Cyan; annotationColorButton.SetBackgroundColor(pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color); annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && annotation != null) { annotationColorButton.SetBackgroundColor(Android.Graphics.Color.Cyan); annotation.Settings.Color = Android.Graphics.Color.Cyan; annotationToolBar.Visibility = ViewStates.Visible; } if (pdfViewerControl.AnnotationMode == AnnotationMode.None && inkannot != null) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Cyan); inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Cyan); inkannot.Settings.Color= Android.Graphics.Color.Cyan; annotationToolBar.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { inkAnnotationColorButton.SetBackgroundColor(Android.Graphics.Color.Cyan); pdfViewerControl.AnnotationSettings.Ink.Color = Android.Graphics.Color.Cyan; inkannotationThicknessButton.SetTextColor(Android.Graphics.Color.Cyan); annotationbottomcolortoolbar.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; OpacityChanged = false; } SetGreenRectangleAnnotation(Android.Graphics.Color.Cyan); SetGreenCircleAnnotation(Android.Graphics.Color.Cyan); SetGreenLineAnnotation(Android.Graphics.Color.Cyan); SetGreenArrowAnnotation(Android.Graphics.Color.Cyan); SetGreenFreeTextAnnotation(Android.Graphics.Color.Cyan); annotationBackGrid.Visibility = ViewStates.Visible; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; } private void RemoveButton_Click(object sender, EventArgs e) { m_shapeAnnot = null; m_freeTextAnnot = null; inkannot = null; signature = null; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Invisible; annotationBackGrid.Visibility = ViewStates.Invisible; annotationColorBarGrid.Visibility = ViewStates.Invisible; if (annotation != null) pdfViewerControl.RemoveAnnotation(annotation); else if (m_selectedStampAnnotation != null) pdfViewerControl.RemoveAnnotation(m_selectedStampAnnotation); IsAnnotationModeSelected = false; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; pdfViewerControl.AnnotationMode = AnnotationMode.None; annotationToolBar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; } private void RedoButton_Click(object sender, EventArgs e) { annotationToolBar.Visibility = ViewStates.Gone; pdfViewerControl.AnnotationMode = AnnotationMode.None; pdfViewerControl.PerformRedo(); IsAnnotationModeSelected = false; } private void UndoButton_Click(object sender, EventArgs e) { annotationToolBar.Visibility = ViewStates.Gone; pdfViewerControl.AnnotationMode = AnnotationMode.None; pdfViewerControl.PerformUndo(); IsAnnotationModeSelected = false; } private void SaveButton_Click(object sender, EventArgs e) { annotationToolBar.Visibility = ViewStates.Gone; m_shapeAnnoationToolbar.Visibility = ViewStates.Gone; pdfViewerControl.AnnotationMode = AnnotationMode.None; IsAnnotationModeSelected = false; Stream stream1 = pdfViewerControl.SaveDocument(); MemoryStream stream = stream1 as MemoryStream; string root = null; string fileName = backupDocumentName + ".pdf"; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) file.Delete(); Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); AlertDialog.Builder alertDialog = new AlertDialog.Builder(mainView.Context); alertDialog.SetTitle("Save"); alertDialog.SetMessage("The modified document is saved in the below location. " + "\n" + file.Path); alertDialog.SetPositiveButton("OK", (senderAlert, args) => { }); Dialog dialog = alertDialog.Create(); dialog.Show(); } private void SelectedannotationColorButton_Click(object sender, EventArgs e) { annotationColorBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; if (annotationBarGrid.Visibility == ViewStates.Visible) annotationBarGrid.Visibility = ViewStates.Invisible; if (annotationBackButton.Visibility == ViewStates.Visible) annotationBackButton.Visibility = ViewStates.Invisible; if (annotationColorButton.Visibility == ViewStates.Visible) annotationColorButton.Visibility = ViewStates.Invisible; } private void PdfViewerControl_TextMarkupDeselected(object sender, TextMarkupDeselectedEventArgs args) { annotationColorBarGrid.Visibility = ViewStates.Gone; annotationButton.Visibility = ViewStates.Gone; annotationBackButton.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationBarGrid.Visibility = ViewStates.Gone; annotationBackGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; annotationToolBar.Visibility = ViewStates.Gone; } private void PdfViewerControl_TextMarkupSelected(object sender, TextMarkupSelectedEventArgs args) { m_shapeAnnot = null; inkannot = null; signature = null; m_freeTextAnnot = null; annotation = (sender as TextMarkupAnnotation); annotationToolBar.Visibility = ViewStates.Visible; annotationBackGrid.Visibility = ViewStates.Visible; annotationColorButton.SetBackgroundColor(annotation.Settings.Color); removeButton.Visibility = ViewStates.Visible; annotationButton.Visibility = ViewStates.Gone; annotationBackButton.Visibility = ViewStates.Gone; IsAnnotationModeSelected = false; inkannotationbottomopacitytoolbar.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; annotationColorBarGrid.Visibility = ViewStates.Gone; searchBarGrid.Visibility = ViewStates.Gone; annotationsToolbar.Visibility = ViewStates.Gone; annotationsGrid.Visibility = ViewStates.Gone; inkannotationthicknessToolbar.Visibility = ViewStates.Gone; inkannotationthicknessGrid.Visibility = ViewStates.Gone; linesLayout1.Visibility = ViewStates.Gone; inkannotationtoolbar.Visibility = ViewStates.Gone; inkannotationgrid.Visibility = ViewStates.Gone; inkannotationbottomgrid.Visibility = ViewStates.Gone; inkannotationbottomtoolbar.Visibility = ViewStates.Gone; toolBarGrid.Visibility = ViewStates.Visible; pdfViewerControl.AnnotationMode = AnnotationMode.None; opacityButton.Visibility = ViewStates.Gone; annotationbottomcolortoolbar.Visibility = ViewStates.Gone; lineView1.Visibility = ViewStates.Gone; } private void PdfViewerControl_CanUndoModified(object sender, CanUndoModifiedEventArgs args) { if (args.CanUndo) { undoButton.SetTextColor(fontColor); } else { undoButton.SetTextColor(Color.Gray); } } private void PdfViewerControl_CanRedoModified(object sender, CanRedoModifiedEventArgs args) { if (args.CanRedo) { redoButton.SetTextColor(fontColor); } else { redoButton.SetTextColor(Color.Gray); } } public override void Destroy() { pdfViewerControl.Unload(); GC.Collect(); GC.WaitForPendingFinalizers(); base.Destroy(); } } internal class MainViewLayoutListener : Java.Lang.Object, View.IOnLayoutChangeListener { internal CustomToolBarPdfViewerDemo sampleView; public void OnLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { if (sampleView.bookmarkToolbar != null && sampleView.pdfViewerControl != null) { if (!sampleView.IsDeviceTablet) { if (!sampleView.isBookmarkVisible) { sampleView.pdfViewerControl.Layout(left, top, right, sampleView.m_bottomToolbars.Top); sampleView.bookmarkToolbar.Layout(0, 0, 0, 0); } else { sampleView.pdfViewerControl.Layout(0, 0, 0, 0); sampleView.bookmarkToolbar.Layout(left, top, right, bottom); } } else { if (!sampleView.isBookmarkVisible) { sampleView.pdfViewerControl.LayoutParameters = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1); sampleView.bookmarkToolbarParentLayout.LayoutParameters = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 0); } else { sampleView.pdfViewerControl.LayoutParameters = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 3); sampleView.bookmarkToolbarParentLayout.LayoutParameters = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 2); } } if (sampleView.stampSelectionView != null && !sampleView.IsDeviceTablet) { if (!sampleView.stampSelectionView.isShowing) { sampleView.pdfViewerControl.Layout(left, top, right, sampleView.m_bottomToolbars.Top); sampleView.stampSelectionView.Layout(0, 0, 0, 0); } else { sampleView.stampSelectionView.Layout(left, top, right, bottom); } } } } } }<file_sep>/iOS/SampleBrowser/Samples/Maps/DataMarkers.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Syncfusion.SfBusyIndicator.iOS; #endregion using System; using Syncfusion.SfMaps.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGPoint= System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class DataMarkers: SampleView { UILabel label; UIView view; UIView markerView; UIView toastView; SFMap maps; internal SfBusyIndicator busyindicator; bool isDisposed; public override void LayoutSubviews () { view.Frame = new CGRect(Frame.Location.X,0,Frame.Size.Width,Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X,0,Frame.Size.Width,Frame.Size.Height);; markerView.Frame = new CGRect(Frame.Location.X+3,Frame.Size.Height-10,Frame.Size.Width-6,30); label.Frame=new CGRect(0,0,Frame.Size.Width,40); SetNeedsDisplay (); } protected override void Dispose(bool disposing) { isDisposed = true; base.Dispose(disposing); } public DataMarkers () { view = new UIView (); busyindicator = new SfBusyIndicator(); busyindicator.ViewBoxWidth=75; busyindicator.ViewBoxHeight=75; busyindicator.Foreground= UIColor.FromRGB (0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType=SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; view.AddSubview (busyindicator); NSTimer.CreateScheduledTimer (TimeSpan.FromSeconds (0.3), delegate { if (isDisposed) return; maps.Frame = new CGRect(Frame.Location.X,60,Frame.Size.Width-6,Frame.Size.Height-60); view.AddSubview (maps); }); view.Frame=new CGRect(0,0,300,400); markerView = new UIView (); label = new UILabel (); label.TextAlignment = UITextAlignment.Center; label.Text = "Top Population Countries"; label.Font = UIFont.SystemFontOfSize (18); label.Frame=new CGRect(0,0,300,40); label.TextColor = UIColor.Black; view.AddSubview (label); maps =new SFMap (); SFShapeFileLayer layer = new SFShapeFileLayer (); layer.Uri = (NSString)NSBundle.MainBundle.PathForResource ("world1", "shp"); PopulationMarker usa= new PopulationMarker(); usa.Latitude =38.8833; usa.Name ="United States"; usa.Longitude=-77.0167; usa.Population ="321,174,000"; layer.Markers.Add(usa); PopulationMarker brazil= new PopulationMarker(); brazil.Latitude=-15.7833; brazil.Longitude=-47.8667; brazil.Name ="Brazil"; brazil.Population= "204,436,000"; layer.Markers.Add(brazil); PopulationMarker india= new PopulationMarker(); india.Latitude=21.0000; india.Longitude=78.0000; india.Name ="India"; india.Population ="1,272,470,000"; layer.Markers.Add(india); PopulationMarker china= new PopulationMarker(); china.Latitude=35.0000; china.Longitude=103.0000; china.Name ="China"; china.Population = "1,370,320,000"; layer.Markers.Add(china); PopulationMarker indonesia= new PopulationMarker(); indonesia.Latitude=-6.1750; indonesia.Longitude=106.8283; indonesia.Name ="Indonesia"; indonesia.Population="255,461,700"; layer.Markers.Add(indonesia); maps.Delegate = new MapsDelegate (this); maps.Layers.Add (layer); AddSubview (view); } public void displayToastWithMessage(NSString toastMessage,NSString typeLabel) { UIWindow keyWindow = UIApplication.SharedApplication.KeyWindow; if(toastView!=null) { toastView.RemoveFromSuperview(); } toastView = new UIView (); UILabel label1 = new UILabel (); UILabel label2=new UILabel (); label1.TextColor = label2.TextColor = UIColor.White; label1.Font = UIFont.SystemFontOfSize (16); label1.Text= toastMessage; label2.Text = typeLabel; label2.Font =UIFont.SystemFontOfSize (12); label1.TextAlignment = label2.TextAlignment = UITextAlignment.Center;; toastView.AddSubview (label1); toastView.AddSubview (label2); toastView.Alpha =1; toastView.BackgroundColor = UIColor.Black.ColorWithAlpha (0.7f); toastView.Layer.CornerRadius = 10; CGSize expectedLabelSize1= toastMessage.GetSizeUsingAttributes (new UIStringAttributes() { Font = label1.Font }); CGSize expectedLabelSize2= typeLabel.GetSizeUsingAttributes (new UIStringAttributes() { Font = label2.Font }); keyWindow.AddSubview(toastView); toastView.Frame = new CGRect(0.0f, 0.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width)+20, 45.0f); label1.Frame = new CGRect(0.0f, 5.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width)+15, 15.0f); label2.Frame = new CGRect(0.0f, 25.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width)+15, 15.0f); toastView.Center = markerView.Center; UIView.Animate (4, 0, UIViewAnimationOptions.CurveEaseInOut, () => { toastView.Alpha= 0.7f; }, () => { toastView.RemoveFromSuperview(); } ); } } public class MapsDelegate:SFMapsDelegate { public MapsDelegate(DataMarkers markers) { mar= markers; } DataMarkers mar; public override void DidLoad (SFMap map) { if (mar.busyindicator != null) { mar.busyindicator.RemoveFromSuperview (); mar.busyindicator = null; } } public override void OnMarkerSelected(SFMap map, MarkerSelectedEventArgs markerSelectedEventArgs) { PopulationMarker Populationmarker = (PopulationMarker)markerSelectedEventArgs.SelectedMarker; mar.displayToastWithMessage((NSString)(Populationmarker.Name + "\n"), (NSString)Populationmarker.Population); } } public class PopulationMarker : SFMapMarker { public PopulationMarker () { } public string Population; public string Name; public override UIView GetView (CGPoint point) { UIImageView image= new UIImageView (new CGRect (point.X - 8, point.Y - 25, 15, 23)); image.Image = new UIImage ("pin.png"); return image; } public override CGPoint GetPoint () { return new CGPoint (-8, -25); } } } <file_sep>/iOS/SampleBrowser/Samples/Schedule/Configuration/Configuration.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; using Syncfusion.SfRangeSlider.iOS; using System.Collections.ObjectModel; using Foundation; using UIKit; using CoreGraphics; namespace SampleBrowser { public class Configuration : SampleView { private static SFSchedule schedule = new SFSchedule(); private ScheduleConfigurationViewModel viewModel = new ScheduleConfigurationViewModel(); private string selectedType; private UILabel labelScheduleView, labelWorkingHours, labelWeekNumber, labelShowNonAccess, labelBlackOutDays; private SfRangeSlider rangeslider; private UIButton buttonScheduleView = new UIButton(); private UIButton doneButton = new UIButton(); private UIPickerView pickerScheduleView; private UISwitch switchWeekNumber, switchNonAccessbleBlock, switchBlackOutDates; private DayViewSettings daySettings; private WeekViewSettings weekSettings; private WorkWeekViewSettings workWeekSettings; private MonthViewSettings monthSettings; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Configuration() { schedule = new SFSchedule(); schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; //Initializing configuration controls pickerScheduleView = new UIPickerView(); rangeslider = new SfRangeSlider(); labelScheduleView = new UILabel(); buttonScheduleView = new UIButton(); labelWorkingHours = new UILabel(); labelWeekNumber = new UILabel(); labelShowNonAccess = new UILabel(); labelBlackOutDays = new UILabel(); switchBlackOutDates = new UISwitch(); switchNonAccessbleBlock = new UISwitch(); switchWeekNumber = new UISwitch(); switchNonAccessbleBlock.On = true; switchBlackOutDates.On = true; switchWeekNumber.On = true; SetNonWorkingHours(); SetMonthSettings(); schedule.ItemsSource = viewModel.CreateAppointments(); this.AddSubview(schedule); this.OptionView = new UIView(); } protected override void Dispose(bool disposing) { if (disposing) { if (schedule != null) { schedule.Dispose(); schedule = null; } if (OptionView != null) { this.OptionView.RemoveFromSuperview(); this.OptionView.Dispose(); this.OptionView = null; } if (buttonScheduleView != null) { buttonScheduleView.TouchUpInside -= ShowPicker1; buttonScheduleView.Dispose(); buttonScheduleView = null; } if (doneButton != null) { doneButton.TouchUpInside -= HidePicker; doneButton.Dispose(); doneButton = null; } if (rangeslider != null) { rangeslider.RangeValueChange -= Slider_RangeValueChange; rangeslider.Dispose(); rangeslider = null; } if (daySettings != null) { daySettings.Dispose(); daySettings = null; } if (labelBlackOutDays != null) { labelBlackOutDays.Dispose(); labelBlackOutDays = null; } if (labelScheduleView != null) { labelScheduleView.Dispose(); labelScheduleView = null; } if (labelShowNonAccess != null) { labelShowNonAccess.Dispose(); labelShowNonAccess = null; } if (labelWeekNumber != null) { labelWeekNumber.Dispose(); labelWeekNumber = null; } if (labelWorkingHours != null) { labelWorkingHours.Dispose(); labelWorkingHours = null; } if (monthSettings != null) { monthSettings.Dispose(); monthSettings = null; } if (pickerScheduleView != null) { pickerScheduleView.Dispose(); pickerScheduleView = null; } if (switchBlackOutDates != null) { switchBlackOutDates.Dispose(); switchBlackOutDates = null; } if (switchNonAccessbleBlock != null) { switchNonAccessbleBlock.Dispose(); switchNonAccessbleBlock = null; } if (switchWeekNumber != null) { switchWeekNumber.Dispose(); switchWeekNumber = null; } if (weekSettings != null) { weekSettings.Dispose(); weekSettings = null; } if (workWeekSettings != null) { workWeekSettings.Dispose(); workWeekSettings = null; } } base.Dispose(disposing); } private void SetNonWorkingHours() { daySettings = new DayViewSettings(); weekSettings = new WeekViewSettings(); workWeekSettings = new WorkWeekViewSettings(); //Non-AccessbleBlocks NonAccessibleBlock lunch_hour = new NonAccessibleBlock(); lunch_hour.StartHour = 13; lunch_hour.EndHour = 14; lunch_hour.Text = (NSString)"LUNCH"; daySettings.NonAccessibleBlockCollection = new NSMutableArray(); weekSettings.NonAccessibleBlockCollection = new NSMutableArray(); workWeekSettings.NonAccessibleBlockCollection = new NSMutableArray(); if (switchNonAccessbleBlock != null && switchNonAccessbleBlock.On) { daySettings.NonAccessibleBlockCollection.Add(lunch_hour); weekSettings.NonAccessibleBlockCollection.Add(lunch_hour); workWeekSettings.NonAccessibleBlockCollection.Add(lunch_hour); } schedule.DayViewSettings = daySettings; schedule.WeekViewSettings = weekSettings; schedule.WorkWeekViewSettings = workWeekSettings; } private void SetMonthSettings() { monthSettings = new MonthViewSettings(); NSDate today = new NSDate(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second schedule.MonthViewSettings = monthSettings; monthSettings.BlackoutDates = new NSMutableArray(); if (switchBlackOutDates != null && switchBlackOutDates.On) { components.Day -= 3; for (int i = 0; i < 3; i++) { NSDate startDate = calendar.DateFromComponents(components); components.Day += 1; schedule.MonthViewSettings.BlackoutDates.Add(startDate); } } if (switchWeekNumber != null && switchWeekNumber.On) { schedule.MonthViewSettings.ShowWeekNumber = true; } else { schedule.MonthViewSettings.ShowWeekNumber = false; } } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } this.CreateOptionView(); base.LayoutSubviews(); } private readonly IList<string> scheduleViewsCollection = new List<string> { "DayView", "WeekView", "WorkWeekView", "MonthView" }; private void Slider_RangeValueChange(object sender, RangeEventArgs e) { schedule.DayViewSettings.WorkStartHour = (int)e.RangeStart; schedule.DayViewSettings.WorkEndHour = (int)e.RangeEnd; schedule.WeekViewSettings.WorkStartHour = (int)e.RangeStart; schedule.WeekViewSettings.WorkEndHour = (int)e.RangeEnd; schedule.WorkWeekViewSettings.WorkStartHour = (int)e.RangeStart; schedule.WorkWeekViewSettings.WorkEndHour = (int)e.RangeEnd; } private void CreateOptionView() { //Schedule View Localization.SchedulePickerModel model = new Localization.SchedulePickerModel(scheduleViewsCollection); pickerScheduleView.Model = model; labelScheduleView.Text = "Select the Schedule Type"; labelScheduleView.TextColor = UIColor.Black; labelScheduleView.TextAlignment = UITextAlignment.Left; buttonScheduleView.SetTitle("WeekView", UIControlState.Normal); buttonScheduleView.SetTitleColor(UIColor.Black, UIControlState.Normal); buttonScheduleView.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; buttonScheduleView.Layer.CornerRadius = 8; buttonScheduleView.Layer.BorderWidth = 2; buttonScheduleView.TouchUpInside += ShowPicker1; buttonScheduleView.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(246, 246, 246); model.PickerChanged += Model_PickerChanged; pickerScheduleView.ShowSelectionIndicator = true; pickerScheduleView.Hidden = true; //working Hours labelWorkingHours.Text = "Working Hours "; labelWorkingHours.TextColor = UIColor.Black; labelWorkingHours.TextAlignment = UITextAlignment.Left; rangeslider.Maximum = 24; rangeslider.Minimum = 0; rangeslider.RangeStart = (nfloat)schedule.WeekViewSettings.WorkStartHour; rangeslider.RangeEnd = (nfloat)schedule.WeekViewSettings.WorkEndHour; rangeslider.ShowRange = true; rangeslider.ShowValueLabel = false; rangeslider.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeslider.TickPlacement = SFTickPlacement.SFTickPlacementNone; rangeslider.LabelColor = UIColor.Gray; rangeslider.TickFrequency = 2; rangeslider.ToolTipPlacement = SFToolTipPlacement.SFToolTipPlacementTopLeft; rangeslider.KnobColor = UIColor.White; rangeslider.RangeValueChange += Slider_RangeValueChange; // show week number labelWeekNumber.Text = "Show Week number "; labelWeekNumber.TextColor = UIColor.Black; labelWeekNumber.TextAlignment = UITextAlignment.Left; switchWeekNumber.ValueChanged += (object sender, EventArgs e) => { SetMonthSettings(); }; //show non acceesible block labelShowNonAccess.Text = "Show Non AccessibleBlocks "; labelShowNonAccess.TextColor = UIColor.Black; labelShowNonAccess.TextAlignment = UITextAlignment.Left; switchNonAccessbleBlock.ValueChanged += (object sender, EventArgs e) => { SetNonWorkingHours(); }; //show black out dates labelBlackOutDays.Text = "Show Blackout dates "; labelBlackOutDays.TextColor = UIColor.Black; labelBlackOutDays.TextAlignment = UITextAlignment.Left; switchBlackOutDates.On = true; switchBlackOutDates.ValueChanged += (object sender, EventArgs e) => { SetMonthSettings(); }; string deviceType = UIDevice.CurrentDevice.Model; if (deviceType == "iPhone" || deviceType == "iPod touch") { labelWorkingHours.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y - 70, this.Frame.Size.Width - 20, 30); rangeslider.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y - 40, this.Frame.Size.Width - 20, 30); switchWeekNumber.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y, this.Frame.Size.Width / 9, 30); labelWeekNumber.Frame = new CGRect((this.Frame.Size.Width / 9) + 30, this.Frame.Y, this.Frame.Size.Width - 20, 30); //switch_weekNumber switchNonAccessbleBlock.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 40, this.Frame.Size.Width / 9, 30); labelShowNonAccess.Frame = new CGRect((this.Frame.Size.Width / 9) + 30, this.Frame.Y + 40, this.Frame.Size.Width - 20, 30); //switch_nonAccessbleBlock switchBlackOutDates.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 80, this.Frame.Size.Width / 9, 30); labelBlackOutDays.Frame = new CGRect((this.Frame.Size.Width / 9) + 30, this.Frame.Y + 80, this.Frame.Size.Width - 20, 30); //label_blackOutDays labelScheduleView.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 120, this.Frame.Size.Width - 20, 30); buttonScheduleView.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 150, this.Frame.Size.Width - 20, 30); doneButton.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, this.Frame.Size.Width - 20, 30); pickerScheduleView.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 170, this.Frame.Size.Width - 20, 150); } else { schedule.DayViewSettings.WorkStartHour = 7; schedule.DayViewSettings.WorkEndHour = 18; schedule.WeekViewSettings.WorkStartHour = 7; schedule.WeekViewSettings.WorkEndHour = 18; schedule.WorkWeekViewSettings.WorkStartHour = 7; schedule.WorkWeekViewSettings.WorkEndHour = 18; labelWorkingHours.Frame = new CGRect(10, 10, 320, 20); rangeslider.Frame = new CGRect(0, 30, 320, 30); switchWeekNumber.Frame = new CGRect(10, 60, 30, 30); labelWeekNumber.Frame = new CGRect(80, 60, 320, 30); //switch_weekNumber switchNonAccessbleBlock.Frame = new CGRect(10, 100, 30, 30); labelShowNonAccess.Frame = new CGRect(80, 100, 320, 30); //switch_nonAccessbleBlock switchBlackOutDates.Frame = new CGRect(10, 140, 30, 30); labelBlackOutDays.Frame = new CGRect(80, 140, 320, 30); //label_blackOutDays labelScheduleView.Frame = new CGRect(10, 180, 320, 20); buttonScheduleView.Frame = new CGRect(0, 210, 320, 30); doneButton.Frame = new CGRect(0, 250, 320, 30); pickerScheduleView.Frame = new CGRect(0, 270, 320, 100); } this.OptionView.AddSubview(labelWorkingHours); this.OptionView.AddSubview(rangeslider); this.OptionView.AddSubview(labelWeekNumber); this.OptionView.AddSubview(switchWeekNumber); this.OptionView.AddSubview(labelShowNonAccess); this.OptionView.AddSubview(switchNonAccessbleBlock); this.OptionView.AddSubview(labelBlackOutDays); this.OptionView.AddSubview(switchBlackOutDates); this.OptionView.AddSubview(labelScheduleView); this.OptionView.AddSubview(buttonScheduleView); this.OptionView.AddSubview(pickerScheduleView); this.OptionView.AddSubview(doneButton); } private void Model_PickerChanged(object sender, Localization.SchedulePickerChangedEventArgs e) { this.selectedType = e.SelectedValue; if (selectedType == "WeekView") { schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; } else if (selectedType == "DayView") { schedule.ScheduleView = SFScheduleView.SFScheduleViewDay; } else if (selectedType == "WorkWeekView") { schedule.ScheduleView = SFScheduleView.SFScheduleViewWorkWeek; } else { schedule.ScheduleView = SFScheduleView.SFScheduleViewMonth; } buttonScheduleView.SetTitle(selectedType.ToString(), UIControlState.Normal); } private void ShowPicker1(object sender, EventArgs e) { doneButton.Hidden = false; pickerScheduleView.Hidden = false; buttonScheduleView.Hidden = false; labelScheduleView.Hidden = false; labelWorkingHours.Hidden = false; } private void HidePicker(object sender, EventArgs e) { doneButton.Hidden = true; pickerScheduleView.Hidden = true; buttonScheduleView.Hidden = false; labelScheduleView.Hidden = false; labelWorkingHours.Hidden = false; } } } <file_sep>/Forms/PdfViewer/PdfViewer/Samples/PDFViewerCustomToolbar/PDFViewerCustomToolbar_Tablet.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfPdfViewer.XForms; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.IO; using Syncfusion.SfRangeSlider.XForms; using Syncfusion.Pdf.Parsing; using System.Collections.ObjectModel; using popuplayout = Syncfusion.XForms.PopupLayout; namespace SampleBrowser.SfPdfViewer { [Preserve(AllMembers = true)] public partial class PDFViewerCustomToolbar_Tablet : SampleView { bool m_isPageInitiated = false; bool isAnnotationEditMode = false; string selectedText = ""; internal Grid parentGrid; ShapeAnnotation selectedShapeAnnotation; FreeTextAnnotation selectedFreeTextAnnotation; StampAnnotation selectedStampAnnotation; TextMarkupAnnotation selectedAnnotation; InkAnnotation selectedInkAnnotation; HandwrittenSignature selectedSignatureAnnotation; PopupAnnotation selectedPopupAnnotation; private float m_backUpVerticalOffset = 0; private float m_backUpHorizontalOffset = 0; private float m_backUpZoomFactor = 0; string currentDocument = "F# Succinctly"; private bool m_canRestoreBackup = false; bool canSetValueToSource = true; internal PdfLoadedDocument bookmarkLoadedDocument; internal IList<ContentBookmark> listViewItemsSource = new ObservableCollection<ContentBookmark>(); internal BookmarkToolbar bookmarkToolbar; internal EditBookmarkPopup editBookmarkPopup; internal Syncfusion.SfPdfViewer.XForms.SfPdfViewer pdfViewer; StampAnnotationView stampView; private bool isDocumentLoaded = false; public PDFViewerCustomToolbar_Tablet() { InitializeComponent(); pdfViewer = pdfViewerControl; string filePath = string.Empty; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif pdfViewerControl.PasswordErrorOccurred += PdfViewerControl_PasswordErrorOccurred; pdfViewerControl.UnhandledConditionOccurred += PdfViewerControl_UnhandledConditionOccurred; var m_pdfDocumentStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath + "Assets." + "F# Succinctly" + ".pdf"); pdfViewerControl.LoadDocument(m_pdfDocumentStream); parentGrid = mainGrid; if (Application.Current.MainPage != null) { toolbar.WidthRequest = Application.Current.MainPage.Width; searchBar.WidthRequest = Application.Current.MainPage.Width; } if (Device.RuntimePlatform == Device.UWP) arrowButton.IsVisible = false; textSearchEntry.TextChanged += TextSearchEntry_TextChanged; pdfViewerControl.TextMatchFound += PdfViewerControl_TextMatchFound; pdfViewerControl.CanUndoModified += PdfViewerControl_CanUndoModified; pdfViewerControl.CanRedoModified += PdfViewerControl_CanRedoModified; pdfViewerControl.CanUndoInkModified += PdfViewerControl_CanUndoInkModified; pdfViewerControl.CanRedoInkModified += PdfViewerControl_CanRedoInkModified; pdfViewerControl.DocumentLoaded += PdfViewerControl_DocumentLoaded; pdfViewerControl.SearchCompleted+= PdfViewerControl_SearchCompleted; TextSelectionMenuItem item = new TextSelectionMenuItem(); item.Text = "Search in browser"; item.Id = "find"; pdfViewerControl.TextSelectionSettings.MenuOptions.Items.Add(item); pdfViewerControl.TextSelectionCompleted += PdfViewerControl_TextSelectionCompleted; ; pdfViewerControl.TextSelectionSettings.MenuOptions.TextSelectionMenuItemClicked += MenuOptions_TextSelectionMenuItemClicked; pdfViewerControl.IsToolbarVisible = false; pdfViewerControl.IsPasswordViewEnabled = false; pdfViewerControl.Tapped += PdfViewerControl_Tapped; pdfViewerControl.PageChanged += PdfViewerControl_PageChanged; pdfViewerControl.ShapeAnnotationSelected += PdfViewerControl_ShapeAnnotationSelected; pdfViewerControl.FreeTextAnnotationSelected += PdfViewerControl_FreeTextAnnotationSelected; pdfViewerControl.ShapeAnnotationDeselected += PdfViewerControl_ShapeAnnotationDeselected; pdfViewerControl.FreeTextAnnotationDeselected += PdfViewerControl_FreeTextAnnotationDeselected; pdfViewerControl.FreeTextPopupAppearing += PdfViewerControl_FreeTextPopupAppearing; pdfViewerControl.FreeTextPopupDisappeared += PdfViewerControl_FreeTextPopupDisappeared; pdfViewerControl.PopupAnnotationSelected += PdfViewerControl_PopupAnnotationSelected; pdfViewerControl.PopupAnnotationDeselected += PdfViewerControl_PopupAnnotationDeselected; pdfViewerControl.PopupAnnotationViewAppearing += PdfViewerControl_PopupAnnotationViewAppearing; pdfViewerControl.PopupAnnotationViewDisappeared += PdfViewerControl_PopupAnnotationViewDisappeared; (BindingContext as PdfViewerViewModel).HighlightColor = pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color; (BindingContext as PdfViewerViewModel).UnderlineColor = pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color; (BindingContext as PdfViewerViewModel).StrikeThroughColor = pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color; (BindingContext as PdfViewerViewModel).SquigglyColor = pdfViewerControl.AnnotationSettings.TextMarkup.Squiggly.Color; (BindingContext as PdfViewerViewModel).InkColor = pdfViewerControl.AnnotationSettings.Ink.Color; (BindingContext as PdfViewerViewModel).EditTextColor = pdfViewerControl.AnnotationSettings.FreeText.TextColor; (BindingContext as PdfViewerViewModel).RectangleStrokeColor = pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor; (BindingContext as PdfViewerViewModel).LineStrokeColor = pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor; (BindingContext as PdfViewerViewModel).CircleStrokeColor = pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor; (BindingContext as PdfViewerViewModel).ArrowStrokeColor = pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor; (BindingContext as PdfViewerViewModel).OpacityButtonColor = pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor; (BindingContext as PdfViewerViewModel).PolygonStrokeColor = pdfViewerControl.AnnotationSettings.Polygon.Settings.StrokeColor; (BindingContext as PdfViewerViewModel).CloudStrokeColor = pdfViewerControl.AnnotationSettings.Polygon.Settings.StrokeColor; (BindingContext as PdfViewerViewModel).PolylineStrokeColor = pdfViewerControl.AnnotationSettings.Polyline.Settings.StrokeColor; (BindingContext as PdfViewerViewModel).PopupColor = pdfViewerControl.AnnotationSettings.Popup.Color; (BindingContext as PdfViewerViewModel).PopupIcon = pdfViewerControl.AnnotationSettings.Popup.Icon; cancelSearchButton.Clicked += CancelSearchButton_Clicked; TapGestureRecognizer bookmarkLayoutTapGesture = new TapGestureRecognizer(); TapGestureRecognizer printLayoutTapGesture = new TapGestureRecognizer(); bookmarkLayout.GestureRecognizers.Add(bookmarkLayoutTapGesture); PrintLayout.GestureRecognizers.Add(printLayoutTapGesture); bookmarkLayoutTapGesture.Tapped += bookmarkButton_Clicked; printLayoutTapGesture.Tapped += PrintButtonClicked; m_isPageInitiated = true; pageNumberEntry.PdfViewer = pdfViewerControl; pageNumberEntry.IsPageNumberEntry = true; pageNumberEntry.Completed += PageNumberEntry_Completed; slider.Value = pdfViewerControl.AnnotationSettings.Ink.Thickness; opacitySlider.Value = pdfViewerControl.AnnotationSettings.Ink.Opacity * 100; slider.ValueChanged += Slider_ValueChanged; fontSizeSlider.ShowValueLabel = false; fontSizeSlider.Minimum = 6; fontSizeSlider.Maximum = 22; fontSizeSlider.Value = 12; fontSizeSlider.KnobColor = (Device.RuntimePlatform == Device.iOS) ? Color.White : Color.Blue; fontSizeSlider.TrackSelectionColor = Color.Blue; fontSizeSlider.TrackColor = Color.Gray; fontSizeSlider.TickFrequency = 2; fontSizeSlider.StepFrequency = 2; fontSizeSlider.ShowRange = false; fontSizeSlider.Orientation = Syncfusion.SfRangeSlider.XForms.Orientation.Horizontal; fontSizeSlider.TickPlacement = TickPlacement.Inline; fontSizeSlider.ToolTipPlacement = ToolTipPlacement.None; eraserThicknessSlider.ValueChanging += EraserThicknessSlider_ValueChanging; eraserThicknessSlider.Minimum = 5; eraserThicknessSlider.Maximum = 150; eraserThicknessSlider.Value = 40; eraserThicknessSlider.KnobColor = (Device.RuntimePlatform == Device.iOS) ? Color.White : Color.Blue; eraserThicknessSlider.TrackSelectionColor = Color.Blue; eraserThicknessSlider.TrackColor = Color.Gray; eraserThicknessSlider.TickFrequency = 10; eraserThicknessSlider.StepFrequency = 1; eraserThicknessSlider.ShowRange = false; eraserThicknessSlider.Orientation = Syncfusion.SfRangeSlider.XForms.Orientation.Horizontal; eraserThicknessSlider.TickPlacement = TickPlacement.Inline; eraserThicknessSlider.ToolTipPlacement = ToolTipPlacement.None; eraserThicknessSlider.Value = pdfViewerControl.AnnotationSettings.InkEraser.Thickness; opacitySlider.ValueChanged += OpacitySlider_ValueChanged; fontSizeSlider.Value = pdfViewerControl.AnnotationSettings.FreeText.TextSize; fontSizeSlider.ValueChanging += FontSizeSlider_ValueChanging; fontSizeSlider.Value = pdfViewerControl.AnnotationSettings.FreeText.TextSize; fontSizeSliderValue.Text = pdfViewerControl.AnnotationSettings.FreeText.TextSize.ToString(); bookmarkToolbar = new BookmarkToolbar(this); editBookmarkPopup = new EditBookmarkPopup(this); bookmarkToolbar.WidthRequest = 0; Grid.SetColumn(bookmarkToolbar, 1); pdfViewerGrid.Children.Add(bookmarkToolbar); signatureButton.FontFamily = FontMappingHelper.SignatureFont; signatureButton.Text = FontMappingHelper.Signature; stampView = new StampAnnotationView(pdfViewer); InitializePasswordDialog(); } private void EraserThicknessSlider_ValueChanging(object sender, ValueEventArgs e) { if (canSetValueToSource) { if (pdfViewerControl.AnnotationMode == AnnotationMode.InkEraser) pdfViewerControl.AnnotationSettings.InkEraser.Thickness = (int)(e.Value); } eraserThicknessSliderValue.Text = ((Int32)e.Value).ToString(); canSetValueToSource = true; } private void PdfViewerControl_PopupAnnotationDeselected(object sender, EventArgs e) { isAnnotationEditMode = false; (BindingContext as PdfViewerViewModel).IsEditPopupAnnotationBarVisible = false; canSetValueToSource = false; selectedPopupAnnotation = null; } private void PdfViewerControl_PopupAnnotationSelected(object sender, EventArgs e) { selectedPopupAnnotation = sender as PopupAnnotation; isAnnotationEditMode = true; (BindingContext as PdfViewerViewModel).PopupDeleteColor = new Color(selectedPopupAnnotation.Settings.Color.R, selectedPopupAnnotation.Settings.Color.G, selectedPopupAnnotation.Settings.Color.B); (BindingContext as PdfViewerViewModel).EditPopupIcon = selectedPopupAnnotation.Settings.Icon; opacitySlider.Value = selectedPopupAnnotation.Settings.Opacity * 100; (BindingContext as PdfViewerViewModel).IsEditPopupAnnotationBarVisible = true; (BindingContext as PdfViewerViewModel).IsMainAnnotationBarVisible = false; canSetValueToSource = true; } private void PdfViewerControl_PopupAnnotationViewDisappeared(object sender, PopupAnnotationViewDisappearedEventArgs e) { (BindingContext as PdfViewerViewModel).IsOpacityBarVisible = false; (BindingContext as PdfViewerViewModel).IsShapeColorBarVisible = false; (BindingContext as PdfViewerViewModel).IsPopupIconSelectorBarVisible = false; if ((BindingContext as PdfViewerViewModel).IsPopupBarVisible) (BindingContext as PdfViewerViewModel).IsPopupBarVisible = false; if (selectedPopupAnnotation != null && !(BindingContext as PdfViewerViewModel).IsEditPopupAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditPopupAnnotationBarVisible = true; } private void PdfViewerControl_PopupAnnotationViewAppearing(object sender, EventArgs e) { (BindingContext as PdfViewerViewModel).IsOpacityBarVisible = false; (BindingContext as PdfViewerViewModel).IsShapeColorBarVisible = false; (BindingContext as PdfViewerViewModel).IsPopupIconSelectorBarVisible = false; if ((BindingContext as PdfViewerViewModel).IsPopupBarVisible) (BindingContext as PdfViewerViewModel).IsPopupBarVisible = false; if ((BindingContext as PdfViewerViewModel).IsEditPopupAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditPopupAnnotationBarVisible = false; } private void EditPopupTextButton_Clicked(object sender, EventArgs e) { pdfViewerControl.EditPopupAnnotationText(); } private void MenuOptions_TextSelectionMenuItemClicked(object sender, EventArgs e) { if ((sender as TextSelectionMenuItem).Id == "find") { DependencyService.Get<IDeviceOpenURI>().OpenURI(this.selectedText); } } private void PdfViewerControl_TextSelectionCompleted(object sender, TextSelectionCompletedEventArgs args) { this.selectedText = args.SelectedText; } private void PdfViewerControl_PageChanged(object sender, PageChangedEventArgs args) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsPickerVisible = false; if(BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; foreach (var item in pdfViewer.CustomBookmarks) { if (item.PageNumber == args.NewPageNumber) { bookmarkToolbar.AddBookmarkButton.IsEnabled = false; break; } else { bookmarkToolbar.AddBookmarkButton.IsEnabled = true; } } } private void PdfViewerControl_Tapped(object sender, TouchInteractionEventArgs e) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsPickerVisible = false; if(BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; } popuplayout.SfPopupLayout popup; int i = 0; private Button okButton = new Button(); private Entry passwordEntry = new Entry(); private Label errorContent = new Label(); void InitializePasswordDialog() { #region Password Protected popup = new popuplayout.SfPopupLayout(); popup.PopupView.ShowFooter = true; popup.StaysOpen = true; popup.PopupView.MinimumWidthRequest = 100; popup.PopupView.MinimumHeightRequest = 100; popup.PopupView.HeightRequest = 210; popup.PopupView.WidthRequest = 330; popup.Closing += Popup_Closing; if (Device.RuntimePlatform == Device.iOS) { popup.PopupView.ShowCloseButton = false; popup.PopupView.HeightRequest = 220; } if (Device.RuntimePlatform != Device.iOS) popup.PopupView.HeightRequest = 200; popup.Closed += Popup_Closed; #region HeaderTemplate popup.PopupView.HeaderTemplate = new DataTemplate(() => { StackLayout layout = new StackLayout() { Padding = new Thickness(20, 15, 0, 0), BackgroundColor = Color.White, HeightRequest = 20 }; Label headerLabel = new Label() { Text = "Password Protected", FontSize = 20, TextColor = Color.Black, FontFamily = "Roboto-Medium", HeightRequest = 24, }; if (Device.RuntimePlatform == Device.iOS) headerLabel.HorizontalOptions = LayoutOptions.Center; layout.Children.Add(headerLabel); return layout; } ); #endregion #region ContentTemplate popup.PopupView.ContentTemplate = new DataTemplate(() => { StackLayout contentLayout = new StackLayout() { BackgroundColor = Color.Transparent, Padding = new Thickness(20, 10, 20, 0), Spacing = 5 }; Label bodyContent = new Label() { BackgroundColor = Color.Transparent, Text = "Enter the password to open this PDF File.", TextColor = Color.Black, FontSize = 15, FontFamily = "Roboto-Regular" }; if (Device.RuntimePlatform == Device.iOS) { passwordEntry.MinimumHeightRequest = 40; passwordEntry.HeightRequest = 40; passwordEntry.Margin = new Thickness(0,10,0,0); } passwordEntry.BackgroundColor = Color.Transparent; passwordEntry.Text = ""; passwordEntry.Placeholder = "Password: <PASSWORD>"; passwordEntry.TextColor = Color.Black; passwordEntry.FontSize = 15; passwordEntry.FontFamily = "Roboto-Regular"; passwordEntry.IsPassword = true; passwordEntry.TextChanged += PasswordEntry_TextChanged; passwordEntry.Completed+= OkButton_Clicked; Label errorContentInstance = new Label() { BackgroundColor = Color.Transparent, Text = "Invalid Password!", TextColor = Color.Red, FontSize = 15, FontFamily = "Roboto-Regular", IsVisible = false }; if (Device.RuntimePlatform == Device.Android) { errorContentInstance.Margin = new Thickness(0, -15, 0, 0); passwordEntry.Margin = new Thickness(-3, 10, 0, 0); } this.errorContent = errorContentInstance; contentLayout.Children.Add(bodyContent); contentLayout.Children.Add(passwordEntry); contentLayout.Children.Add(this.errorContent); return contentLayout; }); #endregion #region FooterTemplate popup.PopupView.FooterTemplate = new DataTemplate(() => { StackLayout layout = new StackLayout() { Orientation = StackOrientation.Horizontal, Spacing = 10 }; if (Device.RuntimePlatform != Device.iOS) layout.Padding = new Thickness(170, 10, 0, 10); layout.BackgroundColor = Color.Transparent; Button cancelButton = new Button() { Text = "Cancel", FontSize = 15, TextColor = Color.Black, FontFamily = "Roboto-Medium", BackgroundColor = Color.Transparent, MinimumWidthRequest = 75, WidthRequest = 75, }; cancelButton.Clicked += CancelButton_Clicked; okButton.Text = "Ok"; okButton.FontSize = 15; //okButton.Margin = new Thickness(20,0,0,0); okButton.TextColor = Color.FromRgba(2, 119, 255, 38); okButton.FontFamily = "Roboto-Medium"; okButton.Clicked += OkButton_Clicked; okButton.IsEnabled = false; okButton.TextColor = Color.FromRgb(176, 176, 176); okButton.BackgroundColor = Color.Transparent; okButton.WidthRequest = 75; okButton.MinimumWidthRequest = 75; if (Device.RuntimePlatform == Device.iOS) okButton.HorizontalOptions = LayoutOptions.FillAndExpand; if (Device.RuntimePlatform == Device.iOS) cancelButton.HorizontalOptions = LayoutOptions.FillAndExpand; if (Device.Idiom == TargetIdiom.Tablet && Device.RuntimePlatform == Device.Android) { layout.Padding = new Thickness(160, 5, 0, 0); layout.Spacing = 0; cancelButton.WidthRequest = 85; okButton.HeightRequest = layout.Height - 10; cancelButton.HeightRequest = layout.Height - 10; //okButton.ContentLayout = .Center; } layout.Children.Add(cancelButton); layout.Children.Add(okButton); return layout; } ); #endregion #endregion } private void Popup_Closing(object sender, Syncfusion.XForms.Core.CancelEventArgs e) { okButton.Clicked -= OkButton_Clicked; passwordEntry.Completed -= OkButton_Clicked; } private void PasswordEntry_TextChanged(object sender, TextChangedEventArgs e) { if (e.NewTextValue == "") { if (okButton != null) { okButton.IsEnabled = false; okButton.TextColor = Color.FromRgba(2, 119, 255, 38); } } else { okButton.IsEnabled = true; okButton.TextColor = Color.FromRgb(2, 119, 255); } } private void OkButton_Clicked(object sender, EventArgs e) { passwordEntry.Unfocus(); if (isDocumentLoaded) return; var filePath = string.Empty; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif pdfViewer.Unload(); var fileStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath + "Assets." + currentDocument + ".pdf"); fileStream.Position = 0; pdfViewer.LoadDocument(fileStream, passwordEntry.Text); } internal void ToggleBookmarkPopup() { Grid.SetRow(editBookmarkPopup, 0); Grid.SetColumn(editBookmarkPopup, 0); Grid.SetRowSpan(editBookmarkPopup, 2); mainGrid.Children.Add(editBookmarkPopup); } internal void PositionToastMessage() { Grid.SetRow(bookmarkToolbar.toastMessageFrame, 0); Grid.SetRowSpan(bookmarkToolbar.toastMessageFrame, 2); Grid.SetColumn(bookmarkToolbar.toastMessageFrame, 0); mainGrid.Children.Add(bookmarkToolbar.toastMessageFrame); } private void CancelButton_Clicked(object sender, EventArgs e) { passwordEntry.Unfocus(); popup.Dismiss(); i = 0; passwordEntry.Text = ""; DisableAllButtons(); pdfViewer.Unload(); } private void Popup_Closed(object sender, EventArgs e) { if (isDocumentLoaded) { EnableAllButtons(); } else { DisableAllButtons(); pdfViewerControl.Unload(); } } private void PdfViewerControl_PasswordErrorOccurred(object sender, PasswordErrorOccurredEventArgs e) { if (e.Title == "Error loading encrypted PDF document") { if (i == 0) { errorContent.IsVisible = false; popup.Show(); i++; isDocumentLoaded = false; } else { errorContent.IsVisible = true; } passwordEntry.Text = ""; passwordEntry.Focus(); } } private void PdfViewerControl_UnhandledConditionOccurred(object sender, UnhandledConditionEventArgs args) { DependencyService.Get<IAlertView>().Show(args.Description); } void DisableAllButtons() { saveButton.IsEnabled = false; bookmarkButton.IsEnabled = false; pageNumberEntry.IsEnabled = false; annotationButton.IsEnabled = false; searchButton.IsEnabled = false; viewModeButton.IsEnabled = false; pageCountLabel.IsEnabled = false; pageDivSeparator.IsEnabled = false; moreOptionsButton.IsEnabled = false; pageCountLabel.TextColor = Color.FromRgb(176,176,176); pageDivSeparator.TextColor = Color.FromRgb(176,176,176); } void EnableAllButtons() { saveButton.IsEnabled = true; bookmarkButton.IsEnabled = true; pageNumberEntry.IsEnabled = true; annotationButton.IsEnabled = true; searchButton.IsEnabled = true; viewModeButton.IsEnabled = true; pageCountLabel.IsEnabled = true; pageDivSeparator.IsEnabled = true; moreOptionsButton.IsEnabled = true; pageCountLabel.TextColor = Color.FromRgb(2,119,255); pageDivSeparator.TextColor = Color.FromRgb(2, 119, 255); } private void PdfViewerControl_FreeTextPopupDisappeared(object sender, FreeTextPopupDisappearedEventArgs args) { (BindingContext as PdfViewerViewModel).IsOpacityBarVisible = false; (BindingContext as PdfViewerViewModel).IsFontSizeSliderBarVisible = false; (BindingContext as PdfViewerViewModel).IsColorBarVisible = false; if ((BindingContext as PdfViewerViewModel).IsEditTextAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditTextAnnotationBarVisible = true; if ((BindingContext as PdfViewerViewModel).IsEditFreeTextAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditFreeTextAnnotationBarVisible = true; } private void AnnotationButtonClicked(object sender, EventArgs args) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; pdfViewerControl.SelectionMode = Syncfusion.SfPdfViewer.XForms.SelectionMode.None; editBookmarkPopup.IsVisible = false; CollapseBookmarkPane(); } private void PdfViewerControl_FreeTextPopupAppearing(object sender, FreeTextPopupAppearingEventArgs args) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; (BindingContext as PdfViewerViewModel).IsOpacityBarVisible = false; (BindingContext as PdfViewerViewModel).IsFontSizeSliderBarVisible = false; (BindingContext as PdfViewerViewModel).IsColorBarVisible = false; if ((BindingContext as PdfViewerViewModel).IsEditTextAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditTextAnnotationBarVisible = false; if ((BindingContext as PdfViewerViewModel).IsEditFreeTextAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditFreeTextAnnotationBarVisible = false; } private void PdfViewerControl_FreeTextAnnotationDeselected(object sender, FreeTextAnnotationDeselectedEventArgs args) { selectedFreeTextAnnotation = null; isAnnotationEditMode = false; canSetValueToSource = false; fontSizeSlider.Value = pdfViewerControl.AnnotationSettings.FreeText.TextSize; fontSizeSliderValue.Text = pdfViewerControl.AnnotationSettings.FreeText.TextSize.ToString(); } private void FontSizeSlider_ValueChanging(object sender, Syncfusion.SfRangeSlider.XForms.ValueEventArgs e) { if (canSetValueToSource) { if (selectedFreeTextAnnotation != null) selectedFreeTextAnnotation.Settings.TextSize = (int)(e.Value); else if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) pdfViewerControl.AnnotationSettings.FreeText.TextSize = (int)(e.Value); } fontSizeSliderValue.Text = ((Int32)e.Value).ToString(); canSetValueToSource = true; } private void PdfViewerControl_ShapeAnnotationDeselected(object sender, ShapeAnnotationDeselectedEventArgs args) { isAnnotationEditMode = false; canSetValueToSource = false; if ((BindingContext as PdfViewerViewModel).IsEditRectangleAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditRectangleAnnotationBarVisible = false; else if ((BindingContext as PdfViewerViewModel).IsEditCircleAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditCircleAnnotationBarVisible = false; else if ((BindingContext as PdfViewerViewModel).IsEditLineAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditLineAnnotationBarVisible = false; else if ((BindingContext as PdfViewerViewModel).IsEditArrowAnnotationBarVisible) (BindingContext as PdfViewerViewModel).IsEditArrowAnnotationBarVisible = false; AnnotationMode annotationMode = args.AnnotationType; selectedShapeAnnotation = null; } private void PdfViewerControl_DocumentLoaded(object sender, EventArgs args) { i = 0; EnableAllButtons(); if (popup != null) popup.Dismiss(); if (errorContent != null) errorContent.IsVisible = false; string filePath = string.Empty; if (Device.RuntimePlatform == Device.Android) { if (m_canRestoreBackup) { pdfViewerControl.ZoomPercentage = m_backUpZoomFactor; pdfViewerControl.VerticalOffset = m_backUpVerticalOffset; pdfViewerControl.HorizontalOffset = m_backUpHorizontalOffset; m_canRestoreBackup = false; } } #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif if ((this.BindingContext as PdfViewerViewModel) != null && (this.BindingContext as PdfViewerViewModel).SelectedItem != null) { if ((this.BindingContext as PdfViewerViewModel).SelectedItem.FileName != currentDocument) currentDocument = (this.BindingContext as PdfViewerViewModel).SelectedItem.FileName; } Stream stream = (typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath + "Assets." + currentDocument + ".pdf")); if (passwordEntry != null && passwordEntry.Text != null && passwordEntry.Text != string.Empty) bookmarkLoadedDocument = new PdfLoadedDocument(stream, passwordEntry.Text); else bookmarkLoadedDocument = new PdfLoadedDocument(stream); bookmarkToolbar.bookmarkLoadedDocument = bookmarkLoadedDocument; //Once the PDF is loaded populate the bookmark listview with the bookmarks of the PDF bookmarkToolbar.PopulateInitialBookmarkList(); isDocumentLoaded = true; } internal void RefreshPageAfterSleep(bool isPageSwitched) { string filePath = string.Empty; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif m_canRestoreBackup = !isPageSwitched; if (!isPageSwitched) { Stream stream = (typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath + "Assets." + currentDocument + ".pdf")); bookmarkLoadedDocument = new PdfLoadedDocument(stream); (BindingContext as PdfViewerViewModel).PdfDocumentStream = stream; if (bookmarkToolbar != null) { bookmarkToolbar.bookmarkLoadedDocument = bookmarkLoadedDocument; //Once the PDF is loaded populate the bookmark listview with the bookmarks of the PDF bookmarkToolbar.PopulateInitialBookmarkList(); } } } internal void CollectGC() { m_backUpHorizontalOffset = pdfViewerControl.HorizontalOffset; m_backUpVerticalOffset = pdfViewerControl.VerticalOffset; m_backUpZoomFactor = pdfViewerControl.ZoomPercentage; pdfViewerControl.Unload(); GC.Collect(); GC.WaitForPendingFinalizers(); } private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e) { isDocumentLoaded = false; currentDocument = (e.SelectedItem as Document).FileName; string filePath = string.Empty; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif pdfViewerControl.Unload(); var pdfDocumentStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath + "Assets." + currentDocument + ".pdf"); pdfViewerControl.LoadDocument(pdfDocumentStream); if (Device.RuntimePlatform == Device.Android) { GC.Collect(); GC.WaitForPendingFinalizers(); } //When a new PDF is opened collapse the bookmark toolbar CollapseBookmarkPane(); } //Collapses the bookmark toolbar internal void CollapseBookmarkPane() { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; bookmarkToolbar.WidthRequest = 0; bookmarkToolbar.isBookmarkPaneVisible = false; } private void PdfViewerControl_InkDeselected(object sender, InkDeselectedEventArgs args) { isAnnotationEditMode = false; canSetValueToSource = false; selectedInkAnnotation = null; selectedSignatureAnnotation = null; } private void PdfViewerControl_InkSelected(object sender, InkSelectedEventArgs args) { if (sender is InkAnnotation) { selectedInkAnnotation = sender as InkAnnotation; isAnnotationEditMode = true; (BindingContext as PdfViewerViewModel).InkDeleteColor = new Color(selectedInkAnnotation.Settings.Color.R, selectedInkAnnotation.Settings.Color.G, selectedInkAnnotation.Settings.Color.B); opacitySlider.Value = selectedInkAnnotation.Settings.Opacity * 100; canSetValueToSource = true; } else { selectedSignatureAnnotation = sender as HandwrittenSignature; isAnnotationEditMode = true; (BindingContext as PdfViewerViewModel).InkDeleteColor = new Color(selectedSignatureAnnotation.Settings.Color.R, selectedSignatureAnnotation.Settings.Color.G, selectedSignatureAnnotation.Settings.Color.B); opacitySlider.Value = selectedSignatureAnnotation.Settings.Opacity * 100; canSetValueToSource = true; } } private void PdfViewerControl_CanRedoInkModified(object sender, CanRedoInkModifiedEventArgs args) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; if (args.CanRedoInk) { if (Device.RuntimePlatform != Device.UWP) inkRedoBtn.TextColor = Color.FromHex("#0076FF"); else { Device.BeginInvokeOnMainThread(() => { inkRedoBtn.TextColor = Color.FromHex("#0076FF"); }); } } else inkRedoBtn.TextColor = Color.DarkGray; } private void PdfViewerControl_CanUndoInkModified(object sender, CanUndoInkModifiedEventArgs args) { if (args.CanUndoInk) { if (Device.RuntimePlatform != Device.UWP) inkUndoBtn.TextColor = Color.FromHex("#0076FF"); else { Device.BeginInvokeOnMainThread(() => { inkUndoBtn.TextColor = Color.FromHex("#0076FF"); }); } } else inkUndoBtn.TextColor = Color.DarkGray; } private void OpacitySlider_ValueChanged(object sender, ValueChangedEventArgs e) { if (canSetValueToSource) { if (selectedInkAnnotation != null) selectedInkAnnotation.Settings.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (selectedSignatureAnnotation != null) selectedSignatureAnnotation.Settings.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (selectedShapeAnnotation != null) selectedShapeAnnotation.Settings.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Opacity = (float)(e.NewValue / 100); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) pdfViewerControl.AnnotationSettings.Polygon.Settings.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) pdfViewerControl.AnnotationSettings.Polyline.Settings.Opacity = (float)(Math.Round(e.NewValue, 0) / 100); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Popup) pdfViewerControl.AnnotationSettings.Popup.Opacity = (float)(e.NewValue / 100); } opacityValue.Text = ((int)Math.Round(e.NewValue, 0)).ToString() + "%"; canSetValueToSource = true; } private void Slider_ValueChanged(object sender, ValueChangedEventArgs e) { if (canSetValueToSource) { if (selectedInkAnnotation != null) selectedInkAnnotation.Settings.Thickness = (float)e.NewValue; else if (selectedSignatureAnnotation != null) selectedSignatureAnnotation.Settings.Thickness = (float)e.NewValue; if (selectedShapeAnnotation != null) selectedShapeAnnotation.Settings.Thickness = (int)e.NewValue; else if (selectedFreeTextAnnotation != null) selectedFreeTextAnnotation.Settings.TextSize = (int)(e.NewValue); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Thickness = (float)e.NewValue; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.Thickness = (int)(e.NewValue); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.Thickness = (int)(e.NewValue); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.Thickness =(int)(e.NewValue); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.Thickness = (int)(e.NewValue); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) pdfViewerControl.AnnotationSettings.Polygon.Settings.Thickness = (int)Math.Round(e.NewValue, 0); else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) pdfViewerControl.AnnotationSettings.Polyline.Settings.Thickness = (int)Math.Round(e.NewValue, 0); } sliderValue.Text = ((Int32)e.NewValue).ToString(); canSetValueToSource = true; } private void PageNumberEntry_Completed(object sender, EventArgs e) { int pageNumber = 0; int.TryParse((sender as CustomEntry).Text, out pageNumber); if(pageNumber>pdfViewerControl.PageCount||pageNumber<0) { DependencyService.Get<IAlertView>().Show("Please enter a valid page number."); pageNumberEntry.Text = pdfViewerControl.PageNumber.ToString(); } else if (pageNumber != 0) pdfViewerControl.GoToPage(pageNumber); } private void PdfViewerControl_SearchCompleted(object sender, TextSearchCompletedEventArgs args) { if (args.NoMatchFound) { DependencyService.Get<IAlertView>().Show("\"" + args.TargetText + "\"" + " not found."); searchNextButton.IsVisible = false; searchPreviousButton.IsVisible = false; } else if (args.NoMoreOccurrence) DependencyService.Get<IAlertView>().Show("No more matches were found."); } private void PdfViewerControl_CanRedoModified(object sender, CanRedoModifiedEventArgs args) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; if (args.CanRedo) redoButton.TextColor = Color.FromHex("#0076FF"); else redoButton.TextColor = Color.DarkGray; } private void PdfViewerControl_CanUndoModified(object sender, CanUndoModifiedEventArgs args) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; if (args.CanUndo) undoButton.TextColor = Color.FromHex("#0076FF"); else undoButton.TextColor = Color.DarkGray; } private void PdfViewerControl_TextMarkupSelected(object sender, TextMarkupSelectedEventArgs args) { selectedAnnotation = sender as TextMarkupAnnotation; isAnnotationEditMode = true; (BindingContext as PdfViewerViewModel).DeleteButtonColor = new Color(selectedAnnotation.Settings.Color.R, selectedAnnotation.Settings.Color.G, selectedAnnotation.Settings.Color.B); } private void PdfViewerControl_TextMarkupDeselected(object sender, TextMarkupDeselectedEventArgs args) { selectedAnnotation = null; isAnnotationEditMode = false; } private void InkBackButton_Clicked(object sender, EventArgs e) { pdfViewerControl.EndInkSession(false); pdfViewerControl.AnnotationMode = AnnotationMode.None; pdfViewerControl.SelectionMode = Syncfusion.SfPdfViewer.XForms.SelectionMode.None; } private void DeleteButton_Clicked(object sender, EventArgs e) { if (selectedAnnotation != null) { pdfViewerControl.RemoveAnnotation(selectedAnnotation); selectedAnnotation = null; isAnnotationEditMode = false; } else if (selectedStampAnnotation != null) { pdfViewerControl.RemoveAnnotation(selectedStampAnnotation); selectedStampAnnotation = null; isAnnotationEditMode = false; } } private void InkDeleteButton_Clicked(object sender, EventArgs e) { if (selectedInkAnnotation != null) { pdfViewerControl.RemoveAnnotation(selectedInkAnnotation); selectedInkAnnotation = null; isAnnotationEditMode = false; } if(selectedSignatureAnnotation != null) { pdfViewerControl.RemoveAnnotation(selectedSignatureAnnotation); selectedSignatureAnnotation = null; isAnnotationEditMode = false; } } private void ShapeDeleteButton_Clicked(object sender, EventArgs e) { if (selectedShapeAnnotation != null) { pdfViewerControl.RemoveAnnotation(selectedShapeAnnotation); selectedShapeAnnotation = null; isAnnotationEditMode = false; } } private void PopupDeleteButton_Clicked(object sender, EventArgs e) { if (selectedPopupAnnotation != null) { pdfViewerControl.RemoveAnnotation(selectedPopupAnnotation); selectedPopupAnnotation = null; isAnnotationEditMode = false; } } private void EditTextDeleteButton_Clicked(object sender, EventArgs e) { if (selectedFreeTextAnnotation != null) { pdfViewerControl.RemoveAnnotation(selectedFreeTextAnnotation); selectedFreeTextAnnotation = null; isAnnotationEditMode = false; } } private void InkButton_Clicked(object sender, EventArgs e) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; pdfViewerControl.AnnotationMode = AnnotationMode.Ink; } private void EndSession_Clicked(object sender, EventArgs e) { pdfViewerControl.EndInkSession(true); } private void CancelSearchButton_Clicked(object sender, EventArgs e) { textSearchEntry.Text = string.Empty; } private void PolygonBackButton_Clicked(object sender, EventArgs e) { pdfViewerControl.AnnotationMode = AnnotationMode.None; pdfViewerControl.SelectionMode = Syncfusion.SfPdfViewer.XForms.SelectionMode.None; } private void CloudBackButton_Clicked(object sender, EventArgs e) { pdfViewerControl.AnnotationMode = AnnotationMode.None; pdfViewerControl.SelectionMode = Syncfusion.SfPdfViewer.XForms.SelectionMode.None; } private void PolylineBackButton_Clicked(object sender, EventArgs e) { pdfViewerControl.AnnotationMode = AnnotationMode.None; pdfViewerControl.SelectionMode = Syncfusion.SfPdfViewer.XForms.SelectionMode.None; } private void PopupBackButton_Clicked(object sender, EventArgs e) { pdfViewerControl.AnnotationMode = AnnotationMode.None; pdfViewerControl.SelectionMode = Syncfusion.SfPdfViewer.XForms.SelectionMode.None; } private void SaveButton_Clicked(object sender, EventArgs e) { string filePath = DependencyService.Get<ISave>().Save(pdfViewerControl.SaveDocument() as MemoryStream); string message = "The PDF has been saved to " + filePath; DependencyService.Get<IAlertView>().Show(message); if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; } void PdfViewerControl_TextMatchFound(object sender, TextMatchFoundEventArgs args) { searchNextButton.IsVisible = true; searchPreviousButton.IsVisible = true; } //private void PdfViewerControl_UnhandledCondition(object sender, UnhandledConditionEventArgs args) //{ // DependencyService.Get<IAlertView>().Show(args.Description); //} private void TextSearchEntry_TextChanged(object sender, TextChangedEventArgs e) { if ((sender as Entry).Text == string.Empty) { pdfViewerControl.CancelSearch(); searchNextButton.IsVisible = false; searchPreviousButton.IsVisible = false; cancelSearchButton.IsVisible = false; } else cancelSearchButton.IsVisible = true; } private void OnSearchClicked(object sender, EventArgs e) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; textSearchEntry.Focus(); pdfViewerControl.AnnotationMode = AnnotationMode.None; pdfViewerControl.SelectionMode = Syncfusion.SfPdfViewer.XForms.SelectionMode.None; CollapseBookmarkPane(); } private void OnCancelClicked(object sender, EventArgs e) { textSearchEntry.Text = string.Empty; textSearchEntry.Focus(); } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Application.Current.MainPage != null && Application.Current.MainPage.Width > 0 && m_isPageInitiated) { toolbar.WidthRequest = Application.Current.MainPage.Width; searchBar.WidthRequest = Application.Current.MainPage.Width; } } private void ShapeAnnotationColorButton_Clicked(object sender, EventArgs e) { if(selectedInkAnnotation!=null) (BindingContext as PdfViewerViewModel).OpacityButtonColor = selectedInkAnnotation.Settings.Color; else if (selectedSignatureAnnotation != null) (BindingContext as PdfViewerViewModel).OpacityButtonColor = selectedSignatureAnnotation.Settings.Color; if (selectedShapeAnnotation != null) (BindingContext as PdfViewerViewModel).OpacityButtonColor = selectedShapeAnnotation.Settings.StrokeColor; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) (BindingContext as PdfViewerViewModel).OpacityButtonColor = pdfViewerControl.AnnotationSettings.Ink.Color; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) (BindingContext as PdfViewerViewModel).OpacityButtonColor = pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) (BindingContext as PdfViewerViewModel).OpacityButtonColor = pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) (BindingContext as PdfViewerViewModel).OpacityButtonColor = pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) (BindingContext as PdfViewerViewModel).OpacityButtonColor = pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) (BindingContext as PdfViewerViewModel).OpacityButtonColor = pdfViewerControl.AnnotationSettings.Polygon.Settings.StrokeColor; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) (BindingContext as PdfViewerViewModel).OpacityButtonColor = pdfViewerControl.AnnotationSettings.Polyline.Settings.StrokeColor; } private void ColorButton_Clicked(object sender, EventArgs e) { switch ((sender as Button).CommandParameter.ToString()) { case "Cyan": { if (!isAnnotationEditMode) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Squiggly) pdfViewerControl.AnnotationSettings.TextMarkup.Squiggly.Color = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Color = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) pdfViewerControl.AnnotationSettings.FreeText.TextColor = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) pdfViewerControl.AnnotationSettings.Polygon.Settings.StrokeColor = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) pdfViewerControl.AnnotationSettings.Polyline.Settings.StrokeColor = Color.FromHex("#00FFFF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Popup) pdfViewerControl.AnnotationSettings.Popup.Color = Color.FromHex("#00FFFF"); (BindingContext as PdfViewerViewModel).OpacityButtonColor = Color.FromHex("#00FFFF"); } else { if (selectedAnnotation != null) selectedAnnotation.Settings.Color = Color.FromHex("#00FFFF"); if (selectedInkAnnotation != null) selectedInkAnnotation.Settings.Color = Color.FromHex("#00FFFF"); if (selectedSignatureAnnotation != null) selectedSignatureAnnotation.Settings.Color = Color.FromHex("#00FFFF"); if (selectedFreeTextAnnotation != null) selectedFreeTextAnnotation.Settings.TextColor = Color.FromHex("#00FFFF"); if (selectedShapeAnnotation != null) selectedShapeAnnotation.Settings.StrokeColor = Color.FromHex("#00FFFF"); if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Color = Color.FromHex("#00FFFF"); } } break; case "Green": { if (!isAnnotationEditMode) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Squiggly) pdfViewerControl.AnnotationSettings.TextMarkup.Squiggly.Color = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Color = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) pdfViewerControl.AnnotationSettings.FreeText.TextColor = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) pdfViewerControl.AnnotationSettings.Polygon.Settings.StrokeColor = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) pdfViewerControl.AnnotationSettings.Polyline.Settings.StrokeColor = Color.Green; if (pdfViewerControl.AnnotationMode == AnnotationMode.Popup) pdfViewerControl.AnnotationSettings.Popup.Color = Color.Green; (BindingContext as PdfViewerViewModel).OpacityButtonColor = Color.Green; } else { if (selectedAnnotation != null) selectedAnnotation.Settings.Color = Color.Green; if (selectedInkAnnotation != null) selectedInkAnnotation.Settings.Color = Color.Green; if (selectedSignatureAnnotation != null) selectedSignatureAnnotation.Settings.Color = Color.Green; if (selectedFreeTextAnnotation != null) selectedFreeTextAnnotation.Settings.TextColor = Color.Green; if (selectedShapeAnnotation != null) selectedShapeAnnotation.Settings.StrokeColor = Color.Green; if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Color = Color.Green; } } break; case "Yellow": { if (!isAnnotationEditMode) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Squiggly) pdfViewerControl.AnnotationSettings.TextMarkup.Squiggly.Color = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Color = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) pdfViewerControl.AnnotationSettings.FreeText.TextColor = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) pdfViewerControl.AnnotationSettings.Polygon.Settings.StrokeColor = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) pdfViewerControl.AnnotationSettings.Polyline.Settings.StrokeColor = Color.Yellow; if (pdfViewerControl.AnnotationMode == AnnotationMode.Popup) pdfViewerControl.AnnotationSettings.Popup.Color = Color.Yellow; (BindingContext as PdfViewerViewModel).OpacityButtonColor = Color.Yellow; } else { if (selectedAnnotation != null) selectedAnnotation.Settings.Color = Color.Yellow; if (selectedInkAnnotation != null) selectedInkAnnotation.Settings.Color = Color.Yellow; if (selectedSignatureAnnotation != null) selectedSignatureAnnotation.Settings.Color = Color.Yellow; if (selectedFreeTextAnnotation != null) selectedFreeTextAnnotation.Settings.TextColor = Color.Yellow; if (selectedShapeAnnotation != null) selectedShapeAnnotation.Settings.StrokeColor = Color.Yellow; if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Color = Color.Yellow; } } break; case "Magenta": { if (!isAnnotationEditMode) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Squiggly) pdfViewerControl.AnnotationSettings.TextMarkup.Squiggly.Color = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Color = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) pdfViewerControl.AnnotationSettings.FreeText.TextColor = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) pdfViewerControl.AnnotationSettings.Polygon.Settings.StrokeColor = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) pdfViewerControl.AnnotationSettings.Polyline.Settings.StrokeColor = Color.FromHex("#FF00FF"); if (pdfViewerControl.AnnotationMode == AnnotationMode.Popup) pdfViewerControl.AnnotationSettings.Popup.Color = Color.FromHex("#FF00FF"); (BindingContext as PdfViewerViewModel).OpacityButtonColor = Color.FromHex("#FF00FF"); } else { if (selectedAnnotation != null) selectedAnnotation.Settings.Color = Color.FromHex("#FF00FF"); if (selectedInkAnnotation != null) selectedInkAnnotation.Settings.Color = Color.FromHex("#FF00FF"); if (selectedSignatureAnnotation != null) selectedSignatureAnnotation.Settings.Color = Color.FromHex("#FF00FF"); if (selectedFreeTextAnnotation != null) selectedFreeTextAnnotation.Settings.TextColor = Color.FromHex("#FF00FF"); if (selectedShapeAnnotation != null) selectedShapeAnnotation.Settings.StrokeColor = Color.FromHex("#FF00FF"); if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Color = Color.FromHex("FF00FF"); } } break; case "Black": { if (!isAnnotationEditMode) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Squiggly) pdfViewerControl.AnnotationSettings.TextMarkup.Squiggly.Color = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Color = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) pdfViewerControl.AnnotationSettings.FreeText.TextColor = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) pdfViewerControl.AnnotationSettings.Polygon.Settings.StrokeColor = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) pdfViewerControl.AnnotationSettings.Polyline.Settings.StrokeColor = Color.Black; if (pdfViewerControl.AnnotationMode == AnnotationMode.Popup) pdfViewerControl.AnnotationSettings.Popup.Color = Color.Black; (BindingContext as PdfViewerViewModel).OpacityButtonColor = Color.Black; } else { if (selectedAnnotation != null) selectedAnnotation.Settings.Color = Color.Black; if (selectedInkAnnotation != null) selectedInkAnnotation.Settings.Color = Color.Black; if (selectedSignatureAnnotation != null) selectedSignatureAnnotation.Settings.Color = Color.Black; if (selectedFreeTextAnnotation != null) selectedFreeTextAnnotation.Settings.TextColor = Color.Black; if (selectedShapeAnnotation != null) selectedShapeAnnotation.Settings.StrokeColor = Color.Black; if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Color = Color.Black; } } break; case "White": { if (!isAnnotationEditMode) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Underline) pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Squiggly) pdfViewerControl.AnnotationSettings.TextMarkup.Squiggly.Color = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) pdfViewerControl.AnnotationSettings.Ink.Color = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) pdfViewerControl.AnnotationSettings.FreeText.TextColor = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) pdfViewerControl.AnnotationSettings.Polygon.Settings.StrokeColor = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) pdfViewerControl.AnnotationSettings.Polyline.Settings.StrokeColor = Color.White; if (pdfViewerControl.AnnotationMode == AnnotationMode.Popup) pdfViewerControl.AnnotationSettings.Popup.Color = Color.White; (BindingContext as PdfViewerViewModel).OpacityButtonColor = Color.White; } else { if (selectedAnnotation != null) selectedAnnotation.Settings.Color = Color.White; if (selectedInkAnnotation != null) selectedInkAnnotation.Settings.Color = Color.White; if (selectedSignatureAnnotation != null) selectedSignatureAnnotation.Settings.Color = Color.White; if (selectedFreeTextAnnotation != null) selectedFreeTextAnnotation.Settings.TextColor = Color.White; if (selectedShapeAnnotation != null) selectedShapeAnnotation.Settings.StrokeColor = Color.White; if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Color = Color.White; } } break; } } private void PdfViewerControl_FreeTextAnnotationSelected(object sender, FreeTextAnnotationSelectedEventArgs args) { selectedFreeTextAnnotation = sender as FreeTextAnnotation; isAnnotationEditMode = true; (BindingContext as PdfViewerViewModel).EditTextDeleteColor = new Color(selectedFreeTextAnnotation.Settings.TextColor.R, selectedFreeTextAnnotation.Settings.TextColor.G, selectedFreeTextAnnotation.Settings.TextColor.B); fontSizeSlider.Value = selectedFreeTextAnnotation.Settings.TextSize; fontSizeSliderValue.Text = selectedFreeTextAnnotation.Settings.TextSize.ToString(); canSetValueToSource = true; } private void EditTextButton_Clicked(object sender, EventArgs e) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; pdfViewerControl.EditFreeTextAnnotation(); } private void OpacityButton_Clicked(object sender, EventArgs e) { if (selectedInkAnnotation != null) opacitySlider.Value = selectedInkAnnotation.Settings.Opacity * 100; else if (selectedSignatureAnnotation != null) opacitySlider.Value = selectedSignatureAnnotation.Settings.Opacity * 100; else if (selectedShapeAnnotation != null) opacitySlider.Value = selectedShapeAnnotation.Settings.Opacity * 100; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) opacitySlider.Value = pdfViewerControl.AnnotationSettings.Ink.Opacity * 100; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) opacitySlider.Value = pdfViewerControl.AnnotationSettings.Rectangle.Settings.Opacity * 100; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) opacitySlider.Value = pdfViewerControl.AnnotationSettings.Circle.Settings.Opacity * 100; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) opacitySlider.Value = pdfViewerControl.AnnotationSettings.Line.Settings.Opacity * 100; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) opacitySlider.Value = pdfViewerControl.AnnotationSettings.Arrow.Settings.Opacity * 100; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) opacitySlider.Value = pdfViewerControl.AnnotationSettings.Polygon.Settings.Opacity * 100; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) opacitySlider.Value = pdfViewerControl.AnnotationSettings.Polyline.Settings.Opacity * 100; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Popup) opacitySlider.Value = pdfViewerControl.AnnotationSettings.Popup.Opacity * 100; } private void ThicknessButton_Clicked(object sender, EventArgs e) { if (selectedInkAnnotation != null && selectedInkAnnotation.Settings.Thickness <= 10) slider.Value = selectedInkAnnotation.Settings.Thickness; else if (selectedSignatureAnnotation != null && selectedSignatureAnnotation.Settings.Thickness <= 10) slider.Value = selectedSignatureAnnotation.Settings.Thickness; else if (selectedShapeAnnotation != null && selectedShapeAnnotation.Settings.Thickness <= 10) slider.Value = selectedShapeAnnotation.Settings.Thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) slider.Value = pdfViewerControl.AnnotationSettings.Ink.Thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) slider.Value = pdfViewerControl.AnnotationSettings.Rectangle.Settings.Thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Circle) slider.Value = pdfViewerControl.AnnotationSettings.Circle.Settings.Thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Line) slider.Value = pdfViewerControl.AnnotationSettings.Line.Settings.Thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) slider.Value = pdfViewerControl.AnnotationSettings.Arrow.Settings.Thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polygon) slider.Value = pdfViewerControl.AnnotationSettings.Polygon.Settings.Thickness; else if (pdfViewerControl.AnnotationMode == AnnotationMode.Polyline) slider.Value = pdfViewerControl.AnnotationSettings.Polyline.Settings.Thickness; } private void PdfViewerControl_ShapeAnnotationSelected(object sender, ShapeAnnotationSelectedEventArgs args) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; selectedShapeAnnotation = sender as ShapeAnnotation; isAnnotationEditMode = true; (BindingContext as PdfViewerViewModel).IsOpacityBarVisible = false; (BindingContext as PdfViewerViewModel).IsThicknessBarVisible = false; (BindingContext as PdfViewerViewModel).IsMainAnnotationBarVisible = false; (BindingContext as PdfViewerViewModel).IsShapeColorBarVisible = false; (BindingContext as PdfViewerViewModel).IsShapeAnnotationBarVisible = false; (BindingContext as PdfViewerViewModel).AnnotationGridHeightRequest = 50; if (args.AnnotationType == AnnotationMode.Rectangle) { (BindingContext as PdfViewerViewModel).RectangleDeleteColor = new Color(selectedShapeAnnotation.Settings.StrokeColor.R, selectedShapeAnnotation.Settings.StrokeColor.G, selectedShapeAnnotation.Settings.StrokeColor.B); (BindingContext as PdfViewerViewModel).IsEditRectangleAnnotationBarVisible = true; } else if (args.AnnotationType == AnnotationMode.Circle) { (BindingContext as PdfViewerViewModel).CircleDeleteColor = new Color(selectedShapeAnnotation.Settings.StrokeColor.R, selectedShapeAnnotation.Settings.StrokeColor.G, selectedShapeAnnotation.Settings.StrokeColor.B); (BindingContext as PdfViewerViewModel).IsEditCircleAnnotationBarVisible = true; } else if (args.AnnotationType == AnnotationMode.Line) { (BindingContext as PdfViewerViewModel).LineDeleteColor = new Color(selectedShapeAnnotation.Settings.StrokeColor.R, selectedShapeAnnotation.Settings.StrokeColor.G, selectedShapeAnnotation.Settings.StrokeColor.B); (BindingContext as PdfViewerViewModel).IsEditLineAnnotationBarVisible = true; } else if (args.AnnotationType == AnnotationMode.Arrow) { (BindingContext as PdfViewerViewModel).ArrowDeleteColor = new Color(selectedShapeAnnotation.Settings.StrokeColor.R, selectedShapeAnnotation.Settings.StrokeColor.G, selectedShapeAnnotation.Settings.StrokeColor.B); (BindingContext as PdfViewerViewModel).IsEditArrowAnnotationBarVisible = true; } else if (args.AnnotationType == AnnotationMode.Polygon) { if (selectedShapeAnnotation.Settings.BorderEffect == BorderEffect.Solid) { (BindingContext as PdfViewerViewModel).PolygonDeleteColor = new Color(selectedShapeAnnotation.Settings.StrokeColor.R, selectedShapeAnnotation.Settings.StrokeColor.G, selectedShapeAnnotation.Settings.StrokeColor.B); (BindingContext as PdfViewerViewModel).IsEditPolygonAnnotationBarVisible = true; } else { (BindingContext as PdfViewerViewModel).CloudDeleteColor = new Color(selectedShapeAnnotation.Settings.StrokeColor.R, selectedShapeAnnotation.Settings.StrokeColor.G, selectedShapeAnnotation.Settings.StrokeColor.B); (BindingContext as PdfViewerViewModel).IsEditCloudAnnotationBarVisible = true; } } else if (args.AnnotationType == AnnotationMode.Polyline) { (BindingContext as PdfViewerViewModel).PolylineDeleteColor = new Color(selectedShapeAnnotation.Settings.StrokeColor.R, selectedShapeAnnotation.Settings.StrokeColor.G, selectedShapeAnnotation.Settings.StrokeColor.B); (BindingContext as PdfViewerViewModel).IsEditPolylineAnnotationBarVisible = true; } opacitySlider.Value = selectedShapeAnnotation.Settings.Opacity * 100; canSetValueToSource = true; } private void ShapeButton_Clicked(object sender, EventArgs e) { } private void EditText_Clicked(object sender, EventArgs e) { pdfViewerControl.AnnotationMode = AnnotationMode.FreeText; if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; } //Handles the click event of the bookmark button private void bookmarkButton_Clicked(object sender, EventArgs e) { bookmarkToolbar.UpdateBookmarkContent(); bookmarkToolbar.UpdateCustomBookmarkView(); if (pdfViewer.CustomBookmarks.Count != 0) { foreach (var item in pdfViewer.CustomBookmarks) { if (item.PageNumber == pdfViewer.PageNumber) { bookmarkToolbar.AddBookmarkButton.IsEnabled = false; break; } else { bookmarkToolbar.AddBookmarkButton.IsEnabled = true; } } } else { bookmarkToolbar.AddBookmarkButton.IsEnabled = true; } //The bookmark toolbar will take 40% of the total width of the application double bookmarkToolbarWidth = 0.4 * mainGrid.Width; //Set the width of the bookmark toolbar based on the isBookmarkPaneVisible property bookmarkToolbar.WidthRequest = bookmarkToolbar.isBookmarkPaneVisible ? 0 : bookmarkToolbarWidth; bookmarkToolbar.isBookmarkPaneVisible = !bookmarkToolbar.isBookmarkPaneVisible; pdfViewerControl.AnnotationMode = AnnotationMode.None; if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; } private void signatureButton_Clicked(object sender, EventArgs e) { pdfViewer.AnnotationMode = AnnotationMode.HandwrittenSignature; if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; } private void StampButton_Clicked(object sender, EventArgs e) { mainGrid.Children.Add(stampView); if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; } private void PdfViewerControl_StampAnnotationSelected(object sender, StampAnnotationSelectedEventArgs args) { selectedStampAnnotation = sender as StampAnnotation; isAnnotationEditMode = true; if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; } private void PdfViewerControl_StampAnnotationDeselected(object sender, StampAnnotationDeselectedEventArgs args) { selectedStampAnnotation = null; isAnnotationEditMode = false; if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; } private void PrintButtonClicked(object sender, EventArgs e) { if (BindingContext is PdfViewerViewModel) (BindingContext as PdfViewerViewModel).IsMoreOptionsToolBarVisible = false; if (pdfViewerControl != null) pdfViewerControl.Print(); } private void polygonButton_Clicked(object sender, EventArgs e) { pdfViewerControl.AnnotationSettings.Polygon.Settings.BorderEffect = BorderEffect.Solid; } private void cloudButton_Clicked(object sender, EventArgs e) { pdfViewerControl.AnnotationSettings.Polygon.Settings.BorderEffect = BorderEffect.Cloudy; } private void Popup_Clicked(object sender, EventArgs e) { pdfViewerControl.AnnotationMode = AnnotationMode.Popup; } private void InkEraser_Clicked(object sender, EventArgs e) { pdfViewerControl.AnnotationMode = AnnotationMode.InkEraser; } private void IconButton_Clicked(object sender, EventArgs e) { switch ((sender as Button).CommandParameter.ToString()) { case "Comment": { if (!isAnnotationEditMode) pdfViewerControl.AnnotationSettings.Popup.Icon = PopupIcon.Comment; else if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Icon = PopupIcon.Comment; } break; case "Note": { if (!isAnnotationEditMode) pdfViewerControl.AnnotationSettings.Popup.Icon = PopupIcon.Note; else if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Icon = PopupIcon.Note; } break; case "Key": { if (!isAnnotationEditMode) pdfViewerControl.AnnotationSettings.Popup.Icon = PopupIcon.Key; else if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Icon = PopupIcon.Key; } break; case "Help": { if (!isAnnotationEditMode) pdfViewerControl.AnnotationSettings.Popup.Icon = PopupIcon.Help; else if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Icon = PopupIcon.Help; } break; case "Insert": { if (!isAnnotationEditMode) pdfViewerControl.AnnotationSettings.Popup.Icon = PopupIcon.Insert; else if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Icon = PopupIcon.Insert; } break; case "Paragraph": { if (!isAnnotationEditMode) pdfViewerControl.AnnotationSettings.Popup.Icon = PopupIcon.Paragraph; else if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Icon = PopupIcon.Paragraph; } break; case "NewParagraph": { if (!isAnnotationEditMode) pdfViewerControl.AnnotationSettings.Popup.Icon = PopupIcon.NewParagraph; else if (selectedPopupAnnotation != null) selectedPopupAnnotation.Settings.Icon = PopupIcon.NewParagraph; } break; } } } } <file_sep>/iOS/SampleBrowser/Samples/Chart/Numerical.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Drawing; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class NumericalAxis : SampleView { public NumericalAxis() { SFChart chart = new SFChart (); chart.Title.Text = (NSString) "England vs West Indies"; chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.PrimaryAxis = new SFCategoryAxis() { Interval = NSObject.FromObject(1), LabelPlacement = SFChartLabelPlacement.BetweenTicks, ShowMajorGridLines = false, PlotOffset = 2, AxisLineOffset = 2, }; chart.PrimaryAxis.Title.Text = (NSString) "Death Overs"; chart.SecondaryAxis = new SFNumericalAxis(); chart.SecondaryAxis.Minimum = new NSNumber(0); chart.SecondaryAxis.Maximum = new NSNumber(25); chart.SecondaryAxis.Interval = new NSNumber(5); chart.SecondaryAxis.AxisLineStyle.LineWidth = 0; chart.SecondaryAxis.MajorTickStyle.LineSize = 0; ChartViewModel dataModel = new ChartViewModel (); SFColumnSeries series = new SFColumnSeries(); series.ItemsSource = dataModel.NumericData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.EnableAnimation = true; series.Label = "England"; series.LegendIcon = SFChartLegendIcon.SeriesType; series.DataMarker.ShowLabel = true; series.DataMarker.LabelStyle.LabelPosition = SFChartDataMarkerLabelPosition.Inner; chart.Series.Add(series); SFColumnSeries series1 = new SFColumnSeries(); series1.ItemsSource = dataModel.NumericData1; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.EnableTooltip = true; series1.EnableAnimation = true; series1.Label = "West Indies"; series1.LegendIcon = SFChartLegendIcon.SeriesType; series1.DataMarker.ShowLabel = true; series1.DataMarker.LabelStyle.LabelPosition = SFChartDataMarkerLabelPosition.Inner; chart.Series.Add(series1); chart.Legend.Visible = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } }<file_sep>/Forms/Accordion/Accordion/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfAccordion { [Preserve(AllMembers = true)] public partial class Themes :SampleView { private InvoiceViewModel invoiceViewModel; public Themes() { InitializeComponent(); } public override void OnDisappearing() { base.OnDisappearing(); invoiceViewModel = this.BindingContext as InvoiceViewModel; invoiceViewModel.ItemInfo.Clear(); this.sfAccordion.Items.Clear(); if (this.sfAccordion != null) { this.sfAccordion.Dispose(); this.sfAccordion = null; } } } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/Helpers/CustomHeaderTemplate.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CustomHeaderTemplate.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System; using System.Diagnostics.CodeAnalysis; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; /// <summary> /// A class contains custom header template. /// </summary> public class CustomHeaderTemplate : Layout<View>, IDisposable { /// <summary> /// Gets or sets the NumberOfLabel /// </summary> public int NumberOfLabel { get; set; } /// <summary> /// Disposes all the objects in the view. /// </summary> public void Dispose() { this.Dispose(true); } /// <summary> /// Positions and sizes the children of a Layout. /// </summary> /// <param name="x">A value representing the x coordinate of the child region bounding box.</param> /// <param name="y">A value representing the y coordinate of the child region bounding box.</param> /// <param name="width">A value representing the width of the child region bounding box.</param> /// <param name="height">A value representing the height of the child region bounding box.</param> protected override void LayoutChildren(double x, double y, double width, double height) { } /// <summary> /// This method is called when the size of the element is set during a layout cycle. This method is called directly /// before the <see cref="Xamarin.Forms.VisualElement.SizeChanged"/> event is emitted. /// </summary> /// <param name="width">The new width of the element.</param> /// <param name="height">The new height of the element.</param> protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); double w = 0; for (var i = 0; i < this.NumberOfLabel; i++) { this.Children.Add(this.CreateDateLayout(i)); this.Children[i].Layout(new Rectangle(w, 0, width / this.NumberOfLabel, height)); w = w + (width / this.NumberOfLabel); } } /// <summary> /// Method to decide whether to call <see cref="Xamarin.Forms.VisualElement.InvalidateMeasure()"/> when adding a child. /// </summary> /// <param name="child">A child of the <see cref="SfDataGrid"/>.</param> /// <returns>A boolean value do decide whether to invalidate when adding a child.</returns> protected override bool ShouldInvalidateOnChildAdded(View child) { return false; } /// <summary> /// Disposes all the objects in the view /// </summary> /// <param name="isDisposing">Disposes the object based on the parameter.</param> protected void Dispose(bool isDisposing) { if (isDisposing) { foreach (var dateLayout in this.Children) { if (dateLayout.GestureRecognizers.Count > 0) { var tapGesture = dateLayout.GestureRecognizers[0] as TapGestureRecognizer; if (tapGesture != null) { tapGesture.Tapped -= this.DateLayout_Tapped; dateLayout.GestureRecognizers.Remove(tapGesture); tapGesture = null; } } } this.Children.Clear(); } } /// <summary> /// Used to Creates Date Layout /// </summary> /// <param name="i">integer type parameter named as i</param> /// <returns>returns the StackLayout value</returns> private View CreateDateLayout(int i) { StackLayout layout = new StackLayout(); layout.Padding = new Thickness(0, 0, 0, 10); layout.Orientation = StackOrientation.Vertical; layout.Children.Add(this.CreateDayLabel(i)); layout.Children.Add(this.CreateDateLabel(i)); this.SetBackgroundColorForLabels(i, layout); this.AddTapGesture(layout); return layout; } /// <summary> /// Adding TapGesture to StackLayout /// </summary> /// <param name="layout">StackLayout type parameter named as layout</param> private void AddTapGesture(StackLayout layout) { var tapGesture = new TapGestureRecognizer(); layout.GestureRecognizers.Add(tapGesture); tapGesture.Tapped += this.DateLayout_Tapped; } /// <summary> /// Triggers when DateLayout is tapped. /// </summary> /// <param name="sender">DateLayout_Tapped event sender</param> /// <param name="e">DateLayout_Tapped args e</param> private void DateLayout_Tapped(object sender, EventArgs e) { var stackLayout = sender as StackLayout; // Update background color for other date cells foreach (var children in (stackLayout.Parent as CustomHeaderTemplate).Children) { children.BackgroundColor = Color.White; ((children as StackLayout).Children[0] as Label).TextColor = Color.Gray; ((children as StackLayout).Children[1] as Label).TextColor = Color.Black; } // Update background color for selected date cell stackLayout.BackgroundColor = Color.FromHex("#007CEE"); (stackLayout.Children[0] as Label).TextColor = Color.White; (stackLayout.Children[1] as Label).TextColor = Color.White; stackLayout = null; } /// <summary> /// Used to Create Date Label. /// </summary> /// <param name="i">integer type parameter named as i</param> /// <returns>returns newly created label</returns> private View CreateDateLabel(int i) { Label dateLabel = new Label(); dateLabel.Opacity = 87; dateLabel.FontSize = 14; dateLabel.HorizontalOptions = LayoutOptions.CenterAndExpand; dateLabel.VerticalOptions = LayoutOptions.CenterAndExpand; dateLabel.VerticalTextAlignment = TextAlignment.End; dateLabel.HeightRequest = 31; dateLabel.FontAttributes = FontAttributes.Bold; dateLabel.Text = DateTime.Now.AddDays(i).Day.ToString(); return dateLabel; } /// <summary> /// Used to Create day Label. /// </summary> /// <param name="i">integer type parameter to add days</param> /// <returns>returns newly created label</returns> private Label CreateDayLabel(int i) { Label dayLabel = new Label(); dayLabel.TextColor = Color.White; dayLabel.Opacity = 54; dayLabel.FontSize = 12; dayLabel.HorizontalOptions = LayoutOptions.CenterAndExpand; dayLabel.VerticalOptions = LayoutOptions.EndAndExpand; dayLabel.VerticalTextAlignment = TextAlignment.End; dayLabel.HeightRequest = 31; dayLabel.Text = DateTime.Now.AddDays(i).DayOfWeek.ToString().Substring(0, 3).ToUpper(); return dayLabel; } /// <summary> /// Used to Set BackgroundColor For Labels /// </summary> /// <param name="i">integer typed parameter named as i</param> /// <param name="layout">returns the layout</param> private void SetBackgroundColorForLabels(int i, StackLayout layout) { if (i == 0) { layout.BackgroundColor = Color.FromRgb(0, 124, 238); layout.BackgroundColor = Color.FromRgb(0, 124, 238); (layout.Children[0] as Label).TextColor = Color.White; (layout.Children[1] as Label).TextColor = Color.White; } else { layout.BackgroundColor = Color.White; layout.BackgroundColor = Color.White; (layout.Children[0] as Label).TextColor = Color.Gray; (layout.Children[1] as Label).TextColor = Color.Black; } } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Swiping/SwipingBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SwipingBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Swiping samples /// </summary> public class SwipingBehaviors : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SwipingViewModel viewModel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Image leftImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Image rightImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int swipedRowIndex; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private FormsView formView; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private CustomLayout customLayout; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type parameter as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.customLayout = bindAble.FindByName<CustomLayout>("custumLayout"); this.dataGrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.rightImage = (Image)bindAble.Resources["rightImage"]; this.leftImage = (Image)bindAble.Resources["leftImage"]; this.viewModel = new SwipingViewModel(); bindAble.BindingContext = this.viewModel; this.dataGrid.ItemsSource = this.viewModel.OrdersInfo; bindAble.PropertyChanged += this.Swiping_PropertyChanged; this.formView = new FormsView(this.dataGrid); this.customLayout.Children.Add(this.formView); this.dataGrid.GridTapped += this.DataGrid_GridTapped; this.rightImage.BindingContextChanged += this.RightImage_BindingContextChanged; this.leftImage.BindingContextChanged += this.LeftImage_BindingContextChanged; this.dataGrid.SwipeEnded += this.DataGrid_SwipeEnded; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type of bindAble parameter</param> protected override void OnDetachingFrom(SampleView bindAble) { bindAble.PropertyChanged -= this.Swiping_PropertyChanged; this.dataGrid.GridTapped -= this.DataGrid_GridTapped; this.rightImage.BindingContextChanged -= this.RightImage_BindingContextChanged; this.leftImage.BindingContextChanged -= this.LeftImage_BindingContextChanged; this.dataGrid.SwipeEnded -= this.DataGrid_SwipeEnded; base.OnDetachingFrom(bindAble); } #region Private Methods /// <summary> /// triggers while Swiping Property was changed /// </summary> /// <param name="sender">Swiping_PropertyChanged event sender</param> /// <param name="e">Swiping_PropertyChanged event args e</param> private void Swiping_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "Width" && this.formView != null && this.formView.Width != -1) { if (this.formView.Visibility == true && this.formView.IsVisible == true) { if (Device.RuntimePlatform == Device.macOS) { this.LayoutMacFormsView(true); } else { this.LayoutFormsView(true); } } else { if (Device.RuntimePlatform == Device.macOS) { this.LayoutMacFormsView(false); } else { this.LayoutFormsView(false); } this.dataGrid.Opacity = 1.0; } } } /// <summary> /// Triggers while DataGrid was tapped. /// </summary> /// <param name="sender">DataGrid_GridTapped event sender</param> /// <param name="e">DataGrid_GridTapped event args</param> private void DataGrid_GridTapped(object sender, GridTappedEventArgs e) { if (Device.RuntimePlatform != Device.UWP) { this.formView.Visibility = false; } else { this.formView.IsVisible = false; } this.dataGrid.Opacity = 1.0; this.dataGrid.IsEnabled = true; } /// <summary> /// Triggers while left image binding context was changed. /// </summary> /// <param name="sender">leftImage_BindingContextChanged event sender</param> /// <param name="e">leftImage_BindingContextChanged event args</param> private void LeftImage_BindingContextChanged(object sender, EventArgs e) { if (this.leftImage.Source == null) { this.LayoutFormsView(false); this.leftImage = sender as Image; this.leftImage.IsVisible = true; (this.leftImage.Parent.Parent as View).GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Edit) }); this.leftImage.Source = new FontImageSource { Glyph = "\ue747", FontFamily = (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.macOS) ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.White }; } } /// <summary> /// Used this method to get a Edit View of Swiping /// </summary> private void Edit() { this.dataGrid.Opacity = 0.25; this.dataGrid.IsEnabled = false; if (Device.RuntimePlatform != Device.macOS) { this.LayoutFormsView(true); } else { this.LayoutMacFormsView(true); } } /// <summary> /// Layouts the FormsView in Mac platform /// </summary> /// <param name="visisble">Indicates true or false type parameter visible</param> private void LayoutMacFormsView(bool visisble) { if (Device.RuntimePlatform != Device.UWP) { this.formView.LayoutTo(new Rectangle(this.dataGrid.Width * (Device.Idiom == TargetIdiom.Phone ? 0.025 : 0.1), (this.dataGrid.Height / 2) - (350 / 2), this.dataGrid.Width - (this.dataGrid.Width * (Device.Idiom == TargetIdiom.Phone ? 0.05 : 0.2)), 350), 350, null); this.formView.Visibility = visisble; this.formView.IsVisible = visisble; } else { this.formView.IsVisible = visisble; } } /// <summary> /// Layouts the FormsView in all platform except MAC /// </summary> /// <param name="visible">Indicates true or false type parameter visible</param> private async void LayoutFormsView(bool visible) { await Task.Delay(10); if (Device.RuntimePlatform != Device.macOS) { string orientation = DependencyService.Get<IDataGridDependencyService>().GetOrientation(); if (orientation != "Portrait" && orientation != "PortraitUpsideDown") { await this.formView.LayoutTo(new Rectangle(this.dataGrid.Width / 8, (this.dataGrid.Height / 2) - (250 / 2), this.dataGrid.Width - (this.dataGrid.Width / 4), 250), 0, null); } else { if (Device.RuntimePlatform != Device.UWP) { await this.formView.LayoutTo(new Rectangle(this.dataGrid.Width * (Device.Idiom == TargetIdiom.Phone ? 0.025 : 0.1), (this.dataGrid.Height / 2) - (350 / 2), this.dataGrid.Width - (this.dataGrid.Width * (Device.Idiom == TargetIdiom.Phone ? 0.05 : 0.2)), 350), 0, null); } else { await this.formView.LayoutTo(new Rectangle(this.dataGrid.Width * (Device.Idiom == TargetIdiom.Phone ? 0.025 : 0.1), (this.dataGrid.Height / 2) - (350 / 2), this.dataGrid.Width - (this.dataGrid.Width * (Device.Idiom == TargetIdiom.Phone ? 0.05 : 0.2)), 350), 0, null); } } } if (Device.RuntimePlatform != Device.UWP) { this.formView.Visibility = visible; this.formView.IsVisible = visible; this.formView.ForceLayout(); } else { this.formView.Visibility = visible; this.formView.IsVisible = visible; this.formView.ForceLayout(); } } /// <summary> /// Used this method to delete a Row records while Delete Image was pressed /// </summary> private void Delete() { this.viewModel.OrdersInfo.RemoveAt(this.swipedRowIndex - 1); } /// <summary> /// Triggers while RightImage Binding Context was changed /// </summary> /// <param name="sender">RightImage_BindingContextChanged event sender</param> /// <param name="e">RightImage_BindingContextChanged event args e</param> private void RightImage_BindingContextChanged(object sender, EventArgs e) { if (this.rightImage.Source == null) { this.rightImage = sender as Image; (this.rightImage.Parent.Parent as View).GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Delete) }); this.rightImage.Source = new FontImageSource { Glyph = "\ue735", FontFamily = (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.macOS) ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.White }; } } /// <summary> /// Triggers while Swiping was ended /// </summary> /// <param name="sender">DataGrid_SwipeEnded event sender</param> /// <param name="e">DataGrid_SwipeEnded event args</param> private void DataGrid_SwipeEnded(object sender, Syncfusion.SfDataGrid.XForms.SwipeEndedEventArgs e) { this.formView.BindingContext = e.RowData; this.swipedRowIndex = e.RowIndex; } #endregion } }<file_sep>/Forms/BadgeView/readme.md Description The following samples are available for maps to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- |<file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/UnBoundColumnViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "UnBoundColumnViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for UnBoundColumn sample. /// </summary> public class UnBoundColumnViewModel { #region Field [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private List<Product> products; #endregion /// <summary> /// Initializes a new instance of the UnBoundColumnViewModel class. /// </summary> public UnBoundColumnViewModel() { ProductRepository product = new ProductRepository(); this.products = product.GetProductDetails(100); } #region ItemsSource /// <summary> /// Gets or sets the value of Products /// </summary> public List<Product> Products { get { return this.products; } set { this.products = value; } } #endregion #region ItemSource Generator /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">generates row count</param> public void SetRowstoGenerate(int count) { ProductRepository product = new ProductRepository(); this.products = product.GetProductDetails(100); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/CustomTooltipBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; namespace SampleBrowser { public class CustomTooltipBehavior : ChartTooltipBehavior { Context context; public CustomTooltipBehavior(Context con) { context = con; } protected override View GetView(TooltipView p0) { ImageView imageView = new ImageView(context); imageView.SetImageResource(Resource.Drawable.grain); LinearLayout rootLayout = new LinearLayout(context); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); rootLayout.Orientation = Orientation.Horizontal; rootLayout.LayoutParameters = layoutParams; rootLayout.SetPadding(5, 5, 5, 5); rootLayout.AddView(imageView); TextView xLabel = new TextView(context); xLabel.Text = (p0.ChartDataPoint as DataPoint).XValue.ToString(); xLabel.TextSize = 12; xLabel.SetTextColor(Color.ParseColor("#FFA500")); TextView yLabel = new TextView(context); yLabel.Text = (p0.ChartDataPoint as DataPoint).YValue.ToString() +"M"; yLabel.TextSize = 15; yLabel.SetTextColor(Color.White); LinearLayout layout = new LinearLayout(context); LinearLayout.LayoutParams linearlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); layout.Orientation = Orientation.Vertical; linearlayoutParams.SetMargins(10, 10, 10, 10); layout.LayoutParameters = linearlayoutParams; layout.AddView(xLabel); layout.AddView(yLabel); rootLayout.AddView(layout); p0.AddView(rootLayout); return p0; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/StackedDoughnut.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Foundation; using Syncfusion.SfChart.iOS; using UIKit; namespace SampleBrowser { public class StackedDoughnut : SampleView { void Chart_LegendItemCreated(object sender, ChartLegendItemCreatedEventArgs e) { ChartDataModel dataModel = e.LegendItem.DataPoint as ChartDataModel; float heightAndWidth = Utility.IsIPad ? 80 : 60; UIView legendView = new UIView(); legendView.Frame = new CGRect(0, 0, 130, heightAndWidth - 10); SFChart legendChart = new SFChart(); legendChart.Frame = new CGRect(0, 0, heightAndWidth, heightAndWidth); UIImageView imageView = new UIImageView(); imageView.Image = UIImage.FromBundle(dataModel.Image); imageView.Frame = new CGRect(legendChart.Frame.X / 2, legendChart.Frame.Y / 2, Utility.IsIPad ? 30 : 20, Utility.IsIPad ? 30 : 20); SFDoughnutSeries series = new SFDoughnutSeries(); series.IsStackedDoughnut = true; series.Color = e.LegendItem.IconColor; series.ItemsSource = new List<ChartDataModel>() { dataModel }; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.StartAngle = -90; series.EndAngle = 270; series.MaximumValue = 100; series.Spacing = 0.2; series.DoughnutCoefficient = 0.8; series.CircularCoefficient = 1.0; series.CapStyle = DoughnutCapStyle.BothCurve; series.CenterView = imageView; legendChart.Series.Add(series); legendView.AddSubview(legendChart); UILabel yLabel = new UILabel(); yLabel.Frame = new CGRect(Utility.IsIPad ? 77 : 57, Utility.IsIPad ? 20 : 10, 80, 18); yLabel.TextColor = e.LegendItem.IconColor; yLabel.Font = UIFont.FromName("Helvetica", 14f); yLabel.Text = dataModel.YValue.ToString() + "%"; UILabel xLabel = new UILabel(); xLabel.Frame = new CGRect(Utility.IsIPad ? 77 : 57, Utility.IsIPad ? 40 : 30, 80, 18); xLabel.TextColor = UIColor.Black; xLabel.Font = UIFont.FromName("Helvetica", 12f); xLabel.Text = dataModel.XValue.ToString(); legendView.AddSubview(yLabel); legendView.AddSubview(xLabel); e.LegendItem.View = legendView; } public StackedDoughnut() { ChartViewModel viewModel = new ChartViewModel(); SFChart chart = new SFChart(); chart.Title.Text = new NSString("Percentage of Loan Closure"); chart.Title.Font = UIFont.SystemFontOfSize(15); chart.Legend.Visible = true; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; chart.Legend.OverflowMode = ChartLegendOverflowMode.Wrap; chart.LegendItemCreated += Chart_LegendItemCreated; ; UIImageView imageView = new UIImageView(); imageView.Image = UIImage.FromBundle("Images/Person.png"); float heightAndWidth = Utility.IsIPad ? 250 : 80; imageView.Frame = new CGRect(chart.Frame.X / 2, chart.Frame.Y / 2, heightAndWidth, heightAndWidth); SFDoughnutSeries doughnutSeries = new SFDoughnutSeries(); doughnutSeries.IsStackedDoughnut = true; doughnutSeries.ColorModel.Palette = SFChartColorPalette.Custom; doughnutSeries.ColorModel.CustomColors = NSArray.FromObjects(UIColor.FromRGBA(0.28f, 0.73f, 0.62f, 1.0f), UIColor.FromRGBA(0.90f, 0.53f, 0.44f, 1.0f), UIColor.FromRGBA(0.59f, 0.53f, 0.79f, 1.0f), UIColor.FromRGBA(0.90f, 0.40f, 0.56f, 1.0f)); doughnutSeries.ItemsSource = viewModel.StackedDoughnutData; doughnutSeries.XBindingPath = "XValue"; doughnutSeries.YBindingPath = "YValue"; doughnutSeries.StartAngle = -90; doughnutSeries.EndAngle = 270; doughnutSeries.MaximumValue = 100; doughnutSeries.Spacing = 0.2; doughnutSeries.DoughnutCoefficient = 0.6; doughnutSeries.CircularCoefficient = 1; doughnutSeries.CapStyle = DoughnutCapStyle.BothCurve; doughnutSeries.CenterView = imageView; chart.Series.Add(doughnutSeries); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } } <file_sep>/Forms/ListView/readme.md The listview is a feature rich list control that renders a set of data items with views or custom templates. It has many features like grouping, sorting, filtering, paging, swiping, multiple selection, dragging and dropping, and layout types. This control has also been optimized to work with large amounts of data. The following samples are available for chart to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Grid Layout](ListView/Samples/GridLayout) | The grid layout which arranges the items in a predefined number of columns. | | [Grouping](ListView/Samples/Grouping) | The grouping capability of ListView which also provides support to freeze the group headers in view when grouped. | | [Selection](ListView/Samples/Selection) | The selection capability of ListView which provides selection mode options like Single, Multiple and None. | | [Horizontal Orientation](ListView/Samples/Orientation) | The horizontal orientation support in ListView where the items are arranged in a horizontal manner. | | [Swiping](ListView/Samples/Swiping) | The swiping functionalities of ListView which allows you to load the swipe views and associate them with custom actions. | | [Item Reordering](ListView/Samples/ItemReordering) | The item reordering by drag and drop on either long press or from drag indicator. | | [Pull To Refresh](ListView/Samples/PullToRefresh) | The pull-to-refresh capability of ListView which allows you to refresh the data source upon pull-to-refresh action. | | [Load More](ListView/Samples/LoadMore) | The loading more items automatically when end of the list is reached on scrolling. | | [AutoFit Items](ListView/Samples/AutoFitContent) | The autofit feature of ListView which automatically re-size the items based on its content dynamically. | | [Data Template Selector](ListView/Samples/DataTemplateSelector) | The template selector feature of ListView which displays incoming and outgoing message on different template. | | [Sorting and Filtering](ListView/Samples/SortingFiltering) | The sorting and filtering capabilities of ListView. | | [Paging](ListView/Samples/Paging) | The paging capabilities of ListView using SfDataPager which allows you to load the data from the data source in an efficient way. | | [Expandable View](ListView/Samples/Accordion) | The Expandable view using SfListView which expand or collapse when tapped over the list item. |<file_sep>/Forms/Carousel/Carousel/Samples/Carousel_Virtualization/Virtualization_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfCarousel { /// <summary> /// Virtualization default. /// </summary> public partial class Virtualization_Default : SampleView { CarouselViewModel carouselViewModel; #region VirtualizationDefault /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.SfCarousel.Virtualization_Default"/> class. /// </summary> public Virtualization_Default() { InitializeComponent(); carouselViewModel = new CarouselViewModel(); if (Device.RuntimePlatform == Device.iOS && Device.Idiom == TargetIdiom.Phone) { brandCarousel.MinimumHeightRequest = 200; brandCarousel.HeightRequest = 200; brandCarousel.ItemHeight = 175; brandCarousel.ItemWidth = 140; } carouselLayout.BindingContext = carouselViewModel; } #endregion #region SB view /// <summary> /// Gets the content. /// </summary> /// <returns>The content.</returns> public View getContent() { return this.Content; } #endregion /// <summary> /// Handles the clicked. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void Handle_Clicked(object sender, System.EventArgs e) { virtualizationButton.IsVisible = false; brandCarousel.IsVisible = true; brandCarousel.ItemsSource = carouselViewModel.DataCollection; } #region handle event /// <summary> /// Handles the tapped. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void Handle_Tapped(object sender, System.EventArgs e) { if (previousLabel != null) previousLabel.Text = "C"; selectedModel = (sender as ImageAdv).ModelObject; this.iconName.Text = selectedModel.Unicode; this.iconText.Text = selectedModel.Name.Replace("-", " ").Replace("0", "").Replace("1", "").Replace("2", "").Replace("3", "").Replace("4", "").Replace("5", "").Replace("6", "").Replace("7", "").Replace("8", "").Replace("9", ""); this.iconName.TextColor = selectedModel.ItemColor; this.Dialog.IsVisible = true; this.Dialog.Opacity = 0; this.Dialog.FadeTo(1, 500, Easing.Linear); } /// <summary> /// Handles the tapped. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void Color_Tapped(object sender, System.EventArgs e) { if (previousLabel != null) previousLabel.Text = "C"; (sender as Label).Text = "B"; selectedModel.ItemColor = (sender as Label).TextColor; this.iconName.TextColor = selectedModel.ItemColor; previousLabel = (sender as Label); } /// <summary> /// Yeses the handle. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void Yes_Handle(object sender, System.EventArgs e) { this.Dialog.Opacity = 1; this.Dialog.IsVisible = false; selectedModel = null; } #endregion #region Member private Label previousLabel = null; private CarouselModel selectedModel = null; #endregion } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Sorting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.App; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using System.Globalization; using System.Linq; using System.ComponentModel; namespace SampleBrowser { public class Sorting:SamplePage { SfDataGrid sfGrid; SortingViewModel viewModel; CheckBox allowsorting; CheckBox allowtristatesorting; CheckBox allowsortingforSupplierID; CheckBox allowMultiSorting; public override Android.Views.View GetSampleContent (Android.Content.Context context) { sfGrid = new SfDataGrid (context); viewModel = new SortingViewModel (); viewModel.SetRowstoGenerate (100); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = viewModel.Products; sfGrid.SelectionMode = SelectionMode.Single; sfGrid.AllowSorting = true; sfGrid.AllowTriStateSorting = true; sfGrid.Alpha = 1.0f; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; this.sfGrid.SortColumnDescriptions.Add (new SortColumnDescription (){ ColumnName ="ProductID", SortDirection = ListSortDirection.Descending }); return sfGrid; } public override void OnApplyChanges () { base.OnApplyChanges (); } public override View GetPropertyWindowLayout (Android.Content.Context context) { LinearLayout linear = new LinearLayout (context); linear.Orientation = Orientation.Vertical; allowsorting = new CheckBox (context); allowtristatesorting = new CheckBox (context); allowMultiSorting = new CheckBox(context); allowsortingforSupplierID = new CheckBox (context); allowsorting.Text = "Allow Sorting"; allowtristatesorting.Text = "Allow TriState Sorting"; allowMultiSorting.Text = "Allow Mutli-Sorting"; allowsortingforSupplierID.Text = "Allow Sorting For SupplierID"; allowsorting.Checked = true; allowtristatesorting.Checked = false; allowMultiSorting.Checked = false; allowsortingforSupplierID.Checked = true; allowsorting.CheckedChange += OnAllowSortingChanged; allowtristatesorting.CheckedChange += OnAllowTriStateSortingChanged; allowMultiSorting.CheckedChange += OnAllowMultiSortingChanged; allowsortingforSupplierID.CheckedChange += OnSortingForSupplierIDChanged; linear.AddView (allowsorting); linear.AddView (allowtristatesorting); linear.AddView(allowMultiSorting); linear.AddView (allowsortingforSupplierID); return linear; } void OnSortingForSupplierIDChanged (object sender, CompoundButton.CheckedChangeEventArgs e) { var supplierId = sfGrid.Columns.FirstOrDefault (x => x.MappingName == "SupplierID"); if (e.IsChecked) supplierId.AllowSorting = true; else supplierId.AllowSorting = false; } void OnAllowTriStateSortingChanged (object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) sfGrid.AllowTriStateSorting = true; else sfGrid.AllowTriStateSorting = false; } void OnAllowMultiSortingChanged (object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) sfGrid.AllowMultiSorting = true; else sfGrid.AllowMultiSorting = false; } void OnAllowSortingChanged (object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) sfGrid.AllowSorting = true; else sfGrid.AllowSorting = false; } void GridAutoGenerateColumns (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "SupplierID") { e.Column.HeaderText = "Supplier ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "ProductID") { e.Column.HeaderText = "Product ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "ProductName") { e.Column.HeaderText = "Product Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Quantity") { e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "UnitPrice") { e.Column.HeaderText = "Unit Price"; e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); } else if (e.Column.MappingName == "UnitsInStock") { e.Column.HeaderText = "Units In Stock"; e.Column.TextAlignment = GravityFlags.Center; } } public override void Destroy () { sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; sfGrid.Dispose (); sfGrid = null; allowsorting = null; allowtristatesorting = null; allowMultiSorting = null; allowsortingforSupplierID = null; viewModel = null; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/ConditionalFormatting/ConditionalFormattingBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ConditionalFormattingBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the ConditionalFormatting samples /// </summary> public class ConditionalFormattingBehaviors : Behavior<Syncfusion.SfDataGrid.XForms.SfDataGrid> { /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="dataGrid">DataGrid type parameter as dataGrid</param> protected override void OnAttachedTo(Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid) { dataGrid.QueryCellStyle += this.DataGrid_QueryCellStyle; base.OnAttachedTo(dataGrid); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="dataGrid">DataGrid type parameter as dataGrid</param> protected override void OnDetachingFrom(Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid) { dataGrid.QueryCellStyle -= this.DataGrid_QueryCellStyle; base.OnDetachingFrom(dataGrid); } /// <summary> /// Fired when a cell comes to the View /// </summary> /// <param name="sender">DataGrid_QueryCellStyle event sender</param> /// <param name="e">DataGrid_QueryCellStyle event args</param> private void DataGrid_QueryCellStyle(object sender, QueryCellStyleEventArgs e) { if (e.Column.MappingName == "Name") { e.Style.FontAttribute = FontAttributes.Bold; e.Handled = true; } } } } <file_sep>/Android/SampleBrowser/Samples/PDF/Conformance.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Android.Views; using Android.Widget; using System.IO; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf.Interactive; namespace SampleBrowser { public partial class Conformance : SamplePage { private Context m_context; private Spinner m_conformance; private LinearLayout advancedLinear1; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates various PDF conformance support in Essential PDF."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView text3 = new TextView(con); text3.TextSize = 19; text3.TextAlignment = TextAlignment.Center; text3.Text = "Please select the conformance"; text3.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text3.SetPadding(5, 100, 5, 5); linear.AddView(text3); advancedLinear1 = new LinearLayout(con); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); string[] list1 = { "PDF/A-1a", "PDF/A-1b", "PDF/A-2a", "PDF/A-2b", "PDF/A-2u", "PDF/A-3a", "PDF/A-3b" , "PDF/A-3u"}; ArrayAdapter<String> array1 = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleSpinnerItem, list1); m_conformance = new Spinner(con); m_conformance.Adapter = array1; m_conformance.SetSelection(0); advancedLinear1.AddView(m_conformance); advancedLinear1.SetPadding(320,0,5,5); linear.AddView(advancedLinear1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate PDF"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { PdfDocument document =null; if(this.m_conformance.SelectedItemPosition == 0) { //Create a new PDF document document = new PdfDocument(PdfConformanceLevel.Pdf_A1A); } else if(this.m_conformance.SelectedItemPosition == 1) { document = new PdfDocument(PdfConformanceLevel.Pdf_A1B); } else if(this.m_conformance.SelectedItemPosition == 2) { document = new PdfDocument(PdfConformanceLevel.Pdf_A2A); } else if(this.m_conformance.SelectedItemPosition == 3) { document = new PdfDocument(PdfConformanceLevel.Pdf_A2B); } else if(this.m_conformance.SelectedItemPosition == 4) { document = new PdfDocument(PdfConformanceLevel.Pdf_A2U); } else { if (this.m_conformance.SelectedItemPosition == 5) { document = new PdfDocument(PdfConformanceLevel.Pdf_A3A); } else if (this.m_conformance.SelectedItemPosition == 6) { document = new PdfDocument(PdfConformanceLevel.Pdf_A3B); } else if (this.m_conformance.SelectedItemPosition == 7) { document = new PdfDocument(PdfConformanceLevel.Pdf_A3U); } Stream imgStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Products.xml"); PdfAttachment attachment = new PdfAttachment("PDF_A.xml",imgStream); attachment.Relationship = PdfAttachmentRelationship.Alternative; attachment.ModificationDate = DateTime.Now; attachment.Description = "PDF_A"; attachment.MimeType = "application/xml"; document.Attachments.Add(attachment); } //Add a page PdfPage page = document.Pages.Add(); //Create font Stream arialFontStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.arial.ttf"); Stream imageStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.AdventureCycle.jpg"); PdfFont font = new PdfTrueTypeFont(arialFontStream, 14); //Create PDF graphics for the page. PdfGraphics graphics = page.Graphics; //Load the image from the disk. PdfImage img = PdfImage.FromStream(imageStream); //Draw the image in the specified location and size. graphics.DrawImage(img, new RectangleF(150, 30, 200, 100)); PdfTextElement textElement = new PdfTextElement("Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based," + " is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, " + "European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional" + " sales teams are located throughout their market base.") { Font = font }; PdfLayoutResult layoutResult = textElement.Draw(page, new RectangleF(0, 150, page.GetClientSize().Width, page.GetClientSize().Height)); MemoryStream stream = new MemoryStream(); //Save the PDF dcoument. document.Save(stream); //Close the PDF document. document.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("PDF_Ab.pdf", "application/pdf", stream, m_context); } } } }<file_sep>/Forms/TabView/TabView/Samples/NestedTab/Model/ContactsInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTabView { [Preserve(AllMembers = true)] public class ContactsInfoRepository { #region Fields private Random random = new Random(); #endregion #region Constructor public ContactsInfoRepository() { } #endregion #region Get Contacts Details public ObservableCollection<ContactsInfo> GetContactDetails(int incValue) { ObservableCollection<ContactsInfo> customerDetails = new ObservableCollection<ContactsInfo>(); for (int i = incValue; i < CustomerNames.Count(); i = i+ incValue) { var dateTime = DateTime.Now.AddHours(-10 * i); dateTime = DateTime.Now.AddSeconds(-45 * (i + i)); dateTime = DateTime.Now.AddSeconds(-2*i); var details = new ContactsInfo() { Message = contactType[(i % 19)], ContactReadType = CustomerNames[i][0].ToString(), ContactName = CustomerNames[i], ContactNumber = "123-456-789", ContactImage = imageColor[(i % 5)], Date = dateTime.ToString(), DateMonth = dateTime.Minute.ToString() + ":" + dateTime.Second.ToString(), MessageCount = dateTime.DayOfWeek.ToString() }; customerDetails.Add(details); } return customerDetails; } #endregion #region Contacts Information string[] contactType = new string[] { "Hi,", "Sent a file", "Welcome", "Can you join the meeting?", ":),", "Thank you :)", "I am waiting", "That's Great!", "Okay", "ok sure", "I'm in meeting", "where is the book?", "need to do it now", "share me the file", "Cool?", ":) that's right,", "Thanks :)", "On the way", "Yes, But need to check", "It's possible?" }; string[] imageColor = new string[] { "#FFFFAEC9", "#FFFF7F27", "#FF00A2E8", "#FFA349A4", "#FFB5E61D" }; string[] CustomerNames = new string[] { "Kyle", "Gina", "Irene", "Katie", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Brenda", "Danielle", "Fiona", "Howard", "Jack", "Larry", "Holly", "Jennifer", "Liz", "Pete", "Steve", "Vince", "Zeke", "Aiden", "Jackson", "Mason", "Liam", "Jacob", "Jayden", "Ethan", "Noah", "Lucas", "Logan", "Caleb", "Caden", "Jack", "Ryan", "Connor", "Michael", "Elijah", "Brayden", "Benjamin", "Nicholas", "Alexander", "William", "Matthew", "James", "Landon", "Nathan", "Dylan", "Evan", "Luke", "Andrew", "Gabriel", "Gavin", "Joshua", "Owen", "Daniel", "Carter", "Tyler", "Cameron", "Christian", "Wyatt", "Henry", "Eli", "Joseph", "Max", "Isaac", "Samuel", "Anthony", "Grayson", "Zachary", "David", "Christopher", "John", "Isaiah", "Levi", "Jonathan", "Oliver", "Chase", "Cooper", "Tristan", "Colton", "Austin", "Colin", "Charlie", "Dominic", "Parker", "Hunter", "Thomas", "Alex", "Ian", "Jordan", "Cole", "Julian", "Aaron", "Carson", "Miles", "Blake", "Brody", "Adam", "Sebastian", "Adrian", "Nolan", "Sean", "Riley", "Bentley", "Xavier", "Hayden", "Jeremiah", "Jason", "Jake", "Asher", "Micah", "Jace", "Brandon", "Josiah", "Hudson", "Nathaniel", "Bryson", "Ryder", "Justin", "Bryce", }; #endregion } } <file_sep>/iOS/SampleBrowser/Samples/AutoComplete/ToleratingTypos.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Foundation; using Syncfusion.SfAutoComplete.iOS; using UIKit; namespace SampleBrowser { public class ToleratingTypos : SampleView { UILabel headerlabel; SfAutoComplete countryAutoComplete; UILabel searchresults; NSMutableArray countryList = new NSMutableArray(); string[] tableItems; string[] imageItems; UITableView tableView; ToleratingTyposHelper helper; public ToleratingTypos() { headerlabel = new UILabel(); headerlabel.Text = "Search by Countries"; headerlabel.TextColor = UIColor.Black; headerlabel.TextAlignment = UITextAlignment.Left; this.AddSubview(headerlabel); countryAutoComplete = new SfAutoComplete(); countryAutoComplete.Watermark = (NSString)"Search Here"; countryAutoComplete.MaxDropDownHeight = 100; countryAutoComplete.FilterItemChanged += CountryAutoComplete_FilterItemChanged; this.AddSubview(countryAutoComplete); List<string> items = new List<string>(); items.Add("Afghanistan"); items.Add("Akrotiri"); items.Add("Albania"); items.Add("Algeria"); items.Add("American Samoa"); items.Add("Andorra"); items.Add("Angola"); items.Add("Anguilla"); items.Add("Antarctica"); items.Add("Antigua and Barbuda"); items.Add("Argentina"); items.Add("Armenia"); items.Add("Aruba"); items.Add("Ashmore and Cartier Islands"); items.Add("Australia"); items.Add("Austria"); items.Add("Azerbaijan"); items.Add("Bahamas, The"); items.Add("Bahrain"); items.Add("Bangladesh"); items.Add("Barbados"); items.Add("Bassas da India"); items.Add("Belarus"); items.Add("Bolivia"); items.Add("Bosnia and Herzegovina"); items.Add("Botswana"); items.Add("Bouvet Island"); items.Add("Brazil"); items.Add("British Indian Ocean Territory"); items.Add("British Virgin Islands"); items.Add("Brunei"); items.Add("Bulgaria"); items.Add("Burkina Faso"); items.Add("Burma"); items.Add("Burundi"); items.Add("Cambodia"); items.Add("Cameroon"); items.Add("Canada"); items.Add("Cape Verde"); items.Add("Cayman Islands"); items.Add("Central African Republic"); items.Add("Chad"); items.Add("Chile"); items.Add("China"); items.Add("Christmas Island"); items.Add("Clipperton Island"); items.Add("Cocos (Keeling) Islands"); items.Add("Colombia"); items.Add("Comoros"); items.Add("Congo"); items.Add("Congo, Republic of the"); items.Add("Cook Islands"); items.Add("Coral Sea Islands"); items.Add("Costa Rica"); items.Add("Cote d'Ivoire"); items.Add("Croatia"); items.Add("Cuba"); items.Add("Cyprus"); items.Add("Czech Republic"); items.Add("Denmark"); items.Add("Dhekelia"); items.Add("Djibouti"); items.Add("Dominica"); items.Add("Dominican Republic"); items.Add("Ecuador"); items.Add("Egypt"); items.Add("El Salvador"); items.Add("Equatorial Guinea"); items.Add("Eritrea"); items.Add("Estonia"); items.Add("Ethiopia"); items.Add("Europa Island"); items.Add("Falkland Islands"); items.Add("Faroe Islands"); items.Add("Fiji"); items.Add("Finland"); items.Add("France"); items.Add("French Guiana"); items.Add("French Polynesia"); items.Add("French Southern and Antarctic Lands"); items.Add("Gabon"); items.Add("Gambia, The"); items.Add("Gaza Strip"); items.Add("Georgia"); items.Add("Germany"); items.Add("Ghana"); items.Add("Gibraltar"); items.Add("Glorioso Islands"); items.Add("Greece"); items.Add("Greenland"); items.Add("Grenada"); items.Add("Guadeloupe"); items.Add("Guam"); items.Add("Guatemala"); items.Add("Guernsey"); items.Add("Guinea"); items.Add("Guinea-Bissau"); items.Add("Guyana"); items.Add("Haiti"); items.Add("Heard Island and McDonald Islands"); items.Add("Holy See"); items.Add("Honduras"); items.Add("Hong Kong"); items.Add("Hungary"); items.Add("Iceland"); items.Add("India"); items.Add("Indonesia"); items.Add("Iran"); items.Add("Iraq"); items.Add("Ireland"); items.Add("Isle of Man"); items.Add("Israel"); items.Add("Italy"); items.Add("Jamaica"); items.Add("Jan Mayen"); items.Add("Japan"); items.Add("Jersey"); items.Add("Jordan"); items.Add("Juan de Nova Island"); items.Add("Kazakhstan"); items.Add("Kenya"); items.Add("Kiribati"); items.Add("Korea, North"); items.Add("Korea, South"); items.Add("Kuwait"); items.Add("Kyrgyzstan"); items.Add("Laos"); items.Add("Latvia"); items.Add("Lebanon"); items.Add("Lesotho"); items.Add("Liberia"); items.Add("Libya"); items.Add("Liechtenstein"); items.Add("Lithuania"); items.Add("Luxembourg"); items.Add("Macau"); items.Add("Macedonia"); items.Add("Madagascar"); items.Add("Malawi"); items.Add("Malaysia"); items.Add("Maldives"); items.Add("Mali"); items.Add("Malta"); items.Add("Marshall Islands"); items.Add("Martinique"); items.Add("Mauritania"); items.Add("Mauritius"); items.Add("Mayotte"); items.Add("Mexico"); items.Add("Micronesia"); items.Add("Moldova"); items.Add("Monaco"); items.Add("Mongolia"); items.Add("Montserrat"); items.Add("Morocco"); items.Add("Mozambique"); items.Add("Namibia"); items.Add("Nauru"); items.Add("Navassa Island"); items.Add("Nepal"); items.Add("Netherlands"); items.Add("Netherlands Antilles"); items.Add("New Caledonia"); items.Add("New Zealand"); items.Add("Nicaragua"); items.Add("Niger"); items.Add("Nigeria"); items.Add("Niue"); items.Add("Norfolk Island"); items.Add("Northern Mariana Islands"); items.Add("Norway"); items.Add("Oman"); items.Add("Pakistan"); items.Add("Palau"); items.Add("Panama"); items.Add("Papua New Guinea"); items.Add("Paracel Islands"); items.Add("Paraguay"); items.Add("Peru"); items.Add("Philippines"); items.Add("Pitcairn Islands"); items.Add("Poland"); items.Add("Portugal"); items.Add("Puerto Rico"); items.Add("Qatar"); items.Add("Reunion"); items.Add("Romania"); items.Add("Russia"); items.Add("Rwanda"); items.Add("Saint Helena"); items.Add("Saint Kitts and Nevis"); items.Add("Saint Lucia"); items.Add("Saint Pierre and Miquelon"); items.Add("Saint Vincent"); items.Add("Samoa"); items.Add("San Marino"); items.Add("Sao Tome and Principe"); items.Add("Saudi Arabia"); items.Add("Senegal"); items.Add("Serbia and Montenegro"); items.Add("Seychelles"); items.Add("Sierra Leone"); items.Add("Singapore"); items.Add("Slovakia"); items.Add("Slovenia"); items.Add("Solomon Islands"); items.Add("Somalia"); items.Add("South Africa"); items.Add("South Georgia"); items.Add("Spain"); items.Add("Spratly Islands"); items.Add("Sri Lanka"); items.Add("Sudan"); items.Add("Suriname"); items.Add("Svalbard"); items.Add("Swaziland"); items.Add("Sweden"); items.Add("Switzerland"); items.Add("Syria"); items.Add("Taiwan"); items.Add("Tajikistan"); items.Add("Tanzania"); items.Add("Thailand"); items.Add("Timor-Leste"); items.Add("Togo"); items.Add("Tokelau"); items.Add("Tonga"); items.Add("Trinidad and Tobago"); items.Add("Tromelin Island"); items.Add("Tunisia"); items.Add("Turkey"); items.Add("Turkmenistan"); items.Add("Turks and Caicos Islands"); items.Add("Tuvalu"); items.Add("Uganda"); items.Add("Ukraine"); items.Add("United Arab Emirates"); items.Add("United Kingdom"); items.Add("United States"); items.Add("Uruguay"); items.Add("Uzbekistan"); items.Add("Vanuatu"); items.Add("Venezuela"); items.Add("Vietnam"); items.Add("Virgin Islands"); items.Add("Wake Island"); items.Add("Wallis and Futuna"); items.Add("West Bank"); items.Add("Western Sahara"); items.Add("Yemen"); items.Add("Zambia"); items.Add("Zimbabwe"); countryAutoComplete.DataSource = items; countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeCustom; searchresults = new UILabel(); searchresults.Text = "Search Results"; searchresults.TextColor = UIColor.Gray; searchresults.TextAlignment = UITextAlignment.Left; this.AddSubview(searchresults); tableView = new UITableView(); tableView.RowHeight = 60; tableItems = new string[] { "General", "Maps", "News", "Video", "Music", "Books", "Flight", "Quick Search" }; imageItems = new string[] { "all.png", "Maps1.png", "Newspaper.png", "Media.png", "Music.png", "Book.png", "Aeroplane.png", "Picture.png" }; ToleratingTypoTableView tableViewSource = new ToleratingTypoTableView(tableItems, imageItems); tableView.Source = tableViewSource; this.AddSubview(tableView); countryAutoComplete.SelectionChanged += (object sender, SelectionEventArgs e) => { if ((sender as SfAutoComplete).SelectedIndex != -1) { tableViewSource.initial = true; tableViewSource.random = new Random().Next(10000, 99999); tableView.ReloadData(); } if ((sender as SfAutoComplete).SelectedIndex == -1) { tableViewSource.initial = false; tableViewSource.random = 0; tableView.ReloadData(); } }; countryAutoComplete.TextChanged += (object sender, TextEventArgs e) => { tableViewSource.initial = false; tableViewSource.random = 0; tableView.ReloadData(); }; helper = new ToleratingTyposHelper(); } bool CountryAutoComplete_FilterItemChanged(object sender, FilterItemEventArgs e) { object value1 = e.Text; object value2 = e.Item; var string1 = value1.ToString().ToLower(); var string2 = value2.ToString().ToLower(); if (string1.Length > 0 && string2.Length > 0) if (string1[0] != string2[0]) return false; var originalString1 = string.Empty; var originalString2 = string.Empty; if (string1.Length < string2.Length) { originalString2 = string2.Remove(string1.Length); originalString1 = string1; } if (string2.Length < string1.Length) { return false; } if (string2.Length == string1.Length) { originalString1 = string1; originalString2 = string2; } bool IsMatchSoundex = helper.ProcessOnSoundexAlgorithmn(originalString1) == helper.ProcessOnSoundexAlgorithmn(originalString2); int Distance = helper.GetDamerauLevenshteinDistance(originalString1, originalString2); if (IsMatchSoundex || Distance <= 4) return true; else return false; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { headerlabel.Frame = new CGRect(10, 10, view.Frame.Width - 20, 30); countryAutoComplete.Frame = new CGRect(10, 40, view.Frame.Width, 40); searchresults.Frame = new CGRect(10, 90, this.Frame.Width, 30); tableView.Frame = new CGRect(10, 130, this.Frame.Width - 20, this.Frame.Height - 160); } } } public class ToleratingTypoTableView : UITableViewSource { string cellIdentifier = "TableCell"; public bool customise; string[] tableItems; string[] imageItems; public int random = 0; internal bool initial; public ToleratingTypoTableView(string[] _items) { tableItems = _items; } public ToleratingTypoTableView(string[] _items, string[] _imageItems) { tableItems = _items; imageItems = _imageItems; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { } public override nint RowsInSection(UITableView tableview, nint section) { int i = tableItems.Length; return (nint)i; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier); if (cell == null) { cell = new UITableViewCell(UITableViewCellStyle.Subtitle, cellIdentifier); } UIView parentView = new UIView(); parentView.Frame = new CGRect(0, 0, cell.Bounds.Width, tableView.RowHeight); UIImageView imageView = new UIImageView(); imageView.Frame = new CGRect(5, 5, 50, tableView.RowHeight - 10); UILabel titleLabel = new UILabel(); titleLabel.Frame = new CGRect(60, 5, cell.Bounds.Width-65, tableView.RowHeight/2-5); titleLabel.TextAlignment = UITextAlignment.Left; UILabel resultLabel = new UILabel(); resultLabel.Frame = new CGRect(60, tableView.RowHeight/2, cell.Bounds.Width - 65, tableView.RowHeight / 2-5); resultLabel.TextAlignment = UITextAlignment.Left; imageView.Image = new UIImage(imageItems[indexPath.Row]); titleLabel.Text = tableItems[indexPath.Row]; resultLabel.Text="About " + random.ToString() + " results"; parentView.AddSubview(imageView); parentView.AddSubview(titleLabel); parentView.AddSubview(resultLabel); foreach(var views in cell.Subviews) { views.RemoveFromSuperview(); } cell.AddSubview(parentView); if (initial) random = random + new Random().Next(300, 999); return cell; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/EmployeeInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "EmployeeInfoRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class used to store the item values /// </summary> public class EmployeeInfoRepository { #region DataSource [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] title = new string[] { "Marketing Assistant", "Engineering Manager", "Senior Tool Designer", "Tool Designer", "Marketing Manager", "Production Supervisor - WC60", "Production Technician - WC10", "Design Engineer", "Production Technician - WC10", "Design Engineer", "Vice President of Engineering", "Production Technician - WC10", "Production Supervisor - WC50", "Production Technician - WC10", "Production Supervisor - WC60", "Production Technician - WC10", "Production Supervisor - WC60", "Production Technician - WC10", "Production Technician - WC30", "Production Control Manager", "Production Technician - WC45", "Production Technician - WC45", "Production Technician - WC30", "Production Supervisor - WC10", "Production Technician - WC20", "Production Technician - WC40", "Network Administrator", "Production Technician - WC50", "Human Resources Manager", "Production Technician - WC40", "Production Technician - WC30", "Production Technician - WC30", "Stocker", "Shipping and Receiving Clerk", "Production Technician - WC50", "Production Technician - WC60", "Production Supervisor - WC50", "Production Technician - WC20", "Production Technician - WC45", "Quality Assurance Supervisor", "Information Services Manager", "Production Technician - WC50", "Master Scheduler", "Production Technician - WC40", "Marketing Specialist", "Recruiter", "Production Technician - WC50", "Maintenance Supervisor", "Production Technician - WC30", }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] employeeName = new string[] { "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Random r = new Random(); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Dictionary<string, string> loginID = new Dictionary<string, string>(); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Dictionary<string, string> gender = new Dictionary<string, string>(); #endregion /// <summary> /// Initializes a new instance of the EmployeeInfoRepository class. /// </summary> public EmployeeInfoRepository() { this.PopulateData(); } /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">generates row count</param> /// <returns>added employee details</returns> public ObservableCollection<Employee> GetEmployeesDetails(int count) { var employees = new ObservableCollection<Employee>(); for (var i = 1; i < count; i++) { employees.Add(this.GetEmployee(i)); } return employees; } /// <summary> /// Generates record rows with given count /// </summary> /// <param name="i">generates row count</param> /// <returns>employee details</returns> public Employee GetEmployee(int i) { var name = this.employeeName[this.r.Next(this.employeeName.Count() - 1)]; return new Employee() { EmployeeID = 1000 + i, Name = name, ContactID = this.r.Next(1001, 2000), Gender = this.gender[name], Title = this.title[this.r.Next(this.title.Count() - 1)], BirthDate = new DateTime(this.r.Next(1975, 1985), this.r.Next(1, 12), this.r.Next(1, 28)), SickLeaveHours = this.r.Next(15, 70), Salary = new decimal(Math.Round(this.r.NextDouble() * 6000.5, 2)) }; } /// <summary> /// Used to add items in gender collection /// </summary> private void PopulateData() { this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Male"); this.gender.Add("<NAME>", "Female"); this.loginID.Add("<NAME>", "sean2"); this.loginID.Add("<NAME>", "phyllis0"); this.loginID.Add("<NAME>", "marvin0"); this.loginID.Add("<NAME>", "michael10"); this.loginID.Add("<NAME>", "cecil0"); this.loginID.Add("<NAME>", "oscar0"); this.loginID.Add("<NAME>", "sandra1"); this.loginID.Add("<NAME>", "selena0"); this.loginID.Add("<NAME>", "emilio0"); this.loginID.Add("<NAME>", "maxwell0"); this.loginID.Add("<NAME>", "mae0"); this.loginID.Add("<NAME>", "ramona0"); this.loginID.Add("<NAME>", "sabria0"); this.loginID.Add("<NAME>", "hannah0"); this.loginID.Add("<NAME>", "kyley0"); this.loginID.Add("<NAME>", "tom1"); this.loginID.Add("<NAME>", "thomas1"); this.loginID.Add("<NAME>", "john6"); this.loginID.Add("<NAME>", "chris3"); this.loginID.Add("<NAME>", "teresa0"); this.loginID.Add("<NAME>", "john7"); this.loginID.Add("<NAME>", "robert2"); this.loginID.Add("<NAME>", "stephen1"); this.loginID.Add("<NAME>", "phillip0"); this.loginID.Add("<NAME>", "gustavo0"); this.loginID.Add("<NAME>", "catherine0"); this.loginID.Add("<NAME>", "kim2"); this.loginID.Add("<NAME>", "humberto0"); this.loginID.Add("<NAME>", "pilar1"); this.loginID.Add("<NAME>", "frances0"); this.loginID.Add("<NAME>", "margaret0"); this.loginID.Add("<NAME>", "carla0"); this.loginID.Add("<NAME>", "jay1"); this.loginID.Add("<NAME>", "ronald0"); this.loginID.Add("<NAME>", "samuel0"); this.loginID.Add("<NAME>", "james2"); this.loginID.Add("<NAME>", "robert1"); this.loginID.Add("<NAME>", "françois1"); this.loginID.Add("<NAME>", "kim3"); this.loginID.Add("<NAME>", "lili0"); this.loginID.Add("<NAME>", "amy1"); this.loginID.Add("<NAME>", "anna0"); this.loginID.Add("<NAME>", "milton0"); this.loginID.Add("<NAME>", "paul2"); this.loginID.Add("<NAME>", "gregory0"); this.loginID.Add("<NAME>", "jphillip0"); this.loginID.Add("<NAME>", "michelle0"); this.loginID.Add("<NAME>", "daniel0"); this.loginID.Add("<NAME>", "cory0"); this.loginID.Add("<NAME>", "james3"); } } } <file_sep>/Android/SampleBrowser/Samples/PDF/Encryption.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Syncfusion.Pdf.Barcode; using System.IO; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf; using Syncfusion.Pdf.Security; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf.Interactive; namespace SampleBrowser { public partial class Encryption : SamplePage { private Context m_context; private Spinner m_rc4Key, m_aesKey, m_encryptionKey; private Spinner m_algorithms; private LinearLayout advancedLinear1; public override View GetSampleContent(Context con) { int numerHeight = getDimensionPixelSize(con, Resource.Dimension.numeric_txt_ht); int width = con.Resources.DisplayMetrics.WidthPixels - 40; LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to create secure PDF document."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); advancedLinear1 = new LinearLayout(con); TextView space3 = new TextView(con); space3.TextSize = 17; space3.TextAlignment = TextAlignment.Center; space3.Text = "Algorithms"; space3.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); space3.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear1.AddView(space3); m_context = con; string[] list1 = new string[] { "RC4", "AES" }; ArrayAdapter<String> array1 = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleSpinnerItem, list1); m_algorithms = new Spinner(con); m_algorithms.Adapter = array1; m_algorithms.SetSelection(1); advancedLinear1.AddView(m_algorithms); linear.AddView(advancedLinear1); TextView space4 = new TextView(con); space4.TextSize = 10; linear.AddView(space4); LinearLayout subLinear = new LinearLayout(con); TextView space2 = new TextView(con); space2.TextSize = 17; space2.TextAlignment = TextAlignment.Center; space2.Text = "Key Size"; space2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); space2.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); subLinear.AddView(space2); string[] list = { "40 Bit", "128 Bit" }; ArrayAdapter<String> array = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleSpinnerItem, list); m_rc4Key = new Spinner(con); m_rc4Key.Adapter = array; m_rc4Key.SetSelection(1); subLinear.AddView(m_rc4Key); //linear.AddView(subLinear); LinearLayout subLinear2 = new LinearLayout(con); TextView sbspace = new TextView(con); sbspace.TextSize = 17; sbspace.TextAlignment = TextAlignment.Center; sbspace.Text = "Key Size"; sbspace.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); sbspace.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); subLinear2.AddView(sbspace); string[] list2 = { "128 Bit", "256 Bit", "256 Revision 6" }; ArrayAdapter<String> array2 = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleSpinnerItem, list2); m_aesKey = new Spinner(con); m_aesKey.Adapter = array2; m_aesKey.SetSelection(1); subLinear2.AddView(m_aesKey); LinearLayout subLinear5 = new LinearLayout(con); TextView sbspace2 = new TextView(con); sbspace2.TextSize = 17; sbspace2.TextAlignment = TextAlignment.Center; sbspace2.Text = "Encryption Options"; sbspace2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); sbspace2.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); subLinear5.AddView(sbspace2); string[] encryptionList = new string[] { "Encrypt all contents", "Encrypt all contents except metadata", "Encrypt only attachments" }; ArrayAdapter<String> array3 = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleSpinnerItem, encryptionList); m_encryptionKey = new Spinner(con); m_encryptionKey.Adapter = array3; m_encryptionKey.SetSelection(0); subLinear5.AddView(m_encryptionKey); //linear.AddView(subLinear5); LinearLayout subLinear3 = new LinearLayout(con); TextView space5 = new TextView(con); space5.TextSize = 10; subLinear3.AddView(space5); TextView text4 = new TextView(con); text4.TextSize = 17; text4.TextAlignment = TextAlignment.Center; text4.Text = "User Password : <PASSWORD>"; text4.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text4.SetPadding(5, 5, 5, 5); subLinear3.AddView(text4); linear.AddView(subLinear3); LinearLayout subLinear4 = new LinearLayout(con); TextView text5 = new TextView(con); text5.TextSize = 17; text5.TextAlignment = TextAlignment.Center; text5.Text = "Owner Password : <PASSWORD>"; text5.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text5.SetPadding(5, 5, 5, 5); subLinear4.AddView(text5); linear.AddView(subLinear4); Button button1 = new Button(con); button1.Text = "Generate PDF"; button1.Click += OnButtonClicked; linear.AddView(button1); m_algorithms.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = array1.GetItem(e.Position); if (selectedItem.Equals("AES")) { linear.RemoveView(button1); linear.RemoveView(subLinear3); linear.RemoveView(subLinear4); linear.RemoveView(subLinear); linear.AddView(subLinear2); linear.AddView(subLinear5); linear.AddView(subLinear3); linear.AddView(subLinear4); linear.AddView(button1); } else { linear.RemoveView(button1); linear.RemoveView(subLinear3); linear.RemoveView(subLinear4); linear.RemoveView(subLinear2); linear.RemoveView(subLinear5); m_encryptionKey.SetSelection(0); linear.AddView(subLinear); linear.AddView(subLinear3); linear.AddView(subLinear4); linear.AddView(button1); } }; m_encryptionKey.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = array3.GetItem(e.Position); if (selectedItem.Equals("Encrypt only attachments")) { linear.RemoveView(button1); linear.RemoveView(subLinear4); linear.RemoveView(subLinear3); linear.RemoveView(subLinear5); linear.RemoveView(subLinear2); linear.AddView(subLinear2); linear.AddView(subLinear5); linear.AddView(subLinear3); linear.AddView(button1); } else { linear.RemoveView(button1); linear.RemoveView(subLinear4); linear.RemoveView(subLinear3); linear.RemoveView(subLinear5); linear.RemoveView(subLinear2); linear.AddView(subLinear2); linear.AddView(subLinear5); linear.AddView(subLinear3); linear.AddView(subLinear4); linear.AddView(button1); } }; return linear; } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } void OnButtonClicked(object sender, EventArgs e) { //Create new PDF document. PdfDocument document = new PdfDocument(); //Add page to the PDF document. PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; //Create font object. PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Bold); PdfBrush brush = PdfBrushes.Black; //Document security PdfSecurity security = document.Security; if (this.m_algorithms.SelectedItemPosition == 0) { security.Algorithm = PdfEncryptionAlgorithm.RC4; if (this.m_rc4Key.SelectedItemPosition == 0) { security.KeySize = PdfEncryptionKeySize.Key40Bit; } else if (this.m_rc4Key.SelectedItemPosition == 1) { security.KeySize = PdfEncryptionKeySize.Key128Bit; } } else if (this.m_algorithms.SelectedItemPosition == 1) { security.Algorithm = PdfEncryptionAlgorithm.AES; if (this.m_aesKey.SelectedItemPosition == 0) { security.KeySize = PdfEncryptionKeySize.Key128Bit; } else if (this.m_aesKey.SelectedItemPosition == 1) { security.KeySize = PdfEncryptionKeySize.Key256Bit; } else if (this.m_aesKey.SelectedItemPosition == 2) { security.KeySize = PdfEncryptionKeySize.Key256BitRevision6; } } if (this.m_encryptionKey.SelectedItemPosition == 0) { security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents; } else if (this.m_encryptionKey.SelectedItemPosition == 1) { security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata; } else if (this.m_encryptionKey.SelectedItemPosition == 2) { //Read the file Stream file = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Products.xml"); //Creates an attachment PdfAttachment attachment = new PdfAttachment("Products.xml", file); attachment.ModificationDate = DateTime.Now; attachment.Description = "About Syncfusion"; attachment.MimeType = "application/txt"; //Adds the attachment to the document document.Attachments.Add(attachment); security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments; } security.OwnerPassword = "<PASSWORD>"; security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint; security.UserPassword = "<PASSWORD>"; string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" + "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm); if (this.m_algorithms.SelectedItemPosition == 1) { if (this.m_aesKey.SelectedItemPosition == 2) { text += String.Format("\n\nRevision: {0}", "Revision 6"); } else if (this.m_aesKey.SelectedItemPosition == 1) { text += String.Format("\n\nRevision: {0}", "Revision 5"); } } // Draw String. graphics.DrawString("Document is Encrypted with following settings", font, brush, Syncfusion.Drawing.PointF.Empty); font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Bold); graphics.DrawString(text, font, brush, new Syncfusion.Drawing.PointF(0, 40)); MemoryStream stream = new MemoryStream(); //Save the PDF document. document.Save(stream); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("Securepdf.pdf", "application/pdf", stream, m_context); } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/Products.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; namespace SampleBrowser { public class Products : INotifyPropertyChanged { public Products () { } #region private variables private int supplierID; private int productID; private string productName; private int quantity; private int unitPrice; private int unitsInStock; #endregion #region Public Properties public int SupplierID { get { return supplierID; } set { this.supplierID = value; RaisePropertyChanged ("SupplierID"); } } public int ProductID { get { return productID; } set { this.productID = value; RaisePropertyChanged ("ProductID"); } } public string ProductName { get { return this.productName; } set { this.productName = value; RaisePropertyChanged ("ProductName"); } } public int Quantity { get { return quantity; } set { this.quantity = value; RaisePropertyChanged ("Quantity"); } } public int UnitPrice { get { return unitPrice; } set { this.unitPrice = value; RaisePropertyChanged ("UnitPrice"); } } public int UnitsInStock { get { return unitsInStock; } set { this.unitsInStock = value; RaisePropertyChanged ("UnitsInStock"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged (String name) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (name)); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/RangeColumn.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { internal class RangeColumn : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Temperature Variation"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.ToggleSeriesVisibility = true; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis categoryaxis = new CategoryAxis(); categoryaxis.ShowMajorGridLines = false; categoryaxis.LabelPlacement = LabelPlacement.BetweenTicks; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Interval = 5; numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.TickSize = 0; numericalaxis.LabelStyle.LabelFormat = "##.##" + (char)0x00B0 + "C"; chart.SecondaryAxis = numericalaxis; RangeColumnSeries rangeColumnSeries = new RangeColumnSeries(); rangeColumnSeries.EnableAnimation = true; rangeColumnSeries.ItemsSource = MainPage.GetRangeColumnData1(); rangeColumnSeries.XBindingPath = "XValue"; rangeColumnSeries.High = "High"; rangeColumnSeries.Low = "Low"; rangeColumnSeries.Label = "India"; rangeColumnSeries.LegendIcon = ChartLegendIcon.SeriesType; RangeColumnSeries rangeColumnSeries1 = new RangeColumnSeries(); rangeColumnSeries1.EnableAnimation = true; rangeColumnSeries1.ItemsSource = MainPage.GetRangeColumnData2(); rangeColumnSeries1.XBindingPath = "XValue"; rangeColumnSeries1.High = "High"; rangeColumnSeries1.Low = "Low"; rangeColumnSeries1.Label = "Germany"; rangeColumnSeries1.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(rangeColumnSeries); chart.Series.Add(rangeColumnSeries1); rangeColumnSeries.TooltipEnabled = true; rangeColumnSeries1.TooltipEnabled = true; rangeColumnSeries.EnableAnimation = true; rangeColumnSeries1.EnableAnimation = true; return chart; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/ErrorBar.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; #endif namespace SampleBrowser { public class ErrorBar : SampleView { public ErrorBar() { SFChart chart = new SFChart(); chart.Title.Text = new NSString("Sales Distribution of Car by Region"); chart.Title.EdgeInsets = new UIEdgeInsets(0, 0, 15, 0); ChartViewModel dataModel = new ChartViewModel(); SFCategoryAxis primaryAxis = new SFCategoryAxis(); primaryAxis.ShowMajorGridLines = false; primaryAxis.PlotOffset = 10; primaryAxis.LabelPlacement = SFChartLabelPlacement.BetweenTicks; NSNumberFormatter formatter = new NSNumberFormatter(); formatter.PositiveSuffix = "%"; primaryAxis.AxisLineOffset = 10; chart.PrimaryAxis = primaryAxis; SFNumericalAxis secondaryAxis = new SFNumericalAxis(); secondaryAxis.Minimum = new NSNumber(15); secondaryAxis.Maximum = new NSNumber(45); secondaryAxis.Interval = new NSNumber(5); secondaryAxis.MajorTickStyle.LineSize = 0; secondaryAxis.AxisLineStyle.LineWidth = 0; chart.SecondaryAxis = secondaryAxis; SFScatterSeries scatterSeries = new SFScatterSeries(); scatterSeries.ItemsSource = dataModel.ErrorBarData; scatterSeries.XBindingPath = "XValue"; scatterSeries.YBindingPath = "YValue"; scatterSeries.ScatterHeight = 20; scatterSeries.ScatterWidth = 20; scatterSeries.ShapeType = ChartScatterShapeType.Ellipse; scatterSeries.ColorModel.Palette = SFChartColorPalette.Natural; chart.Series.Add(scatterSeries); SFErrorBarSeries errorBarSeries = new SFErrorBarSeries(); errorBarSeries.ItemsSource = dataModel.ErrorBarData; errorBarSeries.XBindingPath = "XValue"; errorBarSeries.YBindingPath = "YValue"; errorBarSeries.HorizontalErrorPath = "High"; errorBarSeries.VerticalErrorPath = "Low"; errorBarSeries.HorizontalErrorValue = 3; errorBarSeries.VerticalErrorValue = 3; errorBarSeries.Mode = ErrorBarMode.Vertical; errorBarSeries.Type = ErrorBarType.Fixed; errorBarSeries.HorizontalLineStyle = new ErrorBarLineStyle(); errorBarSeries.HorizontalLineStyle.LineColor = UIColor.Black; errorBarSeries.VerticalLineStyle = new ErrorBarLineStyle(); errorBarSeries.VerticalLineStyle.LineColor = UIColor.Black; errorBarSeries.HorizontalCapLineStyle = new ErrorBarCapLineStyle(); errorBarSeries.HorizontalCapLineStyle.LineColor = UIColor.Black; errorBarSeries.VerticalCapLineStyle = new ErrorBarCapLineStyle(); errorBarSeries.VerticalCapLineStyle.LineColor = UIColor.Black; chart.Series.Add(errorBarSeries); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DocIO/TableOfContents.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.Pdf; using Syncfusion.DocIORenderer; using Syncfusion.OfficeChart; using Syncfusion.Drawing; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using Syncfusion.iOS.Buttons; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using ObjCRuntime; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class TableofContents : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UILabel imageTypelabel; UIButton imageType; UIButton generateButton; //RadioButton SfRadioGroup radioGroup = new SfRadioGroup(); SfRadioButton docxButton = new SfRadioButton(); SfRadioButton pdfButton = new SfRadioButton(); public TableofContents() { label = new UILabel(); imageTypelabel = new UILabel(); imageType = new UIButton(); generateButton = new UIButton(UIButtonType.System); generateButton.TouchUpInside += OnConvertClicked; } void LoadAllowedTextsLabel() { #region Description Label label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to create a Word document with Group shapes"; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 35); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } this.AddSubview(label); #endregion #region ImageFormat Label if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { imageTypelabel.Font = UIFont.SystemFontOfSize(18); imageTypelabel.Frame = new CGRect(10, 45, frameRect.Location.X + frameRect.Size.Width - 20, 50); imageType.Frame = new CGRect(10, 95, frameRect.Location.X + frameRect.Size.Width - 20, 40); } else { imageTypelabel.Frame = new CGRect(10, 50, frameRect.Location.X + frameRect.Size.Width - 20, 50); imageType.Frame = new CGRect(10, 100, frameRect.Location.X + frameRect.Size.Width - 20, 40); } //filter Label imageTypelabel.TextColor = UIColor.Black; imageTypelabel.BackgroundColor = UIColor.Clear; imageTypelabel.Text = "Save As:"; imageTypelabel.TextAlignment = UITextAlignment.Left; imageTypelabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(imageTypelabel); #endregion #region Radio Buttons radioGroup.Axis = UILayoutConstraintAxis.Horizontal; docxButton.SetTitle("DOCX", UIControlState.Normal); radioGroup.AddArrangedSubview(docxButton); pdfButton.SetTitle("PDF", UIControlState.Normal); radioGroup.AddArrangedSubview(pdfButton); docxButton.IsChecked = true; radioGroup.Distribution = UIStackViewDistribution.FillProportionally; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { radioGroup.Frame = new CGRect(110, 55, frameRect.Width - 500, 30); } else { radioGroup.Frame = new CGRect(110, 60, frameRect.Width - 90, 30); } this.AddSubview(radioGroup); #endregion #region Convert Button generateButton.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { generateButton.Frame = new CGRect(0, 105, frameRect.Location.X + frameRect.Size.Width, 10); } else { generateButton.Frame = new CGRect(0, (this.Frame.Size.Height / 4) - 5, frameRect.Location.X + frameRect.Size.Width, 10); } this.AddSubview(generateButton); #endregion } void OnConvertClicked(object sender, EventArgs e) { WordDocument doc = new WordDocument(); doc.EnsureMinimal(); WParagraph para = doc.LastParagraph; para.AppendText("Essential DocIO - Table of Contents"); para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; para.ApplyStyle(BuiltinStyle.Heading4); para = doc.LastSection.AddParagraph() as WParagraph; para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; para.ApplyStyle(BuiltinStyle.Heading4); para = doc.LastSection.AddParagraph() as WParagraph; //Insert TOC TableOfContent toc = para.AppendTOC(1, 3); para.ApplyStyle(BuiltinStyle.Heading4); //Apply built-in paragraph formatting WSection section = doc.LastSection; #region Default Styles WParagraph newPara = section.AddParagraph() as WParagraph; newPara = section.AddParagraph() as WParagraph; newPara.AppendBreak(BreakType.PageBreak); WTextRange text = newPara.AppendText("Document with Default styles") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading1); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading1 of built in style. This sample demonstrates the TOC insertion in a word document. Note that DocIO can only insert TOC field in a word document. It can not refresh or create TOC field. MS Word refreshes the TOC field after insertion. Please update the field or press F9 key to refresh the TOC."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Section1") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading2); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Paragraph1") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading3); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Paragraph2") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading3); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph."); section.AddParagraph(); section = doc.AddSection() as WSection; section.BreakCode = SectionBreakCode.NewPage; newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Section2") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading2); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading2 of built in style. A document can contain any number of sections. Sections are used to apply same formatting for a group of paragraphs. You can insert sections by inserting section breaks."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Paragraph1") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading3); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading3 of built in style. Each section contains any number of paragraphs. A paragraph is a set of statements that gives a meaning for the text."); section.AddParagraph(); newPara = section.AddParagraph() as WParagraph; text = newPara.AppendText("Paragraph2") as WTextRange; newPara.ApplyStyle(BuiltinStyle.Heading3); newPara = section.AddParagraph() as WParagraph; newPara.AppendText("This is the heading3 of built in style. This demonstrates the paragraphs at the same level and style as that of the previous one. A paragraph can have any number formatting. This can be attained by formatting each text range in the paragraph."); #endregion toc.IncludePageNumbers = true; toc.RightAlignPageNumbers = true; toc.UseHyperlinks = true; toc.LowerHeadingLevel = 1; toc.UpperHeadingLevel = 3; toc.UseOutlineLevels = true; //Updates the table of contents. doc.UpdateTableOfContents(); string fileName = null; string ContentType = null; MemoryStream ms = new MemoryStream(); if (pdfButton != null && (bool)pdfButton.IsChecked) { fileName = "Table of Contents.pdf"; ContentType = "application/pdf"; DocIORenderer renderer = new DocIORenderer(); PdfDocument pdfDoc = renderer.ConvertToPDF(doc); pdfDoc.Save(ms); pdfDoc.Close(); } else { fileName = "Table of Contents.docx"; ContentType = "application/msword"; doc.Save(ms, FormatType.Docx); } //Reset the stream position ms.Position = 0; //Close the document instance. doc.Close(); if (ms != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save(fileName, ContentType, ms as MemoryStream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataForm/FormGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using CoreGraphics; using Syncfusion.iOS.DataForm; using System.ComponentModel; namespace SampleBrowser { public class FormGettingStarted : SampleView { #region Field SfDataForm dataForm; UIButton button; UIScrollView scrollView; #endregion #region Constructor public FormGettingStarted() { dataForm = new SfDataForm(); dataForm.AutoGeneratingDataFormItem += DataForm_AutoGeneratingDataFormItem; dataForm.DataObject = new RecipientInfo(); (dataForm.DataObject as INotifyPropertyChanged).PropertyChanged += DataFormGettingStarted_PropertyChanged; dataForm.LabelPosition = LabelPosition.Top; button = new UIButton(); button.SetTitle("Transfer Money", UIControlState.Normal); button.SetTitleColor(this.TintColor, UIControlState.Normal); button.TouchDown += Button_TouchDown; scrollView = new UIScrollView(); scrollView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); this.AddSubview(scrollView); scrollView.AddSubview(this.dataForm); scrollView.AddSubview(button); } private void DataFormGettingStarted_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName.Equals("AccountNumber")) { var value = (string)sender.GetType().GetProperty("AccountNumber1").GetValue(sender); if (!string.IsNullOrEmpty(value)) dataForm.Validate("AccountNumber1"); } else if (e.PropertyName.Equals("AccountNumber1")) { var value = (string)sender.GetType().GetProperty("AccountNumber").GetValue(sender); if (!string.IsNullOrEmpty(value)) dataForm.Validate("AccountNumber"); } } private void DataForm_AutoGeneratingDataFormItem(object sender, AutoGeneratingDataFormItemEventArgs e) { if (e.DataFormItem != null) { if (e.DataFormItem.Name.Equals("AccountNumber") || e.DataFormItem.Name.Equals("AccountNumber1")) (e.DataFormItem as DataFormTextItem).KeyBoardType = UIKeyboardType.NumberPad; else if (e.DataFormItem.Name.Equals("Email")) (e.DataFormItem as DataFormTextItem).KeyBoardType = UIKeyboardType.EmailAddress; else if (e.DataFormItem.Name.Equals("SWIFT")) (e.DataFormItem as DataFormTextItem).AutocapitalizationType = UITextAutocapitalizationType.AllCharacters; } } private void Button_TouchDown(object sender, EventArgs e) { var isValid = dataForm.Validate(); dataForm.Commit(); if (!isValid) return; dataForm.IsReadOnly = true; button.Hidden = true; } #endregion public override void LayoutSubviews() { scrollView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); this.dataForm.Frame = new CGRect(0, 0, this.scrollView.Frame.Width, this.scrollView.Frame.Height - 30); this.button.Frame = new CGRect(0, this.scrollView.Frame.Height - 30, this.scrollView.Frame.Width, 30); base.LayoutSubviews(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/CheckBox/CheckBox_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using System; using UIKit; using Syncfusion.iOS.Buttons; using CoreAnimation; namespace SampleBrowser { public class CheckBox_Mobile : SampleView { bool skip = false; UIImageView image = new UIImageView(); UIStackView mainStackView = new UIStackView(); UILabel hedinglbl = new UILabel(); SfCheckBox selectAll = new SfCheckBox(); SfCheckBox grilledChicken = new SfCheckBox(); SfCheckBox chickenTikka = new SfCheckBox(); SfCheckBox chickenSausage = new SfCheckBox(); SfCheckBox beef = new SfCheckBox(); UIButton button = new UIButton(); CALayer layer = new CALayer(); UIAlertView alertView = new UIAlertView(); public CheckBox_Mobile() { //Image image.Image = UIImage.FromBundle("Images/Pizzaimage.png"); AddSubview(image); //Main statck mainStackView.Axis = UILayoutConstraintAxis.Vertical; //Layer layer.BorderWidth = 1.5f; layer.BorderColor = UIColor.FromRGB(205, 205, 205).CGColor; layer.CornerRadius = 10; Layer.AddSublayer(layer); //heading hedinglbl.Text = "Add Extra Toppings"; hedinglbl.TextColor = UIColor.FromRGB(0, 125, 230); hedinglbl.Font = UIFont.FromName(hedinglbl.Font.FamilyName, 20); mainStackView.AddSubview(hedinglbl); //Select All selectAll.SetTitle("Select All", UIControlState.Normal); selectAll.SetTitleColor(UIColor.Black, UIControlState.Normal); selectAll.StateChanged += SelectAll_StateChanged; mainStackView.AddSubview(selectAll); //GrilledChicken grilledChicken.SetTitle("Grilled Chicken", UIControlState.Normal); grilledChicken.SetTitleColor(UIColor.Black, UIControlState.Normal); grilledChicken.StateChanged += Toppings_StateChanged; mainStackView.AddSubview(grilledChicken); //ChickenTikka chickenTikka.SetTitle("Chicken Tikka", UIControlState.Normal); chickenTikka.SetTitleColor(UIColor.Black, UIControlState.Normal); chickenTikka.StateChanged += Toppings_StateChanged; mainStackView.AddSubview(chickenTikka); //ChickenSausage chickenSausage.SetTitle("Chicken Sausage", UIControlState.Normal); chickenSausage.SetTitleColor(UIColor.Black, UIControlState.Normal); chickenSausage.StateChanged += Toppings_StateChanged; mainStackView.AddSubview(chickenSausage); //Beef beef.SetTitle("Beef", UIControlState.Normal); beef.SetTitleColor(UIColor.Black, UIControlState.Normal); beef.StateChanged += Toppings_StateChanged; mainStackView.AddSubview(beef); //Button button.SetTitle("Order Now", UIControlState.Normal); button.SetTitleColor(UIColor.LightGray, UIControlState.Disabled); button.SetTitleColor(UIColor.White, UIControlState.Normal); button.BackgroundColor = UIColor.FromRGB(0, 125, 230); button.TouchDown += Button_Clicked; button.Enabled = false; AddSubview(button); //Alert alertView.Message = "Your order has been placed successfully !"; alertView.AddButton("OK"); AddSubview(mainStackView); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { image.Frame = new CGRect(0, -2, Frame.Size.Width, 270); mainStackView.Frame = new CGRect(25, 295, Frame.Size.Width - 45, 460); layer.Frame = new CGRect(25, 295, Frame.Size.Width - 45, 460); hedinglbl.Frame = new CGRect(10, 20, 350, 45); selectAll.Frame = new CGRect(20, 110, 200, 30); grilledChicken.Frame = new CGRect(20, 175, 200, 30); chickenTikka.Frame = new CGRect(20,245 , 200, 30); chickenSausage.Frame = new CGRect(20,315 , 200, 30); beef.Frame = new CGRect(20, 380, 200, 30); button.Frame = new CGRect(0, Frame.Size.Height - 40, Frame.Size.Width, 40); hedinglbl.Font = UIFont.FromName(hedinglbl.Font.FamilyName, 30); selectAll.Font = UIFont.FromName(hedinglbl.Font.FamilyName, 20); grilledChicken.Font = UIFont.FromName(hedinglbl.Font.FamilyName, 20); chickenTikka.Font = UIFont.FromName(hedinglbl.Font.FamilyName, 20); chickenSausage.Font = UIFont.FromName(hedinglbl.Font.FamilyName, 20); beef.Font = UIFont.FromName(hedinglbl.Font.FamilyName, 20); } else { view.Frame = new CGRect(Frame.Location.X, 0.0f, Frame.Size.Width, Frame.Size.Height); image.Frame = new CGRect(0, -2, Frame.Size.Width, 150); mainStackView.Frame = new CGRect(15, 165, Frame.Size.Width - 30, 285); layer.Frame = new CGRect(15, 165, Frame.Size.Width - 30, 285); hedinglbl.Frame = new CGRect(10, 10, 250, 30); selectAll.Frame = new CGRect(10, 55, 200, 30); grilledChicken.Frame = new CGRect(10, 100, 200, 30); chickenTikka.Frame = new CGRect(10, 145, 200, 30); chickenSausage.Frame = new CGRect(10, 190, 200, 30); beef.Frame = new CGRect(10, 235, 200, 30); button.Frame = new CGRect(0, 465, Frame.Size.Width, 38); } } base.LayoutSubviews(); } private void SelectAll_StateChanged(object sender, StateChangedEventArgs eventArgs) { if (!skip) { skip = true; grilledChicken.IsChecked = chickenTikka.IsChecked = chickenSausage.IsChecked = beef.IsChecked = eventArgs.IsChecked.Value; button.Enabled = eventArgs.IsChecked.Value; skip = false; } } private void Toppings_StateChanged(object sender, StateChangedEventArgs eventArgs) { if (!skip) { skip = true; selectAll.IsChecked = ValidateNonVegToopings(); if (!selectAll.IsChecked.HasValue || (selectAll.IsChecked.HasValue && selectAll.IsChecked.Value)) button.Enabled = true; else button.Enabled = false; skip = false; } } private void Button_Clicked(object sender, EventArgs e) { bool? temp = ValidateNonVegToopings(); if (!temp.HasValue || (temp.HasValue && temp.Value)) { alertView.Show(); selectAll.IsChecked = false; } } private bool? ValidateNonVegToopings() { if (grilledChicken.IsChecked.Value && chickenTikka.IsChecked.Value && chickenSausage.IsChecked.Value && beef.IsChecked.Value) return true; else if (!grilledChicken.IsChecked.Value && !chickenTikka.IsChecked.Value && !chickenSausage.IsChecked.Value && !beef.IsChecked.Value) return false; else return null; } } } <file_sep>/Android/SampleBrowser/Samples/Chart/MainPage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Graphics; using Com.Syncfusion.Charts; using Java.Util; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace SampleBrowser { public class DataPoint { public DataPoint(object xVal, double yVal) { XValue = xVal; YValue = yVal; } public DataPoint(DateTime xVal, double yVal) { Date = xVal; YValue = yVal; } public DataPoint(object xVal, double high, double low) { XValue = xVal; YValue = High = high; Size = Low = low; } public DataPoint(object xVal, double high, double low, string label) { XValue = xVal; YValue = High = high; Size = Low = low; Label = label; } public DataPoint(double high, double low, DateTime dateTime) { High = high; Low = low; Date = dateTime; } public DataPoint(object xVal, double open, double high, double low, double close) { XValue = xVal; Open = open; High = high; Low = low; Close = close; } public DataPoint(object xVal, double open, double high, double low, double close, double volume) { XValue = xVal; Open = open; High = high; Low = low; Close = close; Volume = volume; } public DataPoint(object xVal, double yVal, double horizontalValues, double verticalValues) { XValue = xVal; YValue = yVal; High = horizontalValues; Low = verticalValues; } public DataPoint(string department, List<double> ages) { Department = department; EmployeeAges = ages; } public object XValue { get; set; } public double YValue { get; set; } public double Size { get; set; } public double High { get; set; } public double Low { get; set; } public double Open { get; set; } public double Close { get; set; } public double Volume { get; set; } public DateTime Date { get; set; } public string Label { get; set; } public string Department { get; set; } public List<double> EmployeeAges { get; set; } } public class MainPage { public static List<DataPoint> GetAreaData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 45)); datas.Add(new DataPoint("2011", 56)); datas.Add(new DataPoint("2012", 23)); datas.Add(new DataPoint("2013", 43)); datas.Add(new DataPoint("2014", Double.NaN)); datas.Add(new DataPoint("2015", 54)); datas.Add(new DataPoint("2016", 43)); datas.Add(new DataPoint("2017", 23)); datas.Add(new DataPoint("2018", 34)); return datas; } public static List<DataPoint> GetDataMarkerData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2013", 1110)); datas.Add(new DataPoint("2014", 1130)); datas.Add(new DataPoint("2015", 1153)); datas.Add(new DataPoint("2016", 1175)); return datas; } public static List<DataPoint> GetDataMarkerData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2013", 1070)); datas.Add(new DataPoint("2014", 1105)); datas.Add(new DataPoint("2015", 1138)); datas.Add(new DataPoint("2016", 1155)); return datas; } public static List<DataPoint> GetStepAreaData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2000, 416)); datas.Add(new DataPoint(2001, 490)); datas.Add(new DataPoint(2002, 470)); datas.Add(new DataPoint(2003, 500)); datas.Add(new DataPoint(2004, 449)); datas.Add(new DataPoint(2005, 470)); datas.Add(new DataPoint(2006, 437)); datas.Add(new DataPoint(2007, 458)); datas.Add(new DataPoint(2008, 500)); datas.Add(new DataPoint(2009, 473)); datas.Add(new DataPoint(2010, 520)); datas.Add(new DataPoint(2011, 509)); return datas; } public static List<DataPoint> GetStepAreaData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2000, 180)); datas.Add(new DataPoint(2001, 240)); datas.Add(new DataPoint(2002, 370)); datas.Add(new DataPoint(2003, 200)); datas.Add(new DataPoint(2004, 229)); datas.Add(new DataPoint(2005, 210)); datas.Add(new DataPoint(2006, 337)); datas.Add(new DataPoint(2007, 258)); datas.Add(new DataPoint(2008, 300)); datas.Add(new DataPoint(2009, 173)); datas.Add(new DataPoint(2010, 220)); datas.Add(new DataPoint(2011, 309)); return datas; } public static List<DataPoint> GetStepAreaData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2006, 463)); datas.Add(new DataPoint(2007, 449)); datas.Add(new DataPoint(2008, 458)); datas.Add(new DataPoint(2009, 450)); datas.Add(new DataPoint(2010, 435)); datas.Add(new DataPoint(2011, 420)); return datas; } public static List<DataPoint> GetStripLineData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Sun", 26)); datas.Add(new DataPoint("Mon", 24)); datas.Add(new DataPoint("Tue", 31)); datas.Add(new DataPoint("Wed", 28)); datas.Add(new DataPoint("Thu", 30)); datas.Add(new DataPoint("Fri", 26)); datas.Add(new DataPoint("Sat", 30)); return datas; } public static List<DataPoint> GetData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 45)); datas.Add(new DataPoint("2011", 89)); datas.Add(new DataPoint("2012", 23)); datas.Add(new DataPoint("2013", 43)); datas.Add(new DataPoint("2014", 54)); return datas; } public static List<DataPoint> GetLogarithmicData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("1995", 80)); datas.Add(new DataPoint("1996", 200)); datas.Add(new DataPoint("1997", 400)); datas.Add(new DataPoint("1998", 600)); datas.Add(new DataPoint("1999", 700)); datas.Add(new DataPoint("2000", 1400)); datas.Add(new DataPoint("2001", 2000)); datas.Add(new DataPoint("2002", 4000)); datas.Add(new DataPoint("2003", 6000)); datas.Add(new DataPoint("2004", 8000)); datas.Add(new DataPoint("2005", 11000)); return datas; } public static List<DataPoint> GetLineData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2005", 21)); datas.Add(new DataPoint("2006", 24)); datas.Add(new DataPoint("2007", 36)); datas.Add(new DataPoint("2008", 38)); datas.Add(new DataPoint("2009", 54)); datas.Add(new DataPoint("2010", 57)); datas.Add(new DataPoint("2011", 70)); return datas; } public static List<DataPoint> GetLineData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2005", 28)); datas.Add(new DataPoint("2006", 44)); datas.Add(new DataPoint("2007", 48)); datas.Add(new DataPoint("2008", 50)); datas.Add(new DataPoint("2009", 66)); datas.Add(new DataPoint("2010", 78)); datas.Add(new DataPoint("2011", 84)); return datas; } public static List<DataPoint> GetStackingLineData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Food", 55)); datas.Add(new DataPoint("Transport", 33)); datas.Add(new DataPoint("Medical", 43)); datas.Add(new DataPoint("Clothes", 32)); datas.Add(new DataPoint("Books", 56)); datas.Add(new DataPoint("Others", 23)); return datas; } public static List<DataPoint> GetStackingLineData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Food", 40)); datas.Add(new DataPoint("Transport", 45)); datas.Add(new DataPoint("Medical", 23)); datas.Add(new DataPoint("Clothes", 54)); datas.Add(new DataPoint("Books", 18)); datas.Add(new DataPoint("Others", 54)); return datas; } public static List<DataPoint> GetStackingLineData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Food", 45)); datas.Add(new DataPoint("Transport", 54)); datas.Add(new DataPoint("Medical", 20)); datas.Add(new DataPoint("Clothes", 23)); datas.Add(new DataPoint("Books", 43)); datas.Add(new DataPoint("Others", 33)); return datas; } public static List<DataPoint> GetStackingLineData4() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Food", 48)); datas.Add(new DataPoint("Transport", 28)); datas.Add(new DataPoint("Medical", 34)); datas.Add(new DataPoint("Clothes", 84)); datas.Add(new DataPoint("Books", 55)); datas.Add(new DataPoint("Others", 56)); return datas; } public static List<DataPoint> GetColumnData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("USA", 46)); datas.Add(new DataPoint("GBR", 27)); datas.Add(new DataPoint("CHN", 26)); return datas; } public static List<DataPoint> GetErrorBarData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("IND", 23, 0.5, 1)); datas.Add(new DataPoint("AUS", 20, 0, 2)); datas.Add(new DataPoint("USA", 35, 1, 2)); datas.Add(new DataPoint("DEU", 28, 2, 0.5)); datas.Add(new DataPoint("ITA", 30, 1, 0)); datas.Add(new DataPoint("UK", 42, 1.5, 1)); datas.Add(new DataPoint("RUS", 27, 0.5, 2)); return datas; } public static List<DataPoint> BoxAndWhiskerData() { var BoxAndWhiskerData = new List<DataPoint>() { new DataPoint("Development", new List<double> { 22, 22, 23, 25, 25, 25, 26, 27, 27, 28, 28, 29, 30, 32, 34, 32, 34, 36, 35, 38 }), new DataPoint("Testing", new List<double> { 22, 33, 23, 25, 26, 28, 29, 30, 34, 33, 32, 31, 50 }), new DataPoint("HR", new List<double> { 22, 24, 25, 30, 32, 34, 36, 38, 39, 41, 35, 36, 40, 56 }), new DataPoint("Finance", new List<double> { 26, 27, 28, 30, 32, 34, 35, 37, 35, 37, 45 }), new DataPoint("Sales", new List<double> { 26, 27, 29, 32, 34, 35, 36, 37, 38, 39, 41, 43, 58 }), }; return BoxAndWhiskerData; } public static ObservableCollection<DataPoint> GetTrendlineDataSource1() { var yValue = new double[] { 10.11, 11.36, 12.34, 12.60, 12.95, 13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36, 41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41, 48.32, 45.65, 46.61, 53.34, 58.53, 59.02, 59.32, 61.24, 62.32, 62.43, 64.86, 63.42, 65.93, 66.99, 67.02, 68.43, 71.01 }; DateTime date = new DateTime(1977, 01, 01); var datas = new ObservableCollection<DataPoint>(); foreach (var y in yValue) { datas.Add(new DataPoint(date, y)); date = date.AddYears(1); } return datas; } public static ObservableCollection<DataPoint> GetTrendlineDataSource2() { var powerData = new ObservableCollection<DataPoint>(); powerData.Add(new DataPoint(1, 10)); powerData.Add(new DataPoint(2, 50)); powerData.Add(new DataPoint(3, 80)); powerData.Add(new DataPoint(4, 110)); powerData.Add(new DataPoint(5, 180)); powerData.Add(new DataPoint(6, 220)); powerData.Add(new DataPoint(7, 300)); powerData.Add(new DataPoint(8, 370)); powerData.Add(new DataPoint(9, 490)); powerData.Add(new DataPoint(10, 500)); return powerData; } public static List<DataPoint> GetColumnData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("USA", 37)); datas.Add(new DataPoint("GBR", 23)); datas.Add(new DataPoint("CHN", 18)); return datas; } public static List<DataPoint> GetColumnData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("USA", 38)); datas.Add(new DataPoint("GBR", 17)); datas.Add(new DataPoint("CHN", 26)); return datas; } public static List<DataPoint> GetHistogramData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(0, 5.250)); datas.Add(new DataPoint(0, 7.750)); datas.Add(new DataPoint(0, 0)); datas.Add(new DataPoint(0, 8.275)); datas.Add(new DataPoint(0, 9.750)); datas.Add(new DataPoint(0, 7.750)); datas.Add(new DataPoint(0, 8.275)); datas.Add(new DataPoint(0, 6.250)); datas.Add(new DataPoint(0, 5.750)); datas.Add(new DataPoint(0, 5.250)); datas.Add(new DataPoint(0, 23.000)); datas.Add(new DataPoint(0, 26.500)); datas.Add(new DataPoint(0, 27.750)); datas.Add(new DataPoint(0, 25.025)); datas.Add(new DataPoint(0, 26.500)); datas.Add(new DataPoint(0, 26.500)); datas.Add(new DataPoint(0, 28.025)); datas.Add(new DataPoint(0, 29.250)); datas.Add(new DataPoint(0, 26.750)); datas.Add(new DataPoint(0, 27.250)); datas.Add(new DataPoint(0, 26.250)); datas.Add(new DataPoint(0, 25.250)); datas.Add(new DataPoint(0, 34.500)); datas.Add(new DataPoint(0, 25.625)); datas.Add(new DataPoint(0, 25.500)); datas.Add(new DataPoint(0, 26.625)); datas.Add(new DataPoint(0, 36.275)); datas.Add(new DataPoint(0, 36.250)); datas.Add(new DataPoint(0, 26.875)); datas.Add(new DataPoint(0, 45.000)); datas.Add(new DataPoint(0, 43.000)); datas.Add(new DataPoint(0, 46.500)); datas.Add(new DataPoint(0, 47.750)); datas.Add(new DataPoint(0, 45.025)); datas.Add(new DataPoint(0, 56.500)); datas.Add(new DataPoint(0, 56.500)); datas.Add(new DataPoint(0, 58.025)); datas.Add(new DataPoint(0, 59.250)); datas.Add(new DataPoint(0, 56.750)); datas.Add(new DataPoint(0, 57.250)); datas.Add(new DataPoint(0, 46.250)); datas.Add(new DataPoint(0, 55.250)); datas.Add(new DataPoint(0, 44.500)); datas.Add(new DataPoint(0, 45.500)); datas.Add(new DataPoint(0, 55.500)); datas.Add(new DataPoint(0, 45.625)); datas.Add(new DataPoint(0, 55.500)); datas.Add(new DataPoint(0, 56.250)); datas.Add(new DataPoint(0, 46.875)); datas.Add(new DataPoint(0, 43.000)); datas.Add(new DataPoint(0, 46.250)); datas.Add(new DataPoint(0, 55.250)); datas.Add(new DataPoint(0, 44.500)); datas.Add(new DataPoint(0, 45.425)); datas.Add(new DataPoint(0, 56.625)); datas.Add(new DataPoint(0, 46.275)); datas.Add(new DataPoint(0, 56.250)); datas.Add(new DataPoint(0, 46.875)); datas.Add(new DataPoint(0, 43.000)); datas.Add(new DataPoint(0, 46.250)); datas.Add(new DataPoint(0, 55.250)); datas.Add(new DataPoint(0, 44.500)); datas.Add(new DataPoint(0, 45.425)); datas.Add(new DataPoint(0, 55.500)); datas.Add(new DataPoint(0, 46.625)); datas.Add(new DataPoint(0, 56.275)); datas.Add(new DataPoint(0, 46.250)); datas.Add(new DataPoint(0, 56.250)); datas.Add(new DataPoint(0, 42.000)); datas.Add(new DataPoint(0, 41.000)); datas.Add(new DataPoint(0, 63.000)); datas.Add(new DataPoint(0, 66.500)); datas.Add(new DataPoint(0, 67.750)); datas.Add(new DataPoint(0, 65.025)); datas.Add(new DataPoint(0, 66.500)); datas.Add(new DataPoint(0, 76.500)); datas.Add(new DataPoint(0, 78.025)); datas.Add(new DataPoint(0, 79.250)); datas.Add(new DataPoint(0, 76.750)); datas.Add(new DataPoint(0, 77.250)); datas.Add(new DataPoint(0, 66.250)); datas.Add(new DataPoint(0, 75.250)); datas.Add(new DataPoint(0, 74.500)); datas.Add(new DataPoint(0, 65.625)); datas.Add(new DataPoint(0, 75.500)); datas.Add(new DataPoint(0, 76.625)); datas.Add(new DataPoint(0, 76.275)); datas.Add(new DataPoint(0, 66.250)); datas.Add(new DataPoint(0, 66.875)); datas.Add(new DataPoint(0, 82.000)); datas.Add(new DataPoint(0, 85.250)); datas.Add(new DataPoint(0, 87.750)); datas.Add(new DataPoint(0, 92.000)); datas.Add(new DataPoint(0, 85.250)); datas.Add(new DataPoint(0, 87.750)); datas.Add(new DataPoint(0, 89.000)); datas.Add(new DataPoint(0, 88.275)); datas.Add(new DataPoint(0, 89.750)); datas.Add(new DataPoint(0, 95.750)); datas.Add(new DataPoint(0, 95.250)); return datas; } public static List<DataPoint> GetBarData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Egg", 2.2)); datas.Add(new DataPoint("Fish", 2.4)); datas.Add(new DataPoint("Misc", 3)); datas.Add(new DataPoint("Tea", 3.1)); return datas; } public static List<DataPoint> GetBarData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Egg", 1.2)); datas.Add(new DataPoint("Fish", 1.3)); datas.Add(new DataPoint("Misc", 1.5)); datas.Add(new DataPoint("Tea", 2.2)); return datas; } public static List<DataPoint> GetAreaData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2000, 4)); datas.Add(new DataPoint(2001, 3.0)); datas.Add(new DataPoint(2002, 3.8)); datas.Add(new DataPoint(2003, 4.4)); datas.Add(new DataPoint(2004, 3.2)); datas.Add(new DataPoint(2005, 3.9)); return datas; } public static List<DataPoint> GetAreaData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2000, 2.6)); datas.Add(new DataPoint(2001, 2.8)); datas.Add(new DataPoint(2002, 2.6)); datas.Add(new DataPoint(2003, 3)); datas.Add(new DataPoint(2004, 3.6)); datas.Add(new DataPoint(2005, 3)); return datas; } public static List<DataPoint> GetAreaData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(1900, 2.8)); datas.Add(new DataPoint(1920, 2.5)); datas.Add(new DataPoint(1940, 2.8)); datas.Add(new DataPoint(1960, 3.0)); datas.Add(new DataPoint(1980, 2.9)); datas.Add(new DataPoint(2000, 2.0)); return datas; } public static List<DataPoint> GetSplineAreaData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2002, 2.2)); datas.Add(new DataPoint(2003, 3.4)); datas.Add(new DataPoint(2004, 2.8)); datas.Add(new DataPoint(2005, 1.6)); datas.Add(new DataPoint(2006, 2.3)); datas.Add(new DataPoint(2007, 2.5)); datas.Add(new DataPoint(2008, 2.9)); datas.Add(new DataPoint(2009, 3.8)); datas.Add(new DataPoint(2010, 1.4)); datas.Add(new DataPoint(2011, 3.1)); return datas; } public static List<DataPoint> GetSplineAreaData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2002, 2.0)); datas.Add(new DataPoint(2003, 1.7)); datas.Add(new DataPoint(2004, 1.8)); datas.Add(new DataPoint(2005, 2.1)); datas.Add(new DataPoint(2006, 2.3)); datas.Add(new DataPoint(2007, 1.7)); datas.Add(new DataPoint(2008, 1.5)); datas.Add(new DataPoint(2009, 2.8)); datas.Add(new DataPoint(2010, 1.5)); datas.Add(new DataPoint(2011, 2.3)); return datas; } public static List<DataPoint> GetSplineAreaData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2002, 0.8)); datas.Add(new DataPoint(2003, 1.3)); datas.Add(new DataPoint(2004, 1.1)); datas.Add(new DataPoint(2005, 1.6)); datas.Add(new DataPoint(2006, 2.0)); datas.Add(new DataPoint(2007, 1.7)); datas.Add(new DataPoint(2008, 2.3)); datas.Add(new DataPoint(2009, 2.7)); datas.Add(new DataPoint(2010, 1.1)); datas.Add(new DataPoint(2011, 2.3)); return datas; } public static List<DataPoint> GetSplineData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Sun", 15)); datas.Add(new DataPoint("Mon", 22)); datas.Add(new DataPoint("Tue", 32)); datas.Add(new DataPoint("Wed", 31)); datas.Add(new DataPoint("Thu", 29)); datas.Add(new DataPoint("Fri", 26)); datas.Add(new DataPoint("Sat", 18)); return datas; } public static List<DataPoint> GetSplineData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Sun", 10)); datas.Add(new DataPoint("Mon", 18)); datas.Add(new DataPoint("Tue", 28)); datas.Add(new DataPoint("Wed", 28)); datas.Add(new DataPoint("Thu", 26)); datas.Add(new DataPoint("Fri", 20)); datas.Add(new DataPoint("Sat", 15)); return datas; } public static List<DataPoint> GetSplineData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Sun", 2)); datas.Add(new DataPoint("Mon", 12)); datas.Add(new DataPoint("Tue", 22)); datas.Add(new DataPoint("Wed", 23)); datas.Add(new DataPoint("Thu", 19)); datas.Add(new DataPoint("Fri", 13)); datas.Add(new DataPoint("Sat", 8)); return datas; } public static List<DataPoint> GetRangeColumnData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Sun", 10.8, 3.1)); datas.Add(new DataPoint("Mon", 14.4, 5.7)); datas.Add(new DataPoint("Tue", 16.9, 8.4)); datas.Add(new DataPoint("Wed", 19.2, 10.6)); datas.Add(new DataPoint("Thu", 16.1, 8.5)); datas.Add(new DataPoint("Fri", 12.5, 6.0)); datas.Add(new DataPoint("Sat", 6.9, 1.5)); return datas; } public static List<DataPoint> GetRangeColumnData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Sun", 9.8, 2.5)); datas.Add(new DataPoint("Mon", 11.4, 4.7)); datas.Add(new DataPoint("Tue", 14.4, 6.4)); datas.Add(new DataPoint("Wed", 17.2, 9.6)); datas.Add(new DataPoint("Thu", 15.1, 7.5)); datas.Add(new DataPoint("Fri", 10.5, 3.0)); datas.Add(new DataPoint("Sat", 7.9, 1.2)); return datas; } public static List<DataPoint> GetRangeBarData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jumbo", 70238)); datas.Add(new DataPoint("FHA", 99595)); datas.Add(new DataPoint("VA", 156398)); datas.Add(new DataPoint("USDA", 256396)); datas.Add(new DataPoint("Const", 356398)); datas.Add(new DataPoint("Total", 459937)); return datas; } public static List<DataPoint> GetRangeArea() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan/10", 45, 32)); datas.Add(new DataPoint("Feb/10", 48, 34)); datas.Add(new DataPoint("Mar/10", 46, 32)); datas.Add(new DataPoint("Apr/10", 48, 36)); datas.Add(new DataPoint("May/10", 46, 32)); datas.Add(new DataPoint("Jun/10", 49, 34)); return datas; } public static List<DataPoint> GetRangeArea1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan/10", 30, 18)); datas.Add(new DataPoint("Feb/10", 24, 12)); datas.Add(new DataPoint("Mar/10", 29, 15)); datas.Add(new DataPoint("Apr/10", 24, 10)); datas.Add(new DataPoint("May/10", 30, 18)); datas.Add(new DataPoint("Jun/10", 24, 10)); return datas; } public static List<DataPoint> GetSplineRangeArea1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", 45, 32)); datas.Add(new DataPoint("Feb", 48, 34)); datas.Add(new DataPoint("Mar", 46, 32)); datas.Add(new DataPoint("Apr", 48, 36)); datas.Add(new DataPoint("May", 46, 32)); datas.Add(new DataPoint("Jun", 49, 34)); return datas; } public static List<DataPoint> GetSplineRangeArea2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", 30, 18)); datas.Add(new DataPoint("Feb", 24, 12)); datas.Add(new DataPoint("Mar", 29, 15)); datas.Add(new DataPoint("Apr", 24, 10)); datas.Add(new DataPoint("May", 30, 18)); datas.Add(new DataPoint("Jun", 24, 10)); return datas; } public static List<DataPoint> GetStepLineData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(1975, 16)); datas.Add(new DataPoint(1980, 12.5)); datas.Add(new DataPoint(1985, 19)); datas.Add(new DataPoint(1990, 14.4)); datas.Add(new DataPoint(1995, 11.5)); datas.Add(new DataPoint(2000, 14)); datas.Add(new DataPoint(2005, 10)); datas.Add(new DataPoint(2010, 16)); return datas; } public static List<DataPoint> GetStepLineData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(1975, 10)); datas.Add(new DataPoint(1980, 7.5)); datas.Add(new DataPoint(1985, 11)); datas.Add(new DataPoint(1990, 7)); datas.Add(new DataPoint(1995, 8)); datas.Add(new DataPoint(2000, 6)); datas.Add(new DataPoint(2005, 3.5)); datas.Add(new DataPoint(2010, 7)); return datas; } public static List<DataPoint> GetStepLineData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2006, 570)); datas.Add(new DataPoint(2007, 579)); datas.Add(new DataPoint(2008, 563)); datas.Add(new DataPoint(2009, 550)); datas.Add(new DataPoint(2010, 545)); datas.Add(new DataPoint(2011, 525)); return datas; } public static List<DataPoint> GetStepLineData4() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(2006, 570)); datas.Add(new DataPoint(2007, 579)); datas.Add(new DataPoint(2008, 563)); datas.Add(new DataPoint(2009, 550)); datas.Add(new DataPoint(2010, 545)); datas.Add(new DataPoint(2011, 525)); return datas; } public static List<DataPoint> GetPieData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("David", 30)); datas.Add(new DataPoint("Steve", 35)); datas.Add(new DataPoint("Micheal", 24)); datas.Add(new DataPoint("John", 11)); datas.Add(new DataPoint("Regev", 25)); datas.Add(new DataPoint("Jack", 39)); datas.Add(new DataPoint("Stephen", 15)); return datas; } public static List<DataPoint> GetDoughnutData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Labour", 10)); datas.Add(new DataPoint("Legal", 8)); datas.Add(new DataPoint("Production", 7)); datas.Add(new DataPoint("License", 5)); datas.Add(new DataPoint("Facilities", 10)); datas.Add(new DataPoint("Taxes", 6)); datas.Add(new DataPoint("Insurance", 18)); return datas; } public static List<MultipleCircleModel> GetStackedDoughnutData() { var datas = new List<MultipleCircleModel>(); datas.Add(new MultipleCircleModel("Vehicle", 62.7, Resource.Drawable.Car)); datas.Add(new MultipleCircleModel("Education", 29.5, Resource.Drawable.Chart_Book)); datas.Add(new MultipleCircleModel("Home", 85.2, Resource.Drawable.House)); datas.Add(new MultipleCircleModel("Personal", 45.6, Resource.Drawable.Personal)); return datas; } public static List<DataPoint> GetPyramidData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Sweet Treats", 120)); datas.Add(new DataPoint("Milk, Youghnut, Cheese", 435)); datas.Add(new DataPoint("Vegetables", 470)); datas.Add(new DataPoint("Meat, Poultry, Fish", 475)); datas.Add(new DataPoint("Fruits", 520)); datas.Add(new DataPoint("Bread, Rice, Pasta", 930)); return datas; } public static List<DataPoint> GetFunnelData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Renewed", 18.2)); datas.Add(new DataPoint("Subscribe", 27.3)); datas.Add(new DataPoint("Support", 55.9)); datas.Add(new DataPoint("Downloaded", 76.8)); datas.Add(new DataPoint("Visited", 100)); return datas; } public static List<DataPoint> GetBubbleData() { var data = new List<DataPoint>(); data.Add(new DataPoint(92.2, 7.8, 1.347, "China")); data.Add(new DataPoint(74, 6.5, 1.241, "India")); data.Add(new DataPoint(90.4, 6.0, 0.238, "Indonesia")); data.Add(new DataPoint(99.4, 2.2, 0.312, "US")); data.Add(new DataPoint(88.6, 1.3, 0.197, "Brazil")); data.Add(new DataPoint(99, 0.7, 0.0818, "Germany")); data.Add(new DataPoint(72, 2.0, 0.0826, "Egypt")); data.Add(new DataPoint(99.6, 3.4, 0.143, "Russia")); data.Add(new DataPoint(99, 0.2, 0.128, "Japan")); data.Add(new DataPoint(86.1, 4.0, 0.115, "Mexico")); data.Add(new DataPoint(92.6, 6.6, 0.096, "Philippines")); data.Add(new DataPoint(61.3, 1.45, 0.162, "Nigeria")); data.Add(new DataPoint(82.2, 3.97, 0.7, "Hong Kong")); data.Add(new DataPoint(79.2, 3.9, 0.162, "Netherland")); data.Add(new DataPoint(72.5, 4.5, 0.7, "Jordan")); data.Add(new DataPoint(81, 3.5, 0.21, "Australia")); data.Add(new DataPoint(66.8, 3.9, 0.028, "Mongolia")); data.Add(new DataPoint(79.2, 2.9, 0.231, "Taiwan")); return data; } public static List<DataPoint> GetCandleData() { var dateTime = new DateTime(2000, 1, 1); var datas = new List<DataPoint>(); datas.Add(new DataPoint(dateTime, 90, 125, 70, 115)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 120, 150, 60, 70)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 190, 200, 140, 160)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 110, 160, 90, 140)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 120, 200, 100, 180)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 70, 100, 45, 50)); return datas; } public static List<DataPoint> GetOhlcData() { var dateTime = new DateTime(2000, 1, 1); var datas = new List<DataPoint>(); datas.Add(new DataPoint(dateTime, 115, 125, 70, 90)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 120, 150, 60, 70)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 160, 200, 140, 190)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 140, 160, 90, 110)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 180, 200, 100, 120)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 70, 100, 45, 50)); return datas; } public static List<DataPoint> GetStackedAreaData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 0.61)); datas.Add(new DataPoint("2001", 0.81)); datas.Add(new DataPoint("2002", 0.91)); datas.Add(new DataPoint("2003", 1)); datas.Add(new DataPoint("2004", 1.19)); datas.Add(new DataPoint("2005", 1.47)); datas.Add(new DataPoint("2006", 1.74)); datas.Add(new DataPoint("2007", 1.98)); datas.Add(new DataPoint("2008", 1.99)); datas.Add(new DataPoint("2009", 1.70)); datas.Add(new DataPoint("2010", 1.48)); datas.Add(new DataPoint("2011", 1.38)); datas.Add(new DataPoint("2012", 1.66)); datas.Add(new DataPoint("2013", 1.66)); datas.Add(new DataPoint("2014", 1.67)); return datas; } public static List<DataPoint> GetStackedAreaData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 0.03)); datas.Add(new DataPoint("2001", 0.05)); datas.Add(new DataPoint("2002", 0.06)); datas.Add(new DataPoint("2003", 0.09)); datas.Add(new DataPoint("2004", 0.14)); datas.Add(new DataPoint("2005", 0.20)); datas.Add(new DataPoint("2006", 0.29)); datas.Add(new DataPoint("2007", 0.46)); datas.Add(new DataPoint("2008", 0.64)); datas.Add(new DataPoint("2009", 0.75)); datas.Add(new DataPoint("2010", 1.06)); datas.Add(new DataPoint("2011", 1.25)); datas.Add(new DataPoint("2012", 1.55)); datas.Add(new DataPoint("2013", 1.55)); datas.Add(new DataPoint("2014", 1.65)); return datas; } public static List<DataPoint> GetStackedAreaData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 0.48)); datas.Add(new DataPoint("2001", 0.53)); datas.Add(new DataPoint("2002", 0.57)); datas.Add(new DataPoint("2003", 0.61)); datas.Add(new DataPoint("2004", 0.63)); datas.Add(new DataPoint("2005", 0.64)); datas.Add(new DataPoint("2006", 0.66)); datas.Add(new DataPoint("2007", 0.76)); datas.Add(new DataPoint("2008", 0.77)); datas.Add(new DataPoint("2009", 0.55)); datas.Add(new DataPoint("2010", 0.54)); datas.Add(new DataPoint("2011", 0.57)); datas.Add(new DataPoint("2012", 0.61)); datas.Add(new DataPoint("2013", 0.67)); datas.Add(new DataPoint("2014", 0.67)); return datas; } public static List<DataPoint> GetStackedAreaData4() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 0.23)); datas.Add(new DataPoint("2001", 0.17)); datas.Add(new DataPoint("2002", 0.17)); datas.Add(new DataPoint("2003", 0.20)); datas.Add(new DataPoint("2004", 0.23)); datas.Add(new DataPoint("2005", 0.36)); datas.Add(new DataPoint("2006", 0.43)); datas.Add(new DataPoint("2007", 0.52)); datas.Add(new DataPoint("2008", 0.72)); datas.Add(new DataPoint("2009", 1.29)); datas.Add(new DataPoint("2010", 1.38)); datas.Add(new DataPoint("2011", 1.82)); datas.Add(new DataPoint("2012", 2.16)); datas.Add(new DataPoint("2013", 2.51)); datas.Add(new DataPoint("2014", 2.61)); return datas; } public static List<DataPoint> GetStackedArea100Data1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 0.61)); datas.Add(new DataPoint("2001", 0.81)); datas.Add(new DataPoint("2002", 0.91)); datas.Add(new DataPoint("2003", 1)); datas.Add(new DataPoint("2004", 1.19)); datas.Add(new DataPoint("2005", 1.47)); datas.Add(new DataPoint("2006", 1.74)); datas.Add(new DataPoint("2007", 1.98)); datas.Add(new DataPoint("2008", 1.99)); datas.Add(new DataPoint("2009", 1.70)); datas.Add(new DataPoint("2010", 1.48)); datas.Add(new DataPoint("2011", 1.38)); datas.Add(new DataPoint("2012", 1.66)); datas.Add(new DataPoint("2013", 1.66)); datas.Add(new DataPoint("2014", 1.67)); return datas; } public static List<DataPoint> GetStackedArea100Data2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 0.03)); datas.Add(new DataPoint("2001", 0.05)); datas.Add(new DataPoint("2002", 0.06)); datas.Add(new DataPoint("2003", 0.09)); datas.Add(new DataPoint("2004", 0.14)); datas.Add(new DataPoint("2005", 0.20)); datas.Add(new DataPoint("2006", 0.29)); datas.Add(new DataPoint("2007", 0.46)); datas.Add(new DataPoint("2008", 0.64)); datas.Add(new DataPoint("2009", 0.75)); datas.Add(new DataPoint("2010", 1.06)); datas.Add(new DataPoint("2011", 1.25)); datas.Add(new DataPoint("2012", 1.55)); datas.Add(new DataPoint("2013", 1.55)); datas.Add(new DataPoint("2014", 1.65)); return datas; } public static List<DataPoint> GetStackedArea100Data3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 0.48)); datas.Add(new DataPoint("2001", 0.53)); datas.Add(new DataPoint("2002", 0.57)); datas.Add(new DataPoint("2003", 0.61)); datas.Add(new DataPoint("2004", 0.63)); datas.Add(new DataPoint("2005", 0.64)); datas.Add(new DataPoint("2006", 0.66)); datas.Add(new DataPoint("2007", 0.76)); datas.Add(new DataPoint("2008", 0.77)); datas.Add(new DataPoint("2009", 0.55)); datas.Add(new DataPoint("2010", 0.54)); datas.Add(new DataPoint("2011", 0.57)); datas.Add(new DataPoint("2012", 0.61)); datas.Add(new DataPoint("2013", 0.67)); datas.Add(new DataPoint("2014", 0.67)); return datas; } public static List<DataPoint> GetStackedArea100Data4() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 0.23)); datas.Add(new DataPoint("2001", 0.17)); datas.Add(new DataPoint("2002", 0.17)); datas.Add(new DataPoint("2003", 0.20)); datas.Add(new DataPoint("2004", 0.23)); datas.Add(new DataPoint("2005", 0.36)); datas.Add(new DataPoint("2006", 0.43)); datas.Add(new DataPoint("2007", 0.52)); datas.Add(new DataPoint("2008", 0.72)); datas.Add(new DataPoint("2009", 1.29)); datas.Add(new DataPoint("2010", 1.38)); datas.Add(new DataPoint("2011", 1.82)); datas.Add(new DataPoint("2012", 2.16)); datas.Add(new DataPoint("2013", 2.51)); datas.Add(new DataPoint("2014", 2.61)); return datas; } public static List<DataPoint> GetStackedBarData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", 6)); datas.Add(new DataPoint("Feb", 8)); datas.Add(new DataPoint("Mar", 12)); datas.Add(new DataPoint("Apr", 15.5)); datas.Add(new DataPoint("May", 20)); datas.Add(new DataPoint("Jun", 24)); return datas; } public static List<DataPoint> GetStackedBarData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", 6)); datas.Add(new DataPoint("Feb", 8)); datas.Add(new DataPoint("Mar", 11)); datas.Add(new DataPoint("Apr", 16)); datas.Add(new DataPoint("May", 21)); datas.Add(new DataPoint("Jun", 25)); return datas; } public static List<DataPoint> GetStackedBarData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", -1)); datas.Add(new DataPoint("Feb", -1.5)); datas.Add(new DataPoint("Mar", -2)); datas.Add(new DataPoint("Apr", -2.5)); datas.Add(new DataPoint("May", -3)); datas.Add(new DataPoint("Jun", -3.5)); return datas; } public static List<DataPoint> GetStackedBar100Data1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", 6)); datas.Add(new DataPoint("Feb", 8)); datas.Add(new DataPoint("Mar", 12)); datas.Add(new DataPoint("Apr", 15)); datas.Add(new DataPoint("May", 20)); datas.Add(new DataPoint("Jun", 24)); return datas; } public static List<DataPoint> GetStackedBar100Data2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", 6)); datas.Add(new DataPoint("Feb", 8)); datas.Add(new DataPoint("Mar", 11)); datas.Add(new DataPoint("Apr", 16)); datas.Add(new DataPoint("May", 21)); datas.Add(new DataPoint("Jun", 25)); return datas; } public static List<DataPoint> GetStackedBar100Data3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", 1)); datas.Add(new DataPoint("Feb", 1.5)); datas.Add(new DataPoint("Mar", 2)); datas.Add(new DataPoint("Apr", 2.5)); datas.Add(new DataPoint("May", 3)); datas.Add(new DataPoint("Jun", 3.5)); return datas; } public static List<DataPoint> GetStackedColumnData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2014", 111.1)); datas.Add(new DataPoint("2015", 127.3)); datas.Add(new DataPoint("2016", 143.4)); datas.Add(new DataPoint("2017", 159.9)); return datas; } public static List<DataPoint> GetStackedColumnData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2014", 76.9)); datas.Add(new DataPoint("2015", 99.5)); datas.Add(new DataPoint("2016", 121.7)); datas.Add(new DataPoint("2017", 142.5)); return datas; } public static List<DataPoint> GetStackedColumnData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2014", 66.1)); datas.Add(new DataPoint("2015", 79.3)); datas.Add(new DataPoint("2016", 91.3)); datas.Add(new DataPoint("2017", 102.4)); return datas; } public static List<DataPoint> GetStackedColumnData4() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2014", 34.1)); datas.Add(new DataPoint("2015", 38.2)); datas.Add(new DataPoint("2016", 44.0)); datas.Add(new DataPoint("2017", 51.6)); return datas; } public static List<DataPoint> GetStackedColumn100Data1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2006", 900)); datas.Add(new DataPoint("2007", 544)); datas.Add(new DataPoint("2008", 880)); datas.Add(new DataPoint("2009", 675)); return datas; } public static List<DataPoint> GetStackedColumn100Data2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2006", 190)); datas.Add(new DataPoint("2007", 226)); datas.Add(new DataPoint("2008", 194)); datas.Add(new DataPoint("2009", 250)); return datas; } public static List<DataPoint> GetStackedColumn100Data3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2006", 250)); datas.Add(new DataPoint("2007", 145)); datas.Add(new DataPoint("2008", 190)); datas.Add(new DataPoint("2009", 220)); return datas; } public static List<DataPoint> GetStackedColumn100Data4() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2006", 150)); datas.Add(new DataPoint("2007", 120)); datas.Add(new DataPoint("2008", 115)); datas.Add(new DataPoint("2009", 125)); return datas; } public static List<DataPoint> GetStackedLine100Data1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Food", 36)); datas.Add(new DataPoint("Transport", 18)); datas.Add(new DataPoint("Medical", 43)); datas.Add(new DataPoint("Clothes", 32)); datas.Add(new DataPoint("Books", 56)); datas.Add(new DataPoint("Others", 23)); return datas; } public static List<DataPoint> GetStackedLine100Data2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Food", 40)); datas.Add(new DataPoint("Transport", 45)); datas.Add(new DataPoint("Medical", 23)); datas.Add(new DataPoint("Clothes", 54)); datas.Add(new DataPoint("Books", 48)); datas.Add(new DataPoint("Others", 54)); return datas; } public static List<DataPoint> GetStackedLine100Data3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Food", 45)); datas.Add(new DataPoint("Transport", 54)); datas.Add(new DataPoint("Medical", 20)); datas.Add(new DataPoint("Clothes", 73)); datas.Add(new DataPoint("Books", 93)); datas.Add(new DataPoint("Others", 54)); return datas; } public static List<DataPoint> GetStackedLine100Data4() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Food", 48)); datas.Add(new DataPoint("Transport", 28)); datas.Add(new DataPoint("Medical", 34)); datas.Add(new DataPoint("Clothes", 84)); datas.Add(new DataPoint("Books", 55)); datas.Add(new DataPoint("Others", 56)); return datas; } public static List<DataPoint> GetScatterMaleData() { var datas = new List<DataPoint>() { new DataPoint( 161, 65 ), new DataPoint( 150, 65 ), new DataPoint(155, 65 ), new DataPoint(160, 65 ), new DataPoint( 148, 66 ), new DataPoint( 145, 66 ), new DataPoint(137, 66 ), new DataPoint(138, 66 ), new DataPoint( 162, 66 ), new DataPoint( 166, 66 ), new DataPoint(159, 66 ), new DataPoint(151, 66 ), new DataPoint( 180, 66 ), new DataPoint( 181, 66 ), new DataPoint(174, 66 ), new DataPoint(159, 66 ), new DataPoint( 151, 67 ), new DataPoint( 148, 67 ), new DataPoint(141, 67 ), new DataPoint(145, 67 ), new DataPoint( 165, 67 ), new DataPoint( 168, 67 ), new DataPoint(159, 67 ), new DataPoint(183, 67 ), new DataPoint( 188, 67 ), new DataPoint( 187, 67 ), new DataPoint(172, 67 ), new DataPoint(193, 67 ), new DataPoint( 153, 68 ), new DataPoint( 153, 68 ), new DataPoint(147, 68 ), new DataPoint(163, 68 ), new DataPoint( 174, 68 ), new DataPoint( 173, 68 ), new DataPoint(160, 68 ), new DataPoint(191, 68 ), new DataPoint( 131, 62 ), new DataPoint( 140, 62 ), new DataPoint(149, 62 ), new DataPoint(115, 62 ), new DataPoint( 164, 63 ), new DataPoint( 162, 63 ), new DataPoint(167, 63 ), new DataPoint(146, 63 ), new DataPoint( 150, 64 ), new DataPoint( 141, 64 ), new DataPoint(142, 64 ), new DataPoint(129, 64 ), new DataPoint( 159, 64 ), new DataPoint( 158, 64 ), new DataPoint(162, 64 ), new DataPoint(136, 64 ), new DataPoint( 176, 64 ), new DataPoint( 170, 64 ), new DataPoint(167, 64 ), new DataPoint(144, 64 ), new DataPoint( 143, 65 ), new DataPoint( 137, 65 ), new DataPoint(137, 65 ), new DataPoint(140, 65 ), new DataPoint( 182, 65 ), new DataPoint( 168, 65 ), new DataPoint(181, 65 ), new DataPoint(165, 65 ), new DataPoint( 214, 74 ), new DataPoint( 211, 74 ), new DataPoint(166, 74 ), new DataPoint(185, 74 ), new DataPoint( 189, 68 ), new DataPoint( 182, 68 ), new DataPoint(181, 68 ), new DataPoint(196, 68 ), new DataPoint( 152, 69 ), new DataPoint( 173, 69 ), new DataPoint(190, 69 ), new DataPoint(161, 69 ), new DataPoint( 173, 69 ), new DataPoint( 185, 69 ), new DataPoint(141, 69 ), new DataPoint(149, 69 ), new DataPoint( 134, 62 ), new DataPoint( 183, 62 ), new DataPoint(155, 62 ), new DataPoint(164, 62 ), new DataPoint( 169, 62 ), new DataPoint( 122, 62 ), new DataPoint(161, 62 ), new DataPoint(166, 62 ), new DataPoint( 137, 63 ), new DataPoint( 140, 63 ), new DataPoint(140, 63 ), new DataPoint(126, 63 ), new DataPoint( 150, 63 ), new DataPoint( 153, 63 ), new DataPoint(154, 63 ), new DataPoint(139, 63 ), new DataPoint( 186, 69 ), new DataPoint( 188, 69 ), new DataPoint(148, 69 ), new DataPoint(174, 69 ), new DataPoint( 164, 70 ), new DataPoint( 182, 70 ), new DataPoint(200, 70 ), new DataPoint(151, 70 ), new DataPoint( 204, 74 ), new DataPoint( 177, 74 ), new DataPoint(194, 74 ), new DataPoint(212, 74 ), new DataPoint( 162, 70 ), new DataPoint( 200, 70 ), new DataPoint(166, 70 ), new DataPoint(177, 70 ), new DataPoint( 188, 70 ), new DataPoint( 156, 70 ), new DataPoint(175, 70 ), new DataPoint(191, 70 ), new DataPoint( 174, 71 ), new DataPoint( 187, 71 ), new DataPoint(208, 71 ), new DataPoint(166, 71 ), new DataPoint( 150, 71 ), new DataPoint( 194, 71 ), new DataPoint(157, 71 ), new DataPoint(183, 71 ), new DataPoint( 204, 71 ), new DataPoint( 162, 71 ), new DataPoint(179, 71 ), new DataPoint(196, 71 ), new DataPoint( 170, 72 ), new DataPoint( 184, 72 ), new DataPoint(197, 72 ), new DataPoint(162, 72 ), new DataPoint( 177, 72 ), new DataPoint( 203, 72 ), new DataPoint(159, 72 ), new DataPoint(178, 72 ), new DataPoint( 198, 72 ), new DataPoint( 167, 72 ), new DataPoint(184, 72 ), new DataPoint(201, 72 ), new DataPoint( 167, 73 ), new DataPoint( 178, 73 ), new DataPoint(215, 73 ), new DataPoint(207, 73 ), new DataPoint( 172, 73 ), new DataPoint( 204, 73 ), new DataPoint(162, 73 ), new DataPoint(182, 73 ), new DataPoint( 201, 73 ), new DataPoint( 172, 73 ), new DataPoint(189, 73 ), new DataPoint(206, 73 ), new DataPoint( 150, 74 ), new DataPoint( 187, 74 ), new DataPoint(153, 74 ), new DataPoint(171, 74 ), }; return datas; } public static List<DataPoint> GetScatterFemaleData() { var datas = new List<DataPoint>() { new DataPoint(115, 57 ), new DataPoint(138, 57 ), new DataPoint(166, 57 ), new DataPoint(122, 57 ), new DataPoint(126, 57 ), new DataPoint(130, 57 ), new DataPoint(125, 57 ), new DataPoint(144, 57 ), new DataPoint(150, 57 ), new DataPoint(120, 57 ), new DataPoint(125, 57 ), new DataPoint(130, 57 ), new DataPoint(103, 58 ), new DataPoint(116, 58 ), new DataPoint(130, 58 ), new DataPoint(126, 58 ), new DataPoint(136, 58 ), new DataPoint(148, 58 ), new DataPoint(119, 58 ), new DataPoint(141, 58 ), new DataPoint(159, 58 ), new DataPoint(120, 58 ), new DataPoint(135, 58 ), new DataPoint(163, 58 ), new DataPoint(119, 59 ), new DataPoint(131, 59 ), new DataPoint(148, 59 ), new DataPoint(123, 59 ), new DataPoint(137, 59 ), new DataPoint(149, 59 ), new DataPoint(121, 59 ), new DataPoint(142, 59 ), new DataPoint(160, 59 ), new DataPoint(118, 59 ), new DataPoint(130, 59 ), new DataPoint(146, 59 ), new DataPoint(119, 60 ), new DataPoint(133, 60 ), new DataPoint(150, 60 ), new DataPoint(133, 60 ), new DataPoint(149, 60 ), new DataPoint(165, 60 ), new DataPoint(130, 60 ), new DataPoint(139, 60 ), new DataPoint(154, 60 ), new DataPoint(118, 60 ), new DataPoint(152, 60 ), new DataPoint(154, 60 ), new DataPoint(130, 61 ), new DataPoint(145, 61 ), new DataPoint(166, 61 ), new DataPoint(131, 61 ), new DataPoint(143, 61 ), new DataPoint(162, 61 ), new DataPoint(131, 61 ), new DataPoint(145, 61 ), new DataPoint(162, 61 ), new DataPoint(115, 61 ), new DataPoint(149, 61 ), new DataPoint(183, 61 ), new DataPoint(121, 62 ), new DataPoint(139, 62 ), new DataPoint(159, 62 ), new DataPoint(135, 62 ), new DataPoint(152, 62 ), new DataPoint(178, 62 ), new DataPoint(130, 62 ), new DataPoint(153, 62 ), new DataPoint(172, 62 ), new DataPoint(114, 62 ), new DataPoint(135, 62 ), new DataPoint(154, 62 ), new DataPoint(126, 63 ), new DataPoint(141, 63 ), new DataPoint(160, 63 ), new DataPoint(135, 63 ), new DataPoint(149, 63 ), new DataPoint(180, 63 ), new DataPoint(132, 63 ), new DataPoint(144, 63 ), new DataPoint(163, 63 ), new DataPoint(122, 63 ), new DataPoint(146, 63 ), new DataPoint(156, 63 ), new DataPoint(133, 64 ), new DataPoint(150, 64 ), new DataPoint(176, 64 ), new DataPoint(133, 64 ), new DataPoint(149, 64 ), new DataPoint(176, 64 ), new DataPoint(136, 64 ), new DataPoint(157, 64 ), new DataPoint(174, 64 ), new DataPoint(131, 64 ), new DataPoint(155, 64 ), new DataPoint(191, 64 ), new DataPoint(136, 65 ), new DataPoint(149, 65 ), new DataPoint(177, 65 ), new DataPoint(143, 65 ), new DataPoint(149, 65 ), new DataPoint(184, 65 ), new DataPoint(128, 65 ), new DataPoint(146, 65 ), new DataPoint(157, 65 ), new DataPoint(133, 65 ), new DataPoint(153, 65 ), new DataPoint(173, 65 ), new DataPoint(141, 66 ), new DataPoint(156, 66 ), new DataPoint(175, 66 ), new DataPoint(125, 66 ), new DataPoint(138, 66 ), new DataPoint(165, 66 ), new DataPoint(122, 66 ), new DataPoint(164, 66 ), new DataPoint(182, 66 ), new DataPoint(137, 66 ), new DataPoint(157, 66 ), new DataPoint(176, 66 ), new DataPoint(149, 67 ), new DataPoint(159, 67 ), new DataPoint(179, 67 ), new DataPoint(156, 67 ), new DataPoint(179, 67 ), new DataPoint(186, 67 ), new DataPoint(147, 67 ), new DataPoint(166, 67 ), new DataPoint(185, 67 ), new DataPoint(140, 67 ), new DataPoint(160, 67 ), new DataPoint(180, 67 ), new DataPoint(145, 68 ), new DataPoint(155, 68 ), new DataPoint(170, 68 ), new DataPoint(129, 68 ), new DataPoint(164, 68 ), new DataPoint(189, 68 ), new DataPoint(150, 68 ), new DataPoint(157, 68 ), new DataPoint(183, 68 ), new DataPoint(144, 68 ), new DataPoint(170, 68 ), new DataPoint(180, 68 ) }; return datas; } public static List<DataPoint> GetScatterDataForZoomPan() { var datas = new List<DataPoint>(); Java.Util.Random random = new Java.Util.Random(); for (int i = 0; i < 300; i++) { double x = random.NextDouble() * 100; double y = random.NextDouble() * 500; double randomDouble = random.NextDouble(); if (randomDouble >= .25 && randomDouble < .5) { x *= -1; } else if (randomDouble >= .5 && randomDouble < .75) { y *= -1; } else if (randomDouble > .75) { x *= -1; y *= -1; } datas.Add(new DataPoint(300 + (x * (random.NextDouble() + 0.12)), 100 + (y * (random.NextDouble() + 0.12)))); } return datas; } public static List<DataPoint> GetLineData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 45.68)); datas.Add(new DataPoint("2011", 89.25)); datas.Add(new DataPoint("2012", 23.73)); datas.Add(new DataPoint("2013", 43.5)); datas.Add(new DataPoint("2014", 54.92)); return datas; } public static List<DataPoint> GetStepLineData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2002", 36)); datas.Add(new DataPoint("2003", 40)); datas.Add(new DataPoint("2004", 34)); datas.Add(new DataPoint("2005", 40)); datas.Add(new DataPoint("2006", 44)); datas.Add(new DataPoint("2007", 38)); datas.Add(new DataPoint("2008", 30)); return datas; } public static List<DataPoint> GetCategoryData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Bentley", 54)); datas.Add(new DataPoint("Audi", 24)); datas.Add(new DataPoint("BMW", 53)); datas.Add(new DataPoint("Jaguar", 63)); datas.Add(new DataPoint("Skoda", 35)); return datas; } public static List<DataPoint> GetNumericalData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(16, 2)); datas.Add(new DataPoint(17, 14)); datas.Add(new DataPoint(18, 7)); datas.Add(new DataPoint(19, 7)); datas.Add(new DataPoint(20, 10)); return datas; } public static List<DataPoint> GetNumericalData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(16, 7)); datas.Add(new DataPoint(17, 7)); datas.Add(new DataPoint(18, 11)); datas.Add(new DataPoint(19, 8)); datas.Add(new DataPoint(20, 24)); return datas; } public static List<DataPoint> GetData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 54)); datas.Add(new DataPoint("2011", 24)); datas.Add(new DataPoint("2012", 53)); datas.Add(new DataPoint("2013", 63)); datas.Add(new DataPoint("2014", 35)); return datas; } public static List<DataPoint> GetData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 14)); datas.Add(new DataPoint("2011", 54)); datas.Add(new DataPoint("2012", 23)); datas.Add(new DataPoint("2013", 53)); datas.Add(new DataPoint("2014", 25)); return datas; } public static List<DataPoint> GetFinancialData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 873.8, 878.85, 855.5, 860.5)); datas.Add(new DataPoint("2011", 861, 868.4, 835.2, 843.45)); datas.Add(new DataPoint("2012", 846.15, 853, 838.5, 847.5)); datas.Add(new DataPoint("2013", 846, 860.75, 841, 855)); datas.Add(new DataPoint("2014", 841, 845, 827.85, 838.65)); return datas; } public static List<DataPoint> GetSelectionData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", 42)); datas.Add(new DataPoint("Feb", 44)); datas.Add(new DataPoint("Mar", 53)); datas.Add(new DataPoint("Apr", 64)); datas.Add(new DataPoint("May", 75)); datas.Add(new DataPoint("Jun", 83)); return datas; } public static List<DataPoint> GetSelectionData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Jan", 38)); datas.Add(new DataPoint("Feb", 50)); datas.Add(new DataPoint("Mar", 56)); datas.Add(new DataPoint("Apr", 60)); datas.Add(new DataPoint("May", 80)); datas.Add(new DataPoint("Jun", 90)); return datas; } public static List<DataPoint> GetTooltipData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2007", 1.61)); datas.Add(new DataPoint("2008", 2.34)); datas.Add(new DataPoint("2009", 2.16)); datas.Add(new DataPoint("2010", 2.1)); datas.Add(new DataPoint("2011", 1.61)); datas.Add(new DataPoint("2012", 2.05)); datas.Add(new DataPoint("2013", 2.5)); datas.Add(new DataPoint("2014", 2.21)); datas.Add(new DataPoint("2015", 2.34)); return datas; } public static List<DataPoint> GetDateTimeValue() { var dateTime = new DateTime(2015, 1, 1); List<DataPoint> datas = new List<DataPoint>(); datas.Add(new DataPoint(dateTime, 10d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 31d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 28d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 45d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 10d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 23d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 35d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 56d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 10d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 39d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 26d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 21d)); dateTime = dateTime.AddMonths(1); datas.Add(new DataPoint(dateTime, 31d)); return datas; } public static List<DataPoint> GetDateTimValue() { var dateTime = new DateTime(2014, 1, 1); var datas = new List<DataPoint>(); datas.Add(new DataPoint(dateTime, 10d)); dateTime = dateTime.AddDays(1); datas.Add(new DataPoint(dateTime, 23d)); dateTime = dateTime.AddDays(1); datas.Add(new DataPoint(dateTime, 22d)); dateTime = dateTime.AddDays(1); datas.Add(new DataPoint(dateTime, 32d)); dateTime = dateTime.AddDays(1); datas.Add(new DataPoint(dateTime, 31d)); dateTime = dateTime.AddDays(1); datas.Add(new DataPoint(dateTime, 12d)); dateTime = dateTime.AddDays(1); datas.Add(new DataPoint(dateTime, 26d)); return datas; } public static List<DataPoint> GetSeriesData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(new DateTime(2000, 2, 11), 15)); datas.Add(new DataPoint(new DateTime(2000, 9, 14), 20)); datas.Add(new DataPoint(new DateTime(2001, 2, 11), 25)); datas.Add(new DataPoint(new DateTime(2001, 9, 16), 21)); datas.Add(new DataPoint(new DateTime(2002, 2, 07), 13)); datas.Add(new DataPoint(new DateTime(2002, 9, 07), 18)); datas.Add(new DataPoint(new DateTime(2003, 2, 11), 24)); datas.Add(new DataPoint(new DateTime(2003, 9, 14), 23)); datas.Add(new DataPoint(new DateTime(2004, 2, 06), 19)); datas.Add(new DataPoint(new DateTime(2004, 9, 06), 31)); datas.Add(new DataPoint(new DateTime(2005, 2, 11), 39)); datas.Add(new DataPoint(new DateTime(2005, 9, 11), 50)); datas.Add(new DataPoint(new DateTime(2006, 2, 11), 24)); return datas; } public static List<DataPoint> GetSeriesData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(new DateTime(2000, 2, 11), 39)); datas.Add(new DataPoint(new DateTime(2000, 9, 14), 30)); datas.Add(new DataPoint(new DateTime(2001, 2, 11), 28)); datas.Add(new DataPoint(new DateTime(2001, 9, 16), 35)); datas.Add(new DataPoint(new DateTime(2002, 2, 07), 39)); datas.Add(new DataPoint(new DateTime(2002, 9, 07), 41)); datas.Add(new DataPoint(new DateTime(2003, 2, 11), 45)); datas.Add(new DataPoint(new DateTime(2003, 9, 14), 48)); datas.Add(new DataPoint(new DateTime(2004, 2, 06), 54)); datas.Add(new DataPoint(new DateTime(2004, 9, 06), 55)); datas.Add(new DataPoint(new DateTime(2005, 2, 11), 57)); datas.Add(new DataPoint(new DateTime(2005, 9, 11), 60)); datas.Add(new DataPoint(new DateTime(2006, 2, 11), 60)); return datas; } public static List<DataPoint> GetSeriesData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(new DateTime(2000, 2, 11), 60)); datas.Add(new DataPoint(new DateTime(2000, 9, 14), 55)); datas.Add(new DataPoint(new DateTime(2001, 2, 11), 48)); datas.Add(new DataPoint(new DateTime(2001, 9, 16), 57)); datas.Add(new DataPoint(new DateTime(2002, 2, 07), 62)); datas.Add(new DataPoint(new DateTime(2002, 9, 07), 64)); datas.Add(new DataPoint(new DateTime(2003, 2, 11), 57)); datas.Add(new DataPoint(new DateTime(2003, 9, 14), 53)); datas.Add(new DataPoint(new DateTime(2004, 2, 06), 63)); datas.Add(new DataPoint(new DateTime(2004, 9, 06), 50)); datas.Add(new DataPoint(new DateTime(2005, 2, 11), 66)); datas.Add(new DataPoint(new DateTime(2005, 9, 11), 65)); datas.Add(new DataPoint(new DateTime(2006, 2, 11), 79)); return datas; } public static List<DataPoint> GetTriangularData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("Bentley", 800)); datas.Add(new DataPoint("Audi", 810)); datas.Add(new DataPoint("BMW", 825)); datas.Add(new DataPoint("Jaguar", 860)); datas.Add(new DataPoint("Skoda", 875)); return datas; } public static Color ConvertHexaToColor(uint hex) { var alpha = (hex & 0xFF000000) >> 24; var red = (hex & 0xFF0000) >> 16; var green = (hex & 0xFF00) >> 8; var blue = (hex & 0xFF); return Color.Argb((int)alpha, (int)red, (int)green, (int)blue); } public static List<DataPoint> GetPolarData1() { List<DataPoint> datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 4)); datas.Add(new DataPoint("2001", 3.0)); datas.Add(new DataPoint("2002", 3.8)); datas.Add(new DataPoint("2003", 3.4)); datas.Add(new DataPoint("2004", 3.2)); datas.Add(new DataPoint("2005", 3.9)); return datas; } public static List<DataPoint> GetPolarData2() { List<DataPoint> datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 2.6)); datas.Add(new DataPoint("2001", 2.8)); datas.Add(new DataPoint("2002", 2.6)); datas.Add(new DataPoint("2003", 3)); datas.Add(new DataPoint("2004", 3.6)); datas.Add(new DataPoint("2005", 3)); return datas; } public static List<DataPoint> GetPolarData3() { List<DataPoint> datas = new List<DataPoint>(); datas.Add(new DataPoint("2000", 2.8)); datas.Add(new DataPoint("2001", 2.5)); datas.Add(new DataPoint("2002", 2.8)); datas.Add(new DataPoint("2003", 3.2)); datas.Add(new DataPoint("2004", 2.9)); datas.Add(new DataPoint("2005", 2)); return datas; } public static List<DataPoint> GetTechnicalIndicatorData() { var dateTime = new DateTime(1990, 1, 1); var datas1 = new List<DataPoint>(); datas1.Add(new DataPoint(dateTime, 65.75, 67.27, 65.75, 65.98, 7938200)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.98, 65.70, 65.04, 65.11, 10185300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.11, 65.05, 64.26, 64.97, 10835800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 64.97, 65.16, 64.09, 64.29, 9613400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 64.29, 62.73, 61.85, 62.44, 17175000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 62.44, 62.02, 61.29, 61.47, 18040600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 61.47, 62.75, 61.55, 61.59, 13456300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 61.59, 64.78, 62.22, 64.64, 8045100)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 64.64, 64.50, 63.03, 63.28, 8608900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.28, 63.70, 62.70, 63.59, 15025500)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.59, 64.45, 63.26, 63.61, 10065800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.61, 64.56, 63.81, 64.52, 6178200)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 64.52, 64.84, 63.66, 63.91, 5478500)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.91, 65.30, 64.50, 65.22, 7964300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.22, 65.36, 64.46, 65.06, 5679300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.06, 64.54, 63.56, 63.65, 10758300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.65, 64.03, 63.33, 63.73, 5665900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.73, 63.40, 62.80, 62.83, 5833000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 62.83, 63.75, 62.96, 63.60, 3500800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.6, 63.64, 62.51, 63.51, 5044700)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.51, 64.03, 63.53, 63.76, 4871300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.76, 63.77, 63.01, 63.65, 7040400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.65, 63.95, 63.58, 63.79, 4727800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.79, 63.47, 62.92, 63.25, 6334900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.25, 63.96, 63.21, 63.48, 6823200)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.48, 63.63, 62.55, 63.50, 9718400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.5, 63.25, 62.82, 62.90, 2827000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 62.9, 62.34, 62.05, 62.18, 4942700)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 62.18, 62.86, 61.94, 62.81, 4582800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 62.81, 63.06, 62.44, 62.83, 12423900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 62.83, 63.16, 62.66, 63.09, 4940500)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.09, 62.89, 62.43, 62.66, 6132300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 62.66, 62.39, 61.90, 62.25, 6263800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 62.25, 61.69, 60.97, 61.50, 5008300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 61.5, 61.87, 61.18, 61.79, 6662500)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 61.79, 63.41, 62.72, 63.16, 5254000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.16, 64.40, 63.65, 63.89, 5356600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.89, 63.45, 61.60, 61.87, 5052600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 61.87, 62.35, 61.30, 61.54, 6266700)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 61.54, 61.49, 60.33, 61.06, 6190800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 61.06, 60.78, 59.84, 60.09, 6452300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 60.09, 59.62, 58.62, 58.80, 5954000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 58.8, 59.60, 58.89, 59.53, 6250000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 59.53, 60.96, 59.42, 60.68, 5307300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 60.68, 61.12, 60.65, 60.73, 6192900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 60.73, 61.19, 60.62, 61.19, 6355600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 61.19, 61.07, 60.54, 60.97, 2946300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 60.97, 61.05, 59.65, 59.75, 2257600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 59.75, 60.58, 55.99, 59.93, 2872000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 59.93, 60.12, 59.26, 59.73, 2737500)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 59.73, 60.11, 59.35, 59.57, 2589700)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 59.57, 60.40, 59.60, 60.10, 7315800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 60.1, 60.31, 59.76, 60.28, 6883900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 60.28, 61.68, 60.50, 61.50, 5570700)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 61.5, 62.72, 61.64, 62.26, 5976000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 62.26, 64.08, 63.10, 63.70, 3641400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 63.7, 64.60, 63.99, 64.39, 6711600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 64.39, 64.45, 63.92, 64.25, 6427000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 64.25, 65.40, 64.66, 64.70, 5863200)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 64.7, 65.86, 65.32, 65.75, 4711400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.75, 65.22, 64.63, 64.75, 5930600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 64.75, 65.39, 64.76, 65.04, 5602700)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.04, 65.30, 64.78, 65.18, 7487300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.18, 65.09, 64.42, 65.09, 9085400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.09, 65.64, 65.20, 65.25, 6455300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.25, 65.59, 64.74, 64.84, 6135500)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 64.84, 65.84, 65.42, 65.82, 5846400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 65.82, 66.75, 65.85, 66.00, 6681200)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 66, 67.41, 66.17, 67.41, 8780000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 67.41, 68.61, 68.06, 68.41, 10780900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.41, 68.91, 68.42, 68.76, 2336450)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.76, 69.58, 68.86, 69.01, 11902000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 69.01, 69.14, 68.74, 68.94, 7513300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.94, 68.73, 68.06, 68.65, 12074800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.65, 68.79, 68.19, 68.67, 8785400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.67, 69.75, 68.68, 68.74, 11373200)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.74, 68.82, 67.71, 67.76, 12378300)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 67.76, 69.05, 68.43, 69.00, 8458700)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 69, 68.39, 67.77, 68.02, 10779200)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.02, 67.94, 67.22, 67.72, 9665400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 67.72, 68.15, 67.32, 67.32, 12258400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 67.32, 67.95, 67.13, 67.32, 7563600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 67.32, 68.00, 67.16, 67.96, 5509900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 67.96, 68.89, 68.34, 68.61, 12135500)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.61, 69.47, 68.30, 68.51, 8462000)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.51, 68.69, 68.21, 68.62, 2011950)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.62, 68.39, 65.80, 68.37, 8536800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.37, 67.75, 65.00, 62.00, 7624900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 67.62, 67.04, 65.04, 67.00, 13694600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 66, 66.83, 65.02, 67.60, 8911200)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 66.6, 66.98, 65.44, 66.73, 6679600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 66.73, 66.84, 65.10, 66.11, 6451900)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 66.11, 66.59, 65.69, 66.38, 6739100)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 66.38, 67.98, 66.51, 67.67, 2103260)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 67.67, 69.21, 68.59, 68.90, 10551800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.9, 69.96, 69.27, 69.44, 5261100)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 69.44, 69.01, 68.14, 68.18, 5905400)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.18, 68.93, 68.08, 68.14, 10283600)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 68.14, 68.60, 66.92, 67.25, 5006800)); dateTime = dateTime.AddMonths(1); datas1.Add(new DataPoint(dateTime, 67.25, 67.77, 67.23, 67.77, 4110000)); return datas1; } public static List<DataPoint> BubbleSeries() { DateTime dt = new DateTime(2000, 1, 1); var Datas = new List<DataPoint>() { new DataPoint ( dt.AddMonths(4), 70 , 5), new DataPoint ( dt.AddMonths(8), 50 , 8), new DataPoint ( dt.AddMonths(12), -30 , 30), new DataPoint ( dt.AddMonths(16), -70 , 10), new DataPoint ( dt.AddMonths(20), 40 , 12), new DataPoint ( dt.AddMonths(24), 80 , 13), new DataPoint ( dt.AddMonths(28), -70 , 6), new DataPoint ( dt.AddMonths(32), 30 , 8), new DataPoint ( dt.AddMonths(36), 80 , 3), new DataPoint ( dt.AddMonths(40), -30 , 5), new DataPoint ( dt.AddMonths(44), -80 , 7), new DataPoint ( dt.AddMonths(48), 40 , 3), new DataPoint ( dt.AddMonths(52), -50 , 8), new DataPoint ( dt.AddMonths(56), -10 , 4), new DataPoint ( dt.AddMonths(60), -80 , 9), new DataPoint ( dt.AddMonths(64), 40 , 10), new DataPoint ( dt.AddMonths(68), -50 , 6) }; return Datas; } public static List<DataPoint> GetGradientData() { DateTime date = new DateTime(2017, 5, 1); List<DataPoint> gradientData = new List<DataPoint>(); gradientData.Add(new DataPoint(29, 80, date)); gradientData.Add(new DataPoint(33, 80, date.AddDays(6))); gradientData.Add(new DataPoint(24, 80, date.AddDays(15))); gradientData.Add(new DataPoint(28, 80, date.AddDays(23))); gradientData.Add(new DataPoint(26, 80, date.AddDays(30))); gradientData.Add(new DataPoint(38, 80, date.AddDays(39))); gradientData.Add(new DataPoint(32, 80, date.AddDays(50))); return gradientData; } } public class Data { public static List<DataPoint> GetDateTimeValue() { var dateTime = new DateTime(2017, 1, 1); var datas = new List<DataPoint>(); System.Random random = new System.Random(); double value = 100; for (int i = 0; i < 365; i++) { if (random.NextDouble() > 0.5) value += random.NextDouble(); else value -= random.NextDouble(); datas.Add(new DataPoint(dateTime, value)); dateTime = dateTime.AddDays(1); } return datas; } public static List<DataPoint> GetAreaData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 45)); datas.Add(new DataPoint("2011", 56)); datas.Add(new DataPoint("2012", 23)); datas.Add(new DataPoint("2013", 43)); datas.Add(new DataPoint("2014", Double.NaN)); datas.Add(new DataPoint("2015", 54)); datas.Add(new DataPoint("2016", 43)); datas.Add(new DataPoint("2017", 23)); datas.Add(new DataPoint("2018", 34)); return datas; } public static List<DataPoint> GetData1() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 45)); datas.Add(new DataPoint("2011", 86)); datas.Add(new DataPoint("2012", 23)); datas.Add(new DataPoint("2013", 43)); datas.Add(new DataPoint("2014", 54)); return datas; } public static List<DataPoint> GetCategoryData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("South Korea", 39)); datas.Add(new DataPoint("India", 20)); datas.Add(new DataPoint("South Africa", 61)); datas.Add(new DataPoint("China", 65)); datas.Add(new DataPoint("France", 45)); datas.Add(new DataPoint("Saudi Arabia", 10)); datas.Add(new DataPoint("Japan", 16)); datas.Add(new DataPoint("Mexico", 31)); return datas; } public static List<DataPoint> GetNumericalData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint(1, 54)); datas.Add(new DataPoint(2, 24)); datas.Add(new DataPoint(3, 53)); datas.Add(new DataPoint(4, 63)); datas.Add(new DataPoint(5, 35)); return datas; } public static List<DataPoint> GetData2() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 54)); datas.Add(new DataPoint("2011", 24)); datas.Add(new DataPoint("2012", 53)); datas.Add(new DataPoint("2013", 63)); datas.Add(new DataPoint("2014", 35)); return datas; } public static List<DataPoint> GetData3() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 14)); datas.Add(new DataPoint("2011", 54)); datas.Add(new DataPoint("2012", 23)); datas.Add(new DataPoint("2013", 53)); datas.Add(new DataPoint("2014", 25)); return datas; } public static List<DataPoint> GetFinancialData() { var datas = new List<DataPoint>(); datas.Add(new DataPoint("2010", 873.8, 878.85, 855.5, 860.5)); datas.Add(new DataPoint("2011", 861, 868.4, 835.2, 843.45)); datas.Add(new DataPoint("2012", 846.15, 853, 838.5, 847.5)); datas.Add(new DataPoint("2013", 846, 860.75, 841, 855)); datas.Add(new DataPoint("2014", 841, 845, 827.85, 838.65)); return datas; } public static List<DataPoint> CrossingData() { var axisCrossingData = new List<DataPoint>(); axisCrossingData.Add(new DataPoint("2000", 70, 5)); axisCrossingData.Add(new DataPoint("2001", 50, 8)); axisCrossingData.Add(new DataPoint("2002", -30, 30)); axisCrossingData.Add(new DataPoint("2003", -70, 10)); axisCrossingData.Add(new DataPoint("2004", 40, 12)); axisCrossingData.Add(new DataPoint("2005", 80, 13)); axisCrossingData.Add(new DataPoint("2006", -70, 6)); axisCrossingData.Add(new DataPoint("2007", 30, 8)); axisCrossingData.Add(new DataPoint("2008", 80, 3)); axisCrossingData.Add(new DataPoint("2009", -30, 5)); axisCrossingData.Add(new DataPoint("2010", -80, 7)); axisCrossingData.Add(new DataPoint("2011", 40, 3)); axisCrossingData.Add(new DataPoint("2012", -50, 8)); axisCrossingData.Add(new DataPoint("2013", -10, 4)); axisCrossingData.Add(new DataPoint("2014", -80, 9)); axisCrossingData.Add(new DataPoint("2015", 40, 10)); axisCrossingData.Add(new DataPoint("2016", -50, 6)); return axisCrossingData; } } }<file_sep>/Forms/DataGrid/DataGrid.Android/SaveAndroid.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SaveAndroid.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion using System; using System.Diagnostics.CodeAnalysis; using System.IO; using Android.Content; using AndroidX.Core.Content; using Java.IO; using SampleBrowser.SfDataGrid.Droid; using Xamarin.Forms; [assembly: Dependency(typeof(SaveAndroid))] namespace SampleBrowser.SfDataGrid.Droid { /// <summary> /// A dependency service to save a exported file in Android /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1400:AccessModifierMustBeDeclared", Justification = "Reviewed.")] class SaveAndroid : ISave { /// <summary> /// Used to save a Exporting grid to Excel and PDF file in Android devices from Interface of ISAVE /// </summary> /// <param name="fileName">string type of filename parameter</param> /// <param name="contentType">string type of contentType parameter</param> /// <param name="stream">MemoryStream type of stream parameter</param> public void Save(string fileName, string contentType, MemoryStream stream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else { root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); } try { FileOutputStream outs = new FileOutputStream(file); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); //// Forms.Context is obsolete, Hence used local context Android.Net.Uri path = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file); intent.SetDataAndType(path, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); Intent chooserIntent = Intent.CreateChooser(intent, "Open With"); chooserIntent.AddFlags(ActivityFlags.NewTask); Android.App.Application.Context.StartActivity(chooserIntent); } } } }<file_sep>/Android/SampleBrowser/Samples/PullToRefresh/ListView/CircleView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Util; namespace SampleBrowser { public class CircleViewOfTemplate : FrameLayout { public string Text { get; set; } public Color backgroundColor { get; set; } public CircleViewOfTemplate(Context context) : base(context) { Text = string.Empty; backgroundColor = Color.Rgb(0, 191, 255); SetWillNotDraw(false); } public CircleViewOfTemplate(Context context, IAttributeSet attributeSet) : base(context, attributeSet) { Text = string.Empty; backgroundColor = Color.Rgb(0, 191, 255); SetWillNotDraw(false); } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); var radius = 25 * Resources.DisplayMetrics.Density; Paint paint = new Paint() { Color = backgroundColor, AntiAlias = true, }; Paint textPaint = new Paint() { Color = Color.White, AntiAlias = true, TextSize = 25 * Resources.DisplayMetrics.Density, TextAlign = Paint.Align.Center }; canvas.DrawCircle(this.Width / 2, this.Height / 2, radius, paint); //Height is added with 7.5, to get the text at center canvas.DrawText(Text, this.Width / 2, (float)(this.Height / 2 + 7.5 * Resources.DisplayMetrics.Density), textPaint); paint = null; textPaint = null; } } }<file_sep>/Forms/Diagram/Diagram.Droid/BorderFrameRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Xamarin.Forms.Platform.Android; using Android.Graphics; using Android.Graphics.Drawables; using Xamarin.Forms; using Android.Content; [assembly: ExportRenderer(typeof(SampleBrowser.SfDiagram.OverviewPanelBorderHelper), typeof(SampleBrowser.SfDiagram.Droid.BorderFrameRenderer))] namespace SampleBrowser.SfDiagram.Droid { public class BorderFrameRenderer : FrameRenderer { public BorderFrameRenderer(Context context) : base(context) { } public override void Draw(Canvas canvas) { base.Draw(canvas); using (var strokePaint = new Paint()) using (var rect = new RectF(0, 0, canvas.Width, canvas.Height)) { // stroke strokePaint.SetStyle(Paint.Style.Stroke); strokePaint.Color = Element.BorderColor.ToAndroid(); strokePaint.StrokeWidth = 5; canvas.DrawRoundRect(rect, Element.CornerRadius * 2, Element.CornerRadius * 2, strokePaint); // stroke } } protected override void OnElementChanged(ElementChangedEventArgs<Frame> e) { base.OnElementChanged(e); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Carousel/LoadMoreSample.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Syncfusion.SfCarousel.iOS; namespace SampleBrowser { /// <summary> /// Load more sample. /// </summary> public class LoadMoreSample:SampleView { #region private variables UILabel applicationLabel, foodLabel, bankingLabel; UIView LoadMoreLayout; UIAlertView alertWindow; SFCarousel applicationCarousel,foodCarousel,bankCarousel; UIScrollView carouselScrollview; CarouselViewModel carouselViewModel; #endregion #region Loadmore sample /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.LoadMoreSample"/> class. /// </summary> public LoadMoreSample() { carouselScrollview = new UIScrollView(); alertWindow = new UIAlertView(); alertWindow.AddButton("OK"); carouselViewModel = new CarouselViewModel(); LoadMoreLayout = new UIView(); LoadMoreLayout.BackgroundColor = UIColor.FromRGB(249, 249, 249); carouselScrollview.BackgroundColor =UIColor.FromRGB(249, 249, 249); applicationLabel = new UILabel(); applicationLabel.Text = "Application"; applicationLabel.TextColor = UIColor.FromRGBA(nfloat.Parse((51 / 255.0).ToString()), nfloat.Parse((51 / 255.0).ToString()), nfloat.Parse((51 / 255.0).ToString()), nfloat.Parse("0.9764705882352941")); applicationLabel.Font = UIFont.FromName("Helvetica", 18f); applicationCarousel = new SFCarousel(); applicationCarousel.ItemWidth = 150; applicationCarousel.ItemHeight = 150; applicationCarousel.AllowLoadMore = true; applicationCarousel.LoadMoreItemsCount = 4; UILabel loadmore2 = new UILabel() { TextColor = UIColor.Black, Text = "Load More...", Font = UIFont.FromName("Helvetica-Bold", 13f), TextAlignment = UITextAlignment.Center }; loadmore2.Frame = new CoreGraphics.CGRect(12, 61, 150, 17); UIView loadView2 = new UIView(); loadView2.BackgroundColor = UIColor.FromRGB(255, 255, 255); loadView2.AddSubview(loadmore2); applicationCarousel.LoadMoreView = loadView2; applicationCarousel.ViewMode = SFCarouselViewMode.SFCarouselViewModeLinear; applicationCarousel.ItemsSource = carouselViewModel.ApplicationCollection; applicationCarousel.ItemSpacing = 15; applicationCarousel.DrawView += DrawAdapterView; foodLabel = new UILabel(); foodLabel.Text = "Food"; foodLabel.TextColor = UIColor.FromRGBA(nfloat.Parse((51 / 255.0).ToString()), nfloat.Parse((51 / 255.0).ToString()), nfloat.Parse((51 / 255.0).ToString()), nfloat.Parse("0.9764705882352941")); foodLabel.Font = UIFont.FromName("Helvetica", 18f); foodCarousel = new SFCarousel(); foodCarousel.ItemWidth = 150; foodCarousel.ItemHeight = 150; foodCarousel.AllowLoadMore = true; foodCarousel.LoadMoreItemsCount = 4; UILabel loadmore = new UILabel() {TextColor=UIColor.Black, Text = "Load More...", Font = UIFont.FromName("Helvetica-Bold", 13f),TextAlignment=UITextAlignment.Center }; UIView loadView = new UIView(); loadmore.Frame = new CoreGraphics.CGRect(12, 61, 150, 17); loadView.BackgroundColor = UIColor.FromRGB(255, 255, 255); loadView.AddSubview(loadmore); foodCarousel.LoadMoreView = loadView; foodCarousel.ItemSpacing = 15; foodCarousel.ViewMode = SFCarouselViewMode.SFCarouselViewModeLinear; foodCarousel.ItemsSource = carouselViewModel.TransportCollection; foodCarousel.DrawView += DrawFoodAdapterView; LoadMoreLayout.AddSubview(applicationLabel); LoadMoreLayout.AddSubview(applicationCarousel); LoadMoreLayout.AddSubview(foodLabel); LoadMoreLayout.AddSubview(foodCarousel); bankingLabel = new UILabel(); bankingLabel.Text = "Banking"; bankingLabel.TextColor = UIColor.FromRGBA(nfloat.Parse((51 / 255.0).ToString()), nfloat.Parse((51 / 255.0).ToString()), nfloat.Parse((51 / 255.0).ToString()), nfloat.Parse("0.9764705882352941")); bankingLabel.Font = UIFont.FromName("Helvetica", 18f); bankCarousel = new SFCarousel(); bankCarousel.ItemWidth = 150; bankCarousel.ItemHeight = 150; bankCarousel.AllowLoadMore = true; bankCarousel.LoadMoreItemsCount = 4; UILabel loadmore1 = new UILabel() { TextColor = UIColor.Black, Text = "Load More...", Font = UIFont.FromName("Helvetica-Bold", 13f), TextAlignment = UITextAlignment.Center }; UIView loadView1 = new UIView(); loadmore1.Frame = new CoreGraphics.CGRect(12, 61, 150, 17); loadView1.BackgroundColor = UIColor.FromRGB(255, 255, 255); loadView1.AddSubview(loadmore1); bankCarousel.LoadMoreView = loadView1; bankCarousel.ItemSpacing = 15; bankCarousel.ViewMode = SFCarouselViewMode.SFCarouselViewModeLinear; bankCarousel.ItemsSource = carouselViewModel.OfficeCollection; bankCarousel.DrawView += DrawBankAdapterView; LoadMoreLayout.AddSubview(applicationLabel); LoadMoreLayout.AddSubview(applicationCarousel); LoadMoreLayout.AddSubview(foodLabel); LoadMoreLayout.AddSubview(foodCarousel); LoadMoreLayout.AddSubview(bankingLabel); LoadMoreLayout.AddSubview(bankCarousel); carouselScrollview.AddSubview(LoadMoreLayout); this.AddSubview(carouselScrollview); } #endregion private void DrawAdapterView(object sender, DrawViewEventArgs e) { UIView carouselView = new UIView(); carouselView.BackgroundColor = UIColor.FromRGB(255, 255, 255); carouselView.Frame = new CoreGraphics.CGRect(0, 0, 150, 150); UILabel iconLabel = new UILabel(); iconLabel.Frame = new CoreGraphics.CGRect(35, 30, 80, 80); iconLabel.Text = (carouselViewModel.ApplicationCollection[e.Index] as CarouselModel).Unicode; iconLabel.Font = UIFont.FromName("Sample", 55f); iconLabel.TextColor = (carouselViewModel.ApplicationCollection[e.Index] as CarouselModel).ItemColor; iconLabel.TextAlignment = UITextAlignment.Center; carouselView.AddSubview(iconLabel); e.View = carouselView; } private void DrawFoodAdapterView(object sender, DrawViewEventArgs e) { UIView carouselView = new UIView(); carouselView.UserInteractionEnabled = true; carouselView.BackgroundColor = UIColor.FromRGB(255, 255, 255); carouselView.Frame = new CoreGraphics.CGRect(0, 0, 100, 100); UILabel iconLabel = new UILabel(); iconLabel.Frame = new CoreGraphics.CGRect(35, 30, 80, 80); iconLabel.Text = (carouselViewModel.TransportCollection[e.Index] as CarouselModel).Unicode; iconLabel.Font = UIFont.FromName("Sample", 55); iconLabel.TextColor = (carouselViewModel.TransportCollection[e.Index] as CarouselModel).ItemColor; iconLabel.TextAlignment = UITextAlignment.Center; carouselView.AddSubview(iconLabel); e.View = carouselView; } private void DrawBankAdapterView(object sender, DrawViewEventArgs e) { UIView carouselView = new UIView(); carouselView.UserInteractionEnabled = true; carouselView.BackgroundColor = UIColor.FromRGB(255, 255, 255); carouselView.Frame = new CoreGraphics.CGRect(0, 0, 100, 100); UILabel iconLabel = new UILabel(); iconLabel.Frame = new CoreGraphics.CGRect(35, 30, 80, 80); iconLabel.Text = (carouselViewModel.OfficeCollection[e.Index] as CarouselModel).Unicode; iconLabel.Font = UIFont.FromName("Sample", 55); iconLabel.TextColor = (carouselViewModel.OfficeCollection[e.Index] as CarouselModel).ItemColor; iconLabel.TextAlignment = UITextAlignment.Center; carouselView.AddSubview(iconLabel); e.View = carouselView; } #region size update /// <summary> /// Layouts the subviews. /// </summary> public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { carouselScrollview.Frame = new CoreGraphics.CGRect(0, 0, this.Frame.Width, this.Frame.Height); carouselScrollview.ContentSize = new CoreGraphics.CGSize(this.Frame.Width, this.Frame.Height); LoadMoreLayout.Frame = new CoreGraphics.CGRect(0, 0, this.Frame.Width, this.Frame.Height); applicationLabel.Frame = new CoreGraphics.CGRect(18, 22, this.Frame.Width, 24); applicationCarousel.Frame = new CoreGraphics.CGRect(0, 64, this.Frame.Width, 150); foodLabel.Frame = new CoreGraphics.CGRect(18, 248, this.Frame.Width, 24); foodCarousel.Frame = new CoreGraphics.CGRect(0, 290, this.Frame.Width, 150); bankingLabel.Frame = new CoreGraphics.CGRect(18, 474, this.Frame.Width, 24); bankCarousel.Frame = new CoreGraphics.CGRect(0, 516, this.Frame.Width, 150); } else { carouselScrollview.Frame = new CoreGraphics.CGRect(0,0,this.Frame.Width, this.Frame.Height); carouselScrollview.ContentSize = new CoreGraphics.CGSize(this.Frame.Width, this.Frame.Height); LoadMoreLayout.Frame = new CoreGraphics.CGRect(0, 0, this.Frame.Width, this.Frame.Height); applicationLabel.Frame=new CoreGraphics.CGRect(18, 22, this.Frame.Width, 24); applicationCarousel.Frame = new CoreGraphics.CGRect(0, 64, this.Frame.Width, 150); foodLabel.Frame = new CoreGraphics.CGRect(18, 248, this.Frame.Width, 24); foodCarousel.Frame = new CoreGraphics.CGRect(0, 290, this.Frame.Width, 150); } } base.LayoutSubviews(); } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/BankInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; using UIKit; namespace SampleBrowser { public class BankInfo:INotifyPropertyChanged { public BankInfo () { } #region private variables private int branchNo; private int customerID; private string customerName; private int savings; private int currentbalance; private int balancescale; private bool isopen; private int transaction; private UIImage customerImage; #endregion #region Public Properties public int CustomerID { get { return customerID; } set { this.customerID = value; RaisePropertyChanged ("Customer ID"); } } public int BranchNo { get { return branchNo; } set { this.branchNo = value; RaisePropertyChanged ("Branch No"); } } public string CustomerName { get { return this.customerName; } set { this.customerName = value; RaisePropertyChanged ("Customer Name"); } } public int Savings { get { return savings; } set { this.savings = value; RaisePropertyChanged ("Savings"); } } public int Current { get { return currentbalance; } set { this.currentbalance = value; RaisePropertyChanged ("CurrentBalance"); } } public int BalanceScale { get { return balancescale; } set { balancescale = value; RaisePropertyChanged ("BalanceScale"); } } public bool IsOpen { get { return isopen; } set { isopen = value; RaisePropertyChanged ("IsOpen"); } } public UIImage CustomerImage { get { return customerImage; } set { customerImage = value; } } public int Transactions { get { return transaction; } set { this.transaction = value; RaisePropertyChanged ("ChartValue"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged (String name) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (name)); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/NumericUpDown/NumericUpDown_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Com.Syncfusion.Numericupdown; #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Numerictextbox; using Android.Graphics; using Android.Views.InputMethods; using Android.Text; using Android.Text.Style; namespace SampleBrowser { public class NumericUpDown_Tab : SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ SfNumericUpDown adultNumericUpDown, infantsNumericUpDown; Button propertyButton; FrameLayout propertyFrameLayout, buttomButtonLayout, topProperty, frame; double actionBarHeight, navigationBarHeight, totalHeight, totalWidth; double minimumValue = 0, maximumValue = 100, minimumPosition = 0, maximumPosition = 100; Context con, context; int width,spinButtonPosition = 0; Boolean maxNegative, minNegative; bool autoReversePosition = false, autoReverse = false; float density; LinearLayout mainLayout, proprtyOptionsLayout, propertylayout; ArrayAdapter<String> spinButtonDataAdapter; Spinner spinButtonSpinner; EditText minimumText, maximumText; SpinButtonAlignment spinButtonAlignment = SpinButtonAlignment.Right; TextView adultText, infantsText; GravityFlags gravity = GravityFlags.CenterVertical; public override View GetSampleContent(Context con1) { con = con1; InitialMethod(); //adultNumericUpDown AdultLayout(); int numerHeight = (int)(density * 55); if (density >= 3) { numerHeight = (int)(density * 65); } adultNumericUpDown = new SfNumericUpDown(con); adultNumericUpDown.FontSize = 18; adultNumericUpDown.TextGravity = GravityFlags.CenterVertical; adultNumericUpDown.LayoutParameters = new ViewGroup.LayoutParams((int)(width * 0.7), numerHeight); adultNumericUpDown.Minimum = 0; adultNumericUpDown.Maximum = 100; adultNumericUpDown.Value = 5; adultNumericUpDown.FormatString = "N"; adultNumericUpDown.AutoReverse = false; adultNumericUpDown.MaximumDecimalDigits = 0; adultNumericUpDown.StepValue = 1; (adultNumericUpDown.GetChildAt(0) as EditText).FocusChange += adultNumericUpDown_Tab_FocusChange; mainLayout.AddView(adultNumericUpDown); //infantsNumericUpDown infantsTextLayout(); infantsNumericUpDown = new SfNumericUpDown(con); infantsNumericUpDown.FontSize = 18; infantsNumericUpDown.TextGravity = GravityFlags.CenterVertical; infantsNumericUpDown.LayoutParameters = new ViewGroup.LayoutParams((int)(width * 0.7), numerHeight); infantsNumericUpDown.Minimum = 0; infantsNumericUpDown.Maximum = 100; infantsNumericUpDown.Value = 2; infantsNumericUpDown.FormatString = "N"; infantsNumericUpDown.AutoReverse = false; infantsNumericUpDown.MaximumDecimalDigits = 0; infantsNumericUpDown.StepValue = 1; (infantsNumericUpDown.GetChildAt(0) as EditText).FocusChange += NumericUpDown_Tab_FocusChange; OptionLayout(); return frame; } private void InitialMethod() { //frame frame = new FrameLayout(con); totalHeight = con.Resources.DisplayMetrics.HeightPixels; totalWidth = con.Resources.DisplayMetrics.WidthPixels; TypedValue tv = new TypedValue(); if (con.Theme.ResolveAttribute(Android.Resource.Attribute.ActionBarSize, tv, true)) { actionBarHeight = TypedValue.ComplexToDimensionPixelSize(tv.Data, con.Resources.DisplayMetrics); } navigationBarHeight = getNavigationBarHeight(con); totalHeight = totalHeight - navigationBarHeight - actionBarHeight; width = con.Resources.DisplayMetrics.WidthPixels - 40; density = con.Resources.DisplayMetrics.Density; //mainFrameLayout FrameLayout mainFrameLayout = new FrameLayout(con); mainFrameLayout.SetPadding(10, 10, 10, 10); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.FillVertical); mainFrameLayout.LayoutParameters = layoutParams; //mainLayout mainLayout = new LinearLayout(con); mainLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); mainLayout.SetGravity(GravityFlags.FillVertical); mainLayout.Orientation = Orientation.Vertical; mainLayout.SetBackgroundColor(Color.White); } private void AdultLayout() { //Adult adultText = new TextView(con); adultText.Text = "Number of adults"; adultText.TextSize = 18; mainLayout.AddView(adultText); } private void infantsTextLayout() { TextView spaceText5 = new TextView(con); spaceText5.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); mainLayout.AddView(spaceText5); //infants infantsText = new TextView(con); infantsText.SetPadding(0, 15, 0, 0); infantsText.Text = "Number of infants"; infantsText.TextSize = 18; mainLayout.AddView(infantsText); } private void OptionLayout() { mainLayout.AddView(infantsNumericUpDown); //Touch Event mainLayout.Touch += (object sender, View.TouchEventArgs e) => { if (adultNumericUpDown.IsFocused || infantsNumericUpDown.IsFocused) { Rect outRect = new Rect(); adultNumericUpDown.GetGlobalVisibleRect(outRect); infantsNumericUpDown.GetGlobalVisibleRect(outRect); if (!outRect.Contains((int)e.Event.RawX, (int)e.Event.RawY)) { adultNumericUpDown.ClearFocus(); infantsNumericUpDown.ClearFocus(); } hideSoftKeyboard((Activity)con); } }; frame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); frame.SetBackgroundColor(Color.White); //numericCenterLayout LinearLayout numericCenterLayout = new LinearLayout(con); numericCenterLayout.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.7), ViewGroup.LayoutParams.MatchParent, GravityFlags.Top); numericCenterLayout.SetX((int)(totalWidth * 0.15)); numericCenterLayout.SetY((int)(totalHeight * 0.1)); numericCenterLayout.AddView(mainLayout); //scrollView1 ScrollView scrollView1 = new ScrollView(con); scrollView1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.5), GravityFlags.Top | GravityFlags.CenterHorizontal); scrollView1.AddView(numericCenterLayout); frame.AddView(scrollView1); //buttomButtonLayout buttomButtonLayout = new FrameLayout(con); buttomButtonLayout.SetBackgroundColor(Color.Transparent); buttomButtonLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1), GravityFlags.Bottom | GravityFlags.CenterHorizontal); //propertyButton propertyButton = new Button(con); propertyButton.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Bottom | GravityFlags.CenterHorizontal); propertyButton.Text = "OPTIONS"; propertyButton.Gravity = GravityFlags.Start; //propertyFrameLayout propertyFrameLayout = new FrameLayout(con); propertyFrameLayout.SetBackgroundColor(Color.Rgb(236, 236, 236)); propertyFrameLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.35), GravityFlags.CenterHorizontal); propertyFrameLayout.AddView(GetPropertyLayout(con)); propertyButton.Click += (object sender, EventArgs e) => { buttomButtonLayout.RemoveAllViews(); propertyFrameLayout.RemoveAllViews(); adultNumericUpDown.ClearFocus(); infantsNumericUpDown.ClearFocus(); propertyFrameLayout.AddView(GetPropertyLayout(con)); }; //scrollView ScrollView scrollView = new ScrollView(con); scrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.35), GravityFlags.Bottom | GravityFlags.CenterHorizontal); scrollView.AddView(propertyFrameLayout); //frame frame.AddView(scrollView); frame.AddView(buttomButtonLayout); frame.FocusableInTouchMode = true; } private void NumericUpDown_Tab_FocusChange(object sender, View.FocusChangeEventArgs e) { if ((sender as EditText).IsFocused) { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); } } private void adultNumericUpDown_Tab_FocusChange(object sender, View.FocusChangeEventArgs e) { if ((sender as EditText).IsFocused) { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); } } //Apply Changes Method public void ApplyChanges() { //adultNumericUpDown adultNumericUpDown.Minimum = minimumValue; adultNumericUpDown.Maximum = maximumValue; adultNumericUpDown.AutoReverse = autoReverse; adultNumericUpDown.SpinButtonAlignment = spinButtonAlignment; adultNumericUpDown.TextGravity = gravity; //infantsNumericUpDown infantsNumericUpDown.Minimum = minimumValue; infantsNumericUpDown.Maximum = maximumValue; infantsNumericUpDown.AutoReverse = autoReverse; infantsNumericUpDown.SpinButtonAlignment = spinButtonAlignment; infantsNumericUpDown.TextGravity = gravity; maxNegative = minNegative = false; } public View GetPropertyLayout(Context context1) { context = context1; width = (context.Resources.DisplayMetrics.WidthPixels) / 2; totalWidth = (context.Resources.DisplayMetrics.WidthPixels); OptionViewLayout(); MinimumLabelLayout(); MaximumLabelLayout(); SpinButtonAlignmentLayout(); AutoReverseLayout(); return propertylayout; } private void OptionViewLayout() { propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; //propertyLabel TextView propertyLabel = new TextView(context); propertyLabel.SetTextColor(Color.ParseColor("#282828")); propertyLabel.Gravity = GravityFlags.CenterVertical; propertyLabel.TextSize = 18; propertyLabel.SetPadding(0, 10, 0, 10); propertyLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.Left | GravityFlags.CenterHorizontal); propertyLabel.Text = " " + "OPTIONS"; //closeLabel TextView closeLabel = new TextView(context); closeLabel.SetBackgroundColor(Color.Transparent); closeLabel.Gravity = GravityFlags.CenterVertical; closeLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLabel.SetBackgroundResource(Resource.Drawable.sfclosebutton); //closeLayout FrameLayout closeLayout = new FrameLayout(context); closeLayout.SetBackgroundColor(Color.Transparent); closeLayout.SetPadding(0, 10, 0, 10); closeLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLayout.AddView(closeLabel); //topProperty topProperty = new FrameLayout(context); topProperty.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); topProperty.SetBackgroundColor(Color.Rgb(230, 230, 230)); topProperty.AddView(propertyLabel); topProperty.AddView(closeLayout); topProperty.Touch += (object sendar, View.TouchEventArgs e) => { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); }; proprtyOptionsLayout = new LinearLayout(context); proprtyOptionsLayout.Orientation = Android.Widget.Orientation.Vertical; //spaceText TextView spaceText1 = new TextView(context); spaceText1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText1); } private void MinimumLabelLayout() { double newNumber; //minimum TextView minimumLabel = new TextView(context); minimumLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); minimumLabel.Text = "Minimum"; minimumLabel.TextSize = 15; //minimumText minimumText = new EditText(context); minimumText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); minimumText.Text = minimumPosition.ToString(); minimumText.TextSize = 16; minimumText.InputType = Android.Text.InputTypes.ClassPhone; minimumText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (minimumText.Text.Length > 0) { String str = e.Text.ToString(); if (str.StartsWith("-") || str.EndsWith("-")) { str = str.Replace("-", ""); minNegative = true; } if (!str.Equals("")) { newNumber = Convert.ToDouble(str); if (minNegative) { newNumber = newNumber * -1; } minimumValue = newNumber; } } minimumPosition = minimumValue; ApplyChanges(); }; //minimumLayout LinearLayout minimumLayout = new LinearLayout(context); minimumLayout.Orientation = Android.Widget.Orientation.Horizontal; minimumLayout.AddView(minimumLabel); minimumLayout.AddView(minimumText); proprtyOptionsLayout.AddView(minimumLayout); //spaceText TextView spaceText2 = new TextView(context); spaceText2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText2); } private void MaximumLabelLayout() { double newNumber; //maximum TextView maximumLabel = new TextView(context); maximumLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); maximumLabel.Text = "Maximum"; maximumLabel.TextSize = 15; //maximumText maximumText = new EditText(context); maximumText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); maximumText.Text = maximumPosition.ToString(); maximumText.TextSize = 16; maximumText.InputType = Android.Text.InputTypes.ClassPhone; maximumText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (maximumText.Text.Length > 0) { String str = e.Text.ToString(); if (str.StartsWith("-") || str.EndsWith("-")) { str = str.Replace("-", ""); maxNegative = true; } if (!str.Equals("")) { newNumber = Convert.ToDouble(str); if (maxNegative) { newNumber = newNumber * -1; } maximumValue = newNumber; } } maximumPosition = maximumValue; ApplyChanges(); }; //maximumLayout LinearLayout maximumLayout = new LinearLayout(context); maximumLayout.Orientation = Android.Widget.Orientation.Horizontal; maximumLayout.AddView(maximumLabel); maximumLayout.AddView(maximumText); proprtyOptionsLayout.AddView(maximumLayout); //spaceText TextView spaceText3 = new TextView(context); spaceText3.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText3); } private void SpinButtonAlignmentLayout() { //spinButtonAlignment TextView spinButtonText = new TextView(context); spinButtonText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.MatchParent, GravityFlags.Center); spinButtonText.TextSize = 15; spinButtonText.Text = "SpinButtonAlignment"; //spinButtonList List<String> spinButtonList = new List<String>(); spinButtonList.Add("Right"); spinButtonList.Add("Left"); spinButtonList.Add("Both"); spinButtonDataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, spinButtonList); spinButtonDataAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem); //spinButtonSpinner spinButtonSpinner = new Spinner(context,SpinnerMode.Dialog); spinButtonSpinner.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); spinButtonSpinner.Adapter = spinButtonDataAdapter; spinButtonSpinner.SetSelection(spinButtonPosition); spinButtonSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = spinButtonDataAdapter.GetItem(e.Position); spinButtonPosition = e.Position; if (selectedItem.Equals("Right")) { spinButtonAlignment = SpinButtonAlignment.Right; gravity = GravityFlags.CenterVertical; } if (selectedItem.Equals("Left")) { spinButtonAlignment = SpinButtonAlignment.Left; gravity = GravityFlags.End | GravityFlags.CenterVertical; } if (selectedItem.Equals("Both")) { spinButtonAlignment = SpinButtonAlignment.Both; gravity = GravityFlags.Center; } ApplyChanges(); }; //spinButtonLayout LinearLayout spinButtonLayout = new LinearLayout(context); spinButtonLayout.Orientation = Android.Widget.Orientation.Horizontal; spinButtonLayout.AddView(spinButtonText); spinButtonLayout.AddView(spinButtonSpinner); proprtyOptionsLayout.AddView(spinButtonLayout); //spaceText TextView spaceText4 = new TextView(context); spaceText4.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText4); } private void AutoReverseLayout() { //AutoReverse TextView autoReverseText = new TextView(context); autoReverseText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); autoReverseText.Text = "AutoReverse"; //autoReverseCheckBox Switch autoReverseCheckBox = new Switch(context); autoReverseCheckBox.Checked = autoReversePosition; autoReverseCheckBox.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { if (!eve.IsChecked) autoReverse = false; else autoReverse = true; autoReversePosition = autoReverse; ApplyChanges(); }; //spaceText TextView spaceText7 = new TextView(context); spaceText7.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); //autoReverseLayout LinearLayout autoReverseLayout = new LinearLayout(context); autoReverseLayout.Orientation = Android.Widget.Orientation.Horizontal; autoReverseLayout.AddView(autoReverseText); autoReverseLayout.AddView(autoReverseCheckBox); autoReverseLayout.AddView(spaceText7); proprtyOptionsLayout.AddView(autoReverseLayout); //spaceText TextView spaceText5 = new TextView(context); spaceText5.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 40, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText5); TextView spaceLabel = new TextView(context); spaceLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent); //layout1 LinearLayout layout1 = new LinearLayout(context); layout1.Orientation = Android.Widget.Orientation.Horizontal; layout1.AddView(spaceLabel); layout1.AddView(proprtyOptionsLayout); //propertylayout propertylayout.AddView(topProperty); propertylayout.AddView(layout1); propertylayout.SetPadding(10, 10, 10, 10); } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); inputMethodManager.HideSoftInputFromWindow(activity.CurrentFocus.WindowToken, 0); } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } private int getStatusBarHeight(Android.Content.Context con) { int barHeight = 0; int resourceId = con.Resources.GetIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { barHeight = con.Resources.GetDimensionPixelSize(resourceId); } return barHeight; } private int getNavigationBarHeight(Android.Content.Context con) { int navBarHeight = 0; int resourceId = con.Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navBarHeight = con.Resources.GetDimensionPixelSize(resourceId); } return navBarHeight; } } } <file_sep>/iOS/SampleBrowser/Samples/Schedule/GettingStarted/Model/Meeting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Foundation; using UIKit; using SampleBrowser; namespace SampleBrowser { /// <summary> /// Custom appointment class /// </summary> [Preserve(AllMembers = true)] public class Meeting { /// <summary> /// Gets of sets the Event name for the meeting /// </summary> public NSString EventName { get; set; } /// <summary> /// Gets or sets the Organizer for the meeting /// </summary> public NSString Organizer { get; set; } /// <summary> /// Gets or sets the From time for the meeting /// </summary> public NSDate From { get; set; } /// <summary> /// Gets or sets the To time for the meeting /// </summary> public NSDate To { get; set; } /// <summary> /// Gets or sets the color for the meeting /// </summary> public UIColor Color { get; set; } /// <summary> /// Gets or sets the minimum height for the meeting /// </summary> public double MinimumHeight { get; set; } /// <summary> /// Gets or sets a value to indicate whether the meeting is all day or not /// </summary> public bool IsAllDay { get; set; } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/FrozenView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using Syncfusion.SfDataGrid; using System.Globalization; using CoreGraphics; using Syncfusion.GridCommon.ScrollAxis; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class FrozenView : SampleView { #region Fields SfDataGrid sfGrid; FrozenViewViewModel viewModel; UIView frozenView; #endregion #region Static Methods static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } #endregion #region Constructor public FrozenView() { sfGrid = new SfDataGrid(); frozenView = new UIView(); this.sfGrid.SelectionMode = SelectionMode.Single; viewModel = new FrozenViewViewModel(); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = viewModel.Products; if (Utility.IsIPad) this.sfGrid.ColumnSizer = ColumnSizer.Star; sfGrid.FrozenRowsCount = 2; sfGrid.FrozenColumnsCount = 1; sfGrid.GridLoaded += DataGrid_GridLoaded; this.sfGrid.GridStyle = new FrozenViewStyle(); this.AddSubview(sfGrid); } private void DataGrid_GridLoaded(object sender, GridLoadedEventArgs e) { var point = sfGrid.RowColumnIndexToPoint(new RowColumnIndex(sfGrid.FrozenRowsCount, 0)); frozenView.Frame = new CGRect(0, point.Y + sfGrid.RowHeight, this.Frame.Width, 1); frozenView.BackgroundColor = UIColor.FromRGB(117, 117, 117); this.AddSubview(frozenView); } #endregion #region Override Methods public override void LayoutSubviews() { this.sfGrid.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { if (disposing) { if(sfGrid !=null) { sfGrid.GridLoaded -= DataGrid_GridLoaded; sfGrid.Dispose(); } frozenView = null; viewModel = null; sfGrid = null; } base.Dispose(disposing); } #endregion #region CallBacks private void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "SupplierID") { e.Column.HeaderText = "Supplier ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "ProductID") { e.Column.HeaderText = "Product ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "ProductName") { e.Column.HeaderText = "Product Name"; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "QuantityPerUnit") { e.Column.HeaderText = "Quantity Per Unit"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "UnitPrice") { e.Column.TextAlignment = UITextAlignment.Center; e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo("en-US"); e.Column.HeaderText = "Unit Price"; } else if (e.Column.MappingName == "UnitsInStock") { e.Column.TextAlignment = UITextAlignment.Center; e.Column.HeaderText = "Units In Stock"; } } #endregion } public class FrozenViewStyle : DataGridStyle { public FrozenViewStyle() { } public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Both; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Exporting/ExportingBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ExportingBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.SfDataGrid.XForms.Exporting; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Exporting samples /// </summary> public class ExportingBehaviors : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Xamarin.Forms.Image excelImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Xamarin.Forms.Image pdfImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Label exportToPdf; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Label exportToExcel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private StackLayout pdfExport; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private StackLayout excelExport; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type parameter as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { var assembly = Assembly.GetAssembly(Application.Current.GetType()); this.dataGrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.excelImage = bindAble.FindByName<Xamarin.Forms.Image>("excelImage"); this.pdfImage = bindAble.FindByName<Xamarin.Forms.Image>("pdfImage"); this.excelImage.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.ExportToExcel) }); this.pdfImage.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.ExportToPdf) }); this.pdfExport = bindAble.FindByName<StackLayout>("PdfStack"); this.excelExport = bindAble.FindByName<StackLayout>("ExcelStack"); this.excelExport.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.ExportToExcel) }); this.pdfExport.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.ExportToPdf) }); this.pdfImage.Source = "PdfExport.png"; this.excelImage.Source = "ExcelExport.png"; this.excelImage.Margin = new Thickness(0, 0, 10, 0); this.exportToPdf = bindAble.FindByName<Label>("exportToPdf"); this.exportToPdf.Focused += this.ExportToPdf_Clicked; //// exportToPdf.Clicked += ExportToPdf_Clicked; this.exportToExcel = bindAble.FindByName<Label>("exportToExcel"); this.exportToExcel.Focused += this.ExportToExcel_Clicked; //// exportToExcel.Clicked += ExportToExcel_Clicked; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type of bindAble parameter</param> protected override void OnDetachingFrom(SampleView bindAble) { this.dataGrid = null; this.pdfImage = null; this.excelImage = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Triggers while Export to Excel button was clicked /// </summary> /// <param name="sender">ExportToExcel_Clicked sender</param> /// <param name="e">ExportToExcel_Clicked EventArgs e</param> private void ExportToExcel_Clicked(object sender, EventArgs e) { this.ExportToExcel(sender); } /// <summary> /// Triggers while Export to PDF button was clicked /// </summary> /// <param name="sender">ExportTo PDF _Clicked sender</param> /// <param name="e">ExportTo PDF _Clicked EventArgs e</param> private void ExportToPdf_Clicked(object sender, EventArgs e) { this.ExportToPdf(sender); } /// <summary> /// Exports the DataGrid to PDF /// </summary> /// <param name="obj">object type parameter</param> private void ExportToPdf(object obj) { DataGridPdfExportingController pdfExport = new DataGridPdfExportingController(); pdfExport.HeaderAndFooterExporting += this.PdfExport_HeaderAndFooterExporting; MemoryStream stream = new MemoryStream(); var doc = pdfExport.ExportToPdf(this.dataGrid, new DataGridPdfExportOption() { FitAllColumnsInOnePage = true }); if (doc == null) { return; } doc.Save(stream); doc.Close(true); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("DataGrid.pdf", "application/pdf", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("DataGrid.pdf", "application/pdf", stream); } } /// <summary> /// Export the DataGrid to Excel /// </summary> /// <param name="obj">object type parameter</param> private void ExportToExcel(object obj) { DataGridExcelExportingController excelExport = new DataGridExcelExportingController(); DataGridExcelExportingOption exportOption = new DataGridExcelExportingOption(); if (Device.RuntimePlatform == Device.iOS) { exportOption.ExportColumnWidth = true; } var excelEngine = excelExport.ExportToExcel(this.dataGrid, exportOption); if (excelEngine == null) { return; } var workbook = excelEngine.Excel.Workbooks[0]; if (workbook == null) { return; } MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("DataGrid.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("DataGrid.xlsx", "application/msexcel", stream); } } /// <summary> /// Fired when Header and Footer are exported to PDF /// </summary> /// <param name="sender">PDF Export_HeaderAndFooterExporting sender</param> /// <param name="e">PDF Export_HeaderAndFooterExporting EventArgs e</param> private void PdfExport_HeaderAndFooterExporting(object sender, PdfHeaderFooterEventArgs e) { var width = e.PdfPage.GetClientSize().Width; PdfStandardFont font = null; PdfPageTemplateElement header = new PdfPageTemplateElement(width, 60); var assmbely = this.GetType().GetTypeInfo().Assembly; #if COMMONSB var imagestream = assmbely.GetManifestResourceStream("SampleBrowser.Icons.SyncfusionLogo.jpg"); #else var imagestream = assmbely.GetManifestResourceStream("SampleBrowser.SfDataGrid.Icons.SyncfusionLogo.jpg"); #endif PdfImage pdfImage = PdfImage.FromStream(imagestream); header.Graphics.DrawImage(pdfImage, new RectangleF(width - 148, 0, 148, 60)); if (Device.RuntimePlatform == Device.iOS) { font = new PdfStandardFont(PdfFontFamily.Helvetica, 18, PdfFontStyle.Bold); } else { font = new PdfStandardFont(PdfFontFamily.Helvetica, 13, PdfFontStyle.Bold); } PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left); header.Graphics.DrawString("Customer Details", font, PdfBrushes.Black, new RectangleF(0, 25, 200, 60), format); e.PdfDocumentTemplate.Top = header; } } } <file_sep>/Android/SampleBrowser/Samples/DocIO/TrackChanges.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.OfficeChart; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using Syncfusion.Drawing; using System.IO; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Webkit; using Android.App; using Android.OS; namespace SampleBrowser { public partial class TrackChanges : SamplePage { private Context m_context; RadioGroup radioGroup; RadioButton acceptAll; RadioButton rejectAll; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to accept or reject the tracked changes in the Word document using Essential DocIO."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; LinearLayout radioLinearLayoutVertical = new LinearLayout(con); radioLinearLayoutVertical.Orientation = Orientation.Vertical; radioGroup = new RadioGroup(con); radioGroup.TextAlignment = TextAlignment.Center; radioGroup.Orientation = Orientation.Vertical; acceptAll = new RadioButton(con); acceptAll.Text = "Accepts all the tracked changes in the Word document"; radioGroup.AddView(acceptAll); rejectAll = new RadioButton(con); rejectAll.Text = "Rejects all the tracked changes in the Word document"; radioGroup.AddView(rejectAll); radioGroup.Check(1); radioLinearLayoutVertical.AddView(radioGroup); linear.AddView(radioLinearLayoutVertical); acceptAll.Checked = true; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button viewButton = new Button(con); viewButton.Text = "View Template"; viewButton.Click += OnButtonClicked1; linear.AddView(viewButton); TextView space3 = new TextView(con); space3.TextSize = 10; linear.AddView(space3); Button generateButton = new Button(con); generateButton.Text = "Generate"; generateButton.Click += OnButtonClicked2; linear.AddView(generateButton); return linear; } void OnButtonClicked1(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.TrackChangesTemplate.docx"); MemoryStream stream = new MemoryStream(); inputStream.CopyTo(stream); stream.Position = 0; inputStream.Dispose(); //Set file content type string contentType = null; string fileName = null; //Save the document as docx fileName = "TrackChangesTemplate.docx"; contentType = "application/msword"; if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save(fileName, contentType, stream, m_context); } } void OnButtonClicked2(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Open an existing template document with single section. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.TrackChangesTemplate.docx"); // Open an existing template document. document.Open(inputStream, FormatType.Docx); inputStream.Dispose(); if (acceptAll.Checked == true) document.Revisions.AcceptAll(); else document.Revisions.RejectAll(); MemoryStream ms = new MemoryStream(); //Set file content type string contentType = null; string fileName = null; //Save the document as docx fileName = "Track Changes.docx"; contentType = "application/msword"; document.Save(ms, FormatType.Docx); document.Dispose(); if (ms != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save(fileName, contentType, ms, m_context); } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DocIO/WordToPDF.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.PDF; using Syncfusion.DocIORenderer; using Syncfusion.OfficeChart; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using ObjCRuntime; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class WordToPDF : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; UIButton button2; public WordToPDF() { label1 = new UILabel(); label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; button2 = new UIButton(UIButtonType.System); button2.TouchUpInside += OnInpTemplateButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to convert a Word document into PDF."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 70); } this.AddSubview(label); button.SetTitle("Convert", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 85, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 110, frameRect.Size.Width, 10); } this.AddSubview(button); button2.SetTitle("Input Template", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button2.Frame = new CGRect(0, 65, frameRect.Location.X + frameRect.Size.Width, 10); } else { button2.Frame = new CGRect(frameRect.Location.X, 70, frameRect.Size.Width, 10); } this.AddSubview(button2); } void OnInpTemplateButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.DocIO.Templates.WordtoPDF.docx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); stream.Position = 0; fileStream.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("WordtoPDF.docx", "application/msword", stream); } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.DocIO.Templates.WordtoPDF.docx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); // Loads the stream into Word Document. WordDocument wordDocument = new WordDocument(fileStream, Syncfusion.DocIO.FormatType.Automatic); //Instantiation of DocIORenderer for Word to PDF conversion DocIORenderer render = new DocIORenderer(); //Sets Chart rendering Options. render.Settings.ChartRenderingOptions.ImageFormat = ExportImageFormat.Jpeg; //Sets ShowInBalloons to render a document comments in converted PDF document. wordDocument.RevisionOptions.CommentDisplayMode = CommentDisplayMode.ShowInBalloons; //Sets the color to be used for Comment Balloon wordDocument.RevisionOptions.CommentColor = RevisionColor.Blue; //Converts Word document into PDF document PdfDocument pdfDocument = render.ConvertToPDF(wordDocument); //Releases all resources used by the Word document and DocIO Renderer objects render.Dispose(); wordDocument.Dispose(); MemoryStream stream = new MemoryStream(); //Save the converted PDF document to MemoryStream. pdfDocument.Save(stream); stream.Position = 0; //Close the PDF document. pdfDocument.Close(true); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("WordtoPDF.pdf", "application/pdf", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Forms/ListView/ListView/Samples/Orientation/Model/PizzaInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class PizzaInfoRepository { #region Constructor public PizzaInfoRepository() { } #endregion #region Properties internal ObservableCollection<PizzaInfo> GetPizzaInfo() { var categoryInfo = new ObservableCollection<PizzaInfo>(); for (int i = 0; i < PizzaNames.Count(); i++) { var info = new PizzaInfo() { PizzaName = PizzaNames[i] }; if (i == 9) info.PizzaImage = "Pizza3.jpg"; else info.PizzaImage = "Pizza" + i + ".jpg"; categoryInfo.Add(info); } return categoryInfo; } internal ObservableCollection<PizzaInfo> GetPizzaInfo1() { var categoryInfo = new ObservableCollection<PizzaInfo>(); for (int i = 0; i < PizzaNames1.Count(); i++) { var info = new PizzaInfo() { PizzaName = PizzaNames1[i] }; if (i == 9) info.PizzaImage = "Pizza12.jpg"; else info.PizzaImage = "Pizza" + (i + 9) + ".jpg"; categoryInfo.Add(info); } return categoryInfo; } #endregion #region CategoryInfo string[] PizzaNames = new string[] { "Supreme", "GodFather", "Ciao-ciao", "Frutti di mare", "Kebabpizza", "Napolitana", "Apricot Chicken", "L<NAME>", "Mr Wedge", "Vegorama", }; string[] PizzaNames1 = new string[] { "Margherita", "Funghi", "Capriciosa", "Stagioni", "Vegetariana", "Formaggi", "Marinara", "Peperoni", "apolitana", "Hawaii" }; #endregion } } <file_sep>/Forms/ListView/ListView/Samples/DataTemplateSelector/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.ListView.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ViewModel : INotifyPropertyChanged { #region Fields private ObservableCollection<MessageInfo> messageInfo; private string newText; private string sendIcon; #endregion #region Properties public ObservableCollection<MessageInfo> MessageInfo { get { return messageInfo; } set { this.messageInfo = value; } } public string NewText { get { return newText; } set { newText = value; OnPropertyChanged("NewText"); } } public string SendIcon { get { return sendIcon; } set { sendIcon = value; } } public Command<object> SendCommand { get; set; } public Command<object> LoadCommand { get; set; } #endregion #region Interface public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion Interface #region Constructor public ViewModel() { InitializeSendCommand(); GenerateSource(); } #endregion #region GenerateSource public void GenerateSource() { MessageInfoRepository Message = new MessageInfoRepository(); LoadCommand = new Command<object>(OnLoaded); MessageInfo = Message.GenerateInfo(); } #endregion #region InitializeCommand private void InitializeSendCommand() { SendIcon = "\ue745"; SendCommand = new Command<object>(OnSendCommand); NewText = ""; } private void OnSendCommand(object obj) { var Listview = obj as Syncfusion.ListView.XForms.SfListView; if (!string.IsNullOrWhiteSpace(NewText)) { MessageInfo.Add(new MessageInfo { Text = NewText, TemplateType = TemplateType.OutGoingText, DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:HH:mm}", System.DateTime.Now), }); (Listview.LayoutManager as LinearLayout).ScrollToRowIndex(MessageInfo.Count - 1, Syncfusion.ListView.XForms.ScrollToPosition.Start); } NewText = null; } private void OnLoaded(object obj) { var ListView = obj as Syncfusion.ListView.XForms.SfListView; var scrollView = ListView.Parent as ScrollView; ListView.HeightRequest = scrollView.Height; if (Device.RuntimePlatform == Device.macOS) { Device.BeginInvokeOnMainThread(() => { ListView.ScrollTo(2500); }); } else { Device.BeginInvokeOnMainThread(() => { (ListView.LayoutManager as LinearLayout).ScrollToRowIndex(this.MessageInfo.Count - 1, Syncfusion.ListView.XForms.ScrollToPosition.Start); }); } } #endregion } } <file_sep>/Android/SampleBrowser/SplashActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Threading; using Android.App; using Android.Content.PM; using Android.OS; namespace SampleBrowser { [Activity(Theme = "@style/Theme.Splash", MainLauncher = true, Icon = "@drawable/icon", ScreenOrientation = ScreenOrientation.Portrait, NoHistory = true)] public class SplashActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Thread.Sleep(100); StartActivity(typeof(MainActivity)); } } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/Model/BookingInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "BookingInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; /// <summary> /// A class contains Properties and Notifies that a property value has changed /// </summary> public class BookingInfo : INotifyPropertyChanged { /// <summary> /// backing field for MovieImage. /// </summary> private ImageSource movieImage; /// <summary> /// backing field for MovieName. /// </summary> private string movieName; /// <summary> /// backing field for SubHeading. /// </summary> private string subHeading; /// <summary> /// Initializes a new instance of the BookingInfo class. /// </summary> public BookingInfo() { } /// <summary> /// Initializes a new instance of the BookingInfo class. /// </summary> /// <param name="name">string type of parameter name</param> public BookingInfo(string name) { this.movieName = name; } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the MovieName and notifies user when collection value gets changed. /// </summary> public string MovieName { get { return this.movieName; } set { if (this.movieName != value) { this.movieName = value; this.RaisedOnPropertyChanged("MovieName"); } } } /// <summary> /// Gets or sets the SubHeading and notifies user when collection value gets changed. /// </summary> public string SubHeading { get { return this.subHeading; } set { if (this.subHeading != value) { this.subHeading = value; this.RaisedOnPropertyChanged("SubHeading"); } } } /// <summary> /// Gets or sets the MovieImage and notifies user when collection value gets changed. /// </summary> public ImageSource MovieImage { get { return this.movieImage; } set { this.movieImage = value; this.RaisedOnPropertyChanged("MovieImage"); } } /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="propertyName">string type of parameter named as propertyName</param> public void RaisedOnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }<file_sep>/Forms/ListView/ListView/Samples/Grouping/Model/ListViewContactsInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewContactsInfo : INotifyPropertyChanged { #region Fields private string contactName; private string contactNo; private string image; private string contactType; #endregion #region Constructor public ListViewContactsInfo() { } #endregion #region Public Properties public string ContactName { get { return this.contactName; } set { this.contactName = value; RaisePropertyChanged("ContactName"); } } public string ContactNumber { get { return contactNo; } set { this.contactNo = value; RaisePropertyChanged("ContactNumber"); } } public string ContactType { get { return contactType; } set { this.contactType = value; RaisePropertyChanged("ContactType"); } } public string ContactImage { get { return this.image; } set { this.image = value; this.RaisePropertyChanged("ContactImage"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Forms/DataForm/DataForm/Samples/Themes/ViewModel/ThemesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using Xamarin.Forms.Internals; namespace SampleBrowser.SfDataForm { [Preserve(AllMembers = true)] public class ThemesViewModel: INotifyPropertyChanged { /// <summary> /// The employee info. /// </summary> private EmployeeInfo employeeInfo; public ThemesViewModel() { this.employeeInfo = new EmployeeInfo(); } /// <summary> /// Gets or sets the recipient information. /// </summary> public EmployeeInfo EmployeeInfo { get { return this.employeeInfo; } set { this.employeeInfo = value; } } /// <summary> /// Occurs when property changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Occurs when property value changes. /// </summary> /// <param name="propertyName">The corresponding name of the property.</param> private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } } <file_sep>/Forms/Schedule/Schedule/Samples/GettingStarted/Behaviors/SetScheduleViewBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Schedule View Behavior class /// </summary> internal class SetScheduleViewBehavior : Behavior<SampleView> { /// <summary> /// schedule initialize /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule schedule; /// <summary> /// localization view model /// </summary> private LocalizationViewModel localizationViewModel; /// <summary> /// view picker /// </summary> private Picker viewPicker; /// <summary> /// locale picker /// </summary> private Picker localePicker; /// <summary> /// current time indicator /// </summary> private Switch currentTime; /// <summary> /// current time label /// </summary> private Label showCurrentTime; /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(SampleView bindable) { if (bindable == null) { return; } base.OnAttachedTo(bindable); this.schedule = bindable.Content.FindByName<Syncfusion.SfSchedule.XForms.SfSchedule>("Schedule"); this.currentTime = bindable.FindByName<Switch>("currentTime"); this.showCurrentTime = bindable.FindByName<Label>("showCurrentTime"); if (Device.RuntimePlatform == Device.Android) { this.schedule.ViewHeaderStyle.DateFontSize = 24; } if (this.schedule?.Locale == "ja") { this.localizationViewModel = new LocalizationViewModel(); this.localePicker = bindable.FindByName<Picker>("localePicker"); if (this.localePicker == null) { return; } this.localePicker.SelectedIndex = 0; this.localePicker.SelectedIndexChanged += this.LocalePicker_SelectedIndexChanged; this.schedule.DataSource = this.localizationViewModel.JapaneseAppointments; } this.viewPicker = bindable.FindByName<Picker>("viewPicker"); if (this.viewPicker == null) { return; } if (bindable.GetType().Equals(typeof(RecursiveAppointments))) { this.viewPicker.SelectedIndex = 3; switch (Device.RuntimePlatform) { case Device.iOS: this.schedule.MonthViewSettings.AppointmentDisplayMode = AppointmentDisplayMode.Appointment; if (Device.RuntimePlatform == Device.iOS && Device.Idiom == TargetIdiom.Tablet) { schedule.MonthViewSettings.AppointmentIndicatorCount = 4; } else if (Device.RuntimePlatform == Device.iOS) { schedule.MonthViewSettings.AppointmentIndicatorCount = 2; } break; case Device.Android: this.schedule.MonthViewSettings.AppointmentDisplayMode = AppointmentDisplayMode.Appointment; break; case Device.UWP: this.schedule.MonthViewSettings.AppointmentDisplayMode = AppointmentDisplayMode.Indicator; break; case Device.WPF: this.schedule.MonthViewSettings.AppointmentDisplayMode = AppointmentDisplayMode.Indicator; break; } } else if (bindable.GetType().Equals(typeof(ViewCustomization))) { this.viewPicker.SelectedIndex = 3; } else if (bindable.GetType().Equals(typeof(Localization))) { this.schedule.MonthViewSettings.AppointmentDisplayMode = AppointmentDisplayMode.Appointment; this.schedule.MonthViewSettings.AppointmentDisplayCount = 2; if (Device.RuntimePlatform == Device.iOS && Device.Idiom == TargetIdiom.Tablet) { schedule.MonthViewSettings.AppointmentIndicatorCount = 4; } else if (Device.RuntimePlatform == Device.iOS) { schedule.MonthViewSettings.AppointmentIndicatorCount = 2; } this.viewPicker.SelectedIndex = 3; } else { switch (Device.RuntimePlatform) { case Device.iOS: schedule.ScheduleView = ScheduleView.MonthView; if (Device.Idiom == TargetIdiom.Tablet) { schedule.MonthViewSettings.AppointmentIndicatorCount = 4; } else { schedule.MonthViewSettings.AppointmentIndicatorCount = 2; } this.viewPicker.SelectedIndex = 3; break; case Device.Android: schedule.ScheduleView = ScheduleView.MonthView; this.viewPicker.SelectedIndex = 3; break; case Device.UWP: schedule.ScheduleView = ScheduleView.WeekView; this.viewPicker.SelectedIndex = 1; break; case Device.WPF: schedule.ScheduleView = ScheduleView.WeekView; this.viewPicker.SelectedIndex = 1; break; } } if (bindable.GetType().Equals(typeof(GettingStarted))) { schedule.ScheduleView = ScheduleView.WeekView; this.viewPicker.SelectedIndex = 1; this.currentTime.Toggled += CurrentTime_Toggled; switch (Device.RuntimePlatform) { case Device.iOS: schedule.ShowAppointmentsInline = true; break; case Device.Android: schedule.ShowAppointmentsInline = true; this.showCurrentTime.FontSize = 18; this.showCurrentTime.TextColor = Color.Gray; break; case Device.UWP: schedule.ShowAppointmentsInline = false; schedule.MonthViewSettings.ShowAgendaView = false; this.showCurrentTime.TextColor = Color.Black; break; case Device.WPF: schedule.ShowAppointmentsInline = false; schedule.MonthViewSettings.ShowAgendaView = false; break; } } this.viewPicker.SelectedIndexChanged += this.ViewPicker_SelectedIndexChanged; } /// <summary> /// method for enabling current time indicator. /// </summary> /// <param name="sender"> return the object</param> /// <param name="e">Event Args</param> private void CurrentTime_Toggled(object sender, ToggledEventArgs e) { if ((sender as Switch).IsToggled) { this.schedule.ShowCurrentTimeIndicator = true; } else { this.schedule.ShowCurrentTimeIndicator = false; } } /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); if (this.viewPicker != null) { this.viewPicker.SelectedIndexChanged -= this.ViewPicker_SelectedIndexChanged; this.viewPicker = null; } if (this.localePicker != null) { this.localePicker.SelectedIndexChanged -= this.LocalePicker_SelectedIndexChanged; this.localePicker = null; } if(currentTime != null) { this.currentTime.Toggled -= CurrentTime_Toggled; this.currentTime = null; } if (showCurrentTime != null) { this.showCurrentTime = null; } if (this.schedule != null) { this.schedule = null; } } /// <summary> /// Method for schedule view selection /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void ViewPicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: this.schedule.ScheduleView = ScheduleView.DayView; break; case 1: this.schedule.ScheduleView = ScheduleView.WeekView; break; case 2: this.schedule.ScheduleView = ScheduleView.WorkWeekView; break; case 3: this.schedule.ScheduleView = ScheduleView.MonthView; break; case 4: this.schedule.ScheduleView = ScheduleView.TimelineView; break; } } /// <summary> /// method for selecting locale /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void LocalePicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: this.schedule.Locale = "ja"; this.schedule.DataSource = this.localizationViewModel.JapaneseAppointments; break; case 1: this.schedule.Locale = "en"; this.schedule.DataSource = this.localizationViewModel.EnglishAppointments; break; case 2: this.schedule.Locale = "fr"; this.schedule.DataSource = this.localizationViewModel.FrenchAppointments; break; case 3: this.schedule.Locale = "es"; this.schedule.DataSource = this.localizationViewModel.SpanishAppointments; break; } } } } <file_sep>/Forms/ImageEditor/ImageEditor/Samples/Customization/Customization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfImageEditor.XForms; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfImageEditor { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Customization : SampleView { bool isOpen; bool isPath; double height = 0, width = 0; void Redo(object sender, System.EventArgs e) { imageEditor.Redo(); if (model.RedoCount > 0) model.RedoCount--; model.UndoCount++; } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.RuntimePlatform.ToLower() == "uwp") return; if ((width != this.width || height != this.height) && (width > -1 || height > -1)) { this.width = width; this.height = height; if (width < height) { if (Device.Idiom == TargetIdiom.Phone) { captionTextBox.Margin = new Thickness(5, 0, 0, 0); shareButton.Margin = new Thickness(0); colorPalette.Padding = new Thickness(0); } else captionTextBox.Margin = new Thickness(50, 0, 50, 0); } else { if (Device.Idiom == TargetIdiom.Phone) { captionTextBox.Margin = new Thickness(75, 0, 50, 0); shareButton.Margin = new Thickness(0, 0, 50, 0); colorPalette.Padding = new Thickness(0, 20, 0, 20); } else { captionTextBox.Margin = new Thickness(200, 0, 200, 0); shareButton.Margin=new Thickness(0, 0, 50, 0); } } } } void ColorClicked(object sender, System.EventArgs e) { var button = sender as Button; var color = button.BackgroundColor; if (isPath) { imageEditor.AddShape(ShapeType.Path, new PenSettings() { Color = color }); } else { if (Settings is PenSettings) { (Settings as PenSettings).Color = color; } else { (Settings as TextSettings).Color = color; } } model.UndoCount++; if (!model.IsImageEdited) model.IsImageEdited = true; } void Handle_Tapped(object sender, System.EventArgs e) { model.DetectTouch(); OpenToolbar(); } void Reset(object sender, System.EventArgs e) { imageEditor.Reset(); model.UndoCount = 0; model.RedoCount = 0; model.IsTouched = false; CloseToolbar(); if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) CloseColorPalette(); model.IsColorPaletteVisible = false; isOpen = false; model.IsImageEdited = false; } void DoodleDraw(object sender, System.EventArgs e) { isPath = true; if (!isOpen) { OpenColorPalette(); isOpen = true; } model.IsColorPaletteVisible = true; imageEditor.ToolbarSettings.SubItemToolbarHeight = 0; imageEditor.AddShape(); } void AddText(object sender, System.EventArgs e) { isPath = false; if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { if (!isOpen) { OpenColorPalette(); isOpen = true; } } model.IsColorPaletteVisible = true; imageEditor.ToolbarSettings.SubItemToolbarHeight = 0; imageEditor.AddText("Text"); } void AddRect(object sender, System.EventArgs e) { isPath = false; if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { if (!isOpen) { OpenColorPalette(); isOpen = true; } } model.IsColorPaletteVisible = true; imageEditor.ToolbarSettings.SubItemToolbarHeight = 0; imageEditor.AddShape(ShapeType.Rectangle); } void Undo(object sender, System.EventArgs e) { if (imageEditor.IsImageEdited || Device.RuntimePlatform == Device.UWP) { imageEditor.Undo(); if (model.UndoCount > 0) model.UndoCount--; model.RedoCount++; } } void Share(object sender, System.EventArgs e) { Share(); } void OpenToolbar() { toolbarGrid.TranslateTo(0, 20, 400, Easing.Linear); } void CloseToolbar() { toolbarGrid.TranslateTo(0, -70, 400, Easing.Linear); } ImageModel model; void CloseColorPalette() { colorPalette.TranslateTo(this.Width, 0, 200, Easing.Linear); } void OpenColorPalette() { colorPalette.TranslateTo((-this.Width + 2 * colorPalette.Width) / 20, 0, 200, Easing.Linear); } async void Share() { imageEditor.Save(); imageEditor.ImageSaved += (sender, args) => { location = args.Location; }; await DelayActionAsync(1000, Sharing); } public async Task DelayActionAsync(int delay, Action action) { await Task.Delay(delay); action(); } void Sharing() { var temp = location; var share = DependencyService.Get<IShare>(); if (string.IsNullOrEmpty(captionTextBox.Text)) { } share.Show("Title", string.IsNullOrEmpty(captionTextBox.Text) ? "Message" : captionTextBox.Text.ToString(), temp); } private string location = ""; public Customization() { model = new ImageModel(); this.BindingContext = model; InitializeComponent(); Assembly assembly = typeof(ImageSerializeModel).GetTypeInfo().Assembly; #if COMMONSB imageEditor.Source = ImageSource.FromResource("SampleBrowser.Icons.EditorTable.jpg", assembly); #else imageEditor.Source = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorTable.jpg", assembly); #endif imageEditor.ToolbarSettings = new ToolbarSettings() { IsVisible = false }; imageEditor.ItemSelected += ImageEditor_ItemSelected; imageEditor.ItemUnselected += ImageEditor_ItemUnselected; if (Device.RuntimePlatform != Device.Android && Device.RuntimePlatform != Device.iOS) { resetButton.Text = "\ue74a"; redoButton.Text = "\ue739"; undoButton.Text = "\ue716"; rectButton.Text = "\ue701"; textButton.Text = "\ue749"; penButton.Text = "\ue747"; shareButton.Text = "\ue751"; captionTextBox.TextColor = Color.Black; } } private object Settings; private void ImageEditor_ItemSelected(object sender, ItemSelectedEventArgs args) { Settings = args.Settings; OpenColorPalette(); } private void ImageEditor_ItemUnselected(object sender, ItemUnselectedEventArgs e) { CloseColorPalette(); isOpen = false; } private void ShareButton_OnClicked(object sender, EventArgs e) { Share(); } } public class InverseBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return !(bool)value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return !(bool)value; } } public class CountToBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((int)value > 0) return true; return false; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (!(bool)value) return 0; return 1; } } }<file_sep>/iOS/SampleBrowser/Samples/DocIO/BuiltInStyle.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class BuiltInStyle : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton button; public BuiltInStyle() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to format the Word document contents with the built-in styles."; label.Lines = 0; label.Font = UIFont.SystemFontOfSize(15); label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 60); } else { label.Frame = new CGRect(frameRect.Location.X, 10, frameRect.Size.Width, 60); } this.AddSubview(label); ; button.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(5, 80, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 80, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { // Creating a new document. WordDocument document = new WordDocument(); WSection section = document.AddSection() as WSection; //Set Margin of the section section.PageSetup.Margins.All = 72; WParagraph para = section.AddParagraph() as WParagraph; section.AddColumn(100, 100); section.AddColumn(100, 100); section.MakeColumnsEqual(); #region Built-in styles # region List Style //List //para = section.AddParagraph() as WParagraph; para.AppendText("This para is written with style List").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.List); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //List5 style para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style List5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.List5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region ListNumber Style //List Number style para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListNumber").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListNumber); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //List Number5 style para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListNumber5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListNumber5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region TOA Heading Style //TOA Heading para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style TOA Heading").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ToaHeading); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion para = section.AddParagraph() as WParagraph; section.BreakCode = SectionBreakCode.NewColumn; # region ListBullet Style //ListBullet para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListBullet").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListBullet); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //ListBullet5 para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListBullet5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListBullet5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region List Continue Style //ListContinue para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListContinue").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListContinue); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //ListContinue5 para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListContinue5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListContinue5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region HTMLSample Style //HtmlSample para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style HtmlSample").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.HtmlSample); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion section = document.AddSection() as WSection; section.BreakCode = SectionBreakCode.NoBreak; # region Document Map Style //Docuemnt Map para = section.AddParagraph() as WParagraph; para.AppendText("This para is written with style DocumentMap\n").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.DocumentMap); IWTextRange textrange = para.AppendText("Google Chrome\n"); textrange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; textrange = para.AppendText("Mozilla Firefox\n"); textrange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; textrange = para.AppendText("Internet Explorer"); textrange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; #endregion # region Heading Styles //Heading Styles para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading1); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading2); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading3); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading4); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading5); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading6); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading7); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading8); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading9); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); # endregion #endregion Built-in styles #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("BuiltinStyle.docx", "application/msword", stream); } #endregion } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Frame; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Forms/ListView/ListView/Samples/ItemReordering/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.ListView.XForms.Control.Helpers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewToDoViewModel : INotifyPropertyChanged { #region Fields private ObservableCollection<ToDoItem> toDoList; private Command<object> markDoneCommand; #endregion #region Constructor public ListViewToDoViewModel() { this.GenerateSource(); MarkDoneCommand = new Command<object>(MarkItemAsDone); } private void MarkItemAsDone(object obj) { var item = obj as ToDoItem; item.IsDone = !item.IsDone; } #endregion #region Property public Command<object> MarkDoneCommand { get { return markDoneCommand; } set { if(markDoneCommand != value) { markDoneCommand = value; OnPropertyChanged("MarkDoneCommand"); } } } public ObservableCollection<ToDoItem> ToDoList { get { return toDoList; } set { this.toDoList = value; } } #endregion #region Method public void GenerateSource() { ToDoListRepository groceryRepository = new ToDoListRepository(); toDoList = groceryRepository.GetToDoList(); } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/SelectionControllerStyle.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SelectionControllerStyle.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.GridCommon.ScrollAxis; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; /// <summary> /// Derived from DataGridStyle to add the custom styles /// </summary> public class SelectionControllerStyle : Syncfusion.SfDataGrid.XForms.DefaultStyle { /// <summary> /// Initializes a new instance of the SelectionControllerStyle class. /// </summary> public SelectionControllerStyle() { } /// <summary> /// Overrides this method to write a custom style for selection back ground color. /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetSelectionBackgroundColor() { return Color.FromHex("#b2d8f7"); } } } <file_sep>/iOS/SampleBrowser/Samples/TreeMap/Hierarchical.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfTreeMap.iOS; #if __UNIFIED__ using UIKit; using CoreGraphics; using Foundation; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Hierarchical : SampleView { #region Fields SFTreeMap tree ; UILabel label; UIView view; #endregion public Hierarchical () { // TreeMap Initialization view = new UIView(); label = new UILabel(); tree = new SFTreeMap (); tree.WeightValuePath = (NSString)"Sales"; SFDesaturationColorMapping desat = new SFDesaturationColorMapping (); desat.Color = UIColor.FromRGB (0x41, 0xB8, 0xC4); desat.From = 1; desat.To = 0.2f; tree.ColorValuePath = (NSString)"Expense"; tree.LeafItemColorMapping = desat; SFTreeMapHierarchicalLevel level = new SFTreeMapHierarchicalLevel() { ChildPadding=4, HeaderStyle = new SFStyle(){Color = UIColor.DarkGray}, ShowHeader = true, HeaderHeight = 20, HeaderPath = (NSString)"Name", ChildPath = (NSString)"RegionalSales" }; tree.Levels.Add (level); tree.LeafItemSettings = new SFLeafItemSetting (){ ShowLabels = true, Gap = 5, BorderColor = UIColor.White, BorderWidth = 2 }; tree.LeafItemSettings.LabelStyle = new SFStyle () { Color = UIColor.White }; tree.LeafItemSettings.LabelPath =(NSString)"Name"; GetPopulationData (); tree.DataSource = PopulationDetails; AddSubview (view); } public override void LayoutSubviews() { label.Text = "Hierarchical"; label.Frame = new CGRect(0, 0, 300, 30); base.LayoutSubviews(); view.Frame = new CGRect(0, 0, Frame.Size.Width, Frame.Size.Height); tree.Frame = new CGRect(0, 0, Frame.Size.Width - 6, Frame.Size.Height); view.AddSubview(tree); label.Frame = new CGRect(0, 0, Frame.Size.Width, 40); tree.LegendSettings.Size = new CGSize(this.Frame.Size.Width, 60); SetNeedsDisplay(); } void GetPopulationData () { NSMutableArray array = new NSMutableArray (); NSMutableArray regional1 = new NSMutableArray (); regional1.Add(getDictionary ("United States", "New York", 2353, 2000)); regional1.Add(getDictionary("United States", "Los Angeles", 3453, 3000)); regional1.Add(getDictionary("United States", "San Francisco", 8456, 8000)); regional1.Add(getDictionary("United States", "Chicago", 6785, 7000)); regional1.Add(getDictionary("United States", "Miami", 7045, 6000)); NSMutableArray regional2 = new NSMutableArray (); regional2.Add(getDictionary ("Canada", "Toronto", 7045, 7000)); regional2.Add(getDictionary("Canada", "Vancouver", 4352, 4000)); regional2.Add(getDictionary("Canada", "Winnipeg", 7843, 7500)); NSMutableArray regional3 = new NSMutableArray (); regional3.Add(getDictionary ("Mexico", "Mexico City", 7843, 6500)); regional3.Add(getDictionary("Mexico", "Cancun", 6683, 6000)); regional3.Add(getDictionary("Mexico", "Acapulco", 2454, 2000)); array.Add(getDictionary1("United States",98456, 87000,regional1)); array.Add(getDictionary1("Canada",43523, 40000,regional2)); array.Add(getDictionary1("Mexico",45634, 46000,regional3)); PopulationDetails = array; } NSDictionary getDictionary1(string continent,double region,double growth,NSMutableArray population) { object[] objects= new object[4]; object[] keys=new object[4]; keys.SetValue ("Name", 0); keys.SetValue ("Expense", 1); keys.SetValue ("Sales", 2); keys.SetValue ("RegionalSales", 3); objects.SetValue ((NSString)continent, 0); objects.SetValue (region, 1); objects.SetValue (growth, 2); objects.SetValue (population, 3); return NSDictionary.FromObjectsAndKeys (objects, keys); } NSDictionary getDictionary(string continent,string region,double growth,double population) { object[] objects= new object[4]; object[] keys=new object[4]; keys.SetValue ("Country", 0); keys.SetValue ("Name", 1); keys.SetValue ("Expense", 2); keys.SetValue ("Sales", 3); objects.SetValue ((NSString)continent, 0); objects.SetValue ((NSString)region, 1); objects.SetValue (growth, 2); objects.SetValue (population, 3); return NSDictionary.FromObjectsAndKeys (objects, keys); } public NSMutableArray PopulationDetails { get; set; } } } <file_sep>/Android/SampleBrowser/Samples/Presentation/HeaderAndFooter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public partial class HeaderAndFooterPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to insert the header and footer in a PowerPoint presentation."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Presentation"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.HeaderFooter.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a existing PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Add footers into all the PowerPoint slides. foreach (ISlide slide in presentation.Slides) { //Enable a date and time footer in slide. slide.HeadersFooters.DateAndTime.Visible = true; //Enable a footer in slide. slide.HeadersFooters.Footer.Visible = true; //Sets the footer text. slide.HeadersFooters.Footer.Text = "Footer"; //Enable a slide number footer in slide. slide.HeadersFooters.SlideNumber.Visible = true; } //Add header into first slide notes page. //Add a notes slide to the slide. INotesSlide notesSlide = presentation.Slides[0].AddNotesSlide(); //Enable a header in notes slide. notesSlide.HeadersFooters.Header.Visible = true; //Sets the header text. notesSlide.HeadersFooters.Header.Text = "Header"; MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("HeaderFooter.pptx", "application/powerpoint", stream, m_context); } } } } <file_sep>/Forms/Presentation/Presentation/Samples/PPTXToPDF/PPTXToPDF.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using SampleBrowser.Core; using Syncfusion.Pdf; using Syncfusion.PresentationRenderer; namespace SampleBrowser.Presentation { public partial class PPTXToPDF : SampleView { public PPTXToPDF() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInpTemplate.HorizontalOptions = LayoutOptions.Start; this.btnInpTemplate.VerticalOptions = LayoutOptions.Center; this.btnInpTemplate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnInpTemplate.VerticalOptions = LayoutOptions.Center; } } void OnInputButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Template.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Template.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); stream.Position = 0; fileStream.Dispose(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Template.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Template.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Convert the PowerPoint document to PDF document. PdfDocument pdfDocument = PresentationToPdfConverter.Convert(presentation); //Save the converted PDF document. MemoryStream pdfStream = new MemoryStream(); pdfDocument.Save(pdfStream); pdfStream.Position = 0; //Close the PDF document. pdfDocument.Close(true); //Close the PowerPoint Presentation. presentation.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("PPTXToPDF.pdf", "application/pdf", pdfStream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("PPTXToPDF.pdf", "application/pdf", pdfStream); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/Employee.cs #pragma warning disable SA1638 // FileHeaderFileNameDocumentationMustMatchFileName #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Employee.cs" company="Sync<EMAIL>"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1649:FileHeaderFileNameDocumentationMustMatchTypeName", Justification = "Reviewed.")] namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties and notifies clients that a property value has changed. /// </summary> public class NotificationObject : INotifyPropertyChanged { /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="propName">string type of parameter as propName</param> public void RaisePropertyChanged(string propName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } } /// <summary> /// Notifies clients that a property value has changed. /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed.")] public class BaseEmployee : NotificationObject { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int employeeID; /// <summary> /// Gets or sets the value of EmployeeID and notifies user when value gets changed /// </summary> public int EmployeeID { get { return this.employeeID; } set { this.employeeID = value; this.RaisePropertyChanged("EmployeeID"); } } } /// <summary> /// Notifies clients that a property value has changed. /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed.")] public class Employee : BaseEmployee { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string name; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int contactID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string title; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DateTime birthDate; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string gender; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double sickLeaveHours; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private decimal salary; /// <summary> /// Gets or sets the value of ContactID and notifies user when value gets changed /// </summary> public int ContactID { get { return this.contactID; } set { this.contactID = value; this.RaisePropertyChanged("ContactID"); } } /// <summary> /// Gets or sets the value of Name and notifies user when value gets changed /// </summary> public string Name { get { return this.name; } set { this.name = value; this.RaisePropertyChanged("Name"); } } /// <summary> /// Gets or sets the value of Salary and notifies user when value gets changed /// </summary> public decimal Salary { get { return this.salary; } set { this.salary = value; this.RaisePropertyChanged("Salary"); } } /// <summary> /// Gets or sets the value of Title and notifies user when value gets changed /// </summary> public string Title { get { return this.title; } set { this.title = value; this.RaisePropertyChanged("Title"); } } /// <summary> /// Gets or sets the value of BirthDate and notifies user when value gets changed /// </summary> public DateTime BirthDate { get { return this.birthDate; } set { this.birthDate = value; this.RaisePropertyChanged("BirthDate"); } } /// <summary> /// Gets or sets the value of Gender and notifies user when value gets changed /// </summary> public string Gender { get { return this.gender; } set { this.gender = value; this.RaisePropertyChanged("Gender"); } } /// <summary> /// Gets or sets the value of SickLeaveHours and notifies user when value gets changed /// </summary> public double SickLeaveHours { get { return this.sickLeaveHours; } set { this.sickLeaveHours = value; this.RaisePropertyChanged("SickLeaveHours"); } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/ViewModel/ChartViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Collections.ObjectModel; using System.Threading.Tasks; using Foundation; using System.Collections.Generic; namespace SampleBrowser { public class ChartViewModel { DateTime time = new DateTime(2015, 01, 01); DateTime dataTime = new DateTime(2015, 01, 1); Random random = new Random(); DateTime date = new DateTime(); public int wave1 = 0; public int wave2 = 180; public int verticalCount; public ObservableCollection<ChartDataModel> PolarData1 { get; set; } public ObservableCollection<ChartDataModel> DataMarkerData { get; set; } public ObservableCollection<ChartDataModel> PolarData2 { get; set; } public ObservableCollection<ChartDataModel> PolarData3 { get; set; } public ObservableCollection<ChartDataModel> AreaData { get; set; } public ObservableCollection<ChartDataModel> AreaData1 { get; set; } public ObservableCollection<ChartDataModel> AreaData2 { get; set; } public ObservableCollection<ChartDataModel> AreaData3 { get; set; } public ObservableCollection<ChartDataModel> StepAreaData1 { get; set; } public ObservableCollection<ChartDataModel> StepAreaData2 { get; set; } public ObservableCollection<ChartDataModel> LineData { get; set; } public ObservableCollection<ChartDataModel> LineData1 { get; set; } public ObservableCollection<ChartDataModel> LineData2 { get; set; } public ObservableCollection<ChartDataModel> StepLineData1 { get; set; } public ObservableCollection<ChartDataModel> StepLineData2 { get; set; } public ObservableCollection<ChartDataModel> StepLineData3 { get; set; } public ObservableCollection<ChartDataModel> ColumnData1 { get; set; } public ObservableCollection<ChartDataModel> ColumnData2 { get; set; } public ObservableCollection<ChartDataModel> ColumnData3 { get; set; } public ObservableCollection<ChartDataModel> BarData1 { get; set; } public ObservableCollection<ChartDataModel> BarData2 { get; set; } public ObservableCollection<ChartDataModel> SplineData1 { get; set; } public ObservableCollection<ChartDataModel> SplineData2 { get; set; } public ObservableCollection<ChartDataModel> SplineAreaData1 { get; set; } public ObservableCollection<ChartDataModel> SplineAreaData2 { get; set; } public ObservableCollection<ChartDataModel> SplineAreaData3 { get; set; } public ObservableCollection<ChartDataModel> RangeColumnData1 { get; set; } public ObservableCollection<ChartDataModel> RangeColumnData2 { get; set; } public ObservableCollection<ChartDataModel> RangeAreaData { get; set; } public ObservableCollection<ChartDataModel> RangeAreaData1 { get; set; } public ObservableCollection<ChartDataModel> RangeBarData { get; set; } public ObservableCollection<ChartDataModel> PieSeriesData { get; set; } public ObservableCollection<ChartDataModel> SemiCircularData { get; set; } public ObservableCollection<ChartDataModel> DoughnutSeriesData { get; set; } public ObservableCollection<ChartDataModel> PyramidData { get; set; } public ObservableCollection<ChartDataModel> FunnelData { get; set; } public ObservableCollection<ChartDataModel> StackedBarData1 { get; set; } public ObservableCollection<ChartDataModel> StackedBarData2 { get; set; } public ObservableCollection<ChartDataModel> StackedBarData3 { get; set; } public ObservableCollection<ChartDataModel> StackedBar100Data1 { get; set; } public ObservableCollection<ChartDataModel> StackedBar100Data2 { get; set; } public ObservableCollection<ChartDataModel> StackedBar100Data3 { get; set; } public ObservableCollection<ChartDataModel> StackedBar100Data4 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData1 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData2 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData3 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData4 { get; set; } public ObservableCollection<ChartDataModel> StackedAreaData1 { get; set; } public ObservableCollection<ChartDataModel> StackedAreaData2 { get; set; } public ObservableCollection<ChartDataModel> StackedAreaData3 { get; set; } public ObservableCollection<ChartDataModel> StackedAreaData4 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data1 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data2 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data3 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data4 { get; set; } public ObservableCollection<ChartDataModel> StepLineData { get; set; } public ObservableCollection<ChartDataModel> CircularData { get; set; } public ObservableCollection<ChartDataModel> MultipleAxisData { get; set; } public ObservableCollection<ChartDataModel> MultipleAxisData1 { get; set; } public ObservableCollection<ChartDataModel> BubbleData { get; set; } public ObservableCollection<ChartDataModel> ScatterData { get; set; } public ObservableCollection<ChartDataModel> BoxAndWhiskerData { get; set; } public ObservableCollection<ChartDataModel> ErrorBarData { get; set; } public ObservableCollection<ChartDataModel> ScatterDataZoomPan { get { var items = new ObservableCollection<ChartDataModel>(); for (int i = 0; i < 300; i++) { double x = random.NextDouble() * 100; double y = random.NextDouble() * 500; double randomDouble = random.NextDouble(); if (randomDouble >= .25 && randomDouble < .5) { x *= -1; } else if (randomDouble >= .5 && randomDouble < .75) { y *= -1; } else if (randomDouble > .75) { x *= -1; y *= -1; } items.Add(new ChartDataModel(300 + (x * (random.NextDouble() + 0.12)), 100 + (y * (random.NextDouble() + 0.12)))); } return items; } } public ObservableCollection<ChartDataModel> Data1 { get; set; } public ObservableCollection<ChartDataModel> Data2 { get; set; } public ObservableCollection<ChartDataModel> datas1 { get; set; } public ObservableCollection<ChartDataModel> Data3 { get; set; } public ObservableCollection<ChartDataModel> CategoryData { get; set; } public ObservableCollection<ChartDataModel> LogarithmicData { get; set; } public ObservableCollection<ChartDataModel> RangeColumnData { get; set; } public ObservableCollection<ChartDataModel> FinancialData { get; set; } public ObservableCollection<ChartDataModel> NumericData { get; set; } public ObservableCollection<ChartDataModel> DateTimeAxisData { get { var dateTime = new DateTime(2017, 1, 1); var datas = new ObservableCollection<ChartDataModel>(); System.Random random = new System.Random(); double value = 100; for (int i = 0; i < 365; i++) { if (random.NextDouble() > 0.5) value += random.NextDouble(); else value -= random.NextDouble(); datas.Add(new ChartDataModel(dateTime, value)); dateTime = dateTime.AddDays(1); } return datas; } } public ObservableCollection<ChartDataModel> GradientData { get { DateTime date = new DateTime(2017, 5, 1); ObservableCollection<ChartDataModel> gradientData = new ObservableCollection<ChartDataModel>(); gradientData.Add(new ChartDataModel(date, 29)); gradientData.Add(new ChartDataModel(date.AddDays(6), 33)); gradientData.Add(new ChartDataModel(date.AddDays(15), 24)); gradientData.Add(new ChartDataModel(date.AddDays(23), 28)); gradientData.Add(new ChartDataModel(date.AddDays(30), 26)); gradientData.Add(new ChartDataModel(date.AddDays(39), 38)); gradientData.Add(new ChartDataModel(date.AddDays(50), 32)); return gradientData; } } public ObservableCollection<ChartDataModel> DateTimeData { get; set; } public ObservableCollection<ChartDataModel> SelectionData { get; set; } public ObservableCollection<ChartDataModel> data { get; set; } public ObservableCollection<ChartDataModel> liveData1 { get { var items = new ObservableCollection<ChartDataModel>(); for (var i = 0; i <= 180; i++) { items.Add(new ChartDataModel(i, Math.Sin(wave1 * (Math.PI / 180.0)))); wave1++; } return items; } } public ObservableCollection<ChartDataModel> liveData2 { get { var items = new ObservableCollection<ChartDataModel>(); for (var i = 0; i <= 180; i++) { items.Add(new ChartDataModel(i, Math.Sin(wave2 * (Math.PI / 180.0)))); wave2++; } return items; } } public ObservableCollection<ChartDataModel> verticalData { get { var items = new ObservableCollection<ChartDataModel>(); date = new DateTime(2011,3,11,14,46,0); for (int i = 0; i < 30; i++) { var verData = dataPointWithTimeInterval(0.15); items.Add(new ChartDataModel(verData.XValue, verData.YValue)); verticalCount = items.Count; } return items; } } public ObservableCollection<ChartDataModel> PieData { get; set; } public ObservableCollection<ChartDataModel> StripLineData { get; set; } public ObservableCollection<ChartDataModel> MultipleSeriesData1 { get; set; } public ObservableCollection<ChartDataModel> MultipleSeriesData2 { get; set; } public ObservableCollection<ChartDataModel> LineSeries1 { get; set; } public ObservableCollection<ChartDataModel> LineSeries2 { get; set; } public ObservableCollection<ChartDataModel> LineSeries3 { get; set; } public ObservableCollection<ChartDataModel> TriangularData { get; set; } public ObservableCollection<ChartDataModel> TooltipData { get; set; } public ObservableCollection<ChartDataModel> DateTimeRangeData { get; set; } public ObservableCollection<ChartDataModel> DateUsageData { get; set; } public ObservableCollection<ChartDataModel> TechnicalIndicatorData { get; set; } public ObservableCollection<ChartDataModel> AxisCrossingData { get; set; } public ChartViewModel() { DateTime calendar = new DateTime(2000, 1, 1); DateTime dt = new DateTime(2000, 1, 1); AxisCrossingData = new ObservableCollection<ChartDataModel>() { new ChartDataModel{XValue = "2000",YValue = 70, Size = 5}, new ChartDataModel{XValue = "2001",YValue = 50, Size = 8}, new ChartDataModel{XValue = "2002",YValue = -30, Size = 30}, new ChartDataModel{XValue = "2003",YValue = -70, Size = 10}, new ChartDataModel{XValue = "2004",YValue = 40, Size = 12}, new ChartDataModel{XValue = "2005",YValue = 80, Size = 13}, new ChartDataModel{XValue = "2006",YValue = -70, Size = 6}, new ChartDataModel{XValue = "2007",YValue = 30, Size = 8}, new ChartDataModel{XValue = "2008",YValue = 80, Size = 3}, new ChartDataModel{XValue = "2009",YValue = -30, Size = 5}, new ChartDataModel{XValue = "2010",YValue = -80, Size = 7}, new ChartDataModel{XValue = "2011",YValue = 40, Size = 3}, new ChartDataModel{XValue = "2012",YValue = -50, Size = 8}, new ChartDataModel{XValue = "2013",YValue = -10, Size = 4}, new ChartDataModel{XValue = "2014",YValue = -80, Size = 9}, new ChartDataModel{XValue = "2015",YValue = 40, Size = 10}, new ChartDataModel{XValue = "2016",YValue = -50, Size = 6}, }; TechnicalIndicatorData = new ObservableCollection<ChartDataModel> { new ChartDataModel(calendar.AddMonths(1), 65.75, 67.27, 65.75, 65.98, 7938200), new ChartDataModel(calendar.AddMonths(2), 65.98, 65.70, 65.04, 65.11, 10185300), new ChartDataModel(calendar.AddMonths(3), 65.11, 65.05, 64.26, 64.97, 10835800), new ChartDataModel(calendar.AddMonths(4), 64.97, 65.16, 64.09, 64.29, 9613400), new ChartDataModel(calendar.AddMonths(5), 64.29, 62.73, 61.85, 62.44, 17175000), new ChartDataModel(calendar.AddMonths(6), 62.44, 62.02, 61.29, 61.47, 18040600), new ChartDataModel(calendar.AddMonths(7), 61.47, 62.75, 61.55, 61.59, 13456300), new ChartDataModel(calendar.AddMonths(8), 61.59, 64.78, 62.22, 64.64, 8045100), new ChartDataModel(calendar.AddMonths(9), 64.64, 64.50, 63.03, 63.28, 8608900), new ChartDataModel(calendar.AddMonths(10), 63.28, 63.70, 62.70, 63.59, 15025500), new ChartDataModel(calendar.AddMonths(11), 63.59, 64.45, 63.26, 63.61, 10065800), new ChartDataModel(calendar.AddMonths(12), 63.61, 64.56, 63.81, 64.52, 6178200), new ChartDataModel(calendar.AddMonths(13), 64.52, 64.84, 63.66, 63.91, 5478500), new ChartDataModel(calendar.AddMonths(14), 63.91, 65.30, 64.50, 65.22, 7964300), new ChartDataModel(calendar.AddMonths(15), 65.22, 65.36, 64.46, 65.06, 5679300), new ChartDataModel(calendar.AddMonths(16), 65.06, 64.54, 63.56, 63.65, 10758300), new ChartDataModel(calendar.AddMonths(17), 63.65, 64.03, 63.33, 63.73, 5665900), new ChartDataModel(calendar.AddMonths(18), 63.73, 63.40, 62.80, 62.83, 5833000), new ChartDataModel(calendar.AddMonths(19), 62.83, 63.75, 62.96, 63.60, 3500800), new ChartDataModel(calendar.AddMonths(20), 63.6, 63.64, 62.51, 63.51, 5044700), new ChartDataModel(calendar.AddMonths(21), 63.51, 64.03, 63.53, 63.76, 4871300), new ChartDataModel(calendar.AddMonths(22), 63.76, 63.77, 63.01, 63.65, 7040400), new ChartDataModel(calendar.AddMonths(23), 63.65, 63.95, 63.58, 63.79, 4727800), new ChartDataModel(calendar.AddMonths(24), 63.79, 63.47, 62.92, 63.25, 6334900), new ChartDataModel(calendar.AddMonths(25), 63.25, 63.96, 63.21, 63.48, 6823200), new ChartDataModel(calendar.AddMonths(26), 63.48, 63.63, 62.55, 63.50, 9718400), new ChartDataModel(calendar.AddMonths(27), 63.5, 63.25, 62.82, 62.90, 2827000), new ChartDataModel(calendar.AddMonths(28), 62.9, 62.34, 62.05, 62.18, 4942700), new ChartDataModel(calendar.AddMonths(29), 62.18, 62.86, 61.94, 62.81, 4582800), new ChartDataModel(calendar.AddMonths(30), 62.81, 63.06, 62.44, 62.83, 12423900), new ChartDataModel(calendar.AddMonths(31), 62.83, 63.16, 62.66, 63.09, 4940500), new ChartDataModel(calendar.AddMonths(32), 63.09, 62.89, 62.43, 62.66, 6132300), new ChartDataModel(calendar.AddMonths(33), 62.66, 62.39, 61.90, 62.25, 6263800), new ChartDataModel(calendar.AddMonths(34), 62.25, 61.69, 60.97, 61.50, 5008300), new ChartDataModel(calendar.AddMonths(35), 61.5, 61.87, 61.18, 61.79, 6662500), new ChartDataModel(calendar.AddMonths(36), 61.79, 63.41, 62.72, 63.16, 5254000), new ChartDataModel(calendar.AddMonths(37), 63.16, 64.40, 63.65, 63.89, 5356600), new ChartDataModel(calendar.AddMonths(38), 63.89, 63.45, 61.60, 61.87, 5052600), new ChartDataModel(calendar.AddMonths(39), 61.87, 62.35, 61.30, 61.54, 6266700), new ChartDataModel(calendar.AddMonths(40), 61.54, 61.49, 60.33, 61.06, 6190800), new ChartDataModel(calendar.AddMonths(41), 61.06, 60.78, 59.84, 60.09, 6452300), new ChartDataModel(calendar.AddMonths(42), 60.09, 59.62, 58.62, 58.80, 5954000), new ChartDataModel(calendar.AddMonths(43), 58.8, 59.60, 58.89, 59.53, 6250000), new ChartDataModel(calendar.AddMonths(44), 59.53, 60.96, 59.42, 60.68, 5307300), new ChartDataModel(calendar.AddMonths(45), 60.68, 61.12, 60.65, 60.73, 6192900), new ChartDataModel(calendar.AddMonths(46), 60.73, 61.19, 60.62, 61.19, 6355600), new ChartDataModel(calendar.AddMonths(47), 61.19, 61.07, 60.54, 60.97, 2946300), new ChartDataModel(calendar.AddMonths(48), 60.97, 61.05, 59.65, 59.75, 2257600), new ChartDataModel(calendar.AddMonths(49), 59.75, 60.58, 55.99, 59.93, 2872000), new ChartDataModel(calendar.AddMonths(50), 59.93, 60.12, 59.26, 59.73, 2737500), new ChartDataModel(calendar.AddMonths(51), 59.73, 60.11, 59.35, 59.57, 2589700), new ChartDataModel(calendar.AddMonths(52), 59.57, 60.40, 59.60, 60.10, 7315800), new ChartDataModel(calendar.AddMonths(53), 60.1, 60.31, 59.76, 60.28, 6883900), new ChartDataModel(calendar.AddMonths(54), 60.28, 61.68, 60.50, 61.50, 5570700), new ChartDataModel(calendar.AddMonths(55), 61.5, 62.72, 61.64, 62.26, 5976000), new ChartDataModel(calendar.AddMonths(56), 62.26, 64.08, 63.10, 63.70, 3641400), new ChartDataModel(calendar.AddMonths(57), 63.7, 64.60, 63.99, 64.39, 6711600), new ChartDataModel(calendar.AddMonths(58), 64.39, 64.45, 63.92, 64.25, 6427000), new ChartDataModel(calendar.AddMonths(59), 64.25, 65.40, 64.66, 64.70, 5863200), new ChartDataModel(calendar.AddMonths(60), 64.7, 65.86, 65.32, 65.75, 4711400), new ChartDataModel(calendar.AddMonths(61), 65.75, 65.22, 64.63, 64.75, 5930600), new ChartDataModel(calendar.AddMonths(62), 64.75, 65.39, 64.76, 65.04, 5602700), new ChartDataModel(calendar.AddMonths(63), 65.04, 65.30, 64.78, 65.18, 7487300), new ChartDataModel(calendar.AddMonths(64), 65.18, 65.09, 64.42, 65.09, 9085400), new ChartDataModel(calendar.AddMonths(65), 65.09, 65.64, 65.20, 65.25, 6455300), new ChartDataModel(calendar.AddMonths(66), 65.25, 65.59, 64.74, 64.84, 6135500), new ChartDataModel(calendar.AddMonths(67), 64.84, 65.84, 65.42, 65.82, 5846400), new ChartDataModel(calendar.AddMonths(68), 65.82, 66.75, 65.85, 66.00, 6681200), new ChartDataModel(calendar.AddMonths(69), 66, 67.41, 66.17, 67.41, 8780000), new ChartDataModel(calendar.AddMonths(70), 67.41, 68.61, 68.06, 68.41, 10780900), new ChartDataModel(calendar.AddMonths(71), 68.41, 68.91, 68.42, 68.76, 2336450), new ChartDataModel(calendar.AddMonths(72), 68.76, 69.58, 68.86, 69.01, 11902000), new ChartDataModel(calendar.AddMonths(73), 69.01, 69.14, 68.74, 68.94, 7513300), new ChartDataModel(calendar.AddMonths(74), 68.94, 68.73, 68.06, 68.65, 12074800), new ChartDataModel(calendar.AddMonths(75), 68.65, 68.79, 68.19, 68.67, 8785400), new ChartDataModel(calendar.AddMonths(76), 68.67, 69.75, 68.68, 68.74, 11373200), new ChartDataModel(calendar.AddMonths(77), 68.74, 68.82, 67.71, 67.76, 12378300), new ChartDataModel(calendar.AddMonths(78), 67.76, 69.05, 68.43, 69.00, 8458700), new ChartDataModel(calendar.AddMonths(79), 69, 68.39, 67.77, 68.02, 10779200), new ChartDataModel(calendar.AddMonths(80), 68.02, 67.94, 67.22, 67.72, 9665400), new ChartDataModel(calendar.AddMonths(81), 67.72, 68.15, 67.32, 67.32, 12258400), new ChartDataModel(calendar.AddMonths(82), 67.32, 67.95, 67.13, 67.32, 7563600), new ChartDataModel(calendar.AddMonths(83), 67.32, 68.00, 67.16, 67.96, 5509900), new ChartDataModel(calendar.AddMonths(84), 67.96, 68.89, 68.34, 68.61, 12135500), new ChartDataModel(calendar.AddMonths(85), 68.61, 69.47, 68.30, 68.51, 8462000), new ChartDataModel(calendar.AddMonths(86), 68.51, 68.69, 68.21, 68.62, 2011950), new ChartDataModel(calendar.AddMonths(87), 68.62, 68.39, 65.80, 68.37, 8536800), new ChartDataModel(calendar.AddMonths(88), 68.37, 67.75, 65.00, 62.00, 7624900), new ChartDataModel(calendar.AddMonths(89), 67.62, 67.04, 65.04, 67.00, 13694600), new ChartDataModel(calendar.AddMonths(90), 66, 66.83, 65.02, 67.60, 8911200), new ChartDataModel(calendar.AddMonths(91), 66.6, 66.98, 65.44, 66.73, 6679600), new ChartDataModel(calendar.AddMonths(92), 66.73, 66.84, 65.10, 66.11, 6451900), new ChartDataModel(calendar.AddMonths(93), 66.11, 66.59, 65.69, 66.38, 6739100), new ChartDataModel(calendar.AddMonths(94), 66.38, 67.98, 66.51, 67.67, 2103260), new ChartDataModel(calendar.AddMonths(95), 67.67, 69.21, 68.59, 68.90, 10551800), new ChartDataModel(calendar.AddMonths(96), 68.9, 69.96, 69.27, 69.44, 5261100), new ChartDataModel(calendar.AddMonths(97), 69.44, 69.01, 68.14, 68.18, 5905400), new ChartDataModel(calendar.AddMonths(98), 68.18, 68.93, 68.08, 68.14, 10283600), new ChartDataModel(calendar.AddMonths(99), 68.14, 68.60, 66.92, 67.25, 5006800), new ChartDataModel(calendar.AddMonths(100), 67.25, 67.77, 67.23, 67.77, 4110000) }; DateTimeRangeData = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2015, 01, 1), 14), new ChartDataModel(new DateTime(2015, 02, 1), 54), new ChartDataModel(new DateTime(2015, 03, 1), 23), new ChartDataModel(new DateTime(2015, 04, 1), 53), new ChartDataModel(new DateTime(2015, 05, 1), 25), new ChartDataModel(new DateTime(2015, 06, 1), 32), new ChartDataModel(new DateTime(2015, 07, 1), 78), new ChartDataModel(new DateTime(2015, 08, 1), 100), new ChartDataModel(new DateTime(2015, 09, 1), 55), new ChartDataModel(new DateTime(2015, 10, 1), 38), new ChartDataModel(new DateTime(2015, 11, 1), 27), new ChartDataModel(new DateTime(2015, 12, 1), 56), new ChartDataModel(new DateTime(2015, 12, 31), 35), }; DateUsageData = new ObservableCollection<ChartDataModel>(); DateUsageData.Add(new ChartDataModel(dataTime, 14)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 54)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 23)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 53)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 25)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 32)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 78)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 100)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 55)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 38)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 27)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 56)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 55)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 38)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 27)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 56)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 30)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 45)); PolarData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("N", 80), new ChartDataModel("NE", 85), new ChartDataModel("E", 78), new ChartDataModel("SE", 90), new ChartDataModel("S", 78), new ChartDataModel("SW", 83), new ChartDataModel("W", 79), new ChartDataModel("NW", 88) }; PolarData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("N", 63), new ChartDataModel("NE", 70), new ChartDataModel("E", 45), new ChartDataModel("SE", 70), new ChartDataModel("S", 47), new ChartDataModel("SW", 65), new ChartDataModel("W", 58), new ChartDataModel("NW", 73) }; PolarData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("N", 42), new ChartDataModel("NE", 40), new ChartDataModel("E", 25), new ChartDataModel("SE", 40), new ChartDataModel("S", 20), new ChartDataModel("SW", 45), new ChartDataModel("W", 40), new ChartDataModel("NW", 40) }; BoxAndWhiskerData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Development", new List<double>{22, 22, 23, 25, 25, 25, 26, 27, 27, 28, 28, 29, 30, 32, 34, 32, 34, 36, 35, 38, 42, 45, 44 }), new ChartDataModel("Test", new List<double>{ 22, 33, 23, 25, 26, 28, 29, 30, 34, 33, 32, 31, 50 } ), new ChartDataModel("HR", new List<double>{ 22, 24, 25, 30, 32, 34, 36, 38, 39, 41, 35, 36, 40, 45, 50 }), new ChartDataModel("Finance", new List<double>{ 26, 27, 28, 30, 32, 34, 35, 37, 35, 37, 45, 52, 53 } ), new ChartDataModel("Sales", new List<double>{ 26, 27, 29, 32, 34, 35, 36, 37, 38, 39, 41, 43 }), }; ErrorBarData = new ObservableCollection<ChartDataModel> { new ChartDataModel("IND", 23, 0.5, 1), new ChartDataModel("AUS", 20, 0, 2), new ChartDataModel("USA", 35, 1, 2), new ChartDataModel("DUE", 28, 2, 0.5), new ChartDataModel("ITA", 30, 1, 0), new ChartDataModel("UK", 42, 1.5, 1), new ChartDataModel("RUS", 27, 0.5, 2) }; AreaData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 45), new ChartDataModel("2011", 56), new ChartDataModel("2012", 23), new ChartDataModel("2013", 43), new ChartDataModel("2014", double.NaN), new ChartDataModel("2015", 54), new ChartDataModel("2016", 43), new ChartDataModel("2017", 23), new ChartDataModel("2018", 34) }; StripLineData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 26), new ChartDataModel("Mon", 24), new ChartDataModel("Tue", 31), new ChartDataModel("Wed", 28), new ChartDataModel("Thu", 30), new ChartDataModel("Fri", 26), new ChartDataModel("Sat", 30), }; LineData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2005", 33), new ChartDataModel("2006", 28), new ChartDataModel("2007", 29), new ChartDataModel("2008", 35), new ChartDataModel("2009", 32), new ChartDataModel("2010", 35), new ChartDataModel("2011", 30) }; LineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2005", 31), new ChartDataModel("2006", 28), new ChartDataModel("2007", 30), new ChartDataModel("2008", 36), new ChartDataModel("2009", 36), new ChartDataModel("2010", 39), new ChartDataModel("2011", 37) }; LineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2005", 39), new ChartDataModel("2006", 36), new ChartDataModel("2007", 40), new ChartDataModel("2008", 44), new ChartDataModel("2009", 45), new ChartDataModel("2010", 48), new ChartDataModel("2011", 46) }; StepLineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2006, 463), new ChartDataModel(2007, 449), new ChartDataModel(2008, 458), new ChartDataModel(2009, 450), new ChartDataModel(2010, 425), new ChartDataModel(2011, 430), }; StepLineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2006, 519), new ChartDataModel(2007, 508), new ChartDataModel(2008, 502), new ChartDataModel(2009, 495), new ChartDataModel(2010, 485), new ChartDataModel(2011, 470), }; StepLineData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2006, 570), new ChartDataModel(2007, 579), new ChartDataModel(2008, 563), new ChartDataModel(2009, 550), new ChartDataModel(2010, 545), new ChartDataModel(2011, 525), }; StepAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2006, 40), new ChartDataModel(2007, 60), new ChartDataModel(2008, 50), new ChartDataModel(2009, 55), new ChartDataModel(2010, 75), new ChartDataModel(2011, 80), }; StepAreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2006, 20), new ChartDataModel(2007, 40), new ChartDataModel(2008, 30), new ChartDataModel(2009, 45), new ChartDataModel(2010, 55), new ChartDataModel(2011, 60), }; ColumnData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("USA", 50), new ChartDataModel("China", 40), new ChartDataModel("Japan", 70), new ChartDataModel("Australia", 60), new ChartDataModel("France", 50), }; ColumnData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("USA", 70), new ChartDataModel("China", 60), new ChartDataModel("Japan", 60), new ChartDataModel("Australia", 56), new ChartDataModel("France", 45), }; ColumnData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("USA", 45), new ChartDataModel("China", 55), new ChartDataModel("Japan", 50), new ChartDataModel("Australia", 40), new ChartDataModel("France", 35), }; BarData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 7.8), new ChartDataModel("2007", 7.2), new ChartDataModel("2008", 6.8), new ChartDataModel("2009", 10.7), new ChartDataModel("2010", 10.8), new ChartDataModel("2011", 9.8) }; BarData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 4.8), new ChartDataModel("2007", 4.6), new ChartDataModel("2008", 7.2), new ChartDataModel("2009", 9.3), new ChartDataModel("2010", 9.7), new ChartDataModel("2011", 9) }; AreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("1900", 4.0), new ChartDataModel("1920", 3.0), new ChartDataModel("1940", 3.8), new ChartDataModel("1960", 3.4), new ChartDataModel("1980", 3.2), new ChartDataModel("2000", 3.9), }; AreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("1900", 2.6), new ChartDataModel("1920", 2.8), new ChartDataModel("1940", 2.6), new ChartDataModel("1960", 3.0), new ChartDataModel("1980", 3.6), new ChartDataModel("2000", 3.0) }; AreaData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("1900", 2.8), new ChartDataModel("1920", 2.5), new ChartDataModel("1940", 2.8), new ChartDataModel("1960", 3.0), new ChartDataModel("1980", 2.9), new ChartDataModel("2000", 2.0) }; SplineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", -1), new ChartDataModel("Feb", -1), new ChartDataModel("Mar", 2), new ChartDataModel("Apr", 8), new ChartDataModel("May", 13), new ChartDataModel("Jun", 18), new ChartDataModel("Jul", 21), new ChartDataModel("Aug", 20), new ChartDataModel("Sep", 16), new ChartDataModel("Oct", 10), new ChartDataModel("Nov", 4), new ChartDataModel("Dec", 0), }; SplineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 7), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 12), new ChartDataModel("Apr", 19), new ChartDataModel("May", 25), new ChartDataModel("Jun", 29), new ChartDataModel("Jul", 31), new ChartDataModel("Aug", 30), new ChartDataModel("Sep", 26), new ChartDataModel("Oct", 20), new ChartDataModel("Nov", 14), new ChartDataModel("Dec", 8), }; SplineAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2002", 2.2), new ChartDataModel("2003", 3.4), new ChartDataModel("2004", 2.8), new ChartDataModel("2005", 1.6), new ChartDataModel("2006", 2.3), new ChartDataModel("2007", 2.5), new ChartDataModel("2008", 2.9), new ChartDataModel("2009", 3.8), new ChartDataModel("2010", 1.4), new ChartDataModel("2011", 3.1), }; SplineAreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2002", 2.0), new ChartDataModel("2003", 1.7), new ChartDataModel("2004", 1.8), new ChartDataModel("2005", 2.1), new ChartDataModel("2006", 2.3), new ChartDataModel("2007", 1.7), new ChartDataModel("2008", 1.5), new ChartDataModel("2009", 2.8), new ChartDataModel("2010", 1.5), new ChartDataModel("2011", 2.3), }; SplineAreaData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2002", 0.8), new ChartDataModel("2003", 1.3), new ChartDataModel("2004", 1.1), new ChartDataModel("2005", 1.6), new ChartDataModel("2006", 2.0), new ChartDataModel("2007", 1.7), new ChartDataModel("2008", 2.3), new ChartDataModel("2009", 2.7), new ChartDataModel("2010", 1.1), new ChartDataModel("2011", 2.3), }; RangeColumnData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6.1, 0.7), new ChartDataModel("Mar", 8.5, 1.9), new ChartDataModel("May", 14.4, 5.7), new ChartDataModel("Jul", 19.2, 10.6), new ChartDataModel("Sep", 16.1, 8.5), new ChartDataModel("Nov", 6.9, 1.5), }; RangeColumnData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 7.7, 1.7), new ChartDataModel("Mar", 7.5, 1.2), new ChartDataModel("May", 11.4, 4.7), new ChartDataModel("Jul", 17.2, 9.6), new ChartDataModel("Sep", 15.1, 7.5), new ChartDataModel("Nov", 7.9, 1.2), }; RangeAreaData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 45, 32), new ChartDataModel("Feb", 48, 34), new ChartDataModel("Mar", 46, 32), new ChartDataModel("Apr", 48, 36), new ChartDataModel("May", 46, 32), new ChartDataModel("Jun", 49, 34), }; RangeAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 30, 18), new ChartDataModel("Feb", 24, 12), new ChartDataModel("Mar", 29, 15), new ChartDataModel("Apr", 24, 10), new ChartDataModel("May", 30, 18), new ChartDataModel("Jun", 24, 10), }; RangeBarData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jumbo", 119238), new ChartDataModel("FHA", 159595), new ChartDataModel("VA", 256398), new ChartDataModel("USDA", 356396), new ChartDataModel("Const", 456398), new ChartDataModel("Total", 559937) }; StepLineData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2002", 36), new ChartDataModel("2003", 40), new ChartDataModel("2004", 34), new ChartDataModel("2005", 40), new ChartDataModel("2006", 44), new ChartDataModel("2007", 38), new ChartDataModel("2008", 30) }; PieSeriesData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Chrome", 94658), new ChartDataModel("UC Browser", 9090), new ChartDataModel("Opera", 2577), }; DoughnutSeriesData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Labour", 28), new ChartDataModel("Legal", 10), new ChartDataModel("Production", 20), new ChartDataModel("License", 15), new ChartDataModel("Facilities", 23), new ChartDataModel("Taxes", 17), new ChartDataModel("Insurance", 12), }; PyramidData = new ObservableCollection<ChartDataModel> { new ChartDataModel("India", 24), new ChartDataModel("Japan", 25), new ChartDataModel("Australia", 20), new ChartDataModel("USA", 35), new ChartDataModel("China", 23), new ChartDataModel("Germany", 27), new ChartDataModel("France", 22), }; FunnelData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Renewed", 18.2), new ChartDataModel("Subscribe", 27.3), new ChartDataModel("Support", 55.9), new ChartDataModel("Downloaded", 76.8), new ChartDataModel("Visited", 100), }; StackedBarData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 12), new ChartDataModel("Apr", 15.5), new ChartDataModel("May", 20), new ChartDataModel("Jun", 24), new ChartDataModel("Jul", 28), new ChartDataModel("Aug", 32), new ChartDataModel("Sep", 33), new ChartDataModel("Oct", 35), new ChartDataModel("Nov", 40), new ChartDataModel("Dec", 42), }; StackedBarData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 12), new ChartDataModel("Apr", 15.5), new ChartDataModel("May", 20), new ChartDataModel("Jun", 24), new ChartDataModel("Jul", 28), new ChartDataModel("Aug", 32), new ChartDataModel("Sep", 33), new ChartDataModel("Oct", 35), new ChartDataModel("Nov", 40), new ChartDataModel("Dec", 42), }; StackedBarData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", -1), new ChartDataModel("Feb", -1.5), new ChartDataModel("Mar", -2), new ChartDataModel("Apr", -2.5), new ChartDataModel("May", -3), new ChartDataModel("Jun", -3.5), new ChartDataModel("Jul", -4), new ChartDataModel("Aug", -4.5), new ChartDataModel("Sep", -5), new ChartDataModel("Oct", -5.5), new ChartDataModel("Nov", -6), new ChartDataModel("Dec", -6.5), }; StackedBar100Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2007", 453), new ChartDataModel("2008", 354), new ChartDataModel("2009", 282), new ChartDataModel("2010", 321), new ChartDataModel("2011", 333), new ChartDataModel("2012", 351), new ChartDataModel("2013", 403), new ChartDataModel("2014", 421), }; StackedBar100Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2007", 876), new ChartDataModel("2008", 564), new ChartDataModel("2009", 242), new ChartDataModel("2010", 121), new ChartDataModel("2011", 343), new ChartDataModel("2012", 451), new ChartDataModel("2013", 203), new ChartDataModel("2014", 431), }; StackedBar100Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2007", 356), new ChartDataModel("2008", 876), new ChartDataModel("2009", 898), new ChartDataModel("2010", 567), new ChartDataModel("2011", 456), new ChartDataModel("2012", 345), new ChartDataModel("2013", 543), new ChartDataModel("2014", 654), }; StackedBar100Data4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2007", 122), new ChartDataModel("2008", 444), new ChartDataModel("2009", 222), new ChartDataModel("2010", 231), new ChartDataModel("2011", 122), new ChartDataModel("2012", 333), new ChartDataModel("2013", 354), new ChartDataModel("2014", 100), }; StackedColumnData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 900), new ChartDataModel("Feb", 820), new ChartDataModel("Mar", 880), new ChartDataModel("Apr", 725), new ChartDataModel("May", 765), new ChartDataModel("Jun", 679), }; StackedColumnData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 190), new ChartDataModel("Feb", 226), new ChartDataModel("Mar", 194), new ChartDataModel("Apr", 250), new ChartDataModel("May", 222), new ChartDataModel("Jun", 181), }; StackedColumnData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 250), new ChartDataModel("Feb", 145), new ChartDataModel("Mar", 190), new ChartDataModel("Apr", 220), new ChartDataModel("May", 225), new ChartDataModel("Jun", 135), }; StackedColumnData4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 150), new ChartDataModel("Feb", 120), new ChartDataModel("Mar", 115), new ChartDataModel("Apr", 125), new ChartDataModel("May", 132), new ChartDataModel("Jun", 137), }; StackedAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2002", 6), new ChartDataModel("2003", 7.5), new ChartDataModel("2004", 6), new ChartDataModel("2005", 6.5), new ChartDataModel("2006", 7.4), new ChartDataModel("2007", 7.9), new ChartDataModel("2008", 7.5), new ChartDataModel("2009", 8.5), new ChartDataModel("2010", 4.8), new ChartDataModel("2011", 9.3), }; StackedAreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2002", 3.5), new ChartDataModel("2003", 4.9), new ChartDataModel("2004", 3.7), new ChartDataModel("2005", 7.5), new ChartDataModel("2006", 4.8), new ChartDataModel("2007", 2.6), new ChartDataModel("2008", 4.7), new ChartDataModel("2009", 3.7), new ChartDataModel("2010", 3.5), new ChartDataModel("2011", 3.6), }; StackedAreaData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2002", 8.1), new ChartDataModel("2003", 8.8), new ChartDataModel("2004", 6.7), new ChartDataModel("2005", 6.4), new ChartDataModel("2006", 4.0), new ChartDataModel("2007", 4.8), new ChartDataModel("2008", 7.4), new ChartDataModel("2009", 3.5), new ChartDataModel("2010", 8.3), new ChartDataModel("2011", 4.7), }; StackedAreaData4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2002", 2.5), new ChartDataModel("2003", 6.1), new ChartDataModel("2004", 6.2), new ChartDataModel("2005", 1.8), new ChartDataModel("2006", 4.0), new ChartDataModel("2007", 6.5), new ChartDataModel("2008", 6.7), new ChartDataModel("2009", 7.2), new ChartDataModel("2010", 8.4), new ChartDataModel("2011", 6.9), }; StackedArea100Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 34), new ChartDataModel("2007", 20), new ChartDataModel("2008", 40), new ChartDataModel("2009", 51), new ChartDataModel("2010", 26), new ChartDataModel("2011", 37), new ChartDataModel("2012", 54), new ChartDataModel("2013", 44), new ChartDataModel("2014", 48), }; StackedArea100Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 51), new ChartDataModel("2007", 26), new ChartDataModel("2008", 37), new ChartDataModel("2009", 51), new ChartDataModel("2010", 26), new ChartDataModel("2011", 37), new ChartDataModel("2012", 43), new ChartDataModel("2013", 23), new ChartDataModel("2014", 55), }; StackedArea100Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 14), new ChartDataModel("2007", 34), new ChartDataModel("2008", 73), new ChartDataModel("2009", 51), new ChartDataModel("2010", 26), new ChartDataModel("2011", 37), new ChartDataModel("2012", 12), new ChartDataModel("2013", 16), new ChartDataModel("2014", 34), }; StackedArea100Data4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 37), new ChartDataModel("2007", 16), new ChartDataModel("2008", 53), new ChartDataModel("2009", 51), new ChartDataModel("2010", 26), new ChartDataModel("2011", 37), new ChartDataModel("2012", 54), new ChartDataModel("2013", 44), new ChartDataModel("2014", 23), }; CircularData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 8000), new ChartDataModel("2011", 8100), new ChartDataModel("2012", 8250), new ChartDataModel("2013", 8600), new ChartDataModel("2014", 8700) }; MultipleAxisData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 20), new ChartDataModel("2011", 21), new ChartDataModel("2012", 22.5), new ChartDataModel("2013", 26), new ChartDataModel("2014", 27) }; MultipleAxisData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 6), new ChartDataModel("2011", 15), new ChartDataModel("2012", 35), new ChartDataModel("2013", 65), new ChartDataModel("2014", 75) }; SemiCircularData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Product A", 14), new ChartDataModel("Product B", 54), new ChartDataModel("Product C", 23), new ChartDataModel("Product D", 53), }; BubbleData = new ObservableCollection<ChartDataModel> { new ChartDataModel(92.2, 7.8, 0.47), new ChartDataModel(74, 6.5, 0.241), new ChartDataModel(90.4, 6.0, 0.238), new ChartDataModel(99.4, 2.2, 0.312), new ChartDataModel(88.6, 1.3, 0.197), new ChartDataModel(54.9, 3.7, 0.177), new ChartDataModel(99, 0.7, 0.0818), new ChartDataModel(72, 2.0, 0.0826), new ChartDataModel(99.6, 3.4, 0.143), new ChartDataModel(99, 0.2, 0.128), new ChartDataModel(86.1, 4.0, 0.115), new ChartDataModel(92.6, 6.6, 0.096), new ChartDataModel(61.3, 14.5, 0.162), new ChartDataModel(56.8, 6.1, 0.151), }; ScatterData = new ObservableCollection<ChartDataModel>(); { for (int i = 0; i < 300; i++) { double x = random.NextDouble() * 100; double y = random.NextDouble() * 500; double randomDouble = random.NextDouble(); if (randomDouble >= .25 && randomDouble < .5) { x *= -1; } else if (randomDouble >= .5 && randomDouble < .75) { y *= -1; } else if (randomDouble > .75) { x *= -1; y *= -1; } ScatterData.Add(new ChartDataModel(300 + (x * (random.NextDouble() + 0.12)), 100 + (y * (random.NextDouble() + 0.12)))); } } RangeColumnData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 35, 17), new ChartDataModel("Feb", 42, -11), new ChartDataModel("Mar", 25, 5), new ChartDataModel("Apr", 32, 10), new ChartDataModel("May", 20, 3), new ChartDataModel("Jun", 41, 30) }; FinancialData = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2000, 01, 17), 115, 125, 70, 90), new ChartDataModel(new DateTime(2000, 02, 17), 120, 150, 60, 70), new ChartDataModel(new DateTime(2000, 03, 17), 160, 200, 140, 190), new ChartDataModel(new DateTime(2000, 04, 17), 140, 160, 90, 110), new ChartDataModel(new DateTime(2000, 05, 17), 180, 200, 100, 120), new ChartDataModel(new DateTime(2000, 06, 17), 70, 100, 45, 50) }; Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 45), new ChartDataModel("2011", 89), new ChartDataModel("2012", 23), new ChartDataModel("2013", 43), new ChartDataModel("2014", 54) }; Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 54), new ChartDataModel("2011", 24), new ChartDataModel("2012", 53), new ChartDataModel("2013", 63), new ChartDataModel("2014", 35) }; Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 14), new ChartDataModel("2011", 54), new ChartDataModel("2012", 23), new ChartDataModel("2013", 53), new ChartDataModel("2014", 25) }; CategoryData = new ObservableCollection<ChartDataModel> { new ChartDataModel("BGD", 87), new ChartDataModel("BTN", 70), new ChartDataModel("NPL", 82), new ChartDataModel("THA", 75), new ChartDataModel("MYS", 90), }; LogarithmicData = new ObservableCollection<ChartDataModel> { new ChartDataModel("1990", 80), new ChartDataModel("1991", 200), new ChartDataModel("1992", 400), new ChartDataModel("1993", 600), new ChartDataModel("1994", 900), new ChartDataModel("1995", 1400), new ChartDataModel("1996", 2000), new ChartDataModel("1997", 4000), new ChartDataModel("1998", 6000), new ChartDataModel("1999", 8000), new ChartDataModel("2000", 9000) }; NumericData = new ObservableCollection<ChartDataModel> { new ChartDataModel(2001, 75), new ChartDataModel(2002, 90), new ChartDataModel(2003, 85), new ChartDataModel(2004, 70), new ChartDataModel(2005, 55), new ChartDataModel(2006, 65), }; DateTimeData = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2014, 02, 1), 10), new ChartDataModel(new DateTime(2015, 03, 2), 30), new ChartDataModel(new DateTime(2016, 04, 3), 15), new ChartDataModel(new DateTime(2017, 05, 4), 65), new ChartDataModel(new DateTime(2018, 06, 5), 90), new ChartDataModel(new DateTime(2019, 07, 5), 85) }; datas1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 6), new ChartDataModel("2011", 15), new ChartDataModel("2012", 35), new ChartDataModel("2013", 65), new ChartDataModel("2014", 75) }; DataMarkerData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2001", 59), new ChartDataModel("2002", 44), new ChartDataModel("2003", 47), new ChartDataModel("2004", 61), new ChartDataModel("2005", 76), }; SelectionData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 42), new ChartDataModel("Feb", 44), new ChartDataModel("Mar", 53), new ChartDataModel("Apr", 64), new ChartDataModel("May", 75), new ChartDataModel("Jun", 83) }; MultipleSeriesData1 = new ObservableCollection<ChartDataModel>(); for (var i = 1; i <= 12; i++) { MultipleSeriesData1.Add(new ChartDataModel(new DateTime(2014, i, 1), random.Next(10, 100))); } MultipleSeriesData2 = new ObservableCollection<ChartDataModel>(); for (var i = 1; i <= 12; i++) { MultipleSeriesData2.Add(new ChartDataModel(new DateTime(2014, i, 1), random.Next(10, 100))); } PieData = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2014, 1, 1), 48), new ChartDataModel(new DateTime(2014, 2, 1), 38), new ChartDataModel(new DateTime(2014, 3, 1), 28), new ChartDataModel(new DateTime(2014, 4, 1), 33), new ChartDataModel(new DateTime(2014, 5, 1), 25), new ChartDataModel(new DateTime(2014, 6, 1), 34) }; TriangularData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Bentley", 800), new ChartDataModel("Audi", 810), new ChartDataModel("BMW", 825), new ChartDataModel("Jaguar", 860), new ChartDataModel("Skoda", 875) }; data = new ObservableCollection<ChartDataModel>(); LineSeries1 = new ObservableCollection<ChartDataModel>(); LineSeries1.Add(new ChartDataModel("2005", 31)); LineSeries1.Add(new ChartDataModel("2006", 28)); LineSeries1.Add(new ChartDataModel("2007", 30)); LineSeries1.Add(new ChartDataModel("2008", 36)); LineSeries1.Add(new ChartDataModel("2009", 36)); LineSeries1.Add(new ChartDataModel("2010", 39)); LineSeries2 = new ObservableCollection<ChartDataModel>(); LineSeries2.Add(new ChartDataModel("2005", 36)); LineSeries2.Add(new ChartDataModel("2006", 32)); LineSeries2.Add(new ChartDataModel("2007", 34)); LineSeries2.Add(new ChartDataModel("2008", 41)); LineSeries2.Add(new ChartDataModel("2009", 42)); LineSeries2.Add(new ChartDataModel("2010", 42)); LineSeries3 = new ObservableCollection<ChartDataModel>(); LineSeries3.Add(new ChartDataModel("2005", 39)); LineSeries3.Add(new ChartDataModel("2006", 36)); LineSeries3.Add(new ChartDataModel("2007", 40)); LineSeries3.Add(new ChartDataModel("2008", 44)); LineSeries3.Add(new ChartDataModel("2009", 45)); LineSeries3.Add(new ChartDataModel("2010", 48)); TooltipData = new ObservableCollection<ChartDataModel>(); TooltipData.Add(new ChartDataModel("2007", 1.61)); TooltipData.Add(new ChartDataModel("2008", 2.34)); TooltipData.Add(new ChartDataModel("2009", 2.16)); TooltipData.Add(new ChartDataModel("2010", 2.1)); TooltipData.Add(new ChartDataModel("2011", 1.61)); TooltipData.Add(new ChartDataModel("2012", 2.05)); TooltipData.Add(new ChartDataModel("2013", 2.5)); TooltipData.Add(new ChartDataModel("2014", 2.21)); TooltipData.Add(new ChartDataModel("2015", 2.34)); } public void LoadData() { for (int i = 1; i <= 30; i++) { NSNumber value = new NSNumber(random.Next(0, 9)); data.Add(new ChartDataModel(i, (double)value)); wave1++; } } public ChartDataModel dataPointWithTimeInterval(double time) { int count = verticalCount; NSNumber value; if (count > 320) { value = random.Next(0, 0); } else if (count > 280) { value = random.Next(-2, 2); } else if (count > 240) { value = random.Next(-3, 3); } else if (count > 200) { value = random.Next(-5, 5); } else if (count > 180) { value = random.Next(-6, 6); } else if (count > 120) { value = random.Next(-7, 7); } else if (count > 30) { value = random.Next(-9, 9); } else { value = random.Next(-3, 3); } date = date.AddSeconds(time); ChartDataModel datapoint = new ChartDataModel(); datapoint.XValue = date; datapoint.YValue = (double)value; return datapoint; } private void addWeek() { dataTime = dataTime.AddDays(7); } } } <file_sep>/Android/SampleBrowser/Samples/Presentation/CreateAnimation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public partial class CreateAnimationPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to create a animation in PowerPoint presentation."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Presentation"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Animation.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Modify the existing animation CreateAnimationWithShape(presentation); MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("CreateAnimationSample.pptx", "application/powerpoint", stream, m_context); } } # region Create Animation private void CreateAnimationWithShape(IPresentation presentation) { //Get the slide from the presentation ISlide slide = presentation.Slides[0]; //Access the animation sequence to create effects ISequence sequence = slide.Timeline.MainSequence; //Add motion path effect to the shape IEffect line1 = sequence.AddEffect(slide.Shapes[8] as IShape, EffectType.PathUp, EffectSubtype.None, EffectTriggerType.OnClick); IMotionEffect motionEffect = line1.Behaviors[0] as IMotionEffect; motionEffect.Timing.Duration = 1f; IMotionPath motionPath = motionEffect.Path; motionPath[1].Points[0].X = 0.00365f; motionPath[1].Points[0].Y = -0.27431f; //Add motion path effect to the shape IEffect line2 = sequence.AddEffect(slide.Shapes[3] as IShape, EffectType.PathDown, EffectSubtype.None, EffectTriggerType.WithPrevious); motionEffect = line2.Behaviors[0] as IMotionEffect; motionEffect.Timing.Duration = 0.75f; motionPath = motionEffect.Path; motionPath[1].Points[0].X = 0.00234f; motionPath[1].Points[0].Y = 0.43449f; //Add wipe effect to the shape IEffect wipe1 = sequence.AddEffect(slide.Shapes[1] as IShape, EffectType.Wipe, EffectSubtype.None, EffectTriggerType.AfterPrevious); wipe1.Behaviors[1].Timing.Duration = 1f; //Add fly effect to the shape IEffect fly1 = sequence.AddEffect(slide.Shapes[5] as IShape, EffectType.Fly, EffectSubtype.Left, EffectTriggerType.AfterPrevious); fly1.Behaviors[1].Timing.Duration = 0.70f; fly1.Behaviors[2].Timing.Duration = 0.70f; ////Add wipe effect to the shape IEffect wipe2 = sequence.AddEffect(slide.Shapes[2] as IShape, EffectType.Wipe, EffectSubtype.None, EffectTriggerType.AfterPrevious); wipe2.Behaviors[1].Timing.Duration = 1f; ////Add fly effect to the shape IEffect fly2 = sequence.AddEffect(slide.Shapes[4] as IShape, EffectType.Fly, EffectSubtype.Right, EffectTriggerType.AfterPrevious); fly2.Behaviors[1].Timing.Duration = 0.70f; fly2.Behaviors[2].Timing.Duration = 0.70f; IEffect fly3 = sequence.AddEffect(slide.Shapes[6] as IShape, EffectType.Fly, EffectSubtype.Top, EffectTriggerType.AfterPrevious); fly3.Behaviors[1].Timing.Duration = 1.50f; fly3.Behaviors[2].Timing.Duration = 1.50f; ////Add flay effect to the shape IEffect fly4 = sequence.AddEffect(slide.Shapes[7] as IShape, EffectType.Fly, EffectSubtype.Left, EffectTriggerType.AfterPrevious); fly4.Behaviors[1].Timing.Duration = 0.50f; fly4.Behaviors[2].Timing.Duration = 0.50f; } #endregion } } <file_sep>/Forms/DataGrid/DataGrid/ISave.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ISave.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System.IO; using System.Threading.Tasks; /// <summary> /// Interface that defines the methods used for saving the exported files in DataGrid. /// </summary> public interface ISave { /// <summary> /// Used to save a Exporting grid to Excel and PDF file by writing ISave Interface /// </summary> /// <param name="filename">string type of filename parameter</param> /// <param name="contentType">string type of contentType parameter</param> /// <param name="stream">MemoryStream type of stream parameter</param> void Save(string filename, string contentType, MemoryStream stream); } /// <summary> /// Interface that defines the methods used for saving the exported files in DataGrid in WindowsPhone. /// </summary> public interface ISaveWindowsPhone { /// <summary> /// Used to save a Exporting grid to Excel and PDF file in UWP devices /// </summary> /// <param name="filename">string type of filename parameter</param> /// <param name="contentType">string type of contentType parameter</param> /// <param name="stream">MemoryStream type of stream parameter</param> /// <returns>returns saved file</returns> Task Save(string filename, string contentType, MemoryStream stream); } /// <summary> /// Interface that defines the methods used for saving the exported files in DataGrid in Android device. /// </summary> public interface IAndroidVersionDependencyService { /// <summary> /// Used to get Android version /// </summary> /// <returns>returns Android version</returns> int GetAndroidVersion(); } /// <summary> /// Interface that defines methods to compose mail /// </summary> public interface IMailService { /// <summary> /// used this method for ComposeMail /// </summary> /// <param name="fileName">string type of parameter fileName</param> /// <param name="recipients">string type of parameter recipients</param> /// <param name="subject">string type of parameter subject</param> /// <param name="messagebody">string type of parameter message body</param> /// <param name="documentStream">MemoryStream type parameter documentStream</param> void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream documentStream); } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/Localization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; using System.Collections.ObjectModel; using Foundation; using UIKit; using CoreGraphics; namespace SampleBrowser { public class Localization : SampleView { private SFSchedule schedule; public static UITableView appView; private readonly IList<string> languages = new List<string>(); private string localisation_Languages; private UIPickerView scheduleTypePicker = new UIPickerView(); private UILabel label = new UILabel(); private UIButton button = new UIButton(), textbutton = new UIButton(); private ScheduleLocalViewModel viewModel; public Localization() { schedule = new SFSchedule(); viewModel = new ScheduleLocalViewModel(); label.Text = "Select the Locale"; label.TextColor = UIColor.Black; this.AddSubview(label); textbutton.SetTitle("French", UIControlState.Normal); textbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; textbutton.BackgroundColor = UIColor.Clear; textbutton.SetTitleColor(UIColor.Black, UIControlState.Normal); textbutton.Hidden = false; textbutton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; textbutton.Layer.BorderWidth = 4; textbutton.Layer.CornerRadius = 8; textbutton.TouchUpInside += ShowPicker; this.AddSubview(textbutton); button.SetTitle("Done\t", UIControlState.Normal); button.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; button.BackgroundColor = UIColor.FromRGB(240, 240, 240); button.SetTitleColor(UIColor.Black, UIControlState.Normal); button.Hidden = true; button.TouchUpInside += HidePicker; schedule.Locale = new NSLocale("fr-FR"); schedule.ItemsSource = getFrenchAppointments(); schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; this.AddSubview(schedule); appView = new UITableView(); appView.RegisterClassForCellReuse(typeof(UITableViewCell), "Cell"); this.AddSubview(appView); this.languages.Add((NSString)"French"); this.languages.Add((NSString)"Spanish"); this.languages.Add((NSString)"English"); this.languages.Add((NSString)"Chinese"); SchedulePickerModel model = new SchedulePickerModel(this.languages); model.PickerChanged += (sender, e) => { this.localisation_Languages = e.SelectedValue; textbutton.SetTitle(localisation_Languages, UIControlState.Normal); if (localisation_Languages == "French") { schedule.Locale = new NSLocale("fr-FR"); schedule.ItemsSource = getFrenchAppointments(); } else if (localisation_Languages == "Spanish") { schedule.Locale = new NSLocale("es-AR"); schedule.ItemsSource = getSpanishAppointments(); } else if (localisation_Languages == "English") { schedule.Locale = new NSLocale("en-US"); schedule.ItemsSource = getEnglishAppointments(); } else if (localisation_Languages == "Chinese") { schedule.Locale = new NSLocale("zh-CN"); schedule.ItemsSource = getChineseAppointments(); } }; scheduleTypePicker.ShowSelectionIndicator = true; scheduleTypePicker.Hidden = true; scheduleTypePicker.Model = model; scheduleTypePicker.BackgroundColor = UIColor.White; this.OptionView = new UIView(); } protected override void Dispose(bool disposing) { if (disposing) { if (schedule != null) { this.schedule.Dispose(); this.schedule = null; } if (textbutton != null) { textbutton.TouchUpInside -= ShowPicker; textbutton.Dispose(); textbutton = null; } if (button != null) { button.TouchUpInside -= HidePicker; button.Dispose(); button = null; } } base.Dispose(disposing); } private void ShowPicker(object sender, EventArgs e) { button.Hidden = false; scheduleTypePicker.Hidden = false; this.BecomeFirstResponder(); } private void HidePicker(object sender, EventArgs e) { button.Hidden = true; scheduleTypePicker.Hidden = true; this.BecomeFirstResponder(); } private ObservableCollection<ScheduleAppointment> getFrenchAppointments() { NSDate today = new NSDate(); viewModel.SetColors(); viewModel.SetFrenchCollectionSubjects(); ObservableCollection<ScheduleAppointment> appCollection = new ObservableCollection<ScheduleAppointment>(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)viewModel.FrenchCollection[i]; appointment.AppointmentBackground = viewModel.ColorCollection[i]; appCollection.Add(appointment); } return appCollection; } private ObservableCollection<ScheduleAppointment> getSpanishAppointments() { NSDate today = new NSDate(); viewModel.SetColors(); viewModel.SetSpanishCollectionSubjects(); ObservableCollection<ScheduleAppointment> appCollection = new ObservableCollection<ScheduleAppointment>(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)viewModel.SpanishCollection[i]; appointment.AppointmentBackground = viewModel.ColorCollection[i]; appCollection.Add(appointment); } return appCollection; } private ObservableCollection<ScheduleAppointment> getEnglishAppointments() { NSDate today = new NSDate(); viewModel.SetColors(); viewModel.SetEnglishCollectionSubjects(); ObservableCollection<ScheduleAppointment> appCollection = new ObservableCollection<ScheduleAppointment>(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)viewModel.EnglishCollection[i]; appointment.AppointmentBackground = viewModel.ColorCollection[i]; appCollection.Add(appointment); } return appCollection; } private ObservableCollection<ScheduleAppointment> getChineseAppointments() { NSDate today = new NSDate(); viewModel.SetColors(); viewModel.SetChineseCollectionSubjects(); ObservableCollection<ScheduleAppointment> appCollection = new ObservableCollection<ScheduleAppointment>(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)viewModel.ChineseCollection[i]; appointment.AppointmentBackground = viewModel.ColorCollection[i]; appCollection.Add(appointment); } return appCollection; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view is SFSchedule) { view.Frame = new CGRect(this.Frame.X, 0, Frame.Size.Width, (Frame.Size.Height)); string deviceType = UIDevice.CurrentDevice.Model; if (deviceType == "iPhone" || deviceType == "iPod touch") { label.Frame = new CGRect(15, 10, this.Frame.Size.Width - 20, 40); textbutton.Frame = new CGRect(10, label.Frame.Size.Height + label.Frame.Y, this.Frame.Size.Width - 20, 40); button.Frame = new CGRect(this.Frame.X + 10, textbutton.Frame.Y + textbutton.Frame.Size.Height, this.Frame.Size.Width - 20, 30); scheduleTypePicker.Frame = new CGRect(0, button.Frame.Y + button.Frame.Size.Height, this.Frame.Size.Width, 100); } else { schedule.WeekViewSettings.WorkStartHour = 7; schedule.WeekViewSettings.WorkEndHour = 18; label.Frame = new CGRect(15, 10, this.Frame.Size.Width - 20, 30); textbutton.Frame = new CGRect(10, 40, this.Frame.Size.Width / 2.5, 30); button.Frame = new CGRect(this.Frame.X + 10, 80, this.Frame.Size.Width / 2.5, 30); scheduleTypePicker.Frame = new CGRect(0, 100, this.Frame.Size.Width / 2.5, 200); } } } base.LayoutSubviews(); this.CreateOptionView(); } public class SchedulePickerModel : UIPickerViewModel { private readonly IList<string> values; public event EventHandler<SchedulePickerChangedEventArgs> PickerChanged; public SchedulePickerModel(IList<string> values) { this.values = values; } public override nint GetComponentCount (UIPickerView picker) { return 1; } public override nint GetRowsInComponent (UIPickerView picker, nint component) { return values.Count; } public override string GetTitle (UIPickerView picker, nint row, nint component) { return values[(int)row]; } public override nfloat GetRowHeight (UIPickerView picker, nint component) { return 30f; } public override void Selected (UIPickerView picker, nint row, nint component) { if (this.PickerChanged != null) { this.PickerChanged(this, new SchedulePickerChangedEventArgs{SelectedValue = values[(int)row]}); } } } public class SchedulePickerChangedEventArgs : EventArgs { public string SelectedValue { get; set; } } private void CreateOptionView() { this.OptionView.AddSubview(label); this.OptionView.AddSubview(textbutton); this.OptionView.AddSubview(scheduleTypePicker); this.OptionView.AddSubview(button); } } } <file_sep>/Forms/RichTextEditor/RichTextEditor.UWP/RTECustomEntryRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.SfRichTextEditor; using SampleBrowser.SfRichTextEditor.UWP; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; [assembly: ExportRenderer(typeof(RTECustomEntry), typeof(RTECustomEntryRenderer))] namespace SampleBrowser.SfRichTextEditor.UWP { public class RTECustomEntryRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { Control.BorderThickness = new Windows.UI.Xaml.Thickness(0); } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/StackingArea100.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.OS; using Android.Graphics; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Android.Views; namespace SampleBrowser { public class StackingArea100 : SamplePage { private SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Trend in Sales of Ethical Produce"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis primaryAxis = new CategoryAxis(); primaryAxis.Interval = 2; primaryAxis.ShowMajorGridLines = false; primaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; chart.PrimaryAxis = primaryAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Minimum = 0; numericalAxis.Maximum = 100; numericalAxis.Interval = 10; numericalAxis.Title.Text = "Spends"; numericalAxis.LineStyle.StrokeWidth = 0; numericalAxis.MajorTickStyle.TickSize = 0; numericalAxis.LabelStyle.LabelFormat = "##.##'%' "; chart.SecondaryAxis = numericalAxis; StackingArea100Series stackingArea100Series1 = new StackingArea100Series(); stackingArea100Series1.EnableAnimation = true; stackingArea100Series1.ItemsSource = MainPage.GetStackedArea100Data1(); stackingArea100Series1.XBindingPath = "XValue"; stackingArea100Series1.YBindingPath = "YValue"; stackingArea100Series1.Label = "Organic"; stackingArea100Series1.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingArea100Series1); StackingArea100Series stackingArea100Series2 = new StackingArea100Series(); stackingArea100Series2.EnableAnimation = true; stackingArea100Series2.ItemsSource = MainPage.GetStackedArea100Data2(); stackingArea100Series2.XBindingPath = "XValue"; stackingArea100Series2.YBindingPath = "YValue"; stackingArea100Series2.Label = "Fair-trade"; stackingArea100Series2.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingArea100Series2); StackingArea100Series stackingArea100Series3 = new StackingArea100Series(); stackingArea100Series3.EnableAnimation = true; stackingArea100Series3.ItemsSource = MainPage.GetStackedArea100Data3(); stackingArea100Series3.XBindingPath = "XValue"; stackingArea100Series3.YBindingPath = "YValue"; stackingArea100Series3.Label = "Veg Alternatives"; stackingArea100Series3.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingArea100Series3); StackingArea100Series stackingArea100Series4 = new StackingArea100Series(); stackingArea100Series4.EnableAnimation = true; stackingArea100Series4.ItemsSource = MainPage.GetStackedArea100Data4(); stackingArea100Series4.XBindingPath = "XValue"; stackingArea100Series4.YBindingPath = "YValue"; stackingArea100Series4.Label = "Others"; stackingArea100Series4.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingArea100Series4); stackingArea100Series1.TooltipEnabled = true; stackingArea100Series2.TooltipEnabled = true; stackingArea100Series3.TooltipEnabled = true; stackingArea100Series4.TooltipEnabled = true; stackingArea100Series1.EnableAnimation = true; stackingArea100Series2.EnableAnimation = true; stackingArea100Series3.EnableAnimation = true; stackingArea100Series4.EnableAnimation = true; return chart; } } }<file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/PullToRefreshTemplate/PullToRefreshTemplateBehaviour.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PullToRefreshTemplateBehaviour.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Syncfusion.SfPullToRefresh.XForms; using Syncfusion.XForms.Border; using Syncfusion.XForms.ProgressBar; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the <see cref="PullToRefreshTemplateBehaviour"/> samples /// </summary> public class PullToRefreshTemplateBehaviour : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfPullToRefresh pullToRefresh; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt transitionType; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DataGridPullToRefreshViewModel viewModel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfCircularProgressBar progressbar; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfBorder border; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type parameter named as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.viewModel = new DataGridPullToRefreshViewModel(); this.progressbar = new SfCircularProgressBar(); this.border = new SfBorder(); this.border.BorderColor = Color.LightGray; this.border.BackgroundColor = Color.White; this.border.CornerRadius = 35; this.border.Content = this.progressbar; this.border.BorderWidth = 0.2; this.progressbar.SegmentCount = 10; this.progressbar.IndicatorInnerRadius = 0.5; this.progressbar.IndicatorOuterRadius = 0.7; this.progressbar.ShowProgressValue = true; this.progressbar.GapWidth = 0.5; this.progressbar.WidthRequest = 70; this.progressbar.HeightRequest = 55; this.progressbar.IndeterminateAnimationDuration = 750; bindAble.BindingContext = this.viewModel; this.pullToRefresh = bindAble.FindByName<SfPullToRefresh>("pullToRefresh"); this.dataGrid = bindAble.FindByName<SfDataGrid>("dataGrid"); this.transitionType = bindAble.FindByName<PickerExt>("transitionType"); this.dataGrid.ItemsSource = this.viewModel.OrdersInfo; this.transitionType.Items.Add("SlideOnTop"); this.transitionType.Items.Add("Push"); this.transitionType.SelectedIndex = 0; this.transitionType.SelectedIndexChanged += this.OnSelectionChanged; this.pullToRefresh.Refreshing += this.PullToRefresh_Refreshing; this.pullToRefresh.Pulling += this.PullToRefresh_Pulling; var pullingTemplate = new DataTemplate(() => { return new ViewCell { View = this.border }; }); this.pullToRefresh.PullingViewTemplate = pullingTemplate; this.pullToRefresh.RefreshingViewTemplate = pullingTemplate; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type parameter named as bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.transitionType.SelectedIndexChanged -= this.OnSelectionChanged; this.pullToRefresh.Refreshing -= this.PullToRefresh_Refreshing; this.pullToRefresh = null; this.dataGrid = null; this.transitionType = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Fired when pulling occurs. /// </summary> /// <param name="sender">PullToRefresh_Refreshing event sender</param> /// <param name="e">PullToRefresh_Refreshing event args</param> private void PullToRefresh_Pulling(object sender, PullingEventArgs e) { this.progressbar.TrackInnerRadius = 0.8; this.progressbar.TrackOuterRadius = 0.1; this.progressbar.IsIndeterminate = false; this.progressbar.ProgressColor = Color.FromRgb(0, 124, 238); this.progressbar.TrackColor = Color.White; var absoluteProgress = Convert.ToInt32(Math.Abs(e.Progress)); this.progressbar.Progress = absoluteProgress; this.progressbar.SetProgress(absoluteProgress, 1, Easing.CubicInOut); } /// <summary> /// Fired when pullToRefresh View is refreshed /// </summary> /// <param name="sender">PullToRefresh_Refreshing event sender</param> /// <param name="e">PullToRefresh_Refreshing event args</param> private async void PullToRefresh_Refreshing(object sender, EventArgs e) { this.pullToRefresh.IsRefreshing = true; await this.AnimateRefresh(); this.viewModel.ItemsSourceRefresh(); this.pullToRefresh.IsRefreshing = false; } /// <summary> /// Increments the <see cref="SfProgressBar"/> progress value /// </summary> /// <returns>Returns the <see cref="Task"/>.</returns> private async Task AnimateRefresh() { this.progressbar.Progress = 0; this.progressbar.IsIndeterminate = true; await Task.Delay(750); this.progressbar.ProgressColor = Color.Red; await Task.Delay(750); this.progressbar.ProgressColor = Color.Green; await Task.Delay(750); this.progressbar.ProgressColor = Color.Orange; await Task.Delay(750); } /// <summary> /// Fired when selected index is changed /// </summary> /// <param name="sender">OnSelectionChanged sender</param> /// <param name="e">OnSelectionChanged event args e</param> private void OnSelectionChanged(object sender, EventArgs e) { if (this.transitionType.SelectedIndex == 0) { this.pullToRefresh.TransitionMode = TransitionType.SlideOnTop; } else { this.pullToRefresh.TransitionMode = TransitionType.Push; } } } } <file_sep>/Forms/Backdrop/Backdrop/Converter/TitleConverter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Globalization; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfBackdrop { [Preserve(AllMembers = true)] public class TitleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { return (bool)value ? "Settings" : "Backdrop Page"; } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } } <file_sep>/Forms/ImageEditor/ImageEditor/Samples/CustomViewSample/CustomViewHomePage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfImageEditor.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfImageEditor { public partial class CustomViewHomePage : ContentPage { bool isReplaced; ObservableCollection<Syncfusion.SfImageEditor.XForms.ToolbarItem> CustomViewItems; Assembly assembly = typeof(CustomViewSample).GetTypeInfo().Assembly; #if COMMONSB string samplePath = "SampleBrowser.Icons."; #else string samplePath = "SampleBrowser.SfImageEditor.Icons."; #endif CustomViewSettings customViewSettings; public CustomViewHomePage(ImageSource source, CustomViewViewModel viewModel) { InitializeComponent(); this.BindingContext = viewModel; // Set source to the SfImageEditor imageEditor.Source = source; imageEditor.RotatableElements = ImageEditorElements.CustomView; imageEditor.SetToolbarItemVisibility("text,transform,shape,path,effects", false); CustomViewItems = new ObservableCollection<Syncfusion.SfImageEditor.XForms.ToolbarItem>() { new CustomToolbarItem(){Icon=ImageSource.FromResource(samplePath+"ITypogy1.png", assembly),CustomName = "ITypogy1",IconHeight=70 }, new CustomToolbarItem(){Icon=ImageSource.FromResource(samplePath+"ITypogy2.png", assembly),CustomName = "ITypogy2",IconHeight=70 }, new CustomToolbarItem(){Icon=ImageSource.FromResource(samplePath+"ITypogy3.png", assembly),CustomName = "ITypogy3",IconHeight=70 }, new CustomToolbarItem(){Icon=ImageSource.FromResource(samplePath+"ITypogy4.png", assembly),CustomName = "ITypogy4",IconHeight=70 }, new CustomToolbarItem(){Icon=ImageSource.FromResource(samplePath+"ITypogy5.png", assembly),CustomName = "ITypogy5",IconHeight=70 }, new CustomToolbarItem(){Icon=ImageSource.FromResource(samplePath+"ITypogy6.png", assembly),CustomName = "ITypogy6",IconHeight=70 } }; // Add the custom tool bar items var item = new FooterToolbarItem() { Text = "Add", Icon = new FontImageSource() { Glyph = "\ue70a", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.Black }, SubItems = CustomViewItems, TextHeight = 20, }; imageEditor.ToolbarSettings.ToolbarItems.Add(item); item = new FooterToolbarItem() { Text = "Replace", IconHeight = Device.RuntimePlatform == Device.Android ? 27 : double.NaN, Icon = new FontImageSource() { Glyph = "\ue740", FontFamily = Device.RuntimePlatform == Device.iOS ? "SB Icons" : Device.RuntimePlatform == Device.Android ? "SB Icons.ttf#" : "SB Icons.ttf#SB Icons", Color = Color.Black }, SubItems = CustomViewItems, TextHeight = 20 }; imageEditor.ToolbarSettings.ToolbarItems.Add(item); item = new FooterToolbarItem() { Icon = new FontImageSource() { Glyph = "\ue764", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.Black }, Text = "Bring Front", TextHeight = 20 }; imageEditor.ToolbarSettings.ToolbarItems.Add(item); item = new FooterToolbarItem() { Icon = new FontImageSource() { Glyph = "\ue70e", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.Black }, Text = "Send Back", TextHeight = 20 }; imageEditor.ToolbarSettings.ToolbarItems.Add(item); imageEditor.ToolbarSettings.SubItemToolbarHeight = 70; imageEditor.ItemSelected += ImageEditor_ItemSelected; imageEditor.ToolbarSettings.ToolbarItemSelected += OnToolbarItemSelected; } private void ImageEditor_ItemSelected(object sender, ItemSelectedEventArgs args) { if (args.Settings != null && args.Settings is CustomViewSettings) { customViewSettings = args.Settings as CustomViewSettings; } } private void OnToolbarItemSelected(object sender, ToolbarItemSelectedEventArgs e) { string text = string.Empty; if (e.ToolbarItem is FooterToolbarItem) { text = e.ToolbarItem.Text; e.MoveSubItemsToFooterToolbar = true; } else if (e.ToolbarItem is CustomToolbarItem) text = (e.ToolbarItem as CustomToolbarItem).CustomName; else text = e.ToolbarItem.Name; if (text == "Replace") { isReplaced = true; //imageEditor.ToolbarSettings.FooterToolbarHeight = 70; } else if (text == "back") { isReplaced = false; //imageEditor.ToolbarSettings.FooterToolbarHeight = 50; } else if (text == "Add") { isReplaced = false; //imageEditor.ToolbarSettings.FooterToolbarHeight = 70; } if (isReplaced && imageEditor.IsSelected && (text == "ITypogy1" || text == "ITypogy2" || text == "ITypogy3" || text == "ITypogy4" || text == "ITypogy5" || text == "ITypogy6")) { imageEditor.Delete(); AddImage(text); } if (!isReplaced) AddImage(text); if (text == "Bring Front") imageEditor.BringToFront(); else if (text == "Send Back") imageEditor.SendToBack(); var properties = typeof(Syncfusion.SfImageEditor.XForms.SfImageEditor).GetRuntimeProperties(); } private void AddImage(string text) { if (text == "ITypogy1") SetSVGImage("Typogy1"); else if (text == "ITypogy2") SetSVGImage("Typogy2"); else if (text == "ITypogy3") SetSVGImage("Typogy3"); else if (text == "ITypogy4") SetSVGImage("Typogy4"); else if (text == "ITypogy5") SetSVGImage("Typogy5"); else if (text == "ITypogy6") SetSVGImage("Typogy6"); } private void SetSVGImage(string name) { object view = null; if (Device.RuntimePlatform == Device.iOS) { Image image = new Image(); image.HeightRequest = 150; image.WidthRequest = 150; image.Aspect = Aspect.AspectFill; string filePath = samplePath + "I" + name + ".png"; image.Source = ImageSource.FromResource(filePath, assembly); view = image; } else { view = DependencyService.Get<ICustomViewDependencyService>().GetCustomView(name, this); } if (isReplaced) imageEditor.AddCustomView(view, new CustomViewSettings() { Bounds = customViewSettings.Bounds,Angle=customViewSettings.Angle }); else { imageEditor.AddCustomView(view, new CustomViewSettings() { }); } } } public class CustomImageEditor : Syncfusion.SfImageEditor.XForms.SfImageEditor { } public interface ICustomViewDependencyService { object GetCustomView(string imageName, object context); Task<Stream> GetImageSource(string uri); } public class CustomToolbarItem : Syncfusion.SfImageEditor.XForms.ToolbarItem { public string CustomName { get; set; } public CustomToolbarItem() { } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/EmployeeInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; namespace SampleBrowser { public class EmployeeInfo:INotifyPropertyChanged { public EmployeeInfo () { } #region private variables private int salary; private int employeeID; private string name; private string title; private string company; private int age; private int bonus; #endregion #region Public Properties public int EmployeeID { get { return employeeID; } set { this.employeeID = value; RaisePropertyChanged ("EmployeeID"); } } public string Name { get { return this.name; } set { this.name = value; RaisePropertyChanged ("Name"); } } public int Age { get{ return age; } set{ age = value; } } public string Title { get { return title; } set { this.title = value; RaisePropertyChanged ("Title"); } } public int Salary { get { return salary; } set { this.salary = value; RaisePropertyChanged ("Salary"); } } public string Company { get{ return company; } set{ company = value; } } public int Bonus { get{ return bonus; } set{ bonus = value; } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged (String name) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (name)); } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfChart.XForms; using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfChart { public class ChartViewModel { DateTime time = new DateTime(2015, 01, 01); DateTime dataTime = new DateTime(2015, 01, 1); Random random = new Random(); private int count; private int wave1; private int wave2 = 180; public ObservableCollection<ChartDataModel> AreaData { get; set; } public ObservableCollection<ChartDataModel> LineData { get; set; } public ObservableCollection<ChartDataModel> LineData1 { get; set; } public ObservableCollection<ChartDataModel> ColumnData1 { get; set; } public ObservableCollection<ChartDataModel> ColumnData2 { get; set; } public ObservableCollection<ChartDataModel> ColumnData3 { get; set; } public ObservableCollection<ChartDataModel> BarData2 { get; set; } public ObservableCollection<RangeSeriesBaseModel> RangeAreaData { get; set; } public ObservableCollection<RangeSeriesBaseModel> RangeAreaData1 { get; set; } public ObservableCollection<ChartDataModel> FunnelData { get; set; } public ObservableCollection<ChartDataModel> StepLineData { get; set; } public ObservableCollection<ChartDataModel> CircularData { get; set; } public ObservableCollection<ChartDataModel> ScatterDataZoomPan { get { var items = new ObservableCollection<ChartDataModel>(); for (int i = 0; i < 300; i++) { double x = random.NextDouble() * 100; double y = random.NextDouble() * 500; double randomDouble = random.NextDouble(); if (randomDouble >= .25 && randomDouble < .5) { x *= -1; } else if (randomDouble >= .5 && randomDouble < .75) { y *= -1; } else if (randomDouble > .75) { x *= -1; y *= -1; } items.Add(new ChartDataModel(300 + (x * (random.NextDouble() + 0.12)), 100 + (y * (random.NextDouble() + 0.12)))); } return items; } } public ObservableCollection<ChartDataModel> Data1 { get; set; } public ObservableCollection<ChartDataModel> Data2 { get; set; } public ObservableCollection<ChartDataModel> Data3 { get; set; } public ObservableCollection<RangeSeriesBaseModel> RangeColumnData { get; set; } public ObservableCollection<ChartDataModel> data { get; set; } public ObservableCollection<ChartDataModel> liveData1 { get; set; } public ObservableCollection<ChartDataModel> liveData2 { get; set; } public ObservableCollection<ChartDataModel> verticalChart { get; set; } public ObservableCollection<ChartDataModel> MultipleSeriesData1 { get; set; } public ObservableCollection<ChartDataModel> MultipleSeriesData2 { get; set; } public ObservableCollection<ChartDataModel> LineSeries1 { get; set; } public ObservableCollection<ChartDataModel> LineSeries2 { get; set; } public ObservableCollection<ChartDataModel> LineSeries3 { get; set; } public ObservableCollection<ChartDataModel> TriangularData { get; set; } public ObservableCollection<ChartDataPoint> DateUsageData { get; set; } public ObservableCollection<ChartDataPoint> TechnicalIndicatorData { get; set; } public ChartViewModel() { DateTime calendar = new DateTime(2000, 1, 1); TechnicalIndicatorData = new ObservableCollection<ChartDataPoint> { new ChartDataPoint(calendar.AddMonths(1), 65.75, 67.27, 65.75, 65.98, 7938200), new ChartDataPoint(calendar.AddMonths(2), 65.98, 65.70, 65.04, 65.11, 10185300), new ChartDataPoint(calendar.AddMonths(3), 65.11, 65.05, 64.26, 64.97, 10835800), new ChartDataPoint(calendar.AddMonths(4), 64.97, 65.16, 64.09, 64.29, 9613400), new ChartDataPoint(calendar.AddMonths(5), 64.29, 62.73, 61.85, 62.44, 17175000), new ChartDataPoint(calendar.AddMonths(6), 62.44, 62.02, 61.29, 61.47, 18040600), new ChartDataPoint(calendar.AddMonths(7), 61.47, 62.75, 61.55, 61.59, 13456300), new ChartDataPoint(calendar.AddMonths(8), 61.59, 64.78, 62.22, 64.64, 8045100), new ChartDataPoint(calendar.AddMonths(9), 64.64, 64.50, 63.03, 63.28, 8608900), new ChartDataPoint(calendar.AddMonths(10), 63.28, 63.70, 62.70, 63.59, 15025500), new ChartDataPoint(calendar.AddMonths(11), 63.59, 64.45, 63.26, 63.61, 10065800), new ChartDataPoint(calendar.AddMonths(12), 63.61, 64.56, 63.81, 64.52, 6178200), new ChartDataPoint(calendar.AddMonths(13), 64.52, 64.84, 63.66, 63.91, 5478500), new ChartDataPoint(calendar.AddMonths(14), 63.91, 65.30, 64.50, 65.22, 7964300), new ChartDataPoint(calendar.AddMonths(15), 65.22, 65.36, 64.46, 65.06, 5679300), new ChartDataPoint(calendar.AddMonths(16), 65.06, 64.54, 63.56, 63.65, 10758300), new ChartDataPoint(calendar.AddMonths(17), 63.65, 64.03, 63.33, 63.73, 5665900), new ChartDataPoint(calendar.AddMonths(18), 63.73, 63.40, 62.80, 62.83, 5833000), new ChartDataPoint(calendar.AddMonths(19), 62.83, 63.75, 62.96, 63.60, 3500800), new ChartDataPoint(calendar.AddMonths(20), 63.6, 63.64, 62.51, 63.51, 5044700), new ChartDataPoint(calendar.AddMonths(21), 63.51, 64.03, 63.53, 63.76, 4871300), new ChartDataPoint(calendar.AddMonths(22), 63.76, 63.77, 63.01, 63.65, 7040400), new ChartDataPoint(calendar.AddMonths(23), 63.65, 63.95, 63.58, 63.79, 4727800), new ChartDataPoint(calendar.AddMonths(24), 63.79, 63.47, 62.92, 63.25, 6334900), new ChartDataPoint(calendar.AddMonths(25), 63.25, 63.96, 63.21, 63.48, 6823200), new ChartDataPoint(calendar.AddMonths(26), 63.48, 63.63, 62.55, 63.50, 9718400), new ChartDataPoint(calendar.AddMonths(27), 63.5, 63.25, 62.82, 62.90, 2827000), new ChartDataPoint(calendar.AddMonths(28), 62.9, 62.34, 62.05, 62.18, 4942700), new ChartDataPoint(calendar.AddMonths(29), 62.18, 62.86, 61.94, 62.81, 4582800), new ChartDataPoint(calendar.AddMonths(30), 62.81, 63.06, 62.44, 62.83, 12423900), new ChartDataPoint(calendar.AddMonths(31), 62.83, 63.16, 62.66, 63.09, 4940500), new ChartDataPoint(calendar.AddMonths(32), 63.09, 62.89, 62.43, 62.66, 6132300), new ChartDataPoint(calendar.AddMonths(33), 62.66, 62.39, 61.90, 62.25, 6263800), new ChartDataPoint(calendar.AddMonths(34), 62.25, 61.69, 60.97, 61.50, 5008300), new ChartDataPoint(calendar.AddMonths(35), 61.5, 61.87, 61.18, 61.79, 6662500), new ChartDataPoint(calendar.AddMonths(36), 61.79, 63.41, 62.72, 63.16, 5254000), new ChartDataPoint(calendar.AddMonths(37), 63.16, 64.40, 63.65, 63.89, 5356600), new ChartDataPoint(calendar.AddMonths(38), 63.89, 63.45, 61.60, 61.87, 5052600), new ChartDataPoint(calendar.AddMonths(39), 61.87, 62.35, 61.30, 61.54, 6266700), new ChartDataPoint(calendar.AddMonths(40), 61.54, 61.49, 60.33, 61.06, 6190800), new ChartDataPoint(calendar.AddMonths(41), 61.06, 60.78, 59.84, 60.09, 6452300), new ChartDataPoint(calendar.AddMonths(42), 60.09, 59.62, 58.62, 58.80, 5954000), new ChartDataPoint(calendar.AddMonths(43), 58.8, 59.60, 58.89, 59.53, 6250000), new ChartDataPoint(calendar.AddMonths(44), 59.53, 60.96, 59.42, 60.68, 5307300), new ChartDataPoint(calendar.AddMonths(45), 60.68, 61.12, 60.65, 60.73, 6192900), new ChartDataPoint(calendar.AddMonths(46), 60.73, 61.19, 60.62, 61.19, 6355600), new ChartDataPoint(calendar.AddMonths(47), 61.19, 61.07, 60.54, 60.97, 2946300), new ChartDataPoint(calendar.AddMonths(48), 60.97, 61.05, 59.65, 59.75, 2257600), new ChartDataPoint(calendar.AddMonths(49), 59.75, 60.58, 55.99, 59.93, 2872000), new ChartDataPoint(calendar.AddMonths(50), 59.93, 60.12, 59.26, 59.73, 2737500), new ChartDataPoint(calendar.AddMonths(51), 59.73, 60.11, 59.35, 59.57, 2589700), new ChartDataPoint(calendar.AddMonths(52), 59.57, 60.40, 59.60, 60.10, 7315800), new ChartDataPoint(calendar.AddMonths(53), 60.1, 60.31, 59.76, 60.28, 6883900), new ChartDataPoint(calendar.AddMonths(54), 60.28, 61.68, 60.50, 61.50, 5570700), new ChartDataPoint(calendar.AddMonths(55), 61.5, 62.72, 61.64, 62.26, 5976000), new ChartDataPoint(calendar.AddMonths(56), 62.26, 64.08, 63.10, 63.70, 3641400), new ChartDataPoint(calendar.AddMonths(57), 63.7, 64.60, 63.99, 64.39, 6711600), new ChartDataPoint(calendar.AddMonths(58), 64.39, 64.45, 63.92, 64.25, 6427000), new ChartDataPoint(calendar.AddMonths(59), 64.25, 65.40, 64.66, 64.70, 5863200), new ChartDataPoint(calendar.AddMonths(60), 64.7, 65.86, 65.32, 65.75, 4711400), new ChartDataPoint(calendar.AddMonths(61), 65.75, 65.22, 64.63, 64.75, 5930600), new ChartDataPoint(calendar.AddMonths(62), 64.75, 65.39, 64.76, 65.04, 5602700), new ChartDataPoint(calendar.AddMonths(63), 65.04, 65.30, 64.78, 65.18, 7487300), new ChartDataPoint(calendar.AddMonths(64), 65.18, 65.09, 64.42, 65.09, 9085400), new ChartDataPoint(calendar.AddMonths(65), 65.09, 65.64, 65.20, 65.25, 6455300), new ChartDataPoint(calendar.AddMonths(66), 65.25, 65.59, 64.74, 64.84, 6135500), new ChartDataPoint(calendar.AddMonths(67), 64.84, 65.84, 65.42, 65.82, 5846400), new ChartDataPoint(calendar.AddMonths(68), 65.82, 66.75, 65.85, 66.00, 6681200), new ChartDataPoint(calendar.AddMonths(69), 66, 67.41, 66.17, 67.41, 8780000), new ChartDataPoint(calendar.AddMonths(70), 67.41, 68.61, 68.06, 68.41, 10780900), new ChartDataPoint(calendar.AddMonths(71), 68.41, 68.91, 68.42, 68.76, 2336450), new ChartDataPoint(calendar.AddMonths(72), 68.76, 69.58, 68.86, 69.01, 11902000), new ChartDataPoint(calendar.AddMonths(73), 69.01, 69.14, 68.74, 68.94, 7513300), new ChartDataPoint(calendar.AddMonths(74), 68.94, 68.73, 68.06, 68.65, 12074800), new ChartDataPoint(calendar.AddMonths(75), 68.65, 68.79, 68.19, 68.67, 8785400), new ChartDataPoint(calendar.AddMonths(76), 68.67, 69.75, 68.68, 68.74, 11373200), new ChartDataPoint(calendar.AddMonths(77), 68.74, 68.82, 67.71, 67.76, 12378300), new ChartDataPoint(calendar.AddMonths(78), 67.76, 69.05, 68.43, 69.00, 8458700), new ChartDataPoint(calendar.AddMonths(79), 69, 68.39, 67.77, 68.02, 10779200), new ChartDataPoint(calendar.AddMonths(80), 68.02, 67.94, 67.22, 67.72, 9665400), new ChartDataPoint(calendar.AddMonths(81), 67.72, 68.15, 67.32, 67.32, 12258400), new ChartDataPoint(calendar.AddMonths(82), 67.32, 67.95, 67.13, 67.32, 7563600), new ChartDataPoint(calendar.AddMonths(83), 67.32, 68.00, 67.16, 67.96, 5509900), new ChartDataPoint(calendar.AddMonths(84), 67.96, 68.89, 68.34, 68.61, 12135500), new ChartDataPoint(calendar.AddMonths(85), 68.61, 69.47, 68.30, 68.51, 8462000), new ChartDataPoint(calendar.AddMonths(86), 68.51, 68.69, 68.21, 68.62, 2011950), new ChartDataPoint(calendar.AddMonths(87), 68.62, 68.39, 65.80, 68.37, 8536800), new ChartDataPoint(calendar.AddMonths(88), 68.37, 67.75, 65.00, 62.00, 7624900), new ChartDataPoint(calendar.AddMonths(89), 67.62, 67.04, 65.04, 67.00, 13694600), new ChartDataPoint(calendar.AddMonths(90), 66, 66.83, 65.02, 67.60, 8911200), new ChartDataPoint(calendar.AddMonths(91), 66.6, 66.98, 65.44, 66.73, 6679600), new ChartDataPoint(calendar.AddMonths(92), 66.73, 66.84, 65.10, 66.11, 6451900), new ChartDataPoint(calendar.AddMonths(93), 66.11, 66.59, 65.69, 66.38, 6739100), new ChartDataPoint(calendar.AddMonths(94), 66.38, 67.98, 66.51, 67.67, 2103260), new ChartDataPoint(calendar.AddMonths(95), 67.67, 69.21, 68.59, 68.90, 10551800), new ChartDataPoint(calendar.AddMonths(96), 68.9, 69.96, 69.27, 69.44, 5261100), new ChartDataPoint(calendar.AddMonths(97), 69.44, 69.01, 68.14, 68.18, 5905400), new ChartDataPoint(calendar.AddMonths(98), 68.18, 68.93, 68.08, 68.14, 10283600), new ChartDataPoint(calendar.AddMonths(99), 68.14, 68.60, 66.92, 67.25, 5006800), new ChartDataPoint(calendar.AddMonths(100), 67.25, 67.77, 67.23, 67.77, 4110000) }; DateUsageData = new ObservableCollection<ChartDataPoint>(); DateUsageData.Add(new ChartDataPoint(dataTime, 14)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 54)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 23)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 53)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 25)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 32)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 78)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 100)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 55)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 38)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 27)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 56)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 55)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 38)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 27)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 56)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 30)); addWeek(); DateUsageData.Add(new ChartDataPoint(dataTime, 45)); AreaData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 45), new ChartDataModel("2011", 56), new ChartDataModel("2012", 23), new ChartDataModel("2013", 43), new ChartDataModel("2014", double.NaN), new ChartDataModel("2015", 54), new ChartDataModel("2016", 43), new ChartDataModel("2017", 23), new ChartDataModel("2018", 34) }; LineData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2005", 28), new ChartDataModel("2006", 25), new ChartDataModel("2007", 26), new ChartDataModel("2008", 27), new ChartDataModel("2009", 32), new ChartDataModel("2010", 35), new ChartDataModel("2011", 30) }; CircularData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 8000), new ChartDataModel("2011", 8100), new ChartDataModel("2012", 8250), new ChartDataModel("2013", 8600), new ChartDataModel("2014", 8700) }; RangeColumnData = new ObservableCollection<RangeSeriesBaseModel> { new RangeSeriesBaseModel("Jan", 35, 17), new RangeSeriesBaseModel("Feb", 42, -11), new RangeSeriesBaseModel("Mar", 25, 5), new RangeSeriesBaseModel("Apr", 32, 10), new RangeSeriesBaseModel("May", 20, 3), new RangeSeriesBaseModel("Jun", 41, 30) }; Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 45), new ChartDataModel("2011", 89), new ChartDataModel("2012", 23), new ChartDataModel("2013", 43), new ChartDataModel("2014", 54) }; Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 54), new ChartDataModel("2011", 24), new ChartDataModel("2012", 53), new ChartDataModel("2013", 63), new ChartDataModel("2014", 35) }; Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 14), new ChartDataModel("2011", 54), new ChartDataModel("2012", 23), new ChartDataModel("2013", 53), new ChartDataModel("2014", 25) }; MultipleSeriesData1 = new ObservableCollection<ChartDataModel>(); for (var i = 1; i <= 12; i++) { MultipleSeriesData1.Add(new ChartDataModel(new DateTime(2014, i, 1), random.Next(10, 100))); } MultipleSeriesData2 = new ObservableCollection<ChartDataModel>(); for (var i = 1; i <= 12; i++) { MultipleSeriesData2.Add(new ChartDataModel(new DateTime(2014, i, 1), random.Next(10, 100))); } TriangularData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Bentley", 800), new ChartDataModel("Audi", 810), new ChartDataModel("BMW", 825), new ChartDataModel("Jaguar", 860), new ChartDataModel("Skoda", 875) }; data = new ObservableCollection<ChartDataModel>(); liveData1 = new ObservableCollection<ChartDataModel>(); liveData2 = new ObservableCollection<ChartDataModel>(); verticalChart = new ObservableCollection<ChartDataModel>(); LineSeries1 = new ObservableCollection<ChartDataModel>(); LineSeries1.Add(new ChartDataModel("2005", 31)); LineSeries1.Add(new ChartDataModel("2006", 28)); LineSeries1.Add(new ChartDataModel("2007", 30)); LineSeries1.Add(new ChartDataModel("2008", 36)); LineSeries1.Add(new ChartDataModel("2009", 36)); LineSeries1.Add(new ChartDataModel("2010", 39)); LineSeries2 = new ObservableCollection<ChartDataModel>(); LineSeries2.Add(new ChartDataModel("2005", 36)); LineSeries2.Add(new ChartDataModel("2006", 32)); LineSeries2.Add(new ChartDataModel("2007", 34)); LineSeries2.Add(new ChartDataModel("2008", 41)); LineSeries2.Add(new ChartDataModel("2009", 42)); LineSeries2.Add(new ChartDataModel("2010", 42)); LineSeries3 = new ObservableCollection<ChartDataModel>(); LineSeries3.Add(new ChartDataModel("2005", 39)); LineSeries3.Add(new ChartDataModel("2006", 36)); LineSeries3.Add(new ChartDataModel("2007", 40)); LineSeries3.Add(new ChartDataModel("2008", 44)); LineSeries3.Add(new ChartDataModel("2009", 45)); LineSeries3.Add(new ChartDataModel("2010", 48)); } public async void LoadData1() { for (var i = 0; i < 180; i++) { liveData1.Add(new ChartDataModel(i, Math.Sin(wave1 * (Math.PI / 180.0)))); wave1++; } for (var i = 0; i < 180; i++) { liveData2.Add(new ChartDataModel(i, Math.Sin(wave2 * (Math.PI / 180.0)))); wave2++; } wave1 = liveData1.Count; await Task.Delay(200); Device.StartTimer(new TimeSpan(0, 0, 0, 0, 10), () => { liveData1.RemoveAt(0); liveData1.Add(new ChartDataModel(wave1, Math.Sin(wave1 * (Math.PI / 180.0)))); wave1++; liveData2.RemoveAt(0); liveData2.Add(new ChartDataModel(wave1, Math.Sin(wave2 * (Math.PI / 180.0)))); wave2++; return true; }); } public void LoadVerticalData() { Random rand = new Random(); for (int j = 11; j < 50; j++) { verticalChart.Add(new ChartDataModel(j, rand.Next(-3, 3))); } int index = (int)verticalChart[verticalChart.Count - 1].Value + 1; Device.StartTimer(new TimeSpan(0, 0, 0, 0, 10), () => { count = count + 1; Random random = new Random(); if (count > 350) { return false; } else if (count > 300) { verticalChart.Add(new ChartDataModel(index, random.Next(0, 0))); } else if (count > 250) { verticalChart.Add(new ChartDataModel(index, random.Next(-2, 1))); } else if (count > 180) { verticalChart.Add(new ChartDataModel(index, random.Next(-3, 2))); } else if (count > 100) { verticalChart.Add(new ChartDataModel(index, random.Next(-7, 6))); } else { verticalChart.Add(new ChartDataModel(index, random.Next(-9, 9))); } index++; return true; }); } private void addWeek() { dataTime = dataTime.AddDays(7); } } } <file_sep>/iOS/SampleBrowser/Samples/NumericUpDown/NumericUpDown_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfNumericUpDown.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class NumericUpDown_Mobile: SampleView { UIPickerView spinPicker; UILabel minPrefixCharacterLabel,maxDropDownHeightLabel, adultLabel, infantLabel, spinLabel,autoReverse; UISwitch autoSwitch; UITextView minimumText,maximumText; UIButton cultureDoneButton,spinAlignmentButton; private string cultureSelectedType; SFNumericUpDown adultNumericUpDown; SFNumericUpDown infantsNumericUpDown; public UIView option = new UIView (); private readonly IList<string> cultureList = new List<string> (); public void optionView() { this.option.AddSubview(autoReverse); this.option.AddSubview(autoSwitch); this.option.AddSubview(spinLabel); this.option.AddSubview (spinAlignmentButton); this.option.AddSubview (minPrefixCharacterLabel); this.option.AddSubview (maxDropDownHeightLabel); this.option.AddSubview (minimumText); this.option.AddSubview (maximumText); this.option.AddSubview(spinPicker); this.option.AddSubview (cultureDoneButton); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; this.OptionView.Frame = view.Frame; option.Frame = new CGRect (0, 70, Frame.Width, Frame.Height); adultNumericUpDown.Frame = new CGRect(10, 40, view.Frame.Width-20, 32); infantsNumericUpDown.Frame = new CGRect(10, 150, view.Frame.Width-20,32); adultLabel.Frame = new CGRect(15, 0, this.Frame.Size.Width-20, 30); infantLabel.Frame = new CGRect(15, 110, this.Frame.Size.Width-20, 30); minimumText.Frame = new CGRect (230, 40, this.Frame.Size.Width - 250, 30); maximumText.Frame = new CGRect (230, 80, this.Frame.Size.Width - 250, 30); minPrefixCharacterLabel.Frame = new CGRect ( 10, 40,this.Frame.Size.Width-10 , 30); maxDropDownHeightLabel.Frame = new CGRect (10, 80, this.Frame.Size.Width - 10, 30); spinLabel.Frame=new CGRect(15,140, this.Frame.Size.Width-20, 40); spinAlignmentButton.Frame=new CGRect(10,180, this.Frame.Size.Width-20, 40); autoReverse.Frame=new CGRect(15, 240, this.Frame.Size.Width-20, 40); autoSwitch.Frame=new CGRect(250,240, this.Frame.Size.Width-20, 40); spinPicker.Frame=new CGRect(0,this.Frame.Size.Height/4, this.Frame.Size.Width,this.Frame.Size.Height/3); cultureDoneButton.Frame=new CGRect(0, this.Frame.Size.Height/4, this.Frame.Size.Width, 40); } this.optionView (); base.LayoutSubviews (); } static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public NumericUpDown_Mobile() { this.OptionView = new UIView(); //cultureList this.cultureList.Add((NSString)"Right"); this.cultureList.Add((NSString)"Left"); this.cultureList.Add((NSString)"Both"); //adultNumericUpDown adultNumericUpDown = new SFNumericUpDown(); adultNumericUpDown.AllowNull = true; adultNumericUpDown.PercentDisplayMode = SFNumericUpDownPercentDisplayMode.Compute; adultNumericUpDown.ValueChangeMode = SFNumericUpDownValueChangeMode.OnLostFocus; adultNumericUpDown.Value = 5; adultNumericUpDown.Minimum = 0; adultNumericUpDown.Maximum = 100; adultNumericUpDown.MaximumDecimalDigits = 0; adultNumericUpDown.Culture = new NSLocale("en_US"); this.AddSubview(adultNumericUpDown); //infantsNumericUpDown infantsNumericUpDown = new SFNumericUpDown(); infantsNumericUpDown.AllowNull = true; infantsNumericUpDown.PercentDisplayMode = SFNumericUpDownPercentDisplayMode.Compute; infantsNumericUpDown.Value = 3; infantsNumericUpDown.Minimum = 0; infantsNumericUpDown.Maximum = 100; infantsNumericUpDown.MaximumDecimalDigits = 0; infantsNumericUpDown.Culture = new NSLocale("en_US"); this.AddSubview(infantsNumericUpDown); mainPageDesign(); } public void mainPageDesign() { //adultLabell adultLabel = new UILabel(); adultLabel.TextColor = UIColor.Black; adultLabel.BackgroundColor = UIColor.Clear; adultLabel.Text = @"Number of Adults"; adultLabel.TextAlignment = UITextAlignment.Left; adultLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(adultLabel); //infantLabell infantLabel = new UILabel(); infantLabel.TextColor = UIColor.Black; infantLabel.BackgroundColor = UIColor.Clear; infantLabel.Text = @"Number of Infants"; infantLabel.TextAlignment = UITextAlignment.Left; infantLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(infantLabel); //autoReversee autoReverse = new UILabel(); autoReverse.TextColor = UIColor.Black; autoReverse.BackgroundColor = UIColor.Clear; autoReverse.Text = @"Auto Reverse"; autoReverse.TextAlignment = UITextAlignment.Left; autoReverse.Font = UIFont.FromName("Helvetica", 16f); //autoSwitchh autoSwitch = new UISwitch(); autoSwitch.ValueChanged += autoReverseToggleChanged; autoSwitch.On = false; //spinLabell spinLabel = new UILabel(); spinLabel.TextColor = UIColor.Black; spinLabel.BackgroundColor = UIColor.Clear; spinLabel.Text = @"Spin Alignment"; spinLabel.TextAlignment = UITextAlignment.Left; spinLabel.Font = UIFont.FromName("Helvetica", 16f); //spinAlignmentButtonn spinAlignmentButton = new UIButton(); spinAlignmentButton.SetTitle("Right", UIControlState.Normal); spinAlignmentButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; spinAlignmentButton.BackgroundColor = UIColor.Clear; spinAlignmentButton.SetTitleColor(UIColor.Black, UIControlState.Normal); spinAlignmentButton.Hidden = false; spinAlignmentButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; spinAlignmentButton.Layer.BorderWidth = 4; spinAlignmentButton.Layer.CornerRadius = 8; spinAlignmentButton.TouchUpInside += ShowSpinPicker; minPrefixCharacterLabel = new UILabel(); maxDropDownHeightLabel = new UILabel(); //minPrefixCharacterLabell minPrefixCharacterLabel.Text = "Minimum"; minPrefixCharacterLabel.TextColor = UIColor.Black; minPrefixCharacterLabel.TextAlignment = UITextAlignment.Left; minPrefixCharacterLabel.Font = UIFont.FromName("Helvetica", 16f); //maxDropDownHeightLabell maxDropDownHeightLabel.Text = "Maximum"; maxDropDownHeightLabel.TextColor = UIColor.Black; maxDropDownHeightLabel.TextAlignment = UITextAlignment.Left; maxDropDownHeightLabel.Font = UIFont.FromName("Helvetica", 16f); //Textt minimumText = new UITextView(); maximumText = new UITextView(); minimumText.Layer.BorderColor = UIColor.Black.CGColor; maximumText.Layer.BorderColor = UIColor.Black.CGColor; minimumText.BackgroundColor = UIColor.FromRGB(246, 246, 246); maximumText.BackgroundColor = UIColor.FromRGB(246, 246, 246); minimumText.KeyboardType = UIKeyboardType.NumberPad; maximumText.KeyboardType = UIKeyboardType.NumberPad; minimumText.Text = "0"; maximumText.Text = "100"; maximumText.Font = UIFont.FromName("Helvetica", 16f); minimumText.Font = UIFont.FromName("Helvetica", 16f); maximumText.Changed += (object sender, EventArgs e) => { if (maximumText.Text.Length > 0) { adultNumericUpDown.Maximum = nfloat.Parse(maximumText.Text); infantsNumericUpDown.Maximum = nfloat.Parse(maximumText.Text); } }; minimumText.Changed += (object sender, EventArgs e) => { if (minimumText.Text.Length > 0) { adultNumericUpDown.Minimum = nfloat.Parse(minimumText.Text); infantsNumericUpDown.Minimum = nfloat.Parse(minimumText.Text); } }; //spinPickerr PickerModel culturePickermodel = new PickerModel(this.cultureList); culturePickermodel.PickerChanged += (sender, e) => { this.cultureSelectedType = e.SelectedValue; spinAlignmentButton.SetTitle(cultureSelectedType, UIControlState.Normal); if (cultureSelectedType == "Right") { adultNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Right; infantsNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Right; adultNumericUpDown.TextAlignment = UITextAlignment.Left; infantsNumericUpDown.TextAlignment=UITextAlignment.Left; } else if (cultureSelectedType == "Left") { adultNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Left; infantsNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Left; adultNumericUpDown.TextAlignment = UITextAlignment.Right; infantsNumericUpDown.TextAlignment = UITextAlignment.Right; } else if (cultureSelectedType == "Both") { adultNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Both; infantsNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Both; adultNumericUpDown.TextAlignment = UITextAlignment.Center; infantsNumericUpDown.TextAlignment = UITextAlignment.Center; } }; spinPicker = new UIPickerView(); spinPicker.ShowSelectionIndicator = true; spinPicker.Hidden = true; spinPicker.Model = culturePickermodel; spinPicker.BackgroundColor = UIColor.White; //cultureDoneButtonn cultureDoneButton = new UIButton(); cultureDoneButton.SetTitle("Done\t", UIControlState.Normal); cultureDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; cultureDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); cultureDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureDoneButton.Hidden = true; cultureDoneButton.TouchUpInside += HideSpinPicker; this.BackgroundColor = UIColor.White; } void ShowSpinPicker (object sender, EventArgs e) { cultureDoneButton.Hidden = false; spinPicker.Hidden = false; this.BecomeFirstResponder (); } void HideSpinPicker (object sender, EventArgs e) { cultureDoneButton.Hidden = true; spinPicker.Hidden = true; this.BecomeFirstResponder (); } private void autoReverseToggleChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { adultNumericUpDown.AutoReverse = true; infantsNumericUpDown.AutoReverse = true; } else { adultNumericUpDown.AutoReverse = false; infantsNumericUpDown.AutoReverse = false; } } public override void TouchesBegan (NSSet touches, UIEvent evt){ this.EndEditing (true); } } } <file_sep>/Forms/ImageEditor/ImageEditor.UWP/Renderers/CustomRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using SampleBrowser.SfImageEditor.UWP.Renderers; using CustomControls = SampleBrowser.SfImageEditor.CustomControls; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; using Button = Xamarin.Forms.Button; using WindowsMedia = Windows.UI.Xaml.Media; using Windows.Storage; using Windows.Storage.Streams; using System.IO; [assembly: ExportRenderer(typeof(CustomControls.CustomButton), typeof(CustomButtonRenderer))] [assembly:ExportRenderer(typeof(CustomControls.CustomEditor), typeof(CustomEditorRenderer))] [assembly:ExportRenderer(typeof(CustomControls.RoundedColorButton), typeof(ColorButtonRenderer))] [assembly: Dependency(typeof(CustomImageView))] namespace SampleBrowser.SfImageEditor.UWP.Renderers { public class CustomEditorRenderer : EditorRenderer { CustomControls.CustomEditor editor; protected override void OnElementChanged(ElementChangedEventArgs<Editor> e) { base.OnElementChanged(e); if (Control != null) { var element = (CustomControls.CustomEditor) e.NewElement; if (element == null) return; editor = element; Control.Loaded += Control_Loaded; Control.Foreground = new WindowsMedia.SolidColorBrush(Colors.Black); Control.Text = element.WatermarkText; Control.GotFocus += Control_GotFocus; if (Device.Idiom == TargetIdiom.Desktop) { Control.Height = 33; } Control.VerticalContentAlignment = VerticalAlignment.Center; Control.TextAlignment = Windows.UI.Xaml.TextAlignment.Center; } } private void Control_Loaded(object sender, RoutedEventArgs e) { //var text = sender as TextBox; //text.Style = App.Current.Resources["CustomTextBoxStyle"] as Windows.UI.Xaml.Style; } private void Control_GotFocus(object sender, RoutedEventArgs e) { var textBox = sender as TextBox; textBox.SelectAll(); textBox.TextChanged += TextBox_TextChanged; } protected override void Dispose(bool disposing) { } private void TextBox_TextChanged(object sender, Windows.UI.Xaml.Controls.TextChangedEventArgs e) { var textBox = sender as TextBox; if (textBox.Text == editor.WatermarkText) textBox.Text = string.Empty; } } public class ColorButtonRenderer : ButtonRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Button> e) { base.OnElementChanged(e); if (Control != null) { var element = e.NewElement as CustomControls.RoundedColorButton; element.SizeChanged += (s, args) => { Control.ApplyTemplate(); var grids = Control.GetVisuals<Windows.UI.Xaml.Controls.Grid>(); foreach (var grid in grids) { grid.Width = 150; grid.Height = 40; grid.CornerRadius = new Windows.UI.Xaml.CornerRadius(15); } }; } } } static class DependencyObjectExtensions { public static IEnumerable<T> GetVisuals<T>(this DependencyObject root) where T : DependencyObject { int count = VisualTreeHelper.GetChildrenCount(root); for (int i = 0; i < count; i++) { var child = VisualTreeHelper.GetChild(root, i); if (child is T) yield return child as T; foreach (var descendants in child.GetVisuals<T>()) { yield return descendants; } } } } public class CustomImageView : ICustomViewDependencyService { public object GetCustomView(string imageName, object context) { Windows.UI.Xaml.Controls.Image svgimage = new Windows.UI.Xaml.Controls.Image() { Height = 200, Width = 200 }; svgimage.Source = new WindowsMedia.Imaging.SvgImageSource(new Uri("ms-appx:///Assets/" + imageName + ".svg", UriKind.Absolute)); return svgimage; } public async Task<Stream> GetImageSource(string uri) { StorageFile imagefile = await StorageFile.GetFileFromPathAsync(uri); IRandomAccessStream stream = await imagefile.OpenAsync(FileAccessMode.Read); return stream.AsStream(); } } // Applies font text color as white for the buttons in the customization sample public class CustomButtonRenderer : ButtonRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e) { base.OnElementChanged(e); if (Control != null) { #if !COMMONSB Control.Style = SampleBrowser.SfImageEditor.UWP.App.Current.Resources["CustomButtonStyle"] as Windows.UI.Xaml.Style; #endif } } } } <file_sep>/Forms/DocIO/DocIO/Samples/EncryptAndDecrypt/EncryptAndDecrypt.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using SampleBrowser.Core; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.DocIO; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using Syncfusion.OfficeChart; using Syncfusion.Drawing; namespace SampleBrowser.DocIO { public partial class EncryptAndDecrypt : SampleView { public EncryptAndDecrypt() { InitializeComponent(); this.encryptButton.IsChecked = true; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.btnGenerate.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Description.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Description.FontSize = 13.5; } this.Description.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { WordDocument document = null; if (this.encryptButton != null && (bool)this.encryptButton.IsChecked) { //Creates a new Word document document = new WordDocument(); document.EnsureMinimal(); // Getting last section of the document. IWSection section = document.LastSection; // Adding a paragraph to the section. IWParagraph paragraph = section.AddParagraph(); // Writing text IWTextRange text = paragraph.AppendText("This document was encrypted with password"); text.CharacterFormat.FontSize = 16f; text.CharacterFormat.FontName = "Bitstream Vera Serif"; // Encrypt the document by giving password document.EncryptDocument("syncfusion"); } else { Assembly assembly = typeof(EncryptAndDecrypt).GetTypeInfo().Assembly; document = new WordDocument(); #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif // Open an existing template document. Stream inputStream = assembly.GetManifestResourceStream(rootPath + "Security Settings.docx"); document.Open(inputStream, FormatType.Docx, "syncfusion"); inputStream.Dispose(); // Getting last section of the document. IWSection section = document.LastSection; // Adding a paragraph to the section. IWParagraph paragraph = section.AddParagraph(); // Writing text IWTextRange text = paragraph.AppendText("\nDemo For Document Decryption with Essential DocIO"); text.CharacterFormat.FontSize = 16f; text.CharacterFormat.FontName = "Bitstream Vera Serif"; text = paragraph.AppendText("\nThis document is Decrypted"); text.CharacterFormat.FontSize = 16f; text.CharacterFormat.FontName = "Bitstream Vera Serif"; } MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Docx); document.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Encrypt and Decrypt.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("Encrypt and Decrypt.docx", "application/msword", stream); } } } <file_sep>/Forms/TabView/TabView/Samples/TabViewGettingStarted/View/TabViewGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XForms.TabView; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SampleBrowser.Core; using System.Collections.ObjectModel; using System.Linq; namespace SampleBrowser.SfTabView { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class TabViewGettingStarted : SampleView { private Syncfusion.XForms.TabView.SfTabView tabView; private ObservableCollection<ListView> ListViewCollection = new ObservableCollection<ListView>(); private TabDataViewModel viewModel = new TabDataViewModel(); public TabViewGettingStarted() { InitializeComponent(); ConfigureListView(); tabView = GetTabView(); tabView.TabHeight = 64; this.Content = tabView; EnableScrollSwitch.Toggled += EnableScrollableSwitch_Toggled; EnableRippleAnimation.Toggled += EnableRippleAnimation_Toggled; } private void EnableRippleAnimation_Toggled(object sender, ToggledEventArgs e) { if (e.Value == true) { this.tabView.EnableRippleAnimation = true; } else { this.tabView.EnableRippleAnimation = false; } } private void EnableScrollableSwitch_Toggled(object sender, ToggledEventArgs e) { if(e.Value == true) { if (this.tabView.OverflowMode == OverflowMode.Scroll) { this.tabView.IsScrollButtonEnabled = true; this.tabView.ScrollButtonForegroundColor = Color.White; this.tabView.VisibleHeaderCount = 3; } else { this.EnableScrollSwitch.IsToggled = false; this.tabView.VisibleHeaderCount = null; } } else { if (this.tabView.OverflowMode == OverflowMode.Scroll) { this.tabView.IsScrollButtonEnabled = false; this.tabView.VisibleHeaderCount = null; } } } private Syncfusion.XForms.TabView.SfTabView GetTabView() { var _tabView = new Syncfusion.XForms.TabView.SfTabView(); _tabView.DisplayMode = TabDisplayMode.ImageWithText; _tabView.OverflowMode = OverflowMode.Scroll; _tabView.TabHeaderBackgroundColor = Color.FromHex("#2196F3"); _tabView.OverflowButtonSettings = new OverflowButtonSettings() { TitleFontColor = Color.White }; _tabView.VisibleHeaderCount = 4; if (Device.RuntimePlatform == "iOS") _tabView.TabHeight = 60; var index = 0; var iconList = new[] {"A", "C", "F", "H", "K"}; foreach (var category in viewModel.Categories) { var tabViewItem = new SfTabItem { Title = category, IconFont = iconList[index], Content = ListViewCollection[index], SelectionColor = Color.White, TitleFontColor = Color.LightBlue, FontIconFontColor = Color.LightBlue, TitleFontSize = Device.Idiom == TargetIdiom.Tablet ? 16 : 12 }; if(Device.RuntimePlatform == "iOS") { tabViewItem.FontIconFontFamily = "TabIcons"; } else if(Device.RuntimePlatform == "Android") { tabViewItem.FontIconFontFamily = "TabIcons.ttf"; } else if(Device.RuntimePlatform == "UWP") { #if COMMONSB tabViewItem.FontIconFontFamily = "/Assets/Fonts/TabIcons.ttf#TabIcons"; #else if (Core.SampleBrowser.IsIndividualSB) { tabViewItem.FontIconFontFamily = "/Assets/Fonts/TabIcons.ttf#TabIcons"; } else { tabViewItem.FontIconFontFamily = $"ms-appx:///SampleBrowser.SfTabView.UWP/Assets/Fonts/TabIcons.ttf#TabIcons"; //@"SampleBrowser.SfTabView.UWP\Assets\Fonts\TabIcons.ttf#TabIcons"; } #endif } _tabView.Items.Add(tabViewItem); index++; } _tabView.SelectionIndicatorSettings = new SelectionIndicatorSettings() { Position = SelectionIndicatorPosition.Bottom, Color = Color.White }; _tabView.TabHeaderPosition = TabHeaderPosition.Top; return _tabView; } private void ConfigureListView() { int i = 0; foreach (var item in viewModel.Categories) { var data = from cust in viewModel.Data where cust.Category == item select cust; DataTemplate dataTemplate; int rowHeight; if (Device.Idiom == TargetIdiom.Tablet) { dataTemplate = new DataTemplate(typeof(ItemViewTabletMode)); rowHeight = 250; } else { dataTemplate = new DataTemplate(typeof(ProductView)); rowHeight = 240; } var listView = new ListView { RowHeight = rowHeight, ItemsSource = data, BackgroundColor = Color.White, ItemTemplate = dataTemplate, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, SeparatorColor = Color.Transparent }; // listView.LayoutManager = new GridLayout() { SpanCount = 3 }; ListViewCollection.Add(listView); i++; } } void Handle_SelectedIndexChanged(object sender, System.EventArgs e) { var picker = sender as Picker; if (picker == null) return; switch (picker.SelectedIndex) { case 0: tabView.OverflowMode = OverflowMode.Scroll; if(tabView.IsScrollButtonEnabled) { this.EnableScrollSwitch.IsToggled = true; } else { this.EnableScrollSwitch.IsToggled = false; } break; case 1: tabView.IsScrollButtonEnabled = false; tabView.OverflowMode = OverflowMode.DropDown; this.EnableScrollSwitch.IsToggled = false; break; } } private void HeaderTypePicker_OnSelectedIndexChanged(object sender, EventArgs e) { var picker = sender as Picker; if (picker == null) return; switch (picker.SelectedIndex) { case 0: tabView.DisplayMode = TabDisplayMode.Text; tabView.TabHeight = 48; break; case 1: tabView.DisplayMode = TabDisplayMode.Image; tabView.TabHeight = 48; break; case 2: tabView.DisplayMode = TabDisplayMode.ImageWithText; tabView.TabHeight = 64; break; default: tabView.DisplayMode = TabDisplayMode.NoHeader; break; } } private void HeaderPositionPicker_OnSelectedIndexChanged(object sender, EventArgs e) { var picker = sender as Picker; if (picker == null) return; switch (picker.SelectedIndex) { case 0: tabView.TabHeaderPosition = TabHeaderPosition.Top; break; default: tabView.TabHeaderPosition = TabHeaderPosition.Bottom; break; } } private void SelectionIndicatorPositionPicker_OnSelectedIndexChanged(object sender, EventArgs e) { var picker = sender as Picker; if(picker == null) return; switch (picker.SelectedIndex) { case 0: tabView.SelectionIndicatorSettings.Position = SelectionIndicatorPosition.Top; break; default: tabView.SelectionIndicatorSettings.Position = SelectionIndicatorPosition.Bottom; break; } } } }<file_sep>/Android/SampleBrowser/Samples/Presentation/WriteProtection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Xml; namespace SampleBrowser { public partial class WriteProtection : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to set a write protection for a PowerPoint presentation."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "Password : <PASSWORD>"; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Presentation"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Transition.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Set the write protection for presentation instance presentation.SetWriteProtection("syncfusion"); MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("WriteProtection.pptx", "application/powerpoint", stream, m_context); } } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/OrderInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "OrderInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties Notifies clients that a property value has changed. /// </summary> public class OrderInfo : INotifyPropertyChanged { #region private variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string orderID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string employeeID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string customerID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string firstname; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string lastname; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string gender; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string shipCity; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string shipCountry; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double freight; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DateTime shippingDate; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private bool isClosed; #endregion /// <summary> /// Initializes a new instance of the OrderInfo class. /// </summary> public OrderInfo() { } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the value of OrderID and notifies user when value gets changed /// </summary> public string OrderID { get { return this.orderID; } set { this.orderID = value; this.RaisePropertyChanged("OrderID"); } } /// <summary> /// Gets or sets the value of EmployeeID and notifies user when value gets changed /// </summary> public string EmployeeID { get { return this.employeeID; } set { this.employeeID = value; this.RaisePropertyChanged("EmployeeID"); } } /// <summary> /// Gets or sets the value of CustomerID and notifies user when value gets changed /// </summary> public string CustomerID { get { return this.customerID; } set { this.customerID = value; this.RaisePropertyChanged("CustomerID"); } } /// <summary> /// Gets or sets the value of FirstName and notifies user when value gets changed /// </summary> public string FirstName { get { return this.firstname; } set { this.firstname = value; this.RaisePropertyChanged("FirstName"); } } /// <summary> /// Gets or sets the value of LastName and notifies user when value gets changed /// </summary> public string LastName { get { return this.lastname; } set { this.lastname = value; this.RaisePropertyChanged("LastName"); } } /// <summary> /// Gets or sets the value of Gender and notifies user when value gets changed /// </summary> public string Gender { get { return this.gender; } set { this.gender = value; this.RaisePropertyChanged("Gender"); } } /// <summary> /// Gets or sets the value of ShipCity and notifies user when value gets changed /// </summary> public string ShipCity { get { return this.shipCity; } set { this.shipCity = value; this.RaisePropertyChanged("ShipCity"); } } /// <summary> /// Gets or sets the value of ShipCountry and notifies user when value gets changed /// </summary> public string ShipCountry { get { return this.shipCountry; } set { this.shipCountry = value; this.RaisePropertyChanged("ShipCountry"); } } /// <summary> /// Gets or sets the value of Freight and notifies user when value gets changed /// </summary> public double Freight { get { return this.freight; } set { this.freight = value; this.RaisePropertyChanged("Freight"); } } /// <summary> /// Gets or sets a value indicating whether IsClosed is true or false and notifies user when value gets changed /// </summary> public bool IsClosed { get { return this.isClosed; } set { this.isClosed = value; this.RaisePropertyChanged("IsClosed"); } } /// <summary> /// Gets or sets the value of ShippingDate and notifies user when value gets changed /// </summary> public DateTime ShippingDate { get { return this.shippingDate; } set { this.shippingDate = value; this.RaisePropertyChanged("ShippingDate"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Forms/DataForm/DataForm/Samples/DynamicFormPage/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; namespace SampleBrowser.SfDataForm { /// <summary> /// Represents the view model of data form dynamic forms sample. /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public class ViewModel { /// <summary> /// Represents the selectionForm information. /// </summary> private List<string> selectedForm; /// <summary> /// Gets or sets the SelectionForm information. /// </summary> public List<string> SelectedForm { get { return this.selectedForm; } set { this.selectedForm = value; } } /// <summary> /// Initializes a new list of the <see cref="SelectedForm"/>. /// </summary> public ViewModel() { List<string> list = new List<string>(); list.Add("Organization Form"); list.Add("Employee Form"); list.Add("Ecommerce"); this.selectedForm = list; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Maps/Sublayer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfBusyIndicator.iOS; using System; using Syncfusion.SfMaps.iOS; #if __UNIFIED__ using Foundation; using CoreGraphics; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGPoint= System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Sublayer : SampleView { internal SFBusyIndicator busyindicator; UIView view; UILabel label; public override void LayoutSubviews() { view.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); ; SetNeedsDisplay(); } public Sublayer() { SFMap maps = new SFMap(); view = new UIView(); view.Frame = new CGRect(0, 0, 300, 400); busyindicator = new SFBusyIndicator(); busyindicator.ViewBoxWidth = 75; busyindicator.ViewBoxHeight = 75; busyindicator.Foreground = UIColor.FromRGB(0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; view.AddSubview(busyindicator); label = new UILabel(); label.TextAlignment = UITextAlignment.Center; label.Text = "Samsung Semiconductor office locations in USA"; label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(0, 0, 400, 40); label.TextColor = UIColor.Black; view.AddSubview(label); NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(0.3), delegate { maps.Frame = new CGRect(Frame.Location.X, 60, Frame.Size.Width - 6, Frame.Size.Height - 60); view.AddSubview(maps); }); SFShapeFileLayer layer = new SFShapeFileLayer(); layer.Uri = (NSString)NSBundle.MainBundle.PathForResource("usa_state", "shp"); layer.ShapeIDPath = (NSString)"Name"; layer.ShapeIDTableField = (NSString)"STATE_NAME"; layer.ShowMapItems = true; layer.DataSource = GetDataSource(); SFShapeSetting shapeSettings = new SFShapeSetting(); shapeSettings.ValuePath = (NSString)"Type"; shapeSettings.Fill = UIColor.FromRGB(229, 229, 229); shapeSettings.StrokeColor = UIColor.FromRGB(208, 208, 208); shapeSettings.StrokeThickness = 2; layer.ShapeSettings = shapeSettings; SFDataLabelSetting dataLabelSetting = new SFDataLabelSetting(); dataLabelSetting.SmartLabelMode = IntersectAction.Trim; layer.DataLabelSettings = dataLabelSetting; SFShapeFileLayer subLayer = new SFShapeFileLayer(); subLayer.Uri = (NSString)NSBundle.MainBundle.PathForResource("Texas", "shp"); SFMapMarker marker1 = new SFMapMarker(); marker1.Latitude = 32.870404; marker1.Longitude = -99.467014; subLayer.Markers.Add(marker1); SFShapeFileLayer subLayer1 = new SFShapeFileLayer(); subLayer1.Uri = (NSString)NSBundle.MainBundle.PathForResource("California", "shp"); SFMapMarker marker2 = new SFMapMarker(); marker2.Latitude = 38.778259; marker2.Longitude = -120.463228; subLayer1.Markers.Add(marker2); SFShapeSetting subshapeSettings = new SFShapeSetting(); subshapeSettings.Fill = UIColor.FromRGB(177, 216, 245); subshapeSettings.StrokeColor = UIColor.FromRGB(141, 204, 244); subshapeSettings.StrokeThickness = 1; subLayer.ShapeSettings = subshapeSettings; subLayer1.ShapeSettings = subshapeSettings; layer.Sublayers.Add(subLayer); layer.Sublayers.Add(subLayer1); maps.Layers.Add(layer); AddSubview(view); maps.Delegate = new MapsSublayerDelegate(this); } NSMutableArray GetDataSource() { NSMutableArray array = new NSMutableArray(); array.Add(getDictionary("Alabama", "AL", 42)); array.Add(getDictionary("Alaska", "AK", 0)); array.Add(getDictionary("Arizona", "AR", 36)); array.Add(getDictionary("Arkansas", "AN", 46)); array.Add(getDictionary("California", "CA", 24)); array.Add(getDictionary("Colorado", "CO", 31)); array.Add(getDictionary("Connecticut", "CN", 18)); array.Add(getDictionary("Delaware", "DE", 28)); array.Add(getDictionary("District of Columbia", "DC", 27)); array.Add(getDictionary("Florida", "FL", 48)); array.Add(getDictionary("Georgia", "GE", 44)); array.Add(getDictionary("Hawaii", "HA", 49)); array.Add(getDictionary("Idaho", "ID", 8)); array.Add(getDictionary("Illinois", "IL", 26)); array.Add(getDictionary("Indiana", "IN", 21)); array.Add(getDictionary("Iowa", "IO", 13)); array.Add(getDictionary("Kansas", "KA", 33)); array.Add(getDictionary("Kentucky", "KE", 32)); array.Add(getDictionary("Louisiana", "LO", 47)); array.Add(getDictionary("Maine", "MA", 3)); array.Add(getDictionary("Maryland", "MY", 30)); array.Add(getDictionary("Massachusetts", "MS", 14)); array.Add(getDictionary("Michigan", "MI", 50)); array.Add(getDictionary("Minnesota", "MN", 10)); array.Add(getDictionary("Mississippi", "MP", 43)); array.Add(getDictionary("Missouri", "MO", 35)); array.Add(getDictionary("Montana", "MT", 2)); array.Add(getDictionary("Nebraska", "NE", 15)); array.Add(getDictionary("Nevada", "NV", 22)); array.Add(getDictionary("New Hampshire", "NH", 12)); array.Add(getDictionary("New Jersey", "NJ", 20)); array.Add(getDictionary("New Mexico", "NM", 41)); array.Add(getDictionary("New York", "NY", 16)); array.Add(getDictionary("North Carolina", "NC", 38)); array.Add(getDictionary("North Dakota", "ND", 4)); array.Add(getDictionary("Ohio", "OH", 25)); array.Add(getDictionary("Oklahoma", "OK", 37)); array.Add(getDictionary("Oregon", "OR", 11)); array.Add(getDictionary("Pennsylvania", "PE", 17)); array.Add(getDictionary("Rhode Island", "RH", 19)); array.Add(getDictionary("South Carolina", "SC", 45)); array.Add(getDictionary("South Dakota", "SD", 5)); array.Add(getDictionary("Tennessee", "TE", 39)); array.Add(getDictionary("Texas", "TX", 40)); array.Add(getDictionary("Utah", "UT", 23)); array.Add(getDictionary("Vermont", "VE", 9)); array.Add(getDictionary("Virginia", "VI", 34)); array.Add(getDictionary("Washington", "WA", 1)); array.Add(getDictionary("West Virginia", "WV", 29)); array.Add(getDictionary("Wisconsin", "WI", 7)); array.Add(getDictionary("Wyoming", "WY", 6)); return array; } NSDictionary getDictionary(string name, string type, int index) { NSString name1 = (NSString)name; object[] objects = new object[3]; object[] keys = new object[3]; keys.SetValue("Name", 0); keys.SetValue("index", 1); keys.SetValue("Type", 2); objects.SetValue(name1, 0); objects.SetValue(index, 1); objects.SetValue(type, 2); return NSDictionary.FromObjectsAndKeys(objects, keys); } } public class MapsSublayerDelegate : SFMapsDelegate { public MapsSublayerDelegate(Sublayer sublayer) { sample = sublayer; } Sublayer sample; public override void DidLoad(SFMap map) { if (sample.busyindicator != null) { sample.busyindicator.RemoveFromSuperview(); sample.busyindicator = null; } } } }<file_sep>/Forms/ListView/ListView/Samples/DataTemplateSelector/Model/MessageInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.ListView.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class MessageInfoRepository : MessageInfo { #region Constructor public MessageInfoRepository() { } #endregion #region MessageInfo internal ObservableCollection<MessageInfo> GenerateInfo() { var MessageInfo = new ObservableCollection<MessageInfo>(); MessageInfo.Add(new MessageInfo() { Text = Descriptions[0], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-77)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[1], ProfileImage = "People_Circle1.png", Username = "Nancy", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-75)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[2], ProfileImage = "People_Circle5.png", Username = "Andrew", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-73)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[3], ProfileImage = "People_Circle1.png", Username = "Nancy", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-72)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[4], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-70)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[5], ProfileImage = "People_Circle5.png", Username = "Andrew", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-69)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[6], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-67)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[7], ProfileImage = "People_Circle17.png", Username = "Catherine", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-66)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[8], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-64)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[9], ProfileImage = "People_Circle5.png", Username = "Andrew", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-54)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[10], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-50)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[11], ProfileImage = "People_Circle1.png", Username = "Nancy", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-48)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[12], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-47)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[13], ProfileImage = "People_Circle5.png", Username = "Andrew", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-45)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[14], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-44)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[15], ProfileImage = "People_Circle5.png", Username = "Andrew", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-42)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[16], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-39)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[17], ProfileImage = "People_Circle1.png", Username = "Nancy", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-30)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[18], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-28)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[19], ProfileImage = "People_Circle5.png", Username = "Andrew", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-24)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[20], DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-21)), TemplateType = TemplateType.OutGoingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[21], ProfileImage = "People_Circle5.png", Username = "Andrew", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-15)), TemplateType = TemplateType.IncomingText }); MessageInfo.Add(new MessageInfo() { Text = Descriptions[22], ProfileImage = "People_Circle1.png", Username = "Nancy", DateTime = string.Format(CultureInfo.InvariantCulture.DateTimeFormat, "{0:d/MM/yyyy HH:mm}", System.DateTime.Now.AddMinutes(-10)), TemplateType = TemplateType.IncomingText }); return MessageInfo; } #endregion #region Properties public string[] Descriptions = new string[] { "Hi Guys, Good morning! I’m very delighted to share with you the news that our team is going to launch a new mobile application.", "Oh! That’s great.", "That is a good news.", "What kind of application are we gonna launch?.", "A kind of “Emergency Broadcast App”.", "Can you please elaborate?", "The app will help users to broadcast emergency messages to friends and family from mobile with location during emergency situations.", "Can we extend this idea broadcast the data all the time? It will be better if we provide options to broadcast to selected people based on timings or profiles.", "That’s a great idea. We can consider that in our requirement.", "Do we have any layout design for the new app?", "Yes, of course. We will be having a dedicated design engineer for design the layout once the requirement is finalized.", "Are we going to develop the app in native or hybrid?", "We should develop this App in Xamarin which provides native experience and performance.", "I haven’t heard of Xamarin Can someone share details about Xamarin?", "Xamarin.Forms is a new library that enables you to build native UIs for iOS, Android and Windows Phone from a single, shared C# codebase.", "That’s great! I will take a look into it.", "Yes, you can. It saves a lot of development time to what I have heard. We may have to dig in deeper for knowing more.", "Does this app going to be supported in wearable technology too?", "No. We are going to develop the mobile version first. Support for wearable watch can be considered in the next version.", "Are we going to recruit a new team? Otherwise, will be migrate our existing engineers from the current product.", "Since our current product is going to complete by the end of next month, we can move the required resources from the current product to this app development. I will share the complete requirement by end of next week.", "Ayah! That’s great.", "Cool. Cheers" }; #endregion } #region Field public enum TemplateType { IncomingText, OutGoingText, } #endregion }<file_sep>/Android/SampleBrowser/Samples/DocIO/PieChart.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Syncfusion.DocIO.DLS; using Syncfusion.DocIO; using Syncfusion.Drawing; using Syncfusion.OfficeChart; using System.Xml; using System.Globalization; namespace SampleBrowser { public partial class PieChart : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to create a pie chart in a Word document."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } private void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); //A new document is created. WordDocument document = new WordDocument(); //Add new section to the Word document IWSection section = document.AddSection(); //Set page margins of the section section.PageSetup.Margins.All = 72; //Add new paragraph to the section IWParagraph paragraph = section.AddParagraph(); //Apply heading style to the title paragraph paragraph.ApplyStyle(BuiltinStyle.Heading1); //Apply center alignment to the paragraph paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; //Append text to the paragraph paragraph.AppendText("Northwind Management Report").CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(46, 116, 181); //Add new paragraph paragraph = section.AddParagraph(); //Get chart data from xml file List<ProductDetail> Products = LoadXMLData(); //Create and Append chart to the paragraph WChart pieChart = document.LastParagraph.AppendChart(446, 270); //Set chart data pieChart.ChartType = OfficeChartType.Pie; pieChart.ChartTitle = "Best Selling Products"; pieChart.ChartTitleArea.FontName = "Calibri (Body)"; pieChart.ChartTitleArea.Size = 14; for (int i = 0; i < Products.Count; i++) { ProductDetail product = Products[i]; pieChart.ChartData.SetValue(i + 2, 1, product.ProductName); pieChart.ChartData.SetValue(i + 2, 2, product.Sum); } //Create a new chart series with the name “Sales” IOfficeChartSerie pieSeries = pieChart.Series.Add("Sales"); pieSeries.Values = pieChart.ChartData[2, 2, 11, 2]; //Setting data label pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true; pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside; //Setting background color pieChart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); pieChart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); pieChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; pieChart.PrimaryCategoryAxis.CategoryLabels = pieChart.ChartData[2, 1, 11, 1]; MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("PieChart.docx", "application/msword", stream, m_context); } } private List<ProductDetail> LoadXMLData () { List<ProductDetail> Products = new List<ProductDetail> (); ProductDetail productDetails; Assembly assembly = Assembly.GetExecutingAssembly (); Stream productXMLStream = assembly.GetManifestResourceStream ("SampleBrowser.Samples.DocIO.Templates.Products.xml"); XmlReader reader = XmlReader.Create (productXMLStream); string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; while (reader.Read ()) { if (reader.IsStartElement ()) { switch (reader.Name) { case "Products": while (reader.Read ()) { if (reader.IsStartElement ()) { switch (reader.Name) { case "SNO": reader.Read (); serailNo = reader.Value; break; case "ProductName": reader.Read (); productName = reader.Value; break; case "Sum": reader.Read (); sum = reader.Value; productDetails = new ProductDetail (int.Parse (serailNo), productName, decimal.Parse (sum, CultureInfo.InvariantCulture)); Products.Add (productDetails); break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Products") break; } break; } } } return Products; } } public class ProductDetail { #region fields private int m_serialNo; private string m_productName; private decimal m_sum; #endregion #region properties public int SNO { get { return m_serialNo; } set { m_serialNo = value; } } public string ProductName { get { return m_productName; } set { m_productName = value; } } public decimal Sum { get { return m_sum; } set { m_sum = value; } } #endregion #region Constructor public ProductDetail(int serialNumber, string productName, decimal sum) { SNO = serialNumber; ProductName = productName; Sum = Math.Round(sum, 3); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Presentation/Tables.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Xml; namespace SampleBrowser { public partial class TablesPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to create a table with specified number of rows and columns in PowerPoint presentation for displaying tabular data."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Presentation"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { //Stream to save the created PowerPoint presnetation MemoryStream stream = new MemoryStream(); //Creates a new instance of the presentation. using (IPresentation presentation = Syncfusion.Presentation.Presentation.Create()) { #region Slide1 //To add a slide to PowerPoint presentation ISlide slide = presentation.Slides.Add(SlideLayoutType.TitleOnly); //To set the table title in a slide SetTableTitle(slide); //To get the table data from an XML file Dictionary<string, Dictionary<string, string>> products = LoadXMLData(); int columnCount = products.Keys.Count + 1; int rowCount = products[products.Keys.ToArray()[0]].Count + 1; //To add a new table in slide. ITable table = slide.Shapes.AddTable(rowCount, columnCount, 61.92, 95.76, 856.8, 378.72); //To set the style for the table. table.BuiltInStyle = BuiltInTableStyle.MediumStyle2Accent6; //To set category title SetCategoryTitle(table); //Iterates and sets the values to the table cells. for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++) { IRow row = table.Rows[rowIndex]; Dictionary<string, string> months = products[products.Keys.ToArray()[0]]; string[] monthName = months.Keys.ToArray(); for (int cellIndex = 0; cellIndex < row.Cells.Count - 1; cellIndex++) { months = products[products.Keys.ToArray()[cellIndex]]; AddHeaderRowAndColumn(row, cellIndex, products.Keys.ToArray(), rowIndex, monthName); AddCellContent(row, rowIndex, monthName, months, cellIndex); } } #endregion //Save the presentation instance to the memory stream. presentation.Save(stream); } stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("Tables.pptx", "application/powerpoint", stream, m_context); } } #region HelperMethods /// <summary> /// Loads the xml content to fill the table cells in the presentation. /// </summary> /// <returns></returns> private Dictionary<string, Dictionary<string, string>> LoadXMLData() { Dictionary<string, Dictionary<string, string>> Products = new Dictionary<string, Dictionary<string, string>>(); Assembly assembly = Assembly.GetExecutingAssembly(); Stream productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.Presentation.Templates.TableData.xml"); XmlReader reader = XmlReader.Create(productXMLStream); string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; string month; while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Products": Dictionary<string, string> Month_Value = new Dictionary<string, string>(); while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Product": while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Month": while (reader.Read()) { month = reader.Name; if (reader.IsStartElement()) { month = reader.Name; while (reader.Read()) { if (reader.IsStartElement()) { if (reader.Name == "Value") { reader.Read(); reader.MoveToContent(); Month_Value.Add(month, reader.Value); } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == month) { break; } } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Month") { break; } } break; case "ProductName": reader.Read(); reader.MoveToContent(); productName = reader.Value; break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Product") { break; } } break; } Products.Add(productName, Month_Value); Month_Value = new Dictionary<string, string>(); } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Products") break; } break; } } } return Products; } /// <summary> /// Sets the table title. /// </summary> /// <param name="slide">Represents the slide instance of the presentation.</param> private void SetTableTitle(ISlide slide) { IShape shape = slide.Shapes[0] as IShape; shape.Left = 84.24; shape.Top = 0; shape.Width = 792; shape.Height = 126.72; ITextBody textFrame = shape.TextBody; IParagraphs paragraphs = textFrame.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; //Instance to hold textparts in paragraph. ITextParts textParts = paragraph.TextParts; textParts.Add(); ITextPart textPart = textParts[0]; textPart.Text = "Target "; IFont font = textPart.Font; font.FontName = "Arial"; font.FontSize = 28; font.Bold = true; font.CapsType = TextCapsType.All; textParts.Add(); //Creates a textpart and assigns value to it. textPart = textParts[1]; textPart.Text = "Vs "; font = textPart.Font; font.FontName = "Arial"; font.FontSize = 18; textParts.Add(); //Creates a textpart and assigns value to it. textPart = textParts[2]; textPart.Text = "PERFORMANCE"; font = textPart.Font; font.FontName = "Arial"; font.FontSize = 28; font.Bold = true; } /// <summary> /// Adds the cell content to the table. /// </summary> /// <param name="row">Represents the instance of row.</param> /// <param name="rowIndex">Represents the row index.</param> /// <param name="monthName">Represnets the array of month name.</param> /// <param name="months">Represnets the dictionary of months and its values.</param> /// <param name="cellIndex">Represents the cell index.</param> private void AddCellContent(IRow row, int rowIndex, string[] monthName, Dictionary<string, string> months, int cellIndex) { if (rowIndex == 0) return; ICell cell = row.Cells[cellIndex + 1]; //Instance to hold paragraphs in cell. IParagraphs paragraphs = cell.TextBody.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Left; ITextParts textParts = paragraph.TextParts; textParts.Add(); //Creates a textpart and assigns value to it. ITextPart textPart = textParts[0]; textPart.Text = months[monthName[rowIndex - 1]]; IFont font = textPart.Font; font.FontName = "Arial"; font.FontSize = 14; } /// <summary> /// Adds the content for the row and column for the table. /// </summary> /// <param name="row">Represents the particular row.</param> /// <param name="cellIndex">Represents the index of the cell.</param> /// <param name="cellContent">Represents the cell content.</param> /// <param name="rowIndex">Represents the index of the row.</param> /// <param name="monthName">Represents the content of monthname for the table.</param> private void AddHeaderRowAndColumn(IRow row, int cellIndex, string[] cellContent, int rowIndex, string[] monthName) { //To set text alignment type inside cell ICell cell = null; if (rowIndex == 0) cell = row.Cells[cellIndex + 1]; else cell = row.Cells[0]; cell.TextBody.VerticalAlignment = VerticalAlignmentType.Middle; //To add a paragraph inside cell IParagraphs paragraphs = cell.TextBody.Paragraphs; if (paragraphs.Count == 0) paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; ITextParts textParts = paragraph.TextParts; if (textParts.Count == 0) textParts.Add(); //Creates a textpart and assigns value to it. ITextPart textPart = textParts[0]; if (rowIndex == 0) textPart.Text = cellContent[cellIndex]; else textPart.Text = monthName[rowIndex - 1]; IFont font = textPart.Font; font.FontName = "Arial"; font.FontSize = 14; font.Bold = true; } /// <summary> /// Sets the title for the category in the table. /// </summary> /// <param name="table">Instance to access the table from the presentation.</param> void SetCategoryTitle(ITable table) { //Instance to hold rows in the table table.Rows[0].Height = 81.44; //To set text alignment type inside cell //ICell cell11 = ; table.Rows[0].Cells[0].TextBody.VerticalAlignment = VerticalAlignmentType.Middle; //To add a paragraph inside cell IParagraphs paragraphs = table.Rows[0].Cells[0].TextBody.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; ITextParts textParts = paragraph.TextParts; textParts.Add(); //Creates a textpart and assigns value to it. ITextPart textPart = textParts[0]; textPart.Text = "Month"; IFont font = textPart.Font; font.FontName = "Arial"; font.FontSize = 14; font.Bold = true; } #endregion HelperMethods } } <file_sep>/Android/SampleBrowser/Samples/PDF/Stamping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf; using System.IO; using System.Reflection; using Syncfusion.Drawing; namespace SampleBrowser { public partial class Stamping : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to stamp or watermark an existing PDF document."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate PDF"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { Stream docStream = typeof(Stamping).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Product Catalog.pdf"); PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular); foreach (PdfPageBase lPage in ldoc.Pages) { PdfGraphics g = lPage.Graphics; PdfGraphicsState state = g.Save(); g.TranslateTransform(ldoc.Pages[0].Size.Width / 2, ldoc.Pages[0].Size.Height / 2); g.SetTransparency(0.25f); SizeF waterMarkSize = font.MeasureString("Sample"); g.RotateTransform(-40); g.DrawString("Sample", font, PdfPens.Red, PdfBrushes.Red, new PointF(-waterMarkSize.Width / 2, -waterMarkSize.Height / 2)); g.Restore(state); } MemoryStream stream = new MemoryStream(); ldoc.Save(stream); ldoc.Close(true); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("Stamping.pdf", "application/pdf", stream, m_context); } } } }<file_sep>/iOS/SampleBrowser/Samples/Diagram/FlowDiagram.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Syncfusion.SfDiagram.iOS; using UIKit; namespace SampleBrowser { public partial class FlowDiagram : SampleView { SfDiagram diagram; UIPickerView selectionPicker1; UILabel gridColor; UIScrollView colorView = new UIScrollView(); UILabel enablegrid; UISwitch gridswitch; UILabel snapgrid; UISwitch snapgridswitch; UILabel sizeindicator; UIImageView plusimg; UIImageView minusimg; UILabel gridSize; UIButton minus; UIButton plus; UIButton currentButton; int width = 12; public FlowDiagram() { diagram = new SfDiagram(); selectionPicker1 = new UIPickerView(); this.OptionView = new UIView(); Node n1 = DrawNode(100, 30, 160, 55, ShapeType.RoundedRectangle, "New idea identified", 30, UIColor.FromRGB(49, 162, 255), UIColor.FromRGB(23, 132, 206)); diagram.AddNode(n1); Node n2 = DrawNode(100, 130, 160, 55, ShapeType.RoundedRectangle, "Meeting With Board", 4, UIColor.FromRGB(49, 162, 255), UIColor.FromRGB(23, 132, 206)); diagram.AddNode(n2); Node n3 = DrawNode(105, 230, 150, 150, ShapeType.Diamond, "Board decides \n whether to \n proceed ", 0, UIColor.FromRGB(0, 194, 192), UIColor.FromRGB(4, 142, 135)); diagram.AddNode(n3); Node n4 = DrawNode(105, 425, 150, 150, ShapeType.Diamond, "Find Project \n Manager, write \n specification", 0, UIColor.FromRGB(0, 194, 192), UIColor.FromRGB(4, 142, 135)); diagram.AddNode(n4); Node n5 = DrawNode(90, 620, 180, 60, ShapeType.RoundedRectangle, "Implement and deliver", 30, UIColor.FromRGB(49, 162, 255), UIColor.FromRGB(23, 132, 206)); diagram.AddNode(n5); Node n6 = DrawNode(320, 275, 200, 60, ShapeType.RoundedRectangle, "Reject and report the reason", 4, UIColor.FromRGB(239, 75, 93), UIColor.FromRGB(201, 32, 61)); diagram.AddNode(n6); Node n7 = DrawNode(320, 470, 200, 60, ShapeType.RoundedRectangle, "Hire new resources", 4, UIColor.FromRGB(239, 75, 93), UIColor.FromRGB(201, 32, 61)); diagram.AddNode(n7); //Create Connector Connector c1 = new Connector(n1, n2); diagram.AddConnector(c1); Connector c2 = new Connector(n2, n3); diagram.AddConnector(c2); Connector c3 = new Connector(n3, n4); c3.Annotations.Add(new Annotation() { Content = CreateConnectorLabel("Yes", -25, 10, 25, 20) }); diagram.AddConnector(c3); Connector c4 = new Connector(n4, n5); c4.Annotations.Add(new Annotation() { Content = CreateConnectorLabel("Yes", -25, 10, 25, 20) }); diagram.AddConnector(c4); Connector c5 = new Connector(n3, n6); c5.Annotations.Add(new Annotation() { Content = CreateConnectorLabel("No", 15, 15, 25, 20) }); diagram.AddConnector(c5); Connector c6 = new Connector(n4, n7); c6.Annotations.Add(new Annotation() { Content = CreateConnectorLabel("No", 15, 15, 25, 20) }); diagram.AddConnector(c6); for (int i = 0; i < diagram.Connectors.Count; i++) { diagram.Connectors[i].Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(127, 132, 133)); diagram.Connectors[i].TargetDecoratorStyle.Fill = (UIColor.FromRGB(127, 132, 133)); diagram.Connectors[i].TargetDecoratorStyle.StrokeColor = (UIColor.FromRGB(127, 132, 133)); diagram.Connectors[i].TargetDecoratorStyle.StrokeWidth = 1; diagram.Connectors[i].Style.StrokeWidth = 1; } diagram.EnableTextEditing = false; diagram.PageSettings.GridSize = 12; diagram.PageSettings.GridColor = UIColor.FromRGB(230, 230, 230); this.AddSubview(diagram); gridColor = new UILabel(); gridColor.Text = "Grid Color"; gridColor.TextColor = UIColor.Black; gridColor.TextAlignment = UITextAlignment.Left; gridColor.BackgroundColor = UIColor.Clear; colorView.BackgroundColor = UIColor.Clear; colorView.ScrollEnabled = true; colorView.ShowsHorizontalScrollIndicator = true; colorView.ShowsVerticalScrollIndicator = false; int x = 50; colorView.AddSubview(AddColorButton(10, UIColor.Red)); colorView.AddSubview(AddColorButton((x * 1), UIColor.Orange)); colorView.AddSubview(AddColorButton((x * 2), UIColor.FromRGB(0, 128, 0))); colorView.AddSubview(AddColorButton((x * 3), UIColor.Blue)); colorView.AddSubview(AddColorButton((x * 4), UIColor.Purple)); colorView.AddSubview(AddColorButton((x * 5), UIColor.FromRGB(51, 255, 255))); colorView.AddSubview(AddColorButton((x * 6), UIColor.FromRGB(255, 0, 255))); colorView.AddSubview(AddColorButton((x * 7), UIColor.Gray)); colorView.AddSubview(AddColorButton((x * 8), UIColor.FromRGB(0, 255, 0))); colorView.AddSubview(AddColorButton((x * 9), UIColor.FromRGB(128, 0, 0))); colorView.AddSubview(AddColorButton((x * 10), UIColor.FromRGB(0, 0, 128))); colorView.AddSubview(AddColorButton((x * 11), UIColor.FromRGB(128, 128, 0))); colorView.AddSubview(AddColorButton((x * 12), UIColor.FromRGB(192, 192, 192))); colorView.AddSubview(AddColorButton((x * 13), UIColor.FromRGB(0, 128, 128))); colorView.ContentSize = new CGSize(850, colorView.ContentSize.Height); enablegrid = new UILabel(); enablegrid.Text = "Show Grid"; enablegrid.TextColor = UIColor.Black; enablegrid.TextAlignment = UITextAlignment.Left; enablegrid.BackgroundColor = UIColor.Clear; enablegrid = new UILabel(); enablegrid.Text = "Show Grid"; enablegrid.TextColor = UIColor.Black; enablegrid.TextAlignment = UITextAlignment.Left; enablegrid.BackgroundColor = UIColor.Clear; gridswitch = new UISwitch(); gridswitch.TouchUpInside += Gridswitch_TouchUpInside; gridswitch.BackgroundColor = UIColor.Clear; snapgrid = new UILabel(); snapgrid.Text = "Snap To Grid"; snapgrid.TextColor = UIColor.Black; snapgrid.TextAlignment = UITextAlignment.Left; snapgrid.BackgroundColor = UIColor.Clear; snapgridswitch = new UISwitch(); snapgridswitch.TouchUpInside += Snapgridswitch_TouchUpInside; snapgridswitch.BackgroundColor = UIColor.Clear; snapgridswitch.Enabled = false; gridSize = new UILabel(); gridSize.Text = "Size"; gridSize.TextColor = UIColor.Black; gridSize.TextAlignment = UITextAlignment.Left; plus = new UIButton(); plus.BackgroundColor = UIColor.White; plus.Layer.CornerRadius = 8; plus.Layer.BorderWidth = 0.5f; plus.TouchUpInside += Plus_TouchUpInside; plusimg = new UIImageView(); plusimg.Image = UIImage.FromBundle("Images/Diagram/CSplus.png"); plus.AddSubview(plusimg); minus = new UIButton(); minus.BackgroundColor = UIColor.White; minus.Layer.CornerRadius = 8; minus.Layer.BorderWidth = 0.5f; minus.TouchUpInside += Minus_TouchUpInside; minusimg = new UIImageView(); minusimg.Image = UIImage.FromBundle("Images/Diagram/CSsub.png"); minus.AddSubview(minusimg); sizeindicator = new UILabel(); sizeindicator.Text = width.ToString(); sizeindicator.BackgroundColor = UIColor.Clear; sizeindicator.TextColor = UIColor.Black; sizeindicator.TextAlignment = UITextAlignment.Center; optionView(); gridColor.Frame = new CGRect(this.Frame.X + 10, 20, 100, 30); colorView.Frame = new CGRect(this.Frame.X + 10, 60, 300, 45); colorView.ContentSize = new CGSize(850, colorView.ContentSize.Height); enablegrid.Frame = new CGRect(this.Frame.X + 10, 120, 100, 30); gridswitch.Frame = new CGRect(this.Frame.X + 250, 120, 40, 30); snapgrid.Frame = new CGRect(this.Frame.X + 10, 170, 100, 30); snapgridswitch.Frame = new CGRect(this.Frame.X + 250, 170, 40, 30); gridSize.Frame = new CGRect(this.Frame.X + 10, 220, PopoverSize.Width - 20, 30); plus.Frame = new CGRect(this.Frame.X + 160, 270, 30, 30); plusimg.Frame = new CGRect(0, 0, 30, 30); minus.Frame = new CGRect(this.Frame.X + 60, 270, 30, 30); minusimg.Frame = new CGRect(0, 0, 30, 30); sizeindicator.Frame = new CGRect(this.Frame.X + 110, 270, 30, 30); diagram.ConnectorClicked += Diagram_ConnectorClicked; diagram.ContextMenuSettings.Visibility = false; } public override void LayoutSubviews() { base.LayoutSubviews(); diagram.LayoutSubviews(); //diagram.EnableSelectors = false; UpdateSelectors(); //Create Node } void Diagram_ConnectorClicked(object sender, ConnectorClickedEventArgs args) { diagram.ClearSelection(); } private UIButton AddColorButton(int v, UIColor color) { UIButton button = new UIButton(); button.BackgroundColor = color; button.Frame = new CGRect(v, 5, 30, 30); button.Layer.CornerRadius = 15; button.Layer.BorderColor = UIColor.White.CGColor; button.Layer.BorderWidth = 1.5f; button.TouchUpInside+= Button_TouchUpInside; return button; } private void UpdateSelectors() { diagram.ShowSelectorHandle(false, SelectorPosition.SourcePoint); diagram.ShowSelectorHandle(false, SelectorPosition.TargetPoint); diagram.ShowSelectorHandle(false, SelectorPosition.Rotator); diagram.ShowSelectorHandle(false, SelectorPosition.TopLeft); diagram.ShowSelectorHandle(false, SelectorPosition.TopRight); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleLeft); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleRight); diagram.ShowSelectorHandle(false, SelectorPosition.BottomCenter); diagram.ShowSelectorHandle(false, SelectorPosition.BottomLeft); diagram.ShowSelectorHandle(false, SelectorPosition.BottomRight); diagram.ShowSelectorHandle(false, SelectorPosition.TopCenter); } private void optionView() { this.OptionView.AddSubview(gridColor); this.OptionView.AddSubview(colorView); this.OptionView.AddSubview(enablegrid); this.OptionView.AddSubview(gridswitch); this.OptionView.AddSubview(snapgrid); this.OptionView.AddSubview(snapgridswitch); this.OptionView.AddSubview(gridSize); this.OptionView.AddSubview(plus); this.OptionView.AddSubview(minus); this.OptionView.AddSubview(sizeindicator); } void Plus_TouchUpInside(object sender, EventArgs e) { if (diagram.PageSettings.ShowGrid) { if (width < 20) { width++; diagram.PageSettings.GridSize = width; sizeindicator.Text = diagram.PageSettings.GridSize.ToString(); } } } void Minus_TouchUpInside(object sender, EventArgs e) { if (diagram.PageSettings.ShowGrid) { if (width > 5) { width--; diagram.PageSettings.GridSize = width; sizeindicator.Text = diagram.PageSettings.GridSize.ToString(); } } } void Gridswitch_TouchUpInside(object sender, EventArgs e) { if((sender as UISwitch).On) { diagram.PageSettings.ShowGrid = true; snapgridswitch.Enabled = true; } else { diagram.PageSettings.ShowGrid = false; if (snapgridswitch.On) snapgridswitch.Enabled = false; } } void Snapgridswitch_TouchUpInside(object sender, EventArgs e) { if (gridswitch.On) { if ((sender as UISwitch).On) { diagram.PageSettings.SnapToGrid = true; } else { diagram.PageSettings.SnapToGrid = false; } } } //Creates the Node with Specified input private Node DrawNode(float x, float y, float w, float h, ShapeType shape, string annotation, float CornerRadius, UIColor fill, UIColor stroke) { var node = new Node(); node.OffsetX = x; node.OffsetY = y; node.Width = w; node.Height = h; node.ShapeType = shape; node.CornerRadius = CornerRadius; node.Annotations.Add(new Annotation() { Content = CreateNodeLabel(annotation, node.Width, node.Height), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }); node.Style.Brush = new SolidBrush(fill); node.Style.StrokeBrush = new SolidBrush(stroke); node.Style.StrokeWidth = 1; return node; } //Create Node's Annotation UILabel CreateNodeLabel(string text, nfloat width, nfloat height) { var label = new UILabel() { Text = text, TextAlignment = UITextAlignment.Center, TextColor = UIColor.FromRGB(255, 255, 255), Font = UIFont.FromName(".SF UI Text", 14), LineBreakMode = UILineBreakMode.WordWrap, Lines = 0 }; label.Layer.ShouldRasterize = true; label.Layer.RasterizationScale = UIScreen.MainScreen.Scale; label.Frame = new CGRect(0, 0, width, label.Text.StringSize(label.Font).Height * 3); return label; } //Create Connector's Annotationn UILabel CreateConnectorLabel(string text, int x, int y, int w, int h) { var label = new UILabel() { Text = text, TextColor = UIColor.FromRGB(127, 132, 133), Font = UIFont.FromName("Arial", 14), Frame = new CGRect(x, y, w, h) }; label.Layer.RasterizationScale = UIScreen.MainScreen.Scale; label.Layer.ShouldRasterize = true; return label; } void Button_TouchUpInside(object sender, EventArgs e) { if(diagram.PageSettings.ShowGrid) { if (currentButton != null) { currentButton.Layer.BorderColor = UIColor.White.CGColor; (sender as UIButton).Layer.BorderWidth = 1.5f; } currentButton = sender as UIButton; diagram.PageSettings.GridColor = (sender as UIButton).BackgroundColor; (sender as UIButton).Layer.BorderColor = UIColor.FromRGB(30, 144, 255).CGColor; (sender as UIButton).Layer.BorderWidth = 2.5f; } } } }<file_sep>/Forms/RadialMenu/readme.md The `SfRadialMenu` displays a hierarchical menu in a circular layout, which is optimized for touch enabled devices. Typically, it is used as a context menu, and it can expose more menu items in the same space than traditional menus. The following samples are available for radial menu to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](RadialMenu/Samples/GettingStarted_RadialMenu)| It demonstrates the arrangement of sub menu items and its event like `Opened`,`Opening`,`Closed` and `Closing`.| |[Customization](RadialMenu/Samples/Customization_RadialMenu)| It shows the way of customizing radial menu items with icon fonts. The color of `SfRotator` items are changed to exhibit the Tapped event in radial menu items.| |[Segmentation](RadialMenu/Samples/SlotIndex_RadialMenu)| It demonstrates the segment arrangement support, in which items are arranged based on segment index rather than the created order.| <file_sep>/Forms/Schedule/Schedule/Samples/ViewCustomization/Behaviors/MonthCellCustomViewBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Month Cell Custom View Behavior class /// </summary> public class MonthCellCustomViewBehavior : Behavior<StackLayout> { /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(StackLayout bindable) { base.OnAttachedTo(bindable); var button = bindable.FindByName<Image>("Image"); var label = bindable.FindByName<Label>("label"); if (CustomizationViewModel.MonthCellItem != null) { if (CustomizationViewModel.MonthCellItem.IsLeadingDay || CustomizationViewModel.MonthCellItem.IsTrailingDay) { label.TextColor = Color.Gray; } else { label.TextColor = Color.Black; } } if (CustomizationViewModel.ScheduleAppointment != null) { if (CustomizationViewModel.ScheduleAppointment.Subject == "Conference") { button.Source = "Conference_schedule.png"; } else if (CustomizationViewModel.ScheduleAppointment.Subject == "System Troubleshoot") { button.Source = "Troubleshoot.png"; } else if (CustomizationViewModel.ScheduleAppointment.Subject == "Checkup") { button.Source = "Stethoscope.png"; } else if (CustomizationViewModel.ScheduleAppointment.Subject == "Jeni's Birthday") { button.Source = "cake_schedule.png"; } } } /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(StackLayout bindable) { base.OnDetachingFrom(bindable); } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/StepArea.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; #endif namespace SampleBrowser { public class StepArea : SampleView { public StepArea () { SFChart chart = new SFChart (); chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.Title.Text = new NSString ("Electricity Production"); SFNumericalAxis primaryAxis = new SFNumericalAxis (); primaryAxis.Title.Text = new NSString ("Year"); primaryAxis.Interval = new NSNumber (2); primaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; primaryAxis.ShowMajorGridLines = false; primaryAxis.MajorTickStyle.LineSize = 8; chart.PrimaryAxis = primaryAxis; SFNumericalAxis secondaryAxis = new SFNumericalAxis (); secondaryAxis.Title.Text = new NSString ("Production (Billion as kWh)"); secondaryAxis.Minimum = new NSNumber(0); secondaryAxis.Maximum = new NSNumber(600); secondaryAxis.Interval = new NSNumber(100); secondaryAxis.AxisLineStyle.LineWidth = 0; secondaryAxis.MajorTickStyle.LineWidth = 0; NSNumberFormatter formatter = new NSNumberFormatter(); formatter.PositiveSuffix = "B"; secondaryAxis.LabelStyle.LabelFormatter = formatter; chart.SecondaryAxis = secondaryAxis; ChartViewModel dataModel = new ChartViewModel (); SFStepAreaSeries series1 = new SFStepAreaSeries(); series1.ItemsSource = dataModel.StepAreaData1; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.EnableTooltip = true; series1.Label = "Renewable"; series1.EnableAnimation = true; series1.LegendIcon = SFChartLegendIcon.Rectangle; chart.Series.Add(series1); SFStepAreaSeries series2 = new SFStepAreaSeries(); series2.ItemsSource = dataModel.StepAreaData2; series2.XBindingPath = "XValue"; series2.YBindingPath = "YValue"; series2.EnableTooltip = true; series2.Label = "Non-Renewable"; series2.EnableAnimation = true; series2.LegendIcon = SFChartLegendIcon.Rectangle; chart.Series.Add(series2); chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } }<file_sep>/Android/SampleBrowser/Samples/AutoComplete/DiacriticSample/MusicInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Android.Graphics; namespace SampleBrowser { public class MusicInfo { public string SongTitle { get; set; } public string SongAuther { get; set; } public string SongSize { get; set; } public string SongLength { get; set; } public string SongThumbnail { get; set; } public Color SongTheme { get; set; } public Color CurrentColor { get; set; } } public class MusicInfoRepository { #region Constructor List<Color> Colors = new List<Color>(); public MusicInfoRepository() { Colors.Add(Color.LightGray); Colors.Add(Color.SkyBlue); Colors.Add(Color.Green); Colors.Add(Color.RosyBrown); Colors.Add(Color.Lime); Colors.Add(Color.Pink); Colors.Add(Color.Gold); Colors.Add(Color.BlueViolet); Colors.Add(Color.LawnGreen); Colors.Add(Color.Violet); Colors.Add(Color.Tomato); Colors.Add(Color.Orange); Colors.Add(Color.MediumVioletRed); Colors.Add(Color.Plum); Colors.Add(Color.Purple); Colors.Add(Color.CornflowerBlue); Colors.Add(Color.RosyBrown); Colors.Add(Color.RoyalBlue); Colors.Add(Color.OrangeRed); Colors.Add(Color.Orchid); Colors.Add(Color.ForestGreen); Colors.Add(Color.Gray); Colors.Add(Color.Red); Colors.Add(Color.Brown); Colors.Add(Color.Purple); Colors.Add(Color.CornflowerBlue); Colors.Add(Color.GreenYellow); Colors.Add(Color.RoyalBlue); Colors.Add(Color.OrangeRed); Colors.Add(Color.Orchid); Colors.Add(Color.ForestGreen); Colors.Add(Color.Gray); Colors.Add(Color.DeepPink); Colors.Add(Color.Brown); } #endregion #region Properties internal ObservableCollection<MusicInfo> GetMusicInfo() { var random = new Random(); var musiqInfo = new ObservableCollection<MusicInfo>(); for (int i = 0; i < SongsNames.Count(); i++) { var info = new MusicInfo() { SongTitle = SongsNames[i], SongAuther = SongAuthers[i], SongSize = random.Next(50, 600).ToString() + "." + random.Next(1, 10) / 2 + "KB", SongLength = "5.55", SongTheme = Colors[i], SongThumbnail = (i % 2 == 0) ? "I" : "T", }; musiqInfo.Add(info); } return musiqInfo; } #endregion #region SongInfo string[] SongsNames = new string[] { "Whât is thé wéâthér tódây?", "Hów tó bóók my flight?", "Whéré is my lócâtión?", "Is bânk ópén tódây?", "Why sky is blué?", "Gét mé sóméthing", "List óf hólidâys", "Diréct mé tó hómé", "Hów tó gâin wéight?", "Hów tó drâw ân éléphânt?", "Whéré cân I buy â câmérâ?", "Guidé mé âll thé wây", "Hów tó mâké â câké?", "Sây, Hélló Wórld!", "Hów tó mâké â róbót?", "Cónnéct Móbilé tó TV?", "Whât timé nów in Indiâ?", "Whó is whó in thé wórld?", "Hów tó drâw â rósé?", "Hów cân I léârn Tâmil?", "Hów cân I léârn Jâpânésé?", "Hów tó réâch néârést âirpórt?", }; string[] SongAuthers = new string[] { "Coldplay", "<NAME>", "<NAME> & <NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "Righteous Brothers", "Shakira", "<NAME>", "<NAME> ft. <NAME>", "<NAME>", "Enigma", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "The Beach Boys", "The Brothers Four", "<NAME>", "<NAME>", "<NAME>", "Green Day", "Beck", "<NAME>", }; #endregion } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/LiveUpdate.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using System; using System.Threading.Tasks; using System.Collections.ObjectModel; namespace SampleBrowser { public class LiveUpdate : SamplePage { private readonly ObservableCollection<DataPoint> data = new ObservableCollection<DataPoint>(); private readonly ObservableCollection<DataPoint> data2 = new ObservableCollection<DataPoint>(); private int wave1; private int wave2 = 180; private SfChart chart; public override View GetSampleContent(Context context) { LoadData(); chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.PrimaryAxis = new NumericalAxis() { ShowMajorGridLines = false }; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; var axis = new NumericalAxis {Minimum = -1.5, Maximum = 1.5, ShowMajorGridLines= false}; chart.SecondaryAxis = axis; axis.LabelStyle.LabelsPosition = AxisElementPosition.Outside; axis.TickPosition = AxisElementPosition.Outside; var lineSeries = new FastLineSeries {ItemsSource = data, XBindingPath = "XValue", YBindingPath = "YValue" }; var fastLine = new FastLineSeries(); fastLine.ItemsSource = data2; fastLine.XBindingPath = "XValue"; fastLine.YBindingPath = "YValue"; chart.Series.Add(fastLine); chart.Series.Add(lineSeries); UpdateData(); return chart; } private void LoadData() { for (var i = 0; i < 180; i++) { data.Add(new DataPoint(i, Math.Sin(wave1*(Math.PI/180.0)))); wave1++; } for (var i = 0; i < 180; i++) { data2.Add(new DataPoint(i, Math.Sin(wave2 * (Math.PI / 180.0)))); wave2++; } wave1 = data.Count; } private async void UpdateData() { while (true) { await Task.Delay(10); data.RemoveAt(0); data.Add(new DataPoint(wave1, Math.Sin(wave1*(Math.PI/180.0)))); wave1++; data2.RemoveAt(0); data2.Add(new DataPoint(wave1, Math.Sin(wave2 * (Math.PI / 180.0)))); wave2++; } } } }<file_sep>/iOS/SampleBrowser/Samples/RangeSlider/Orientation.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfRangeSlider.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Orientation : SampleView { SfRangeSlider rangeSlider1, rangeSlider2, rangeSlider3; UILabel hertzLabel1,hertzLabel2,hertzLabel3,decibelLabel1,decibelLabel2,decibelLabel3; public Orientation () { //RangeSlider 1 rangeSlider1 = new SfRangeSlider(); rangeSlider1.Maximum=12; rangeSlider1.Minimum =-12; rangeSlider1.RangeStart =-12; rangeSlider1.RangeEnd =(nfloat)2.2; rangeSlider1.Value = (nfloat)2.2; rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementNone; rangeSlider1.TickFrequency =12; rangeSlider1.Orientation = SFOrientation.SFOrientationVertical; rangeSlider1.ValuePlacement = SFValuePlacement.SFValuePlacementTopLeft; rangeSlider1.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeSlider1.KnobColor = UIColor.White; rangeSlider1.TrackSelectionColor = UIColor.FromRGB (182, 182, 182); rangeSlider1.TrackColor = UIColor.FromRGB (182, 182, 182); rangeSlider1.ShowRange = false; //RangeSlider 2 rangeSlider2 = new SfRangeSlider(); rangeSlider2.Maximum=12; rangeSlider2.Minimum =-12; rangeSlider2.RangeStart =-12; rangeSlider2.RangeEnd =(nfloat)(-4.7); rangeSlider2.Value = (nfloat)(-4.7); rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementNone; rangeSlider2.TickFrequency = 12; rangeSlider2.Orientation = SFOrientation.SFOrientationVertical; rangeSlider2.ValuePlacement = SFValuePlacement.SFValuePlacementTopLeft; rangeSlider2.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeSlider2.KnobColor = UIColor.White; rangeSlider2.ShowRange = false; rangeSlider2.TrackSelectionColor = UIColor.FromRGB (182, 182, 182); rangeSlider2.TrackColor = UIColor.FromRGB (182, 182, 182); //RangeSlider 3 rangeSlider3 = new SfRangeSlider(); rangeSlider3.Maximum=12; rangeSlider3.Minimum =-12; rangeSlider3.RangeStart =-12; rangeSlider3.RangeEnd =(nfloat)6; rangeSlider3.Value = (nfloat)6; rangeSlider3.TickPlacement = SFTickPlacement.SFTickPlacementNone; rangeSlider3.TickFrequency = 12; rangeSlider3.Orientation = SFOrientation.SFOrientationVertical; rangeSlider3.ValuePlacement = SFValuePlacement.SFValuePlacementTopLeft; rangeSlider3.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeSlider3.KnobColor = UIColor.White; rangeSlider3.ShowRange = false; rangeSlider3.TrackSelectionColor = UIColor.FromRGB (182, 182, 182); rangeSlider3.TrackColor = UIColor.FromRGB (182, 182, 182); rangeSlider1.ValueChange += Slider_ValueChange; rangeSlider2.ValueChange += Slider_ValueChange; rangeSlider3.ValueChange += Slider_ValueChange; this.AddSubview (rangeSlider3); this.AddSubview (rangeSlider1); this.AddSubview (rangeSlider2); mainPageDesign(); } void Slider_ValueChange(object sender, ValueEventArgs e) { SetValue(sender as SfRangeSlider, e.Value); } public void SetValue(SfRangeSlider r, nfloat value) { nfloat f = (nfloat)Math.Round(value, 1); if (r == rangeSlider1) decibelLabel1.Text = f.ToString() + "db"; else if (r == rangeSlider2) decibelLabel2.Text = f.ToString() + "db"; else decibelLabel3.Text = f.ToString() + "db"; } public void mainPageDesign() { //HertzLabel1 hertzLabel1 = new UILabel(); hertzLabel1.TextColor = UIColor.FromRGB(109, 109, 114); hertzLabel1.Text = "60Hz"; hertzLabel1.TextAlignment = UITextAlignment.Center; hertzLabel1.Font = UIFont.FromName("Helvetica", 20f); //HertzLabel21 hertzLabel2 = new UILabel(); hertzLabel2.TextColor = UIColor.FromRGB(109, 109, 114); hertzLabel2.Text = "170Hz"; hertzLabel2.TextAlignment = UITextAlignment.Center; hertzLabel2.Font = UIFont.FromName("Helvetica", 20f); //HertzLabel3 hertzLabel3 = new UILabel(); hertzLabel3.TextColor = UIColor.FromRGB(109, 109, 114); hertzLabel3.Text = "310Hz"; hertzLabel3.TextAlignment = UITextAlignment.Center; hertzLabel3.Font = UIFont.FromName("Helvetica", 20f); //Decibellabel1 decibelLabel1 = new UILabel(); decibelLabel1.TextColor = UIColor.FromRGB(57, 181, 247); decibelLabel1.Text = "2.2db"; decibelLabel1.TextAlignment = UITextAlignment.Center; decibelLabel1.Font = UIFont.FromName("Helvetica", 14f); //Decibellabel2 decibelLabel2 = new UILabel(); decibelLabel2.TextColor = UIColor.FromRGB(57, 181, 247); decibelLabel2.Text = "-4.7db"; decibelLabel2.TextAlignment = UITextAlignment.Center; decibelLabel2.Font = UIFont.FromName("Helvetica", 14f); //DecibelLabel3 decibelLabel3=new UILabel();; decibelLabel3.TextColor = UIColor.FromRGB(57, 181, 247); decibelLabel3.Text = "6.0db"; decibelLabel3.TextAlignment = UITextAlignment.Center; decibelLabel3.Font = UIFont.FromName("Helvetica", 14f); //Adding to view this.AddSubview(hertzLabel1); this.AddSubview(hertzLabel2); this.AddSubview(hertzLabel3); this.AddSubview(decibelLabel1); this.AddSubview(decibelLabel2); this.AddSubview(decibelLabel3); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { view.Frame = Frame; hertzLabel1.Frame = new CGRect(0, this.Frame.Size.Height / 7, this.Frame.Size.Width / 3, 30); hertzLabel2.Frame = new CGRect(this.Frame.Size.Width / 3, this.Frame.Size.Height / 7, this.Frame.Size.Width / 3, 30); hertzLabel3.Frame = new CGRect((this.Frame.Size.Width / 3) * 2, this.Frame.Size.Height / 7, this.Frame.Size.Width / 3, 30); decibelLabel1.Frame = new CGRect(0, this.Frame.Size.Height / 5, this.Frame.Size.Width / 3, 30); decibelLabel2.Frame = new CGRect(this.Frame.Size.Width / 3, this.Frame.Size.Height / 5, this.Frame.Size.Width / 3, 30); decibelLabel3.Frame = new CGRect((this.Frame.Size.Width / 3) * 2, this.Frame.Size.Height / 5, this.Frame.Size.Width / 3, 30); rangeSlider1.Frame = new CGRect(0, this.Frame.Size.Height / 4, this.Frame.Size.Width / 4, this.Frame.Size.Height - this.Frame.Size.Height / 4 - 50); rangeSlider2.Frame = new CGRect(this.Frame.Size.Width / 3, this.Frame.Size.Height / 4, this.Frame.Size.Width / 3, this.Frame.Size.Height - this.Frame.Size.Height / 4 - 50); rangeSlider3.Frame = new CGRect((this.Frame.Size.Width / 3) * 2, this.Frame.Size.Height / 4, this.Frame.Size.Width / 3, this.Frame.Size.Height - this.Frame.Size.Height / 4 - 50); } else { view.Frame = Bounds; hertzLabel1.Frame = new CGRect(40, this.Frame.Size.Height / 7 - 40, this.Frame.Size.Width / 3, 30); hertzLabel2.Frame = new CGRect(this.Frame.Size.Width / 3, this.Frame.Size.Height / 7 - 40, this.Frame.Size.Width / 3, 30); hertzLabel3.Frame = new CGRect((this.Frame.Size.Width / 3) * 2 - 20, this.Frame.Size.Height / 7 - 40, this.Frame.Size.Width / 3, 30); decibelLabel1.Frame = new CGRect(40, this.Frame.Size.Height / 5 - 40, this.Frame.Size.Width / 3, 30); decibelLabel2.Frame = new CGRect(this.Frame.Size.Width / 3, this.Frame.Size.Height / 5 - 40, this.Frame.Size.Width / 3, 30); decibelLabel3.Frame = new CGRect((this.Frame.Size.Width / 3) * 2 - 20, this.Frame.Size.Height / 5 - 40, this.Frame.Size.Width / 3, 30); rangeSlider1.Frame = new CGRect(70, this.Frame.Size.Height / 4 - 40, this.Frame.Size.Width / 4, this.Frame.Size.Height - this.Frame.Size.Height / 4 - 50); rangeSlider2.Frame = new CGRect(this.Frame.Size.Width / 3, this.Frame.Size.Height / 4 - 40, this.Frame.Size.Width / 3, this.Frame.Size.Height - this.Frame.Size.Height / 4 - 50); rangeSlider3.Frame = new CGRect((this.Frame.Size.Width / 3) * 2 - 20, this.Frame.Size.Height / 4 - 40, this.Frame.Size.Width / 3, this.Frame.Size.Height - this.Frame.Size.Height / 4 - 50); } } base.LayoutSubviews (); } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/Model/OrderInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "OrderInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains Properties and Notifies that a property value has changed /// </summary> public class OrderInfo : INotifyPropertyChanged { #region private variables /// <summary> /// backing field for OrderID. /// </summary> private string orderID; /// <summary> /// backing field for EmployeeID. /// </summary> private string employeeID; /// <summary> /// backing field for CustomerID. /// </summary> private string customerID; /// <summary> /// backing field for ShipCountry. /// </summary> private string shipCountry; #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the OrderID value. /// </summary> public string OrderID { get { return this.orderID; } set { this.orderID = value; this.RaisePropertyChanged("OrderID"); } } /// <summary> /// Gets or sets the EmployeeID value. /// </summary> public string EmployeeID { get { return this.employeeID; } set { this.employeeID = value; this.RaisePropertyChanged("EmployeeID"); } } /// <summary> /// Gets or sets the CustomerID value. /// </summary> public string CustomerID { get { return this.customerID; } set { this.customerID = value; this.RaisePropertyChanged("CustomerID"); } } /// <summary> /// Gets or sets the ShipCountry value. /// </summary> public string ShipCountry { get { return this.shipCountry; } set { this.shipCountry = value; this.RaisePropertyChanged("ShipCountry"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Forms/PdfViewer/PdfViewer.iOS/AlertViewDelegate.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Foundation; using UIKit; namespace SampleBrowser.SfPdfViewer.iOS { internal class AlertViewDelegate : UIAlertViewDelegate { Syncfusion.SfPdfViewer.XForms.SfPdfViewer pdfviewer; UIAlertView uiAlertView; UIAlertView alert; int pageNum = 0; nint clickedButtonIndex = -1; NSObject notificationToken; public AlertViewDelegate(Syncfusion.SfPdfViewer.XForms.SfPdfViewer pdfviewerControl) { pdfviewer = pdfviewerControl; alert = new UIAlertView(); alert.AlertViewStyle = UIAlertViewStyle.Default; alert.Title = "Error"; alert.AddButton("Ok"); alert.Message = "Please enter a valid page number"; } public override bool ShouldEnableFirstOtherButton(UIAlertView alertView) { return alertView.GetTextField(0).Text.Length > 0; } public override void Clicked(UIAlertView alertview, nint buttonIndex) { uiAlertView = alertview; clickedButtonIndex = buttonIndex; if (buttonIndex != alertview.CancelButtonIndex) { alertview.GetTextField(0).ResignFirstResponder(); if (int.TryParse(alertview.GetTextField(0).Text, out pageNum) && pageNum > 0 && pageNum <= pdfviewer.PageCount) pdfviewer.PageNumber = pageNum; } notificationToken = NSNotificationCenter.DefaultCenter.AddObserver((NSString)"UIKeyboardDidHideNotification", KeyboardDidHide); } void KeyboardDidHide(NSNotification obj) { if (clickedButtonIndex != -1 && clickedButtonIndex != uiAlertView.CancelButtonIndex && uiAlertView.GetTextField(0).Text != "" && (!(int.TryParse(uiAlertView.GetTextField(0).Text, out pageNum) && pageNum > 0 && pageNum <= pdfviewer.PageCount))) alert.Show(); NSNotificationCenter.DefaultCenter.RemoveObserver(notificationToken); } public override void Presented(UIAlertView alertView) { UITextRange textRange = alertView.GetTextField(0).SelectedTextRange; alertView.GetTextField(0).SelectAll(null); alertView.GetTextField(0).SelectedTextRange = textRange; } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/LoadMore.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Threading.Tasks; using System.Globalization; using Syncfusion.SfDataGrid; using Android.Graphics; namespace SampleBrowser { public class LoadMore : SamplePage { SfDataGrid sfGrid; LoadMoreViewModel viewModel; public override Android.Views.View GetSampleContent(Android.Content.Context context) { sfGrid = new SfDataGrid(context); viewModel = new LoadMoreViewModel(); viewModel.SetRowstoGenerate(30); sfGrid.SelectionMode = SelectionMode.Single; sfGrid.AutoGeneratingColumn += GridGenerateColumns; sfGrid.ItemsSource = (viewModel.OrdersInfo); sfGrid.AllowLoadMore = true; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; this.sfGrid.LoadMoreCommand = new Command(ExecuteCommand); this.sfGrid.GridStyle = new LoadMoreStyle(); sfGrid.LoadMoreView.Alpha = 0.1f; return sfGrid; } #region Private Methods void GridGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo("en-US"); e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "Last Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ShippingDate") { e.Column.HeaderText = "Shipping Date"; e.Column.Format = "d"; } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextAlignment = GravityFlags.CenterVertical; } } private async void ExecuteCommand() { try { this.sfGrid.IsBusy = true; await Task.Delay(new TimeSpan(0, 0, 3)); this.viewModel.LoadMoreItems(); this.sfGrid.IsBusy = false; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } } #endregion public override void Destroy() { sfGrid.AutoGeneratingColumn -= GridGenerateColumns; sfGrid.Dispose(); sfGrid = null; viewModel = null; } public class LoadMoreStyle : DataGridStyle { public LoadMoreStyle() { } public override Color GetLoadMoreViewBackgroundColor() { return Color.ParseColor("#E0E0E0"); } public override Color GetLoadMoreViewForegroundColor() { return Color.ParseColor("#000000"); } public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Horizontal; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/DragDrop.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class DragDrop : SampleView { /// <summary> /// Intialize the schedule. /// </summary> public SFSchedule schedule = new SFSchedule(); /// <summary> /// Label for toast view. /// </summary> UILabel toastUIView; /// <summary> /// The drop point. /// </summary> private CGPoint dropPoint; public DragDrop() { schedule = new SFSchedule(); schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; NonAccessibleBlock nonAccessibleBlock = new NonAccessibleBlock(); //Create new instance of NonAccessibleBlocksCollection NSMutableArray nonAccessibleBlocksCollection = new NSMutableArray(); WeekViewSettings weekViewSettings = new WeekViewSettings(); nonAccessibleBlock.StartHour = 13; nonAccessibleBlock.EndHour = 14; nonAccessibleBlock.Text = (NSString)"LUNCH"; nonAccessibleBlock.BackgroundColor = UIColor.Black; nonAccessibleBlocksCollection.Add(nonAccessibleBlock); weekViewSettings.NonAccessibleBlockCollection = nonAccessibleBlocksCollection; schedule.WeekViewSettings = weekViewSettings; schedule.AllowAppointmentDrag = true; schedule.AppointmentDragStarting += Schedule_AppointmentDragStarting; schedule.AppointmentDrop += Schedule_AppointmentDrop; schedule.AppointmentDragOver += Schedule_AppointmentDragOver; schedule.ItemsSource = CreateAppointments(); this.AddSubview(schedule); } private void Schedule_AppointmentDragOver(object sender, Syncfusion.SfSchedule.iOS.DraggingEventArgs e) { dropPoint = e.DraggingPoint; } /// <summary> /// drop event for schedule appointment. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Schedule_AppointmentDrop(object sender, AppointmentDropEventArgs e) { if (IsInNonAccessRegion(e.DropTime)) { DisplayToast("Appointment cannot be dropped on blocked time slots"); e.Cancel = true; return; } if (!(e.Appointment as ScheduleAppointment).IsAllDay && IsAllDayRegion(dropPoint)) { e.Cancel = false; (e.Appointment as ScheduleAppointment).IsAllDay = true; (e.Appointment as ScheduleAppointment).StartTime = e.DropTime; (e.Appointment as ScheduleAppointment).EndTime = e.DropTime; DisplayToast("Moved to " + FormattedDate(e.DropTime)); } else if ((e.Appointment as ScheduleAppointment).IsAllDay && IsAllDayRegion(dropPoint)) { e.Cancel = false; NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents startDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, e.DropTime); NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, e.DropTime); NSDate startDate = calendar.DateFromComponents(startDateComponents); NSDate endDate = calendar.DateFromComponents(endDateComponents); e.DropTime = startDate; (e.Appointment as ScheduleAppointment).StartTime = startDate; (e.Appointment as ScheduleAppointment).IsAllDay = true; (e.Appointment as ScheduleAppointment).EndTime = endDate; DisplayToast("Moved to " + FormattedDate(startDate)); } else if ((e.Appointment as ScheduleAppointment).IsAllDay && !(IsAllDayRegion(dropPoint))) { e.Cancel = false; NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents startDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, e.DropTime); NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, e.DropTime); endDateComponents.Hour = endDateComponents.Hour + 1; NSDate startDate = calendar.DateFromComponents(startDateComponents); NSDate endDate = calendar.DateFromComponents(endDateComponents); e.DropTime = startDate; (e.Appointment as ScheduleAppointment).StartTime = startDate; (e.Appointment as ScheduleAppointment).IsAllDay = false; (e.Appointment as ScheduleAppointment).EndTime = endDate; DisplayToast("Moved to " + FormattedDate(startDate)); } else { e.Cancel = false; DisplayToast("Moved to " + FormattedDate(e.DropTime)); } } private string FormattedDate(NSDate startDate) { NSDateFormatter dateFormat = new NSDateFormatter(); dateFormat.DateFormat = "EEEE, MMM d, h:mm a"; return dateFormat.ToString(startDate); } /// <summary> /// check the appointment with in non accessible block region. /// </summary> /// <param name="dropTime"></param> /// <returns></returns> private bool IsInNonAccessRegion(NSDate dropTime) { NSCalendar calendar = NSCalendar.CurrentCalendar; NSDateComponents start = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, dropTime); if (schedule.WeekViewSettings.NonAccessibleBlockCollection.GetItem<NonAccessibleBlock>(0).StartHour == start.Hour || schedule.WeekViewSettings.NonAccessibleBlockCollection.GetItem<NonAccessibleBlock>(0).StartHour - 1 == start.Hour && start.Minute > 0) { return true; } return false; } /// <summary> /// Ises all day region. /// </summary> /// <returns><c>true</c>, if all day region was ised, <c>false</c> otherwise.</returns> /// <param name="point">Point.</param> private bool IsAllDayRegion(CGPoint point) { double headerHeight; headerHeight = schedule.HeaderHeight + schedule.ViewHeaderHeight; if (headerHeight > point.Y) { return true; } return false; } /// <summary> /// drag starting event for schedule appointment. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Schedule_AppointmentDragStarting(object sender, DragStartingEventArgs e) { e.Cancel = false; } /// <summary> /// displaying toast when drag or drop the appointment. /// </summary> /// <param name="ToastText"></param> void DisplayToast(string ToastText) { toastUIView = new UILabel(); toastUIView.Hidden = false; toastUIView.Text = ToastText; toastUIView.Layer.CornerRadius = 20f; toastUIView.TextColor = UIColor.White; toastUIView.LineBreakMode = UILineBreakMode.WordWrap; toastUIView.Lines = 2; toastUIView.TextAlignment = UITextAlignment.Center; toastUIView.ClipsToBounds = true; toastUIView.Font = UIFont.SystemFontOfSize(14); toastUIView.BackgroundColor = UIColor.FromRGB(101.0f / 255.0f, 101.0f / 255.0f, 101.0f / 255.0f); toastUIView.Layer.ZPosition = 10; this.AddSubview(toastUIView); toastUIView.Frame = new CGRect((this.Frame.Right / 10), this.Frame.Bottom - 150, (this.Frame.Right - ((this.Frame.Right / 10) * 2)), 50); UIView.Animate(0.5, 0, UIViewAnimationOptions.CurveLinear, () => { toastUIView.Alpha = 1.0f; }, () => { UIView.Animate(3.0, () => { toastUIView.Alpha = 0.0f; }); } ); } protected override void Dispose(bool disposing) { if (disposing) { if (schedule != null) { schedule.AppointmentDragStarting -= Schedule_AppointmentDragStarting; schedule.AppointmentDrop -= Schedule_AppointmentDrop; schedule.AppointmentDragOver -= Schedule_AppointmentDragOver; schedule.Dispose(); schedule = null; } } base.Dispose(disposing); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view is UILabel) { this.BringSubviewToFront(toastUIView); toastUIView.Frame = new CGRect((this.Frame.Right / 10), this.Frame.Bottom - 150, (this.Frame.Right - ((this.Frame.Right / 10) * 2)), 50); } else { view.Frame = Bounds; } } base.LayoutSubviews(); } /// <summary> /// create appointments. /// </summary> /// <returns></returns> IEnumerable<ScheduleAppointment> CreateAppointments() { NSDate today = new NSDate(); setColors(); setSubjects(); List<ScheduleAppointment> appCollection = new List<ScheduleAppointment>(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 1); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)subjectCollection[i]; appointment.AppointmentBackground = colorCollection[i]; if (i == 10 || i == 7) { appointment.IsAllDay = true; } appCollection.Add(appointment); } return appCollection; } //adding subject collection. List<String> subjectCollection; private void setSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); } // adding colors collection List<UIColor> colorCollection; private void setColors() { colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0xF0, 0x96, 0x09)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DocIO/EncryptAndDecrypt.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.Pdf; using Syncfusion.DocIORenderer; using Syncfusion.OfficeChart; using Syncfusion.Drawing; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using Syncfusion.iOS.Buttons; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using ObjCRuntime; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class EncryptandDecrypt : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton imageType; UIButton generateButton; //RadioButton SfRadioGroup radioGroup = new SfRadioGroup(); SfRadioButton encryptButton = new SfRadioButton(); SfRadioButton decryptButton = new SfRadioButton(); public EncryptandDecrypt() { label = new UILabel(); imageType = new UIButton(); generateButton = new UIButton(UIButtonType.System); generateButton.TouchUpInside += OnConvertClicked; } void LoadAllowedTextsLabel() { #region Description Label label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to encrypt and decrypt the Word document using Essential DocIO."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 35); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } this.AddSubview(label); #endregion #region ImageFormat Label imageType.Frame = new CGRect(10, 100, frameRect.Location.X + frameRect.Size.Width - 20, 40); #endregion #region Radio Buttons for encrypt and decrypt radioGroup.Axis = UILayoutConstraintAxis.Horizontal; encryptButton.SetTitle("Encrypt", UIControlState.Normal); radioGroup.AddArrangedSubview(encryptButton); decryptButton.SetTitle("Decrypt", UIControlState.Normal); radioGroup.AddArrangedSubview(decryptButton); encryptButton.IsChecked = true; radioGroup.Distribution = UIStackViewDistribution.FillProportionally; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { radioGroup.Frame = new CGRect(5, 60, frameRect.Width - 500, 40); } else { radioGroup.Frame = new CGRect(5, 65, frameRect.Width - 90, 40); } this.AddSubview(radioGroup); #endregion #region Convert Button generateButton.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { generateButton.Frame = new CGRect(0, 115, frameRect.Location.X + frameRect.Size.Width, 10); } else { generateButton.Frame = new CGRect(0, 120, frameRect.Location.X + frameRect.Size.Width, 10); } this.AddSubview(generateButton); #endregion } void OnConvertClicked(object sender, EventArgs e) { WordDocument document = null; if (encryptButton != null && (bool)encryptButton.IsChecked) { //Creates a new Word document document = new WordDocument(); document.EnsureMinimal(); // Getting last section of the document. IWSection section = document.LastSection; // Adding a paragraph to the section. IWParagraph paragraph = section.AddParagraph(); // Writing text IWTextRange text = paragraph.AppendText("This document was encrypted with password"); text.CharacterFormat.FontSize = 16f; text.CharacterFormat.FontName = "Bitstream Vera Serif"; // Encrypt the document by giving password document.EncryptDocument("<PASSWORD>"); } else { Assembly assembly = Assembly.GetExecutingAssembly(); document = new WordDocument(); // Open an existing template document. Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Security Settings.docx"); document.Open(inputStream, FormatType.Docx, "syncfusion"); inputStream.Dispose(); // Getting last section of the document. IWSection section = document.LastSection; // Adding a paragraph to the section. IWParagraph paragraph = section.AddParagraph(); // Writing text IWTextRange text = paragraph.AppendText("\nDemo For Document Decryption with Essential DocIO"); text.CharacterFormat.FontSize = 16f; text.CharacterFormat.FontName = "Bitstream Vera Serif"; text = paragraph.AppendText("\nThis document is Decrypted"); text.CharacterFormat.FontSize = 16f; text.CharacterFormat.FontName = "Bitstream Vera Serif"; } string fileName = null; string ContentType = null; MemoryStream ms = new MemoryStream(); fileName = "Encrypt and Decrypt.docx"; ContentType = "application/msword"; document.Save(ms, FormatType.Docx); //Reset the stream position ms.Position = 0; //Close the document instance. document.Close(); if (ms != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save(fileName, ContentType, ms as MemoryStream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Forms/ListView/ListView/Samples/Selection/Helper/Converter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Syncfusion.ListView.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; using SelectionMode = Syncfusion.ListView.XForms.SelectionMode; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class SelectionModeToVisbileConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((SelectionMode) value == SelectionMode.Multiple) return true; else return false; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class IconColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return Color.FromHex("#1a75ff"); else return Color.FromHex("#b3b3b3"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class SelectionIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return "Selected.png"; else return "UnSelect.png"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Android/SampleBrowser/Samples/TreeMap/TreeMapDrilldown.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Treemap; using Org.Json; namespace SampleBrowser { public class TreeMapDrilldown : SamplePage { SfTreeMap treeMap; public TreeMapDrilldown() { } public override View GetSampleContent(Context context) { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; int screenHeight = displayMetrics.HeightPixels; LinearLayout layout = new LinearLayout(context); layout.Orientation = Orientation.Vertical; TextView textView = new TextView(context); textView.TextAlignment = TextAlignment.Center; textView.TextSize = 18; textView.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; textView.SetHeight((int)(screenHeight * 0.05)); textView.Text = "Continents by population"; layout.AddView(textView); treeMap = new SfTreeMap(context); treeMap.WeightValuePath = "Population"; treeMap.ColorValuePath = "Growth"; treeMap.HighlightOnSelection = false; treeMap.LeafItemSettings = new LeafItemSetting() { ShowLabels = true, Gap = 5, LabelPath = "Region", StrokeColor = Android.Graphics.Color.Gray, StrokeWidth = 1 }; TreeMapFlatLevel level = new TreeMapFlatLevel { ShowHeader = true, GroupPath = "Continent", GroupStrokeColor = Android.Graphics.Color.Gray, GroupStrokeWidth = 1, GroupPadding = 5, LabelPath = "Continent", HeaderStyle = new Style() { TextColor = Android.Graphics.Color.Black }, HeaderHeight = 25 }; TreeMapFlatLevel level1 = new TreeMapFlatLevel { ShowHeader = true, GroupPath = "States", GroupStrokeColor = Android.Graphics.Color.Gray, GroupStrokeWidth = 1, GroupPadding = 5, LabelPath = "States", HeaderStyle = new Style() { TextColor = Android.Graphics.Color.Black }, HeaderHeight = 25 }; treeMap.Levels.Add(level); treeMap.Levels.Add(level1); PaletteColorMapping colorMapping = new PaletteColorMapping(); colorMapping.Colors.Add(Color.ParseColor("#C044A5")); colorMapping.Colors.Add(Color.ParseColor("#665197")); colorMapping.Colors.Add(Color.ParseColor("#FF4652")); colorMapping.Colors.Add(Color.ParseColor("#8B2286")); colorMapping.Colors.Add(Color.ParseColor("#448FC0")); treeMap.LeafItemColorMapping = colorMapping; treeMap.DataSource = GetDataSource(); treeMap.EnableDrilldown = true; treeMap.ShowTooltip = true; layout.AddView(treeMap); return layout; } JSONArray GetDataSource() { JSONArray array = new JSONArray(); #region Africa array.Put(GetJsonObject("Africa", "Eastern Africa", "Ethiopia", 107534882)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Tanzania", 59091392)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Kenya", 50950879)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Uganda", 44270563)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Mozambique", 30528673)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Madagascar", 26262810)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Malawi", 19164728)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Zambia", 17609178)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Zimbabwe", 16913261)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Somalia", 15181925)); array.Put(GetJsonObject("Africa", "Eastern Africa", "South Sudan", 12919053)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Rwanda", 12501156)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Burundi", 107534882)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Eritrea", 5187948)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Mauritius", 1268315)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Djibouti", 971408)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Réunion", 883247)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Comoros", 832347)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Mayotte", 259682)); array.Put(GetJsonObject("Africa", "Eastern Africa", "Seychelles", 95235)); array.Put(GetJsonObject("Africa", "Middle Africa", "Democratic Republic of the Congo", 84004989)); array.Put(GetJsonObject("Africa", "Middle Africa", "Angola", 30774205)); array.Put(GetJsonObject("Africa", "Middle Africa", "Cameroon", 24678234)); array.Put(GetJsonObject("Africa", "Middle Africa", "Chad", 15353184)); array.Put(GetJsonObject("Africa", "Middle Africa", "Congo", 5399895)); array.Put(GetJsonObject("Africa", "Middle Africa", "Central African Republic", 4737423)); array.Put(GetJsonObject("Africa", "Middle Africa", "Gabon", 2067561)); array.Put(GetJsonObject("Africa", "Middle Africa", "Equatorial Guinea", 1313894)); array.Put(GetJsonObject("Africa", "Middle Africa", "Sao Tome and Principe", 208818)); array.Put(GetJsonObject("Africa", "Northern Africa", "Egypt", 99375741)); array.Put(GetJsonObject("Africa", "Northern Africa", "Algeria", 42008054)); array.Put(GetJsonObject("Africa", "Northern Africa", "Sudan", 41511526)); array.Put(GetJsonObject("Africa", "Northern Africa", "Morocco", 36191805)); array.Put(GetJsonObject("Africa", "Northern Africa", "Tunisia", 11659174)); array.Put(GetJsonObject("Africa", "Northern Africa", "Libya", 6470956)); array.Put(GetJsonObject("Africa", "Northern Africa", "Western Sahara", 567421)); array.Put(GetJsonObject("Africa", "Southern Africa", "South Africa", 57398421)); array.Put(GetJsonObject("Africa", "Southern Africa", "Namibia", 2587801)); array.Put(GetJsonObject("Africa", "Southern Africa", "Botswana", 2333201)); array.Put(GetJsonObject("Africa", "Southern Africa", "Lesotho", 2263010)); array.Put(GetJsonObject("Africa", "Southern Africa", "Swaziland", 1391385)); array.Put(GetJsonObject("Africa", "Western Africa", "Nigeria", 195875237)); array.Put(GetJsonObject("Africa", "Western Africa", "Ghana", 29463643)); array.Put(GetJsonObject("Africa", "Western Africa", "Côte d'Ivoire", 24905843)); array.Put(GetJsonObject("Africa", "Western Africa", "Niger", 22311375)); array.Put(GetJsonObject("Africa", "Western Africa", "Burkina Faso", 19751651)); array.Put(GetJsonObject("Africa", "Western Africa", "Mali", 19107706)); array.Put(GetJsonObject("Africa", "Western Africa", "Senegal", 16294270)); array.Put(GetJsonObject("Africa", "Western Africa", "Guinea", 13052608)); array.Put(GetJsonObject("Africa", "Western Africa", "Benin", 11485674)); array.Put(GetJsonObject("Africa", "Western Africa", "Togo", 7990926)); array.Put(GetJsonObject("Africa", "Western Africa", "Sierra Leone", 7719729)); array.Put(GetJsonObject("Africa", "Western Africa", "Liberia", 4853516)); array.Put(GetJsonObject("Africa", "Western Africa", "Mauritania", 4540068)); array.Put(GetJsonObject("Africa", "Western Africa", "Gambia", 2163765)); array.Put(GetJsonObject("Africa", "Western Africa", "Guinea-Bissau", 1907268)); array.Put(GetJsonObject("Africa", "Western Africa", "Cabo Verde", 553335)); array.Put(GetJsonObject("Africa", "Western Africa", "<NAME>", 4074)); #endregion #region Asia array.Put(GetJsonObject("Asia", "Central Asia", "Uzbekistan", 32364996)); array.Put(GetJsonObject("Asia", "Central Asia", "Kazakhstan", 18403860)); array.Put(GetJsonObject("Asia", "Central Asia", "Tajikistan", 9107211)); array.Put(GetJsonObject("Asia", "Central Asia", "Kyrgyzstan", 6132932)); array.Put(GetJsonObject("Asia", "Central Asia", "Turkmenistan", 5851466)); array.Put(GetJsonObject("Asia", "Eastern Asia", "China", 1415045928)); array.Put(GetJsonObject("Asia", "Eastern Asia", "Japan", 127185332)); array.Put(GetJsonObject("Asia", "Eastern Asia", "South Korea", 51164435)); array.Put(GetJsonObject("Asia", "Eastern Asia", "North Korea", 25610672)); array.Put(GetJsonObject("Asia", "Eastern Asia", "Taiwan", 23694089)); array.Put(GetJsonObject("Asia", "Eastern Asia", "Hong Kong", 7428887)); array.Put(GetJsonObject("Asia", "Eastern Asia", "Mongolia", 3121772)); array.Put(GetJsonObject("Asia", "Eastern Asia", "Macao", 632418)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Indonesia", 266794980)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Philippines", 106512074)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Viet Nam", 96491146)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Thailand", 69183173)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Myanmar", 53855735)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Malaysia", 32042458)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Cambodia", 16245729)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Laos", 6961210)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Singapore", 5791901)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Timor-Leste", 1324094)); array.Put(GetJsonObject("Asia", "Southeastern Asia", "Brunei Darussalam", 434076)); array.Put(GetJsonObject("Asia", "Southern Asia", "India", 1354051854)); array.Put(GetJsonObject("Asia", "Southern Asia", "Pakistan", 200813818)); array.Put(GetJsonObject("Asia", "Southern Asia", "Bangladesh", 166368149)); array.Put(GetJsonObject("Asia", "Southern Asia", "Iran", 82011735)); array.Put(GetJsonObject("Asia", "Southern Asia", "Afghanistan", 36373176)); array.Put(GetJsonObject("Asia", "Southern Asia", "Nepal", 29624035)); array.Put(GetJsonObject("Asia", "Southern Asia", "Sri Lanka", 20950041)); array.Put(GetJsonObject("Asia", "Southern Asia", "Bhutan", 817054)); array.Put(GetJsonObject("Asia", "Southern Asia", "Maldives", 444259)); array.Put(GetJsonObject("Asia", "Western Asia", "Turkey", 81916871)); array.Put(GetJsonObject("Asia", "Western Asia", "Iraq", 39339753)); array.Put(GetJsonObject("Asia", "Western Asia", "Saudi Arabia", 33554343)); array.Put(GetJsonObject("Asia", "Western Asia", "Yemen", 28915284)); array.Put(GetJsonObject("Asia", "Western Asia", "Syria", 18284407)); array.Put(GetJsonObject("Asia", "Western Asia", "Azerbaijan", 9923914)); array.Put(GetJsonObject("Asia", "Western Asia", "Jordan", 9903802)); array.Put(GetJsonObject("Asia", "Western Asia", "United Arab Emirates", 9541615)); array.Put(GetJsonObject("Asia", "Western Asia", "Israel", 8452841)); array.Put(GetJsonObject("Asia", "Western Asia", "Lebanon", 6093509)); array.Put(GetJsonObject("Asia", "Western Asia", "State of Palestine", 5052776)); array.Put(GetJsonObject("Asia", "Western Asia", "Oman", 4829946)); array.Put(GetJsonObject("Asia", "Western Asia", "Kuwait", 4197128)); array.Put(GetJsonObject("Asia", "Western Asia", "Georgia", 3907131)); array.Put(GetJsonObject("Asia", "Western Asia", "Armenia", 2934152)); array.Put(GetJsonObject("Asia", "Western Asia", "Qatar", 2694849)); array.Put(GetJsonObject("Asia", "Western Asia", "Bahrain", 1566993)); array.Put(GetJsonObject("Asia", "Western Asia", "Cyprus", 1189085)); #endregion #region Northa America array.Put(GetJsonObject("North America", "Central America", "Mexico", 130759074)); array.Put(GetJsonObject("North America", "Central America", "Guatemala", 17245346)); array.Put(GetJsonObject("North America", "Central America", "Honduras", 9417167)); array.Put(GetJsonObject("North America", "Central America", "El, Salvador", 6411558)); array.Put(GetJsonObject("North America", "Central America", "Nicaragua", 6284757)); array.Put(GetJsonObject("North America", "Central America", "Costa, Rica", 4953199)); array.Put(GetJsonObject("North America", "Central America", "Panama", 4162618)); array.Put(GetJsonObject("North America", "Central America", "Belize", 382444)); array.Put(GetJsonObject("North America", "Northern America", "U.S", 322179605)); array.Put(GetJsonObject("North America", "Northern America", "Canada", 36953765)); array.Put(GetJsonObject("North America", "Northern America", "Bermuda", 61070)); array.Put(GetJsonObject("North America", "Northern America", "Greenland", 56565)); array.Put(GetJsonObject("North America", "Northern America", "Saint Pierre & Miquelon", 6342)); #endregion #region SouthAmerica array.Put(GetJsonObject("South America", "South America", "Brazil", 204519000)); array.Put(GetJsonObject("South America", "South America", "Colombia", 48549000)); array.Put(GetJsonObject("South America", "South America", "Argentina", 43132000)); array.Put(GetJsonObject("South America", "South America", "Peru", 31153000)); array.Put(GetJsonObject("South America", "South America", "Venezuela", 30620000)); array.Put(GetJsonObject("South America", "South America", "Chile", 18006000)); array.Put(GetJsonObject("South America", "South America", "Ecuador", 16279000)); array.Put(GetJsonObject("South America", "South America", "Bolivia", 10520000)); array.Put(GetJsonObject("South America", "South America", "Paraguay", 7003000)); array.Put(GetJsonObject("South America", "South America", "Uruguay", 3310000)); array.Put(GetJsonObject("South America", "South America", "Guyana", 747000)); array.Put(GetJsonObject("South America", "South America", "Suri Name", 560000)); array.Put(GetJsonObject("South America", "South America", "French Guiana", 262000)); array.Put(GetJsonObject("South America", "South America", "Falkland Islands", 3000)); #endregion #region Europe array.Put(GetJsonObject("Europe", "Eastern Europe", "Russia", 143964709)); array.Put(GetJsonObject("Europe", "Eastern Europe", "Ukraine", 44009214)); array.Put(GetJsonObject("Europe", "Eastern Europe", "Poland", 38104832)); array.Put(GetJsonObject("Europe", "Eastern Europe", "Romania", 19580634)); array.Put(GetJsonObject("Europe", "Eastern Europe", "Crech, Republic", 10625250)); array.Put(GetJsonObject("Europe", "Eastern Europe", "Hungary", 9688847)); array.Put(GetJsonObject("Europe", "Eastern Europe", "Belarus", 9452113)); array.Put(GetJsonObject("Europe", "Eastern Europe", "Bulgaria", 7036848)); array.Put(GetJsonObject("Europe", "Eastern Europe", "Slovakia", 5449816)); array.Put(GetJsonObject("Europe", "Eastern Europe", "Moldova", 4041065)); array.Put(GetJsonObject("Europe", "Northern Europe", "United Kingdom", 66573504)); array.Put(GetJsonObject("Europe", "Northern Europe", "Sweden", 9982709)); array.Put(GetJsonObject("Europe", "Northern Europe", "Denmark", 5754356)); array.Put(GetJsonObject("Europe", "Northern Europe", "Finland", 5542517)); array.Put(GetJsonObject("Europe", "Northern Europe", "Norway", 5353363)); array.Put(GetJsonObject("Europe", "Northern Europe", "Ireland", 4803748)); array.Put(GetJsonObject("Europe", "Northern Europe", "Lithuania", 2876475)); array.Put(GetJsonObject("Europe", "Northern Europe", "Latvia", 1929938)); array.Put(GetJsonObject("Europe", "Northern Europe", "Estonia", 1306788)); array.Put(GetJsonObject("Europe", "Northern Europe", "Iceland", 337780)); array.Put(GetJsonObject("Europe", "Northern Europe", "Channel Islands", 166083)); array.Put(GetJsonObject("Europe", "Northern Europe", "Isle of Man", 84831)); array.Put(GetJsonObject("Europe", "Northern Europe", "Faeroe Islands", 49489)); array.Put(GetJsonObject("Europe", "Southern Europe", "Italy", 59290969)); array.Put(GetJsonObject("Europe", "Southern Europe", "Spain", 46397452)); array.Put(GetJsonObject("Europe", "Southern Europe", "Greece", 11142161)); array.Put(GetJsonObject("Europe", "Southern Europe", "Portugal", 10291196)); array.Put(GetJsonObject("Europe", "Southern Europe", "Serbia", 8762027)); array.Put(GetJsonObject("Europe", "Southern Europe", "Croatia", 4164783)); array.Put(GetJsonObject("Europe", "Southern Europe", "Bosnia and Herzegovina", 3503554)); array.Put(GetJsonObject("Europe", "Southern Europe", "Albania", 2934363)); array.Put(GetJsonObject("Europe", "Southern Europe", "Macedonia", 2085051)); array.Put(GetJsonObject("Europe", "Southern Europe", "Slovenia", 2081260)); array.Put(GetJsonObject("Europe", "Southern Europe", "Montenegro", 629219)); array.Put(GetJsonObject("Europe", "Southern Europe", "Malta", 432089)); array.Put(GetJsonObject("Europe", "Southern Europe", "Andorra", 76953)); array.Put(GetJsonObject("Europe", "Southern Europe", "Gibraltar", 34733)); array.Put(GetJsonObject("Europe", "Southern Europe", "San Marino", 33557)); array.Put(GetJsonObject("Europe", "Southern Europe", "Holy, See", 801)); array.Put(GetJsonObject("Europe", "Western Europe", "Germany", 82293457)); array.Put(GetJsonObject("Europe", "Western Europe", "France", 65233271)); array.Put(GetJsonObject("Europe", "Western Europe", "Netherlands", 17084459)); array.Put(GetJsonObject("Europe", "Western Europe", "Belgium", 11498519)); array.Put(GetJsonObject("Europe", "Western Europe", "Austria", 8751820)); array.Put(GetJsonObject("Europe", "Western Europe", "Switzerland", 8544034)); array.Put(GetJsonObject("Europe", "Western Europe", "Luxembourg", 590321)); array.Put(GetJsonObject("Europe", "Western Europe", "Monaco", 38897)); array.Put(GetJsonObject("Europe", "Western Europe", "Liechtenstein", 38155)); #endregion return array; } JSONObject GetJsonObject(string continent, string states, string region, double population) { JSONObject obj = new JSONObject(); obj.Put("Continent", continent); obj.Put("States", states); obj.Put("Region", region); obj.Put("Population", population); return obj; } } }<file_sep>/iOS/SampleBrowser/Samples/PDF/ImageInsertion.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf; using Syncfusion.Pdf.Barcode; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Interactive; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class ImageInsertion : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label1; UIButton button ; public ImageInsertion() { label1 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label1.Frame = frameRect; label1.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label1.Text = "This sample demonstrates how to insert images in a PDF document."; label1.Font = UIFont.SystemFontOfSize(15); label1.Lines = 0; label1.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label1.Font = UIFont.SystemFontOfSize(18); label1.Frame = new CGRect(0, 12, frameRect.Location.X + frameRect.Size.Width, 50); } else { label1.Frame = new CGRect(frameRect.Location.X, 12, frameRect.Size.Width, 50); } this.AddSubview(label1); button.SetTitle("Generate PDF", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 70, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 70, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { // Create a new instance of PdfDocument class. PdfDocument document = new PdfDocument(); // Add a new page to the newly created document. PdfPage page = document.Pages.Add(); PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold); PdfGraphics g = page.Graphics; g.DrawString("JPEG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 40)); //Load JPEG image to stream. Stream jpgImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Xamarin_JPEG.jpg"); //Load the JPEG image PdfImage jpgImage = new PdfBitmap(jpgImageStream); //Draw the JPEG image g.DrawImage(jpgImage,new Syncfusion.Drawing.RectangleF(0,70,515,215)); g.DrawString("PNG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 355)); //Load PNG image to stream. Stream pngImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Xamarin_PNG.png"); //Load the PNG image PdfImage pngImage = new PdfBitmap(pngImageStream); //Draw the PNG image g.DrawImage(pngImage,new Syncfusion.Drawing.RectangleF(0,365,199,300)); MemoryStream stream = new MemoryStream(); //Save the PDF document document.Save(stream); stream.Position = 0; //Close the PDF document document.Close(true); if (stream != null) { SaveiOS iosSave = new SaveiOS(); iosSave.Save("ImageInsertion.pdf", "application/pdf", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } } <file_sep>/Forms/BadgeView/BadgeView/Samples/Notification/HelperClass/BadgeViewConverter.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "BadgeViewConverter.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfBadgeView { using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Xamarin.Forms; /// <summary> /// BadgeView Converter Class /// </summary> [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1027:TabsMustNotBeUsed", Justification = "Reviewed.")] public class BadgeViewConverter : IValueConverter { /// <summary> /// This method is used to convert the string to color /// </summary> /// <param name="value">Gets the value</param> /// <param name="targetType">Gets the target type</param> /// <param name="parameter">Gets the parameter</param> /// <param name="culture">Gets the culture</param> /// <returns>Return the color</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (string.IsNullOrEmpty(value.ToString())) { return Color.Black; } else { return Color.FromHex("#007cee"); } } /// <summary> /// This method is used to convert back the color to string /// </summary> /// <param name="value">Gets the value</param> /// <param name="targetType">Gets the target type</param> /// <param name="parameter">Gets the parameter</param> /// <param name="culture">Gets the culture</param> /// <returns>Returns the string</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }<file_sep>/iOS/SampleBrowser/Samples/XlsIO/CollectionObjects.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XlsIO; using Syncfusion.SfDataGrid; using System.IO; using Syncfusion.Drawing; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.ComponentModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class CollectionObjects : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; UIButton btnInput; UIButton btnImport; SfDataGrid sfGrid; CLRObjectViewModel viewmodel; public CollectionObjects() { label = new UILabel(); label1 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; btnInput = new UIButton(UIButtonType.System); btnInput.TouchUpInside += OnButtonInputClicked; btnImport = new UIButton(UIButtonType.System); btnImport.TouchUpInside += OnButtonImportClicked; sfGrid = new SfDataGrid(); viewmodel = new CLRObjectViewModel(); sfGrid.AutoGenerateColumns = false; sfGrid.RowHeight = 50; sfGrid.AllowEditing = true; sfGrid.EditTapAction = TapAction.OnTap; sfGrid.ColumnSizer = ColumnSizer.Star; sfGrid.SelectionMode = SelectionMode.None; sfGrid.HeaderRowHeight = 40; sfGrid.ItemsSource = viewmodel.CustomersInfo; GridTextColumn brand = new GridTextColumn(); brand.MappingName = "BrandName"; brand.HeaderText = "Brand"; brand.HeaderTextAlignment = UIKit.UITextAlignment.Center; GridTextColumn vehicleType = new GridTextColumn(); vehicleType.MappingName = "VehicleType.VehicleName"; vehicleType.HeaderText = "Vehicle Type"; vehicleType.HeaderTextAlignment = UIKit.UITextAlignment.Center; GridTextColumn model = new GridTextColumn(); model.MappingName = "VehicleType.Model.ModelName"; model.HeaderText = "Model"; model.HeaderTextAlignment = UIKit.UITextAlignment.Center; sfGrid.Columns.Add(brand); sfGrid.Columns.Add(vehicleType); sfGrid.Columns.Add(model); this.AddSubview(sfGrid); } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample allows you to import/export data from/to Collection Objects."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } else { label.Frame = new CGRect(5, 5, frameRect.Size.Width, 70); } this.AddSubview(label); btnInput.SetTitle("Input Template", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { btnInput.Frame = new CGRect(0, 65, frameRect.Location.X + frameRect.Size.Width, 10); } else { btnInput.Frame = new CGRect(5, 75, frameRect.Size.Width, 10); } this.AddSubview(btnInput); btnImport.SetTitle("Import From Excel", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { btnImport.Frame = new CGRect(0, 95, frameRect.Location.X + frameRect.Size.Width, 10); } else { btnImport.Frame = new CGRect(5, 105, frameRect.Size.Width, 10); } this.AddSubview(btnImport); button.SetTitle("Export To Excel", UIControlState.Normal); button.Enabled = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 125, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(5, 135, frameRect.Size.Width, 10); } this.AddSubview(button); this.sfGrid.Frame = new CGRect(0, 155, this.Frame.Width, this.Frame.Height-155); base.LayoutSubviews(); } void OnButtonInputClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExportData.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); IWorksheet sheet = workbook.Worksheets[0]; #endregion workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("InputTemplate.xlsx", "application/msexcel", stream); } } void OnButtonImportClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExportData.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); IWorksheet sheet = workbook.Worksheets[0]; #endregion Dictionary<string, string> mappingProperties = new Dictionary<string, string>(); mappingProperties.Add("Brand", "BrandName"); mappingProperties.Add("Vehicle Type", "VehicleType.VehicleName"); mappingProperties.Add("Model", "VehicleType.Model.ModelName"); List<Brand> CLRObjects = sheet.ExportData<Brand>(4, 1, 141, 3, mappingProperties); button.Enabled = true; sfGrid.ItemsSource = CLRObjects; } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; //A new workbook is created.[Equivalent to creating a new workbook in MS Excel] //The new workbook will have 1 worksheets IWorkbook workbook = application.Workbooks.Create(1); //The first worksheet object in the worksheets collection is accessed. IWorksheet worksheet = workbook.Worksheets[0]; worksheet.ImportData((List<Brand>)sfGrid.ItemsSource, 4, 1, true); #region Define Styles IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle"); IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle"); pageHeader.Font.FontName = "Calibri"; pageHeader.Font.Size = 16; pageHeader.Font.Bold = true; pageHeader.Color = Color.FromArgb(0, 146, 208, 80); pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Font.Bold = true; tableHeader.Font.FontName = "Calibri"; tableHeader.Color = Color.FromArgb(0, 146, 208, 80); #endregion #region Apply Styles // Apply style for header worksheet["A1:C2"].Merge(); worksheet["A1"].Text = "Automobile Brands in the US"; worksheet["A1"].CellStyle = pageHeader; worksheet["A4:C4"].CellStyle = tableHeader; worksheet["A1:C1"].CellStyle.Font.Bold = true; worksheet.UsedRange.AutofitColumns(); #endregion workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("ImportCollectionObjects.xlsx", "application/msexcel", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } [Preserve(AllMembers = true)] public class CLRObjectViewModel : INotifyPropertyChanged { private bool isDataGridExported; public bool IsDataGridExported { get { return isDataGridExported; } set { isDataGridExported = value; RaisePropertyChanged("IsDataGridExported"); } } public CLRObjectViewModel() { CustomersInfo = new List<Brand>(); foreach (int i in Enumerable.Range(1, 20)) { CustomersInfo.Add(new Brand()); } } #region ItemsSource private List<Brand> customersInfo; public List<Brand> CustomersInfo { get { return customersInfo; } set { this.customersInfo = value; RaisePropertyChanged("CustomersInfo"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } /// <summary> /// Class used to store the customer details /// </summary> /// [Preserve(AllMembers = true)] public class CustomerObject : INotifyPropertyChanged { public CustomerObject() { } #region private variables private string _salesPerson; private int _salesJanJune; private int _salesJulyDec; private string _change; #endregion #region Public Properties public string SalesPerson { get { return _salesPerson; } set { this._salesPerson = value; RaisePropertyChanged("SalesPerson"); } } public int SalesJanJune { get { return _salesJanJune; } set { this._salesJanJune = value; RaisePropertyChanged("SalesJanJune"); } } public int SalesJulyDec { get { return _salesJulyDec; } set { this._salesJulyDec = value; RaisePropertyChanged("SalesJulyDec"); } } public string Change { get { return _change; } set { this._change = value; RaisePropertyChanged("Change"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String Name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(Name)); } #endregion } public class Brand { private string m_brandName; [DisplayNameAttribute("Brand")] public string BrandName { get { return m_brandName; } set { m_brandName = value; RaisePropertyChanged("BrandName"); } } private VehicleType m_vehicleType; public VehicleType VehicleType { get { return m_vehicleType; } set { m_vehicleType = value; RaisePropertyChanged("VehicleType"); } } public Brand(string brandName) { m_brandName = brandName; } public Brand() { } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String Name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(Name)); } #endregion } public class VehicleType { private string m_vehicleName; [DisplayNameAttribute("Vehicle Type")] public string VehicleName { get { return m_vehicleName; } set { m_vehicleName = value; RaisePropertyChanged("VehicleName"); } } private ModelObject m_model; public ModelObject Model { get { return m_model; } set { m_model = value; RaisePropertyChanged("Model"); } } public VehicleType(string vehicle) { m_vehicleName = vehicle; } public VehicleType() { } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String Name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(Name)); } #endregion } public class ModelObject { private string m_modelName; [DisplayNameAttribute("Model")] public string ModelName { get { return m_modelName; } set { m_modelName = value; RaisePropertyChanged("ModelName"); } } public ModelObject(string name) { m_modelName = name; } public ModelObject() { } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String Name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(Name)); } #endregion } } <file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/PullToRefreshView/PullToRefreshViewBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PullToRefreshViewBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using System; using System.Diagnostics.CodeAnalysis; using Core; using Syncfusion.ListView.XForms; using Syncfusion.SfPullToRefresh.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the PullToRefreshViewBehavior samples /// </summary> public class PullToRefreshViewBehavior : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Image imagedata; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Label label2; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Label label3; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfListView listView; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfPullToRefresh pullToRefresh; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Grid subGrid1; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Grid subGrid2; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt transitionType; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PullToRefreshViewModel viewModel; /// <summary> /// Used to Update whether Data value /// </summary> /// <param name="temperature">double parameter named as temperature</param> internal void UpdateData(double temperature) { this.label2.Text = string.Format("{0}°/12°", new object[] { temperature }); this.label3.Text = this.viewModel.Data.Month; this.imagedata.Source = this.viewModel.Data.ImageName; } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">Sample View typed parameter named as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.viewModel = new PullToRefreshViewModel(); bindAble.BindingContext = this.viewModel; this.pullToRefresh = bindAble.FindByName<SfPullToRefresh>("pullToRefresh"); this.subGrid1 = bindAble.FindByName<Grid>("SubGrid1"); this.subGrid2 = bindAble.FindByName<Grid>("SubGrid2"); this.listView = bindAble.FindByName<SfListView>("listView"); this.transitionType = bindAble.FindByName<PickerExt>("transitionType"); this.label2 = bindAble.FindByName<Label>("label2"); this.label3 = bindAble.FindByName<Label>("label3"); this.imagedata = bindAble.FindByName<Image>("imagedata"); this.subGrid1.BindingContext = this.viewModel.Data; this.pullToRefresh.PullingThreshold = 100; this.listView.ItemsSource = this.viewModel.SelectedData; if (Device.RuntimePlatform == Device.iOS) { this.pullToRefresh.SizeChanged += this.Pull_SizeChanged; } this.pullToRefresh.Refreshing += this.PullToRefresh_Refreshing; this.pullToRefresh.Refreshed += this.PullToRefresh_Refreshed; this.listView.SelectionChanging += this.ListView_SelectionChanging; this.transitionType.Items.Add("Push"); this.transitionType.Items.Add("SlideOnTop"); this.transitionType.SelectedIndex = 1; this.transitionType.SelectedIndexChanged += this.OnSelectionChanged; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView typed parameter named as bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.pullToRefresh.SizeChanged -= this.Pull_SizeChanged; this.pullToRefresh.Refreshing -= this.PullToRefresh_Refreshing; this.pullToRefresh.Refreshed -= this.PullToRefresh_Refreshed; this.listView.SelectionChanging -= this.ListView_SelectionChanging; this.transitionType.SelectedIndexChanged -= this.OnSelectionChanged; this.pullToRefresh = null; this.viewModel = null; this.listView = null; this.subGrid1 = null; this.subGrid2 = null; this.transitionType = null; this.label2 = null; this.label3 = null; this.imagedata = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Fired when selected index gets changed /// </summary> /// <param name="sender">OnSelectionChanged event sender</param> /// <param name="e">OnSelectionChanged event args e</param> private void OnSelectionChanged(object sender, EventArgs e) { if (this.transitionType.SelectedIndex == 0) { this.pullToRefresh.TransitionMode = TransitionType.Push; } else { this.pullToRefresh.TransitionMode = TransitionType.SlideOnTop; } } /// <summary> /// Triggers while pull to refresh View completes refreshing. /// </summary> /// <param name="sender">PullToRefresh_Refreshed event sender</param> /// <param name="e">PullToRefresh_Refreshed event args e</param> private void PullToRefresh_Refreshed(object sender, EventArgs e) { this.pullToRefresh.IsRefreshing = false; } /// <summary> /// Triggers while pull size gets changed /// </summary> /// <param name="sender">Pull_SizeChanged sender</param> /// <param name="e">Pull_SizeChanged event args e</param> private void Pull_SizeChanged(object sender, EventArgs e) { this.pullToRefresh.WidthRequest = this.pullToRefresh.Bounds.Width; this.pullToRefresh.HeightRequest = this.pullToRefresh.Bounds.Height + 10; } /// <summary> /// Triggers while pull to refresh view was refreshing /// </summary> /// <param name="sender">PullToRefresh_Refreshing sender</param> /// <param name="args">PullToRefresh_Refreshing event args e</param> private void PullToRefresh_Refreshing(object sender, EventArgs args) { this.pullToRefresh.IsRefreshing = true; Device.StartTimer( new TimeSpan( 0, 0, 0, 1, 500), () => { Random rnd = new Random(); int i = rnd.Next(20, 40); this.UpdateData(i); this.pullToRefresh.IsRefreshing = false; return false; }); } /// <summary> /// Triggers while list view selection was changing /// </summary> /// <param name="sender">ListView_SelectionChanging event sender</param> /// <param name="e">ListView_SelectionChanging event args e</param> private void ListView_SelectionChanging(object sender, ItemSelectionChangingEventArgs e) { if (e.AddedItems.Count > 0) { this.viewModel.Data = e.AddedItems[0] as WeatherData; this.UpdateData(this.viewModel.Data.Temperature); } else if (e.AddedItems.Count == 0) { e.Cancel = true; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/TreeView/TreeGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using CoreGraphics; using UIKit; using Syncfusion.iOS.TreeView; using Syncfusion.TreeView.Engine; namespace SampleBrowser { public class TreeGettingStarted : SampleView { SfTreeView treeView; FoodSpeciesViewModel viewModel; public TreeGettingStarted() { treeView = new SfTreeView(); viewModel = new FoodSpeciesViewModel(); treeView.FullRowSelect = true; treeView.AutoExpandMode = AutoExpandMode.AllNodesExpanded; treeView.ExpandActionTarget = ExpandActionTarget.Node; treeView.ChildPropertyName = "Species"; treeView.ItemsSource = viewModel.SpeciesType; treeView.Adapter = new GettingStartedAdapter(); this.AddSubview(treeView); } public override void LayoutSubviews() { this.treeView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }<file_sep>/Forms/Switch/Switch/Samples/GettingStartedSample/ViewModel/TokensViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.XForms.Buttons; namespace SampleBrowser.SfSwitch { public class TokensViewModel { private ObservableCollection<SfSegmentItem> tokenCollections; public ObservableCollection<SfSegmentItem> TokenCollections { get { return tokenCollections; } set { tokenCollections = value; } } public TokensViewModel() { TokenCollections = new ObservableCollection<SfSegmentItem> { new SfSegmentItem {Text = "AudioBooks"}, new SfSegmentItem {Text = "eBooks"}, new SfSegmentItem {Text = "Comics"}, new SfSegmentItem {Text = "Genres"}, new SfSegmentItem {Text = "Top Sellings"} }; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/CircularGauge/Pointers.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfGauge.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using System.Drawing; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class Pointers : SampleView { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } UIScrollView scroll; SFCircularGauge gauge1; SFCircularGauge gauge2; SFCircularGauge gauge3; SFCircularGauge gauge4; SFCircularGauge gauge5; public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; CGSize sz = this.Frame.Size; gauge1.Frame = new CGRect(0, 0, sz.Width, sz.Height / 2); gauge2.Frame = new CGRect(0, sz.Height / 3, sz.Width, sz.Height / 2); gauge3.Frame = new CGRect(0, sz.Height / 3 * 2, sz.Width, sz.Height / 2); // gauge4.Frame = new CGRect(10, 470, (float)this.Frame.Width - 20, (float)this.Frame.Height / 2 - 20); // gauge5.Frame = new CGRect(10, 600, (float)this.Frame.Width - 20, (float)this.Frame.Height / 2 - 20); } base.LayoutSubviews(); } public Pointers() { scroll = new UIScrollView(); gauge1 = new SFCircularGauge(); SFGaugeHeader header1 = new SFGaugeHeader(); header1.Position = new CGPoint(0.5, 0.6); header1.TextStyle = UIFont.SystemFontOfSize(14); header1.Text = (Foundation.NSString)"Inverted Triangle"; header1.TextColor = UIColor.Black; gauge1.Headers.Add(header1); SFCircularScale scale1 = new SFCircularScale(); scale1.StartAngle = 90; scale1.SweepAngle = 270; scale1.ScaleStartOffset = 0.7f; scale1.ScaleEndOffSet = 0.68f; scale1.StartValue = 0; scale1.EndValue = 100; scale1.RimColor = UIColor.Gray; scale1.Interval = 50; scale1.ShowLabels = false; scale1.ShowTicks = false; scale1.MinorTicksPerInterval = 0; SFMarkerPointer pointer1 = new SFMarkerPointer(); pointer1.Value = 80; pointer1.Offset = 0.7f; pointer1.MarkerShape = MarkerShape.InvertedTriangle; pointer1.Color = UIColor.FromRGB(0, 180, 174); scale1.Pointers.Add(pointer1); gauge1.Scales.Add(scale1); gauge2 = new SFCircularGauge(); SFGaugeHeader header2 = new SFGaugeHeader(); header2.Position = new CGPoint(0.5, 0.6); header2.TextStyle = UIFont.SystemFontOfSize(14); header2.Text = (Foundation.NSString)"Triangle"; header2.TextColor = UIColor.Black; gauge2.Headers.Add(header2); SFCircularScale scale2 = new SFCircularScale(); scale2.StartAngle = 90; scale2.SweepAngle = 270; scale2.ScaleStartOffset = 0.7f; scale2.ScaleEndOffSet = 0.68f; scale2.StartValue = 0; scale2.EndValue = 100; scale2.RimColor = UIColor.Gray; scale2.Interval = 50; scale2.ShowLabels = false; scale2.ShowTicks = false; scale2.MinorTicksPerInterval = 0; SFMarkerPointer pointer2 = new SFMarkerPointer(); pointer2.Value = 80; pointer2.Offset = 0.68f; pointer2.MarkerShape = MarkerShape.Triangle; pointer2.Color = UIColor.Green; scale2.Pointers.Add(pointer2); gauge2.Scales.Add(scale2); gauge3 = new SFCircularGauge(); SFGaugeHeader header3 = new SFGaugeHeader(); header3.Position = new CGPoint(0.5, 0.6); header3.TextStyle = UIFont.SystemFontOfSize(14); header3.Text = (Foundation.NSString)"Range Pointer"; header3.TextColor = UIColor.Black; gauge3.Headers.Add(header3); SFCircularScale scale3 = new SFCircularScale(); scale3.StartAngle = 90; scale3.SweepAngle = 270; scale3.ScaleStartOffset = 0.7f; scale3.ScaleEndOffSet = 0.68f; scale3.StartValue = 0; scale3.EndValue = 100; scale3.RimColor = UIColor.Gray; scale3.Interval = 50; scale3.ShowLabels = false; scale3.ShowTicks = false; scale3.MinorTicksPerInterval = 0; SFRangePointer pointer3 = new SFRangePointer(); pointer3.Value = 60; pointer3.Offset = 0.6f; pointer3.Width = 15; pointer3.Color = UIColor.FromRGB(255, 38, 128); scale3.Pointers.Add(pointer3); gauge3.Scales.Add(scale3); gauge4 = new SFCircularGauge(); SFGaugeHeader header4 = new SFGaugeHeader(); header4.Position = new CGPoint(0.5, 0.7); header4.TextStyle = UIFont.SystemFontOfSize(14); header4.Text = (Foundation.NSString)"Multiple Needle"; header4.TextColor = UIColor.Black; gauge4.Headers.Add(header4); SFCircularScale scale4 = new SFCircularScale(); scale4.StartAngle = 90; scale4.SweepAngle = 270; scale4.ScaleStartOffset = 0.7f; scale4.ScaleEndOffSet = 0.68f; scale4.StartValue = 0; scale4.EndValue = 100; scale4.RimColor = UIColor.Gray; scale4.Interval = 50; scale4.ShowLabels = false; scale4.ShowTicks = false; scale4.MinorTicksPerInterval = 0; SFNeedlePointer pointer4 = new SFNeedlePointer(); pointer4.Value = 80; pointer4.Color = UIColor.Purple; pointer4.LengthFactor = 0.7f; pointer4.KnobRadius = 0; pointer4.Width = 10; pointer4.PointerType = SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle; scale4.Pointers.Add(pointer4); gauge4.Scales.Add(scale4); gauge5 = new SFCircularGauge(); SFGaugeHeader header5 = new SFGaugeHeader(); header5.Position = new CGPoint(0.5, 0.6); header5.TextStyle = UIFont.SystemFontOfSize(14); header5.Text = (Foundation.NSString)"Needle Pointer"; header5.TextColor = UIColor.Black; gauge5.Headers.Add(header5); SFCircularScale scale5 = new SFCircularScale(); scale5.StartAngle = 90; scale5.SweepAngle = 270; scale5.ScaleStartOffset = 0.7f; scale5.ScaleEndOffSet = 0.68f; scale5.StartValue = 0; scale5.EndValue = 100; scale5.RimColor = UIColor.Gray; scale5.Interval = 50; scale5.ShowLabels = false; scale5.ShowTicks = false; scale5.MinorTicksPerInterval = 0; SFNeedlePointer pointer5 = new SFNeedlePointer(); pointer5.Value = 40; pointer5.Color = UIColor.Purple; pointer5.LengthFactor = 0.5f; pointer5.KnobRadiusFactor = 0.05f; pointer5.Width = 10; pointer5.KnobColor = UIColor.White; pointer5.KnobStrokeColor = UIColor.FromRGB(237, 125, 49); pointer5.KnobStrokeWidth = 2f; pointer5.TailLengthFactor = 0.2f; pointer5.TailColor = UIColor.FromRGB(237, 125, 49); pointer5.TailStrokeColor = UIColor.FromRGB(237, 125, 49); pointer5.PointerType = SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle; scale5.Pointers.Add(pointer5); SFNeedlePointer pointer6 = new SFNeedlePointer(); pointer6.Value = 70; pointer6.Color = UIColor.Purple; pointer6.LengthFactor = 0.6f; pointer6.KnobRadiusFactor = 0.05f; pointer6.Width = 10; pointer6.KnobColor = UIColor.White; pointer6.KnobStrokeColor = UIColor.FromRGB(237, 125, 49); pointer6.KnobStrokeWidth = 2f; pointer6.TailLengthFactor = 0.25f; pointer6.TailColor = UIColor.FromRGB(237, 125, 49); pointer6.TailStrokeColor = UIColor.FromRGB(237, 125, 49); pointer6.PointerType = SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle; scale5.Pointers.Add(pointer6); gauge5.Scales.Add(scale5); scroll.AddSubview(gauge1); scroll.AddSubview(gauge2); scroll.AddSubview(gauge3); scroll.AddSubview(gauge4); scroll.AddSubview(gauge5); this.AddSubview(scroll); } protected override void Dispose(bool disposing) { //gauge1.Scales[0].Pointers.Clear(); //gauge1.Scales.Clear(); //gauge1.Dispose(); //gauge2.Scales[0].Pointers.Clear(); //gauge2.Scales.Clear(); //gauge2.Dispose(); //gauge3.Scales[0].Pointers.Clear(); //gauge3.Scales.Clear(); //gauge3.Dispose(); //gauge4.Scales[0].Pointers.Clear(); //gauge4.Scales.Clear(); //gauge4.Dispose(); //gauge5.Scales[0].Pointers.Clear(); //gauge5.Scales.Clear(); //gauge5.Dispose(); base.Dispose(disposing); } } } <file_sep>/Forms/Presentation/Presentation/Samples/CreateAnimation/CreateAnimation.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using SampleBrowser.Core; namespace SampleBrowser.Presentation { public partial class CreateAnimation : SampleView { public CreateAnimation() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Animation.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Animation.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Modify the existing animation CreateAnimationWithShape(presentation); //Save the Presentation to stream MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("CreateAnimationSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("CreateAnimationSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } # region Create Animation private void CreateAnimationWithShape(IPresentation presentation) { //Get the slide from the presentation ISlide slide = presentation.Slides[0]; //Access the animation sequence to create effects ISequence sequence = slide.Timeline.MainSequence; //Add motion path effect to the shape IEffect line1 = sequence.AddEffect(slide.Shapes[8] as IShape, EffectType.PathUp, EffectSubtype.None, EffectTriggerType.OnClick); IMotionEffect motionEffect = line1.Behaviors[0] as IMotionEffect; motionEffect.Timing.Duration = 1f; IMotionPath motionPath = motionEffect.Path; motionPath[1].Points[0].X = 0.00365f; motionPath[1].Points[0].Y = -0.27431f; //Add motion path effect to the shape IEffect line2 = sequence.AddEffect(slide.Shapes[3] as IShape, EffectType.PathDown, EffectSubtype.None, EffectTriggerType.WithPrevious); motionEffect = line2.Behaviors[0] as IMotionEffect; motionEffect.Timing.Duration = 0.75f; motionPath = motionEffect.Path; motionPath[1].Points[0].X = 0.00234f; motionPath[1].Points[0].Y = 0.43449f; //Add wipe effect to the shape IEffect wipe1 = sequence.AddEffect(slide.Shapes[1] as IShape, EffectType.Wipe, EffectSubtype.None, EffectTriggerType.AfterPrevious); wipe1.Behaviors[1].Timing.Duration = 1f; //Add fly effect to the shape IEffect fly1 = sequence.AddEffect(slide.Shapes[5] as IShape, EffectType.Fly, EffectSubtype.Left, EffectTriggerType.AfterPrevious); fly1.Behaviors[1].Timing.Duration = 0.70f; fly1.Behaviors[2].Timing.Duration = 0.70f; ////Add wipe effect to the shape IEffect wipe2 = sequence.AddEffect(slide.Shapes[2] as IShape, EffectType.Wipe, EffectSubtype.None, EffectTriggerType.AfterPrevious); wipe2.Behaviors[1].Timing.Duration = 1f; ////Add fly effect to the shape IEffect fly2 = sequence.AddEffect(slide.Shapes[4] as IShape, EffectType.Fly, EffectSubtype.Right, EffectTriggerType.AfterPrevious); fly2.Behaviors[1].Timing.Duration = 0.70f; fly2.Behaviors[2].Timing.Duration = 0.70f; IEffect fly3 = sequence.AddEffect(slide.Shapes[6] as IShape, EffectType.Fly, EffectSubtype.Top, EffectTriggerType.AfterPrevious); fly3.Behaviors[1].Timing.Duration = 1.50f; fly3.Behaviors[2].Timing.Duration = 1.50f; ////Add flay effect to the shape IEffect fly4 = sequence.AddEffect(slide.Shapes[7] as IShape, EffectType.Fly, EffectSubtype.Left, EffectTriggerType.AfterPrevious); fly4.Behaviors[1].Timing.Duration = 0.50f; fly4.Behaviors[2].Timing.Duration = 0.50f; } #endregion } } <file_sep>/Forms/DataGrid/DataGrid/Samples/CustomGrouping/CustomGroupingBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CustomGroupingBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the CustomGrouping samples /// </summary> public class CustomGroupingBehavior : Behavior<Syncfusion.SfDataGrid.XForms.SfDataGrid> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">dataGrid type of bindAble</param> protected override void OnAttachedTo(Syncfusion.SfDataGrid.XForms.SfDataGrid bindAble) { this.dataGrid = bindAble; this.dataGrid.GroupColumnDescriptions.Add(new GroupColumnDescription() { ColumnName = "Total", KeySelector = (string ColumnName, object o) => { var total = (o as SalesByDate).Total; if (total > 1000 && total < 5000) { return ">1 K and <5 K"; } else if (total > 5000 && total < 10000) { return ">5 K and <10 K"; } else if (total > 10000 && total < 50000) { return ">10 K and <50 K"; } else if (total > 20000 && total < 50000) { return ">20 K and <50 K"; } else if (total > 50000) { return ">50 K"; } else { return "<1 K"; } } }); this.dataGrid.CellRenderers.Remove("CaptionSummary"); this.dataGrid.CellRenderers.Add("CaptionSummary", new GroupCaptionRenderer()); this.dataGrid.CellRenderers.Remove("TableSummary"); this.dataGrid.CellRenderers.Add("TableSummary", new TableSummaryRenderer()); base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">DataGrid type of parameter bindAble</param> protected override void OnDetachingFrom(Syncfusion.SfDataGrid.XForms.SfDataGrid bindAble) { this.dataGrid = null; base.OnDetachingFrom(bindAble); } } } <file_sep>/Forms/Schedule/Schedule/Samples/GettingStarted/ViewModel/ScheduleViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Schedule View Model /// </summary> [Preserve(AllMembers = true)] public class ScheduleViewModel : INotifyPropertyChanged { #region Properties /// <summary> /// team management /// </summary> private List<string> teamManagement; /// <summary> /// current day meetings /// </summary> private List<string> currentDayMeetings; /// <summary> /// minimum time meetings /// </summary> private List<string> minTimeMeetings; /// <summary> /// color collection /// </summary> private List<Color> colorCollection; /// <summary> /// start time collection /// </summary> private List<DateTime> startTimeCollection; /// <summary> /// end time collection /// </summary> private List<DateTime> endTimeCollection; /// <summary> /// work start hour value. /// </summary> private double workStartHour = 8; /// <summary> /// end hour value /// </summary> private double endHour = 16; /// <summary> /// random numbers /// </summary> ////creating random number collection private List<int> randomNums = new List<int>(); #endregion Properties #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ScheduleViewModel" /> class. /// </summary> public ScheduleViewModel() { this.Appointments = new ObservableCollection<Meeting>(); this.CreateRandomNumbersCollection(); this.CreateStartTimeCollection(); this.CreateEndTimeCollection(); this.CreateSubjectCollection(); this.CreateColorCollection(); this.InitializeDataForBookings(); this.IntializeAppoitments(); } #endregion Constructor /// <summary> /// Property changed event handler /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets appointments /// </summary> public ObservableCollection<Meeting> Appointments { get; set; } /// <summary> /// Gets or sets work start hour /// </summary> public double WorkStartHour { get { return this.workStartHour; } set { this.workStartHour = value; this.RaiseOnPropertyChanged("WorkStartHour"); } } /// <summary> /// Gets or sets end hour /// </summary> public double EndHour { get { return this.endHour; } set { this.endHour = value; this.RaiseOnPropertyChanged("EndHour"); } } #region Methods #region GettingTimeRanges /// <summary> /// Method for get timing range. /// </summary> /// <returns>return time collection</returns> private List<Point> GettingTimeRanges() { List<Point> randomTimeCollection = new List<Point>(); randomTimeCollection.Add(new Point(9, 11)); randomTimeCollection.Add(new Point(12, 14)); randomTimeCollection.Add(new Point(15, 17)); return randomTimeCollection; } #endregion GettingTimeRanges #region InitializeDataForBookings /// <summary> /// Method for initialize data bookings. /// </summary> private void InitializeDataForBookings() { this.currentDayMeetings = new List<string>(); this.currentDayMeetings.Add("General Meeting"); this.currentDayMeetings.Add("Plan Execution"); this.currentDayMeetings.Add("Project Plan"); this.currentDayMeetings.Add("Consulting"); this.currentDayMeetings.Add("Performance Check"); this.currentDayMeetings.Add("Yoga Therapy"); this.currentDayMeetings.Add("Plan Execution"); this.currentDayMeetings.Add("Project Plan"); this.currentDayMeetings.Add("Consulting"); this.currentDayMeetings.Add("Performance Check"); // MinimumHeight Appointment Subjects this.minTimeMeetings = new List<string>(); this.minTimeMeetings.Add("Work log alert"); this.minTimeMeetings.Add("Birthday wish alert"); this.minTimeMeetings.Add("Task due date"); this.minTimeMeetings.Add("Status mail"); this.minTimeMeetings.Add("Start sprint alert"); this.colorCollection = new List<Color>(); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); } #endregion InitializeDataForBookings #region InitializeAppointments /// <summary> /// Initialize appointments /// </summary> /// <param name="count">count value</param> private void IntializeAppoitments() { Random randomTime = new Random(); List<Point> randomTimeCollection = this.GettingTimeRanges(); DateTime date; DateTime dateFrom = DateTime.Now.AddDays(-100); DateTime dateTo = DateTime.Now.AddDays(100); var random = new Random(); var dateCount = random.Next(4); DateTime dateRangeStart = DateTime.Now.AddDays(0); DateTime dateRangeEnd = DateTime.Now.AddDays(1); for (date = dateFrom; date < dateTo; date = date.AddDays(1)) { if (date.Day % 7 != 0) { for (int additionalAppointmentIndex = 0; additionalAppointmentIndex < 1; additionalAppointmentIndex++) { Meeting meeting = new Meeting(); int hour = randomTime.Next((int)randomTimeCollection[additionalAppointmentIndex].X, (int)randomTimeCollection[additionalAppointmentIndex].Y); meeting.From = new DateTime(date.Year, date.Month, date.Day, hour, 0, 0); meeting.To = meeting.From.AddHours(1); meeting.EventName = this.currentDayMeetings[randomTime.Next(9)]; meeting.Color = this.colorCollection[randomTime.Next(9)]; meeting.IsAllDay = false; meeting.StartTimeZone = string.Empty; meeting.EndTimeZone = string.Empty; this.Appointments.Add(meeting); } } else { Meeting meeting = new Meeting(); meeting.From = new DateTime(date.Year, date.Month, date.Day, randomTime.Next(9, 11), 0, 0); meeting.To = meeting.From.AddDays(2).AddHours(1); meeting.EventName = this.currentDayMeetings[randomTime.Next(9)]; meeting.Color = this.colorCollection[randomTime.Next(9)]; meeting.IsAllDay = true; meeting.StartTimeZone = string.Empty; meeting.EndTimeZone = string.Empty; this.Appointments.Add(meeting); } } // Minimum Height Meetings DateTime minDate; DateTime minDateFrom = DateTime.Now.AddDays(-2); DateTime minDateTo = DateTime.Now.AddDays(2); for (minDate = minDateFrom; minDate < minDateTo; minDate = minDate.AddDays(1)) { Meeting meeting = new Meeting(); meeting.From = new DateTime(minDate.Year, minDate.Month, minDate.Day, randomTime.Next(9, 18), 30, 0); meeting.To = meeting.From; meeting.EventName = this.minTimeMeetings[randomTime.Next(0, 4)]; meeting.Color = this.colorCollection[randomTime.Next(0, 10)]; meeting.StartTimeZone = string.Empty; meeting.EndTimeZone = string.Empty; // Setting Mininmum Appointment Height for Schedule Appointments if (Device.RuntimePlatform == "Android") { meeting.MinimumHeight = 50; } else { meeting.MinimumHeight = 25; } this.Appointments.Add(meeting); } } #endregion InitializeAppointments #region SubjectCollection /// <summary> /// Subject collection /// </summary> ////creating subject collection private void CreateSubjectCollection() { this.teamManagement = new List<string>(); this.teamManagement.Add("General Meeting"); this.teamManagement.Add("Plan Execution"); this.teamManagement.Add("Project Plan"); this.teamManagement.Add("Consulting"); this.teamManagement.Add("Performance Check"); this.teamManagement.Add("General Meeting"); this.teamManagement.Add("Plan Execution"); this.teamManagement.Add("Project Plan"); this.teamManagement.Add("Consulting"); this.teamManagement.Add("Performance Check"); } #endregion SubjectCollection #region creating color collection /// <summary> /// color collection /// </summary> ////creating color collection private void CreateColorCollection() { this.colorCollection = new List<Color>(); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FFF09609")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); } #endregion creating color collection #region CreateRandomNumbersCollection /// <summary> /// random numbers collection /// </summary> private void CreateRandomNumbersCollection() { this.randomNums = new List<int>(); Random rand = new Random(); for (int i = 0; i < 10; i++) { int random = rand.Next(9, 15); this.randomNums.Add(random); } } #endregion CreateRandomNumbersCollection #region CreateStartTimeCollection /// <summary> /// start time collection /// </summary> //// creating StartTime collection private void CreateStartTimeCollection() { this.startTimeCollection = new List<DateTime>(); DateTime currentDate = DateTime.Now; int count = 0; for (int i = -5; i < 5; i++) { DateTime startTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, this.randomNums[count], 0, 0); DateTime startDateTime = startTime.AddDays(i); this.startTimeCollection.Add(startDateTime); count++; } } #endregion CreateStartTimeCollection #region CreateEndTimeCollection /// <summary> /// end time collection /// </summary> //// creating EndTime collection private void CreateEndTimeCollection() { this.endTimeCollection = new List<DateTime>(); DateTime currentDate = DateTime.Now; int count = 0; for (int i = -5; i < 5; i++) { DateTime endTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, this.randomNums[count] + 1, 0, 0); DateTime endDateTime = endTime.AddDays(i); if (i == -3 || i == 3) { endDateTime = endTime.AddDays(i).AddHours(22); } this.endTimeCollection.Add(endDateTime); count++; } } #endregion CreateEndTimeCollection #endregion Methods /// <summary> /// Invoke method when property changed /// </summary> /// <param name="propertyName">property name</param> private void RaiseOnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }<file_sep>/Forms/Maps/Maps/Samples/ColorMappings/ColorMappingsModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] public class AgricultureData { public AgricultureData(string name, string type, int count) { Name = name; Type = type; index = count; } public string Name { get; set; } public string Type { get; set; } public int index { get; set; } } } <file_sep>/iOS/SampleBrowser/Samples/Chart/Doughnut.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Doughnut : SampleView { public Doughnut () { SFChart chart = new SFChart (); chart.Title.Text = new NSString ("Project Cost Breakdown"); chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; chart.Legend.OverflowMode = ChartLegendOverflowMode.Wrap; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Delegate = new CenterViewUpdater(); chart.AddChartBehavior(new SFChartSelectionBehavior()); ChartViewModel dataModel = new ChartViewModel (); SFDoughnutSeries series = new SFDoughnutSeries(); series.StrokeColor = UIColor.White; series.ItemsSource = dataModel.DoughnutSeriesData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.DataMarker.ShowLabel = true; series.ExplodeOnTouch = true; series.DataMarker.LabelContent = SFChartLabelContent.Percentage; series.EnableAnimation = true; series.ColorModel.Palette = SFChartColorPalette.Natural; var centerView= new UIView(); centerView.Frame = new CGRect(chart.Frame.X / 2, chart.Frame.Y / 2, 100, 40); UILabel xLabel = new UILabel(); xLabel.Text = "Tap on slice"; xLabel.Font = UIFont.FromName("Helvetica", 12f); xLabel.TextAlignment = UITextAlignment.Center; xLabel.Frame = new CGRect(5, centerView.Frame.Y, centerView.Frame.Width, centerView.Frame.Height); UILabel yLabel = new UILabel(); yLabel.TextAlignment = UITextAlignment.Center; centerView.AddSubview(xLabel); centerView.AddSubview(yLabel); series.CenterView = centerView; series.EnableDataPointSelection = true; chart.Series.Add(series); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } class CenterViewUpdater : SFChartDelegate { public override void WillDataPointSelect(SFChart chart, SFChartSelectionChangingInfo info) { var doughnutSeries = info.SelectedSeries as SFDoughnutSeries; var xlabel = doughnutSeries.CenterView.Subviews[0] as UILabel; var ylabel = doughnutSeries.CenterView.Subviews[1] as UILabel; if (doughnutSeries.ExplodeIndex >= 0) { var datapoints = doughnutSeries.ItemsSource as ObservableCollection<ChartDataModel>; xlabel.Text = datapoints[doughnutSeries.ExplodeIndex].XValue.ToString(); ylabel.Text = datapoints[doughnutSeries.ExplodeIndex].YValue + "M"; var segments = doughnutSeries.Segments; xlabel.TextColor = segments[doughnutSeries.ExplodeIndex].Color; xlabel.Font = UIFont.FromName("Helvetica", 12f); xlabel.Frame = new CGRect(0, 0, doughnutSeries.CenterView.Frame.Width, doughnutSeries.CenterView.Frame.Height / 2); xlabel.TextAlignment = UITextAlignment.Center; ylabel.Font = UIFont.FromName("Helvetica", 10f); ylabel.Frame = new CGRect(0, doughnutSeries.CenterView.Frame.Height / 2, doughnutSeries.CenterView.Frame.Width, doughnutSeries.CenterView.Frame.Height / 2); ylabel.TextAlignment = UITextAlignment.Center; doughnutSeries.SelectedDataPointColor = segments[doughnutSeries.ExplodeIndex].Color; } else { xlabel.Text = "Tap on slice"; xlabel.Font = UIFont.FromName("Helvetica", 12f); xlabel.TextColor = UIColor.Black; xlabel.Frame = new CGRect(0, 0, doughnutSeries.CenterView.Frame.Width, doughnutSeries.CenterView.Frame.Height); ylabel.Text = string.Empty; } } } }<file_sep>/Android/SampleBrowser/Samples/Chart/readme.md The chart control can plot more than 25 chart types, ranging from line charts to specialized financial charts. Its rich feature set includes functionalities like data binding, multiple axes, legends, animations, data labels, annotations, trackballs, tooltips, and zooming. The following samples are available for chart to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Line Chart](Series/Line.cs)| This sample demonstrates how to create a line chart and customize its appearance with built-in color palette. | | [Step Line Chart](Series/StepLine.cs)| This sample demonstrates how to create a step line chart and customize its appearance with built-in color palette. | | [Bar Chart](Series/Bar.cs)| This sample demonstrates how to create a simple bar chart and customize its appearance with built-in color palette. | | [Area Chart](Series/Area.cs) | This sample demonstrates how to create an area chart and customize its appearance with built-in color palette. | | [Spline Chart](Series/Spline.cs) | This sample demonstrates how to create a spline chart with data point markers and customize its appearance with built-in color palette. | | [Column Chart](Series/Column.cs) | This sample demonstrates how to create a column chart with data labels and customize its appearance with built-in color palette. | | [Step Area Chart](Series/StepArea.cs)| This sample demonstrates how to create a step area chart and customize its appearance with built-in color palette. | | [Spline Area Chart](Series/SplineArea.cs)| This sample demonstrates how to create a spline area chart and customize its appearance with built-in color palette. | | [Pie Chart](Series/PieSeries.cs)| This sample demonstrates how to create a simple pie chart with data labels, configuration of [segments grouping] (https://help.syncfusion.com/xamarin/sfchart/charttypes#group-small-data-points-into-others), and [exploding segments on touch] (https://help.syncfusion.com/xamarin/sfchart/charttypes#exploding-a-pie-segment) features. | | [Semi Pie Chart](Series/SemiPie.cs)| This sample demonstrates how to configure the start and end angles in a pie chart to render data points using semi pie. | | [Doughnut Chart](Series/Doughnut.cs)| This sample demonstrates how to create a simple doughnut chart with data labels, configuration of [center view] (https://help.syncfusion.com/xamarin/sfchart/charttypes#add-view-to-the-center-of-doughnut-chart), and [exploding segments on touch] (https://help.syncfusion.com/xamarin/sfchart/charttypes#exploding-a-doughnut-segment) features. | | [Semi Doughnut Chart](Series/SemiDoughnut.cs)| This sample demonstrates how to configure the start and end angles in a doughnut chart to render data points using semi doughnut. | | [Pyramid Chart](Series/Pyramid.cs)| This sample demonstrates how to configure a pyramid chart and customize its appearance with built-in color palette. | | [Funnel Chart](Series/Funnel.cs)| This sample demonstrates how to configure a funnel chart with data labels and customize its appearance with built-in color palette. | | [Bubble Chart](Series/Bubble.cs)| This sample demonstrates how to configure a bubble chart and customize its tooltip with data template to show all the required values from the underlying object. | | [Scatter Chart](Series/Scatter.cs)| This sample demonstrates how to configure a scatter chart with different shapes. | | [Range Column Chart](Series/RangeColumn.cs)| This sample demonstrates how to configure a range column chart and customize its appearance with built-in color palette. | | [Range Area Chart](Series/RangeArea.cs)| This sample demonstrates how to configure a range area chart and customize its appearance with built-in color palette. | | [Spline Range Area](Series/SplineRangeArea.cs)| This sample demonstrates how to configure a spline range area chart and customize its appearance with built-in color palette. | | [Candle Chart](Series/Candle.cs)| This sample demonstrates how to configure a candle chart. | | [OHLC Chart](Series/OHLC.cs)| | This sample demonstrates how to configure an OHLC chart. | | [Polar Chart](Series/Polar.cs)| This sample demonstrates how to configure a polar chart and its start angle. | | [Radar Chart](Series/Radar.cs)| This sample demonstrates how to configure a radar chart and its start angle. | | [Stacked Column Chart](Series/StackingColumn.cs)| This sample demonstrates how to configure a stacked column chart and customize its appearance with built-in color palette. | | [100% Stacked Column Chart](Series/StackingColumn100.cs)| This sample demonstrates how to configure a 100% stacked column chart and customize its appearance with built-in color palette. | | [Stacked Bar Chart](Series/StackingBar.cs)| This sample demonstrates how to configure a stacked bar chart and customize its appearance with built-in color palette. | | [100% Stacked Bar Chart](Series/StackingBar100.cs)| This sample demonstrates how to configure a 100% stacked bar chart and customize its appearance with built-in color palette. | | [Stacked Area Chart](Series/StackingArea.cs)| This sample demonstrates how to configure a stacked area chart and customize its appearance with built-in color palette. | | [100% Stacked Area Chart](Series/StackingArea100.cs)| This sample demonstrates how to configure a 100% stacked area chart and customize its appearance with built-in color palette. | | [Category Axis](Series/Category.cs)| This sample demonstrates how to configure the category axis and its label placement. Category axis is an indexed based axis that plots values based on its index in data source. | | [Numeric Axis](Series/Numerical.cs)| This sample demonstrates how to configure numerical axis and its minimum, maximum, and interval values. It is used to plot numerical data in a chart. | | [Logarithmic Axis](Series/Logarithmic.cs)| This sample demonstrates how to configure logarithmic axis. It is used to plot the log value in a chart. | | [Date Time Axis](Series/Date.cs)| This sample demonstrates how to configure date-time axes and format labels to show the first label of a month with name and number, and consecutive labels with number. | | [Multiple Axes](Series/MultipleAxis.cs)| This sample demonstrates how to configure multiple axes in a single chart and position them on either side of a chart. | | [Axis Crossing](Series/AxisCrossing.cs)| This sample demonstrates how to position x-axis and y axis relative to each other. | | [Trackball](Series/Trackball.cs)|This sample demonstrates how to enable the trackball and customize its labels with data template. The trackball displays labels for the data points that are closer to the point where you touch and hold on the chart area. | | [Zooming And Panning](Series/ZoomingAndPanning.cs)| This sample demonstrates how to configure zooming and panning behaviors in a chart. | | [Tooltip](Series/TooltipCustomization.cs)| This sample demonstrates how to configure a tooltip and customize its appearance with data template. | | [DataPoint Selection](Series/DataPointSelection.cs)| This sample demonstrates how to configure selection behavior in a chart and update other views in the same page based on the selection. | | [Gradient Chart](Series/GradientChart.cs)| This sample demonstrates how to apply gradient to area series. | | [Annotations](Series/AnnotationCustomization.cs)| This sample demonstrates how to configure different types of annotations in a chart. | | [Live Update](Series/LiveUpdate.cs)| This sample demonstrates how to add and remove data at run time. | | [StripLines](Series/StripLines.cs)| This sample demonstrates how to use strip lines to highlight different regions and set the labels for each region in a chart. | | [Vertical Chart](Series/VerticalChart.cs)| This sample demonstrates how to transpose the rendering of a chart. Rotate all the series types to plot data in a vertical direction and view the data from a different perspective. | | [DataMarker Customization](Series/DataMarkerCustomization.cs)| This sample demonstrates how to enable data markers and customize the labels with data template. | | [AutoScrolling](Series/AutoScrolling.cs)| This sample demonstrates how to enable the auto scrolling feature in a chart. The auto scrolling feature is used to focus on a minimal set of data points by visualizing only a few items in the UI and viewing the remaining data points by scrolling. | | [Technical Indicator](Series/TechnicalIndicators.cs)| This sample demonstrates how to configure technical indicators. The available technical indicators are RSI, momentum, Bollinger bands, accumulation distribution, EMA, SMA, stochastic, ATR, MACD, and TMA. |<file_sep>/Android/SampleBrowser/Samples/DataForm/Helpers/ListViewAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Collections.ObjectModel; namespace SampleBrowser { /// <summary> /// Represents a class that used as data source for list view. /// </summary> public class ListViewCustomAdapter : BaseAdapter { internal ObservableCollection<ContactsInfo> ContactList { get; set; } private Activity context; public override int Count { get { return ContactList.Count; } } public ListViewCustomAdapter(Activity activity) { context = activity; ContactList = new ListViewGroupingViewModel().ContactsInfo; } public override Java.Lang.Object GetItem(int position) { return null; } public override long GetItemId(int position) { return position; } public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent) { Android.Views.View view = convertView; var item = ContactList[position]; //// no view to re-use, create new if (view == null) { view = context.LayoutInflater.Inflate(Resource.Layout.ListViewRowLayout, null); } view.FindViewById<TextView>(Resource.Id.Text1).Text = item.ContactName; view.FindViewById<ImageView>(Resource.Id.Image).SetImageResource(item.ContactImage); return view; } } }<file_sep>/Forms/Chips/readme.md The `Chips` control allows the users to enter information, make selections, filter content, or trigger actions. Chips should appear dynamically as a group of multiple interactive elements | Sample | Description | | ------ | ----------- | |[Getting Started](Chip/Samples/ChipTypes)|It demonstrates the available chip group types.| |[Customization](Chip/Samples/GettingStarted)|It demonstrates the basic functionalities of Chip,custom arrangement of Icon,close button and selectionIndicator.| <file_sep>/Forms/DataGrid/DataGrid.Android/DataGridDependencyService.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DataGridDependencyService.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Content.Res; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using SampleBrowser.SfDataGrid.Droid; using Xamarin.Forms; [assembly: Dependency(typeof(DataGridDependencyService))] namespace SampleBrowser.SfDataGrid.Droid { /// <summary> /// A dependency Service for DataGrid Samples. /// </summary> internal class DataGridDependencyService : IDataGridDependencyService { /// <summary> /// Used to get the device orientation in Android platform /// </summary> /// <returns>System Configuration Orientation in string value</returns> public string GetOrientation() { return Resources.System.Configuration.Orientation.ToString(); } } }<file_sep>/Forms/TreeMap/TreeMap/Samples/TreeMapGettingStarted/TreeMapGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfTreeMap.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfTreeMap { [Preserve(AllMembers = true)] //[XamlCompilation(XamlCompilationOptions.Compile)] public partial class TreeMapGettingStarted : SampleView { public static bool IsDarkTheme = false; ToolbarItem baritem; LayoutTypes layoutType = LayoutTypes.Squarified; Label label3, label4, label5, label6, label9; double groupPadding = 4; RangeColorMapping rangeMapping; DesaturationColorMapping desaturationMapping; UniColorMapping uniMapping; PaletteColorMapping paletteMapping; Syncfusion.SfTreeMap.XForms.ColorMapping treeMapColorMapping; Picker picker1, picker2; Xamarin.Forms.Slider toggleButton, toggleButton2; public TreeMapGettingStarted() { InitializeComponent(); baritem = new ToolbarItem(); this.BindingContext = this; ObservableCollection<Range> ranges = new ObservableCollection<Range>(); ranges.Add(new Range() { LegendLabel = "1 % Growth", From = 0, To = 1, Color = Color.FromHex("#77D8D8") }); ranges.Add(new Range() { LegendLabel = "2 % Growth", From = 0, To = 2, Color = Color.FromHex("#AED960") }); ranges.Add(new Range() { LegendLabel = "3 % Growth", From = 0, To = 3, Color = Color.FromHex("#FFAF51") }); ranges.Add(new Range() { LegendLabel = "4 % Growth", From = 0, To = 4, Color = Color.FromHex("#F3D240") }); this.TreeMap.LeafItemColorMapping = rangeMapping = new RangeColorMapping() { Ranges = ranges }; treeMapColorMapping = rangeMapping; desaturationMapping = new DesaturationColorMapping() { From = 1, To = 0.2, Color = Color.FromHex("#02AEDC") }; this.TreeMap.DataSource = new PopulationViewModel().PopulationDetails; uniMapping = new UniColorMapping() { Color = Color.FromHex("#D21243") }; paletteMapping = new PaletteColorMapping(); paletteMapping.Colors.Add(Color.FromHex("#BD8EC2")); paletteMapping.Colors.Add(Color.FromHex("#FFD34E")); paletteMapping.Colors.Add(Color.FromHex("#55B949")); paletteMapping.Colors.Add(Color.FromHex("#00B2DA")); paletteMapping.Colors.Add(Color.FromHex("#744A94")); paletteMapping.Colors.Add(Color.FromHex("#A1A616")); paletteMapping.Colors.Add(Color.FromHex("#0753A1")); DrawOptionsPage(); baritem.Clicked += buttonClicked; this.PropertyView = GetOptionPage(); toggleButton.Value = groupPadding; } private void DrawOptionsPage() { toggleButton = new Xamarin.Forms.Slider(); toggleButton.MinimumTrackColor = Color.FromHex("#177CE7"); toggleButton.MaximumTrackColor = Color.DarkGray; toggleButton.ThumbColor = Color.FromHex("#1a1aff"); toggleButton.Value = 2; toggleButton2 = new Xamarin.Forms.Slider(); toggleButton2.Value = 2; toggleButton.Maximum = 20; toggleButton2.Maximum = 20; toggleButton2.ValueChanged += (object sender, ValueChangedEventArgs e) => { //groupGap = e.NewValue; }; toggleButton.ValueChanged += (object sender, ValueChangedEventArgs e) => { groupPadding = e.NewValue; ApplyChanges(); }; picker1 = new Picker(); picker2 = new Picker(); picker1.Items.Add("Squarified"); picker1.Items.Add("Slice And Dice Horizontal"); picker1.Items.Add("Slice And Dice Vertical"); picker1.Items.Add("Slice And Dice Auto"); picker1.HeightRequest = 40; picker1.SelectedIndex = 0; picker1.SelectedIndexChanged += picker1_SelectedIndexChanged; picker2.Items.Add("RangeColorMapping"); picker2.Items.Add("DesaturationColorMapping"); picker2.Items.Add("UniColorMapping"); picker2.Items.Add("PaletteColorMapping"); picker2.HeightRequest = 40; picker2.SelectedIndex = 0; picker2.SelectedIndexChanged += picker2_SelectedIndexChanged; label6 = new Label() { Text = " " + "Settings", FontSize = 60, HeightRequest = 60, VerticalTextAlignment = TextAlignment.End, }; label3 = new Label() { Text = "Layout Type", HeightRequest = 20, VerticalTextAlignment = TextAlignment.End, }; label4 = new Label() { Text = "Color Mapping", HeightRequest = 20, VerticalTextAlignment = TextAlignment.End, }; label5 = new Label() { Text = "Group Padding", HeightRequest = 30, VerticalTextAlignment = TextAlignment.Center, }; label9 = new Label() { Text = "Group Gap", HeightRequest = 20, VerticalTextAlignment = TextAlignment.Center, }; if (Device.RuntimePlatform == Device.Android) { picker1.BackgroundColor = Color.FromRgb(239, 239, 239); picker2.BackgroundColor = Color.FromRgb(239, 239, 239); label3.FontSize = 20; label4.FontSize = 20; label5.FontSize = 20; } //label10.WidthRequest = tree.Width; //label11.WidthRequest = tree.Width; label5.WidthRequest = label9.Width; if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { label5.WidthRequest = 150; label9.WidthRequest = 150; picker1.HeightRequest = 60; picker2.HeightRequest = 60; FileImageSource images = new FileImageSource(); images.File = "options.png"; baritem.IconImageSource = images; label3.Text = " " + "Layout Type"; label3.HeightRequest = 22; label4.Text = " " + "Color Mapping"; label4.HeightRequest = 22; label5.Text = " " + "Group Padding"; label5.HeightRequest = 22; label9.TextColor = Color.White; } if (Device.RuntimePlatform == Device.iOS) { picker1.HeightRequest = 0; label3.Text = ""; } } private StackLayout GetOptionPage() { // toggleButton.WidthRequest = picker1.Width - label5.Width; // toggleButton2.WidthRequest = picker1.Width - label9.Width; toggleButton.HorizontalOptions = LayoutOptions.Fill; toggleButton2.HorizontalOptions = LayoutOptions.Fill; var layoutpage = new StackLayout { Spacing = 10, Orientation = StackOrientation.Vertical, //Padding = Device.OnPlatform(iOS: 10, Android : 10, WinPhone : 50), Children = { label5, toggleButton } }; // var togglepage = new StackLayout // { // Spacing = 10, // Orientation = StackOrientation.Vertical, // //Padding = Device.OnPlatform(iOS: 10, Android : 10, WinPhone : 50), // Children = { label9, toggleButton2 } // }; var page1 = new StackLayout { Spacing = 10, Orientation = StackOrientation.Vertical, //Padding = Device.OnPlatform(iOS: 10, Android : 10, WinPhone : 50), Children = { label3, picker1 } }; var page2 = new StackLayout { Spacing = 10, Orientation = StackOrientation.Vertical, //Padding = Device.OnPlatform(iOS: 10, Android : 10, WinPhone : 50), Children = { label4, picker2 } }; var page3 = new StackLayout { Spacing = 40, Orientation = StackOrientation.Vertical, //Padding = Device.OnPlatform(iOS: 10, Android: 10, WinPhone: 10), Children = { page1, page2 } }; var page = new StackLayout { Spacing = 40, Orientation = StackOrientation.Vertical, Padding = 10, Children = { page3, layoutpage } }; var page4 = new StackLayout { Spacing = 40, Orientation = StackOrientation.Vertical, //Padding = Device.OnPlatform(iOS: 10, Android: 10, WinPhone: 10), Children = { label6, page } }; if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { page.Spacing = 25; FileImageSource images = new FileImageSource(); images.File = "options.png"; baritem.IconImageSource = images; return page4; } return page; } void buttonClicked(object sender, EventArgs e) { if (baritem.Text == "Options") { Content = GetOptionPage(); baritem.Text = "Done"; } else { baritem.Text = "Options"; ApplyChanges(); Content = this.TreeMap; } } void ApplyChanges() { if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { FileImageSource images = new FileImageSource(); images.File = "options.png"; baritem.IconImageSource = images; } if (!(treeMapColorMapping is RangeColorMapping)) { this.TreeMap.LegendSettings.ShowLegend = false; } else { this.TreeMap.LegendSettings.ShowLegend = true; ; } this.TreeMap.LayoutType = layoutType; this.TreeMap.LeafItemColorMapping = treeMapColorMapping; (this.TreeMap.Levels[0] as TreeMapFlatLevel).GroupPadding = groupPadding; this.TreeMap.Refresh(); } void picker1_SelectedIndexChanged(object sender, EventArgs e) { switch (picker1.SelectedIndex) { case 0: { layoutType = LayoutTypes.Squarified; break; } case 1: { layoutType = LayoutTypes.SliceAndDiceHorizontal; break; } case 2: { layoutType = LayoutTypes.SliceAndDiceVertical; break; } case 3: { layoutType = LayoutTypes.SliceAndDiceAuto; break; } } ApplyChanges(); } void picker2_SelectedIndexChanged(object sender, EventArgs e) { switch (picker2.SelectedIndex) { case 0: { treeMapColorMapping = rangeMapping; break; } case 1: { treeMapColorMapping = desaturationMapping; break; } case 2: { treeMapColorMapping = uniMapping; break; } case 3: { treeMapColorMapping = paletteMapping; break; } } ApplyChanges(); } //protected override bool OnBackButtonPressed() //{ // Content = this.TreeMap; // return base.OnBackButtonPressed(); //} } } <file_sep>/Forms/XlsIO/XlsIO/Samples/WorksheetToImagePage/WorksheetToImagePage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using SampleBrowser.Core; using Syncfusion.XlsIO; using Syncfusion.XlsIORenderer; using Xamarin.Forms; using LayoutOptions = Xamarin.Forms.LayoutOptions; namespace SampleBrowser.XlsIO { /// <summary> /// This class is the conversion of a simple Excel document to an image. /// </summary> public partial class WorksheetToImagePage : SampleView { public WorksheetToImagePage() { InitializeComponent(); this.pngButton.IsChecked = true; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.btnGenerate.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.btnInput.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Content_1.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnInput.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInput.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; } this.Content_1.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnInput.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; } } internal void OnButtonClicked(object sender, EventArgs e) { //XlsIORenderer renderer = new XlsIORenderer(); ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; #if COMMONSB Stream stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ExpenseReport.xlsx"); #else Stream stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ExpenseReport.xlsx"); #endif IWorkbook workbook = application.Workbooks.Open(stream); IWorksheet worksheet = workbook.Worksheets[0]; application.XlsIORenderer = new XlsIORenderer(); MemoryStream image = new MemoryStream(); ExportImageOptions imageOptions = new ExportImageOptions(); string fileName = null; string contentType = null; if (this.jpegButton.IsChecked != null && (bool)this.jpegButton.IsChecked) { imageOptions.ImageFormat = ExportImageFormat.Jpeg; fileName = "Image.jpeg"; contentType = "image/jpeg"; } else { imageOptions.ImageFormat = ExportImageFormat.Png; fileName = "Image.png"; contentType = "image/png"; } //Convert to image worksheet.ConvertToImage(worksheet.UsedRange, imageOptions, image); image.Position = 0; if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save(fileName, contentType, image); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save(fileName, contentType, image); } } internal void OnInputButtonClicked(object sender, EventArgs e) { //Load Input Template to memory stream. #if COMMONSB Stream file = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ExpenseReport.xlsx"); #else Stream file = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ExpenseReport.xlsx"); #endif file.Position = 0; MemoryStream stream = new MemoryStream(); file.CopyTo(stream); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.xlsx", "application/msexcel", stream); } } } } <file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/StampAnnotationView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using CoreGraphics; namespace SampleBrowser { internal class StampAnnotationView : UIView { UIButton backButton; UIView titleBar, parent, transparentView, bottomBar; UILabel title; UIButton approved, notApproved, expired, confidential, draft; UIButton closeButton; CustomToolbar mainView; internal StampAnnotationView(CustomToolbar customToolbar) { parent = new UIView(); transparentView = new UIView(); mainView = customToolbar; titleBar = new UIView(); backButton = new UIButton(); backButton.SetTitle("\ue71b", UIControlState.Normal); backButton.Font = mainView.highFont; backButton.SetTitleColor(UIColor.DarkGray, UIControlState.Normal); titleBar.AddSubview(backButton); backButton.TouchUpInside += BackButton_TouchUpInside; title = new UILabel(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { title.TextAlignment = UITextAlignment.Right; title.Text = "CHOOSE STAMP"; title.TextColor = UIColor.FromRGB(0, 118, 255); } else { title.TextAlignment = UITextAlignment.Center; title.Text = "Choose Stamp"; title.TextColor = UIColor.Black; } titleBar.AddSubview(title); titleBar.BackgroundColor = UIColor.FromRGB(249, 249, 249); parent.AddSubview(titleBar); UIImage imageApproved = UIImage.FromBundle("Approved.png"); UIImage imageNotApproved = UIImage.FromBundle("NotApproved.png"); UIImage imageDraft = UIImage.FromBundle("Draft.png"); UIImage imageConfidential = UIImage.FromBundle("Confidential.png"); UIImage imageExpired = UIImage.FromBundle("Expired.png"); approved = new UIButton(); approved.SetImage(imageApproved, UIControlState.Normal); approved.TouchUpInside += Stamp_TouchUpInside; parent.AddSubview(approved); notApproved = new UIButton(); notApproved.SetImage(imageNotApproved, UIControlState.Normal); notApproved.TouchUpInside += Stamp_TouchUpInside; parent.AddSubview(notApproved); draft = new UIButton(); draft.SetImage(imageDraft, UIControlState.Normal); draft.TouchUpInside += Stamp_TouchUpInside; parent.AddSubview(draft); confidential = new UIButton(); confidential.SetImage(imageConfidential, UIControlState.Normal); confidential.TouchUpInside += Stamp_TouchUpInside; parent.AddSubview(confidential); expired = new UIButton(); expired.SetImage(imageExpired, UIControlState.Normal); expired.TouchUpInside += Stamp_TouchUpInside; parent.AddSubview(expired); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { transparentView.BackgroundColor = UIColor.Black; transparentView.Alpha = 0.5f; AddSubview(transparentView); } AddSubview(parent); bottomBar = new UIView(); bottomBar.BackgroundColor = UIColor.FromRGB(249, 249, 249); parent.AddSubview(bottomBar); closeButton = new UIButton(); closeButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); closeButton.SetTitle("Close", UIControlState.Normal); closeButton.Font = UIFont.SystemFontOfSize(16); bottomBar.AddSubview(closeButton); closeButton.TouchUpInside += CloseButton_TouchUpInside; parent.BackgroundColor = UIColor.White; } private void BackButton_TouchUpInside(object sender, EventArgs e) { Hide(); } private void CloseButton_TouchUpInside(object sender, EventArgs e) { Hide(); } private void Hide() { RemoveFromSuperview(); mainView.isStampViewVisible = false; } private void Stamp_TouchUpInside(object sender, EventArgs e) { UIButton button = sender as UIButton; UIImage image = null; if (button == approved) image = UIImage.FromBundle("Approved.png"); else if (button == notApproved) image = UIImage.FromBundle("NotApproved.png"); else if (button == draft) image = UIImage.FromBundle("Draft.png"); else if (button == expired) image = UIImage.FromBundle("Expired.png"); else if (button == confidential) image = UIImage.FromBundle("Confidential.png"); UIImageView customStamp = new UIImageView(); customStamp.Image = image; customStamp.Frame = new CGRect(200, 200, 200, 50); mainView.pdfViewerControl.AddStamp(customStamp, new CGPoint(220, 300), mainView.pdfViewerControl.PageNumber); Hide(); } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { transparentView.Frame = Frame; nfloat width = 500, height = 400; nfloat left = (Frame.Width - width) / 2; nfloat top = (Frame.Height - height) / 2; parent.Frame = new CGRect(left, top, width, height); titleBar.Frame = new CGRect(0, 0, parent.Frame.Width, 50); title.Frame = new CGRect(0, 0, parent.Frame.Width, 50); bottomBar.Frame = new CGRect(0, parent.Frame.Height - 50, parent.Frame.Width, 50); closeButton.Frame = new CGRect(420, 0, parent.Frame.Width - 420, 50); nfloat gap = 20, stampWidth = 200, stampHeight = 60; approved.Frame = new CGRect(40, 70, stampWidth, stampHeight); confidential.Frame = new CGRect(260, 70, stampWidth, stampHeight); draft.Frame = new CGRect(40, 70 + stampHeight + gap, stampWidth, stampHeight); expired.Frame = new CGRect(260, 70 + stampHeight + gap, stampWidth, stampHeight); notApproved.Frame = new CGRect(40, 70 + 2*(stampHeight + gap), stampWidth, stampHeight); } else { parent.Frame = Frame; titleBar.Frame = new CGRect(0, 0, Frame.Width, 50); backButton.Frame = new CGRect(0, 0, 50, 50); title.Frame = new CGRect(50, 0, Frame.Width - 80, 50); nfloat left = (Frame.Width - 100 - 100 - 30) / 2; approved.Frame = new CGRect(left, 70, 100, 30); confidential.Frame = new CGRect(left + 130, 70, 100, 30); draft.Frame = new CGRect(left, 120, 100, 30); expired.Frame = new CGRect(left + 130, 120, 100, 30); notApproved.Frame = new CGRect(left, 170, 100, 30); } base.LayoutSubviews(); } } }<file_sep>/Android/SampleBrowser/Samples/Rating/Rating_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Util; using System; using System.Collections.Generic; using Android.Content; using Android.Views; using Android.Widget; using Com.Syncfusion.Rating; using Android.Content.Res; using Android.Graphics; namespace SampleBrowser { public class Rating_Mobile { /********************************* **Local Varabile Inizialization** *********************************/ TextView title, movieLabel, time, description, dummyLabel2, dummyLabel, ratingLable, showLable; LinearLayout pageLayout, columnLayout, imageLayout, contentLayout, padLayout; LinearLayout textLayout, timeLayout, valueLayout, ratingLayout; LinearLayout descriptionLayout, propertylayout, countStack; TooltipPlacement toolTipPosition = TooltipPlacement.None; ArrayAdapter<String> precisionAdapter, placementAdapter; SfRatingSettings sfRatingSettings, sfRatingSetings1; Precision precisionPosition = Precision.Standard; LinearLayout.LayoutParams layoutParams; Spinner precisionSpinner, toolTipSpinner; int constCount = 5, height, width; SfRating sfRating, sfRating1; EditText itemCountEntry; ImageView imageView; Context context; public View GetSampleContent(Context con) { height = con.Resources.DisplayMetrics.HeightPixels / 2; width = con.Resources.DisplayMetrics.WidthPixels / 2; SamplePageContent(con); /************* **SfRating1** *************/ sfRatingSettings = new SfRatingSettings(); sfRating1 = new SfRating(con); sfRating1.ItemSize = 17; sfRating1.Precision = Precision.Exact; sfRating1.Value = 3.5; sfRating1.ReadOnly = true; sfRating1.ItemSpacing = 0; sfRating1.TooltipPlacement = TooltipPlacement.None; sfRatingSettings.RatedFill = Color.ParseColor("#fbd10a"); sfRatingSettings.UnRatedFill = Color.ParseColor("#cdcccb"); sfRatingSettings.RatedStrokeWidth = 0; sfRatingSettings.UnRatedStrokeWidth = 0; sfRating1.RatingSettings = sfRatingSettings; sfRating1.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent ,(int)(20 * con.Resources.DisplayMetrics.Density)); /************ **SfRating** ************/ sfRatingSetings1 = new SfRatingSettings(); sfRatingSetings1.RatedStroke = Color.ParseColor("#2095f2"); sfRating = new SfRating(con); sfRating.ItemSize = 40; sfRating.ItemSpacing = 20; sfRating.ItemCount = 5; sfRating.TooltipPrecision = 1; sfRating.Value = 3; sfRating.RatingSettings = sfRatingSetings1; sfRating.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(40 * con.Resources.DisplayMetrics.Density)); //sfRating Value Changed Listener sfRating.ValueChanged += (object sender, ValueChangedEventArgs e) => { if (!e.Value.ToString().Equals("")) { UpdateText(e.Value); } }; //mainView LinearLayout mainView = new LinearLayout(con); mainView.AddView(GetView(con)); return mainView; } private LinearLayout GetView(Context con) { //PageLayout pageLayout = new LinearLayout(con); pageLayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent,LinearLayout.LayoutParams.WrapContent); pageLayout.Orientation = Android.Widget.Orientation.Vertical; pageLayout.AddView(title); //ColumnLayout columnLayout = new LinearLayout(con); columnLayout.Orientation = Android.Widget.Orientation.Horizontal; columnLayout.SetPadding(0, 10, 0, 0); //image Layout imageLayout = new LinearLayout(con); FrameLayout.LayoutParams layoutParams1 = new FrameLayout.LayoutParams(width, (height), GravityFlags.Center); imageLayout.AddView(imageView, layoutParams1); imageLayout.SetGravity(GravityFlags.Center); //Content Layout contentLayout = new LinearLayout(con); contentLayout.Orientation = Android.Widget.Orientation.Vertical; contentLayout.SetPadding(10, 5, 20, 0); contentLayout.AddView(movieLabel); //Text Layout textLayout = new LinearLayout(con); textLayout.Orientation = Android.Widget.Orientation.Horizontal; textLayout.SetPadding(0, 5, 0, 0); textLayout.AddView(time); //Rating Layout ratingLayout = new LinearLayout(con); ratingLayout.SetPadding(5, 2, 0, 0); ratingLayout.AddView(sfRating1); textLayout.AddView(ratingLayout); contentLayout.AddView(textLayout); //DescriptionLayout descriptionLayout = new LinearLayout(con); descriptionLayout.SetPadding(0, 0, 0, 0); descriptionLayout.AddView(description); contentLayout.AddView(descriptionLayout); contentLayout.LayoutParameters = new ViewGroup.LayoutParams(width, height); columnLayout.AddView(imageLayout); columnLayout.AddView(contentLayout); pageLayout.AddView(columnLayout); //Time Layout timeLayout = new LinearLayout(con); timeLayout.SetPadding(30, 35, 30, 0); //Separator FrameLayout.LayoutParams separatorparams = new FrameLayout.LayoutParams(width * 2, 2, GravityFlags.Center); SeparatorView separatorView = new SeparatorView(con, width * 2); separatorView.separatorColor = Color.ParseColor("#a5a5a5"); timeLayout.AddView(separatorView, separatorparams); pageLayout.AddView(timeLayout); pageLayout.AddView(dummyLabel2); //PadLayout padLayout = new LinearLayout(con); padLayout.Orientation = Android.Widget.Orientation.Horizontal; padLayout.AddView(dummyLabel); padLayout.AddView(sfRating); pageLayout.AddView(padLayout); //Value Layout valueLayout = new LinearLayout(con); valueLayout.Orientation = Android.Widget.Orientation.Horizontal; valueLayout.SetPadding(30, 15, 0, 0); valueLayout.AddView(ratingLable); UpdateText(sfRating.Value); valueLayout.AddView(showLable); pageLayout.AddView(valueLayout); return pageLayout; } private void SamplePageContent(Context con) { //TitleLabel title = new TextView(con); title.TextSize = 25; title.SetTextColor(Color.ParseColor("#282828")); title.Text = "Movie Rating"; title.SetPadding(30, 40, 0, 0); //ImageView imageView = new ImageView(con); imageView.SetScaleType(ImageView.ScaleType.FitXy); imageView.SetImageResource(Resource.Drawable.movie); imageView.SetPadding(30, 10, 10, 0); //MovieLabel movieLabel = new TextView(con); movieLabel.TextSize = 16; movieLabel.SetTextColor(Color.ParseColor("#282828")); movieLabel.Text = "The walk ( 2015 )"; //TimeLabel time = new TextView(con); time.TextSize = 9; time.SetTextColor(Color.ParseColor("#282828")); time.Text = "PG | 2 h 20 min "; //Description description = new TextView(con); description.TextSize = 8; description.SetTextColor(Color.ParseColor("#282828")); description.SetLineSpacing(6, 1); description.Text = "In 1973, French street performer <NAME> is trying to make a living in Paris with juggling acts and wire walking, much to the chagrin of his father. During one performance, he eats a hard candy which was given to him by an audience member and injures his tooth. He visits the dentist and, while in the waiting room, sees a picture in a magazine of the Twin Towers in New York City. He analyzes the photo and decides to make it his mission to walk a tightrope between the two buildings. Meanwhile, he is evicted from his parents' house by his father, citing his lack of income and the fact that he's a street performer. Philippe returns to the circus that inspired him to wire walk as a child and practices in the big top after hours, but is caught by <NAME>, whom he impresses with his juggling skills. "; description.SetPadding(0, 0, 20, 0); //Dummy Label dummyLabel2 = new TextView(con); dummyLabel2.TextSize = 15; dummyLabel2.SetPadding(30, 28, 0, 0); dummyLabel2.SetTextColor(Color.ParseColor("#282828")); dummyLabel2.Text = "Rate"; dummyLabel = new TextView(con); dummyLabel.Text = " "; //Rating Label ratingLable = new TextView(con); ratingLable.TextSize = 10; ratingLable.SetTextColor(Color.ParseColor("#282828")); ratingLable.Text = "Rating : "; //Show Label showLable = new TextView(con); showLable.TextSize = 10; showLable.SetTextColor(Color.ParseColor("#282828")); } private void UpdateText(double rateValue) { int tempIntValue = (int)rateValue; float tempFloatValue = (float)rateValue; float diffenceValue = tempFloatValue - tempIntValue; String changeValue; if (diffenceValue == 0) changeValue = tempIntValue.ToString(); else { String valueString = String.Format("{0:0.#}", tempFloatValue); changeValue = valueString; } showLable.Text = changeValue + " / " + sfRating.ItemCount; } public void OnApplyChanges() { sfRating.Precision = precisionPosition; sfRating.TooltipPlacement = toolTipPosition; sfRating.ItemCount = constCount; sfRating.Value = 3; if (sfRating.Value > constCount) sfRating.Value = 0; UpdateText(sfRating.Value); } public View GetPropertyWindowLayout(Context context1) { context = context1; width = (context.Resources.DisplayMetrics.WidthPixels) / 2; propertylayout = new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; layoutParams = new LinearLayout.LayoutParams(width * 2, 3); layoutParams.SetMargins(0, 0, 0, 10); PrecisionLayout(); TooltipLayout(); ItemCountLayout(); return propertylayout; } private void PrecisionLayout() { /************* **Precision** *************/ TextView precisionLabel = new TextView(context); precisionLabel.TextSize = 20; precisionLabel.Text = "Precision"; //Precision Spinner precisionSpinner = new Spinner(context,SpinnerMode.Dialog); precisionSpinner.SetGravity(GravityFlags.Left); //Precision List List<String> precisionList = new List<String>(); precisionList.Add("Standard"); precisionList.Add("Half"); precisionList.Add("Exact"); //precision Adapter precisionAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, precisionList); precisionAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); precisionSpinner.Adapter = precisionAdapter; //Precision Spinner ItemSelected Listener precisionSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = precisionAdapter.GetItem(e.Position); if (selectedItem.Equals("Standard")) { precisionPosition = Precision.Standard; } if (selectedItem.Equals("Half")) { precisionPosition = Precision.Half; } if (selectedItem.Equals("Exact")) { precisionPosition = Precision.Exact; } }; propertylayout.AddView(precisionLabel); //Separator SeparatorView separatorLine2 = new SeparatorView(context, width * 2); separatorLine2.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); // propertylayout.AddView(separatorLine2, layoutParams); //AdjLabel TextView adjLabel2 = new TextView(context); adjLabel2.SetHeight(14); propertylayout.AddView(adjLabel2); precisionSpinner.SetPadding(0, 0, 0, 20); propertylayout.AddView(precisionSpinner); } private void TooltipLayout() { /*********** **ToolTip** ***********/ TextView tooltipLabel = new TextView(context); tooltipLabel.TextSize = 20; tooltipLabel.Text = "Tooltip Placement"; LinearLayout.LayoutParams toollabelParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); toollabelParams.SetMargins(0, 10, 0, 0); //ToolTip Spinner toolTipSpinner = new Spinner(context,SpinnerMode.Dialog); toolTipSpinner.SetGravity(GravityFlags.Left); //Placement List List<String> placementList = new List<String>(); placementList.Add("None"); placementList.Add("TopLeft"); placementList.Add("BottomRight"); //Placement Adapter placementAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, placementList); placementAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); toolTipSpinner.Adapter = placementAdapter; //ToolTip Spinner Item Selected Listener toolTipSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = placementAdapter.GetItem(e.Position); if (selectedItem.Equals("None")) { toolTipPosition = TooltipPlacement.None; } if (selectedItem.Equals("TopLeft")) { toolTipPosition = TooltipPlacement.TopLeft; } if (selectedItem.Equals("BottomRight")) { toolTipPosition = TooltipPlacement.BottomRight; } }; //CenterText TextView centerText = new TextView(context); propertylayout.AddView(centerText); propertylayout.AddView(tooltipLabel); //Separator SeparatorView separate3 = new SeparatorView(context, width * 2); separate3.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); // propertylayout.AddView(separate3, layoutParams); toolTipSpinner.SetPadding(0, 0, 0, 20); //AdjLabel TextView adjLabel3 = new TextView(context); adjLabel3.SetHeight(20); propertylayout.AddView(adjLabel3); propertylayout.AddView(toolTipSpinner); } private void ItemCountLayout() { /************ **ItemCount** *************/ TextView itemLabel = new TextView(context); itemLabel.Text = "Item Count"; itemLabel.Gravity = GravityFlags.CenterVertical; itemLabel.TextSize = 20; //ItemCount Text itemCountEntry = new EditText(context); itemCountEntry.Text = "5"; itemCountEntry.TextSize = 16; itemCountEntry.InputType = Android.Text.InputTypes.ClassPhone; itemCountEntry.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (itemCountEntry.Text.Length > 0) { try { constCount = Convert.ToInt32(e.Text.ToString()); } catch (Exception) { constCount = 1; } } }; //EntryParams LinearLayout.LayoutParams entryParams = new LinearLayout.LayoutParams(width - 20, ViewGroup.LayoutParams.WrapContent); entryParams.Gravity = GravityFlags.Center; entryParams.SetMargins(-10, 10, 0, 0); LinearLayout.LayoutParams labelParams = new LinearLayout.LayoutParams(width - 20, ViewGroup.LayoutParams.MatchParent); labelParams.SetMargins(0, 10, 0, 0); TextView centerText = new TextView(context); propertylayout.AddView(centerText); //CountStack countStack = new LinearLayout(context); countStack.AddView(itemLabel, labelParams); countStack.AddView(itemCountEntry, entryParams); countStack.Orientation = Android.Widget.Orientation.Horizontal; propertylayout.AddView(countStack); //Separator SeparatorView separatorLine4 = new SeparatorView(context, width * 2); separatorLine4.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 3); layoutParams.SetMargins(0, 10, 0, 0); // propertylayout.AddView(separatorLine4, layoutParams); propertylayout.SetPadding(20, 20, 20, 20); } } } <file_sep>/Forms/TabView/TabView/Samples/NestedTab/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser.SfTabView { public class ViewModel { public ObservableCollection<ContactsInfo> DialledCalls1 { get; set; } public ObservableCollection<ContactsInfo> ReceivedCalls1 { get; set; } public ObservableCollection<ContactsInfo> MissedCalls1 { get; set; } public ObservableCollection<ContactsInfo> ListData1 { get; set; } public ObservableCollection<ContactsInfo> FavoriteListData1 { get; set; } public ObservableCollection<ContactsInfo> SpeedDial1 { get; set; } public ObservableCollection<ContactsInfo> DialledCalls2 { get; set; } public ObservableCollection<ContactsInfo> ReceivedCalls2 { get; set; } public ObservableCollection<ContactsInfo> MissedCalls2 { get; set; } public ObservableCollection<ContactsInfo> ListData2 { get; set; } public ObservableCollection<ContactsInfo> FavoriteListData2 { get; set; } public ObservableCollection<ContactsInfo> SpeedDial2 { get; set; } ContactsInfoRepository collection = new ContactsInfoRepository(); public ViewModel() { DialledCalls1 = collection.GetContactDetails(2); ReceivedCalls1 = collection.GetContactDetails(3); MissedCalls1 = collection.GetContactDetails(4); ListData1 = collection.GetContactDetails(1); FavoriteListData1 = collection.GetContactDetails(7); SpeedDial1 = collection.GetContactDetails(27); DialledCalls2 = collection.GetContactDetails(3); ReceivedCalls2 = collection.GetContactDetails(4); MissedCalls2 = collection.GetContactDetails(7); ListData2 = collection.GetContactDetails(1); FavoriteListData2 = collection.GetContactDetails(9); SpeedDial2 = collection.GetContactDetails(29); } } } <file_sep>/Forms/ImageEditor/ImageEditor/Samples/ImageEditor/ImageEditor.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfImageEditor.XForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfImageEditor { public partial class ImageEditor : SampleView { double height = 0, width = 0; internal static bool isLoaded = false; void ImageTapped(object sender, System.EventArgs e) { LoadFromStream((sender as Image).Source); } void LoadFromStream(ImageSource source) { if (Device.RuntimePlatform.ToLower() == "ios") { Navigation.PushAsync(new NavigationPage(new SfImageEditorPage(source))); } else if (Device.RuntimePlatform.ToLower() == "uwp") { Navigation.PushAsync(new SfImageEditorPage(source)); } else { Navigation.PushModalAsync(new SfImageEditorPage(source)); } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.RuntimePlatform.ToLower() == "uwp" && Device.Idiom == TargetIdiom.Desktop) { imageGrid.RowDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 70, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(2, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Clear(); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); } else if ((width != this.width || height != this.height) && (width > -1 || height > -1)) { this.width = width; this.height = height; if (width < height) { imageGrid.RowDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 70, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.6, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Clear(); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); } else { imageGrid.RowDefinitions.Clear(); mainGrid.ColumnDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 10, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1.6, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0.5, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0.5, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0.5, GridUnitType.Star) }); } } } ImageModel model; public ImageEditor() { model = new ImageModel(); BindingContext = model; InitializeComponent(); } } public class ImageModel : INotifyPropertyChanged { public ImageSource BroweImage1 { get; set; } public ImageSource BroweImage2 { get; set; } public ImageSource BroweImage3 { get; set; } public int UndoCount { get; set; } public int RedoCount { get; set; } private bool isColorPaletteVisible; public bool IsColorPaletteVisible { get { return isColorPaletteVisible; } set { isColorPaletteVisible = value; OnPropertyChanged("IsColorPaletteVisible"); } } public bool IsImageEdited { get; set; } private bool isTouched; public event PropertyChangedEventHandler PropertyChanged; public bool IsTouched { get { return isTouched; } set { isTouched = value; OnPropertyChanged("IsTouched"); } } public ImageModel() { Assembly assembly = typeof(ImageSerializeModel).GetTypeInfo().Assembly; #if COMMONSB BroweImage1 = ImageSource.FromResource("SampleBrowser.Icons.EditorPerson1.png",assembly); BroweImage2 = ImageSource.FromResource("SampleBrowser.Icons.EditorPerson2.png",assembly); BroweImage3 = ImageSource.FromResource("SampleBrowser.Icons.EditorPerson3.png",assembly); #else BroweImage1 = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorPerson1.png", assembly); BroweImage2 = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorPerson2.png", assembly); BroweImage3 = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorPerson3.png", assembly); #endif } private void OnPropertyChanged(string name) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } public void DetectTouch() { IsTouched = !isTouched; OnPropertyChanged("IsTouched"); } } public class SfImageEditorPage : ContentPage { public SfImageEditorPage(ImageSource imagesource) { Syncfusion.SfImageEditor.XForms.SfImageEditor editor = new Syncfusion.SfImageEditor.XForms.SfImageEditor(); editor.Source = imagesource; editor.RotatableElements = ImageEditorElements.Text; editor.ToolbarSettings.VisibleShapesItems = ImageEditorShapes.Rectangle | ImageEditorShapes.Circle | ImageEditorShapes.Arrow | ImageEditorShapes.Line | ImageEditorShapes.DoubleArrow | ImageEditorShapes.Dotted | ImageEditorShapes.DottedArrow | ImageEditorShapes.DottedDoubleArrow; Content = editor; } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/SwipeDelete.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using CoreGraphics; using UIKit; using System.Threading.Tasks; namespace SampleBrowser { public class SwipeDelete:SampleView { #region Fields SfDataGrid SfGrid; SwipingViewModel viewModel; private bool IsUndoClicked{ get; set; } private int swipedRowindex; private bool isSuspend; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public SwipeDelete () { this.SfGrid = new SfDataGrid (); this.viewModel = new SwipingViewModel (); this.SfGrid.ItemsSource = viewModel.OrdersInfo; this.SfGrid.AutoGenerateColumns = false; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.ColumnSizer = ColumnSizer.Star; UILabel leftSwipeViewText = new UILabel (); leftSwipeViewText.Text = "Deleted"; leftSwipeViewText.TextColor = UIColor.White; leftSwipeViewText.TextAlignment = UITextAlignment.Left; leftSwipeViewText.BackgroundColor = UIColor.FromRGB(26, 170, 135); UILabel leftSwipeViewButton = new UILabel(); leftSwipeViewButton.UserInteractionEnabled = true; leftSwipeViewButton.Text = "UNDO"; leftSwipeViewButton.TextColor = UIColor.White; leftSwipeViewButton.Font = UIFont.BoldSystemFontOfSize(14); leftSwipeViewButton.TextAlignment = UITextAlignment.Right; leftSwipeViewButton.BackgroundColor = UIColor.FromRGB(26,170,135); leftSwipeViewButton.AddGestureRecognizer(new UITapGestureRecognizer(UndoTapped)); SwipeView leftSwipeView = new SwipeView (); leftSwipeView.BackgroundColor = UIColor.FromRGB(26, 170, 135); leftSwipeView.AddSubview (leftSwipeViewText); leftSwipeView.AddSubview (leftSwipeViewButton); UILabel rightSwipeViewText = new UILabel (); rightSwipeViewText.Text = "Deleted"; rightSwipeViewText.TextColor = UIColor.White; rightSwipeViewText.TextAlignment = UITextAlignment.Left; rightSwipeViewText.BackgroundColor = UIColor.FromRGB(26, 170, 135); UILabel rightSwipeViewButton = new UILabel (); rightSwipeViewButton.UserInteractionEnabled = true; rightSwipeViewButton.Text = "UNDO"; rightSwipeViewButton.TextColor = UIColor.White; rightSwipeViewButton.Font = UIFont.BoldSystemFontOfSize(14); rightSwipeViewButton.TextAlignment = UITextAlignment.Right; rightSwipeViewButton.BackgroundColor = UIColor.FromRGB(26, 170, 135); rightSwipeViewButton.AddGestureRecognizer(new UITapGestureRecognizer(UndoTapped)); SwipeView rightSwipeView = new SwipeView (); rightSwipeView.BackgroundColor = UIColor.FromRGB(26, 170, 135); rightSwipeView.AddSubview (rightSwipeViewText); rightSwipeView.AddSubview (rightSwipeViewButton); this.SfGrid.AllowSwiping = true; this.SfGrid.LeftSwipeView = leftSwipeView; this.SfGrid.RightSwipeView = rightSwipeView; this.SfGrid.SwipeEnded += SfGrid_SwipeEnded; this.SfGrid.SwipeStarted += SfGrid_SwipeStarted; GridTextColumn CustomerID = new GridTextColumn(); CustomerID.MappingName = "CustomerID"; CustomerID.HeaderText = "Customer ID"; GridTextColumn OrderID = new GridTextColumn(); OrderID.MappingName = "OrderID"; OrderID.HeaderText = "Order ID"; GridTextColumn EmployeeID = new GridTextColumn(); EmployeeID.MappingName = "EmployeeID"; EmployeeID.HeaderText = "Employee ID"; GridTextColumn Name = new GridTextColumn(); Name.MappingName = "FirstName"; Name.HeaderText = "Name"; this.SfGrid.Columns.Add(OrderID); this.SfGrid.Columns.Add(CustomerID); this.SfGrid.Columns.Add(EmployeeID); this.SfGrid.Columns.Add(Name); this.AddSubview (SfGrid); } void UndoTapped (UITapGestureRecognizer gesture) { if (gesture.State == UIGestureRecognizerState.Ended) { var removedData = viewModel.OrdersInfo[swipedRowindex - 1]; var isSelected = SfGrid.SelectedItems.Contains(removedData); viewModel.OrdersInfo.Remove(removedData); viewModel.OrdersInfo.Insert(swipedRowindex - 1, removedData); if (isSelected) SfGrid.SelectedItems.Add(removedData); IsUndoClicked = true; } } void SfGrid_SwipeStarted (object sender, SwipeStartedEventArgs e) { SfGrid.MaxSwipeOffset = (int)SfGrid.Frame.Width; if (isSuspend) e.Cancel = true; } private async void SfGrid_SwipeEnded (object sender, SwipeEndedEventArgs e) { isSuspend = true; swipedRowindex = e.RowIndex; if(Math.Abs(e.SwipeOffset) >= SfGrid.MaxSwipeOffset/2) { await Task.Delay(2000); if (!IsUndoClicked) viewModel.OrdersInfo.RemoveAt(swipedRowindex - 1); else { var removedData = viewModel.OrdersInfo[swipedRowindex - 1]; var isSelected = SfGrid.SelectedItems.Contains(removedData); viewModel.OrdersInfo.Remove(removedData); viewModel.OrdersInfo.Insert(swipedRowindex - 1, removedData); if (isSelected) SfGrid.SelectedItems.Add(removedData); IsUndoClicked = false; }isSuspend = false; } else isSuspend= false; } public override void LayoutSubviews () { this.SfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews (); } protected override void Dispose(bool disposing) { if (disposing) { if (SfGrid != null) { SfGrid.Dispose(); } viewModel = null; SfGrid = null; } base.Dispose(disposing); } } public class SwipeView : UIView { public override bool Hidden { get { return base.Hidden; } set { base.Hidden = value;} } public SwipeView() { } public override void LayoutSubviews() { var start = 0; var childWidth = this.Frame.Width / 2; try { this.Subviews[0].Frame = new CGRect(start + 20, 0, childWidth - 20, this.Frame.Height); this.Subviews[1].Frame = new CGRect(childWidth, 0, childWidth - 15, this.Frame.Height); } catch (Exception e) { Console.WriteLine(e.Message); } } } } <file_sep>/Forms/DataForm/DataForm/Samples/ContactForm/Helpers/ContactFormBehaviors.cs #region Copyright // <copyright file="ContactFormBehaviors.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; /// <summary> /// User defined behaviour to respond arbitrary conditions and events of ContactForm. /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public class ContactFormBehaviors : Behavior<SampleView> { /// <summary> /// A layout used to display image in the contact form list to tap the view to add and edit the contact list. /// </summary> private Grid myGrid; /// <summary> /// A layout used to display illustration view in the contact form list to tap the view to add and edit the contact list. /// </summary> private Grid transparent; /// <summary> /// A layout used to display contact form list with contact image, contact name and phone number. /// </summary> private Grid customView; /// <summary> /// Attaches to the superclass and then calls the OnAttachTo method on this object. /// </summary> /// <param name="bindable">The bindable object to which the behavior was attached.</param> protected async override void OnAttachedTo(SampleView bindable) { await Task.Delay(200); this.customView = bindable.FindByName<Grid>("gridLayout"); this.transparent = bindable.FindByName<Grid>("Illustrationgrid"); this.myGrid = new Grid(); this.myGrid.VerticalOptions = LayoutOptions.FillAndExpand; this.myGrid.HorizontalOptions = LayoutOptions.FillAndExpand; this.myGrid.RowDefinitions = new RowDefinitionCollection { new RowDefinition { Height = new GridLength(1.1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, }; this.myGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); this.myGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1.8, GridUnitType.Star) }); this.myGrid.Children.Add(new Image() { Opacity = 1.0, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Source = "TapEditIllustration.png" }, 1, 1); this.myGrid.BackgroundColor = Color.Transparent; this.myGrid.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Collapse) }); this.customView.Children.Add(this.myGrid); base.OnAttachedTo(bindable); } /// <summary> /// Calls the OnDetachingFrom method and then detaches from the superclass. /// </summary> /// <param name="bindable">The bindable object from which the behavior was detached.</param> protected override void OnDetachingFrom(SampleView bindable) { this.myGrid = null; this.transparent = null; this.customView = null; base.OnDetachingFrom(bindable); } /// <summary> /// Collapse the views in the contact form. /// </summary> private void Collapse() { this.myGrid.IsEnabled = false; this.myGrid.IsVisible = false; this.transparent.IsVisible = false; this.customView.Children.Remove(this.myGrid); this.customView.Children.Remove(this.transparent); } } } <file_sep>/Forms/DataSource/DataSource.UWP/CustomListViewRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Platform.UWP; using Xamarin.Forms; using System.Collections.Specialized; using System.ComponentModel; using Windows.Foundation; using SampleBrowser.DataSource; [assembly: ExportRenderer(typeof(CustomListView), typeof(SampleBrowser.DataSource.UWP.CustomListViewRenderer))] namespace SampleBrowser.DataSource.UWP { public class CustomListViewRenderer : ListViewRenderer { internal Windows.UI.Xaml.Controls.ListView NativeListView { get { return this.Control as Windows.UI.Xaml.Controls.ListView; } } protected override void OnElementChanged(ElementChangedEventArgs<ListView> e) { base.OnElementChanged(e); if (e.NewElement != null) { if (e.NewElement.ItemsSource != null) { (e.NewElement.ItemsSource as INotifyCollectionChanged).CollectionChanged += CustomListViewRenderer_CollectionChanged; } } } private void CustomListViewRenderer_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (this.NativeListView != null && this.Element != null) { var itemsource = this.Element.ItemsSource; this.NativeListView.ItemsSource = null; this.NativeListView.ItemsSource = itemsource; } } } } <file_sep>/Forms/AvatarView/AvatarView/Samples/GroupView/GroupView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.Core; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfAvatarView { public partial class GroupView : SampleView { private GroupModel selectedGroup; public GroupModel SelectedGroup { get { return selectedGroup; } set { selectedGroup = value; if (value != null) this.PeopleListView.IsVisible = true; else this.PeopleListView.IsVisible = false; this.OnPropertyChanged(); } } private People selectedPerson; public People SelectedPerson { get { return selectedPerson; } set { selectedPerson = value; if (value != null) this.PersonView.IsVisible = true; else this.PersonView.IsVisible = false; this.OnPropertyChanged(); } } private ObservableCollection<GroupModel> groupCollection = new ObservableCollection<GroupModel>(); public ObservableCollection<GroupModel> GroupCollection { get { return groupCollection; } set { groupCollection = value; this.OnPropertyChanged(); } } public GroupView() { InitializeComponent(); this.GroupCollection.Add(new GroupModel(5) { GroupName = "Marketing Managers" }); this.GroupCollection.Add(new GroupModel(10) { GroupName = "Marketing Representative" }); this.GroupCollection.Add(new GroupModel(3) { GroupName = "Marketing Heads" }); this.GroupCollection.Add(new GroupModel(4) { GroupName = "Sales Managers" }); this.GroupCollection.Add(new GroupModel(9) { GroupName = "Sales Representative" }); this.GroupCollection.Add(new GroupModel(2) { GroupName = "Sales Heads" }); this.GroupCollection.Add(new GroupModel(5) { GroupName = "Process Managers" }); this.GroupCollection.Add(new GroupModel(10) { GroupName = "Process Representative" }); this.GroupCollection.Add(new GroupModel(2) { GroupName = "Process Heads" }); this.GroupCollection.Add(new GroupModel(3) { GroupName = "Coordinaters" }); this.GroupCollection.Add(new GroupModel(3) { GroupName = "Desinger" }); this.GroupCollection.Add(new GroupModel(2) { GroupName = "Field Managers" }); this.GroupCollection.Add(new GroupModel(2) { GroupName = "Server Team" }); this.BindingContext = this; this.ExtButton.Clicked += ExtButton_Clicked; } private void ExtButton_Clicked(object sender, EventArgs e) { if (this.PersonView.IsVisible) { this.SelectedPerson = null; } else { this.SelectedGroup = null; } } } public class GroupModel { public String GroupName { get; set; } public ObservableCollection<People> PeopleCollection { get; set; } private ObservableCollection<People> TotalPeople { get; set; } public String TotalParticipants { get; set; } public GroupModel(int peopleCount) { this.TotalParticipants = peopleCount.ToString() + " Participants"; this.PopulateAllPeople(); this.PopulatePeopleBasedOnCount(peopleCount); } private void PopulateAllPeople() { this.TotalPeople = new ObservableCollection<People>(); this.TotalPeople.Add(new People() { Name = "Kyle", Image = "Avatar1.png" , Backgroundcolor= Color.FromHex("#90DDFE") }); this.TotalPeople.Add(new People() { Name = "Gina" , Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Michael", Image = "People_Square18.png", Backgroundcolor= Color.White }); this.TotalPeople.Add(new People() { Name = "Oscar", Image = "People_Square23.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "William", Image = "Avatar5.png", Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Bill" , Backgroundcolor= Color.FromHex("#D7E99C") }); this.TotalPeople.Add(new People() { Name = "Daniel", Image = "Avatar7.png", Backgroundcolor = Color.FromHex("#D7E99C") }); this.TotalPeople.Add(new People() { Name = "Frank", Backgroundcolor= Color.FromHex("#FE9B90") }); this.TotalPeople.Add(new People() { Name = "Howard", Image = "Avatar9.png", Backgroundcolor = Color.FromHex("#D7E99C") }); this.TotalPeople.Add(new People() { Name = "Jack" , Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Holly" , Backgroundcolor = Color.FromHex("#FE9B90") }); this.TotalPeople.Add(new People() { Name = "Steve", Image = "Avatar2.png", Backgroundcolor = Color.FromHex("#F5EF9A") }); this.TotalPeople.Add(new People() { Name = "Vince" ,Backgroundcolor = Color.FromHex("#D7E99C") }); this.TotalPeople.Add(new People() { Name = "Zeke", Image = "Avatar4.png", Backgroundcolor = Color.FromHex("#D7E99C") }); this.TotalPeople.Add(new People() { Name = "Aiden", Image = "People_Square10.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Jackson", Image = "People_Square15.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Mason" , Backgroundcolor = Color.BlanchedAlmond }); this.TotalPeople.Add(new People() { Name = "Liam", Image = "Avatar8.png", Backgroundcolor = Color.FromHex("#F5EF9A") }); this.TotalPeople.Add(new People() { Name = "Jacob" , Backgroundcolor = Color.FromHex("#F5EF9A") }); this.TotalPeople.Add(new People() { Name = "Jayden", Image = "People_Square14.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Ethan", Image = "Avatar1.png", Backgroundcolor = Color.FromHex("#F5EF9A") }); this.TotalPeople.Add(new People() { Name = "Alexander", Image = "People_Square8.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Sebastian", Image = "Avatar3.png", Backgroundcolor = Color.FromHex("#F5EF9A") }); this.TotalPeople.Add(new People() { Name = "Clara", Image = "People_Square3.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Victoriya", Image = "People_Square25.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Ellie", Image = "People_Square6.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Gabriella", Image = "People_Square9.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Arianna", Image = "People_Square2.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Sarah", Image = "People_Square17.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Kaylee", Image = "People_Square10.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Adriana", Image = "People_Square1.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Finley", Image = "People_Square7.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Daleyza", Image = "People_Square4.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Leila", Image = "People_Square11.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Mckenna", Image = "People_Square15.png", Backgroundcolor = Color.White }); this.TotalPeople.Add(new People() { Name = "Jacqueline", Backgroundcolor = Color.FromHex("#9AA8F5") }); this.TotalPeople.Add(new People() { Name = "Brynn" , Backgroundcolor = Color.FromHex("#FCCE65") }); this.TotalPeople.Add(new People() { Name = "Sawyer", Image = "Avatar8.png", Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Rosalie", Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Maci", Image = "Avatar10.png", Backgroundcolor = Color.FromHex("#FE9B90") }); this.TotalPeople.Add(new People() { Name = "Miranda", Backgroundcolor = Color.FromHex("#90DDFE") }); this.TotalPeople.Add(new People() { Name = "Talia", Image = "Avatar4.png", Backgroundcolor = Color.FromHex("#FE9B90") }); this.TotalPeople.Add(new People() { Name = "Shelby", Backgroundcolor = Color.FromHex("#9FEFC5") }); this.TotalPeople.Add(new People() { Name = "Haven", Image = "Avatar6.png", Backgroundcolor = Color.FromHex("#FE9B90") }); this.TotalPeople.Add(new People() { Name = "Brynn" ,Backgroundcolor = Color.FromHex("#E79AF5") }); this.TotalPeople.Add(new People() { Name = "Yaretzi", Image = "Avatar8.png", Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Zariah", Image = "Avatar6.png", Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Karla", Backgroundcolor = Color.FromHex("#D7E99C") }); this.TotalPeople.Add(new People() { Name = "Cassandra", Image = "Avatar8.png", Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Pearl", Backgroundcolor = Color.FromHex("#FBBC93") }); this.TotalPeople.Add(new People() { Name = "Irene", Image = "Avatar10.png", Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Zelda", Backgroundcolor = Color.FromHex("#F5EF9A") }); this.TotalPeople.Add(new People() { Name = "Wren", Image = "Avatar4.png", Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Yamileth", Backgroundcolor = Color.FromHex("#9AA8F5") }); this.TotalPeople.Add(new People() { Name = "Belen", Image = "Avatar6.png", Backgroundcolor = Color.FromHex("#9AA8F5") }); this.TotalPeople.Add(new People() { Name = "Briley", Backgroundcolor = Color.FromHex("#FE9B90") }); this.TotalPeople.Add(new People() { Name = "Jada", Image = "Avatar8.png", Backgroundcolor = Color.FromHex("#9FCC69") }); this.TotalPeople.Add(new People() { Name = "Jaden", Backgroundcolor = Color.FromHex("#FE9B90") }); this.TotalPeople.Add(new People() { Name = "George", Backgroundcolor= Color.FromHex("#FCCE65") }); this.TotalPeople.Add(new People() { Name = "Ellanaa", Image = "Avatar8.png", Backgroundcolor = Color.FromHex("#9AA8F5") }); this.TotalPeople.Add(new People() { Name = "James", Backgroundcolor = Color.FromHex("#9FCC69") }); } //Random random = new Random(); static int count = 0; private void PopulatePeopleBasedOnCount(int peopleCount) { this.PeopleCollection = new ObservableCollection<People>(); for (int i = 0; i < peopleCount; i++) { while (true) { if (this.TotalPeople.Count <= count) count = 0; var person = (this.TotalPeople[count++]); if (!this.PeopleCollection.Contains(person)) { this.PeopleCollection.Add(person); break; } } } } } public class People { public String Name { get; set; } public String Image { get; set; } public Color Backgroundcolor { get; set; } } }<file_sep>/Forms/SegmentedControl/SegmentedControl.iOS/Renderer/Renderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.SfSegmentedControl; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(ViewCell), typeof(CustomListView))] namespace SampleBrowser.SfSegmentedControl { public class CustomListView : ViewCellRenderer { public override UITableViewCell GetCell(Cell segmentitem, UITableViewCell reusableCell, UITableView segment) { var listviewCell = base.GetCell(segmentitem, reusableCell, segment); if (listviewCell != null) { listviewCell.SelectionStyle = UITableViewCellSelectionStyle.None; } return listviewCell; } } }<file_sep>/Forms/Presentation/Presentation/Samples/Comments/Comments.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.OfficeChart; using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.Presentation { public partial class Comments : SampleView { public Comments() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } private void OnButtonClicked(object sender, EventArgs e) { string resourcePath =""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Images.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Images.pptx"; #endif Assembly assembly = typeof(Comments).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); #region Slide 1 ISlide slide1 = presentation.Slides[0]; IShape shape1 = (IShape)slide1.Shapes[0]; shape1.Left = 1.27 * 72; shape1.Top = 0.85 * 72; shape1.Width = 10.86 * 72; shape1.Height = 3.74 * 72; ITextBody textFrame = shape1.TextBody; IParagraphs paragraphs = textFrame.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Left; ITextParts textParts = paragraph.TextParts; textParts.Add(); ITextPart textPart = textParts[0]; textPart.Text = "Essential Presentation "; textPart.Font.CapsType = TextCapsType.All; textPart.Font.FontName = "Calibri Light (Headings)"; textPart.Font.FontSize = 80; textPart.Font.Color = ColorObject.Black; IComment comment = slide1.Comments.Add(0.35, 0.04, "Author1", "A1", "Essential Presentation is available from 13.1 versions of Essential Studio", DateTime.Now); #endregion #region Slide2 ISlide slide2 = presentation.Slides.Add(SlideLayoutType.Blank); IPresentationChart chart = slide2.Shapes.AddChart(230, 80, 500, 400); //Specifies the chart title chart.ChartTitle = "Sales Analysis"; //Sets chart data - Row1 chart.ChartData.SetValue(1, 2, "Jan"); chart.ChartData.SetValue(1, 3, "Feb"); chart.ChartData.SetValue(1, 4, "March"); //Sets chart data - Row2 chart.ChartData.SetValue(2, 1, 2010); chart.ChartData.SetValue(2, 2, 60); chart.ChartData.SetValue(2, 3, 70); chart.ChartData.SetValue(2, 4, 80); //Sets chart data - Row3 chart.ChartData.SetValue(3, 1, 2011); chart.ChartData.SetValue(3, 2, 80); chart.ChartData.SetValue(3, 3, 70); chart.ChartData.SetValue(3, 4, 60); //Sets chart data - Row4 chart.ChartData.SetValue(4, 1, 2012); chart.ChartData.SetValue(4, 2, 60); chart.ChartData.SetValue(4, 3, 70); chart.ChartData.SetValue(4, 4, 80); //Creates a new chart series with the name IOfficeChartSerie serieJan = chart.Series.Add("Jan"); //Sets the data range of chart serie – start row, start column, end row, end column serieJan.Values = chart.ChartData[2, 2, 4, 2]; //Creates a new chart series with the name IOfficeChartSerie serieFeb = chart.Series.Add("Feb"); //Sets the data range of chart serie – start row, start column, end row, end column serieFeb.Values = chart.ChartData[2, 3, 4, 3]; //Creates a new chart series with the name IOfficeChartSerie serieMarch = chart.Series.Add("March"); //Sets the data range of chart series – start row, start column, end row, end column serieMarch.Values = chart.ChartData[2, 4, 4, 4]; //Sets the data range of the category axis chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 4, 1]; //Specifies the chart type chart.ChartType = OfficeChartType.Column_Clustered_3D; slide2.Comments.Add(0.35, 0.04, "Author2", "A2", "All 3D-chart types are supported in Presentation library.", DateTime.Now); #endregion #region Slide3 ISlide slide3 = presentation.Slides.Add(SlideLayoutType.ContentWithCaption); slide3.Background.Fill.FillType = FillType.Solid; slide3.Background.Fill.SolidFill.Color = ColorObject.White; //Adds shape in slide IShape shape2 = (IShape)slide3.Shapes[0]; shape2.Left = 0.47 * 72; shape2.Top = 1.15 * 72; shape2.Width = 3.5 * 72; shape2.Height = 4.91 * 72; ITextBody textFrame1 = shape2.TextBody; //Instance to hold paragraphs in textframe IParagraphs paragraphs1 = textFrame1.Paragraphs; IParagraph paragraph1 = paragraphs1.Add(); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Left; ITextPart textpart1 = paragraph1.AddTextPart(); textpart1.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph2 = paragraphs1.Add(); paragraph2.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph2.AddTextPart(); textpart1.Text = "Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph3 = paragraphs1.Add(); paragraph3.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph3.AddTextPart(); textpart1.Text = "Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph4 = paragraphs1.Add(); paragraph4.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph4.AddTextPart(); textpart1.Text = "Lorem tortor neque, purus taciti quis id. Elementum integer orci accumsan minim phasellus vel."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); slide3.Shapes.RemoveAt(1); slide3.Shapes.RemoveAt(1); //Adds picture in the shape resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.tablet.jpg"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.tablet.jpg"; #endif fileStream = assembly.GetManifestResourceStream(resourcePath); IPicture picture1 = slide3.Shapes.AddPicture(fileStream, 5.18 * 72, 1.15 * 72, 7.3 * 72, 5.31 * 72); fileStream.Dispose(); slide3.Comments.Add(0.14, 0.04, "Author3", "A3", "Can we use a different font family for this text?", DateTime.Now); #endregion MemoryStream memoryStream = new MemoryStream(); presentation.Save(memoryStream); presentation.Close(); memoryStream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("CommentsSamples.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", memoryStream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("CommentsSamples.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", memoryStream); } } } <file_sep>/Forms/Rotator/Rotator/Samples/Rotator/Rotator_Tablet.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfRotator.XForms; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfRotator { public partial class Rotator_TabletView : SampleView { double width; int totalCart = 0; public Rotator_TabletView() { InitializeComponent(); width = Core.SampleBrowser.ScreenWidth; sfRotator.BindingContext = new RotatorViewModel(); settingsWindows(); } #region Settings options private void settingsWindows() { directionPicker.Items.Add("BottomToTop"); directionPicker.Items.Add("Horizontal"); directionPicker.Items.Add("LeftToRight"); directionPicker.Items.Add("RightToLeft"); directionPicker.Items.Add("TopToBottom"); directionPicker.Items.Add("Vertical"); directionPicker.SelectedIndex = 1; directionPicker.SelectedIndexChanged += picker1_SelectedIndexChanged; tabPicker.Items.Add("Bottom"); tabPicker.Items.Add("Top"); tabPicker.Items.Add("Left"); tabPicker.Items.Add("Right"); tabPicker.SelectedIndex = 0; modePicker.Items.Add("Dots"); modePicker.Items.Add("Thumbnail"); modePicker.SelectedIndex = 0; tabPicker.SelectedIndexChanged += picker2_SelectedIndexChanged; modePicker.SelectedIndexChanged += picker3_SelectedIndexChanged; toggleButton.Toggled += toggleStateChanged; if (Device.RuntimePlatform == Device.Android) { root.HorizontalOptions = LayoutOptions.Center; } else if (Device.RuntimePlatform == Device.iOS) { sfRotator.WidthRequest = width; sfRotator.HeightRequest = Core.SampleBrowser.ScreenHeight / 2 + 20; emptyLabel.WidthRequest = 200; } if (Device.RuntimePlatform == Device.Android) { directionLabel.FontSize = 20; tabLabel.FontSize = 20; emptyLabel.FontSize = 20; modeLabel.FontSize = 20; } if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { emptyLabel.WidthRequest = 150; directionPicker.HeightRequest = 90; tabPicker.HeightRequest = 90; directionLabel.Text = " " + "Tick Placement"; directionLabel.HeightRequest = 22; tabLabel.Text = " " + "Label Placement"; tabLabel.HeightRequest = 22; modeLabel.Text = " " + "Label Placement"; modeLabel.HeightRequest = 22; emptyLabel.Text = " " + "Label"; emptyLabel.HeightRequest = 22; } } void picker1_SelectedIndexChanged(object sender, EventArgs e) { switch (directionPicker.SelectedIndex) { case 0: { sfRotator.NavigationDirection = NavigationDirection.BottomToTop; break; } case 1: { sfRotator.NavigationDirection = NavigationDirection.Horizontal; break; } case 2: { sfRotator.NavigationDirection = NavigationDirection.LeftToRight; break; } case 3: { sfRotator.NavigationDirection = NavigationDirection.RightToLeft; break; } case 4: { sfRotator.NavigationDirection = NavigationDirection.TopToBottom; break; } case 5: { sfRotator.NavigationDirection = NavigationDirection.Vertical; break; } } } void picker2_SelectedIndexChanged(object sender, EventArgs e) { switch (tabPicker.SelectedIndex) { case 0: { sfRotator.NavigationStripPosition = NavigationStripPosition.Bottom; break; } case 1: { sfRotator.NavigationStripPosition = NavigationStripPosition.Top; break; } case 2: { sfRotator.NavigationStripPosition = NavigationStripPosition.Left; break; } case 3: { sfRotator.NavigationStripPosition = NavigationStripPosition.Right; break; } } } void picker3_SelectedIndexChanged(object sender, EventArgs e) { switch (modePicker.SelectedIndex) { case 0: { sfRotator.NavigationStripMode = NavigationStripMode.Dots; break; } case 1: { sfRotator.NavigationStripMode = NavigationStripMode.Thumbnail; break; } } } void toggleStateChanged(object sender, ToggledEventArgs e) { sfRotator.EnableAutoPlay = e.Value; } void Handle_Clicked(object sender, System.EventArgs e) { mButton.BackgroundColor = sButton.BackgroundColor = xButton.BackgroundColor = xLButton.BackgroundColor = Color.White; mButton.TextColor = sButton.TextColor = xButton.TextColor = xLButton.TextColor = Color.Black; (sender as Button).BackgroundColor = Color.FromHex("#f1852a"); (sender as Button).TextColor = Color.White; } void Handle_ClickedAdd(object sender, System.EventArgs e) { totalCart++; TotalCart.Text = "(" + totalCart.ToString() + ")"; } void Handle_ClickedBuy(object sender, System.EventArgs e) { //App.Current.MainPage.DisplayAlert("Order Details", "Order has been placed successfully", "OK"); } #endregion public View getContent() { return this.Content; } public View getPropertyView() { return this.PropertyView; } } } <file_sep>/Forms/Rotator/Rotator/Samples/RotatorModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Xamarin.Forms; namespace SampleBrowser { class RotatorModel { public RotatorModel(string imagestr) { Image = imagestr; } private String _image; public String Image { get { return _image; } set { _image = value; } } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Model/SalesByDate.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public class SalesByDate : NotificationObject { #region Fields private string name; private DateTime date; private int qS1; private int qS2; private int qS3; private int qS4; private int total; #endregion #region Property /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name { get { return name; } set { name = value; RaisePropertyChanged("Name"); } } /// <summary> /// Gets or sets the year. /// </summary> /// <value>The year.</value> public DateTime Date { get { return date; } set { date = value; RaisePropertyChanged("Date"); } } /// <summary> /// Gets or sets the Q s1. /// </summary> /// <value>The Q s1.</value> public int QS1 { get { return qS1; } set { qS1 = value; RaisePropertyChanged("QS1"); } } /// <summary> /// Gets or sets the Q s2. /// </summary> /// <value>The Q s2.</value> public int QS2 { get { return qS2; } set { qS2 = value; RaisePropertyChanged("QS2"); } } /// <summary> /// Gets or sets the Q s3. /// </summary> /// <value>The Q s3.</value> public int QS3 { get { return qS3; } set { qS3 = value; RaisePropertyChanged("QS3"); } } /// <summary> /// Gets or sets the Q s4. /// </summary> /// <value>The Q s4.</value> public int QS4 { get { return qS4; } set { qS4 = value; RaisePropertyChanged("QS4"); } } /// <summary> /// Gets or sets the total. /// </summary> /// <value>The total.</value> public int Total { get { return total; } set { total = value; RaisePropertyChanged("Total"); } } #endregion } }<file_sep>/Android/SampleBrowser/Common/Adapters/RecyclerViewAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.Graphics; using Android.Views; using Android.Widget; using AndroidX.RecyclerView.Widget; namespace SampleBrowser { public class RecyclerViewAdapter : RecyclerView.Adapter { #region fields private List<SampleModel> items; private TextView prevSelectedView; private int selectedIndex = -1; #endregion #region ctor public RecyclerViewAdapter(List<SampleModel> values) { items = values; } #endregion #region event public event EventHandler<ListViewSelectionChangedEventArgs> ItemClick; #endregion #region properties public override int ItemCount { get { return items.Count; } } #endregion #region methods public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) { var viewHolder = holder as RecyclerViewViewItemHolder; var item = items[position]; viewHolder.SampleNameView.Text = item.Title; if (selectedIndex != position) { viewHolder.SampleNameView.SetTextColor(Color.Black); } if (selectedIndex == -1 && position == 0) { prevSelectedView = viewHolder.SampleNameView; viewHolder.SampleNameView.SetTextColor(Color.ParseColor("#0277F5")); } if (selectedIndex == position) { viewHolder.SampleNameView.SetTextColor(Color.ParseColor("#0277F5")); } var textView = viewHolder.UpdateTagView; var layoutParams = textView.LayoutParameters as ViewGroup.LayoutParams; if (string.IsNullOrEmpty(item.Type)) { textView.Visibility = ViewStates.Gone; } else { textView.Visibility = ViewStates.Visible; if (item.Type.ToLower().Equals("updated")) { textView.Text = "U"; textView.SetBackgroundResource(Resource.Drawable.updatetagcircle); } else if (item.Type.ToLower().Equals("new")) { textView.Text = "N"; textView.SetBackgroundResource(Resource.Drawable.newtagcircle); } else if (item.Type.ToLower().Equals("preview")) { textView.Text = "P"; textView.SetBackgroundResource(Resource.Drawable.previewtagcircle); } layoutParams.Width = (int)(20 * MainActivity.Density); layoutParams.Height = (int)(20 * MainActivity.Density); textView.LayoutParameters = layoutParams; } } public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { var itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.CustomListViewLayout, parent, false); var viewHolder = new RecyclerViewViewItemHolder(itemView, OnClick); return viewHolder; } private void OnClick(TextView selectedView, int position) { var eventArgs = new ListViewSelectionChangedEventArgs { PreviousSelectedItem = prevSelectedView, SelectedItem = selectedView, SelectedIndex = position }; selectedIndex = position; if (prevSelectedView == selectedView) { return; } ItemClick?.Invoke(this, eventArgs); prevSelectedView = selectedView; } #endregion } public class ListViewSelectionChangedEventArgs : EventArgs { #region properties public int SelectedIndex { get; set; } public TextView SelectedItem { get; set; } public TextView PreviousSelectedItem { get; set; } #endregion } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/StackingLine100.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; namespace SampleBrowser { public class StackingLine100 : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "Monthly Expenses of a Family"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis PrimaryAxis = new CategoryAxis(); PrimaryAxis.ShowMajorGridLines = false; PrimaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; PrimaryAxis.LabelPlacement = LabelPlacement.BetweenTicks; chart.PrimaryAxis = PrimaryAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.PlotOffset = 20; numericalAxis.Minimum = 0; numericalAxis.Maximum = 100; numericalAxis.Interval = 10; numericalAxis.LineStyle.StrokeWidth = 0; numericalAxis.MajorTickStyle.TickSize = 0; numericalAxis.LabelStyle.LabelFormat = "#'%' "; chart.SecondaryAxis = numericalAxis; StackingLine100Series stackingLine100Series1 = new StackingLine100Series(); stackingLine100Series1.EnableAnimation = true; stackingLine100Series1.Label = "Daughter"; stackingLine100Series1.ItemsSource = MainPage.GetStackedLine100Data1(); stackingLine100Series1.XBindingPath = "XValue"; stackingLine100Series1.YBindingPath = "YValue"; stackingLine100Series1.DataMarker.ShowMarker = true; stackingLine100Series1.DataMarker.MarkerColor = Color.White; stackingLine100Series1.DataMarker.MarkerWidth = 10; stackingLine100Series1.DataMarker.MarkerHeight = 10; stackingLine100Series1.DataMarker.MarkerStrokeColor = Color.ParseColor("#00bdae"); stackingLine100Series1.DataMarker.MarkerStrokeWidth = 2; stackingLine100Series1.StrokeWidth = 3; stackingLine100Series1.LegendIcon = ChartLegendIcon.SeriesType; StackingLine100Series stackingLine100Series2 = new StackingLine100Series(); stackingLine100Series2.EnableAnimation = true; stackingLine100Series2.Label = "Son"; stackingLine100Series2.ItemsSource = MainPage.GetStackedLine100Data2(); stackingLine100Series2.XBindingPath = "XValue"; stackingLine100Series2.YBindingPath = "YValue"; stackingLine100Series2.DataMarker.ShowMarker = true; stackingLine100Series2.DataMarker.MarkerColor = Color.White; stackingLine100Series2.DataMarker.MarkerWidth = 10; stackingLine100Series2.DataMarker.MarkerHeight = 10; stackingLine100Series2.DataMarker.MarkerStrokeColor = Color.ParseColor("#404041"); stackingLine100Series2.DataMarker.MarkerStrokeWidth = 2; stackingLine100Series2.StrokeWidth = 3; stackingLine100Series2.LegendIcon = ChartLegendIcon.SeriesType; StackingLine100Series stackingLine100Series3 = new StackingLine100Series(); stackingLine100Series3.EnableAnimation = true; stackingLine100Series3.Label = "Mother"; stackingLine100Series3.ItemsSource = MainPage.GetStackedLine100Data3(); stackingLine100Series3.XBindingPath = "XValue"; stackingLine100Series3.YBindingPath = "YValue"; stackingLine100Series3.DataMarker.ShowMarker = true; stackingLine100Series3.DataMarker.MarkerColor = Color.White; stackingLine100Series3.DataMarker.MarkerWidth = 10; stackingLine100Series3.DataMarker.MarkerHeight = 10; stackingLine100Series3.DataMarker.MarkerStrokeColor = Color.ParseColor("#357cd2"); stackingLine100Series3.DataMarker.MarkerStrokeWidth = 2; stackingLine100Series3.StrokeWidth = 3; stackingLine100Series3.LegendIcon = ChartLegendIcon.SeriesType; StackingLine100Series stackingLine100Series4 = new StackingLine100Series(); stackingLine100Series4.EnableAnimation = true; stackingLine100Series4.Label = "Father"; stackingLine100Series4.ItemsSource = MainPage.GetStackedLine100Data4(); stackingLine100Series4.XBindingPath = "XValue"; stackingLine100Series4.YBindingPath = "YValue"; stackingLine100Series4.DataMarker.ShowMarker = true; stackingLine100Series4.DataMarker.MarkerColor = Color.White; stackingLine100Series4.DataMarker.MarkerWidth = 10; stackingLine100Series4.DataMarker.MarkerHeight = 10; stackingLine100Series4.DataMarker.MarkerStrokeColor = Color.ParseColor("#e56590"); stackingLine100Series4.DataMarker.MarkerStrokeWidth = 2; stackingLine100Series4.StrokeWidth = 3; stackingLine100Series4.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingLine100Series1); chart.Series.Add(stackingLine100Series2); chart.Series.Add(stackingLine100Series3); chart.Series.Add(stackingLine100Series4); stackingLine100Series1.TooltipEnabled = true; stackingLine100Series2.TooltipEnabled = true; stackingLine100Series3.TooltipEnabled = true; stackingLine100Series4.TooltipEnabled = true; stackingLine100Series1.EnableAnimation = true; stackingLine100Series2.EnableAnimation = true; stackingLine100Series3.EnableAnimation = true; stackingLine100Series4.EnableAnimation = true; return chart; } } }<file_sep>/iOS/SampleBrowser/Samples/Diagram/MindMap.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using CoreGraphics; using System.Drawing; using Syncfusion.SfDiagram.iOS; using UIKit; using SolidBrush = Syncfusion.SfDiagram.iOS.SolidBrush; using Pen = Syncfusion.SfDiagram.iOS.Pen; namespace SampleBrowser { public partial class MindMap : SampleView { Node RootNode; UserHandleCollection DefaultHandles; UserHandleCollection RightSideHandle; UserHandleCollection LeftSideHandles; Node SelectedNode; UIView Notifier; UIView InfoNotifier; UITextView textinput; UserHandlePosition CurrentHandle; Random rnd = new Random(); UIImageView ExpandTemplate; UIImageView CollapseTemplate; List<NodeStyle> nodeStyleCollection = new List<NodeStyle>(); LineStyle lineStyle; String path; UITextView CommentBoxEntry=new UITextView(); List<UIColor> FColor = new List<UIColor>(); List<UIColor> SColor = new List<UIColor>(); string CommentText; int index; SfDiagram diagram = new SfDiagram(); UILabel schemaLabel; UIPickerView selectionPicker1; UIScrollView scrollView = new UIScrollView(); object objShape1 = ShapeType.RoundedRectangle; object objShape2 = ShapeType.RoundedRectangle; object objShape3 = ShapeType.RoundedRectangle; object objShape4 = ShapeType.RoundedRectangle; object objShape5 = ShapeType.RoundedRectangle; SegmentType segment = SegmentType.CurveSegment; int themeIndex = 0; String simpleCurveTree = "default"; SfGraphics gra = new SfGraphics(); List<Point> point = new List<Point>(); DecoratorType Dectype = DecoratorType.None; UIColor connColor = UIColor.Gray; ApplyColorFrom connColorFrom = ApplyColorFrom.TargetBorder; ApplyColorFrom connDecColorFrom = ApplyColorFrom.TargetBorder; VerticalAlignment fontVerticalAlignment = VerticalAlignment.Center; UIButton defaultTree=new UIButton(); UIButton contTree= new UIButton(); UIButton orgTree= new UIButton(); UIButton simpleTree= new UIButton(); private UILabel layoutOptionLabel; private UISwitch layoutOptionSwitch; public MindMap() { selectionPicker1 = new UIPickerView(); this.OptionView = new UIView(); schemaLabel = new UILabel(); schemaLabel.Text = "Schema"; schemaLabel.TextColor = UIColor.Black; schemaLabel.TextAlignment = UITextAlignment.Left; schemaLabel.BackgroundColor = UIColor.Clear; scrollView.BackgroundColor = UIColor.Clear; scrollView.ScrollEnabled = true; scrollView.ShowsHorizontalScrollIndicator = true; scrollView.ShowsVerticalScrollIndicator = false; defaultTree = AddLayoutButton(10, "mindmapDefault"); defaultTree.Layer.BorderWidth = 2; defaultTree.Layer.BorderColor = UIColor.FromRGB(30,144,255).CGColor; defaultTree.TouchUpInside+= DefaultTree_TouchUpInside; scrollView.AddSubview(defaultTree); contTree = AddLayoutButton(170, "mindmapconttree"); contTree.TouchUpInside += ContTree_TouchUpInside; scrollView.AddSubview(contTree); orgTree = AddLayoutButton(330, "mindmaportho"); orgTree.TouchUpInside+= OrgTree_TouchUpInside; scrollView.AddSubview(orgTree); simpleTree = AddLayoutButton(490, "mindmapsimpletree"); simpleTree.TouchUpInside+= SimpleTree_TouchUpInside; scrollView.AddSubview(simpleTree); layoutOptionLabel = new UILabel(); layoutOptionLabel.Text = "Free Form"; layoutOptionLabel.TextColor = UIColor.Black; layoutOptionLabel.TextAlignment = UITextAlignment.Left; layoutOptionLabel.BackgroundColor = UIColor.Clear; layoutOptionSwitch = new UISwitch(); layoutOptionSwitch.TouchUpInside += LayoutOptionSwitch_TouchUpInside; layoutOptionSwitch.BackgroundColor = UIColor.Clear; var width = 150; var height = 75; path = "Images/Diagram/MindMapImages/"; var node = AddNode(300, 400, width, height, "Goals"); AddNodeStyle(node, HexToRGB("#d0ebff"), HexToRGB("#81bfea")); RootNode = node; diagram.AddNode(node); SColor.Add(HexToRGB("#d1afdf")); SColor.Add(HexToRGB("#90C8C2")); SColor.Add(HexToRGB("#8BC1B7")); SColor.Add(HexToRGB("#E2C180")); SColor.Add(HexToRGB("#BBBFD6")); SColor.Add(HexToRGB("#ACCBAA")); FColor.Add(HexToRGB("#e9d4f1")); FColor.Add(HexToRGB("#d4efed")); FColor.Add(HexToRGB("#c4f2e8")); FColor.Add(HexToRGB("#f7e0b3")); FColor.Add(HexToRGB("#DEE2FF")); FColor.Add(HexToRGB("#E5FEE4")); var ch1node = AddNode(100, 100, width, height, "Financial"); index = rnd.Next(5); AddNodeStyle(ch1node, FColor[index], SColor[index]); diagram.AddNode(ch1node); var ch1childnode = AddNode(100, 100, width, height, "Investment"); AddNodeStyle(ch1childnode, (ch1node.Style.Brush as SolidBrush).FillColor, (ch1node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch1childnode); var ch2node = AddNode(100, 600, width, height, "Social"); index = rnd.Next(5); AddNodeStyle(ch2node, FColor[index], SColor[index]); diagram.AddNode(ch2node); var ch2childnode1 = AddNode(100, 100, width, height, "Friends"); AddNodeStyle(ch2childnode1, (ch2node.Style.Brush as SolidBrush).FillColor, (ch2node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch2childnode1); var ch2childnode2 = AddNode(100, 100, width, height, "Family"); AddNodeStyle(ch2childnode2, (ch2node.Style.Brush as SolidBrush).FillColor, (ch2node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch2childnode2); var ch3node = AddNode(500, 100, width, height, "Personal"); index = rnd.Next(5); AddNodeStyle(ch3node, FColor[index], SColor[index]); diagram.AddNode(ch3node); var ch3childnode1 = AddNode(500, 100, width, height, "Sports"); AddNodeStyle(ch3childnode1, (ch3node.Style.Brush as SolidBrush).FillColor, (ch3node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch3childnode1); var ch3childnode2 = AddNode(500, 100, width, height, "Food"); AddNodeStyle(ch3childnode2, (ch3node.Style.Brush as SolidBrush).FillColor, (ch3node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch3childnode2); var ch4node = AddNode(500, 600, width, height, "Work"); index = rnd.Next(5); AddNodeStyle(ch4node, FColor[index], SColor[index]); diagram.AddNode(ch4node); var ch4childnode1 = AddNode(500, 100, width, height, "Project"); AddNodeStyle(ch4childnode1, (ch4node.Style.Brush as SolidBrush).FillColor, (ch4node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch4childnode1); var ch4childnode2 = AddNode(500, 100, width, height, "Career"); AddNodeStyle(ch4childnode2, (ch4node.Style.Brush as SolidBrush).FillColor, (ch4node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch4childnode2); diagram.AddConnector(AddConnector(node, ch1node)); diagram.AddConnector(AddConnector(node, ch2node)); diagram.AddConnector(AddConnector(node, ch3node)); diagram.AddConnector(AddConnector(node, ch4node)); diagram.AddConnector(AddConnector(ch1node, ch1childnode)); diagram.AddConnector(AddConnector(ch2node, ch2childnode1)); diagram.AddConnector(AddConnector(ch2node, ch2childnode2)); diagram.AddConnector(AddConnector(ch3node, ch3childnode1)); diagram.AddConnector(AddConnector(ch3node, ch3childnode2)); diagram.AddConnector(AddConnector(ch4node, ch4childnode1)); diagram.AddConnector(AddConnector(ch4node, ch4childnode2)); diagram.UserHandleClicked += Diagram_UserHandleClicked; AddHandles(); diagram.NodeClicked += Diagram_NodeClicked; diagram.Clicked += Diagram_DiagramClicked; diagram.Loaded += Diagram_Loaded; SelectedNode = node; diagram.TextChanged += Diagram_TextChanged; diagram.ConnectorClicked += Diagram_ConnectorClicked; this.AddSubview(diagram); diagram.ContextMenuSettings.Visibility = false; schemaLabel.Frame = new CGRect(this.Frame.X + 10, 100, 100, 30); scrollView.Frame = new CGRect(this.Frame.X + 10, 150, 300, 150); layoutOptionLabel.Frame = new CGRect(this.Frame.X + 10, 20, 150, 30); layoutOptionSwitch.Frame = new CGRect(this.Frame.X + 240, 20, 50, 30); scrollView.ContentSize = new CGSize(700, scrollView.ContentSize.Height); optionView(); } private void LayoutOptionSwitch_TouchUpInside(object sender, EventArgs e) { if ((sender as UISwitch).On) { (diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm = true; } else { (diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm = false; } } void DefaultTree_TouchUpInside(object sender, EventArgs e) { defaultTree.Layer.BorderWidth = 2; defaultTree.Layer.BorderColor = UIColor.FromRGB(30, 144, 255).CGColor; contTree.Layer.BorderWidth = 2; contTree.Layer.BorderColor = UIColor.Clear.CGColor; orgTree.Layer.BorderWidth = 2; orgTree.Layer.BorderColor = UIColor.Clear.CGColor; simpleTree.Layer.BorderWidth = 2; simpleTree.Layer.BorderColor = UIColor.Clear.CGColor; simpleCurveTree = "default"; objShape1 = ShapeType.RoundedRectangle; objShape2 = ShapeType.RoundedRectangle; objShape3 = ShapeType.RoundedRectangle; objShape4 = ShapeType.RoundedRectangle; objShape5 = ShapeType.RoundedRectangle; segment = SegmentType.CurveSegment; fontVerticalAlignment = VerticalAlignment.Center; Dectype = DecoratorType.None; connColor = UIColor.Black; connColorFrom = ApplyColorFrom.TargetBorder; connDecColorFrom = ApplyColorFrom.TargetBorder; UpdateLayoutStyle(themeIndex); } void ContTree_TouchUpInside(object sender, EventArgs e) { defaultTree.Layer.BorderWidth = 2; defaultTree.Layer.BorderColor = UIColor.Clear.CGColor; contTree.Layer.BorderWidth = 2; contTree.Layer.BorderColor = UIColor.FromRGB(30, 144, 255).CGColor; orgTree.Layer.BorderWidth = 2; orgTree.Layer.BorderColor = UIColor.Clear.CGColor; simpleTree.Layer.BorderWidth = 2; simpleTree.Layer.BorderColor = UIColor.Clear.CGColor; simpleCurveTree = "contCurveTree"; Pen pe = new Pen(); pe.StrokeBrush = new SolidBrush(HexToRGB("#949494")); pe.StrokeWidth = 3; point.Add(new Point(0, 37)); point.Add(new Point(150, 37)); gra.DrawLines(pe, point); objShape1 = ShapeType.Ellipse; objShape2 = gra; objShape3 = gra; objShape4 = gra; objShape5 = gra; segment = SegmentType.CurveSegment; fontVerticalAlignment = VerticalAlignment.Top; Dectype = DecoratorType.None; connColor = UIColor.Black; connColorFrom = ApplyColorFrom.TargetBorder; connDecColorFrom = ApplyColorFrom.TargetBorder; UpdateLayoutStyle(themeIndex); } void OrgTree_TouchUpInside(object sender, EventArgs e) { defaultTree.Layer.BorderWidth = 2; defaultTree.Layer.BorderColor = UIColor.Clear.CGColor; contTree.Layer.BorderWidth = 2; contTree.Layer.BorderColor = UIColor.Clear.CGColor; orgTree.Layer.BorderWidth = 2; orgTree.Layer.BorderColor = UIColor.FromRGB(30, 144, 255).CGColor; simpleTree.Layer.BorderWidth = 2; simpleTree.Layer.BorderColor = UIColor.Clear.CGColor; simpleCurveTree = "contCurveTree"; simpleCurveTree = "orthotree"; objShape1 = ShapeType.Rectangle; objShape2 = ShapeType.Rectangle; objShape3 = ShapeType.Rectangle; objShape4 = ShapeType.Rectangle; objShape5 = ShapeType.Rectangle; segment = SegmentType.OrthoSegment; fontVerticalAlignment = VerticalAlignment.Center; Dectype = DecoratorType.None; connColor = UIColor.Black; connColorFrom = ApplyColorFrom.TargetBorder; connDecColorFrom = ApplyColorFrom.TargetBorder; UpdateLayoutStyle(themeIndex); } void SimpleTree_TouchUpInside(object sender, EventArgs e) { defaultTree.Layer.BorderWidth = 2; defaultTree.Layer.BorderColor = UIColor.Clear.CGColor; contTree.Layer.BorderWidth = 2; contTree.Layer.BorderColor = UIColor.Clear.CGColor; orgTree.Layer.BorderWidth = 2; orgTree.Layer.BorderColor = UIColor.Clear.CGColor; simpleTree.Layer.BorderWidth = 2; simpleTree.Layer.BorderColor = UIColor.FromRGB(30, 144, 255).CGColor; simpleCurveTree = "simpleCurveTree"; objShape1 = ShapeType.RoundedRectangle; objShape2 = ShapeType.RoundedRectangle; objShape3 = ShapeType.RoundedRectangle; objShape4 = ShapeType.RoundedRectangle; objShape5 = ShapeType.RoundedRectangle; segment = SegmentType.CurveSegment; fontVerticalAlignment = VerticalAlignment.Center; Dectype = DecoratorType.None; connColor = HexToRGB("#949494"); connColorFrom = ApplyColorFrom.Custom; connDecColorFrom = ApplyColorFrom.Custom; UpdateLayoutStyle(themeIndex); } private void UpdateLayoutStyle(int themeIndex) { if (themeIndex == 0) { nodeStyleCollection.Clear(); bool m_repeatmode = true; if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#d7ebf6")), HexToRGB("#d7ebf6"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#ffebc4")), HexToRGB("#ffebc4"), objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#ffcdcd")), HexToRGB("#ffcdcd"), objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#e7eeb8")), HexToRGB("#e7eeb8"), objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#d7ebf6")), HexToRGB("#d7ebf6"), objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "orthotree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#d7ebf6")), HexToRGB("#b4d6e8"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#ffebc4")), HexToRGB("#f2dcb1"), objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#ffcdcd")), HexToRGB("#ecb6b6"), objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#e7eeb8")), HexToRGB("#d6dda6"), objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#d7ebf6")), HexToRGB("#b4d6e8"), objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { m_repeatmode = false; nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#d7ebf6")), HexToRGB("#b4d6e8"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { m_repeatmode = false; nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#d7ebf6")), HexToRGB("#d7ebf6"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#949494")), HexToRGB("#949494"), objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#949494")), HexToRGB("#949494"), objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#949494")), HexToRGB("#949494"), objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#949494")), HexToRGB("#949494"), objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connColorFrom,Dectype , connDecColorFrom, connDecColorFrom) {Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Branch, m_repeatmode)); } if (themeIndex == 1) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#eea4af")),HexToRGB("#ce2340"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#c6ebb4")),HexToRGB("#7cea56"), objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#a7c7ed")),HexToRGB("#2f75d3"), objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#eac4a1")),HexToRGB("#ce7023"), objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#ede3a2")),HexToRGB("#d6bb29"), objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 2) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#f0a8e1")),HexToRGB("#da2eb8"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#eec3eb")),HexToRGB("#ae8fa7"), objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#f0e8f0")),HexToRGB("#ae8fa7"), objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#9a88b7")),HexToRGB("#716587"), objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#efa6c8")),HexToRGB("#ae7893"), objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 3) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#f3d8d6")),HexToRGB("#e3a39f"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#e9afa4")),HexToRGB("#cd3e24"), objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#e6c6a7")),HexToRGB("#c5752d"), objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#e9d5b3")),HexToRGB("#cc9d44"), objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#ebc3a2")),HexToRGB("#cf7225"), objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 4) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#dabeb7")),HexToRGB("#a66757"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#c4b2a3")),HexToRGB("#714621"), objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#cec3cd")),HexToRGB("#897386"), objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#d2c2b9")),HexToRGB("#977460"), objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#d1c4c0")),HexToRGB("#92736e"), objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 5) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#c5cacd")),HexToRGB("#747f86"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#d3d2d6")),HexToRGB("#96979f"), objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#e7e8e7")),HexToRGB("#c2bac1"), objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#b3b9bb")),HexToRGB("#475859"), objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#c9cfce")),HexToRGB("#7f8d8a"), objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 6) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#a1c6de")),HexToRGB("#2174b1"), objShape1, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#a8c6ee")),HexToRGB("#2f76da"), objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#a4baef")),HexToRGB("#285cda"), objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#babaf3")),HexToRGB("#585be4"), objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(HexToRGB("#b9dadf")),HexToRGB("#57a5b3"), objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Clear),UIColor.Clear, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape2, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape3, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape4, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(UIColor.Gray),UIColor.Gray, objShape5, StrokeStyle.Default, new TextStyle((int)(14 ),UIColor.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } } private UIButton AddLayoutButton(int v, string img) { UIButton button = new UIButton(); button.BackgroundColor = UIColor.Clear; button.Frame = new CGRect(v, 0, 150, 100); var imgView = new UIImageView(); imgView.Frame = new CGRect(0, 0, 150, 100); imgView.Image = UIImage.FromBundle("Images/Diagram/MindMapImages/" + img); button.AddSubview(imgView); return button; } private void optionView() { this.OptionView.AddSubview(schemaLabel); this.OptionView.AddSubview(scrollView); this.OptionView.AddSubview(layoutOptionLabel); this.OptionView.AddSubview(layoutOptionSwitch); } private UIColor HexToRGB(string hexavalue) { int r = Convert.ToInt32(hexavalue.Substring(1, 2), 16); int g = Convert.ToInt32(hexavalue.Substring(3, 2), 16); int b = Convert.ToInt32(hexavalue.Substring(5, 2), 16); return UIColor.FromRGB(r, g, b); } private Connector AddConnector(Node node, Node ch1node) { var c1 = new Connector(); c1.SourceNode = node; c1.TargetNode = ch1node; c1.Style.StrokeBrush = new SolidBrush((c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor); c1.Style.StrokeStyle = StrokeStyle.Dashed; c1.Style.StrokeWidth = 3; c1.TargetDecoratorStyle.Fill = (c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor; c1.TargetDecoratorStyle.StrokeColor = (c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor; c1.SegmentType = SegmentType.CurveSegment; return c1; } private void AddNodeStyle(Node node, UIColor fill, UIColor Stroke) { node.Style.Brush = new SolidBrush(fill); node.Style.StrokeBrush = new SolidBrush(Stroke); } Node AddNode(int x, int y, int w, int h, string text) { var node = new Node(x, y, w, h); node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 2; node.Annotations.Add(new Annotation() { Content = text, FontSize = 15, TextBrush = new SolidBrush(UIColor.Black) }); return node; } private void AddAnnotation(string headertext) { Notifier = new UIView(); Notifier.Frame = new CGRect(UIScreen.MainScreen.Bounds.Width / 2 - 150, UIScreen.MainScreen.Bounds.Height / 2 - 190, 300, 150); Notifier.Layer.CornerRadius = 5; Notifier.BackgroundColor = UIColor.White; diagram.PageSettings.BackgroundColor = UIColor.DarkGray; diagram.Layer.Opacity = 0.2f; var title = new UILabel(); title.Frame = new CGRect(10, 10, Notifier.Frame.Width, 30); title.Text = headertext; title.TextColor = UIColor.Black; Notifier.AddSubview(title); textinput = new UITextView(); textinput.Frame = new CGRect(0, 50, Notifier.Frame.Width - 20, 50); textinput.BecomeFirstResponder(); Notifier.AddSubview(textinput); UIButton ok = new UIButton(); ok.Frame = new CGRect(0, 100, Notifier.Frame.Width, 50); ok.SetTitle("OK", UIControlState.Normal); ok.SetTitleColor(UIColor.Black, UIControlState.Normal); ok.TouchUpInside += Ok_TouchUpInside; Notifier.AddSubview(ok); this.AddSubview(Notifier); } private void AddHandles() { var template = new UIImageView(); template.Frame = new CGRect(0, 0, 25, 25); var img = UIImage.FromBundle(path + "plus.png"); template.Image = img; var template1 = new UIImageView(); template1.Frame = new CGRect(0, 0, 25, 25); img = UIImage.FromBundle(path + "plus.png"); template1.Image = img; var deltemplate = new UIImageView(); deltemplate.Frame = new CGRect(0, 0, 25, 25); img = UIImage.FromBundle(path + "delete.png"); deltemplate.Image = img; ExpandTemplate = new UIImageView(); ExpandTemplate.Frame = new CGRect(0, 0, 25, 25); img = UIImage.FromBundle(path + "expand.png"); ExpandTemplate.Image = img; CollapseTemplate = new UIImageView(); CollapseTemplate.Frame = new CGRect(0, 0, 25, 25); img = UIImage.FromBundle(path + "collpase.png"); CollapseTemplate.Image = img; var moretemplate = new UIImageView(); moretemplate.Frame = new CGRect(0, 0, 25, 25); img = UIImage.FromBundle(path + "more.png"); moretemplate.Image = img; DefaultHandles = new UserHandleCollection(diagram); DefaultHandles.Add(new UserHandle("Left", UserHandlePosition.Left, template)); DefaultHandles.Add(new UserHandle("Right", UserHandlePosition.Right, template1)); DefaultHandles.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, CollapseTemplate)); DefaultHandles.Add(new UserHandle("info", UserHandlePosition.TopRight, moretemplate)); diagram.UserHandles = DefaultHandles; RightSideHandle = new UserHandleCollection(diagram); RightSideHandle.Add(new UserHandle("Right", UserHandlePosition.Right, template)); RightSideHandle.Add(new UserHandle("Delete", UserHandlePosition.Bottom, deltemplate)); RightSideHandle.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, CollapseTemplate)); RightSideHandle.Add(new UserHandle("info", UserHandlePosition.TopRight, moretemplate)); LeftSideHandles = new UserHandleCollection(diagram); LeftSideHandles.Add(new UserHandle("Left", UserHandlePosition.Left, template)); LeftSideHandles.Add(new UserHandle("Delete", UserHandlePosition.Bottom, deltemplate)); LeftSideHandles.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, CollapseTemplate)); LeftSideHandles.Add(new UserHandle("info", UserHandlePosition.TopRight, moretemplate)); } void Diagram_TextChanged(object sender, TextChangedEventArgs args) { args.Item.TextBrush = new SolidBrush(UIColor.Black); args.Item.FontSize = 15; } private void Diagram_Loaded(object sender) { diagram.EnableDrag = false; diagram.ShowSelectorHandle(false, SelectorPosition.SourcePoint); diagram.ShowSelectorHandle(false, SelectorPosition.TargetPoint); diagram.ShowSelectorHandle(false, SelectorPosition.Rotator); diagram.ShowSelectorHandle(false, SelectorPosition.TopLeft); diagram.ShowSelectorHandle(false, SelectorPosition.TopRight); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleLeft); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleRight); diagram.ShowSelectorHandle(false, SelectorPosition.BottomCenter); diagram.ShowSelectorHandle(false, SelectorPosition.BottomLeft); diagram.ShowSelectorHandle(false, SelectorPosition.BottomRight); diagram.ShowSelectorHandle(false, SelectorPosition.TopCenter); diagram.LayoutManager = new LayoutManager() { Layout = new MindMapLayout() { MindMapOrientation = Syncfusion.SfDiagram.iOS.Orientation.Horizontal, HorizontalSpacing = 70, } }; if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) { diagram.LayoutManager.Layout.UpdateLayout(); } diagram.Select(RootNode); diagram.BringToView(RootNode); UpdateLayoutStyle(0); } private void Diagram_DiagramClicked(object sender, DiagramClickedEventArgs args) { diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; if (Notifier != null && Notifier.Superview==this) { Notifier.RemoveFromSuperview(); } if (InfoNotifier != null && InfoNotifier.Superview == this) { if (CommentBoxEntry != null && CommentBoxEntry.Text != null) { SelectedNode.Content = CommentBoxEntry.Text; } InfoNotifier.RemoveFromSuperview(); } SelectedNode = null; } private void Diagram_UserHandleClicked(object sender, UserHandleClickedEventArgs args) { if (Notifier != null && Notifier.Superview == this) { Notifier.RemoveFromSuperview(); diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; } else if (InfoNotifier != null && InfoNotifier.Superview == this) { InfoNotifier.RemoveFromSuperview(); } else { if (args.Item.Name == "Delete") { diagram.RemoveNode(SelectedNode, true); if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayout(); } else if (args.Item.Name == "ExpColl") { if (SelectedNode.IsExpanded) { SelectedNode.IsExpanded = false; args.Item.Content = ExpandTemplate; diagram.UserHandles[0].Visible = false; if (SelectedNode == RootNode) diagram.UserHandles[1].Visible = false; } else { SelectedNode.IsExpanded = true; args.Item.Content = CollapseTemplate; diagram.UserHandles[0].Visible = true; if (SelectedNode == RootNode) diagram.UserHandles[1].Visible = true; } if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayout(); diagram.Select(SelectedNode); UpdateHandle(); } else if (args.Item.Name == "info") { ShowInfo(); } else { if (args.Item.Name == "Left") { CurrentHandle = UserHandlePosition.Left; AddAnnotation("Add Topic"); } else if (args.Item.Name == "Right") { CurrentHandle = UserHandlePosition.Right; AddAnnotation("Add Topic"); } } } } void ShowInfo() { int iconSize = 30; int notifierHeight = 50; int iconMargin = 85; diagram.PageSettings.BackgroundColor = UIColor.DarkGray; diagram.Layer.Opacity = 0.2f; InfoNotifier = new UIView(); InfoNotifier.Frame = new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height - 200); InfoNotifier.BackgroundColor = UIColor.FromRGB(39, 144, 249); this.AddSubview(InfoNotifier); UILabel title = new UILabel(); title.Frame = new CGRect(15, 5, 150, 50); if (SelectedNode.Content == null || (SelectedNode.Content as String).Equals("")) title.Text = " Add Note"; else title.Text = " Edit Note"; title.TextColor = UIColor.White; title.Font = UIFont.BoldSystemFontOfSize(18); InfoNotifier.AddSubview(title); UITextView CommentBoxEntry = new UITextView(); CommentBoxEntry.BecomeFirstResponder(); CommentBoxEntry.Frame = new CGRect(0, notifierHeight, InfoNotifier.Frame.Width, InfoNotifier.Frame.Height); if (SelectedNode.Content == null) { CommentBoxEntry.Text = ""; } CommentBoxEntry.Changed+= CommentBoxEntry_Changed; CommentBoxEntry.Text = (SelectedNode.Content as String); InfoNotifier.AddSubview(CommentBoxEntry); UIButton ok = new UIButton(); ok.Frame = new CGRect(InfoNotifier.Frame.Width - (iconMargin / 2), (notifierHeight / 2) - (iconSize / 2), iconSize, iconSize); ok.SetImage(new UIImage("Images/Diagram/MindMapImages/diagramTick.png"), UIControlState.Normal); ok.TouchUpInside += Ok_TouchUpInside1; InfoNotifier.AddSubview(ok); UIButton cancel = new UIButton(); cancel.Frame = new CGRect(InfoNotifier.Frame.Width - iconMargin, (notifierHeight / 2) - (iconSize / 2), iconSize, iconSize); cancel.SetImage(new UIImage("Images/Diagram/MindMapImages/diagramCross.png"), UIControlState.Normal); cancel.TouchUpInside += Cancel_TouchUpInside; InfoNotifier.AddSubview(cancel); } void Ok_TouchUpInside(object sender, EventArgs e) { diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; Notifier.RemoveFromSuperview(); if (textinput.Text == null) { textinput.Text = ""; } var node = new Node(); if (CurrentHandle == UserHandlePosition.Left) { node.OffsetX = SelectedNode.OffsetX - SelectedNode.Width - 100; node.OffsetY = SelectedNode.OffsetY; } else if (CurrentHandle == UserHandlePosition.Right) { node.OffsetX = SelectedNode.OffsetX + SelectedNode.Width + 100; node.OffsetY = SelectedNode.OffsetY; } node.Width = SelectedNode.Width; node.Height = SelectedNode.Height; node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 3; if (SelectedNode == RootNode) { index = rnd.Next(5); node.Style.Brush = new SolidBrush(FColor[index]); node.Style.StrokeBrush = new SolidBrush(SColor[index]); } else { node.Style = SelectedNode.Style; } node.Annotations.Add(new Annotation() { Content = textinput.Text, FontSize = 15, TextBrush = new SolidBrush(UIColor.Black) }); diagram.AddNode(node); var c1 = new Connector(); c1.SourceNode = SelectedNode; c1.TargetNode = node; c1.Style.StrokeBrush = node.Style.StrokeBrush; c1.Style.StrokeWidth = 3; c1.TargetDecoratorStyle.Fill = (node.Style.StrokeBrush as SolidBrush).FillColor; c1.TargetDecoratorStyle.StrokeColor = (node.Style.StrokeBrush as SolidBrush).FillColor; c1.SegmentType = SegmentType.CurveSegment; c1.Style.StrokeStyle = StrokeStyle.Dashed; diagram.AddConnector(c1); if (CurrentHandle == UserHandlePosition.Left) { diagram.UserHandles = LeftSideHandles; if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateLeftOrTop(); } else if (CurrentHandle == UserHandlePosition.Right) { diagram.UserHandles = RightSideHandle; if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateRightOrBottom(); } diagram.Select(node); SelectedNode = node; diagram.BringToView(node); if (node.Children.Any()) { diagram.UserHandles[2].Visible = true; } else diagram.UserHandles[2].Visible = false; UpdateLayoutStyle(themeIndex); } void Ok_TouchUpInside1(object sender, EventArgs e) { diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; if (CommentBoxEntry.Text != null) { SelectedNode.Content = CommentText; CommentText = null; } InfoNotifier.RemoveFromSuperview(); } void Cancel_TouchUpInside(object sender, EventArgs e) { diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; InfoNotifier.RemoveFromSuperview(); } private void Diagram_NodeClicked(object sender, NodeClickedEventArgs args) { SelectedNode = args.Item; diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; if (Notifier != null && Notifier.Superview==this) { Notifier.RemoveFromSuperview(); } else if (InfoNotifier != null && InfoNotifier.Superview == this) { InfoNotifier.RemoveFromSuperview(); } else { if (args.Item != RootNode && args.Item.OffsetX > RootNode.OffsetX) { diagram.UserHandles = RightSideHandle; } else if (args.Item != RootNode && args.Item.OffsetX < RootNode.OffsetX) { diagram.UserHandles = LeftSideHandles; } else if (args.Item == RootNode) { diagram.UserHandles = DefaultHandles; } if (SelectedNode.IsExpanded) { diagram.UserHandles[0].Visible = true; if (SelectedNode == RootNode) diagram.UserHandles[1].Visible = true; diagram.UserHandles[2].Content = CollapseTemplate; } else { diagram.UserHandles[0].Visible = false; if (SelectedNode == RootNode) diagram.UserHandles[1].Visible = false; diagram.UserHandles[2].Content = ExpandTemplate; } UpdateHandle(); if (SelectedNode.Children.Any()) { diagram.UserHandles[2].Visible = true; } else diagram.UserHandles[2].Visible = false; } } private String GetNodeDirection(Node node) { if(node == RootNode) { return "Center"; } else if (node.OffsetX > RootNode.OffsetX) { return "Right"; } else { return "Left"; } } internal void UpdateHandle() { var side = GetNodeDirection(SelectedNode); if (side == "Right") { if (SelectedNode.IsExpanded) { diagram.UserHandles[2].Content = ExpandTemplate; } else { diagram.UserHandles[2].Content = CollapseTemplate; } } else if (side == "Left") { //ExpColl if (SelectedNode.IsExpanded) { diagram.UserHandles[2].Content = CollapseTemplate; } else { diagram.UserHandles[2].Content = ExpandTemplate; } } } void Diagram_ConnectorClicked(object sender, ConnectorClickedEventArgs args) { diagram.ClearSelection(); if (Notifier != null && Notifier.Superview == this) { Notifier.RemoveFromSuperview(); } else if (InfoNotifier != null && InfoNotifier.Superview == this) { InfoNotifier.RemoveFromSuperview(); } } void CommentBoxEntry_Changed(object sender, EventArgs e) { CommentText = (sender as UITextView).Text; } } }<file_sep>/Forms/TreeMap/readme.md The tree map control provides a simple and effective way to visualize flat or hierarchical data as clustered rectangles with a specific, weighted attribute determining the size of each rectangle. This control has highly customizable features such as displaying hierarchical and flat-level data, legends, different layouts, and color mapping. The following samples are available for tree map to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Getting Started](TreeMap/Samples/TreeMapGettingStarted)| The tree map control provides a simple and effective way to visualize flat or hierarchical data as clustered rectangles. This sample explains a basic tree map control with color mapping and legend support. | | [Hierarchical](TreeMap/Samples/Hierarchical)| This sample shows how to add hierarchical data in a tree map. | | [Customization](TreeMap/Samples/TreeMapCustomization)| This sample shows how to customize tree map nodes with custom templates. | <file_sep>/Android/SampleBrowser/Samples/DataForm/Helpers/DataFormLayoutManagerExt.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.Android.DataForm; using Syncfusion.Android.DataForm.Editors; using Android.Graphics; namespace SampleBrowser { /// <summary> /// Represents a class that used to customize the DataForm. /// </summary> public class DataFormLayoutManagerExt : DataFormLayoutManager { public DataFormLayoutManagerExt(SfDataForm dataform) : base(dataform) { } /// <summary> /// Overridden to set the left padding for editor. /// </summary> protected override int GetLeftPaddingForEditor(DataFormItem dataFormItem) { if (dataFormItem.Name.Equals("MiddleName") || dataFormItem.Name.Equals("LastName") || dataFormItem.Name.Equals("ContactType")) { return 56; } return base.GetLeftPaddingForEditor(dataFormItem); } protected override int GetLeftPaddingForLabel(DataFormItem dataFormItem) { if (dataFormItem.Name.Equals("SaveTo")) { return 60; } return base.GetLeftPaddingForLabel(dataFormItem); } } }<file_sep>/Forms/DataForm/DataForm/Samples/ContactForm/Model/ContactInfo.cs #region Copyright // <copyright file="ContactInfo.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using Syncfusion.XForms.DataForm; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.ComponentModel.DataAnnotations; /// <summary> /// Represents the fields and properties of the data form. /// </summary> [Preserve(AllMembers = true)] public class ContactInfo : INotifyPropertyChanged { #region Fields /// <summary> /// Represents the contact name of the contact information. /// </summary> private string contactName; /// <summary> /// Represents the middle name of the contact information. /// </summary> private string middelName; /// <summary> /// Represents the last name of the contact information. /// </summary> private string lastname; /// <summary> /// Represents the contact number of the contact information. /// </summary> private string contactNo; /// <summary> /// Represents the contact image. /// </summary> private ImageSource image; /// <summary> /// Represents the contact type of the contact information. /// </summary> private ContactsType contactType; /// <summary> /// Represents the email type of the contact information. /// </summary> private ContactsType emailType; /// <summary> /// Represents the email field of the contact information. /// </summary> private string email; /// <summary> /// Represents the address type of the contact information. /// </summary> private AddressType addressType; /// <summary> /// Represents the adress of the contact information. /// </summary> private string address; /// <summary> /// Represents the notes of the contact information. /// </summary> private string notes; /// <summary> /// Represents the birth date of the contact information. /// </summary> private DateTime birthDate; /// <summary> /// Represents the group name of the contact information. /// </summary> private string groupName; /// <summary> /// Represents the save field of the contact information. /// </summary> private Save saveTo; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ContactInfo"/> class. /// </summary> public ContactInfo() { } /// <summary> /// Represents a method that will handle when a property is changed on a component. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Describes the possible contact type values. /// </summary> public enum ContactsType { /// <summary> /// Represents home. /// </summary> Home, /// <summary> /// Represents work. /// </summary> Work, /// <summary> /// Represents other contact type. /// </summary> Other, } /// <summary> /// Describes the possible address type. /// </summary> public enum AddressType { /// <summary> /// Represents home. /// </summary> Home, /// <summary> /// Represents office. /// </summary> Office } /// <summary> /// Describes the possible types to save. /// </summary> public enum Save { /// <summary> /// Represents sim. /// </summary> Sim, /// <summary> /// Represents phone. /// </summary> Phone } #endregion #region Public Properties /// <summary> /// Gets or sets the contact field in the contacts information. /// </summary> [DisplayOptions(ColumnSpan = 5)] [Display( GroupName = "Name", Order = 1 , ShortName ="Contact name")] public string ContactName { get { return this.contactName; } set { this.contactName = value; this.RaisePropertyChanged("ContactName"); } } /// <summary> /// Gets or sets the middle name field in the contacts information. /// </summary> [DisplayOptions(ColumnSpan = 5)] [Display( GroupName = "Name", Order = 2, ShortName = "Middle name")] public string MiddleName { get { return this.middelName; } set { this.middelName = value; this.RaisePropertyChanged("MiddleName"); } } /// <summary> /// Gets or sets the last name in the contacts information. /// </summary> [DisplayOptions(ColumnSpan = 5)] [Display( GroupName = "Name", Order = 3, ShortName = "Last name")] public string LastName { get { return this.lastname; } set { this.lastname = value; this.RaisePropertyChanged("LastName"); } } /// <summary> /// Gets or sets the contact number field in the contacts information. /// </summary> [Display( Order = 4, ShortName = "Contact number")] [DisplayOptions(ColumnSpan = 3)] [DataType(DataType.PhoneNumber)] [StringLength(10, ErrorMessage = "Phone number should not exceed 10 digits.")] public string ContactNumber { get { return this.contactNo; } set { this.contactNo = value; this.RaisePropertyChanged("ContactNumber"); } } /// <summary> /// Gets or sets the contact type in the contacts information. /// </summary> [DisplayOptions(ShowLabel = false , ColumnSpan = 2)] [Display(Order = 5)] public ContactsType ContactType { get { return this.contactType; } set { this.contactType = value; this.RaisePropertyChanged("ContactType"); } } /// <summary> /// Gets or sets the contact image in the contacts information. /// </summary> [Display(AutoGenerateField = false)] public ImageSource ContactImage { get { return this.image; } set { this.image = value; this.RaisePropertyChanged("ContactImage"); } } /// <summary> /// Gets or sets the email field in the contacts information. /// </summary> [Display( Order = 6)] [DisplayOptions(ColumnSpan = 3)] public string Email { get { return this.email; } set { this.email = value; this.RaisePropertyChanged("Email"); } } /// <summary> /// Gets or sets the email type in the contacts information. /// </summary> [DisplayOptions(ShowLabel = false , ColumnSpan = 2)] [Display(Order = 7)] public ContactsType EmailType { get { return this.emailType; } set { this.emailType = value; this.RaisePropertyChanged("EmailType"); } } /// <summary> /// Gets or sets the address field in the contacts information. /// </summary> [Display( Order = 8)] [DisplayOptions(ColumnSpan = 3)] public string Address { get { return this.address; } set { this.address = value; this.RaisePropertyChanged("Address"); } } /// <summary> /// Gets or sets the address type in the contacts information. /// </summary> [DisplayOptions(ShowLabel = false, ColumnSpan = 2)] [Display(Order = 9)] public AddressType AddressTypes { get { return this.addressType; } set { this.addressType = value; this.RaisePropertyChanged("AddressType"); } } /// <summary> /// Gets or sets the notes field in the contacts information. /// </summary> [DataType(DataType.MultilineText)] [Display( Order = 10)] [DisplayOptions(ColumnSpan = 5)] public string Notes { get { return this.notes; } set { this.notes = value; this.RaisePropertyChanged("Notes"); } } /// <summary> /// Gets or sets the birth date field in the contacts information. /// </summary> [Display( Order = 11, ShortName = "Birth date")] [DisplayOptions(ColumnSpan = 5)] public DateTime BirthDate { get { return this.birthDate; } set { this.birthDate = value; this.RaisePropertyChanged("BirthDate"); } } /// <summary> /// Gets or sets the group name field in the contacts information. /// </summary> [Display(Order = 12, ShortName = "Group name")] [DisplayOptions(ColumnSpan = 5)] public string GroupName { get { return this.groupName; } set { this.groupName = value; this.RaisePropertyChanged("GroupName"); } } /// <summary> /// Gets or sets the save field in the contacts information. /// </summary> [Display(ShortName = "Save To", Order = 13)] [DisplayOptions(ColumnSpan = 5)] public Save SaveTo { get { return this.saveTo; } set { this.saveTo = value; this.RaisePropertyChanged("SaveTo"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Occurs when propery value is changed. /// </summary> /// <param name="name">Property name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/iOS/SampleBrowser/Samples/DigitalGauge/readme.md The digital gauge control is used to display alphanumeric characters in digital mode. It displays a range of values that uses characters in combination with numbers. The following sample is available for digital gauge to demonstrate the functionalities of its feature. | Sample | Description | | ------ | ----------- | | [Digital Gauge](DigitalGauge.cs)| A digital gauge is used to display alphanumeric characters in digital modes. In this sample, current time is displayed in four types of digital modes such as 7 segment, 14 segment, 16 segment, and 8*8 segment. | <file_sep>/iOS/SampleBrowser/Samples/XlsIO/ImportNestedCollection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XlsIO; using System.IO; using Syncfusion.Drawing; using System.Reflection; using System.Collections.Generic; using Syncfusion.iOS.Buttons; using System.ComponentModel; using System.Xml.Serialization; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class ImportNestedCollection : SampleView { public ImportNestedCollection() { this.layoutList.Add((NSString)"Default"); this.layoutList.Add((NSString)"Merge"); this.layoutList.Add((NSString)"Repeat"); } CGRect frameRect = new CGRect (); float frameMargin = 8.0f; private readonly IList<string> layoutList = new List<string>(); string selectedLayout; UILabel layoutLabel; UIButton layoutDoneButton; UIButton layoutButton; UIPickerView layoutPicker; UILabel groupLabel; UISwitch groupSwitch; UILabel groupOptionsLabel; SfRadioGroup radioGroup = new SfRadioGroup(); SfRadioButton expandButton = new SfRadioButton(); SfRadioButton collapseButton = new SfRadioButton(); UITextField textField; UIButton button; bool isLoaded = false; bool isGroupEnabled = false; bool isTextEnabled = false; void LoadAllowedTextsLabel() { #region Description Label UILabel label = new UILabel (); label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to filter data within a range of Excel worksheet."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width ,35); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width ,50); } this.AddSubview (label); #endregion #region Layout Region layoutLabel = new UILabel(); layoutDoneButton = new UIButton(); layoutButton = new UIButton(); layoutPicker = new UIPickerView(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { layoutLabel.Font = UIFont.SystemFontOfSize(18); layoutLabel.Frame = new CGRect(10, 45, this.Frame.Size.Width / 2, 50); layoutButton.Frame = new CGRect(150, 45, this.Frame.Size.Width / 2, 40); } else { layoutLabel.Frame = new CGRect(10, 50, this.Frame.Size.Width / 2, 50); layoutButton.Frame = new CGRect(150, 50, this.Frame.Size.Width / 2, 40); } //filter Label layoutLabel.TextColor = UIColor.Black; layoutLabel.BackgroundColor = UIColor.Clear; layoutLabel.Text = @"Layout Options"; layoutLabel.TextAlignment = UITextAlignment.Left; layoutLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(layoutLabel); //filter button layoutButton.SetTitle("Default", UIControlState.Normal); layoutButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; layoutButton.BackgroundColor = UIColor.Clear; layoutButton.SetTitleColor(UIColor.Black, UIControlState.Normal); layoutButton.Hidden = false; layoutButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; layoutButton.Layer.BorderWidth = 4; layoutButton.Layer.CornerRadius = 8; layoutButton.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(layoutButton); layoutButton.TouchUpInside += ShowLayoutPicker; //filterpicker PickerModel layoutPickermodel = new PickerModel(this.layoutList); layoutPickermodel.PickerChanged += (sender, e) => { this.selectedLayout = e.SelectedValue; layoutButton.SetTitle(selectedLayout, UIControlState.Normal); }; layoutPicker = new UIPickerView(); layoutPicker.ShowSelectionIndicator = true; layoutPicker.Hidden = true; layoutPicker.Model = layoutPickermodel; layoutPicker.BackgroundColor = UIColor.White; //filterDoneButtonn layoutDoneButton = new UIButton(); layoutDoneButton.SetTitle("Done\t", UIControlState.Normal); layoutDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; layoutDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); layoutDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); layoutDoneButton.Hidden = true; layoutDoneButton.TouchUpInside += HideLayoutPicker; layoutPicker.Frame = new CGRect(150, 50, this.Frame.Size.Width / 2, this.Frame.Size.Height / 3); layoutDoneButton.Frame = new CGRect(150, 55, this.Frame.Size.Width / 2, 40); this.AddSubview(layoutPicker); this.AddSubview(layoutDoneButton); #endregion #region Group Region //unique records label groupLabel = new UILabel(); groupLabel.TextColor = UIColor.Black; groupLabel.BackgroundColor = UIColor.Clear; groupLabel.Text = @"Apply Group"; groupLabel.TextAlignment = UITextAlignment.Left; groupLabel.Font = UIFont.FromName("Helvetica", 16f); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) groupLabel.Frame = new CGRect(60, 105, this.Frame.Size.Width / 2, 40); else groupLabel.Frame = new CGRect(60, 110, this.Frame.Size.Width / 2, 40); this.AddSubview(groupLabel); //unique records switch groupSwitch = new UISwitch(); groupSwitch.On = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) groupSwitch.Frame = new CGRect(150, 105, this.Frame.Size.Width / 2, 40); else groupSwitch.Frame = new CGRect(150, 110, this.Frame.Size.Width / 2, 40); groupSwitch.TouchUpInside += ShowGroupOptions; this.AddSubview(groupSwitch); #endregion #region Group Options Region //filter Label groupOptionsLabel = new UILabel(); groupOptionsLabel.TextColor = UIColor.Black; groupOptionsLabel.BackgroundColor = UIColor.Clear; groupOptionsLabel.Text = "Options"; groupOptionsLabel.TextAlignment = UITextAlignment.Left; groupOptionsLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(groupOptionsLabel); groupOptionsLabel.Hidden = true; radioGroup.Axis = UILayoutConstraintAxis.Vertical; expandButton.SetTitle("Expand", UIControlState.Normal); radioGroup.AddArrangedSubview(expandButton); collapseButton.SetTitle("Group at Level", UIControlState.Normal); radioGroup.AddArrangedSubview(collapseButton); expandButton.IsChecked = true; radioGroup.Distribution = UIStackViewDistribution.FillProportionally; this.AddSubview(radioGroup); radioGroup.Hidden = true; expandButton.StateChanged += ShowHideTextField; collapseButton.StateChanged += ShowHideTextField; textField = new UITextField(); textField.TextColor = UIColor.Black; textField.BackgroundColor = UIColor.Clear; textField.Text = "1"; textField.TextAlignment = UITextAlignment.Left; textField.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(textField); textField.Hidden = true; #endregion #region Button Region //button button = new UIButton (UIButtonType.System); button.SetTitle("Generate Excel", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 155, frameRect.Location.X + frameRect.Size.Width, 20); } else { button.Frame = new CGRect(0, 160, frameRect.Location.X + frameRect.Size.Width, 20); } button.TouchUpInside += OnButtonClicked; this.AddSubview (button); #endregion isLoaded = true; } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; IWorkbook workbook = application.Workbooks.Create(1); IWorksheet worksheet = workbook.Worksheets[0]; IList<Brands> list = GetVehicleDetails(); int index = layoutList.IndexOf(selectedLayout); ExcelImportDataOptions importDataOptions = new ExcelImportDataOptions(); importDataOptions.FirstRow = 4; if (index == 0) importDataOptions.NestedDataLayoutOptions = ExcelNestedDataLayoutOptions.Default; else if (index == 1) importDataOptions.NestedDataLayoutOptions = ExcelNestedDataLayoutOptions.Merge; else if (index == 2) importDataOptions.NestedDataLayoutOptions = ExcelNestedDataLayoutOptions.Repeat; if (groupSwitch.Selected) { if (expandButton.IsChecked.Value) { importDataOptions.NestedDataGroupOptions = ExcelNestedDataGroupOptions.Expand; } else if (collapseButton.IsChecked.Value) { importDataOptions.NestedDataGroupOptions = ExcelNestedDataGroupOptions.Collapse; if (textField.Text != string.Empty) { importDataOptions.CollapseLevel = int.Parse(textField.Text); } } } worksheet.ImportData(list, importDataOptions); #region Define Styles IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle"); IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle"); pageHeader.Font.FontName = "Calibri"; pageHeader.Font.Size = 16; pageHeader.Font.Bold = true; pageHeader.Color = Color.FromArgb(0, 146, 208, 80); pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Font.Bold = true; tableHeader.Font.FontName = "Calibri"; tableHeader.Color = Color.FromArgb(0, 146, 208, 80); #endregion #region Apply Styles // Apply style for header worksheet["A1:C2"].Merge(); worksheet["A1"].Text = "Automobile Brands in the US"; worksheet["A1"].CellStyle = pageHeader; worksheet["A4:C4"].CellStyle = tableHeader; worksheet["A1:C1"].CellStyle.Font.Bold = true; worksheet.UsedRange.AutofitColumns(); #endregion MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("ImportData.xlsx", "application/msexcel", stream); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); if(!isLoaded) LoadAllowedTextsLabel (); base.LayoutSubviews(); } void ShowLayoutPicker(object sender, EventArgs e) { layoutDoneButton.Hidden = false; layoutPicker.Hidden = false; groupLabel.Hidden = true; groupSwitch.Hidden = true; groupOptionsLabel.Hidden = true; radioGroup.Hidden = true; textField.Hidden = true; button.Hidden = true; this.BecomeFirstResponder(); } void HideLayoutPicker(object sender, EventArgs e) { layoutDoneButton.Hidden = true; layoutPicker.Hidden = true; groupLabel.Hidden = false; groupSwitch.Hidden = false; if (isGroupEnabled) { groupOptionsLabel.Hidden = false; radioGroup.Hidden = false; if (isTextEnabled) { textField.Hidden = false; } } button.Hidden = false; this.BecomeFirstResponder(); } void ShowGroupOptions(object sender, EventArgs e) { isGroupEnabled = true; if (groupSwitch.On) { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) groupOptionsLabel.Frame = new CGRect(150, 150, this.Frame.Size.Width / 2, 25); else groupOptionsLabel.Frame = new CGRect(150, 155, this.Frame.Size.Width / 2, 25); groupOptionsLabel.Hidden = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { radioGroup.Frame = new CGRect(150, 180, this.Frame.Size.Width / 2, 80); } else { radioGroup.Frame = new CGRect(150, 185, this.Frame.Size.Width / 2, 80); } radioGroup.Hidden = false; if (isTextEnabled) { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) textField.Frame = new CGRect(160, 270, this.Frame.Size.Width / 2, 30); else textField.Frame = new CGRect(160, 275, this.Frame.Size.Width / 2, 30); textField.Hidden = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 310, frameRect.Location.X + frameRect.Size.Width, 20); } else { button.Frame = new CGRect(0, 315, frameRect.Location.X + frameRect.Size.Width, 20); } } else { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 270, frameRect.Location.X + frameRect.Size.Width, 20); } else { button.Frame = new CGRect(0, 275, frameRect.Location.X + frameRect.Size.Width, 20); } } } else { groupOptionsLabel.Hidden = true; radioGroup.Hidden = true; textField.Hidden = true; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 155, frameRect.Location.X + frameRect.Size.Width, 20); } else { button.Frame = new CGRect(0, 160, frameRect.Location.X + frameRect.Size.Width, 20); } isGroupEnabled = false; } this.BecomeFirstResponder(); } void ShowHideTextField(object sender, EventArgs e) { if(collapseButton.IsChecked.Value) { isTextEnabled = true; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) textField.Frame = new CGRect(160, 270, this.Frame.Size.Width / 2, 30); else textField.Frame = new CGRect(160, 275, this.Frame.Size.Width / 2, 30); textField.Hidden = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 310, frameRect.Location.X + frameRect.Size.Width, 20); } else { button.Frame = new CGRect(0, 315, frameRect.Location.X + frameRect.Size.Width, 20); } } else { isTextEnabled = false; textField.Hidden = true; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 270, frameRect.Location.X + frameRect.Size.Width, 20); } else { button.Frame = new CGRect(0, 275, frameRect.Location.X + frameRect.Size.Width, 20); } } this.BecomeFirstResponder(); } #region Helper Methods private IList<Brands> GetVehicleDetails() { XmlSerializer deserializer = new XmlSerializer(typeof(BrandObjects)); string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExportData.xml"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); TextReader textReader = new StreamReader(fileStream); BrandObjects brands = (BrandObjects)deserializer.Deserialize(textReader); List<Brands> list = new List<Brands>(); string brandName = brands.BrandObject[0].BrandName; string vehicleType = brands.BrandObject[0].VahicleType; string modelName = brands.BrandObject[0].ModelName; Brands brand = new Brands(brandName); brand.VehicleTypes = new List<VehicleTypes>(); VehicleTypes vehicle = new VehicleTypes(vehicleType); vehicle.Models = new List<Models>(); Models model = new Models(modelName); brand.VehicleTypes.Add(vehicle); list.Add(brand); foreach (BrandObject brandObj in brands.BrandObject) { if (brandName == brandObj.BrandName) { if (vehicleType == brandObj.VahicleType) { vehicle.Models.Add(new Models(brandObj.ModelName)); continue; } else { vehicle = new VehicleTypes(brandObj.VahicleType); vehicle.Models = new List<Models>(); vehicle.Models.Add(new Models(brandObj.ModelName)); brand.VehicleTypes.Add(vehicle); vehicleType = brandObj.VahicleType; } continue; } else { brand = new Brands(brandObj.BrandName); vehicle = new VehicleTypes(brandObj.VahicleType); vehicle.Models = new List<Models>(); vehicle.Models.Add(new Models(brandObj.ModelName)); brand.VehicleTypes = new List<VehicleTypes>(); brand.VehicleTypes.Add(vehicle); vehicleType = brandObj.VahicleType; list.Add(brand); brandName = brandObj.BrandName; } } textReader.Close(); return list; } #endregion } #region Helper Class [XmlRootAttribute("BrandObjects")] public class BrandObjects { [XmlElement("BrandObject")] public BrandObject[] BrandObject { get; set; } } public class BrandObject { public string BrandName { get; set; } public string VahicleType { get; set; } public string ModelName { get; set; } } public class Brands { private string m_brandName; [DisplayNameAttribute("Brand")] public string BrandName { get { return m_brandName; } set { m_brandName = value; } } private IList<VehicleTypes> m_vehicleTypes; public IList<VehicleTypes> VehicleTypes { get { return m_vehicleTypes; } set { m_vehicleTypes = value; } } public Brands(string brandName) { m_brandName = brandName; } } public class VehicleTypes { private string m_vehicleName; [DisplayNameAttribute("Vehicle Type")] public string VehicleName { get { return m_vehicleName; } set { m_vehicleName = value; } } private IList<Models> m_models; public IList<Models> Models { get { return m_models; } set { m_models = value; } } public VehicleTypes(string vehicle) { m_vehicleName = vehicle; } } public class Models { private string m_modelName; [DisplayNameAttribute("Model")] public string ModelName { get { return m_modelName; } set { m_modelName = value; } } public Models(string name) { m_modelName = name; } } #endregion } <file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/EditTextAnnotationHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Reflection; using CoreGraphics; using Syncfusion.SfPdfViewer.iOS; using Syncfusion.SfRangeSlider.iOS; using UIKit; namespace SampleBrowser { class EditTextAnnotationHelper { CustomToolbar parent; TextMarkupAnnotationHelper textmarkupHelper; AnnotationHelper annotHelper; internal const float DefaultToolbarHeight = 50f; CGColor separatorgray = UIColor.FromRGBA(red: 0.86f, green: 0.86f, blue: 0.86f, alpha: 1.0f).CGColor; internal UIButton editButton = new UIButton(); internal UIButton editTextButton = new UIButton(); internal const float DefaultEditToolbarHeight = 50f; internal UILabel rangeSliderLabel = new UILabel(); public EditTextAnnotationHelper(CustomToolbar customtoolbar) { parent = customtoolbar; } public EditTextAnnotationHelper(TextMarkupAnnotationHelper helper, CustomToolbar customtoolbar) { textmarkupHelper = helper; parent = customtoolbar; } public EditTextAnnotationHelper(AnnotationHelper annottoolbar, CustomToolbar customtoolbar) { annotHelper = annottoolbar; parent = customtoolbar; } internal void PdfViewerControl_FreeTextPopupDisappearing(object sender, FreeTextPopupDisappearedEventArgs args) { if (args.PopupResult == FreeTextPopupResult.Cancel || args.PopupResult == FreeTextPopupResult.Ok) { parent.editTextAnnotationToolbar.RemoveFromSuperview(); if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) parent.pdfViewerControl.AnnotationMode = AnnotationMode.None; } } internal void PdfViewerControl_FreeTextAnnotationSelected(object sender, FreeTextAnnotationSelectedEventArgs args) { parent.annotation = sender as FreeTextAnnotation; parent.toolbarBackbutton.RemoveFromSuperview(); parent.isOpacityNeeded = false; parent.iseditEnable = true; parent.annotationFrame = parent.Frame; parent.annotationFrame.Height = DefaultToolbarHeight; parent.annotationFrame.Y = parent.parentView.Frame.Height - parent.annotationFrame.Height + 4; parent.editTextAnnotationToolbar.Frame = parent.annotationFrame; parent.editTextAnnotationToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); parent.editTextAnnotationToolbar.RemoveFromSuperview(); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) editTextButton.Frame = new CGRect(65, 7, 35, 35); else editTextButton.Frame = new CGRect(40, 7, 35, 35); editTextButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; editTextButton.Font = parent.highFont; editTextButton.SetTitle("\ue700", UIControlState.Normal); editTextButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.editTextAnnotationToolbar.Add(editTextButton); if (parent.iseditEnable) { editButton.Frame = new CGRect(parent.parentView.Frame.Width - 200, 7, 35, 35); editButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; editButton.Font = parent.highFont; editButton.TouchUpInside += EditButton_TouchUpInside; editButton.SetTitle("\ue720", UIControlState.Normal); editButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.editTextAnnotationToolbar.Add(editButton); } else { editButton.RemoveFromSuperview(); } parent.edittextThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 150, 7, 30, 30); parent.edittextThicknessButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.edittextThicknessButton.Font = parent.fontSizeFont; parent.edittextThicknessButton.SetTitle("\ue700", UIControlState.Normal); parent.edittextThicknessButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.editTextAnnotationToolbar.Add(parent.edittextThicknessButton); parent.edittextColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 100, 7, 30, 30); parent.edittextColorButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; if (parent.annotation != null) parent.edittextColorButton.BackgroundColor = (parent.annotation as FreeTextAnnotation).Settings.TextColor; else parent.edittextColorButton.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.FreeText.TextColor; parent.editTextAnnotationToolbar.Add(parent.edittextColorButton); parent.editTextAnnotationToolbar = parent.UpdateToolbarBorder(parent.editTextAnnotationToolbar, parent.annotationFrame); parent.Add(parent.editTextAnnotationToolbar); parent.edittextDeleteButton.Frame = new CGRect(parent.parentView.Frame.Width - 55, 7, 35, 35); parent.edittextDeleteButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.edittextDeleteButton.TouchUpInside += parent.inkHelper.InkdeleteButton_TouchUpInside; parent.edittextDeleteButton.Font = parent.highFont; parent.edittextDeleteButton.SetTitle("\ue714", UIControlState.Normal); parent.edittextDeleteButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.editTextAnnotationToolbar.Add(parent.edittextDeleteButton); } private void EditButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.EditFreeTextAnnotation(); } internal void PdfViewerControl_FreeTextAnnotationDeselected(object sender, FreeTextAnnotationDeselectedEventArgs args) { parent.editTextAnnotationButton.BackgroundColor = new UIColor(0, 0, 0, 0); parent.annotation = null; parent.iseditEnable = false; parent.edittextThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 100, 7, 30, 30); parent.editTextAnnotationToolbar.Add(parent.edittextThicknessButton); parent.edittextColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 55, 7, 30, 30); parent.editTextAnnotationToolbar.Add(parent.edittextColorButton); parent.edittextDeleteButton.RemoveFromSuperview(); parent.editTextAnnotationToolbar.RemoveFromSuperview(); parent.thicknessToolbar.RemoveFromSuperview(); parent.colorToolbar.RemoveFromSuperview(); parent.opacityPanel.RemoveFromSuperview(); editButton.RemoveFromSuperview(); parent.FontSizePanel.RemoveFromSuperview(); parent.rangeSlider.RemoveFromSuperview(); parent.isOpacityNeeded = false; parent.annotationToolbar.Add(parent.editTextAnnotationButton); parent.FontSizePanel.RemoveFromSuperview(); } internal void EditTextThicknessButton_TouchUpInside(object sender, EventArgs e) { parent.colorToolbar.RemoveFromSuperview(); parent.FontSizePanel.Frame = parent.Frame; CGRect rect = new CGRect(); rect = parent.Frame; rect.Height = DefaultEditToolbarHeight + 16; rect.Y = parent.parentView.Frame.Height - (DefaultToolbarHeight + parent.editTextAnnotationToolbar.Frame.Height + 10); rect.Width = parent.parentView.Frame.Width; parent.FontSizePanel.Frame = rect; parent.rangeSlider.ToolTipPlacement = SFToolTipPlacement.SFToolTipPlacementBottomRight; parent.rangeSlider.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin; parent.rangeSlider.ShowValueLabel = false; parent.rangeSlider.Minimum = 6; parent.rangeSlider.Maximum = 22; parent.rangeSlider.TickFrequency = 2; parent.rangeSlider.StepFrequency = 2; parent.rangeSlider.ShowRange = false; parent.rangeSlider.Value = (nfloat)parent.pdfViewerControl.AnnotationSettings.FreeText.TextSize; parent.rangeSlider.Orientation = SFOrientation.SFOrientationHorizontal; parent.rangeSlider.TickPlacement = SFTickPlacement.SFTickPlacementInline; parent.rangeSlider.SnapsTo = SFSnapsTo.SFSnapsToTicks; parent.FontSizePanel.BackgroundColor = UIColor.FromRGB(249, 249, 249); parent.Add(parent.FontSizePanel); parent.FontSizePanel.Add(parent.rangeSlider); parent.rangeSlider.Frame = new CGRect(rect.X + 8, 35, rect.Width - 8, 30); parent.rangeSlider.ValueChange += RangeSlider_ValueChange; rangeSliderLabel.AccessibilityIdentifier = "RangeSliderLabelLabel"; rangeSliderLabel.Frame = new CGRect(((parent.FontSizePanel.Frame.Width) / 2) - 40, 8, 80, 22); rangeSliderLabel.Text = "Font:" + parent.rangeSlider.Value + "pt"; rangeSliderLabel.TextColor = new UIColor(red: 0.17f, green: 0.17f, blue: 0.17f, alpha: 1.0f); parent.FontSizePanel.Add(rangeSliderLabel); parent.rangeSlider.BringSubviewToFront(parent.rangeSlider); parent.FontSizePanel.Layer.BorderColor = new CGColor(0.2f, 0.2f); parent.FontSizePanel.Layer.BorderWidth = 1; } private void RangeSlider_ValueChange(object sender, ValueEventArgs e) { rangeSliderLabel.Text = "Font:" + (int)e.Value + "pt"; if (parent.annotation != null) (parent.annotation as FreeTextAnnotation).Settings.TextSize = (float)e.Value; else parent.pdfViewerControl.AnnotationSettings.FreeText.TextSize = (float)e.Value; } internal void PdfViewerControl_FreeTextAnnotationAdded(object sender, FreeTextAnnotationAddedEventArgs args) { parent.rangeSlider.RemoveFromSuperview(); parent.FontSizePanel.RemoveFromSuperview(); parent.isAnnotationToolbarVisible = false; parent.annotHelper.RemoveAllToolbars(false); parent.annotationToolbar.Add(parent.editTextAnnotationButton); parent.Add(parent.annotationToolbar); parent.FontSizePanel.RemoveFromSuperview(); parent.toolbarBackbutton.RemoveFromSuperview(); } internal void EditTextAnnotationButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.AnnotationMode = AnnotationMode.FreeText; parent.annotationFrame = parent.Frame; parent.annotationFrame.Height = DefaultToolbarHeight; parent.annotationFrame.Y = parent.parentView.Frame.Height - parent.annotationFrame.Height + 4; parent.editTextAnnotationToolbar.Frame = parent.annotationFrame; parent.editTextAnnotationToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); parent.editTextAnnotationToolbar.RemoveFromSuperview(); editTextButton.Frame = new CGRect(65, 7, 35, 35); editTextButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; editTextButton.Font = parent.highFont; editTextButton.SetTitle("\ue700", UIControlState.Normal); editTextButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.editTextAnnotationToolbar.Add(editTextButton); if (parent.iseditEnable) { editButton.Frame = new CGRect(parent.parentView.Frame.Width - 200, 7, 35, 35); editButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; editButton.Font = parent.highFont; editButton.TouchUpInside += EditButton_TouchUpInside; editButton.SetTitle("\ue709", UIControlState.Normal); editButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.editTextAnnotationToolbar.Add(editButton); } else { parent.toolbarBackbutton.Frame = new CGRect(15, 7, 35, 35); parent.toolbarBackbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.toolbarBackbutton.TouchUpInside += parent.ToolbarBackbutton_TouchUpInside; parent.toolbarBackbutton.Font = parent.highFont; parent.toolbarBackbutton.SetTitle("\ue708", UIControlState.Normal); parent.toolbarBackbutton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.editTextAnnotationToolbar.Add(parent.toolbarBackbutton); } if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.edittextThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 100, 7, 30, 30); else parent.edittextThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 100, 7, 30, 30); parent.edittextThicknessButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.edittextThicknessButton.Font = parent.fontSizeFont; parent.edittextThicknessButton.SetTitle("\ue700", UIControlState.Normal); parent.edittextThicknessButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.editTextAnnotationToolbar.Add(parent.edittextThicknessButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.edittextColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 55, 7, 30, 30); else parent.edittextColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 55, 7, 30, 30); parent.edittextColorButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.edittextColorButton.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.FreeText.TextColor; parent.editTextAnnotationToolbar.Add(parent.edittextColorButton); parent.editTextAnnotationToolbar = parent.UpdateToolbarBorder(parent.editTextAnnotationToolbar, parent.annotationFrame); parent.Add(parent.editTextAnnotationToolbar); } } }<file_sep>/iOS/SampleBrowser/Samples/Carousel/Carousel_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfCarousel.iOS; using System; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Carousel_Mobile : SampleView { SfCarousel carousel; SfCarouselItem carouselItem; UILabel offsetLabel,scaleOffsetLabel,rotationAngleLabel; UITextView offsetTextfield,scaleOffsetTextfield,rotationAngleTextfield; UILabel viewModeLabel; UIButton viewButton = new UIButton (); UIButton viewDoneButton=new UIButton(); UIPickerView viewModePicker; public UIView option=new UIView(); private string selectedType; private readonly IList<string> viewModeList = new List<string>{ "Default", "Linear" }; public Carousel_Mobile () { viewModePicker = new UIPickerView (); PickerModel viewModel = new PickerModel (viewModeList); viewModePicker.Model = viewModel; viewModeLabel = new UILabel (); viewButton = new UIButton (); this.OptionView = new UIView (); NSMutableArray<SfCarouselItem> carouselItemCollection = new NSMutableArray<SfCarouselItem> (); carousel = new SfCarousel (); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) carousel.Frame = new CGRect ( 150,150, 300,650); else carousel.Frame = new CGRect ( 0,0, 300,430); carousel.ItemHeight = 300; carousel.ItemWidth = 150; carousel.SelectedItemOffset = 20; for (int i = 1; i <= 7; i++) { carouselItem = new SfCarouselItem (); carouselItem.ImageName = "image"+i+".png"; carouselItemCollection.Add (carouselItem); } carousel.DataSource = carouselItemCollection; carousel.SelectedIndex = 2; this.AddSubview (carousel); offsetLabel = new UILabel (); scaleOffsetLabel = new UILabel (); rotationAngleLabel = new UILabel (); offsetLabel.Text = "OFFSET"; offsetLabel.TextColor = UIColor.Black; offsetLabel.TextAlignment = UITextAlignment.Left; offsetLabel.Font=UIFont.FromName("Helvetica", 14f); scaleOffsetLabel.Text = "SCALE OFFSET"; scaleOffsetLabel.TextColor = UIColor.Black; scaleOffsetLabel.TextAlignment = UITextAlignment.Left; scaleOffsetLabel.Font=UIFont.FromName("Helvetica", 14f); rotationAngleLabel.Text = "ROTATION ANGLE"; rotationAngleLabel.TextColor = UIColor.Black; rotationAngleLabel.TextAlignment = UITextAlignment.Left; rotationAngleLabel.Font=UIFont.FromName("Helvetica", 14f); offsetTextfield = new UITextView (); offsetTextfield.TextAlignment = UITextAlignment.Center; offsetTextfield.Layer.BorderColor = UIColor.Black.CGColor; offsetTextfield.KeyboardType = UIKeyboardType.NumberPad; offsetTextfield.BackgroundColor = UIColor.FromRGB(246,246,246); offsetTextfield.Text = "60"; offsetTextfield.Changed+= (object sender, EventArgs e) => { if(offsetTextfield.Text.Length>0){ carousel.Offset = nfloat.Parse(offsetTextfield.Text); } else{ carousel.Offset = 60; } }; scaleOffsetTextfield = new UITextView (); scaleOffsetTextfield.TextAlignment = UITextAlignment.Center; scaleOffsetTextfield.Layer.BorderColor = UIColor.Black.CGColor; scaleOffsetTextfield.BackgroundColor = UIColor.FromRGB(246,246,246); scaleOffsetTextfield.KeyboardType = UIKeyboardType.NumberPad; scaleOffsetTextfield.Text = "0.8"; scaleOffsetTextfield.Changed+= (object sender, EventArgs e) => { if(scaleOffsetTextfield.Text.Length>0){ carousel.ScaleOffset = nfloat.Parse(scaleOffsetTextfield.Text); } else{ carousel.ScaleOffset = (nfloat)0.8; } }; rotationAngleTextfield = new UITextView (); rotationAngleTextfield.TextAlignment = UITextAlignment.Center; rotationAngleTextfield.Layer.BorderColor = UIColor.Black.CGColor; rotationAngleTextfield.BackgroundColor = UIColor.FromRGB(246,246,246); rotationAngleTextfield.KeyboardType = UIKeyboardType.NumberPad; rotationAngleTextfield.Text = "45"; rotationAngleTextfield.Changed+= (object sender, EventArgs e) => { if(rotationAngleTextfield.Text.Length>0) { carousel.RotationAngle = int.Parse(rotationAngleTextfield.Text); } else { carousel.RotationAngle = 45; } }; //viewModeLabel viewModeLabel.Text = "VIEW MODE"; viewModeLabel.TextColor = UIColor.Black; viewModeLabel.TextAlignment = UITextAlignment.Left; //viewButton viewButton.SetTitle("Default",UIControlState.Normal); viewButton.SetTitleColor(UIColor.Black,UIControlState.Normal); viewButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; viewButton.Layer.CornerRadius = 8; viewButton.Layer.BorderWidth = 2; viewButton.TouchUpInside += ShowviewModePicker; viewButton.Layer.BorderColor =UIColor.FromRGB(246,246,246).CGColor; //viewDoneButton viewDoneButton.SetTitle("Done\t",UIControlState.Normal); viewDoneButton.SetTitleColor(UIColor.Black,UIControlState.Normal); viewDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; viewDoneButton.TouchUpInside += HidePicker; viewDoneButton.Hidden = true; viewDoneButton.BackgroundColor = UIColor.FromRGB(246,246,246); viewModel.PickerChanged += viewSelectedIndexChanged; viewModePicker.ShowSelectionIndicator = true; viewModePicker.Hidden = true; //viewModePicker.BackgroundColor = UIColor.Gray; } public void optionView() { this.option.AddSubview (scaleOffsetLabel); this.option.AddSubview (rotationAngleLabel); this.option.AddSubview (offsetTextfield); this.option.AddSubview (scaleOffsetTextfield); this.option.AddSubview (rotationAngleTextfield); this.option.AddSubview (offsetLabel); this.option.AddSubview (viewModeLabel); this.option.AddSubview (viewButton); this.option.AddSubview (viewModePicker); this.option.AddSubview (viewDoneButton); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; this.OptionView.Frame = view.Frame; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { var height = this.Frame.Height; viewModePicker.Frame = new CGRect(0, 330, 300, 40); viewDoneButton.Frame = new CGRect(0, 270, 300, 40); carousel.ItemHeight = 180; carousel.Frame = new CGRect(0, 0, this.Frame.Size.Width, this.Frame.Size.Height); offsetLabel.Frame = new CGRect(10, 20, this.Frame.Size.Width - 20, 30); scaleOffsetLabel.Frame = new CGRect(10, 90, this.Frame.Size.Width - 20, 30); rotationAngleLabel.Frame = new CGRect(10, 160, this.Frame.Size.Width - 20, 30); offsetTextfield.Frame = new CGRect(200, 20, 100, 30); scaleOffsetTextfield.Frame = new CGRect(200, 90, 100, 30); rotationAngleTextfield.Frame = new CGRect(200, 160, 100, 30); viewModeLabel.Frame = new CGRect(10, 220, this.Frame.Size.Width - 20, 30); viewButton.Frame = new CGRect(10, 260, 300, 30); } else { option.Frame = new CGRect(0, 50, Frame.Width, Frame.Height); carousel.Frame = new CGRect(0, 0, this.Frame.Size.Width, this.Frame.Size.Height); offsetLabel.Frame = new CGRect(10, 20, this.Frame.Size.Width - 10, 30); scaleOffsetLabel.Frame = new CGRect(10, 70, this.Frame.Size.Width - 10, 30); rotationAngleLabel.Frame = new CGRect(10, 120, this.Frame.Size.Width - 10, 30); offsetTextfield.Frame = new CGRect(230, 20, this.Frame.Size.Width - 250, 30); scaleOffsetTextfield.Frame = new CGRect(230, 70, this.Frame.Size.Width - 250, 30); rotationAngleTextfield.Frame = new CGRect(230, 120, this.Frame.Size.Width - 250, 30); viewModeLabel.Frame = new CGRect(10, 170, this.Frame.Size.Width - 10, 30); viewButton.Frame = new CGRect(10, 200, this.Frame.Size.Width - 20, 30); viewModePicker.Frame = new CGRect(0, this.Frame.Size.Height / 3, this.Frame.Size.Width, this.Frame.Size.Height / 3); viewDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 3, this.Frame.Size.Width, 30); } } this.optionView (); base.LayoutSubviews (); } void ShowviewModePicker (object sender, EventArgs e) { offsetTextfield.EndEditing(true); scaleOffsetTextfield.EndEditing(true); rotationAngleTextfield.EndEditing(true); viewDoneButton.Hidden = false; viewModePicker.Hidden = false; viewButton.Hidden = true; } void HidePicker (object sender, EventArgs e) { viewDoneButton.Hidden = true; viewModePicker.Hidden = true; viewButton.Hidden = false; } private void viewSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; viewButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Default") carousel.ViewMode = SFCarouselViewMode.SFCarouselViewModeDefault; else carousel.ViewMode = SFCarouselViewMode.SFCarouselViewModeLinear; } } }<file_sep>/Forms/RangeNavigator/RangeNavigator/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.RangeNavigator.XForms; using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfRangeNavigator { [Preserve(AllMembers = true)] public partial class Themes : SampleView { public Themes () { InitializeComponent (); ((Syncfusion.SfChart.XForms.SfChart)RangeNavigator.Content).Series.Clear(); ((Syncfusion.SfChart.XForms.SfChart)RangeNavigator.Content).Series.Add(new SplineAreaSeries() { ItemsSource = series.ItemsSource, XBindingPath = "XValue", YBindingPath = "YValue" }); if (Device.RuntimePlatform == Device.Android) { RangeNavigator.HeightRequest = 150; } else if (Device.RuntimePlatform == Device.iOS) { RangeNavigator.HeightRequest = 100; } else if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { chart.Margin = new Thickness(5); RangeNavigator.Margin = new Thickness(5); RangeNavigator.Intervals = Syncfusion.RangeNavigator.XForms.DateTimeIntervalType.Quarter | Syncfusion.RangeNavigator.XForms.DateTimeIntervalType.Month; RangeNavigator.TooltipFormat = "dd/MM/yy"; RangeNavigator.LeftTooltipStyle = new TooltipStyle() { FontSize = 10 }; RangeNavigator.RightTooltipStyle = new TooltipStyle() { FontSize = 10 }; } } void RangeNavigator_RangeChanged(object sender, RangeChangedEventArgs e) { dateTimeAxis.Minimum = e.ViewRangeStartDate; dateTimeAxis.Maximum = e.ViewRangeEndDate; } } }<file_sep>/iOS/SampleBrowser/Samples/Diagram/NodeCustomization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using CoreGraphics; using Syncfusion.SfDiagram.iOS; using UIKit; namespace SampleBrowser { public partial class NodeCustomization : SampleView { SfDiagram diagram; public NodeCustomization() { //Initialize sfdiagram diagram = new SfDiagram(); var node1 = DrawNode(((float)(280)), 150, 155, 50, ShapeType.RoundedRectangle); node1.Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(206, 98, 9)); node1.Annotations.Add(new Annotation() { Content = CreateLabel("Establish Project and Team", 12) }); diagram.AddNode(node1); var node2 = DrawNode(((float)(280)), (float)(node1.OffsetY + 90), 155, 50, ShapeType.RoundedRectangle); node2.Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(206, 98, 9)); node2.Style.Brush = new LinearGradientBrush(0, 30, 150, 30, new UIColor[] { UIColor.FromRGB(255, 130, 0), UIColor.FromRGB(255, 37, 0) }, GradientDrawingOptions.DrawsAfterEndLocation); node2.Style.StrokeWidth = 0; node2.Annotations.Add(new Annotation() { Content = CreateLabel("Define Scope", 12) }); diagram.AddNode(node2); var node3 = DrawNode(((float)(280)), (float)(node2.OffsetY + 90), 155, 50, ShapeType.RoundedRectangle); node3.Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(206, 98, 9)); node3.Style.StrokeStyle = StrokeStyle.Dashed; node3.Annotations.Add(new Annotation() { Content = CreateLabel("Analyze process As-Is", 12) }); diagram.AddNode(node3); var node4 = DrawNode(((float)(280)), (float)(node3.OffsetY + 90), 155, 50, ShapeType.RoundedRectangle); node4.Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(206, 98, 9)); node4.Style.StrokeWidth = 0; node4.Annotations.Add(new Annotation() { Content = CreateLabel("Identify opportunities for improvement", 12) }); diagram.AddNode(node4); var node5 = DrawNode(((float)(280)), (float)(node4.OffsetY + 90), 155, 50, ShapeType.RoundedRectangle); node5.Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(206, 98, 9)); node5.Style.StrokeWidth = 0; node5.Annotations.Add(new Annotation() { Content = CreateLabel("Design and implement improved processess", 12) }); diagram.AddNode(node5); var node6 = DrawCustomShape(53, 155); node6.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.5, IsVisible = false }); diagram.AddNode(node6); var labelnode6 = new Node(33.5f, 195, 80, 35); labelnode6.Annotations.Add(new Annotation() { Content = "Sponsor", FontSize = 10, }); labelnode6.Style = new Style() { StrokeBrush = new SolidBrush(UIColor.Clear), Brush = new SolidBrush(UIColor.Clear) }; diagram.AddNode(labelnode6); var node7 = DrawCustomShape(53, 347); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0, IsVisible = false }); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.3, IsVisible = false }); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.6, IsVisible = false }); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 1, IsVisible = false }); diagram.AddNode(node7); var labelnode7 = new Node(55, 393, 60, 50); labelnode7.Annotations.Add(new Annotation() { Content = "Domain Experts", FontSize = 10, }); labelnode7.Style = new Style() { StrokeBrush = new SolidBrush(UIColor.Clear), Brush = new SolidBrush(UIColor.Clear) }; diagram.AddNode(labelnode7); var node8 = DrawCustomShape(590, 155); node8.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.5, IsVisible = false }); diagram.AddNode(node8); var labelnode8 = new Node(590.5f, 200, 78, 49); labelnode8.Annotations.Add(new Annotation() { Content = "Project Manager", FontSize = 10, }); labelnode8.Style = new Style() { StrokeBrush = new SolidBrush(UIColor.Clear), Brush = new SolidBrush(UIColor.Clear) }; diagram.AddNode(labelnode8); var node9 = DrawCustomShape(590, 347); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0, IsVisible = false }); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.3, IsVisible = false }); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.6, IsVisible = false }); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 1, IsVisible = false }); diagram.AddNode(node9); var labelnode9 = new Node(591, 398.5f, 65, 39); labelnode9.Annotations.Add(new Annotation() { Content = "Business Analyst", FontSize = 10, }); labelnode9.Style = new Style() { StrokeBrush = new SolidBrush(UIColor.Clear), Brush = new SolidBrush(UIColor.Clear) }; diagram.AddNode(labelnode9); diagram.AddConnector(DrawConnector(node1, node2, node1.Ports[2], node2.Ports[0], SegmentType.OrthoSegment, UIColor.FromRGB(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, UIColor.FromRGB(127, 132, 133), UIColor.FromRGB(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node2, node3, node2.Ports[2], node3.Ports[0], SegmentType.OrthoSegment, UIColor.FromRGB(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, UIColor.FromRGB(127, 132, 133), UIColor.FromRGB(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node3, node4, node3.Ports[2], node4.Ports[0], SegmentType.OrthoSegment, UIColor.FromRGB(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, UIColor.FromRGB(127, 132, 133), UIColor.FromRGB(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node4, node5, node4.Ports[2], node5.Ports[0], SegmentType.OrthoSegment, UIColor.FromRGB(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, UIColor.FromRGB(127, 132, 133), UIColor.FromRGB(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node6, node1, node6.Ports[0], node1.Ports[3], SegmentType.OrthoSegment, UIColor.FromRGB(127, 132, 133), StrokeStyle.Dashed, DecoratorType.Filled45Arrow, UIColor.FromRGB(127, 132, 133), UIColor.FromRGB(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node8, node1, node8.Ports[0], node1.Ports[1], SegmentType.OrthoSegment, UIColor.FromRGB(127, 132, 133), StrokeStyle.Dashed, DecoratorType.Filled45Arrow, UIColor.FromRGB(127, 132, 133), UIColor.FromRGB(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node7, node2, node7.Ports[0], node2.Ports[3], SegmentType.StraightSegment, UIColor.Black, StrokeStyle.Default, DecoratorType.Square, UIColor.Black, UIColor.Black, 6)); diagram.AddConnector(DrawConnector(node7, node3, node7.Ports[1], node3.Ports[3], SegmentType.StraightSegment, UIColor.Black, StrokeStyle.Default, DecoratorType.Square, UIColor.Black, UIColor.Black, 6)); diagram.AddConnector(DrawConnector(node7, node4, node7.Ports[2], node4.Ports[3], SegmentType.StraightSegment, UIColor.Black, StrokeStyle.Default, DecoratorType.Square, UIColor.Black, UIColor.Black, 6)); diagram.AddConnector(DrawConnector(node7, node5, node7.Ports[3], node5.Ports[3], SegmentType.StraightSegment, UIColor.Black, StrokeStyle.Default, DecoratorType.Square, UIColor.Black, UIColor.Black, 6)); diagram.AddConnector(DrawConnector(node9, node2, node9.Ports[0], node2.Ports[1], SegmentType.StraightSegment, UIColor.Black, StrokeStyle.Default, DecoratorType.Circle, UIColor.Black, UIColor.Black, 6)); diagram.AddConnector(DrawConnector(node9, node3, node9.Ports[1], node3.Ports[1], SegmentType.StraightSegment, UIColor.Black, StrokeStyle.Default, DecoratorType.Circle, UIColor.Black, UIColor.Black, 6)); diagram.AddConnector(DrawConnector(node9, node4, node9.Ports[2], node4.Ports[1], SegmentType.StraightSegment, UIColor.Black, StrokeStyle.Default, DecoratorType.Circle, UIColor.Black, UIColor.Black, 6)); diagram.AddConnector(DrawConnector(node9, node5, node9.Ports[3], node5.Ports[1], SegmentType.StraightSegment, UIColor.Black, StrokeStyle.Default, DecoratorType.Circle, UIColor.Black, UIColor.Black, 6)); } public override void LayoutSubviews() { base.LayoutSubviews(); //Set diagram width and height diagram.Width = (float)Frame.Width; diagram.Height = (float)Frame.Height; diagram.EnableSelectors = false; this.AddSubview(diagram); diagram.LayoutSubviews(); diagram.Loaded += Diagram_Loaded; } private void Diagram_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); } //Creates the Node with Specified input Node DrawNode(float x, float y, float w, float h, ShapeType shape) { var node = new Node(); node.OffsetX = x; node.OffsetY = y; node.Width = w; node.Height = h; node.ShapeType = shape; node.Style.StrokeWidth = 1; node.CornerRadius = 30; node.Style.Brush = new SolidBrush(UIColor.FromRGB(255,129,0)); node.Ports.Add(new Port() { NodeOffsetX = 0.5, NodeOffsetY = 0, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.5, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 0.5, NodeOffsetY = 1, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.5, IsVisible = false }); return node; } Node DrawCustomShape(float x, float y) { var node = new Node(x, y, 40, 40); SfGraphics grap = new SfGraphics(); Pen stroke = new Pen(); stroke.Brush = new SolidBrush(UIColor.Clear); stroke.StrokeWidth = 3; stroke.StrokeBrush = new SolidBrush(UIColor.FromRGB(24,161,237)); grap.DrawEllipse(stroke, new System.Drawing.Rectangle(10, 0, 20, 20)); grap.DrawArc(stroke, 0, 20, 40, 40, 180, 180); node.UpdateSfGraphics(grap); return node; } Connector DrawConnector(Node Src, Node Trgt, Port srcport, Port trgtport, SegmentType type, UIColor strokeColor, StrokeStyle style, DecoratorType decorator, UIColor fillColor, UIColor strokeFill, float sw) { var Conn = new Connector(Src, Trgt); Conn.SourcePort = srcport; Conn.TargetPort = trgtport; Conn.SegmentType = type; Conn.TargetDecoratorType = decorator; Conn.TargetDecoratorStyle.Fill = fillColor; Conn.TargetDecoratorStyle.StrokeColor = strokeFill; Conn.Style.StrokeWidth = 1; Conn.Style.StrokeBrush = new SolidBrush(strokeColor); Conn.Style.StrokeStyle = style; Conn.TargetDecoratorStyle.Size = sw; Conn.TargetDecoratorStyle.StrokeWidth = 1; return Conn; } //Create Node's Annotation UILabel CreateLabel(string text,int Size) { var label = new UILabel(); label.Frame = new CGRect(2, 0, 150, 45); label.TextAlignment = UITextAlignment.Center; label.Text = text; label.TextColor = UIColor.White; label.Font = UIFont.FromName("Arial", 10); label.LineBreakMode = UILineBreakMode.WordWrap; label.Lines = 0; label.Layer.ShouldRasterize = true; label.Layer.RasterizationScale = UIScreen.MainScreen.Scale; return label; } } }<file_sep>/Forms/PdfViewer/PdfViewer.Droid/Renderer/CustomEntryRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Android.Graphics; using SampleBrowser.SfPdfViewer; using SampleBrowser.SfPdfViewer.Droid; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))] namespace SampleBrowser.SfPdfViewer.Droid { class CustomEntryRenderer : EntryRenderer { public CustomEntryRenderer(Context context) : base(context){ } protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (e.OldElement == null) { if (Control != null) #pragma warning disable CS0618 // Type or member is obsolete Control.Background.SetColorFilter(Android.Graphics.Color.Rgb(0, 118, 255), PorterDuff.Mode.SrcAtop); #pragma warning restore CS0618 // Type or member is obsolete var nativeEditText = (global::Android.Widget.EditText)Control; nativeEditText.SetSelectAllOnFocus(true); } } } }<file_sep>/Forms/ImageEditor/ImageEditor.UWP/FileStore.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.IO; using Windows.ApplicationModel; using Windows.Storage; namespace SampleBrowser.SfImageEditor.UWP { public class FileStore: IFileStore { public string GetFilePath() { return Path.Combine(Package.Current.InstalledLocation.Path, "image.png"); } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/TemplateColumn/StockCell.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Views; using Android.Content; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public class StockCell : GridCell { TextView stockText; ImageView stockImage; public StockCell (Context context) : base (context) { stockText = new TextView (context); stockImage = new ImageView (context); stockText.Gravity = GravityFlags.Right; stockText.SetTextColor (Color.Rgb (51, 51, 51)); this.CanRendererUnload = false; this.AddView (stockText); this.AddView (stockImage); } protected override void UnLoad () { if (this.Parent != null) (this.Parent as VirtualizingCellsControl).RemoveView (this); } protected override void OnDraw (Canvas canvas) { stockText.Text = DataColumn.CellValue.ToString (); if (Convert.ToDouble (DataColumn.CellValue) > 0.05) stockImage.SetImageResource (Resource.Drawable.GreenUp); else stockImage.SetImageResource (Resource.Drawable.RedDown); base.OnDraw (canvas); } protected override void OnLayout (bool changed, int left, int top, int right, int bottom) { stockImage.Layout ((int)(15 * Resources.DisplayMetrics.Density), 0, (int)(35 * Resources.DisplayMetrics.Density), Height); stockText.Layout ((int)(35 * Resources.DisplayMetrics.Density), (int)(10 * Resources.DisplayMetrics.Density), Width - 20, Height); } } } <file_sep>/Forms/LinearGauge/LinearGauge/Samples/Ranges/Ranges.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfLinearGauge { [Preserve(AllMembers = true)] public partial class Ranges : SampleView { public Ranges() { InitializeComponent(); this.BackgroundColor = Color.White; if(gauge1!= null) { if (Device.RuntimePlatform == Device.UWP) gauge1.Scales[0].LabelOffset = 27; else gauge1.Scales[0].LabelOffset = 20; } var height = (int)Core.SampleBrowser.ScreenHeight/4; if(Device.RuntimePlatform != Device.UWP && height > 0) { if (gauge1 != null) gauge1.HeightRequest = height ; if (gauge != null) gauge.HeightRequest = height; if (gauge2 != null) gauge2.HeightRequest = height; } } } }<file_sep>/iOS/SampleBrowser/Samples/Maps/Sublayer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfBusyIndicator.iOS; using System; using Syncfusion.SfMaps.iOS; #if __UNIFIED__ using Foundation; using CoreGraphics; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGPoint= System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Sublayer : SampleView { internal SfBusyIndicator busyindicator; UIView view; UILabel label; bool isDisposed; public override void LayoutSubviews() { view.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); label.Frame = new CGRect(0f, 0f, Frame.Size.Width, 40); SetNeedsDisplay(); } protected override void Dispose(bool disposing) { isDisposed = true; base.Dispose(disposing); } public Sublayer() { SFMap maps = new SFMap(); view = new UIView(); view.Frame = new CGRect(0, 0, 300, 400); busyindicator = new SfBusyIndicator(); busyindicator.ViewBoxWidth = 75; busyindicator.ViewBoxHeight = 75; busyindicator.Foreground = UIColor.FromRGB(0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; view.AddSubview(busyindicator); label = new UILabel(); label.TextAlignment = UITextAlignment.Center; label.Text = "Rivers in Australia"; label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(0, 0, 400, 40); label.TextColor = UIColor.Black; view.AddSubview(label); NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(0.3), delegate { if (isDisposed) return; maps.Frame = new CGRect(Frame.Location.X, 60, Frame.Size.Width - 6, Frame.Size.Height - 60); view.AddSubview(maps); }); SFShapeFileLayer layer = new SFShapeFileLayer(); layer.Uri = (NSString)NSBundle.MainBundle.PathForResource("australia", "shp"); SFShapeSetting shapeSettings = new SFShapeSetting(); shapeSettings.StrokeThickness = 1; shapeSettings.StrokeColor = UIColor.White; shapeSettings.Fill = UIColor.FromRGB(172, 249, 247); layer.ShapeSettings = shapeSettings; SFShapeFileLayer subLayer = new SFShapeFileLayer(); subLayer.Uri = (NSString)NSBundle.MainBundle.PathForResource("river", "shp"); SFShapeSetting subLayerSettings = new SFShapeSetting(); subLayerSettings.StrokeThickness = 2; subLayerSettings.Fill = UIColor.FromRGB(0, 168, 204); subLayer.ShapeSettings = subLayerSettings; layer.Sublayers.Add(subLayer); maps.Layers.Add(layer); AddSubview(view); maps.Delegate = new MapsSublayerDelegate(this); } } public class MapsSublayerDelegate : SFMapsDelegate { public MapsSublayerDelegate(Sublayer sublayer) { sample = sublayer; } Sublayer sample; public override void DidLoad(SFMap map) { if (sample.busyindicator != null) { sample.busyindicator.RemoveFromSuperview(); sample.busyindicator = null; } } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/ViewModel/IncrementalLoadingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfDataGrid; using CoreFoundation; using IncrementalLoading.NorthwindService; using System.Data.Services.Client; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Net; using System.Text; using System.Windows; using UIKit; using CoreGraphics; using System.Collections.ObjectModel; using System.Threading.Tasks; using System.Timers; using Syncfusion.Data; namespace SampleBrowser { public class IncrementalLoadingViewModel : INotifyPropertyChanged { #region Members NorthwindEntities northwindEntity; #endregion #region Ctor public UIActivityIndicatorView LoaderIndicator; public UILabel LoaderLable; public UIView LoaderBorder; public IncrementalLoadingViewModel () { LoaderBorder = new UIView (); this.LoaderLable = new UILabel (); this.LoaderIndicator = new UIActivityIndicatorView (); this.LoaderIndicator.Color = UIColor.FromRGB (255, 255, 255); LoaderBorder.BackgroundColor = UIColor.FromRGB(70, 183, 118); LoaderBorder.Add (LoaderLable); LoaderBorder.Add (LoaderIndicator); string uri = "http://services.odata.org/Northwind/Northwind.svc/"; if (CheckConnection (uri).Result) { gridSource = new IncrementalList<Order> (LoadMoreItems) { MaxItemsCount = 1000 }; northwindEntity = new NorthwindEntities (new Uri (uri)); } else { NoNetwork = true; IsBusy = false; } } #endregion #region Properties private IncrementalList<Order> gridSource; public IncrementalList<Order> GridSource { get { return gridSource; } set { gridSource = value; RaisePropertyChanged ("GridSource"); } } private bool isBusy; public bool IsBusy { get { return isBusy; } set { isBusy = value; if (isBusy) { this.LoaderLable.Text = "Fetching Data... "; } else { if (noNetwork) { LoaderLable.LineBreakMode = UILineBreakMode.WordWrap; LoaderLable.Lines = 0; this.LoaderLable.Text = "No Network Found..! \nSearching for a network..."; } } RaisePropertyChanged ("IsBusy"); } } private bool noNetwork; public bool NoNetwork { get { return noNetwork; } set { noNetwork = value; RaisePropertyChanged ("NoNetwork"); } } #endregion #region INotifyPropertyChanged Member public event PropertyChangedEventHandler PropertyChanged; void RaisePropertyChanged (string propertyName) { if (PropertyChanged != null) { PropertyChanged (this, new PropertyChangedEventArgs (propertyName)); } } #endregion #region Methods void LoadMoreItems (uint count, int baseIndex) { BackgroundWorker worker = new BackgroundWorker (); worker.DoWork += (o, ae) => { DataServiceQuery<Order> query = northwindEntity.Orders.Expand ("Customer"); query = query.Skip<Order> (baseIndex).Take<Order> (15) as DataServiceQuery<Order>; IAsyncResult ar = query.BeginExecute (null, null); var items = query.EndExecute (ar); var list = items.ToList (); DispatchQueue.MainQueue.DispatchAsync (new Action (() => { GridSource.LoadItems (list); })); }; worker.RunWorkerCompleted += (o, ae) => { IsBusy = false; UIView.Animate (2, () => { for (int i = 5; i < 0; i--) { LoaderBorder.Alpha = i - 0.1f; } LoaderBorder.Hidden = true; }); this.LoaderIndicator.StopAnimating (); this.LoaderIndicator.HidesWhenStopped = true; this.LoaderLable.Hidden = true; }; IsBusy = true; { this.LoaderLable.Hidden = false; LoaderBorder.Hidden = false; UIView.Animate (2, () => { this.LoaderIndicator.StartAnimating (); }); } worker.RunWorkerAsync (); } private async Task<bool> CheckConnection (String url) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url); request.Timeout = 5000; request.Credentials = CredentialCache.DefaultNetworkCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse (); await Task.Delay(0); if (response.StatusCode == HttpStatusCode.OK) return true; else return false; } catch { return false; } } #endregion } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/Themes/PopupThemeBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PopupThemeBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Core; using Syncfusion.XForms.Buttons; using Syncfusion.XForms.Themes; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the PopupThemeBehavior samples /// </summary> public class PopupThemeBehavior : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.XForms.PopupLayout.SfPopupLayout popupLayout; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private GettingStartedViewModel viewModel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfButton alertWithTitle; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Color contentBackGroundColor; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Color contentTextColor; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Color headerTextColor; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type parameter named as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { base.OnAttachedTo(bindAble); this.popupLayout = bindAble.FindByName<Syncfusion.XForms.PopupLayout.SfPopupLayout>("popupLayout"); this.viewModel = new GettingStartedViewModel(); this.alertWithTitle = bindAble.FindByName<SfButton>("AlertTitle"); this.alertWithTitle.Clicked += this.AlertWithTitle_Clicked; this.contentBackGroundColor = Color.White; this.contentTextColor = Color.Gray; this.headerTextColor = Color.Black; bindAble.BindingContext = this.viewModel; } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type parameter named as bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.popupLayout = null; this.alertWithTitle.Clicked -= this.AlertWithTitle_Clicked; base.OnDetachingFrom(bindAble); } /// <summary> /// Fired when <see cref="Button"/> has been clicked. /// </summary> /// <param name="sender">A <see cref="Button"/>.</param> /// <param name="e">A <see cref="Button"/> event properties.</param> private void AlertWithTitle_Clicked(object sender, EventArgs e) { ICollection<ResourceDictionary> mergedDictionaries = null; #if COMMONSB var parent = ((((sender as SfButton).Parent as StackLayout).Parent as ScrollView).Parent as Syncfusion.XForms.PopupLayout.SfPopupLayout).Parent; while (parent != null) { if (parent is ThemesPage) { mergedDictionaries = (parent as Page).Resources.MergedDictionaries; break; } parent = parent.Parent; } parent = null; #else mergedDictionaries = (((((sender as SfButton).Parent as StackLayout).Parent as ScrollView).Parent as Syncfusion.XForms.PopupLayout.SfPopupLayout).Parent as SampleView).Resources.MergedDictionaries; #endif // Fix for XAMARIN-35079 Theming does not apply properly when change dark to light in Popup sample Browser var darkTheme = (mergedDictionaries != null) ? mergedDictionaries.OfType<DarkTheme>().FirstOrDefault() : null; var lightTheme = (mergedDictionaries != null) ? mergedDictionaries.OfType<LightTheme>().FirstOrDefault() : null; var darkThemeIndex = mergedDictionaries.IndexOf(darkTheme); var lightThemeIndex = mergedDictionaries.IndexOf(lightTheme); if (darkTheme != null && darkThemeIndex > lightThemeIndex) { this.popupLayout.PopupView.PopupStyle.BorderColor = Color.Transparent; this.popupLayout.PopupView.BackgroundColor = Color.FromHex("#232323"); this.contentBackGroundColor = Color.FromHex("#232323"); this.contentTextColor = Color.FromHex("#707070"); this.headerTextColor = Color.FromHex("#D1D1D1"); } else { this.popupLayout.PopupView.PopupStyle.BorderColor = Color.Transparent; this.popupLayout.PopupView.BackgroundColor = Color.White; this.contentBackGroundColor = Color.White; this.contentTextColor = Color.FromHex("#414141"); this.headerTextColor = Color.FromHex("#414141"); } this.popupLayout.PopupView.AcceptButtonText = "AGREE"; this.popupLayout.PopupView.DeclineButtonText = "DECLINE"; this.popupLayout.PopupView.AppearanceMode = Syncfusion.XForms.PopupLayout.AppearanceMode.TwoButton; this.popupLayout.PopupView.HeaderHeight = 70; this.popupLayout.PopupView.FooterHeight = 70; //// HeaderTemplate var alertWithTitleHeader = new DataTemplate(() => { var headerStack = new StackLayout(); if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { headerStack.Padding = new Thickness(18, 17, 20, 5); } else { headerStack.Padding = new Thickness(19, 20, 20, 5); } var label = new Label() { LineBreakMode = Xamarin.Forms.LineBreakMode.WordWrap, Text = "Use Google's location service?", FontSize = 18, HorizontalOptions = LayoutOptions.Center, TextColor = headerTextColor, FontAttributes = FontAttributes.Bold }; headerStack.Children.Add(label); return headerStack; }); //// ContentTemplate var alertWithTitleContent = new DataTemplate(() => { var ContentStack = new StackLayout(); ContentStack.Orientation = StackOrientation.Horizontal; if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { ContentStack.Padding = new Thickness(20, 0, 5, 0); } else { ContentStack.Padding = new Thickness(20, 5, 5, 8); } var label = new Label() { Text = "Let Google help apps determine location. This means sending anonymous location date to Google, even when no apps are running.", FontSize = 16.5, BackgroundColor = contentBackGroundColor, TextColor = contentTextColor }; ContentStack.Children.Add(label); return ContentStack; }); this.popupLayout.PopupView.HeaderTemplate = alertWithTitleHeader; this.popupLayout.PopupView.ContentTemplate = alertWithTitleContent; this.popupLayout.Show(); mergedDictionaries = null; } } } <file_sep>/Forms/Picker/Picker/Samples/Extensions/DatePicker.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SelectionChangedEventArgs = Syncfusion.SfPicker.XForms.SelectionChangedEventArgs; using Syncfusion.SfPicker.XForms; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfPicker { public class CustomDatePicker : Syncfusion.SfPicker.XForms.SfPicker { public Dictionary<string, string> months; public ObservableCollection<object> Date { get; set; } public ObservableCollection<object> Day; public ObservableCollection<object> Month; public ObservableCollection<object> Year; public ObservableCollection<object> Time { get; set; } public ObservableCollection<object> Minute; public ObservableCollection<object> Hour; public ObservableCollection<object> Format; public ObservableCollection<string> Headers { get; set; } public CustomDatePicker() { months = new Dictionary<string, string>(); Date = new ObservableCollection<object>(); Day = new ObservableCollection<object>(); Month = new ObservableCollection<object>(); Year = new ObservableCollection<object>(); Headers = new ObservableCollection<string>(); if (Device.RuntimePlatform == Device.Android) { Headers.Add("MONTH"); Headers.Add("DAY"); Headers.Add("YEAR"); } else { Headers.Add("Month"); Headers.Add("Day"); Headers.Add("Year"); } PopulateDateCollection(); this.ItemsSource = Date; this.ColumnHeaderText = Headers; this.SelectionChanged += CustomDatePicker_SelectionChanged; } private void CustomDatePicker_SelectionChanged(object sender, SelectionChangedEventArgs e) { UpdateDays(Date, e); } public void UpdateDays(ObservableCollection<object> Date, SelectionChangedEventArgs e) { Device.BeginInvokeOnMainThread(() => { try { if (Date.Count == 3) { bool isupdate = false; if (e.OldValue != null && e.NewValue != null) { if (!object.Equals((e.OldValue as IList)[0], (e.NewValue as IList)[0])) { isupdate = true; } if (!object.Equals((e.OldValue as IList)[2], (e.NewValue as IList)[2])) { isupdate = true; } } if (isupdate) { ObservableCollection<object> days = new ObservableCollection<object>(); int month = DateTime.ParseExact(months[(e.NewValue as IList)[0].ToString()], "MMMM", CultureInfo.InvariantCulture).Month; int year = int.Parse((e.NewValue as IList)[2].ToString()); for (int j = 1; j <= DateTime.DaysInMonth(year, month); j++) { if (j < 10) { days.Add("0" + j); } else days.Add(j.ToString()); } ObservableCollection<object> oldvalue = new ObservableCollection<object>(); foreach (var item in e.NewValue as IList) { oldvalue.Add(item); } if (days.Count > 0) { Date.RemoveAt(1); Date.Insert(1, days); } if ((Date[1] as IList).Contains(oldvalue[1])) { this.SelectedItem = oldvalue; } else { oldvalue[1] = (Date[1] as IList)[(Date[1] as IList).Count - 1]; this.SelectedItem = oldvalue; } } } } catch { } }); } private void PopulateDateCollection() { //populate months for (int i = 1; i < 13; i++) { if(!months.ContainsKey(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3))) months.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3), CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i)); Month.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i).Substring(0, 3)); } //populate year for (int i = 1990; i < 2050; i++) { Year.Add(i.ToString()); } //populate Days for (int i = 1; i <= DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); i++) { if (i < 10) { Day.Add("0" + i); } else Day.Add(i.ToString()); } Date.Add(Month); Date.Add(Day); Date.Add(Year); } } } <file_sep>/iOS/SampleBrowser/Samples/XlsIO/SaveiOS.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Foundation; using QuickLook; using System; using System.Threading.Tasks; using SampleBrowser; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Reflection; using UIKit; namespace SampleBrowser { class SaveiOS { public void Save(string filename, String contentType, MemoryStream stream ) { string exception = string.Empty; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filePath = Path.Combine(path, filename); try { FileStream fileStream = File.Open(filePath, FileMode.Create); stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { exception = e.ToString(); } if (exception != string.Empty) return; UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (currentController.PresentedViewController != null) currentController = currentController.PresentedViewController; UIView currentView = currentController.View; QLPreviewController qlPreview = new QLPreviewController(); QLPreviewItem item = new QLPreviewItemBundle(filename, filePath); qlPreview.DataSource = new PreviewControllerDS(item); currentController.PresentViewController((UIViewController)qlPreview, true, (Action)null); } } }<file_sep>/Forms/CheckBox/CheckBox/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.Buttons; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfCheckBox { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Themes : SampleView { public Themes() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Tablet || Device.Idiom == TargetIdiom.Desktop) { title.FontSize = 22; if (Device.Idiom == TargetIdiom.Tablet) { grilledChicken.FontSize = chickenTikka.FontSize = 20; chickenSausage.FontSize = beef.FontSize = 20; } title.Margin = new Thickness(0, 20, 0, 10); grilledChicken.Margin = new Thickness(0, 30, 0, 0); chickenTikka.Margin = new Thickness(0, 30, 0, 0); chickenSausage.Margin = new Thickness(0, 30, 0, 0); beef.Margin = new Thickness(0, 30, 0, 30); } if (Device.RuntimePlatform == Device.WPF || Device.RuntimePlatform == Device.UWP) { MainStack1.HorizontalOptions = LayoutOptions.Center; MainStack1.VerticalOptions = LayoutOptions.Start; } } } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/OnBoardHelps/EditingBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "EditingBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.Threading.Tasks; using Xamarin.Forms; /// <summary> /// Editing Behavior class performs editing animation. /// </summary> public class EditingBehavior : Behavior<Image> { /// <summary> /// Holds the edit illustration image. /// </summary> private Image editIllustrationImage; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="image">Image which is attached.</param> protected override void OnAttachedTo(Image image) { base.OnAttachedTo(image); this.editIllustrationImage = image; this.AnimateEditIllustrationImage(); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="image">Image which is attached.</param> protected override void OnDetachingFrom(Image image) { base.OnDetachingFrom(image); this.editIllustrationImage = null; } /// <summary> /// Used animate edit Illustration Image /// </summary> private async void AnimateEditIllustrationImage() { // Default opacity value as zero and we set 1 as dynamically, we have dont this operation two time due to achive // double click animate view. this.editIllustrationImage.Opacity = 0; await this.editIllustrationImage.FadeTo(1, 250); this.editIllustrationImage.Opacity = 0; await this.editIllustrationImage.FadeTo(1, 250); await Task.Delay(1000); this.AnimateEditIllustrationImage(); } } }<file_sep>/Android/SampleBrowser/Samples/DocIO/NestedMailMerge.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using System.Data; using System.Collections; namespace SampleBrowser { public partial class NestedMailMerge : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to perform Mail merge for nested groups in Word document using Essential DocIO."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Creating a new document. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Template_Letter.doc"); //Open Template document document.Open(inputStream, FormatType.Word2013); inputStream.Dispose(); inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Employees.xml"); DataSet ds = new DataSet(); ds.ReadXml(inputStream); ArrayList commands = new ArrayList(); //DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE) DictionaryEntry entry = new DictionaryEntry("Employees", string.Empty); commands.Add(entry); // To retrive customer details DataTable table = ds.Tables["Customers"]; string relation = table.ParentRelations[0].ChildColumns[0].ColumnName + " = %Employees." + table.ParentRelations[0].ParentColumns[0].ColumnName + "%"; entry = new DictionaryEntry("Customers", relation); commands.Add(entry); // To retrieve order details table = ds.Tables["Orders"]; relation = table.ParentRelations[0].ChildColumns[0].ColumnName + " = %Customers." + table.ParentRelations[0].ParentColumns[0].ColumnName + "%"; entry = new DictionaryEntry("Orders", relation); commands.Add(entry); //Executes nested Mail merge using explicit relational data. document.MailMerge.ExecuteNestedGroup(ds, commands); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("NestedMailMerge.docx", "application/msword", stream, m_context); } } } } <file_sep>/iOS/SampleBrowser/.github/PULL_REQUEST_TEMPLATE/featureTemplate.md **Feature description** * Clearly and concisely describe the problem or feature (this cannot be empty). **Analysis and design** * If there is an external design, link to its project documentation area. * If there is an internal discussion on the forum, provide the link. **Solution description** * Describe your code changes in detail for reviewers. **Areas affected and ensured** * List the areas are affected by your code changes. **Additional checklist** * [ ] Does it follow the design [guidelines](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/)? It is mandatory that, we should not move the changes without reading this. * [ ] Properly working in Xamarin.Forms [previewer](https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-previewer?tabs=vswin). * [ ] Ensured in iOS, Android, UWP and macOS (if supported). * [ ] Doesn’t have memory leak. Please check the list of items to be ensured [here](https://syncfusion.atlassian.net/wiki/spaces/XAMRIN/pages/880875734/Memory+Leak). * [ ] Have you added [Preserve](https://syncfusion.atlassian.net/wiki/spaces/XAMRIN/pages/192124218/Guidelines+for+adding+Preserve+attribute) attribute if needed? * [ ] Have you ensured the changes in Android API 19 and iOS 9? <file_sep>/Forms/Chart/Chart/Samples/Trackball/TrackballViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { class TrackballViewModel { public ObservableCollection<ChartDataModel> LineSeries1 { get; set; } public ObservableCollection<ChartDataModel> LineSeries2 { get; set; } public ObservableCollection<ChartDataModel> LineSeries3 { get; set; } public TrackballViewModel() { LineSeries1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2000, 2, 11), 15), new ChartDataModel(new DateTime(2000, 9, 14), 20), new ChartDataModel(new DateTime(2001, 2, 11), 25), new ChartDataModel(new DateTime(2001, 9, 16), 21), new ChartDataModel(new DateTime(2002, 2, 07), 13), new ChartDataModel(new DateTime(2002, 9, 07), 18), new ChartDataModel(new DateTime(2003, 2, 11), 24), new ChartDataModel(new DateTime(2003, 9, 14), 23), new ChartDataModel(new DateTime(2004, 2, 06), 19), new ChartDataModel(new DateTime(2004, 9, 06), 31), new ChartDataModel(new DateTime(2005, 2, 11), 39), new ChartDataModel(new DateTime(2005, 9, 11), 50), new ChartDataModel(new DateTime(2006, 2, 11), 24) }; LineSeries2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2000, 2, 11), 39), new ChartDataModel(new DateTime(2000, 9, 14), 30), new ChartDataModel(new DateTime(2001, 2, 11), 28), new ChartDataModel(new DateTime(2001, 9, 16), 35), new ChartDataModel(new DateTime(2002, 2, 07), 39), new ChartDataModel(new DateTime(2002, 9, 07), 41), new ChartDataModel(new DateTime(2003, 2, 11), 45), new ChartDataModel(new DateTime(2003, 9, 14), 48), new ChartDataModel(new DateTime(2004, 2, 06), 54), new ChartDataModel(new DateTime(2004, 9, 06), 55), new ChartDataModel(new DateTime(2005, 2, 11), 57), new ChartDataModel(new DateTime(2005, 9, 11), 60), new ChartDataModel(new DateTime(2006, 2, 11), 60) }; LineSeries3 = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2000, 2, 11), 60), new ChartDataModel(new DateTime(2000, 9, 14), 55), new ChartDataModel(new DateTime(2001, 2, 11), 48), new ChartDataModel(new DateTime(2001, 9, 16), 57), new ChartDataModel(new DateTime(2002, 2, 07), 62), new ChartDataModel(new DateTime(2002, 9, 07), 64), new ChartDataModel(new DateTime(2003, 2, 11), 57), new ChartDataModel(new DateTime(2003, 9, 14), 53), new ChartDataModel(new DateTime(2004, 2, 06), 63), new ChartDataModel(new DateTime(2004, 9, 06), 50), new ChartDataModel(new DateTime(2005, 2, 11), 66), new ChartDataModel(new DateTime(2005, 9, 11), 65), new ChartDataModel(new DateTime(2006, 2, 11), 79) }; } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/AnnotationCustomization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; namespace SampleBrowser { class AnnotationCustomization:SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.AreaBackgroundColor = Color.Rgb(245, 245, 245); NumericalAxis categoryaxis = new NumericalAxis(); categoryaxis.ShowMajorGridLines = false; categoryaxis.Minimum = 0; categoryaxis.Maximum = 4; categoryaxis.LineStyle.StrokeColor = Color.White; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.ShowMajorGridLines = false; numericalaxis.Minimum = 20; numericalaxis.Maximum = 70; numericalaxis.LineStyle.StrokeColor = Color.White; chart.SecondaryAxis = numericalaxis; LineAnnotation lineAnnotation = new LineAnnotation(); lineAnnotation.Text = "Line"; lineAnnotation.X1 = 2.5; lineAnnotation.X2 = 3.5; lineAnnotation.Y1 = 52; lineAnnotation.Y2 = 63; lineAnnotation.LabelStyle.MarginTop = 5; lineAnnotation.LabelStyle.MarginRight = 5; lineAnnotation.LabelStyle.MarginLeft = 5; lineAnnotation.LabelStyle.MarginBottom = 5; lineAnnotation.LineCap = ChartLineCap.Arrow; HorizontalLineAnnotation horizontalAnnotation = new HorizontalLineAnnotation(); horizontalAnnotation.Y1 = 45; horizontalAnnotation.Text = "Horizontal Line"; horizontalAnnotation.LineCap = ChartLineCap.Arrow; horizontalAnnotation.ShowAxisLabel = true; VerticalLineAnnotation verticalAnnotation = new VerticalLineAnnotation(); verticalAnnotation.X1 = 2; verticalAnnotation.Text = "Vertical Line"; verticalAnnotation.LineCap = ChartLineCap.Arrow; verticalAnnotation.ShowAxisLabel = true; RectangleAnnotation RectAnnotation = new RectangleAnnotation(); RectAnnotation.X1 = 0.5; RectAnnotation.X2 = 1.5; RectAnnotation.Y1 = 25; RectAnnotation.Y2 = 35; RectAnnotation.Text = "Rectangle"; EllipseAnnotation eleAnnotation = new EllipseAnnotation(); eleAnnotation.X1 = 2.5; eleAnnotation.X2 = 3.5; eleAnnotation.Y1 = 25; eleAnnotation.Y2 = 35; eleAnnotation.Text = "Ellipse"; TextAnnotation textAnnotation = new TextAnnotation(); textAnnotation.X1 = 1; textAnnotation.Y1 = 57.5; textAnnotation.Text = "Text Annotation"; chart.Annotations.Add(textAnnotation); chart.Annotations.Add(eleAnnotation); chart.Annotations.Add(RectAnnotation); chart.Annotations.Add(verticalAnnotation); chart.Annotations.Add(horizontalAnnotation); chart.Annotations.Add(lineAnnotation); return chart; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Carousel/Carousel_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfCarousel.iOS; using System.Collections.Generic; using System; using Syncfusion.Drawing; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Carousel_Tablet: SampleView { SFCarousel carousel; SFCarouselItem carouselItem; UILabel offsetLabel,scaleOffsetLabel,rotationAngleLabel; UIView contentView = new UIView (); UILabel propertiesLabel=new UILabel(); UIButton showPropertyButton,closeButton; UIView subView; UITextView offsetTextfield,scaleOffsetTextfield,rotationAngleTextfield; UILabel viewModeLabel; PickerModel viewModel; UIButton viewButton = new UIButton (); UIButton viewDoneButton=new UIButton(); UIPickerView viewModePicker; private string selectedType; private UIView activeview; // Controller that activated the keyboard private float scroll_amount = 0.0f; // amount to scroll private float bottom = 0.0f; // bottom point private float offset = 10.0f; // extra offset private bool moveViewUp = false; private readonly IList<string> viewModeList = new List<string>{ "Default", "Linear" }; public Carousel_Tablet() { //Carousel carousel = new SFCarousel (); carousel.ItemHeight = 350; carousel.ItemWidth = 200; carousel.SelectedItemOffset = 20; //CarouselItem collection creation NSMutableArray<SFCarouselItem> carouselItemCollection = new NSMutableArray<SFCarouselItem>(); for (int i = 1; i <= 7; i++) { carouselItem = new SFCarouselItem (); carouselItem.ImageName = "image"+i+".png"; carouselItemCollection.Add (carouselItem); } carousel.DataSource = carouselItemCollection; carousel.SelectedIndex = 2; carousel.Frame = new CGRect(125, 190, 350, 650); this.AddSubview (carousel); variableDeclaration(); autoHide(); loadOptionView(); } public void autoHide() { NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, KeyBoardUpNotification); NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, KeyBoardDownNotification); } private void KeyBoardUpNotification(NSNotification notification) { // get the keyboard size var r = UIKeyboard.BoundsFromNotification(notification); // Find what opened the keyboard foreach (UIView view in this.contentView.Subviews) { if (view.IsFirstResponder) activeview = view; } // Bottom of the controller = initial position + height + offset bottom = ((float)(activeview.Frame.Y + activeview.Frame.Height + offset)); // Calculate how far we need to scroll scroll_amount = ((float)(r.Height - (contentView.Frame.Size.Height - bottom))); // Perform the scrolling if (scroll_amount > 0) { moveViewUp = true; ScrollTheView(moveViewUp); } else { moveViewUp = false; } } private void KeyBoardDownNotification(NSNotification notification) { if (moveViewUp) { ScrollTheView(false); subView.Frame = new CGRect(0, this.Frame.Size.Height - this.Frame.Size.Height / 3, this.Frame.Size.Width, this.Frame.Size.Height / 3); } } private void ScrollTheView(bool move) { // scroll the view up or down UIView.BeginAnimations(string.Empty, System.IntPtr.Zero); UIView.SetAnimationDuration(0.1); var frame = contentView.Frame; if (move) { frame.Y -= scroll_amount; } else { frame.Y += scroll_amount; scroll_amount = 0; } subView.Frame = new CGRect(0, (this.Frame.Size.Height - this.Frame.Size.Height/2)-50, this.Frame.Size.Width, this.Frame.Size.Height / 3); UIView.CommitAnimations(); } public void variableDeclaration() { viewModePicker = new UIPickerView(); viewModel = new PickerModel(viewModeList); viewModePicker.Model = viewModel; viewModeLabel = new UILabel(); viewButton = new UIButton(); showPropertyButton = new UIButton(); closeButton = new UIButton(); offsetLabel = new UILabel(); scaleOffsetLabel = new UILabel(); rotationAngleLabel = new UILabel(); } public void loadOptionView() { //offsetLabel offsetLabel.Text = "Offset"; offsetLabel.TextColor = UIColor.Black; offsetLabel.TextAlignment = UITextAlignment.Left; offsetLabel.Font = UIFont.FromName("Helvetica", 14f); //scaleOffsetLabel scaleOffsetLabel.Text = "Scale Offset"; scaleOffsetLabel.TextColor = UIColor.Black; scaleOffsetLabel.TextAlignment = UITextAlignment.Left; scaleOffsetLabel.Font = UIFont.FromName("Helvetica", 14f); //rotatingAngleLabel rotationAngleLabel.Text = "Rotation Angle"; rotationAngleLabel.TextColor = UIColor.Black; rotationAngleLabel.TextAlignment = UITextAlignment.Left; rotationAngleLabel.Font = UIFont.FromName("Helvetica", 14f); //offsetTextField offsetTextfield = new UITextView(); offsetTextfield.TextAlignment = UITextAlignment.Center; offsetTextfield.Layer.BorderColor = UIColor.Black.CGColor; offsetTextfield.KeyboardType = UIKeyboardType.NumberPad; offsetTextfield.BackgroundColor = UIColor.FromRGB(246, 246, 246); offsetTextfield.Text = "60"; offsetTextfield.Changed += (object sender, EventArgs e) => { if (offsetTextfield.Text.Length > 0) { carousel.Offset = nfloat.Parse(offsetTextfield.Text); } else { carousel.Offset = 60; } if (offsetTextfield.Text.Length > 0) { if (((nfloat)0) <= (nfloat.Parse(offsetTextfield.Text))) { if ((nfloat.Parse(offsetTextfield.Text)) <= (nfloat)100) carousel.Offset = nfloat.Parse(offsetTextfield.Text); else { carousel.Offset = (nfloat)60; offsetTextfield.Text = "60"; } } else { carousel.Offset = (nfloat)60; offsetTextfield.Text = "60"; } } }; //scaleOffsetTextField scaleOffsetTextfield = new UITextView(); scaleOffsetTextfield.TextAlignment = UITextAlignment.Center; scaleOffsetTextfield.Layer.BorderColor = UIColor.Black.CGColor; scaleOffsetTextfield.BackgroundColor = UIColor.FromRGB(246, 246, 246); scaleOffsetTextfield.KeyboardType = UIKeyboardType.NumberPad; scaleOffsetTextfield.Text = "0.8"; scaleOffsetTextfield.Changed += (object sender, EventArgs e) => { if (scaleOffsetTextfield.Text.Length > 0) { carousel.ScaleOffset = nfloat.Parse(scaleOffsetTextfield.Text); } else { carousel.ScaleOffset = (nfloat)0.8; } if (scaleOffsetTextfield.Text.Length > 0) { if (((nfloat)0) <= (nfloat.Parse(scaleOffsetTextfield.Text))) { if ((nfloat.Parse(scaleOffsetTextfield.Text)) <= (nfloat)1) carousel.ScaleOffset = nfloat.Parse(scaleOffsetTextfield.Text); else { carousel.ScaleOffset = (nfloat)0.8; scaleOffsetTextfield.Text = "0.8"; } } else { carousel.ScaleOffset = (nfloat)0.8; scaleOffsetTextfield.Text = "0.8"; } } }; //rotationAngleTextfield rotationAngleTextfield = new UITextView(); rotationAngleTextfield.TextAlignment = UITextAlignment.Center; rotationAngleTextfield.Layer.BorderColor = UIColor.Black.CGColor; rotationAngleTextfield.BackgroundColor = UIColor.FromRGB(246, 246, 246); rotationAngleTextfield.KeyboardType = UIKeyboardType.NumberPad; rotationAngleTextfield.Text = "45"; rotationAngleTextfield.Changed += (object sender, EventArgs e) => { if (rotationAngleTextfield.Text.Length > 0) { carousel.RotationAngle = int.Parse(rotationAngleTextfield.Text); } else { carousel.RotationAngle = 45; } if (rotationAngleTextfield.Text.Length > 0) { if (((nfloat)0) <= (nfloat.Parse(rotationAngleTextfield.Text))) { if ((nfloat.Parse(rotationAngleTextfield.Text)) <= (nfloat)360) carousel.RotationAngle = nfloat.Parse(rotationAngleTextfield.Text); else { carousel.RotationAngle = (nfloat)45; rotationAngleTextfield.Text = "45"; } } else { carousel.RotationAngle = (nfloat)45; rotationAngleTextfield.Text = "45"; } } }; //viewModeLabel viewModeLabel.Text = "View Mode"; viewModeLabel.Font = UIFont.FromName("Helvetica", 14f); viewModeLabel.TextColor = UIColor.Black; viewModeLabel.TextAlignment = UITextAlignment.Left; //viewButton viewButton.SetTitle("Default", UIControlState.Normal); viewButton.Font = UIFont.FromName("Helvetica", 14f); viewButton.SetTitleColor(UIColor.Black, UIControlState.Normal); viewButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; viewButton.Layer.CornerRadius = 8; viewButton.Layer.BorderWidth = 2; viewButton.TouchUpInside += ShowviewModePicker; viewButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //viewDoneButton viewDoneButton.SetTitle("Done\t", UIControlState.Normal); viewDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); viewDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; viewDoneButton.TouchUpInside += HidePicker; viewDoneButton.Hidden = true; viewDoneButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); viewModel.PickerChanged += viewSelectedIndexChanged; viewModePicker.ShowSelectionIndicator = true; viewModePicker.Hidden = true; viewModePicker.BackgroundColor = UIColor.Gray; //adding to contentView subView = new UIView(); contentView.AddSubview(rotationAngleLabel); contentView.AddSubview(offsetTextfield); contentView.AddSubview(scaleOffsetTextfield); contentView.AddSubview(rotationAngleTextfield); contentView.AddSubview(offsetLabel); contentView.AddSubview(scaleOffsetLabel); contentView.AddSubview(viewModeLabel); contentView.AddSubview(viewButton); contentView.AddSubview(viewModePicker); contentView.AddSubview(viewDoneButton); contentView.BackgroundColor = UIColor.FromRGB(230, 230, 230); subView.AddSubview(closeButton); //adding to subView propertiesLabel.Text = "OPTIONS"; subView.AddSubview(propertiesLabel); subView.BackgroundColor = UIColor.FromRGB(240, 240, 240); subView.AddSubview(contentView); this.AddSubview(subView); this.AddSubview(showPropertyButton); //showPropertyButton showPropertyButton.Hidden = true; showPropertyButton.SetTitle(" OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = false; showPropertyButton.Hidden = true; }; //closeButton closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; }; //AddingGesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer(() => { subView.Hidden = true; showPropertyButton.Hidden = false; } ); propertiesLabel.UserInteractionEnabled = true; propertiesLabel.AddGestureRecognizer(tapgesture); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; carousel.Frame = new CGRect ( 0,0, this.Frame.Size.Width,this.Frame.Size.Height-this.Frame.Size.Height/3); subView.Frame = new CGRect (0, this.Frame.Size.Height-this.Frame.Size.Height/3, this.Frame.Size.Width, this.Frame.Size.Height/3); contentView.Frame=new CGRect(0,40,subView.Frame.Size.Width,subView.Frame.Size.Height); offsetLabel.Frame = new CGRect ( 110, 30,this.Frame.Size.Width-210 , 30); scaleOffsetLabel.Frame = new CGRect (110, 80, contentView.Frame.Size.Width - 210, 30); rotationAngleLabel.Frame = new CGRect (110, 130, contentView.Frame.Size.Width - 210, 30); offsetTextfield.Frame = new CGRect (430, 30, contentView.Frame.Size.Width - 550, 30); scaleOffsetTextfield.Frame = new CGRect (430, 80, contentView.Frame.Size.Width - 550, 30); rotationAngleTextfield.Frame = new CGRect (430, 130, contentView.Frame.Size.Width - 550, 30); showPropertyButton.Frame = new CGRect (0, this.Frame.Size.Height-25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect (this.Frame.Width - 30, 5, 20, 30); propertiesLabel.Frame = new CGRect (10, 5, this.Frame.Width, 30); viewModeLabel.Frame = new CGRect ( 110,180, contentView.Frame.Size.Width - 210, 30); viewButton.Frame=new CGRect ( 430, 180, contentView.Frame.Size.Width - 550, 30); viewModePicker.Frame = new CGRect (100, 20, contentView.Frame.Size.Width-200, 150); viewDoneButton.Frame = new CGRect (100, 20, contentView.Frame.Size.Width-200, 30); } base.LayoutSubviews (); } void ShowviewModePicker (object sender, EventArgs e) { offsetTextfield.EndEditing(true); scaleOffsetTextfield.EndEditing(true); rotationAngleTextfield.EndEditing(true); viewDoneButton.Hidden = false; viewModePicker.Hidden = false; } void HidePicker (object sender, EventArgs e) { viewDoneButton.Hidden = true; viewModePicker.Hidden = true; } private void viewSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; viewButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Default") carousel.ViewMode = SFCarouselViewMode.SFCarouselViewModeDefault; else carousel.ViewMode = SFCarouselViewMode.SFCarouselViewModeLinear; } } }<file_sep>/Forms/ListView/ListView/Samples/Accordion/Model/Contact.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.ComponentModel; using Xamarin.Forms; namespace SampleBrowser.SfListView { public class Contact : INotifyPropertyChanged { #region Fields private string contactName; private string callTime; private string contactImage; private bool isVisible = false; #endregion #region Properties public bool IsVisible { get { return isVisible; } set { isVisible = value; this.RaisedOnPropertyChanged("IsVisible"); } } public string ContactName { get { return contactName; } set { if (contactName != value) { contactName = value; this.RaisedOnPropertyChanged("ContactName"); } } } public string CallTime { get { return callTime; } set { if (callTime != value) { callTime = value; this.RaisedOnPropertyChanged("CallTime"); } } } public string ContactImage { get { return this.contactImage; } set { this.contactImage = value; this.RaisedOnPropertyChanged("ContactImage"); } } #endregion #region Constrator public Contact() { } public Contact(string Name) { contactName = Name; } #endregion #region Interface Member public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DocIO/EmployeeReport.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using System.Collections.Generic; #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using System.Data; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class EmployeeReport : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton button; public EmployeeReport() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to create a letter format document by filling the data using Mail merge functionality of DocIO."; label.Lines = 0; label.Font = UIFont.SystemFontOfSize(15); label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 70); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 70); } this.AddSubview(label); button.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(5, 90, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 90, frameRect.Size.Width, 10); } button.TouchUpInside += OnButtonClicked; this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Creating a new document. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.EmployeesReportDemo.doc"); //Open Template document document.Open(inputStream, FormatType.Word2013); inputStream.Dispose(); System.Data.DataTable table = GetDataTable(); //Uses the mail merge events handler for image fields document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_ProductImage); document.MailMerge.ExecuteGroup(table); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("MailMerge.docx", "application/msword", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Frame; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } /// <summary> /// Gets the Employees record in DataTable format /// </summary> /// <returns></returns> private System.Data.DataTable GetDataTable() { //Data source DataSet ds = new DataSet(); ds.Tables.Add(); //Defining columns ds.Tables[0].TableName = "Employees"; ds.Tables[0].Columns.Add("Photo"); ds.Tables[0].Columns.Add("FirstName"); ds.Tables[0].Columns.Add("LastName"); ds.Tables[0].Columns.Add("Title"); ds.Tables[0].Columns.Add("Address"); ds.Tables[0].Columns.Add("City"); ds.Tables[0].Columns.Add("Region"); ds.Tables[0].Columns.Add("Country"); ds.Tables[0].Columns.Add("PostalCode"); ds.Tables[0].Columns.Add("HomePhone"); ds.Tables[0].Columns.Add("Extension"); ds.Tables[0].Columns.Add("BirthDate"); //Set values. DataRow row; row = ds.Tables["Employees"].NewRow(); row["Photo"] = "SampleImage.png"; row["FirstName"] = "Nancy"; row["LastName"] = "Davolio"; row["Title"] = "Sales Representative"; row["Address"] = "507 - 20th Ave. E.Apt. 2A"; row["City"] = "Seattle"; row["Region"] = "WA"; row["Country"] = "USA"; row["PostalCode"] = "98122"; row["HomePhone"] = "(206) 555-9857"; row["Extension"] = "5467"; row["BirthDate"] = "08-12-1948 12:00:00 AM"; ds.Tables["Employees"].Rows.Add(row); row = ds.Tables["Employees"].NewRow(); row["Photo"] = "SampleImage.png"; row["FirstName"] = "Andrew"; row["LastName"] = "Fuller"; row["Title"] = "Vice President, Sales"; row["Address"] = "507 - 20th Ave. E.Apt. 2A"; row["City"] = "Tacoma"; row["Region"] = "WA"; row["Country"] = "USA"; row["PostalCode"] = "98401"; row["HomePhone"] = "(206) 555-9842"; row["Extension"] = "3457"; row["BirthDate"] = "19-02-1952 12:00:00 AM"; ds.Tables["Employees"].Rows.Add(row); row = ds.Tables["Employees"].NewRow(); row["Photo"] = "SampleImage.png"; row["FirstName"] = "Janet"; row["LastName"] = "Leverling"; row["Title"] = "Sales Representative"; row["Address"] = "722 Moss Bay Blvd"; row["City"] = "Kirkland"; row["Region"] = "WA"; row["Country"] = "USA"; row["PostalCode"] = "98033"; row["HomePhone"] = "(206) 555-3412"; row["Extension"] = "3355"; row["BirthDate"] = "30-08-1963 12:00:00 AM"; ds.Tables["Employees"].Rows.Add(row); System.Data.DataTable table = ds.Tables["Employees"]; return table; } /// <summary> /// Execute the MergeImageFieldEvent to merge the images to corresponding image fields /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void MergeField_ProductImage(object sender, MergeImageFieldEventArgs args) { Assembly assembly = typeof(MailMerge).GetTypeInfo().Assembly; string rootPath = "SampleBrowser.Samples.DocIO.Templates."; //Binds image from file system during mail merge if (args.FieldName == "Photo") { string ProductFileName = args.FieldValue.ToString(); Stream inputStream = assembly.GetManifestResourceStream(rootPath + ProductFileName); args.ImageStream = inputStream; } } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/AxisCrossing.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; namespace SampleBrowser { class AxisCrossing: SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Profit/loss percentage comparison"; CategoryAxis primaryAxis = new CategoryAxis(); primaryAxis.CrossesAt = 0; primaryAxis.PlotOffset = 7; primaryAxis.AxisLineOffset = 7; primaryAxis.ShowMajorGridLines = false; primaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; primaryAxis.Interval = 2; primaryAxis.Name = "XAxis"; primaryAxis.CrossingAxisName = "YAxis"; primaryAxis.ShowMajorGridLines = false; chart.PrimaryAxis = primaryAxis; NumericalAxis secondaryAxis = new NumericalAxis(); secondaryAxis.ShowMajorGridLines = false; secondaryAxis.Maximum = -100; secondaryAxis.Minimum = 100; secondaryAxis.Interval = 20; secondaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; secondaryAxis.Name = "YAxis"; secondaryAxis.ShowMajorGridLines = false; secondaryAxis.ShowMinorGridLines = false; secondaryAxis.CrossingAxisName = "XAxis"; secondaryAxis.LabelCreated += SecondaryAxis_LabelCreated; chart.SecondaryAxis = secondaryAxis; ScatterSeries scatterSeries = new ScatterSeries() { Name = "series1", ItemsSource = Data.CrossingData(), XBindingPath = "XValue", YBindingPath = "YValue", ScatterWidth = 15, ScatterHeight = 15, TooltipEnabled = true, }; scatterSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; ChartZoomPanBehavior zoomPanBehavior = new ChartZoomPanBehavior(); chart.Behaviors.Add(zoomPanBehavior); chart.Series.Add(scatterSeries); chart.SecondaryAxis.CrossesAt = 8; return chart; } void SecondaryAxis_LabelCreated(object sender, ChartAxis.LabelCreatedEventArgs e) { e.AxisLabel.LabelContent = e.AxisLabel.LabelContent + "%"; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/PullToRefresh.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Syncfusion.SfDataGrid; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Threading.Tasks; using UIKit; namespace SampleBrowser { public class PullToRefresh : SampleView { #region Fields SfDataGrid SfGrid; PullToRefreshViewModel viewModel; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public PullToRefresh() { this.SfGrid = new SfDataGrid(); viewModel = new PullToRefreshViewModel(); this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.ItemsSource = viewModel.OrdersInfo; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.AllowPullToRefresh = true; this.SfGrid.PullToRefreshCommand = new Command(ExecuteCommand); this.AddSubview(this.SfGrid); } void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo("en-US"); e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Index") { e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "Last Name"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 10; } else if (e.Column.MappingName == "ShippingDate") { e.Column.HeaderText = "Shipping Date"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; e.Column.Format = "d"; } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } } private async void ExecuteCommand() { try { this.SfGrid.IsBusy = true; await Task.Delay(new TimeSpan(0, 0, 3)); this.viewModel.ItemsSourceRefresh(); this.SfGrid.IsBusy = false; } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } } public override void LayoutSubviews() { this.SfGrid.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { SfGrid.Dispose(); base.Dispose(disposing); } } } <file_sep>/iOS/SampleBrowser/Samples/RadialMenu/ContextualMenu.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Foundation; using Syncfusion.SfRadialMenu.iOS; using UIKit; namespace SampleBrowser { public class ContextualMenu : SampleView { SfRadialMenu radialMenu; UIButton shareButton; UILabel shareText, titleLabel; UIAlertView alertWindow; UIView shareView; UIStringAttributes underlineAttr = new UIStringAttributes { UnderlineStyle = NSUnderlineStyle.Single, ForegroundColor = UIColor.FromRGB(30,168,242) }; public ContextualMenu() { titleLabel = new UILabel(); titleLabel.Text = "About Syncfusion"; titleLabel.Font = UIFont.FromName("Helvetica", 20f); shareText = new UILabel(); shareText.Text = "\tSyncfusion is the enterprise technology partner of choice for software development, delivering a broad range of web, mobile, and desktop controls coupled with a service-oriented approach throughout the entire application lifecycle. Syncfusion has established itself as the trusted partner worldwide for use in applications."; shareText.Lines = 0; shareText.LineBreakMode = UILineBreakMode.WordWrap; shareText.Font = UIFont.FromName("Helvetica", 16f); shareView = new UIView(); shareView.BackgroundColor = UIColor.White; shareButton = new UIButton(); shareButton.SetAttributedTitle(new NSAttributedString("Tap here to follow us", underlineAttr), UIControlState.Normal); shareButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; shareButton.BackgroundColor = UIColor.Clear; shareButton.SetTitleColor(UIColor.FromRGB(41,146,247), UIControlState.Normal); shareButton.TouchUpInside += shareButtonClicked; shareView.Add(shareButton); radialMenu = new SfRadialMenu(); radialMenu.Hidden = true; CGRect apprect = UIScreen.MainScreen.Bounds; //radialMenu.Position = new CGPoint(apprect.Width / 2, apprect.Height - apprect.Height/3 - 55); radialMenu.IsDragEnabled = false; radialMenu.RimRadius = 100; radialMenu.CenterButtonRadius = 25; radialMenu.CenterButtonBorderThickness = 2; radialMenu.EnableRotation = true; radialMenu.RimColor = UIColor.Clear; radialMenu.CenterButtonText = "\ue703"; radialMenu.CenterButtonBackgroundColor = UIColor.FromRGB(0,207,72); radialMenu.CenterButtonTextColor = UIColor.White; radialMenu.CenterButtonIconFont = UIFont.FromName("Social", 30); radialMenu.CenterButtonTextFrame = new CGRect(-1,5,50,50); radialMenu.Closed+= RadialMenu_Closed; SfRadialMenuItem facebook = new SfRadialMenuItem() {Image="facebook.png", FontIconFrame= new CGRect(0,4,30,30),IconFont = UIFont.FromName("Social", 20),FontIconColor=UIColor.White, FontIcon = "\ue700" }; facebook.ItemTapped += facebook_ItemTapped; radialMenu.Items.Add(facebook); SfRadialMenuItem gplus = new SfRadialMenuItem() { Image = "gplus.png", FontIconFrame = new CGRect(0, 4, 30, 30),IconFont = UIFont.FromName("Social", 20),FontIconColor = UIColor.White, FontIcon = "\ue707" }; gplus.ItemTapped += gPlus_ItemTapped; radialMenu.Items.Add(gplus); SfRadialMenuItem twitter = new SfRadialMenuItem() {Image = "twitter.png", FontIconFrame = new CGRect(0, 4, 30, 30), IconFont = UIFont.FromName("Social", 20),FontIconColor = UIColor.White, FontIcon = "\ue704"}; twitter.ItemTapped += twitter_ItemTapped; radialMenu.Items.Add(twitter); SfRadialMenuItem pinterest = new SfRadialMenuItem() { Image = "pinterest.png", FontIconFrame = new CGRect(0, 4, 30, 30),IconFont = UIFont.FromName("Social", 20),FontIconColor = UIColor.White, FontIcon = "\ue705"}; pinterest.ItemTapped += pinterest_ItemTapped; radialMenu.Items.Add(pinterest); SfRadialMenuItem linkedIn = new SfRadialMenuItem() { Image = "linkedin.png", FontIconFrame = new CGRect(0, 4, 30, 30),IconFont = UIFont.FromName("Social", 20),FontIconColor = UIColor.White, FontIcon = "\ue706"}; linkedIn.ItemTapped += linkedIn_ItemTapped; radialMenu.Items.Add(linkedIn); SfRadialMenuItem instagram = new SfRadialMenuItem() {Image = "instagram.png", FontIconFrame = new CGRect(0, 4, 30, 30), IconFont = UIFont.FromName("Social", 20),FontIconColor = UIColor.White, FontIcon = "\ue708"}; instagram.ItemTapped += instagram_ItemTapped; radialMenu.Items.Add(instagram); alertWindow = new UIAlertView(); alertWindow.AddButton("OK"); this.Add(titleLabel); this.Add(shareText); this.Add(shareView); this.Add(radialMenu); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { titleLabel.Frame = new CGRect(10, 10, Frame.Width, 30); shareText.Frame = new CGRect(5, 40, Frame.Width-10, 160); shareView.Frame = new CGRect(10,210,Frame.Width-20,Frame.Height/2); shareButton.Frame = new CGRect(0, 0, shareView.Frame.Width, shareView.Frame.Height); radialMenu.Position = new CGPoint(Frame.Width/2, shareView.Frame.Top+shareView.Frame.Height/2); } else { titleLabel.Frame = new CGRect(10, 10, Frame.Width, 30); shareText.Frame = new CGRect(5, 40, Frame.Width - 10, 160); shareView.Frame = new CGRect(10, 210, Frame.Width - 20, Frame.Height / 2); shareButton.Frame = new CGRect(0, 0, shareView.Frame.Width, shareView.Frame.Height); radialMenu.Position = new CGPoint(Frame.Width / 2, shareView.Frame.Top + shareView.Frame.Height / 2); } } base.LayoutSubviews(); } void facebook_ItemTapped(object sender, EventArgs e) { alertWindow.Message = "Shared in Facebook"; alertWindow.Show(); } void gPlus_ItemTapped(object sender, EventArgs e) { alertWindow.Message = "Shared in Google+"; alertWindow.Show(); } void twitter_ItemTapped(object sender, EventArgs e) { alertWindow.Message = "Shared in Twitter"; alertWindow.Show(); } void pinterest_ItemTapped(object sender, EventArgs e) { alertWindow.Message = "Shared in Pinterest"; alertWindow.Show(); } void linkedIn_ItemTapped(object sender, EventArgs e) { alertWindow.Message = "Shared in LinkedIn"; alertWindow.Show(); } void instagram_ItemTapped(object sender, EventArgs e) { alertWindow.Message = "Shared in Instagram"; alertWindow.Show(); } void RadialMenu_Closed(object sender, EventArgs e) { shareButton.SetAttributedTitle(new NSAttributedString("Tap here to share", underlineAttr), UIControlState.Normal); radialMenu.Hidden = true; } void shareButtonClicked(object sender, EventArgs e) { if (radialMenu.Hidden) { shareButton.SetAttributedTitle(new NSAttributedString("", underlineAttr), UIControlState.Normal); radialMenu.Hidden = false; radialMenu.Open(); } this.BecomeFirstResponder(); } } } <file_sep>/Android/SampleBrowser/Samples/Calendar/CalendarConfiguration/CalendarConfiguration_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Calendar; using Com.Syncfusion.Calendar.Enums; using Com.Syncfusion.Navigationdrawer; using Android.Graphics; using Java.Util; using Android.Text.Format; using Java.Text; namespace SampleBrowser { public class CalendarConfiguration_Mobile : IDisposable { /********************************* **Local Variable Inizialisation** *********************************/ private SelectionMode selectioMode = SelectionMode.SingleSelection; private LinearLayout.LayoutParams minMaxSeparatorLayoutParam; private LinearLayout.LayoutParams underMaxSeparatorLayoutParam; private DatePickerDialog minDatePicker, maxDatePicker; private LinearLayout propertylayout; private FrameLayout mainView; private Button minDateButton, maxDateButton; private Calendar minPick, maxPick; private TextView spaceAdder2, maxDate; private SeparatorView underMaxSeparator; private ArrayAdapter<String> dataAdapter; private SeparatorView minMaxSeparator; private TextView spaceAdder1, minDate; private const int DATEDIALOGID = 0; private SfCalendar calendar; private Spinner modeSpinner; private Context context; private TextView viewModetxt; private int width; public View GetSampleContent(Context con) { context = con; /************ **Calendar** ************/ MonthViewLabelSetting labelSettings = new MonthViewLabelSetting(); labelSettings.DateLabelSize = 14; MonthViewSettings monthViewSettings = new MonthViewSettings(); monthViewSettings.MonthViewLabelSetting = labelSettings; monthViewSettings.TodayTextColor = Color.ParseColor("#1B79D6"); monthViewSettings.InlineBackgroundColor = Color.ParseColor("#E4E8ED"); monthViewSettings.CurrentMonthTextColor = Color.ParseColor("#F7F7F7"); monthViewSettings.SelectedDayTextColor = Color.Black; monthViewSettings.WeekDayBackgroundColor = Color.ParseColor("#464646"); monthViewSettings.WeekDayTextColor = Color.ParseColor("#F9F9F9"); monthViewSettings.PreviousMonthTextColor = Color.ParseColor("#BFBFBF"); monthViewSettings.PreviousMonthBackgroundColor = Color.ParseColor("#F9F9F9"); //Calendar Inizializatation calendar = new SfCalendar(con); calendar.ShowEventsInline = false; calendar.HeaderHeight = 100; calendar.ViewMode = ViewMode.MonthView; calendar.MonthViewSettings = monthViewSettings; calendar.DrawMonthCell += Calendar_DrawMonthCell; //main View mainView = new FrameLayout(con); mainView.AddView(calendar); return mainView; } public View GetPropertyWindowLayout(Context co) { context = co; width = context.Resources.DisplayMetrics.WidthPixels / 2; ViewmodeLayout(); MinimumDateLayout(); MaximumDateLayout(); /****************** **propertylayout** ******************/ propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; propertylayout.AddView(viewModetxt); propertylayout.AddView(modeSpinner); propertylayout.AddView(spaceAdder1); propertylayout.AddView(minDate); propertylayout.AddView(minDateButton); //propertylayout.AddView(minMaxSeparator, minMaxSeparatorLayoutParam); propertylayout.AddView(spaceAdder2); propertylayout.AddView(maxDate); propertylayout.AddView(maxDateButton); //propertylayout.AddView (underMaxSeparator,underMaxSeparatorLayoutParam); propertylayout.SetPadding(10, 10, 10, 10); return propertylayout; } private void ViewmodeLayout() { /************ **ViewMode** ************/ viewModetxt = new TextView(context); viewModetxt.TextSize = 20; viewModetxt.Text = "Selection Mode"; modeSpinner = new Spinner(context, SpinnerMode.Dialog); //Selection List List<String> selectionList = new List<String>(); selectionList.Add("Single Selection"); selectionList.Add("Multiple Selection"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, selectionList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); modeSpinner.Adapter = dataAdapter; //Mode Spinner Item Changed Listener modeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Single Selection")) { selectioMode = SelectionMode.SingleSelection; } if (selectedItem.Equals("Multiple Selection")) { selectioMode = SelectionMode.MultiSelection; } }; } private void MinimumDateLayout() { /**************** **Minimum Date** ****************/ spaceAdder1 = new TextView(context); minPick = Calendar.Instance; minPick.Set(2012, 0, 1); maxPick = Calendar.Instance; maxPick.Set(2018, 11, 1); //Minimum Date Text minDate = new TextView(context); minDate.Text = "Min Date"; minDate.TextSize = 20; minDate.Gravity = GravityFlags.Left; //minDateButton minDateButton = new Button(context); minDateButton.SetBackgroundColor(Color.ParseColor("#8CD4CF")); minDateButton.Text = "1/1/2012"; minDateButton.TextSize = 16; minDatePicker = new DatePickerDialog(context, MinDateSetting, 2012, 1, 1); minDateButton.Click += (object sender, EventArgs e) => { minDatePicker.Show(); }; //Separator 1 minMaxSeparator = new SeparatorView(context, width * 2); minMaxSeparator.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); minMaxSeparatorLayoutParam = new LinearLayout.LayoutParams(width * 2, 5); minMaxSeparatorLayoutParam.SetMargins(0, 20, 0, 0); } private void MaximumDateLayout() { /**************** **Maximum Date** ****************/ spaceAdder2 = new TextView(context); maxDate = new TextView(context); maxDate.Text = "Max Date"; maxDate.TextSize = 20; maxDate.Gravity = GravityFlags.Left; //maxDateButton maxDateButton = new Button(context); maxDateButton.Text = "1/12/2018"; maxDateButton.TextSize = 16; maxDateButton.SetBackgroundColor(Color.ParseColor("#8CD4CF")); maxDatePicker = new DatePickerDialog(context, MaxDateSetting, 2018, 12, 1); maxDateButton.Click += (object sender, EventArgs e) => { maxDatePicker.Show(); }; //Separator 1 underMaxSeparator = new SeparatorView(context, width * 2); underMaxSeparator.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); underMaxSeparatorLayoutParam = new LinearLayout.LayoutParams(width * 2, 5); underMaxSeparatorLayoutParam.SetMargins(0, 20, 0, 0); } /******************************* **Minimum DateSelect Method** *******************************/ private void MinDateSetting(object sender, DatePickerDialog.DateSetEventArgs e) { DateTime newMinDate = e.Date; Calendar minCal = Calendar.Instance; minCal.Set(newMinDate.Year, newMinDate.Month - 1, newMinDate.Day); if (calendar.MaxDate == null || (calendar.MaxDate != null && minCal.Before(calendar.MaxDate))) { calendar.MinDate = minCal; StringBuilder stringBuilder = new StringBuilder().Append(newMinDate.Day).Append("/").Append(newMinDate.Month).Append("/").Append(newMinDate.Year); minDateButton.Text = stringBuilder.ToString(); } } /******************************* **Maximum DateSelect Method** *******************************/ private void MaxDateSetting(object sender, DatePickerDialog.DateSetEventArgs e) { DateTime newMaxDate = e.Date; Calendar maxCal = Calendar.Instance; maxCal.Set(newMaxDate.Year, newMaxDate.Month - 1, newMaxDate.Day); if (calendar.MinDate == null || (calendar.MinDate != null && maxCal.After(calendar.MinDate))) { calendar.MaxDate = maxCal; StringBuilder stringBuilder = new StringBuilder().Append(newMaxDate.Day).Append("/").Append(newMaxDate.Month).Append("/").Append(newMaxDate.Year); maxDateButton.Text = stringBuilder.ToString(); } } /************************ **Apply Changes Method** ************************/ public void ApplyChanges() { calendar.SelectionMode = selectioMode; } /************************ **DrawMonthCell Method** ************************/ private void Calendar_DrawMonthCell(object sender, DrawMonthCellEventArgs e) { SimpleDateFormat compareString = new SimpleDateFormat("dd/MM/yyyy"); String temp = new SimpleDateFormat("dd/MM/yyyy").Format(e.MonthCell.Date.Time); Java.Util.Date date = compareString.Parse(temp); string dayString = new SimpleDateFormat("EEEE").Format(date); if (dayString.ToLower().Equals("sunday") || dayString.ToLower().Equals("saturday")) { e.MonthCell.TextColor = Color.ParseColor("#0990e9"); e.MonthCell.FontAttribute = Typeface.Create(" ", TypefaceStyle.Bold); } else { e.MonthCell.TextColor = Color.ParseColor("#7F7F7F"); e.MonthCell.FontAttribute = Typeface.Create(" ", TypefaceStyle.Italic); } } public void Dispose() { if (calendar != null) { calendar.DrawMonthCell -= Calendar_DrawMonthCell; calendar.Dispose(); calendar = null; } if (viewModetxt != null) { viewModetxt.Dispose(); viewModetxt = null; } if (modeSpinner != null) { modeSpinner.Dispose(); modeSpinner = null; } if (spaceAdder1 != null) { spaceAdder1.Dispose(); spaceAdder1 = null; } if (spaceAdder2 != null) { spaceAdder2.Dispose(); spaceAdder2 = null; } if (minDate != null) { minDate.Dispose(); minDate = null; } if (maxDate != null) { maxDate.Dispose(); maxDate = null; } if (minPick != null) { minPick.Dispose(); minPick = null; } if (maxPick != null) { maxPick.Dispose(); maxPick = null; } if (minDateButton != null) { minDateButton.Dispose(); minDateButton = null; } if (maxDateButton != null) { maxDateButton.Dispose(); maxDateButton = null; } if (mainView != null) { mainView.Dispose(); mainView = null; } if (propertylayout != null) { propertylayout.Dispose(); propertylayout = null; } if (minDatePicker != null) { minDatePicker.Dispose(); minDatePicker = null; } if (maxDatePicker != null) { maxDatePicker.Dispose(); maxDatePicker = null; } if (underMaxSeparatorLayoutParam != null) { underMaxSeparatorLayoutParam.Dispose(); underMaxSeparatorLayoutParam = null; } if (minMaxSeparatorLayoutParam != null) { minMaxSeparatorLayoutParam.Dispose(); minMaxSeparatorLayoutParam = null; } if (dataAdapter != null) { dataAdapter.Dispose(); dataAdapter = null; } if (underMaxSeparator != null) { underMaxSeparator.Dispose(); underMaxSeparator = null; } if (minMaxSeparator != null) { minMaxSeparator.Dispose(); minMaxSeparator = null; } } } }<file_sep>/Forms/PDF/PDF/Samples/RTLSupport/RTLSupport.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Xamarin.Forms; using System.IO; using SampleBrowser.Core; using System.Reflection; namespace SampleBrowser.PDF { public partial class RTLSupport : SampleView { public RTLSupport() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { //Create a new PDF document PdfDocument document = new PdfDocument(); //Add a page PdfPage page = document.Pages.Add(); //Create font #if COMMONSB Stream arialFontStream = typeof(RTLSupport).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.arial.ttf"); #else Stream arialFontStream = typeof(RTLSupport).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.arial.ttf"); #endif PdfFont font = new PdfTrueTypeFont(arialFontStream, 14); //Read the text from text file #if COMMONSB Stream rtlText = typeof(RTLSupport).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.arabic.txt"); #else Stream rtlText = typeof(RTLSupport).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.arabic.txt"); #endif StreamReader reader = new StreamReader(rtlText, System.Text.Encoding.Unicode); string text = reader.ReadToEnd(); reader.Dispose(); //Create a brush PdfBrush brush = new PdfSolidBrush(new PdfColor(0, 0, 0)); PdfPen pen = new PdfPen(new PdfColor(0,0,0)); SizeF clipBounds = page.Graphics.ClientSize; RectangleF rect = new RectangleF(0, 0, clipBounds.Width, clipBounds.Height); //Set the property for RTL text PdfStringFormat format = new PdfStringFormat(); format.TextDirection = PdfTextDirection.RightToLeft; format.Alignment = PdfTextAlignment.Right; format.ParagraphIndent = 35f; //Draw text. page.Graphics.DrawString(text, font, brush, rect, format); MemoryStream stream = new MemoryStream(); //Save the PDF document. document.Save(stream); //Close the PDF document. document.Close(); stream.Position = 0; if ( Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("RTLText.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("RTLText.pdf", "application/pdf", stream); } } } <file_sep>/iOS/SampleBrowser/Samples/RadialMenu/RadialMenuCustomization.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Syncfusion.SfRadialMenu.iOS; using UIKit; namespace SampleBrowser { public class RadialMenuCustomization : SampleView { UIView centerView; UIImageView centerImage; SfRadialMenu radialMenu; CustomDrawing drawingTool; UIView colorPaletteView; UILabel startUpLabel; bool isEraserSelected; UIColor tempColor; void DrawingTool_Tapped(object sender, EventArgs e) { startUpLabel.Hidden = true; } void HandleEventHandler(object sender, EventArgs e) { tempColor = (sender as UIButton).BackgroundColor; if (isEraserSelected) drawingTool.PenColor = UIColor.White; else drawingTool.PenColor = tempColor; } static Random rand = new Random(); public static UIColor GetRandomColor() { UIColor color = UIColor.FromRGB( rand.Next(255), rand.Next(255), rand.Next(255)); return color; } public RadialMenuCustomization() { tempColor = GetRandomColor(); isEraserSelected = false; colorPaletteView = new UIView(); colorPaletteView.BackgroundColor = UIColor.FromRGB(230, 230, 230); nfloat elementCount = UIScreen.MainScreen.Bounds.Width / 30; nfloat xPos = 5; for (int i = 0; i < elementCount; i++) { UIButton button = new UIButton(); button.Tag = 1000 + i; button.Layer.CornerRadius = 15; button.Frame = new CGRect(xPos, 5, 30, 30); button.BackgroundColor = GetRandomColor(); button.AddTarget(HandleEventHandler, UIControlEvent.TouchDown); colorPaletteView.Add(button); xPos += 40; } startUpLabel = new UILabel(); startUpLabel.Text = "Touch to draw"; startUpLabel.TextColor = UIColor.FromRGB(0, 191, 255); startUpLabel.TextAlignment = UITextAlignment.Center; startUpLabel.BackgroundColor = UIColor.Clear; radialMenu = new SfRadialMenu(); radialMenu.IsDragEnabled = false; radialMenu.RimRadius = 120; radialMenu.CenterButtonRadius = 40; radialMenu.CenterButtonBorderThickness = 0; radialMenu.CenterButtonBorderColor = UIColor.Clear; radialMenu.CenterButtonBackgroundColor = UIColor.Clear; radialMenu.EnableRotation = true; radialMenu.RimColor = UIColor.Clear; radialMenu.SeparatorThickness = 10; radialMenu.SeparatorColor = UIColor.Clear; centerView = new UIView(); centerView.Frame = new CGRect(0, 0, 80, 80); centerImage = new UIImageView(); centerImage.Image = UIImage.FromBundle("blue.png"); centerImage.Frame = new CGRect(0, 0, 80, 80); centerView.Add(centerImage); UILabel centerLabel = new UILabel(); centerLabel.Frame = new CGRect(0, 5, 80, 80); centerLabel.Text = "U"; centerLabel.TextAlignment = UITextAlignment.Center; centerLabel.Font = UIFont.FromName("ios", 30); centerLabel.TextColor = UIColor.White; centerView.Add(centerLabel); radialMenu.EnableCenterButtonAnimation = false; radialMenu.CenterButtonView = centerView; UIView penView = new UIView(); penView.Frame = new CGRect(0, 0, 80, 80); UIImageView penImage = new UIImageView(); penImage.Image = UIImage.FromBundle("green.png"); penImage.Frame = new CGRect(0, 0, 80, 80); penView.Add(penImage); UILabel penLabel = new UILabel(); penLabel.Frame = new CGRect(0, 5, 80, 80); penLabel.Text = "L"; penLabel.TextAlignment = UITextAlignment.Center; penLabel.Font = UIFont.FromName("ios", 30); penLabel.TextColor = UIColor.White; penView.Add(penLabel); SfRadialMenuItem pen = new SfRadialMenuItem() { Height = 80, Width = 80, View = penView, BackgroundColor = UIColor.Clear }; pen.ItemTapped += Pen_ItemTapped; radialMenu.Items.Add(pen); UIView brushView = new UIView(); brushView.Frame = new CGRect(0, 0, 80, 80); UIImageView brushImage = new UIImageView(); brushImage.Image = UIImage.FromBundle("green.png"); brushImage.Frame = new CGRect(0, 0, 80, 80); brushView.Add(brushImage); UILabel brushLabel = new UILabel(); brushLabel.Frame = new CGRect(0, 5, 80, 80); brushLabel.Text = "A"; brushLabel.TextAlignment = UITextAlignment.Center; brushLabel.Font = UIFont.FromName("ios", 30); brushLabel.TextColor = UIColor.White; brushView.Add(brushLabel); SfRadialMenuItem brush = new SfRadialMenuItem() { Height = 80, Width = 80, View = brushView, BackgroundColor = UIColor.Clear }; brush.ItemTapped += Brush_ItemTapped; radialMenu.Items.Add(brush); UIView eraserView = new UIView(); eraserView.Frame = new CGRect(0, 0, 80, 80); UIImageView eraserImage = new UIImageView(); eraserImage.Image = UIImage.FromBundle("green.png"); eraserImage.Frame = new CGRect(0, 0, 80, 80); eraserView.Add(eraserImage); UILabel eraserLabel = new UILabel(); eraserLabel.Frame = new CGRect(0, 5, 80, 80); eraserLabel.Text = "R"; eraserLabel.TextAlignment = UITextAlignment.Center; eraserLabel.Font = UIFont.FromName("ios", 30); eraserLabel.TextColor = UIColor.White; eraserView.Add(eraserLabel); SfRadialMenuItem eraser = new SfRadialMenuItem() { Height = 80, Width = 80, View = eraserView, BackgroundColor = UIColor.Clear }; eraser.ItemTapped += Eraser_ItemTapped; radialMenu.Items.Add(eraser); UIView removeView = new UIView(); removeView.Frame = new CGRect(0, 0, 80, 80); UIImageView removeImage = new UIImageView(); removeImage.Image = UIImage.FromBundle("green.png"); removeImage.Frame = new CGRect(0, 0, 80, 80); removeView.Add(removeImage); UILabel removeLabel = new UILabel(); removeLabel.Frame = new CGRect(0, 5, 80, 80); removeLabel.Text = "Q"; removeLabel.TextAlignment = UITextAlignment.Center; removeLabel.Font = UIFont.FromName("ios", 30); removeLabel.TextColor = UIColor.White; removeView.Add(removeLabel); SfRadialMenuItem remove = new SfRadialMenuItem() { Height = 80, Width = 80, View = removeView, BackgroundColor = UIColor.Clear }; remove.ItemTapped += Remove_ItemTapped; radialMenu.Items.Add(remove); UIView paintView = new UIView(); paintView.Frame = new CGRect(0, 0, 80, 80); UIImageView paintImage = new UIImageView(); paintImage.Image = UIImage.FromBundle("green.png"); paintImage.Frame = new CGRect(0, 0, 80, 80); paintView.Add(paintImage); UILabel paintLabel = new UILabel(); paintLabel.Frame = new CGRect(0, 5, 80, 80); paintLabel.Text = "G"; paintLabel.TextAlignment = UITextAlignment.Center; paintLabel.Font = UIFont.FromName("ios", 30); paintLabel.TextColor = UIColor.White; paintView.Add(paintLabel); SfRadialMenuItem paint = new SfRadialMenuItem() { Height = 80, Width = 80, View = paintView, BackgroundColor = UIColor.Clear }; paint.ItemTapped += Paint_ItemTapped; radialMenu.Items.Add(paint); UIView paintBoxView = new UIView(); paintBoxView.Frame = new CGRect(0, 0, 80, 80); UIImageView paintBoxImage = new UIImageView(); paintBoxImage.Image = UIImage.FromBundle("green.png"); paintBoxImage.Frame = new CGRect(0, 0, 80, 80); paintBoxView.Add(paintBoxImage); UILabel paintBoxLabel = new UILabel(); paintBoxLabel.Frame = new CGRect(0, 5, 80, 80); paintBoxLabel.Text = "V"; paintBoxLabel.TextAlignment = UITextAlignment.Center; paintBoxLabel.Font = UIFont.FromName("ios", 30); paintBoxLabel.TextColor = UIColor.White; paintBoxView.Add(paintBoxLabel); SfRadialMenuItem paintBox = new SfRadialMenuItem() { Height = 80, Width = 80, View = paintBoxView, BackgroundColor = UIColor.Clear }; paintBox.ItemTapped += PaintBox_ItemTapped; radialMenu.Items.Add(paintBox); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { //radialMenu.RimRadius = 250; radialMenu.CenterButtonRadius = 50; centerLabel.Font = UIFont.FromName("ios", 40); pen.IconFont = UIFont.FromName("ios", 40); pen.Height = 100; pen.Width = 100; brush.IconFont = UIFont.FromName("ios", 40); brush.Height = 100; brush.Width = 100; eraser.IconFont = UIFont.FromName("ios", 40); eraser.Height = 100; eraser.Width = 100; remove.Height = 100; remove.Width = 100; remove.IconFont = UIFont.FromName("ios", 40); paintBox.Height = 100; paintBox.Width = 100; paintBox.IconFont = UIFont.FromName("ios", 40); paint.Height = 100; paint.Width = 100; paint.IconFont = UIFont.FromName("ios", 40); } drawingTool = new CustomDrawing(); drawingTool.PenColor = tempColor; drawingTool.Tapped += DrawingTool_Tapped; this.ClipsToBounds = true; this.Add(drawingTool); this.Add(startUpLabel); this.Add(colorPaletteView); this.Add(radialMenu); } void Pen_ItemTapped(object sender, EventArgs e) { isEraserSelected = false; drawingTool.LineWidth = 1; drawingTool.PenColor = tempColor; radialMenu.Close(); } void Brush_ItemTapped(object sender, EventArgs e) { isEraserSelected = false; drawingTool.LineWidth = 10; drawingTool.PenColor = tempColor; radialMenu.Close(); } void Remove_ItemTapped(object sender, EventArgs e) { isEraserSelected = false; drawingTool.Clear(); drawingTool.BackgroundColor = UIColor.White; radialMenu.Close(); } void Paint_ItemTapped(object sender, EventArgs e) { isEraserSelected = false; drawingTool.LineWidth = 60; drawingTool.PenColor = tempColor; radialMenu.Close(); } void PaintBox_ItemTapped(object sender, EventArgs e) { isEraserSelected = false; drawingTool.BackgroundColor = tempColor; radialMenu.Close(); } void Eraser_ItemTapped(object sender, EventArgs e) { isEraserSelected = true; drawingTool.LineWidth = 30; drawingTool.PenColor = UIColor.White; radialMenu.Close(); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { radialMenu.Position = new CGPoint(Frame.Width / 2, Frame.Height); drawingTool.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); startUpLabel.Frame = new CGRect(0, Frame.Height / 2 - 15, Frame.Width, 30); colorPaletteView.Frame = new CGRect(0, 0, Frame.Width, 40); } else { radialMenu.Position = new CGPoint(Frame.Width / 2, Frame.Height); drawingTool.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); startUpLabel.Frame = new CGRect(0, Frame.Height / 2 - 15, Frame.Width, 30); colorPaletteView.Frame = new CGRect(0, 0, Frame.Width, 40); } } base.LayoutSubviews(); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/StackedHeaderRow/StackedHeaderRow.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "StackedHeaderRow.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Xaml; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A sampleView that contains the StackedHeader sample. /// </summary> public partial class StackedHeaderRow : SampleView { #region Constructor /// <summary> /// Initializes a new instance of the StackedHeaderRow class. /// </summary> public StackedHeaderRow() { this.InitializeComponent(); } #endregion } }<file_sep>/Forms/ProgressBar/ProgressBar/Samples/Circular/CircularCustomContent.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfProgressBar { using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.ProgressBar; using Xamarin.Forms; public partial class CircularCustomContent : SampleView { public CircularCustomContent() { InitializeComponent(); this.CustomContentCircularProgressBar.AnimationDuration = 0; this.VideoPlayerProgressBar.AnimationDuration = 2000; this.SetCustomContentProgress(); } public void Dispose(bool disposing) { CustomContentCircularProgressBar?.Dispose(disposing); VideoPlayerProgressBar?.Dispose(disposing); } public override void OnDisappearing() { this.Dispose(true); } private async void SetCustomContentProgress() { double progress = 0; while (progress < 75) { this.CustomContentCircularProgressBar.Progress = progress += 1; this.CustomContentProgressBarLabel.Text = progress + "%"; await Task.Delay(50); } } private void PlayButton_Clicked(object sender, System.EventArgs e) { this.VideoPlayerProgressBar.Progress = 100; this.PauseButton.IsVisible = true; this.PlayButton.IsVisible = false; } private void PauseButton_Clicked(object sender, System.EventArgs e) { this.VideoPlayerProgressBar.SetProgress( (double)this.VideoPlayerProgressBar.GetValue(SfCircularProgressBar.ActualProgressValueProperty), 0, Easing.Linear); this.PlayButton.IsVisible = true; this.PauseButton.IsVisible = false; } private void VideoPlayerProgressBar_ValueChanged(object sender, ProgressValueEventArgs e) { if (e.Progress.Equals(100)) { this.VideoPlayerProgressBar.SetProgress(0, 0, Easing.Linear); } if (e.Progress.Equals(0)) { this.VideoPlayerProgressBar.Progress = 100; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/PDFViewer/Helpers/TextMarkupAnnotationHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Reflection; using CoreGraphics; using Syncfusion.SfPdfViewer.iOS; using UIKit; namespace SampleBrowser { public class TextMarkupAnnotationHelper { CustomToolbar m_parent; InkAnnotationHelper m_inkannot; AnnotationHelper m_annotHelper; internal const float DefaultToolbarHeight = 50f; private CustomToolbar Parent { get { return m_parent; } set { m_parent = value; } } private InkAnnotationHelper InkAnnot { get { return m_inkannot; } set { m_inkannot = value; } } private AnnotationHelper AnnotHelper { get { return m_annotHelper; } set { m_annotHelper = value; } } public TextMarkupAnnotationHelper(CustomToolbar customtoolbar) { Parent = customtoolbar; } public TextMarkupAnnotationHelper(InkAnnotationHelper inkannottoolbar, CustomToolbar customtoolbar) { InkAnnot = inkannottoolbar; Parent = customtoolbar; } public TextMarkupAnnotationHelper(AnnotationHelper annottoolbar, CustomToolbar customtoolbar) { AnnotHelper = annottoolbar; Parent = customtoolbar; } internal void AnnotationColor_TouchUpInside(object sender, EventArgs e) { if (Parent.annotation != null) { if (Parent.annotation is TextMarkupAnnotation) { ((TextMarkupAnnotation)Parent.annotation).Settings.Color = (sender as UIButton).BackgroundColor; Parent.colorButton.BackgroundColor = (sender as UIButton).BackgroundColor; } else if (Parent.annotation is InkAnnotation) { ((InkAnnotation)Parent.annotation).Settings.Color = (sender as UIButton).BackgroundColor; Parent.inkColorButton.BackgroundColor = (sender as UIButton).BackgroundColor; Parent.opacitybutton.SetTitleColor((sender as UIButton).BackgroundColor, UIControlState.Normal); Parent.inkThicknessButton.SetTitleColor((sender as UIButton).BackgroundColor, UIControlState.Normal); } } else { if (Parent.pdfViewerControl.AnnotationMode == AnnotationMode.Highlight) { Parent.pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color = (sender as UIButton).BackgroundColor; Parent.colorButton.BackgroundColor = (sender as UIButton).BackgroundColor; } else if (Parent.pdfViewerControl.AnnotationMode == AnnotationMode.Strikethrough) { Parent.pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color = (sender as UIButton).BackgroundColor; Parent.colorButton.BackgroundColor = (sender as UIButton).BackgroundColor; } else if (Parent.pdfViewerControl.AnnotationMode == AnnotationMode.Underline) { Parent.pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color = (sender as UIButton).BackgroundColor; Parent.colorButton.BackgroundColor = (sender as UIButton).BackgroundColor; } else if (Parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { Parent.pdfViewerControl.AnnotationSettings.Ink.Color = (sender as UIButton).BackgroundColor; Parent.inkColorButton.BackgroundColor = (sender as UIButton).BackgroundColor; Parent.opacitybutton.SetTitleColor((sender as UIButton).BackgroundColor, UIControlState.Normal); Parent.inkThicknessButton.SetTitleColor((sender as UIButton).BackgroundColor, UIControlState.Normal); } } Parent.isColorSelected = false; Parent.colorToolbar.RemoveFromSuperview(); Parent.opacityPanel.RemoveFromSuperview(); } internal void HighlightAnnotationButton_TouchUpInside(object sender, EventArgs e) { Parent.pdfViewerControl.AnnotationMode = AnnotationMode.Highlight; Parent.textAnnotationToolbar.RemoveFromSuperview(); Parent.isAnnotationToolbarVisible = true; Parent.deleteButton.RemoveFromSuperview(); Parent.highlightToolbar = CreateSeparateAnnotationToolbar(Parent.highlightToolbar, Parent.highlightEnable, "\ue710", false, Parent.pdfViewerControl.AnnotationSettings.TextMarkup.Highlight.Color); Parent.Add(Parent.highlightToolbar); } internal void UnderlineAnnotationButton_TouchUpInside(object sender, EventArgs e) { Parent.pdfViewerControl.AnnotationMode = AnnotationMode.Underline; Parent.textAnnotationToolbar.RemoveFromSuperview(); Parent.isAnnotationToolbarVisible = true; Parent.deleteButton.RemoveFromSuperview(); Parent.underlineToolbar = CreateSeparateAnnotationToolbar(Parent.underlineToolbar, Parent.underlineEnable, "\ue70c", false, Parent.pdfViewerControl.AnnotationSettings.TextMarkup.Underline.Color); Parent.Add(Parent.underlineToolbar); } internal void StrikeOutAnnotationButton_TouchUpInside(object sender, EventArgs e) { Parent.pdfViewerControl.AnnotationMode = AnnotationMode.Strikethrough; Parent.textAnnotationToolbar.RemoveFromSuperview(); Parent.isAnnotationToolbarVisible = true; Parent.deleteButton.RemoveFromSuperview(); Parent.strikeOutToolbar = CreateSeparateAnnotationToolbar(Parent.strikeOutToolbar, Parent.strikeEnable, "\ue71e", false, Parent.pdfViewerControl.AnnotationSettings.TextMarkup.Strikethrough.Color); Parent.Add(Parent.strikeOutToolbar); } internal void TextMarkupAnnotationButton_TouchUpInside(object sender, EventArgs e) { Parent.annotationFrame = Parent.Frame; Parent.annotationFrame.Height = DefaultToolbarHeight; Parent.annotationFrame.Y = Parent.parentView.Frame.Height - Parent.annotationFrame.Height + 4; Parent.textAnnotationToolbar.Frame = Parent.annotationFrame; Parent.textAnnotationToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); Parent.toolbarBackbutton.Frame = new CGRect(15, 7, 35, 35); Parent.toolbarBackbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.toolbarBackbutton.TouchUpInside += Parent.ToolbarBackbutton_TouchUpInside; Parent.toolbarBackbutton.Font = Parent.highFont; Parent.toolbarBackbutton.SetTitle("\ue708", UIControlState.Normal); Parent.toolbarBackbutton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); Parent.textAnnotationToolbar.Add(Parent.toolbarBackbutton); Parent.highlightAnnotationButton.Frame = new CGRect(Parent.parentView.Frame.Width / 2 - 100, 7, 35, 35); Parent.highlightAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.highlightAnnotationButton.TouchUpInside += HighlightAnnotationButton_TouchUpInside; Parent.highlightAnnotationButton.Font = Parent.highFont; Parent.highlightAnnotationButton.SetTitle("\ue710", UIControlState.Normal); Parent.highlightAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); Parent.textAnnotationToolbar.Add(Parent.highlightAnnotationButton); Parent.underlineAnnotationButton.Frame = new CGRect(Parent.parentView.Frame.Width / 2, 7, 35, 35); Parent.underlineAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.underlineAnnotationButton.TouchUpInside += UnderlineAnnotationButton_TouchUpInside; ; Parent.underlineAnnotationButton.Font = Parent.highFont; Parent.underlineAnnotationButton.SetTitle("\ue70c", UIControlState.Normal); Parent.underlineAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); Parent.textAnnotationToolbar.Add(Parent.underlineAnnotationButton); Parent.strikeOutAnnotationButton.Frame = new CGRect(Parent.parentView.Frame.Width / 2 + 100, 7, 35, 35); Parent.strikeOutAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.strikeOutAnnotationButton.TouchUpInside += StrikeOutAnnotationButton_TouchUpInside; ; Parent.strikeOutAnnotationButton.Font = Parent.highFont; Parent.strikeOutAnnotationButton.SetTitle("\ue71e", UIControlState.Normal); Parent.strikeOutAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); Parent.textAnnotationToolbar.Add(Parent.strikeOutAnnotationButton); Parent.textAnnotationToolbar = Parent.UpdateToolbarBorder(Parent.textAnnotationToolbar, Parent.annotationFrame); Parent.Add(Parent.textAnnotationToolbar); } internal void TextToolbarBackButton_TouchUpInside(object sender, EventArgs e) { Parent.pdfViewerControl.AnnotationMode = AnnotationMode.None; Parent.annotHelper.RemoveAllToolbars(false); Parent.Add(Parent.textAnnotationToolbar); Parent.isAnnotationToolbarVisible = true; Parent.textToolbarBackButton.RemoveFromSuperview(); } internal void PdfViewerControl_TextMarkupSelected(object sender, TextMarkupSelectedEventArgs args) { Parent.annotation = sender as IAnnotation; if (args.AnnotationType == TextMarkupAnnotationType.Highlight) { Parent.highlightToolbar = CreateSeparateAnnotationToolbar(Parent.highlightToolbar, Parent.highlightEnable, "\ue710", true, (Parent.annotation as TextMarkupAnnotation).Settings.Color); Parent.Add(Parent.highlightToolbar); } else if (args.AnnotationType == TextMarkupAnnotationType.Underline) { Parent.underlineToolbar = CreateSeparateAnnotationToolbar(Parent.underlineToolbar, Parent.underlineEnable, "\ue70c", true, (Parent.annotation as TextMarkupAnnotation).Settings.Color); Parent.Add(Parent.underlineToolbar); } else { Parent.strikeOutToolbar = CreateSeparateAnnotationToolbar(Parent.strikeOutToolbar, Parent.strikeEnable, "\ue71e", true, (Parent.annotation as TextMarkupAnnotation).Settings.Color); Parent.Add(Parent.strikeOutToolbar); } Parent.toolbarBackbutton.RemoveFromSuperview(); Parent.textAnnotationToolbar.RemoveFromSuperview(); Parent.colorToolbar.RemoveFromSuperview(); Parent.isAnnotationToolbarVisible = true; } internal void PdfViewerControl_TextMarkupDeselected(object sender, TextMarkupDeselectedEventArgs args) { if (args.AnnotationType == TextMarkupAnnotationType.Highlight) Parent.highlightToolbar.RemoveFromSuperview(); else if (args.AnnotationType == TextMarkupAnnotationType.Underline) Parent.underlineToolbar.RemoveFromSuperview(); else Parent.strikeOutToolbar.RemoveFromSuperview(); Parent.colorToolbar.RemoveFromSuperview(); Parent.textAnnotationToolbar.RemoveFromSuperview(); Parent.isAnnotationToolbarVisible = false; Parent.annotation = null; } internal UIView CreateSeparateAnnotationToolbar(UIView separateToolbar, UIButton enableLabel, string imageName, bool isSelected, UIColor colorButtonColor) { Parent.isOpacityNeeded = false; Parent.separateAnnotationFrame = Parent.Frame; Parent.separateAnnotationFrame.Height = DefaultToolbarHeight; Parent.separateAnnotationFrame.Y = Parent.parentView.Frame.Height - Parent.separateAnnotationFrame.Height + 4; separateToolbar.Frame = Parent.separateAnnotationFrame; separateToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); enableLabel.Frame = new CGRect(45, 7, 35, 35); enableLabel.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; enableLabel.Font = Parent.highFont; enableLabel.SetTitle(imageName, UIControlState.Normal); enableLabel.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); separateToolbar.Add(enableLabel); Parent.IsSelected = isSelected; if (!isSelected) { Parent.textToolbarBackButton.Frame = new CGRect(Parent.parentView.Frame.Width - 55, 7, 35, 35); Parent.textToolbarBackButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.textToolbarBackButton.TouchUpInside += TextToolbarBackButton_TouchUpInside; ; ; Parent.textToolbarBackButton.Font = Parent.highFont; Parent.textToolbarBackButton.SetTitle("\ue715", UIControlState.Normal); Parent.textToolbarBackButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); separateToolbar.Add(Parent.textToolbarBackButton); Parent.colorButton.Frame = new CGRect(Parent.parentView.Frame.Width - 130, 7, 35, 35); } else { Parent.deleteButton.Frame = new CGRect(Parent.parentView.Frame.Width - 100, 7, 35, 35); Parent.deleteButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.deleteButton.TouchUpInside += DeleteButton_TouchUpInside; ; Parent.deleteButton.Font = Parent.highFont; Parent.deleteButton.SetTitle("\ue714", UIControlState.Normal); Parent.deleteButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); separateToolbar.Add(Parent.deleteButton); Parent.colorButton.Frame = new CGRect(Parent.parentView.Frame.Width - 55, 7, 35, 35); } Parent.colorButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.colorButton.BackgroundColor = colorButtonColor; separateToolbar.Add(Parent.colorButton); separateToolbar = Parent.UpdateToolbarBorder(separateToolbar, Parent.separateAnnotationFrame); return separateToolbar; } internal void DeleteButton_TouchUpInside(object sender, EventArgs e) { Parent.pdfViewerControl.RemoveAnnotation(Parent.annotation); Parent.annotHelper.RemoveAllToolbars(false); } internal void ColorButton_TouchUpInside(object sender, EventArgs e) { Parent.isThicknessTouched = false; Parent.thicknessToolbar.RemoveFromSuperview(); if (!Parent.isColorSelected) { Parent.isColorSelected = true; Parent.colorFrame = Parent.Frame; Parent.colorFrame.Height = DefaultToolbarHeight; Parent.colorFrame.Y = Parent.parentView.Frame.Height - (DefaultToolbarHeight + Parent.colorFrame.Height - 4); Parent.colorToolbar.Frame = Parent.colorFrame; Parent.colorToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); Parent.redButton.Frame = new CGRect(Parent.parentView.Frame.Width - 50, 7, 30, 30); Parent.redButton.BackgroundColor = UIColor.Red; Parent.redButton.TouchUpInside += AnnotationColor_TouchUpInside; Parent.colorToolbar.AddSubview(Parent.redButton); Parent.blueButton.Frame = new CGRect(Parent.parentView.Frame.Width - 100, 7, 30, 30); Parent.blueButton.BackgroundColor = UIColor.Blue; Parent.blueButton.TouchUpInside += AnnotationColor_TouchUpInside; Parent.colorToolbar.AddSubview(Parent.blueButton); Parent.greenButton.Frame = new CGRect(Parent.parentView.Frame.Width - 150, 7, 30, 30); Parent.greenButton.BackgroundColor = UIColor.Green; Parent.greenButton.TouchUpInside += AnnotationColor_TouchUpInside; Parent.colorToolbar.AddSubview(Parent.greenButton); Parent.grayButton.Frame = new CGRect(Parent.parentView.Frame.Width - 200, 7, 30, 30); Parent.grayButton.BackgroundColor = UIColor.Gray; Parent.grayButton.TouchUpInside += AnnotationColor_TouchUpInside; Parent.colorToolbar.AddSubview(Parent.grayButton); Parent.blackButton.Frame = new CGRect(Parent.parentView.Frame.Width - 250, 7, 30, 30); Parent.blackButton.BackgroundColor = UIColor.Black; Parent.blackButton.TouchUpInside += AnnotationColor_TouchUpInside; Parent.colorToolbar.AddSubview(Parent.blackButton); Parent.yellowButton.Frame = new CGRect(Parent.parentView.Frame.Width - 300, 7, 30, 30); Parent.yellowButton.BackgroundColor = UIColor.Yellow; Parent.yellowButton.TouchUpInside += AnnotationColor_TouchUpInside; Parent.colorToolbar.AddSubview(Parent.yellowButton); Parent.whiteButton.Frame = new CGRect(Parent.parentView.Frame.Width - 350, 7, 30, 30); Parent.whiteButton.BackgroundColor = UIColor.White; Parent.whiteButton.TouchUpInside += AnnotationColor_TouchUpInside; Parent.colorToolbar.AddSubview(Parent.whiteButton); if (Parent.isOpacityNeeded) { Parent.redButton.Frame = new CGRect(Parent.parentView.Frame.Width - 90, 7, 30, 30); Parent.blueButton.Frame = new CGRect(Parent.parentView.Frame.Width - 130, 7, 30, 30); Parent.greenButton.Frame = new CGRect(Parent.parentView.Frame.Width - 170, 7, 30, 30); Parent.grayButton.Frame = new CGRect(Parent.parentView.Frame.Width - 220, 7, 30, 30); Parent.blackButton.Frame = new CGRect(Parent.parentView.Frame.Width - 260, 7, 30, 30); Parent.yellowButton.Frame = new CGRect(Parent.parentView.Frame.Width - 310, 7, 30, 30); Parent.whiteButton.Frame = new CGRect(Parent.parentView.Frame.Width - 350, 7, 30, 30); if (Parent.annotation is InkAnnotation || Parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { Parent.opacitybutton.Frame = new CGRect(Parent.parentView.Frame.Width - 50, 7, 35, 35); Parent.opacitybutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.opacitybutton.Font = Parent.highFont; Parent.opacitybutton.SetTitle("\ue71a", UIControlState.Normal); if (Parent.annotation != null) Parent.opacitybutton.SetTitleColor((Parent.annotation as InkAnnotation).Settings.Color, UIControlState.Normal); else Parent.opacitybutton.SetTitleColor(Parent.pdfViewerControl.AnnotationSettings.Ink.Color, UIControlState.Normal); Parent.colorToolbar.AddSubview(Parent.opacitybutton); } } else { Parent.opacitybutton.RemoveFromSuperview(); } Parent.colorToolbar = Parent.UpdateToolbarBorder(Parent.colorToolbar, Parent.colorFrame); Parent.opacityPanel.RemoveFromSuperview(); Parent.isOpacitySelected = false; Parent.Add(Parent.colorToolbar); } else { Parent.opacitybutton.RemoveFromSuperview(); Parent.colorToolbar.RemoveFromSuperview(); Parent.opacityPanel.RemoveFromSuperview(); Parent.isColorSelected = false; Parent.isOpacitySelected = false; } } } }<file_sep>/Forms/ListView/ListView/Samples/Paging/Helper/Behaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms.DataPager; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class SfListViewPagingBehavior : Behavior<SampleView> { #region Fields private Syncfusion.ListView.XForms.SfListView listView; private PagingViewModel PagingViewModel; private SfDataPager dataPager; #endregion #region Methods protected override void OnAttachedTo(SampleView bindable) { listView = bindable.FindByName<Syncfusion.ListView.XForms.SfListView>("listView"); dataPager = bindable.FindByName<SfDataPager>("dataPager"); PagingViewModel = new PagingViewModel(); listView.BindingContext = PagingViewModel; dataPager.Source = PagingViewModel.pagingProducts; dataPager.OnDemandLoading += DataPager_OnDemandLoading; base.OnAttachedTo(bindable); } private void DataPager_OnDemandLoading(object sender, OnDemandLoadingEventArgs e) { var source = PagingViewModel.pagingProducts.Skip(e.StartIndex).Take(e.PageSize); listView.ItemsSource = source.ToList<PagingProduct>().ToList(); } protected override void OnDetachingFrom(SampleView bindable) { listView = null; PagingViewModel = null; dataPager = null; base.OnDetachingFrom(bindable); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/DocIO/BookmarkNavigation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public partial class BookmarkNavigation : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to insert, retrieve, replace and delete the contents of a specified bookmark using BookmarkNavigator functionality of DocIO."; text1.SetPadding(5, 5, 5, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button viewButton = new Button(con); viewButton.Text = "View Template"; viewButton.Click += OnButtonClicked1; linear.AddView(viewButton); Button button1 = new Button (con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked1(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Bookmark_Template.docx"); MemoryStream stream = new MemoryStream(); inputStream.CopyTo(stream); stream.Position = 0; inputStream.Dispose(); //Set file content type string contentType = null; string fileName = null; //Save the document as docx fileName = "Bookmark_Template.docx"; contentType = "application/msword"; if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save(fileName, contentType, stream, m_context); } } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly (); // Creating a new document. WordDocument document = new WordDocument(); //Adds section with one empty paragraph to the Word document document.EnsureMinimal(); //sets the page margins document.LastSection.PageSetup.Margins.All = 72f; //Appends bookmark to the paragraph document.LastParagraph.AppendBookmarkStart("NorthwindDatabase"); document.LastParagraph.AppendText("Northwind database with relational data"); document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase"); // Open an existing template document with single section. WordDocument nwdInformation = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Bookmark_Template.docx"); // Open an existing template document. nwdInformation.Open(inputStream, FormatType.Doc); inputStream.Dispose(); // Open an existing template document with multiple section. WordDocument templateDocument = new WordDocument(); inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.BkmkDocumentPart_Template.docx"); // Open an existing template document. templateDocument.Open(inputStream, FormatType.Doc); inputStream.Dispose(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the template document. BookmarksNavigator bk = new BookmarksNavigator(templateDocument); // Move to the NorthWind bookmark in template document bk.MoveToBookmark("NorthWind"); //Gets the bookmark content as WordDocumentPart WordDocumentPart documentPart = bk.GetContent(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the Northwind information document. bk = new BookmarksNavigator(nwdInformation); // Move to the information bookmark bk.MoveToBookmark("Information"); // Get the content of information bookmark. TextBodyPart bodyPart = bk.GetBookmarkContent(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the destination document. bk = new BookmarksNavigator(document); // Move to the NorthWind database in the destination document bk.MoveToBookmark("NorthwindDatabase"); //Replace the bookmark content using word document parts bk.ReplaceContent(documentPart); // Move to the Northwind_Information in the destination document bk.MoveToBookmark("Northwind_Information"); // Replacing content of Northwind_Information bookmark. bk.ReplaceBookmarkContent(bodyPart); #region Bookmark selection for table // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the Northwind information document. bk = new BookmarksNavigator(nwdInformation); bk.MoveToBookmark("SuppliersTable"); //Sets the column index where the bookmark starts within the table bk.CurrentBookmark.FirstColumn = 1; //Sets the column index where the bookmark ends within the table bk.CurrentBookmark.LastColumn = 5; // Get the content of suppliers table bookmark. bodyPart = bk.GetBookmarkContent(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the destination document. bk = new BookmarksNavigator(document); bk.MoveToBookmark("Table"); bk.ReplaceBookmarkContent(bodyPart); #endregion // Move to the text bookmark bk.MoveToBookmark("Text"); //Deletes the bookmark content bk.DeleteBookmarkContent(true); // Inserting text inside the bookmark. This will preserve the source formatting bk.InsertText("Northwind Database contains the following table:"); #region tableinsertion WTable tbl = new WTable(document); tbl.TableFormat.Borders.BorderType = BorderStyle.None; tbl.TableFormat.IsAutoResized = true; tbl.ResetCells(8, 2); IWParagraph paragraph; tbl.Rows[0].IsHeader = true; paragraph = tbl[0, 0].AddParagraph(); paragraph.AppendText("Suppliers"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[0, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[1, 0].AddParagraph(); paragraph.AppendText("Customers"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[1, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[2, 0].AddParagraph(); paragraph.AppendText("Employees"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[2, 1].AddParagraph(); paragraph.AppendText("3"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[3, 0].AddParagraph(); paragraph.AppendText("Products"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[3, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[4, 0].AddParagraph(); paragraph.AppendText("Inventory"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[4, 1].AddParagraph(); paragraph.AppendText("2"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[5, 0].AddParagraph(); paragraph.AppendText("Shippers"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[5, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[6, 0].AddParagraph(); paragraph.AppendText("PO Transactions"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[6, 1].AddParagraph(); paragraph.AppendText("3"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[7, 0].AddParagraph(); paragraph.AppendText("Sales Transactions"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[7, 1].AddParagraph(); paragraph.AppendText("7"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; bk.InsertTable(tbl); #endregion bk.MoveToBookmark("Image"); bk.DeleteBookmarkContent(true); // Inserting image to the bookmark. IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture; inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Northwind.png"); pic.LoadImage(inputStream); inputStream.Dispose(); pic.WidthScale = 50f; // It reduce the image size because it don't fit pic.HeightScale = 75f; // in document page. #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("BookmarkNavigation.docx", "application/msword", stream, m_context); } #endregion } } } <file_sep>/Forms/TreeView/TreeView/Samples/NodeWithImage/Model/FileManager.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public class Folder : INotifyPropertyChanged { #region Fields private string fileName; private string imageIcon; private ObservableCollection<File> files; #endregion #region Constructor public Folder() { } #endregion #region Properties public ObservableCollection<File> Files { get { return files; } set { files = value; RaisedOnPropertyChanged("SubFiles"); } } public string FileName { get { return fileName; } set { fileName = value; RaisedOnPropertyChanged("FileName"); } } public string ImageIcon { get { return imageIcon; } set { imageIcon = value; RaisedOnPropertyChanged("ImageIcon"); } } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } [Preserve(AllMembers = true)] public class File : INotifyPropertyChanged { #region Fields private string fileName; private ImageSource imageIcon; private ObservableCollection<SubFile> subFiles; #endregion #region Constructor public File() { } #endregion #region Properties public ObservableCollection<SubFile> SubFiles { get { return subFiles; } set { subFiles = value; RaisedOnPropertyChanged("SubFiles"); } } public string FileName { get { return fileName; } set { fileName = value; RaisedOnPropertyChanged("FileName"); } } public ImageSource ImageIcon { get { return imageIcon; } set { imageIcon = value; RaisedOnPropertyChanged("ImageIcon"); } } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } [Preserve(AllMembers = true)] public class SubFile : INotifyPropertyChanged { #region Fields private string fileName; private ImageSource imageIcon; #endregion #region Constructor public SubFile() { } #endregion #region Properties public string FileName { get { return fileName; } set { fileName = value; RaisedOnPropertyChanged("FolderName"); } } public ImageSource ImageIcon { get { return imageIcon; } set { imageIcon = value; RaisedOnPropertyChanged("ImageIcon"); } } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } }<file_sep>/iOS/SampleBrowser/Samples/PopupLayout/Popup Customizations/CustomView/TheaterTile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Syncfusion.SfDataGrid; using Syncfusion.iOS.PopupLayout; using UIKit; namespace SampleBrowser { public class TheaterTile : GridCell { TheaterLayout theaterLayout; UIImageView infoImage; UILabel theaterTitle; UILabel theaterLocation; UILabel timing1; UILabel timing2; UILabel overlayTags; SfPopupLayout infopopup; SfPopupLayout termsAndConditionsPopup; object rowData; SfDataGrid dataGrid; UILabel message; public TheaterTile() { theaterLayout = new TheaterLayout(); infoImage = new UIImageView(); infoImage.Alpha = 0.54f; infoImage.UserInteractionEnabled = true; var tapGesture = new UITapGestureRecognizer(DisplayInfo) { NumberOfTapsRequired = 1 }; infoImage.AddGestureRecognizer(tapGesture); theaterTitle = new UILabel(); theaterTitle.Font = UIFont.PreferredCaption1; theaterLocation = new UILabel(); theaterLocation.Font = UIFont.PreferredFootnote; theaterLocation.TextColor = UIColor.LightGray; timing1 = new UILabel(); timing1.TextColor = UIColor.FromRGB(0, 124, 238); timing1.Font = UIFont.PreferredCaption2; timing1.TextAlignment = UITextAlignment.Center; timing1.Layer.BorderColor = UIColor.FromRGBA(0, 124, 238, 26).CGColor; timing1.Layer.BorderWidth = 0.5f; timing1.UserInteractionEnabled = true; var timingTapGesture = new UITapGestureRecognizer(TimingTapped) { NumberOfTapsRequired = 1 }; timing1.AddGestureRecognizer(timingTapGesture); timing2 = new UILabel(); timing2.TextColor = UIColor.FromRGB(0, 124, 238); timing2.Font = UIFont.PreferredCaption2; timing2.TextAlignment = UITextAlignment.Center; timing2.Layer.BorderColor = UIColor.FromRGBA(0, 124, 238, 26).CGColor; timing2.UserInteractionEnabled = true; var timingTapGesture2 = new UITapGestureRecognizer(TimingTapped) { NumberOfTapsRequired = 1 }; timing2.AddGestureRecognizer(timingTapGesture2); timing2.Layer.BorderWidth = 0.5f; theaterLayout.AddSubview(theaterTitle); theaterLayout.AddSubview(theaterLocation); theaterLayout.AddSubview(timing1); theaterLayout.AddSubview(timing2); theaterLayout.AddSubview(infoImage); this.AddSubview(theaterLayout); this.CanRendererUnload = false; } private void TimingTapped() { DisplayTermsAndCondtionsPopup(); } private void DisplayTermsAndCondtionsPopup() { termsAndConditionsPopup = new SfPopupLayout(); termsAndConditionsPopup.IsOpen = false; termsAndConditionsPopup.PopupView.HeaderTitle = "Terms & Conditions"; termsAndConditionsPopup.PopupView.BackgroundColor = UIColor.White; termsAndConditionsPopup.PopupView.ShowHeader = true; termsAndConditionsPopup.PopupView.PopupStyle.HeaderBackgroundColor = UIColor.White; UIView view = new UIView(); message = new UILabel(); view.BackgroundColor = UIColor.White; message.TextColor = UIColor.Gray; message.Font = UIFont.SystemFontOfSize(14); message.AutoresizingMask = UIViewAutoresizing.All; termsAndConditionsPopup.PopupView.ShowCloseButton = false; view.AddSubview(message); termsAndConditionsPopup.PopupView.PopupStyle.BorderColor = UIColor.LightGray; termsAndConditionsPopup.PopupView.AppearanceMode = AppearanceMode.TwoButton; termsAndConditionsPopup.PopupView.HeaderHeight = 40; termsAndConditionsPopup.PopupView.FooterHeight = 40; termsAndConditionsPopup.PopupView.ShowFooter = true; message.Text = "1. Children below the age of 18 cannot be admitted for movies certified A. \n2. Please carry proof of age for movies certified A. \n3. Drinking and alcohol is strictly prohibited inside the premises. \n4. Please purchase tickets for children above age of 3."; message.Lines = 10; message.TextAlignment = UITextAlignment.Left; message.LineBreakMode = UILineBreakMode.WordWrap; termsAndConditionsPopup.PopupView.AcceptButtonText = "Accept"; termsAndConditionsPopup.PopupView.DeclineButtonText = "Decline"; termsAndConditionsPopup.StaysOpen = true; termsAndConditionsPopup.PopupView.ContentView = view; termsAndConditionsPopup.PopupView.PopupStyle.AcceptButtonTextColor = UIColor.FromRGB(0, 124, 238); termsAndConditionsPopup.PopupView.PopupStyle.DeclineButtonTextColor = UIColor.FromRGB(0, 124, 238); termsAndConditionsPopup.PopupView.PopupStyle.AcceptButtonBackgroundColor = UIColor.White; termsAndConditionsPopup.PopupView.PopupStyle.DeclineButtonBackgroundColor = UIColor.White; termsAndConditionsPopup.PopupView.AcceptButtonClicked += PopupView_AcceptButtonClicked; termsAndConditionsPopup.PopupView.AppearanceMode = AppearanceMode.TwoButton; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { termsAndConditionsPopup.PopupView.PopupStyle.HeaderFontSize = 14; message.Font = UIFont.PreferredCaption1; termsAndConditionsPopup.PopupView.Frame = new CGRect(-1, -1, this.DataColumn.Renderer.DataGrid.Frame.Width - 20, this.DataColumn.Renderer.DataGrid.Frame.Height / 1.75); } else { termsAndConditionsPopup.PopupView.PopupStyle.HeaderFontSize = 20; message.Font = UIFont.PreferredBody; termsAndConditionsPopup.PopupView.Frame = new CGRect(-1, -1, (this.DataColumn.Renderer.DataGrid.Frame.Width / 10) *6, this.DataColumn.Renderer.DataGrid.Frame.Height / 3); } termsAndConditionsPopup.IsOpen = true; message.Frame = new CGRect(10, 0, termsAndConditionsPopup.PopupView.Frame.Width - 20, view.Frame.Height); } private void PopupView_AcceptButtonClicked(object sender, System.ComponentModel.CancelEventArgs e) { if (termsAndConditionsPopup.PopupView.AcceptButtonText == "Accept") { termsAndConditionsPopup.PopupView.ContentView = CreateSeatSelectionPage(); termsAndConditionsPopup.StaysOpen = true; e.Cancel = true; } else if(termsAndConditionsPopup.PopupView.AcceptButtonText == "Proceed") { overlayTags = new UILabel(); overlayTags.Hidden = false; overlayTags.Text = "Tickets booked successfully"; overlayTags.Layer.CornerRadius = 20f; overlayTags.TextColor = UIColor.White; overlayTags.TextAlignment = UITextAlignment.Center; overlayTags.ClipsToBounds = true; overlayTags.Font = UIFont.SystemFontOfSize(14); overlayTags.BackgroundColor = UIColor.FromRGB(101.0f / 255.0f, 101.0f / 255.0f, 101.0f / 255.0f); overlayTags.Layer.ZPosition = 1000; dataGrid.Superview.AddSubview(overlayTags); overlayTags.Frame = new CoreGraphics.CGRect((dataGrid.Superview.Frame.Right / 2) - 100, dataGrid.Superview.Frame.Bottom - 20, 200, 40); UIView.Animate(0.5, 0, UIViewAnimationOptions.CurveLinear, () => { overlayTags.Alpha = 1.0f; }, () => { UIView.Animate(3.0, () => { overlayTags.Alpha = 0.0f; }); } ); } } private UIView CreateSeatSelectionPage() { UIView seatSelectionMainLayout = new UIView(); seatSelectionMainLayout.BackgroundColor = UIColor.White; SeatSelectionLayout numberOfSeatsLayout = new SeatSelectionLayout(termsAndConditionsPopup); numberOfSeatsLayout.Frame = new CGRect(5, 5, termsAndConditionsPopup.PopupView.Frame.Width - 10, 42); numberOfSeatsLayout.AddSubview(CreateSeatSelectionLayout("1")); numberOfSeatsLayout.AddSubview(CreateSeatSelectionLayout("2")); numberOfSeatsLayout.AddSubview(CreateSeatSelectionLayout("3")); numberOfSeatsLayout.AddSubview(CreateSeatSelectionLayout("4")); numberOfSeatsLayout.AddSubview(CreateSeatSelectionLayout("5")); numberOfSeatsLayout.AddSubview(CreateSeatSelectionLayout("6")); numberOfSeatsLayout.AddSubview(CreateSeatSelectionLayout("7")); numberOfSeatsLayout.AddSubview(CreateSeatSelectionLayout("8")); UILabel title2 = new UILabel(); title2.Text = "Select your seat class"; title2.TextColor = UIColor.Black; title2.Font = UIFont.SystemFontOfSize(14); title2.Frame = new CGRect(15, 92, termsAndConditionsPopup.PopupView.Frame.Width, 16); UILabel clas = new UILabel(); clas.Text = "Silver"; clas.TextColor = UIColor.Gray; clas.Font = UIFont.PreferredCaption1; clas.Frame = new CGRect(15, 133, 60, 20); UILabel cost = new UILabel(); cost.Text = "$ 19.69"; cost.TextColor = UIColor.Black; cost.Font = UIFont.PreferredCaption1; cost.Frame = new CGRect(termsAndConditionsPopup.PopupView.Frame.Width /2 - 60, 133, 60, 20); UILabel avail = new UILabel(); avail.Text = "Available"; avail.TextColor = UIColor.Green; avail.Font = UIFont.PreferredCaption1; avail.Frame = new CGRect(termsAndConditionsPopup.PopupView.Frame.Width - 80, 133, 60, 20); UILabel clas2 = new UILabel(); clas2.Text = "Premier"; clas2.TextColor = UIColor.Gray; clas2.Font = UIFont.PreferredCaption1; clas2.Frame = new CGRect(15, 153, 60, 20); UILabel cost2 = new UILabel(); cost2.Text = "$ 23.65"; cost2.TextColor = UIColor.Black; cost2.Font = UIFont.PreferredCaption1; cost2.Frame = new CGRect(termsAndConditionsPopup.PopupView.Frame.Width / 2 - 60, 153, 60, 20); UILabel avail2 = new UILabel(); avail2.Text = "Unavailable"; avail2.TextColor = UIColor.Red; avail2.Font = UIFont.PreferredCaption1; avail2.Frame = new CGRect(termsAndConditionsPopup.PopupView.Frame.Width - 80, 153, 80, 20); seatSelectionMainLayout.AddSubview(numberOfSeatsLayout); seatSelectionMainLayout.AddSubview(title2); seatSelectionMainLayout.AddSubview(clas); seatSelectionMainLayout.AddSubview(cost); seatSelectionMainLayout.AddSubview(avail); seatSelectionMainLayout.AddSubview(clas2); seatSelectionMainLayout.AddSubview(cost2); seatSelectionMainLayout.AddSubview(avail2); termsAndConditionsPopup.PopupView.HeaderTitle = "How many seats ?"; termsAndConditionsPopup.PopupView.PopupStyle.HeaderTextColor = UIColor.Black; termsAndConditionsPopup.PopupView.PopupStyle.HeaderBackgroundColor = UIColor.White; termsAndConditionsPopup.PopupView.PopupStyle.BorderThickness = 1; termsAndConditionsPopup.PopupView.ShowFooter = true; termsAndConditionsPopup.PopupView.ShowCloseButton = true; termsAndConditionsPopup.PopupView.AppearanceMode = AppearanceMode.OneButton; termsAndConditionsPopup.PopupView.FooterHeight = 40; termsAndConditionsPopup.PopupView.AcceptButtonText = "Proceed"; termsAndConditionsPopup.PopupView.PopupStyle.AcceptButtonBackgroundColor = UIColor.FromRGB(0, 124, 238); termsAndConditionsPopup.PopupView.PopupStyle.AcceptButtonTextColor = UIColor.White; return seatSelectionMainLayout; } private UILabel CreateSeatSelectionLayout(string count) { var seatCountLabel = new UILabel(); if (count == "2") { seatCountLabel.BackgroundColor = UIColor.FromRGB(0, 124, 238); seatCountLabel.TextColor = UIColor.White; } else { seatCountLabel.BackgroundColor = UIColor.White; seatCountLabel.TextColor = UIColor.Black; } seatCountLabel.Text = count; seatCountLabel.Font = UIFont.BoldSystemFontOfSize(12); seatCountLabel.TextAlignment = UITextAlignment.Center; seatCountLabel.UserInteractionEnabled = true; var tapGesture = new UITapGestureRecognizer(SeatSelected) { NumberOfTapsRequired = 1 }; seatCountLabel.AddGestureRecognizer(tapGesture); return seatCountLabel; } void SeatSelected(UITapGestureRecognizer tasture) { foreach (var v in tasture.View.Superview.Subviews) { (v as UILabel).TextColor = UIColor.Black; v.BackgroundColor = UIColor.White; } tasture.View.BackgroundColor = UIColor.FromRGB(0, 124, 238); (tasture.View as UILabel).TextColor = UIColor.White; } private void DisplayInfo() { DisplayInfoPopup(); } private void DisplayInfoPopup() { infopopup = new SfPopupLayout(); infopopup.IsOpen = false; infopopup.PopupView.AppearanceMode = AppearanceMode.OneButton; infopopup.PopupView.HeaderTitle = (rowData as TicketBookingInfo).TheaterName; infopopup.PopupView.BackgroundColor = UIColor.White; infopopup.PopupView.ShowCloseButton = true; infopopup.PopupView.PopupStyle.HeaderTextColor = UIColor.Black; infopopup.PopupView.PopupStyle.HeaderTextAlignment = UIKit.UITextAlignment.Center; infopopup.PopupView.PopupStyle.HeaderBackgroundColor = UIColor.White; infopopup.PopupView.ShowFooter = false; infopopup.PopupView.FooterHeight = 35; infopopup.PopupView.HeaderHeight = 30; infopopup.StaysOpen = false; infopopup.PopupView.PopupStyle.HeaderFontSize = 16; infopopup.PopupView.ShowHeader = true; infopopup.PopupView.Frame = new CGRect(-1, -1, this.DataColumn.Renderer.DataGrid.Frame.Width - 40, this.DataColumn.Renderer.DataGrid.Frame.Height / 2); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { infopopup.PopupView.PopupStyle.HeaderFontSize = 14; infopopup.PopupView.Frame = new CGRect(-1, -1, this.DataColumn.Renderer.DataGrid.Frame.Width - 20, this.DataColumn.Renderer.DataGrid.Frame.Height / 1.75); } else { infopopup.PopupView.PopupStyle.HeaderFontSize = 20; infopopup.PopupView.Frame = new CGRect(-1, -1, (this.DataColumn.Renderer.DataGrid.Frame.Width / 10) * 6, this.DataColumn.Renderer.DataGrid.Frame.Height / 3.5); } infopopup.PopupView.ContentView = CreateInfoPopupContent(); infopopup.IsOpen = true; } private UIView CreateInfoPopupContent() { UIView mainview = new UIView(); UILabel location = new UILabel(); location.Lines = 10; location.Font = UIFont.PreferredCaption1; location.TextColor = UIColor.FromRGB(0,124, 238); location.LineBreakMode = UILineBreakMode.WordWrap; location.Text = (rowData as TicketBookingInfo).TheaterLocation + "421 E DRACHMAN TUCSON AZ 85705 - 7598 USA"; UILabel facilitiesLabel = new UILabel(); facilitiesLabel.Text = "Available Facilities"; facilitiesLabel.TextAlignment = UITextAlignment.Center; UIImageView mtick = new UIImageView(); mtick.Image = UIImage.FromFile("Images/Popup_MTicket.png"); UIImageView park = new UIImageView(); park.Image = UIImage.FromFile("Images/Popup_Parking.png"); UIImageView food = new UIImageView(); food.Image = UIImage.FromFile("Images/Popup_FoodCourt.png"); UILabel ticketLabel = new UILabel(); ticketLabel.Text = "M-Ticket"; ticketLabel.TextColor = UIColor.Black; ticketLabel.Font = UIFont.PreferredCaption2; UILabel parkingLabel = new UILabel(); parkingLabel.Text = "Parking"; parkingLabel.TextColor = UIColor.Black; parkingLabel.Font = UIFont.PreferredCaption2; UILabel foodLabel = new UILabel(); foodLabel.Text = "Food Court"; foodLabel.TextColor = UIColor.Black; foodLabel.Font = UIFont.PreferredCaption2; mainview.AddSubview(location); mainview.AddSubview(facilitiesLabel); mainview.AddSubview(mtick); mainview.AddSubview(park); mainview.AddSubview(food); mainview.AddSubview(ticketLabel); mainview.AddSubview(parkingLabel); mainview.AddSubview(foodLabel); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { location.Frame = new CGRect(Bounds.Left + 16, Bounds.Top + 20, 240, 40); facilitiesLabel.Frame = new CGRect(0, location.Frame.Bottom + 12, infopopup.PopupView.Frame.Width, 40); mtick.Frame = new CGRect(Bounds.Left + 55, facilitiesLabel.Frame.Bottom + 10, 20, 20); park.Frame = new CGRect(mtick.Frame.Right + 65, facilitiesLabel.Frame.Bottom + 10, 20, 20); food.Frame = new CGRect(park.Frame.Right + 55, facilitiesLabel.Frame.Bottom + 10, 20, 20); ticketLabel.Frame = new CGRect(Bounds.Left + 45, mtick.Frame.Bottom + 10, 50, 20); parkingLabel.Frame = new CGRect(ticketLabel.Frame.Right + 35, mtick.Frame.Bottom + 10, 50, 20); foodLabel.Frame = new CGRect(parkingLabel.Frame.Right + 15, mtick.Frame.Bottom + 10, 60, 20); } else { location.Frame = new CGRect(Bounds.Left + 16, Bounds.Top + 20, infopopup.PopupView.Frame.Width, 60); facilitiesLabel.Frame = new CGRect(0, location.Frame.Bottom + 12, infopopup.PopupView.Frame.Width, 40); mtick.Frame = new CGRect(Bounds.Width / 6, facilitiesLabel.Frame.Bottom + 10, 20, 20); park.Frame = new CGRect(mtick.Frame.Right + 75, facilitiesLabel.Frame.Bottom + 10, 20, 20); food.Frame = new CGRect(park.Frame.Right + 75, facilitiesLabel.Frame.Bottom + 10, 20, 20); ticketLabel.Frame = new CGRect(Bounds.Width / 7, mtick.Frame.Bottom + 10, 50, 20); parkingLabel.Frame = new CGRect(ticketLabel.Frame.Right + 55, mtick.Frame.Bottom + 10, 50, 20); foodLabel.Frame = new CGRect(parkingLabel.Frame.Right + 40, mtick.Frame.Bottom + 10, 60, 20); } return mainview; } protected override void UnLoad() { this.RemoveFromSuperview(); } public override void LayoutSubviews() { base.LayoutSubviews(); dataGrid = this.DataColumn.Renderer.DataGrid; rowData = (this.DataColumn.RowData); infoImage.Image = (rowData as TicketBookingInfo).InfoImage; theaterTitle.Text = (rowData as TicketBookingInfo).TheaterName; theaterLocation.Text = (rowData as TicketBookingInfo).TheaterLocation; timing1.Text = (rowData as TicketBookingInfo).Timing1; timing2.Text = (rowData as TicketBookingInfo).Timing2; if (timing2.Text == null) timing2.Hidden = true; this.theaterLayout.Frame = new CGRect(Bounds.Left, Bounds.Top, Bounds.Width, Bounds.Height); } } public class TheaterLayout : UIView { public TheaterLayout() { } public override void LayoutSubviews() { this.Subviews[0].Frame = new CGRect(Bounds.Left + 16, Bounds.Top + 16, Bounds.Width - 60, 25); this.Subviews[1].Frame = new CGRect(Bounds.Left + 16, this.Subviews[0].Frame.Bottom + 6, Bounds.Width - 60 ,25); this.Subviews[2].Frame = new CGRect(Bounds.Left + 16, this.Subviews[1].Frame.Bottom + 6, 80,32); this.Subviews[3].Frame = new CGRect(this.Subviews[2].Frame.Right + 10, this.Subviews[1].Frame.Bottom + 6, 80,32); this.Subviews[4].Frame = new CGRect(this.Subviews[1].Frame.Right, Bounds.Height / 2 - 12 , 24, 24); } } public class SeatSelectionLayout : UIView { SfPopupLayout popup; public SeatSelectionLayout(SfPopupLayout pop) { popup = pop; } public override void LayoutSubviews() { nfloat temp = 0; for (int i = 0; i < this.Subviews.Length; i++) { this.Subviews[i].Frame = new CGRect(temp, this.Frame.Top, (popup.PopupView.Frame.Width - 10) / 8, 42); temp = temp + ((popup.PopupView.Frame.Width - 10) / 8); } } } } <file_sep>/Forms/Presentation/Presentation/Samples/GettingStarted/GettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using SampleBrowser.Core; namespace SampleBrowser.Presentation { public partial class GettingStarted : SampleView { public GettingStarted() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.FontSize = 13.5; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.HelloWorld.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.HelloWorld.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); #region Slide1 //Get the first slide from Presentation ISlide slide1 = presentation.Slides[0]; //Get the shape from slide and set bounds IShape titleShape = slide1.Shapes[0] as IShape; titleShape.Left = 0.33 * 72; titleShape.Top = 0.58 * 72; titleShape.Width = 12.5 * 72; titleShape.Height = 1.75 * 72; //Set a content to the text box and apply text formatting ITextBody textFrame1 = (slide1.Shapes[0] as IShape).TextBody; IParagraphs paragraphs1 = textFrame1.Paragraphs; IParagraph paragraph = paragraphs1.Add(); paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart1 = paragraph.AddTextPart(); textPart1.Text = "Essential Presentation"; textPart1.Font.CapsType = TextCapsType.All; textPart1.Font.FontName = "Arial"; textPart1.Font.Bold = true; textPart1.Font.FontSize = 40; IShape subtitle = slide1.Shapes[1] as IShape; subtitle.Left = 0.5 * 72; subtitle.Top = 3 * 72; subtitle.Width = 11.8 * 72; subtitle.Height = 1.7 * 72; ITextBody textFrame2 = (slide1.Shapes[1] as IShape).TextBody; textFrame2.VerticalAlignment = VerticalAlignmentType.Top; IParagraphs paragraphs2 = textFrame2.Paragraphs; IParagraph para = paragraphs2.Add(); para.HorizontalAlignment = HorizontalAlignmentType.Left; ITextPart textPart2 = para.AddTextPart(); textPart2.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus.Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet."; textPart2.Font.FontName = "Arial"; textPart2.Font.FontSize = 21; para = paragraphs2.Add(); para.HorizontalAlignment = HorizontalAlignmentType.Left; textPart2 = para.AddTextPart(); textPart2.Text = "Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet. Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula.For more details please "; textPart2.Font.FontName = "Arial"; textPart2.Font.FontSize = 21; //Add hyperlink to the paragraph ITextPart textPart3 = para.AddTextPart(); textPart3.Font.FontName = "Arial"; textPart3.Text = "click here"; textPart3.SetHyperlink("https://msdn.microsoft.com/en-in/library/mt299001.aspx"); #endregion //Save the Presentation to stream MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("GettingStartedSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("GettingStartedSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/OnBoardHelps/SwipingBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SwipingBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using Xamarin.Forms; /// <summary> /// Swiping Behavior class performs swiping animation. /// </summary> public class SwipingBehavior : Behavior<Image> { /// <summary> /// Holds the swiping illustration image. /// </summary> private Image swipeIllustrationImage; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="image">Image which is attached.</param> protected override void OnAttachedTo(Image image) { base.OnAttachedTo(image); this.swipeIllustrationImage = image; this.AnimateSwipeIllustration(); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="image">Image which is attached.</param> protected override void OnDetachingFrom(Image image) { base.OnDetachingFrom(image); this.swipeIllustrationImage = null; } /// <summary> /// used to animate swiping illustration. /// </summary> private async void AnimateSwipeIllustration() { await this.swipeIllustrationImage.TranslateTo(90, 0, 1800); await this.swipeIllustrationImage.TranslateTo(0, 0, 0); this.AnimateSwipeIllustration(); } } }<file_sep>/Forms/TextInputLayout/TextInputLayout/Samples/SignUpView/SignUpView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.Core.XForms; using System.Collections.Generic; using Xamarin.Forms; using Syncfusion.XForms.TextInputLayout; namespace SampleBrowser.SfTextInputLayout { /// <summary> /// Sign up view. /// </summary> public partial class SignUpView : SampleView { /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.SfTextInputLayout.SignUpView"/> class. /// </summary> public SignUpView() { InitializeComponent(); picker.SelectedIndex = 0; picker2.SelectedIndexChanged += (sender, e) => { picker3.IsVisible = (picker2.SelectedIndex == 0); fontAttributeLabel.IsVisible = (picker2.SelectedIndex == 0); }; if (Device.RuntimePlatform == Device.WPF) { stateLayout.IsVisible = false; birthdayLayoutGrid.IsVisible = false; fontAttributeGrid.IsVisible = false; fontSizeGrid.IsVisible = false; fontFamilyGrid.IsVisible = false; submitButton.HeightRequest = 35; resetButton.HeightRequest = 35; } } public override void OnDisappearing() { labelGesture.Tapped -= GestureRecognizer_Tapped; } /// <summary> /// Raised when the Label is clicked. /// </summary> /// <param name="sender">The sender</param> /// <param name="e">The eventArgs</param> private void GestureRecognizer_Tapped(object sender, System.EventArgs e) { if(Device.RuntimePlatform != Device.UWP) date_Picker.Focus(); } /// <summary> /// Paised when the picker selected item changed. /// </summary> /// <param name="sender">The sender</param> /// <param name="e">The eventArgs</param> private void GenderPicker_SelectedIndexChanged(object sender, System.EventArgs e) { Picker pickerInstance = sender as Picker; signUpViewModel.Gender = (string)pickerInstance.ItemsSource[pickerInstance.SelectedIndex]; } } }<file_sep>/Android/SampleBrowser/Samples/XlsIO/PerformancePage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syncfusion.XlsIO; using COLOR = Syncfusion.Drawing; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using System.Data; using System.IO; using Com.Syncfusion.Numerictextbox; using Syncfusion.Android.MaskedEdit; namespace SampleBrowser { class PerformancePage: SamplePage { private CheckBox chkImport; private SfMaskedEdit textBox1; private SfMaskedEdit textBox2; private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates the performance of Syncfusion XlsIO library to create larger Excel files."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text3 = new TextView(con); text3.TextSize = 15; text3.Text = "Enter the no. of rows"; text3.SetTextColor(Color.ParseColor("#262626")); linear.AddView(text3); textBox1 = new SfMaskedEdit(con); textBox1.Value = 5000; linear.AddView(textBox1); TextView space3 = new TextView(con); space3.TextSize = 10; linear.AddView(space3); TextView text4 = new TextView(con); text4.TextSize = 15; text4.TextAlignment = TextAlignment.Center; text4.Text = "Enter the no. of columns"; linear.AddView(text4); textBox2 = new SfMaskedEdit(con); textBox2.Value = 50; linear.AddView(textBox2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); chkImport = new CheckBox(con); chkImport.Text = "Import on Save"; linear.AddView(chkImport); TextView text = new TextView(con); text.TextSize = 13; text.Text = "Import on Save option directly serialize data while saving the workbook."; linear.AddView(text); TextView space2 = new TextView(con); space1.TextSize = 10; linear.AddView(space2); m_context = con; Button button1 = new Button(con); button1.Text = "Generate Excel"; button1.Click += Button1_Click; linear.AddView(button1); return linear; } private void Button1_Click(object sender, EventArgs e) { int rowCount = Convert.ToInt32(textBox1.Value); int colCount = Convert.ToInt32(textBox2.Value); //Step 1 : Instantiate the spreadsheet creation engine. ExcelEngine excelEngine = new ExcelEngine(); //Step 2 : Instantiate the excel application object. IApplication application = excelEngine.Excel; IWorkbook workbook; workbook = application.Workbooks.Create(1); IWorksheet sheet = workbook.Worksheets[0]; if (chkImport.Checked) { workbook.Version = ExcelVersion.Excel2013; DataTable dataTable = new DataTable(); for (int column = 1; column <= colCount; column++) { dataTable.Columns.Add("Column: " + column.ToString(), typeof(int)); } //Adding data into data table for (int row = 1; row < rowCount; row++) { dataTable.Rows.Add(); for (int column = 1; column <= colCount; column++) { dataTable.Rows[row - 1][column - 1] = row * column; } } sheet.ImportDataTable(dataTable, 1, 1, true, true); } else { IMigrantRange migrantRange = sheet.MigrantRange; for (int column = 1; column <= colCount; column++) { migrantRange.ResetRowColumn(1, column); migrantRange.SetValue("Column: " + column.ToString()); } //Writing Data using normal interface for (int row = 2; row <= rowCount; row++) { //double columnSum = 0.0; for (int column = 1; column <= colCount; column++) { //Writing number migrantRange.ResetRowColumn(row, column); migrantRange.SetValue(row * column); } } } workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("CreateSheet.xlsx", "application/msexcel", stream, m_context); } } } }<file_sep>/Android/SampleBrowser/Samples/XlsIO/WorksheetToImagePage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using Syncfusion.XlsIORenderer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using System.Reflection; namespace SampleBrowser { public partial class WorksheetToImagePage : SamplePage { private Context m_context; RadioGroup radioGroup; RadioButton pngButton; RadioButton jpegButton; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample illustrates the conversion of a simple Excel document to an image."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; LinearLayout radioLinearLayout = new LinearLayout(con); radioLinearLayout.Orientation = Orientation.Horizontal; TextView imageType = new TextView(con); imageType.Text = "Image Format : "; imageType.TextSize = 19; radioLinearLayout.AddView(imageType); radioGroup = new RadioGroup(con); radioGroup.TextAlignment = TextAlignment.Center; radioGroup.Orientation = Orientation.Horizontal; pngButton = new RadioButton(con); pngButton.Text = "PNG"; radioGroup.AddView(pngButton); jpegButton = new RadioButton(con); jpegButton.Text = "JPEG"; radioGroup.AddView(jpegButton); radioGroup.Check(1); radioLinearLayout.AddView(radioGroup); linear.AddView(radioLinearLayout); pngButton.Checked = true; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button templateButton = new Button(con); templateButton.Text = "Input Template"; templateButton.Click += OnButtonClicked; linear.AddView(templateButton); Button convertButton = new Button (con); convertButton.Text = "Convert"; convertButton.Click += OnConvertButtonClicked; linear.AddView (convertButton); return linear; } private void OnConvertButtonClicked(object sender, EventArgs e) { //Instantiate excel engine ExcelEngine excelEngine = new ExcelEngine(); //Excel application IApplication application = excelEngine.Excel; //Get assembly manifest resource Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.ExpenseReport.xlsx"); //Open Workbook IWorkbook workbook = application.Workbooks.Open(fileStream); //Get Worksheet IWorksheet worksheet = workbook.Worksheets[0]; //Initialize XlsIORenderer application.XlsIORenderer = new XlsIORenderer(); //Set file content type string contentType = "image/png"; ExportImageOptions imageOptions = new ExportImageOptions(); imageOptions.ImageFormat = ExportImageFormat.Png; //Create a new memory stream MemoryStream stream = new MemoryStream(); if(pngButton.Checked) { worksheet.ConvertToImage(worksheet.UsedRange, imageOptions, stream); } else { imageOptions.ImageFormat = ExportImageFormat.Jpeg; worksheet.ConvertToImage(worksheet.UsedRange, imageOptions, stream); contentType = "image/jpeg"; } workbook.Close(); excelEngine.Dispose(); //Save and view the generated file. SaveAndView(stream, contentType, true); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream filestream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.ExpenseReport.xlsx"); MemoryStream stream = new MemoryStream(); filestream.CopyTo(stream); SaveAndView(stream, "application/msexcel", false); } void SaveAndView(MemoryStream stream, string contentType, bool image) { if (stream != null) { stream.Position = 0; SaveAndroid androidSave = new SaveAndroid(); if (image) androidSave.Save("Image." + contentType.Split('/').ToArray()[1], contentType, stream, m_context); else androidSave.Save("Template.xlsx", contentType, stream, m_context); } } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/CustomerDetails.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CustomerDetails.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties /// </summary> public class CustomerDetails { #region private variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string customerID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string firstname; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string lastname; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string gender; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string city; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string country; #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the value of CustomerID and notifies user when value gets changed /// </summary> public string CustomerID { get { return this.customerID; } set { this.customerID = value; this.RaisePropertyChanged("CustomerID"); } } /// <summary> /// Gets or sets the value of FirstName and notifies user when value gets changed /// </summary> public string FirstName { get { return this.firstname; } set { this.firstname = value; this.RaisePropertyChanged("FirstName"); } } /// <summary> /// Gets or sets the value of LastName and notifies user when value gets changed /// </summary> public string LastName { get { return this.lastname; } set { this.lastname = value; this.RaisePropertyChanged("LastName"); } } /// <summary> /// Gets or sets the value of Gender and notifies user when value gets changed /// </summary> public string Gender { get { return this.gender; } set { this.gender = value; this.RaisePropertyChanged("Gender"); } } /// <summary> /// Gets or sets the value of City and notifies user when value gets changed /// </summary> public string City { get { return this.city; } set { this.city = value; this.RaisePropertyChanged("City"); } } /// <summary> /// Gets or sets the value of Country and notifies user when value gets changed /// </summary> public string Country { get { return this.country; } set { this.country = value; this.RaisePropertyChanged("Country"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type of parameter name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/iOS/SampleBrowser/Resources/Samples/LinearGauge/Ranges.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif using Syncfusion.SfGauge.iOS; namespace SampleBrowser { public class Ranges : SampleView { SFLinearGauge linearGauge; SFLinearGauge linearGauge1; SFLinearGauge linearGauge2; static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; CGSize sz = this.Frame.Size; linearGauge.Frame = new CGRect(0, 0, sz.Width, sz.Height / 3); linearGauge1.Frame = new CGRect(0, sz.Height / 3, sz.Width, sz.Height / 3); linearGauge2.Frame = new CGRect(0, sz.Height / 3 * 2, sz.Width, sz.Height / 3); } base.LayoutSubviews(); } public Ranges() { this.BackgroundColor = UIColor.White; linearGauge = new SFLinearGauge(); linearGauge.BackgroundColor = UIColor.White; linearGauge.Header = new SFLinearLabel(); SFLinearScale scale = new SFLinearScale(); scale.Minimum = 0; scale.Maximum = 100; scale.Interval = 25; scale.LabelOffset = 10; scale.LabelColor = UIColor.FromRGB(66, 66, 66); scale.LabelFont = UIFont.FromName("Helvetica", 14f); scale.ShowTicks = false; scale.ScaleBarColor = UIColor.Clear; SFSymbolPointer pointer = new SFSymbolPointer(); pointer.SymbolPosition = SymbolPointerPosition.Far; pointer.Thickness = 12; pointer.Value = 35; pointer.Color = UIColor.Black; pointer.MarkerShape = MarkerShape.InvertedTriangle; scale.Pointers.Add(pointer); SFLinearRange range1 = new SFLinearRange(); range1.StartValue = 0; range1.EndValue = 25; range1.StartWidth = 20; range1.EndWidth = 20; range1.Color = UIColor.FromRGB(26, 35, 126); scale.Ranges.Add(range1); SFLinearRange range2 = new SFLinearRange(); range2.StartValue = 25; range2.EndValue = 50; range2.StartWidth = 20; range2.EndWidth = 20; range2.Color = UIColor.FromRGB(40, 53, 147); scale.Ranges.Add(range2); SFLinearRange range3 = new SFLinearRange(); range3.StartValue = 50; range3.EndValue = 75; range3.StartWidth = 20; range3.EndWidth = 20; range3.Color = UIColor.FromRGB(63, 81, 181); scale.Ranges.Add(range3); SFLinearRange range4 = new SFLinearRange(); range4.StartValue = 75; range4.EndValue = 100; range4.StartWidth = 20; range4.EndWidth = 20; range4.Color = UIColor.FromRGB(92, 107, 192); scale.Ranges.Add(range4); linearGauge.Scales.Add(scale); linearGauge1 = new SFLinearGauge(); linearGauge1.BackgroundColor = UIColor.White; linearGauge1.Header = new SFLinearLabel(); SFLinearScale scale1 = new SFLinearScale(); scale1.Minimum = 0; scale1.Maximum = 100; scale1.Interval = 25; scale1.LabelOffset = 20; scale1.LabelColor = UIColor.FromRGB(66, 66, 66); scale1.LabelFont = UIFont.FromName("Helvetica", 14f); scale1.ShowTicks = false; scale1.ScaleBarColor = UIColor.Clear; SFSymbolPointer pointer1 = new SFSymbolPointer(); pointer1.SymbolPosition = SymbolPointerPosition.Far; pointer1.Thickness = 12; pointer1.Value = 35; pointer1.Color = UIColor.Black; pointer1.MarkerShape = MarkerShape.InvertedTriangle; scale1.Pointers.Add(pointer1); SFLinearRange range5 = new SFLinearRange(); range5.StartValue = 0; range5.EndValue = 25; range5.StartWidth = 10; range5.EndWidth = 15; range5.Color = UIColor.FromRGB(109, 229, 0); scale1.Ranges.Add(range5); SFLinearRange range6 = new SFLinearRange(); range6.StartValue = 25; range6.EndValue = 50; range6.StartWidth = 15; range6.EndWidth = 20; range6.Color = UIColor.FromRGB(83, 173, 0); scale1.Ranges.Add(range6); SFLinearRange range7 = new SFLinearRange(); range7.StartValue = 50; range7.EndValue = 75; range7.StartWidth = 20; range7.EndWidth = 25; range7.Color = UIColor.FromRGB(0, 145, 72); scale1.Ranges.Add(range7); SFLinearRange range8 = new SFLinearRange(); range8.StartValue = 75; range8.EndValue = 100; range8.StartWidth = 25; range8.EndWidth = 30; range8.Color = UIColor.FromRGB(2, 102, 35); scale1.Ranges.Add(range8); linearGauge1.Scales.Add(scale1); linearGauge2 = new SFLinearGauge(); linearGauge2.BackgroundColor = UIColor.White; linearGauge2.Header = new SFLinearLabel(); SFLinearScale scale2 = new SFLinearScale(); scale2.Minimum = 0; scale2.Maximum = 100; scale2.Interval = 25; scale2.LabelOffset = 20; scale2.LabelColor = UIColor.FromRGB(66, 66, 66); scale2.LabelFont = UIFont.FromName("Helvetica", 14f); scale2.ShowTicks = false; scale2.ScaleBarColor = UIColor.Clear; SFSymbolPointer pointer2 = new SFSymbolPointer(); pointer2.SymbolPosition = SymbolPointerPosition.Far; pointer2.Thickness = 12; pointer2.Value = 35; pointer2.Color = UIColor.Black; pointer2.MarkerShape = MarkerShape.InvertedTriangle; scale2.Pointers.Add(pointer2); SFLinearRange range9 = new SFLinearRange(); range9.StartValue = 0; range9.EndValue = 100; range9.StartWidth = 20; range9.EndWidth = 20; GaugeGradientStop color3 = new GaugeGradientStop(); color3.Value = 0; color3.Color = UIColor.FromRGB(255, 249, 194); GaugeGradientStop color4 = new GaugeGradientStop(); color4.Value = 100; color4.Color = UIColor.FromRGB(253, 145, 215); range9.GradientStops.Add(color3); range9.GradientStops.Add(color4); scale2.Ranges.Add(range9); linearGauge2.Scales.Add(scale2); this.AddSubview(linearGauge); this.AddSubview(linearGauge1); this.AddSubview(linearGauge2); } } } <file_sep>/Forms/Chart/readme.md The chart control can plot more than 25 chart types, ranging from line charts to specialized financial charts. Its rich feature set includes functionalities like data binding, multiple axes, legends, animations, data labels, annotations, trackballs, tooltips, and zooming. The following samples are available for chart to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Line Chart](Chart/Samples/LineChart) | This sample demonstrates how to create a line chart and customize its appearance with built-in color palette. | | [Step Line Chart](Chart/Samples/StepLineChart)| This sample demonstrates how to create a step line chart and customize its appearance with built-in color palette. | | [Bar Chart](Chart/Samples/BarChart)| This sample demonstrates how to create a simple bar chart and customize its appearance with built-in color palette. | | [Area Chart](Chart/Samples/AreaChart) | This sample demonstrates how to create an area chart and customize its appearance with built-in color palette. | | [Spline Chart](Chart/Samples/SplineChart) | This sample demonstrates how to create a spline chart with data point markers and customize its appearance with built-in color palette. | | [Column Chart](Chart/Samples/ColumnChart) | This sample demonstrates how to create a column chart with data labels and customize its appearance with built-in color palette. | | [Step Area Chart](Chart/Samples/StepAreaChart)| This sample demonstrates how to create a step area chart and customize its appearance with built-in color palette. | | [Spline Area Chart](Chart/Samples/SplineAreaChart)| This sample demonstrates how to create a spline area chart and customize its appearance with built-in color palette. | | [Pie Chart](Chart/Samples/PieChart)| This sample demonstrates how to create a simple pie chart with data labels, configuration of [segments grouping] (https://help.syncfusion.com/xamarin/sfchart/charttypes#group-small-data-points-into-others), and [exploding segments on touch] (https://help.syncfusion.com/xamarin/sfchart/charttypes#exploding-a-pie-segment) features. | | [Semi Pie Chart](Chart/Samples/SemiPieChart)| This sample demonstrates how to configure the start and end angles in a pie chart to render data points using semi pie. | | [Doughnut Chart](Chart/Samples/DoughnutChart)| This sample demonstrates how to create a simple doughnut chart with data labels, configuration of [center view] (https://help.syncfusion.com/xamarin/sfchart/charttypes#add-view-to-the-center-of-doughnut-chart), and [exploding segments on touch] (https://help.syncfusion.com/xamarin/sfchart/charttypes#exploding-a-doughnut-segment) features. | | [Semi Doughnut Chart](Chart/Samples/SemiDoughnutChart)| This sample demonstrates how to configure the start and end angles in a doughnut chart to render data points using semi doughnut. | | [Pyramid Chart](Chart/Samples/PyramidChart)| This sample demonstrates how to configure a pyramid chart and customize its appearance with built-in color palette. | | [Funnel Chart](Chart/Samples/FunnelChart)| This sample demonstrates how to configure a funnel chart with data labels and customize its appearance with built-in color palette. | | [Bubble Chart](Chart/Samples/BubbleChart)| This sample demonstrates how to configure a bubble chart and customize its tooltip with data template to show all the required values from the underlying object. | | [Scatter Chart](Chart/Samples/ScatterChart)| This sample demonstrates how to configure a scatter chart with different shapes. | | [Range Column Chart](Chart/Samples/RangeColumnChart)| This sample demonstrates how to configure a range column chart and customize its appearance with built-in color palette. | | [Range Area Chart](Chart/Samples/RangeAreaChart)| This sample demonstrates how to configure a range area chart and customize its appearance with built-in color palette. | | [Spline Range Area](Chart/Samples/SplineRangeAreaChart)| This sample demonstrates how to configure a spline range area chart and customize its appearance with built-in color palette. | | [Candle Chart](Chart/Samples/CandleChart)| This sample demonstrates how to configure a candle chart. | | [OHLC Chart](Chart/Samples/OHLCChart)| This sample demonstrates how to configure an OHLC chart. | | [Polar Chart](Chart/Samples/PolarChart)| This sample demonstrates how to configure a polar chart and its start angle. | | [Radar Chart](Chart/Samples/RadarChart)| This sample demonstrates how to configure a radar chart and its start angle. | | [Stacked Column Chart](Chart/Samples/StackedColumnChart)| This sample demonstrates how to configure a stacked column chart and customize its appearance with built-in color palette. | | [100% Stacked Column Chart](Chart/Samples/StackedColumn100Chart)| This sample demonstrates how to configure a 100% stacked column chart and customize its appearance with built-in color palette. | | [Stacked Bar Chart](Chart/Samples/StackedBarChart)| This sample demonstrates how to configure a stacked bar chart and customize its appearance with built-in color palette. | | [100% Stacked Bar Chart](Chart/Samples/StackedBar100Chart)| This sample demonstrates how to configure a 100% stacked bar chart and customize its appearance with built-in color palette. | | [Stacked Area Chart](Chart/Samples/StackedAreaChart)| This sample demonstrates how to configure a stacked area chart and customize its appearance with built-in color palette. | | [100% Stacked Area Chart](Chart/Samples/StackedArea100Chart)| This sample demonstrates how to configure a 100% stacked area chart and customize its appearance with built-in color palette. | | [Category Axis](Chart/Samples/CategoryAxis)| This sample demonstrates how to configure the category axis and its label placement. Category axis is an indexed based axis that plots values based on its index in data source. | | [Numeric Axis](Chart/Samples/NumericAxis)| This sample demonstrates how to configure numerical axis and its minimum, maximum, and interval values. It is used to plot numerical data in a chart. | | [Logarithmic Axis](Chart/Samples/LogarithmicAxis)| This sample demonstrates how to configure logarithmic axis. It is used to plot the log value in a chart. | | [Date Time Axis](Chart/Samples/DateTimeAxis)| This sample demonstrates how to configure date-time axes and format labels to show the first label of a month with name and number, and consecutive labels with number. | | [Multiple Axes](Chart/Samples/MultipleAxes)| This sample demonstrates how to configure multiple axes in a single chart and position them on either side of a chart. | | [Axis Crossing](Chart/Samples/AxisCrossing)| This sample demonstrates how to position x-axis and y axis relative to each other. | | [Trackball](Chart/Samples/Trackball)| This sample demonstrates how to enable the trackball and customize its labels with data template. The trackball displays labels for the data points that are closer to the point where you touch and hold on the chart area. | | [Zooming And Panning](Chart/Samples/ZoomingAndPanning)| This sample demonstrates how to configure zooming and panning behaviors in a chart. | | [Tooltip](Chart/Samples/Tooltip)| This sample demonstrates how to configure a tooltip and customize its appearance with data template. | | [DataPoint Selection](Chart/Samples/DataPointSelection)| This sample demonstrates how to configure selection behavior in a chart and update other views in the same page based on the selection. | | [Legend template](Chart/Samples/Legend)| This sample demonstrates how to enable legends and customize legend items with data template. | | [Gradient Chart](Chart/Samples/GradientChart)| This sample demonstrates how to apply gradient to area series. | | [Annotations](Chart/Samples/Annotations)| This sample demonstrates how to configure different types of annotations in a chart. | | [Live Update](Chart/Samples/LiveUpdate)| This sample demonstrates how to add and remove data at run time. | | [StripLines](Chart/Samples/StripLines)| This sample demonstrates how to use strip lines to highlight different regions and set the labels for each region in a chart. | | [Vertical Chart](Chart/Samples/VerticalChart)| This sample demonstrates how to transpose the rendering of a chart. Rotate all the series types to plot data in a vertical direction and view the data from a different perspective. | | [DataMarker Customization](Chart/Samples/DataMarkerCustomization)| This sample demonstrates how to enable data markers and customize the labels with data template. | | [Auto Scrolling](Chart/Samples/AutoScrolling)| This sample demonstrates how to enable the auto scrolling feature in a chart. The auto scrolling feature is used to focus on a minimal set of data points by visualizing only a few items in the UI and viewing the remaining data points by scrolling. | | [Technical Indicator](Chart/Samples/TechnicalIndicator)| This sample demonstrates how to configure technical indicators. The available technical indicators are RSI, momentum, Bollinger bands, accumulation distribution, EMA, SMA, stochastic, ATR, MACD, and TMA. | <file_sep>/Forms/XlsIO/XlsIO/Samples/PerformancePage/PerformancePage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XlsIO; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.XlsIO { public partial class PerformancePage : SampleView { public PerformancePage() { InitializeComponent(); } private void BtnGenerate_Clicked(object sender, EventArgs e) { int rows = Convert.ToInt32(this.rowCount.Text); int columns = Convert.ToInt32(this.colCount.Text); //Step 1 : Instantiate the spreadsheet creation engine. ExcelEngine excelEngine = new ExcelEngine(); //Step 2 : Instantiate the excel application object. IApplication application = excelEngine.Excel; IWorkbook workbook; workbook = application.Workbooks.Create(1); workbook.Version = ExcelVersion.Excel2013; IWorksheet sheet = workbook.Worksheets[0]; if (this.Import.IsChecked.Value) { DataTable dataTable = new DataTable(); for (int column = 1; column <= columns; column++) { dataTable.Columns.Add("Column: " + column.ToString(), typeof(int)); } //Adding data into data table for (int row = 1; row < rows; row++) { dataTable.Rows.Add(); for (int column = 1; column <= columns; column++) { dataTable.Rows[row - 1][column - 1] = row * column; } } sheet.ImportDataTable(dataTable, 1, 1, true, true); } else { IMigrantRange migrantRange = sheet.MigrantRange; for (int column = 1; column <= Convert.ToInt32(this.colCount.Text); column++) { migrantRange.ResetRowColumn(1, column); migrantRange.SetValue("Column: " + column.ToString()); } //Writing Data using normal interface for (int row = 2; row <= rows; row++) { //double columnSum = 0.0; for (int column = 1; column <= columns; column++) { //Writing number migrantRange.ResetRowColumn(row, column); migrantRange.SetValue(row * column); } } } MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Sample.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("Sample.xlsx", "application/msexcel", stream); } } } }<file_sep>/Android/SampleBrowser/Samples/Carousel/Carousel_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Carousel; using Java.Util; using Android.Graphics; namespace SampleBrowser { public class Carousel_Mobile { /********************************* **Local Variable Inizialisation** *********************************/ LinearLayout.LayoutParams lineParams, labelParams, entryParams, adjustParams, lineParams2; LinearLayout propertylayout, offSetStack, scaleStack, rotateStack; EditText offSet, scaleOffset, RotateAngle; SfCarousel carousel; int offSetValue = 60, RotationAngleValue = 45, width; double scaleOffsetValue = 0.8; Spinner tickSpinner; ArrayAdapter<String> dataAdapter; ViewMode viewMode; Context context; public View GetSampleContent(Context context1) { context = context1; carousel = new SfCarousel(context); List<SfCarouselItem> tempCollection = new List<SfCarouselItem>(); for (int i = 1; i <= 7; i++) { SfCarouselItem carouselItem = new SfCarouselItem(context); carouselItem.ImageName = "images" + i; tempCollection.Add(carouselItem); } carousel.DataSource = tempCollection; carousel.SelectedIndex = 3; carousel.ScaleOffset = 0.8f; if (context.Resources.DisplayMetrics.Density > 1.5) { carousel.ItemHeight = Convert.ToInt32(250 * context.Resources.DisplayMetrics.Density); carousel.ItemWidth = Convert.ToInt32(180 * context.Resources.DisplayMetrics.Density); } carousel.LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); return carousel; } public View GetPropertyWindowLayout(Context context) { int dp = (int)context.Resources.DisplayMetrics.Density; width = (context.Resources.DisplayMetrics.WidthPixels) / 2; propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; offsetLayout(); ScaleOffsetLayout(); RotationAngleLayout(); VisualModeLayout(); return propertylayout; } private void offsetLayout() { lineParams = new LinearLayout.LayoutParams(width * 2, 5); lineParams.SetMargins(0, 10, 0, 0); //labelParams labelParams = new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.MatchParent); labelParams.SetMargins(0, 5, 0, 0); entryParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); adjustParams = new LinearLayout.LayoutParams(width / 3, ViewGroup.LayoutParams.WrapContent); entryParams.SetMargins(0, 5, 20, 0); propertylayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); propertylayout.SetBackgroundColor(Color.White); //offsetLabel TextView offsetLabel = new TextView(context); offsetLabel.Text = "Offset"; offsetLabel.TextSize = 20; offsetLabel.Gravity = GravityFlags.CenterVertical; offSetStack = new LinearLayout(context); TextView centerLabel1 = new TextView(context); //offSet offSet = new EditText(context); offSet.Text = "60"; offSet.InputType = Android.Text.InputTypes.ClassNumber; offSet.TextSize = 20; offSet.SetTextColor(Color.Black); offSetStack.AddView(offsetLabel, labelParams); offSetStack.AddView(centerLabel1, adjustParams); offSetStack.SetGravity(GravityFlags.Center); offSetStack.AddView(offSet, entryParams); offSetStack.Orientation = Orientation.Horizontal; propertylayout.AddView(offSetStack); //offSet TextChanged Listener offSet.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (offSet.Text.Length > 0) { int i = Convert.ToInt32(e.Text.ToString()); if (i >= 40 && i <= 100) offSetValue = i; else offSetValue = 60; } }; //lineParams lineParams2 = new LinearLayout.LayoutParams(width * 2, 5); lineParams2.SetMargins(0, 20, 0, 0); } private void ScaleOffsetLayout() { //scaleLabel TextView scaleLabel = new TextView(context); scaleLabel.Text = "Scale Offset"; scaleLabel.TextSize = 20; scaleLabel.Gravity = GravityFlags.CenterVertical; scaleStack = new LinearLayout(context); TextView centerLabel2 = new TextView(context); TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //scaleOffset scaleOffset = new EditText(context); scaleOffset.InputType = Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.NumberFlagSigned | Android.Text.InputTypes.ClassNumber; scaleOffset.TextSize = 20; scaleOffset.Text = "0.8"; scaleOffset.SetTextColor(Color.Black); scaleStack.AddView(scaleLabel, labelParams); scaleStack.AddView(centerLabel2, adjustParams); scaleStack.AddView(scaleOffset, entryParams); scaleStack.SetGravity(GravityFlags.Center); scaleStack.Orientation = Orientation.Horizontal; propertylayout.AddView(scaleStack); //scaleOffset TextChanged Listener scaleOffset.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (scaleOffset.Text.Length > 0) { float i = (float)Convert.ToDouble(e.Text.ToString()); if (i >= 0.5 && i <= 1) scaleOffsetValue = i; else scaleOffsetValue = 0.8; } }; } private void RotationAngleLayout() { //rotateLabel TextView rotateLabel = new TextView(context); rotateLabel.Text = "Rotation Angle"; rotateLabel.TextSize = 20; rotateLabel.Gravity = GravityFlags.CenterVertical; rotateStack = new LinearLayout(context); TextView centerLabel3 = new TextView(context); TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //RotateAngle RotateAngle = new EditText(context); RotateAngle.InputType = Android.Text.InputTypes.ClassNumber; RotateAngle.TextSize = 20; RotateAngle.Text = "45"; RotateAngle.SetTextColor(Color.Black); rotateStack.AddView(rotateLabel, labelParams); rotateStack.AddView(centerLabel3, adjustParams); rotateStack.AddView(RotateAngle, entryParams); rotateStack.SetGravity(GravityFlags.Center); rotateStack.Orientation = Orientation.Horizontal; propertylayout.AddView(rotateStack); //RotateAngle TextChanged Listener RotateAngle.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (RotateAngle.Text.Length > 0) { int i = Convert.ToInt32(e.Text.ToString()); if (i >= 0 && i <= 360) RotationAngleValue = i; else RotationAngleValue = 45; } }; propertylayout.SetPadding(5, 0, 5, 0); } private void VisualModeLayout() { LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width * 2, 5); layoutParams.SetMargins(0, 5, 0, 0); TextView adjLabe5 = new TextView(context); propertylayout.AddView(adjLabe5); //Visual Mode TextView placementLabel = new TextView(context); placementLabel.Text = "View Mode"; placementLabel.TextSize = 20; placementLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); placementLabel.SetTextColor(Color.Black); placementLabel.Gravity = GravityFlags.Left; TextView adjLabel2 = new TextView(context); adjLabel2.SetHeight(14); //tickSpinner tickSpinner = new Spinner(context,SpinnerMode.Dialog); tickSpinner.SetPadding(0, 0, 0, 0); propertylayout.AddView(placementLabel); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); //adjLabel TextView adjLabel3 = new TextView(context); adjLabel3.SetHeight(20); propertylayout.AddView(tickSpinner); TextView adjLabel4 = new TextView(context); propertylayout.AddView(adjLabel4); //positionList List<String> positionList = new List<String>(); positionList.Add("Default"); positionList.Add("Linear"); //dataAdapter dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, positionList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //tickSpinner tickSpinner.Adapter = dataAdapter; tickSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Default")) { viewMode = ViewMode.Default; } else if (selectedItem.Equals("Linear")) { viewMode = ViewMode.Linear; } }; } public void OnApplyChanges() { carousel.Offset = offSetValue; carousel.RotationAngle = RotationAngleValue; carousel.ScaleOffset = (float)scaleOffsetValue; carousel.ViewMode = viewMode; } } } <file_sep>/iOS/SampleBrowser/Samples/XlsIO/Extensions.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Linq; using Syncfusion.XlsIO; using System.Xml; using Foundation; namespace SampleBrowser { public static class TypeExtension { public static PropertyInfo[] GetProperties(this Type type) { IEnumerator<PropertyInfo> propertyEnum = type.GetTypeInfo().DeclaredProperties.GetEnumerator(); IList<PropertyInfo> listProperties = new List<PropertyInfo>(); while (propertyEnum.MoveNext()) { listProperties.Add(propertyEnum.Current); } return listProperties.ToArray<PropertyInfo>(); } public static PropertyInfo GetProperty(this Type type,string name) { IEnumerator<PropertyInfo> propertyEnum = type.GetTypeInfo().DeclaredProperties.GetEnumerator(); while (propertyEnum.MoveNext()) { if (propertyEnum.Current.Name == name) return propertyEnum.Current; } return null; } } public class XlsIOExtensions { /// <summary> /// Import XML file into XlsIO /// </summary> /// <param name="fileStream">XML file stream</param> /// <param name="sheet">Worksheet to import</param> /// <param name="row">Row to which import begin</param> /// <param name="col">Column to which import begin</param> /// <param name="header">Imports header if true</param> public void ImportXML(Stream fileStream, IWorksheet sheet, int row, int col, bool header) { XmlReader reader = XmlReader.Create(fileStream); IEnumerable<Customers> customers = GetData(reader); PropertyInfo[] propertyInfo = null; bool headerXML = true; int newCol = col; foreach (object obj in customers) { if (obj != null) { propertyInfo = obj.GetType().GetProperties(); if (header && headerXML) { foreach (var cell in propertyInfo) { sheet[row, newCol].Text = cell.Name; newCol++; } row++; headerXML = false; } newCol = col; foreach (var cell in propertyInfo) { Type currentRecordType = obj.GetType(); PropertyInfo property = currentRecordType.GetProperty(cell.Name); sheet[row, newCol].Value2 = property.GetValue(obj, null); newCol++; } headerXML = false; row++; } } } private IEnumerable<Customers> GetData(XmlReader reader ) { List<Customers> collection = new List<Customers>(); string customers = ""; string companyName = ""; string contactName = ""; string contactTitle = ""; string address = ""; string city = ""; string postalCode = ""; string country = ""; string phone = ""; string fax = ""; while (reader.Read ()) { if (reader.IsStartElement ()) { switch (reader.Name) { case "Customers": while (reader.Read ()) { if (reader.IsStartElement ()) { switch (reader.Name) { case "CustomerID": reader.Read (); customers = reader.Value; break; case "CompanyName": reader.Read (); companyName = reader.Value; break; case "ContactName": reader.Read (); contactName = reader.Value; break; case "ContactTitle": reader.Read (); contactTitle = reader.Value; break; case "Address": reader.Read (); address = reader.Value; break; case "City": reader.Read (); city = reader.Value; break; case "PostalCode": reader.Read (); postalCode = reader.Value; break; case "Country": reader.Read (); country = reader.Value; break; case "Phone": reader.Read (); phone = reader.Value; break; case "Fax": reader.Read (); fax = reader.Value; Customers temp = new Customers (customers, companyName, contactName, contactTitle, address, city, postalCode, country, phone, fax); collection.Add (temp); break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Customers") break; } break; } } } return collection.AsEnumerable(); } } [Preserve(AllMembers = true)] public class Customers { public Customers(string id, string company,string name, string title,string address,string city,string code,string country,string phone,string fax) { CustomerID = id; CompanyName = company; ContactName = name; ContactTitle = title; Address = address; City = city; PostalCode = code; Country = country; Phone = phone; Fax = fax; } public string CustomerID { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string Address { get; set; } public string City { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string Phone { get; set; } public string Fax { get; set; } } [Preserve(AllMembers = true)] public class CLRObject { public string SalesPerson { get; set; } public int SalesJanJune { get; set; } public int SalesJulyDec { get; set; } public int Change { get; set; } } }<file_sep>/iOS/SampleBrowser/Samples/ComboBox/readme.md The `SfComboBox` control is an editor component that allow users to type a text and choose an option from the list of predefined options. Also, it has editable and non-editable support to select. The following sample is available for combo box to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](ComboBox.cs)| It demonstrates the basic functionalities like filtering pattern, sensing diacritics in languages, editable options and control customization.| <file_sep>/Forms/XlsIO/XlsIO/Samples/DataTablePage/DataTablePage.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using System.Xml.Linq; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using SampleBrowser.Core; using Syncfusion.SfDataGrid; using Syncfusion.SfDataGrid.XForms; using Syncfusion.XlsIO; namespace SampleBrowser.XlsIO { /// <summary> /// This class used to import/export DataTable from/to an Excel worksheet. /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public partial class DataTablePage : SampleView { public DataTablePage() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP)) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInput.BackgroundColor = Color.Gray; this.btnImport.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; } if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.iOS) { this.dataGrid.DefaultColumnWidth = 120; } else { this.dataGrid.DefaultColumnWidth = 160; } this.dataGrid.ItemsSource = SetGridData(); } private object SetGridData() { List<CustomerObject> customerObjects = new List<CustomerObject>(); for (int i = 0; i < 20; i++) { customerObjects.Add(new CustomerObject()); } return customerObjects; } internal void OnInputClicked(object sender, EventArgs e) { Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = null; #if COMMONSB fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ExportSales.xlsx"); #else fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ExportSales.xlsx"); #endif MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.xlsx", "application/msexcel", stream); } } internal void OnImportClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; //Initializing Workbook Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = null; #if COMMONSB fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ExportSales.xlsx"); #else fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ExportSales.xlsx"); #endif IWorkbook workbook = application.Workbooks.Open(fileStream); workbook.Version = ExcelVersion.Excel2013; IWorksheet sheet = workbook.Worksheets[0]; //Export SheetData as DataTable DataTable dataTable = sheet.ExportDataTable(sheet.UsedRange, ExcelExportDataTableOptions.ColumnNames); //Convert DataTable to ObservableCollection ObservableCollection<CustomerObject> data = new ObservableCollection<CustomerObject>(); UpdateGridData(data, dataTable); //Set DataSource to Grid dataGrid.ItemsSource = data; this.btnGenerate.IsEnabled = true; workbook.Close(); excelEngine.Dispose(); } private void UpdateGridData(ObservableCollection<CustomerObject> data, DataTable dataTable) { foreach (System.Data.DataRow row in dataTable.Rows) { data.Add(new CustomerObject() { SalesPerson = row[0].ToString(), SalesJanJune = int.Parse(row[1].ToString()), SalesJulyDec = int.Parse(row[2].ToString()), Change = int.Parse(row[3].ToString()) }); } } internal void OnExportClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; //Initializing Workbook //A new workbook is created.[Equivalent to creating a new workbook in MS Excel] //The new workbook will have 1 worksheets IWorkbook workbook = application.Workbooks.Create(1); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; //Create new DataTable to store the data from DataGrid DataTable dataTable = new DataTable(); //Convert the Grid's data to DataTable ConvertGridDataToDataTable(dataTable, dataGrid.ItemsSource); //Import the DataTable to worksheet sheet.ImportDataTable(dataTable, 5, 1, false); // Define Styles IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle"); IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle"); pageHeader.Font.RGBColor = COLOR.Color.FromArgb(255, 83, 141, 213); pageHeader.Font.FontName = "Calibri"; pageHeader.Font.Size = 18; pageHeader.Font.Bold = true; pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Font.Color = ExcelKnownColors.Black; tableHeader.Font.Bold = true; tableHeader.Font.Size = 11; tableHeader.Font.FontName = "Calibri"; tableHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; tableHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Color = COLOR.Color.FromArgb(255, 118, 147, 60); tableHeader.Borders[ExcelBordersIndex.EdgeLeft].LineStyle = ExcelLineStyle.Thin; tableHeader.Borders[ExcelBordersIndex.EdgeRight].LineStyle = ExcelLineStyle.Thin; tableHeader.Borders[ExcelBordersIndex.EdgeTop].LineStyle = ExcelLineStyle.Thin; tableHeader.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin; // Apply Styles // Apply style for header sheet["A1:D1"].Merge(); sheet["A1"].Text = "Yearly Sales Report"; sheet["A1"].CellStyle = pageHeader; sheet["A1"].RowHeight = 20; sheet["A2:D2"].Merge(); sheet["A2"].Text = "Namewise Sales Comparison Report"; sheet["A2"].CellStyle = pageHeader; sheet["A2"].CellStyle.Font.Bold = false; sheet["A2"].CellStyle.Font.Size = 16; sheet["A2"].RowHeight = 20; sheet["A3:A4"].Merge(); sheet["D3:D4"].Merge(); sheet["B3:C3"].Merge(); sheet["B3"].Text = "Sales"; sheet["A3:D4"].CellStyle = tableHeader; sheet["A3"].Text = "Sales Person"; sheet["B4"].Text = "Jan - Jun"; sheet["C4"].Text = "Jul - Dec"; sheet["D3"].Text = "Change (%)"; sheet.Columns[0].ColumnWidth = 19; sheet.Columns[1].ColumnWidth = 10; sheet.Columns[2].ColumnWidth = 10; sheet.Columns[3].ColumnWidth = 11; // Saving workbook and disposing objects workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("DataTable.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("DataTable.xlsx", "application/msexcel", stream); } } private void ConvertGridDataToDataTable(DataTable dataTable, object itemsSource) { ObservableCollection<CustomerObject> items = (ObservableCollection<CustomerObject>)itemsSource; dataTable.Columns.Add("SalesPerson"); dataTable.Columns.Add("SalesJanJune"); dataTable.Columns.Add("SalesJulyDec"); dataTable.Columns.Add("Change"); foreach (CustomerObject customerObject in items) { dataTable.Rows.Add(customerObject.SalesPerson, customerObject.SalesJanJune, customerObject.SalesJulyDec, customerObject.Change); } } } }<file_sep>/Forms/BadgeView/BadgeView.iOS/FontIconiOSRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "FontIconiOSRenderer.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion [assembly: Xamarin.Forms.ExportRenderer(typeof(SampleBrowser.SfBadgeView.FontIconLabel), typeof(SampleBrowser.SfBadgeView.FontIconiOSRenderer))] namespace SampleBrowser.SfBadgeView { using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Globalization; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; /// <summary> /// Font Icon Renderer class /// </summary> [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1027:TabsMustNotBeUsed", Justification = "Reviewed.")] public class FontIconiOSRenderer : LabelRenderer { public FontIconiOSRenderer() { } /// <summary> /// Ons the element changed. /// </summary> /// <param name="e">event args</param> protected override void OnElementChanged(ElementChangedEventArgs<Label> e) { base.OnElementChanged(e); double? fs = e.NewElement?.FontSize; if (fs == null) { return; } UIFont font = UIFont.FromName("FONT Sf Badge view", (int)fs); Control.Font = font; } /// <summary> /// Ons the element property changed. /// </summary> /// <param name="sender">Sender</param> /// <param name="e">event args</param> protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName.Equals("Text")) { Label label = sender as Label; UIFont font = UIFont.FromName("FONT Sf Badge view", (int)label.FontSize); Control.Font = font; } } } }<file_sep>/iOS/SampleBrowser/Samples/DataSource/Helper/CustomTableCell.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreAnimation; using System; using System.Collections.Generic; using System.Text; using UIKit; namespace SampleBrowser { public class CustomTableCell : UITableViewCell { #region Field private UILabel Label1; private UILabel Label2; private UILabel Label3; private UILabel Label4; private UIImageView imageview; #endregion #region Constructor public CustomTableCell() { this.AutosizesSubviews = true; Label1 = CreateLabel(Label1); Label2 = CreateLabel(Label2); Label3 = CreateLabel(Label3); Label4 = CreateLabel(Label4); imageview= new UIImageView(); SelectionStyle = UITableViewCellSelectionStyle.Blue; this.AddSubviews(new UIView[] { imageview, Label1, Label2, Label3, Label4 }); this.Layer.AddSublayer(new CALayer()); } #endregion #region Private Method private UILabel CreateLabel(UILabel label) { label = new UILabel(); label.TextColor = UIColor.Black; label.TextAlignment = UITextAlignment.Left; label.LineBreakMode = UILineBreakMode.CharacterWrap; label.Font = UIFont.FromName("Helvetica Neue", 12); return label; } public void UpdateCell( object obj) { if (obj is BookDetails) { var bookDetails = obj as BookDetails; Label1.Text = "Name : " + bookDetails.CustomerName; Label2.Text = "Book ID : " + bookDetails.BookID.ToString(); Label3.Text = "Book Name : " + bookDetails.BookName; Label4.Text = "Price : " + "$" + bookDetails.Price.ToString(); imageview.Image = bookDetails.CustomerImage; } } #endregion #region override public override void LayoutSubviews() { // this.Layer.Frame = this.Frame; this.Layer.Sublayers[0].BackgroundColor = UIColor.LightGray.CGColor; this.Layer.Sublayers[0].Frame = new CoreGraphics.CGRect(0, 0, this.Frame.Width, 0.5); imageview.Frame = new CoreGraphics.CGRect(10, 10, 80, this.Frame.Height- 20); nfloat y=0; foreach (var subview in this.Subviews) { if (subview is UILabel) { subview.Frame = new CoreGraphics.CGRect(imageview.Frame.Right + 30, y + 10, (this.Frame.Width - 30 - imageview.Frame.Right) , (this.Frame.Height -20)/4); y += subview.Frame.Height; } } } #endregion } } <file_sep>/Forms/DataGrid/DataGrid/Samples/ContextMenu/ContextMenu.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ContextMenu.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.PopupLayout; using Xamarin.Forms; using Xamarin.Forms.Xaml; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A sampleView that contains the ContextMenu sample. /// </summary> public partial class ContextMenu : SampleView { /// <summary> /// Initializes a new instance of the ContextMenu class. /// </summary> public ContextMenu() { this.InitializeComponent(); } /// <summary> /// You can override this method while view has disappears /// </summary> public override void OnDisappearing() { popUpLayout.Dispose(); base.OnDisappearing(); } } }<file_sep>/Forms/AutoComplete/AutoComplete/Samples/HeaderFooterSample/ContactsInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace HeaderFooter { [Preserve(AllMembers = true)] public class ContactsInfoRepository { #region Fields private Random random = new Random(); #endregion #region Constructor public ContactsInfoRepository() { } #endregion #region Get Contacts Details public ObservableCollection<ContactsInfo> GetContactDetails() { ObservableCollection<ContactsInfo> customerDetails = new ObservableCollection<ContactsInfo>(); for (int i = 0; i < CustomerNames.Count(); i++) { var details = new ContactsInfo() { Message = contactType[(i % 19)], ContactReadType = (i < 5), ContactName = CustomerNames[i], ContactNumber = "@" + CustomerNames[i].Replace(" ", ".").ToLower() + random.Next(1000).ToString(), ContactImage = "People_Circle" + (i % 30) + ".png", }; customerDetails.Add(details); } return customerDetails; } #endregion #region Contacts Information string[] contactType = new string[] { "Hi,", "Sent a file", "Welcome", "Can you join the meeting?", ":),", "Thank you :)", "You: I am waiting", "That's Great!", "You: Okay", "ok sure", "I'm in meeting", "where is the book?", "You: need to do it now", "share me the file", "Cool?", ":) that's right,", "Thanks :)", "You: On the way", "Yes, But need to check", "It's possible?" }; string[] CustomerNames = new string[] { "Kyle", "Victoriya", "Clara", "Ellie", "Gabriella", "Alexander", "Nora", "Lucy", "Sebastian", "Arianna", "Sarah", "Kaylee", "Jacob", "Adriana", "Ethan", "Finley", "Daleyza", "Leila", "Jayden", "Mckenna", "Jacqueline", "Brynn", "Sawyer", "Liam", "Rosalie", "Maci", "Mason", "Jackson", "Miranda", "Talia", "Shelby", "Haven", "Yaretzi", "Zariah", "Karla", "Zeke", "Cassandra", "Pearl", "Aiden", "Irene", "Zelda", "Wren", "Vince", "Yamileth", "Steve", "Belen", "Briley", "Jada", "Holly", "Jaden" }; #endregion } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/OnBoardHelps/OnBoardHelps.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "OnBoardHelps.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using Core; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; [Preserve(AllMembers = true)] [XamlCompilation(XamlCompilationOptions.Compile)] /// <summary> /// A sampleView that contains the OnBoardHelps sample. /// </summary> public partial class OnBoardHelps : SampleView { /// <summary> /// Initializes a new instance of the OnBoardHelps class. /// </summary> public OnBoardHelps() { this.InitializeComponent(); } /// <summary> /// You can override this method while View was disappear from window /// </summary> public override void OnDisappearing() { base.OnDisappearing(); if (Device.RuntimePlatform == Device.UWP) { if (this.popupLayout != null) { this.popupLayout.Dismiss(); this.popupLayout.Dispose(); this.popupLayout = null; } if (this.dataGrid != null) { this.dataGrid.Dispose(); this.dataGrid = null; } } else { this.popupLayout.Dispose(); } } } }<file_sep>/iOS/SampleBrowser/Utility/Control.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Foundation; using UIKit; namespace SampleBrowser { public class Control : NSObject { #region ctor public Control() { } #endregion #region properties public NSString ControlName { get; set; } public NSString Name { get; set; } public NSString DisplayName { get; set; } public new NSString Description { get; set; } public UIImage Image { get; set; } public NSString Tag { get; set; } public NSString Type1 { get; set; } public NSString Type2 { get; set; } public bool IsMultipleSampleView { get; set; } #endregion } }<file_sep>/Forms/ProgressBar/readme.md The progress bar provides a customizable visual that indicates the progress of a task. It includes features such as the ability to visualize progress in rectangle and circular shapes, determinate and indeterminate states, segments, and customized ranges in different colors. It also supports animation. The following samples are available for ProgressBar to demonstrate the types. | Sample | Description | | ------ | ----------- | | [Linear](ProgressBar/Samples/Linear) |This sample demonstrates how to configure the linear progress bar with different states, segments, and animation to visualize the progress changes and to customize the visual appearance in a Xamarin.Forms application.| | [Circular](ProgressBar/Samples/Circular) | This sample demonstrates how to configure the circular progress bar with different states and segments, define custom content, animation and to customize the visual appearance in a Xamarin.Forms application.| <file_sep>/iOS/SampleBrowser/Samples/Model/Model.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; namespace SampleBrowser { public class ChartDataModel { public IComparable XValue { get; set; } public double YValue { get; set; } public double Open { get; set; } public double Close { get; set; } public double Size { get; set; } public double High { get; set; } public double Low { get; set; } public double Volume { get; set; } public ChartDataModel() { } public ChartDataModel(IComparable xValue, double yValue) { XValue = xValue; YValue = yValue; } public ChartDataModel(IComparable xValue, double value1, double value2) { XValue = xValue; High = value1; YValue = value1; Low = value2; Size = value2; } public ChartDataModel(IComparable xValue, double open, double high, double low, double close) { XValue = xValue; High = high; Low = low; Open = open; Close = close; } public ChartDataModel(IComparable xValue, double open, double high, double low, double close, double volume) { XValue = xValue; High = high; Low = low; Open = open; Close = close; Volume = volume; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/AutoRowHeightViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "AutoRowHeightViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for AutoRowHeight sample. /// </summary> public class AutoRowHeightViewModel : INotifyPropertyChanged { #region Field [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<ReleaseInfo> releaseInformation; #endregion /// <summary> /// Initializes a new instance of the AutoRowHeightViewModel class. /// </summary> public AutoRowHeightViewModel() { ReleaseInfoRepository details = new ReleaseInfoRepository(); this.releaseInformation = details.GetReleaseDetails(28); } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region ItemsSource /// <summary> /// Gets or sets the value of ReleaseInformation /// </summary> public ObservableCollection<ReleaseInfo> ReleaseInformation { get { return this.releaseInformation; } set { this.releaseInformation = value; } } #endregion #region Property Changed /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="propertyName">string type of parameter propertyName</param> public void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion } } <file_sep>/Forms/DocIO/DocIO/Samples/WordToHTML/WordToHTML.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using SampleBrowser.Core; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.DocIO; namespace SampleBrowser.DocIO { public partial class WordToHTML : SampleView { public WordToHTML() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { // if (!SampleBrowser.DocIO.App.isUWP) // { // this.Content_1.FontSize = 18.5; // } // else // { this.Content_1.FontSize = 13.5; // } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = typeof(WordToHTML).GetTypeInfo().Assembly; // Creating a new document. WordDocument document = new WordDocument(); #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif Stream inputStream = assembly.GetManifestResourceStream(rootPath + "WordtoHTML.doc"); //Open the Word document to convert document.Open(inputStream, FormatType.Doc); //Export the Word document to HTML file MemoryStream stream = new MemoryStream(); HTMLExport htmlExport = new HTMLExport(); htmlExport.SaveAsXhtml(document, stream); document.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("WordtoHTML.html", "application/html", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("WordtoHTML.html", "application/html", stream); if (!(Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP)) { //Set the stream to start position to read the content as string stream.Position = 0; StreamReader reader = new StreamReader(stream); string htmlString = reader.ReadToEnd(); //Set the HtmlWebViewSource to the html string HtmlWebViewSource html = new HtmlWebViewSource(); html.Html = htmlString; //Create the web view control to view the web page WebView view = new WebView(); view.Source = html; ContentPage webpage = new ContentPage(); webpage.Content = view; this.Content.Navigation.PushAsync(webpage); } } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/IDataGridDependencyService.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "IDataGridDependencyService.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// Interface that defines the methods required for the DataGrid SampleBrowser. /// </summary> public interface IDataGridDependencyService { /// <summary> /// Used to get device orientation in platform specific by using IDataGridDependencyService Interface /// </summary> /// <returns>returns device orientation as landscape or portrait</returns> string GetOrientation(); } } <file_sep>/Forms/ListView/ListView/Samples/Swiping/Helper/Behavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; using Syncfusion.ListView.XForms; using Xamarin.Forms; namespace SampleBrowser.SfListView { public class ListViewSwipingBehavior : Behavior<Syncfusion.ListView.XForms.SfListView> { Syncfusion.ListView.XForms.SfListView ListView; ListViewSwipingViewModel viewModel; protected override void OnAttachedTo(Syncfusion.ListView.XForms.SfListView bindable) { ListView = bindable; viewModel = new ListViewSwipingViewModel(); ListView.BindingContext = viewModel; (ListView.BindingContext as ListViewSwipingViewModel).ResetSwipeView += Behavior_ResetSwipeView; base.OnAttachedTo(bindable); } private void Behavior_ResetSwipeView(object sender, ResetEventArgs e) { ListView.ResetSwipe(); } } } <file_sep>/Forms/Presentation/Presentation/Samples/FindAndReplace/FindAndReplace.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using SampleBrowser.Core; using Syncfusion.PresentationRenderer; using System.Text.RegularExpressions; namespace SampleBrowser.Presentation { public partial class FindAndReplace : SampleView { public FindAndReplace() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Content_2.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Content_3.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Content_4.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Content_5.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.btnGenerate.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.btnInput.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Content_1.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.Content_2.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.Content_3.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.Content_4.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.Content_5.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnInput.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInput.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; this.Content_2.FontSize = 13.5; this.Content_3.FontSize = 13.5; this.Content_4.FontSize = 13.5; this.Content_5.FontSize = 13.5; } this.Content_1.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.Content_2.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.Content_3.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.Content_4.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.Content_5.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; } } internal void OnInputButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.InputTemplate.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.InputTemplate.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); stream.Position = 0; fileStream.Dispose(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } void OnReplaceButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.InputTemplate.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.InputTemplate.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Finds the first occurrence of a particular text. ITextSelection textSelection = presentation.Find("{product}", false, false); if (textSelection != null) { //Gets the found text as single text part ITextPart textPart = textSelection.GetAsOneTextPart(); //Replace the text textPart.Text = "Service"; } Regex regex = new Regex("{[A-Za-z]+}"); //Finds all the occurrence of a particular text pattern ITextSelection[] textSelections = presentation.FindAll(regex); if (textSelections != null) { foreach (ITextSelection textSelection2 in textSelections) { //Gets the found text as single text part ITextPart textPart = textSelection2.GetAsOneTextPart(); //Replace the text textPart.Text = "Service"; } } MemoryStream memoryStream = new MemoryStream(); presentation.Save(memoryStream); memoryStream.Position = 0; //Close the PowerPoint Presentation. presentation.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("FindAndReplace.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", memoryStream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("FindAndReplace.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", memoryStream); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/RangeNavigator/CustomizationRangeNavigator.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using nfloat = System.Single; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; #endif namespace SampleBrowser { public class CustomizationRangeNavigator : SampleView { UILabel lblTitle; UILabel lblValue; SFDateTimeRangeNavigator rangeNavigator; public CustomizationRangeNavigator() { rangeNavigator = new SFDateTimeRangeNavigator(); lblTitle = new UILabel(); lblTitle.TextAlignment = UITextAlignment.Center; lblTitle.Font = UIFont.FromName("Helvetica", 14f); lblValue = new UILabel(); lblValue.TextAlignment = UITextAlignment.Center; lblValue.Font = UIFont.FromName("Helvetica", 14f); rangeNavigator.ShowTooltip = false; rangeNavigator.Delegate = new CustomizationDelegate(lblTitle, lblValue); DateTime minDate = new DateTime(2015, 1, 1, 0, 0, 0); DateTime maxDate = new DateTime(2015, 12, 1, 0, 0, 0); DateTime startDate = new DateTime(2015, 6, 15, 0, 0, 0); DateTime endDate = new DateTime(2015, 9, 15, 0, 0, 0); rangeNavigator.Minimum = DateTimeToNSDate(minDate); rangeNavigator.Maximum = DateTimeToNSDate(maxDate); rangeNavigator.ViewRangeStart = DateTimeToNSDate(startDate); rangeNavigator.ViewRangeEnd = DateTimeToNSDate(endDate); rangeNavigator.EdgeInsets = new UIEdgeInsets(0, 0, 20, 0); rangeNavigator.Content.Layer.BorderWidth = 1.0f; rangeNavigator.Content.Layer.BorderColor = UIColor.LightGray.CGColor; rangeNavigator.LeftThumbStyle.LineWidth = 3.0f; rangeNavigator.LeftThumbStyle.Width = 28.0f; rangeNavigator.LeftThumbStyle.LineColor = UIColor.FromRGBA(95.0f / 255.0f, 104.0f / 255.0f, 114.0f / 255.0f, 1.0f); rangeNavigator.RightThumbStyle.LineWidth = 3.0f; rangeNavigator.RightThumbStyle.Width = 28.0f; rangeNavigator.RightThumbStyle.LineColor = UIColor.FromRGBA(95.0f / 255.0f, 104.0f / 255.0f, 114.0f / 255.0f, 1.0f); rangeNavigator.MinorScaleStyle.IsVisible = false; rangeNavigator.MinorScaleStyle.ShowGridLines = false; rangeNavigator.MajorScaleStyle.LabelTextColor = UIColor.FromRGBA(95.0f / 255.0f, 104.0f / 255.0f, 114.0f / 255.0f, 1.0f); rangeNavigator.MajorScaleStyle.SelectedLabelTextColor = UIColor.FromRGBA(28.0f / 255.0f, 178.0f / 255.0f, 213.0f / 255.0f, 1.0f); ChartViewModel dataModel = new ChartViewModel(); SFSplineAreaSeries series = new SFSplineAreaSeries(); series.Alpha = 0.6f; series.BorderColor = UIColor.FromRGBA (28.0f/255.0f, 178.0f/255.0f, 213.0f/255.0f, 1.0f); series.Color = UIColor.FromRGBA (124.0f/255.0f, 230.0f/255.0f, 199.0f/255.0f, 1.0f); series.ItemsSource = dataModel.DateTimeRangeData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; ((SFChart)rangeNavigator.Content).Series.Add(series); ThumbLayer thumbLayer = new ThumbLayer(); rangeNavigator.ThumbLayer = thumbLayer; this.AddSubview(lblTitle); this.AddSubview(lblValue); this.AddSubview(rangeNavigator); NSDateFormatter resultFormatter = new NSDateFormatter(); resultFormatter.DateFormat = "MMM dd"; lblTitle.Text = string.Format(@"Data usage cycle: {0} - {1}", resultFormatter.ToString(rangeNavigator.ViewRangeStart), resultFormatter.ToString(rangeNavigator.ViewRangeEnd)); lblValue.Text = string.Format(@"Data usage - 101 MB"); //this.control = this; } public static NSDate DateTimeToNSDate(DateTime date) { DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime( new DateTime(2001, 1, 1, 0, 0, 0)); return NSDate.FromTimeIntervalSinceReferenceDate((date - reference).TotalSeconds); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view == lblTitle) lblTitle.Frame = new CGRect(Frame.X, 10, Frame.Width, 35); else if (view == rangeNavigator) rangeNavigator.Frame = new CGRect(Frame.X, 55, Frame.Width, 180); else if (view == lblValue) lblValue.Frame = new CGRect(Frame.X, 230, Frame.Width, 35); else view.Frame = Frame; } base.LayoutSubviews(); } } public class CustomizationDelegate : SFRangeNavigatorDelegate { UILabel lblTitle; UILabel lblValue; ChartViewModel dataModel; ObservableCollection<ChartDataModel> dataPoints; public CustomizationDelegate(UILabel _lblTitle, UILabel _lblValue) { lblTitle = _lblTitle; lblValue = _lblValue; dataModel = new ChartViewModel(); dataPoints = new ObservableCollection<ChartDataModel>(); dataPoints = dataModel.DateTimeRangeData; } public override void RangeChanged(SFDateTimeRangeNavigator rangeNavigator, NSDate startDate, NSDate endDate) { NSDateFormatter resultFormatter = new NSDateFormatter(); resultFormatter.DateFormat = "MMM dd"; lblTitle.Text = string.Format(@"Data usage cycle: {0} - {1}", resultFormatter.ToString(startDate), resultFormatter.ToString(endDate)); NSDateFormatter dateFormatter = new NSDateFormatter(); dateFormatter.DateFormat = @"MMM dd"; ChartDataModel data = new ChartDataModel(); NSDate date; NSNumber value; int y = 0; for (int i = 0; i < dataPoints.Count; i++) { data = dataPoints[i]; date = (CustomizationRangeNavigator.DateTimeToNSDate((DateTime)data.XValue)); if ((startDate.Compare(date) == NSComparisonResult.Ascending || startDate.Compare(date) == NSComparisonResult.Same) && (date.Compare(endDate) == NSComparisonResult.Ascending || date.Compare(endDate) == NSComparisonResult.Same)) { value = (NSNumber)data.YValue; y += (int)value; } } lblValue.Text = string.Format(@"Data usage - {0} MB", y); } } public class ThumbLayer : SFRangeNavigatorThumbLayer { public override void DrawLeftThumbInContext(CGContext ctx, CGPoint startPoint, CGPoint endPoint) { CGRect rect = new CGRect(startPoint.X - 14, endPoint.Y - 14, 14, 14); DrawTriangleInContext(ctx, rect, 1, false); rect = new CGRect(startPoint.X - 14.5f, (float)endPoint.Y + 0.5f, 15.5f, 12f); DrawRectShapeInContext(ctx, rect); // Sets the region to be captured for dragging the left thumb. // When you are changing the default position or size of the thumb by overriding drawLeftThumbInContext method, // this method should be called mandatorily to set the region a user can touch to drag the thumb. this.SetLeftThumbFrame(new CGRect(startPoint.X - 14, startPoint.Y, 22, endPoint.Y + 16)); } public override void DrawRightThumbInContext(CGContext ctx, CGPoint startPoint, CGPoint endPoint) { CGRect rect = new CGRect(startPoint.X, endPoint.Y - 14, 14, 14); DrawTriangleInContext(ctx, rect, 1, true); rect = new CGRect(startPoint.X - 1f, endPoint.Y + 0.5f, 15.5f, 12f); DrawRectShapeInContext(ctx, rect); // Sets the region to be captured for dragging the right thumb. // When you are changing the default position or size of the thumb by overriding drawRightThumbInContext method, // this method should be called mandatorily to set the region a user can touch to drag the thumb. this.SetRightThumbFrame(new CGRect(startPoint.X, startPoint.Y - 16, 22, endPoint.Y + 16)); } //utility for drawing triangle shape public void DrawTriangleInContext(CGContext ctx, CGRect rect, float BorderWidth, bool isLeft) { UIColor color = UIColor.FromRGBA(95.0f / 255.0f, 104.0f / 255.0f, 114.0f / 255.0f, 1.0f); ctx.SetLineWidth(BorderWidth); ctx.SetStrokeColor(color.CGColor); ctx.SetFillColor(color.CGColor); ctx.SaveState(); if (isLeft) ctx.MoveTo(rect.GetMinX(), rect.GetMinY()); else ctx.MoveTo(rect.GetMaxX(), rect.GetMinY()); ctx.AddLineToPoint(rect.GetMinX(), rect.GetMaxY()); ctx.AddLineToPoint(rect.GetMaxX(), rect.GetMaxY()); ctx.ClosePath(); ctx.DrawPath(CGPathDrawingMode.FillStroke); ctx.RestoreState(); } //utility for drawing rectangle shape public void DrawRectShapeInContext(CGContext ctx, CGRect rect) { ctx.SetFillColor(UIColor.FromRGBA(95.0f / 255.0f, 104.0f / 255.0f, 114.0f / 255.0f, 1.0f).CGColor); ctx.SetStrokeColor(UIColor.FromRGBA(95.0f / 255.0f, 104.0f / 255.0f, 114.0f / 255.0f, 1.0f).CGColor); ctx.StrokeRect(rect); ctx.FillRect(rect); // Add rounded rect over plain rect with 4 pixel below the origin y, so that it will visible only the bottom rounded corners CGRect cornerRect = new CGRect(rect.X, rect.Y + 4, rect.Width, rect.Height); nfloat radius = 4; nfloat minx = cornerRect.GetMinX(), midx = cornerRect.GetMidX(), maxx = cornerRect.GetMaxX(); nfloat miny = cornerRect.GetMinY(), midy = cornerRect.GetMidY(), maxy = cornerRect.GetMaxY(); ctx.SaveState(); ctx.MoveTo(minx, miny); ctx.AddArcToPoint(minx, miny, midx, miny, radius); ctx.AddArcToPoint(maxx, miny, maxx, midy, radius); ctx.AddArcToPoint(maxx, maxy, midx, maxy, radius); ctx.AddArcToPoint(minx, maxy, minx, midy, radius); ctx.ClosePath(); ctx.DrawPath(CGPathDrawingMode.FillStroke); ctx.RestoreState(); } } }<file_sep>/iOS/SampleBrowser/Samples/TreeView/Helpers/CustomAdapters/NodeImageAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using View=UIKit.UIView; using UIKit; using Syncfusion.iOS.TreeView; namespace SampleBrowser { public class NodeImageAdapter : TreeViewAdapter { public NodeImageAdapter() { } protected override View CreateContentView(TreeViewItemInfoBase itemInfo) { var gridView = new NodeImageView(); return gridView; } protected override void UpdateContentView(View view, TreeViewItemInfoBase itemInfo) { var grid = view as NodeImageView; var treeViewNode = itemInfo.Node; if (grid != null) { var imageView = grid.Subviews[0] as UIImageView; if (imageView != null) imageView.Image = (treeViewNode.Content as FileManager).ImageIcon; var label1 = grid.Subviews[1] as UILabel; if (label1 != null) label1.Text = (treeViewNode.Content as FileManager).FileName; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataSource/Model/BookDetailsRepository.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Foundation; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Reflection; using UIKit; namespace SampleBrowser { public class BookDetailsRepository { public BookDetailsRepository() { } #region private variables private Random random = new Random(); #endregion #region GetBookDetails public ObservableCollection<BookDetails> GetBookDetails(int count) { ObservableCollection<BookDetails> bookDetails = new ObservableCollection<BookDetails>(); for (int i = 1; i <= count; i++) { var image = LoadResource("Image" + (i % 23) + ".png").ToArray(); var imageData = NSData.FromArray(image); var customerImage = UIImage.LoadFromData(imageData, UIScreen.MainScreen.Scale); var ord = new BookDetails() { BookID = BookID[random.Next(8)], BookName = BookNames[random.Next(5)], Price = random.Next(30, 200), CustomerName = CustomerNames[random.Next(7)], CustomerImage = customerImage }; bookDetails.Add(ord); } return bookDetails; } public MemoryStream LoadResource(String Name) { MemoryStream aMem = new MemoryStream(); var assm = Assembly.GetExecutingAssembly(); var path = String.Format("SampleBrowser.Resources.Images.{0}", Name); var aStream = assm.GetManifestResourceStream(path); aStream.CopyTo(aMem); return aMem; } #endregion #region DataSource string[] BookNames = new string[] { "<NAME>", "Money", "The Information", "The BottleFactory", "Flaub<NAME>", "Molloy", "<NAME>", "A Good Man", "The History Man", "The Horse", "Chocolate", "<NAME>", "<NAME>", "Caprice", "Towards the End ", "Polygots", "Death Soul", "Charade", "Changing places", "Under the Net", "Fire Flies", }; int[] BookID = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; string[] CustomerNames = new string[] { "Kyle", "Gina", "Irene", "Katie", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Brenda", "Danielle", "Fiona", "Howard", "Jack", "Larry", "Holly", "Jennifer", "Liz", "Pete", "Steve", "Vince", "Zeke" }; #endregion } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/Model/ProductInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; namespace SampleBrowser { public class ProductInfoRespository { /// <summary> /// Gets the orders details. /// </summary> /// <param name="count">The count.</param> /// <returns></returns> public List<ProductInfo> GetProductDetails (int count) { List<ProductInfo> productDetails = new List<ProductInfo> (); SetProduct (); SetProductPrice (); for (int i = 10001; i <= count + 10000; i++) { productDetails.Add (getProduct (i)); } return productDetails; } Random r = new Random (); private ProductInfo getProduct (int i) { ProductInfo product = new ProductInfo (); var productName = ProductName [r.Next (ProductName.Count () - 1)]; var Productcoll = Product [productName]; product.ProductID = i; product.UserRating = r.Next (3, 5); product.ShippingDays = r.Next (1, 5); product.ProductType = productName; product.Product = Productcoll [r.Next (Productcoll.Length - 1)]; var productModel = ProductModel [product.Product]; product.Availability = r.Next (0, 20) % 5 == 0 ? false : true; product.Price = ProductPrice [productName]; product.ProductModel = productModel [r.Next (productModel.Count ())]; return product; } string[] ProductName = new string[] { "Laptop", "Mobile", "Watch", "Footware" }; Dictionary<string, string[]> Product = new Dictionary<string, string[]> (); Dictionary<string, string[]> ProductModel = new Dictionary<string, string[]> (); Dictionary<string, int> ProductPrice = new Dictionary<string, int> (); private void SetProduct () { string[] laptop = new string[] { "Dell", "HP", "Asus", "Sony", "Apple", "Lenovo" }; string[] mobile = new string[] { "Nokia", "Samsung", "SonyMobile", "HTC", "IPhone" }; string[] watch = new string[] { "FastTrack", "ROLEX", "Casio", "Geneva", "Seiko" }; string[] footware = new string[] { "Reebok", "Puma" }; Product.Add ("Laptop", laptop); Product.Add ("Mobile", mobile); Product.Add ("Watch", watch); Product.Add ("Footware", footware); ProductModel.Add ("Dell", new string[] { "XPS15", "XPS12" }); ProductModel.Add ("HP", new string[] { "Pavilion_G6", "Envy_X2" }); ProductModel.Add ("Asus", new string[] { "Transformer" }); ProductModel.Add ("Sony", new string[] { "Vaio" }); ProductModel.Add ("Apple", new string[] { "Macbook_Air", "Macbook_Pro2" }); ProductModel.Add ("Lenovo", new string[] { "Yoga" }); ProductModel.Add ("Nokia", new string[] { "Lumia_920", "Lumia_800" }); ProductModel.Add ("Samsung", new string[] { "S3" }); ProductModel.Add ("SonyMobile", new string[] { "Xperia_Tipo", "Xperia_Z" }); ProductModel.Add ("IPhone", new string[] { "Iphone5" }); ProductModel.Add ("HTC", new string[] { "8x", "One_X" }); ProductModel.Add ("FastTrack", new string[] { "Fastrack", "Men_Black" }); ProductModel.Add ("Casio", new string[] { "G-Shock" }); ProductModel.Add ("Geneva", new string[] { "Carrera", "Monaco" }); ProductModel.Add ("Seiko", new string[] { "Aquaracer" }); ProductModel.Add ("ROLEX", new string[] { "Sea_Dweller Deepsea", "Submariner" }); ProductModel.Add ("Puma", new string[] { "Aquil", "Axis_XT" }); ProductModel.Add ("Reebok", new string[] { "Advantage_Runner", "FieldEffect", "RunCruise" }); } private void SetProductPrice () { ProductPrice.Add ("Laptop", r.Next (1200, 1500)); ProductPrice.Add ("Mobile", r.Next (250, 350)); ProductPrice.Add ("Watch", r.Next (120, 150)); ProductPrice.Add ("Footware", r.Next (35, 45)); } string[] ProductID = new string[] { "ALFKI", "FRANS", "MEREP", "FOLKO", "SIMOB", "WARTH", "VAFFE", "FURIB", "SEVES", "LINOD", "RISCU", "PICCO", "BLONP", "WELLI", "FOLIG" }; } } <file_sep>/Forms/Carousel/Carousel/SampleViewClass/Carousel_Virtualization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfCarousel { /// <summary> /// Carousel virtualization. /// </summary> public class Carousel_Virtualization:SampleView { #region constructor public Carousel_Virtualization() { #region device and tablet Virtualization_Default busy = new Virtualization_Default(); this.Content = busy.getContent(); #endregion } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Schedule/WorkingHours.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Android.Views; using Android.Widget; using Com.Syncfusion.Sfrangeslider; using System.Collections.Generic; using Java.Util; using Android.Graphics; using Java.Text; using Android.App; using Android.OS; using Com.Syncfusion.Schedule; using System.Collections.ObjectModel; using Com.Syncfusion.Schedule.Enums; namespace SampleBrowser { public class Timetable : SamplePage, IDisposable { private SfSchedule sfschedule; private NonAccessibleBlocksCollection nonAccessibleBlocksCollection; private NonAccessibleBlocksCollection nonAccessibleBlocks; private Context con; private List<String> subjectCollection; private List<Calendar> startTimeCollection; private List<Calendar> endTimeCollection; private ScheduleAppointmentCollection appointmentCollection; public override View GetSampleContent(Context context) { con = context; sfschedule = new SfSchedule(context); InitializingAppointmentData(); sfschedule.ScheduleView = ScheduleView.DayView; sfschedule.TimeIntervalHeight = -1; sfschedule.VisibleDatesChanged += Sfschedule_VisibleDatesChanged; var dayViewSettings = new DayViewSettings(); dayViewSettings.StartHour = 9; dayViewSettings.EndHour = 16; sfschedule.DayViewSettings = dayViewSettings; nonAccessibleBlocksCollection = new NonAccessibleBlocksCollection(); var lunch = new NonAccessibleBlock(); lunch.StartTime = 12; lunch.EndTime = 13; lunch.Text = "Lunch Break"; nonAccessibleBlocksCollection.Add(lunch); nonAccessibleBlocks = nonAccessibleBlocksCollection; sfschedule.DayViewSettings.NonAccessibleBlocks = nonAccessibleBlocks; LinearLayout layout = new LinearLayout(context); layout.Orientation = Android.Widget.Orientation.Vertical; layout.AddView(sfschedule); return layout; } // Creating appointments for ScheduleAppointmentCollection public void InitializingAppointmentData() { SetSubjects(); SetStartTime(); SetEndTime(); } private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("Wellness"); subjectCollection.Add("Language Arts"); subjectCollection.Add("Mathematics"); subjectCollection.Add("Social Studies"); subjectCollection.Add("Physical Education"); subjectCollection.Add("Geography"); } private void SetStartTime() { //appointment1 startTimeCollection = new List<Calendar>(); var currentDate1 = Calendar.Instance; var startTime1 = (Calendar)currentDate1.Clone(); startTime1.Set( startTime1.Get(CalendarField.Year), startTime1.Get(CalendarField.Month), startTime1.Get(CalendarField.DayOfMonth), 9, 1, 0); // appointment2 var currentDate2 = Calendar.Instance; var startTime2 = (Calendar)currentDate2.Clone(); startTime2.Set( startTime2.Get(CalendarField.Year), startTime2.Get(CalendarField.Month), startTime2.Get(CalendarField.DayOfMonth), 10, 1, 0); //appointment3 var currentDate3 = Calendar.Instance; var startTime3 = (Calendar)currentDate3.Clone(); startTime3.Set( startTime3.Get(CalendarField.Year), startTime3.Get(CalendarField.Month), startTime3.Get(CalendarField.DayOfMonth), 11, 11, 0); //appointment4 var currentDate4 = Calendar.Instance; var startTime4 = (Calendar)currentDate4.Clone(); startTime4.Set( startTime4.Get(CalendarField.Year), startTime4.Get(CalendarField.Month), startTime4.Get(CalendarField.DayOfMonth), 13, 1, 0); // appointment5 var currentDate5 = Calendar.Instance; var startTime5 = (Calendar)currentDate5.Clone(); startTime5.Set( startTime5.Get(CalendarField.Year), startTime5.Get(CalendarField.Month), startTime5.Get(CalendarField.DayOfMonth), 14, 1, 0); // appointment6 var currentDate6 = Calendar.Instance; var startTime6 = (Calendar)currentDate6.Clone(); startTime6.Set( startTime6.Get(CalendarField.Year), startTime6.Get(CalendarField.Month), startTime6.Get(CalendarField.DayOfMonth), 15, 11, 0); startTimeCollection.Add(startTime1); startTimeCollection.Add(startTime2); startTimeCollection.Add(startTime3); startTimeCollection.Add(startTime4); startTimeCollection.Add(startTime5); startTimeCollection.Add(startTime6); } private void SetEndTime() { endTimeCollection = new List<Calendar>(); // appointment1 var currentDate1 = Calendar.Instance; var endTime1 = (Calendar)currentDate1.Clone(); endTime1.Set( endTime1.Get(CalendarField.Year), endTime1.Get(CalendarField.Month), endTime1.Get(CalendarField.DayOfMonth), 10, 0, 0); // appointment2 var currentDate2 = Calendar.Instance; var endTime2 = (Calendar)currentDate2.Clone(); endTime2.Set( endTime2.Get(CalendarField.Year), endTime2.Get(CalendarField.Month), endTime2.Get(CalendarField.DayOfMonth), 11, 0, 0); //appointment3 var currentDate3 = Calendar.Instance; var endTime3 = (Calendar)currentDate3.Clone(); endTime3.Set( endTime3.Get(CalendarField.Year), endTime3.Get(CalendarField.Month), endTime3.Get(CalendarField.DayOfMonth), 12, 0, 0); //appointment4 var currentDate4 = Calendar.Instance; var endTime4 = (Calendar)currentDate4.Clone(); endTime4.Set( endTime4.Get(CalendarField.Year), endTime4.Get(CalendarField.Month), endTime4.Get(CalendarField.DayOfMonth), 14, 0, 0); // appointment5 var currentDate5 = Calendar.Instance; var endTime5 = (Calendar)currentDate5.Clone(); endTime5.Set( endTime5.Get(CalendarField.Year), endTime5.Get(CalendarField.Month), endTime5.Get(CalendarField.DayOfMonth), 15, 0, 0); // appointment6 var currentDate6 = Calendar.Instance; var endTime6 = (Calendar)currentDate6.Clone(); endTime6.Set( endTime6.Get(CalendarField.Year), endTime6.Get(CalendarField.Month), endTime6.Get(CalendarField.DayOfMonth), 16, 0, 0); endTimeCollection.Add(endTime1); endTimeCollection.Add(endTime2); endTimeCollection.Add(endTime3); endTimeCollection.Add(endTime4); endTimeCollection.Add(endTime5); endTimeCollection.Add(endTime6); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private Color GetColors(string subject) { if (subject == "Wellness") { return Color.ParseColor("#FFA2C139"); } else if (subject == "Language Arts") { return Color.ParseColor("#FFD80073"); } else if (subject == "Mathematics") { return Color.ParseColor("#FFE671B8"); } else if (subject == "Social Studies") { return Color.ParseColor("#FF1BA1E2"); } else if (subject == "Physical Education") { return Color.ParseColor("#FF00ABA9"); } else { return Color.ParseColor("#FF339933"); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private string GetStaff(string subject) { if (subject == "Wellness") { return "Mr. Jamison"; } else if (subject == "Language Arts") { return "Ms. Casey"; } else if (subject == "Mathematics") { return "Mr. Percorino"; } else if (subject == "Social Studies") { return "Ms. Gawade"; } else if (subject == "Physical Education") { return "Mr. Shilling"; } else { return "Mr. <NAME>"; } } private void Sfschedule_VisibleDatesChanged(object sender, VisibleDatesChangedEventArgs e) { appointmentCollection = new ScheduleAppointmentCollection(); var visibleDates = e.VisibleDates; var rand = new Java.Util.Random(); var endCalendar = Calendar.Instance; var startCalendar = Calendar.Instance; var breakStartValue = Calendar.Instance; var breakEndValue = Calendar.Instance; var break1StartValue = Calendar.Instance; var break2StartValue = Calendar.Instance; for (int i = 0; i < visibleDates.Count; i++) { if (visibleDates[i].Get(CalendarField.DayOfWeek) == 1 || visibleDates[i].Get(CalendarField.DayOfWeek) == 7) { sfschedule.DayViewSettings.NonAccessibleBlocks = null; } else { sfschedule.DayViewSettings.NonAccessibleBlocks = nonAccessibleBlocks; } if (visibleDates[i].Get(CalendarField.DayOfWeek) == 1 || visibleDates[i].Get(CalendarField.DayOfWeek) == 7) { continue; } // Periods Appointments for (int j = 0; j < startTimeCollection.Count; j++) { startCalendar.Set(visibleDates[i].Get(CalendarField.Year), visibleDates[i].Get(CalendarField.Month), visibleDates[i].Get(CalendarField.Date), startTimeCollection[j].Get(CalendarField.HourOfDay), startTimeCollection[j].Get(CalendarField.Minute), startTimeCollection[j].Get(CalendarField.Second)); endCalendar.Set(visibleDates[i].Get(CalendarField.Year), visibleDates[i].Get(CalendarField.Month), visibleDates[i].Get(CalendarField.Date), endTimeCollection[j].Get(CalendarField.HourOfDay), endTimeCollection[j].Get(CalendarField.Minute), endTimeCollection[j].Get(CalendarField.Second)); var subject = subjectCollection[rand.NextInt(subjectCollection.Count)]; appointmentCollection.Add(new ScheduleAppointment() { StartTime = (Calendar)startCalendar.Clone(), EndTime = (Calendar)endCalendar.Clone(), Subject = subject + " (" + startTimeCollection[j].Get(CalendarField.HourOfDay).ToString() + ":00 - " + endTimeCollection[j].Get(CalendarField.HourOfDay).ToString() + ":00" + ") \n\n" + GetStaff(subject), Color = GetColors(subject), }); } // Break Timings breakStartValue.Set(visibleDates[i].Get(CalendarField.Year), visibleDates[i].Get(CalendarField.Month), visibleDates[i].Get(CalendarField.Date), 11, 01, 0); breakEndValue.Set(visibleDates[i].Get(CalendarField.Year), visibleDates[i].Get(CalendarField.Month), visibleDates[i].Get(CalendarField.Date), 11, 10, 0); appointmentCollection.Add(new ScheduleAppointment() { StartTime = (Calendar)breakStartValue.Clone(), EndTime = (Calendar)breakEndValue.Clone(), Color = Color.LightGray }); break1StartValue.Set(visibleDates[i].Get(CalendarField.Year), visibleDates[i].Get(CalendarField.Month), visibleDates[i].Get(CalendarField.Date), 15, 01, 0); break2StartValue.Set(visibleDates[i].Get(CalendarField.Year), visibleDates[i].Get(CalendarField.Month), visibleDates[i].Get(CalendarField.Date), 15, 10, 0); appointmentCollection.Add(new ScheduleAppointment() { StartTime = (Calendar)break1StartValue.Clone(), EndTime = (Calendar)break2StartValue.Clone(), Color = Color.LightGray }); } sfschedule.ItemsSource = appointmentCollection; } public void Dispose() { if (sfschedule != null) { sfschedule.VisibleDatesChanged -= Sfschedule_VisibleDatesChanged; sfschedule.Dispose(); sfschedule = null; } if (nonAccessibleBlocksCollection != null) { nonAccessibleBlocksCollection.Clear(); nonAccessibleBlocksCollection = null; } if (subjectCollection != null) { subjectCollection.Clear(); subjectCollection = null; } if (startTimeCollection != null) { startTimeCollection.Clear(); startTimeCollection = null; } if (endTimeCollection != null) { endTimeCollection.Clear(); endTimeCollection = null; } if (appointmentCollection != null) { appointmentCollection.Clear(); appointmentCollection = null; } if (nonAccessibleBlocks != null) { nonAccessibleBlocks.Clear(); nonAccessibleBlocks = null; } if (con != null) { con = null; } } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/Editing.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Syncfusion.SfDataGrid; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class Editing : SampleView { SfDataGrid sfGrid; EditingViewModel viewmodel; public Editing() { sfGrid = new SfDataGrid(); viewmodel = new EditingViewModel(); sfGrid.AutoGenerateColumns = false; sfGrid.RowHeight = 50; sfGrid.AllowEditing = true; sfGrid.SelectionMode = SelectionMode.Single; sfGrid.NavigationMode = NavigationMode.Cell; sfGrid.EditTapAction = TapAction.OnTap; sfGrid.ColumnSizer = ColumnSizer.Star; sfGrid.HeaderRowHeight = 40; sfGrid.ItemsSource = viewmodel.DealerInformation; GridNumericColumn productPrice = new GridNumericColumn(); productPrice.MappingName = "ProductPrice"; productPrice.HeaderText = "Product Price"; productPrice.HeaderTextAlignment = UIKit.UITextAlignment.Center; GridDateTimeColumn shippedDate = new GridDateTimeColumn(); shippedDate.MappingName = "ShippedDate"; shippedDate.HeaderText = "Shipped Date"; shippedDate.Format = "d"; shippedDate.HeaderTextAlignment = UIKit.UITextAlignment.Center; GridPickerColumn dealerName = new GridPickerColumn(); dealerName.MappingName = "DealerName"; dealerName.HeaderText = "Dealer Name"; dealerName.ItemsSource = viewmodel.CustomerNames; dealerName.HeaderTextAlignment = UIKit.UITextAlignment.Center; GridTextColumn productNo = new GridTextColumn(); productNo.MappingName = "ProductNo"; productNo.HeaderText = "Product No"; productNo.HeaderTextAlignment = UIKit.UITextAlignment.Center; sfGrid.Columns.Add(productNo); sfGrid.Columns.Add(dealerName); sfGrid.Columns.Add(shippedDate); sfGrid.Columns.Add(productPrice); this.AddSubview(sfGrid); } public override void LayoutSubviews() { this.sfGrid.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { if (disposing) { if (sfGrid != null) sfGrid.Dispose(); viewmodel = null; sfGrid = null; } base.Dispose(disposing); } } }<file_sep>/Forms/Chart/Chart/Samples/BoxAndWhiskerChart/BoxAndWhiskerChart.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class BoxAndWhiskerChart : SampleView { public BoxAndWhiskerChart() { InitializeComponent(); boxPlotMode.SelectedIndex = 0; boxPlotMode.SelectedIndexChanged += BoxPlotMode_SelectedIndexChanged; symbolType.SelectedIndex = 0; symbolType.SelectedIndexChanged += SymbolType_SelectedIndexChanged; } private void SymbolType_SelectedIndexChanged(object sender, EventArgs e) { switch (symbolType.SelectedIndex) { case 0: boxPlotSeries.SymbolType = ChartSymbolType.Ellipse; break; case 1: boxPlotSeries.SymbolType = ChartSymbolType.Diamond; break; case 2: boxPlotSeries.SymbolType = ChartSymbolType.Cross; break; case 3: boxPlotSeries.SymbolType = ChartSymbolType.Hexagon; break; case 4: boxPlotSeries.SymbolType = ChartSymbolType.InvertedTriangle; break; case 5: boxPlotSeries.SymbolType = ChartSymbolType.Pentagon; break; case 6: boxPlotSeries.SymbolType = ChartSymbolType.Plus; break; case 7: boxPlotSeries.SymbolType = ChartSymbolType.Rectangle; break; case 8: boxPlotSeries.SymbolType = ChartSymbolType.Triangle; break; } } private void BoxPlotMode_SelectedIndexChanged(object sender, EventArgs e) { switch (boxPlotMode.SelectedIndex) { case 0: boxPlotSeries.BoxPlotMode = BoxPlotMode.Exclusive; break; case 1: boxPlotSeries.BoxPlotMode = BoxPlotMode.Inclusive; break; case 2: boxPlotSeries.BoxPlotMode = BoxPlotMode.Normal; break; } } private void ShowMedian_Toggled(object sender, ToggledEventArgs e) { boxPlotSeries.ShowMedian = e.Value; } } }<file_sep>/Forms/DataForm/DataForm/Samples/Themes/Helpers/SfDataFormThemesBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.DataForm; using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfDataForm { [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public class SfDataFormThemesBehavior : Behavior<Syncfusion.XForms.DataForm.SfDataForm> { /// <summary> /// DataForm control to edit the data fields of any data object /// </summary> private Syncfusion.XForms.DataForm.SfDataForm dataForm; /// <summary> /// Attaches to the superclass and then calls the OnAttachedTo method on this object. /// </summary> /// <param name="bindable">The bindable object to which the behavior was attached.</param> protected override void OnAttachedTo(Syncfusion.XForms.DataForm.SfDataForm bindable) { this.dataForm = bindable; base.OnAttachedTo(bindable); } /// <summary> /// Calls the OnDetachingFrom method and then detaches from the superclass. /// </summary> /// <param name="bindable">The bindable object from which the behavior was detached.</param> protected override void OnDetachingFrom(Syncfusion.XForms.DataForm.SfDataForm bindable) { base.OnDetachingFrom(bindable); this.dataForm = null; } } } <file_sep>/Android/SampleBrowser/Samples/SfMaskedEdit/SfMaskedEditProperties.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Syncfusion.Android.MaskedEdit; using System; using System.Collections.Generic; using System.Globalization; namespace SampleBrowser { class SfMaskedEditProperties { InputValidationMode validateMask; SfMaskedEditText_Mobile textMask; SfMaskedEditText_Tab tabMask; int validatePosition = 0; int culturePosition = 0; int promptPosition = 0; /// <summary> /// Contain the close button visibility details /// </summary> ClearButtonVisibilityMode clearButtonVisibility; /// <summary> /// It contain the index for the spinner /// </summary> int visibilityPosition = 1; bool ishidePrompt = false; public SfMaskedEditProperties(SfMaskedEditText_Mobile maskedEdit) { textMask = maskedEdit; } public SfMaskedEditProperties(SfMaskedEditText_Tab maskedEdit) { tabMask = maskedEdit; } internal InputValidationMode ValidationLayout(Context context, LinearLayout propertylayout, bool isMobile) { TextView validationLabel = new TextView(context); validationLabel.TextSize = 20; validationLabel.Text = "Validation On"; //CutCopy Spinner Spinner validationSpinner = new Spinner(context, SpinnerMode.Dialog); validationSpinner.SetGravity(GravityFlags.Left); //CutCopy List List<String> validationList = new List<String>(); validationList.Add("Key Press"); validationList.Add("Lost Focus"); ArrayAdapter<String> validationAdopter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, validationList); validationAdopter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); validationSpinner.Adapter = validationAdopter; validationSpinner.SetSelection(validatePosition); //cutcopy Spinner ItemSelected Listener validationSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = validationAdopter.GetItem(e.Position); validatePosition = e.Position; if (selectedItem.Equals("Key Press")) { validateMask = InputValidationMode.KeyPress; } if (selectedItem.Equals("Lost Focus")) { validateMask = InputValidationMode.LostFocus; } if (isMobile) { textMask.ValidationMask = validateMask; } else { tabMask.ValidationMask = validateMask; tabMask.OnApplyChanges(); } }; if (isMobile) { propertylayout.AddView(validationLabel); //AdjLabel TextView adjLabel2 = new TextView(context); adjLabel2.SetHeight(14); adjLabel2.SetPadding(0, 0, 0, 20); propertylayout.AddView(adjLabel2); validationSpinner.SetPadding(0, 0, 0, 20); propertylayout.AddView(validationSpinner); } else { LinearLayout validationLayout = new LinearLayout(context); validationLayout.Orientation = Android.Widget.Orientation.Horizontal; validationLayout.AddView(validationLabel); LinearLayout.LayoutParams validationSpinnerLayout = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); validationSpinnerLayout.SetMargins(160, 0, 70, 0); validationLayout.AddView(validationSpinner,validationSpinnerLayout); tabMask.ProprtyOptionsLayout.AddView(validationLayout); TextView spaceText2 = new TextView(context); spaceText2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); tabMask.ProprtyOptionsLayout.AddView(spaceText2); } return validateMask; } internal void CultureLayout(Context context, LinearLayout propertylayout, bool isMobile) { TextView cultureLabel = new TextView(context); cultureLabel.TextSize = 20; cultureLabel.Text = "Culture"; //culture Spinner Spinner cultureSpinner = new Spinner(context, SpinnerMode.Dialog); cultureSpinner.SetGravity(GravityFlags.Left); //culture List List<String> cultureList = new List<String>(); cultureList.Add("United States"); cultureList.Add("United Kingdom"); cultureList.Add("Japan"); cultureList.Add("France"); cultureList.Add("Italy"); //culture Adapter ArrayAdapter<string> cultureAdopter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, cultureList); cultureAdopter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); cultureSpinner.Adapter = cultureAdopter; cultureSpinner.SetSelection(culturePosition); CultureInfo currentCulture = new CultureInfo("en-us"); //culture Spinner ItemSelected Listener cultureSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = cultureAdopter.GetItem(e.Position); culturePosition = e.Position; if (selectedItem.Equals("United States")) { currentCulture = new CultureInfo("en-us"); } else if (selectedItem.Equals("United Kingdom")) { currentCulture = new CultureInfo("en-GB"); } else if (selectedItem.Equals("Japan")) { currentCulture = new CultureInfo("ja-JP"); } else if (selectedItem.Equals("France")) { currentCulture = new CultureInfo("fr-FR"); } else if (selectedItem.Equals("Italy")) { currentCulture = new CultureInfo("it-IT"); } if (isMobile) { textMask.CurrentCulture = currentCulture; } else { tabMask.CurrentCulture = currentCulture; tabMask.OnApplyChanges(); } }; if (isMobile) { TextView spaceText = new TextView(context); propertylayout.AddView(spaceText); propertylayout.AddView(cultureLabel); //AdjLabel TextView adjLabel2 = new TextView(context); adjLabel2.SetHeight(14); adjLabel2.SetPadding(0, 0, 0, 20); propertylayout.AddView(adjLabel2); cultureSpinner.SetPadding(0, 0, 0, 0); propertylayout.AddView(cultureSpinner); } else { tabMask.OnApplyChanges(); LinearLayout cultureLayout = new LinearLayout(context); cultureLayout.Orientation = Android.Widget.Orientation.Horizontal; cultureLayout.AddView(cultureLabel); LinearLayout.LayoutParams cultureSpinnerLayout = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); cultureSpinnerLayout.SetMargins(220, 0, 65, 0); cultureLayout.AddView(cultureSpinner,cultureSpinnerLayout); tabMask.ProprtyOptionsLayout.AddView(cultureLayout); TextView spaceText3 = new TextView(context); spaceText3.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); tabMask.ProprtyOptionsLayout.AddView(spaceText3); } } /// <summary> /// Add the close button property in property window. /// </summary> /// <param name="context">It is context</param> /// <param name="propertylayout">it is a property layout</param> /// <param name="isMobile">It will enable when deploy in mobile</param> internal void CloseButtonVisibilityLayout(Context context, LinearLayout propertylayout, bool isMobile) { TextView visibilityLabel = new TextView(context); visibilityLabel.TextSize = 20; visibilityLabel.Text = "Clear Button Visibility"; //visibility Spinner Spinner visibilitySpinner = new Spinner(context, SpinnerMode.Dialog); visibilitySpinner.SetGravity(GravityFlags.Left); //visibility List List<String> visibilityList = new List<String>(); visibilityList.Add("Never"); visibilityList.Add("While Editing"); ArrayAdapter<String> visibilityAdopter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, visibilityList); visibilityAdopter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); visibilitySpinner.Adapter = visibilityAdopter; visibilitySpinner.SetSelection(visibilityPosition); //visibility Spinner ItemSelected Listener visibilitySpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = visibilityAdopter.GetItem(e.Position); visibilityPosition = e.Position; if (selectedItem.Equals("Never")) { clearButtonVisibility = ClearButtonVisibilityMode.Never; } if (selectedItem.Equals("While Editing")) { clearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; } if (isMobile) { textMask.ClearButtonVisibility = clearButtonVisibility; } else { tabMask.ClearButtonVisibility = clearButtonVisibility; tabMask.OnApplyChanges(); } }; if (isMobile) { TextView spaceText = new TextView(context); propertylayout.AddView(spaceText); propertylayout.AddView(visibilityLabel); //AdjLabel TextView adjLabel2 = new TextView(context); adjLabel2.SetHeight(14); adjLabel2.SetPadding(0, 0, 0, 20); propertylayout.AddView(adjLabel2); visibilitySpinner.SetPadding(0, 0, 0, 20); propertylayout.AddView(visibilitySpinner); } else { LinearLayout visibilityLayout = new LinearLayout(context); visibilityLayout.Orientation = Android.Widget.Orientation.Horizontal; visibilityLayout.AddView(visibilityLabel); LinearLayout.LayoutParams visibilitySpinnerLayout = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); visibilitySpinnerLayout.SetMargins(160, 0, 70, 0); visibilityLayout.AddView(visibilitySpinner, visibilitySpinnerLayout); tabMask.ProprtyOptionsLayout.AddView(visibilityLayout); TextView spaceText2 = new TextView(context); spaceText2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); tabMask.ProprtyOptionsLayout.AddView(spaceText2); } } internal void HideLayout(Context context, LinearLayout propertylayout, bool isMobile) { TextView hidePromtText = new TextView(context); hidePromtText.Text = "Hide Prompt On Leave"; hidePromtText.Gravity = GravityFlags.Center; hidePromtText.TextSize = 20; Switch hidePromptSwitch = new Switch(context); hidePromptSwitch.Checked = ishidePrompt; hidePromptSwitch.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { ishidePrompt = eve.IsChecked; if (isMobile) { textMask.HidePrompt = eve.IsChecked; } else { tabMask.HidePrompt = eve.IsChecked; tabMask.OnApplyChanges(); } }; LinearLayout.LayoutParams hidePromptSwitchParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); if(SfMaskedEditText.IsTabletDevice(context)) hidePromptSwitchParams.SetMargins(0, 0,110, 0); else hidePromptSwitchParams.SetMargins(0, 10, 0, 0); LinearLayout hidePromptLayout = new LinearLayout(context); hidePromptLayout.AddView(hidePromtText); hidePromptLayout.AddView(hidePromptSwitch, hidePromptSwitchParams); hidePromptLayout.Orientation = Orientation.Horizontal; if (isMobile) { TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); propertylayout.AddView(hidePromptLayout); TextView textSpacing1 = new TextView(context); propertylayout.AddView(textSpacing1); propertylayout.SetPadding(5, 0, 5, 0); } else { tabMask.OnApplyChanges(); tabMask.ProprtyOptionsLayout.AddView(hidePromptLayout); TextView spaceText4 = new TextView(context); spaceText4.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); tabMask.ProprtyOptionsLayout.AddView(spaceText4); } } internal void PromptLayout(Context context, LinearLayout propertylayout, bool isMobile) { TextView promptLabel = new TextView(context); promptLabel.TextSize = 20; promptLabel.Text = "Prompt Character"; //prompt Spinner Spinner promptSpinner = new Spinner(context, SpinnerMode.Dialog); promptSpinner.SetGravity(GravityFlags.Left); //prompt List List<char> promptList = new List<char>(); promptList.Add('_'); promptList.Add('*'); promptList.Add('~'); //prompt Adapter ArrayAdapter<char> promptAdopter = new ArrayAdapter<char>(context, Android.Resource.Layout.SimpleSpinnerItem, promptList); promptAdopter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); promptSpinner.Adapter = promptAdopter; promptSpinner.SetSelection(promptPosition); //prompt Spinner ItemSelected Listener promptSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { promptPosition = e.Position; char prompt = promptAdopter.GetItem(e.Position); if (isMobile) textMask.CurrentPrompt = prompt; else { tabMask.CurrentPrompt = prompt; tabMask.OnApplyChanges(); } }; LinearLayout.LayoutParams promptspinnerLayout = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); if (SfMaskedEditText.IsTabletDevice(context)) promptspinnerLayout.SetMargins(120, 0,90, 0); else promptspinnerLayout.SetMargins(200, 0, 0, 0); LinearLayout promptLayout = new LinearLayout(context); promptLayout.AddView(promptLabel); promptLayout.AddView(promptSpinner, promptspinnerLayout); promptLayout.Orientation = Orientation.Horizontal; if (isMobile) propertylayout.AddView(promptLayout); else { tabMask.OnApplyChanges(); tabMask.ProprtyOptionsLayout.AddView(promptLayout); } } } }<file_sep>/Forms/RichTextEditor/RichTextEditor.Android/PhotoPickerService.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using SampleBrowser.SfRichTextEditor.Droid; using SampleBrowser.SfRichTextEditor.Samples; using Xamarin.Forms; #if COMMONSB using MainActivity = SampleBrowser.Droid.MainActivity; #endif [assembly: Dependency(typeof(PhotoPickerService))] namespace SampleBrowser.SfRichTextEditor.Droid { public class PhotoPickerService : IPhotoPickerService { public Task<Stream> GetImageStreamAsync() { // Define the Intent for getting images Intent intent = new Intent(); intent.SetType("image/*"); intent.SetAction(Intent.ActionGetContent); // Start the picture-picker activity (resumes in MainActivity.cs) MainActivity.Instance.StartActivityForResult( Intent.CreateChooser(intent, "Select Picture"), MainActivity.PickImageId); // Save the TaskCompletionSource object as a MainActivity property MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<Stream>(); // Return Task object return MainActivity.Instance.PickImageTaskCompletionSource.Task; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/ContextMenu/ContextMenuBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ContextMenuBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.GridCommon.ScrollAxis; using Syncfusion.SfDataGrid.XForms; using Syncfusion.XForms.PopupLayout; using Xamarin.Forms; /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the ContextMenu samples /// </summary> public class ContextMenuBehavior : Behavior<SampleView> { #region Fields [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.XForms.PopupLayout.SfPopupLayout popupLayout; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SortingViewModel viewModel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Label sortAscendingLabel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Image sortAscendingImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Label sortDescendingLabel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Image sortDescendingImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Label groupingLabel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Image groupingImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Image clearGroupingImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Image clearSortingImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Label clearGroupingLabel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Label clearSortingLabel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string currentColumn; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private BoxView verticalBoxview; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private BoxView horizontalBoxview; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Grid myGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Grid transparent; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Grid customView; #endregion #region constructor /// <summary> /// Initializes a new instance of the ContextMenuBehavior class. /// </summary> public ContextMenuBehavior() { } #endregion #region Override /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of bindAble</param> protected async override void OnAttachedTo(SampleView bindAble) { this.dataGrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.dataGrid.GridLongPressed += this.DataGrid_GridLongPressed; this.viewModel = bindAble.FindByName<SortingViewModel>("viewModel"); this.popupLayout = bindAble.FindByName<Syncfusion.XForms.PopupLayout.SfPopupLayout>("popUpLayout"); this.popupLayout.PopupView.AnimationMode = AnimationMode.Fade; this.popupLayout.PopupView.AnimationDuration = 100; this.popupLayout.PopupView.ShowCloseButton = false; this.popupLayout.PopupView.ShowFooter = false; this.popupLayout.PopupView.ShowHeader = false; this.popupLayout.PopupView.HeightRequest = 195; if (Device.Idiom == TargetIdiom.Phone) { this.popupLayout.PopupView.WidthRequest = 190; } else { this.popupLayout.PopupView.WidthRequest = 210; } this.popupLayout.PopupView.ContentTemplate = new DataTemplate(() => { return PopupViewInitialization(); }); var assembly = Assembly.GetAssembly(Application.Current.GetType()); await Task.Delay(200); this.customView = bindAble.FindByName<Grid>("customLayout"); this.transparent = bindAble.FindByName<Grid>("transparent"); this.myGrid = new Grid(); this.myGrid.VerticalOptions = LayoutOptions.FillAndExpand; this.myGrid.HorizontalOptions = LayoutOptions.FillAndExpand; this.myGrid.RowDefinitions = new RowDefinitionCollection { new RowDefinition { Height = new GridLength(1.1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, }; this.myGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); this.myGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1.8, GridUnitType.Star) }); this.myGrid.Children.Add( new Image() { Opacity = 1.0, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Source = "ContextMenuIllustration.png" }, 1, 1); this.myGrid.BackgroundColor = Color.Transparent; this.myGrid.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Collapse) }); this.customView.Children.Add(this.myGrid); base.OnAttachedTo(bindAble); } #endregion #region override /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type of bindAble parameter</param> protected override void OnDetachingFrom(SampleView bindAble) { this.dataGrid.GridLongPressed -= this.DataGrid_GridLongPressed; this.sortAscendingLabel = null; this.sortAscendingImage = null; this.sortDescendingLabel = null; this.sortDescendingImage = null; this.groupingLabel = null; this.groupingImage = null; this.clearGroupingImage = null; this.clearSortingImage = null; this.clearGroupingLabel = null; this.clearSortingLabel = null; this.verticalBoxview = null; this.horizontalBoxview = null; base.OnDetachingFrom(bindAble); } #endregion #region methods /// <summary> /// Method for removing the child element of CustomView /// </summary> private void Collapse() { this.myGrid.IsEnabled = false; this.myGrid.IsVisible = false; this.transparent.IsVisible = false; this.customView.Children.Remove(this.myGrid); this.customView.Children.Remove(this.transparent); } /// <summary> /// Method that initializes a PopUpView /// </summary> /// <returns>returns the popupContent which was added</returns> private Grid PopupViewInitialization() { Grid popupcontent = new Grid(); popupcontent.Padding = new Thickness(4, 2, 5, 2); popupcontent.BackgroundColor = Color.White; popupcontent.HorizontalOptions = LayoutOptions.FillAndExpand; popupcontent.VerticalOptions = LayoutOptions.FillAndExpand; popupcontent.RowDefinitions.Add(new RowDefinition { Height = 30 }); popupcontent.RowDefinitions.Add(new RowDefinition { Height = 30 }); popupcontent.RowDefinitions.Add(new RowDefinition { Height = 30 }); popupcontent.RowDefinitions.Add(new RowDefinition { Height = 1 }); popupcontent.RowDefinitions.Add(new RowDefinition { Height = 30 }); popupcontent.RowDefinitions.Add(new RowDefinition { Height = 30 }); popupcontent.ColumnDefinitions.Add(new ColumnDefinition { Width = 20 }); popupcontent.ColumnDefinitions.Add(new ColumnDefinition { Width = 140 }); this.verticalBoxview = new BoxView(); this.verticalBoxview.BackgroundColor = Color.Gray; this.verticalBoxview.WidthRequest = 3; this.verticalBoxview.Opacity = 0.5f; this.horizontalBoxview = new BoxView(); this.horizontalBoxview.BackgroundColor = Color.Gray; this.horizontalBoxview.WidthRequest = 3; this.horizontalBoxview.Opacity = 0.5f; this.horizontalBoxview.Margin = new Thickness(5, 0, 0, 0); this.sortAscendingLabel = this.CreateLabel("Sort Ascending"); this.sortDescendingLabel = this.CreateLabel("Sort Descending"); this.groupingLabel = this.CreateLabel("Group this Column"); this.clearGroupingLabel = this.CreateLabel("Clear Grouping"); this.clearSortingLabel = this.CreateLabel("Clear Sorting"); if (this.dataGrid.GroupColumnDescriptions.Count > 0) { this.clearGroupingLabel.Opacity = 1; } else { this.clearGroupingLabel.Opacity = 0.5f; } if (this.dataGrid.SortColumnDescriptions.Count > 0 || this.dataGrid.GroupColumnDescriptions.Count > 0) { this.clearSortingLabel.Opacity = 1; } else { this.clearSortingLabel.Opacity = 0.5f; } this.sortAscendingImage = this.CreateImage("\ue71e"); this.sortDescendingImage = this.CreateImage("\ue729"); this.groupingImage = this.CreateImage("\ue75c"); this.clearSortingImage = this.CreateImage("\ue75d"); this.clearGroupingImage = this.CreateImage("\ue70d"); if (this.dataGrid.GroupColumnDescriptions.Count > 0) { this.clearGroupingImage.Opacity = 1; } else { this.clearGroupingImage.Opacity = 0.5f; } if (this.dataGrid.SortColumnDescriptions.Count > 0 || this.dataGrid.GroupColumnDescriptions.Count > 0) { this.clearSortingImage.Opacity = 1; } else { this.clearSortingImage.Opacity = 0.5f; } this.AddGestureRecognizer(); popupcontent.Children.Add(this.sortAscendingImage, 0, 0); popupcontent.Children.Add(this.sortAscendingLabel, 1, 0); popupcontent.Children.Add(this.sortDescendingImage, 0, 1); popupcontent.Children.Add(this.sortDescendingLabel, 1, 1); popupcontent.Children.Add(this.clearSortingImage, 0, 2); popupcontent.Children.Add(this.clearSortingLabel, 1, 2); popupcontent.Children.Add(this.horizontalBoxview, 0, 3); popupcontent.Children.Add(this.groupingImage, 0, 4); popupcontent.Children.Add(this.groupingLabel, 1, 4); popupcontent.Children.Add(this.clearGroupingImage, 0, 5); popupcontent.Children.Add(this.clearGroupingLabel, 1, 5); Grid.SetColumnSpan(this.horizontalBoxview, 3); return popupcontent; } /// <summary> /// Fired when grid is long pressed /// </summary> /// <param name="sender">DataGrid_GridLongPressed event sender</param> /// <param name="e">DataGrid_GridLongPressed args e</param> private void DataGrid_GridLongPressed(object sender, GridLongPressedEventArgs e) { this.currentColumn = this.dataGrid.Columns[e.RowColumnIndex.ColumnIndex].MappingName; this.popupLayout.ShowAtTouchPoint(); } /// <summary> /// Clear the sort column descriptions in DataGrid. /// </summary> private void Clear_Sorting() { if (this.dataGrid.SortColumnDescriptions.Count > 0) { if (this.dataGrid.GroupColumnDescriptions.Any(x => x.ColumnName == this.currentColumn) && this.dataGrid.SortColumnDescriptions.Any(x => x.ColumnName == this.currentColumn)) { this.dataGrid.SortColumnDescriptions.Clear(); } else { this.dataGrid.SortColumnDescriptions.Clear(); } } this.popupLayout.IsOpen = false; } /// <summary> /// Clear the group column descriptions in DataGrid /// </summary> private void Clear_Grouping() { if (this.dataGrid.GroupColumnDescriptions.Count > 0) { if (this.dataGrid.SortColumnDescriptions.Any(x => x.ColumnName == this.currentColumn) && this.dataGrid.GroupColumnDescriptions.Any(x => x.ColumnName == this.currentColumn)) { this.dataGrid.GroupColumnDescriptions.Clear(); this.dataGrid.SortColumnDescriptions.Clear(); } else { this.dataGrid.GroupColumnDescriptions.Clear(); } } this.popupLayout.IsOpen = false; } /// <summary> /// Sorts the data in ascending order /// </summary> private void Sorting_Ascending() { this.dataGrid.SortColumnDescriptions.Clear(); this.dataGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = this.currentColumn, SortDirection = Syncfusion.Data.ListSortDirection.Ascending }); this.clearSortingImage.Opacity = 0.5f; this.clearSortingLabel.Opacity = 0.5f; this.popupLayout.IsOpen = false; } /// <summary> /// Sorts the data in descending order /// </summary> private void Sorting_Descending() { this.dataGrid.SortColumnDescriptions.Clear(); this.dataGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = this.currentColumn, SortDirection = Syncfusion.Data.ListSortDirection.Descending }); this.popupLayout.IsOpen = false; } /// <summary> /// Adds a group column description to the DataGrid /// </summary> private void GroupingColumn() { this.dataGrid.GroupColumnDescriptions.Clear(); this.dataGrid.GroupColumnDescriptions.Add(new GroupColumnDescription() { ColumnName = this.currentColumn }); this.popupLayout.IsOpen = false; } /// <summary> /// Used to create Label with desired properties /// </summary> /// <param name="text">string type text</param> /// <returns>returns a created label</returns> private Label CreateLabel(string text) { return new Label() { Text = text, TextColor = Color.FromHex("#000000"), FontSize = 16, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center, Opacity = 87, }; } /// <summary> /// Used to create Image with desired properties /// </summary> /// <param name="path">string type path</param> /// <returns>returns a created Image</returns> private Image CreateImage(string path) { return new Image() { Source = new FontImageSource { Glyph = path, FontFamily = (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.macOS) ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.FromRgb(88, 88, 89), }, WidthRequest = 20, HeightRequest = 20, HorizontalOptions = LayoutOptions.CenterAndExpand, VerticalOptions = LayoutOptions.CenterAndExpand, }; } /// <summary> /// Method for adding TapGesture /// </summary> private void AddGestureRecognizer() { this.sortAscendingImage.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Sorting_Ascending) }); this.sortAscendingLabel.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Sorting_Ascending) }); this.sortDescendingLabel.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Sorting_Descending) }); this.sortDescendingImage.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Sorting_Descending) }); this.groupingLabel.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.GroupingColumn) }); this.groupingImage.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.GroupingColumn) }); this.clearGroupingImage.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Clear_Grouping) }); this.clearGroupingLabel.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Clear_Grouping) }); this.clearSortingImage.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Clear_Sorting) }); this.clearSortingLabel.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Clear_Sorting) }); } #endregion } } <file_sep>/Forms/Expander/Expander/Samples/GettingStarted/ViewModel/InvoiceViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using Xamarin.Forms.Internals; namespace SampleBrowser.SfExpander { [Preserve(AllMembers = true)] public class InvoiceViewModel : INotifyPropertyChanged { #region Properties public ObservableCollection<InvoiceItem> ItemInfo { get; set; } #endregion #region Constructor public InvoiceViewModel() { ItemInfo = new ObservableCollection<InvoiceItem>(); for (int i = 0; i < items.Count(); i++) { var invoiceItem = new InvoiceItem(); invoiceItem.ItemName = items[i]; invoiceItem.ItemPrice = prices[i]; ItemInfo.Add(invoiceItem); } } #endregion #region Fields string[] items = new string[] { "2018 Subaru Outback", "All-Weather Mats", "Door Edge Guard Kit", "Rear Bumper Cover", "Wheel Locks", "Gas Full Tank" }; string[] prices = new string[] { "$35,705.00", "$101.00", "$162.00", "$107.00", "$81.00", "$64.00" }; #endregion #region Interface Member public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/AutoRowHeight.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using CoreGraphics; namespace SampleBrowser { public class AutoRowHeight:SampleView { #region Fields SfDataGrid SfGrid; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public AutoRowHeight () { this.SfGrid = new SfDataGrid (); this.SfGrid.AllowSorting = false; this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.AllowTriStateSorting = false; this.SfGrid.AlternationCount = 2; this.SfGrid.ColumnSizer = ColumnSizer.None; this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; this.SfGrid.ItemsSource = new AutoRowHeightViewModel ().ReleaseInformation; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.QueryRowHeight += GridQueryRowHeight; if (!UserInterfaceIdiomIsPhone) { GridTextColumn sno = new GridTextColumn(); sno.MappingName = "SNo"; sno.HeaderText = "S.No"; sno.ColumnSizer = ColumnSizer.Auto; sno.HeaderTextAlignment = UITextAlignment.Center; sno.TextAlignment = UITextAlignment.Center; this.SfGrid.Columns.Insert(0, sno); this.SfGrid.ColumnSizer = ColumnSizer.Star; } this.AddSubview (SfGrid); } void GridAutoGenerateColumns (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "SNo") e.Cancel = true; if (e.Column.MappingName == "ReleaseVersion") { e.Column.LineBreakMode = UILineBreakMode.WordWrap; e.Column.HeaderText = "Release Version"; e.Column.TextAlignment = UITextAlignment.Left | UITextAlignment.Center; e.Column.HeaderTextMargin = new Thickness(8, 12, 8, 16); e.Column.TextMargin = new Thickness(8, 12, 8, 16); } else if (e.Column.MappingName == "Platform") { e.Column.HeaderText = "Platform"; e.Column.LineBreakMode = UILineBreakMode.WordWrap; e.Column.TextAlignment = UITextAlignment.Left ; e.Column.HeaderTextMargin = new Thickness(16, 12, 8, 12); e.Column.TextMargin = new Thickness(16, 12, 8, 12); } else if (e.Column.MappingName == "Features") { e.Column.HeaderText = "Feature"; e.Column.TextAlignment = UITextAlignment.Left; e.Column.LineBreakMode = UILineBreakMode.WordWrap; e.Column.HeaderTextMargin = new Thickness(8, 12, 8, 12); e.Column.TextMargin = new Thickness(8, 12, 8, 12); } else if (e.Column.MappingName == "Description") { e.Column.HeaderText = "Description"; e.Column.TextAlignment = UITextAlignment.Left; e.Column.LineBreakMode = UILineBreakMode.WordWrap; e.Column.HeaderTextMargin = new Thickness(8, 12, 8, 12); e.Column.TextMargin = new Thickness(8, 12, 8, 12); } } void GridQueryRowHeight (object sender, QueryRowHeightEventArgs e) { if (e.RowIndex > 0) { double height = SfDataGridHelpers.GetRowHeight(SfGrid, e.RowIndex); e.Height = height; e.Handled = true; } } public override void LayoutSubviews () { this.SfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews (); } protected override void Dispose(bool disposing) { SfGrid.Dispose(); base.Dispose(disposing); } } } <file_sep>/Forms/TreeView/TreeView/Samples/LoadOnDemand/Model/MusicInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public class MusicInfo : INotifyPropertyChanged { #region Fields public string itemName; public int id; public bool hasChildNodes; #endregion #region Properties public string ItemName { get { return itemName; } set { itemName = value; OnPropertyChanged("ItemName"); } } public int ID { get { return id; } set { id = value; OnPropertyChanged("ID"); } } public bool HasChildNodes { get { return hasChildNodes; } set { hasChildNodes = value; OnPropertyChanged("HasChildNodes"); } } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <file_sep>/Forms/PDF/PDF/Samples/Booklet/Booklet.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Parsing; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using System.Reflection; using SampleBrowser.Core; namespace SampleBrowser.PDF { public partial class Booklet : SampleView { public Booklet() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { //Load PDF document to stream. #if COMMONSB Stream docStream = typeof(Booklet).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.JavaScript Succinctly.pdf"); #else Stream docStream = typeof(Booklet).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.JavaScript Succinctly.pdf"); #endif //Load the PDF document into the loaded document object. PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream); float width = 1224; float height = 792; //Create a booklet form exisitng PDF document PdfDocument document = PdfBookletCreator.CreateBooklet(ldoc, new SizeF(width, height), true); MemoryStream stream = new MemoryStream(); //Save the PDF document document.Save(stream); //Close the PDF document document.Close(true); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Booklet.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("Booklet.pdf", "application/pdf", stream); } } } <file_sep>/Forms/GradientView/GradientView/Samples/GradientGettingStarted/GettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GettingStarted.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfGradientView { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.Buttons; using Syncfusion.XForms.Graphics; using Xamarin.Forms; using Xamarin.Forms.Xaml; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public partial class GettingStarted : SampleView { /// <summary> /// Gets or sets the selected chip index. /// </summary> private int chipSelectedIndex = 0; /// <summary> /// Gets or sets the linear gradient start point. /// </summary> private Point startPoint = new Point(0.5, 0); /// <summary> /// Gets or sets the linear gradient end point. /// </summary> private Point endPoint = new Point(0.5, 1); /// <summary> /// Gets or sets the rotation angle. /// </summary> private int rotationAngle = 0; public GettingStarted() { InitializeComponent(); gradientAngle.Text = "\xe702"; if (Device.RuntimePlatform == Device.UWP) { toggleButton.VisibleSegmentsCount = 1; } else { toggleButton.VisibleSegmentsCount = 2; } } /// <summary> /// Gradient background changes based on selected chip. /// </summary> /// <param name="sender">chip</param> /// <param name="e">event arguments</param> private void Chip1_Clicked(object sender, EventArgs e) { int selectedIndex = 0; var selectedChip = sender as SfChip; var viewModel = (chipControl.BindingContext as GettingStartedViewModel); for (int i = 0; i < chipControl.Items.Count; i++) { var chip = chipControl.Items[i]; if (chip == selectedChip) { chip.BorderColor = Color.White; chip.BorderWidth = 2; selectedIndex = i; } else { chip.BorderColor = Color.Transparent; chip.BorderWidth = 0; } } chipSelectedIndex = selectedIndex; if (toggleButton.SelectedIndex == 0) { SfLinearGradientBrush brush = viewModel.LinearGradientBrushes[chipSelectedIndex]; brush.StartPoint = startPoint; brush.EndPoint = endPoint; viewModel.BackgroundGradient = brush; } else { viewModel.BackgroundGradient = viewModel.RadialGradientBrushes[chipSelectedIndex]; } } /// <summary> /// Toggle between linear and radial gradient. /// </summary> /// <param name="sender">segmented control</param> /// <param name="e">event arguments</param> private void ToggleButton_SelectionChanged(object sender, Syncfusion.XForms.Buttons.SelectionChangedEventArgs e) { var viewModel = (this.BindingContext as GettingStartedViewModel); var chip = chipControl; if (e.Index == 0) { gradientAngle.Text = "\xe702"; SfLinearGradientBrush brush = viewModel.LinearGradientBrushes[chipSelectedIndex]; brush.StartPoint = startPoint; brush.EndPoint = endPoint; viewModel.BackgroundGradient = brush; } else { gradientAngle.Text = "\xe701"; viewModel.BackgroundGradient = viewModel.RadialGradientBrushes[chipSelectedIndex]; rotationAngle = 0; startPoint = new Point(0.5, 0); endPoint = new Point(0.5, 1); } } /// <summary> /// Change the gradient start and end point. /// </summary> /// <param name="sender">button</param> /// <param name="e">event arguments</param> private void GradientAngle_Clicked(object sender, EventArgs e) { var button = sender as SfButton; var linearGradient = (gradientView.BackgroundBrush as SfLinearGradientBrush); string fontText = string.Empty; if (linearGradient != null) { rotationAngle += 45; rotationAngle = rotationAngle > 315 ? 0 : rotationAngle; } else { fontText = (gradientAngle.Text == "\xe701") ? "\xe703" : "\xe701"; } switch (rotationAngle) { case 0: startPoint = new Point(0.5, 0); endPoint = new Point(0.5, 1); gradientAngle.Text = "\xe702"; break; case 45: startPoint = new Point(1, 0); endPoint = new Point(0, 1); gradientAngle.Text = "\xe704"; break; case 90: startPoint = new Point(1, 0.5); endPoint = new Point(0, 0.5); gradientAngle.Text = "\xe705"; break; case 135: startPoint = new Point(1, 1); endPoint = new Point(0, 0); gradientAngle.Text = "\xe700"; break; case 180: startPoint = new Point(0.5, 1); endPoint = new Point(0.5, 0); gradientAngle.Text = "\xe702"; break; case 225: startPoint = new Point(0, 1); endPoint = new Point(1, 0); gradientAngle.Text = "\xe704"; break; case 270: startPoint = new Point(0, 0.5); endPoint = new Point(1, 0.5); gradientAngle.Text = "\xe705"; break; case 315: startPoint = new Point(0, 0); endPoint = new Point(1, 1); gradientAngle.Text = "\xe700"; break; } if (linearGradient != null) { linearGradient.StartPoint = startPoint; linearGradient.EndPoint = endPoint; } else { gradientAngle.Text = string.IsNullOrEmpty(fontText) ? "\xe701" : fontText; var color1 = gradientView.BackgroundBrush.GradientStops[0].Color; var color2 = gradientView.BackgroundBrush.GradientStops[1].Color; gradientView.BackgroundBrush.GradientStops[0].Color = color2; gradientView.BackgroundBrush.GradientStops[1].Color = color1; } } /// <summary> /// Modifies the row height based on orientation. /// </summary> /// <param name="sender">grid</param> /// <param name="e">event arguments</param> private void Grid_SizeChanged(object sender, EventArgs e) { var grid = sender as Grid; if (grid.Width > 0 && grid.Height > 0) { if (grid.Width > grid.Height) { if (Device.Idiom == TargetIdiom.Phone) { grid.RowDefinitions[0].Height = new GridLength(2, GridUnitType.Star); grid.RowDefinitions[1].Height = new GridLength(2, GridUnitType.Star); } else { grid.RowDefinitions[0].Height = new GridLength(3, GridUnitType.Star); grid.RowDefinitions[1].Height = new GridLength(1, GridUnitType.Star); } } else { grid.RowDefinitions[0].Height = new GridLength(3, GridUnitType.Star); grid.RowDefinitions[1].Height = new GridLength(1, GridUnitType.Star); } } } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/Model/EmployeeInfoRespository.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace SampleBrowser { public class EmployeeInfoRespository { public EmployeeInfoRespository () { PopulateData (); } Random r = new Random (); Dictionary<string, string> loginID = new Dictionary<string, string> (); Dictionary<string, string> gender = new Dictionary<string, string> (); public ObservableCollection<Employee> GetEmployeesDetails (int count) { var employees = new ObservableCollection<Employee> (); for (var i = 1; i < count; i++) { employees.Add (GetEmployee (i)); } return employees; } public Employee GetEmployee (int i) { var name = employeeName [r.Next (employeeName.Count () - 1)]; return new Employee () { EmployeeID = 1000 + i, Name = name, ContactID = r.Next (1001, 2000), Gender = gender [name], Title = title [r.Next (title.Count () - 1)], BirthDate = new DateTime (r.Next (1975, 1985), r.Next (1, 12), r.Next (1, 28)), SickLeaveHours = r.Next (15, 70), Salary = new decimal (Math.Round (r.NextDouble () * 6000.5, 2)) }; } private void PopulateData () { gender.Add ("<NAME>", "Male"); gender.Add ("Phyll<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Male"); gender.Add ("<NAME>", "Female"); loginID.Add ("<NAME>", "sean2"); loginID.Add ("<NAME>", "phyllis0"); loginID.Add ("<NAME>", "marvin0"); loginID.Add ("<NAME>", "michael10"); loginID.Add ("<NAME>", "cecil0"); loginID.Add ("<NAME>", "oscar0"); loginID.Add ("<NAME>", "sandra1"); loginID.Add ("<NAME>", "selena0"); loginID.Add ("<NAME>", "emilio0"); loginID.Add ("<NAME>", "maxwell0"); loginID.Add ("<NAME>", "mae0"); loginID.Add ("<NAME>", "ramona0"); loginID.Add ("<NAME>", "sabria0"); loginID.Add ("<NAME>", "hannah0"); loginID.Add ("<NAME>", "kyley0"); loginID.Add ("<NAME>", "tom1"); loginID.Add ("<NAME>", "thomas1"); loginID.Add ("<NAME>", "john6"); loginID.Add ("<NAME>", "chris3"); loginID.Add ("<NAME>", "teresa0"); loginID.Add ("<NAME>", "john7"); loginID.Add ("<NAME>", "robert2"); loginID.Add ("<NAME>", "stephen1"); loginID.Add ("<NAME>", "phillip0"); loginID.Add ("<NAME>", "gustavo0"); loginID.Add ("<NAME>", "catherine0"); loginID.Add ("<NAME>", "kim2"); loginID.Add ("<NAME>", "humberto0"); loginID.Add ("<NAME>", "pilar1"); loginID.Add ("<NAME>", "frances0"); loginID.Add ("<NAME>", "margaret0"); loginID.Add ("<NAME>", "carla0"); loginID.Add ("<NAME>", "jay1"); loginID.Add ("<NAME>", "ronald0"); loginID.Add ("<NAME>", "samuel0"); loginID.Add ("<NAME>", "james2"); loginID.Add ("<NAME>", "robert1"); loginID.Add ("<NAME>", "françois1"); loginID.Add ("<NAME>", "kim3"); loginID.Add ("<NAME>", "lili0"); loginID.Add ("<NAME>", "amy1"); loginID.Add ("<NAME>", "anna0"); loginID.Add ("<NAME>", "milton0"); loginID.Add ("<NAME>", "paul2"); loginID.Add ("<NAME>", "gregory0"); loginID.Add ("<NAME>", "jphillip0"); loginID.Add ("<NAME>", "michelle0"); loginID.Add ("<NAME>", "daniel0"); loginID.Add ("<NAME>", "cory0"); loginID.Add ("<NAME>", "james3"); } private string[] title = new string[] { "Marketing Assistant", "Engineering Manager", "Senior Tool Designer", "Tool Designer", "Marketing Manager", "Production Supervisor - WC60", "Production Technician - WC10", "Design Engineer", "Production Technician - WC10", "Design Engineer", "Vice President of Engineering", "Production Technician - WC10", "Production Supervisor - WC50", "Production Technician - WC10", "Production Supervisor - WC60", "Production Technician - WC10", "Production Supervisor - WC60", "Production Technician - WC10", "Production Technician - WC30", "Production Control Manager", "Production Technician - WC45", "Production Technician - WC45", "Production Technician - WC30", "Production Supervisor - WC10", "Production Technician - WC20", "Production Technician - WC40", "Network Administrator", "Production Technician - WC50", "Human Resources Manager", "Production Technician - WC40", "Production Technician - WC30", "Production Technician - WC30", "Stocker", "Shipping and Receiving Clerk", "Production Technician - WC50", "Production Technician - WC60", "Production Supervisor - WC50", "Production Technician - WC20", "Production Technician - WC45", "Quality Assurance Supervisor", "Information Services Manager", "Production Technician - WC50", "Master Scheduler", "Production Technician - WC40", "Marketing Specialist", "Recruiter", "Production Technician - WC50", "Maintenance Supervisor", "Production Technician - WC30", }; private string[] employeeName = new string[] { "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" }; } } <file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/ListViewPullToRefresh/Model/BlogsInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "BlogsInfoRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using Xamarin.Forms; /// <summary> /// A class used to assign collection values for a Model properties /// </summary> public class BlogsInfoRepository { #region BlogsInfo [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] internal string[] BlogsTitle = { "Syncfusion is Attending dotnet Cologne and Magdeburger Dev Days Conferences", "Syncfusion Celebrates World Book Day", "What do e-books mean for developers?", "Q&A from “File-Format Manipulation in Xamarin.Forms” Webinar", "Syncfusion Sponsoring Global Azure Bootcamp Chennai", "Intel Forms Dedicated AI Group", "Upcoming Webinar: File-Format Manipulation in Xamarin.Forms, April 18", "Processing More Data in Less Time", "Syncfusion Sponsoring Xamarin Dev Days in Irving, Texas", "Syncfusion Presents at C# Corner Annual Conference", "Syncfusion Attending NG-CONF", "Visual Studio 2017 + Xamarin + Syncfusion Webinar Q&A", "Guest Blog: Moving from Emacs to Visual Studio", "Webinar on How Syncfusion Extends VS-Xamarin Integration", "Microsoft Forges Ahead with AI Advancements", "Syncfusion Celebrates Sim-Shipping Essential Studio with Visual Studio 2017", "Visual Studio: A Future and a Past", "Syncfusion to host Xamarin Dev Days Raleigh - June 10th 2017", "Syncfusion Xamarin Charts Webinar Q&A", "Guest Blog: Forms with Elm and Essential Studio" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.internal field does not need documentation")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] internal string[] BlogsCategory = { "Syncfusion", "Syncfusion", "E-book, Succinctly Series", "webinar, Xamarin", "Azure, Code Camp", "Deep Learning", "C#, DocIO, Mobile", "BI, Big Data", "Code Camp, Xamarin", "C#", "JavaScript, Web", "Essential Studio, Mobile", "Succinctly Series", "Mobile, Xamarin", "E-book, Microsoft", "Syncfusion", "Succinctly Series", "Code Camp, Xamarin", "Xamarin", "Syncfusion" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.internal field does not need documentation")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] internal string[] BlogsAuthers = { "<NAME>", "<EMAIL>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "Syncfusion Guest Blogger", "Tres Watkins", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "Syncfusion Guest Blogger" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.internal field does not need documentation")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] internal string[] BlogsReadMoreInfo = { "Syncfusion is always pleased to have the opportunity to talk to you in person." + " This month, we’re looking forward to seeing those of you who are attending either the dotnet Cologne conference," + " May 4–5, or the Magdeburger Developer Days Conference, May 10–11, in Germany. \n\nWe’re proud to be a silver" + " sponsor of the dotnet Cologne conference and a gold sponsor of the Magdeburger Developer Days Conference." + " We will have a booth at both with three of our developers and our director of sales ready to answer any questions" + " and give away prizes. If you’re planning to attend either conference, be sure to stop by and say hello to George, " + "Jayakrishnan, Soundara, and Christian!", "Sunday, April 23, was World Book Day, a celebration of reading and publishing designated by UNESCO." + " Syncfusion is proud to be contributing to the knowledge of the world with our Succinctly series, helping developers " + "get a quick start on new technologies for free. We’ve published 113 e-books, and counting!\n\nNot all of us are developers," + " though, and often our tastes in books span many genres, so we asked our employees, " + "“What are your favorite books and authors?” And they responded!\n\nOur favorite genre was science fiction," + " closely followed by fantasy, sometimes loved by the same person.", "April 23 is World Book Day, an international celebration of books and authors established by " + "UNESCO to recognize the immeasurable contributions to civilization that books have made, and to encourage " + "readership around the world, especially in youngsters.\n\nBooks play a critical role in what we do at Syncfusion, " + "and not just when we consult our in-office library of mostly technical references. " + "The Succinctly series of e-books we produce is one way we contribute to the growth and enrichment of the development " + "community at large. In about 100 pages, experienced developers can glean the information they " + "need to get started with an unfamiliar technology quickly.", "On April 18, Syncfusion hosted a webinar on file-format manipulation in Xamarin.Forms. " + "Product solutions specialist <NAME> gave a thorough overview of the subject. In this blog post, " + "we’d like to address the questions we received from the audience.\n\nWhy parse a string to set a date value?\nIt was " + "done this way in this sample, but XlsIO just requires a DateTime object, so you can initialize it as desired." + "\n\nDo developers use OData RESTful services to populate content in layouts created using the file, creation, " + "layout, and handling capabilities you showed today?\nYes, this will work.", "Syncfusion is happy to support the Global Azure Bootcamp in Chennai this Saturday, April 22, 2017." + "\n\nThis one-day event will feature learning opportunities including sessions about Microsoft Azure, " + "talks with experts, and hands-on labs. Global Azure Bootcamps started in April 2013 in more than 134 locations " + "around the world.These events expanded to 183 in 2015 and continue to grow, with more than 250 events planned for this Saturday!\n\nSyncfusion will provide some free licenses for the raffle. Winners will receive a complimentary one-year license of Essential Studio Enterprise Edition. This includes more than 800 components for web, desktop, and mobile development, as well as the Big Data, Dashboard, Reporting, and Data Integration Platforms.", "We post news about AI advancements on a regular basis on this blog, but how can we resist when so many " + "companies are exploring the power of this field? The latest company to fully invest in the trend towards " + "AI-powered technology is Intel. In late March, they announced the formation of the Intel Artificial Intelligence" + " Products Group (AIPG), an organization that intends to consolidate the company’s AI efforts across all its " + "divisions.\n\nThis move towards unifying AI projects isn’t simply a pivot towards the future; Intel has invested " + "heavily in AI development. Over the past two years, Intel has acquired an AI-processor startup, a computer-vision " + "developer, a driverless car developer, and an FPGA manufacturer. Each of these acquisitions either gives Intel an" + " entry point to specific AI development targets or provides a technology to support AI development.", "On Tuesday, April 18, join product solutions specialist <NAME> as he explores the extensive capabilities of " + "Syncfusion’s file-format manipulation libraries for Xamarin.Forms.\n\nSyncfusion has long been a leader of building" + " powerful, dependency-free file-format libraries for working with Excel, Word, and PDF documents, and now, even " + "PowerPoint presentations. These libraries are used across a spectrum of business scenarios, but are most often " + "used to create richly formatted reports. Combining these libraries with cross-platform mobile development enabled " + "by Xamarin.Forms can greatly simplify your document needs within your mobile apps, whether it involves file " + "conversion, filling templates, importing data, or generating documents from scratch.", "Want to see how fast we can summarize a billion rows of data? Don’t blink. It takes just six seconds.\n\nRemember " + "the good ol’ days, before Apache Spark 2.0, when life was simpler and processing 173 GB of data took a whole 30" + " seconds? You actually had time to sip your coffee before the bar charts rendered.\n\nThose days are gone. In this" + " post-Spark 2.0 world, using the combined force of the Syncfusion Big Data Platform and the Dashboard Platform, " + "you can process and visualize that same amount of data within six seconds. Advances in Apache Spark have increased" + " Syncfusion’s data processing speed by a factor of five to ten times, generally speaking.", "Syncfusion is sponsoring the Xamarin Dev Days event in Irving, Texas on April 15th. We are delighted to be able to " + "support this regional community of Xamarin developers. Each attendee will get a free license to " + "Syncfusion Essential Studio for Xamarin, some swag, and some great learning!\n\nOther ways we support the " + "developer community at large is through free webinars like “What’s New in Xamarin Forms” and " + "“Fall Madly in Love with 10 Xamarin Charts!”\n\nIf you are in the Irving, Texas area and would like to sign up, " + "go to https://ti.to/xamarin/dev-days-irving-2017/en and click Register. ", "This weekend in Delhi, India, Syncfusion is proud to be one of the platinum sponsors of the C# Corner " + "Annual Conference 2017 at the Leela Ambience Convention Hotel. At the long sold-out conference, " + "attendees will benefit from over 30 speakers on over 35 technologies. Along with thousands of others," + " several of our developers will be attending to learn from other experts and share their own expertise." + "\n\nFor anyone in attendance interested in mobile development, Syncfusion’s own Harikrishna Natarajan will " + "be giving a presentation entitled Creating Real World User Interfaces with Xamarin.Forms that we hope you will " + "find very informative.", "In just one week, ng-conf, the world’s original Angular conference, will be held in Salt Lake City. The event " + "boasts a stacked lineup of sessions and workshops showcasing the great tooling that Angular provides. " + "Syncfusion is proud to be a silver sponsor for the event, and our very own <NAME> and <NAME>" + " will be attending. If you’re going, drop by the Syncfusion booth and say hi!\n\nRemember, Syncfusion has more " + "than 80 UI components for Angular app development, and recently published a free new e-book on Angular, Angular 2 " + "Succinctly. Keep an eye on our Facebook and Twitter feeds next week to see what’s happening at ng-conf," + " and let us know if you’ll be there!", "On March 21, 2017, <NAME>, product solutions specialist for Syncfusion, presented the webinar Visual Studio " + "+ Xamarin + Syncfusion­—a primer on how to use Xamarin and Visual Studio in conjunction with Syncfusion components" + ".\n\nDid you miss the webinar? Watch the recording here and download the sample Aaron used.\n\nThe following " + "section contains all the questions asked by attendees during the webinar with answers provided by Aaron " + "and additional Syncfusion staff. ", "In college, I did everything in UNIX. On UNIX, everything was centered around programming. Of course, " + "you probably had to be a programmer to get anything done or at least appreciate it. The big debate of the day" + " was the merits of vi vs emacs. After much deliberation, I settled on emacs. Despite its power," + " vi was just a bit too cryptic for me. Emacs was very powerful, still quite cryptic, but had nearly " + "endless options for customization.\n\nYou could start up emacs and stay there all day. It didn’t matter" + " whether you wanted to run a command shell, query a database, read email, or even browse the web," + " there was no reason to leave emacs. Regardless of the type of file you were editing, " + "there was a custom mode available to help with editing that file. Whether it was the password file," + " Fortran, lisp, C, C++, HTML, SQL, Eiffel, or something else, " + "there was a language-specific editor mode ready to help with syntax highlighting, indention support, " + "matching parenthesis, and more", "Xamarin is to development what the Rosetta Stone was to Egyptologists—a bridge to unknown languages, " + "or at least to the languages of Objective-C and Swift, which may not be known to C# developers. " + "Now, with the integration of Xamarin and Visual Studio, " + ".NET developers can use C# to build native apps for Android and iOS." + "\n\nSyncfusion adds a lot of power to the Microsoft-Xamarin mix by offering Essential Studio for Xamarin. " + "Tomorrow’s webinar, Visual Studio 2017 + Xamarin + Syncfusion, presented by <NAME> at 11:00 a.m. EDT, " + "will demonstrate how you can use Syncfusion’s suite of Xamarin controls to quickly build native apps " + "that run on Windows, Android, and iOS.", "In December of 2016, Microsoft unveiled its new chatbot, Zo." + " Intended as the next step in Microsoft’s ongoing efforts to develop more capable AI, " + "Zo has been rolled out on more platforms and been made available to more users." + "\n\nChatbots are social AIs designed to interact with human users via text chatting or direct, " + "spoken communication. There are a variety of uses for chatbots, from allowing for a more natural " + "user interface to simply being a form of entertainment. The chief concern is that software programmed " + "to communicate with a human must acquire language and deploy it correctly, a challenge of titanic proportions. ", "As you’ve probably noticed, Visual Studio 2017 was released on Tuesday. Excitement has been mounting " + "since the release candidate came out in November, and the final version is finally here. " + "We at Syncfusion have been jumping up and down—usually figuratively, " + "but sometimes literally—with anticipation because we’ve been wanting to share that " + "we’re SIM-SHIPPING Essential Studio 2017 Volume 1 with Visual Studio 2017!\n\nOh yes, " + "that’s 800+ Essential Studio components and frameworks fully compatible with VS2017, " + "all for your seamless developing convenience. You are very welcome.\n\nWe were so excited " + "about sim-shipping we had to throw an early party for Visual Studio 2017 and keep it secret until now. " + "After all, it’s not every year you turn 20 and become a brand new version of yourself. We strongly felt " + "this deserved cake.", "With the Visual Studio 2017 launch underway, " + "developers around the globe are focusing on how the new features in Microsoft’s updated IDE will improve their dev-ops." + " Because of Visual Studio’s impetus to constantly move development forward, " + "much of the conversation surrounding these launches has to do with what’s coming, not what has been." + "\n\nBut with this release, Visual Studio celebrates its twentieth birthday. To reflect on this notable milestone, " + "Syncfusion asked a variety of developers when they started working with Visual Studio and what features meaningfully " + "changed how they develop.\n\nThe majority of people we surveyed said they started working with Visual Studio 6.0," + " which was released in 1998. The previous year, Microsoft released Visual Studio 97, " + "described in this Microsoft Systems Journal article:", "We will be hosting Xamarin Dev Days here at Syncfusion on Saturday, June 10th, 2017! " + "Join us for a day of focused, hands-on learning. " + "Sign up here.\n\nThe morning of each event is spent exploring mobile development in expert-led sessions," + " while the afternoon is dedicated to coding. With Xamarin.Forms, " + "developers can build cross-platform, native UIs with one shared C# codebase.\n\nOur presenters will be <NAME>," + " a Xamarin MVP, and <NAME>, Xamarin technical solutions professional at Microsoft. " + "We are glad to have both leading sessions again. " + "Our new colleague <NAME>, product solution specialist at Syncfusion, will also participate at the event." + " We’re sure that Aaron will provide insight for attendees since, as he said, " + "“I have dipped my toes into the Xamarin world after writing a cross-platform app " + "that searches thousands of curated recipes via an API.”", "Syncfusion would like to thank all attendees of last week’s webinar, " + "“Fall Madly in Love with These 10 Xamarin Charts!” " + "for participating as Syncfusion Product Manager Chad Church showed off some of our coolest charts. " + "Here’s the webinar if you missed it.\n\nAs promised, " + "here is a summary of the Q&A portion from the end of the webinar, " + "plus answers to questions we couldn’t get to then:\n\nDoes the chart work inside a ScrollView?\nYes." + "\n\nWhat about MVVM support? I use Prism and a kind of pure MVVM model." + " Is it easy to integrate the charts in that model?\nYes. There’s complete MVVM support. " + "Prism and other packages should all work well.", "(This guest blog was written by <NAME>, " + "February 2017.)\n\nWhenever web developers are asked about a language or framework they want to try, " + "most likely the language Elm will be mentioned.\n\nThis is not an Elm primer, " + "so I assume you have a little experience with the Elm basics. " + "If not, the following paragraphs will give you an idea what can be achieved with the Elm platform." + "\n\nAs much as Elm libraries try to cover everything needed for web applications development, " + "there are gaps and inadequate solutions. " + "This is why pure Elm applications may be good for demos and simple applications, " + "but are not always feasible for production code. We will often have to enhance Elm code with JavaScript libraries." }; #endregion #region ItemsSource /// <summary> /// Used to add Record rows in View /// </summary> /// <returns>generate items</returns> internal ObservableCollection<ListViewBlogsInfo> GenerateSource() { ObservableCollection<ListViewBlogsInfo> blogsInfo = new ObservableCollection<ListViewBlogsInfo>(); Assembly assembly = this.GetType().Assembly; int blogsTitleCount = this.BlogsTitle.Count() - 1; int blogsCategoryCount = this.BlogsCategory.Count() - 1; int blogsAuthorCount = this.BlogsAuthers.Count() - 1; int blogsReadMoreCount = this.BlogsReadMoreInfo.Count() - 1; for (int i = 0; i < 5; i++) { ListViewBlogsInfo blog = new ListViewBlogsInfo { BlogTitle = this.BlogsTitle[blogsTitleCount - i], BlogCategory = this.BlogsCategory[blogsCategoryCount - i], BlogAuthor = this.BlogsAuthers[blogsAuthorCount - i], BlogAuthorIcon = new FontImageSource { Glyph = "\ue72a", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.FromRgb(51, 173, 225), }, BlogCategoryIcon = new FontImageSource { Glyph = "\ue738", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.FromRgb(51, 173, 225), }, BlogFacebookIcon = "FacebookLine.png", BlogTwitterIcon = "TwitterLine.png", BlogGooglePlusIcon = "GooglePlusLine.png", BlogLinkedInIcon = "LinkedInLine.png", ReadMoreContent = this.BlogsReadMoreInfo[blogsReadMoreCount - i] }; blogsInfo.Insert(0, blog); } return blogsInfo; } #endregion } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/GridGettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace SampleBrowser { public class GridGettingStartedViewModel { private OrderDetailsRepository order; public GridGettingStartedViewModel() { order = new OrderDetailsRepository(); OrdersInfo = order.GetOrderDetails(100); } private Random random = new Random(); internal void ItemsSourceRefresh() { var count = random.Next(1, 6); for (int i = 11000; i < 11000 + count; i++) { int val = i + random.Next(100, 150); this.OrdersInfo.Insert(0, order.RefreshItemsource(val)); } } #region ItemsSource private ObservableCollection<OrderInfo> _ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return _ordersInfo; } set { this._ordersInfo = value; } } #endregion } } <file_sep>/Forms/DataForm/DataForm/Samples/ContactForm/ViewModel/ContactsInfoRepository.cs #region Copyright // <copyright file="ContactsInfoRepository.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Internals; /// <summary> /// Represents the repository of data form fields and events. /// </summary> [Preserve(AllMembers = true)] public class ContactsInfoRepository { #region Fields /// <summary> /// Represents a pseudo random number generator. /// </summary> private Random random = new Random(); #endregion #region Contacts Information /// <summary> /// Represents the possible contact types. /// </summary> private string[] contactType = new string[] { "HOME", "WORK", "MOBILE", "OTHER", "BUSINESS" }; /// <summary> /// Represents the customers names. /// </summary> private string[] customerNames = new string[] { "Liz", "Ralph", "Oscar", "Torrey", "Gina", "Irene", "Katie", "Fiona", "Kyle", "Michael", "William", "Bill", "Wyatt", "Henry", "Eli", "Joseph", "Max", "Isaac", "Samuel", "Grayson", "Zachary", "David", "Christopher", "John", "Isaiah", "Levi", "Jonathan", "Oliver", "Chase", "Cooper", "Tristan", "Colton", "Austin", "Colin", "Charlie", "Dominic", "Parker", "Hunter", "Thomas", "Alex", "Ian", "Jordan", "Cole", "Julian", "Aaron", "Carson", "Miles", }; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ContactsInfoRepository"/> class. /// </summary> public ContactsInfoRepository() { } #endregion #region Get Contacts Details /// <summary> /// Gets the contact details of the customer. /// </summary> /// <param name="count">Represents the number of elements.</param> /// <returns>Returns the contact details.</returns> public ObservableCollection<ContactInfo> GetContactDetails(int count) { ObservableCollection<ContactInfo> customerDetails = new ObservableCollection<ContactInfo>(); for (int i = 0; i < 25; i++) { var details = new ContactInfo() { ContactType = ContactInfo.ContactsType.Home, ContactNumber = this.random.Next(1000000000, 2100000000).ToString(), ContactName = this.customerNames[i], ContactImage = "People_Circle" + (i % 9) + ".png", }; customerDetails.Add(details); } return customerDetails; } #endregion } }<file_sep>/Forms/Chart/Chart/Samples/ErrorBarChart/ErrorBarSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace SampleBrowser.SfChart.Samples.ErrorBarChart { public class ErrorBarSeriesViewModel { public ObservableCollection<ChartDataModel> ErrorBarSeriesData { get; set; } public ErrorBarSeriesViewModel() { ErrorBarSeriesData = new ObservableCollection<ChartDataModel> { new ChartDataModel("IND", 23, 0.5, 1), new ChartDataModel("AUS", 20, 0, 2), new ChartDataModel("USA", 35, 1, 2), new ChartDataModel("DEU", 28, 2, 0.5), new ChartDataModel("ITA", 30, 1, 0), new ChartDataModel("UK", 42, 1.5, 1), new ChartDataModel("RUS", 27, 0.5, 2) }; } } } <file_sep>/Forms/Picker/Picker/Samples/Extensions/TimePicker.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfPicker.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfPicker { public class CustomTimePicker : Syncfusion.SfPicker.XForms.SfPicker { public ObservableCollection<object> Time { get; set; } public ObservableCollection<object> Minute; public ObservableCollection<object> Hour; public ObservableCollection<object> Format; public ObservableCollection<string> Headers { get; set; } public CustomTimePicker() { Time = new ObservableCollection<object>(); Hour = new ObservableCollection<object>(); Minute = new ObservableCollection<object>(); Format = new ObservableCollection<object>(); Headers = new ObservableCollection<string>(); if (Device.RuntimePlatform == Device.Android) { Headers.Add("HOUR"); Headers.Add("MINUTE"); Headers.Add("MERIDIEM"); } else { Headers.Add("Hour"); Headers.Add("Minute"); Headers.Add("Meridiem"); } PopulateTimeCollection(); this.ItemsSource = Time; this.ColumnHeaderText = Headers; } private void PopulateTimeCollection() { for (int i = 1; i <= 12; i++) { if (i < 10) { Hour.Add("0" + i); } else Hour.Add(i.ToString()); } for (int j = 0; j < 60; j++) { if (j < 10) { Minute.Add("0" + j); } else Minute.Add(j.ToString()); } Format.Add("AM"); Format.Add("PM"); Time.Add(Hour); Time.Add(Minute); Time.Add(Format); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/GridGettingStarted/GettingStartedBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GettingStartedBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Syncfusion.SfDataGrid.XForms.DataPager; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Paging samples /// </summary> public class GettingStartedBehavior : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid datagrid; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.datagrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.datagrid.QueryRowHeight += this.Datagrid_QueryRowHeight; this.datagrid.PropertyChanged += this.Datagrid_PropertyChanged; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">A sampleView type of bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.datagrid = null; this.datagrid.QueryRowHeight -= this.Datagrid_QueryRowHeight; this.datagrid.PropertyChanged -= this.Datagrid_PropertyChanged; base.OnDetachingFrom(bindAble); } /// <summary> /// Fired when a row comes in to View /// </summary> /// <param name="sender">DataGrid_QueryRowHeight sender</param> /// <param name="e">QueryRowHeightEventArgs parameter e</param> private void Datagrid_QueryRowHeight(object sender, QueryRowHeightEventArgs e) { if (SfDataGridHelpers.IsCaptionSummaryRow(this.datagrid, e.RowIndex)) { e.Height = 40; if (Device.Idiom == TargetIdiom.Tablet) { e.Height = 50; } e.Handled = true; } } /// <summary> /// Fired when a grid property is changed. /// </summary> /// <param name="sender">DataGrid_PropertyChanged sender</param> /// <param name="e">PropertyChangedEventArgs parameter e</param> private void Datagrid_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Width") { this.datagrid.Columns[0].Width = this.datagrid.Width / 2; } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Diagram/MindMap.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Syncfusion.SfDiagram.iOS; using UIKit; namespace SampleBrowser { public class MindMap : SampleView { Node RootNode; UserHandleCollection DefaultHandles; UserHandleCollection RightSideHandle; UserHandleCollection LeftSideHandles; Node SelectedNode; UIView Notifier; UIView InfoNotifier; UITextView textinput; UserHandlePosition CurrentHandle; Random rnd = new Random(); UIImageView ExpandTemplate; UIImageView CollapseTemplate; String path; UITextView CommentBoxEntry=new UITextView(); List<UIColor> FColor = new List<UIColor>(); List<UIColor> SColor = new List<UIColor>(); int index; SfDiagram diagram = new SfDiagram(); public MindMap() { var width = 150; var height = 75; path = "Images/Diagram/MindMapImages"; var node = AddNode(300, 400, width, height, "Goals"); AddNodeStyle(node, HexToRGB("#d0ebff"), HexToRGB("#81bfea")); RootNode = node; diagram.AddNode(node); SColor.Add(HexToRGB("#d1afdf")); SColor.Add(HexToRGB("#90C8C2")); SColor.Add(HexToRGB("#8BC1B7")); SColor.Add(HexToRGB("#E2C180")); SColor.Add(HexToRGB("#BBBFD6")); SColor.Add(HexToRGB("#ACCBAA")); FColor.Add(HexToRGB("#e9d4f1")); FColor.Add(HexToRGB("#d4efed")); FColor.Add(HexToRGB("#c4f2e8")); FColor.Add(HexToRGB("#f7e0b3")); FColor.Add(HexToRGB("#DEE2FF")); FColor.Add(HexToRGB("#E5FEE4")); var ch1node = AddNode(100, 100, width, height, "Financial"); index = rnd.Next(5); AddNodeStyle(ch1node, FColor[index], SColor[index]); diagram.AddNode(ch1node); var ch1childnode = AddNode(100, 100, width, height, "Investment"); AddNodeStyle(ch1childnode, (ch1node.Style.Brush as SolidBrush).FillColor, (ch1node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch1childnode); var ch2node = AddNode(100, 600, width, height, "Social"); index = rnd.Next(5); AddNodeStyle(ch2node, FColor[index], SColor[index]); diagram.AddNode(ch2node); var ch2childnode1 = AddNode(100, 100, width, height, "Friends"); AddNodeStyle(ch2childnode1, (ch2node.Style.Brush as SolidBrush).FillColor, (ch2node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch2childnode1); var ch2childnode2 = AddNode(100, 100, width, height, "Family"); AddNodeStyle(ch2childnode2, (ch2node.Style.Brush as SolidBrush).FillColor, (ch2node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch2childnode2); var ch3node = AddNode(500, 100, width, height, "Personal"); index = rnd.Next(5); AddNodeStyle(ch3node, FColor[index], SColor[index]); diagram.AddNode(ch3node); var ch3childnode1 = AddNode(500, 100, width, height, "Sports"); AddNodeStyle(ch3childnode1, (ch3node.Style.Brush as SolidBrush).FillColor, (ch3node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch3childnode1); var ch3childnode2 = AddNode(500, 100, width, height, "Food"); AddNodeStyle(ch3childnode2, (ch3node.Style.Brush as SolidBrush).FillColor, (ch3node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch3childnode2); var ch4node = AddNode(500, 600, width, height, "Work"); index = rnd.Next(5); AddNodeStyle(ch4node, FColor[index], SColor[index]); diagram.AddNode(ch4node); var ch4childnode1 = AddNode(500, 100, width, height, "Project"); AddNodeStyle(ch4childnode1, (ch4node.Style.Brush as SolidBrush).FillColor, (ch4node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch4childnode1); var ch4childnode2 = AddNode(500, 100, width, height, "Career"); AddNodeStyle(ch4childnode2, (ch4node.Style.Brush as SolidBrush).FillColor, (ch4node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch4childnode2); diagram.AddConnector(AddConnector(node, ch1node)); diagram.AddConnector(AddConnector(node, ch2node)); diagram.AddConnector(AddConnector(node, ch3node)); diagram.AddConnector(AddConnector(node, ch4node)); diagram.AddConnector(AddConnector(ch1node, ch1childnode)); diagram.AddConnector(AddConnector(ch2node, ch2childnode1)); diagram.AddConnector(AddConnector(ch2node, ch2childnode2)); diagram.AddConnector(AddConnector(ch3node, ch3childnode1)); diagram.AddConnector(AddConnector(ch3node, ch3childnode2)); diagram.AddConnector(AddConnector(ch4node, ch4childnode1)); diagram.AddConnector(AddConnector(ch4node, ch4childnode2)); diagram.UserHandleClicked += Diagram_UserHandleClicked; AddHandles(); diagram.NodeClicked += Diagram_NodeClicked; diagram.Clicked += Diagram_DiagramClicked; diagram.Loaded += Diagram_Loaded; SelectedNode = node; diagram.TextChanged += Diagram_TextChanged; diagram.ConnectorClicked += Diagram_ConnectorClicked; this.AddSubview(diagram); } private UIColor HexToRGB(string hexavalue) { int r = Convert.ToInt32(hexavalue.Substring(1, 2), 16); int g = Convert.ToInt32(hexavalue.Substring(3, 2), 16); int b = Convert.ToInt32(hexavalue.Substring(5, 2), 16); return UIColor.FromRGB(r, g, b); } private Connector AddConnector(Node node, Node ch1node) { var c1 = new Connector(); c1.SourceNode = node; c1.TargetNode = ch1node; c1.Style.StrokeBrush = new SolidBrush((c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor); c1.Style.StrokeStyle = StrokeStyle.Dashed; c1.Style.StrokeWidth = 3; c1.TargetDecoratorStyle.Fill = (c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor; c1.TargetDecoratorStyle.StrokeColor = (c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor; c1.SegmentType = SegmentType.CurveSegment; return c1; } private void AddNodeStyle(Node node, UIColor fill, UIColor Stroke) { node.Style.Brush = new SolidBrush(fill); node.Style.StrokeBrush = new SolidBrush(Stroke); } Node AddNode(int x, int y, int w, int h, string text) { var node = new Node(x, y, w, h); node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 3; node.Annotations.Add(new Annotation() { Content = text, FontSize = 15, TextBrush = new SolidBrush(UIColor.Black) }); return node; } private void AddAnnotation(string headertext) { Notifier = new UIView(); Notifier.Frame = new CGRect(UIScreen.MainScreen.Bounds.Width / 2 - 150, UIScreen.MainScreen.Bounds.Height / 2 - 75, 300, 150); Notifier.Layer.CornerRadius = 5; Notifier.BackgroundColor = UIColor.White; diagram.PageSettings.BackgroundColor = UIColor.DarkGray; diagram.Layer.Opacity = 0.2f; var title = new UILabel(); title.Frame = new CGRect(10, 10, Notifier.Frame.Width, 30); title.Text = headertext; title.TextColor = UIColor.Black; Notifier.Add(title); textinput = new UITextView(); textinput.Frame = new CGRect(10, 50, Notifier.Frame.Width, 50); textinput.Changed+= Textinput_Changed; UIButton ok = new UIButton(); ok.SetTitle("OK", UIControlState.Normal); ok.TouchUpInside += Ok_TouchUpInside; Notifier.AddSubview(textinput); Notifier.AddSubview(ok); this.AddSubview(Notifier); } private void AddHandles() { var template = new UIImageView(); template.Frame = new CGRect(0, 0, 25, 25); var img = new UIImage(path + "plus.png"); template.Image = img; var deltemplate = new UIImageView(); deltemplate.Frame = new CGRect(0, 0, 25, 25); img = new UIImage(path + "delete.png"); deltemplate.Image = img; ExpandTemplate = new UIImageView(); ExpandTemplate.Frame = new CGRect(0, 0, 25, 25); img = new UIImage(path + "expand.png"); ExpandTemplate.Image = img; CollapseTemplate = new UIImageView(); CollapseTemplate.Frame = new CGRect(0, 0, 25, 25); img = new UIImage(path + "collpase.png"); CollapseTemplate.Image = img; var moretemplate = new UIImageView(); moretemplate.Frame = new CGRect(0, 0, 25, 25); img = new UIImage(path + "more.png"); moretemplate.Image = img; DefaultHandles = new UserHandleCollection(diagram); DefaultHandles.Add(new UserHandle("Left", UserHandlePosition.Left, template)); DefaultHandles.Add(new UserHandle("Right", UserHandlePosition.Right, template)); DefaultHandles.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, CollapseTemplate)); DefaultHandles.Add(new UserHandle("info", UserHandlePosition.TopRight, moretemplate)); diagram.UserHandles = DefaultHandles; RightSideHandle = new UserHandleCollection(diagram); RightSideHandle.Add(new UserHandle("Right", UserHandlePosition.Right, template)); RightSideHandle.Add(new UserHandle("Delete", UserHandlePosition.Bottom, deltemplate)); RightSideHandle.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, CollapseTemplate)); RightSideHandle.Add(new UserHandle("info", UserHandlePosition.TopRight, moretemplate)); LeftSideHandles = new UserHandleCollection(diagram); LeftSideHandles.Add(new UserHandle("Left", UserHandlePosition.Left, template)); LeftSideHandles.Add(new UserHandle("Delete", UserHandlePosition.Bottom, deltemplate)); LeftSideHandles.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, CollapseTemplate)); LeftSideHandles.Add(new UserHandle("info", UserHandlePosition.TopRight, moretemplate)); } void Diagram_TextChanged(object sender, TextChangedEventArgs args) { args.Item.TextBrush = new SolidBrush(UIColor.Black); args.Item.FontSize = 15; } private void Diagram_Loaded(object sender) { diagram.EnableDrag = false; diagram.ShowSelectorHandle(false, SelectorPosition.SourcePoint); diagram.ShowSelectorHandle(false, SelectorPosition.TargetPoint); diagram.ShowSelectorHandle(false, SelectorPosition.Rotator); diagram.ShowSelectorHandle(false, SelectorPosition.TopLeft); diagram.ShowSelectorHandle(false, SelectorPosition.TopRight); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleLeft); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleRight); diagram.ShowSelectorHandle(false, SelectorPosition.BottomCenter); diagram.ShowSelectorHandle(false, SelectorPosition.BottomLeft); diagram.ShowSelectorHandle(false, SelectorPosition.BottomRight); diagram.ShowSelectorHandle(false, SelectorPosition.TopCenter); diagram.LayoutManager = new LayoutManager() { Layout = new MindMapLayout() { MindMapOrientation = Syncfusion.SfDiagram.iOS.Orientation.Horizontal, HorizontalSpacing = 70, } }; diagram.LayoutManager.Layout.UpdateLayout(); diagram.Select(RootNode); diagram.BringToView(RootNode); } private void Diagram_DiagramClicked(object sender, DiagramClickedEventArgs args) { diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; if (Notifier != null && Notifier.Superview==this) { Notifier.RemoveFromSuperview(); } if (InfoNotifier != null && InfoNotifier.Superview == this) { if (CommentBoxEntry.Text != null) { SelectedNode.Content = CommentBoxEntry.Text; } InfoNotifier.RemoveFromSuperview(); } SelectedNode = null; } private void Diagram_UserHandleClicked(object sender, UserHandleClickedEventArgs args) { if (Notifier != null && Notifier.Superview == this) { Notifier.RemoveFromSuperview(); diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; } else if (InfoNotifier != null && InfoNotifier.Superview == this) { InfoNotifier.RemoveFromSuperview(); } else { if (args.Item.Name == "Delete") { diagram.RemoveNode(SelectedNode, true); (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayout(); } else if (args.Item.Name == "ExpColl") { if (SelectedNode.IsExpanded) { SelectedNode.IsExpanded = false; args.Item.Content = CollapseTemplate; diagram.UserHandles[0].Visible = false; if (SelectedNode == RootNode) diagram.UserHandles[1].Visible = false; } else { SelectedNode.IsExpanded = true; args.Item.Content = ExpandTemplate; diagram.UserHandles[0].Visible = true; if (SelectedNode == RootNode) diagram.UserHandles[1].Visible = true; } (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayout(); diagram.Select(SelectedNode); } else if (args.Item.Name == "info") { ShowInfo(); } else { if (args.Item.Name == "Left") { CurrentHandle = UserHandlePosition.Left; AddAnnotation("Add Topic"); } else if (args.Item.Name == "Right") { CurrentHandle = UserHandlePosition.Right; AddAnnotation("Add Topic"); } } } } void ShowInfo() { InfoNotifier = new UIView(); InfoNotifier.Frame = new CGRect(UIScreen.MainScreen.Bounds.Width / 2 - 150, UIScreen.MainScreen.Bounds.Height / 2 - 125, 300, 250); InfoNotifier.Layer.CornerRadius = 5; InfoNotifier.BackgroundColor = UIColor.White; this.AddSubview(InfoNotifier); UILabel title = new UILabel(); title.Frame = new CGRect(0, 0, InfoNotifier.Frame.Width, 30); title.Text = " Add Comments"; title.TextColor = UIColor.Black; InfoNotifier.AddSubview(title); UITextView CommentBoxEntry = new UITextView(); CommentBoxEntry.Frame = new CGRect(0, 120, InfoNotifier.Frame.Width, InfoNotifier.Frame.Height - 120); if (SelectedNode.Content == null) { CommentBoxEntry.Text = ""; } CommentBoxEntry.Text = (SelectedNode.Content as String); InfoNotifier.AddSubview(CommentBoxEntry); UIButton ok = new UIButton(); ok.Frame = new CGRect(0, 250, InfoNotifier.Frame.Width, 50); ok.SetTitle("OK", UIControlState.Normal); ok.TouchUpInside+= Ok_TouchUpInside1; InfoNotifier.AddSubview(ok); } void Textinput_Changed(object sender, EventArgs e) { Notifier.Frame = new CGRect(Notifier.Frame.X, 50, Notifier.Frame.Width, Notifier.Frame.Height); } void Ok_TouchUpInside(object sender, EventArgs e) { diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; Notifier.RemoveFromSuperview(); if (textinput.Text == null) { textinput.Text = ""; } var node = new Node(); if (CurrentHandle == UserHandlePosition.Left) { node.OffsetX = SelectedNode.OffsetX - SelectedNode.Width - 100; node.OffsetY = SelectedNode.OffsetY; } else if (CurrentHandle == UserHandlePosition.Right) { node.OffsetX = SelectedNode.OffsetX + SelectedNode.Width + 100; node.OffsetY = SelectedNode.OffsetY; } node.Width = SelectedNode.Width; node.Height = SelectedNode.Height; node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 3; if (SelectedNode == RootNode) { index = rnd.Next(5); node.Style.Brush = new SolidBrush(FColor[index]); node.Style.StrokeBrush = new SolidBrush(SColor[index]); } else { node.Style = SelectedNode.Style; } node.Annotations.Add(new Annotation() { Content = textinput.Text, FontSize = 15, TextBrush = new SolidBrush(UIColor.Black) }); diagram.AddNode(node); var c1 = new Connector(); c1.SourceNode = SelectedNode; c1.TargetNode = node; c1.Style.StrokeBrush = node.Style.StrokeBrush; c1.Style.StrokeWidth = 3; c1.TargetDecoratorStyle.Fill = (node.Style.StrokeBrush as SolidBrush).FillColor; c1.TargetDecoratorStyle.StrokeColor = (node.Style.StrokeBrush as SolidBrush).FillColor; c1.SegmentType = SegmentType.CurveSegment; c1.Style.StrokeStyle = StrokeStyle.Dashed; diagram.AddConnector(c1); if (CurrentHandle == UserHandlePosition.Left) { diagram.UserHandles = LeftSideHandles; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLeftOrTop(); } else if (CurrentHandle == UserHandlePosition.Right) { diagram.UserHandles = RightSideHandle; (diagram.LayoutManager.Layout as MindMapLayout).UpdateRightOrBottom(); } diagram.Select(node); SelectedNode = node; diagram.BringToView(node); } void Ok_TouchUpInside1(object sender, EventArgs e) { if (CommentBoxEntry.Text != null) { SelectedNode.Content = CommentBoxEntry.Text; } InfoNotifier.RemoveFromSuperview(); } private void Diagram_NodeClicked(object sender, NodeClickedEventArgs args) { SelectedNode = args.Item; diagram.Layer.Opacity = 1; diagram.PageSettings.BackgroundColor = UIColor.White; if (Notifier != null && Notifier.Superview==this) { Notifier.RemoveFromSuperview(); } else if (InfoNotifier != null && InfoNotifier.Superview == this) { InfoNotifier.RemoveFromSuperview(); } else { if (args.Item != RootNode && args.Item.OffsetX > RootNode.OffsetX) { diagram.UserHandles = RightSideHandle; } else if (args.Item != RootNode && args.Item.OffsetX < RootNode.OffsetX) { diagram.UserHandles = LeftSideHandles; } else if (args.Item == RootNode) { diagram.UserHandles = DefaultHandles; } if (SelectedNode.IsExpanded) { diagram.UserHandles[0].Visible = true; if (SelectedNode == RootNode) diagram.UserHandles[1].Visible = true; diagram.UserHandles[2].Content = ExpandTemplate; } else { diagram.UserHandles[0].Visible = false; if (SelectedNode == RootNode) diagram.UserHandles[1].Visible = false; diagram.UserHandles[2].Content = CollapseTemplate; } } } void Diagram_ConnectorClicked(object sender, ConnectorClickedEventArgs args) { diagram.ClearSelection(); if (Notifier != null && Notifier.Superview == this) { Notifier.RemoveFromSuperview(); } else if (InfoNotifier != null && InfoNotifier.Superview == this) { InfoNotifier.RemoveFromSuperview(); } } void Ok_Clicked1(object sender, EventArgs e) { if (CommentBoxEntry.Text != null) { SelectedNode.Content = CommentBoxEntry.Text; } InfoNotifier.RemoveFromSuperview(); } } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/Model/ContactInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ContactInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; /// <summary> /// A class contains Properties and Notifies that a property value has changed /// </summary> public class ContactInfo : INotifyPropertyChanged { /// <summary> /// backing field for CallTime. /// </summary> private string callTime; /// <summary> /// backing field for ContactImage. /// </summary> private string contactImage; /// <summary> /// backing field for ContactName. /// </summary> private string contactName; /// <summary> /// Initializes a new instance of the ContactInfo class. /// </summary> public ContactInfo() { } /// <summary> /// Initializes a new instance of the ContactInfo class. /// </summary> /// <param name="name">string type parameter named as name</param> public ContactInfo(string name) { this.contactName = name; } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets ContactName and notifies user when collection value gets changed. /// </summary> public string ContactName { get { return this.contactName; } set { if (this.contactName != value) { this.contactName = value; this.RaisedOnPropertyChanged("ContactName"); } } } /// <summary> /// Gets or sets CallTime and notifies user when collection value gets changed. /// </summary> public string CallTime { get { return this.callTime; } set { if (this.callTime != value) { this.callTime = value; this.RaisedOnPropertyChanged("CallTime"); } } } /// <summary> /// Gets or sets ContactImage and notifies user when collection value gets changed. /// </summary> public string ContactImage { get { return this.contactImage; } set { this.contactImage = value; this.RaisedOnPropertyChanged("ContactImage"); } } /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="propertyName">string type parameter named as propertyName</param> public void RaisedOnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/ImageEditor/ImageEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfImageEditor.iOS; using Foundation; using UIKit; using CoreGraphics; using System.Drawing; namespace SampleBrowser { public partial class ImageEditor : SampleView { UINavigationController navigationController; public ImageEditor() { } public override void MovedToSuperview() { base.MovedToSuperview(); var view = Superview; var window = UIApplication.SharedApplication.KeyWindow; navigationController = window.RootViewController as UINavigationController; } public override void LayoutSubviews() { base.LayoutSubviews(); UIView mainView = new UIView(); nfloat TotalWidth = Frame.Width - 20; int height=150; mainView.Frame = new CGRect(0, 0,TotalWidth, Frame.Height); /*------Header Label-------*/ UILabel label = new UILabel(new CGRect(20, 50, TotalWidth, 25)); label.BackgroundColor = UIColor.Clear; label.Font = UIFont.SystemFontOfSize(25); label.TextAlignment = UITextAlignment.Left; label.TextColor = UIColor.Gray; label.Text = "Sample Pictures"; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { height=200; } UIButton imageView1 = new UIButton(new CGRect(0, 100, TotalWidth / 3, height)); imageView1.SetImage(UIImage.FromBundle("Images/ImageEditor/image2.png"), UIControlState.Normal); imageView1.ImageView.ContentMode = UIViewContentMode.ScaleToFill; imageView1.TouchDown += (sender, e) => { navigationController.PushViewController(new ImageEditorViewController(imageView1.CurrentImage), false); }; mainView.AddSubview(imageView1); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { height=200; } UIButton imageView2 = new UIButton(new CGRect(TotalWidth / 3, 100, TotalWidth / 3, height)); imageView2.SetImage(UIImage.FromBundle("Images/ImageEditor/image3.png"), UIControlState.Normal); imageView2.ImageView.ContentMode = UIViewContentMode.ScaleToFill; mainView.AddSubview(imageView2); imageView2.TouchDown += (sender, e) => { navigationController.PushViewController(new ImageEditorViewController(imageView2.CurrentImage), false); }; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { height=200; } UIButton imageView3 = new UIButton(new CGRect(2 * (TotalWidth / 3), 100, TotalWidth/ 3, height)); imageView3.SetImage(UIImage.FromBundle("Images/ImageEditor/image4.png"), UIControlState.Normal); imageView3.ImageView.ContentMode = UIViewContentMode.ScaleToFill; imageView3.TouchDown += (sender, e) => { navigationController.PushViewController(new ImageEditorViewController(imageView3.CurrentImage), false); }; mainView.AddSubview(imageView3); AddSubview(label); AddSubview(mainView); } } public class ImageEditorViewController : UIViewController { UIImage _image; public ImageEditorViewController(UIImage image) { _image = image; } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); SfImageEditor sfImageEditor = new SfImageEditor(new CGRect(View.Frame.Location.X, 60, View.Frame.Size.Width, View.Frame.Size.Height - 60)); sfImageEditor.Image = _image; this.View.Add(sfImageEditor); } } }<file_sep>/Android/SampleBrowser/Samples/DataForm/readme.md The Data Form control helps editing the fields of any data object and simplifying the development of various forms like login, reservation, and data entry. Key features include different layouts, grouping, support for built-in and custom editors, validation, localization and data annotations. The following samples are available for data form to demonstrate the functionalities of each feature. | Sample | Description | |-----------------|-------------| | [Getting Started](DataForm/Samples/GettingStarted)| This sample showcases simple DataForm by loading a set of fields.| | [Contact Form](DataForm/Samples/ContactForm)| This sample showcases read only and layout customization capabilities of DataForm. | <file_sep>/Android/SampleBrowser/Samples/DataGrid/DataVirtualization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Graphics; using Android.Views; using System.Globalization; namespace SampleBrowser { public class DataVirtualization:SamplePage { SfDataGrid sfGrid; public override Android.Views.View GetSampleContent (Android.Content.Context context) { sfGrid = new SfDataGrid (context); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumn; sfGrid.ItemsSource = new DataVirtualizationViewModel ().ViewSource; sfGrid.GridStyle.AlternatingRowColor = Color.Rgb (206, 206, 206); return sfGrid; } void GridAutoGenerateColumn (object sender, AutoGeneratingColumnArgs e) { if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; } else if (e.Column.MappingName == "Name") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ContactID") { e.Column.HeaderText = "Contact ID"; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Title") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "SickLeaveHours") { e.Column.HeaderText = "Sick Leave Hours"; } else if (e.Column.MappingName == "Salary") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); } else if (e.Column.MappingName == "BirthDate") { e.Column.HeaderText = "Birth Date"; e.Column.TextAlignment = GravityFlags.Center; e.Column.Format = "d"; } } public override void Destroy () { sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumn; sfGrid.Dispose (); sfGrid = null; } } } <file_sep>/Android/SampleBrowser/Samples/Rotator/Rotator_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Android.Content; using Com.Syncfusion.Rotator; using System.Collections; using Android.Graphics; namespace SampleBrowser { public class Rotator_Mobile { /********************************* **Local Varabile Inizialization** *********************************/ ArrayAdapter<String> tabAdapter, directionAdapter, modeAdapter; double navigationBarHeight, statusBarHeight; Spinner directionSpinner, tabStripSpinner, modeSpinner; LinearLayout propertylayout, stackView3; LinearLayout.LayoutParams layoutParams2, layoutParams3; int height,width; TextView adjlabel3; SfRotator rotator; Context context; public Android.Views.View GetSampleContent(Android.Content.Context context) { Context con = context; List<SfRotatorItem> images = new List<SfRotatorItem>(); List<int> imageID = new List<int>(); SamplPageContent(con); /*********** **Rotator** ***********/ rotator = new SfRotator(con); rotator.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, height / 2);//ActionBar.LayoutParameters(ViewGroup.LayoutParams.MATCH_PARENT,height/2); rotator.NavigationStripMode = NavigationStripMode.Dots; rotator.NavigationDirection = NavigationDirection.Horizontal; rotator.NavigationStripPosition = NavigationStripPosition.Bottom; rotator.SelectedIndex = 2; rotator.EnableAutoPlay = false; rotator.SetBackgroundColor(Color.ParseColor("#ececec")); //Images Id List imageID.Add(Resource.Drawable.movie1); imageID.Add(Resource.Drawable.movie2); imageID.Add(Resource.Drawable.movie3); imageID.Add(Resource.Drawable.movie4); imageID.Add(Resource.Drawable.movie5); SfRotatorItem item; ImageView image; for (int i = 0; i < imageID.Count; i++) { item = new SfRotatorItem(con); image = new ImageView(con); image.SetImageResource(imageID[i]); image.SetScaleType(ImageView.ScaleType.FitXy); item.Content = image; images.Add(item); } rotator.DataSource = images; //Main View LinearLayout mainView = new LinearLayout(con); mainView.AddView(GetView(con)); return mainView; } private LinearLayout GetView(Context con) { LinearLayout completeLayout = new LinearLayout(con); completeLayout.Orientation = Orientation.Vertical; completeLayout.LayoutParameters = (new ActionBar.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent)); completeLayout.AddView(rotator); completeLayout.AddView(adjlabel3); //ScrollView ScrollView scrollView = new ScrollView(con); scrollView.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)((height / 2) - (navigationBarHeight + statusBarHeight + 20)))); scrollView.AddView(GetPropertyLayout(con)); completeLayout.AddView(scrollView); return completeLayout; } private void SamplPageContent(Context con) { height = (int)(con.Resources.DisplayMetrics.HeightPixels); statusBarHeight = getStatusBarHeight(con); navigationBarHeight = getNavigationBarHeight(con); //AdjLabel adjlabel3 = new TextView(con); adjlabel3.LayoutParameters = (new ActionBar.LayoutParams(ViewGroup.LayoutParams.MatchParent, 10)); } public View GetPropertyLayout(Android.Content.Context context1) { context = context1; width = context.Resources.DisplayMetrics.WidthPixels / 2; propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width * 2, 2); layoutParams.SetMargins(0, 5, 0, 0); DirectionLayout(); TapPositionLayout(); NavigationStripLayout(); EnableAutoPlayLayout(); return propertylayout; } private void DirectionLayout() { /****************** **DirectionLabel** ******************/ TextView directionLabel = new TextView(context); directionLabel.Text = " " + "Navigation Direction"; directionLabel.TextSize = 15; directionLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Bold); directionLabel.SetTextColor(Color.Black); directionLabel.Gravity = GravityFlags.Left; //AdjLabel TextView adjLabel2 = new TextView(context); adjLabel2.SetHeight(14); propertylayout.AddView(adjLabel2); //DirectionSpinner directionSpinner = new Spinner(context,SpinnerMode.Dialog); directionSpinner.SetPadding(0, 0, 0, 0); propertylayout.AddView(directionLabel); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 2); //AdjLabel TextView adjLabel3 = new TextView(context); adjLabel3.SetHeight(20); propertylayout.AddView(adjLabel3); propertylayout.AddView(directionSpinner); TextView adjLabel4 = new TextView(context); propertylayout.AddView(adjLabel4); //Direction List List<String> directionList = new List<String>(); directionList.Add("Horizontal"); directionList.Add("Vertical"); //Direction adapter directionAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, directionList); directionAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //Direction Spinner Item Selected Listener directionSpinner.Adapter = directionAdapter; directionSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = directionAdapter.GetItem(e.Position); if (selectedItem.Equals("Horizontal")) { rotator.NavigationDirection = NavigationDirection.Horizontal; } else if (selectedItem.Equals("Vertical")) { rotator.NavigationDirection = NavigationDirection.Vertical; } }; } private void TapPositionLayout() { /**************** **Tap Position** ****************/ TextView tabPoitionLabel = new TextView(context); tabPoitionLabel.Text = " " + "Navigation Strip Position"; tabPoitionLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Bold); tabPoitionLabel.Gravity = GravityFlags.Left; tabPoitionLabel.TextSize = 15; tabPoitionLabel.SetTextColor(Color.Black); //Tab List List<String> tabList = new List<String>(); tabList.Add("Bottom"); tabList.Add("Top"); tabList.Add("Right"); tabList.Add("Left"); tabStripSpinner = new Spinner(context,SpinnerMode.Dialog); //Tap Adapter tabAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, tabList); tabAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //Tab Spinner tabStripSpinner.Adapter = tabAdapter; tabStripSpinner.SetPadding(0, 0, 0, 0); //Tab Spinner ItemSelected Listener tabStripSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = tabAdapter.GetItem(e.Position); if (selectedItem.Equals("Bottom")) { rotator.NavigationStripPosition = NavigationStripPosition.Bottom; } else if (selectedItem.Equals("Top")) { rotator.NavigationStripPosition = NavigationStripPosition.Top; } if (selectedItem.Equals("Right")) { rotator.NavigationStripPosition = NavigationStripPosition.Right; } else if (selectedItem.Equals("Left")) { rotator.NavigationStripPosition = NavigationStripPosition.Left; } }; //Layout Params layoutParams2 = new LinearLayout.LayoutParams(width * 2, 2); layoutParams2.SetMargins(0, 5, 0, 0); propertylayout.AddView(tabPoitionLabel); SeparatorView separate2 = new SeparatorView(context, width * 2); separate2.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 2); //sanpSToLabel TextView snapsToLabel = new TextView(context); snapsToLabel.SetHeight(20); propertylayout.AddView(snapsToLabel); propertylayout.AddView(tabStripSpinner); propertylayout.SetPadding(15, 0, 15, 0); //AdjLabel TextView adjLabel12 = new TextView(context); adjLabel12.SetHeight(20); propertylayout.AddView(adjLabel12); } private void NavigationStripLayout() { /******************* **Navigation Mode** *******************/ TextView modeLabel = new TextView(context); modeLabel.Text = " " + "Navigation Strip Mode"; modeLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Bold); modeLabel.Gravity = GravityFlags.Left; modeLabel.TextSize = 15; modeLabel.SetTextColor(Color.Black); //Mode List List<String> modeList = new List<String>(); modeList.Add("Dots"); modeList.Add("Thumbnail"); //Mode Adapter modeAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, modeList); modeAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //Mode Spinner modeSpinner = new Spinner(context,SpinnerMode.Dialog); modeSpinner.Adapter = modeAdapter; modeSpinner.SetPadding(0, 0, 0, 0); //Mode Spinner Item Selected Listener modeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = modeAdapter.GetItem(e.Position); if (selectedItem.Equals("Dots")) { rotator.NavigationStripMode = NavigationStripMode.Dots; } else if (selectedItem.Equals("Thumbnail")) { rotator.NavigationStripMode = NavigationStripMode.Thumbnail; } }; //LayoutParams layoutParams3 = new LinearLayout.LayoutParams(width * 2, 7); layoutParams2.SetMargins(0, 5, 0, 0); propertylayout.AddView(modeLabel); //Separator SeparatorView separate4 = new SeparatorView(context, width * 2); separate4.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 2); LinearLayout.LayoutParams layoutParams8 = new LinearLayout.LayoutParams(width * 2, 2); layoutParams8.SetMargins(0, 5, 0, 0); //Adjust Label TextView adjustLabel = new TextView(context); adjustLabel.SetHeight(20); propertylayout.AddView(adjustLabel); propertylayout.AddView(modeSpinner); propertylayout.SetPadding(15, 0, 15, 0); TextView adjLabel13 = new TextView(context); adjLabel13.SetHeight(20); propertylayout.AddView(adjLabel13); } private void EnableAutoPlayLayout() { /******************** **Enable Auto Play** ********************/ TextView autoPlayLabel = new TextView(context); autoPlayLabel.Text = " " + "Enable AutoPlay"; autoPlayLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Bold); autoPlayLabel.Gravity = GravityFlags.Center; autoPlayLabel.TextSize = 16; //Auto Play Switch Switch playSwitch = new Switch(context); playSwitch.Checked = false; playSwitch.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { rotator.EnableAutoPlay = e.IsChecked; }; //LayoutParams LinearLayout.LayoutParams layoutParams5 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams3.SetMargins(0, 5, 0, 0); LinearLayout.LayoutParams layoutParams4 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, 55); layoutParams4.SetMargins(0, 5, 0, 0); //StackView stackView3 = new LinearLayout(context); stackView3.AddView(autoPlayLabel); stackView3.AddView(playSwitch, layoutParams5); stackView3.Orientation = Orientation.Horizontal; propertylayout.AddView(stackView3); TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //Separater SeparatorView separate3 = new SeparatorView(context, width * 2); separate3.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 2); LinearLayout.LayoutParams layoutParams7 = new LinearLayout.LayoutParams( width * 2, 2); layoutParams7.SetMargins(0, 10, 0, 0); } private int getStatusBarHeight(Context con) { int barHeight = 0; int resourceId = con.Resources.GetIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { barHeight = con.Resources.GetDimensionPixelSize(resourceId); } return barHeight; } private int getNavigationBarHeight(Context con) { int navBarHeight = 0; int resourceId = con.Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navBarHeight = con.Resources.GetDimensionPixelSize(resourceId); } return navBarHeight; } } } <file_sep>/Forms/ImageEditor/ImageEditor/Samples/BannerCreator/BannerCreator.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Reflection; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfImageEditor { public partial class BannerCreator : SampleView { ImageSerializeModel model; ViewModel viewModel; Model data; double height = 0, width = 0; public BannerCreator() { data = new Model(); viewModel = new ViewModel(); model = new ImageSerializeModel(viewModel); InitializeComponent(); BindingContext = model; } void ImageTapped(object sender, System.EventArgs e) { LoadFromStream((sender as Image).Source, viewModel, data); } void LoadFromStream(ImageSource source, ViewModel viewModel, Model data) { if (Device.RuntimePlatform.ToLower() == "ios") { Navigation.PushAsync(new NavigationPage(new ImageEditorToolbarPage(source, viewModel, data))); } else if (Device.RuntimePlatform.ToLower() == "uwp") { Navigation.PushAsync(new ImageEditorToolbarPage(source, viewModel, data)); } else { Navigation.PushModalAsync(new ImageEditorToolbarPage(source, viewModel, data)); } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.RuntimePlatform.ToLower() == "uwp") return; if ((width != this.width || height != this.height) && (width > -1 || height > -1)) { this.width = width; this.height = height; if (width < height) { imageGrid.RowDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 70, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.6, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Clear(); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); } else { imageGrid.RowDefinitions.Clear(); mainGrid.ColumnDefinitions.Clear(); imageGrid.Padding = new Thickness(20, 10, 20, 0); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0.1, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1.5, GridUnitType.Star) }); imageGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(0, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0.5, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0.5, GridUnitType.Star) }); mainGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0.5, GridUnitType.Star) }); } } } } public class ImageSerializeModel { public ImageSource BroweImage1 { get; set; } public ImageSource BroweImage2 { get; set; } public ImageSource BroweImage3 { get; set; } public ImageSerializeModel(ViewModel viewmodel) { BroweImage1 = viewmodel.ModelList[0].Name; BroweImage2 = viewmodel.ModelList[1].Name; BroweImage3 = viewmodel.ModelList[2].Name; } } public class ViewModel { public ObservableCollection<Model> ModelList { get; set; } public ViewModel() { Assembly assembly = typeof(ImageSerializeModel).GetTypeInfo().Assembly; ModelList = new ObservableCollection<Model> { #if COMMONSB new Model { Name=ImageSource.FromResource("SampleBrowser.Icons.EditorDashboard.jpg",assembly),ImageName="Dashboard"} , new Model { Name=ImageSource.FromResource("SampleBrowser.Icons.EditorSuccinity.png",assembly),ImageName="Succinity"} , new Model { Name=ImageSource.FromResource("SampleBrowser.Icons.EditorTwitter.jpeg",assembly),ImageName="Twitter"} , #else new Model { Name=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorDashboard.jpg",assembly),ImageName="Dashboard"} , new Model { Name=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorSuccinity.png",assembly),ImageName="Succinity"} , new Model { Name=ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.EditorTwitter.jpeg",assembly),ImageName="Twitter"} , #endif }; } } public class Model : INotifyPropertyChanged { private ImageSource name; public ImageSource Name { get { return name; } set { name = value; RaisePropertyChanged("Name"); } } private string _imagestream; public string Imagestream { get { return _imagestream; } set { _imagestream = value; RaisePropertyChanged("Imagestream"); } } private Stream _stream; public Stream Strm { get { return _stream; } set { _stream = value; RaisePropertyChanged("Strm"); } } private string _imageName; public string ImageName { get { return _imageName; } set { _imageName = value; RaisePropertyChanged("ImageName"); } } public event PropertyChangedEventHandler PropertyChanged; void RaisePropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } } <file_sep>/Forms/ProgressBar/ProgressBar/Samples/Circular/CircularSegment.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfProgressBar { using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.ProgressBar; using Xamarin.Forms; public partial class CircularSegment : SampleView { private bool isDisposed; public CircularSegment() { InitializeComponent(); this.SegmentedPaddingCircularProgressBar.AnimationDuration = 2000; this.SegmentedCircularProgressBar.AnimationDuration = 2000; this.SegmentedFillingStyle.AnimationDuration = 0; #pragma warning disable CS4014 this.SetSegmentedFillingStyleProgress(); #pragma warning restore CS4014 } public void Dispose(bool disposing) { SegmentedCircularProgressBar?.Dispose(disposing); SegmentedPaddingCircularProgressBar?.Dispose(disposing); SegmentedFillingStyle?.Dispose(disposing); } public override void OnDisappearing() { isDisposed = true; this.Dispose(true); } private void SegmentedCircularProgressBar_ValueChanged(object sender, ProgressValueEventArgs e) { if (e.Progress.Equals(75)) { this.SegmentedCircularProgressBar.SetProgress(0, 0, Easing.Linear); } if (e.Progress.Equals(0)) { this.SegmentedCircularProgressBar.Progress = 75; } } private void SegmentedPaddingCircularProgressBar_ValueChanged(object sender, ProgressValueEventArgs e) { if (e.Progress.Equals(75)) { this.SegmentedPaddingCircularProgressBar.SetProgress(0, 0, Easing.Linear); } if (e.Progress.Equals(0)) { this.SegmentedPaddingCircularProgressBar.Progress = 75; } } private async Task SetSegmentedFillingStyleProgress() { double progress = 0; this.SegmentedFillingStyle.Progress = 0; await Task.Delay(300); while (progress < 100) { if (isDisposed) { break; } this.SegmentedFillingStyle.Progress = progress += 5; await Task.Delay(300); } if (!this.isDisposed) { await SetSegmentedFillingStyleProgress(); } } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Styles/SelectionStyle.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SelectionStyle.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Derived from DataGridStyle to add the custom styles /// </summary> public class SelectionStyle : DataGridStyle { /// <summary> /// Initializes a new instance of the SelectionStyle class. /// </summary> public SelectionStyle() { } /// <summary> /// Overrides this method to write a custom style for header back ground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetHeaderBackgroundColor() { return Color.FromHex("#e0e0e0"); } /// <summary> /// Overrides this method to write a custom style for record foreground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetRecordForegroundColor() { return Color.Black; } /// <summary> /// Overrides this method to write a custom style for record background color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetRecordBackgroundColor() { return Color.White; } } } <file_sep>/Android/SampleBrowser/Samples/PDF/ImageInsertion.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Java.IO; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.IO; using Syncfusion.Pdf.Parsing; using System.Threading.Tasks; using Syncfusion.Pdf; using System.Reflection; using Syncfusion.Pdf.Security; using Syncfusion.Drawing; using Syncfusion.Pdf.Graphics; namespace SampleBrowser { public partial class ImageInsertion : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to insert images in a PDF document."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate PDF"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { // Create a new instance of PdfDocument class. PdfDocument document = new PdfDocument(); // Add a new page to the newly created document. PdfPage page = document.Pages.Add(); PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold); PdfGraphics g = page.Graphics; g.DrawString("JPEG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 40)); //Load JPEG image to stream. Stream jpgImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Xamarin_JPEG.jpg"); //Load the JPEG image PdfImage jpgImage = new PdfBitmap(jpgImageStream); //Draw the JPEG image g.DrawImage(jpgImage,new Syncfusion.Drawing.RectangleF(0,70,515,215)); g.DrawString("PNG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 355)); //Load PNG image to stream. Stream pngImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Xamarin_PNG.png"); //Load the PNG image PdfImage pngImage = new PdfBitmap(pngImageStream); //Draw the PNG image g.DrawImage(pngImage,new Syncfusion.Drawing.RectangleF(0,365,199,300)); MemoryStream stream = new MemoryStream(); //Save the PDF document document.Save(stream); stream.Position = 0; //Close the PDF document document.Close(true); if (stream != null) { stream.Position=0; SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("ImageInsertion.pdf", "application/pdf", stream, m_context); } } } }<file_sep>/Android/SampleBrowser/Samples/LinearGauge/ScalesAndPointers.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfLinearGauge; namespace SampleBrowser { public class ScalesAndPointers : SamplePage { public static int pointervalue = 30; public static int barvalue=75; List<String> adapter, adapter1, adapter2; LinearScale outerScale; SymbolPointer outerScale_needlePointer; LinearLayout optionsPage; BarPointer rangePointer; public override View GetSampleContent(Android.Content.Context con) { /**************** **Linear Gauge** ****************/ SfLinearGauge linearGauge = new SfLinearGauge(con); ObservableCollection<LinearScale> scales = new ObservableCollection<LinearScale>(); ObservableCollection<LinearPointer> pointers = new ObservableCollection<LinearPointer>(); linearGauge.SetX(0); linearGauge.SetY(0); linearGauge.SetBackgroundColor(Color.Rgb(255, 255, 255)); linearGauge.SetOrientation(SfLinearGauge.Orientation.Horizontal); //OuterScale outerScale = new LinearScale(); outerScale.Minimum = 0; outerScale.Maximum = 100; outerScale.ScaleBarSize = 40; outerScale.Interval = 10; outerScale.ScaleBarColor = Color.ParseColor("#e0e9f9"); outerScale.MinorTicksPerInterval = 0; outerScale.LabelFontSize = 14; outerScale.LabelColor = Color.ParseColor("#424242"); outerScale.CornerRadius = 20; outerScale.CornerRadiusType = CornerRadiusType.End; //OuterScale MajorTicksSettings LinearTickSettings outerScale_majorTicksSettings = new LinearTickSettings(); outerScale_majorTicksSettings.Color = Color.ParseColor("#9E9E9E");// outerScale_majorTicksSettings.Length = 10; outerScale_majorTicksSettings.StrokeWidth = 1; outerScale.MajorTickSettings = outerScale_majorTicksSettings; //Symbol Pointer outerScale_needlePointer = new SymbolPointer(); outerScale_needlePointer.SymbolPosition = SymbolPointerPosition.Away; outerScale_needlePointer.Value = pointervalue; outerScale_needlePointer.StrokeWidth = 12; outerScale_needlePointer.Color = Color.ParseColor("#5b86e5"); outerScale_needlePointer.MarkerShape = MarkerShape.Triangle; outerScale_needlePointer.EnableAnimation = false; pointers.Add(outerScale_needlePointer); //Bar Pointer rangePointer = new BarPointer(); rangePointer.Value = barvalue; rangePointer.StrokeWidth = 30; rangePointer.EnableAnimation = false; rangePointer.CornerRadius = 15; rangePointer.CornerRadiusType = CornerRadiusType.End; rangePointer.GradientStops = new ObservableCollection<GaugeGradientStop>() { new GaugeGradientStop() { Value = 0, Color = Color.ParseColor("#36d1dc") }, new GaugeGradientStop() { Value = 75, Color = Color.ParseColor("#5b86e5") } }; pointers.Add(rangePointer); outerScale.Pointers = pointers; scales.Add(outerScale); linearGauge.Scales = scales; //Linear Gauge Layout LinearLayout linearGaugeLayout = new LinearLayout(con); linearGaugeLayout.SetBackgroundColor(Color.Rgb(255, 255, 255)); linearGaugeLayout.AddView(linearGauge); return linearGaugeLayout; } public override View GetPropertyWindowLayout(Android.Content.Context context) { TextView pointervalue1 = new TextView(context); pointervalue1.Text = "Opposite Position"; pointervalue1.Typeface = Typeface.DefaultBold; pointervalue1.SetTextColor(Color.ParseColor("#262626")); pointervalue1.TextSize = 20; Spinner selectLabelMode = new Spinner(context, SpinnerMode.Dialog); adapter = new List<String>() { "False", "True" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += SelectLabelMode_ItemSelected; TextView pointervalue2 = new TextView(context); pointervalue2.Text = "Corner Radius Type"; pointervalue2.Typeface = Typeface.DefaultBold; pointervalue2.SetTextColor(Color.ParseColor("#262626")); pointervalue2.TextSize = 20; Spinner selectLabelModel1 = new Spinner(context, SpinnerMode.Dialog); adapter1 = new List<String>() { "End", "Start", "Both", "None" }; ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter1); dataAdapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelModel1.Adapter = dataAdapter1; selectLabelModel1.ItemSelected += SelectLabelModel1_ItemSelected; TextView pointervalue3 = new TextView(context); pointervalue3.Text = "Marker Shapes"; pointervalue3.Typeface = Typeface.DefaultBold; pointervalue3.SetTextColor(Color.ParseColor("#262626")); pointervalue3.TextSize = 20; Spinner selectLabelModel2 = new Spinner(context, SpinnerMode.Dialog); adapter2 = new List<String>() { "Triangle", "Inverted Triangle", "Circle", "Diamond", "Rectangle", "Image" }; ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter2); dataAdapter2.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelModel2.Adapter = dataAdapter2; selectLabelModel2.ItemSelected += SelectLabelModel2_ItemSelected; optionsPage = new LinearLayout(context); optionsPage.Orientation = Orientation.Vertical; optionsPage.AddView(pointervalue1); optionsPage.AddView(selectLabelMode); optionsPage.AddView(pointervalue2); optionsPage.AddView(selectLabelModel1); optionsPage.AddView(pointervalue3); optionsPage.AddView(selectLabelModel2); optionsPage.SetPadding(10, 10, 10, 10); optionsPage.SetBackgroundColor(Color.White); return optionsPage; } private void SelectLabelModel2_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter2[e.Position]; if (selectedItem.Equals("Triangle")) { outerScale_needlePointer.MarkerShape = MarkerShape.Triangle; } else if (selectedItem.Equals("Inverted Triangle")) { outerScale_needlePointer.MarkerShape = MarkerShape.InvertedTriangle; } else if (selectedItem.Equals("Circle")) { outerScale_needlePointer.MarkerShape = MarkerShape.Circle; } else if (selectedItem.Equals("Diamond")) { outerScale_needlePointer.MarkerShape = MarkerShape.Diamond; } else if (selectedItem.Equals("Rectangle")) { outerScale_needlePointer.MarkerShape = MarkerShape.Rectangle; } else if (selectedItem.Equals("Image")) { outerScale_needlePointer.MarkerShape = MarkerShape.Image; outerScale_needlePointer.ImageSource = "location.png"; } } private void SelectLabelModel1_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter1[e.Position]; if (selectedItem.Equals("Start")) { outerScale.CornerRadiusType = CornerRadiusType.Start; rangePointer.CornerRadiusType = CornerRadiusType.Start; } else if (selectedItem.Equals("End")) { outerScale.CornerRadiusType = CornerRadiusType.End; rangePointer.CornerRadiusType = CornerRadiusType.End; } else if (selectedItem.Equals("Both")) { outerScale.CornerRadiusType = CornerRadiusType.Both; rangePointer.CornerRadiusType = CornerRadiusType.Both; } else if (selectedItem.Equals("None")) { outerScale.CornerRadiusType = CornerRadiusType.None; rangePointer.CornerRadiusType = CornerRadiusType.None; } } private void SelectLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter[e.Position]; if (selectedItem.Equals("True")) { outerScale.OpposedPosition = true; } else if (selectedItem.Equals("False")) { outerScale.OpposedPosition = false; } } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/ZoomingandPanning.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using CoreAnimation; #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class ZoomingandPanning : SampleView { SFChart chart; UILabel label; public ZoomingandPanning() { chart = new SFChart(); chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.Title.Text = new NSString("Height vs Weight"); chart.Delegate = new TooltipGenerator(); SFNumericalAxis primary = new SFNumericalAxis(); primary.ShowMajorGridLines = false; primary.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; primary.Minimum = new NSNumber(100); primary.Maximum = new NSNumber(220); primary.Interval = new NSNumber(20); primary.Title.Text = new NSString("Height in Inches"); chart.PrimaryAxis = primary; SFNumericalAxis secondary = new SFNumericalAxis(); secondary.Title.Text = new NSString("Weight in Pounds"); secondary.ShowMajorGridLines = false; secondary.Minimum = new NSNumber(50); secondary.Maximum = new NSNumber(80); secondary.Interval = new NSNumber(5); chart.SecondaryAxis = secondary; ChartViewModel dataModel = new ChartViewModel(); SFScatterSeries series = new SFScatterSeries(); series.ItemsSource = dataModel.ScatterMaleData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.ScatterHeight = 10; series.ScatterWidth = 10; series.Alpha = 0.7f; series.EnableAnimation = true; series.Label = "Male"; series.LegendIcon = SFChartLegendIcon.SeriesType; chart.Series.Add(series); SFScatterSeries series1 = new SFScatterSeries(); series1.ItemsSource = dataModel.ScatterFemaleData; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.EnableTooltip = true; series1.ScatterHeight = 10; series1.ScatterWidth = 10; series1.ShapeType = ChartScatterShapeType.Diamond; series1.Alpha = 0.7f; series1.EnableAnimation = true; series1.Label = "Female"; series1.LegendIcon = SFChartLegendIcon.SeriesType; chart.Series.Add(series1); chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; var tooltip = new SFChartTooltipBehavior(); tooltip.BackgroundColor = UIColor.FromRGBA(64.0f / 255.0f, 64.0f / 255.0f, 65.0f / 255.0f, 1.0f); chart.AddChartBehavior(tooltip); label = new UILabel(); label.Text = "Pinch to zoom or double tap and drag to select a region to zoom in"; label.Font = UIFont.FromName("Helvetica", 12f); label.TextAlignment = UITextAlignment.Center; label.LineBreakMode = UILineBreakMode.WordWrap; label.Lines = 2; label.BackgroundColor = UIColor.FromRGB(249, 249, 249); label.TextColor = UIColor.FromRGB(79, 86, 91); chart.AddChartBehavior(new SFChartZoomPanBehavior() { EnableSelectionZooming = true }); this.AddSubview(chart); CALayer topLine = new CALayer(); topLine.Frame = new CGRect(0, 0, UIScreen.MainScreen.ApplicationFrame.Width, 0.5); topLine.BackgroundColor = UIColor.FromRGB(178, 178, 178).CGColor; label.Layer.AddSublayer(topLine); this.AddSubview(label); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view == chart) chart.Frame = new CGRect(0, 0, Frame.Width, Frame.Height - 48); else if (view == label) label.Frame = new CGRect(0, Frame.Height - 32, Frame.Width, 40); else view.Frame = Frame; } base.LayoutSubviews(); } class TooltipGenerator : SFChartDelegate { public override void WillShowTooltip(SFChart chart, SFChartTooltip tooltipView) { UIView customView = new UIView(); customView.Frame = new CGRect(0, 0, 95, 55); var height = customView.Frame.Height / 3; UILabel label = new UILabel(); label.Frame = new CGRect(0, 0, customView.Frame.Width, height); label.TextColor = UIColor.White; label.Font = UIFont.FromName("Helvetica", 12f); label.TextAlignment = UITextAlignment.Center; label.Text = tooltipView.Series.Label; UILabel box = new UILabel(); box.Frame = new CGRect(customView.Frame.X, label.Frame.Height, customView.Frame.Width, 1); box.BackgroundColor = UIColor.White; UILabel xLabel = new UILabel(); xLabel.Frame = new CGRect(5, 35, 60, height); xLabel.TextColor = UIColor.LightGray; xLabel.Font = UIFont.FromName("Helvetica", 12f); xLabel.Text = "Height : "; UILabel xValue = new UILabel(); xValue.Frame = new CGRect(53, 35, 40, height); xValue.TextColor = UIColor.White; xValue.Font = UIFont.FromName("Helvetica", 12f); xValue.Text = (tooltipView.DataPoint as ChartDataModel).XValue.ToString(); UILabel yLabel = new UILabel(); yLabel.Frame = new CGRect(5, 20, 60, height); yLabel.TextColor = UIColor.LightGray; yLabel.Font = UIFont.FromName("Helvetica", 12f); yLabel.Text = "Weight : "; UILabel yValue = new UILabel(); yValue.Frame = new CGRect(54, 20, 55, height); yValue.TextColor = UIColor.White; yValue.Font = UIFont.FromName("Helvetica", 12f); yValue.Text = (tooltipView.DataPoint as ChartDataModel).YValue + " lbs"; customView.AddSubview(label); customView.AddSubview(box); customView.AddSubview(xLabel); customView.AddSubview(xValue); customView.AddSubview(yLabel); customView.AddSubview(yValue); tooltipView.CustomView = customView; } } } }<file_sep>/Forms/Diagram/Diagram/Samples/Connectors/Connectors.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Xamarin.Forms; using Syncfusion.SfDiagram.XForms; using SampleBrowser.Core; using System.Collections.ObjectModel; namespace SampleBrowser.SfDiagram { public partial class Connectors : SampleView { private float size = 1; private Node RootNode; public Connectors() { InitializeComponent(); diagram.ContextMenuSettings.Visibility = false; diagram.IsReadOnly = true; if (Device.RuntimePlatform == Device.Android) Xamarin.Forms.DependencyService.Get<IText>().GenerateFactor(); if (Device.RuntimePlatform == Device.UWP) { diagram.PageSettings.PageWidth = 1600; diagram.BackgroundColor = Color.White; } ObservableCollection<Employee> employees = new ObservableCollection<Employee>(); employees.Add(new Employee() { Name = "Elizabeth", EmpId = "1", ParentId = "", Designation = "CEO" }); employees.Add(new Employee() { Name = "Christina", EmpId = "2", ParentId = "1", Designation = "Manager" }); employees.Add(new Employee() { Name = "Yang", EmpId = "3", ParentId = "1", Designation = "Manager" }); employees.Add(new Employee() { Name = "Yoshi", EmpId = "4", ParentId = "2", Designation = "Team Lead" }); employees.Add(new Employee() { Name = "Yoshi", EmpId = "5", ParentId = "2", Designation = "Co-ordinator" }); employees.Add(new Employee() { Name = "Philip", EmpId = "6", ParentId = "4", Designation = "Developer" }); employees.Add(new Employee() { Name = "Philip", EmpId = "7", ParentId = "4", Designation = "Testing Engineer" }); employees.Add(new Employee() { Name = "Roland", EmpId = "8", ParentId = "3", Designation = "Team Lead" }); employees.Add(new Employee() { Name = "Yoshi", EmpId = "9", ParentId = "3", Designation = "Co-ordinator" }); employees.Add(new Employee() { Name = "Yuonne", EmpId = "10", ParentId = "8", Designation = "Developer" }); employees.Add(new Employee() { Name = "Philip", EmpId = "10", ParentId = "8", Designation = "Testing Engineer" }); //Initializes the DataSourceSettings diagram.DataSourceSettings = new DataSourceSettings() { DataSource = employees, Id = "EmpId", ParentId = "ParentId" }; //Initializes the Layout DirectedTreeLayout treelayout = new DirectedTreeLayout() { HorizontalSpacing = 80, VerticalSpacing = 50 * DiagramUtility.currentDensity, TreeOrientation = TreeOrientation.TopToBottom }; diagram.LayoutManager = new LayoutManager() { Layout = treelayout }; for (int i = 0; i < diagram.Connectors.Count; i++) { diagram.Connectors[i].TargetDecoratorType = DecoratorType.None; diagram.Connectors[i].Style.StrokeWidth = 1 * DiagramUtility.currentDensity; } diagram.BeginNodeRender += Diagram_BeginNodeRender; diagram.Loaded += Diagram_Loaded; strokeStyle.Items.Add("Default"); strokeStyle.Items.Add("Dashed"); strokeStyle.Items.Add("Dotted"); strokeStyle.SelectedIndex = 0; strokeStyle.SelectedIndexChanged += StrokeStyle_SelectedIndexChanged; } private Node GetParent(string parentId) { foreach (Node node in diagram.Nodes) { if ((node.Content as Employee).EmpId == parentId) { return node; } } return RootNode; } private void StrokeStyle_SelectedIndexChanged(object sender, EventArgs e) { Picker picker = (Picker)sender; switch (picker.SelectedItem.ToString()) { case "Default": foreach (Connector connector in diagram.Connectors) { connector.Style.StrokeStyle = StrokeStyle.Default; } break; case "Dashed": foreach (Connector connector in diagram.Connectors) { connector.Style.StrokeStyle = StrokeStyle.Dashed; } break; case "Dotted": foreach (Connector connector in diagram.Connectors) { connector.Style.StrokeStyle = StrokeStyle.Dotted; } break; } } private void OnGridSizeSubtract(object sender, EventArgs e) { if (size > 1) { size--; if (Device.RuntimePlatform == Device.Android) { foreach (Connector connector in diagram.Connectors) { connector.Style.StrokeWidth = size * (1 * DiagramUtility.currentDensity); } } else foreach (Connector connector in diagram.Connectors) { connector.Style.StrokeWidth = size; } GridtThickness.Text = size.ToString(); } } private void OnGridSizePlus(object sender, EventArgs e) { if (size < 5) { size++; if (Device.RuntimePlatform == Device.Android) { foreach (Connector connector in diagram.Connectors) { connector.Style.StrokeWidth = size * (1 * DiagramUtility.currentDensity); } } else foreach (Connector connector in diagram.Connectors) { connector.Style.StrokeWidth = size; } GridtThickness.Text = size.ToString(); } } private void Diagram_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); } private void Diagram_BeginNodeRender(object sender, BeginNodeRenderEventArgs args) { var node = args.Item; node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 0; if ((node.Content as Employee).Designation == "Manager") node.Style.Brush = new SolidBrush(Color.FromRgb(23, 132, 206)); else if ((node.Content as Employee).Designation == "CEO") { node.Style.Brush = new SolidBrush(Color.FromRgb(201, 32, 61)); RootNode = node; } else if ((node.Content as Employee).Designation == "Team Lead" || (node.Content as Employee).Designation == "Co-ordinator") node.Style.Brush = new SolidBrush(Color.FromRgb(4, 142, 135)); else node.Style.Brush = new SolidBrush(Color.FromRgb(206, 98, 9)); if (Device.RuntimePlatform == Device.UWP) { node.Width = 100; node.Height = 50; } else { node.Width = 144 * DiagramUtility.factor; node.Height = 60 * DiagramUtility.factor; } AnnotationCollection annotations = new AnnotationCollection(); if (Device.RuntimePlatform == Device.Android) annotations.Add(new Annotation() { Content = (node.Content as Employee).Designation, FontSize = 14 * DiagramUtility.factor, TextBrush = new SolidBrush(Color.White) }); else annotations.Add(new Annotation() { Content = (node.Content as Employee).Designation, FontSize = 15 * DiagramUtility.factor, TextBrush = new SolidBrush(Color.White) }); node.Annotations = annotations; } private void OnStraight(object sender, EventArgs e) { OnSegmentChange(SegmentType.StraightSegment); StraightSegment.BackgroundColor = Color.DodgerBlue; CurveSegment.BackgroundColor = Color.FromHex("#fdfdfd"); OrthoSegment.BackgroundColor = Color.FromHex("#fdfdfd"); (StraightIcon.Source as FontImageSource).Color = Color.White; (CurveIcon.Source as FontImageSource).Color = Color.FromHex("#000000"); (OrthoIcon.Source as FontImageSource).Color = Color.FromHex("#000000"); } private void OnCurve(object sender, EventArgs e) { OnSegmentChange(SegmentType.CurveSegment); CurveSegment.BackgroundColor = Color.DodgerBlue; StraightSegment.BackgroundColor = Color.FromHex("#fdfdfd"); OrthoSegment.BackgroundColor = Color.FromHex("#fdfdfd"); (StraightIcon.Source as FontImageSource).Color = Color.FromHex("#000000"); (CurveIcon.Source as FontImageSource).Color = Color.White; (OrthoIcon.Source as FontImageSource).Color = Color.FromHex("#000000"); } private void OnOrtho(object sender, EventArgs e) { OnSegmentChange(SegmentType.OrthoSegment); OrthoSegment.BackgroundColor = Color.DodgerBlue; StraightSegment.BackgroundColor = Color.FromHex("#fdfdfd"); CurveSegment.BackgroundColor = Color.FromHex("#fdfdfd"); (StraightIcon.Source as FontImageSource).Color = Color.FromHex("#000000"); (CurveIcon.Source as FontImageSource).Color = Color.FromHex("#000000"); (OrthoIcon.Source as FontImageSource).Color = Color.White; } void OnSegmentChange(SegmentType segmenttype) { foreach (Connector connector in diagram.Connectors) { connector.SegmentType = segmenttype; } } } //Employee Business Object public class Employee { public string ParentId { get; set; } public string Name { get; set; } public string Designation { get; set; } public string EmpId { get; set; } } //Employee Collection public class Employees : ObservableCollection<Employee> { } } <file_sep>/Forms/Chart/Chart/Samples/RadarChart/RadarChart.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class RadarChart : SampleView { public RadarChart() { InitializeComponent(); angle.SelectedIndex = 3; angle.SelectedIndexChanged += polarStartAngle_Changed; radarDrawType.SelectedIndex = 1; radarDrawType.SelectedIndexChanged += radarDrawType_Changed; if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { secondaryAxisLabelSyle.LabelFormat = "0'M'"; } else { secondaryAxisLabelSyle.LabelFormat = "#'M'"; } if (Device.RuntimePlatform == Device.macOS || Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { Chart.Legend.OverflowMode = ChartLegendOverflowMode.Scroll; } } void polarStartAngle_Changed(object sender, EventArgs e) { switch (angle.SelectedIndex) { case 0: primary.PolarAngle = ChartPolarAngle.Rotate0; secondary.PolarAngle = ChartPolarAngle.Rotate0; break; case 1: primary.PolarAngle = ChartPolarAngle.Rotate90; secondary.PolarAngle = ChartPolarAngle.Rotate90; break; case 2: primary.PolarAngle = ChartPolarAngle.Rotate180; secondary.PolarAngle = ChartPolarAngle.Rotate180; break; case 3: primary.PolarAngle = ChartPolarAngle.Rotate270; secondary.PolarAngle = ChartPolarAngle.Rotate270; break; } } void radarDrawType_Changed(object sender, EventArgs e) { switch (radarDrawType.SelectedIndex) { case 0: series1.DrawType = PolarRadarSeriesDrawType.Line; series2.DrawType = PolarRadarSeriesDrawType.Line; series3.DrawType = PolarRadarSeriesDrawType.Line; break; case 1: series1.DrawType = PolarRadarSeriesDrawType.Area; series2.DrawType = PolarRadarSeriesDrawType.Area; series3.DrawType = PolarRadarSeriesDrawType.Area; break; } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if ((Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS)) { if (height > 0 && width > 0) { if (height > width) { Chart.Legend.DockPosition = LegendPlacement.Top; } else { Chart.Legend.DockPosition = LegendPlacement.Right; } } } } } } <file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/README.md The pull-to-refresh control provides a panel that can be pulled to refresh data in an application through user interaction or programmatically. The appearance and transition of the progress indicator can be customized. The following samples are available for pull-to-refresh to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Weather Data](PullToRefreshDemo.cs) | This sample showcases the pull-to-refresh capability with a simple layout displaying the weather condition of various cities and allows you to update the weather conditions upon pull-to-refresh action. | | [Pull To Refresh with UICollectionView](UICollectionViewInPullToRefresh.cs) | This sample showcases the pull-to-refresh capability when hosting the UICollectionView control that allows you to refresh the bound data source of the list upon pull-to-refresh action. | | [Pull To Refresh with DataGrid](SfDataGridInPullToRefresh.cs)| This sample showcases the pull-to-refresh capability when hosting the DataGrid control that allows you to refresh the bound data source of the grid upon pull-to-refresh action. |<file_sep>/Android/SampleBrowser/Samples/Presentation/OLEObject.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public partial class OLEObjectPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to insert and extract a OLE Object in PowerPoint presentation."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Create Presentation"; button1.Click += OnInsertOleButtonClicked; linear.AddView(button1); Button button2 = new Button(con); button2.Text = "Open Embedded File"; button2.Click += OnButtonClicked; linear.AddView(button2); return linear; } void OnInsertOleButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); //New Instance of PowerPoint is Created.[Equivalent to launching MS PowerPoint with no slides]. IPresentation presentation = Syncfusion.Presentation.Presentation.Create(); ISlide slide = presentation.Slides.Add(SlideLayoutType.TitleOnly); IShape titleShape = slide.Shapes[0] as IShape; titleShape.Left = 0.65 * 72; titleShape.Top = 0.24 * 72; titleShape.Width = 11.5 * 72; titleShape.Height = 1.45 * 72; titleShape.TextBody.AddParagraph("Ole Object"); titleShape.TextBody.Paragraphs[0].Font.Bold = true; titleShape.TextBody.Paragraphs[0].HorizontalAlignment = HorizontalAlignmentType.Left; IShape heading = slide.Shapes.AddTextBox(100, 100, 100, 100); heading.Left = 0.84 * 72; heading.Top = 1.65 * 72; heading.Width = 2.23 * 72; heading.Height = 0.51 * 72; heading.TextBody.AddParagraph("MS Word Object"); heading.TextBody.Paragraphs[0].Font.Italic = true; heading.TextBody.Paragraphs[0].Font.Bold = true; heading.TextBody.Paragraphs[0].Font.FontSize = 18; string mswordPath = "SampleBrowser.Samples.Presentation.Templates.OleTemplate.docx"; //Get the word file as stream Stream wordStream = assembly.GetManifestResourceStream(mswordPath); string imagePath = "SampleBrowser.Samples.Presentation.Templates.OlePicture.png"; //Image to be displayed, This can be any image Stream imageStream = assembly.GetManifestResourceStream(imagePath); IOleObject oleObject = slide.Shapes.AddOleObject(imageStream, "Word.Document.12", wordStream); //Set size and position of the ole object oleObject.Left = 4.53 * 72; oleObject.Top = 0.79 * 72; oleObject.Width = 4.26 * 72; oleObject.Height = 5.92 * 72; //Set DisplayAsIcon as true, to open the embedded document in separate (default) application. oleObject.DisplayAsIcon = true; MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("InsertOLEObject.pptx", "application/powerpoint", stream, m_context); } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.EmbeddedOleObject.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Gets the first slide of the Presentation ISlide slide = presentation.Slides[0]; //Gets the Ole Object of the slide IOleObject oleObject = slide.Shapes[2] as IOleObject; //Gets the file data of embedded Ole Object. byte[] array = oleObject.ObjectData; //Gets the file Name of OLE Object string outputFile = oleObject.FileName; MemoryStream stream = new MemoryStream(array); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save (outputFile, "application/msword", stream, m_context); } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Bubble.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { internal class Bubble : SamplePage { BubbleTooltipBehavior tooltipBehavior; public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "World Countries Details"; chart.Title.TextSize = 15; NumericalAxis primaryAxis = new NumericalAxis(); primaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; primaryAxis.Minimum = 60; primaryAxis.Maximum = 100; primaryAxis.Interval = 5; primaryAxis.Title.Text = "Literacy Rate"; primaryAxis.ShowMajorGridLines = false; primaryAxis.ShowMinorGridLines = false; chart.PrimaryAxis = primaryAxis; NumericalAxis secondaryAxis = new NumericalAxis(); secondaryAxis.Minimum = 0; secondaryAxis.Maximum = 10; secondaryAxis.Interval = 2.5; secondaryAxis.Title.Text = "GDP Growth Rate"; secondaryAxis.ShowMajorGridLines = false; secondaryAxis.ShowMinorGridLines = false; chart.SecondaryAxis = secondaryAxis; var bubble = new BubbleSeries(); bubble.MinimumRadius = 5; bubble.MaximumRadius = 40; bubble.Alpha = 0.7f; bubble.ColorModel.ColorPalette = ChartColorPalette.Natural; bubble.ItemsSource = MainPage.GetBubbleData(); bubble.XBindingPath = "XValue"; bubble.YBindingPath = "YValue"; bubble.Size = "Size"; bubble.EnableAnimation = true; chart.Series.Add(bubble); bubble.TooltipEnabled = true; tooltipBehavior = new BubbleTooltipBehavior(context); chart.Behaviors.Add(tooltipBehavior); chart.TooltipCreated += Chart_TooltipCreated; return chart; } private void Chart_TooltipCreated(object sender, SfChart.TooltipCreatedEventArgs e) { tooltipBehavior.MarginLeft = 80; tooltipBehavior.MarginTop = 40; tooltipBehavior.MarginRight = 65; tooltipBehavior.MarginBottom = 40; tooltipBehavior.BackgroundColor = Color.ParseColor("#404041"); tooltipBehavior.TextColor = Color.Transparent; tooltipBehavior.StrokeWidth = 1f; } } class BubbleTooltipBehavior : ChartTooltipBehavior { Context context; public BubbleTooltipBehavior(Context con) { context = con; } protected override View GetView(TooltipView p0) { LinearLayout rootLayout = new LinearLayout(context); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); rootLayout.Orientation = Orientation.Vertical; rootLayout.LayoutParameters = layoutParams; rootLayout.SetPadding(10, 5, 5, 5); TextView label = new TextView(context); label.Text = (p0.ChartDataPoint as DataPoint).Label.ToString(); label.TextSize = 12; label.TextAlignment = Android.Views.TextAlignment.Center; label.SetPadding(150, 0, 0, 0); label.SetTextColor(Color.White); LinearLayout line = new LinearLayout(context); LinearLayout.LayoutParams linelayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 4); line.LayoutParameters = linelayoutParams; line.SetBackgroundColor(Color.White); LinearLayout xLayout = new LinearLayout(context); xLayout.Orientation = Orientation.Horizontal; xLayout.SetPadding(0, 5, 0, 0); TextView xLabel = new TextView(context); xLabel.Text = "Literacy Rate : "; xLabel.TextSize = 12; xLabel.SetTextColor(Color.ParseColor("#CCCCCC")); TextView xValue = new TextView(context); xValue.Text = (p0.ChartDataPoint as DataPoint).XValue + "%"; xValue.TextSize = 12; xValue.SetTextColor(Color.White); xLayout.AddView(xLabel); xLayout.AddView(xValue); LinearLayout yLayout = new LinearLayout(context); yLayout.Orientation = Orientation.Horizontal; yLayout.SetPadding(0, 5, 0, 0); TextView yLabel = new TextView(context); yLabel.Text = "GDP Growth Rate : "; yLabel.TextSize = 12; yLabel.SetTextColor(Color.ParseColor("#CCCCCC")); TextView yValue = new TextView(context); yValue.Text = (p0.ChartDataPoint as DataPoint).YValue.ToString(); yValue.TextSize = 12; yValue.SetTextColor(Color.White); yLayout.AddView(yLabel); yLayout.AddView(yValue); LinearLayout sizeLayout = new LinearLayout(context); sizeLayout.Orientation = Orientation.Horizontal; sizeLayout.SetPadding(0, 5, 0, 0); TextView sizeLabel = new TextView(context); sizeLabel.Text = "Population : "; sizeLabel.TextSize = 12; sizeLabel.SetTextColor(Color.ParseColor("#CCCCCC")); TextView sizeValue = new TextView(context); sizeValue.Text = (p0.ChartDataPoint as DataPoint).Size + " Billion"; sizeValue.TextSize = 12; sizeValue.SetTextColor(Color.White); sizeLayout.AddView(sizeLabel); sizeLayout.AddView(sizeValue); rootLayout.AddView(label); rootLayout.AddView(line); rootLayout.AddView(xLayout); rootLayout.AddView(yLayout); rootLayout.AddView(sizeLayout); p0.AddView(rootLayout); return p0; } } }<file_sep>/Forms/Maps/Maps/Samples/MapsGettingStarted/MapsGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfMaps.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] //[XamlCompilation(XamlCompilationOptions.Compile)] public partial class MapsGettingStarted : SampleView { public MapsGettingStarted() { InitializeComponent(); (this.Maps.Layers[0] as ShapeFileLayer).ShapeSettings.ColorMappings.Clear(); (this.Maps.Layers[0] as ShapeFileLayer).MarkerSettings.TooltipSettings.TooltipTemplate = grid.Resources["toolTipTemplate"] as DataTemplate; } } public class CustomMarker : MapMarker { public String ImageName { get; set; } public String Location { get; set; } public String Population { get; set; } public CustomMarker() { ImageName = "pin.png"; } } } <file_sep>/Forms/Border/Border/Samples/GettingStartedSample/GettingStartedSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using SelectionChangedEventArgs = Syncfusion.XForms.Buttons.SelectionChangedEventArgs; using Syncfusion.XForms.Buttons; using System.Collections.ObjectModel; using Xamarin.Forms; namespace SampleBrowser.SfBorder { #region Getting Started Sample Class public partial class GettingStartedSample : SampleView { #region Constructor GettingStartedSampleViewModel viewModel; public GettingStartedSample() { InitializeComponent(); viewModel = new GettingStartedSampleViewModel(); this.BorderColorSegment.ItemsSource = viewModel.PrimaryColors; this.BindingContext = viewModel; if(Device.RuntimePlatform == Device.UWP) { shadow.IsVisible = false; } } void Handle_SelectionChanged(object sender, SelectionChangedEventArgs e) { viewModel.BorderColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; this.BorderColorSegment.SelectionTextColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; } void BorderTypeToggled(object sender, Xamarin.Forms.ToggledEventArgs e) { border.DashArray = dottedArraySwitch.IsToggled ? new double[] { 10, 5 } : new double[] { 0, 0 }; } #endregion } #endregion }<file_sep>/Forms/Schedule/Schedule/Samples/Resource/ViewModel/ResourceViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfSchedule.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Resource View Model class. [Preserve(AllMembers = true)] #region ResourceViewModel public class ResourceViewModel : INotifyPropertyChanged { /// <summary> /// current day meetings /// </summary> private List<string> currentDayMeetings; /// <summary> /// minimum time meetings /// </summary> private List<string> minTimeMeetings; /// <summary> /// color collection /// </summary> private List<Color> colorCollection; /// <summary> /// list of meeting /// </summary> private ObservableCollection<Meeting> listOfMeeting; /// <summary> /// name collection /// </summary> private List<string> nameCollection; /// <summary> /// resources /// </summary> private ObservableCollection<object> resources; /// <summary> /// selected Resources /// </summary> private ObservableCollection<object> selectedResources; /// <summary> /// Initializes a new instance of the <see cref="ResourceViewModel" /> class. /// </summary> public ResourceViewModel() { this.ListOfMeeting = new ObservableCollection<Meeting>(); Resources = new ObservableCollection<object>(); SelectedResources = new ObservableCollection<object>(); this.InitializeDataForBookings(); this.InitializeResources(); this.BookingAppointments(); } private void InitializeResources() { Random random = new Random(); for (int i = 0; i < 15; i++) { Employees employees = new Employees(); employees.Name = nameCollection[i]; employees.Color = Color.FromRgb(random.Next(0, 255), random.Next(10, 255), random.Next(100, 255)); employees.ID = i.ToString(); if (i < 9) { if (employees.Name == "Brooklyn") { employees.Image = "People_Circle8.png"; } else if (employees.Name == "Sophia") { employees.Image = "People_Circle1.png"; } else if (employees.Name == "Stephen") { employees.Image = "People_Circle12.png"; } else if (employees.Name == "<NAME>") { employees.Image = "People_Circle2.png"; } else if (employees.Name == "Daniel") { employees.Image = "People_Circle14.png"; } else if (employees.Name == "Emilia") { employees.Image = "People_Circle3.png"; } else if (employees.Name == "<NAME>") { employees.Image = "People_Circle4.png"; } else if (employees.Name == "<NAME>") { employees.Image = "People_Circle5.png"; } else if (employees.Name == "<NAME>") { employees.Image = "People_Circle6.png"; } } else { employees.Image = null; } Resources.Add(employees); } for (int i = 0; i < 10; i++) { SelectedResources.Add(Resources[random.Next(Resources.Count)]); } } /// <summary> /// Property changed event handler /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region ListOfMeeting /// <summary> /// Gets or sets list of meeting /// </summary> public ObservableCollection<Meeting> ListOfMeeting { get { return this.listOfMeeting; } set { this.listOfMeeting = value; this.RaiseOnPropertyChanged("ListOfMeeting"); } } #endregion public ObservableCollection<object> Resources { get { return resources; } set { resources = value; this.RaiseOnPropertyChanged("Resources"); } } public ObservableCollection<object> SelectedResources { get { return selectedResources; } set { selectedResources = value; this.RaiseOnPropertyChanged("selectedResources"); } } #region BookingAppointments /// <summary> /// Method for booking appointments. /// </summary> private void BookingAppointments() { Random randomTime = new Random(); List<Point> randomTimeCollection = this.GettingTimeRanges(); DateTime date; DateTime dateFrom = DateTime.Now.AddDays(-80); DateTime dateTo = DateTime.Now.AddDays(80); DateTime dateRangeStart = DateTime.Now.AddDays(-70); DateTime dateRangeEnd = DateTime.Now.AddDays(70); for (date = dateFrom; date < dateTo; date = date.AddDays(1)) { if ((DateTime.Compare(date, dateRangeStart) > 0) && (DateTime.Compare(date, dateRangeEnd) < 0)) { for (int additionalAppointmentIndex = 0; additionalAppointmentIndex < 3; additionalAppointmentIndex++) { Meeting meeting = new Meeting(); int hour = randomTime.Next((int)randomTimeCollection[additionalAppointmentIndex].X, (int)randomTimeCollection[additionalAppointmentIndex].Y); meeting.From = new DateTime(date.Year, date.Month, date.Day, randomTime.Next(9, 14), 0, 0); meeting.To = meeting.From.AddHours(randomTime.Next(1, 3)); meeting.EventName = this.currentDayMeetings[randomTime.Next(9)]; meeting.Color = this.colorCollection[randomTime.Next(9)]; meeting.IsAllDay = false; meeting.StartTimeZone = string.Empty; meeting.EndTimeZone = string.Empty; var coll = new ObservableCollection<object> { (resources[randomTime.Next(Resources.Count)] as Employees).ID }; meeting.Resources = coll; this.ListOfMeeting.Add(meeting); } } else { Meeting meeting = new Meeting(); meeting.From = new DateTime(date.Year, date.Month, date.Day, randomTime.Next(9, 11), 0, 0); meeting.To = meeting.From.AddDays(2).AddHours(1); meeting.EventName = this.currentDayMeetings[randomTime.Next(9)]; meeting.Color = this.colorCollection[randomTime.Next(9)]; meeting.IsAllDay = true; meeting.StartTimeZone = string.Empty; meeting.EndTimeZone = string.Empty; var coll = new ObservableCollection<object> { (resources[randomTime.Next(Resources.Count)] as Employees).ID }; meeting.Resources = coll; this.ListOfMeeting.Add(meeting); } } // Minimum Height Meetings DateTime minDate; DateTime minDateFrom = DateTime.Now.AddDays(-2); DateTime minDateTo = DateTime.Now.AddDays(2); for (minDate = minDateFrom; minDate < minDateTo; minDate = minDate.AddDays(1)) { Meeting meeting = new Meeting(); meeting.From = new DateTime(minDate.Year, minDate.Month, minDate.Day, randomTime.Next(9, 18), 30, 0); meeting.To = meeting.From; meeting.EventName = this.minTimeMeetings[randomTime.Next(0, 4)]; meeting.Color = this.colorCollection[randomTime.Next(0, 10)]; meeting.StartTimeZone = string.Empty; meeting.EndTimeZone = string.Empty; // Setting Mininmum Appointment Height for Schedule Appointments if (Device.RuntimePlatform == "Android") { meeting.MinimumHeight = 50; } else { meeting.MinimumHeight = 25; } this.ListOfMeeting.Add(meeting); } } #endregion BookingAppointments #region GettingTimeRanges /// <summary> /// Method for get timing range. /// </summary> /// <returns>return time collection</returns> private List<Point> GettingTimeRanges() { List<Point> randomTimeCollection = new List<Point>(); randomTimeCollection.Add(new Point(9, 11)); randomTimeCollection.Add(new Point(12, 14)); randomTimeCollection.Add(new Point(15, 17)); return randomTimeCollection; } #endregion GettingTimeRanges #region InitializeDataForBookings /// <summary> /// Method for initialize data bookings. /// </summary> private void InitializeDataForBookings() { this.currentDayMeetings = new List<string>(); this.currentDayMeetings.Add("General Meeting"); this.currentDayMeetings.Add("Plan Execution"); this.currentDayMeetings.Add("Project Plan"); this.currentDayMeetings.Add("Consulting"); this.currentDayMeetings.Add("Performance Check"); this.currentDayMeetings.Add("Yoga Therapy"); this.currentDayMeetings.Add("Plan Execution"); this.currentDayMeetings.Add("Project Plan"); this.currentDayMeetings.Add("Consulting"); this.currentDayMeetings.Add("Performance Check"); // MinimumHeight Appointment Subjects this.minTimeMeetings = new List<string>(); this.minTimeMeetings.Add("Work log alert"); this.minTimeMeetings.Add("Birthday wish alert"); this.minTimeMeetings.Add("Task due date"); this.minTimeMeetings.Add("Status mail"); this.minTimeMeetings.Add("Start sprint alert"); this.colorCollection = new List<Color>(); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); this.nameCollection = new List<string>(); this.nameCollection.Add("Brooklyn"); this.nameCollection.Add("<NAME>"); this.nameCollection.Add("Sophia"); this.nameCollection.Add("Stephen"); this.nameCollection.Add("<NAME>"); this.nameCollection.Add("Daniel"); this.nameCollection.Add("Emilia"); this.nameCollection.Add("<NAME>"); this.nameCollection.Add("<NAME>"); this.nameCollection.Add("<NAME>"); this.nameCollection.Add("<NAME>"); this.nameCollection.Add("<NAME>"); this.nameCollection.Add("<NAME>"); this.nameCollection.Add("<NAME>"); this.nameCollection.Add("<NAME>"); } #endregion InitializeDataForBookings #region Property Changed Event /// <summary> /// Invoke method when property changed /// </summary> /// <param name="propertyName">property name</param> private void RaiseOnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } #endregion }<file_sep>/iOS/SampleBrowser/Samples/XlsIO/DataTable.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XlsIO; using Syncfusion.SfDataGrid; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.ComponentModel; using System.Data; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class DataTable : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; UIButton btnInput; UIButton btnImport; SfDataGrid sfGrid; public DataTable() { label = new UILabel(); label1 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnExportButtonClicked; btnInput = new UIButton(UIButtonType.System); btnInput.TouchUpInside += OnButtonInputClicked; btnImport = new UIButton(UIButtonType.System); btnImport.TouchUpInside += OnButtonImportClicked; sfGrid = new SfDataGrid(); sfGrid.AutoGenerateColumns = false; sfGrid.RowHeight = 50; sfGrid.AllowEditing = true; sfGrid.EditTapAction = TapAction.OnTap; sfGrid.ColumnSizer = ColumnSizer.Star; sfGrid.SelectionMode = SelectionMode.None; sfGrid.HeaderRowHeight = 40; sfGrid.ItemsSource = GetEmptyData(); GridTextColumn salesPerson = new GridTextColumn(); salesPerson.MappingName = "SalesPerson"; salesPerson.HeaderText = "Name"; salesPerson.HeaderTextAlignment = UIKit.UITextAlignment.Center; GridTextColumn salesJanJune = new GridTextColumn(); salesJanJune.MappingName = "SalesJanJune"; salesJanJune.HeaderText = "Jan-June"; salesPerson.HeaderTextAlignment = UIKit.UITextAlignment.Center; GridTextColumn salesJulyDec = new GridTextColumn(); salesJulyDec.MappingName = "SalesJulyDec"; salesJulyDec.HeaderText = "July-Dec"; salesPerson.HeaderTextAlignment = UIKit.UITextAlignment.Center; GridTextColumn change = new GridTextColumn(); change.MappingName = "Change"; change.HeaderText = "Change"; salesPerson.HeaderTextAlignment = UIKit.UITextAlignment.Center; sfGrid.Columns.Add(salesPerson); sfGrid.Columns.Add(salesJanJune); sfGrid.Columns.Add(salesJulyDec); sfGrid.Columns.Add(change); this.AddSubview(sfGrid); } private object GetEmptyData() { List<CustomerObject> customerObjects = new List<CustomerObject>(); for (int i = 0; i < 20; i++) customerObjects.Add(new CustomerObject()); return customerObjects; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample allows you to import/export data from/to DataTable."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } this.AddSubview(label); btnInput.SetTitle("Input Template", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { btnInput.Frame = new CGRect(0, 65, frameRect.Location.X + frameRect.Size.Width, 10); } else { btnInput.Frame = new CGRect(5, 65, frameRect.Size.Width, 10); } this.AddSubview(btnInput); btnImport.SetTitle("Import From Excel", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { btnImport.Frame = new CGRect(0, 95, frameRect.Location.X + frameRect.Size.Width, 10); } else { btnImport.Frame = new CGRect(5, 95, frameRect.Size.Width, 10); } this.AddSubview(btnImport); button.SetTitle("Export To Excel", UIControlState.Normal); button.Enabled = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 125, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(5, 125, frameRect.Size.Width, 10); } this.AddSubview(button); this.sfGrid.Frame = new CGRect(0, 145, this.Frame.Width, this.Frame.Height - 145); base.LayoutSubviews(); } void OnButtonInputClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExportSales.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("InputTemplate.xlsx", "application/msexcel", stream); } } void OnButtonImportClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExportSales.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); IWorksheet sheet = workbook.Worksheets[0]; #endregion //Export DataTable from Excel worksheet System.Data.DataTable dataTable = sheet.ExportDataTable(sheet.UsedRange, ExcelExportDataTableOptions.ColumnNames); //Set exported DataTable as datasource to DataGrid sfGrid.ItemsSource = dataTable; button.Enabled = true; } void OnExportButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; //A new workbook is created.[Equivalent to creating a new workbook in MS Excel] //The new workbook will have 1 worksheets IWorkbook workbook = application.Workbooks.Create(1); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; //Get DataGrid's datasource as DataTable System.Data.DataTable dataTable = (System.Data.DataTable)sfGrid.ItemsSource; //Import DataTable to Excel worksheet. sheet.ImportDataTable(dataTable, 5, 1, false); #region Define Styles IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle"); IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle"); pageHeader.Font.RGBColor = COLOR.Color.FromArgb(255, 83, 141, 213); pageHeader.Font.FontName = "Calibri"; pageHeader.Font.Size = 18; pageHeader.Font.Bold = true; pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Font.Color = ExcelKnownColors.Black; tableHeader.Font.Bold = true; tableHeader.Font.Size = 11; tableHeader.Font.FontName = "Calibri"; tableHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; tableHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Color = COLOR.Color.FromArgb(255, 118, 147, 60); tableHeader.Borders[ExcelBordersIndex.EdgeLeft].LineStyle = ExcelLineStyle.Thin; tableHeader.Borders[ExcelBordersIndex.EdgeRight].LineStyle = ExcelLineStyle.Thin; tableHeader.Borders[ExcelBordersIndex.EdgeTop].LineStyle = ExcelLineStyle.Thin; tableHeader.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin; #endregion #region Apply Styles // Apply style for header sheet["A1:D1"].Merge(); sheet["A1"].Text = "Yearly Sales Report"; sheet["A1"].CellStyle = pageHeader; sheet["A1"].RowHeight = 20; sheet["A2:D2"].Merge(); sheet["A2"].Text = "Namewise Sales Comparison Report"; sheet["A2"].CellStyle = pageHeader; sheet["A2"].CellStyle.Font.Bold = false; sheet["A2"].CellStyle.Font.Size = 16; sheet["A2"].RowHeight = 20; sheet["A3:A4"].Merge(); sheet["D3:D4"].Merge(); sheet["B3:C3"].Merge(); sheet["B3"].Text = "Sales"; sheet["A3:D4"].CellStyle = tableHeader; sheet["A3"].Text = "Sales Person"; sheet["B4"].Text = "Jan - Jun"; sheet["C4"].Text = "Jul - Dec"; sheet["D3"].Text = "Change (%)"; sheet.Columns[0].ColumnWidth = 19; sheet.Columns[1].ColumnWidth = 10; sheet.Columns[2].ColumnWidth = 10; sheet.Columns[3].ColumnWidth = 11; #endregion workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("DataTable.xlsx", "application/msexcel", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Forms/DataGrid/DataGrid.iOS/FormsViewRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "FormsViewRenderer.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion using System; using System.Collections.Generic; using System.Text; using SampleBrowser.SfDataGrid; using SampleBrowser.SfDataGrid.iOS; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(FormsView), typeof(FormsViewRenderer))] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed.")] namespace SampleBrowser.SfDataGrid.iOS { /// <summary> /// A custom View renderer for IOS platform /// </summary> internal class FormsViewRenderer : ViewRenderer { /// <summary> /// Gets the value of the PCL View /// </summary> public FormsView FormsView { get { return this.Element as FormsView; } } /// <summary> /// Called while Element has changed in View /// </summary> /// <param name="e">Element Changed Event of View args e</param> protected override void OnElementChanged(ElementChangedEventArgs<View> e) { if (e.NewElement != null) { this.BackgroundColor = this.Element.BackgroundColor.ToUIColor(); } base.OnElementChanged(e); } /// <summary> /// Called while Elements property has changed in View /// </summary> /// <param name="sender">Indicates sender of the event</param> /// <param name="e">Indicates PropertyChangedEvent args e</param> protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == "Visibility") { if (this.FormsView.Visibility) { this.Hidden = false; if (this.Control != null) { this.Control.Hidden = false; } } else { this.Hidden = true; if (this.Control != null) { this.Control.Hidden = true; } } } } } } <file_sep>/Forms/Schedule/Schedule/Samples/DragDrop/Behaviors/DragDropBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Drag drop behavior. /// </summary> internal class DragDropBehaviour : Behavior<SampleView> { /// <summary> /// schedule initialize /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule schedule; /// <summary> /// view picker /// </summary> private Picker viewPicker; /// <summary> /// label value /// </summary> private Label label; /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(SampleView bindable) { base.OnAttachedTo(bindable); this.schedule = bindable.Content.FindByName<Syncfusion.SfSchedule.XForms.SfSchedule>("Schedule"); if (Device.RuntimePlatform == Device.Android) { this.schedule.ViewHeaderStyle.DateFontSize = 24; } this.viewPicker = bindable.FindByName<Picker>("viewPicker"); this.label = bindable.Content.FindByName<Label>("labelIndicator"); this.label.WidthRequest = this.schedule.Width; this.label.BackgroundColor = Color.FromHex("#2e2f30"); if (bindable.GetType().Equals(typeof(RecursiveAppointments))) { this.viewPicker.SelectedIndex = 3; } else if (bindable.GetType().Equals(typeof(ViewCustomization))) { this.viewPicker.SelectedIndex = 0; } else { this.viewPicker.SelectedIndex = 2; } this.viewPicker.SelectedIndexChanged += this.ViewPicker_SelectedIndexChanged; this.schedule.AppointmentDrop += this.Schedule_AppointmentDrop; this.schedule.CellTapped += this.Schedule_CellTapped; this.SetNonAccessibleBlocks(); } /// <summary> /// Disposing the elements /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); if (this.viewPicker != null) { this.viewPicker.SelectedIndexChanged -= this.ViewPicker_SelectedIndexChanged; this.viewPicker = null; } if (this.schedule != null) { this.schedule.AppointmentDrop -= this.Schedule_AppointmentDrop; this.schedule.CellTapped -= this.Schedule_CellTapped; this.schedule = null; } } /// <summary> /// Schedules the cell tapped. /// </summary> /// <param name="sender">Sender value.</param> /// <param name="e">E value.</param> private void Schedule_CellTapped(object sender, CellTappedEventArgs e) { this.label.HeightRequest = 0; } /// <summary> /// Schedules the appointment drop. /// </summary> /// <param name="sender">Sender value.</param> /// <param name="e">E value.</param> private async void Schedule_AppointmentDrop(object sender, AppointmentDropEventArgs e) { e.Cancel = false; var appointment = e.Appointment as ScheduleAppointment; this.label.Opacity = 1; this.label.HeightRequest = 50; if (Device.RuntimePlatform == "Android" || Device.RuntimePlatform == "iOS") { if (this.IsInNonAccessRegion(e.DropTime)) { e.Cancel = true; this.label.Text = "Cannot be moved to blocked time slots"; await this.label.FadeTo(0, 2000, Easing.SpringIn); this.label.HeightRequest = 0; return; } } this.label.Text = this.GetDroppedLocation(e.DropTime); await this.label.FadeTo(0, 2000, Easing.SpringIn); this.label.HeightRequest = 0; } /// <summary> /// Views the picker selected index changed. /// </summary> /// <param name="sender">Sender value.</param> /// <param name="e">EventArgs value.</param> private void ViewPicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: this.schedule.ScheduleView = ScheduleView.DayView; break; case 1: this.schedule.ScheduleView = ScheduleView.WeekView; break; case 2: this.schedule.ScheduleView = ScheduleView.WorkWeekView; break; case 3: this.schedule.ScheduleView = ScheduleView.TimelineView; break; } } /// <summary> /// Sets the non accessible blocks. /// </summary> private void SetNonAccessibleBlocks() { if (Device.RuntimePlatform == "Android" || Device.RuntimePlatform == "iOS") { NonAccessibleBlocksCollection nonAccessibleBlocks = new NonAccessibleBlocksCollection(); var nonAccessibleBlock = new NonAccessibleBlock(); nonAccessibleBlock.StartTime = 13; nonAccessibleBlock.EndTime = 14; nonAccessibleBlock.Text = "Lunch time"; nonAccessibleBlocks.Add(nonAccessibleBlock); var dayViewSettings = new DayViewSettings(); dayViewSettings.NonAccessibleBlocks = nonAccessibleBlocks; this.schedule.DayViewSettings = dayViewSettings; var weekViewSettings = new WeekViewSettings(); weekViewSettings.NonAccessibleBlocks = nonAccessibleBlocks; this.schedule.WeekViewSettings = weekViewSettings; var workWeekViewSettings = new WorkWeekViewSettings(); workWeekViewSettings.NonAccessibleBlocks = nonAccessibleBlocks; this.schedule.WorkWeekViewSettings = workWeekViewSettings; } } /// <summary> /// Gets the dropped location. /// </summary> /// <returns>The dropped location.</returns> /// <param name="startTime">Start time.</param> private string GetDroppedLocation(DateTime startTime) { return "Moved to " + startTime.ToString("dddd, dd MMMM, hh:mm tt"); } /// <summary> /// check the drop time in non-accessible region. /// </summary> /// <returns><c>true</c>, if in non access region was used, <c>false</c> otherwise.</returns> /// <param name="dropTime">Drop time.</param> private bool IsInNonAccessRegion(DateTime dropTime) { if (this.schedule.WorkWeekViewSettings.NonAccessibleBlocks[0].StartTime == dropTime.Hour || (this.schedule.WorkWeekViewSettings.NonAccessibleBlocks[0].StartTime - 1 == dropTime.Hour && dropTime.Minute > 0)) { return true; } return false; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/SalesInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; namespace SampleBrowser { public class SalesInfoRepository { private readonly List<string> _salesParsonNames = new List<string>() { "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" }; public ObservableCollection<SalesByDate> GetSalesDetailsByDay(int days) { var collection = new ObservableCollection<SalesByDate>(); var r = new Random(); for (var i = 0; i < days; i++) { var dt = DateTime.Now; var s = new SalesByDate { Name = _salesParsonNames[r.Next(5)], QS1 = (10000 - i) * (i + 1), QS2 = (10000 - i) * (i + 1), QS3 = (10000 - i) * (i + 1), QS4 = (100000 - i) * (i + 1), }; s.Total = s.QS1 + s.QS2 + s.QS3 + s.QS4; s.Date = dt.AddDays(-1 * i); collection.Add(s); } return collection; } } }<file_sep>/Forms/Kanban/Kanban/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.Generic; using SampleBrowser.Core; using Syncfusion.SfKanban.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfKanban { [Preserve(AllMembers = true)] public partial class Themes : SampleView { public Themes () { InitializeComponent (); column1.Categories = new List<object> { "Open", "Postponed", "Validated" }; column2.Categories = new List<object> { "In Progress" }; column3.Categories = new List<object> { "Code Review" }; column4.Categories = new List<object> { "Closed", "Closed-No Code Changes", "Resolved" }; List<KanbanWorkflow> keyfield = new List<KanbanWorkflow>(); keyfield.Add(new KanbanWorkflow("Open", new List<object> { "In Progress" })); keyfield.Add(new KanbanWorkflow("In Progress", new List<object> { "Postponed", "Validated", "Code Review", "Closed-No Code Changes" })); keyfield.Add(new KanbanWorkflow("Code Review", new List<object> { "Closed", "Resolved" })); keyfield.Add(new KanbanWorkflow("Closed", new List<object> { "Open" })); keyfield.Add(new KanbanWorkflow("Postponed", new List<object> { "In Progress" })); keyfield.Add(new KanbanWorkflow("Validated", new List<object> { "In Progress" })); keyfield.Add(new KanbanWorkflow("Closed-No Code Changes", new List<object> { })); keyfield.Add(new KanbanWorkflow("Resolved", new List<object> { })); kanban.Workflows = keyfield; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Barcode/Code128BBarcode.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfBarcode.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public class Code128BBarcode : SampleView { SFBarcode barcode; CGRect frameRect = new CGRect (); float frameMargin = 8.0f; public Code128BBarcode () { barcode = new SFBarcode(); } void LoadAllowedTextsLabel() { UILabel label = new UILabel (); label.Frame = frameRect; label.Text = "Allowed Characters"; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Font = UIFont.BoldSystemFontOfSize(12); label.SizeToFit(); label.Frame = new CGRect(frameRect.Location.X, 10, frameRect.Size.Width, label.Frame.Size.Height); this.AddSubview (label); frameRect.Location = new CGPoint(frameRect.Location.X, (10+ label.Frame.Size.Height + frameMargin)); frameRect.Size = new CGSize(frameRect.Size.Width, (frameRect.Size.Height - label.Frame.Size.Height + frameMargin)); UILabel allowedTextsLabel = new UILabel (); allowedTextsLabel.Frame = frameRect; allowedTextsLabel.TextColor = UIColor.FromRGB (63/255.0f, 63/255.0f, 63/255.0f); allowedTextsLabel.Text = "ASCII values from 32 to 127\nSPACE ! \" # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \\ ]^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ DEL"; allowedTextsLabel.Font = UIFont.SystemFontOfSize (10.0f); allowedTextsLabel.Lines = 0; allowedTextsLabel.SizeToFit (); allowedTextsLabel.Frame = new CGRect(frameRect.Location.X, frameRect.Location.Y, frameRect.Size.Width , allowedTextsLabel.Frame.Size.Height); this.AddSubview(allowedTextsLabel); frameRect.Location = new CGPoint(frameRect.Location.X, (frameRect.Location.Y + allowedTextsLabel.Frame.Size.Height + frameMargin)); frameRect.Size = new CGSize(frameRect.Size.Width, frameRect.Size.Height - allowedTextsLabel.Frame.Size.Height); } void LoadBarcode() { barcode.BackgroundColor = UIColor.FromRGB (242/255.0f, 242/255.0f, 242/255.0f); barcode.Frame = frameRect; barcode.Text = (NSString)"ISBN-678504"; barcode.Symbology = SFBarcodeSymbolType.SFBarcodeSymbolTypeCode128B; SFCode128BSettings settings = new SFCode128BSettings(); settings.BarHeight = 80; settings.NarrowBarWidth = 1f; barcode.SymbologySettings = settings; this.AddSubview(barcode); } public override void LayoutSubviews () { frameRect = Frame; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); LoadBarcode (); base.LayoutSubviews (); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/BoxAndWhisker.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class BoxAndWhisker : SampleView { public BoxAndWhisker() { SFChart chart = new SFChart(); chart.Title.Text = new NSString("Employee Age Group in Various Department"); chart.Title.EdgeInsets = new UIEdgeInsets(0, 0, 15, 0); SFCategoryAxis primaryAxis = new SFCategoryAxis(); primaryAxis.LabelPlacement = SFChartLabelPlacement.BetweenTicks; primaryAxis.ShowMajorGridLines = false; primaryAxis.Title.Text = new NSString("Department"); chart.PrimaryAxis = primaryAxis; SFNumericalAxis secoundaryAxis = new SFNumericalAxis(); secoundaryAxis.Title.Text = new NSString("Age"); secoundaryAxis.Maximum = new NSNumber(60); secoundaryAxis.Minimum = new NSNumber(20); secoundaryAxis.Interval = new NSNumber(5); secoundaryAxis.ShowMinorGridLines = false; secoundaryAxis.AxisLineStyle.LineWidth = 0; secoundaryAxis.MajorTickStyle.LineSize = 0; chart.SecondaryAxis = secoundaryAxis; ChartViewModel dataModel = new ChartViewModel(); SFBoxAndWhiskerSeries boxPlotSeries = new SFBoxAndWhiskerSeries(); boxPlotSeries.ItemsSource = dataModel.BoxAndWhiskerData; boxPlotSeries.XBindingPath = "Department"; boxPlotSeries.YBindingPath = "EmployeeAges"; boxPlotSeries.BoxPlotMode = BoxPlotMode.Exclusive; boxPlotSeries.EnableTooltip = true; boxPlotSeries.ShowMedian = true; boxPlotSeries.ColorModel.Palette = SFChartColorPalette.Custom; boxPlotSeries.ColorModel.CustomColors = NSArray.FromObjects(UIColor.FromRGBA(0 / 255.0f, 189 / 255.0f, 174 / 255.0f, 255 / 255.0f), UIColor.FromRGBA(128 / 255.0f, 132 / 255.0f, 232 / 255.0f, 255 / 255.0f), UIColor.FromRGBA(53 / 255.0f, 124 / 255.0f, 210 / 255.0f, 255 / 255.0f), UIColor.FromRGBA(229 / 255.0f, 101 / 255.0f, 144 / 255.0f, 255 / 255.0f), UIColor.FromRGBA(248 / 255.0f, 184 / 255.0f, 131 / 255.0f, 255 / 255.0f)); chart.Series.Add(boxPlotSeries); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Styles.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Syncfusion.SfDataGrid; using UIKit; using System.Globalization; namespace SampleBrowser { public class Styles:SampleView { #region Fields SfDataGrid SfGrid; UISegmentedControl segmentControl; GridGettingStartedViewModel viewmodel; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public Styles() { this.SfGrid = new SfDataGrid (); viewmodel = new GridGettingStartedViewModel (); this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; this.SfGrid.ItemsSource = viewmodel.OrdersInfo; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.SelectionMode = SelectionMode.Multiple; this.SfGrid.GridViewCreated += SfGrid_GridViewCreated; segmentControl = new UISegmentedControl(); segmentControl.ControlStyle = UISegmentedControlStyle.Bezeled; segmentControl.InsertSegment("Dark", 0,true); segmentControl.InsertSegment("Blue", 1, true); segmentControl.InsertSegment("Red", 2, true); segmentControl.InsertSegment("Green", 3, true); segmentControl.InsertSegment("Purple", 4, true); segmentControl.SelectedSegment = 0; segmentControl.ValueChanged += SegmentControl_ValueChanged; this.AddSubview (segmentControl); this.AddSubview (SfGrid); } void SegmentControl_ValueChanged (object sender, EventArgs e) { nint value = segmentControl.SelectedSegment; if (value == 0) { this.SfGrid.GridStyle = new Dark (); } else if (value == 1) { this.SfGrid.GridStyle = new Blue (); } else if (value == 2) { this.SfGrid.GridStyle = new Red (); } else if (value == 3) { this.SfGrid.GridStyle = new Green (); } else if (value == 4) { this.SfGrid.GridStyle = new Purple(); } } void SfGrid_GridViewCreated (object sender, GridViewCreatedEventArgs e) { this.SfGrid.SelectedItem = viewmodel.OrdersInfo [3]; this.SfGrid.GridStyle = new Dark(); } void GridAutoGenerateColumns (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Index") { e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "<NAME>"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "<NAME>"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "ShippingDate") { e.Column.HeaderText = "Shipping Date"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; e.Column.Format = "d"; } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } } public override void LayoutSubviews () { segmentControl.Frame = new CGRect (0, 0, this.Frame.Width, 30); this.SfGrid.Frame = new CGRect (0, segmentControl.Frame.Height, this.Frame.Width, this.Frame.Height - 30); base.LayoutSubviews (); } protected override void Dispose(bool disposing) { SfGrid.Dispose(); base.Dispose(disposing); } } } <file_sep>/iOS/SampleBrowser/Samples/Chart/DataMarker.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Foundation; using Syncfusion.SfChart.iOS; using UIKit; namespace SampleBrowser { public class DataMarker : SampleView { SFChart chart; public DataMarker() { chart = new SFChart(); chart.Title.Text = new NSString("Population of India (2013 - 2016)"); SFCategoryAxis primary = new SFCategoryAxis(); primary.ShowMajorGridLines = false; primary.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; primary.PlotOffset = 30; primary.AxisLineOffset = 30; chart.PrimaryAxis = primary; chart.SecondaryAxis = new SFNumericalAxis(); chart.SecondaryAxis.ShowMajorGridLines = false; chart.SecondaryAxis.Minimum = new NSNumber(900); chart.SecondaryAxis.Maximum = new NSNumber(1300); chart.SecondaryAxis.Interval = new NSNumber(80); chart.SecondaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; chart.SecondaryAxis.Title.Text = new NSString("Population"); ChartViewModel dataModel = new ChartViewModel(); SFLineSeries series = new SFLineSeries(); series.ItemsSource = dataModel.DataMarkerData1; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.DataMarker.LabelStyle.LabelPosition = SFChartDataMarkerLabelPosition.Center; series.DataMarker.ShowMarker = true; series.DataMarker.MarkerColor = UIColor.White; series.DataMarker.MarkerBorderColor = UIColor.FromRGBA(0.0f / 255.0f, 189.0f / 255.0f, 174.0f / 255.0f, 1.0f); series.DataMarker.MarkerBorderWidth = 2; series.DataMarker.MarkerWidth = 6f; series.DataMarker.MarkerHeight = 6f; series.DataMarker.LabelStyle.OffsetY = -18; series.DataMarker.ShowLabel = true; series.Label = "Male"; chart.Series.Add(series); SFLineSeries series1 = new SFLineSeries(); series1.ItemsSource = dataModel.DataMarkerData2; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.DataMarker.LabelStyle.LabelPosition = SFChartDataMarkerLabelPosition.Center; series1.DataMarker.ShowMarker = true; series1.DataMarker.MarkerColor = UIColor.White; series1.DataMarker.MarkerBorderColor = UIColor.FromRGBA(64.0f / 255.0f, 64.0f / 255.0f, 65.0f / 255.0f, 1.0f); series1.DataMarker.MarkerBorderWidth = 2; series1.DataMarker.MarkerWidth = 6f; series1.DataMarker.MarkerHeight = 6f; series1.DataMarker.MarkerType = SFChartDataMarkerType.Square; series1.DataMarker.LabelStyle.OffsetY = 18; series1.DataMarker.ShowLabel = true; series1.Label = "Female"; chart.Series.Add(series1); chart.Delegate = new ChartDataMarkerDelegate(); chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } public class ChartDataMarkerDelegate : SFChartDelegate { public override UIView ViewForDataMarkerLabel(SFChart chart, NSString label, nint index, SFSeries series) { var dataPoint = (series.ItemsSource as IList<ChartDataModel>); UIView customView = new UIView(); customView.Frame = new CGRect(0, 0, 63, 20); UIImageView imageView = new UIImageView(); imageView.Frame = new CGRect(3, 2, 15, 15); UILabel value = new UILabel(); value.Frame = new CGRect(25, 0, 35, 20); value.Font = UIFont.FromName("Helvetica", 10f); value.Text = label + "M"; value.TextColor = UIColor.White; if (series.Label == "Male") { imageView.Image = UIImage.FromBundle("Images/Male.png"); customView.BackgroundColor = UIColor.FromRGBA(0.0f / 255.0f, 189.0f / 255.0f, 174.0f / 255.0f, 1.0f); } else { imageView.Image = UIImage.FromBundle("Images/Female.png"); customView.BackgroundColor = UIColor.FromRGBA(64.0f / 255.0f, 64.0f / 255.0f, 65.0f / 255.0f, 1.0f); } customView.AddSubview(imageView); customView.AddSubview(value); return customView; } public override NSString GetFormattedAxisLabel(SFChart chart, NSString label, NSObject value, SFAxis axis) { if (axis == chart.SecondaryAxis) { String formattedLabel = label + "M"; label = new NSString(formattedLabel); return label; } return label; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/UnboundViews/UnBoundviewsBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "UnboundViewsBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the UnboundColumns samples /// </summary> public class UnboundViewsBehaviors : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] public Syncfusion.SfDataGrid.XForms.SfDataGrid DataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] public SalesInfoViewModel ViewModel; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type parameter as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { base.OnAttachedTo(bindAble); this.DataGrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.ViewModel = bindAble.FindByName<SalesInfoViewModel>("viewModel"); this.DataGrid.GridStyle = new UnboundRowStyle(); this.DataGrid.QueryCellStyle += this.DataGrid_QueryCellStyle; this.DataGrid.QueryRowHeight += this.DataGrid_QueryRowHeight; this.DataGrid.QueryUnboundRow += this.DataGrid_QueryUnboundRow; this.DataGrid.SelectionChanged += this.DataGrid_SelectionChanged; this.DataGrid.SelectionChanging += this.DataGrid_SelectionChanging; if (Device.Idiom == TargetIdiom.Tablet || Device.Idiom == TargetIdiom.Desktop) { this.DataGrid.UnboundRows.Insert(0, new GridUnboundRow() { Position = UnboundRowsPosition.FixedTop }); this.DataGrid.UnboundRows.Insert(0, new GridUnboundRow() { Position = UnboundRowsPosition.Top }); } } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">A sampleView type of bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.DataGrid.QueryCellStyle -= this.DataGrid_QueryCellStyle; this.DataGrid.QueryRowHeight -= this.DataGrid_QueryRowHeight; this.DataGrid.QueryUnboundRow -= this.DataGrid_QueryUnboundRow; this.DataGrid.SelectionChanged -= this.DataGrid_SelectionChanged; this.DataGrid.SelectionChanging -= this.DataGrid_SelectionChanging; base.OnDetachingFrom(bindAble); } /// <summary> /// Fired when selection is about to change in the data grid. /// </summary> /// <param name="sender">The data grid instance.</param> /// <param name="e">The event args.</param> private void DataGrid_SelectionChanging(object sender, GridSelectionChangingEventArgs e) { if (e.AddedItems.Count > 0 && e.AddedItems[0] == null) { e.Cancel = true; } } /// <summary> /// Queries to set the row heights for the rows /// </summary> /// <param name="sender">DataGrid_GridLoaded sender</param> /// <param name="e">GridLoadedEventArgs parameter e</param> private void DataGrid_QueryRowHeight(object sender, QueryRowHeightEventArgs e) { if (this.DataGrid.IsUnboundRow(e.RowIndex)) { e.Height = 70; e.Handled = true; } } /// <summary> /// Occurs to query the value and settings for cell in Unbound row. /// </summary> /// <param name="sender">DataGrid_QueryUnboundRow sender</param> /// <param name="e">GridUnboundRowEventArgs parameter e</param> private void DataGrid_QueryUnboundRow(object sender, GridUnboundRowEventArgs e) { if (e.UnboundAction == UnboundActions.QueryData) { if (e.GridUnboundRow.Position == UnboundRowsPosition.FixedTop) { double sum = 0; if (e.RowColumnIndex.ColumnIndex == 0) { e.Value = "Total sales by year"; } else if (e.RowColumnIndex.ColumnIndex == 1) { for (int i = 0; i < this.ViewModel.DailySalesDetails.Count; i++) { sum += this.ViewModel.DailySalesDetails[i].QS1; e.Value = sum; } } else if (e.RowColumnIndex.ColumnIndex == 2) { for (int i = 0; i < this.ViewModel.DailySalesDetails.Count; i++) { sum += this.ViewModel.DailySalesDetails[i].QS2; e.Value = sum; } } else if (e.RowColumnIndex.ColumnIndex == 3) { for (int i = 0; i < this.ViewModel.DailySalesDetails.Count; i++) { sum += this.ViewModel.DailySalesDetails[i].QS3; e.Value = sum; } } else if (e.RowColumnIndex.ColumnIndex == 4) { for (int i = 0; i < this.ViewModel.DailySalesDetails.Count; i++) { sum += this.ViewModel.DailySalesDetails[i].QS1 + this.ViewModel.DailySalesDetails[i].QS2 + this.ViewModel.DailySalesDetails[i].QS3; e.Value = sum / this.ViewModel.DailySalesDetails.Count; } } } else if (e.GridUnboundRow.Position == UnboundRowsPosition.Top) { double sum = 0; if (e.RowColumnIndex.ColumnIndex == 0) { e.Value = "Average by year"; } else if (e.RowColumnIndex.ColumnIndex == 1) { for (int i = 0; i < this.ViewModel.DailySalesDetails.Count; i++) { sum += this.ViewModel.DailySalesDetails[i].QS1; e.Value = sum / this.ViewModel.DailySalesDetails.Count; } } else if (e.RowColumnIndex.ColumnIndex == 2) { for (int i = 0; i < this.ViewModel.DailySalesDetails.Count; i++) { sum += this.ViewModel.DailySalesDetails[i].QS2; e.Value = sum / this.ViewModel.DailySalesDetails.Count; } } else if (e.RowColumnIndex.ColumnIndex == 3) { for (int i = 0; i < this.ViewModel.DailySalesDetails.Count; i++) { sum += this.ViewModel.DailySalesDetails[i].QS3; e.Value = sum / this.ViewModel.DailySalesDetails.Count; } } else if (e.RowColumnIndex.ColumnIndex == 4) { for (int i = 0; i < this.ViewModel.DailySalesDetails.Count; i++) { sum += this.ViewModel.DailySalesDetails[i].QS1 + this.ViewModel.DailySalesDetails[i].QS2 + this.ViewModel.DailySalesDetails[i].QS3; e.Value = sum / this.ViewModel.DailySalesDetails.Count; } } } else if (e.GridUnboundRow.Position == UnboundRowsPosition.FixedBottom) { double sum = 0; if (e.RowColumnIndex.ColumnIndex == 0) { e.Value = "Sum of selection"; } else if (e.RowColumnIndex.ColumnIndex == 1) { if (this.DataGrid.SelectedItems.Count > 0) { for (int i = 0; i < this.DataGrid.SelectedItems.Count; i++) { e.Value = sum += this.DataGrid.SelectedItems[i] != null ? (this.DataGrid.SelectedItems[i] as SalesByDate).QS2 : 0; } } else { e.Value = null; } } else if (e.RowColumnIndex.ColumnIndex == 2) { if (this.DataGrid.SelectedItems.Count > 0) { for (int i = 0; i < this.DataGrid.SelectedItems.Count; i++) { e.Value = sum += this.DataGrid.SelectedItems[i] != null ? (this.DataGrid.SelectedItems[i] as SalesByDate).QS3 : 0; } } else { e.Value = null; } } else if (e.RowColumnIndex.ColumnIndex == 3) { if (this.DataGrid.SelectedItems.Count > 0) { for (int i = 0; i < this.DataGrid.SelectedItems.Count; i++) { e.Value = sum += this.DataGrid.SelectedItems[i] != null ? (this.DataGrid.SelectedItems[i] as SalesByDate).QS2 + (this.DataGrid.SelectedItems[i] as SalesByDate).QS3 : 0; } } else { e.Value = null; } } } e.Handled = true; } } /// <summary> /// Fired when DataGrid selection changed. /// </summary> /// <param name="sender">dataGrid_SelectionChanged sender</param> /// <param name="e">GridSelectionChangedEventArgs parameter e</param> private void DataGrid_SelectionChanged(object sender, GridSelectionChangedEventArgs e) { this.DataGrid.InvalidateUnboundRow(this.DataGrid.UnboundRows[this.DataGrid.UnboundRows.Count - 1]); } /// <summary> /// Triggers when a cell comes to the View /// </summary> /// <param name="sender">DataGrid_QueryCellStyle event sender</param> /// <param name="e">DataGrid_QueryCellStyle event args e</param> private void DataGrid_QueryCellStyle(object sender, QueryCellStyleEventArgs e) { if (e.ColumnIndex == 3 || (this.DataGrid.GetUnboundRowAtRowIndex(e.RowIndex) != null && this.DataGrid.GetUnboundRowAtRowIndex(e.RowIndex).Position == UnboundRowsPosition.FixedBottom)) { e.Style.BackgroundColor = Color.FromRgb(225, 245, 254); } e.Handled = true; } } } <file_sep>/Forms/MaskedEdit/MaskedEdit/Samples/MaskedEdit/MaskedEdit_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.MaskedEdit; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.XForms.Editors; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfMaskedEdit { public partial class MaskedEdit_Default : SampleView { public MaskedEdit_Default() { InitializeComponent(); buttonaStack.Padding = new Thickness(0, 20, 0, 0); OptionView(); } public void OptionView() { double height = Bounds.Height; lblToAccountError.IsVisible = false; ErrorToAccount.IsVisible = false; lblAmountError.IsVisible = false; ErrorAmount.IsVisible = false; lblEmailError.IsVisible = false; ErrorEmail.IsVisible = false; lblPhoneError.IsVisible = false; ErrorPhone.IsVisible = false; sfToAccount.MaskInputRejected += SfToAccount_MaskInputRejected; sfToAccount.ValueChanged += SfToAccount_ValueChanged; sfAmount.MaskInputRejected += SfAmount_MaskInputRejected; sfAmount.ValueChanged += SfAmount_ValueChanged; sfEmail.MaskInputRejected += SfEmail_MaskInputRejected; sfEmail.ValueChanged += SfEmail_ValueChanged; sfPhone.MaskInputRejected += SfPhone_MaskInputRejected; sfPhone.ValueChanged += SfPhone_ValueChanged; //Toggle button hidePromptToggle.Toggled += ToggleChanged; localePicker.Items.Add("United States"); localePicker.Items.Add("United Kingdom"); localePicker.Items.Add("Japan"); localePicker.Items.Add("France"); localePicker.Items.Add("Italy"); localePicker.SelectedIndexChanged += localePicker_Changed; localePicker.SelectedIndex = 0; validationPicker.Items.Add("Lost Focus"); validationPicker.Items.Add("Key Press"); validationPicker.SelectedIndexChanged += ValidationPicker_SelectedIndexChanged; validationPicker.SelectedIndex = 1; visibilityPicker.Items.Add("Never"); visibilityPicker.Items.Add("While Editing"); visibilityPicker.SelectedIndexChanged += VisibilityPicker_SelectedIndexChanged; visibilityPicker.SelectedIndex = 1; promptPicker.Items.Add("_"); promptPicker.Items.Add("*"); promptPicker.Items.Add("~"); promptPicker.SelectedIndexChanged += PromptPicker_SelectedIndexChanged; promptPicker.SelectedIndex = 0; //Device Settings if (Device.RuntimePlatform == Device.iOS) { sfToAccount.HeightRequest = 30; sfDesc.HeightRequest = 30; sfAmount.HeightRequest = 30; sfPhone.HeightRequest = 30; sfEmail.HeightRequest = 30; lblHidePromt.VerticalOptions = LayoutOptions.End; lblPrompt.VerticalOptions = LayoutOptions.End; column1.Width = new GridLength(200, GridUnitType.Absolute); lblToAccount.TextColor = Color.FromHex("#535359"); lblDesc.TextColor = Color.FromHex("#535359"); lblAmount.TextColor = Color.FromHex("#535359"); lblEmail.TextColor = Color.FromHex("#535359"); lblPhone.TextColor = Color.FromHex("#535359"); submitButton.BackgroundColor = Color.FromHex("#2196f3"); submitButton.TextColor = Color.White; } else if (Device.RuntimePlatform == Device.Android) { submitButton.BackgroundColor = Color.FromHex("#2196f3"); submitButton.CornerRadius = 1; submitButton.BorderWidth = 0; submitButton.TextColor = Color.White; submitButton.FontFamily = "Roboto"; pickerLayout1.Padding = new Thickness(-2, 0, 0, 0); pickerLayout2.Padding = new Thickness(-2, 0, 0, 0); lblAmount.HeightRequest = 25; lblToAccount.HeightRequest = 25; lblDesc.HeightRequest = 25; lblEmail.HeightRequest = 25; lblPhone.HeightRequest = 25; sfToAccount.HeightRequest = 45; maskEdit1.Padding = new Thickness(-3, -10, 0, 0); maskEdit2.Padding = new Thickness(-3, -10, 0, 0); maskEdit3.Padding = new Thickness(-3, -10, 0, 0); maskEdit4.Padding = new Thickness(-3, -10, 0, 0); maskEdit5.Padding = new Thickness(-3, -10, 0, 0); sfToAccount.Margin = new Thickness(0, 0, 0, 0); sfDesc.Margin = new Thickness(0, 0, 0, 0); sfAmount.Margin = new Thickness(0, 0, 0, 0); sfPhone.Margin = new Thickness(0, 0, 0, 0); sfEmail.Margin = new Thickness(0, 0, 0, 0); } else if (Device.RuntimePlatform == Device.UWP) { submitButton.FontSize = 16; if (Device.Idiom == TargetIdiom.Desktop) { sfToAccount.HeightRequest = 40; sfDesc.HeightRequest = 40; sfAmount.HeightRequest = 40; sfPhone.HeightRequest = 40; sfEmail.HeightRequest = 40; sfToAccount.FontSize = 23; sfDesc.FontSize = 23; sfAmount.FontSize = 23; sfPhone.FontSize = 23; sfEmail.FontSize = 23; submitButton.HeightRequest = 35; sfToAccount.WidthRequest = 300; sfDesc.WidthRequest = 300; sfAmount.WidthRequest = 300; sfPhone.WidthRequest = 300; sfEmail.WidthRequest = 300; sfToAccount.WatermarkFontSize = 20; sfDesc.WatermarkFontSize = 20; sfAmount.WatermarkFontSize = 20; sfPhone.WatermarkFontSize = 20; sfEmail.WatermarkFontSize = 20; sampleLayout.HorizontalOptions = LayoutOptions.Start; hidePromptToggle.HorizontalOptions = LayoutOptions.End; localePicker.HorizontalOptions = LayoutOptions.Start; localePicker.WidthRequest = 320.0; validationPicker.HorizontalOptions = LayoutOptions.Start; validationPicker.WidthRequest = 320.0; promptPicker.WidthRequest = 65.0; } else { sfToAccount.HeightRequest = 35; sfDesc.HeightRequest = 35; sfAmount.HeightRequest = 35; sfPhone.HeightRequest = 35; sfEmail.HeightRequest = 35; sfToAccount.FontSize = 18; sfDesc.FontSize = 18; sfAmount.FontSize = 18; sfPhone.FontSize = 18; sfEmail.FontSize = 18; sfToAccount.WatermarkFontSize = 18; sfDesc.WatermarkFontSize = 18; sfAmount.WatermarkFontSize = 18; sfPhone.WatermarkFontSize = 18; sfEmail.WatermarkFontSize = 18; hidePromptToggle.HorizontalOptions = LayoutOptions.End; column2.Width = new GridLength(1, GridUnitType.Star); promptPicker.WidthRequest = 65.0; optionLayout.Padding = new Thickness(10, 0, 0, 0); } } } private void VisibilityPicker_SelectedIndexChanged(object sender, EventArgs e) { string visibility = (sender as Picker).SelectedItem.ToString(); if (visibility == "Never") { sfToAccount.ClearButtonVisibility = ClearButtonVisibilityMode.Never; sfDesc.ClearButtonVisibility = ClearButtonVisibilityMode.Never; sfAmount.ClearButtonVisibility = ClearButtonVisibilityMode.Never; sfEmail.ClearButtonVisibility = ClearButtonVisibilityMode.Never; sfPhone.ClearButtonVisibility = ClearButtonVisibilityMode.Never; } else { sfToAccount.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; sfDesc.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; sfAmount.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; sfEmail.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; sfPhone.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; } } private void SfPhone_ValueChanged(object sender, Syncfusion.XForms.MaskedEdit.ValueChangedEventArgs e) { HideError(lblPhoneError, ErrorPhone, row9); } private void SfPhone_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { ShowError(lblPhoneError, ErrorPhone, row9, e.RejectionHint); } private void SfEmail_ValueChanged(object sender, Syncfusion.XForms.MaskedEdit.ValueChangedEventArgs e) { HideError(lblEmailError, ErrorEmail, row7); } private void SfEmail_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { ShowError(lblEmailError, ErrorEmail, row7, e.RejectionHint); } private void SfAmount_ValueChanged(object sender, Syncfusion.XForms.MaskedEdit.ValueChangedEventArgs e) { HideError(lblAmountError, ErrorAmount, row5); } private void SfAmount_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { ShowError(lblAmountError, ErrorAmount, row5, e.RejectionHint); } private void SfToAccount_ValueChanged(object sender, Syncfusion.XForms.MaskedEdit.ValueChangedEventArgs e) { HideError(lblToAccountError, ErrorToAccount, row2); } private void SfToAccount_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { ShowError(lblToAccountError, ErrorToAccount, row2, e.RejectionHint); } private void HideError(Label label, StackLayout stacklayout, RowDefinition row) { stacklayout.IsVisible = false; label.IsVisible = false; label.Text = ""; row.Height = new GridLength(0, GridUnitType.Absolute); } private void ShowError(Label label, StackLayout stacklayout, RowDefinition row, MaskedTextResultHint hint) { string hintText = GetRejectionHintText(hint); if (!string.IsNullOrEmpty(hintText)) { stacklayout.IsVisible = true; label.IsVisible = true; label.Text = hintText; row.Height = new GridLength(1, GridUnitType.Auto); } } private string GetRejectionHintText(MaskedTextResultHint hint) { string hintText = string.Empty; switch(hint) { case MaskedTextResultHint.AlphanumericCharacterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.DigitExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.LetterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.SignedDigitExpected: hintText = "Invalid character!"; break; //case MaskedTextResultHint.UnavailableEditPosition: // hintText = "Invalid typed character!"; // break; } return hintText; } private void PromptPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (promptPicker.SelectedIndex) { case 1: { sfToAccount.PromptChar = '*'; sfDesc.PromptChar = '*'; sfAmount.PromptChar = '*'; sfPhone.PromptChar = '*'; sfEmail.PromptChar = '*'; } break; case 0: { sfToAccount.PromptChar = '_'; sfDesc.PromptChar = '_'; sfAmount.PromptChar = '_'; sfPhone.PromptChar = '_'; sfEmail.PromptChar = '_'; } break; case 2: { sfToAccount.PromptChar = '~'; sfDesc.PromptChar = '~'; sfAmount.PromptChar = '~'; sfPhone.PromptChar = '~'; sfEmail.PromptChar = '~'; } break; } } private void ValidationPicker_SelectedIndexChanged(object sender, EventArgs e) { sfToAccount.ValidationMode = (InputValidationMode)validationPicker.SelectedIndex; sfDesc.ValidationMode = (InputValidationMode)validationPicker.SelectedIndex; sfAmount.ValidationMode = (InputValidationMode)validationPicker.SelectedIndex; sfEmail.ValidationMode = (InputValidationMode)validationPicker.SelectedIndex; sfPhone.ValidationMode = (InputValidationMode)validationPicker.SelectedIndex; } void ToggleChanged(object sender, ToggledEventArgs e) { sfToAccount.HidePromptOnLeave = e.Value; sfDesc.HidePromptOnLeave = e.Value; sfAmount.HidePromptOnLeave = e.Value; sfPhone.HidePromptOnLeave = e.Value; sfEmail.HidePromptOnLeave = e.Value; } void Handle_Clicked(object sender, System.EventArgs e) { if ((sfToAccount.Value == null || sfToAccount.Value.ToString() == string.Empty) || (sfDesc.Value == null || sfDesc.Value.ToString() == string.Empty) || (sfAmount.Value == null || sfAmount.Value.ToString() == string.Empty) || (sfEmail.Value == null || sfEmail.Value.ToString() == string.Empty) || (sfPhone.Value == null || sfPhone.Value.ToString() == string.Empty)) { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Status", "Please fill all the required data!", "Ok"); } else if((sfToAccount.HasError || sfDesc.HasError || sfAmount.HasError || sfEmail.HasError || sfPhone.HasError)) { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Status", "Please enter valid details", "Ok"); } else { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Status", string.Format("Amount of {0} has been transferred successfully!", sfAmount.Value), "Ok"); sfToAccount.Value = string.Empty; sfDesc.Value = string.Empty; sfAmount.Value = string.Empty; sfEmail.Value = string.Empty; sfPhone.Value = string.Empty; } } public void localePicker_Changed(object c, EventArgs e) { switch (localePicker.SelectedIndex) { case 0: { sfToAccount.Culture = new System.Globalization.CultureInfo("en-US"); sfDesc.Culture = new System.Globalization.CultureInfo("en-US"); sfAmount.Culture = new System.Globalization.CultureInfo("en-US"); sfPhone.Culture = new System.Globalization.CultureInfo("en-US"); sfEmail.Culture = new System.Globalization.CultureInfo("en-US"); } break; case 1: { sfToAccount.Culture = new System.Globalization.CultureInfo("en-GB"); sfDesc.Culture = new System.Globalization.CultureInfo("en-GB"); sfAmount.Culture = new System.Globalization.CultureInfo("en-GB"); sfPhone.Culture = new System.Globalization.CultureInfo("en-GB"); sfEmail.Culture = new System.Globalization.CultureInfo("en-GB"); } break; case 2: { sfToAccount.Culture = new System.Globalization.CultureInfo("ja-JP"); sfDesc.Culture = new System.Globalization.CultureInfo("ja-JP"); sfAmount.Culture = new System.Globalization.CultureInfo("ja-JP"); sfPhone.Culture = new System.Globalization.CultureInfo("ja-JP"); sfEmail.Culture = new System.Globalization.CultureInfo("ja-JP"); } break; case 3: { sfToAccount.Culture = new System.Globalization.CultureInfo("fr-FR"); sfDesc.Culture = new System.Globalization.CultureInfo("fr-FR"); sfAmount.Culture = new System.Globalization.CultureInfo("fr-FR"); sfPhone.Culture = new System.Globalization.CultureInfo("fr-FR"); sfEmail.Culture = new System.Globalization.CultureInfo("fr-FR"); } break; case 4: { sfToAccount.Culture = new System.Globalization.CultureInfo("it-IT"); sfDesc.Culture = new System.Globalization.CultureInfo("it-IT"); sfAmount.Culture = new System.Globalization.CultureInfo("it-IT"); sfPhone.Culture = new System.Globalization.CultureInfo("it-IT"); sfEmail.Culture = new System.Globalization.CultureInfo("it-IT"); } break; } } public View getContent() { return this.Content; } public View getPropertyView() { return this.PropertyView; } /// <summary> /// Invoked when the cursor position gets changing. /// </summary> /// <param name="sender">Masked edit.</param> /// <param name="e">CursorPositionChangingEventArgs.</param> private void SfPhone_CursorPositionChanging(object sender, CursorPositionChangingEventArgs e) { if (e.NewValue <= 1 && !(e.NewValue == 0 && e.OldValue == sfPhone.Mask.Length)) e.Cancel = true; } } }<file_sep>/Forms/DocIO/DocIO/Samples/NestedMailMerge/NestedMailMerge.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using SampleBrowser.Core; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Xamarin.Forms; using System.Data; using System.Collections; namespace SampleBrowser.DocIO { public partial class NestedMailMerge : SampleView { public NestedMailMerge() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.FontSize = 13.5; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = typeof(MailMerge).GetTypeInfo().Assembly; #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif // Creating a new document. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream(rootPath + "Template_Letter.doc"); //Open Template document document.Open(inputStream, FormatType.Word2013); inputStream.Dispose(); inputStream = assembly.GetManifestResourceStream(rootPath + "Employees.xml"); System.Data.DataSet ds = new DataSet(); ds.ReadXml(inputStream); System.Collections.ArrayList commands = new ArrayList(); //DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE) System.Collections.DictionaryEntry entry = new DictionaryEntry("Employees", string.Empty); commands.Add(entry); // To retrive customer details DataTable table = ds.Tables["Customers"]; string relation = table.ParentRelations[0].ChildColumns[0].ColumnName + " = %Employees." + table.ParentRelations[0].ParentColumns[0].ColumnName + "%"; entry = new DictionaryEntry("Customers", relation); commands.Add(entry); // To retrieve order details table = ds.Tables["Orders"]; relation = table.ParentRelations[0].ChildColumns[0].ColumnName + " = %Customers." + table.ParentRelations[0].ParentColumns[0].ColumnName + "%"; entry = new DictionaryEntry("Orders", relation); commands.Add(entry); //Executes nested Mail merge using explicit relational data. document.MailMerge.ExecuteNestedGroup(ds, commands); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("NestedMailMerge.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("NestedMailMerge.docx", "application/msword", stream); } } } <file_sep>/Forms/Chart/Chart/Samples/StepAreaChart/StepAreaSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class StepAreaSeriesViewModel { public ObservableCollection<ChartDataModel> StepAreaData1 { get; set; } public ObservableCollection<ChartDataModel> StepAreaData2 { get; set; } public StepAreaSeriesViewModel() { StepAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2000, 416), new ChartDataModel(2001, 490), new ChartDataModel(2002, 470), new ChartDataModel(2003, 500), new ChartDataModel(2004, 449), new ChartDataModel(2005, 470), new ChartDataModel(2006, 437), new ChartDataModel(2007, 458), new ChartDataModel(2008, 500), new ChartDataModel(2009, 473), new ChartDataModel(2010, 520), new ChartDataModel(2011, 509), }; StepAreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2000, 180), new ChartDataModel(2001, 240), new ChartDataModel(2002, 370), new ChartDataModel(2003, 200), new ChartDataModel(2004, 229), new ChartDataModel(2005, 210), new ChartDataModel(2006, 337), new ChartDataModel(2007, 258), new ChartDataModel(2008, 300), new ChartDataModel(2009, 173), new ChartDataModel(2010, 220), new ChartDataModel(2011, 309), }; } } }<file_sep>/iOS/SampleBrowser/Samples/RangeSlider/RangeSliderGettingStarted_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfRangeSlider.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class RangeSliderGettingStarted_Mobile : SampleView { SfRangeSlider rangeSlider1, rangeSlider2; UILabel departureLabel,arrivalLabel,ticksLabel,placementLabel,timeLabel1,showLabel,snapsToLabel,timeLabel2,timeLabel3; UIButton positionbutton = new UIButton (); UIButton positionbutton1 = new UIButton (); UIButton doneButton=new UIButton(); UIPickerView positionPicker1, positionPicker2; UISwitch labelswitch, labelswitch1; public UIView option=new UIView(); private string selectedType; private readonly IList<string> TAlignment = new List<string> { "BottomRight", "TopLeft", "Inline", "Outside", "None" }; private readonly IList<string> LAlignment = new List<string> { "BottomRight", "TopLeft" }; public void optionView() { this.option.AddSubview (ticksLabel); this.option.AddSubview (positionbutton); this.option.AddSubview (placementLabel); this.option.AddSubview (positionbutton1); this.option.AddSubview (positionPicker1); this.option.AddSubview (positionPicker2); this.option.AddSubview (doneButton); this.option.AddSubview (showLabel); this.option.AddSubview (labelswitch); this.option.AddSubview (snapsToLabel); this.option.AddSubview (labelswitch1); } public RangeSliderGettingStarted_Mobile () { //RangeSlider 1 rangeSlider1 = new SfRangeSlider(); rangeSlider1.Maximum = 12; rangeSlider1.Minimum = 0; rangeSlider1.RangeStart = 0; rangeSlider1.RangeEnd = 12; rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementBottomRight; rangeSlider1.TickFrequency = 2; rangeSlider1.ToolTipPlacement = SFToolTipPlacement.SFToolTipPlacementTopLeft; rangeSlider1.ValuePlacement = SFValuePlacement.SFValuePlacementBottomRight; rangeSlider1.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeSlider1.KnobColor = UIColor.White; rangeSlider1.TrackSelectionColor = UIColor.FromRGB (65, 115, 185); rangeSlider1.TrackColor = UIColor.FromRGB (182, 182, 182); //RangeSlider 2 rangeSlider2 = new SfRangeSlider(); rangeSlider2.Frame = new CGRect(10, 100, this.Frame.Size.Width, this.Frame.Size.Height); rangeSlider2.Maximum = 12; rangeSlider2.Minimum = 0; rangeSlider2.RangeStart = 0; rangeSlider2.RangeEnd = 12; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementBottomRight; rangeSlider2.TickFrequency = 2; rangeSlider2.ValuePlacement = SFValuePlacement.SFValuePlacementBottomRight; rangeSlider2.ToolTipPlacement = SFToolTipPlacement.SFToolTipPlacementTopLeft; rangeSlider2.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeSlider2.KnobColor = UIColor.White; rangeSlider2.TrackSelectionColor = UIColor.FromRGB(65, 115, 185); rangeSlider2.TrackColor = UIColor.FromRGB(182, 182, 182); rangeSlider2.RangeValueChange += Slider_RangeValueChange; rangeSlider1.RangeValueChange += Slider_RangeValueChange; this.AddSubview(rangeSlider1); this.AddSubview(rangeSlider2); mainPageDesign(); this.optionView(); } void Slider_RangeValueChange(object sender, RangeEventArgs e) { SetValue(sender as SfRangeSlider,e.RangeStart,e.RangeEnd); } public void mainPageDesign() { //DepartureLabel departureLabel = new UILabel(); departureLabel.Text = "Departure"; departureLabel.TextColor = UIColor.Black; departureLabel.TextAlignment = UITextAlignment.Left; departureLabel.Font = UIFont.FromName("Helvetica", 18f); //TicksLabel ticksLabel = new UILabel(); ticksLabel.Text = "Tick Placement"; ticksLabel.TextColor = UIColor.Black; ticksLabel.TextAlignment = UITextAlignment.Left; //placementLabell placementLabel = new UILabel(); placementLabel.Text = "Label Placement"; placementLabel.TextColor = UIColor.Black; placementLabel.TextAlignment = UITextAlignment.Left; //timeLabel11 timeLabel1 = new UILabel(); timeLabel1.Text = "(in Hours)"; timeLabel1.TextColor = UIColor.Gray; timeLabel1.TextAlignment = UITextAlignment.Left; timeLabel1.Font = UIFont.FromName("Helvetica", 14f); //TimeLabel2 timeLabel2 = new UILabel(); timeLabel2.Text = "(in Hours)"; timeLabel2.TextColor = UIColor.Gray; timeLabel2.TextAlignment = UITextAlignment.Left; timeLabel2.Font = UIFont.FromName("Helvetica", 14f); //snapsToLabel snapsToLabel = new UILabel(); snapsToLabel.Text = "Snap To Tick"; snapsToLabel.TextColor = UIColor.Black; snapsToLabel.TextAlignment = UITextAlignment.Left; //TimeLabel 2 timeLabel2 = new UILabel(); timeLabel2.Text = "Time: 12 AM - 12 PM"; timeLabel2.TextColor = UIColor.Gray; timeLabel2.TextAlignment = UITextAlignment.Left; timeLabel2.Font = UIFont.FromName("Helvetica", 14f); //TimeLabel 3 timeLabel3 = new UILabel(); timeLabel3.Text = "Time: 12 AM - 12 PM"; timeLabel3.TextColor = UIColor.Gray; timeLabel3.TextAlignment = UITextAlignment.Left; timeLabel3.Font = UIFont.FromName("Helvetica", 14f); //PostionButton positionbutton = new UIButton(); positionbutton.SetTitle("BottomRight", UIControlState.Normal); positionbutton.SetTitleColor(UIColor.Black, UIControlState.Normal); positionbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; positionbutton.Layer.CornerRadius = 8; positionbutton.Layer.BorderWidth = 2; positionbutton.TouchUpInside += ShowPicker1; positionbutton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //PositionButton1 positionbutton1 = new UIButton(); positionbutton1.SetTitle("BottomRight", UIControlState.Normal); positionbutton1.SetTitleColor(UIColor.Black, UIControlState.Normal); positionbutton1.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; positionbutton1.Layer.CornerRadius = 8; positionbutton1.Layer.BorderWidth = 2; positionbutton1.TouchUpInside += ShowPicker2; positionbutton1.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //DoneButton doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(246, 246, 246); //ShowLabel showLabel = new UILabel(); showLabel.Text = "Show Label"; showLabel.TextColor = UIColor.Black; showLabel.TextAlignment = UITextAlignment.Left; //LabelSwitch labelswitch = new UISwitch(); labelswitch.On = true; labelswitch.ValueChanged += toggleChanged; //labelSwitch 1 labelswitch1 = new UISwitch(); labelswitch1.On = false; labelswitch1.ValueChanged += toggleChanged1; //ArrivalLabel arrivalLabel = new UILabel(); arrivalLabel.Text = "Arrival"; arrivalLabel.TextColor = UIColor.Black; arrivalLabel.TextAlignment = UITextAlignment.Left; arrivalLabel.Font = UIFont.FromName("Helvetica", 18f); this.OptionView = new UIView(); //PositionPicker 1 positionPicker1 = new UIPickerView(); positionPicker1.ShowSelectionIndicator = true; positionPicker1.Hidden = true; PickerModel model = new PickerModel(TAlignment); model.PickerChanged += SelectedIndexChanged; positionPicker1.Model = model; //PositionPicker 2 positionPicker2 = new UIPickerView(); positionPicker2.ShowSelectionIndicator = true; positionPicker2.Hidden = true; PickerModel model1 = new PickerModel(LAlignment); model1.PickerChanged += SelectedIndexChanged1; positionPicker2.Model = model1; //Adding to view this.AddSubview(departureLabel); this.AddSubview(arrivalLabel); this.AddSubview(timeLabel1); this.AddSubview(timeLabel2); this.AddSubview(timeLabel2); this.AddSubview(timeLabel3); } public void SetValue(SfRangeSlider r,nfloat start, nfloat end) { if (r == rangeSlider1) { if (Math.Round (start) < 1) { if (Math.Round (end) == 12) timeLabel2.Text = "Time: 12 AM - " + Math.Round (end) + " PM"; else timeLabel2.Text = "Time: 12 AM - " + Math.Round (end) + " AM"; } else { if (Math.Round (end) == 12) timeLabel2.Text = "Time: " + Math.Round (start) + " AM - " + Math.Round (end) + " PM"; else timeLabel2.Text = "Time: " + Math.Round (start) + " AM - " + Math.Round (end) + " AM"; } if (Math.Round (start) == Math.Round (end)) { if (Math.Round (start) < 1) timeLabel2.Text = "Time: 12 AM"; else if (Math.Round (start) == 12) timeLabel2.Text = "Time: 12 PM"; else timeLabel2.Text = "Time: " + Math.Round (start) + " AM"; } } else if(r==rangeSlider2){ if (Math.Round (start) < 1) { if (Math.Round (end) == 12) timeLabel3.Text = "Time: 12 AM - " + Math.Round (end) + " PM"; else timeLabel3.Text = "Time: 12 AM - " + Math.Round (end) + " AM"; } else { if (Math.Round (end) == 12) timeLabel3.Text = "Time: " + Math.Round (start) + " AM - " + Math.Round (end) + " PM"; else timeLabel3.Text = "Time: " + Math.Round (start) + " AM - " + Math.Round (end) + " AM"; } if (Math.Round (start) == Math.Round (end)) { if (Math.Round (start) < 1) timeLabel3.Text = "Time: 12 AM"; else if (Math.Round (start) == 12) timeLabel3.Text = "Time: 12 PM"; else timeLabel3.Text = "Time: " + Math.Round (start) + " AM"; } } } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; this.OptionView.Frame = view.Frame; option.Frame = new CGRect (0, 50, Frame.Width, Frame.Height); departureLabel.Frame = new CGRect (this.Frame.X + 10, this.Frame.Size.Height/6,85, 30); arrivalLabel.Frame = new CGRect (this.Frame.X + 10,this.Frame.Size.Height -(this.Frame.Size.Height/2.5f), 80, 30); timeLabel1.Frame = new CGRect (this.Frame.X + 95, this.Frame.Size.Height / 6, this.Frame.Size.Width-20, 30); timeLabel2.Frame = new CGRect (this.Frame.X + 65, this.Frame.Size.Height -(this.Frame.Size.Height/2.5f), 85, 30); timeLabel2.Frame = new CGRect (this.Frame.X + 10, (this.Frame.Size.Height/6)+30,150, 30); timeLabel3.Frame = new CGRect (this.Frame.X + 10,(this.Frame.Size.Height -(this.Frame.Size.Height/2.5f))+30, 150, 30); rangeSlider1.Frame = new CGRect (2, (nfloat)(this.Frame.Size.Height/3.5), this.Frame.Size.Width - 4, 100); rangeSlider2.Frame = new CGRect (2, this.Frame.Size.Height -(nfloat)(this.Frame.Size.Height/3.5), this.Frame.Size.Width - 4, 100); ticksLabel.Frame = new CGRect (10, this.Frame.Y, this.Frame.Size.Width - 20, 25); positionbutton.Frame=new CGRect(10, this.Frame.Y+25, this.Frame.Size.Width - 20, 25); placementLabel.Frame = new CGRect (10, this.Frame.Y+55, this.Frame.Size.Width - 20, 25); positionbutton1.Frame=new CGRect(10, this.Frame.Y+85, this.Frame.Size.Width - 20, 25); positionPicker1.Frame = new CGRect (this.Frame.X, this.Frame.Size.Height/3, this.Frame.Size.Width, this.Frame.Size.Height/3); positionPicker2.Frame = new CGRect (this.Frame.X, this.Frame.Size.Height/3, this.Frame.Size.Width , this.Frame.Size.Height/3); showLabel.Frame = new CGRect (10, this.Frame.Y+110, this.Frame.Size.Width - 20, 25); labelswitch.Frame = new CGRect (this.Frame.Size.Width-(labelswitch.Frame.Width)-20, this.Frame.Y+120, labelswitch.Frame.Width, 25); snapsToLabel.Frame = new CGRect (10, this.Frame.Y+150, this.Frame.Size.Width - 20, 25); labelswitch1.Frame = new CGRect (this.Frame.Size.Width-(labelswitch.Frame.Width)-20, this.Frame.Y+160, labelswitch.Frame.Width, 25); doneButton.Frame = new CGRect (0, this.Frame.Y+190, this.Frame.Size.Width, 30); } base.LayoutSubviews (); } void ShowPicker1 (object sender, EventArgs e) { doneButton.Hidden = false; positionPicker1.Hidden = false; positionPicker2.Hidden = true; } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; positionPicker2.Hidden = true; positionPicker1.Hidden = true; } void ShowPicker2 (object sender, EventArgs e) { doneButton.Hidden = false; positionPicker1.Hidden = true; positionPicker2.Hidden = false; } private void SelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; positionbutton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "TopLeft") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementTopLeft; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementTopLeft; } else if (selectedType == "BottomRight") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementBottomRight; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementBottomRight; } else if (selectedType == "Inline") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementInline; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementInline; } else if (selectedType == "Outside") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementOutSide; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementOutSide; } else if (selectedType == "None") { rangeSlider1.TickPlacement = SFTickPlacement.SFTickPlacementNone; rangeSlider2.TickPlacement = SFTickPlacement.SFTickPlacementNone; } } private void SelectedIndexChanged1(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; positionbutton1.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "TopLeft") { rangeSlider1.ValuePlacement = SFValuePlacement.SFValuePlacementTopLeft; rangeSlider2.ValuePlacement = SFValuePlacement.SFValuePlacementTopLeft; } else if (selectedType == "BottomRight") { rangeSlider1.ValuePlacement = SFValuePlacement.SFValuePlacementBottomRight; rangeSlider2.ValuePlacement = SFValuePlacement.SFValuePlacementBottomRight; } } private void toggleChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { rangeSlider1.ShowValueLabel = true; rangeSlider2.ShowValueLabel = true; } else { rangeSlider1.ShowValueLabel = false; rangeSlider2.ShowValueLabel = false; } } private void toggleChanged1(object sender, EventArgs e) { if (((UISwitch)sender).On) { rangeSlider1.SnapsTo = SFSnapsTo.SFSnapsToTicks; rangeSlider2.SnapsTo = SFSnapsTo.SFSnapsToTicks; } else { rangeSlider1.SnapsTo = SFSnapsTo.SFSnapsToNone; rangeSlider2.SnapsTo = SFSnapsTo.SFSnapsToNone; } } } }<file_sep>/Forms/Maps/Maps/Samples/BubbleVisualization/BubbleVisualization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfMaps.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] // [XamlCompilation(XamlCompilationOptions.Compile)] public partial class BubbleVisualization : SampleView { public BubbleVisualization() { InitializeComponent(); grid.SizeChanged += Grid_SizeChanged; Uri uri = new Uri("https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population"); (this.sfmap.Layers[0] as ShapeFileLayer).BubbleMarkerSettings.TooltipSettings.TooltipTemplate = grid.Resources["toolTipTemplate"] as DataTemplate; this.Link.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(() => Launcher.OpenAsync(uri)) }); } private void Grid_SizeChanged(object sender, EventArgs e) { if (sfmap.Bounds.Width > sfmap.Bounds.Height) { (this.sfmap.Layers[0] as ShapeFileLayer).LegendSettings.LegendPosition = new Point(75, 45); (this.sfmap.Layers[0] as ShapeFileLayer).LegendSettings.HorizontalAlignment = HorizontalAlignment.Start; } else { (this.sfmap.Layers[0] as ShapeFileLayer).LegendSettings.LegendPosition = new Point(50, 5); (this.sfmap.Layers[0] as ShapeFileLayer).LegendSettings.HorizontalAlignment = HorizontalAlignment.Center; } } } } <file_sep>/iOS/SampleBrowser/Samples/Chart/GradientChart.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Drawing; using CoreGraphics; using Foundation; using Syncfusion.Drawing; using Syncfusion.SfChart.iOS; using UIKit; namespace SampleBrowser { public class GradientChart : SampleView { public GradientChart() { SFChart chart = new SFChart(); chart.Title.Text = (NSString)"Oxygen Level"; chart.ColorModel.Palette = SFChartColorPalette.Custom; ChartGradientColor gradientColor = new ChartGradientColor() { StartPoint = new CGPoint(0.5f, 1), EndPoint = new CGPoint(0.5f, 0) }; ChartGradientStop stopColor1 = new ChartGradientStop() { Color = UIColor.White, Offset = 0 }; ChartGradientStop stopColor2 = new ChartGradientStop() { Color = UIColor.FromRGBA(0, 128f / 255f, 223f / 255f, 1.0f), Offset = 1 }; gradientColor.GradientStops.Add(stopColor1); gradientColor.GradientStops.Add(stopColor2); ChartGradientColorCollection gradientColorsCollection = new ChartGradientColorCollection() { gradientColor }; chart.ColorModel.CustomGradientColors = gradientColorsCollection; chart.PrimaryAxis = new SFDateTimeAxis() { PlotOffset = 6, EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift, ShowMajorGridLines = false, ShowMinorGridLines = false }; NSDateFormatter formatter = new NSDateFormatter(); formatter.DateFormat = new NSString("MMM dd"); chart.PrimaryAxis.LabelStyle.LabelFormatter = formatter; chart.SecondaryAxis = new SFNumericalAxis { Maximum = new NSNumber(50), Interval = new NSNumber(5) }; NSNumberFormatter secondaryAxisFormatter = new NSNumberFormatter(); secondaryAxisFormatter.PositiveSuffix = "%"; chart.SecondaryAxis.LabelStyle.LabelFormatter = secondaryAxisFormatter; ChartViewModel dataModel = new ChartViewModel(); SFSplineAreaSeries series = new SFSplineAreaSeries(); series.ItemsSource = dataModel.GradientData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.BorderColor = UIColor.FromRGBA(0, 128f / 255f, 223f / 255f, 1.0f); series.BorderWidth = 2; series.DataMarker.ShowLabel = true; series.DataMarker.MarkerWidth = 8; series.DataMarker.MarkerHeight = 8; series.DataMarker.MarkerColor = UIColor.White; series.DataMarker.MarkerBorderColor = UIColor.FromRGBA(0, 128f / 255f, 223f / 255f, 1.0f); series.DataMarker.MarkerBorderWidth = 2; series.DataMarker.ShowMarker = true; series.DataMarker.LabelStyle.OffsetY = -10; series.DataMarker.LabelStyle.BackgroundColor = UIColor.FromRGBA(0, 128f / 255f, 223f / 255f, 1.0f); NSNumberFormatter dataMarkerFormatter = new NSNumberFormatter(); dataMarkerFormatter.PositiveSuffix = "%"; series.DataMarker.LabelStyle.LabelFormatter = dataMarkerFormatter; chart.Series.Add(series); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } } <file_sep>/iOS/SampleBrowser/Samples/PDF/DigitalSignatureValidation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using System.Reflection; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Security; using MessageUI; using System.Security.Cryptography.X509Certificates; using System.Text; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class DigitalSignatureValidation : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label1; UIButton button; UILabel label2; public DigitalSignatureValidation() { label1 = new UILabel(); label2 = new UILabel(); label2.Hidden = true; button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label1.Frame = frameRect; label1.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label1.Text = "This sample demonstrates how to validate digitally signed PDF document signature."; label1.Font = UIFont.SystemFontOfSize(15); label1.Lines = 0; label1.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label1.Font = UIFont.SystemFontOfSize(18); label1.Frame = new CGRect(0, 12, frameRect.Location.X + frameRect.Size.Width, 50); } else { label1.Frame = new CGRect(frameRect.Location.X, 12, frameRect.Size.Width, 50); } this.AddSubview(label1); button.SetTitle("Validate signature", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 70, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 70, frameRect.Size.Width, 10); } this.AddSubview(button); label2.Frame = frameRect; label2.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label2.Text = ""; label2.Font = UIFont.SystemFontOfSize(15); label2.Lines = 0; label2.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label2.Font = UIFont.SystemFontOfSize(18); label2.Frame = new CGRect(0, 90, frameRect.Location.X + frameRect.Size.Width, frameRect.Size.Height - 100); } else { label2.Frame = new CGRect(frameRect.Location.X, 90, frameRect.Size.Width, frameRect.Size.Height - 100); } this.AddSubview(label2); } void OnButtonClicked(object sender, EventArgs e) { label2.Hidden = false; StringBuilder builder = new StringBuilder(); Stream docStream = typeof(DigitalSignatureValidation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.SignedDocument.pdf"); //Load the PDF document into the loaded document object. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream); //Get signature field PdfLoadedSignatureField lSigFld = loadedDocument.Form.Fields[0] as PdfLoadedSignatureField; //X509Certificate2Collection to check the signer's identity using root certificates X509CertificateCollection collection = new X509CertificateCollection(); //Get the certificate stream from .pfx file. Stream certificateStream = typeof(DigitalSignatureValidation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.PDF.pfx"); byte[] data = new byte[certificateStream.Length]; certificateStream.Read(data, 0, data.Length); //Create new X509Certificate2 with the root certificate X509Certificate2 certificate = new X509Certificate2(data, "<PASSWORD>"); //Add the certificate to the collection collection.Add(certificate); //Validate signature and get the validation result PdfSignatureValidationResult result = lSigFld.ValidateSignature(collection); builder.AppendLine("Signature is " + result.SignatureStatus); builder.AppendLine(); builder.AppendLine("--------Validation Summary--------"); builder.AppendLine(); //Checks whether the document is modified or not bool isModified = result.IsDocumentModified; if (isModified) builder.AppendLine("The document has been altered or corrupted since the signature was applied."); else builder.AppendLine("The document has not been modified since the signature was applied."); //Signature details builder.AppendLine("Digitally signed by " + lSigFld.Signature.Certificate.IssuerName); builder.AppendLine("Valid From : " + lSigFld.Signature.Certificate.ValidFrom); builder.AppendLine("Valid To : " + lSigFld.Signature.Certificate.ValidTo); builder.AppendLine("Signature Algorithm : " + result.SignatureAlgorithm); builder.AppendLine("Hash Algorithm : " + result.DigestAlgorithm); //Revocation validation details builder.AppendLine("OCSP revocation status : " + result.RevocationResult.OcspRevocationStatus); if (result.RevocationResult.OcspRevocationStatus == RevocationStatus.None && result.RevocationResult.IsRevokedCRL) builder.AppendLine("CRL is revoked."); //Close the PDF document loadedDocument.Close(true); label2.Text = builder.ToString(); } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } } <file_sep>/Android/SampleBrowser/Samples/ImageEditor/BannerCreator.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Syncfusion.SfImageEditor.Android; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Content; using Android.Content.PM; using Android.Graphics.Drawables; using Android.Views; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; using Android.Content.Res; using System.Text; namespace SampleBrowser { public class BannerCreator : SamplePage { internal static Activity Activity { get; set; } View view { get; set; } public static int Image { get; set; } ImageButton imageview1; ImageButton imageview2; ImageButton imageview3; Context con { get; set; } public static String Name; public override Android.Views.View GetSampleContent(Android.Content.Context context) { con = context; LayoutInflater layoutInflater = LayoutInflater.From(context); view = layoutInflater.Inflate(Resource.Layout.ImageEditorBannercreator, null); imageview1 = view.FindViewById<ImageButton>(Resource.Id.banner1); imageview2 = view.FindViewById<ImageButton>(Resource.Id.banner2); imageview3 = view.FindViewById<ImageButton>(Resource.Id.banner3); imageview1.Click += pictureOnClick1; imageview2.Click += pictureOnClick2; imageview3.Click += pictureOnClick3; return view; } public void pictureOnClick1(object sender, EventArgs e) { Name = "Coffee"; Activity = con as Activity; Activity?.StartActivity(typeof(ImageEditorActivity)); Image = Resource.Drawable.editordashboard; } public void pictureOnClick2(object sender, EventArgs e) { Name = "Food"; Activity = con as Activity; Activity?.StartActivity(typeof(ImageEditorActivity)); Image = Resource.Drawable.editorsuccinity; } public void pictureOnClick3(object sender, EventArgs e) { Name = "Syncfusion"; Activity = con as Activity; Activity?.StartActivity(typeof(ImageEditorActivity)); Image = Resource.Drawable.editortwitter; } } [Activity(Label = "SfImageEditor", ScreenOrientation = ScreenOrientation.Portrait, Icon = "@drawable/icon")] public class ImageEditorActivity : Activity { View view { get; set; } SfImageEditor editor; Share share; string location = ""; ViewModel viewModel; AssetManager assets; LinearLayout visibilityLayout; protected override void OnCreate(Bundle savedInstanceState) { viewModel = new ViewModel(); assets = this.Assets; LayoutInflater layoutInflater = LayoutInflater.From(this); view = layoutInflater.Inflate(Resource.Layout.EditorBannerMain, null); SetContentView(view); LinearLayout mainLayout = FindViewById<LinearLayout> (Resource.Id.editor_layout); visibilityLayout = FindViewById<LinearLayout> (Resource.Id.visibility_layout); visibilityLayout.Visibility = ViewStates.Gone; Button ok = FindViewById<Button> (Resource.Id.button); Button cancel = FindViewById<Button> (Resource.Id.button2); ok.Click += Ok_Click; cancel.Click += Cancel_Click; editor = new SfImageEditor(this); var bitmap = BitmapFactory.DecodeResource(Resources, BannerCreator.Image); editor.Bitmap = bitmap; mainLayout.AddView(editor); editor.ToolbarSettings.ToolbarItems.Clear(); FooterToolbarItem banner = new FooterToolbarItem() { Text = "Banner Types", SubItems = new List<ToolbarItem>() { new ToolbarItem(){Text="Facebook Post"}, new ToolbarItem(){Text="Facebook Cover"}, new ToolbarItem(){Text="Twitter Cover"}, new ToolbarItem(){Text="Twitter Post"}, new ToolbarItem(){Text="YouTubeChannel Cover"}, }, }; HeaderToolbarItem item2 = new HeaderToolbarItem(); item2.Text = "Share"; item2.Icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.share); HeaderToolbarItem crop = new HeaderToolbarItem(); crop.Text = "Banner Types"; editor.ToolbarSettings.ToolbarItems.Add(item2); editor.ToolbarSettings.ToolbarItems.Add(banner); editor.ToolbarSettings.ToolbarItemSelected += (sender, e) => { if (e.ToolbarItem is HeaderToolbarItem) if ((e.ToolbarItem as HeaderToolbarItem).Text == "Share") { ShareImage(); } if (e.ToolbarItem is ToolbarItem) { var toolitem = e.ToolbarItem as ToolbarItem; if (toolitem.Text != "Banner Types" && toolitem.Text != "Share") { visibilityLayout.Visibility = ViewStates.Visible; } if (toolitem.Text == "Facebook Post") editor.ToggleCropping(1200, 900); else if (toolitem.Text == "Facebook Cover") editor.ToggleCropping(851, 315); else if (toolitem.Text == "Twitter Cover") editor.ToggleCropping(1500, 500); else if (toolitem.Text == "Twitter Post") editor.ToggleCropping(1024, 512); else if (toolitem.Text == "YouTubeChannel Cover") editor.ToggleCropping(2560, 1440); } }; base.OnCreate(savedInstanceState); } async void ShareImage() { editor.Save(); editor.ImageSaving += (sender, e) => { e.Cancel = false; }; editor.ImageSaved += (sender, e) => { location = e.Location; }; await DelayActionAsync(2500, Sharing); } public async Task DelayActionAsync(int delay, Action action) { await Task.Delay(delay); action(); } void Sharing() { share = new Share(); share.Show("Share", "Message", location); } void Ok_Click(object sender, EventArgs e) { editor.Crop(); visibilityLayout.Visibility = ViewStates.Gone; } void Cancel_Click(object sender, EventArgs e) { editor.ToggleCropping(); visibilityLayout.Visibility = ViewStates.Gone; } } public class Share { private readonly Context _context; public Share() { _context = Application.Context; } public Task Show(string title, string message, string filePath) { var extension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower(); var contentType = string.Empty; switch (extension) { case "pdf": contentType = "application/pdf"; break; case "png": contentType = "image/png"; break; case "jpg": contentType = "image/jpg"; break; default: contentType = "application/octetstream"; break; } var intent = new Intent(Intent.ActionSend); intent.SetType(contentType); intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + filePath)); intent.PutExtra(Intent.ExtraText, message ?? string.Empty); intent.PutExtra(Intent.ExtraSubject, title ?? string.Empty); var chooserIntent = Intent.CreateChooser(intent, title ?? string.Empty); chooserIntent.SetFlags(ActivityFlags.ClearTop); chooserIntent.SetFlags(ActivityFlags.NewTask); _context.StartActivity(chooserIntent); return Task.FromResult(true); } } } <file_sep>/Android/SampleBrowser/Samples/RangeNavigator/DataUsage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Rangenavigator; using Android.Graphics; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Java.Util; using Android.Util; using Java.Text; using System.Collections.ObjectModel; namespace SampleBrowser { public class DataUsage : SamplePage { List<DataPoint> dataPoints; TextView dataRangeText; TextView dataUsageText; public override View GetSampleContent(Context context) { LayoutInflater layoutInflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService); View view = layoutInflater.Inflate(Resource.Layout.range_navigator_data_usage, null); CustomRangeNavigator sfRangeNavigator = view.FindViewById<CustomRangeNavigator>(Resource.Id.range_navigator_datausage); dataRangeText = view.FindViewById<TextView>(Resource.Id.date_time_range_text); dataUsageText = view.FindViewById<TextView>(Resource.Id.date_time_usage_mb); sfRangeNavigator.SetMinimumHeight(100); SfChart rangeNavigatorContent = new SfChart(context); sfRangeNavigator.Intervals = Com.Syncfusion.Rangenavigator.DateTimeIntervalType.Month | Com.Syncfusion.Rangenavigator.DateTimeIntervalType.Week; Calendar min = new GregorianCalendar(2015, 0, 1); Calendar max = new GregorianCalendar(2015, 4, 1); Calendar rangeStart = new GregorianCalendar(2015, 1, 13); Calendar rangeEnd = new GregorianCalendar(2015, 2, 13); sfRangeNavigator.Minimum = min.Time; sfRangeNavigator.Maximum = max.Time; sfRangeNavigator.ViewRangeStart = rangeStart.Time; sfRangeNavigator.ViewRangeEnd = rangeEnd.Time; sfRangeNavigator.TooltipEnabled = false; UpdateChart(rangeNavigatorContent, Visibility.Gone); sfRangeNavigator.Content = rangeNavigatorContent; sfRangeNavigator.SetClipChildren(false); dataRangeText.SetPadding(5, 20, 5, 5); dataUsageText.SetPadding(5, 5, 5, 5); sfRangeNavigator.RangeChanged += SfRangeNavigator_RangeChanged; sfRangeNavigator.MinorScaleLabelsCreate += SfRangeNavigator_LabelsGenerated; sfRangeNavigator.MinorScaleStyle.ShowGridLines = false; sfRangeNavigator.MajorScaleStyle.SelectedLabelTextColor = Color.ParseColor("#1cb2d5"); sfRangeNavigator.MajorScaleStyle.LabelTextColor = Color.ParseColor("#5f6872"); return view; } void SfRangeNavigator_LabelsGenerated(object sender, SfDateTimeRangeNavigator.MinorScaleLabelsCreateEventArgs e) { e.MinorScaleLabels.Clear(); } void SfRangeNavigator_RangeChanged(object sender, SfDateTimeRangeNavigator.RangeChangedEventArgs e) { dataRangeText.Text = "Data usage cycle " + new SimpleDateFormat("MMM dd").Format(e.ViewRangeStart) + " - " + new SimpleDateFormat("MMM dd").Format(e.ViewRangeEnd); DateTime minimum = ConvertToDateTime(e.ViewRangeStart); DateTime maximum = ConvertToDateTime(e.ViewRangeEnd); double dataUsage = 0; for (int i = 0; i < dataPoints.Count; i++) { DataPoint chartDataPoint = (DataPoint)dataPoints[i]; DateTime ChartDate = (DateTime)chartDataPoint.Date; if (ChartDate > minimum && ChartDate < maximum) { dataUsage = dataUsage + (Double)chartDataPoint.YValue; } } dataUsageText.Text = "Date Usage " + (int)dataUsage + " MB"; } SfChart UpdateChart(SfChart chart, Visibility axisVisibility) { DateTimeAxis dateTimeAxis = new DateTimeAxis(); dateTimeAxis.Visibility = axisVisibility; dateTimeAxis.LabelStyle.LabelFormat = "dd/MMM"; dateTimeAxis.ShowMajorGridLines = axisVisibility == Visibility.Visible ? true : false; chart.PrimaryAxis = dateTimeAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Visibility = axisVisibility; numericalAxis.ShowMajorGridLines = axisVisibility == Visibility.Visible ? true : false; chart.SecondaryAxis = numericalAxis; chart.Series.Add(new SplineAreaSeries() { ItemsSource = GetDateTimeValue(), XBindingPath = "Date", YBindingPath = "YValue", Alpha = 0.5f, Color = Color.ParseColor("#7ce6c7"), StrokeColor = Color.ParseColor("#1cb2d5") }); return chart; } public List<DataPoint> GetDateTimeValue() { var dateTime = new DateTime(2015, 1, 1); dataPoints = new List<DataPoint>(); dataPoints.Add(new DataPoint(dateTime, 10d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 31d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 28d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 45d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 10d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 23d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 35d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 56d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 10d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 39d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 26d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 21d)); dateTime = dateTime.AddMonths(1); dataPoints.Add(new DataPoint(dateTime, 31d)); return dataPoints; } public static DateTime ConvertToDateTime(object date) { if (date == null) return DateTime.Now; var nativeDate = (Java.Util.Date)date; var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return dateTime.AddMilliseconds(((Java.Util.Date)date).Time).ToLocalTime(); } } }<file_sep>/Forms/ListView/ListView/Samples/Accordion/ViewModel/AccordionViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.ListView.XForms; using Syncfusion.ListView.XForms.Helpers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfListView { public class AccordionViewModel : INotifyPropertyChanged { #region Fields int counter = 11; #endregion #region Properties public ObservableCollection<Contact> ContactsInfo { get; set; } #endregion #region Constructor public AccordionViewModel() { ContactsInfo = new ObservableCollection<Contact>(); int i = 0; foreach (var cusName in CustomerNames) { if (counter == 13) counter = 1; var contact = new Contact(cusName); contact.CallTime = CallTime[i]; contact.ContactImage = "People_Circle" + counter + ".png"; i++; ContactsInfo.Add(contact); counter++; } } #endregion #region Fields string[] CustomerNames = new string[] { "Kyle", "Irene", "Gina", "Katie", "Victoria", "Lily", "Torrey", "Lena", "Violet", "Daniel", "Lucy", "Brenda", "Danielle", "Howard", "Fiona", "Holly", "Liz", "Marley", "Jack", "Pete", "Vince", "Steve", "Katherin", "Aliza", "Masona", "Larry", "Lia", "Jayden ", "Ethani", "Noah ", "John", "Rose", "Erin" }; string[] CallTime = new string[] { "Tunisia, 1 days ago", "Colombia, 1 days ago", "Fiji, 1 days ago", "Belgium, 1 days ago", "Japan, 1 days ago", "Argentina, 2 days ago", "Mexico, 2 days ago", "Guinea, 2 days ago", "Australia, 2 days ago", "Uruguay, 2 days ago", "Denmark, 3 days ago", "Peru, 3 days ago", "Greece, 3 days ago", "Austria, 3 days ago", "Hungary, 3 days ago", "Japan, 4 days ago", "Malaysia, 4 days ago", "Bermuda, 4 days ago", "Egypt, 4 days ago", "Philippines, 4 days ago", "Sweden, 5 days ago", "Vietnam, 5 days ago", "Yemen, 5 days ago", "Nepal, 5 days ago", "Kenya, 5 days ago", "Iceland, 6 days ago", "Canada, 6 days ago", "Angola, 6 days ago", "Italy, 6 days ago", "Monaco, 6 days ago", "Sudan, 1 week ago", "Togo, 1 week ago", "Benin, 1 week ago" }; #endregion #region Interface Member public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/FormattingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; namespace SampleBrowser { public class FormattingViewModel { public FormattingViewModel() { SetRowstoGenerate(100); } #region ItemsSource private List<BankInfo> bankInfo; public List<BankInfo> BankInfo { get { return bankInfo; } set { this.bankInfo = value; } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { BankRepository bank = new BankRepository(); bankInfo = bank.GetBankDetails(200); } #endregion } } <file_sep>/Forms/Cards/readme.md Syncfusion CardView for Xamarin.Forms provides a perfect way to display content and actions on a single topic.<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/MultipleAxes.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class MultipleAxes : SampleView { public MultipleAxes () { SFChart chart = new SFChart (); chart.Title.Text = new NSString("Mutiple Axes"); chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.ColorModel.Palette = SFChartColorPalette.Natural; SFCategoryAxis primaryAxis = new SFCategoryAxis (); primaryAxis.LabelPlacement = SFChartLabelPlacement.BetweenTicks; primaryAxis.Title.Text = new NSString("Years"); chart.PrimaryAxis = primaryAxis; chart.SecondaryAxis = new SFNumericalAxis (){ ShowMajorGridLines = false }; chart.SecondaryAxis.Title.Text = new NSString ("Revenue (in millions)"); NSNumberFormatter formatter = new NSNumberFormatter (); formatter.PositiveFormat = "$"; chart.SecondaryAxis.LabelStyle.LabelFormatter = formatter; ChartViewModel dataModel = new ChartViewModel (); SFColumnSeries series = new SFColumnSeries(); series.ItemsSource = dataModel.MultipleAxisData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.Label = new NSString("Revenue"); series.EnableAnimation = true; chart.Series.Add(series); SFLineSeries series1 = new SFLineSeries(); series1.ItemsSource = dataModel.MultipleAxisData1; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.EnableTooltip = true;series1.Label = new NSString("Customers"); series1.YAxis = new SFNumericalAxis() { OpposedPosition = true, Minimum = new NSNumber(0), Maximum = new NSNumber(80), Interval = new NSNumber(5), ShowMajorGridLines = false }; series1.YAxis.Title.Text = new NSString("Number of Customers"); series1.EnableAnimation = true; chart.Series.Add(series1); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } }<file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/ListViewPullToRefresh/SfListViewPullToRefreshBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SfListViewPullToRefreshBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Core; using Syncfusion.ListView.XForms; using Syncfusion.SfPullToRefresh.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] #region PullToRefreshBehavior /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the ListViewPullToRefreshBehavior samples /// </summary> public class SfListViewPullToRefreshBehavior : Behavior<SampleView> { #region Fields [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ListViewPullToRefreshViewModel pulltoRefreshViewModel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfListView listView; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfPullToRefresh pullToRefresh; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt picker; #endregion #region Overrides /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of parameter named as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.listView = bindAble.FindByName<SfListView>("listView"); this.pulltoRefreshViewModel = new ListViewPullToRefreshViewModel(); this.pulltoRefreshViewModel.Navigation = bindAble.Navigation; this.listView.BindingContext = this.pulltoRefreshViewModel; this.listView.ItemsSource = this.pulltoRefreshViewModel.BlogsInfo; this.pullToRefresh = bindAble.FindByName<SfPullToRefresh>("pullToRefresh"); this.pullToRefresh.Refreshing += this.PullToRefresh_Refreshing; this.picker = bindAble.FindByName<PickerExt>("transitionTypePicker"); this.picker.Items.Add("SlideOnTop"); this.picker.Items.Add("Push"); this.picker.SelectedIndex = 1; this.picker.SelectedIndexChanged += this.Picker_SelectedIndexChanged; base.OnAttachedTo(bindAble); } /// <summary> /// Fired when picker selected index is changed. /// </summary> /// <param name="sender">Picker_SelectedIndexChanged event sender</param> /// <param name="e">Picker_SelectedIndexChanged event args e</param> private void Picker_SelectedIndexChanged(object sender, EventArgs e) { if (this.picker.SelectedIndex == 0) { this.pullToRefresh.RefreshContentThreshold = 0; this.pullToRefresh.TransitionMode = TransitionType.SlideOnTop; } else { this.pullToRefresh.RefreshContentThreshold = 50; this.pullToRefresh.TransitionMode = TransitionType.Push; } } #endregion #region Private Methods /// <summary> /// Triggers while PullToRefresh View was refreshing /// </summary> /// <param name="sender">PullToRefresh_Refreshing event sender</param> /// <param name="args">PullToRefresh_Refreshing event args e</param> private async void PullToRefresh_Refreshing(object sender, EventArgs args) { this.pullToRefresh.IsRefreshing = true; await Task.Delay(1200); int blogsTitleCount = this.pulltoRefreshViewModel.Source.BlogsTitle.Count() - 1; if (this.pulltoRefreshViewModel.BlogsInfo.Count - 1 == blogsTitleCount) { this.pullToRefresh.IsRefreshing = false; return; } int blogsCategoryCount = this.pulltoRefreshViewModel.Source.BlogsCategory.Count() - 1; int blogsAuthorCount = this.pulltoRefreshViewModel.Source.BlogsAuthers.Count() - 1; int blogsReadMoreCount = this.pulltoRefreshViewModel.Source.BlogsReadMoreInfo.Count() - 1; for (int i = 0; i < 3; i++) { int blogsCount = this.pulltoRefreshViewModel.BlogsInfo.Count; ListViewBlogsInfo item = new ListViewBlogsInfo { BlogTitle = this.pulltoRefreshViewModel.Source.BlogsTitle[blogsTitleCount - blogsCount], BlogAuthor = this.pulltoRefreshViewModel.Source.BlogsAuthers[blogsAuthorCount - blogsCount], BlogCategory = this.pulltoRefreshViewModel.Source.BlogsCategory[blogsCategoryCount - blogsCount], ReadMoreContent = this.pulltoRefreshViewModel.Source.BlogsReadMoreInfo[blogsReadMoreCount - blogsCount], BlogAuthorIcon = new FontImageSource { Glyph = "\ue72a", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.FromRgb(51, 173, 225), }, BlogCategoryIcon = new FontImageSource { Glyph = "\ue738", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.FromRgb(51, 173, 225), }, BlogFacebookIcon = "FacebookLine.png", BlogTwitterIcon = "TwitterLine.png", BlogGooglePlusIcon = "GooglePlusLine.png", BlogLinkedInIcon = "LinkedInLine.png", }; this.pulltoRefreshViewModel.BlogsInfo.Insert(0, item); } this.pullToRefresh.IsRefreshing = false; } #endregion } #endregion }<file_sep>/Android/SampleBrowser/Samples/TreeView/ViewModel/FileManagerViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public class FileManagerViewModel { public ObservableCollection<FileManager> Folders { get; set; } public FileManagerViewModel() { GenerateFiles(); } private void GenerateFiles() { var doc = new FileManager() { FileName = "Documents", ImageIcon = Resource.Drawable.treeview_folder }; var download = new FileManager() { FileName = "Downloads", ImageIcon = Resource.Drawable.treeview_folder }; var mp3 = new FileManager() { FileName = "Music", ImageIcon = Resource.Drawable.treeview_folder }; var pics = new FileManager() { FileName = "Pictures", ImageIcon = Resource.Drawable.treeview_folder }; var video = new FileManager() { FileName = "Videos", ImageIcon = Resource.Drawable.treeview_folder }; var pollution = new FileManager() { FileName = "Environmental Pollution.docx", ImageIcon = Resource.Drawable.treeview_word }; var globalwarming = new FileManager() { FileName = "Global Warming.ppt", ImageIcon = Resource.Drawable.treeview_ppt }; var sanitation = new FileManager() { FileName = "Sanitation.docx", ImageIcon = Resource.Drawable.treeview_word }; var socialnetwork = new FileManager() { FileName = "Social Network.pdf", ImageIcon = Resource.Drawable.treeview_pdf }; var youthempower = new FileManager() { FileName = "Youth Empowerment.pdf", ImageIcon = Resource.Drawable.treeview_pdf }; var game = new FileManager() { FileName = "Game.exe", ImageIcon = Resource.Drawable.treeview_exe }; var tutorials = new FileManager() { FileName = "Tutorials.zip", ImageIcon = Resource.Drawable.treeview_zip }; var typescript = new FileManager() { FileName = "TypeScript.7z", ImageIcon = Resource.Drawable.treeview_zip }; var uiguide = new FileManager() { FileName = "UI-Guide.pdf", ImageIcon = Resource.Drawable.treeview_pdf }; var song = new FileManager() { FileName = "Gouttes", ImageIcon = Resource.Drawable.treeview_mp3 }; var camera = new FileManager() { FileName = "Camera Roll", ImageIcon = Resource.Drawable.treeview_folder }; var stone = new FileManager() { FileName = "Stone.jpg", ImageIcon = Resource.Drawable.treeview_png }; var wind = new FileManager() { FileName = "Wind.jpg", ImageIcon = Resource.Drawable.treeview_png }; var img0 = new FileManager() { FileName = "WIN_20160726_094117.JPG", ImageIcon = Resource.Drawable.treeview_img0 }; var img1 = new FileManager() { FileName = "WIN_20160726_094118.JPG", ImageIcon = Resource.Drawable.treeview_img1 }; var video0 = new FileManager() { FileName = "Naturals.mp4", ImageIcon = Resource.Drawable.treeview_video }; var video1 = new FileManager() { FileName = "Wild.mpeg", ImageIcon = Resource.Drawable.treeview_video }; doc.SubFolder = new ObservableCollection<FileManager> { pollution, globalwarming, sanitation, socialnetwork, youthempower }; download.SubFolder = new ObservableCollection<FileManager> { game, tutorials, typescript, uiguide }; mp3.SubFolder = new ObservableCollection<FileManager> { song }; pics.SubFolder = new ObservableCollection<FileManager> { camera, stone, wind }; camera.SubFolder = new ObservableCollection<FileManager> { img0, img1 }; video.SubFolder = new ObservableCollection<FileManager> { video0, video1 }; this.Folders = new ObservableCollection<FileManager>(); Folders.Add(doc); Folders.Add(download); Folders.Add(mp3); Folders.Add(pics); Folders.Add(video); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/CircularGauge/GradientRange.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfGauge.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using System.Drawing; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class GradientRange : SampleView { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } SFCircularGauge gauge; public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } if (Utility.IsIpad) { gauge.Frame = new CGRect(50, 50, (float)this.Frame.Width - 100, (float)this.Frame.Height - 100); } else { gauge.Frame = new CGRect(10, 10, (float)this.Frame.Width - 20, (float)this.Frame.Height - 20); } base.LayoutSubviews(); } public GradientRange() { gauge = new SFCircularGauge(); gauge.BackgroundColor = UIColor.White; ObservableCollection<SFCircularScale> scales = new ObservableCollection<SFCircularScale>(); SFCircularScale scale = new SFCircularScale(); scale.StartValue = 0; scale.EndValue = 100; scale.Interval = 10; scale.ShowRim = false; scale.ShowTicks = false; scale.ShowLabels = false; SFCircularRange range = new SFCircularRange(); range.Offset = 0.8f; range.StartValue = 0; range.EndValue = 100; range.Width = 25; GaugeGradientStop color1 = new GaugeGradientStop(); color1.Value = 0; color1.Color = UIColor.FromRGB(240, 62, 62); range.GradientStops.Add(color1); GaugeGradientStop color2 = new GaugeGradientStop(); color2.Value = 35; color2.Color = UIColor.FromRGB(255, 221, 0); range.GradientStops.Add(color2); GaugeGradientStop color3 = new GaugeGradientStop(); color3.Value = 75; color3.Color = UIColor.FromRGB(255, 221, 0); range.GradientStops.Add(color3); GaugeGradientStop color4 = new GaugeGradientStop(); color4.Value = 100; color4.Color = UIColor.FromRGB(48, 179, 45); range.GradientStops.Add(color4); scale.Ranges.Add(range); ObservableCollection<SFMarkerPointer> pointers = new ObservableCollection<SFMarkerPointer>(); SFMarkerPointer pointer = new SFMarkerPointer(); pointer.MarkerShape = MarkerShape.InvertedTriangle; pointer.Offset = 0.8f; pointer.Value = 55; pointer.MarkerWidth = 15; pointer.MarkerHeight = 15; pointer.Color = UIColor.Red; pointers.Add(pointer); scale.Pointers.Add(pointer); SFGaugeHeader header1 = new SFGaugeHeader(); header1.Text = (Foundation.NSString)"0"; header1.TextColor = UIColor.FromRGB(240, 62, 62); header1.Position = new CGPoint(0.28, 0.86); header1.TextStyle = UIFont.BoldSystemFontOfSize(12); gauge.Headers.Add(header1); SFGaugeHeader header2 = new SFGaugeHeader(); header2.Text = (Foundation.NSString)"100"; header2.TextColor = UIColor.FromRGB(48, 179, 45); header2.Position = new CGPoint(0.75, 0.86); header2.TextStyle = UIFont.BoldSystemFontOfSize(12); gauge.Headers.Add(header2); SFGaugeHeader header3 = new SFGaugeHeader(); header3.Text = (Foundation.NSString)"55%"; header3.TextColor = UIColor.FromRGB(240, 62, 62); header3.Position = new CGPoint(0.5, 0.5); header1.TextStyle = UIFont.BoldSystemFontOfSize(16); gauge.Headers.Add(header3); scales.Add(scale); gauge.Scales = scales; this.AddSubview(gauge); } protected override void Dispose(bool disposing) { //gauge.Scales[0].Pointers.Clear(); //gauge.Scales[0].Ranges[0].GradientColors.Clear(); //gauge.Scales[0].Ranges.Clear(); //gauge.Scales.Clear(); //gauge.Dispose(); base.Dispose(disposing); } } } <file_sep>/Android/SampleBrowser/Samples/DataSource/Model/Contacts.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SampleBrowser { public class Contacts { private string contactName; private string contactNumber; private Color color; public Contacts(string name, string number) { contactName = name; contactNumber = number; } public string ContactName { get { return contactName; } set { contactName = value; } } public string ContactNumber { get { return contactNumber; } set { contactNumber = value; } } public Color ContactColor { get { return color; } set { color = value; } } } }<file_sep>/Forms/ImageEditor/ImageEditor.Android/Share.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using System.Threading.Tasks; namespace SampleBrowser.SfImageEditor.Droid { public class Share: IShare { private readonly Context _context; public Share() { _context = Application.Context; } public void Show( string title, string message, string filePath) { var extension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower(); var contentType = string.Empty; switch (extension) { case "pdf": contentType = "application/pdf"; break; case "png": contentType = "image/png"; break; case "jpg": contentType = "image/jpg"; break; default: contentType = "application/octetstream"; break; } Java.IO.File file = new Java.IO.File(filePath); if (file.Exists()) { Intent email = new Intent(Intent.ActionSend); Android.Net.Uri uri = Android.Support.V4.Content.FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file); email.PutExtra(Intent.ExtraSubject, message); email.PutExtra(Intent.ExtraStream, uri); email.SetFlags(ActivityFlags.NewTask); email.SetType(contentType); Application.Context.StartActivity(email); } } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/ImageResourceExtension.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ImageResourceExtension.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; [ContentProperty("Source")] [Preserve(AllMembers = true)] /// <summary> /// Returns the object created from the markup extension. /// </summary> public class ImageResourceExtension : IMarkupExtension { /// <summary> /// Gets or sets the value for Source /// </summary> public string Source { get; set; } /// <summary> /// Used to provide the image source value /// </summary> /// <param name="serviceProvider">IServiceProvider type parameter</param> /// <returns>IServiceProvider type of image Source</returns> public object ProvideValue(IServiceProvider serviceProvider) { if (this.Source == null) { return null; } // Do your translation lookup here, using whatever method you require var imageSource = ImageSource.FromResource(this.Source); return imageSource; } } }<file_sep>/Forms/TreeView/TreeView/Samples/NodeWithImage/ViewModel/FileManagerViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public class FileManagerViewModel { private ObservableCollection<object> checkedItems; public ObservableCollection<object> CheckedItems { get { return checkedItems; } set { this.checkedItems = value; } } public ObservableCollection<Folder> Folders { get; set; } public ObservableCollection<File> Files { get; set; } public ObservableCollection<SubFile> SubFiles { get; set; } public FileManagerViewModel() { this.Folders = GetFiles(); } private ObservableCollection<Folder> GetFiles() { var nodeImageInfo = new ObservableCollection<Folder>(); Assembly assembly = typeof(NodeWithImage).GetTypeInfo().Assembly; var doc = new Folder() { FileName = "Documents", ImageIcon = "Doc.png" }; var download = new Folder() { FileName = "Downloads", ImageIcon = "Doc.png" }; var mp3 = new Folder() { FileName = "Music", ImageIcon = "Doc.png" }; var pictures = new Folder() { FileName = "Pictures", ImageIcon = "Doc.png" }; var video = new Folder() { FileName = "Videos", ImageIcon = "Doc.png" }; var pollution = new File() { FileName = "Environmental Pollution.docx", ImageIcon = "Word.png" }; var globalWarming = new File() { FileName = "Global Warming.ppt", ImageIcon = "PP.png" }; var sanitation = new File() { FileName = "Sanitation.docx", ImageIcon = "Word.png" }; var socialNetwork = new File() { FileName = "Social Network.pdf", ImageIcon = "PDF_Icon.png" }; var youthEmpower = new File() { FileName = "Youth Empowerment.pdf", ImageIcon = "PDF_Icon.png" }; var games = new File() { FileName = "Game.exe", ImageIcon = "EXE.png" }; var tutorials = new File() { FileName = "Tutorials.zip", ImageIcon = "Zip.png" }; var typeScript = new File() { FileName = "TypeScript.7z", ImageIcon = "Zip.png" }; var uiGuide = new File() { FileName = "UI-Guide.pdf", ImageIcon = "PDF_Icon.png" }; var song = new File() { FileName = "Gouttes", ImageIcon = "Audio.png" }; var camera = new File() { FileName = "Camera Roll", ImageIcon = "Doc.png" }; var stone = new File() { FileName = "Stone.jpg", ImageIcon = "Png.png" }; var wind = new File() { FileName = "Wind.jpg", ImageIcon = "Png.png" }; var img0 = new SubFile() { FileName = "WIN_20160726_094117.JPG", ImageIcon = "People_Circle6.png" }; var img1 = new SubFile() { FileName = "WIN_20160726_094118.JPG", ImageIcon = "People_Circle5.png" }; var video1 = new File() { FileName = "Naturals.mp4", ImageIcon = "Video.png" }; var video2 = new File() { FileName = "Wild.mpeg", ImageIcon = "Video.png" }; doc.Files = new ObservableCollection<File> { pollution, globalWarming, sanitation, socialNetwork, youthEmpower }; download.Files = new ObservableCollection<File> { games, tutorials, typeScript, uiGuide }; mp3.Files = new ObservableCollection<File> { song }; pictures.Files = new ObservableCollection<File> { camera, stone, wind }; camera.SubFiles = new ObservableCollection<SubFile> { img0, img1 }; video.Files = new ObservableCollection<File> { video1, video2 }; nodeImageInfo.Add(doc); nodeImageInfo.Add(download); nodeImageInfo.Add(mp3); nodeImageInfo.Add(pictures); nodeImageInfo.Add(video); checkedItems = new ObservableCollection<object>(); checkedItems.Add(pollution); checkedItems.Add(sanitation); checkedItems.Add(youthEmpower); checkedItems.Add(camera); checkedItems.Add(video1); checkedItems.Add(video1); checkedItems.Add(typeScript); checkedItems.Add(typeScript); return nodeImageInfo; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/XlsIO/FindandReplace.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XlsIO; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class FindandReplace : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button_1; UIButton button ; public FindandReplace() { label = new UILabel (); label1 = new UILabel (); button_1 = new UIButton (UIButtonType.System); button = new UIButton (UIButtonType.System); button_1.TouchUpInside += OnButtonClicked_1; button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to find the word Berlin and replace it as Rome within the worksheet."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width , 50); } else { label.Frame = new CGRect (5, 5, frameRect.Size.Width , 60); } this.AddSubview (label); button_1.SetTitle("Input Template",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button_1.Frame = new CGRect (0, 65, frameRect.Location.X + frameRect.Size.Width , 20); } else { button_1.Frame = new CGRect (5, 70, frameRect.Size.Width , 20); } this.AddSubview (button_1); button.SetTitle("Replace all",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect (0, 95, frameRect.Location.X + frameRect.Size.Width , 20); } else { button.Frame = new CGRect (5, 100, frameRect.Size.Width , 20); } this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ReplaceOptions.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly (); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); IWorksheet sheet = workbook.Worksheets[0]; #endregion string replaceText = "Berlin"; ExcelFindOptions option = ExcelFindOptions.None; option |= ExcelFindOptions.MatchCase; option |= ExcelFindOptions.MatchEntireCellContent; sheet.Replace (replaceText, "Rome", option); workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("FindAndReplace.xlsx", "application/msexcel", stream); } } void OnButtonClicked_1(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ReplaceOptions.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly (); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("InputTemplate.xlsx", "application/msexcel", stream ); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/Forms/Calculate/Calculate/Samples/FunctionsLibrary/ComputeCommand.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Calculate; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms.Internals; namespace SampleBrowser.Calculate { [Preserve(AllMembers = true)] public class ComputeCommand : ICommand { private FunctionsLibraryViewModel viewModel; private CalcData calcData; public ComputeCommand(FunctionsLibraryViewModel _viewModel) { viewModel = _viewModel; calcData = viewModel._CalcData; } public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { calcData.SetValueRowCol(viewModel.TxtA1, 1, 1); calcData.SetValueRowCol(viewModel.TxtA2, 2, 1); calcData.SetValueRowCol(viewModel.TxtA3, 3, 1); calcData.SetValueRowCol(viewModel.TxtA4, 4, 1); calcData.SetValueRowCol(viewModel.TxtA5, 5, 1); calcData.SetValueRowCol(viewModel.TxtB1, 1, 2); calcData.SetValueRowCol(viewModel.TxtB2, 2, 2); calcData.SetValueRowCol(viewModel.TxtB3, 3, 2); calcData.SetValueRowCol(viewModel.TxtB4, 4, 2); calcData.SetValueRowCol(viewModel.TxtB5, 5, 2); calcData.SetValueRowCol(viewModel.TxtC1, 1, 3); calcData.SetValueRowCol(viewModel.TxtC2, 2, 3); calcData.SetValueRowCol(viewModel.TxtC3, 3, 3); calcData.SetValueRowCol(viewModel.TxtC4, 4, 3); calcData.SetValueRowCol(viewModel.TxtC5, 5, 3); try { viewModel.TxtResult = viewModel.Engine.ParseAndComputeFormula(viewModel.TxtGen); } catch(Exception) { App.Current.MainPage.DisplayAlert("Warning!", "Invalid expression", "OK"); } } private void RaiseCanExcuteChanged() { if (CanExecuteChanged != null) CanExecuteChanged(this, new EventArgs()); } } [Preserve(AllMembers = true)] public class CalcData : ICalcData { public CalcData() { } public event ValueChangedEventHandler ValueChanged; Dictionary<string, object> values = new Dictionary<string, object>(); public object GetValueRowCol(int row, int col) { object value = null; var key = RangeInfo.GetAlphaLabel(col) + row; this.values.TryGetValue(key, out value); return value; } public void SetValueRowCol(object value, int row, int col) { var key = RangeInfo.GetAlphaLabel(col) + row; if (!values.ContainsKey(key)) values.Add(key, value); else if (values.ContainsKey(key) && values[key] != value) values[key] = value; } public void WireParentObject() { } private void OnValueChanged(int row, int col, string value) { if (ValueChanged != null) ValueChanged(this, new ValueChangedEventArgs(row, col, value)); } } } <file_sep>/Android/SampleBrowser/Samples/CircularGauge/CircularGauge.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfCircularGauge; using System.Collections.ObjectModel; using Android.Graphics; using Com.Syncfusion.Gauges.SfCircularGauge.Enums; using Android.Renderscripts; namespace SampleBrowser { public class CircularGauge: SamplePage { NeedlePointer pointer; double value; public override View GetSampleContent (Context con) { SfCircularGauge sfCircularGauge = new SfCircularGauge(con); ObservableCollection<CircularScale> circularScales = new ObservableCollection<CircularScale>(); CircularScale scale = new CircularScale(); scale.StartValue = 0; scale.EndValue = 100; scale.Interval = 10; scale.StartAngle = 135; scale.SweepAngle = 270; scale.RimWidth = 10; scale.RimColor = Color.ParseColor("#E0E0E0"); scale.LabelColor = Color.Black; scale.LabelOffset = 0.8; scale.ShowTicks = false; scale.MinorTicksPerInterval = 0; ObservableCollection<CircularPointer> pointers = new ObservableCollection<CircularPointer>(); pointer = new NeedlePointer(); pointer.Value = 60; pointer.KnobRadius = 10; pointer.Color = Color.ParseColor("#757575"); pointer.KnobColor = Color.ParseColor("#757575"); pointer.LengthFactor = 0.6; pointer.Type = Com.Syncfusion.Gauges.SfCircularGauge.Enums.NeedleType.Triangle; pointers.Add(pointer); scale.CircularPointers = pointers; circularScales.Add(scale); sfCircularGauge.CircularScales = circularScales; sfCircularGauge.SetBackgroundColor(Color.White); LinearLayout linearLayout = new LinearLayout(con); linearLayout.AddView(sfCircularGauge); linearLayout.SetPadding(30, 30, 30, 30); linearLayout.SetBackgroundColor(Color.White); return linearLayout; } public override View GetPropertyWindowLayout(Android.Content.Context context) { TextView pointervalue = new TextView(context); pointervalue.Text = "Change Pointer Value"; pointervalue.Typeface = Typeface.DefaultBold; pointervalue.SetTextColor(Color.ParseColor("#262626")); pointervalue.TextSize = 20; SeekBar pointerSeek = new SeekBar(context); pointerSeek.Max = 100; pointerSeek.Progress = 60; pointerSeek.ProgressChanged += pointerSeek_ProgressChanged; LinearLayout optionsPage = new LinearLayout(context); optionsPage.Orientation = Orientation.Vertical; optionsPage.AddView(pointervalue); optionsPage.AddView(pointerSeek); optionsPage.SetPadding(10,10,10,10); optionsPage.SetBackgroundColor(Color.White); return optionsPage; } void pointerSeek_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { value = e.Progress; pointer.Value = value; } public override void OnApplyChanges() { base.OnApplyChanges(); } } } <file_sep>/Forms/Shimmer/Shimmer/Samples/ShimmerCustomization/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Buttons; using Syncfusion.XForms.Border; using Syncfusion.XForms.Shimmer; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Xamarin.Forms; namespace SampleBrowser.SfShimmer { public class ViewModel : INotifyPropertyChanged { private int waveWidth = 200; private Color waveColor = Color.FromHex("#D1D1D1"); private Color shimmerColor = Color.FromHex("#EBEBEB"); private int duration = 1000; public int WaveWidth { get { return waveWidth; } set { waveWidth = value; RaisePropertyChanged("WaveWidth"); } } public int Duration { get { return duration; } set { duration = value; RaisePropertyChanged("Duration"); } } public Color WaveColor { get { return waveColor; } set { waveColor = value; RaisePropertyChanged("WaveColor"); } } public Color ShimmerColor { get { return shimmerColor; } set { shimmerColor = value; RaisePropertyChanged("ShimmerColor"); } } public ObservableCollection<Color> ShimmerColors { get; set; } public List<Color> WaveColors { get; set; } public event PropertyChangedEventHandler PropertyChanged; public Array ShimmerTypes { get { return Enum.GetValues(typeof(ShimmerTypes)); } } public Array WaveDirectionTypes { get { return Enum.GetValues(typeof(WaveDirection)); } } private void RaisePropertyChanged(string v) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(v)); } public ViewModel() { ShimmerColors = new ObservableCollection<Color> { Color.FromHex("#EBEBEB"), Color.FromHex("#E7E7F9"), Color.FromHex("#E1EFFF"), Color.FromHex("#F4E2EE"), Color.FromHex("#F6F6DB"), }; WaveColors = new List<Color> { Color.FromHex("#D1D1D1"), Color.FromHex("#CECEEF"), Color.FromHex("#B8D4F2"), Color.FromHex("#DFBFD5"), Color.FromHex("#E7E7B2"), }; } } }<file_sep>/Forms/TabView/TabView/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XForms.TabView; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SampleBrowser.Core; using System.Collections.ObjectModel; using System.Linq; namespace SampleBrowser.SfTabView { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Themes : SampleView { public Themes() { InitializeComponent(); if (Device.RuntimePlatform == "iOS") { furnitureLabel.FontFamily = clothingLabel.FontFamily = shoesLabel.FontFamily = fruitsLabel.FontFamily = toysLabel.FontFamily = "TabIcons"; } else if (Device.RuntimePlatform == "Android") { furnitureLabel.FontFamily = clothingLabel.FontFamily = shoesLabel.FontFamily = fruitsLabel.FontFamily = toysLabel.FontFamily = "TabIcons.ttf#TabIcons"; } else if (Device.RuntimePlatform == "UWP") { furnitureLabel.FontFamily = clothingLabel.FontFamily = shoesLabel.FontFamily = fruitsLabel.FontFamily = toysLabel.FontFamily = "/Assets/Fonts/TabIcons.ttf#TabIcons"; if (Core.SampleBrowser.IsIndividualSB) { furnitureLabel.FontFamily = clothingLabel.FontFamily = shoesLabel.FontFamily = fruitsLabel.FontFamily = toysLabel.FontFamily = "/Assets/Fonts/TabIcons.ttf#TabIcons"; } else { furnitureLabel.FontFamily = clothingLabel.FontFamily = shoesLabel.FontFamily = fruitsLabel.FontFamily = toysLabel.FontFamily = $"ms-appx:///SampleBrowser.SfTabView.UWP/Assets/Fonts/TabIcons.ttf#TabIcons"; //@"SampleBrowser.SfTabView.UWP\Assets\Fonts\TabIcons.ttf#TabIcons"; } } } } }<file_sep>/Forms/Schedule/Schedule/Samples/AppointmentEditor/Behaviors/EditorLayoutBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Editor Layout Behavior class. /// </summary> internal class EditorLayoutBehavior : Behavior<StackLayout> { #region Fields /// <summary> /// editor scroll view. /// </summary> private ScrollView editorScrollView; /// <summary> /// save button. /// </summary> private Button saveButton; /// <summary> /// cancel button. /// </summary> private Button cancelButton; /// <summary> /// Save button grid. /// </summary> private Grid saveButtonGrid; /// <summary> /// cancel button grid. /// </summary> private Grid cancelButtonGrid; /// <summary> /// end date picker. /// </summary> private DatePicker endDatePicker; /// <summary> /// end time picker. /// </summary> private TimePicker endTimePicker; /// <summary> /// selected appointment. /// </summary> private Meeting selectedAppointment; /// <summary> /// selected date. /// </summary> private DateTime selectedDate; /// <summary> /// start date picker. /// </summary> private DatePicker startDatePicker; /// <summary> /// start time picker. /// </summary> private TimePicker startTimePicker; /// <summary> /// editor layout. /// </summary> private StackLayout editorLayout; /// <summary> /// Allday grid. /// </summary> private Grid allDayGrid; /// <summary> /// Allday label. /// </summary> private Label allDayLabel; /// <summary> /// all day switch. /// </summary> private Switch switchAllDay; /// <summary> /// event name text. /// </summary> private Entry eventNameText; /// <summary> /// organizer text. /// </summary> private Entry organizerText; /// <summary> /// editor buttons. /// </summary> private Grid editorButtonsGrid; /// <summary> /// end time label layout /// </summary> private Grid endTimeLabelLayout; /// <summary> /// start date time picker layout. /// </summary> private Grid startDateTimePickerLayout; /// <summary> /// start date picker layout /// </summary> private Grid startDatePickerLayout; /// <summary> /// start time picker layout. /// </summary> private Grid startTimePickerLayout; /// <summary> /// end date time picker layout. /// </summary> private Grid endDateTimePickerLayout; /// <summary> /// end date picker layout. /// </summary> private Grid endDatePickerLayout; /// <summary> /// end time picker layout. /// </summary> private Grid endTimePickerLayout; /// <summary> /// start time label layout. /// </summary> private Grid startTimeLabelLayout; /// <summary> /// organizer layout. /// </summary> private Grid organizerLayout; /// <summary> /// start time zone picker. /// </summary> private Picker startTimeZonePicker; /// <summary> /// end time zone picker /// </summary> private Picker endTimeZonePicker; /// <summary> /// start time zone /// </summary> private string startTimeZone; /// <summary> /// end time zone /// </summary> private string endTimeZone; #endregion #region OpenEditor /// <summary> /// Method for editor open /// </summary> /// <param name="appointment">appointment value</param> /// <param name="date">date value</param> public void OpenEditor(Meeting appointment, DateTime date) { this.editorScrollView.ScrollToAsync(0, 0, false); this.cancelButton.BackgroundColor = Color.FromHex("#E5E5E5"); this.saveButton.BackgroundColor = Color.FromHex("#2196F3"); this.eventNameText.Placeholder = "Event name"; this.organizerText.Placeholder = "Organizer"; this.selectedAppointment = null; if (appointment != null) { this.selectedAppointment = appointment; this.selectedDate = date; } else { this.selectedDate = date; } this.UpdateEditor(); } #endregion #region UpdateElements /// <summary> /// Method for editor elements /// </summary> internal void AddEditorElements() { if (Device.RuntimePlatform == "UWP" && Device.Idiom == TargetIdiom.Phone) { this.organizerLayout.IsVisible = false; this.startDateTimePickerLayout.Padding = new Thickness(20, 0, 20, 0); this.startDateTimePickerLayout.ColumnDefinitions.Clear(); this.startDateTimePickerLayout.RowDefinitions = new RowDefinitionCollection() { new RowDefinition { Height = GridLength.Auto }, new RowDefinition { Height = GridLength.Auto }, }; Grid.SetRow(this.startDatePickerLayout, 0); Grid.SetColumnSpan(this.startDatePickerLayout, 3); Grid.SetColumn(this.startTimePickerLayout, 0); Grid.SetColumnSpan(this.startTimePickerLayout, 3); Grid.SetRow(this.startTimePickerLayout, 1); this.startDatePickerLayout.HeightRequest = 40; this.startTimePickerLayout.HeightRequest = 40; this.startTimeLabelLayout.Padding = new Thickness(20, 5, 0, 0); this.startDateTimePickerLayout.Padding = new Thickness(20, 0, 20, 0); this.endDateTimePickerLayout.ColumnDefinitions.Clear(); this.endDateTimePickerLayout.Padding = new Thickness(20, 0, 20, 0); this.endDateTimePickerLayout.RowDefinitions = new RowDefinitionCollection() { new RowDefinition { Height = GridLength.Auto }, new RowDefinition { Height = GridLength.Auto }, }; Grid.SetRow(this.endDatePickerLayout, 0); Grid.SetRow(this.endTimePickerLayout, 1); Grid.SetColumnSpan(this.endDatePickerLayout, 3); Grid.SetColumn(this.endTimePickerLayout, 0); Grid.SetColumnSpan(this.endTimePickerLayout, 3); this.endDatePickerLayout.HeightRequest = 40; this.endTimePickerLayout.HeightRequest = 40; this.endTimeLabelLayout.Padding = new Thickness(20, 5, 0, 0); } else if (Device.RuntimePlatform == "Android") { this.editorLayout.Padding = 20; } } #endregion #region Get TimeZone Index from TimeZoneCollection #region OnAttached /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(StackLayout bindable) { this.editorLayout = bindable; this.editorScrollView = bindable.FindByName<ScrollView>("editorScrollView"); this.eventNameText = bindable.FindByName<Entry>("eventNameText"); this.organizerText = bindable.FindByName<Entry>("organizerText"); this.cancelButtonGrid = bindable.FindByName<Grid>("cancelButtonGrid"); this.saveButtonGrid = bindable.FindByName<Grid>("saveButtonGrid"); this.cancelButton = bindable.FindByName<Button>("cancelButton"); this.saveButton = bindable.FindByName<Button>("saveButton"); this.editorButtonsGrid = bindable.FindByName<Grid>("editorButtons"); this.endDatePicker = bindable.FindByName<DatePicker>("endDate_picker"); this.endTimePicker = bindable.FindByName<TimePicker>("endTime_picker"); this.startDatePicker = bindable.FindByName<DatePicker>("startDate_picker"); this.startTimePicker = bindable.FindByName<TimePicker>("startTime_picker"); this.allDayGrid = bindable.FindByName<Grid>("allDayGrid"); this.allDayLabel = bindable.FindByName<Label>("allDayLabel"); this.switchAllDay = bindable.FindByName<Switch>("switchAllDay"); this.startTimeZonePicker = bindable.FindByName<Picker>("startTimeZonePicker"); this.startTimeZonePicker.SelectedIndex = 0; this.startTimeZonePicker.ItemsSource = TimeZoneCollection.TimeZoneList; this.startTimeZonePicker.SelectedIndexChanged += this.StartTimeZonePicker_SelectedIndexChanged; this.endTimeZonePicker = bindable.FindByName<Picker>("endTimeZonePicker"); this.endTimeZonePicker.SelectedIndex = 0; this.endTimeZonePicker.ItemsSource = TimeZoneCollection.TimeZoneList; this.endTimeZonePicker.SelectedIndexChanged += this.EndTimeZonePicker_SelectedIndexChanged; this.endTimeLabelLayout = bindable.FindByName<Grid>("endTimeLabel_layout"); this.startDateTimePickerLayout = bindable.FindByName<Grid>("StartdateTimePicker_layout"); this.startDatePickerLayout = bindable.FindByName<Grid>("start_datepicker_layout"); this.organizerLayout = bindable.FindByName<Grid>("organizer_layout"); this.startTimePickerLayout = bindable.FindByName<Grid>("start_timepicker_layout"); this.startTimeLabelLayout = bindable.FindByName<Grid>("startTimeLabel_layout"); this.endDateTimePickerLayout = bindable.FindByName<Grid>("EndDateTimePicker_layout"); this.endDatePickerLayout = bindable.FindByName<Grid>("end_datepicker_layout"); this.endDateTimePickerLayout = bindable.FindByName<Grid>("EndDateTimePicker_layout"); this.endTimePickerLayout = bindable.FindByName<Grid>("end_timepicker_layout"); //// Editor Layout Date and time Picker Alignment for UWP if (Device.RuntimePlatform == "UWP" && Device.Idiom == TargetIdiom.Desktop) { this.startDatePicker.HorizontalOptions = LayoutOptions.StartAndExpand; this.startTimePicker.HorizontalOptions = LayoutOptions.StartAndExpand; this.endDatePicker.HorizontalOptions = LayoutOptions.StartAndExpand; this.endTimePicker.HorizontalOptions = LayoutOptions.StartAndExpand; this.startDatePicker.WidthRequest = 450; this.startTimePicker.WidthRequest = 450; this.endDatePicker.WidthRequest = 450; this.endTimePicker.WidthRequest = 450; } if (Device.RuntimePlatform == "WPF") { editorLayout.BackgroundColor = Color.FromHex("#80000000"); editorLayout.Spacing = 0; editorScrollView.BackgroundColor = Color.White; editorScrollView.WidthRequest = 450; editorScrollView.HorizontalOptions = LayoutOptions.Center; editorScrollView.VerticalOptions = LayoutOptions.FillAndExpand; editorScrollView.Padding = new Thickness(20, 20, 20, 0); editorButtonsGrid.BackgroundColor = Color.White; editorButtonsGrid.WidthRequest = 450; editorButtonsGrid.HeightRequest = 70; editorButtonsGrid.HorizontalOptions = LayoutOptions.Center; editorButtonsGrid.Padding = new Thickness(20, 0, 20, 20); cancelButtonGrid.Padding = new Thickness(20, 20, 10, 10); saveButtonGrid.Padding = new Thickness(10, 20, 20, 10); allDayLabel.VerticalOptions = LayoutOptions.Center; } else { allDayGrid.HeightRequest = 40; allDayLabel.HeightRequest = 40; editorButtonsGrid.HeightRequest = 50; editorButtonsGrid.Padding = new Thickness(20, 0, 20, -10); saveButtonGrid.Padding = new Thickness(0, 0, 0, 0); cancelButtonGrid.Padding = new Thickness(0, 0, 0, 0); } this.saveButton.Clicked += this.SaveButton_Clicked; this.cancelButton.Clicked += this.CancelButton_Clicked; this.switchAllDay.Toggled += this.SwitchAllDay_Toggled; } #endregion #region OnDetachingFrom /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(StackLayout bindable) { this.saveButton.Clicked -= this.SaveButton_Clicked; this.cancelButton.Clicked -= this.CancelButton_Clicked; this.switchAllDay.Toggled -= this.SwitchAllDay_Toggled; this.startTimeZonePicker.SelectedIndexChanged -= this.StartTimeZonePicker_SelectedIndexChanged; this.endTimeZonePicker.SelectedIndexChanged -= this.EndTimeZonePicker_SelectedIndexChanged; this.organizerLayout = null; this.editorLayout = null; this.eventNameText = null; this.organizerText = null; this.cancelButton = null; this.saveButton = null; this.saveButtonGrid = null; this.cancelButtonGrid = null; this.editorButtonsGrid = null; this.endDatePicker = null; this.endTimePicker = null; this.startDatePicker = null; this.startTimePicker = null; this.allDayGrid = null; this.allDayLabel = null; this.switchAllDay = null; this.endTimeLabelLayout = null; this.startDateTimePickerLayout = null; this.startDatePickerLayout = null; this.startTimePickerLayout = null; this.startTimeLabelLayout = null; this.endDateTimePickerLayout = null; this.endDatePickerLayout = null; this.endDateTimePickerLayout = null; this.endTimePickerLayout = null; } #endregion /// <summary> /// Method for time zone. /// </summary> /// <param name="timeZone">time zone</param> /// <returns>return the time zone</returns> private int GetTimeZoneIndex(string timeZone) { for (int i = 0; i < TimeZoneCollection.TimeZoneList.Count; i++) { if (timeZone.Equals(TimeZoneCollection.TimeZoneList[i])) { return i; } } return 0; } #endregion #region Start TimeZone Picker_Selected /// <summary> /// method for selecting start time zone /// </summary> /// <param name="sender">return the object</param> /// <param name="e"> Event Args</param> private void StartTimeZonePicker_SelectedIndexChanged(object sender, EventArgs e) { if ((sender as Picker).SelectedItem as string == "Default") { this.startTimeZone = string.Empty; } else { this.startTimeZone = (sender as Picker).SelectedItem as string; } } #endregion #region End TimeZone Picker_Selected /// <summary> /// Method for selecting end time zone. /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void EndTimeZonePicker_SelectedIndexChanged(object sender, EventArgs e) { if ((sender as Picker).SelectedItem as string == "Default") { this.endTimeZone = string.Empty; } else { this.endTimeZone = (sender as Picker).SelectedItem as string; } } #endregion /// <summary> /// Method for all day switch toggled. /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> #region SwitchAllDay_Toggled private void SwitchAllDay_Toggled(object sender, ToggledEventArgs e) { if ((sender as Switch).IsToggled) { this.startTimePicker.Time = new TimeSpan(12, 0, 0); this.startTimePicker.IsEnabled = false; this.endTimePicker.Time = new TimeSpan(12, 0, 0); this.endTimePicker.IsEnabled = false; this.startTimeZonePicker.IsEnabled = false; this.endTimeZonePicker.IsEnabled = false; } else { this.startTimePicker.IsEnabled = true; this.endTimePicker.IsEnabled = true; (sender as Switch).IsToggled = false; this.startTimeZonePicker.IsEnabled = true; this.endTimeZonePicker.IsEnabled = true; } } #endregion #region CancelButton_Clicked /// <summary> /// Method for cancel. /// </summary> /// <param name="sender">Return the object</param> /// <param name="e">Event Args</param> private void CancelButton_Clicked(object sender, EventArgs e) { ScheduleAppointmentModifiedEventArgs args = new ScheduleAppointmentModifiedEventArgs(); args.Appointment = null; args.IsModified = false; (this.editorLayout.BindingContext as EditorLayoutViewModel).OnAppointmentModified(args); this.editorLayout.IsVisible = false; } #endregion #region SaveButton_Clicked /// <summary> /// Method for save button. /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void SaveButton_Clicked(object sender, EventArgs e) { var endDate = this.endDatePicker.Date; var startDate = this.startDatePicker.Date; var endTime = this.endTimePicker.Time; var startTime = this.startTimePicker.Time; if (endDate < startDate) { Application.Current.MainPage.DisplayAlert(" ", "End time should be greater than start time", "OK"); } else if (endDate == startDate) { if (endTime < startTime) { Application.Current.MainPage.DisplayAlert(" ", "End time should be greater than start time", "OK"); } else { this.AppointmentDetails(); this.editorLayout.IsVisible = false; } } else { this.AppointmentDetails(); this.editorLayout.IsVisible = false; } } #endregion #region AppointmentDetails /// <summary> /// Method for appointment details. /// </summary> private void AppointmentDetails() { if (this.selectedAppointment == null) { this.selectedAppointment = new Meeting(); this.selectedAppointment.Color = Color.FromHex("#5EDAF2"); } if (this.eventNameText.Text != null) { this.selectedAppointment.EventName = this.eventNameText.Text.ToString(); if (string.IsNullOrEmpty(this.selectedAppointment.EventName)) { this.selectedAppointment.EventName = "Untitled"; } } if (this.organizerText.Text != null) { this.selectedAppointment.Organizer = this.organizerText.Text.ToString(); } this.selectedAppointment.From = this.startDatePicker.Date.Add(this.startTimePicker.Time); this.selectedAppointment.To = this.endDatePicker.Date.Add(this.endTimePicker.Time); this.selectedAppointment.IsAllDay = this.switchAllDay.IsToggled; this.selectedAppointment.StartTimeZone = this.startTimeZone; this.selectedAppointment.EndTimeZone = this.endTimeZone; ScheduleAppointmentModifiedEventArgs args = new ScheduleAppointmentModifiedEventArgs(); args.Appointment = this.selectedAppointment; args.IsModified = true; (this.editorLayout.BindingContext as EditorLayoutViewModel).OnAppointmentModified(args); } #endregion #region UpdateEditor /// <summary> /// Method for update editor. /// </summary> private void UpdateEditor() { if (this.selectedAppointment != null) { this.eventNameText.Text = this.selectedAppointment.EventName.ToString(); this.organizerText.Text = this.selectedAppointment.Organizer; this.startDatePicker.Date = this.selectedAppointment.From; this.endDatePicker.Date = this.selectedAppointment.To; this.startTimeZonePicker.SelectedIndex = this.GetTimeZoneIndex(this.selectedAppointment.StartTimeZone); this.endTimeZonePicker.SelectedIndex = this.GetTimeZoneIndex(this.selectedAppointment.EndTimeZone); if (!this.selectedAppointment.IsAllDay) { this.startTimePicker.Time = new TimeSpan(this.selectedAppointment.From.Hour, this.selectedAppointment.From.Minute, this.selectedAppointment.From.Second); this.endTimePicker.Time = new TimeSpan(this.selectedAppointment.To.Hour, this.selectedAppointment.To.Minute, this.selectedAppointment.To.Second); this.switchAllDay.IsToggled = false; } else { this.startTimePicker.Time = new TimeSpan(12, 0, 0); this.startTimePicker.IsEnabled = false; this.endTimePicker.Time = new TimeSpan(12, 0, 0); this.endTimePicker.IsEnabled = false; this.switchAllDay.IsToggled = true; } } else { this.eventNameText.Text = ""; this.organizerText.Text = ""; this.switchAllDay.IsToggled = false; this.startDatePicker.Date = this.selectedDate; this.startTimePicker.Time = new TimeSpan(this.selectedDate.Hour, this.selectedDate.Minute, this.selectedDate.Second); this.endDatePicker.Date = this.selectedDate; if (this.selectedDate.Hour == 23) { this.endTimePicker.Time = new TimeSpan(this.selectedDate.Hour, this.selectedDate.Minute + 59, this.selectedDate.Second + 59); } else { this.endTimePicker.Time = new TimeSpan(this.selectedDate.Hour + 1, this.selectedDate.Minute, this.selectedDate.Second); } this.startTimeZonePicker.SelectedIndex = 0; this.endTimeZonePicker.SelectedIndex = 0; } } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/TreeMap/GettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfTreeMap.iOS; using System.Collections.Generic; #if __UNIFIED__ using UIKit; using CoreGraphics; using Foundation; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class GettingStarted : SampleView { #region Fields SFTreeMap tree ; UILabel label; UIView view; #endregion public GettingStarted () { // TreeMap Initialization view = new UIView(); label = new UILabel(); tree = new SFTreeMap (); tree.WeightValuePath = (NSString)"Population"; tree.ColorValuePath = (NSString)"Growth"; tree.Levels.Add (new SFTreeMapFlatLevel (){ GroupPath = (NSString)"Continent", HeaderStyle = new SFStyle(){Color = UIColor.DarkGray}, HeaderHeight = 22, ShowHeader =true }); // Leaf Item Settings tree.LeafItemSettings = new SFLeafItemSetting (); tree.LeafItemSettings.LabelStyle = new SFStyle () { Font = UIFont.SystemFontOfSize (12), Color = UIColor.White }; tree.LeafItemSettings.LabelPath = (NSString)"Region"; tree.LeafItemSettings.ShowLabels = true; tree.LeafItemSettings.Gap = 2; tree.LeafItemSettings.BorderColor=UIColor.Gray; tree.LeafItemSettings.BorderWidth = 1; //Color Mappings NSMutableArray ranges = new NSMutableArray (); ranges.Add (new SFRange () { LegendLabel = (NSString)"1 % Growth", From = 0, To = 1, Color = UIColor.FromRGB (0x77, 0xD8, 0xD8) }); ranges.Add (new SFRange () { LegendLabel = (NSString)"2 % Growth", From = 0, To = 2, Color = UIColor.FromRGB (0xAE, 0xD9, 0x60) }); ranges.Add (new SFRange () { LegendLabel = (NSString)"3 % Growth", From = 0, To = 3, Color = UIColor.FromRGB (0xFF, 0xAF, 0x51) }); ranges.Add (new SFRange () { LegendLabel = (NSString)"4 % Growth", From = 0, To = 4, Color = UIColor.FromRGB (0xF3, 0xD2, 0x40) }); tree.LeafItemColorMapping = new SFRangeColorMapping () { Ranges = ranges }; // Legend Settings CGSize legendSize = new CGSize (this.Frame.Size.Width, 60); CGSize iconSize = new CGSize (17, 17); UIColor legendColor = UIColor.Gray; tree.LegendSettings = new SFLegendSetting () { LabelStyle = new SFStyle () { Font = UIFont.SystemFontOfSize (12), Color = legendColor }, IconSize = iconSize, ShowLegend = true, Size = legendSize }; GetPopulationData (); tree.DataSource = PopulationDetails; CustomLabelTooltipSetting tooltipSetting = new CustomLabelTooltipSetting(); tree.ShowTooltip = true; tree.TooltipSettings = tooltipSetting; AddSubview (view); } public override void LayoutSubviews() { // Popup Window label.Text = "Getting Started"; label.Frame = new CGRect(0, 0, 300, 30); base.LayoutSubviews(); view.Frame = new CGRect(0, 0, Frame.Size.Width, Frame.Size.Height); tree.Frame = new CGRect(0, 0, Frame.Size.Width - 6, Frame.Size.Height); view.AddSubview(tree); label.Frame = new CGRect(0, 0, Frame.Size.Width, 40); tree.LegendSettings.Size = new CGSize(this.Frame.Size.Width, 60); SetNeedsDisplay(); } void GetPopulationData() { NSMutableArray array = new NSMutableArray(); array.Add(getDictionary("Asia", "Indonesia", 3, 237641326)); array.Add(getDictionary("Asia", "Russia", 2, 152518015)); array.Add(getDictionary("North America", "United States", 4, 315645000)); array.Add(getDictionary("North America", "Mexico", 2, 112336538)); array.Add(getDictionary("North America", "Canada", 1, 35056064)); array.Add(getDictionary("South America", "Colombia", 1, 47000000)); array.Add(getDictionary("South America", "Brazil", 3, 193946886)); array.Add(getDictionary("Africa", "Nigeria", 2, 170901000)); array.Add(getDictionary("Africa", "Egypt", 1, 83661000)); array.Add(getDictionary("Europe", "Germany", 1, 81993000)); array.Add(getDictionary("Europe", "France", 1, 65605000)); array.Add(getDictionary("Europe", "UK", 1, 63181775)); PopulationDetails = array; } NSDictionary getDictionary(string continent,string region,double growth,double population) { object[] objects= new object[4]; object[] keys=new object[4]; keys.SetValue ("Continent", 0); keys.SetValue ("Region", 1); keys.SetValue ("Growth", 2); keys.SetValue ("Population", 3); objects.SetValue ((NSString)continent, 0); objects.SetValue ((NSString)region, 1); objects.SetValue (growth, 2); objects.SetValue (population, 3); return NSDictionary.FromObjectsAndKeys (objects, keys); } public NSMutableArray PopulationDetails { get; set; } } public class CustomLabelTooltipSetting : TooltipSetting { public CustomLabelTooltipSetting() { } public override UIView GetView(object shapeData) { NSArray array = (NSArray)shapeData; NSDictionary dic = new NSDictionary(); for (nuint i = 0; i < array.Count; i++) { dic = array.GetItem<NSDictionary>(i); } UIView view = new UIView(); NSString topText = (NSString)(dic["Region"]); NSString bottomText = (NSString)(dic["Growth"].ToString() + "%"); UILabel topLabel = new UILabel(); topLabel.Text = topText; topLabel.Font = UIFont.SystemFontOfSize(12); topLabel.TextColor = UIColor.White; topLabel.TextAlignment = UITextAlignment.Center; UILabel bottomLabel = new UILabel(); bottomLabel.Text = bottomText; bottomLabel.Font = UIFont.SystemFontOfSize(12); bottomLabel.TextColor = UIColor.White; bottomLabel.TextAlignment = UITextAlignment.Center; view.AddSubview(topLabel); view.AddSubview(bottomLabel); CGSize expectedLabelSize1 = topText.GetSizeUsingAttributes(new UIStringAttributes() { Font = topLabel.Font }); CGSize expectedLabelSize2 = bottomText.GetSizeUsingAttributes(new UIStringAttributes() { Font = bottomLabel.Font }); view.Frame = new CGRect(0.0f, 0.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width), 35.0f); topLabel.Frame = new CGRect(0.0f, 0.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width), 15.0f); bottomLabel.Frame = new CGRect(0.0f, 20.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width), 15.0f); return view; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/StocksViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; using System.Timers; namespace SampleBrowser { public class StocksViewModel : INotifyPropertyChanged, IDisposable { #region Members ObservableCollection<StockData> data; Random r = new Random(123345345); internal Timer timer; private bool enableTimer = false; //private DelegateCommand<object> btonClick; private double timerValue; private string buttonContent; private int noOfUpdates = 500; List<string> StockSymbols = new List<string>(); string[] accounts = new string[] { "American Funds", "College Savings", "Day Trading", "Retirement Savings", "Mountain Ranges", "Fidelity Funds", "Mortages", "Housing Loans" }; string[] product = new string[]{ "Crab", "Bag", "Cashew", "Syrup", "Meat", "Lax", "Filo" }; #endregion /// <summary> /// Gets the stocks. /// </summary> /// <value>The stocks.</value> public ObservableCollection<StockData> Stocks { get { return this.data; } } #region Constructor /// <summary> /// Initializes a new instance of the <see cref="StocksViewModel"/> class. /// </summary> public StocksViewModel() { this.data = new ObservableCollection<StockData>(); this.AddRows(2000); this.timer = new Timer(); this.ResetRefreshFrequency(2500); timer.Interval = (double)TimeSpan.FromMilliseconds(200).Milliseconds; ButtonContent = "Start Timer"; timer.Elapsed += timer_Tick; ButtonClicked(); } #endregion #region Timer and updating code /// <summary> /// Sets the interval. /// </summary> /// <param name="time">The time.</param> public void SetInterval(TimeSpan time) { this.timer.Interval = Convert.ToDouble(time); } /// <summary> /// Starts the timer. /// </summary> public void StartTimer() { if (!this.timer.Enabled) { this.timer.Start(); this.ButtonContent = "Stop Timer"; } } /// <summary> /// Gets or sets the timer value. /// </summary> /// <value>The timer value.</value> public double TimeSpanValue { get { return timerValue; } set { timerValue = value; this.timer.Interval = Convert.ToDouble(TimeSpan.FromMilliseconds(timerValue)); RaisePropertyChanged("TimeSpanValue"); } } /// <summary> /// Gets or sets the button contnt. /// </summary> /// <value>The button contnt.</value> public string ButtonContent { get { return buttonContent; } set { buttonContent = value; RaisePropertyChanged("ButtonContent"); } } /// <summary> /// Gets the bton click. /// </summary> /// <value>The bton click.</value> // public DelegateCommand<object> BtonClick // { // get { return btonClick; } // } /// <summary> /// Determines whether this instance [can button click]. /// </summary> /// <returns> /// <c>true</c> if this instance [can button click]; otherwise, <c>false</c>. /// </returns> bool CanButtonClick(object param) { return true; } /// <summary> /// Buttons the clicked. /// </summary> /// <param name="param">The param.</param> /// public void ButtonClicked() { if (ButtonContent.Equals("Start Timer")) { this.EnableTimer = true; this.StartTimer(); ButtonContent = "Stop Timer"; } else { this.EnableTimer = false; this.StopTimer(); ButtonContent = "Start Timer"; } } /// <summary> /// Stops the timer. /// </summary> public void StopTimer() { this.timer.Stop(); } /// <summary> /// Handles the Tick event of the timer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void timer_Tick(object sender, object e) { int startTime = DateTime.Now.Millisecond; noOfUpdates = 100; ChangeRows(noOfUpdates); } /// <summary> /// Gets or sets a value indicating whether [enable timer]. /// </summary> /// <value><c>true</c> if [enable timer]; otherwise, <c>false</c>.</value> public bool EnableTimer { get { return this.enableTimer; } set { this.enableTimer = value; } } /// <summary> /// Adds the rows. /// </summary> /// <param name="count">The count.</param> private void AddRows(int count) { for (int i = 0; i < count; ++i) { var newRec = new StockData(); newRec.Symbol = ChangeSymbol(); newRec.Account = ChangeAccount(i); newRec.Open = Math.Round(r.NextDouble() * 30, 2); newRec.LastTrade = Math.Round((1 + r.NextDouble() * 50)); double d = r.NextDouble(); if (d < .5) newRec.StockChange = Math.Round(d, 2); else newRec.StockChange = Math.Round(d, 2) * -1; newRec.PreviousClose = Math.Round(r.NextDouble() * 30, 2); newRec.Volume = r.Next(); newRec.Product = ChangeProduct(i); data.Add(newRec); } } /// <summary> /// Changes the symbol. /// </summary> /// <returns></returns> private String ChangeSymbol() { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; do { builder = new StringBuilder(); for (int i = 0; i < 4; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } } while (StockSymbols.Contains(builder.ToString())); StockSymbols.Add(builder.ToString()); return builder.ToString(); } /// <summary> /// Changes the account. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> private String ChangeAccount(int index) { return accounts[index % accounts.Length]; } /// <summary> /// Changes the Product. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> private String ChangeProduct(int index) { return product[index % product.Length]; } /// <summary> /// Resets the refresh frequency. /// </summary> /// <param name="changesPerTick">The changes per tick.</param> public void ResetRefreshFrequency(int changesPerTick) { if (this.timer == null) { return; } if (!this.noOfUpdates.Equals(changesPerTick)) { this.StopTimer(); this.noOfUpdates = changesPerTick; if (enableTimer) this.StartTimer(); } } public object SelectedItem { get { return noOfUpdates; } set { noOfUpdates = 2; RaisePropertyChanged("SelectedItem"); } } public List<int> ComboCollection { get { return new List<int> { 500, 5000, 50000, 500000 }; } } /// <summary> /// Changes the rows. /// </summary> /// <param name="count">The count.</param> private void ChangeRows(int count) { if (data.Count < count) count = data.Count; for (int i = 0; i < count; ++i) { int recNo = r.Next(data.Count); StockData recRow = data[recNo]; data[recNo].LastTrade = Math.Round((1 + r.NextDouble() * 50)); double d = r.NextDouble(); if (d < .5) { data[recNo].StockChange = Math.Round(d, 2); } else { data[recNo].StockChange = Math.Round(d, 2) * -1; } data[recNo].Open = Math.Round(r.NextDouble() * 50, 2); data[recNo].PreviousClose = Math.Round(r.NextDouble() * 30, 2); data[recNo].Volume = r.Next(); } } #endregion public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String Name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(Name)); } #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (this.timer != null) { this.timer.Elapsed -= timer_Tick; this.StopTimer(); } } #endregion } } <file_sep>/Forms/DataForm/DataForm/Samples/GettingStarted/ViewModel/RecipientInfoViewModel.cs #region Copyright // <copyright file="RecipientInfoViewModel.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; /// <summary> /// Represents the view model of data form getting started sample. /// </summary> [Preserve(AllMembers = true)] public class RecipientInfoViewModel : INotifyPropertyChanged { /// <summary> /// Represents the recipient information. /// </summary> private RecipientInfo recipientInfo; /// <summary> /// Represents a value indicating whether visible or not. /// </summary> private bool isVisible; /// <summary> /// Initializes a new instance of the <see cref="RecipientInfoViewModel"/> class. /// </summary> public RecipientInfoViewModel() { this.recipientInfo = new RecipientInfo(); this.isVisible = true; this.CommitCommand = new Command<object>(this.OnCommit); } /// <summary> /// Represents the method that will handle when a property is changed on a component. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the recipient information. /// </summary> public RecipientInfo RecipientInfo { get { return this.recipientInfo; } set { this.recipientInfo = value; } } /// <summary> /// Gets or sets a value indicating whether visible or not. /// </summary> public bool IsVisible { get { return this.isVisible; } set { this.isVisible = value; this.OnPropertyChanged("IsVisible"); } } /// <summary> /// Gets or sets an ICommand implementation wrapping a commit action. /// </summary> public Command<object> CommitCommand { get; set; } /// <summary> /// Commits the value of the specific editor to corresponding property in the business object. /// </summary> /// <param name="dataForm">The corresponding DataForm.</param> private void OnCommit(object dataForm) { var dataFormLayout = dataForm as Syncfusion.XForms.DataForm.SfDataForm; var isValid = dataFormLayout.Validate(); dataFormLayout.Commit(); if (!isValid) { App.Current.MainPage.DisplayAlert("Alert", "Please enter valid details", "Ok"); return; } App.Current.MainPage.DisplayAlert("Alert", "Money Transferred", "Ok"); dataFormLayout.IsReadOnly = true; this.IsVisible = false; } /// <summary> /// Occurs when property value changes. /// </summary> /// <param name="propertyName">The corresponding name of the property.</param> private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } } <file_sep>/Forms/RichTextEditor/RichTextEditor.iOS/RTECustomEntryRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using SampleBrowser.SfRichTextEditor; using SampleBrowser.SfRichTextEditor.iOS; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(RTECustomEntry), typeof(RTECustomEntryRenderer))] namespace SampleBrowser.SfRichTextEditor.iOS { public class RTECustomEntryRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { Control.BorderStyle = UITextBorderStyle.None; Control.Layer.CornerRadius = 10; Control.TextColor = UIColor.FromRGB(89, 89, 89); } } } }<file_sep>/Android/SampleBrowser/Samples/TreeMap/FlatCollection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Org.Json; #endregion using System; using Android.Views; using Android.Graphics; using Com.Syncfusion.Treemap; using System.Collections.Generic; using Android.Widget; using Com.Syncfusion.Treemap.Enums; using Android.Content; using Range = Com.Syncfusion.Treemap.Range; namespace SampleBrowser { public class FlatCollection : SamplePage { public FlatCollection() { } SfTreeMap tree; public override View GetSampleContent(Context context) { tree = new SfTreeMap(context); tree.WeightValuePath = "Population"; tree.ColorValuePath = "Growth"; tree.HighlightOnSelection = false; var margin = context.Resources.DisplayMetrics.Density * 20; float density = context.Resources.DisplayMetrics.Density; //LeafItemSetting tree.LeafItemSettings = new LeafItemSetting() { ShowLabels = true, Gap = 5, LabelPath = "Region", StrokeColor = Color.White, StrokeWidth = 2 }; tree.LeafItemSettings.LabelStyle = new Style() { Margin = new Margin(margin / 2, margin, 0, 0), TextSize = 18, TextColor = Color.White }; TreeMapFlatLevel level = new TreeMapFlatLevel { ShowHeader = true, GroupPath = "Continent", GroupStrokeColor = Color.Gray, GroupStrokeWidth = 1, GroupPadding = 5, HeaderHeight = 25 }; level.HeaderStyle = new Style() { TextColor = Color.Gray, TextSize = 16 }; tree.Levels.Add(level); //RangeColorMapping List<Range> ranges = new List<Range>(); ranges.Add(new Range() { LegendLabel = "1 % Growth", From = 0, To = 1, Color = Color.ParseColor("#77D8D8") }); ranges.Add(new Range() { LegendLabel = "2 % Growth", From = 0, To = 2, Color = Color.ParseColor("#AED960") }); ranges.Add(new Range() { LegendLabel = "3 % Growth", From = 0, To = 3, Color = Color.ParseColor("#FFAF51") }); ranges.Add(new Range() { LegendLabel = "4 % Growth", From = 0, To = 4, Color = Color.ParseColor("#F3D240") }); tree.LeafItemColorMapping = new RangeColorMapping() { Ranges = ranges }; //LegendSetting Size legendSize = new Size(300, 100); Size iconSize = new Size(12, 12); Color legendColor = Color.Gray; tree.LegendSettings = new LegendSetting() { LabelStyle = new Style() { TextSize = 12, TextColor = legendColor }, IconSize = iconSize, ShowLegend = true, LegendSize = legendSize }; tree.ShowTooltip = true; CustomTooltipSetting tooltip = new CustomTooltipSetting(context); tree.TooltipSettings = tooltip; tree.DataSource = GetDataSource(); return tree; } JSONArray GetDataSource() { JSONArray array = new JSONArray(); array.Put(getJsonObject("Asia", "Indonesia", 3, 237641326)); array.Put(getJsonObject("Asia", "Russia", 2, 152518015)); array.Put(getJsonObject("North America", "United States", 4, 315645000)); array.Put(getJsonObject("North America", "Mexico", 2, 112336538)); array.Put(getJsonObject("North America", "Canada", 1, 35056064)); array.Put(getJsonObject("South America", "Colombia", 1, 47000000)); array.Put(getJsonObject("South America", "Brazil", 3, 193946886)); array.Put(getJsonObject("Africa", "Nigeria", 2, 170901000)); array.Put(getJsonObject("Africa", "Egypt", 1, 83661000)); array.Put(getJsonObject("Europe", "Germany", 1, 81993000)); array.Put(getJsonObject("Europe", "France", 1, 65605000)); array.Put(getJsonObject("Europe", "UK", 1, 63181775)); return array; } JSONObject getJsonObject(String continent, String region, double growth, double population) { JSONObject obj = new JSONObject(); obj.Put("Continent", continent); obj.Put("Region", region); obj.Put("Growth", growth); obj.Put("Population", population); return obj; } } public class CustomTooltipSetting : TooltipSetting { Context context; public CustomTooltipSetting(Context con) { context = con; } public override View GetView(object data, Context context) { LinearLayout layout = new LinearLayout(context); LinearLayout.LayoutParams linearlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layout.Orientation = Orientation.Vertical; layout.LayoutParameters = linearlayoutParams; layout.SetGravity(GravityFlags.CenterHorizontal); TextView topLabel = new TextView(context); topLabel.Text = ((JSONObject)data).GetString("Region"); topLabel.TextSize = 12; topLabel.SetTextColor(Color.ParseColor("#FFFFFF")); topLabel.Gravity = GravityFlags.CenterHorizontal; TextView SplitLine = new TextView(context); SplitLine.Text = "-------"; SplitLine.SetTextColor(Color.Gray); SplitLine.Gravity = GravityFlags.CenterHorizontal; TextView bottoLabel = new TextView(context); var growth = ((JSONObject)data).GetDouble("Growth"); bottoLabel.Text = ((int)growth).ToString() + "%"; bottoLabel.TextSize = 12; bottoLabel.SetTextColor(Color.ParseColor("#FFFFFF")); bottoLabel.Gravity = GravityFlags.CenterHorizontal; layout.AddView(topLabel); layout.AddView(SplitLine); layout.AddView(bottoLabel); return layout; } } } <file_sep>/Android/SampleBrowser/Samples/ProgressBar/Circular.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser { using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Syncfusion.Android.ProgressBar; public class Circular : SamplePage { private Context context; private LinearLayout.LayoutParams layoutParams; private SfCircularProgressBar segmentedFillingStyle; private SfCircularProgressBar circularCustomContentProgressBar; private SfCircularProgressBar trackInsideStyle; private SfCircularProgressBar videoPlayerProgressBar; private ImageButton playButton, pauseButton; public override View GetSampleContent(Context ctx) { this.context = ctx; this.layoutParams = new LinearLayout.LayoutParams( this.context.Resources.DisplayMetrics.WidthPixels / 3, this.context.Resources.DisplayMetrics.HeightPixels / 5); LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; LinearLayout row1 = new LinearLayout(this.context); LinearLayout row2 = new LinearLayout(this.context); LinearLayout row3 = new LinearLayout(this.context); LinearLayout row4 = new LinearLayout(this.context); LinearLayout row5 = new LinearLayout(this.context); LinearLayout row6 = new LinearLayout(this.context); LinearLayout row7 = new LinearLayout(this.context); linearLayout.AddView(this.GetTextView("Determinate and indeterminate")); linearLayout.AddView(row1); linearLayout.AddView(this.GetTextView("Custom content")); linearLayout.AddView(row2); linearLayout.AddView(this.GetTextView("Radius customization")); linearLayout.AddView(row3); linearLayout.AddView(row4); linearLayout.AddView(this.GetTextView("Segment")); linearLayout.AddView(row5); linearLayout.AddView(this.GetTextView("Custom angle")); linearLayout.AddView(row6); linearLayout.AddView(this.GetTextView("Range colors")); linearLayout.AddView(row7); row1.AddView(this.GetCircularDeterminate()); row1.AddView(this.GetCircularIndeterminate()); row2.AddView(this.GetCircularCustomContent()); row2.AddView(this.GetCircularVideoPlayer()); row3.AddView(this.GetCircularTrackOutside()); row3.AddView(this.GetCircularFilledIndicator()); row3.AddView(this.GetCircularTrackInside()); row4.AddView(this.GetCircularThinTrackStyle()); row5.AddView(this.GetCircularSegment()); row5.AddView(this.GetCircularSegmentPadding()); row5.AddView(this.GetCircularSegmentFillStyle()); row6.AddView(this.GetCircularAngleCustomization()); row7.AddView(this.GetCircularRangeColors()); ScrollView scrollView = new ScrollView(this.context); scrollView.AddView(linearLayout); return scrollView; } private View GetTextView(string content) { TextView textView = new TextView(this.context) { Text = content }; textView.SetPadding(15, 30, 0, 0); textView.TextSize = 15; return textView; } private View GetCustomContentTextView(double content) { string custContent = content + "%"; TextView textView = new TextView(this.context) { Text = custContent, TextSize = 20, TextAlignment = TextAlignment.Center, Gravity = GravityFlags.Center, }; textView.SetTextColor(Color.ParseColor("#007cee")); return textView; } private View GetCircularDeterminate() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(new SfCircularProgressBar(this.context) { Progress = 75, ShowProgressValue = false, LayoutParameters = this.layoutParams }); return linearLayout; } private View GetCircularIndeterminate() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(new SfCircularProgressBar(this.context) { IsIndeterminate = true, LayoutParameters = this.layoutParams }); return linearLayout; } private View GetCircularCustomContent() { #pragma warning disable CS4014 LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; this.circularCustomContentProgressBar = new SfCircularProgressBar(this.context) { Progress = 75, AnimationDuration = 0, LayoutParameters = this.layoutParams }; this.SetCustomContentProgress(); linearLayout.AddView(this.circularCustomContentProgressBar); return linearLayout; #pragma warning restore CS4014 } private View GetCircularVideoPlayer() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; this.videoPlayerProgressBar = new SfCircularProgressBar(this.context) { Progress = 100, ShowProgressValue = true, TrackInnerRadius = 0f, IndicatorOuterRadius = 0.7f, IndicatorInnerRadius = 0.65f, AnimationDuration = 10000, LayoutParameters = this.layoutParams }; GridLayout.LayoutParams gridLayoutParams = new GridLayout.LayoutParams { RowSpec = GridLayout.InvokeSpec(0), ColumnSpec = GridLayout.InvokeSpec(0) }; GridLayout custContentLayout = new GridLayout(this.context); this.playButton = new ImageButton(this.context) { Visibility = ViewStates.Invisible }; this.playButton.SetImageResource(Resource.Drawable.SfProgressPlay); this.playButton.SetBackgroundColor(Color.ParseColor("#00FFFFFF")); this.playButton.Click += this.PlayButton_Click; custContentLayout.AddView(this.playButton, gridLayoutParams); this.pauseButton = new ImageButton(this.context); this.pauseButton.SetImageResource(Resource.Drawable.SfProgressPause); this.pauseButton.SetBackgroundColor(Color.ParseColor("#00FFFFFF")); this.pauseButton.Click += this.PauseButton_Click; custContentLayout.AddView(this.pauseButton, gridLayoutParams); this.videoPlayerProgressBar.Content = custContentLayout; this.videoPlayerProgressBar.ValueChanged += this.ProgressBar_ValueChanged100; linearLayout.AddView(this.videoPlayerProgressBar); return linearLayout; } private void PauseButton_Click(object sender, EventArgs e) { this.videoPlayerProgressBar.Progress = (double)GetInternalPropertyValue(typeof(ProgressBarBase), this.videoPlayerProgressBar, "ActualProgress"); this.playButton.Visibility = ViewStates.Visible; this.pauseButton.Visibility = ViewStates.Invisible; } private void PlayButton_Click(object sender, EventArgs e) { this.videoPlayerProgressBar.Progress = 100; this.pauseButton.Visibility = ViewStates.Visible; this.playButton.Visibility = ViewStates.Invisible; } public static object GetInternalPropertyValue(Type type, object obj, string name) { var properties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance); return properties.Where(propertyInfo => propertyInfo.Name.Equals(name)) .Select(propertyInfo => propertyInfo.GetValue(obj)) .FirstOrDefault(); } private View GetCircularTrackOutside() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; SfCircularProgressBar progressBar = new SfCircularProgressBar(this.context) { Progress = 100, IndicatorOuterRadius = 0.7f, IndicatorInnerRadius = 0.65f, ShowProgressValue = false, AnimationDuration = 10000, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged100; linearLayout.AddView(progressBar); return linearLayout; } private View GetCircularFilledIndicator() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; SfCircularProgressBar progressBar = new SfCircularProgressBar(this.context) { Progress = 100, IndicatorOuterRadius = 0.7f, IndicatorInnerRadius = 0f, ShowProgressValue = false, AnimationDuration = 10000, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged100; linearLayout.AddView(progressBar); return linearLayout; } private View GetCircularTrackInside() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; this.trackInsideStyle = new SfCircularProgressBar(this.context) { TrackOuterRadius = 0.7f, TrackInnerRadius = 0f, ShowProgressValue = true, AnimationDuration = 0, LayoutParameters = this.layoutParams }; this.SetTrackInsideStyleProgress(); linearLayout.AddView(this.trackInsideStyle); return linearLayout; } private async void SetTrackInsideStyleProgress() { double progress = 0; while (progress < 100) { this.trackInsideStyle.Progress = progress += 0.25; LinearLayout custContentLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; custContentLayout.AddView(this.GetCustomContentTextView((int)progress)); this.trackInsideStyle.Content = custContentLayout; await Task.Delay(50); } this.trackInsideStyle.Progress = 0; this.SetTrackInsideStyleProgress(); } private View GetCircularThinTrackStyle() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; SfCircularProgressBar progressBar = new SfCircularProgressBar(this.context) { Progress = 100, IndicatorOuterRadius = 0.75f, IndicatorInnerRadius = 0.6f, TrackOuterRadius = 0.7f, TrackInnerRadius = 0.65f, ShowProgressValue = false, AnimationDuration = 10000, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged100; linearLayout.AddView(progressBar); return linearLayout; } private View GetCircularSegment() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; SfCircularProgressBar progressBar = new SfCircularProgressBar(this.context) { Progress = 75, ShowProgressValue = false, SegmentCount = 4, AnimationDuration = 10000, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged75; linearLayout.AddView(progressBar); return linearLayout; } private View GetCircularSegmentPadding() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; SfCircularProgressBar progressBar = new SfCircularProgressBar(this.context) { Progress = 75, ShowProgressValue = false, TrackInnerRadius = 0.6f, IndicatorInnerRadius = 0.65f, IndicatorOuterRadius = 0.7f, SegmentCount = 4, AnimationDuration = 10000, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged75; linearLayout.AddView(progressBar); return linearLayout; } private View GetCircularSegmentFillStyle() { #pragma warning disable CS4014 LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; this.segmentedFillingStyle = new SfCircularProgressBar(this.context) { ShowProgressValue = false, SegmentCount = 20, AnimationDuration = 0, LayoutParameters = this.layoutParams }; this.SetSegmentedFillingStyleProgress(); linearLayout.AddView(this.segmentedFillingStyle); return linearLayout; #pragma warning restore CS4014 } private View GetCircularAngleCustomization() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; SfCircularProgressBar progressBar = new SfCircularProgressBar(this.context) { Progress = 100, StartAngle = 130, EndAngle = 410, ShowProgressValue = false, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged100; linearLayout.AddView(progressBar); return linearLayout; } private View GetCircularRangeColors() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; RangeColorCollection rangeColorCollection = new RangeColorCollection { new RangeColor { Color = Color.ParseColor("#36BBE1"), Start = 0, End = 25 }, new RangeColor { Color = Color.ParseColor("#9AEDE1"), Start = 25, End = 50 }, new RangeColor { Color = Color.ParseColor("#FFDC28"), Start = 50, End = 75 }, new RangeColor { Color = Color.ParseColor("#E15E0D"), Start = 75, End = 100 } }; SfCircularProgressBar progressBar = new SfCircularProgressBar(this.context) { Progress = 100, ShowProgressValue = false, RangeColors = rangeColorCollection, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged100; linearLayout.AddView(progressBar); return linearLayout; } private async void ProgressBar_ValueChanged100(object sender, ProgressValueEventArgs e) { SfCircularProgressBar progressbar = sender as SfCircularProgressBar; if (e.Progress.Equals(100)) { progressbar.AnimationDuration = 0; progressbar.Progress = 0; } if (e.Progress.Equals(0)) { progressbar.AnimationDuration = 10000; await Task.Delay(100); progressbar.Progress = 100; } } private async void ProgressBar_ValueChanged75(object sender, ProgressValueEventArgs e) { SfCircularProgressBar progressbar = sender as SfCircularProgressBar; if (e.Progress.Equals(75)) { progressbar.AnimationDuration = 0; await Task.Delay(50); progressbar.Progress = 0; } if (e.Progress.Equals(0)) { progressbar.AnimationDuration = 10000; await Task.Delay(100); progressbar.Progress = 75; } } private async Task SetSegmentedFillingStyleProgress() { double progress = 0; this.segmentedFillingStyle.Progress = 0; await Task.Delay(300); while (progress < 100) { this.segmentedFillingStyle.Progress = progress += 5; await Task.Delay(300); } await this.SetSegmentedFillingStyleProgress(); } private async Task SetCustomContentProgress() { double progress = 0; while (progress < 75) { this.circularCustomContentProgressBar.Progress = progress += 1; LinearLayout custContentLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; custContentLayout.AddView(this.GetCustomContentTextView(progress)); TextView textView = new TextView(this.context) { Text = "used", TextAlignment = TextAlignment.Center, Gravity = GravityFlags.Center, TextSize = 10 }; textView.SetTextColor(Color.ParseColor("#007cee")); custContentLayout.AddView(textView); this.circularCustomContentProgressBar.Content = custContentLayout; await Task.Delay(50); } } } }<file_sep>/iOS/SampleBrowser/Samples/TreeMap/DataLabel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfTreeMap.iOS; using System.Collections.Generic; #if __UNIFIED__ using UIKit; using CoreGraphics; using Foundation; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class DataLabel : SampleView { SFTreeMap tree; UILabel label; UIView option = new UIView(); UIPickerView labelMode; UIView view; public DataLabel() { // TreeMap Initialization view = new UIView(); label = new UILabel(); tree = new SFTreeMap(); tree.WeightValuePath = (NSString)"Population"; tree.ColorValuePath = (NSString)"Population"; // Leaf Item Settings tree.LeafItemSettings = new SFLeafItemSetting(); tree.LeafItemSettings.LabelStyle = new SFStyle() { Font = UIFont.SystemFontOfSize(12), Color = UIColor.White }; tree.LeafItemSettings.LabelPath = (NSString)"Region"; tree.LeafItemSettings.ShowLabels = true; tree.LeafItemSettings.Gap = 2; tree.LeafItemSettings.BorderColor = UIColor.Gray; tree.LeafItemSettings.BorderWidth = 1; //Color Mappings NSMutableArray ranges = new NSMutableArray(); ranges.Add(new SFRange() { LegendLabel = (NSString)"200M - 1.3B", From = 200000000, To = 10000000000, Color = UIColor.FromRGB(75, 19, 79) }); ranges.Add(new SFRange() { LegendLabel = (NSString)"100M - 200M", From = 100000000, To = 200000000, Color = UIColor.FromRGB(140, 48, 77) }); ranges.Add(new SFRange() { LegendLabel = (NSString)"20M - 100M", From = 20000000, To = 100000000, Color = UIColor.FromRGB(200, 75, 75) }); tree.LeafItemColorMapping = new SFRangeColorMapping() { Ranges = ranges }; LabelCustomTooltipSetting tooltipSetting = new LabelCustomTooltipSetting(); tree.ShowTooltip = true; tree.TooltipSettings = tooltipSetting; // Legend Settings CGSize legendSize = new CGSize(this.Frame.Size.Width, 60); CGSize iconSize = new CGSize(17, 17); UIColor legendColor = UIColor.Gray; tree.LegendSettings = new SFLegendSetting() { LabelStyle = new SFStyle() { Font = UIFont.SystemFontOfSize(12), Color = legendColor }, IconSize = iconSize, ShowLegend = true, Size = legendSize }; GetPopulationData(); tree.DataSource = PopulationDetails; AddSubview(view); CreateOptionView(); this.OptionView = option; } public override void LayoutSubviews() { // Popup Window base.LayoutSubviews(); label.Text = "DataLabel"; label.Frame = new CGRect(0, 0, 300, 30); view.Frame = new CGRect(0, 0, Frame.Size.Width, Frame.Size.Height); tree.Frame = new CGRect(0, 0, Frame.Size.Width - 6, Frame.Size.Height); view.AddSubview(tree); label.Frame = new CGRect(0, 0, Frame.Size.Width, 40); tree.LegendSettings.Size = new CGSize(this.Frame.Size.Width, 60); SetNeedsDisplay(); } private void CreateOptionView() { labelMode = new UIPickerView(); UILabel text1 = new UILabel(); text1.Text = "DataLabelOverflowMode"; text1.TextAlignment = UITextAlignment.Left; text1.TextColor = UIColor.Black; text1.Frame = new CGRect(10, 10, 320, 40); text1.Font = UIFont.FromName("Helvetica", 14f); List<string> position1 = new List<string> { "Trim", "Wrap", "Hide" }; var picker1 = new CustomLabelPickerModel(position1); labelMode.Model = picker1; labelMode.SelectedRowInComponent(0); labelMode.Frame = new CGRect(10, 50, 200, 70); picker1.ValueChanged += (sender, e) => { if (picker1.SelectedValue == "Trim") tree.LeafItemSettings.OverflowMode = LabelOverflowMode.Trim; else if (picker1.SelectedValue == "Wrap") tree.LeafItemSettings.OverflowMode = LabelOverflowMode.Wrap; else if (picker1.SelectedValue == "Hide") tree.LeafItemSettings.OverflowMode = LabelOverflowMode.Hide; }; this.option.AddSubview(text1); this.option.AddSubview(labelMode); } void GetPopulationData() { NSMutableArray array = new NSMutableArray(); array.Add(getDictionary("China", 1388232693)); array.Add(getDictionary("India", 1342512706)); array.Add(getDictionary("United States of America", 326474013)); array.Add(getDictionary("Indonesia", 263510146)); array.Add(getDictionary("Bygil", 211243220)); array.Add(getDictionary("Pakistan", 196744376)); array.Add(getDictionary("Nigergy", 191835936)); array.Add(getDictionary("Bangladesh", 164827718)); array.Add(getDictionary("Russian Federation", 143375006)); array.Add(getDictionary("Mexico", 130222815)); array.Add(getDictionary("Japan", 126045211)); array.Add(getDictionary("ygEthiopia", 104344901)); array.Add(getDictionary("Philippines", 103796832)); array.Add(getDictionary("Viet Nam", 95414640)); array.Add(getDictionary("Egypt", 95215102)); array.Add(getDictionary("D.R. Congo", 82242685)); array.Add(getDictionary("Iran", 80945718)); array.Add(getDictionary("Ggyermany", 80636124)); array.Add(getDictionary("Tgyurkey", 80417526)); array.Add(getDictionary("Tgyhailand", 68297547)); array.Add(getDictionary("United Kingdom", 65511098)); array.Add(getDictionary("France", 64938716)); array.Add(getDictionary("Italy", 59797978)); array.Add(getDictionary("Tanzania", 56877529)); array.Add(getDictionary("South Africa", 554360)); array.Add(getDictionary("Myanmar", 54836483)); array.Add(getDictionary("Republic of Korea", 50704971)); array.Add(getDictionary("Colombia", 49067981)); array.Add(getDictionary("Kenya", 48466928)); array.Add(getDictionary("Spain", 46070146)); array.Add(getDictionary("Ukraine", 44405055)); array.Add(getDictionary("Argentina", 44272125)); array.Add(getDictionary("Algeria", 41063753)); array.Add(getDictionary("Sudan", 42166323)); array.Add(getDictionary("Uganda", 41652938)); array.Add(getDictionary("Iraq", 38654287)); array.Add(getDictionary("Poland", 38563573)); array.Add(getDictionary("Canada", 36626083)); array.Add(getDictionary("Morocco", 35241418)); array.Add(getDictionary("Afghanistan", 3416938)); array.Add(getDictionary("Saudi Arabia", 32742664)); array.Add(getDictionary("Peru", 32166473)); array.Add(getDictionary("Venezuela", 31925705)); array.Add(getDictionary("Malaysia", 31164177)); array.Add(getDictionary("Uzbekistan", 30690914)); array.Add(getDictionary("Mozambique", 29537914)); array.Add(getDictionary("Nepal", 29187037)); array.Add(getDictionary("Ghana", 28656723)); array.Add(getDictionary("Yemen", 28119546)); array.Add(getDictionary("Angola", 26655513)); array.Add(getDictionary("Madagascar", 25612972)); array.Add(getDictionary("Dem Peoples Republic of Korea", 25405296)); array.Add(getDictionary("Australia", 24641662)); array.Add(getDictionary("Cameroon", 24513689)); array.Add(getDictionary("Côte dIvoire", 23815886)); array.Add(getDictionary("Taiwan", 23405309)); array.Add(getDictionary("Niger", 21563607)); PopulationDetails = array; } NSDictionary getDictionary(string region, double population) { object[] objects = new object[2]; object[] keys = new object[2]; keys.SetValue("Region", 0); keys.SetValue("Population", 1); objects.SetValue((NSString)region, 0); objects.SetValue(population, 1); return NSDictionary.FromObjectsAndKeys(objects, keys); } public NSMutableArray PopulationDetails { get; set; } } public class LabelCustomTooltipSetting : TooltipSetting { public LabelCustomTooltipSetting() { } public override UIView GetView(object shapeData) { NSDictionary dic = (NSDictionary)shapeData; var million = "M"; UIView view = new UIView(); NSString topText = (NSString)(dic["Region"]); var text = (NSString)(dic["Population"].ToString()); var population = Convert.ToInt32(text) / 1000000; NSString bottomText = (NSString)((NSString)(population.ToString()) + (NSString)(million.ToString())); UILabel topLabel = new UILabel(); topLabel.Text = topText; topLabel.Font = UIFont.SystemFontOfSize(12); topLabel.TextColor = UIColor.White; topLabel.TextAlignment = UITextAlignment.Center; UILabel bottomLabel = new UILabel(); bottomLabel.Text = bottomText; bottomLabel.Font = UIFont.SystemFontOfSize(12); bottomLabel.TextColor = UIColor.White; bottomLabel.TextAlignment = UITextAlignment.Center; view.AddSubview(topLabel); view.AddSubview(bottomLabel); CGSize expectedLabelSize1 = topText.GetSizeUsingAttributes(new UIStringAttributes() { Font = topLabel.Font }); CGSize expectedLabelSize2 = bottomText.GetSizeUsingAttributes(new UIStringAttributes() { Font = bottomLabel.Font }); view.Frame = new CGRect(0.0f, 0.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width), 35.0f); topLabel.Frame = new CGRect(0.0f, 0.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width), 15.0f); bottomLabel.Frame = new CGRect(0.0f, 20.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width), 15.0f); return view; } } } public class CustomLabelPickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public CustomLabelPickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new CGRect(0, 0, 130, 70)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); } } <file_sep>/iOS/SampleBrowser/Samples/ImageEditor/Serialization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfImageEditor.iOS; using Foundation; using UIKit; using CoreGraphics; using System.Drawing; using Photos; using System.IO; using System.Collections.ObjectModel; using System.Reflection; using System.Collections.Generic; namespace SampleBrowser { public class Serialization : SampleView { CustomCollectionView CustomCollectionView = new CustomCollectionView(); SerializationViewModel ViewModel = new SerializationViewModel(); UINavigationController navigationController; List<SerializationModel> list = new List<SerializationModel>(); UIButton deleteIcon; public override void MovedToSuperview() { base.MovedToSuperview(); var view = Superview; var window = UIApplication.SharedApplication.KeyWindow; navigationController = window.RootViewController as UINavigationController; } public override void LayoutSubviews() { base.LayoutSubviews(); CustomCollectionView.Frame = new CGRect(0, 70, Frame.Width, Frame.Height - 150); CustomCollectionView.DataSource = ViewModel.ModelCollection; CustomCollectionView.ItemSelected += (sender, e) => { var model = e as SerializationModel; ValidateItem(model); }; CustomCollectionView.LongPressed += (sender, e) => { if ((e as SerializationModel).Name != "Create New") { deleteIcon.Alpha = 1; EnableSelection(); } }; this.BackgroundColor = UIColor.FromRGB(242, 242, 242); /*------Header Label-------*/ UILabel label = new UILabel(new CGRect(20, 50, Frame.Width, 25)); label.BackgroundColor = UIColor.Clear; label.Font = UIFont.SystemFontOfSize(25); label.TextAlignment = UITextAlignment.Left; label.TextColor = UIColor.Gray; label.Text = "Serialization"; /*------Delete------------*/ deleteIcon = new UIButton(new CGRect(Frame.Width / 2 - 50, Frame.Height - 60, 100, 50)); deleteIcon.Alpha = 0; deleteIcon.BackgroundColor = UIColor.Clear; deleteIcon.TouchUpInside += (sender, e) => { for (int i = 0; i < list.Count; i++) { if (ViewModel.ModelCollection.Contains(list[i])) { ViewModel.ModelCollection.Remove(list[i]); } } foreach (var item1 in ViewModel.ModelCollection) { item1.IsImageSelected = false; item1.IsItemSelectedToDelete = false; list = new List<SerializationModel>(); } CustomCollectionView.DataSource = ViewModel.ModelCollection; deleteIcon.Alpha = 0; }; UIImageView DeleteButton = new UIImageView(new CGRect(0,0, 100, 50)); DeleteButton.Image = UIImage.FromBundle("Images/ImageEditor/Delete1.png"); DeleteButton.ContentMode = UIViewContentMode.ScaleAspectFit; deleteIcon.AddSubview(DeleteButton); AddSubview(label); AddSubview(CustomCollectionView); AddSubview(deleteIcon); } void ValidateItem(SerializationModel model) { if (model.Name == "Create New") { deleteIcon.Alpha = 0; navigationController.PushViewController(new EditorViewController(model, CustomCollectionView, ViewModel), false); foreach (var item1 in ViewModel.ModelCollection) { item1.IsImageSelected = false; item1.IsItemSelectedToDelete = false; } CustomCollectionView.DataSource = ViewModel.ModelCollection; list = new List<SerializationModel>(); } else if (!model.IsImageSelected) navigationController.PushViewController(new EditorViewController(model, CustomCollectionView, ViewModel), false); else { if (!model.IsItemSelectedToDelete) { model.IsItemSelectedToDelete = true; list.Add(model); } else { model.IsItemSelectedToDelete = false; if(list.Count!=0) list.Remove(model); } CustomCollectionView.DataSource = ViewModel.ModelCollection; } } void EnableSelection() { foreach (var item in ViewModel.ModelCollection) { item.IsImageSelected = true; } CustomCollectionView.DataSource = ViewModel.ModelCollection; } } public class EditorViewController : UIViewController { SerializationModel _model; SfImageEditor sfImageEditor; SerializationViewModel _serializationViewModel; CustomCollectionView _collectionView; string itemName = ""; public EditorViewController(SerializationModel model, CustomCollectionView collectionView, SerializationViewModel serializationViewModel) { _model = model; _serializationViewModel = serializationViewModel; _collectionView = collectionView; } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); sfImageEditor = new SfImageEditor(new CGRect(View.Frame.Location.X, 60, View.Frame.Size.Width, View.Frame.Size.Height - 60)); sfImageEditor.Image = UIImage.FromBundle("Images/ImageEditor/WhiteImage.png"); var sampleTimer = NSTimer.CreateTimer(TimeSpan.FromSeconds(3.0), delegate { ReadFile(); Dispose(); }); sampleTimer.Fire(); sfImageEditor.ImageSaving += (sender, e) => { e.Cancel = true; var stream = e.Stream; var byteArray = ReadFully(stream); NSData data = NSData.FromArray(byteArray); if (_model.Name == "Create New") { var count = _collectionView.DataSource.Count; SerializationModel item = new SerializationModel() { Name = itemName != "" ? itemName : ValidateName(), ImageAlignment = UIViewContentMode.Center, ImageBackgroundColor = UIColor.FromRGB(255, 255, 255), id = count - 1, EditsStrm = null }; item.EditsStrm = sfImageEditor.SaveEdits(); item.Image = UIImage.LoadFromData(data); item.ImageAlignment = UIViewContentMode.ScaleAspectFit; _serializationViewModel.ModelCollection.Add(item); EditsViewModel.EditsCollection.Add(new EditsModel() { Name = item.Name }); } else { _model.EditsStrm = sfImageEditor.SaveEdits(); _model.Image = UIImage.LoadFromData(data); _model.ImageAlignment = UIViewContentMode.ScaleAspectFit; } _collectionView.DataSource = _serializationViewModel.ModelCollection; }; this.View.Add(sfImageEditor); } string ValidateName() { String Name = "NewItem"; int j = 1; for (int i = 0; i < _serializationViewModel.ModelCollection.Count; i++) { if ( _serializationViewModel.ModelCollection[i].Name == Name) { Name = "NewItem " + j; j++; } } return Name; } public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } private void ReadFile() { if (_model.id != -1) { if (_model.EditsStrm == null ) sfImageEditor.LoadEdits(EditsViewModel.EditsCollection[_model.id].Stream); else sfImageEditor.LoadEdits(_model.EditsStrm); } } } public class EditsViewModel { public static ObservableCollection<EditsModel> EditsCollection = new ObservableCollection<EditsModel>() { new EditsModel(){Name = "Chart"}, new EditsModel(){Name = "Venn"}, new EditsModel(){Name = "FreeHand"}, }; } public class EditsModel { private string name; public string Name { get { return name; } set { name = value; } } private Stream stream; public Stream Stream { get { return this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Resources.Images.ImageEditor." + name + ".txt"); } set { stream = value; } } } public class SerializationModel { public string Name { get; set; } public int id { get; set; } public UIImage Image { get; set; } public UIViewContentMode ImageAlignment { get; set; } public UIColor ImageBackgroundColor { get; set; } public Stream Strm { get; set; } public Stream EditsStrm { get; set; } public bool IsImageSelected { get; set; } public bool IsItemSelectedToDelete { get; set; } } public class SerializationViewModel { public ObservableCollection<SerializationModel> ModelCollection { get; set; } public SerializationViewModel() { ModelCollection = new ObservableCollection<SerializationModel>() { new SerializationModel(){ Name ="<NAME>", Image = UIImage.FromBundle("Images/ImageEditor/CreateNew.png"),ImageAlignment= UIViewContentMode.Center,ImageBackgroundColor=UIColor.FromRGB(6,93,199),id=-1,EditsStrm=null,IsItemSelectedToDelete=false }, new SerializationModel(){ Name ="Chart", Image = UIImage.FromBundle("Images/ImageEditor/Chart.jpg"),ImageAlignment= UIViewContentMode.ScaleAspectFit,ImageBackgroundColor=UIColor.FromRGB(255,255,255),Strm=EditsViewModel.EditsCollection[0].Stream,id=0,EditsStrm=null,IsImageSelected =false,IsItemSelectedToDelete=false}, new SerializationModel(){ Name ="<NAME>", Image = UIImage.FromBundle("Images/ImageEditor/Venn.jpg"),ImageAlignment= UIViewContentMode.ScaleAspectFit,ImageBackgroundColor=UIColor.FromRGB(255,255,255),Strm=EditsViewModel.EditsCollection[1].Stream,id=1,EditsStrm=null,IsImageSelected = false,IsItemSelectedToDelete=false}, new SerializationModel(){ Name ="Freehand", Image = UIImage.FromBundle("Images/ImageEditor/Freehand.jpg"),ImageAlignment= UIViewContentMode.ScaleAspectFit,ImageBackgroundColor=UIColor.FromRGB(255,255,255),Strm=EditsViewModel.EditsCollection[2].Stream,id=2,EditsStrm=null,IsImageSelected =false ,IsItemSelectedToDelete=false}, }; } } public class CustomCollectionView : UIScrollView { ObservableCollection<SerializationModel> dataSource; public CustomCollectionView() { } public ObservableCollection<SerializationModel> DataSource { get { return dataSource; } set { dataSource = value; GenerateCollectionView(); } } public int NumberofColums = 2; public event CollectionViewSelectionEventHandler ItemSelected; public event CollectionViewSelectionEventHandler LongPressed; void GenerateCollectionView() { //Remove subViews foreach (UIView view in this.Subviews) { view.RemoveFromSuperview(); } if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { NumberofColums = 3; } int index = 0, x = 0, y = 30; int padding = 30; nfloat ItemSize = (Frame.Width / NumberofColums) - padding; x = padding / 2; ContentSize = new CGSize(Frame.Width, (ItemSize + padding) * ((DataSource.Count / NumberofColums) + 1)); foreach (var model in DataSource) { CGRect rect = new CGRect(x, y, ItemSize, ItemSize); this.AddSubview(GetItemView(model, rect)); index++; if (index % NumberofColums != 0) { x += (15 + (int)ItemSize); } else { x = padding / 2; y += (int)ItemSize + 10; } } } UIView GetItemView(SerializationModel model, CGRect frame) { UIButton button = new UIButton(frame); UIImageView imageView = new UIImageView(new CGRect(0, 5, frame.Width, frame.Height - 20)); imageView.Alpha = 1f; imageView.Image = model.Image; imageView.BackgroundColor = model.ImageBackgroundColor; imageView.ContentMode = model.ImageAlignment; button.AddSubview(imageView); UILabel label = new UILabel(); if (model.Name != "Create New") { label.Frame = new CGRect(0, frame.Height - 40, frame.Width, 25); label.Alpha = 0.5f; label.BackgroundColor = UIColor.LightGray; if (model.IsImageSelected) { UIImageView SelectedView = new UIImageView(new CGRect(frame.Width - 25, 10, 20, 20)); if (!model.IsItemSelectedToDelete) { SelectedView.Image = UIImage.FromBundle("Images/ImageEditor/NotSelected.png"); imageView.Alpha = 1f; } else { SelectedView.Image = UIImage.FromBundle("Images/ImageEditor/Selected.png"); imageView.Alpha = 0.3f; } SelectedView.BackgroundColor = UIColor.Clear; SelectedView.ContentMode = UIViewContentMode.ScaleAspectFit; button.AddSubview(SelectedView); } } else { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Frame = new CGRect(0, frame.Height / 2 + 50, frame.Width, 25); } else label.Frame = new CGRect(0, frame.Height / 2 + 20, frame.Width, 25); label.Alpha = 1f; label.BackgroundColor = UIColor.Clear; label.TextColor = UIColor.White; } label.Font = UIFont.SystemFontOfSize(18); label.TextAlignment = UITextAlignment.Center; label.Text = model.Name; button.AddSubview(label); UILongPressGestureRecognizer detector = new UILongPressGestureRecognizer((UILongPressGestureRecognizer obj) => { OnLongPressed(this, model); }); button.AddGestureRecognizer(detector); button.TouchUpInside += (sender, e) => { OnItemSelected(this, model); }; return button; } internal void OnItemSelected(object sender, SerializationModel args) { this.ItemSelected?.Invoke(sender, args); } internal void OnLongPressed(object sender, SerializationModel args) { this.LongPressed?.Invoke(sender, args); } } public delegate void CollectionViewSelectionEventHandler(object sender, SerializationModel e); public delegate void CollectionViewLongPressEventHandler(object sender, SerializationModel e); } <file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/ItemSourceSelector.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ItemSourceSelector.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Syncfusion.SfDataGrid.XForms; /// <summary> /// Implementation class for ItemsSourceSelector interface /// </summary> public class ItemSourceSelector : IItemsSourceSelector { /// <summary> /// Implementation class for ItemsSourceSelector interface /// </summary> /// <param name="record"> The record </param> /// <param name="dataContext">The Binding Context</param> /// <returns>The Collection</returns> public IEnumerable GetItemsSource(object record, object dataContext) { if (record == null) { return null; } var orderinfo = record as DealerInfo; var countryName = orderinfo.ShipCountry; var viewModel = dataContext as EditingViewModel; // Returns ShipCity collection based on ShipCountry. if (viewModel.ShipCities.ContainsKey(countryName)) { string[] shipcities = null; viewModel.ShipCities.TryGetValue(countryName, out shipcities); return shipcities.ToList(); } return null; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Rotator/Rotator_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Foundation; using Syncfusion.SfRotator.iOS; using System.Collections.Generic; using CoreGraphics; namespace SampleBrowser { public class Rotator_Tablet : SampleView { SFRotator rotator; NSMutableArray array; UIView sub_View; UIView contentView = new UIView (); UIView controlView = new UIView (); UISwitch autoPlaySwitch; UIPickerView navigationModePicker,navigationDirectionPicker,tabStripPicker; UILabel navigationModeLabel,navigationDirectionLabel,tabStripLabel,autoPlayLabel,propertiesLabel; UIButton navigationModeButton,navigationDirectionButton,tabStripButton; UIButton doneButton,showPropertyButton,closeButton; private string selectedType; private readonly IList<string> navigationModeList = new List<string>{ "Dots", "Thumbnail" }; private readonly IList<string> navigationDirectionList = new List<string>{ "Horizontal", "Vertical" }; private readonly IList<string> tabStripPositionList = new List<string>{ "Left", "Top", "Right", "Bottom" }; public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Frame; sub_View.Frame = new CGRect (0, view.Frame.Size.Height-view.Frame.Size.Height/3 , view.Frame.Size.Width, view.Frame.Size.Height/3); controlView.Frame=new CGRect(100,40,this.Frame.Size.Width-200,this.Frame.Size.Height); contentView.Frame=new CGRect(0,40,sub_View.Frame.Size.Width,sub_View.Frame.Size.Height-20); rotator.Frame = new CGRect (0,0,controlView.Frame.Size.Width, 400); navigationModeLabel.Frame = new CGRect (110, 40, contentView.Frame.Size.Width-200,30 ); navigationDirectionLabel.Frame = new CGRect (110,90, contentView.Frame.Size.Width-200, 30); tabStripLabel.Frame = new CGRect (110, 130,contentView.Frame.Size.Width-200, 30); navigationModePicker.Frame = new CGRect (100, 50, contentView.Frame.Size.Width-200, 150); navigationDirectionPicker.Frame = new CGRect (100, 50, contentView.Frame.Size.Width-200 , 150); tabStripPicker.Frame = new CGRect (100, 50, contentView.Frame.Size.Width-200, 150); doneButton.Frame = new CGRect (100, 20, contentView.Frame.Size.Width-200, 30); navigationModeButton.Frame = new CGRect (350, 40,contentView.Frame.Size.Width-520,30 ); navigationDirectionButton.Frame = new CGRect (350,90,contentView.Frame.Size.Width-520,30 ); tabStripButton.Frame = new CGRect (350,130,contentView.Frame.Size.Width-520,30 ); autoPlayLabel.Frame=new CGRect(110, 175, contentView.Frame.Size.Width-220, 20); autoPlaySwitch.Frame=new CGRect(350,175, contentView.Frame.Size.Width-220, 20); showPropertyButton.Frame = new CGRect (0, this.Frame.Size.Height - 25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect (this.Frame.Size.Width - 30, 5, 20, 30); propertiesLabel.Frame = new CGRect (10, 5, this.Frame.Width, 30); } base.LayoutSubviews (); } public Rotator_Tablet () { array = new NSMutableArray (); getRotatorItem (); //Control Initialization rotator = new SFRotator (); rotator.DataSource = array; rotator.EnableLooping=true; rotator.NavigationStripMode=SFRotatorNavigationStripMode.Dots; rotator.SelectedIndex=0; rotator.NavigationDelay = 2; getPropertiesInitialization (); } void getRotatorItem() { SFRotatorItem item1 = new SFRotatorItem (); UIView view1 = new UIView(); UIImageView image1 =new UIImageView(); image1.Frame = view1.Frame; image1.Image = UIImage.FromFile ("movie1.png"); item1.View = view1; view1.AddSubview(image1); SFRotatorItem item2 = new SFRotatorItem (); UIView view2 = new UIView(); UIImageView image2 =new UIImageView(); image2.Frame = view2.Frame; image2.Image = UIImage.FromFile ("movie2.png"); item2.View = view2; view2.AddSubview(image2); SFRotatorItem item3 = new SFRotatorItem (); UIView view3 = new UIView(); UIImageView image3 =new UIImageView(); image3.Frame = view3.Frame; image3.Image = UIImage.FromFile ("movie3.png"); item3.View = view3; view3.AddSubview(image3); SFRotatorItem item4 = new SFRotatorItem (); UIView view4 = new UIView(); UIImageView image4 =new UIImageView(); image4.Frame = view4.Frame; image4.Image = UIImage.FromFile ("movie4.png"); item4.View = view4; view4.AddSubview(image4); SFRotatorItem item5 = new SFRotatorItem (); UIView view5 = new UIView(); UIImageView image5 =new UIImageView(); image5.Frame = view5.Frame; image5.Image = UIImage.FromFile ("movie5.png"); item5.View = view5; view5.AddSubview(image5); SFRotatorItem item6 = new SFRotatorItem (); UIView view6 = new UIView(); UIImageView image6 =new UIImageView(); image6.Frame = view6.Frame; image6.Image = UIImage.FromFile ("movie6.png"); item6.View = view6; view6.AddSubview(image6); SFRotatorItem item7 = new SFRotatorItem (); UIView view7 = new UIView(); UIImageView image7 =new UIImageView(); image7.Frame = view7.Frame; image7.Image = UIImage.FromFile ("movie7.png"); item7.View = view7; view7.AddSubview(image7); image1.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image2.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image3.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image4.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image5.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image6.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image7.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; array.Add (item1); array.Add (item2); array.Add (item3); array.Add (item4); array.Add (item5); //array.Add (item6); //array.Add (item7); } void getPropertiesInitialization() { navigationModePicker = new UIPickerView (); navigationDirectionPicker = new UIPickerView (); tabStripPicker = new UIPickerView (); PickerModel navigationModeModel = new PickerModel (navigationModeList); navigationModePicker.Model = navigationModeModel; PickerModel navigationDirectionModel = new PickerModel (navigationDirectionList); navigationDirectionPicker.Model = navigationDirectionModel; PickerModel tabStripModel = new PickerModel (tabStripPositionList); tabStripPicker.Model = tabStripModel; //navigationModeLabel navigationModeLabel = new UILabel(); navigationModeLabel.Text = "NavigationStrip Mode"; navigationModeLabel.Font=UIFont.FromName("Helvetica", 14f); navigationModeLabel.TextColor = UIColor.Black; navigationModeLabel.TextAlignment = UITextAlignment.Left; navigationDirectionLabel = new UILabel(); navigationDirectionLabel.Text = "Navigation Direction"; navigationDirectionLabel.Font=UIFont.FromName("Helvetica", 14f); navigationDirectionLabel.TextColor = UIColor.Black; navigationDirectionLabel.TextAlignment = UITextAlignment.Left; tabStripLabel = new UILabel(); tabStripLabel.Text = "NavigationStrip Position"; tabStripLabel.Font=UIFont.FromName("Helvetica", 14f); tabStripLabel.TextColor = UIColor.Black; tabStripLabel.TextAlignment = UITextAlignment.Left; //navigationModeButton navigationModeButton = new UIButton(); navigationModeButton.SetTitle("Dots",UIControlState.Normal); navigationModeButton.Font=UIFont.FromName("Helvetica", 14f); navigationModeButton.SetTitleColor(UIColor.Black,UIControlState.Normal); navigationModeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; navigationModeButton.Layer.CornerRadius = 8; navigationModeButton.Layer.BorderWidth = 2; navigationModeButton.Layer.BorderColor =UIColor.FromRGB(246,246,246).CGColor; //navigationDirectionButton navigationDirectionButton = new UIButton(); navigationDirectionButton.SetTitle("Horizontal",UIControlState.Normal); navigationDirectionButton.Font=UIFont.FromName("Helvetica", 14f); navigationDirectionButton.SetTitleColor(UIColor.Black,UIControlState.Normal); navigationDirectionButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; navigationDirectionButton.Layer.CornerRadius = 8; navigationDirectionButton.Layer.BorderWidth = 2; navigationDirectionButton.Layer.BorderColor =UIColor.FromRGB(246,246,246).CGColor; //tabStripButton tabStripButton = new UIButton(); tabStripButton.SetTitle("Bottom",UIControlState.Normal); tabStripButton.Font=UIFont.FromName("Helvetica", 14f); tabStripButton.SetTitleColor(UIColor.Black,UIControlState.Normal); tabStripButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; tabStripButton.Layer.CornerRadius = 8; tabStripButton.Layer.BorderWidth = 2; tabStripButton.TouchUpInside += ShowtabStripPicker; tabStripButton.Layer.BorderColor =UIColor.FromRGB(246,246,246).CGColor; //doneButton doneButton = new UIButton (); doneButton.SetTitle("Done\t",UIControlState.Normal); doneButton.Font=UIFont.FromName("Helvetica", 14f); doneButton.SetTitleColor(UIColor.Black,UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(240,240,240); //picker navigationModeModel.PickerChanged += navigationModeSelectedIndexChanged; navigationDirectionModel.PickerChanged += navigationDirectionSelectedIndexChanged; tabStripModel.PickerChanged += tabStripSelectedIndexChanged; navigationModePicker.ShowSelectionIndicator = true; navigationModePicker.Hidden = true; navigationModePicker.BackgroundColor = UIColor.Gray; navigationDirectionPicker.BackgroundColor = UIColor.Gray; navigationDirectionPicker.ShowSelectionIndicator = true; navigationDirectionPicker.Hidden = true; tabStripPicker.BackgroundColor = UIColor.Gray; tabStripPicker.ShowSelectionIndicator = true; tabStripPicker.Hidden = true; //autoPlayLabel autoPlayLabel = new UILabel(); autoPlayLabel.TextColor = UIColor.Black; autoPlayLabel.BackgroundColor= UIColor.Clear; autoPlayLabel.Text=@"Enable AutoPlay"; autoPlayLabel.TextAlignment= UITextAlignment.Left; autoPlayLabel.Font=UIFont.FromName("Helvetica", 14f); //allowSwitch autoPlaySwitch = new UISwitch(); autoPlaySwitch.ValueChanged += autoPlayToggleChanged; autoPlaySwitch.On=false; autoPlaySwitch.OnTintColor = UIColor.FromRGB (50, 150, 221); controlView.AddSubview (rotator); this.AddSubview (controlView); sub_View = new UIView (); propertiesLabel = new UILabel (); closeButton = new UIButton (); showPropertyButton = new UIButton (); //adding to content view contentView.AddSubview (navigationModeLabel); contentView.AddSubview (navigationModeButton); contentView.AddSubview (navigationDirectionLabel); contentView.AddSubview (navigationDirectionButton); contentView.AddSubview (tabStripLabel); contentView.AddSubview (tabStripButton); contentView.AddSubview (autoPlayLabel); contentView.AddSubview (autoPlaySwitch); contentView.AddSubview (doneButton); contentView.AddSubview (navigationModePicker); contentView.AddSubview (tabStripPicker); contentView.AddSubview (navigationDirectionPicker); contentView.BackgroundColor=UIColor.FromRGB(240,240,240); //adding to sub_view sub_View.AddSubview (contentView); sub_View.AddSubview(closeButton); sub_View.AddSubview(propertiesLabel); sub_View.BackgroundColor=UIColor.FromRGB(230,230,230); this.AddSubview(sub_View); propertiesLabel.Text="OPTIONS"; //showPropertyButton showPropertyButton.Hidden = true; showPropertyButton.SetTitle("OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(230,230,230); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { sub_View.Hidden = false; showPropertyButton.Hidden = true; }; this.AddSubview(showPropertyButton); //CloseButton closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(230,230,230); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { sub_View.Hidden = true; showPropertyButton.Hidden = false; }; //AddingGesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer (() =>{ sub_View.Hidden = true; showPropertyButton.Hidden = false; } ); propertiesLabel.UserInteractionEnabled = true; propertiesLabel.AddGestureRecognizer (tapgesture); } void ShowtabStripPicker (object sender, EventArgs e) { doneButton.Hidden = false; navigationModePicker.Hidden = true; navigationDirectionPicker.Hidden = true; tabStripPicker.Hidden = false; navigationModeButton.Hidden = true; tabStripLabel.Hidden = true; tabStripButton.Hidden = true; navigationDirectionButton.Hidden = true; navigationDirectionLabel.Hidden = true; autoPlayLabel.Hidden = true; autoPlaySwitch.Hidden = true; } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; navigationDirectionPicker.Hidden = true; navigationModePicker.Hidden = true; tabStripPicker.Hidden = true; navigationModeButton.Hidden = false; navigationModeLabel.Hidden = false; tabStripLabel.Hidden = false; tabStripButton.Hidden = false; navigationDirectionButton.Hidden = false; navigationDirectionLabel.Hidden = false; autoPlayLabel.Hidden = false; autoPlaySwitch.Hidden = false; } private void navigationModeSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; navigationModeButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Dots") rotator.NavigationStripMode = SFRotatorNavigationStripMode.Dots; else rotator.NavigationStripMode = SFRotatorNavigationStripMode.Thumbnail; } private void navigationDirectionSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; navigationDirectionButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Horizontal") rotator.NavigationDirection = SFRotatorNavigationDirection.Horizontal; else rotator.NavigationDirection = SFRotatorNavigationDirection.Vertical; } private void tabStripSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; tabStripButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Left") rotator.NavigationStripPosition = SFRotatorNavigationStripPosition.Left; else if (selectedType == "Top") rotator.NavigationStripPosition =SFRotatorNavigationStripPosition.Top; else if (selectedType == "Right") rotator.NavigationStripPosition =SFRotatorNavigationStripPosition.Right; else rotator.NavigationStripPosition =SFRotatorNavigationStripPosition.Bottom; } private void autoPlayToggleChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { rotator.EnableAutoPlay = true; } else { rotator.EnableAutoPlay = false; } } } } <file_sep>/Forms/CircularGauge/CircularGauge/Samples/MultipleScales/MultipleScales.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfGauge.XForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Xamarin.Forms.Internals; namespace SampleBrowser.SfCircularGauge { [Preserve(AllMembers = true)] public partial class MultipleScales : SampleView { public MultipleScales() { InitializeComponent(); scale1_StartAngle_slider.BindingContext = viewModel; scale1_SweepAngle_slider.BindingContext = viewModel; scale2_StartAngle_slider.BindingContext = viewModel; scale2_SweepAngle_slider.BindingContext = viewModel; //directionPicker.SelectedIndex = 0; //directionPicker.SelectedIndexChanged += DirectionPicker_SelectedIndexChanged; } //private void DirectionPicker_SelectedIndexChanged(object sender, EventArgs e) //{ // switch (directionPicker.SelectedIndex) // { // case 0: // scale1.Direction = ScaleDirection.Clockwise; // scale2.Direction = ScaleDirection.Clockwise; // break; // case 1: // scale1.Direction = ScaleDirection.AntiClockwise; // scale2.Direction = ScaleDirection.AntiClockwise; // break; // } //} } } <file_sep>/Android/SampleBrowser/Samples/TreeView/Helper/CustomAdapter/TemplateAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Views; using Android.Widget; using Syncfusion.Android.TreeView; using Syncfusion.TreeView.Engine; namespace SampleBrowser { public class TemplateAdapter : TreeViewAdapter { public TemplateAdapter() { } protected override View CreateContentView(TreeViewItemInfoBase itemInfo) { var gridView = new TemplateView(TreeView.Context, itemInfo); return gridView; } protected override void UpdateContentView(View view, TreeViewItemInfoBase itemInfo) { var grid = view as TemplateView; var treeViewNode = itemInfo.Node; if (grid != null) { var label = grid.GetChildAt(0) as ContentLabel; if (label != null) { label.Text = (treeViewNode.Content as MailFolder).FolderName; if ((treeViewNode.Content as MailFolder).MailsCount > 0) label.SetTypeface(Android.Graphics.Typeface.Default, Android.Graphics.TypefaceStyle.Bold); } var label1 = grid.GetChildAt(1) as ContentLabel; if (label1 != null) { if ((treeViewNode.Content as MailFolder).MailsCount > 0) { label1.Text = (treeViewNode.Content as MailFolder).MailsCount.ToString(); label1.SetTextColor(Android.Graphics.Color.White); label1.SetBackgroundColor(Android.Graphics.Color.ParseColor("#FF6377EB")); } } } } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/Doughnut.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using System.Collections.Generic; namespace SampleBrowser { public class Doughnut : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "Project Cost Breakdown"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.OverflowMode = ChartLegendOverflowMode.Wrap; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; DoughnutSeries doughnutSeries = new DoughnutSeries(); doughnutSeries.DataPointSelectionEnabled = true; doughnutSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; doughnutSeries.ExplodableOnTouch = true; doughnutSeries.ItemsSource = MainPage.GetDoughnutData(); doughnutSeries.XBindingPath = "XValue"; doughnutSeries.YBindingPath = "YValue"; doughnutSeries.DataMarker.ShowLabel = true; doughnutSeries.DataMarker.LabelStyle.LabelFormat = "#.##'M'"; doughnutSeries.EnableAnimation = true; chart.Series.Add(doughnutSeries); LinearLayout layout = new LinearLayout(context); layout.Orientation = Orientation.Vertical; TextView label = new TextView(context); label.Gravity = GravityFlags.Center; label.TextAlignment = Android.Views.TextAlignment.Center; label.Text = "Tap on slice"; TextView label1 = new TextView(context); label1.Gravity = GravityFlags.Center; label1.TextAlignment = Android.Views.TextAlignment.Center; layout.AddView(label); layout.AddView(label1); doughnutSeries.CenterView = layout; chart.SelectionChanging += (object sender, SfChart.SelectionChangingEventArgs e) => { if (doughnutSeries.ExplodeIndex >= 0) { var datapoints = e.P1.SelectedSeries.ItemsSource as List<DataPoint>; var datapoint = datapoints[e.P1.SelectedDataPointIndex].YValue; double total = 0; for (int i = 0; i < datapoints.Count; i++) { total = total + (double)datapoints[i].YValue; } double percentageValue = ((double)datapoint / total) * 100; string percentage = percentageValue.ToString("N2") + "%"; label.Text = percentage; var segments = e.P1.SelectedSeries.Segments; label.SetTextColor(segments[e.P1.SelectedDataPointIndex].Color); label1.Text = datapoints[e.P1.SelectedDataPointIndex].XValue.ToString(); label.TextSize = 19; doughnutSeries.CenterView = layout; e.P1.Cancel = true; } else { label1.Text = string.Empty; label.Text = "Tap on slice"; label.TextSize = 13; label.SetTextColor(label1.TextColors); doughnutSeries.CenterView = layout; e.P1.Cancel = true; } }; return chart; } } }<file_sep>/Forms/RadialMenu/RadialMenu/Samples/Customization_RadialMenu/Rotator_ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using Xamarin.Forms; namespace SampleBrowser.SfRadialMenu { public class Rotator_ViewModel : INotifyPropertyChanged { public Rotator_ViewModel() { RotatorCollection.Add(new Rotator_Model("Team Eagle", Color.FromHex("#f99363"), "35", "4", "36", "19", "9", "85")); RotatorCollection.Add(new Rotator_Model("Team Tiger", Color.FromHex("#7d8ff2"), "2", "1", "22", "1", "1", "18")); } private List<Rotator_Model> rotatorCollection = new List<Rotator_Model>(); public List<Rotator_Model> RotatorCollection { get { return rotatorCollection; } set { rotatorCollection = value; RaisepropertyChanged("RotatorCollection"); } } public event PropertyChangedEventHandler PropertyChanged; void RaisepropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Scatter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; using Com.Syncfusion.Charts.Enums; using Com.Syncfusion.Navigationdrawer; namespace SampleBrowser { internal class Scatter : SamplePage { List<string> scatterSeriesType; ScatterSeries scatter; ScatterTooltipBehavior tooltipBehavior; public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "Height vs Weight"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.ColorModel.ColorPalette = ChartColorPalette.Natural; NumericalAxis primariyAxis = new NumericalAxis(); primariyAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; primariyAxis.ShowMajorGridLines = false; primariyAxis.Minimum = 100; primariyAxis.Maximum = 220; primariyAxis.Interval = 20; primariyAxis.Title.Text = "Height in Inches"; chart.PrimaryAxis = primariyAxis; NumericalAxis secondaryAxis = new NumericalAxis(); secondaryAxis.ShowMajorGridLines = false; secondaryAxis.Minimum = 50; secondaryAxis.Maximum = 80; secondaryAxis.Interval = 5; secondaryAxis.Title.Text = "Weight in Pounds"; chart.SecondaryAxis = secondaryAxis; scatter = new ScatterSeries(); scatter.Alpha = 0.7f; scatter.ScatterWidth = 12; scatter.ScatterHeight = 12; scatter.ItemsSource = MainPage.GetScatterMaleData(); scatter.XBindingPath = "XValue"; scatter.YBindingPath = "YValue"; scatter.Label = "Male"; scatter.LegendIcon = ChartLegendIcon.SeriesType; scatter.TooltipEnabled = true; scatter.EnableAnimation = true; ScatterSeries scatter1 = new ScatterSeries(); scatter1.Alpha = 0.7f; scatter1.ScatterWidth = 12; scatter1.ScatterHeight = 12; scatter1.ShapeType = ChartScatterShapeType.Diamond; scatter1.ItemsSource = MainPage.GetScatterFemaleData(); scatter1.XBindingPath = "XValue"; scatter1.YBindingPath = "YValue"; scatter1.Label = "Female"; scatter1.LegendIcon = ChartLegendIcon.SeriesType; scatter1.EnableAnimation = true; scatter1.TooltipEnabled = true; chart.Series.Add(scatter); chart.Series.Add(scatter1); tooltipBehavior = new ScatterTooltipBehavior(context); chart.Behaviors.Add(tooltipBehavior); chart.TooltipCreated += Chart_TooltipCreated; return chart; } private void Chart_TooltipCreated(object sender, SfChart.TooltipCreatedEventArgs e) { tooltipBehavior.MarginLeft = 30; tooltipBehavior.MarginTop = 20; tooltipBehavior.MarginRight = 55; tooltipBehavior.MarginBottom = 40; tooltipBehavior.BackgroundColor = Color.ParseColor("#404041"); tooltipBehavior.TextColor = Color.Transparent; tooltipBehavior.StrokeWidth = 1f; } public override View GetPropertyWindowLayout(Android.Content.Context context) { int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; LinearLayout propertylayout = new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams( width * 2, 05); layoutParams1.SetMargins(0, 20, 0, 0); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); propertylayout.AddView(separate, layoutParams1); Spinner selectLabelMode = new Spinner(context, SpinnerMode.Dialog); scatterSeriesType = new List<String>() { "Ellipse", "Cross", "Diamond", "Hexagon", "Triangle", "InvertedTriangle", "Plus", "Pentagon", "Rectangle" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, scatterSeriesType); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += SelectLabelMode_ItemSelected; propertylayout.AddView(selectLabelMode); return propertylayout; } private void SelectLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { switch (e.Position) { case 0: scatter.ShapeType = ChartScatterShapeType.Ellipse; break; case 1: scatter.ShapeType = ChartScatterShapeType.Cross; break; case 2: scatter.ShapeType = ChartScatterShapeType.Diamond; break; case 3: scatter.ShapeType = ChartScatterShapeType.Hexagon; break; case 4: scatter.ShapeType = ChartScatterShapeType.Triangle; break; case 5: scatter.ShapeType = ChartScatterShapeType.InvertedTriangle; break; case 6: scatter.ShapeType = ChartScatterShapeType.Plus; break; case 7: scatter.ShapeType = ChartScatterShapeType.Pentagon; break; case 8: scatter.ShapeType = ChartScatterShapeType.Rectangle; break; } } } class ScatterTooltipBehavior : ChartTooltipBehavior { Context context; public ScatterTooltipBehavior(Context con) { context = con; } protected override View GetView(TooltipView p0) { LinearLayout rootLayout = new LinearLayout(context); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); rootLayout.Orientation = Orientation.Vertical; rootLayout.LayoutParameters = layoutParams; rootLayout.SetPadding(10, 5, 5, 5); TextView label = new TextView(context); label.Text = p0.Series.Label; label.TextSize = 12; label.TextAlignment = Android.Views.TextAlignment.Center; label.SetPadding(80, 0, 0, 0); label.SetTextColor(Color.White); LinearLayout line = new LinearLayout(context); LinearLayout.LayoutParams linelayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 4); line.LayoutParameters = linelayoutParams; line.SetBackgroundColor(Color.White); LinearLayout xLayout = new LinearLayout(context); xLayout.Orientation = Orientation.Horizontal; xLayout.SetPadding(0, 5, 0, 0); TextView xLabel = new TextView(context); xLabel.Text = "Height : "; xLabel.TextSize = 12; xLabel.SetTextColor(Color.ParseColor("#CCCCCC")); TextView xValue = new TextView(context); xValue.Text = (p0.ChartDataPoint as DataPoint).XValue.ToString(); xValue.TextSize = 12; xValue.SetTextColor(Color.White); xLayout.AddView(xLabel); xLayout.AddView(xValue); LinearLayout yLayout = new LinearLayout(context); yLayout.Orientation = Orientation.Horizontal; yLayout.SetPadding(0, 5, 0, 0); TextView yLabel = new TextView(context); yLabel.Text = "Weight : "; yLabel.TextSize = 12; yLabel.SetTextColor(Color.ParseColor("#CCCCCC")); TextView yValue = new TextView(context); yValue.Text = (p0.ChartDataPoint as DataPoint).YValue + " lbs"; yValue.TextSize = 12; yValue.SetTextColor(Color.White); yLayout.AddView(yLabel); yLayout.AddView(yValue); rootLayout.AddView(label); rootLayout.AddView(line); rootLayout.AddView(yLayout); rootLayout.AddView(xLayout); p0.AddView(rootLayout); return p0; } } }<file_sep>/Android/SampleBrowser/Common/Adapters/HomeScreenAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.Generic; using Android.App; using Android.Views; using Android.Widget; namespace SampleBrowser { public class HomeScreenAdapter : BaseAdapter<SampleModel> { #region fields private List<SampleModel> items; private Activity context; #endregion #region ctor public HomeScreenAdapter(Activity context, List<SampleModel> items) : base() { this.context = context; this.items = items; } #endregion #region properties public override int Count { get { return items.Count; } } #endregion #region methods public override SampleModel this[int position] { get { return items[position]; } } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; var item = items[position]; if (view == null) { view = context.LayoutInflater.Inflate(Resource.Layout.CustomView, null); } view.FindViewById<TextView>(Resource.Id.Text1).Text = item.Title; view.FindViewById<TextView>(Resource.Id.Text2).Text = item.Description; int resourceid = context.Resources.GetIdentifier("drawable/" + item.ImageId, null, context.PackageName); if (resourceid == 0) { resourceid = context.Resources.GetIdentifier("drawable/rangenavigator", null, context.PackageName); } view.FindViewById<ImageView>(Resource.Id.Image).SetImageResource(resourceid); TextView textView = (TextView)view.FindViewById(Resource.Id.tagText); if (!string.IsNullOrEmpty(item.Type)) { textView.Visibility = ViewStates.Visible; if (item.Type.ToLower().Equals("new")) { textView.Text = "New"; textView.SetBackgroundResource(Resource.Drawable.newtagbackground); } else if (item.Type.ToLower().Equals("updated")) { textView.Text = "Updated"; textView.SetBackgroundResource(Resource.Drawable.updatetagbackground); } else if (item.Type.ToLower().Equals("preview")) { textView.Text = "Preview"; textView.SetBackgroundResource(Resource.Drawable.previewtagbackground); } } else { textView.Visibility = ViewStates.Invisible; } return view; } #endregion } }<file_sep>/Android/SampleBrowser/Samples/CircularGauge/CircularGaugeAnnotation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfCircularGauge; using System.Collections.ObjectModel; using Android.Graphics; using Com.Syncfusion.Gauges.SfCircularGauge.Enums; using Android.Renderscripts; using System.Threading.Tasks; using static Android.App.ActionBar; namespace SampleBrowser { public class CircularGaugeAnnotation : SamplePage { public SfCircularGauge Gauge { get; set; } public SfCircularGauge Annotation1 { get; set; } public SfCircularGauge Annotation2 { get; set; } public TextView LabelAnnotation1 { get; set; } public TextView LabelAnnotation2 { get; set; } public TextView LabelAnnotation3 { get; set; } public override View GetSampleContent (Context con) { var density = con.Resources.DisplayMetrics.Density; LabelAnnotation1 = new TextView(con); LabelAnnotation1.Text = "4:55PM"; LabelAnnotation1.TextSize = 14; LabelAnnotation1.SetHeight(25); LabelAnnotation1.SetWidth(75); LabelAnnotation1.SetTextColor(Color.Black); LabelAnnotation1.TextAlignment = TextAlignment.Center; LabelAnnotation2 = new TextView(con); LabelAnnotation2.Text = "10s"; LabelAnnotation2.TextSize = 12; LabelAnnotation2.SetHeight(20); LabelAnnotation2.SetWidth(35); LabelAnnotation2.SetTextColor(Color.Black); LabelAnnotation2.TextAlignment = TextAlignment.Center; LabelAnnotation3 = new TextView(con); LabelAnnotation3.Text = "55M"; LabelAnnotation3.TextSize = 12; LabelAnnotation3.SetHeight(20); LabelAnnotation3.SetWidth(35); LabelAnnotation3.SetTextColor(Color.Black); LabelAnnotation3.TextAlignment = TextAlignment.Center; Annotation1 = new SfCircularGauge(con) { Annotations = new CircularGaugeAnnotationCollection { new GaugeAnnotation { View = LabelAnnotation2, Angle = 250, Offset = 0.7f } }, CircularScales = new ObservableCollection<CircularScale> { new CircularScale { StartAngle = 270, SweepAngle = 360, ShowLabels = false, StartValue = 0, EndValue = 60, Interval = 5, RimColor = Color.Rgb(237, 238, 239), CircularRanges = new ObservableCollection<CircularRange> { new CircularRange {StartValue = 0, EndValue = 30, Color = Color.Gray, InnerStartOffset = 0.925, OuterStartOffset = 1, InnerEndOffset = 0.925, OuterEndOffset = 1}, }, MajorTickSettings = new TickSetting { Color = Color.Black, StartOffset = 1, EndOffset = .85, Width = 2 }, MinorTickSettings = new TickSetting { Color = Color.Black, StartOffset = 1, EndOffset = .90, Width = 0.5 }, CircularPointers = new ObservableCollection<CircularPointer> { new NeedlePointer { Type = NeedleType.Triangle, KnobRadius = 4, Width = 3, EnableAnimation = false, KnobColor = Color.Black, Color = Color.Black } } } } }; LinearLayout layout1 = new LinearLayout(con); layout1.LayoutParameters = new LinearLayout.LayoutParams((int)(80 * density), (int)(80 * density)); layout1.AddView(Annotation1); Annotation2 = new SfCircularGauge(con) { Annotations = new CircularGaugeAnnotationCollection { new GaugeAnnotation { View = LabelAnnotation3, Angle = 245, Offset = 0.7f } }, CircularScales = new ObservableCollection<CircularScale> { new CircularScale { StartAngle = 270, SweepAngle = 360, StartValue = 0, EndValue = 60, Interval = 5, ShowLabels = false, RimColor = Color.Rgb(237, 238, 239), CircularRanges = new ObservableCollection<CircularRange> { new CircularRange {StartValue = 0, EndValue = 30, Color = Color.Gray, InnerStartOffset = 0.925, OuterStartOffset = 1, InnerEndOffset = 0.925, OuterEndOffset = 1}, }, MajorTickSettings = new TickSetting { Color = Color.Black, StartOffset = 1, EndOffset = .85, Width = 2 }, MinorTickSettings = new TickSetting { Color = Color.Black, StartOffset = 1, EndOffset = .90, Width = 0.5 }, CircularPointers = new ObservableCollection<CircularPointer> { new NeedlePointer { Type = NeedleType.Triangle, KnobRadius = 4, Width = 3, EnableAnimation = false, KnobColor = Color.Black, Color = Color.Black } } } } }; LinearLayout layout2 = new LinearLayout(con); layout2.LayoutParameters = new LinearLayout.LayoutParams((int)(80 * density),(int)(80 * density)); layout2.AddView(Annotation2); Gauge = new SfCircularGauge(con) { Annotations = new CircularGaugeAnnotationCollection { new GaugeAnnotation { View = layout1, Angle = 90, Offset = .5f }, new GaugeAnnotation { View = LabelAnnotation1, Angle = 00, Offset = .3f }, new GaugeAnnotation { View = layout2, Angle = 180, Offset = .5f }, }, CircularScales = new ObservableCollection<CircularScale> { new CircularScale { StartValue = 0, EndValue = 12, Interval = 1, MinorTicksPerInterval = 4, RimColor = Color.Rgb(237, 238, 239), LabelColor = Color.Gray, LabelOffset = .8, ScaleEndOffset = .925, StartAngle = 270, SweepAngle = 360, LabelTextSize = 14, ShowFirstLabel = false, MinorTickSettings = new TickSetting { Color = Color.Black, StartOffset = 1, EndOffset = .95, Width = 1 }, MajorTickSettings = new TickSetting { Color = Color.Black, StartOffset = 1, EndOffset = .9, Width = 3 }, CircularRanges = new ObservableCollection<CircularRange> { new CircularRange {StartValue = 0, EndValue = 3, Color= Color.Gray, InnerStartOffset = 0.925, OuterStartOffset = 1, InnerEndOffset = 0.925, OuterEndOffset = 1}, }, CircularPointers = new ObservableCollection<CircularPointer> { new NeedlePointer { EnableAnimation = false, KnobRadius = 6, LengthFactor = .75, KnobColor = Color.White, Color = Color.Black, Width = 3.5, KnobStrokeColor = Color.Black, KnobStrokeWidth = 5 , TailLengthFactor = 0.25, TailColor = Color.Black}, new NeedlePointer { EnableAnimation = false, KnobRadius = 6, LengthFactor = .4, KnobColor = Color.White, Color = Color.Black, Width = 5, Type = NeedleType.Triangle }, new NeedlePointer { EnableAnimation = false, KnobRadius = 6, LengthFactor = .65, KnobColor = Color.White, Color =Color.Black, Width = 5, Type = NeedleType.Triangle }, } } } }; DynamicUpdate(); LinearLayout linearLayout = new LinearLayout(con); linearLayout.AddView(Gauge); linearLayout.SetPadding(30, 30, 30, 30); linearLayout.SetBackgroundColor(Color.White); return linearLayout; } private async void DynamicUpdate() { while (true) { var dataTime = DateTime.Now; var hour = (double)dataTime.Hour; hour = hour > 12 ? hour % 12 : hour; var min = (double)dataTime.Minute; var sec = (double)dataTime.Second; Gauge.CircularScales[0].CircularPointers[0].Value = sec / 5; Gauge.CircularScales[0].CircularPointers[1].Value = hour + min / 60; Gauge.CircularScales[0].CircularPointers[2].Value = min / 5 + (sec / 60 * .2); Annotation1.CircularScales[0].CircularPointers[0].Value = sec; Annotation2.CircularScales[0].CircularPointers[0].Value = min + sec / 60; var meridiem = dataTime.Hour > 12 ? "PM" : "AM"; LabelAnnotation1.Text = hour.ToString() + " : " + min.ToString() + " " + meridiem; LabelAnnotation2.Text = sec.ToString() + " S"; LabelAnnotation3.Text = min.ToString() + " M"; await Task.Delay(1000); } } } } <file_sep>/Forms/Chart/Chart/Samples/Annotations/Annotations.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class Annotations : SampleView { public Annotations() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { if (Device.Idiom != TargetIdiom.Phone) { ChartAnnotationLabelStyle verticalAnnotationLabelStyle = new ChartAnnotationLabelStyle(); verticalAnnotationLabelStyle.Margin = new Thickness(0, 0, 5, 20); verticalAnnotationLabelStyle.VerticalTextAlignment = ChartAnnotationAlignment.Start; verticalAnnotationLabelStyle.HorizontalTextAlignment = ChartAnnotationAlignment.Start; verticalLineAnnotation.LabelStyle = verticalAnnotationLabelStyle; verticalLineAnnotation.AxisLabelStyle = new ChartLabelStyle() { Margin = Device.RuntimePlatform == Device.UWP ? new Thickness(5) : new Thickness(10), BackgroundColor = Color.FromRgb(37, 143, 251), TextColor = Color.White, }; ChartAnnotationLabelStyle horizontalAnnotationLabelStyle = new ChartAnnotationLabelStyle(); horizontalAnnotationLabelStyle.Margin = new Thickness(0, 0, 0, 20); horizontalAnnotationLabelStyle.VerticalTextAlignment = ChartAnnotationAlignment.Start; horizontalAnnotationLabelStyle.HorizontalTextAlignment = ChartAnnotationAlignment.End; horizontalLineAnnotation.LabelStyle = horizontalAnnotationLabelStyle; horizontalLineAnnotation.AxisLabelStyle = new ChartLabelStyle() { Margin = Device.RuntimePlatform == Device.UWP ? new Thickness(5) : new Thickness(10), BackgroundColor = Color.FromRgb(37, 143, 251), TextColor = Color.White, }; ChartAnnotationLabelStyle labelStyle = new ChartAnnotationLabelStyle(); rectangleAnnotation.LabelStyle = labelStyle; ellipseAnnotation.LabelStyle = labelStyle; textAnnotation.LabelStyle = labelStyle; if (Device.RuntimePlatform == Device.WPF) { chart.ChartPadding = new Thickness(0, 0, 5, 0); } } } } } } <file_sep>/Android/SampleBrowser/Samples/PDF/ZugFerd_XML/ZugFerdInvoice.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml; using System.Xml.Linq; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.Pdf.Grid; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Tables; using Syncfusion.Pdf; using Syncfusion.Drawing; using Syncfusion.Pdf.Interactive; using System.Reflection; namespace Syncfusion.ZugFerd { /// <summary> /// zugFerd Invoice /// </summary> public class ZugFerdInvoice { public string InvoiceNumber { get; set; } public DateTime InvoiceDate { get; set; } public CurrencyCodes Currency { get; set; } public InvoiceType Type { get; set; } public UserDetails Buyer { get; set; } public UserDetails Seller { get; set; } public ZugFerdProfile Profile { get; set; } public float TotalAmount { get; set; } List<Product> products = new List<Product>(); public void AddProduct(string productID, string productName,float price, float quantity, float totalPrice) { Product product = new Product() { ProductID = productID, productName = productName, Price = price, Quantity = quantity, Total = totalPrice }; products.Add(product); } public void AddProduct(Product product) { products.Add(product); } public ZugFerdInvoice(string invoiceNumber, DateTime invoiceDate, CurrencyCodes currency) { InvoiceNumber= invoiceNumber; InvoiceDate = invoiceDate; Currency = currency; } public Stream Save(Stream stream) { XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); #region Header writer.WriteStartElement("rsm:CrossIndustryDocument"); writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteAttributeString("xmlns", "rsm", null, "urn:ferd:CrossIndustryDocument:invoice:1p0"); writer.WriteAttributeString("xmlns", "ram", null, "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12"); writer.WriteAttributeString("xmlns", "udt", null, "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15"); #endregion #region SpecifiedExchangedDocumentContext writer.WriteStartElement("rsm:SpecifiedExchangedDocumentContext"); writer.WriteStartElement("ram:TestIndicator"); writer.WriteElementString("udt:Indicator", "true"); writer.WriteEndElement(); writer.WriteStartElement("ram:GuidelineSpecifiedDocumentContextParameter"); writer.WriteElementString("ram:ID", "urn:ferd:CrossIndustryDocument:invoice:1p0:" + Profile.ToString().ToLower()); writer.WriteEndElement(); writer.WriteEndElement(); #endregion WriteHeaderExchangeDocument(writer); writer.WriteStartElement("rsm:SpecifiedSupplyChainTradeTransaction"); writer.WriteStartElement("ram:ApplicableSupplyChainTradeAgreement"); //Seller details. WriteUserDetails(writer, "ram:SellerTradeParty", Seller); //Buyer details WriteUserDetails(writer, "ram:BuyerTradeParty", Buyer); //End of ApplicableSupplyChainTradeAgreement writer.WriteEndElement(); writer.WriteStartElement("ram:ApplicableSupplyChainTradeSettlement"); writer.WriteElementString("ram:InvoiceCurrencyCode", Currency.ToString("g")); writer.WriteStartElement("ram:SpecifiedTradeSettlementMonetarySummation"); WriteOptionalAmount(writer, "ram:GrandTotalAmount", TotalAmount); writer.WriteEndElement(); writer.WriteEndElement(); AddTradeLineItems(writer); writer.WriteEndDocument(); writer.Flush(); stream.Position = 0; return stream; } private void AddTradeLineItems(XmlTextWriter writer) { foreach (Product product in this.products) { writer.WriteStartElement("ram:IncludedSupplyChainTradeLineItem"); if (Profile != ZugFerdProfile.Basic) { writer.WriteStartElement("ram:SpecifiedSupplyChainTradeAgreement"); writer.WriteStartElement("ram:GrossPriceProductTradePrice"); WriteAttribute(writer, "ram:BasisQuantity", "unitCode", "KGM", product.Quantity.ToString()); writer.WriteEndElement(); writer.WriteEndElement(); } writer.WriteStartElement("ram:SpecifiedSupplyChainTradeDelivery"); WriteAttribute(writer, "ram:BilledQuantity", "unitCode", "KGM", product.Quantity.ToString()); writer.WriteEndElement(); writer.WriteStartElement("ram:SpecifiedSupplyChainTradeSettlement"); writer.WriteStartElement("ram:SpecifiedTradeSettlementMonetarySummation"); WriteAttribute(writer, "ram:LineTotalAmount", "currencyID", this.Currency.ToString("g"), FormatValue(TotalAmount)); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("ram:SpecifiedTradeProduct"); WriteOptionalElement(writer, "ram:Name", product.productName); writer.WriteEndElement(); writer.WriteEndElement(); } } private void WriteAttribute(XmlTextWriter writer, string tagName, string attributeName, string attributeValue, string nodeValue) { writer.WriteStartElement(tagName); writer.WriteAttributeString(attributeName, attributeValue); writer.WriteValue(nodeValue); writer.WriteEndElement(); } private void WriteOptionalElement(XmlTextWriter writer, string tagName, string value) { if (!String.IsNullOrEmpty(value)) { writer.WriteElementString(tagName, value); } } private void WriteOptionalAmount(XmlTextWriter writer, string tagName, float value, int numDecimals = 2) { if (value !=float.MinValue) { writer.WriteStartElement(tagName); writer.WriteAttributeString("currencyID", Currency.ToString("g")); writer.WriteValue(FormatValue(value, numDecimals)); writer.WriteEndElement(); } } private void WriteUserDetails(XmlTextWriter writer, string customerTag, UserDetails user) { if (user != null) { writer.WriteStartElement(customerTag); if (!String.IsNullOrEmpty(user.ID)) { writer.WriteElementString("ram:ID", user.ID); } if (!String.IsNullOrEmpty(user.Name)) { writer.WriteElementString("ram:Name", user.Name); } writer.WriteStartElement("ram:PostalTradeAddress"); writer.WriteElementString("ram:PostcodeCode", user.Postcode); writer.WriteElementString("ram:LineOne", string.IsNullOrEmpty(user.ContactName) ? user.Street : user.ContactName); if (!string.IsNullOrEmpty(user.ContactName)) writer.WriteElementString("ram:LineTwo", user.Street); writer.WriteElementString("ram:CityName", user.City); writer.WriteElementString("ram:CountryID", user.Country.ToString("g")); writer.WriteEndElement(); writer.WriteEndElement(); } } private void WriteHeaderExchangeDocument(XmlTextWriter writer) { #region HeaderExchangedDocument writer.WriteStartElement("rsm:HeaderExchangedDocument"); writer.WriteElementString("ram:ID", InvoiceNumber); writer.WriteElementString("ram:Name", GetInvoiceTypeName(Type)); writer.WriteElementString("ram:TypeCode", String.Format("{0}", GetInvoiceTypeCode(Type))); writer.WriteStartElement("ram:IssueDateTime"); writer.WriteStartElement("udt:DateTimeString"); writer.WriteAttributeString("format", "102"); writer.WriteValue(ConvertDateFormat(InvoiceDate, "102")); writer.WriteEndElement(); writer.WriteEndElement(); // AddNotes(writer, Notes); writer.WriteEndElement(); #endregion } private string ConvertDateFormat(DateTime date, String format = "102") { if (format.Equals("102")) { return date.ToString("yyyymmdd"); } else { return date.ToString("yyyy-MM-ddTHH:mm:ss"); } } private string GetInvoiceTypeName(InvoiceType type) { switch (type) { case InvoiceType.Invoice: return "RECHNUNG"; case InvoiceType.Correction: return "KORREKTURRECHNUNG"; case InvoiceType.CreditNote: return "GUTSCHRIFT"; case InvoiceType.DebitNote: return ""; case InvoiceType.SelfBilledInvoice: return ""; default: return ""; } } private int GetInvoiceTypeCode(InvoiceType type) { if ((int)type > 1000) { type -= 1000; } return (int)type; } private string FormatValue(float value, int numDecimals = 2) { string formatString = "0."; for (int i = 0; i < numDecimals; i++) { formatString += "0"; } return value.ToString(formatString).Replace(",", "."); } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/ErrorBar.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; namespace SampleBrowser { public class ErrorBar : SamplePage { SfChart chart; ErrorBarSeries errorBar; TextView type; List<string> types; TextView mode; List<string> modes; TextView horizontalDirection; List<string> horizonatalDirections; TextView verticalDirection; List<string> verticalDirections; TextView horizontalValue; TextView verticalValue; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Sales Distribution of Car by Region"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); CategoryAxis primaryaxis = new CategoryAxis(); primaryaxis.ShowMajorGridLines = false; primaryaxis.AxisLineOffset = 10; primaryaxis.PlotOffset = 10; primaryaxis.MajorTickStyle.TickSize = 10; primaryaxis.LabelPlacement = LabelPlacement.BetweenTicks; chart.PrimaryAxis = primaryaxis; NumericalAxis secondaryAxis = new NumericalAxis(); secondaryAxis.Minimum = 15; secondaryAxis.Maximum = 45; secondaryAxis.Interval = 5; secondaryAxis.LabelStyle.LabelFormat = "#'%'"; secondaryAxis.LineStyle.StrokeWidth = 0; secondaryAxis.MajorTickStyle.TickSize = 0; chart.SecondaryAxis = secondaryAxis; ScatterSeries scatterSeries = new ScatterSeries(); scatterSeries.ItemsSource = MainPage.GetErrorBarData(); scatterSeries.XBindingPath = "XValue"; scatterSeries.YBindingPath = "YValue"; scatterSeries.ScatterHeight = 20; scatterSeries.ScatterWidth = 20; scatterSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; scatterSeries.ShapeType = ChartScatterShapeType.Ellipse; chart.Series.Add(scatterSeries); errorBar = new ErrorBarSeries(); errorBar.ItemsSource = MainPage.GetErrorBarData(); errorBar.XBindingPath = "XValue"; errorBar.YBindingPath = "YValue"; errorBar.HorizontalErrorPath = "High"; errorBar.VerticalErrorPath = "Low"; errorBar.HorizontalErrorValue = 3; errorBar.VerticalErrorValue = 3; errorBar.Type = ErrorBarType.Fixed; errorBar.Mode = ErrorBarMode.Vertical; chart.Series.Add(errorBar); return chart; } public override View GetPropertyWindowLayout(Android.Content.Context context) { int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; LinearLayout propertylayout = new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams( width * 2, 5); layoutParams1.SetMargins(0, 20, 0, 0); type = new TextView(context); type.Text = "Error Bar Type"; type.SetPadding(5, 20, 0, 20); mode = new TextView(context); mode.Text = "Drawing Mode"; mode.SetPadding(5, 30, 0, 20); horizontalDirection = new TextView(context); horizontalDirection.Text = "Horizontal Direction"; horizontalDirection.SetPadding(5, 30, 0, 20); verticalDirection = new TextView(context); verticalDirection.Text = "Vertical Direction"; verticalDirection.SetPadding(5, 30, 0, 20); horizontalValue = new TextView(context); horizontalValue.Text = "Horizontal Error : 3.0"; horizontalValue.SetPadding(5, 30, 0, 20); verticalValue = new TextView(context); verticalValue.Text = "Vertical Error : 3.0"; verticalValue.SetPadding(5, 20, 0, 20); Spinner errorBarType = new Spinner(context, SpinnerMode.Dialog); Spinner errorBarDrawingMode = new Spinner(context, SpinnerMode.Dialog); errorBarDrawingMode.SetSelection(2); SeekBar errorBarHorizontalError = new SeekBar(context); errorBarHorizontalError.Max = 3; errorBarHorizontalError.Progress = 3; SeekBar errorBarVerticalError = new SeekBar(context); errorBarVerticalError.Max = 3; errorBarVerticalError.Progress = 3; Spinner errorBarHorizontalDirection = new Spinner(context, SpinnerMode.Dialog); Spinner errorBarVerticalDirection = new Spinner(context, SpinnerMode.Dialog); types = new List<string>() { "Fixed", "Custom", "percentage", "StandardDeviation", "StandardErrors" }; modes = new List<string>() { "Both", "Horizontal", "Vertical" }; horizonatalDirections = new List<string> { "Both", "Minus", "Plus" }; verticalDirections = new List<string> { "Both", "Minus", "Plus" }; ArrayAdapter<string> dataAdapter = new ArrayAdapter<string> (context, Android.Resource.Layout.SimpleSpinnerItem, types); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); errorBarType.Adapter = dataAdapter; ArrayAdapter<string> dataAdapter1 = new ArrayAdapter<string> (context, Android.Resource.Layout.SimpleSpinnerItem, modes); dataAdapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); errorBarDrawingMode.Adapter = dataAdapter1; ArrayAdapter<string> dataAdapter2 = new ArrayAdapter<string> (context, Android.Resource.Layout.SimpleSpinnerItem, horizonatalDirections); dataAdapter2.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); errorBarHorizontalDirection.Adapter = dataAdapter2; ArrayAdapter<string> dataAdapter3 = new ArrayAdapter<string> (context, Android.Resource.Layout.SimpleSpinnerItem, verticalDirections); dataAdapter3.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); errorBarVerticalDirection.Adapter = dataAdapter3; errorBarType.ItemSelected += Type_ItemSelected; errorBarDrawingMode.ItemSelected += Mode_ItemSelected; errorBarHorizontalError.ProgressChanged += HorizontalError_ProgressChanged; errorBarVerticalError.ProgressChanged += VerticalError_ProgressChanged; errorBarHorizontalDirection.ItemSelected += HorizontalDirection_ItemSelected; errorBarVerticalDirection.ItemSelected += VerticalDirection_ItemSelected; propertylayout.AddView(type); propertylayout.AddView(errorBarType); propertylayout.AddView(mode); propertylayout.AddView(errorBarDrawingMode); propertylayout.AddView(horizontalValue); propertylayout.AddView(errorBarHorizontalError); propertylayout.AddView(verticalValue); propertylayout.AddView(errorBarVerticalError); propertylayout.AddView(horizontalDirection); propertylayout.AddView(errorBarHorizontalDirection); propertylayout.AddView(verticalDirection); propertylayout.AddView(errorBarVerticalDirection); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); propertylayout.AddView(separate, layoutParams1); return propertylayout; } private void VerticalError_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { double verticalError = 0.0; verticalError = (int)e.Progress; errorBar.VerticalErrorValue = verticalError; verticalValue.Text = "Vertical Error : " + verticalError; } private void HorizontalError_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { double horizontalError = 0.0; horizontalError = (int)e.Progress; errorBar.HorizontalErrorValue = horizontalError; horizontalValue.Text = "Horizontal Error : " + horizontalError; } private void VerticalDirection_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { switch (e.Position) { case 0: errorBar.VerticalDirection = ErrorBarDirection.Both; break; case 1: errorBar.VerticalDirection = ErrorBarDirection.Minus; break; case 2: errorBar.VerticalDirection = ErrorBarDirection.Plus; break; } } private void HorizontalDirection_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { switch (e.Position) { case 0: errorBar.HorizontalDirection = ErrorBarDirection.Both; break; case 1: errorBar.HorizontalDirection = ErrorBarDirection.Minus; break; case 2: errorBar.HorizontalDirection = ErrorBarDirection.Plus; break; } } private void Mode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { switch (e.Position) { case 0: errorBar.Mode = ErrorBarMode.Both; break; case 1: errorBar.Mode = ErrorBarMode.Horizontal; break; case 2: errorBar.Mode = ErrorBarMode.Vertical; break; } } private void Type_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { switch (e.Position) { case 0: errorBar.Type = ErrorBarType.Fixed; break; case 1: errorBar.Type = ErrorBarType.Custom; break; case 2: errorBar.Type = ErrorBarType.Percentage; break; case 3: errorBar.Type = ErrorBarType.StandardDeviation; break; case 4: errorBar.Type = ErrorBarType.StandardErrors; break; } } } } <file_sep>/Forms/XlsIO/XlsIO.UWP/SaveWindows.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="SaveWindows.cs" company=" Syncfusion Inc."> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> #endregion using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using SampleBrowser.XlsIO; using SampleBrowser.XlsIO.UWP; using Windows.Storage; using Windows.Storage.Pickers; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; [assembly: Dependency(typeof(SaveWindows))] namespace SampleBrowser.XlsIO.UWP { [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed.")] /// <summary> /// This class is used to save option for Windows/UWP. /// </summary> internal class SaveWindows : ISaveWindowsPhone { /// <summary> /// This method used to provide save option for Windows/UWP. /// </summary> /// <param name="filename">Name of the output file.</param> /// <param name="contentType">Content type of the output file.</param> /// <param name="stream">output file of MemoryStream.</param> /// <returns>Return Null if the storageFile is null.</returns> public async Task Save(string filename, string contentType, MemoryStream stream) { if (Device.Idiom != TargetIdiom.Desktop) { StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile outFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (Stream outStream = await outFile.OpenStreamForWriteAsync()) { outStream.Write(stream.ToArray(), 0, (int)stream.Length); } if (contentType != "application/html") { await Windows.System.Launcher.LaunchFileAsync(outFile); } } else { StorageFile storageFile = null; FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.Desktop; savePicker.SuggestedFileName = filename; switch (contentType) { case "application/vnd.openxmlformats-officedocument.presentationml.presentation": savePicker.FileTypeChoices.Add("PowerPoint Presentation", new List<string>() { ".pptx", }); break; case "application/msexcel": savePicker.FileTypeChoices.Add("Excel Files", new List<string>() { ".xlsx", }); break; case "application/msword": savePicker.FileTypeChoices.Add("Word Document", new List<string>() { ".docx" }); break; case "application/pdf": savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string>() { ".pdf" }); break; case "application/html": savePicker.FileTypeChoices.Add("HTML Files", new List<string>() { ".html" }); break; case "text/html": savePicker.FileTypeChoices.Add("HTML Files", new List<string>() { ".html" }); break; case "image/png": savePicker.FileTypeChoices.Add("Png Image", new List<string>() { ".png" }); break; case "image/jpeg": savePicker.FileTypeChoices.Add("Jpeg Image", new List<string>() { ".jpeg" }); break; case "application/json": savePicker.FileTypeChoices.Add("json", new List<string>() { ".json" }); break; } storageFile = await savePicker.PickSaveFileAsync(); if (storageFile == null) { return; } using (Stream outStream = await storageFile.OpenStreamForWriteAsync()) { if (outStream.CanSeek) { outStream.SetLength(0); } outStream.Write(stream.ToArray(), 0, (int)stream.Length); outStream.Flush(); outStream.Dispose(); } stream.Flush(); stream.Dispose(); await Windows.System.Launcher.LaunchFileAsync(storageFile); } } } [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed.")] /// <summary> /// This class is used to render the images used in samples. /// </summary> internal class SfImageRenderer : ImageRenderer { /// <summary> /// Initializes a new instance of the <see cref="SfImageRenderer" /> class. /// </summary> public SfImageRenderer() { } [SuppressMessage("StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Justification = "Reviewed.")] /// <summary> /// Method used to dispose class property /// </summary> /// <param name="disposing">TRUE if Element Property Changed</param> protected override void Dispose(bool disposing) { this.Element.PropertyChanged -= OnElementPropertyChanged; base.Dispose(false); } } } <file_sep>/Forms/RichTextEditor/RichTextEditor/Samples/Localization/Localization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.RichTextEditor; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Resources; using System.Text; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfRichTextEditor { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Localization : SampleView { public Localization() { InitializeComponent(); } private void localePicker_SelectedIndexChanged(object sender, EventArgs e) { Picker picker = sender as Picker; string text = ""; if (picker.SelectedItem.Equals("Japanese")) { text = "<p>こんにちは、<br><br>リッチテキストエディターコンポーネントは、コンテンツを作成および更新するための最高のユーザーエクスペリエンスを提供するWYSIWYG(\"あなたが見るものはあなたが得るもの\")エディターです。</p>"; this.ChangedLanguage("ja-JP", text); } if (picker.SelectedItem.Equals("English")) { text = "<p>Hi,<br><br>The rich text editor component is WYSIWYG (\"what you see is what you get\") editor that provides the best user experience to create and update the content.</p>"; this.ChangedLanguage("en-US", text); } if (picker.SelectedItem.Equals("German")) { text = "<p>Hallo,<br><br>Die Rich-Text-Editor-Komponente ist der WYSIWYG-Editor (\"Was Sie sehen, ist was Sie erhalten\"), der die beste Benutzererfahrung beim Erstellen und Aktualisieren des Inhalts bietet.</p>"; this.ChangedLanguage("de-DE", text); } if (picker.SelectedItem.Equals("Spanish")) { text = "<p>Hola,<br><br>El componente del editor de texto enriquecido es el editor WYSIWYG (\"lo que ves es lo que obtienes \") que proporciona la mejor experiencia de usuario para crear y actualizar el contenido.</p>"; this.ChangedLanguage("es-ES", text); } } void ChangedLanguage(string name, string text) { grid.Children.Clear(); #if COMMONSB RichTextEditorResourceManager.Manager = new ResourceManager("SampleBrowser.Samples.RichTextEditor.Resources.Syncfusion.SfRichTextEditor.XForms", Application.Current.GetType().Assembly); #else RichTextEditorResourceManager.Manager = new ResourceManager("SampleBrowser.SfRichTextEditor.Resources.Syncfusion.SfRichTextEditor.XForms", Application.Current.GetType().Assembly); #endif if (Device.RuntimePlatform != Device.UWP) { Thread.CurrentThread.CurrentUICulture = new CultureInfo(name); } else { CultureInfo.CurrentUICulture = new CultureInfo(name); } Syncfusion.XForms.RichTextEditor.SfRichTextEditor sfRichTextEditor = new Syncfusion.XForms.RichTextEditor.SfRichTextEditor(); sfRichTextEditor.ToolbarOptions = ToolbarOptions.Alignment | ToolbarOptions.Bold | ToolbarOptions.BulletList | ToolbarOptions.ClearFormat | ToolbarOptions.DecreaseIndent | ToolbarOptions.FontColor | ToolbarOptions.FontSize | ToolbarOptions.HighlightColor | ToolbarOptions.Hyperlink | ToolbarOptions.IncreaseIndent | ToolbarOptions.Italic | ToolbarOptions.NumberList | ToolbarOptions.ParagraphFormat | ToolbarOptions.Redo | ToolbarOptions.Underline | ToolbarOptions.Undo; sfRichTextEditor.VerticalOptions = LayoutOptions.FillAndExpand; sfRichTextEditor.HorizontalOptions = LayoutOptions.FillAndExpand; sfRichTextEditor.Text = text; grid.Children.Add(sfRichTextEditor); } } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/Model/OrderInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "OrderInfoRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class used to assign collection values for a Model properties /// </summary> public class OrderInfoRepository { #region private variables /// <summary> /// Instance of the random data generator. /// </summary> private readonly Random random = new Random(); #endregion #region MainGrid DataSource /// <summary> /// Holds the data for CustomerID. /// </summary> private readonly string[] customerID = { "Alfki", "Frans", "Merep", "Folko", "Simob", "Warth", "Vaffe", "Furib", "Seves", "Linod", "Riscu", "Picco", "Blonp", "Welli", "Folig" }; /// <summary> /// Holds the data for ShipCountry. /// </summary> private readonly string[] shipCountry = { "Argentina", "Austria", "Belgium", "Brazil", "Canada", "Denmark", "Finland", "France", "Germany", "Ireland", "Italy", "Mexico", "Norway", "Poland", "Portugal", "Spain", "Sweden", "UK", "USA" }; #endregion #region GetOrderDetails /// <summary> /// Used to assign the Collection values to Model Properties. /// </summary> /// <param name="count">record rows count</param> /// <returns> added orderDetails items </returns> public ObservableCollection<OrderInfo> GetOrderDetails(int count) { var orderDetails = new ObservableCollection<OrderInfo>(); for (var i = 10001; i <= count + 10000; i++) { var ord = new OrderInfo { OrderID = i.ToString(), CustomerID = this.customerID[this.random.Next(15)], EmployeeID = this.random.Next(1700, 1800).ToString(), ShipCountry = this.shipCountry[this.random.Next(5)] }; orderDetails.Add(ord); } return orderDetails; } #endregion } }<file_sep>/iOS/SampleBrowser/Resources/Samples/ComboBox/ComboBox_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.iOS.ComboBox; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class ComboBox_Mobile:SampleView { NSMutableArray sizeDetails = new NSMutableArray(); UILabel isEditableLabel,diacriticModeLabel,comboBoxModeLabel,sizeLabel,textColorLabel,backColorLabel,waterMarkLabel,spaceLabel; UIButton comboBoxButton = new UIButton (); UIButton sizeButton = new UIButton(); UIButton textColorButton, backColorButton; UIButton suggestionDoneButton=new UIButton(); UIPickerView suggestionModePicker, comboBoxModePicker,sizePicker,textColorPicker,backColorPicker; UITextView waterMarkText; private string selectedType; private readonly IList<string> exp = new List<string> (); private string experienceSelectedType; SfComboBox sizeComboBox,resolutionComboBox,orientationComboBox; UILabel comboBoxHeaderLabel,sizetextLabel,resolutionLabel,orientationLabel; UISwitch isEditableSwitch, diacriticsSwitch; UIButton comboBoxDoneButton = new UIButton (); UIButton sizeDoneButton, textColorDoneButton, backColorDoneButton; NSMutableArray jobTitle = new NSMutableArray (); NSMutableArray resolutionDetails = new NSMutableArray(); NSMutableArray orientationDetails = new NSMutableArray(); PickerModel comboBoxModel,sizeModel,textColorModel,backColorModel; public UIView option = new UIView(); UIView controlView = new UIView(); UIScrollView propertyScrollView; private readonly IList<string> comboBoxModeList = new List<string>{ "Append", "Suggest", "SuggestAppend" }; private readonly IList<string> sizeList = new List<string>{ "Small", "Medium", "Large" }; private readonly IList<string> textColorList = new List<string>{ "Black", "Blue", "Red", "Yellow" }; private readonly IList<string> backColorList = new List<string>{ "Transparent", "Blue", "Red", "Yellow" }; public void createOptionView() { propertyScrollView = new UIScrollView(); propertyScrollView.Frame = this.OptionView.Frame; propertyScrollView.ContentSize = new CGSize(propertyScrollView.Frame.Width,propertyScrollView.Frame.Height+120); this.propertyScrollView.AddSubview (textColorLabel); this.propertyScrollView.AddSubview (backColorLabel); this.propertyScrollView.AddSubview(waterMarkLabel); this.propertyScrollView.AddSubview(spaceLabel); this.propertyScrollView.AddSubview (sizeButton); this.propertyScrollView.AddSubview (textColorButton); this.propertyScrollView.AddSubview(backColorButton); this.propertyScrollView.AddSubview (waterMarkText); this.propertyScrollView.AddSubview (isEditableLabel); this.propertyScrollView.AddSubview(diacriticModeLabel); this.propertyScrollView.AddSubview(diacriticsSwitch); this.propertyScrollView.AddSubview(isEditableSwitch); this.propertyScrollView.AddSubview (comboBoxModeLabel); this.propertyScrollView.AddSubview (sizeLabel); this.propertyScrollView.AddSubview (comboBoxButton); this.propertyScrollView.AddSubview (suggestionModePicker); this.propertyScrollView.AddSubview (comboBoxModePicker); this.propertyScrollView.AddSubview(sizePicker); this.propertyScrollView.AddSubview(textColorPicker); this.propertyScrollView.AddSubview(backColorPicker); this.propertyScrollView.AddSubview (suggestionDoneButton); this.propertyScrollView.AddSubview(comboBoxDoneButton); this.propertyScrollView.AddSubview(sizeDoneButton); this.propertyScrollView.AddSubview(textColorDoneButton); this.propertyScrollView.AddSubview(backColorDoneButton); this.option.AddSubview(propertyScrollView); } public ComboBox_Mobile() { mainPageDesign(); //sizeComboBox sizeComboBox = new SfComboBox(); sizeComboBox.ComboBoxSource = sizeDetails ; sizeComboBox.IsEditable = false; sizeComboBox.Text = (NSString)"150%(Recommended)"; sizeComboBox.SuggestionMode = SuggestionMode.StartsWith; sizeComboBox.MaxDropDownHeight=160; sizeComboBox.ItemHeight = 40; sizeComboBox.DropDownCornerRadius = 5; sizeComboBox.Watermark = (NSString)"Search Here"; //resolutionComboBox resolutionComboBox = new SfComboBox(); resolutionComboBox.IsEditable = false; resolutionComboBox.MaxDropDownHeight = 160; resolutionComboBox.ItemHeight = 40; resolutionComboBox.DropDownCornerRadius = 5; resolutionComboBox.Text = (NSString)"1920 x 1080 (Recommended)"; resolutionComboBox.ComboBoxSource = resolutionDetails; resolutionComboBox.SuggestionMode = SuggestionMode.StartsWith; resolutionComboBox.Watermark = (NSString)"Search Here"; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.controlView.AddSubview(sizeComboBox); this.controlView.AddSubview(resolutionComboBox); this.AddSubview(controlView); } else { this.AddSubview(sizeComboBox); this.AddSubview(resolutionComboBox); } loadOptionView(); } public void mainPageDesign() { this.OptionView = new UIView(); controlView = new UIView(); this.addingSourceList(); isEditableSwitch = new UISwitch(); diacriticsSwitch = new UISwitch(); suggestionModePicker = new UIPickerView(); comboBoxModePicker = new UIPickerView(); sizePicker = new UIPickerView(); textColorPicker = new UIPickerView(); backColorPicker = new UIPickerView(); sizeDoneButton = new UIButton(); textColorDoneButton = new UIButton(); backColorDoneButton = new UIButton(); comboBoxModel = new PickerModel(comboBoxModeList); comboBoxModePicker.Model = comboBoxModel; comboBoxModePicker.Select(1,0,false); sizeModel = new PickerModel(sizeList); sizePicker.Model = sizeModel; sizePicker.Select(2, 0, false); textColorModel = new PickerModel(textColorList); textColorPicker.Model = textColorModel; textColorPicker.Select(0, 0, false); backColorModel = new PickerModel(backColorList); backColorPicker.Model = backColorModel; backColorPicker.Select(0, 0, false); isEditableLabel = new UILabel(); diacriticModeLabel = new UILabel(); comboBoxModeLabel = new UILabel(); sizeLabel = new UILabel(); textColorLabel = new UILabel(); backColorLabel = new UILabel(); waterMarkLabel = new UILabel(); spaceLabel = new UILabel(); comboBoxButton = new UIButton(); sizeButton = new UIButton(); textColorButton = new UIButton(); backColorButton = new UIButton(); comboBoxHeaderLabel = new UILabel(); sizetextLabel = new UILabel(); resolutionLabel = new UILabel(); orientationLabel = new UILabel(); //searchButton = new UIButton(); //comboBoxHeaderLabell comboBoxHeaderLabel.Text = "Scale And Layout"; comboBoxHeaderLabel.TextColor = UIColor.Black; comboBoxHeaderLabel.TextAlignment = UITextAlignment.Left; comboBoxHeaderLabel.Font = UIFont.FromName("Helvetica-Bold", 15f); //sizetextLabell sizetextLabel.Text = "Change the size of text, apps and other items"; sizetextLabel.Lines = 2; sizetextLabel.LineBreakMode = UILineBreakMode.WordWrap; sizetextLabel.TextColor = UIColor.Black; sizetextLabel.TextAlignment = UITextAlignment.Left; sizetextLabel.Font = UIFont.FromName("Helvetica", 16f); //resolutionLabell resolutionLabel.Text = "Resolution"; resolutionLabel.TextColor = UIColor.Black; resolutionLabel.TextAlignment = UITextAlignment.Left; resolutionLabel.Font = UIFont.FromName("Helvetica", 16f); //orientationLabell orientationLabel.Text = "Orientation"; orientationLabel.TextColor = UIColor.Black; orientationLabel.TextAlignment = UITextAlignment.Left; orientationLabel.Font = UIFont.FromName("Helvetica", 16f); //experienceButtonn orientationComboBox = new SfComboBox(); orientationComboBox.ComboBoxSource = orientationDetails; orientationComboBox.IsEditable = false; orientationComboBox.Text = (NSString)"Landscape"; orientationComboBox.SuggestionMode = SuggestionMode.StartsWith; orientationComboBox.MaxDropDownHeight = 160; orientationComboBox.ItemHeight = 40; orientationComboBox.DropDownCornerRadius = 5; orientationComboBox.Watermark = (NSString)"Search Here"; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.controlView.AddSubview(orientationComboBox); } else { this.AddSubview(orientationComboBox); } //comboBoxDoneButtonn comboBoxDoneButton.SetTitle("Done\t", UIControlState.Normal); comboBoxDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; comboBoxDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); comboBoxDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); comboBoxDoneButton.Hidden = true; comboBoxDoneButton.TouchUpInside += HideexperiencePicker; sizeDoneButton.SetTitle("Done\t", UIControlState.Normal); sizeDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; sizeDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); sizeDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); sizeDoneButton.Hidden = true; sizeDoneButton.TouchUpInside += HideexperiencePicker; textColorDoneButton.SetTitle("Done\t", UIControlState.Normal); textColorDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; textColorDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); textColorDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); textColorDoneButton.Hidden = true; textColorDoneButton.TouchUpInside += HideexperiencePicker; backColorDoneButton.SetTitle("Done\t", UIControlState.Normal); backColorDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; backColorDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); backColorDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); backColorDoneButton.Hidden = true; backColorDoneButton.TouchUpInside += HideexperiencePicker; //add vieww if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.controlView.AddSubview(comboBoxDoneButton); this.controlView.AddSubview(sizeDoneButton); this.controlView.AddSubview(textColorDoneButton); this.controlView.AddSubview(backColorDoneButton); this.controlView.AddSubview(comboBoxHeaderLabel); this.controlView.AddSubview(sizetextLabel); this.controlView.AddSubview(resolutionLabel); this.controlView.AddSubview(orientationLabel); } else { this.AddSubview(comboBoxDoneButton); this.AddSubview(sizeDoneButton); this.AddSubview(textColorDoneButton); this.AddSubview(backColorDoneButton); this.AddSubview(comboBoxHeaderLabel); this.AddSubview(sizetextLabel); this.AddSubview(resolutionLabel); this.AddSubview(orientationLabel); } } public void loadOptionView() { //isEditableLabell isEditableLabel.Text = "IsEditable"; isEditableLabel.TextColor = UIColor.Black; isEditableLabel.TextAlignment = UITextAlignment.Left; isEditableLabel.Font = UIFont.FromName("Helvetica", 14f); isEditableSwitch.ValueChanged += IsEditableSwitch_ValueChanged; diacriticModeLabel.Text = "Enable Diacritics"; diacriticModeLabel.TextColor = UIColor.Black; diacriticModeLabel.TextAlignment = UITextAlignment.Left; diacriticModeLabel.Font = UIFont.FromName("Helvetica", 14f); diacriticsSwitch.ValueChanged += DiacriticsSwitch_ValueChanged; isEditableSwitch.ValueChanged += IsEditableSwitch_ValueChanged; comboBoxModeLabel.Text = "ComboBox Mode"; comboBoxModeLabel.TextColor = UIColor.Black; comboBoxModeLabel.TextAlignment = UITextAlignment.Left; comboBoxModeLabel.Font = UIFont.FromName("Helvetica", 14f); //sizeLabell sizeLabel.Text = "Size"; sizeLabel.TextColor = UIColor.Black; sizeLabel.TextAlignment = UITextAlignment.Left; sizeLabel.Font = UIFont.FromName("Helvetica", 14f); //textColorLabell textColorLabel.Text = "Text Color"; textColorLabel.TextColor = UIColor.Black; textColorLabel.TextAlignment = UITextAlignment.Left; textColorLabel.Font = UIFont.FromName("Helvetica", 14f); //backColorLabel backColorLabel.Text = "Back Color"; backColorLabel.TextColor = UIColor.Black; backColorLabel.TextAlignment = UITextAlignment.Left; backColorLabel.Font = UIFont.FromName("Helvetica", 14f); waterMarkLabel.Text = "WaterMark"; waterMarkLabel.TextColor = UIColor.Black; waterMarkLabel.TextAlignment = UITextAlignment.Left; waterMarkLabel.Font = UIFont.FromName("Helvetica", 14f); spaceLabel.Text = ""; //Text waterMarkText = new UITextView(); waterMarkText.Layer.BorderColor = UIColor.Black.CGColor; waterMarkText.BackgroundColor = UIColor.FromRGB(246, 246, 246); waterMarkText.KeyboardType = UIKeyboardType.Default; waterMarkText.Text = "Search Here"; waterMarkText.Changed += (object sender, EventArgs e) => { if (waterMarkText.Text.Length > 0) { sizeComboBox.Watermark = (NSString)waterMarkText.Text; resolutionComboBox.Watermark = (NSString)waterMarkText.Text; orientationComboBox.Watermark = (NSString)waterMarkText.Text; } else { sizeComboBox.Watermark = (NSString)""; resolutionComboBox.Watermark = (NSString)""; orientationComboBox.Watermark = (NSString)""; } }; //comboBoxButton comboBoxButton.SetTitle("Suggest", UIControlState.Normal); comboBoxButton.SetTitleColor(UIColor.Black, UIControlState.Normal); comboBoxButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; comboBoxButton.Layer.CornerRadius = 8; comboBoxButton.Layer.BorderWidth = 2; comboBoxButton.TouchUpInside += ShowcomboBoxModePicker; comboBoxButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //SizeButton sizeButton.SetTitle("Large", UIControlState.Normal); sizeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); sizeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; sizeButton.Layer.CornerRadius = 8; sizeButton.Layer.BorderWidth = 2; sizeButton.TouchUpInside += ShowsizePicker; sizeButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; textColorButton.SetTitle("Black", UIControlState.Normal); textColorButton.SetTitleColor(UIColor.Black, UIControlState.Normal); textColorButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; textColorButton.Layer.CornerRadius = 8; textColorButton.Layer.BorderWidth = 2; textColorButton.TouchUpInside += ShowtextColorPicker; textColorButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; backColorButton.SetTitle("Transparent", UIControlState.Normal); backColorButton.SetTitleColor(UIColor.Black, UIControlState.Normal); backColorButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; backColorButton.Layer.CornerRadius = 8; backColorButton.Layer.BorderWidth = 2; backColorButton.TouchUpInside += ShowbackColorPicker; backColorButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; comboBoxModel.PickerChanged += comboBoxSelectedIndexChanged; sizeModel.PickerChanged += sizeSelectedIndexChanged; textColorModel.PickerChanged += textColorSelectedIndexChanged; backColorModel.PickerChanged += backColorSelectedIndexChanged; suggestionModePicker.ShowSelectionIndicator = true; suggestionModePicker.Hidden = true; suggestionModePicker.BackgroundColor = UIColor.Gray; comboBoxModePicker.BackgroundColor = UIColor.Gray; comboBoxModePicker.ShowSelectionIndicator = true; comboBoxModePicker.Hidden = true; sizePicker.BackgroundColor = UIColor.Gray; sizePicker.ShowSelectionIndicator = true; sizePicker.Hidden = true; textColorPicker.BackgroundColor = UIColor.Gray; textColorPicker.ShowSelectionIndicator = true; textColorPicker.Hidden = true; backColorPicker.BackgroundColor = UIColor.Gray; backColorPicker.ShowSelectionIndicator = true; backColorPicker.Hidden = true; } private void ShowcomboBoxModePicker(object sender, EventArgs e) { waterMarkText.EndEditing(true); comboBoxModePicker.Hidden = false; comboBoxDoneButton.Hidden = false; sizePicker.Hidden = true; textColorPicker.Hidden = true; backColorPicker.Hidden = true; } private void ShowbackColorPicker(object sender, EventArgs e) { waterMarkText.EndEditing(true); comboBoxModePicker.Hidden = true; textColorPicker.Hidden = true; backColorPicker.Hidden = false; backColorDoneButton.Hidden = false; sizePicker.Hidden = true; } private void ShowtextColorPicker(object sender, EventArgs e) { waterMarkText.EndEditing(true); comboBoxModePicker.Hidden = true; textColorPicker.Hidden = false; textColorDoneButton.Hidden = false; backColorPicker.Hidden = true; sizePicker.Hidden = true; } private void ShowsizePicker(object sender, EventArgs e) { waterMarkText.EndEditing(true); sizePicker.Hidden = false; sizeDoneButton.Hidden = false; comboBoxModePicker.Hidden = true; textColorPicker.Hidden = true; backColorPicker.Hidden = true; } private void IsEditableSwitch_ValueChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { orientationComboBox.IsEditable = true; resolutionComboBox.IsEditable = true; sizeComboBox.IsEditable = true; } else { orientationComboBox.IsEditable = false; resolutionComboBox.IsEditable = false; sizeComboBox.IsEditable = false; } } void DiacriticsSwitch_ValueChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { orientationComboBox.IgnoreDiacritic = true; resolutionComboBox.IgnoreDiacritic = true; sizeComboBox.IgnoreDiacritic = true; } else { orientationComboBox.IgnoreDiacritic = false; resolutionComboBox.IgnoreDiacritic = false; sizeComboBox.IgnoreDiacritic = false; } } public void addingSourceList() { sizeDetails.Add((NSString)"100%"); sizeDetails.Add((NSString)"125%"); sizeDetails.Add((NSString)"150%(Recommended)"); sizeDetails.Add((NSString)"175%"); resolutionDetails.Add((NSString)"1920 x 1080 (Recommended)"); resolutionDetails.Add((NSString)"1680 x 1050"); resolutionDetails.Add((NSString)"1600 x 900"); resolutionDetails.Add((NSString)"1440 x 900"); resolutionDetails.Add((NSString)"1400 x 1050"); resolutionDetails.Add((NSString)"1366 x 768"); resolutionDetails.Add((NSString)"1360 x 768"); resolutionDetails.Add((NSString)"1280 x 1024"); resolutionDetails.Add((NSString)"1280 x 960"); resolutionDetails.Add((NSString)"1280 x 720"); resolutionDetails.Add((NSString)"854 x 480"); resolutionDetails.Add((NSString)"800 x 480"); resolutionDetails.Add((NSString)"480 X 640"); resolutionDetails.Add((NSString)"480 x 320"); resolutionDetails.Add((NSString)"432 x 240"); resolutionDetails.Add((NSString)"360 X 640"); resolutionDetails.Add((NSString)"320 x 240"); orientationDetails.Add((NSString)"Landscape"); orientationDetails.Add((NSString)"Portrait"); orientationDetails.Add((NSString)"Landscape (flipped)"); orientationDetails.Add((NSString)"Portrait (flipped)"); } public override void TouchesBegan (NSSet touches, UIEvent evt) { this.EndEditing (true); } void HideexperiencePicker (object sender, EventArgs e) { comboBoxDoneButton.Hidden = true; comboBoxModePicker.Hidden = true; sizePicker.Hidden = true; sizeDoneButton.Hidden = true; textColorPicker.Hidden = true; textColorDoneButton.Hidden = true; backColorPicker.Hidden = true; backColorDoneButton.Hidden = true; this.BecomeFirstResponder (); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; this.OptionView.Frame = view.Frame; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { controlView.Frame = new CGRect(150, 40, view.Frame.Size.Width - 300, view.Frame.Size.Height - 40); isEditableLabel.Frame = new CGRect(10, 10, this.Frame.Size.Width - 10, 30); diacriticModeLabel.Frame = new CGRect(10, 60, this.Frame.Size.Width - 10, 30); isEditableSwitch.Frame = new CGRect(200, 10, this.Frame.Size.Width - 10, 30); diacriticsSwitch.Frame = new CGRect(200, 60, this.Frame.Size.Width - 10, 30); comboBoxModeLabel.Frame = new CGRect(10, 110, this.Frame.Size.Width - 20, 30); comboBoxButton.Frame = new CGRect(10, 150, 300, 30); comboBoxModePicker.Frame = new CGRect(0, this.Frame.Size.Height / 4, 350, this.Frame.Size.Height / 3); sizeLabel.Frame = new CGRect(10, 190, this.Frame.Size.Width - 10, 30); sizeButton.Frame = new CGRect(10, 220, 300, 30); sizePicker.Frame = new CGRect(0, this.Frame.Size.Height / 4, 350, this.Frame.Size.Height / 3); textColorLabel.Frame = new CGRect(10, 270, this.Frame.Size.Width - 10, 30); textColorButton.Frame = new CGRect(10, 300, 300, 30); textColorPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4, 350, this.Frame.Size.Height / 3); backColorLabel.Frame = new CGRect(10, 350, this.Frame.Size.Width - 10, 30); backColorButton.Frame = new CGRect(10, 380, 300, 30); backColorPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4, 350, this.Frame.Size.Height / 3); waterMarkLabel.Frame = new CGRect(10, 430, this.Frame.Size.Width - 10, 30); waterMarkText.Frame = new CGRect(150, 430, 300, 30); spaceLabel.Frame = new CGRect(10, 510, this.Frame.Size.Width - 10, 30); suggestionDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4, this.Frame.Size.Width, 30); comboBoxHeaderLabel.Frame = new CGRect(10, 10, controlView.Frame.Width, 30); sizetextLabel.Frame = new CGRect(10, 50, controlView.Frame.Width, 30); resolutionLabel.Frame = new CGRect(10, 130, controlView.Frame.Width, 30); orientationLabel.Frame = new CGRect(10, 210, controlView.Frame.Width, 30); sizeComboBox.Frame = new CGRect(10, 80, controlView.Frame.Size.Width - 20, 40); resolutionComboBox.Frame = new CGRect(10, 160, controlView.Frame.Size.Width - 20, 40); orientationComboBox.Frame = new CGRect(10, 240, controlView.Frame.Size.Width - 20, 40); comboBoxDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4, 325, 40); sizeDoneButton.Frame = new CGRect(0, this.Frame.Size.Height /4 , 325, 40); textColorDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4, 325, 40); backColorDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4, 325, 40); } else { option.Frame = new CGRect(0, 40, Frame.Width, Frame.Height); isEditableLabel.Frame = new CGRect(10, 10, this.Frame.Size.Width - 10, 30); diacriticModeLabel.Frame = new CGRect(10, 60, this.Frame.Size.Width - 10, 30); isEditableSwitch.Frame = new CGRect(200, 10, this.Frame.Size.Width - 10, 30); diacriticsSwitch.Frame = new CGRect(200, 60, this.Frame.Size.Width - 10, 30); comboBoxModeLabel.Frame = new CGRect(10, 110, this.Frame.Size.Width - 20, 30); comboBoxButton.Frame = new CGRect(10, 150, this.Frame.Size.Width - 20, 30); comboBoxModePicker.Frame = new CGRect(0, this.Frame.Size.Height / 4, this.Frame.Size.Width, this.Frame.Size.Height / 3); sizeLabel.Frame = new CGRect(10, 190, this.Frame.Size.Width - 10, 30); sizeButton.Frame = new CGRect(10, 220, this.Frame.Size.Width - 20, 30); sizePicker.Frame = new CGRect(0, this.Frame.Size.Height / 4, this.Frame.Size.Width, this.Frame.Size.Height / 3); textColorLabel.Frame = new CGRect(10, 270, this.Frame.Size.Width - 10, 30); textColorButton.Frame = new CGRect(10, 300, this.Frame.Size.Width - 20, 30); textColorPicker.Frame = new CGRect(0, this.Frame.Size.Height / 3, this.Frame.Size.Width, this.Frame.Size.Height / 3); backColorLabel.Frame = new CGRect(10, 350, this.Frame.Size.Width - 10, 30); backColorButton.Frame = new CGRect(10, 380, this.Frame.Size.Width - 20, 30); backColorPicker.Frame = new CGRect(0, this.Frame.Size.Height / 2, this.Frame.Size.Width, this.Frame.Size.Height / 3); waterMarkLabel.Frame = new CGRect(10, 430, this.Frame.Size.Width - 10, 30); waterMarkText.Frame = new CGRect(150, 430, this.Frame.Size.Width - 20, 30); spaceLabel.Frame = new CGRect(10, 510, this.Frame.Size.Width - 10, 30); suggestionDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4, this.Frame.Size.Width, 30); comboBoxHeaderLabel.Frame = new CGRect(10, 10, view.Frame.Width, 30); sizetextLabel.Frame = new CGRect(10, 50, view.Frame.Width, 30); resolutionLabel.Frame = new CGRect(10, 130, view.Frame.Width, 30); orientationLabel.Frame = new CGRect(10, 210, view.Frame.Width, 30); sizeComboBox.Frame = new CGRect(10, 80, this.Frame.Size.Width - 20, 40); resolutionComboBox.Frame = new CGRect(10, 160, this.Frame.Size.Width - 20, 40); orientationComboBox.Frame = new CGRect(10, 240, this.Frame.Size.Width - 20, 40); comboBoxDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4, this.Frame.Size.Width, 40); sizeDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4, this.Frame.Size.Width, 40); textColorDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 3, this.Frame.Size.Width, 40); backColorDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 2, this.Frame.Size.Width, 40); } } this.createOptionView (); base.LayoutSubviews (); } private void comboBoxSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; comboBoxButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Append") { sizeComboBox.ComboBoxMode = ComboBoxMode.Append; resolutionComboBox.ComboBoxMode = ComboBoxMode.Append; orientationComboBox.ComboBoxMode = ComboBoxMode.Append; } else if (selectedType == "Suggest") { sizeComboBox.ComboBoxMode = ComboBoxMode.Suggest; resolutionComboBox.ComboBoxMode = ComboBoxMode.Suggest; orientationComboBox.ComboBoxMode = ComboBoxMode.Append; } else if (selectedType == "SuggestAppend") { sizeComboBox.ComboBoxMode = ComboBoxMode.SuggestAppend; resolutionComboBox.ComboBoxMode = ComboBoxMode.SuggestAppend; orientationComboBox.ComboBoxMode = ComboBoxMode.Append; } } private void sizeSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; sizeButton.SetTitle(selectedType, UIControlState.Normal); if (selectedType == "Small") { sizeComboBox.TextSize = 13; resolutionComboBox.TextSize = 13; orientationComboBox.TextSize = 13; comboBoxHeaderLabel.Font = UIFont.SystemFontOfSize(13f); sizetextLabel.Font = UIFont.SystemFontOfSize(13f); resolutionLabel.Font = UIFont.SystemFontOfSize(13f); orientationLabel.Font = UIFont.SystemFontOfSize(13f); } else if (selectedType == "Medium") { sizeComboBox.TextSize = 15; resolutionComboBox.TextSize = 15; orientationComboBox.TextSize = 15; comboBoxHeaderLabel.Font = UIFont.SystemFontOfSize(15f); sizetextLabel.Font = UIFont.SystemFontOfSize(15f); resolutionLabel.Font = UIFont.SystemFontOfSize(15f); orientationLabel.Font = UIFont.SystemFontOfSize(15f); } else if (selectedType == "Large") { sizeComboBox.TextSize = 17; resolutionComboBox.TextSize = 17; orientationComboBox.TextSize = 17; comboBoxHeaderLabel.Font = UIFont.SystemFontOfSize(17f); sizetextLabel.Font = UIFont.SystemFontOfSize(17f); resolutionLabel.Font = UIFont.SystemFontOfSize(17f); orientationLabel.Font = UIFont.SystemFontOfSize(17f); } } private void textColorSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; textColorButton.SetTitle(selectedType, UIControlState.Normal); if (selectedType == "Black") { sizeComboBox.TextColor = UIColor.Black; resolutionComboBox.TextColor = UIColor.Black; orientationComboBox.TextColor = UIColor.Black; } else if (selectedType == "Blue") { sizeComboBox.TextColor = UIColor.Blue; resolutionComboBox.TextColor = UIColor.Blue; orientationComboBox.TextColor = UIColor.Blue; } else if (selectedType == "Red") { sizeComboBox.TextColor = UIColor.Red; resolutionComboBox.TextColor = UIColor.Red; orientationComboBox.TextColor = UIColor.Red; } else if (selectedType == "Yellow") { sizeComboBox.TextColor = UIColor.Yellow; resolutionComboBox.TextColor = UIColor.Yellow; orientationComboBox.TextColor = UIColor.Yellow; } } private void backColorSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; backColorButton.SetTitle(selectedType, UIControlState.Normal); if (selectedType == "Transparent") { sizeComboBox.BackgroundColor = UIColor.Clear; resolutionComboBox.BackgroundColor = UIColor.Clear; orientationComboBox.BackgroundColor = UIColor.Clear; this.BackgroundColor = UIColor.Clear; } else if (selectedType == "Blue") { sizeComboBox.BackgroundColor = UIColor.Blue; resolutionComboBox.BackgroundColor = UIColor.Blue; orientationComboBox.BackgroundColor = UIColor.Blue; this.BackgroundColor = UIColor.Blue; } else if (selectedType == "Red") { sizeComboBox.BackgroundColor = UIColor.Red; resolutionComboBox.BackgroundColor = UIColor.Red; orientationComboBox.BackgroundColor = UIColor.Red; this.BackgroundColor = UIColor.Red; } else if (selectedType == "Yellow") { sizeComboBox.BackgroundColor = UIColor.Yellow; resolutionComboBox.BackgroundColor = UIColor.Yellow; orientationComboBox.BackgroundColor = UIColor.Yellow; this.BackgroundColor = UIColor.Yellow; } } } } <file_sep>/Android/SampleBrowser/Samples/RangeNavigator/RangeNavigator.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Com.Syncfusion.Rangenavigator; using Java.Util; namespace SampleBrowser { public class RangeNavigator : SamplePage { SfChart chartTop; public override View GetSampleContent(Context context) { LayoutInflater layoutInflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService); View view = layoutInflater.Inflate(Resource.Layout.range_navigator_getting_Started, null); chartTop = view.FindViewById<SfChart>(Resource.Id.TopChart); UpdateChart(chartTop, Visibility.Visible); SfDateTimeRangeNavigator sfRangeNavigator = view.FindViewById<SfDateTimeRangeNavigator>(Resource.Id.RangeNavigator); Calendar min = new GregorianCalendar(2015, 0, 1); Calendar max = new GregorianCalendar(2015, 11, 31); sfRangeNavigator.Minimum = min.Time; sfRangeNavigator.Maximum = max.Time; Calendar visibleMinimum = new GregorianCalendar(2015, 4, 1); Calendar visibleMaximum = new GregorianCalendar(2015, 7, 1); sfRangeNavigator.ViewRangeStart = visibleMinimum.Time; sfRangeNavigator.ViewRangeEnd = visibleMaximum.Time; View contentView = sfRangeNavigator.Content; SfChart sfchart = new SfChart(context) { PrimaryAxis = new DateTimeAxis() { Visibility = Visibility.Gone, ShowMajorGridLines = false }, SecondaryAxis = new NumericalAxis() { Visibility = Visibility.Gone, ShowMajorGridLines = false } }; sfchart.Series.Add(new SplineAreaSeries() { ItemsSource = MainPage.GetDateTimeValue(), XBindingPath = "Date", YBindingPath = "YValue", Alpha = 0.5f }); sfRangeNavigator.Content = sfchart; sfRangeNavigator.RangeChanged += sfRangeNavigator_RangeChanged; return view; } void sfRangeNavigator_RangeChanged(object sender, SfDateTimeRangeNavigator.RangeChangedEventArgs e) { ((DateTimeAxis)chartTop.PrimaryAxis).Minimum = e.ViewRangeStart; ((DateTimeAxis)chartTop.PrimaryAxis).Maximum = e.ViewRangeEnd; } SfChart UpdateChart(SfChart chart, Visibility axisVisibility) { DateTimeAxis dateTimeAxis = new DateTimeAxis(); dateTimeAxis.Visibility = axisVisibility; dateTimeAxis.LabelStyle.LabelFormat = "dd/MMM"; dateTimeAxis.ShowMajorGridLines = axisVisibility == Visibility.Visible ? true : false; chart.PrimaryAxis = dateTimeAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Visibility = axisVisibility; numericalAxis.ShowMajorGridLines = axisVisibility == Visibility.Visible ? true : false; chart.SecondaryAxis = numericalAxis; chart.Series.Add(new SplineAreaSeries() { ItemsSource = MainPage.GetDateTimeValue(), XBindingPath = "Date", YBindingPath = "YValue", Alpha = 0.5f }); return chart; } } }<file_sep>/Android/SampleBrowser/Samples/Calculate/FunctionsLibrary.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Views.InputMethods; using Syncfusion.Calculate; namespace SampleBrowser { public class FunctionsLibrary : SamplePage, IDisposable { #region Fields private ScrollView scrollView; private EditText formulaEdit; private TextViewExt computedValueEdit; private EditText txtA1; private EditText txtA2; private EditText txtA3; private EditText txtA4; private EditText txtA5; private EditText txtB1; private EditText txtB2; private EditText txtB3; private EditText txtB4; private EditText txtB5; private EditText txtC1; private EditText txtC2; private EditText txtC3; private EditText txtC4; private EditText txtC5; private Context context; private CalcData calcData; private CalcEngine engine; #endregion public override View GetSampleContent(Context context) { this.context = context; InitializeEngine(); CreateFunctionLibraryDesign(context); return scrollView; } #region Private Methods private void CreateFunctionLibraryDesign(Context context) { int width = (int)(context.Resources.DisplayMetrics.WidthPixels - context.Resources.DisplayMetrics.Density); scrollView = new ScrollView(context); scrollView.SetPadding(10, 10, 10, 20); LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; linearLayout.Focusable = true; linearLayout.FocusableInTouchMode = true; linearLayout.SetPadding(10, 10, 10, 10); LinearLayout linearLayout1 = new LinearLayout(context); linearLayout1.Orientation = Orientation.Vertical; TextView titleText = new TextView(context) { Text = "Functions Library", TextAlignment = TextAlignment.Center, Gravity = GravityFlags.Center, TextSize = 30 }; titleText.SetTypeface(null, TypefaceStyle.Bold); titleText.SetWidth(width); TextView descText = new TextView(context) { Text = "This sample demonstrates the calculation using various Excel-like functions.", TextAlignment = TextAlignment.TextStart, Gravity = GravityFlags.FillHorizontal, TextSize = 12 }; descText.SetPadding(0, 10, 0, 0); descText.SetWidth(width); linearLayout1.AddView(titleText); linearLayout1.AddView(descText); LinearLayout linearLayout2 = new LinearLayout(context); linearLayout2.Orientation = Orientation.Horizontal; linearLayout2.SetPadding(0, 10, 0, 0); TextView functionsText = new TextView(context) { Text = "Select a function", Gravity = GravityFlags.Start, TextSize = 15 }; functionsText.SetWidth((int)(width * 0.4)); Spinner spinner = new Spinner(context, SpinnerMode.Dialog); var functions = GetLibraryFunctions(); var adapter = new ArrayAdapter<string>(context, Resource.Drawable.SpinnerExt, functions); spinner.Adapter = adapter; spinner.SetGravity(GravityFlags.Start); spinner.SetMinimumWidth(width - (int)(width * 0.4)); spinner.ItemSelected += Spinner_ItemSelected; linearLayout2.AddView(functionsText); linearLayout2.AddView(spinner); LinearLayout gridLinearLayout = new LinearLayout(context) { Orientation = Orientation.Vertical }; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent); layoutParams.TopMargin = 25; gridLinearLayout.LayoutParameters = layoutParams; gridLinearLayout.SetBackgroundResource(Resource.Drawable.LinearLayout_Border); int padding = gridLinearLayout.PaddingLeft + gridLinearLayout.PaddingRight; int firstColWidth = (int)(width * 0.1) - padding; int cellWidth = ((width - firstColWidth) / 3) - padding; // First Row LinearLayout linearLayout3 = new LinearLayout(context) { Orientation = Orientation.Horizontal }; linearLayout3.SetPadding(0, 10, 0, 0); TextView text00 = new TextView(context); text00.SetWidth((int)(width * 0.1)); TextView text01 = new TextView(context) { Text = "A", Gravity = GravityFlags.Center, TextSize = 15 }; text01.SetWidth(cellWidth); TextView text02 = new TextView(context) { Text = "B", Gravity = GravityFlags.Center, TextSize = 15 }; text02.SetWidth(cellWidth); TextView text03 = new TextView(context) { Text = "C", Gravity = GravityFlags.Center, TextSize = 15 }; text03.SetWidth(cellWidth); linearLayout3.AddView(text00); linearLayout3.AddView(text01); linearLayout3.AddView(text02); linearLayout3.AddView(text03); // Second Row LinearLayout linearLayout4 = new LinearLayout(context) { Orientation = Orientation.Horizontal }; linearLayout4.SetPadding(0, 10, 0, 0); TextView text10 = new TextView(context) { Text = "1", Gravity = GravityFlags.Center, TextSize = 15 }; text10.SetWidth((int)(width * 0.1)); txtA1 = CreateEditText(context, "32"); txtA1.SetWidth(cellWidth); txtB1 = CreateEditText(context, "50"); txtB1.SetWidth(cellWidth); txtC1 = CreateEditText(context, "10"); txtC1.SetWidth(cellWidth); linearLayout4.AddView(text10); linearLayout4.AddView(txtA1); linearLayout4.AddView(txtB1); linearLayout4.AddView(txtC1); // Third Row LinearLayout linearLayout5 = new LinearLayout(context) { Orientation = Orientation.Horizontal }; linearLayout5.SetPadding(0, 10, 0, 0); TextView text20 = new TextView(context) { Text = "2", Gravity = GravityFlags.Center, TextSize = 15 }; text20.SetWidth((int)(width * 0.1)); txtA2 = CreateEditText(context, "12"); txtA2.SetWidth(cellWidth); txtB2 = CreateEditText(context, "24"); txtB2.SetWidth(cellWidth); txtC2 = CreateEditText(context, "90"); txtC2.SetWidth(cellWidth); linearLayout5.AddView(text20); linearLayout5.AddView(txtA2); linearLayout5.AddView(txtB2); linearLayout5.AddView(txtC2); // Fourth Row LinearLayout linearLayout6 = new LinearLayout(context) { Orientation = Orientation.Horizontal }; linearLayout6.SetPadding(0, 10, 0, 0); TextView text30 = new TextView(context) { Text = "3", Gravity = GravityFlags.Center, TextSize = 15 }; text30.SetWidth((int)(width * 0.1)); txtA3 = CreateEditText(context, "88"); txtA3.SetWidth(cellWidth); txtB3 = CreateEditText(context, "-22"); txtB3.SetWidth(cellWidth); txtC3 = CreateEditText(context, "37"); txtC3.SetWidth(cellWidth); linearLayout6.AddView(text30); linearLayout6.AddView(txtA3); linearLayout6.AddView(txtB3); linearLayout6.AddView(txtC3); // Fifth Row LinearLayout linearLayout7 = new LinearLayout(context) { Orientation = Orientation.Horizontal }; linearLayout7.SetPadding(0, 10, 0, 0); TextView text40 = new TextView(context) { Text = "4", Gravity = GravityFlags.Center, TextSize = 15 }; text40.SetWidth((int)(width * 0.1)); txtA4 = CreateEditText(context, "73"); txtA4.SetWidth(cellWidth); txtB4 = CreateEditText(context, "91"); txtB4.SetWidth(cellWidth); txtC4 = CreateEditText(context, "21"); txtC4.SetWidth(cellWidth); linearLayout7.AddView(text40); linearLayout7.AddView(txtA4); linearLayout7.AddView(txtB4); linearLayout7.AddView(txtC4); // Sixth Row LinearLayout linearLayout11 = new LinearLayout(context) { Orientation = Orientation.Horizontal }; linearLayout11.SetPadding(0, 10, 0, 0); TextView text50 = new TextView(context) { Text = "5", Gravity = GravityFlags.Center, TextSize = 15 }; text50.SetWidth((int)(width * 0.1)); txtA5 = CreateEditText(context, "63"); txtA5.SetWidth(cellWidth); txtB5 = CreateEditText(context, "29"); txtB5.SetWidth(cellWidth); txtC5 = CreateEditText(context, "44"); txtC5.SetWidth(cellWidth); linearLayout11.AddView(text50); linearLayout11.AddView(txtA5); linearLayout11.AddView(txtB5); linearLayout11.AddView(txtC5); LinearLayout linearLayout8 = new LinearLayout(context); linearLayout8.Orientation = Orientation.Horizontal; linearLayout8.SetPadding(0, 25, 0, 0); TextView formulaText = new TextView(context) { Text = "Formula", Gravity = GravityFlags.Start, TextSize = 15 }; formulaText.SetWidth((int)(width * 0.4)); formulaEdit = new EditText(context) { TextSize = 15 }; formulaEdit.SetWidth(width - (int)(width * 0.4)); formulaEdit.SetSingleLine(true); linearLayout8.AddView(formulaText); linearLayout8.AddView(formulaEdit); LinearLayout linearLayout9 = new LinearLayout(context); linearLayout9.SetPadding(0, 5, 0, 0); Button compute = new Button(context); compute.Text = "Compute"; compute.Click += Compute_Click; compute.SetWidth(width); linearLayout9.AddView(compute); LinearLayout linearLayout10 = new LinearLayout(context); linearLayout10.Orientation = Orientation.Horizontal; linearLayout10.SetPadding(0, 20, 0, 0); TextView computedText = new TextView(context) { Text = "Computed Value", Gravity = GravityFlags.Start, TextSize = 15 }; computedText.SetWidth((int)(width * 0.4)); computedValueEdit = new TextViewExt(context) { TextSize = 15 }; computedValueEdit.SetWidth(width - (int)(width * 0.4)); computedValueEdit.SetSingleLine(true); linearLayout10.AddView(computedText); linearLayout10.AddView(computedValueEdit); gridLinearLayout.AddView(linearLayout3); gridLinearLayout.AddView(linearLayout4); gridLinearLayout.AddView(linearLayout5); gridLinearLayout.AddView(linearLayout6); gridLinearLayout.AddView(linearLayout7); gridLinearLayout.AddView(linearLayout11); linearLayout.AddView(linearLayout1); linearLayout.AddView(linearLayout2); linearLayout.AddView(gridLinearLayout); linearLayout.AddView(linearLayout8); linearLayout.AddView(linearLayout9); linearLayout.AddView(linearLayout10); linearLayout.Touch += (object sender, View.TouchEventArgs e) => { if (e.Event.Action == MotionEventActions.Up) { ClearFocus(); } }; scrollView.AddView(linearLayout); } private void InitializeEngine() { calcData = new CalcData(); engine = new CalcEngine(calcData); engine.UseNoAmpersandQuotes = true; int i = CalcEngine.CreateSheetFamilyID(); engine.RegisterGridAsSheet("CalcData", calcData, i); } private EditText CreateEditText(Context context, string text) { return new EditText(context) { Text = text, TextSize = 15, Gravity = GravityFlags.Center, InputType = Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber }; } private void Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { var item = (sender as Spinner).SelectedItem.ToString(); switch (item) { case "SUM": case "AVG": case "MAX": case "MIN": case "AVERAGE": case "SUMSQ": case "AVEDEV": case "PRODUCT": case "AVERAGEA": case "GAMMADIST": case "GEOMEAN": case "HARMEAN": case "NORMDIST": case "COUNT": case "COUNTA": case "DEVSQ": case "KURT": case "MAXA": case "MEDIAN": case "MINA": case "GCD": case "LCM": case "STDEV.P": case "STDEV.S": case "IMAGINARYDIFFERENCE": case "IMPRODUCT": case "PPMT": case "IPMT": case "ISPMT": case "SYD": formulaEdit.Text = "=" + item + "(A1,B1,C1,C4)"; break; case "PI": formulaEdit.Text = "=" + item + "()*(A1+B1*C1)"; break; case "VLOOKUP": formulaEdit.Text = "=" + item + "(A1,A2:C5,2,true)"; break; case "HLOOKUP": formulaEdit.Text = "=" + item + "(A1,A2:C5,3,true)"; break; case "INDEX": formulaEdit.Text = "=" + item + "(A1:C5,3,2)"; break; case "CHAR": case "UNICHAR": formulaEdit.Text = "=" + item + "(C2)"; break; case "DB": case "DDB": formulaEdit.Text = "=" + item + "(A1,B1,C1,5)"; break; case "HYPGEOMDIST": formulaEdit.Text = "=" + item + "(C1,A2,A1,B1)"; break; case "IMSUM": case "IMSQRT": case "IMDIV": formulaEdit.Text = "=" + item + "(\"1+4i\",\"1+3i\")"; break; case "SIGN": case "GAMMAIN": case "COUNTBLANK": case "FISHERINV": case "EVEN": case "INDIRECT": case "ISEVEN": case "ISODD": case "ISREF": case "N": case "TAN": case "ODD": case "RADIANS": case "SQRTPI": case "FACTDOUBLE": case "GAMMALN": case "NORMSDIST": case "SEC": case "SECH": case "COT": case "COTH": case "CSC": case "CSCH": case "ACOT": case "ACOTH": case "ACSCH": case "TRUNCATE": case "GAMMALN.PRECISE": case "DEC2BIN": case "DEC2OCT": case "DEC2HEX": case "HEX2BIN": case "HEX2OCT": case "HEX2DEC": case "OCT2BIN": case "OCT2HEX": case "OCT2DEC": case "IMABS": case "IMAGINARY": case "IMREAL": case "IMCONJUGATE": case "IMARGUMENT": case "IMSIN": case "IMCSC": case "IMCOS": case "IMSEC": case "IMTAN": case "IMCOT": case "IMSINH": case "IMCSCH": case "IMCOSH": case "IMSECH": case "IMTANH": case "IMCOTH": case "IMLOG10": case "IMLOG2": case "IMLN": case "IMEXP": case "ERF": case "ERF.PRECISE": case "ERFC.PRECISE": case "ERFC": case "FORMULATEXT": case "ISFORMULA": case "TYPE": case "WEEKNUM": case "ISOWEEKNUM": case "ROW": case "AREAS": case "MUNIT": case "DEGREES": formulaEdit.Text = "=" + item + "(A1)"; break; case "MORMSINV": formulaEdit.Text = "=" + item + "(A1/100)"; break; case "NORMINV": formulaEdit.Text = "=" + item + "(0.98,A2,A3)"; break; case "FINV": formulaEdit.Text = "=" + item + "(1,A1,B1)"; break; case "IFERROR": formulaEdit.Text = "=" + item + "(A1,\"Error in calculation\")"; break; case "ACOS": case "ASECH": formulaEdit.Text = "=" + item + "(0.5)"; break; case "ASIN": case "ATANH": case "FISHER": formulaEdit.Text = "=" + item + "(0.6)"; break; case "BIN2DEC": case "BIN2OCT": case "BIN2HEX": formulaEdit.Text = "=" + item + "(11000011)"; break; case "LARGE": case "QUARTILE": case "QUARTILE.EXC": case "QUARTILE.INC": case "SMALL": formulaEdit.Text = "=" + item + "({C1,A2,C4,B2},3)"; break; case "CORREL": case "COVARIANCE.P": case "COVARIANCE.S": case "INTERCEPT": case "PEARSON": case "RSQ": case "SLOPE": case "STEYX": formulaEdit.Text = "=" + item + "({C1,A2,C4},{B2,A1,C5})"; break; case "PERCENTILE.EXC": case "PERCENTILE.INC": formulaEdit.Text = "=" + item + "({C1,A2,C4},0.7)"; break; case "FORECAST": formulaEdit.Text = "=" + item + "(A4,{C1,A2,C4},{B2,A1,C5})"; break; case "RANDBETWEEN": formulaEdit.Text = "=" + item + "(C1,A1)"; break; case "PERCENTRANK": formulaEdit.Text = "=" + item + "(A1:A5,A3)"; break; case "TRANSPOSE": formulaEdit.Text = "=" + item + "({100,200,300})"; break; case "TRIMMEAN": formulaEdit.Text = "=" + item + "(A1:A5,10%)"; break; case "POW": case "POWER": case "SUMX2MY2": case "SUMX2PY2": case "SUMXMY2": case "CHIDIST": case "CHITEST": case "CONCATENATE": case "COMBIN": case "COVAR": case "PERCENTILE": case "PERMUT": case "ATAN2": case "EFFECT": case "QUOTIENT": case "BIGMUL": case "DIVREM": case "IEEEREMAINDER": case "COMBINA": case "PERMUTATIONA": case "CHISQ.DIST.RT": case "IHDIST": case "COMPLEX": case "IMSUB": case "IMPOWER": case "GESTEP": case "DELTA": case "BITAND": case "BITOR": case "BITXOR": case "BITLSHIFT": case "BITRSHIFT": case "BESSELI": case "BESSELJ": case "BESSELY": case "BESSELK": case "BASE": case "DAYS": case "EDATE": case "EOMONTH": case "WORKDAY.INTL": case "WORKDAY": case "YEARFRAC": case "DAYS360": case "MOD": formulaEdit.Text = "=" + item + "(A1,C1)"; break; case "IF": formulaEdit.Text = "=" + item + "(A1+B1>C1+A4,True)"; break; case "SUMIF": formulaEdit.Text = "=" + item + "(A1:A5,\">C5\")"; break; case "NOT": formulaEdit.Text = "=" + item + "(IF(A1+B1>C1,True))"; break; case "FALSE": case "TRUE": formulaEdit.Text = "=(IF(A1+B1>C1,True))" + item + "()"; break; case "LEFT": case "RIGHT": case "LEFTB": case "RIGHTB": formulaEdit.Text = "=" + item + "(A1,3)"; break; case "LEN": case "LENB": case "INT": case "COLUMN": case "ISERROR": case "ISNUMBER": case "ISLOGICAL": case "ISNA": case "ISERR": case "ISBLANK": case "ISTEXT": case "ISNONTEXT": case "EXP": case "SINH": case "SQRT": case "LOG10": case "LN": case "ACOSH": case "ASINH": case "ATAN": case "COS": case "SIN": case "COSH": case "TANH": case "LOG": case "FACT": formulaEdit.Text = "=" + item + "(Sum(A1,B1,C1))"; break; case "ABS": formulaEdit.Text = "=" + item + "(B3)"; break; case "FV": case "PMT": case "MIRR": case "NPER": case "NPV": case "RATE": case "DATE": case "TIME": case "EXPONDIST": case "FDIST": case "LOGNORMDIST": case "NEGBINOMDIST": case "POISSON": case "STANDARDSIZE": case "WEIBULL": case "SUBSTITUTE": case "MULTINOMIAL": case "SLN": case "SKEW.P": case "F.DIST.RT": formulaEdit.Text = "=" + item + "(A1,B1,C1)"; break; case "RAND": formulaEdit.Text = "=" + item + "()*Sum(A1,B1,C1)"; break; case "CEILING": case "FLOOR": case "ROUNDDOWN": case "ROUND": formulaEdit.Text = "=" + item + "(Sum(A1,B1,C1),0.5)"; break; case "DAY": case "HOUR": case "MINUTE": case "SECOND": case "MONTH": case "WEEKDAY": case "YEAR": formulaEdit.Text = "=" + item + "(A1)"; break; case "DATEVALUE": formulaEdit.Text = "=" + item + "(\"1990/01/24\")"; break; case "OFFSET": formulaEdit.Text = "=" + item + "(A1,2,2)"; break; case "MID": formulaEdit.Text = "=" + item + "(\"MidPoint\",1,A1)"; break; case "MIDB": formulaEdit.Text = "=" + item + "(\"Simple Text\",1,6)"; break; case "EXACT": formulaEdit.Text = "=" + item + "(A1,A1)"; break; case "FIXED": case "PROB": case "SKEW": case "STDEV": case "STDEVA": case "STDEVP": case "STDEVPA": case "VAR": case "VARA": case "VARP": case "VARPA": case "ZTEST": case "UNIDIST": formulaEdit.Text = "=" + item + "(A1,A2,A3)"; break; case "LOWER": formulaEdit.Text = "=" + item + "(\"LOWERTEXT\")"; break; case "UPPER": formulaEdit.Text = "=" + item + "(\"uppertext\")"; break; case "TRIM": formulaEdit.Text = "=" + item + "(\"Simple Text\")"; break; case "TEXT": formulaEdit.Text = "=" + item + "(Sum(A1,B1,C1),$0.00)"; break; case "XIRR": formulaEdit.Text = "=" + item + "(A1:A5," + DateTime.Now + ",0.1)"; break; case "VALUE": formulaEdit.Text = "=" + item + "(Avg(A1,B1,C1))"; break; case "MODE": formulaEdit.Text = "=" + item + "(A1,B1,C1,A1)"; break; case "MODE.SNGL": formulaEdit.Text = "=" + item + "(A1,B1,B1,C4)"; break; case "MODE.MULT": formulaEdit.Text = "=" + item + "(A1,B1,C1,C1)"; break; case "TRUNC": formulaEdit.Text = "=" + item + "(A1/1.3,3)"; break; case "COUNTIF": case "NORM.S.DIST": formulaEdit.Text = "=" + item + "(A1,True)"; break; case "AND": case "OR": case "XOR": formulaEdit.Text = "=" + item + "(A1<B1,C5<B4)"; break; case "IFNA": formulaEdit.Text = "=" + item + "(VLOOKUP(A1,A2:A5,2,true),\"Not Found\")"; break; case "LOOKUP": formulaEdit.Text = "=" + item + "(B2,A1:B4,C1:C5)"; break; case "SUMPRODUCT": case "GROWTH": formulaEdit.Text = "=" + item + "(A1:A5,B1:B5,C1:C5)"; break; case "MATCH": formulaEdit.Text = "=" + item + "(B3,A2:B4,0)"; break; case "FIND": case "FINDB": case "SEARCH": case "SEARCHB": formulaEdit.Text = "=" + item + "(\"n\",\"Syncfusion\",1)"; break; case "CHOOSE": formulaEdit.Text = "=" + item + "(4,A1,A2,A3,A4,A5)"; break; case "CLEAN": formulaEdit.Text = "=" + item + "(CHAR(9)&\"Monthly report\"&CHAR(10))"; break; case "DOLLAR": case "ROUNDUP": case "ROMAN": case "CEILING.MATH": formulaEdit.Text = "=" + item + "(A4, 4)"; break; case "DOLLARDE": case "DOLLARFR": formulaEdit.Text = "=" + item + "(C2,B5)"; break; case "DURATION": formulaEdit.Text = "=" + item + "(A1,A3,C1,B2,2,1)"; break; case "FVSCHEDULE": formulaEdit.Text = "=" + item + "(1,{0.09,0.11,0.1})"; break; case "DISC": formulaEdit.Text = "=" + item + "(A1,B4,C1,C4,1)"; break; case "INTRATE": formulaEdit.Text = "=" + item + "(\"01/24/1990\",\"01/24/1991\",A5,B5,2)"; break; case "CUMIPMT": formulaEdit.Text = "=" + item + "(A2/12,A3*12,A4,1,1,0)"; break; case "CUMPRINC": formulaEdit.Text = "=" + item + "(0.1,A3,A4,1,1,0)"; break; case "NA": case "SHEET": case "SHEETS": case "NOW": case "TODAY": formulaEdit.Text = "=" + item + "()"; break; case "ERROR.TYPE": formulaEdit.Text = "=" + item + "(#REF!)"; break; case "SUBTOTAL": formulaEdit.Text = "=" + item + "(9,A1:B4,C1:C5)"; break; case "PV": formulaEdit.Text = "=" + item + "(A3, A4, A2,B4, 0)"; break; case "ACCRINT": formulaEdit.Text = "=" + item + "(DATE(A1,A2,B2), DATE(C1,C2,B2), DATE(B1,B2,C1),0.1,C5,2,0)"; break; case "ACCRINTM": formulaEdit.Text = "=" + item + "(DATE(A1,A2,B2),DATE(C2,C4,C5),0.1,B5,2)"; break; case "VDB": formulaEdit.Text = "=" + item + "(A1,A2,A3,DATE(A1,A2,B2),DATE(C2,C4,C5))"; break; case "TIMEVALUE": formulaEdit.Text = "=" + item + "(\"2:24 AM\")"; break; case "MROUND": formulaEdit.Text = "=" + item + "(A1,3)"; break; case "NORMSINV": case "NORM.S.INV": formulaEdit.Text = "=" + item + "(0.8)"; break; case "LOGEST": case "LOGESTB": formulaEdit.Text = "=" + item + "(A1:A5,B1:B5,TRUE,TRUE)"; break; case "PERCENTRANK.EXC": case "PERCENTRANK.INC": case "Z.TEST": formulaEdit.Text = "=" + item + "(A1:A5,3)"; break; case "STANDARDIZE": formulaEdit.Text = "=" + item + "(A1,A5,1.5)"; break; case "ADDRESS": formulaEdit.Text = "=" + item + "(2,3)"; break; case "AVERAGEIF": formulaEdit.Text = "=" + item + "(B2:B5,\"<23000\")"; break; case "AVERAGEIFS": formulaEdit.Text = "=" + item + "(A2:A5, C2:C5, \">30\", A2:A5, \"<90\")"; break; case "SUMIFS": formulaEdit.Text = "=" + item + "(A2:A5, C1:C5,\">C4\")"; break; case "NETWORKDAYS": formulaEdit.Text = "=" + item + "(C4,B5)"; break; case "CONFIDENCE.T": case "CONFIDENCE": case "GAMMAINV": case "LOGINV": formulaEdit.Text = "=" + item + "(0.6,B2,A1)"; break; case "BINOMDIST": formulaEdit.Text = "=" + item + "(A1,B1,0.6,TRUE)"; break; case "CHISQ.TEST": formulaEdit.Text = "=" + item + "(A1:A3, C1:C3)"; break; case "MMULT": formulaEdit.Text = "=" + item + "(A2:A5, B2:B5)"; break; case "NORM.DIST": formulaEdit.Text = "=" + item + "(A2,A3,B1,TRUE)"; break; case "NORM.INV": formulaEdit.Text = "=" + item + "(0.908789,A5,B2)"; break; case "WEIBULL.DIST": case "GAMMA.DIST": case "LOGNORM.DIST": case "F.DIST": formulaEdit.Text = "=" + item + "(A2,A3,A4,TRUE)"; break; case "EXPON.DIST": case "CHISQ.DIST": formulaEdit.Text = "=" + item + "(0.3,A3,TRUE)"; break; case "GAMMA.INV": case "F.INV.RT": case "LOGNORM.INV": case "CONFIDENCE.NORM": formulaEdit.Text = "=" + item + "(0.068094,A3,A4)"; break; case "BINOM.INV": case "CRITBINOM": formulaEdit.Text = "=" + item + "(A1,0.5,0.6)"; break; case "HYPGEOM.DIST": formulaEdit.Text = "=" + item + "(A1,A2,A3,A4,TRUE)"; break; case "BETA.DIST": formulaEdit.Text = "=" + item + "(A2,A3,A4,TRUE,B1,B2)"; break; case "CHISQ.INV": case "CHISQ.INV.RT": case "T.INV": case "CHIINV": formulaEdit.Text = "=" + item + "(0.5,A3)"; break; case "BINOM.DIST": case "NEGBINOM.DIST": formulaEdit.Text = "=" + item + "(A1,A3,0.7,TRUE)"; break; case "RANK.AVG": formulaEdit.Text = "=" + item + "(A2,A1:A5,1)"; break; case "RANK.EQ": formulaEdit.Text = "=" + item + "(B3,B1:B5,1)"; break; case "RANK": formulaEdit.Text = "=" + item + "(C4,C1:C5,1)"; break; case "POISSON.DIST": case "T.DIST": formulaEdit.Text = "=" + item + "(A1,A2,TRUE)"; break; case "CONVERT": formulaEdit.Text = "=" + item + "(A1,\"F\",\"C\")"; break; case "REPLACE": case "REPLACEB": formulaEdit.Text = "=" + item + "(\"SimpleText\",6,5,\"*\")"; break; case "CODE": case "UNICODE": case "ASC": case "JIS": case "ENCODEURL": case "T": formulaEdit.Text = "=" + item + "(\"SimpleText\")"; break; case "PROPER": formulaEdit.Text = "=" + item + "(\"SimPleTeXt\")"; break; case "NUMBERVALUE": formulaEdit.Text = "=" + item + "(\"2.500,27\",\",\",\".\")"; break; case "REPT": formulaEdit.Text = "=" + item + "(\"SimpleText\",3)"; break; case "MDETERM": case "ROWS": case "COLUMNS": case "IRR": formulaEdit.Text = "=" + item + "(A1:A5)"; break; case "MINVERSE": formulaEdit.Text = "=" + item + "({1,2,4})"; break; case "DECIMAL": formulaEdit.Text = "=" + item + "(\"FF\",16)"; break; case "SERIESSUM": formulaEdit.Text = "=" + item + "(A3,0,2,A1:A5)"; break; case "ARABIC": formulaEdit.Text = "=" + item + "(\"LVII\")"; break; case "NETWORKDAYS.INTL": formulaEdit.Text = "=" + item + "(\"1990/01/24\",\"1992/01/24\")"; break; case "HYPERLINK": formulaEdit.Text = "=" + item + "(\"http:\\www.syncfusion.com\",\"Syncfusion\")"; break; case "INFO": formulaEdit.Text = "=" + item + "(\"NUMFILE\")"; break; case "CELL": formulaEdit.Text = "=" + item + "(\"col\",C3)"; break; } } private void Compute_Click(object sender, EventArgs e) { ClearFocus(); calcData.SetValueRowCol(txtA1.Text, 1, 1); calcData.SetValueRowCol(txtA2.Text, 2, 1); calcData.SetValueRowCol(txtA3.Text, 3, 1); calcData.SetValueRowCol(txtA4.Text, 4, 1); calcData.SetValueRowCol(txtA5.Text, 5, 1); calcData.SetValueRowCol(txtB1.Text, 1, 2); calcData.SetValueRowCol(txtB2.Text, 2, 2); calcData.SetValueRowCol(txtB3.Text, 3, 2); calcData.SetValueRowCol(txtB4.Text, 4, 2); calcData.SetValueRowCol(txtB5.Text, 5, 2); calcData.SetValueRowCol(txtC1.Text, 1, 3); calcData.SetValueRowCol(txtC2.Text, 2, 3); calcData.SetValueRowCol(txtC3.Text, 3, 3); calcData.SetValueRowCol(txtC4.Text, 4, 3); calcData.SetValueRowCol(txtC5.Text, 5, 3); computedValueEdit.Text = engine.ParseAndComputeFormula(formulaEdit.Text); } private List<string> GetLibraryFunctions() { List<string> libraryFunctions = new List<string>(); foreach (string item in engine.LibraryFunctions.Keys) { libraryFunctions.Add(item); } libraryFunctions.Sort(); libraryFunctions.RemoveAt(0); libraryFunctions.RemoveAt(0); libraryFunctions.RemoveAt(0); libraryFunctions.Remove("ACCRINTM"); libraryFunctions.Remove("AVERAGEIFS"); libraryFunctions.Remove("BETA.DIST"); libraryFunctions.Remove("BIGMUL"); libraryFunctions.Remove("IMAGINARYDIFFERENCE"); libraryFunctions.Remove("IMPRODUCT"); libraryFunctions.Remove("IMSUB"); libraryFunctions.Remove("F.INV.RT"); libraryFunctions.Remove("HYPGEOM.DIST"); libraryFunctions.Remove("IMCONJUGATE"); libraryFunctions.Remove("MIRR"); libraryFunctions.Remove("FORMULATEXT"); libraryFunctions.Remove("GROWTH"); libraryFunctions.Remove("IRR"); libraryFunctions.Remove("MDETERN"); libraryFunctions.Remove("MMULT"); libraryFunctions.Remove("NORM.INV"); libraryFunctions.Remove("PROPER"); libraryFunctions.Remove("REPLACEB"); libraryFunctions.Remove("UNICODE"); libraryFunctions.Remove("XIRR"); return libraryFunctions; } private void ClearFocus() { if (txtA1.IsFocused || txtA2.IsFocused || txtA3.IsFocused || txtA4.IsFocused || txtA5.IsFocused || txtB1.IsFocused || txtB2.IsFocused || txtB3.IsFocused || txtB4.IsFocused || txtB5.IsFocused || txtC1.IsFocused || txtC2.IsFocused || txtC3.IsFocused || txtC4.IsFocused || txtC5.IsFocused || formulaEdit.IsFocused) { txtA1.ClearFocus(); txtA2.ClearFocus(); txtA3.ClearFocus(); txtA4.ClearFocus(); txtA5.ClearFocus(); txtB1.ClearFocus(); txtB2.ClearFocus(); txtB3.ClearFocus(); txtB4.ClearFocus(); txtB5.ClearFocus(); txtC1.ClearFocus(); txtC2.ClearFocus(); txtC3.ClearFocus(); txtC4.ClearFocus(); txtC5.ClearFocus(); formulaEdit.ClearFocus(); } Activity activity = (Activity)context; InputMethodManager inputMethodManager = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); if (activity.CurrentFocus != null) { inputMethodManager.HideSoftInputFromWindow(activity.CurrentFocus.WindowToken, 0); } } public override void Destroy() { scrollView = null; formulaEdit = null; computedValueEdit = null; txtA1 = null; txtA2 = null; txtA3 = null; txtA4 = null; txtA5 = null; txtB1 = null; txtB2 = null; txtB3 = null; txtB4 = null; txtB5 = null; txtC1 = null; txtC2 = null; txtC3 = null; txtC4 = null; txtC5 = null; context = null; calcData = null; if (engine != null) { engine.Dispose(); } base.Destroy(); } public void Dispose() { if (scrollView != null) { scrollView.Dispose(); scrollView = null; } if (formulaEdit != null) { formulaEdit.Dispose(); formulaEdit = null; } if (computedValueEdit != null) { computedValueEdit.Dispose(); computedValueEdit = null; } if (txtA1 != null) { txtA1.Dispose(); txtA1 = null; } if (txtA2 != null) { txtA2.Dispose(); txtA2 = null; } if (txtA3 != null) { txtA3.Dispose(); txtA3 = null; } if (txtA4 != null) { txtA4.Dispose(); txtA4 = null; } if (txtA5 != null) { txtA5.Dispose(); txtA5 = null; } if (txtB1 != null) { txtB1.Dispose(); txtB1 = null; } if (txtB2 != null) { txtB2.Dispose(); txtB2 = null; } if (txtB3 != null) { txtB3.Dispose(); txtB3 = null; } if (txtB4 != null) { txtB4.Dispose(); txtB4 = null; } if (txtB5 != null) { txtB5.Dispose(); txtB5 = null; } if (txtC1 != null) { txtC1.Dispose(); txtC1 = null; } if (txtC2 != null) { txtC2.Dispose(); txtC2 = null; } if (txtC3 != null) { txtC3.Dispose(); txtC3 = null; } if (txtC4 != null) { txtC4.Dispose(); txtC4 = null; } if (txtC5 != null) { txtC5.Dispose(); txtC5 = null; } if (engine != null) { engine.Dispose(); engine = null; } } #endregion } public class CalcData : ICalcData { public event ValueChangedEventHandler ValueChanged; public CalcData() { } private Dictionary<string, object> values = new Dictionary<string, object>(); public object GetValueRowCol(int row, int col) { object value = null; var key = RangeInfo.GetAlphaLabel(col) + row; this.values.TryGetValue(key, out value); return value; } public void SetValueRowCol(object value, int row, int col) { var key = RangeInfo.GetAlphaLabel(col) + row; if (!values.ContainsKey(key)) { values.Add(key, value); } else { if (values.ContainsKey(key) && values[key] != value) { values[key] = value; } } } public void WireParentObject() { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Verified")] private void OnValueChanged(int row, int col, string value) { if (ValueChanged != null) { ValueChanged(this, new ValueChangedEventArgs(row, col, value)); } } } }<file_sep>/Forms/Chart/Chart/Samples/StripLines/StripLines.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfChart.XForms; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfChart { public partial class StripLines : SampleView { public StripLines() { InitializeComponent(); (Chart.SecondaryAxis as NumericalAxis).Minimum = 10; (Chart.SecondaryAxis as NumericalAxis).Maximum = 40; if(Device.RuntimePlatform==Device.UWP) { chartDataMarker.MarkerBorderWidth = 2; } else { chartDataMarker.MarkerBorderWidth = 4; } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/VerticalChart.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Threading.Tasks; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class VerticalChart : SampleView { SFChart chart ; ChartVerticalDataModel dataModel; public VerticalChart () { chart = new SFChart (); SFDateTimeAxis xAxis = new SFDateTimeAxis (); NSDateFormatter formatter = new NSDateFormatter (); formatter.DateFormat = new NSString ("mm:ss"); xAxis.LabelStyle.LabelFormatter = formatter; xAxis.Title.Text = new NSString ("Time(sec)"); xAxis.ShowMajorGridLines = false; chart.PrimaryAxis = xAxis; SFNumericalAxis yAxis = new SFNumericalAxis (); yAxis.Minimum = new NSNumber(-10); yAxis.Maximum = new NSNumber (10); yAxis.Interval = new NSNumber (10); yAxis.Title.Text = new NSString ("Velocity(m/s)"); yAxis.ShowMajorGridLines = false; chart.SecondaryAxis = yAxis; chart.Title.Text = new NSString ("Seismograph of Japan Earthquake 2011"); chart.Title.Font = UIFont.FromName ("Helvetica neue",15); dataModel = new ChartVerticalDataModel(); chart.DataSource = dataModel as ChartVerticalDataModel; this.AddSubview(chart); UpdateData (); } async void UpdateData() { await Task.Delay(50); var datapoint = dataModel.dataPointWithTimeInterval (0.13); dataModel.DataPoints.Add (datapoint); chart.InsertDataPointAtIndex ((int)dataModel.DataPoints.Count - 1, 0); if(dataModel.DataPoints.Count < 340) UpdateData (); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } public class ChartVerticalDataModel : SFChartDataSource { public NSMutableArray DataPoints; public NSDate date; Random random; public ChartVerticalDataModel () { DataPoints = new NSMutableArray (); random = new Random (); NSCalendar calendar = new NSCalendar (NSCalendarType.Gregorian); NSDateComponents components = new NSDateComponents (); date = new NSDate (); components.Year = 2011; components.Month = 3; components.Day = 11; components.Hour = 14; components.Minute = 46; components.Second = 0; date = calendar.DateFromComponents(components); for (int i = 0; i <30; i++) { DataPoints.Add (dataPointWithTimeInterval(0.15)); } } public SFChartDataPoint dataPointWithTimeInterval(double time) { int count = (int)DataPoints.Count; NSNumber value; if(count>320) { value = random.Next (0, 0); } else if(count>280) { value = random.Next (-2, 2); } else if(count>240) { value = random.Next (-3, 3); } else if(count>200) { value = random.Next (-5, 5); } else if(count>180) { value = random.Next (-6, 6); } else if(count>120) { value = random.Next (-7, 7); } else if (count > 30) { value = random.Next (-9, 9); } else { value = random.Next (-3, 3); } date = date.AddSeconds (time); SFChartDataPoint datapoint = new SFChartDataPoint(); datapoint.XValue = NSObject.FromObject (date); datapoint.YValue = value; return datapoint; } public override nint NumberOfSeriesInChart (SFChart chart) { return 1; } public override SFSeries GetSeries (SFChart chart, nint index) { SFFastLineSeries series = new SFFastLineSeries (); series.IsTransposed = true; series.EnableAnimation = true; return series; } public override SFChartDataPoint GetDataPoint (SFChart chart, nint index, nint seriesIndex) { return DataPoints.GetItem<SFChartDataPoint> ((nuint)index); } public override nint GetNumberOfDataPoints (SFChart chart, nint index) { return (int)DataPoints.Count; } } } <file_sep>/Android/SampleBrowser/Samples/ImageEditor/ImageEditorCustomView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Syncfusion.SfImageEditor.Android; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Content; using Android.Provider; using Java.IO; using Android.Content.PM; using Android.Graphics.Drawables; using Android.Runtime; using Android.Views; using System.Collections.ObjectModel; using System.Collections.Generic; namespace SampleBrowser { public class ImageEditorCustomView : SamplePage { internal static Activity Activity { get; set; } View view { get; set; } public static int Image { get; set; } ImageButton imageview3; ImageButton imageview4; ImageButton imageview5; Context con { get; set; } void View_LayoutChange(object sender, View.LayoutChangeEventArgs e) { var height = GetImageHeight(imageview3, view.Width / 3); imageview3.LayoutParameters = new TableRow.LayoutParams((int)view.Width / 3, (int)height); imageview4.LayoutParameters = new TableRow.LayoutParams((int)view.Width / 3, (int)height); imageview5.LayoutParameters = new TableRow.LayoutParams((int)view.Width / 3, (int)height); } public override Android.Views.View GetSampleContent(Android.Content.Context context) { con = context; LayoutInflater layoutInflater = LayoutInflater.From(context); view = layoutInflater.Inflate(Resource.Layout.ImageEditorCustomView, null); imageview3 = view.FindViewById<ImageButton>(Resource.Id.imageview3); imageview4 = view.FindViewById<ImageButton>(Resource.Id.imageview4); imageview5 = view.FindViewById<ImageButton>(Resource.Id.imageview5); view.LayoutChange -= View_LayoutChange; view.LayoutChange += View_LayoutChange; imageview3.Click += pictureOnClick1; imageview4.Click += pictureOnClick2; imageview5.Click += pictureOnClick3; LinearLayout layout = new LinearLayout(context); return view; } public void pictureOnClick1(object sender, EventArgs e) { Activity = con as Activity; Activity?.StartActivity(typeof(CustomViewActivity)); Image = Resource.Drawable.CustomViewImage1; } public void pictureOnClick2(object sender, EventArgs e) { Activity = con as Activity; Activity?.StartActivity(typeof(CustomViewActivity)); Image = Resource.Drawable.CustomViewImage2; } public void pictureOnClick3(object sender, EventArgs e) { Activity = con as Activity; Activity?.StartActivity(typeof(CustomViewActivity)); Image = Resource.Drawable.CustomViewImage3; } private float GetImageHeight(ImageButton button, float renderWidth) { float originalWidth = 572; float originalHeight = 860; float renderedHeight = (renderWidth * originalHeight) / originalWidth; return renderedHeight; } [Activity(Label = "SfImageEditor", ScreenOrientation = ScreenOrientation.Portrait, Icon = "@drawable/icon")] public class CustomViewActivity : Activity { CustomViewSettings customViewSettings; void ImageEditor_ItemSelected(object sender, ItemSelectedEventArgs e) { if (e.Settings != null && e.Settings is CustomViewSettings) { customViewSettings = e.Settings as CustomViewSettings; } } List<ToolbarItem> CustomViewItems; SfImageEditor imageEditor; bool isReplaced; string imageName; protected override void OnCreate(Bundle savedInstanceState) { imageEditor = new SfImageEditor(this); var bitmap = BitmapFactory.DecodeResource(Resources, ImageEditorCustomView.Image); imageEditor.Bitmap = bitmap; imageEditor.ItemSelected += ImageEditor_ItemSelected; SetContentView(imageEditor); base.OnCreate(savedInstanceState); imageEditor.SetToolbarItemVisibility("text,transform,shape,path,effects", false); CustomViewItems = new List<ToolbarItem>() { new CustomToolbarItem(){Icon=BitmapFactory.DecodeResource(Resources, Resource.Drawable.ITypogy1),CustomName = "ITypogy1",IconHeight=70 }, new CustomToolbarItem(){Icon=BitmapFactory.DecodeResource(Resources, Resource.Drawable.ITypogy2),CustomName = "ITypogy2",IconHeight=70 }, new CustomToolbarItem(){Icon=BitmapFactory.DecodeResource(Resources, Resource.Drawable.ITypogy3),CustomName = "ITypogy3",IconHeight=70 }, new CustomToolbarItem(){Icon=BitmapFactory.DecodeResource(Resources, Resource.Drawable.ITypogy4),CustomName = "ITypogy4",IconHeight=70 }, new CustomToolbarItem(){Icon=BitmapFactory.DecodeResource(Resources, Resource.Drawable.ITypogy5),CustomName = "ITypogy5",IconHeight=70 }, new CustomToolbarItem(){Icon=BitmapFactory.DecodeResource(Resources, Resource.Drawable.ITypogy6),CustomName = "ITypogy6",IconHeight=70 } }; // Add the custom tool bar items var item = new FooterToolbarItem() { Text = "Add", Icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.AddIcon), SubItems = CustomViewItems, TextHeight = 20, }; imageEditor.ToolbarSettings.ToolbarItems.Add(item); item = new FooterToolbarItem() { Text = "Replace", Icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ReplaceIcon), SubItems = CustomViewItems, TextHeight = 20 }; imageEditor.ToolbarSettings.ToolbarItems.Add(item); item = new FooterToolbarItem() { Icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.BringFrontIcon), Text = "Bring Front", TextHeight = 20 }; imageEditor.ToolbarSettings.ToolbarItems.Add(item); item = new FooterToolbarItem() { Icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.SendBack), Text = "Send Back", TextHeight = 20 }; imageEditor.ToolbarSettings.ToolbarItems.Add(item); imageEditor.ToolbarSettings.SubItemToolbarHeight = 70; imageEditor.ToolbarSettings.ToolbarItemSelected += OnToolbarItemSelected; } private void OnToolbarItemSelected(object sender, ToolbarItemSelectedEventArgs e) { string text = string.Empty; //e.ToolbarItem.Name; if (text != "back") { if (e.ToolbarItem is FooterToolbarItem) { text = e.ToolbarItem.Text; e.MoveSubItemsToFooterToolbar = true; } else if (e.ToolbarItem is CustomToolbarItem) text = (e.ToolbarItem as CustomToolbarItem).CustomName; else text = e.ToolbarItem.Text; if (text == "Replace") { isReplaced = true; //imageEditor.ToolbarSettings.FooterToolbarHeight = 70; } else if (text == "back") { isReplaced = false; //imageEditor.ToolbarSettings.FooterToolbarHeight = 50; } else if (text == "Add") { isReplaced = false; //imageEditor.ToolbarSettings.FooterToolbarHeight = 70; } if (isReplaced && imageEditor.IsSelected && (text == "ITypogy1" || text == "ITypogy2" || text == "ITypogy3" || text == "ITypogy4" || text == "ITypogy5" || text == "ITypogy6")) { imageEditor.Delete(); AddImage(text); } if (!isReplaced) AddImage(text); if (text == "Bring Front") imageEditor.BringToFront(); else if (text == "Send Back") imageEditor.SendToBack(); } else { isReplaced = false; } } private void AddImage(string text) { if (text == "ITypogy1") SetSVGImage("ITypogy1"); else if (text == "ITypogy2") SetSVGImage("ITypogy2"); else if (text == "ITypogy3") SetSVGImage("ITypogy3"); else if (text == "ITypogy4") SetSVGImage("ITypogy4"); else if (text == "ITypogy5") SetSVGImage("ITypogy5"); else if (text == "ITypogy6") SetSVGImage("ITypogy6"); } private void SetSVGImage(string name) { imageName = name; ImageView view = new ImageView(this); view.LayoutParameters = new ViewGroup.LayoutParams(200, 200); if (imageName == "ITypogy1") view.SetImageResource(Resource.Drawable.Typogy1); else if (imageName == "ITypogy2") view.SetImageResource(Resource.Drawable.Typogy2); else if (imageName == "ITypogy3") view.SetImageResource(Resource.Drawable.Typogy3); else if (imageName == "ITypogy4") view.SetImageResource(Resource.Drawable.Typogy4); else if (imageName == "ITypogy5") view.SetImageResource(Resource.Drawable.Typogy5); else if (imageName == "ITypogy6") view.SetImageResource(Resource.Drawable.Typogy6); if (isReplaced) imageEditor.AddCustomView(view, new CustomViewSettings() { Bounds = customViewSettings.Bounds }); else { imageEditor.AddCustomView(view, new CustomViewSettings() { }); } } } public class CustomToolbarItem : ToolbarItem { public string CustomName { get; set; } public CustomToolbarItem() { } } } } <file_sep>/Forms/RadialMenu/RadialMenu/Samples/Customization_RadialMenu/Rotator_Model.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; using Xamarin.Forms; namespace SampleBrowser.SfRadialMenu { public class Rotator_Model : INotifyPropertyChanged { public Rotator_Model(string teamName, Color teamNameColor, string fifaCurrent, string fifaHighest, string fifaLowest, string eloCurrent, string eloHighest, string eloLowest) { TeamName = teamName; TeamColor = teamNameColor; FIFACurrent = fifaCurrent; FIFAHightest = fifaHighest; FIFALowest = fifaLowest; EloCurrent = eloCurrent; EloHightest = eloHighest; EloLowest = eloLowest; } private String teamName; public String TeamName { get { return teamName; } set { teamName = value; } } private Color color; public Color TeamColor { get { return color; } set { color = value; RaisepropertyChanged("TeamColor"); } } private String fifaCurrent; public String FIFACurrent { get { return fifaCurrent; } set { fifaCurrent = value; } } private String fifaHightest; public String FIFAHightest { get { return fifaHightest; } set { fifaHightest = value; } } private String fifaLowest; public String FIFALowest { get { return fifaLowest; } set { fifaLowest = value; } } private String eloCurrent; public String EloCurrent { get { return eloCurrent; } set { eloCurrent = value; } } private String eloHightest; public String EloHightest { get { return eloHightest; } set { eloHightest = value; } } private String eloLowest; public String EloLowest { get { return eloLowest; } set { eloLowest = value; } } public event PropertyChangedEventHandler PropertyChanged; void RaisepropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/iOS/SampleBrowser/Samples/Calendar/CalendarConfiguration_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfCalendar.iOS; using Syncfusion.SfRangeSlider.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class CalendarConfiguration_Mobile : SampleView { private SFCalendar calendar; private string selectedType; private UILabel labelCalendarView; private UIButton buttonCalendarView = new UIButton(); private UIButton doneButton = new UIButton(); private UIPickerView pickerCalendarView; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public CalendarConfiguration_Mobile() { //Calendar calendar = new SFCalendar(); calendar.ViewMode = SFCalendarViewMode.SFCalendarViewModeMonth; //calendar. NSMutableArray<NSString> customLabel = new NSMutableArray<NSString>(); customLabel.Add((NSString)"SUN"); customLabel.Add((NSString)"MON"); customLabel.Add((NSString)"TUE"); customLabel.Add((NSString)"WED"); customLabel.Add((NSString)"THU"); customLabel.Add((NSString)"FRI"); customLabel.Add((NSString)"SAT"); calendar.CustomDayLabels = customLabel; calendar.HeaderHeight = 40; //MonthViewSettings SFMonthViewSettings monthSettings = new SFMonthViewSettings(); monthSettings.WeekDayFontAttribute = UIFont.FromName("Menlo-Italic", 16f); monthSettings.FontAttribute = UIFont.FromName("Menlo-Regular", 16f); monthSettings.HeaderTextColor = UIColor.White; monthSettings.HeaderBackgroundColor = UIColor.FromRGB(61, 61, 61); monthSettings.DayLabelTextColor = UIColor.White; monthSettings.DayLabelBackgroundColor = UIColor.FromRGB(61, 61, 61); monthSettings.DateSelectionColor = UIColor.FromRGB(61, 61, 61); monthSettings.DateSelectionTextColor = UIColor.White; calendar.MonthViewSettings = monthSettings; this.OptionView1(); this.AddSubview(calendar); } public UIView Option { get; set; } = new UIView(); public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; this.OptionView.Frame = view.Frame; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { var height = this.Frame.Height; pickerCalendarView.Frame = new CGRect(0, 160, 300, 70); doneButton.Frame = new CGRect(0, 100, 300, 40); labelCalendarView.Frame = new CGRect(10, 20, this.Frame.Size.Width - 20, 30); buttonCalendarView.Frame = new CGRect(10, 80, 300, 30); } else { Option.Frame = new CGRect(0, 90, Frame.Width, Frame.Height); labelCalendarView.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y - 20, this.Frame.Size.Width - 20, 30); buttonCalendarView.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 20, this.Frame.Size.Width - 20, 30); pickerCalendarView.Frame = new CGRect(this.Frame.X, this.Frame.Size.Height / 4, this.Frame.Size.Width, this.Frame.Size.Height / 3); doneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4, this.Frame.Size.Width, 40); } } base.LayoutSubviews(); } private readonly IList<string> calendarViewsCollection = new List<string> { "Single Selection", "Multi Selection" }; public void OptionView1() { //Intializing configurationc controls pickerCalendarView = new UIPickerView(); labelCalendarView = new UILabel(); buttonCalendarView = new UIButton(); this.OptionView = new UIView(); //CalendarView PickerModel model = new PickerModel(calendarViewsCollection); pickerCalendarView.Model = model; labelCalendarView.Text = "SELECTION MODE: "; labelCalendarView.TextColor = UIColor.Black; labelCalendarView.TextAlignment = UITextAlignment.Left; buttonCalendarView.SetTitle("Single Selection", UIControlState.Normal); buttonCalendarView.SetTitleColor(UIColor.Black, UIControlState.Normal); buttonCalendarView.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; buttonCalendarView.Layer.CornerRadius = 8; buttonCalendarView.Layer.BorderWidth = 2; buttonCalendarView.TouchUpInside += ShowPicker1; buttonCalendarView.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(246, 246, 246); model.PickerChanged += SelectedIndexChanged1; pickerCalendarView.ShowSelectionIndicator = true; pickerCalendarView.Hidden = true; //picker_calendarView.BackgroundColor = UIColor.Gray; //adding subviews to the option view this.Option.AddSubview(labelCalendarView); this.Option.AddSubview(buttonCalendarView); this.Option.AddSubview(pickerCalendarView); this.Option.AddSubview(doneButton); } private void ShowPicker1(object sender, EventArgs e) { doneButton.Hidden = false; pickerCalendarView.Hidden = false; buttonCalendarView.Hidden = true; labelCalendarView.Hidden = true; } private void HidePicker(object sender, EventArgs e) { doneButton.Hidden = true; pickerCalendarView.Hidden = true; buttonCalendarView.Hidden = false; labelCalendarView.Hidden = false; } private void SelectedIndexChanged1(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; if (selectedType == "Single Selection") { calendar.SelectionMode = SFCalenderSelectionMode.SFCalenderSelectionModeSingle; } else if (selectedType == "Multi Selection") { calendar.SelectionMode = SFCalenderSelectionMode.SFCalenderSelectionModeMultiple; } else if (selectedType == "Range Selection") { calendar.SelectionMode = SFCalenderSelectionMode.SFCalenderSelectionModeRange; } buttonCalendarView.SetTitle(selectedType.ToString(), UIControlState.Normal); } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/CustomSorting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Syncfusion.Data; using Syncfusion.SfDataGrid; using System.ComponentModel; namespace SampleBrowser { public class CustomSorting : SamplePage { #region Fields CustomerViewModel viewModel; SfDataGrid sfGrid; #endregion #region Override Methods public override View GetSampleContent(Context context) { sfGrid = new SfDataGrid (context); viewModel = new CustomerViewModel (); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = viewModel.CustomerInformation; sfGrid.AllowSorting = true; sfGrid.SelectionMode = SelectionMode.Single; sfGrid.AllowTriStateSorting = true; sfGrid.GridStyle.AlternatingRowColor = Color.Rgb(206, 206, 206); sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; sfGrid.SortComparers.Add(new SortComparer () { Comparer = new CustomerInfo (), PropertyName="FirstName" }); sfGrid.SortColumnDescriptions.Add(new SortColumnDescription () { ColumnName = "FirstName", SortDirection = ListSortDirection.Descending }); return sfGrid; } public override void Destroy() { sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; sfGrid.Dispose(); sfGrid = null; viewModel = null; } #endregion #region CallBacks private void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "City") { e.Column.HeaderText = "City"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Country") { e.Column.HeaderText = "Country"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "<NAME>"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = GravityFlags.CenterVertical; } } #endregion } }<file_sep>/Forms/StepProgressBar/StepProgressBar/Samples/GettingStarted/GettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.ProgressBar; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfStepProgressBar { public partial class GettingStarted : SampleView { StationViewModel viewModel = new StationViewModel(); public GettingStarted() { InitializeComponent(); trainProgress.TitleSpace = 25; DateTime toStartTime; DateTime.TryParse("7:15:00 AM", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out toStartTime); double timeDiff = DateTime.Now.Subtract(toStartTime).TotalSeconds; viewModel.PopulationStationTimeTable(timeDiff); BindableLayout.SetItemsSource(trainProgress, viewModel.StationInfoCollection); PopulateStepViews(); } private async void PopulateStepViews() { while (true) { for (int i = 0; i < viewModel.StationInfoCollection.Count; i++) { if (viewModel.StationInfoCollection[i].Status == StepStatus.InProgress) this.upComingStationLabel.Text = viewModel.StationInfoCollection[i].Name + viewModel.NextStationTime; } await Task.Delay(1000); } } } public class StationViewModel { Station station; private ObservableCollection<Station> stationInfoCollection = new ObservableCollection<Station>(); internal ObservableCollection<DummyStation> tempCollection = new ObservableCollection<DummyStation>(); public ObservableCollection<Station> StationInfoCollection { get { return stationInfoCollection; } set { stationInfoCollection = value; } } private string nextStationTime; public string NextStationTime { get { return nextStationTime; } set { nextStationTime = value; } } public StationViewModel() { } private double trainStartTimeDiff; public void PopulationStationTimeTable(double startTimeDiff) { trainStartTimeDiff = startTimeDiff; this.PopulateViewModel(); for (int i = 0; i < tempCollection.Count; i++) { DummyStation dummyStation = tempCollection[i]; StationInfoCollection.Add(CreateStationInfo(dummyStation.Name, dummyStation.ToArrival, dummyStation.ToDistance, dummyStation.FromArrival, i, dummyStation.FromDistance)); } } public void PopulateViewModel() { if (tempCollection.Count == 0) { tempCollection.Add(new DummyStation() { Name = "New York, NY", ToArrival = "7:15:00 AM", ToDistance = 0, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Yonkers, NY", ToArrival = "7:44:00 AM", ToDistance = 14, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "<NAME>", ToArrival = "8:03:00 AM", ToDistance = 32, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Poughkeepsie, NY", ToArrival = "8:53:00 AM", ToDistance = 76, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Rhinecliff, NY", ToArrival = "8:57:00 AM", ToDistance = 81, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "<NAME>", ToArrival = "9:18:00 AM", ToDistance = 114, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Albany-Rensselaer", ToArrival = "9:50:00 AM", ToDistance = 141, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Schenectady, NY", ToArrival = "10:24:00 AM", ToDistance = 159, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Amsterdam, NY", ToArrival = "10:44:00 AM", ToDistance = 177, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Utica, NY", ToArrival = "11:41:00 AM", ToDistance = 237, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Rome, NY", ToArrival = "11:54:00 AM", ToDistance = 250, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Syracuse, NY", ToArrival = "12:43:00 PM", ToDistance = 291, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Rochester, NY", ToArrival = "1:55:00 PM", ToDistance = 370, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Buffalo-Depew, NY", ToArrival = "3:01:00 PM", ToDistance = 431, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Buffalo-Exchange St., NY", ToArrival = "3:14:00 PM", ToDistance = 437, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Niagara Falls, NY", ToArrival = "4:26:00 PM", ToDistance = 460, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "<NAME>, ON", ToArrival = "4:33:00 PM", ToDistance = 462, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "St. Catharines, ON", ToArrival = "5:08:00 PM", ToDistance = 473, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Grimsby, ON", ToArrival = "5:27:00 PM", ToDistance = 488, FromArrival = "7 15:00 PM", FromDistance = 0 }); tempCollection.Add(new DummyStation() { Name = "Toronto, ON", ToArrival = "6:40:00 PM", ToDistance = 544, FromArrival = "7 15:00 PM", FromDistance = 0 }); } } StepStatus lastStationStatus; private DateTime SetTrainTiming(DateTime dateTime) { return dateTime.AddSeconds(trainStartTimeDiff - 6090); } public Station CreateStationInfo(string name, string toArrrival, double toDistance, string froArrrival, int index, double froDistance = 0) { DateTime dateTimeArr; DateTime toStartTime; DateTime.TryParse("7:00:00 AM", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out toStartTime); DateTime toEndTime; DateTime.TryParse("7:00:00 PM", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out toEndTime); StepStatus currentStatus = StepStatus.NotStarted; DateTime.TryParse(toArrrival, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTimeArr); dateTimeArr = SetTrainTiming(dateTimeArr); if (lastStationStatus == StepStatus.Completed) { currentStatus = StepStatus.InProgress; } if (dateTimeArr <= DateTime.Now) { currentStatus = StepStatus.Completed; } lastStationStatus = currentStatus; station = new Station() { Name = name, Arrival = dateTimeArr.TimeOfDay.ToString().Remove(5), Depature = dateTimeArr.AddMinutes(2).TimeOfDay.ToString().Remove(5), ArrivalDateTime = dateTimeArr, DepatureDateTime = dateTimeArr.AddMinutes(2), Distance = "Station at " + toDistance.ToString() + " Miles", Status = currentStatus }; if (station.Status == StepStatus.Completed) { station.ProgressedDistance = 100; } else if (station.Status == StepStatus.InProgress) { CalcuateProgressedPercentage(dateTimeArr, station, index); } else { station.ProgressedDistance = 0; } previousStationDepaturedTime = dateTimeArr.AddMinutes(2); return station; } private DateTime previousStationDepaturedTime; private async void CalcuateProgressedPercentage(DateTime upcomingStationDepaturedTime, Station station, int index) { station.ProgressedDistance = 0; DateTime lastStationDepaturedTime = previousStationDepaturedTime; while (station.ProgressedDistance < 100) { var actualDurationDifference = upcomingStationDepaturedTime.Subtract(lastStationDepaturedTime).TotalMinutes; var currentDurationDifference = DateTime.Now.Subtract(lastStationDepaturedTime).TotalMinutes; var timeDifference = DateTime.Now.Subtract(station.ArrivalDateTime).TotalSeconds; station.ProgressedDistance = (currentDurationDifference / actualDurationDifference) * 100; if (StationInfoCollection.Count > index && StationInfoCollection[index].ProgressedDistance < station.ProgressedDistance) StationInfoCollection[index].ProgressedDistance = station.ProgressedDistance; DateTime diffStationTime; DateTime.TryParse("0:00:00 AM", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out diffStationTime); diffStationTime = diffStationTime.AddSeconds((-timeDifference)); NextStationTime = ", in "; if (diffStationTime.Minute > 0) { NextStationTime += diffStationTime.Minute.ToString() + " Minute(s)"; } else { NextStationTime += diffStationTime.Second.ToString() + " Second(s)"; } await Task.Delay(1000); } for (int i = 0; i < tempCollection.Count; i++) { DummyStation s = tempCollection[i]; Station tempStation = CreateStationInfo(s.Name, s.ToArrival, s.ToDistance, s.FromArrival, i, s.FromDistance); Station currentStation = StationInfoCollection[i]; if (currentStation.ProgressedDistance != tempStation.ProgressedDistance) StationInfoCollection[i].ProgressedDistance = tempStation.ProgressedDistance; if (currentStation.Status != tempStation.Status) StationInfoCollection[i].Status = tempStation.Status; } } } public class DummyStation { public string Name { get; set; } public string ToArrival { get; set; } public double ToDistance { get; set; } public string FromArrival { get; set; } public double FromDistance { get; set; } } public class Station : INotifyPropertyChanged { private string name; public string Name { get { return name; } set { if (name != value) { name = value; RaisePropertyChange(); } } } private string arrival; public string Arrival { get { return arrival; } set { if (arrival != value) { arrival = value; RaisePropertyChange(); } } } private DateTime arrivalDateTime; public DateTime ArrivalDateTime { get { return arrivalDateTime; } set { if (arrivalDateTime != value) { arrivalDateTime = value; RaisePropertyChange(); } } } private DateTime depatureDateTime; public DateTime DepatureDateTime { get { return depatureDateTime; } set { if (depatureDateTime != value) { depatureDateTime = value; RaisePropertyChange(); } } } private string depature; public string Depature { get { return depature; } set { if (depature != value) { depature = value; RaisePropertyChange(); } } } private double progressDistance = 0; public double ProgressedDistance { get { return progressDistance; } set { if (progressDistance != value) { progressDistance = value; RaisePropertyChange("Status"); RaisePropertyChange(); } } } private string distance; public string Distance { get { return distance; } set { if (distance != value) { distance = value; RaisePropertyChange(); } } } private StepStatus status; public StepStatus Status { get { return status; } set { if (status != value) { status = value; RaisePropertyChange(); } } } public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChange([CallerMemberName] string propertyname = null) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyname)); } } } public class StatusToTextVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((DateTime)value > DateTime.Now) { return Color.FromHex("#4A515E"); } return Color.FromHex("#219F06"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }<file_sep>/Forms/Schedule/Schedule/Samples/ViewCustomization/Behaviors/CustomViewBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Custom View Behavior class /// </summary> internal class CustomViewBehavior : Behavior<Syncfusion.SfSchedule.XForms.SfSchedule> { /// <summary> /// Gets or sets associated object /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule AssociatedObject { get; set; } /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(Syncfusion.SfSchedule.XForms.SfSchedule bindable) { base.OnAttachedTo(bindable); this.AssociatedObject = bindable; this.AssociatedObject.MoveToDate = DateTime.Now.AddDays(1); bindable.VisibleDatesChangedEvent += this.BindableVisibleDatesChangedEvent; if (Device.RuntimePlatform == "iOS") { bindable.MonthViewSettings.TodayBackground = Color.Transparent; } } /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(Syncfusion.SfSchedule.XForms.SfSchedule bindable) { base.OnDetachingFrom(bindable); bindable.VisibleDatesChangedEvent -= this.BindableVisibleDatesChangedEvent; this.AssociatedObject = null; } /// <summary> /// Visible dates changed event /// </summary> /// <param name="sender">return the object</param> /// <param name="e">VisibleDates Changed Event Args</param> private void BindableVisibleDatesChangedEvent(object sender, VisibleDatesChangedEventArgs e) { var viewModel = this.AssociatedObject.BindingContext as CustomizationViewModel; if (this.AssociatedObject.ScheduleView == ScheduleView.MonthView) { var midDate = e.visibleDates[e.visibleDates.Count / 2].ToString("MMMM yyyy"); viewModel.HeaderLabelValue = midDate; } else { viewModel.HeaderLabelValue = e.visibleDates[0].Date.ToString("MMMM yyyy"); } } } }<file_sep>/Forms/Button/Button/Samples/ToggleButtonSample/ToggleButtonSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfButton { public partial class ToggleButtonSample : SampleView { public ToggleButtonSample() { InitializeComponent(); if (Device.RuntimePlatform == Device.WPF) { centerAlignButton.ImageSource = "button_alignCenter.png"; rightAlignButton.ImageSource = "button_alignRight.png"; leftAlignButton.ImageSource = "button_alignLeft.png"; } if (Device.RuntimePlatform == Device.UWP) { layout.HeightRequest = 40; } } private void FontButton_Clicked(object sender, System.EventArgs e) { Syncfusion.XForms.Buttons.SfButton button = (sender as Syncfusion.XForms.Buttons.SfButton); if (button == boldButton || button == italicButton) { if (boldButton.IsChecked && italicButton.IsChecked) { hellowWorld.FontAttributes = FontAttributes.Bold | FontAttributes.Italic; } else if (boldButton.IsChecked) { hellowWorld.FontAttributes = FontAttributes.Bold; } else if (italicButton.IsChecked) { hellowWorld.FontAttributes = FontAttributes.Italic; } else { hellowWorld.FontAttributes = FontAttributes.None; } } else if (button == underlineButton) { underlineBoxView.IsVisible = underlineButton.IsChecked; } } void Handle_Clicked(object sender, System.EventArgs e) { Syncfusion.XForms.Buttons.SfButton button = (sender as Syncfusion.XForms.Buttons.SfButton); if (button == centerAlignButton) { textStack.HorizontalOptions = LayoutOptions.Center; hellowWorld.HorizontalTextAlignment = TextAlignment.Center; centerAlignButton.BackgroundColor = Color.LightGray; leftAlignButton.BackgroundColor = Color.Transparent; rightAlignButton.BackgroundColor = Color.Transparent; } else if (button == leftAlignButton) { textStack.HorizontalOptions = LayoutOptions.Start; hellowWorld.HorizontalTextAlignment = TextAlignment.Start; centerAlignButton.BackgroundColor = Color.Transparent; leftAlignButton.BackgroundColor = Color.LightGray; rightAlignButton.BackgroundColor = Color.Transparent; } else if (button == rightAlignButton) { textStack.HorizontalOptions = LayoutOptions.End; hellowWorld.HorizontalTextAlignment = TextAlignment.End; centerAlignButton.BackgroundColor = Color.Transparent; leftAlignButton.BackgroundColor = Color.Transparent; rightAlignButton.BackgroundColor = Color.LightGray; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/BankRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfDataGrid; using System.IO; using System.Reflection; namespace SampleBrowser { public class BankRepository { public BankRepository () { } #region private variables private Random random = new Random (); #endregion #region GetBankDetails public List<BankInfo> GetBankDetails (int count) { List<BankInfo> bankDetails = new List<BankInfo> (); for (int i = 1; i <= count; i++) { var ord = new BankInfo () { CustomerID = i, BranchNo = BranchNo [random.Next (15)], Current = CurrentBalance [random.Next (15)], Savings = Savings [random.Next (15)], CustomerName = Customers [random.Next (15)], BalanceScale = random.Next (1, 100), IsOpen = ((i % random.Next (1, 10) > 2) ? true : false), CustomerImage = ImageHelper.ToUIImage (new ImageMapStream (LoadResource ("Image" + (i % 29) + ".png").ToArray ())), Transactions = random.Next(80) }; bankDetails.Add (ord); } return bankDetails; } public MemoryStream LoadResource (String Name) { MemoryStream aMem = new MemoryStream (); var assm = Assembly.GetExecutingAssembly (); var path = String.Format ("SampleBrowser.Resources.Images.{0}", Name); var aStream = assm.GetManifestResourceStream (path); aStream.CopyTo (aMem); return aMem; } #endregion int[] BranchNo = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; int[] CurrentBalance = new int[] { 25678, 34455, 44554, 23456, 78434, 93455, 34564, 34567, 23424, 65567, 22529, 34368, 12546, 90558, 6489, 55373 }; int[] Savings = new int[] { 46678, 34455, 5545, 67367, 28755, 73455, 34574, 3657, 23424, 55176, 22459, 34368, 15646, 25558, 68789, 98683, }; string[] Customers = new string[] { "Adams", "Crowley", "Ellis", "Gable", "Irvine", "Keefe", "Mendoza", "Owens", "Rooney", "Waddell", "Thomas", "Betts", "Doran", "Fitzgerald", "Holmes", "Jefferson", "Landry", "Newberry", "Perez", "Spencer", "Vargas", "Grimes", "Edwards", "Stark", "Cruise", "Fitz", "Chief", "Blanc", "Perry", "Stone", "Williams", "Lane", "Jobs" }; } } <file_sep>/Forms/PdfViewer/PdfViewer.Droid/Renderer/SfFontButtonRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Xamarin.Forms.Platform.Android.AppCompat; using Xamarin.Forms; using System.ComponentModel; using Android.Graphics; using SampleBrowser.SfPdfViewer.Droid; using SampleBrowser.SfPdfViewer; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(SfFontButton), typeof(SfFontButtonRenderer))] namespace SampleBrowser.SfPdfViewer.Droid { public class SfFontButtonRenderer : Xamarin.Forms.Platform.Android.ButtonRenderer { public SfFontButtonRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e) { base.OnElementChanged(e); double? fontSize = e.NewElement?.FontSize; if (fontSize == null || e.NewElement.FontFamily == null) { return; } Typeface font = Typeface.CreateFromAsset(Context.Assets, e.NewElement.FontFamily); Control.Typeface = font; Control.TextSize = 25; if ((Element as SfFontButton).ButtonName == "viewModeButton") Control.TextSize = 22; else if ((Element as SfFontButton).ButtonName == "popupButton") Control.TextSize = 28; else if ((Element as SfFontButton).ButtonName == "renameBookmarkButton") Control.TextSize = 16; else if ((Element as SfFontButton).ButtonName == "deleteBookmarkButton") Control.TextSize = 16; else if ((Element as SfFontButton).ButtonName == "customHeader") Control.TextSize = 20; else if ((Element as SfFontButton).ButtonName == "defaultHeader") Control.TextSize = 25; } } }<file_sep>/iOS/SampleBrowser/Samples/DataGrid/TemplateColumnCell/LinearGuageCell.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Syncfusion.SfRangeSlider.iOS; using Syncfusion.SfBarcode.iOS; using Syncfusion.SfGauge.iOS; using Syncfusion.SfDataGrid; using Syncfusion.Data; using CoreAnimation; using System.Diagnostics; using Syncfusion.SfChart.iOS; using Foundation; namespace SampleBrowser { public class GridImageCell:GridCell { private UIImageView imageview; CoreGraphics.CGRect framespec = new CoreGraphics.CGRect (); public GridImageCell () { imageview = new UIImageView (); this.CanRendererUnload = false; } protected override void UnLoad () { this.RemoveFromSuperview (); } public override void LayoutSubviews () { base.LayoutSubviews (); if (imageview.Superview == null) { this.AddSubview (imageview); framespec = new CoreGraphics.CGRect(20, 3, 60, (nfloat)DataColumn.Renderer.DataGrid.RowHeight - 5); } imageview.Frame = framespec; imageview.Image = (UIImage)DataColumn.RowData.GetType ().GetProperty ("CustomerImage").GetValue (DataColumn.RowData); } public override void Draw (CoreGraphics.CGRect rect) { base.Draw (rect); } protected override void Dispose (bool disposing) { this.imageview = null; base.Dispose (disposing); } } public class BoolFormatCell : GridCell { UISwitch swicth; public BoolFormatCell () { swicth = new UISwitch (); swicth.ValueChanged += Swicth_ValueChanged; this.CanRendererUnload = false; this.AddSubview (swicth); } void Swicth_ValueChanged (object sender, EventArgs e) { bool isChecked = (sender as UISwitch).On; DataColumn.Renderer.DataGrid.View.GetPropertyAccessProvider().SetValue (DataColumn.RowData, DataColumn.GridColumn.MappingName, isChecked); } protected override void UnLoad () { this.RemoveFromSuperview (); } public override void Draw (CoreGraphics.CGRect rect) { base.Draw (rect); } public override void LayoutSubviews () { this.swicth.Frame = new CoreGraphics.CGRect (30, 17, this.Bounds.Width, this.Bounds.Height); this.swicth.On = Convert.ToBoolean (DataColumn.CellValue); base.LayoutSubviews (); } protected override void Dispose (bool disposing) { if (this.swicth != null) { this.swicth.ValueChanged -= Swicth_ValueChanged; this.swicth.Dispose (); this.swicth = null; } base.Dispose (disposing); } } //public class LinearGuageCell:GridCell //{ // SFLinearGauge linearGauge; // SFSymbolPointer symbolPointer; // SFBarPointer rangePointer; // public LinearGuageCell () // { // linearGauge = new SFLinearGauge (); // linearGauge.Frame = new CoreGraphics.CGRect (2, 2, 105, 40); // linearGauge.BackgroundColor = base.BackgroundColor; // linearGauge.Orientation = SFLinearGaugeOrientation.SFLinearGaugeOrientationHorizontal; // //Scale // SFLinearScale scale = new SFLinearScale (); // scale.Minimum = 0; // scale.Maximum = 100; // scale.Interval = 50; // scale.ScaleBarLength = 100; // scale.ScaleBarColor = UIColor.FromRGB (250, 236, 236); // scale.LabelColor = UIColor.FromRGB (84, 84, 84); // scale.MinorTicksPerInterval = 1; // scale.ScaleBarSize = 13; // scale.ScalePosition = SFLinearGaugeScalePosition.SFLinearGaugeScalePositionForward; // scale.Hidden = true; // //SymbolPointer // symbolPointer = new SFSymbolPointer (); // symbolPointer.Offset = 0; // symbolPointer.Thickness = 3; // symbolPointer.Color = UIColor.FromRGB (65, 77, 79); // //BarPointer // rangePointer = new SFBarPointer (); // rangePointer.Color = UIColor.FromRGB (206, 69, 69); // rangePointer.Thickness = 10; // //Range // SFLinearRange range = new SFLinearRange (); // range.StartValue = 0; // range.EndValue = 50; // range.Color = UIColor.FromRGB (234, 248, 249); // range.StartWidth = 10; // range.EndWidth = 10; // range.Offset = -0.17f; // scale.Ranges.Add (range); // //Range // SFLinearRange range2 = new SFLinearRange (); // range2.StartValue = 50; // range2.EndValue = 100; // range2.Color = UIColor.FromRGB (50, 184, 198); // range2.StartWidth = 10; // range2.EndWidth = 10; // range2.Offset = -0.17f; // scale.Ranges.Add (range2); // //Minor Ticks setting // SFLinearTickSettings minor = new SFLinearTickSettings (); // minor.Length = 10; // minor.Color = UIColor.FromRGB (175, 175, 175); // minor.Thickness = 1; // scale.MinorTickSettings = minor; // //Major Ticks setting // SFLinearTickSettings major = new SFLinearTickSettings (); // major.Length = 10; // major.Color = UIColor.FromRGB (175, 175, 175); // major.Thickness = 1; // scale.MajorTickSettings = major; // scale.Pointers.Add (symbolPointer); // scale.Pointers.Add (rangePointer); // linearGauge.Scales.Add (scale); // CanRenderUnLoad = false; // this.AddSubview (linearGauge); // } // protected override void UnLoad () // { // this.RemoveFromSuperview (); // } // public override void Draw (CoreGraphics.CGRect rect) // { // this.linearGauge.Frame = new CoreGraphics.CGRect (rect.Left, rect.Top, Bounds.Width, Bounds.Height); // base.Draw (rect); // } // public override void LayoutSubviews () // { // base.LayoutSubviews (); // symbolPointer.Value = (nfloat)Convert.ToDouble (DataColumn.CellValue); // } // protected override void Dispose (bool disposing) // { // if (linearGauge != null) { // this.linearGauge.Dispose (); // } // this.linearGauge = null; // this.rangePointer = null; // this.symbolPointer = null; // base.Dispose (disposing); // } //} //public class LineChartCell : GridCell //{ // SFChart chart ; // ChartLineDataSource dataModel; // public LineChartCell () // { // chart = new SFChart (); // SFCategoryAxis primaryAxis = new SFCategoryAxis (); // primaryAxis.PlotOffset = 5; // chart.PrimaryAxis = primaryAxis; // SFNumericalAxis secondaryAxis = new SFNumericalAxis (); // chart.SecondaryAxis = secondaryAxis; // dataModel = new ChartLineDataSource (); // chart.DataSource = dataModel as SFChartDataSource; // chart.PrimaryAxis.ShowMajorGridLines = false; // chart.PrimaryAxis.Visible = false; // chart.SecondaryAxis.Visible = false; // chart.SecondaryAxis.ShowMajorGridLines = false; // chart.Legend.Visible = false; // this.AddSubview (chart); // this.CanRenderUnLoad = false; // } // protected override void UnLoad () // { // this.RemoveFromSuperview (); // } // public override void LayoutSubviews () // { // chart.Frame = new CoreGraphics.CGRect (0, 0, 105, 50); // //if((this.DataColumn.RowData as BankInfo).CustomerID <14) // // dataModel.DataPoints.ReplaceObject((nint)((this.DataColumn.RowData as BankInfo).CustomerID),new SFChartDataPoint (NSObject.FromObject ("20"+(this.DataColumn.RowData as BankInfo).CustomerID.ToString()), NSObject.FromObject((this.DataColumn.RowData as BankInfo).CustomerID.ToString()))); // //chart.ReloadData (); // base.LayoutSubviews (); // } // public override void Draw (CoreGraphics.CGRect rect) // { // base.Draw (rect); // } //} //public class ChartLineDataSource : SFChartDataSource //{ // public NSMutableArray DataPoints; // public ChartLineDataSource () // { // DataPoints = new NSMutableArray (); // AddDataPointsForChart("2010", 45); // AddDataPointsForChart("2011", 86); // AddDataPointsForChart("2012", 23); // AddDataPointsForChart("2013", 43); // AddDataPointsForChart("2014", 54); // AddDataPointsForChart("2010", 48); // AddDataPointsForChart("2011", 68); // AddDataPointsForChart("2012", 20); // AddDataPointsForChart("2013", 56); // AddDataPointsForChart("2014", 53); // AddDataPointsForChart("2010", 48); // AddDataPointsForChart("2011", 61); // AddDataPointsForChart("2012", 13); // AddDataPointsForChart("2013", 76); // AddDataPointsForChart("2014", 04); // } // void AddDataPointsForChart (String month, Double value) // { // //DataPoints.Add (new SFChartDataPoint (NSObject.FromObject (month), NSObject.FromObject(value))); // } // public override nint NumberOfSeriesInChart (SFChart chart) // { // return 1; // } // public override SFSeries GetSeries (SFChart chart, nint index) // { // SFLineSeries series = new SFLineSeries (); // series.DataMarker.ShowLabel = false; // series.LineWidth = 1; // return series; // } // public override SFChartDataPoint GetDataPoint (SFChart chart, nint index, nint seriesIndex) // { // return null;// DataPoints.GetItem<SFChartDataPoint> ((nuint)index);//returns the datapoint for each series. // } // public override nint GetNumberOfDataPoints (SFChart chart, nint index) // { // return (int)DataPoints.Count;//No of datapoints needed for each series. // } //} } <file_sep>/Forms/NumericUpDown/readme.md The numeric up down is an advanced version of the entry control that restricts input to numeric values. It supports up and down repeat buttons to increase and decrease values. It also provides a gesture-friendly UI culture that can be configured to display different formats like currency format, scientific format, and more. | Sample | Description | | ------ | ----------- | | [Online shopping](NumericUpDown/Samples/NumericUpDown) |This sample demonstrates how to select any number of fruits using numeric up and down in a Xamarin Forms application. Users can change Minimum, Maximum, AutoReverse, FontSize, SelectAllOnFocus, and SpinButtonAlignment properties in the option page.|<file_sep>/Forms/Chart/Chart/Samples/StepLineChart/StepLineSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class StepLineSeriesViewModel { public ObservableCollection<ChartDataModel> StepLineData1 { get; set; } public ObservableCollection<ChartDataModel> StepLineData2 { get; set; } public StepLineSeriesViewModel() { StepLineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(1975, 16), new ChartDataModel(1980, 12.5), new ChartDataModel(1985, 19), new ChartDataModel(1990, 14.4), new ChartDataModel(1995, 11.5), new ChartDataModel(2000, 14), new ChartDataModel(2005, 10), new ChartDataModel(2010, 16), }; StepLineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(1975, 10), new ChartDataModel(1980, 7.5), new ChartDataModel(1985, 11), new ChartDataModel(1990, 7), new ChartDataModel(1995, 8), new ChartDataModel(2000, 6), new ChartDataModel(2005, 3.5), new ChartDataModel(2010, 7), }; } } }<file_sep>/Android/SampleBrowser/Samples/DataSource/ViewModel/ContactsViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; namespace SampleBrowser { public class ContatsViewModel { #region Constructor public ContatsViewModel() { ContactsList = new ContactsLists(); } #endregion #region ItemsSource private ContactsLists contactsList; public ContactsLists ContactsList { get { return this.contactsList; } set { this.contactsList = value; } } #endregion #region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Doughnut.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Doughnut : SampleView { public Doughnut () { SFChart chart = new SFChart (); chart.Title.Text = new NSString ("Project Cost Breakdown"); chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; chart.Legend.OverflowMode = ChartLegendOverflowMode.Wrap; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; ChartViewModel dataModel = new ChartViewModel (); SFDoughnutSeries series = new SFDoughnutSeries(); series.StrokeColor = UIColor.White; series.ItemsSource = dataModel.DoughnutSeriesData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.DataMarker.ShowLabel = true; series.ExplodeOnTouch = true; series.DataMarker.LabelContent = SFChartLabelContent.Percentage; series.EnableAnimation = true; series.ColorModel.Palette = SFChartColorPalette.Natural; chart.Series.Add(series); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } }<file_sep>/iOS/SampleBrowser/Samples/TabView/OrderDetails.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; namespace SampleBrowser { internal class OrderDetails { public OrderDetails(string image, string title, string price, string offer, string rating,string description) { Image = image; Title = title; Price = price; Offer = offer; Rating = rating; Description = description; } public string Title { get; set; } public string Description { get; set; } public string Price { get; set; } public string Offer { get; set; } public string Image { get; set; } public string Rating { get; set; } } } <file_sep>/Forms/Schedule/Schedule/Samples/Timetable/Behaviors/TimetableBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Time table Behavior class /// </summary> internal class TimetableBehavior : Behavior<Syncfusion.SfSchedule.XForms.SfSchedule> { /// <summary> /// Gets or sets associated object /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule AssociatedObject { get; set; } /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(Syncfusion.SfSchedule.XForms.SfSchedule bindable) { base.OnAttachedTo(bindable); this.AssociatedObject = bindable; if (Device.RuntimePlatform == Device.Android) { this.AssociatedObject.ViewHeaderStyle.DateFontSize = 24; } bindable.VisibleDatesChangedEvent += this.BindableVisibleDatesChangedEvent; } /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(Syncfusion.SfSchedule.XForms.SfSchedule bindable) { base.OnDetachingFrom(bindable); bindable.VisibleDatesChangedEvent -= this.BindableVisibleDatesChangedEvent; this.AssociatedObject = null; } /// <summary> /// visible dates changed event /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Visible Dates Changed Event Args</param> private void BindableVisibleDatesChangedEvent(object sender, VisibleDatesChangedEventArgs e) { var viewModel = this.AssociatedObject.BindingContext as TimetableViewModel; var sfschedule = this.AssociatedObject; viewModel.Appointments = new ScheduleAppointmentCollection(); var visibleDates = e.visibleDates; var rand = new Random(); var endCalendar = DateTime.Now.Date; var startCalendar = DateTime.Now.Date; var breakStartValue = DateTime.Now.Date; var breakEndValue = DateTime.Now.Date; var break1StartValue = DateTime.Now.Date; var break2StartValue = DateTime.Now.Date; for (int i = 0; i < visibleDates.Count; i++) { if (visibleDates[i].DayOfWeek == DayOfWeek.Sunday || visibleDates[i].DayOfWeek == DayOfWeek.Saturday) { sfschedule.DayViewSettings.NonAccessibleBlocks = null; } else { sfschedule.DayViewSettings.NonAccessibleBlocks = viewModel.NonAccessibleBlocks; } if (visibleDates[i].DayOfWeek == DayOfWeek.Sunday || visibleDates[i].DayOfWeek == DayOfWeek.Saturday) { continue; } // Periods Appointments for (int j = 0; j < viewModel.StartTimeCollection.Count; j++) { startCalendar = new DateTime(visibleDates[i].Year, visibleDates[i].Month, visibleDates[i].Day, viewModel.StartTimeCollection[j].Hour, viewModel.StartTimeCollection[j].Minute, viewModel.StartTimeCollection[j].Second); endCalendar = new DateTime(visibleDates[i].Year, visibleDates[i].Month, visibleDates[i].Day, viewModel.EndTimeCollection[j].Hour, viewModel.EndTimeCollection[j].Minute, viewModel.EndTimeCollection[j].Second); var subject = viewModel.SubjectCollection[rand.Next(viewModel.SubjectCollection.Count)]; viewModel.Appointments.Add(new ScheduleAppointment() { StartTime = startCalendar, EndTime = endCalendar, Subject = subject + " (" + viewModel.StartTimeCollection[j].Hour.ToString() + ":00 -" + viewModel.EndTimeCollection[j].Hour.ToString() + ":00" + ")\n\n" + viewModel.GetStaff(subject), Color = viewModel.GetColors(subject), }); } // Break Timings breakStartValue = new DateTime(visibleDates[i].Year, visibleDates[i].Month, visibleDates[i].Day, 11, 01, 0); breakEndValue = new DateTime(visibleDates[i].Year, visibleDates[i].Month, visibleDates[i].Day, 11, 10, 0); viewModel.Appointments.Add(new ScheduleAppointment() { StartTime = breakStartValue, EndTime = breakEndValue, Color = Color.LightGray }); break1StartValue = new DateTime(visibleDates[i].Year, visibleDates[i].Month, visibleDates[i].Day, 15, 01, 0); break2StartValue = new DateTime(visibleDates[i].Year, visibleDates[i].Month, visibleDates[i].Day, 15, 10, 0); viewModel.Appointments.Add(new ScheduleAppointment() { StartTime = break1StartValue, EndTime = break2StartValue, Color = Color.LightGray }); } sfschedule.DataSource = viewModel.Appointments; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/FilteringViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "FilteringViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for Filtering sample. /// </summary> public class FilteringViewModel : INotifyPropertyChanged { #region Fields [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] internal FilterChanged Filtertextchanged; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string filtertext = string.Empty; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string selectedcolumn = "All Columns"; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string selectedcondition = "Contains"; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private List<BookInfo> bookInfo; #endregion #region Constructor /// <summary> /// Initializes a new instance of the FilteringViewModel class. /// </summary> public FilteringViewModel() { this.SetRowstoGenerate(100); } #endregion /// <summary> /// Used to send a Notification while Filter Changed /// </summary> internal delegate void FilterChanged(); /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Filtering #region Property /// <summary> /// Gets or sets the value of FilterText and notifies user when value gets changed /// </summary> public string FilterText { get { return this.filtertext; } set { this.filtertext = value; this.OnFilterTextChanged(); this.RaisePropertyChanged("FilterText"); } } /// <summary> /// Gets or sets the value of SelectedCondition /// </summary> public string SelectedCondition { get { return this.selectedcondition; } set { this.selectedcondition = value; } } /// <summary> /// Gets or sets the value of SelectedColumn /// </summary> public string SelectedColumn { get { return this.selectedcolumn; } set { this.selectedcolumn = value; } } #endregion #region ItemsSource /// <summary> /// Gets or sets the value of BookInfo /// </summary> public List<BookInfo> BookInfo { get { return this.bookInfo; } set { this.bookInfo = value; } } #endregion #region Public Methods /// <summary> /// used to decide generate records or not /// </summary> /// <param name="o">object type parameter</param> /// <returns>true or false value</returns> public bool FilerRecords(object o) { double res; bool checkNumeric = double.TryParse(this.FilterText, out res); var item = o as BookInfo; if (item != null && this.FilterText.Equals(string.Empty) && !string.IsNullOrEmpty(this.FilterText)) { return true; } else { if (item != null) { if (checkNumeric && !this.SelectedColumn.Equals("All Columns") && !this.SelectedCondition.Equals("Contains")) { bool result = this.MakeNumericFilter(item, this.SelectedColumn, this.SelectedCondition); return result; } else if (this.SelectedColumn.Equals("All Columns")) { if (item.BookName.ToLower().Contains(this.FilterText.ToLower()) || item.FirstName.ToString().ToLower().Contains(this.FilterText.ToLower()) || item.LastName.ToString().ToLower().Contains(this.FilterText.ToLower()) || item.CustomerID.ToString().ToLower().Contains(this.FilterText.ToLower()) || item.BookID.ToString().ToLower().Contains(this.FilterText.ToLower())) { return true; } return false; } else { bool result = this.MakeStringFilter(item, this.SelectedColumn, this.SelectedCondition); return result; } } } return false; } #endregion #endregion #region ItemSource Generator /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">generates row count</param> public void SetRowstoGenerate(int count) { BookRepository bookrepository = new BookRepository(); this.bookInfo = bookrepository.GetBookDetails(count); } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="propertyName">string type parameter propertyName</param> [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1630:DocumentationTextMustContainWhitespace", Justification = "Reviewed.")] public void RaisePropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion #region Private Methods /// <summary> /// Used to call the filter text changed() /// </summary> private void OnFilterTextChanged() { if (this.Filtertextchanged != null) { this.Filtertextchanged(); } } /// <summary> /// Used decide to make the string filter /// </summary> /// <param name="o">o</param> /// <param name="option">option</param> /// <param name="condition">condition</param> /// <returns>true or false value</returns> [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1630:DocumentationTextMustContainWhitespace", Justification = "Reviewed.")] private bool MakeStringFilter(BookInfo o, string option, string condition) { var value = o.GetType().GetProperty(option); var exactValue = value.GetValue(o, null); exactValue = exactValue.ToString().ToLower(); string text = this.FilterText.ToLower(); var methods = typeof(string).GetMethods(); if (methods.Count() != 0) { if (condition == "Contains") { var methodInfo = methods.FirstOrDefault(method => method.Name == condition); bool result1 = (bool)methodInfo.Invoke(exactValue, new object[] { text }); return result1; } else if (exactValue.ToString() == text.ToString()) { bool result1 = string.Equals(exactValue.ToString(), text.ToString()); if (condition == "Equals") { return result1; } else if (condition == "NotEquals") { return false; } } else if (condition == "NotEquals") { return true; } return false; } else { return false; } } /// <summary> /// Used decide to make the numeric filter /// </summary> /// <param name="o">o</param> /// <param name="option">option</param> /// <param name="condition">condition</param> /// <returns>true or false value</returns> [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1630:DocumentationTextMustContainWhitespace", Justification = "Reviewed.")] private bool MakeNumericFilter(BookInfo o, string option, string condition) { var value = o.GetType().GetProperty(option); var exactValue = value.GetValue(o, null); double res; bool checkNumeric = double.TryParse(exactValue.ToString(), out res); if (checkNumeric) { switch (condition) { case "Equals": try { if (exactValue.ToString() == this.FilterText) { if (Convert.ToDouble(exactValue) == Convert.ToDouble(this.FilterText)) { return true; } } } catch (Exception e) { Debug.WriteLine(e.Message); } break; case "NotEquals": try { if (Convert.ToDouble(this.FilterText) != Convert.ToDouble(exactValue)) { return true; } } catch (Exception e) { Debug.WriteLine(e.Message); return true; } break; } } return false; } #endregion } } <file_sep>/Android/SampleBrowser/Common/SamplePage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Views; using Android.Content; namespace SampleBrowser { public class SamplePage { #region properties public View SampleView { get; set; } internal View PropertyView { get; set; } #endregion #region methods public virtual View GetSampleContent(Context context) { return new View(context); } public virtual void OnApplyChanges(View view) { OnApplyChanges(); } public virtual void OnApplyChanges() { } public virtual View GetPropertyWindowLayout(Context context) { return null; } public virtual void Destroy() { } #endregion } }<file_sep>/Android/SampleBrowser/Samples/ImageEditor/ImageEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Syncfusion.SfImageEditor.Android; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Content; using Android.Provider; using Java.IO; using Android.Content.PM; using Android.Graphics.Drawables; using Android.Runtime; using Android.Views; namespace SampleBrowser { public class ImageEditor : SamplePage { internal static Activity Activity { get; set; } View view { get; set; } public static int Image { get; set; } ImageButton imageview3; ImageButton imageview4; ImageButton imageview5; Context con { get; set; } void View_LayoutChange(object sender, View.LayoutChangeEventArgs e) { var height = GetImageHeight(imageview3, view.Width / 3); imageview3.LayoutParameters=new TableRow.LayoutParams((int)view.Width / 3,(int)height); imageview4.LayoutParameters = new TableRow.LayoutParams((int)view.Width / 3, (int)height); imageview5.LayoutParameters = new TableRow.LayoutParams((int)view.Width / 3, (int)height); } public override Android.Views.View GetSampleContent(Android.Content.Context context) { con = context; LayoutInflater layoutInflater = LayoutInflater.From(context); view = layoutInflater.Inflate(Resource.Layout.GettingStartedImageEditor, null); imageview3 = view.FindViewById<ImageButton>(Resource.Id.imageview3); imageview4 = view.FindViewById<ImageButton>(Resource.Id.imageview4); imageview5 = view.FindViewById<ImageButton>(Resource.Id.imageview5); view.LayoutChange -= View_LayoutChange; view.LayoutChange+= View_LayoutChange; imageview3.Click += pictureOnClick1; imageview4.Click += pictureOnClick2; imageview5.Click += pictureOnClick3; LinearLayout layout = new LinearLayout(context); return view; } public void pictureOnClick1(object sender, EventArgs e) { Activity = con as Activity; Activity?.StartActivity(typeof(SfImageEditorActivity)); Image = Resource.Drawable.imageedit2; } public void pictureOnClick2(object sender, EventArgs e) { Activity = con as Activity; Activity?.StartActivity(typeof(SfImageEditorActivity)); Image = Resource.Drawable.imageedit3; } public void pictureOnClick3(object sender, EventArgs e) { Activity = con as Activity; Activity?.StartActivity(typeof(SfImageEditorActivity)); Image = Resource.Drawable.imageedit4; } private float GetImageHeight(ImageButton button, float renderWidth) { float originalWidth = 216; float originalHeight = 319; float renderedHeight = (renderWidth * originalHeight) / originalWidth; return renderedHeight; } [Activity(Label = "SfImageEditor", ScreenOrientation = ScreenOrientation.Portrait, Icon = "@drawable/icon")] public class SfImageEditorActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { SfImageEditor editor = new SfImageEditor(this); var bitmap = BitmapFactory.DecodeResource(Resources, ImageEditor.Image); editor.Bitmap = bitmap; editor.ToolbarSettings.VisibleShapesItems = ImageEditorShapes.Rectangle | ImageEditorShapes.Circle | ImageEditorShapes.Arrow | ImageEditorShapes.Line | ImageEditorShapes.DoubleArrow | ImageEditorShapes.Dotted | ImageEditorShapes.DottedArrow | ImageEditorShapes.DottedDoubleArrow; SetContentView(editor); base.OnCreate(savedInstanceState); } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/BusyIndicator/BusyIndicator_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfBusyIndicator.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class BusyIndicator_Mobile : SampleView { private readonly IList<string> animationTypes = new List<string> (); private string selectedType; UIPickerView animationPicker = new UIPickerView (); UIButton animationTextButton = new UIButton (); UILabel animationTypeLabel = new UILabel (); UIButton doneButton = new UIButton (); SFBusyIndicator busyIndicator; public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; busyIndicator.Frame=new CGRect(0,0, this.Frame.Size.Width,this.Frame.Size.Height); animationTypeLabel.Frame=new CGRect(15, 40, this.Frame.Size.Width-20, 40); animationTextButton.Frame=new CGRect(10,80, this.Frame.Size.Width-20, 40); animationPicker.Frame=new CGRect(0,this.Frame.Size.Height-( this.Frame.Size.Height/3), this.Frame.Size.Width,this.Frame.Size.Height/3); doneButton.Frame=new CGRect(0, this.Frame.Size.Height-( this.Frame.Size.Height/3), this.Frame.Size.Width, 40); } base.LayoutSubviews (); } static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } #region View lifecycle //NSArray animationTypes = new NSArray (); public BusyIndicator_Mobile() { //BusyIndicator busyIndicator = new SFBusyIndicator (); busyIndicator.Foreground = UIColor.FromRGB (36,63,217); busyIndicator.ViewBoxWidth = 100; busyIndicator.ViewBoxHeight = 100; busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeBall; this.AddSubview (busyIndicator); mainPageDesign(); } public void mainPageDesign() { //Animation Types animationTypeLabel.Text = "Animation Types"; this.animationTypes.Add((NSString)"Ball"); this.animationTypes.Add((NSString)"Battery"); this.animationTypes.Add((NSString)"DoubleCircle"); this.animationTypes.Add((NSString)"ECG"); this.animationTypes.Add((NSString)"Globe"); this.animationTypes.Add((NSString)"HorizontalPulsingBox"); this.animationTypes.Add((NSString)"MovieTimer"); this.animationTypes.Add((NSString)"Print"); this.animationTypes.Add((NSString)"Rectangle"); this.animationTypes.Add((NSString)"RollingBall"); this.animationTypes.Add((NSString)"SingleCircle"); this.animationTypes.Add((NSString)"SlicedCircle"); this.animationTypes.Add((NSString)"ZoomingTarget"); this.animationTypes.Add((NSString)"Gear"); this.animationTypes.Add((NSString)"Box"); animationTypeLabel.TextColor = UIColor.Black; this.AddSubview(animationTypeLabel); //AnimationTextButton animationTextButton.SetTitle("Ball", UIControlState.Normal); animationTextButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; animationTextButton.BackgroundColor = UIColor.Clear; animationTextButton.SetTitleColor(UIColor.Black, UIControlState.Normal); animationTextButton.Hidden = false; animationTextButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; animationTextButton.Layer.BorderWidth = 4; animationTextButton.Layer.CornerRadius = 8; animationTextButton.TouchUpInside += ShowPicker; this.AddSubview(animationTextButton); PickerModel model = new PickerModel(this.animationTypes); model.PickerChanged += (sender, e) => { this.selectedType = e.SelectedValue; animationTextButton.SetTitle(selectedType, UIControlState.Normal); if (selectedType == "Ball") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(36, 63, 217); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeBall; } else if (selectedType == "Battery") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(167, 0, 21); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeBattery; } else if (selectedType == "DoubleCircle") { busyIndicator.Duration = 0.6f; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(149, 140, 123); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeDoubleCircle; } else if (selectedType == "ECG") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(218, 144, 26); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeECG; } else if (selectedType == "Globe") { busyIndicator.Duration = 0.5f; busyIndicator.ViewBoxWidth = 100; busyIndicator.ViewBoxHeight = 100; busyIndicator.Foreground = UIColor.FromRGB(158, 168, 238); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeGlobe; } else if (selectedType == "HorizontalPulsingBox") { busyIndicator.Duration = 0.2f; busyIndicator.ViewBoxWidth = 100; busyIndicator.ViewBoxHeight = 100; busyIndicator.Foreground = UIColor.FromRGB(228, 46, 6); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeHorizontalPulsingBox; } else if (selectedType == "MovieTimer") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 100; busyIndicator.ViewBoxHeight = 100; busyIndicator.Foreground = UIColor.FromRGB(45, 45, 45); busyIndicator.SecondaryColor = UIColor.FromRGB(155, 155, 155); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeMovieTimer; } else if (selectedType == "Print") { busyIndicator.Duration = 0.5f; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(94, 111, 248); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypePrint; } else if (selectedType == "Rectangle") { busyIndicator.Duration = 0.1f; busyIndicator.ViewBoxWidth = 100; busyIndicator.ViewBoxHeight = 100; busyIndicator.Foreground = UIColor.FromRGB(39, 170, 158); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeRectangle; } else if (selectedType == "RollingBall") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(45, 45, 45); busyIndicator.SecondaryColor = UIColor.White; busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeRollingBall; } else if (selectedType == "SingleCircle") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(175, 37, 65); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSingleCircle; } else if (selectedType == "SlicedCircle") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(119, 151, 114); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; } else if (selectedType == "ZoomingTarget") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(237, 143, 60); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeZoomingTarget; } else if (selectedType == "Gear") { busyIndicator.Duration = 1.5f; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.Gray; busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeGear; } else if (selectedType == "Box") { busyIndicator.Duration = 0.1f; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(36, 63, 217); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeBox; } }; //AnimationPicker animationPicker.ShowSelectionIndicator = true; animationPicker.Hidden = false; animationPicker.Model = model; animationPicker.BackgroundColor = UIColor.White; this.AddSubview(animationPicker); //DoneButton doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.Hidden = false; doneButton.TouchUpInside += HidePicker; this.AddSubview(doneButton); this.BackgroundColor = UIColor.White; } void ShowPicker (object sender, EventArgs e) { doneButton.Hidden = false; animationPicker.Hidden = false; this.BecomeFirstResponder (); } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; animationPicker.Hidden = true; this.BecomeFirstResponder (); } #endregion } }<file_sep>/Forms/Diagram/Diagram/Samples/OrganizationChart/OrganizationChart.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfDiagram.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfDiagram { public partial class OrganizationChart : SampleView { Dictionary<string, Color> FillColor; Dictionary<string, Color> StrokeColor; Frame Notifier; bool IsOverviewEnabled; public OrganizationChart() { InitializeComponent(); if (Device.RuntimePlatform == Device.Android) { Xamarin.Forms.DependencyService.Get<IText>().GenerateFactor(); diagram.IsReadOnly = true; } if (Device.RuntimePlatform == Device.UWP) { diagram.IsReadOnly = true; diagram.BackgroundColor = Color.White; } diagram.EnableSelectors = false; diagram.PageSettings.PageBackGround = Color.White; diagram.NodeClicked += Diagram_NodeClicked; diagram.DiagramClicked += Diagram_DiagramClicked; FillColor = new Dictionary<string, Color>(); FillColor.Add("Managing Director", Color.FromRgb(239, 75, 93)); FillColor.Add("Project Manager", Color.FromRgb(49, 162, 255)); FillColor.Add("Senior Manager", Color.FromRgb(49, 162, 255)); FillColor.Add("Project Lead", Color.FromRgb(0, 194, 192)); FillColor.Add("Senior S/W Engg", Color.FromRgb(0, 194, 192)); FillColor.Add("Software Engg", Color.FromRgb(0, 194, 192)); FillColor.Add("Team Lead", Color.FromRgb(0, 194, 192)); FillColor.Add("Project Trainee", Color.FromRgb(255, 129, 0)); StrokeColor = new Dictionary<string, Color>(); StrokeColor.Add("Managing Director", Color.FromRgb(201, 32, 61)); StrokeColor.Add("Project Manager", Color.FromRgb(23, 132, 206)); StrokeColor.Add("Senior Manager", Color.FromRgb(23, 132, 206)); StrokeColor.Add("Project Lead", Color.FromRgb(4, 142, 135)); StrokeColor.Add("Senior S/W Engg", Color.FromRgb(4, 142, 135)); StrokeColor.Add("Software Engg", Color.FromRgb(4, 142, 135)); StrokeColor.Add("Team Lead", Color.FromRgb(4, 142, 135)); StrokeColor.Add("Project Trainee", Color.FromRgb(206, 98, 9)); DataModel datamodel = new DataModel(); DataSourceSettings settings = new DataSourceSettings(); datamodel.Data(); settings.ParentId = "ReportingPerson"; settings.Id = "Name"; settings.DataSource = datamodel.employee; diagram.DataSourceSettings = settings; //To Represent LayoutManager Properties if (Device.RuntimePlatform == Device.UWP) { diagram.LayoutManager = new LayoutManager() { Layout = new DirectedTreeLayout() { Type = LayoutType.Hierarchical, HorizontalSpacing = 35, } }; } else { diagram.LayoutManager = new LayoutManager() { Layout = new DirectedTreeLayout() { Type = LayoutType.Organization, HorizontalSpacing = 35, } }; } for (int i = 0; i < diagram.Connectors.Count; i++) { diagram.Connectors[i].TargetDecoratorType = DecoratorType.None; diagram.Connectors[i].Style.StrokeBrush = new SolidBrush(Color.FromRgb(127, 132, 133)); diagram.Connectors[i].Style.StrokeWidth = 1; } if (Device.RuntimePlatform != Device.UWP) overview.PreventRefresh = true; diagram.BeginNodeRender += Diagram_BeginNodeRender; diagram.BeginNodeLayout += Diagram_BeginNodeLayout; diagram.ItemLongPressed += Diagram_ItemLongPressed; diagram.Loaded += Diagram_Loaded; diagram.LayoutNodeDropped += Diagram_OnLayoutNodeDropped; diagram.OverviewPanel = overview; if (Device.RuntimePlatform == Device.iOS) { overview.Width = 200; overview.Height = 200; } diagram.EndNodeLayout += Diagram_EndNodeLayout; ToggleOverview(true); if (Device.RuntimePlatform != Device.UWP && Device.Idiom != TargetIdiom.Tablet) { ToggleOverview(false); IsOverviewEnabled = false; overviewSwitch.IsVisible = false; LayoutTextLabel.IsVisible = false; } if(Device.RuntimePlatform == Device.UWP) { LayoutNodeDrag.IsVisible = false; LayoutNodeDragLabel.IsVisible = false; } } private void Diagram_EndNodeLayout(object sender, EventArgs e) { UpdateOverviewPanel(); } private void UpdateOverviewPanel() { if (diagram.OverviewPanel != null && IsOverviewEnabled) { diagram.OverviewPanel.ForceRefresh(); } } private void Diagram_OnLayoutNodeDropped(object sender, LayoutNodeDroppedEventArgs args) { Node draggedNode = args.DraggedItem as Node; Node droppedNode = args.DroppedItem as Node; bool contain = true; if (draggedNode != null && draggedNode != droppedNode) { Node ParentNode = GetParent((droppedNode.Content as DiagramEmployee).ReportingPerson); do { if (ParentNode != draggedNode) { contain = false; } else { contain = true; break; } ParentNode = GetParent((ParentNode.Content as DiagramEmployee).ReportingPerson); } while (ParentNode != null); if (!contain) { List<Connector> connectors = draggedNode.InConnectors as List<Connector>; Connector con; bool hasChild = false; for (int i = 0; i < connectors.Count; i++) { con = connectors[i]; con.SourceNode = droppedNode; hasChild = true; } if (hasChild) { Node PrevParentNode = GetParent((draggedNode.Content as DiagramEmployee).ReportingPerson); if (PrevParentNode != null && PrevParentNode.OutConnectors.Count == 0) { (PrevParentNode.Content as DiagramEmployee).HasChild = false; if (Device.RuntimePlatform == Device.iOS) DrawTemplate(PrevParentNode); else UpdateTemplate(PrevParentNode, ""); } DiagramEmployee ParentEmployee = (droppedNode.Content as DiagramEmployee); (draggedNode.Content as DiagramEmployee).ReportingPerson = ParentEmployee.Name; ParentEmployee.HasChild = true; UpdateTemplate(droppedNode, "-"); ExpandAll(draggedNode); droppedNode.IsExpanded = true; diagram.LayoutManager.Layout.UpdateLayout(); UpdateOverviewPanel(); } } } } private void ExpandAll(Node node) { if ((node.Content as DiagramEmployee).HasChild) { node.IsExpanded = true; UpdateTemplate(node, "-"); if (node.OutConnectors.Count() > 0) { foreach (var c in node.OutConnectors) { if (c.TargetNode != null) { ExpandAll(c.TargetNode); } } } } } private Node GetParent(string parentId) { foreach (Node node in diagram.Nodes) { if ((node.Content as DiagramEmployee).Name == parentId) { return node; } } return null; } void LayoutNodeDrag_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e) { if (LayoutNodeDrag.IsToggled) { (diagram.LayoutManager.Layout as DirectedTreeLayout).IsDraggable = true; } else { (diagram.LayoutManager.Layout as DirectedTreeLayout).IsDraggable = false; } } private void Diagram_Loaded(object sender) { var RootNode = diagram.Nodes[0]; diagram.BringToView(RootNode); UpdateOverviewPanel(); } private void ToggleOverview(bool isShow) { if (isShow) { if(Device.RuntimePlatform == Device.UWP) parent.RowDefinitions[1].Height = GridLength.Star; ToggleOverviewPanel(isShow, 200); } else { if (Device.RuntimePlatform == Device.UWP) parent.RowDefinitions[1].Height = GridLength.Auto; ToggleOverviewPanel(isShow, 0); } } private void ToggleOverviewPanel(bool state, int heightReq) { IsOverviewEnabled = state; OverviewPanel.IsVisible = state; OverviewPanel.HeightRequest = heightReq; } private void Diagram_ItemLongPressed(object sender, ItemLongPressedEventArgs args) { if (args.Item is Node && !LayoutNodeDrag.IsToggled) DisplayInfo(args.Item as Node); } void Diagram_NodeClicked(object sender, NodeClickedEventArgs args) { if ((args.Item.Content as DiagramEmployee).HasChild && args.Item.IsExpanded) { UpdateTemplate(args.Item, "+"); args.Item.IsExpanded = false; } else if ((args.Item.Content as DiagramEmployee).HasChild && !args.Item.IsExpanded) { UpdateTemplate(args.Item, "-"); args.Item.IsExpanded = true; } if (Device.RuntimePlatform == Device.iOS) diagram.OverviewPanel.ForceRefresh(); } private void Diagram_BeginNodeRender(object sender, BeginNodeRenderEventArgs args) { var node = (args.Item as Node); UpdateTemplate(node, "-"); } private void Diagram_BeginNodeLayout(object sender, BeginNodeLayoutEventArgs args) { if (!args.HasChildNodes) { args.Type = ChartType.Left; args.Orientation = Orientation.Vertical; } } void overview_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e) { ToggleOverview(overviewSwitch.IsToggled); } private void DrawTemplate(Node node) { node.Style.StrokeWidth = 1; StackLayout root; var NodeTemplate = new DataTemplate(() => { root = new StackLayout() { WidthRequest = node.Width, HeightRequest = node.Height, Orientation = StackOrientation.Horizontal, BackgroundColor = Color.Transparent }; Image image = new Image(); image.WidthRequest = 35; image.HeightRequest = 35; image.Margin = new Thickness(8); image.Source = (node.Content as DiagramEmployee).ImageUrl; root.Children.Add(image); StackLayout content = new StackLayout() { WidthRequest = 100, HeightRequest = 40, Orientation = StackOrientation.Vertical }; Label name = new Label() { TextColor = Color.FromRgb(255, 255, 255), Margin = new Thickness(0, 8, 0, 0), Text = (node.Content as DiagramEmployee).Name, FontSize = 10, HorizontalOptions = LayoutOptions.StartAndExpand }; Label designation = new Label() { Text = (node.Content as DiagramEmployee).Designation, TextColor = Color.FromRgb(255, 255, 255), FontSize = 10, HorizontalOptions = LayoutOptions.StartAndExpand }; content.Children.Add(name); content.Children.Add(designation); root.Children.Add(content); Frame style = new Frame(); style.Content = root; style.Padding = new Thickness(0); style.CornerRadius = 5; style.BackgroundColor = FillColor[(node.Content as DiagramEmployee).Designation]; style.BorderColor = StrokeColor[((node.Content as DiagramEmployee).Designation)]; style.HasShadow = false; return style; }); node.Template = NodeTemplate; } private void UpdateTemplate(Node node, string state) { if (Device.RuntimePlatform == Device.UWP) { node.Width = 150; node.Height = 50; } node.Style.StrokeWidth = 1; StackLayout root; var NodeTemplate = new DataTemplate(() => { root = new StackLayout() { Orientation = StackOrientation.Horizontal, BackgroundColor = Color.Transparent }; Image image = new Image(); image.WidthRequest = 35; image.HeightRequest = 35; image.Margin = new Thickness(8); if (Device.RuntimePlatform == Device.UWP) { image.Source = ImagePathConverter.GetImageSource((node.Content as DiagramEmployee).ImageUrl); } else { image.Source = (node.Content as DiagramEmployee).ImageUrl; } root.Children.Add(image); StackLayout content = new StackLayout() { WidthRequest = 100, HeightRequest = 40, Orientation = StackOrientation.Vertical }; Label name = new Label() { TextColor = Color.FromRgb(255, 255, 255), Margin = new Thickness(0, 8, 0, 0), Text = (node.Content as DiagramEmployee).Name, FontSize = 10, HorizontalOptions = LayoutOptions.StartAndExpand }; // name.SetBinding(Label.TextProperty, new Binding((node.Content as Employee).Name)); Label designation = new Label() { Text = (node.Content as DiagramEmployee).Designation, TextColor = Color.FromRgb(255, 255, 255), FontSize = 10, HorizontalOptions = LayoutOptions.StartAndExpand }; // designation.SetBinding(Label.TextProperty, new Binding((node.Content as Employee).Designation)); content.Children.Add(name); content.Children.Add(designation); root.Children.Add(content); if (Device.RuntimePlatform != Device.UWP) if ((node.Content as DiagramEmployee).HasChild) { root.WidthRequest = 180; Label Expand = new Label() { TextColor = Color.White, Text = state, FontSize = 35, VerticalOptions = LayoutOptions.Center }; Expand.Margin = new Thickness(0, 0, 5, 3); root.Children.Add(Expand); } if (Device.RuntimePlatform == Device.Android) return root; else { Frame style = new Frame(); style.Content = root; style.Padding = new Thickness(0); style.CornerRadius = 5; style.BackgroundColor = FillColor[(node.Content as DiagramEmployee).Designation]; style.BorderColor = StrokeColor[((node.Content as DiagramEmployee).Designation)]; style.HasShadow = false; return style; } }); if (Device.RuntimePlatform == Device.Android) { node.Style.Brush = new SolidBrush(FillColor[(node.Content as DiagramEmployee).Designation]); node.Style.StrokeBrush = new SolidBrush(StrokeColor[((node.Content as DiagramEmployee).Designation)]); } node.Template = NodeTemplate; } void Diagram_DiagramClicked(object sender, DiagramClickedEventArgs args) { if (Notifier != null) { parent.Children.Remove(Notifier); Notifier = null; diagram.EnableZoomAndPan = true; diagram.NodeClicked += Diagram_NodeClicked; diagram.ItemLongPressed += Diagram_ItemLongPressed; } } void Ok_Clicked(object sender, EventArgs e) { parent.Children.Remove(Notifier); Notifier = null; diagram.EnableZoomAndPan = true; diagram.NodeClicked += Diagram_NodeClicked; diagram.ItemLongPressed += Diagram_ItemLongPressed; } void DisplayInfo(Node node) { diagram.EnableZoomAndPan = false; diagram.NodeClicked -= Diagram_NodeClicked; diagram.ItemLongPressed -= Diagram_ItemLongPressed; StackLayout root; root = new StackLayout(); Image image = new Image(); image.WidthRequest = 120; image.HeightRequest = 120; image.VerticalOptions = LayoutOptions.Start; image.HorizontalOptions = LayoutOptions.Center; image.Source = (node.Content as DiagramEmployee).ImageUrl; root.Children.Add(image); Label Name = new Label { Text = (node.Content as DiagramEmployee).Name, HorizontalOptions = LayoutOptions.CenterAndExpand }; Name.TextColor = Color.Black; Name.FontAttributes = FontAttributes.Bold; root.Children.Add(Name); Grid grid = new Grid(); grid.RowSpacing = 12; grid.HorizontalOptions = LayoutOptions.CenterAndExpand; grid.Margin = new Thickness(0, 22, 0, 0); grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }); grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) }); grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); var Designation = new Label { Text = "Designation:", HorizontalOptions = LayoutOptions.End }; var DesignationValue = new Label { Text = (node.Content as DiagramEmployee).Designation, HorizontalOptions = LayoutOptions.Start, FontAttributes = FontAttributes.Bold, TextColor = Color.Black }; var ID = new Label { Text = "ID:", HorizontalOptions = LayoutOptions.End }; var IDValue = new Label { Text = (node.Content as DiagramEmployee).ID, HorizontalOptions = LayoutOptions.Start, FontAttributes = FontAttributes.Bold, TextColor = Color.Black }; var DOJ = new Label { Text = "DOJ:", HorizontalOptions = LayoutOptions.End }; var DOJValue = new Label { Text = (node.Content as DiagramEmployee).DOJ, HorizontalOptions = LayoutOptions.Start, FontAttributes = FontAttributes.Bold, TextColor = Color.Black }; grid.Children.Add(Designation, 0, 0); grid.Children.Add(DesignationValue, 1, 0); grid.Children.Add(ID, 0, 1); grid.Children.Add(IDValue, 1, 1); grid.Children.Add(DOJ, 0, 2); grid.Children.Add(DOJValue, 1, 2); if ((node.Content as DiagramEmployee).ReportingPerson != null) { var Supervisor = new Label { Text = "Supervisor:", HorizontalOptions = LayoutOptions.End }; var SupervisorValue = new Label { Text = (node.Content as DiagramEmployee).ReportingPerson, HorizontalOptions = LayoutOptions.Start, FontAttributes = FontAttributes.Bold, TextColor = Color.Black }; grid.Children.Add(Supervisor, 0, 3); grid.Children.Add(SupervisorValue, 1, 3); } BoxView line = new BoxView() { BackgroundColor = Color.Gray, VerticalOptions = LayoutOptions.Start, HorizontalOptions = LayoutOptions.FillAndExpand, HeightRequest = 1 }; grid.Children.Add(line, 0, 4); Grid.SetColumnSpan(line, 2); Button button = new Button { Text = "CLOSE", BackgroundColor = Color.White, HorizontalOptions = LayoutOptions.FillAndExpand, WidthRequest = 300, Margin = new Thickness(0, 2, 0, 2) }; button.Clicked += Ok_Clicked; grid.Children.Add(button, 0, 4); Grid.SetColumnSpan(button, 2); root.Children.Add(grid); Notifier = new Frame(); Notifier.WidthRequest = 300; if (Device.RuntimePlatform == Device.Android) Notifier.HeightRequest = 350; else Notifier.HeightRequest = 350; Notifier.Content = root; Notifier.VerticalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Center }; Notifier.HorizontalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Center }; Notifier.CornerRadius = 5; Notifier.BackgroundColor = Color.White; Notifier.BorderColor = FillColor[(node.Content as DiagramEmployee).Designation]; parent.Children.Add(Notifier); } } [Preserve(AllMembers = true)] public class OverviewPanelBorderHelper : Frame { } } <file_sep>/Forms/ComboBox/ComboBox/Samples/ToleratingTypos/ToleratingTypos.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfComboBox { public partial class ToleratingTypos : SampleView, INotifyPropertyChanged { bool check = true; SelectionIndicatorViewModel view = new SelectionIndicatorViewModel(); public ToleratingTypos() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { layoutRoot.HorizontalOptions = LayoutOptions.Center; layoutRoot.WidthRequest = 500; } this.BindingContext = view; check = false; listView.SeparatorColor = Color.Transparent; check = true; } public override void OnAppearing() { base.OnAppearing(); } void Handle_SelectionChanged(object sender, Syncfusion.XForms.ComboBox.SelectionChangedEventArgs e) { List<object> items=new List<object>(); if (e.Value != null && (((e.Value is string && (string)e.Value != string.Empty)) || (e.Value is IList && (e.Value as IList).Count > 0)) && check) { if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { if (e.Value as ObservableCollection<object> != null) { items = new List<object>(e.Value as ObservableCollection<object>); } } else { for (int ii = 0; ii < (e.Value as List<object>).Count; ii++) { var collection = (e.Value as List<object>)[ii]; items.Add(collection); } } view.SelectedItem1 = items; if (items.Count > 0) { listView.SeparatorColor = Color.Black; } else { listView.SeparatorColor = Color.Transparent; } } else { view.SelectedItem1 = null; } } } public class Applicationlist { private string appimage; public string AppImage { get { return appimage; } set { appimage = value; } } private string name; public string AppName { get { return name; } set { name = value; } } private string date; public string Date { get { return date; } set { date = value; } } } public class SelectionIndicatorViewModel : INotifyPropertyChanged { private ObservableCollection<Applicationlist> appCollection; public ObservableCollection<Applicationlist> AppCollection { get { return appCollection; } set { appCollection = value; RaisePropertyChanged("AppCollection"); } } private List<object> selectedItem; public List<object> SelectedItem1 { get { return selectedItem; } set { selectedItem = value; RaisePropertyChanged("SelectedItem1"); } } public SelectionIndicatorViewModel() { appCollection = new ObservableCollection<Applicationlist>(); appCollection.Add(new Applicationlist() { AppImage = "Calculator.png", AppName = "Calculator", Date = "Updated 2 days ago" }); appCollection.Add(new Applicationlist() { AppImage = "Camera.png", AppName = "Camera",Date = "Updated 4 days ago" }); appCollection.Add(new Applicationlist() { AppImage = "CDMusic.png", AppName = "CD Music", Date = "Updated 9 days ago" }); appCollection.Add(new Applicationlist() { AppImage = "Excel.png", AppName = "Excel", Date = "Updated 2 hours ago" }); appCollection.Add(new Applicationlist() { AppImage = "GmailFill.png", AppName = "Gmail", Date = "Updated 9 days ago" }); appCollection.Add(new Applicationlist() { AppImage = "ChromeFill.png", AppName = "Google Chrome", Date = "Updated 2 hours ago" }); appCollection.Add(new Applicationlist() { AppImage = "Instagram.png", AppName = "Instagram", Date = "Updated 8 days ago" }); appCollection.Add(new Applicationlist() { AppImage = "Maps_Red.png", AppName = "Maps", Date = "Updated 11 days ago" }); appCollection.Add(new Applicationlist() { AppImage = "MicrosoftPowerPoint.png", AppName = "Microsoft Power Point", Date = "Updated 9 days ago" }); appCollection.Add(new Applicationlist() { AppImage = "MicrosoftWord.png", AppName = "Microsoft Word", Date = "Updated 7 days ago" }); appCollection.Add(new Applicationlist() { AppImage = "SkypeFill.png", AppName = "Skype", Date = "Updated 1 day ago" }); appCollection.Add(new Applicationlist() { AppImage = "Twitter.png", AppName = "Twitter", Date = "Updated 6 weeks ago" }); appCollection.Add(new Applicationlist() { AppImage = "YahooFill.png", AppName = "Yahoo", Date = "Updated 2 days ago" }); } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } public class SelectionBoolToBackgroundColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return (bool)value == true ? Color.FromRgb(211, 211, 211) : Color.White; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/PullToRefresh/PullToRefreshBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PullToRefreshBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfPullToRefresh.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the PullToRefresh samples /// </summary> public class PullToRefreshBehavior : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfPullToRefresh.XForms.SfPullToRefresh pullToRefresh; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid datagrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt transitionType; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DataBindingViewModel viewModel; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of parameter bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.viewModel = new DataBindingViewModel(); bindAble.BindingContext = this.viewModel; this.pullToRefresh = bindAble.FindByName<Syncfusion.SfPullToRefresh.XForms.SfPullToRefresh>("pullToRefresh"); this.datagrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.datagrid.ItemsSource = this.viewModel.OrdersInfo; this.transitionType = bindAble.FindByName<PickerExt>("transitionType"); this.datagrid.ItemsSource = this.viewModel.OrdersInfo; this.transitionType.Items.Add("SlideOnTop"); this.transitionType.Items.Add("Push"); this.transitionType.SelectedIndex = 0; this.transitionType.SelectedIndexChanged += this.OnSelectionChanged; this.pullToRefresh.Refreshing += this.PullToRefresh_Refreshing; if (Device.RuntimePlatform == Device.UWP) { this.pullToRefresh.ProgressBackgroundColor = Color.FromHex("0065ff"); this.pullToRefresh.ProgressStrokeColor = Color.FromHex("#ffffff"); } base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">bindAble Object type of bindAble</param> protected override void OnDetachingFrom(BindableObject bindAble) { this.transitionType.SelectedIndexChanged -= this.OnSelectionChanged; this.pullToRefresh.Refreshing -= this.PullToRefresh_Refreshing; this.pullToRefresh = null; this.datagrid = null; this.viewModel = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Triggers while PullToRefresh View was refreshing /// </summary> /// <param name="sender">PullToRefresh_Refreshing event sender</param> /// <param name="e">PullToRefresh_Refreshing event args e</param> private async void PullToRefresh_Refreshing(object sender, EventArgs e) { this.pullToRefresh.IsRefreshing = true; await Task.Delay(1200); this.viewModel.ItemsSourceRefresh(); this.pullToRefresh.IsRefreshing = false; } /// <summary> /// Triggers while selection of records was changed /// </summary> /// <param name="sender">OnSelectionChanged sender</param> /// <param name="e">OnSelectionChanged event args e</param> private void OnSelectionChanged(object sender, EventArgs e) { if (Device.RuntimePlatform == Device.UWP) { this.pullToRefresh.ProgressBackgroundColor = Color.FromHex("0065ff"); this.pullToRefresh.ProgressStrokeColor = Color.FromHex("#ffffff"); } if (this.transitionType.SelectedIndex == 0) { this.pullToRefresh.TransitionMode = TransitionType.SlideOnTop; } else { this.pullToRefresh.TransitionMode = TransitionType.Push; } } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/OnBoardHelps/OnBoardHelpsBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "OnBoardHelpsBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using Core; using Syncfusion.SfDataGrid.XForms; using Syncfusion.XForms.PopupLayout; using Xamarin.Forms; using SfDataGrid = Syncfusion.SfDataGrid.XForms.SfDataGrid; /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the OnBoardHelps samples /// </summary> public class OnBoardHelpsBehavior : Behavior<SampleView> { /// <summary> /// Holds the instance of the DataGrid. /// </summary> private SfDataGrid datagrid; /// <summary> /// Holds the instance of PopupLayout. /// </summary> private SfPopupLayout popupLayout; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type parameter named as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { base.OnAttachedTo(bindAble); this.popupLayout = bindAble.Content.FindByName<SfPopupLayout>("popupLayout"); this.datagrid = bindAble.Content.FindByName<SfDataGrid>("dataGrid"); this.datagrid.GridLoaded += this.Datagrid_GridLoaded; this.datagrid.AutoGeneratingColumn += this.Datagrid_AutoGeneratingColumn; } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type parameter named as bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.datagrid.AutoGeneratingColumn -= this.Datagrid_AutoGeneratingColumn; this.datagrid.GridLoaded -= this.Datagrid_GridLoaded; this.popupLayout.Dispose(); this.popupLayout = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Fired when DataGrid comes in to the View /// </summary> /// <param name="sender">DataGrid_GridLoaded event sender</param> /// <param name="e">DataGrid_GridLoaded events args e</param> private void Datagrid_GridLoaded(object sender, GridLoadedEventArgs e) { this.popupLayout.PopupView.HeightRequest = this.datagrid.Height; this.popupLayout.PopupView.WidthRequest = this.datagrid.Width; if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.Android) { this.popupLayout.Show((double)0, 90); } else if (Device.RuntimePlatform == Device.iOS) { this.popupLayout.Show((double)0, 50); } else { this.popupLayout.Show((double)0, 40); } } /// <summary> /// Occurs when <see cref="AutoGenerateColumns"/>is set as true. Using this event, the user /// can customize the columns being generated automatically. /// </summary> /// <param name="sender">DataGrid_AutoGeneratingColumn event sender</param> /// <param name="e">DataGrid_AutoGeneratingColumn event args e</param> private void Datagrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnEventArgs e) { e.Column.HeaderFontAttribute = FontAttributes.Bold; } } }<file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/UICollectionView Helper/CollectionViewCell.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using CoreGraphics; namespace SampleBrowser { public class CollectionViewCell : UICollectionViewCell { public static NSString CellID = new NSString("userCell"); public CircleView imageView { get; set; } public UILabel senderLabel { get; set; } public UILabel dateLabel { get; set; } public UILabel subjectLabel { get; set; } public UILabel detailsLabel { get; set; } public CollectionViewCell(IntPtr handle) : base(handle) { } [Export("initWithFrame:")] public CollectionViewCell(CGRect frame) : base(frame) { InitializeViews(); } private void InitializeViews() { imageView = new CircleView(new CGRect(5, 10, 45, 50)); senderLabel = new UILabel(new CGRect(55, 5, this.Frame.Width - 60, 20)); senderLabel.Lines = 1; senderLabel.Font = UIFont.BoldSystemFontOfSize(16); dateLabel = new UILabel(new CGRect(senderLabel.Frame.Width, 5, 40, 20)); dateLabel.Font = UIFont.BoldSystemFontOfSize(10); dateLabel.TextColor = UIColor.FromRGB(0, 121, 255); subjectLabel = new UILabel(new CGRect(55, 25, this.Frame.Width - 70, 20)); subjectLabel.Lines = 1; subjectLabel.LineBreakMode = UILineBreakMode.TailTruncation; subjectLabel.Font = UIFont.BoldSystemFontOfSize(13); detailsLabel = new UILabel(new CGRect(55, 45, this.Frame.Width - 70, 20)); detailsLabel.Lines = 1; detailsLabel.LineBreakMode = UILineBreakMode.TailTruncation; detailsLabel.Font = UIFont.SystemFontOfSize(12); ContentView.AddSubview(imageView); ContentView.AddSubview(senderLabel); ContentView.AddSubview(dateLabel); ContentView.AddSubview(subjectLabel); ContentView.AddSubview(detailsLabel); } public void UpdateRow(Mail data) { senderLabel.Text = data.Sender; subjectLabel.Text = data.Subject; detailsLabel.Text = data.Details; dateLabel.Text = "20 Oct"; imageView.ViewColor = data.BackgroundColor; imageView.text = data.Sender[0].ToString(); imageView.SetNeedsDisplay(); } } }<file_sep>/Forms/Picker/Picker.UWP/ButtonRenderer.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Xamarin.Forms.Platform.UWP; using Button = Xamarin.Forms.Button; [assembly: ExportRenderer(typeof(SampleBrowser.SfPicker.CustomButton), typeof(SampleBrowser.UWP.CustomButtonRenderer))] namespace SampleBrowser.UWP { public class CustomButtonRenderer : ButtonRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Button> e) { base.OnElementChanged(e); if (e.NewElement == null) return; Control.Padding = new Windows.UI.Xaml.Thickness(2, 2, 2, 2); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Paging/PagerAppearance.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PagerAppearance.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Syncfusion.SfDataGrid.XForms.DataPager; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Custom class of Data Pager Appearance Manager to override the Colors /// </summary> public class PagerAppearance : AppearanceManager { /// <summary> /// Override this method to apply the custom style for pager button /// </summary> /// <param name="shape">Shape of the numeric button</param> /// <returns>Color as given</returns> public override Color GetPagerButtonBorderColor(ButtonShape shape = ButtonShape.Rectangle) { if (shape == ButtonShape.Rectangle) { return Color.Transparent; } else { return Color.FromHex("#CACACA"); } } } } <file_sep>/Forms/ImageEditor/ImageEditor/CustomControls/CustomEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfImageEditor.CustomControls { public class CustomEditor : Editor { public CustomEditor() { } public static readonly BindableProperty WatermarkTextProperty = BindableProperty.Create("WatermarkText", typeof(string), typeof(CustomEditor), "Enter a caption !!!", BindingMode.Default, null, null); public string WatermarkText { get { return (string)GetValue(WatermarkTextProperty); } set { SetValue(WatermarkTextProperty, value); } } } public class RoundedColorButton : Button { } public class CustomButton : Button { } public class CustomImageView :Image { } } <file_sep>/Android/SampleBrowser/Samples/CircularGauge/Pointers.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfCircularGauge; using System.Collections.ObjectModel; using Android.Graphics; using Com.Syncfusion.Gauges.SfCircularGauge.Enums; using Android.Renderscripts; using static Android.App.ActionBar; namespace SampleBrowser { public class Pointers : SamplePage { public override View GetSampleContent(Context con) { SfCircularGauge sfCircularGauge = new SfCircularGauge(con); ObservableCollection<Header> headers = new ObservableCollection<Header>(); Header header = new Header(); header.Text = "Inverted Traingle"; header.TextSize = 18; header.TextColor = Color.Black; header.Position = new PointF((float)0.5, (float)0.6); headers.Add(header); sfCircularGauge.Headers = headers; ObservableCollection<CircularScale> circularScales = new ObservableCollection<CircularScale>(); CircularScale scale = new CircularScale(); scale.StartAngle = 180; scale.SweepAngle = 180; scale.ScaleStartOffset = 0.7; scale.ScaleEndOffset = 0.68; scale.StartValue = 0; scale.EndValue = 100; scale.RimColor = Color.Gray; scale.Interval = 50; scale.ShowLabels = false; scale.ShowTicks = false; scale.MinorTicksPerInterval = 0; ObservableCollection<CircularPointer> pointers = new ObservableCollection<CircularPointer>(); MarkerPointer markerPointer = new MarkerPointer(); markerPointer.Value = 80; markerPointer.Color = Color.ParseColor("#00bdae"); markerPointer.Offset = 0.7; markerPointer.MarkerShape = Com.Syncfusion.Gauges.SfCircularGauge.Enums.MarkerShape.InvertedTriangle; pointers.Add(markerPointer); scale.CircularPointers = pointers; circularScales.Add(scale); sfCircularGauge.CircularScales = circularScales; sfCircularGauge.SetBackgroundColor(Color.White); //triangle SfCircularGauge sfCircularGauge1 = new SfCircularGauge(con); ObservableCollection<Header> headers1 = new ObservableCollection<Header>(); Header header1 = new Header(); header1.Text = "Traingle"; header1.TextSize = 18; header1.TextColor = Color.Black; header1.Position = new PointF((float)0.5, (float)0.6); headers1.Add(header1); sfCircularGauge1.Headers = headers1; ObservableCollection<CircularScale> circularScales1 = new ObservableCollection<CircularScale>(); CircularScale scale1 = new CircularScale(); scale1.StartAngle = 180; scale1.SweepAngle = 180; scale1.ScaleStartOffset = 0.7; scale1.ScaleEndOffset = 0.68; scale1.StartValue = 0; scale1.EndValue = 100; scale1.RimColor = Color.Gray; scale1.Interval = 50; scale1.ShowLabels = false; scale1.ShowTicks = false; scale1.MinorTicksPerInterval = 0; ObservableCollection<CircularPointer> pointers1 = new ObservableCollection<CircularPointer>(); MarkerPointer markerPointer1 = new MarkerPointer(); markerPointer1.Value = 80; markerPointer1.Color = Color.Green; markerPointer1.Offset = 0.68; markerPointer1.MarkerShape = Com.Syncfusion.Gauges.SfCircularGauge.Enums.MarkerShape.Triangle; pointers1.Add(markerPointer1); scale1.CircularPointers = pointers1; circularScales1.Add(scale1); sfCircularGauge1.CircularScales = circularScales1; sfCircularGauge1.SetBackgroundColor(Color.White); //range pointer SfCircularGauge sfCircularGauge2 = new SfCircularGauge(con); ObservableCollection<Header> headers2 = new ObservableCollection<Header>(); Header header2 = new Header(); header2.Text = "Range Pointer"; header2.TextSize = 18; header2.TextColor = Color.Black; header2.Position = new PointF((float)0.5, (float)0.6); headers2.Add(header2); sfCircularGauge2.Headers = headers2; ObservableCollection<CircularScale> circularScales2 = new ObservableCollection<CircularScale>(); CircularScale scale2 = new CircularScale(); scale2.StartAngle = 180; scale2.SweepAngle = 180; scale2.StartValue = 0; scale2.EndValue = 100; scale2.RadiusFactor = 0.7; scale2.RimColor = Color.Gray; scale2.Interval = 50; scale2.ShowLabels = false; scale2.ShowTicks = false; scale2.RimWidth = 3; scale2.MinorTicksPerInterval = 0; ObservableCollection<CircularPointer> pointers2 = new ObservableCollection<CircularPointer>(); RangePointer rangePointer = new RangePointer(); rangePointer.Value = 60; rangePointer.Color = Color.ParseColor("#FF2680"); rangePointer.Offset = 0.6; rangePointer.Width = 20; rangePointer.EnableAnimation = false; pointers2.Add(rangePointer); scale2.CircularPointers = pointers2; circularScales2.Add(scale2); sfCircularGauge2.CircularScales = circularScales2; sfCircularGauge2.SetBackgroundColor(Color.White); //needlepointer SfCircularGauge sfCircularGauge3 = new SfCircularGauge(con); ObservableCollection<Header> headers3 = new ObservableCollection<Header>(); Header header3 = new Header(); header3.Text = "Needle Pointer"; header3.TextSize = 18; header3.TextColor = Color.Black; header3.Position = new PointF((float)0.5, (float)0.6); headers3.Add(header3); sfCircularGauge3.Headers = headers3; ObservableCollection<CircularScale> circularScales3 = new ObservableCollection<CircularScale>(); CircularScale scale3 = new CircularScale(); scale3.StartAngle = 180; scale3.SweepAngle = 180; scale3.StartValue = 0; scale3.EndValue = 100; scale3.RadiusFactor = 0.7; scale3.RimColor = Color.Gray; scale3.Interval = 50; scale3.ShowLabels = false; scale3.ShowTicks = false; scale3.RimWidth = 3; scale3.MinorTicksPerInterval = 0; ObservableCollection<CircularPointer> pointers3 = new ObservableCollection<CircularPointer>(); NeedlePointer needlePointer = new NeedlePointer(); needlePointer.Value = 80; needlePointer.Color = Color.Purple; needlePointer.LengthFactor = 0.7; needlePointer.KnobRadius = 0; needlePointer.Width = 10; needlePointer.Type = NeedleType.Triangle; pointers3.Add(needlePointer); scale3.CircularPointers = pointers3; circularScales3.Add(scale3); sfCircularGauge3.CircularScales = circularScales3; sfCircularGauge3.SetBackgroundColor(Color.White); SfCircularGauge sfCircularGauge4 = new SfCircularGauge(con); ObservableCollection<Header> headers4 = new ObservableCollection<Header>(); Header header4 = new Header(); header4.Text = "Multiple Needle"; header4.TextSize = 18; header4.TextColor = Color.Black; header4.Position = new PointF((float)0.5, (float)0.7); headers4.Add(header4); sfCircularGauge4.Headers = headers4; ObservableCollection<CircularScale> circularScales4 = new ObservableCollection<CircularScale>(); CircularScale scale4 = new CircularScale(); scale4.StartAngle = 180; scale4.SweepAngle = 180; scale4.StartValue = 0; scale4.EndValue = 100; scale4.RadiusFactor = 0.7; scale4.RimColor = Color.Gray; scale4.Interval = 50; scale4.ShowLabels = false; scale4.ShowTicks = false; scale4.RimWidth = 3; scale4.MinorTicksPerInterval = 0; ObservableCollection<CircularPointer> pointers4 = new ObservableCollection<CircularPointer>(); NeedlePointer needlePointer1 = new NeedlePointer(); needlePointer1.Value = 40; needlePointer1.Color = Color.ParseColor("#ed7d31"); needlePointer1.LengthFactor = 0.5; needlePointer1.KnobRadiusFactor = 0.05; needlePointer1.KnobColor = Color.White; needlePointer1.Width = 10; needlePointer1.Type = NeedleType.Triangle; needlePointer1.TailStrokeColor = Color.ParseColor("#ed7d31"); needlePointer1.KnobStrokeWidth = 2; needlePointer1.KnobStrokeColor = Color.ParseColor("#ed7d31"); pointers4.Add(needlePointer1); NeedlePointer needlePointer2 = new NeedlePointer(); needlePointer2.Value = 70; needlePointer2.Color = Color.ParseColor("#ed7d31"); needlePointer2.LengthFactor = 0.6; needlePointer2.KnobRadiusFactor = 0.05; needlePointer2.KnobColor = Color.White; needlePointer2.Width = 10; needlePointer2.Type = NeedleType.Triangle; needlePointer2.TailStrokeColor = Color.ParseColor("#ed7d31"); needlePointer2.KnobStrokeWidth = 2; needlePointer2.KnobStrokeColor = Color.ParseColor("#ed7d31"); pointers4.Add(needlePointer2); scale4.CircularPointers = pointers4; circularScales4.Add(scale4); sfCircularGauge4.CircularScales = circularScales4; sfCircularGauge4.SetBackgroundColor(Color.White); LinearLayout linearLayout = new LinearLayout(con); linearLayout.Orientation = Orientation.Vertical; linearLayout.LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent); linearLayout.AddView(sfCircularGauge, LayoutParams.WrapContent, (int)(250 * con.Resources.DisplayMetrics.Density)); linearLayout.AddView(sfCircularGauge1, LayoutParams.WrapContent, (int)(250 * con.Resources.DisplayMetrics.Density)); linearLayout.AddView(sfCircularGauge2, LayoutParams.WrapContent, (int)(250 * con.Resources.DisplayMetrics.Density)); linearLayout.AddView(sfCircularGauge3, LayoutParams.WrapContent, (int)(250 * con.Resources.DisplayMetrics.Density)); linearLayout.AddView(sfCircularGauge4, LayoutParams.WrapContent, (int)(250 * con.Resources.DisplayMetrics.Density)); linearLayout.SetPadding(30, 30, 30, 30); ScrollView mainView = new ScrollView(con); mainView.AddView(linearLayout); return mainView; } } } <file_sep>/Forms/TabView/TabView/Samples/CustomView/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfTabView { public class ViewModelCustomTab : INotifyPropertyChanged { private ObservableCollection<ContactsInfo> messageLogs = new ObservableCollection<ContactsInfo>(); public ObservableCollection<ContactsInfo> MessageLogs { get { return messageLogs; } set { messageLogs = value; RaisePropertyChanged("MessageLogs"); } } public ObservableCollection<ContactsInfo> ListData { get; set; } private string readCount= "0"; public string ReadCount { get { return readCount; } set { readCount = value; RaisePropertyChanged("ReadCount"); } } ContactsInfoRepository collection = new ContactsInfoRepository(); public ViewModelCustomTab() { MessageLogs = collection.GetContactDetails(2); ListData = collection.GetContactDetails(1); for (int i = 0; i < 5; i++) { AddMessage(); } //Device.StartTimer(TimeSpan.FromMilliseconds(0), () => //{ // return AddMessage(); //}); } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion int count = 0; public bool AddMessage() { if (count++ >= 5) { return false; } ReadCount = count.ToString(); ContactsInfo currentInfo = MessageLogs[MessageLogs.Count-1]; currentInfo.Read = true; currentInfo.DateMonth = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString(); currentInfo.MessageCount = DateTime.Now.DayOfWeek.ToString(); MessageLogs.Remove(currentInfo); MessageLogs.Insert(0, currentInfo); return true; } } } <file_sep>/iOS/SampleBrowser/Samples/Calculate/Helper/FunctionsHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; namespace SampleBrowser { public static class FunctionsHelper { public static void GetFunction(string item, UITextField formulaEdit) { switch (item) { case "SUM": case "AVG": case "MAX": case "MIN": case "AVERAGE": case "SUMSQ": case "AVEDEV": case "PRODUCT": case "AVERAGEA": case "GAMMADIST": case "GEOMEAN": case "HARMEAN": case "NORMDIST": case "COUNT": case "COUNTA": case "DEVSQ": case "KURT": case "MAXA": case "MEDIAN": case "MINA": case "GCD": case "LCM": case "STDEV.P": case "STDEV.S": case "IMAGINARYDIFFERENCE": case "IMPRODUCT": case "PPMT": case "IPMT": case "ISPMT": case "SYD": formulaEdit.Text = "=" + item + "(A1,B1,C1,C4)"; break; case "PI": formulaEdit.Text = "=" + item + "()*(A1+B1*C1)"; break; case "VLOOKUP": formulaEdit.Text = "=" + item + "(A1,A2:C5,2,true)"; break; case "HLOOKUP": formulaEdit.Text = "=" + item + "(A1,A2:C5,3,true)"; break; case "INDEX": formulaEdit.Text = "=" + item + "(A1:C5,3,2)"; break; case "CHAR": case "UNICHAR": formulaEdit.Text = "=" + item + "(C2)"; break; case "DB": case "DDB": formulaEdit.Text = "=" + item + "(A1,B1,C1,5)"; break; case "HYPGEOMDIST": formulaEdit.Text = "=" + item + "(C1,A2,A1,B1)"; break; case "IMSUM": case "IMSQRT": case "IMDIV": formulaEdit.Text = "=" + item + "(\"1+4i\",\"1+3i\")"; break; case "SIGN": case "GAMMAIN": case "COUNTBLANK": case "FISHERINV": case "EVEN": case "INDIRECT": case "ISEVEN": case "ISODD": case "ISREF": case "N": case "TAN": case "ODD": case "RADIANS": case "SQRTPI": case "FACTDOUBLE": case "GAMMALN": case "NORMSDIST": case "SEC": case "SECH": case "COT": case "COTH": case "CSC": case "CSCH": case "ACOT": case "ACOTH": case "ACSCH": case "TRUNCATE": case "GAMMALN.PRECISE": case "DEC2BIN": case "DEC2OCT": case "DEC2HEX": case "HEX2BIN": case "HEX2OCT": case "HEX2DEC": case "OCT2BIN": case "OCT2HEX": case "OCT2DEC": case "IMABS": case "IMAGINARY": case "IMREAL": case "IMCONJUGATE": case "IMARGUMENT": case "IMSIN": case "IMCSC": case "IMCOS": case "IMSEC": case "IMTAN": case "IMCOT": case "IMSINH": case "IMCSCH": case "IMCOSH": case "IMSECH": case "IMTANH": case "IMCOTH": case "IMLOG10": case "IMLOG2": case "IMLN": case "IMEXP": case "ERF": case "ERF.PRECISE": case "ERFC.PRECISE": case "ERFC": case "FORMULATEXT": case "ISFORMULA": case "TYPE": case "WEEKNUM": case "ISOWEEKNUM": case "ROW": case "AREAS": case "MUNIT": case "DEGREES": formulaEdit.Text = "=" + item + "(A1)"; break; case "MORMSINV": formulaEdit.Text = "=" + item + "(A1/100)"; break; case "NORMINV": formulaEdit.Text = "=" + item + "(0.98,A2,A3)"; break; case "FINV": formulaEdit.Text = "=" + item + "(1,A1,B1)"; break; case "IFERROR": formulaEdit.Text = "=" + item + "(A1,\"Error in calculation\")"; break; case "ACOS": case "ASECH": formulaEdit.Text = "=" + item + "(0.5)"; break; case "ASIN": case "ATANH": case "FISHER": formulaEdit.Text = "=" + item + "(0.6)"; break; case "BIN2DEC": case "BIN2OCT": case "BIN2HEX": formulaEdit.Text = "=" + item + "(11000011)"; break; case "LARGE": case "QUARTILE": case "QUARTILE.EXC": case "QUARTILE.INC": case "SMALL": formulaEdit.Text = "=" + item + "({C1,A2,C4,B2},3)"; break; case "CORREL": case "COVARIANCE.P": case "COVARIANCE.S": case "INTERCEPT": case "PEARSON": case "RSQ": case "SLOPE": case "STEYX": formulaEdit.Text = "=" + item + "({C1,A2,C4},{B2,A1,C5})"; break; case "PERCENTILE.EXC": case "PERCENTILE.INC": formulaEdit.Text = "=" + item + "({C1,A2,C4},0.7)"; break; case "FORECAST": formulaEdit.Text = "=" + item + "(A4,{C1,A2,C4},{B2,A1,C5})"; break; case "RANDBETWEEN": formulaEdit.Text = "=" + item + "(C1,A1)"; break; case "PERCENTRANK": formulaEdit.Text = "=" + item + "(A1:A5,A3)"; break; case "TRANSPOSE": formulaEdit.Text = "=" + item + "({100,200,300})"; break; case "TRIMMEAN": formulaEdit.Text = "=" + item + "(A1:A5,10%)"; break; case "POW": case "POWER": case "SUMX2MY2": case "SUMX2PY2": case "SUMXMY2": case "CHIDIST": case "CHITEST": case "CONCATENATE": case "COMBIN": case "COVAR": case "PERCENTILE": case "PERMUT": case "ATAN2": case "EFFECT": case "QUOTIENT": case "BIGMUL": case "DIVREM": case "IEEEREMAINDER": case "COMBINA": case "PERMUTATIONA": case "CHISQ.DIST.RT": case "IHDIST": case "COMPLEX": case "IMSUB": case "IMPOWER": case "GESTEP": case "DELTA": case "BITAND": case "BITOR": case "BITXOR": case "BITLSHIFT": case "BITRSHIFT": case "BESSELI": case "BESSELJ": case "BESSELY": case "BESSELK": case "BASE": case "DAYS": case "EDATE": case "EOMONTH": case "WORKDAY.INTL": case "WORKDAY": case "YEARFRAC": case "DAYS360": case "MOD": formulaEdit.Text = "=" + item + "(A1,C1)"; break; case "IF": formulaEdit.Text = "=" + item + "(A1+B1>C1+A4,True)"; break; case "SUMIF": formulaEdit.Text = "=" + item + "(A1:A5,\">C5\")"; break; case "NOT": formulaEdit.Text = "=" + item + "(IF(A1+B1>C1,True))"; break; case "FALSE": case "TRUE": formulaEdit.Text = "=(IF(A1+B1>C1,True))" + item + "()"; break; case "LEFT": case "RIGHT": case "LEFTB": case "RIGHTB": formulaEdit.Text = "=" + item + "(A1,3)"; break; case "LEN": case "LENB": case "INT": case "COLUMN": case "ISERROR": case "ISNUMBER": case "ISLOGICAL": case "ISNA": case "ISERR": case "ISBLANK": case "ISTEXT": case "ISNONTEXT": case "EXP": case "SINH": case "SQRT": case "LOG10": case "LN": case "ACOSH": case "ASINH": case "ATAN": case "COS": case "SIN": case "COSH": case "TANH": case "LOG": case "FACT": formulaEdit.Text = "=" + item + "(Sum(A1,B1,C1))"; break; case "ABS": formulaEdit.Text = "=" + item + "(B3)"; break; case "FV": case "PMT": case "MIRR": case "NPER": case "NPV": case "RATE": case "DATE": case "TIME": case "EXPONDIST": case "FDIST": case "LOGNORMDIST": case "NEGBINOMDIST": case "POISSON": case "STANDARDSIZE": case "WEIBULL": case "SUBSTITUTE": case "MULTINOMIAL": case "SLN": case "SKEW.P": case "F.DIST.RT": formulaEdit.Text = "=" + item + "(A1,B1,C1)"; break; case "RAND": formulaEdit.Text = "=" + item + "()*Sum(A1,B1,C1)"; break; case "CEILING": case "FLOOR": case "ROUNDDOWN": case "ROUND": formulaEdit.Text = "=" + item + "(Sum(A1,B1,C1),0.5)"; break; case "DAY": case "HOUR": case "MINUTE": case "SECOND": case "MONTH": case "WEEKDAY": case "YEAR": formulaEdit.Text = "=" + item + "(A1)"; break; case "DATEVALUE": formulaEdit.Text = "=" + item + "(\"1990/01/24\")"; break; case "OFFSET": formulaEdit.Text = "=" + item + "(A1,2,2)"; break; case "MID": formulaEdit.Text = "=" + item + "(\"MidPoint\",1,A1)"; break; case "MIDB": formulaEdit.Text = "=" + item + "(\"Simple Text\",1,6)"; break; case "EXACT": formulaEdit.Text = "=" + item + "(A1,A1)"; break; case "FIXED": case "PROB": case "SKEW": case "STDEV": case "STDEVA": case "STDEVP": case "STDEVPA": case "VAR": case "VARA": case "VARP": case "VARPA": case "ZTEST": case "UNIDIST": formulaEdit.Text = "=" + item + "(A1,A2,A3)"; break; case "LOWER": formulaEdit.Text = "=" + item + "(\"LOWERTEXT\")"; break; case "UPPER": formulaEdit.Text = "=" + item + "(\"uppertext\")"; break; case "TRIM": formulaEdit.Text = "=" + item + "(\"Simple Text\")"; break; case "TEXT": formulaEdit.Text = "=" + item + "(Sum(A1,B1,C1),$0.00)"; break; case "XIRR": formulaEdit.Text = "=" + item + "(A1:A5," + DateTime.Now + ",0.1)"; break; case "VALUE": formulaEdit.Text = "=" + item + "(Avg(A1,B1,C1))"; break; case "MODE": formulaEdit.Text = "=" + item + "(A1,B1,C1,A1)"; break; case "MODE.SNGL": formulaEdit.Text = "=" + item + "(A1,B1,B1,C4)"; break; case "MODE.MULT": formulaEdit.Text = "=" + item + "(A1,B1,C1,C1)"; break; case "TRUNC": formulaEdit.Text = "=" + item + "(A1/1.3,3)"; break; case "COUNTIF": case "NORM.S.DIST": formulaEdit.Text = "=" + item + "(A1,True)"; break; case "AND": case "OR": case "XOR": formulaEdit.Text = "=" + item + "(A1<B1,C5<B4)"; break; case "IFNA": formulaEdit.Text = "=" + item + "(VLOOKUP(A1,A2:A5,2,true),\"Not Found\")"; break; case "LOOKUP": formulaEdit.Text = "=" + item + "(B2,A1:B4,C1:C5)"; break; case "SUMPRODUCT": case "GROWTH": formulaEdit.Text = "=" + item + "(A1:A5,B1:B5,C1:C5)"; break; case "MATCH": formulaEdit.Text = "=" + item + "(B3,A2:B4,0)"; break; case "FIND": case "FINDB": case "SEARCH": case "SEARCHB": formulaEdit.Text = "=" + item + "(\"n\",\"Syncfusion\",1)"; break; case "CHOOSE": formulaEdit.Text = "=" + item + "(4,A1,A2,A3,A4,A5)"; break; case "CLEAN": formulaEdit.Text = "=" + item + "(CHAR(9)&\"Monthly report\"&CHAR(10))"; break; case "DOLLAR": case "ROUNDUP": case "ROMAN": case "CEILING.MATH": formulaEdit.Text = "=" + item + "(A4, 4)"; break; case "DOLLARDE": case "DOLLARFR": formulaEdit.Text = "=" + item + "(C2,B5)"; break; case "DURATION": formulaEdit.Text = "=" + item + "(A1,A3,C1,B2,2,1)"; break; case "FVSCHEDULE": formulaEdit.Text = "=" + item + "(1,{0.09,0.11,0.1})"; break; case "DISC": formulaEdit.Text = "=" + item + "(A1,B4,C1,C4,1)"; break; case "INTRATE": formulaEdit.Text = "=" + item + "(\"01/24/1990\",\"01/24/1991\",A5,B5,2)"; break; case "CUMIPMT": formulaEdit.Text = "=" + item + "(A2/12,A3*12,A4,1,1,0)"; break; case "CUMPRINC": formulaEdit.Text = "=" + item + "(0.1,A3,A4,1,1,0)"; break; case "NA": case "SHEET": case "SHEETS": case "NOW": case "TODAY": formulaEdit.Text = "=" + item + "()"; break; case "ERROR.TYPE": formulaEdit.Text = "=" + item + "(#REF!)"; break; case "SUBTOTAL": formulaEdit.Text = "=" + item + "(9,A1:B4,C1:C5)"; break; case "PV": formulaEdit.Text = "=" + item + "(A3, A4, A2,B4, 0)"; break; case "ACCRINT": formulaEdit.Text = "=" + item + "(DATE(A1,A2,B2), DATE(C1,C2,B2), DATE(B1,B2,C1),0.1,C5,2,0)"; break; case "ACCRINTM": formulaEdit.Text = "=" + item + "(DATE(A1,A2,B2),DATE(C2,C4,C5),0.1,B5,2)"; break; case "VDB": formulaEdit.Text = "=" + item + "(A1,A2,A3,DATE(A1,A2,B2),DATE(C2,C4,C5))"; break; case "TIMEVALUE": formulaEdit.Text = "=" + item + "(\"2:24 AM\")"; break; case "MROUND": formulaEdit.Text = "=" + item + "(A1,3)"; break; case "NORMSINV": case "NORM.S.INV": formulaEdit.Text = "=" + item + "(0.8)"; break; case "LOGEST": case "LOGESTB": formulaEdit.Text = "=" + item + "(A1:A5,B1:B5,TRUE,TRUE)"; break; case "PERCENTRANK.EXC": case "PERCENTRANK.INC": formulaEdit.Text = "=" + item + "(A1:A5,3)"; break; case "STANDARDIZE": formulaEdit.Text = "=" + item + "(A1,A5,1.5)"; break; case "ADDRESS": formulaEdit.Text = "=" + item + "(2,3)"; break; case "AVERAGEIF": formulaEdit.Text = "=" + item + "(B2:B5,\"<23000\")"; break; case "AVERAGEIFS": formulaEdit.Text = "=" + item + "(A2:A5, C2:C5, \">30\", A2:A5, \"<90\")"; break; case "SUMIFS": formulaEdit.Text = "=" + item + "(A2:A5, C1:C5,\">C4\")"; break; case "NETWORKDAYS": formulaEdit.Text = "=" + item + "(C4,B5)"; break; case "CONFIDENCE.T": case "CONFIDENCE": case "GAMMAINV": case "LOGINV": formulaEdit.Text = "=" + item + "(0.6,B2,A1)"; break; case "BINOMDIST": formulaEdit.Text = "=" + item + "(A1,B1,0.6,TRUE)"; break; case "MMULT": formulaEdit.Text = "=" + item + "(A2:A5, B2:B5)"; break; case "NORM.DIST": formulaEdit.Text = "=" + item + "(A2,A3,B1,TRUE)"; break; case "NORM.INV": formulaEdit.Text = "=" + item + "(0.908789,A5,B2)"; break; case "WEIBULL.DIST": case "GAMMA.DIST": case "LOGNORM.DIST": case "F.DIST": formulaEdit.Text = "=" + item + "(A2,A3,A4,TRUE)"; break; case "EXPON.DIST": case "CHISQ.DIST": formulaEdit.Text = "=" + item + "(0.3,A3,TRUE)"; break; case "GAMMA.INV": case "F.INV.RT": case "LOGNORM.INV": case "CONFIDENCE.NORM": formulaEdit.Text = "=" + item + "(0.068094,A3,A4)"; break; case "BINOM.INV": case "CRITBINOM": formulaEdit.Text = "=" + item + "(A1,0.5,0.6)"; break; case "HYPGEOM.DIST": formulaEdit.Text = "=" + item + "(A1,A2,A3,A4,TRUE)"; break; case "CHISQ.INV": case "CHISQ.INV.RT": case "T.INV": case "CHIINV": formulaEdit.Text = "=" + item + "(0.5,A3)"; break; case "BINOM.DIST": case "NEGBINOM.DIST": formulaEdit.Text = "=" + item + "(A1,A3,0.7,TRUE)"; break; case "RANK.AVG": formulaEdit.Text = "=" + item + "(A2,A1:A5,1)"; break; case "RANK.EQ": formulaEdit.Text = "=" + item + "(B3,B1:B5,1)"; break; case "RANK": formulaEdit.Text = "=" + item + "(C4,C1:C5,1)"; break; case "POISSON.DIST": case "T.DIST": formulaEdit.Text = "=" + item + "(A1,A2,TRUE)"; break; case "CONVERT": formulaEdit.Text = "=" + item + "(A1,\"F\",\"C\")"; break; case "REPLACE": case "REPLACEB": formulaEdit.Text = "=" + item + "(\"SimpleText\",6,5,\"*\")"; break; case "CODE": case "UNICODE": case "ASC": case "JIS": case "ENCODEURL": case "T": formulaEdit.Text = "=" + item + "(\"SimpleText\")"; break; case "PROPER": formulaEdit.Text = "=" + item + "(\"SimPleTeXt\")"; break; case "NUMBERVALUE": formulaEdit.Text = "=" + item + "(\"2.500,27\",\",\",\".\")"; break; case "REPT": formulaEdit.Text = "=" + item + "(\"SimpleText\",3)"; break; case "MDETERM": case "ROWS": case "COLUMNS": case "IRR": formulaEdit.Text = "=" + item + "(A1:A5)"; break; case "MINVERSE": formulaEdit.Text = "=" + item + "({1,2,4})"; break; case "DECIMAL": formulaEdit.Text = "=" + item + "(\"FF\",16)"; break; case "SERIESSUM": formulaEdit.Text = "=" + item + "(A3,0,2,A1:A5)"; break; case "ARABIC": formulaEdit.Text = "=" + item + "(\"LVII\")"; break; case "NETWORKDAYS.INTL": formulaEdit.Text = "=" + item + "(\"1990/01/24\",\"1992/01/24\")"; break; case "HYPERLINK": formulaEdit.Text = "=" + item + "(\"http:\\www.syncfusion.com\",\"Syncfusion\")"; break; case "INFO": formulaEdit.Text = "=" + item + "(\"NUMFILE\")"; break; case "CELL": formulaEdit.Text = "=" + item + "(\"col\",C3)"; break; } } } }<file_sep>/Forms/Picker/Picker/Samples/DateTimePicker/DateTimePicker.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SelectionChangedEventArgs = Syncfusion.SfPicker.XForms.SelectionChangedEventArgs; using Syncfusion.SfPicker.XForms; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using System.Globalization; using SampleBrowser.Core; namespace SampleBrowser.SfPicker { public partial class DateTimePicker : SampleView { ObservableCollection<object> currenttime; public DateTimePicker() { InitializeComponent(); this.BindingContext = new DateTimePickerViewModel(); //picker.OnColumnLoaded += Picker_GetColumnWidth; //picker.OnPopUpOpened += Picker_OnPopUpOpened; popuppicker.Closed += Popuppicker_OnPopUpClosed; popupendpicker.Closed += Popupendpicker_OnPopUpClosed; currenttime = new ObservableCollection<object>(); currenttime.Add(DateTime.Now.ToString("hh")); currenttime.Add(DateTime.Now.ToString("mm")); currenttime.Add(DateTime.Now.ToString("tt")); if (Device.RuntimePlatform == Device.Android) { popuppicker.BackgroundColor = Color.White; popupendpicker.BackgroundColor = Color.White; starttimebutton.WidthRequest = 30; endtimebutton.WidthRequest = 30; } startdate.Text = DateTime.Now.ToString("hh") + ":" + DateTime.Now.ToString("mm") + " " + DateTime.Now.ToString("tt"); enddate.Text = DateTime.Now.ToString("hh") + ":" + DateTime.Now.ToString("mm") + " " + DateTime.Now.ToString("tt"); https://gitlab.syncfusion.com/essential-studio/xamarinforms-samplebrowser.git var no = false; if (no) goto https; startdate.Focused += Startdate_Focused; enddate.Focused += Enddate_Focused; if (Device.RuntimePlatform == Device.Android) { submit.BackgroundColor = Color.FromHex("#009688"); submit.TextColor = Color.White; submit.Text = "SUBMIT"; submit.FontFamily = "sans-serif-medium"; submit.WidthRequest = 100; submit.HeightRequest = 35; startdate.FontSize = 14; enddate.FontSize = 14; picker.PickerWidth = 300; innergrid.Margin = new Thickness(10, 3, 10, 3); scroll.Margin = new Thickness(10, 0, 10, 3); apptimelabel.Margin = new Thickness(0, 5, 0, 5); description.HeightRequest = 40; popuppicker.HeaderText = "TIME PICKER"; popupendpicker.HeaderText = "TIME PICKER"; picker.HeaderText = "APPOINTMENT DATE"; row1.Height = new GridLength(190); popuppicker.ColumnHeaderFontSize = 14; popupendpicker.ColumnHeaderFontSize = 14; picker.SelectedItemFontSize = 22; picker.ColumnHeaderFontSize = 16; applabel.TextColor = Color.Black; apptimelabel.TextColor = Color.Black; } if (Device.RuntimePlatform == Device.iOS) { startdate.Parent = tempGrid; enddate.Parent = tempGrid; //frame.OutlineColor = Color.White; submit.WidthRequest = 250; submit.HeightRequest = 30; submit.BorderWidth = 1; popuppicker.SelectedItemFontSize = 25; popupendpicker.SelectedItemFontSize = 25; startlayout.HeightRequest = 30; endlayout.HeightRequest = 30; startlabel.TextColor = Color.FromRgba(0, 0, 0, 0.5); endlabel.TextColor = Color.FromRgba(0, 0, 0, 0.5); popuppicker.SelectedItemFontFamily = "HelveticaNeue-Thin"; popuppicker.UnSelectedItemFontFamily = "HelveticaNeue-Thin"; popupendpicker.SelectedItemFontFamily = "HelveticaNeue-Thin"; popupendpicker.UnSelectedItemFontFamily = "HelveticaNeue-Thin"; picker.SelectedItemFontFamily = "HelveticaNeue-Thin"; picker.UnSelectedItemFontFamily = "HelveticaNeue-Thin"; startlabel.FontFamily = "HelveticaNeue-Thin"; startdate.FontFamily = "HelveticaNeue-Thin"; endlabel.FontFamily = "HelveticaNeue-Thin"; enddate.FontFamily = "HelveticaNeue-Thin"; submit.FontFamily = "HelveticaNeue-Thin"; submit.BorderColor = Color.FromHex("#cdcdcd"); submit.FontSize = 14; scroll.Margin = new Thickness(10); desGrid.Margin = new Thickness(0, 10, 0, 50); submit.FontAttributes = FontAttributes.Bold; } if (Device.RuntimePlatform == Device.iOS && Device.Idiom == TargetIdiom.Phone) { picker.WidthRequest = 300; } if (Device.RuntimePlatform == Device.UWP) { applabel.FontAttributes = FontAttributes.Bold; deslabel.FontAttributes = FontAttributes.Bold; apptimelabel.FontAttributes = FontAttributes.Bold; startlabel.TextColor = Color.Gray; endlabel.TextColor = Color.Gray; scroll.Margin = new Thickness(0); innergrid.Margin = new Thickness(20); if (Device.Idiom != TargetIdiom.Phone) { innergrid.HorizontalOptions = LayoutOptions.Start; innergrid.WidthRequest = 500; innergrid.VerticalOptions = LayoutOptions.Start; } startdate.VerticalOptions = LayoutOptions.Center; enddate.VerticalOptions = LayoutOptions.Center; popuppicker.PickerHeight = 350; popuppicker.PickerWidth = 300; startdate.IsEnabled = true; scroll.Margin = new Thickness(10); enddate.IsEnabled = true; startdate.HeightRequest = 40; enddate.HeightRequest = 40; popupendpicker.PickerHeight = 350; popupendpicker.PickerWidth = 300; popuppicker.HeaderText = "PICK A TIME"; popupendpicker.HeaderText = "PICK A TIME"; if (Device.Idiom == TargetIdiom.Phone) { scroll.Margin = new Thickness(5, 0, 5, 10); } submit.BorderWidth = 0; popuppicker.HeaderText = "PICK A TIME"; popupendpicker.HeaderText = "PICK A TIME"; submit.Margin = new Thickness(0,15,0,0); submit.BackgroundColor = Color.FromHex("#cdcdcd"); submit.TextColor = Color.Black; } var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += (s, e) => { if (Device.RuntimePlatform == Device.Android && Device.RuntimePlatform == Device.iOS) popuppicker.IsOpen = true; }; startdate.GestureRecognizers.Add(tapGestureRecognizer); var tapGestureRecognizer2 = new TapGestureRecognizer(); tapGestureRecognizer2.Tapped += (s, e) => { if (Device.RuntimePlatform == Device.Android && Device.RuntimePlatform == Device.iOS) popupendpicker.IsOpen = true; }; enddate.GestureRecognizers.Add(tapGestureRecognizer2); } private void Enddate_Focused(object sender, FocusEventArgs e) { enddate.Unfocus(); popupendpicker.IsOpen = true; } private void Startdate_Focused(object sender, FocusEventArgs e) { startdate.Unfocus(); popuppicker.IsOpen = true; } private void Popupendpicker_OnPopUpClosed(object sender, EventArgs e) { if (string.IsNullOrEmpty(enddate.Text)) { (this.BindingContext as DateTimePickerViewModel).SelectedEndTime = currenttime; } else { (this.BindingContext as DateTimePickerViewModel).SelectedEndTime = GetCollectionfromstring(enddate.Text); } } private void Popuppicker_OnPopUpClosed(object sender, EventArgs e) { if (string.IsNullOrEmpty(startdate.Text)) { (this.BindingContext as DateTimePickerViewModel).SelectedStartTime = currenttime; } else { (this.BindingContext as DateTimePickerViewModel).SelectedStartTime = GetCollectionfromstring(startdate.Text); } } void Picker_GetColumnWidth(object sender, ColumnLoadedEventArgs e) { if (Device.RuntimePlatform == Device.Android) { if (e.Column == 0) e.ColumnWidth = 356; if (e.Column == 1) e.ColumnWidth = 216; } } private void Button_Click(object sender, EventArgs e) { popuppicker.IsOpen = true; } private void Button_Click_2(object sender, EventArgs e) { popupendpicker.IsOpen = true; } private void popuppicker_OkButtonClicked(object sender, SelectionChangedEventArgs e) { if (popupendpicker.IsOpen) { if((e.NewValue as ObservableCollection<object>).Count!=0) (this.BindingContext as DateTimePickerViewModel).SelectedEndTime = GetCollectionfromList(e.NewValue as IList); enddate.Text = GetStringfromCollection((this.BindingContext as DateTimePickerViewModel).SelectedEndTime); } else { if ((e.NewValue as ObservableCollection<object>).Count != 0) { (this.BindingContext as DateTimePickerViewModel).SelectedStartTime = GetCollectionfromList(e.NewValue as IList); startdate.Text = GetStringfromCollection((this.BindingContext as DateTimePickerViewModel).SelectedStartTime); } } } private void popuppicker_CancelButtonClicked(object sender, SelectionChangedEventArgs e) { if (popupendpicker.IsOpen) { (this.BindingContext as DateTimePickerViewModel).SelectedEndTime = GetCollectionfromstring(enddate.Text); } else { (this.BindingContext as DateTimePickerViewModel).SelectedStartTime = GetCollectionfromstring(startdate.Text); } } private void Button_Clicked(object sender, EventArgs e) { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Appointment Details","Your appointment has been scheduled at "+GetStringfromCollection1(picker.SelectedItem as ICollection) + " between "+ startdate.Text + " - " + enddate.Text , "OK"); startdate.Text = DateTime.Now.ToString("hh") + ":" + DateTime.Now.ToString("mm") + " " + DateTime.Now.ToString("tt"); enddate.Text = DateTime.Now.ToString("hh") + ":" + DateTime.Now.ToString("mm") + " " + DateTime.Now.ToString("tt"); description.Text = ""; } #region get Collections and String ObservableCollection<object> GetCollectionfromList(IList dates) { ObservableCollection<object> items = new ObservableCollection<object>(); foreach (var item in dates) { items.Add(item); } return items; } string GetStringfromCollection(ICollection collection) { string dates = string.Empty; int i = 0; foreach (var item in collection) { dates += item; if (i == 0) dates += ":"; else dates += " "; i++; } return dates; } string GetStringfromCollection1(ICollection collection) { string dates = string.Empty; int i = 0; foreach (var item in collection) { dates += item; dates += " "; i++; } return dates; } ObservableCollection<object> GetCollectionfromstring(string text) { if (!string.IsNullOrEmpty(text)) { text = text.Replace(":", " "); var str = text.Split(' ').Where(s => !string.IsNullOrEmpty(s)); ObservableCollection<object> items = new ObservableCollection<object>(); foreach (var item in str) { items.Add(item); } return items; } return currenttime; } #endregion } public class DateTimePickerViewModel : INotifyPropertyChanged { private ObservableCollection<object> _appointmentDate; public ObservableCollection<object> AppointmentDate { get { return _appointmentDate; } set { _appointmentDate = value; RaisePropertyChanged("StartDate"); } } private ObservableCollection<object> _selecttime; public ObservableCollection<object> SelectedStartTime { get { return _selecttime; } set { _selecttime = value; RaisePropertyChanged("SelectedStartTime"); } } private ObservableCollection<object> _selectedendtime; public ObservableCollection<object> SelectedEndTime { get { return _selectedendtime; } set { _selectedendtime = value;RaisePropertyChanged("SelectedEndTime"); } } public event PropertyChangedEventHandler PropertyChanged; void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } public DateTimePickerViewModel() { ObservableCollection<object> currentTime = new ObservableCollection<object>(); currentTime.Add(DateTime.Now.ToString("hh")); currentTime.Add(DateTime.Now.ToString("mm")); currentTime.Add(DateTime.Now.ToString("tt")); this.SelectedStartTime = currentTime; this.SelectedEndTime = currentTime; ObservableCollection<object> todaycollection = new ObservableCollection<object>(); //Select today dates todaycollection.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0,3)); if (DateTime.Now.Date.Day < 10) todaycollection.Add("0" + DateTime.Now.Date.Day); else todaycollection.Add(DateTime.Now.Date.Day.ToString()); todaycollection.Add(DateTime.Now.Date.Year.ToString()); this.AppointmentDate = todaycollection; } } public class CustomButton:Button { } } <file_sep>/Forms/Rating/Rating/Samples/Rating/Rating_Tablet.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfRating.XForms; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfRating { public partial class Rating_Tablet : SampleView { SfRatingSettings sfRatingSettings, sfsecondRatingSettings; int ratingItemCount; String ratingValue, ratingCount, ratingResult; public Rating_Tablet() { InitializeComponent(); precisionPicker.Items.Add("Standard"); precisionPicker.Items.Add("Half"); precisionPicker.Items.Add("Exact"); precisionPicker.SelectedIndex = 0; precisionPicker.SelectedIndexChanged += precisionPicker_SelectedIndexChanged; sfRatingSettings = new SfRatingSettings(); sfRatingSettings.RatedFill = Color.FromHex("#fbd10a"); sfRatingSettings.UnRatedFill = Color.White; sfRatingSettings.RatedStroke = Color.FromHex("#fbd10a"); sfRatingSettings.RatedStrokeWidth = 1; sfRatingSettings.UnRatedStrokeWidth = 1; sfRating1.RatingSettings = sfRatingSettings; sfsecondRatingSettings = new SfRatingSettings(); sfsecondRatingSettings.UnRatedFill = Color.White; sfsecondRatingSettings.RatedStrokeWidth = 1; sfsecondRatingSettings.UnRatedStrokeWidth = 1; sfRating2.RatingSettings = sfsecondRatingSettings; sfRating1.TooltipPlacement = TooltipPlacement.None; sfRating2.TooltipPlacement = TooltipPlacement.None; sfRating2.ValueChanged += ValueChanged; } void ValueChanged(object sender, ValueEventArgs e) { ratingValue = Convert.ToString(Math.Round(e.Value, 1)); ratingItemCount = sfRating2.ItemCount; ratingCount = Convert.ToString(ratingItemCount); ratingResult = " " + ratingValue + "/" + ratingCount; showValue.Text = ratingResult; } public void toggleStateChanged(object e, ToggledEventArgs eve) { if (eve.Value) { sfRating2.TooltipPlacement = TooltipPlacement.TopLeft; } else { sfRating2.TooltipPlacement = TooltipPlacement.None; } } public View getContent() { return this.Content; } public View getPropertyContent() { return this.PropertyView; } public void precisionPicker_SelectedIndexChanged(object c, EventArgs e) { switch (precisionPicker.SelectedIndex) { case 0: { sfRating2.Precision = Precision.Standard; sfRating2.TooltipPrecision = 0; break; } case 1: { sfRating2.Precision = Precision.Half; sfRating2.TooltipPrecision = 1; break; } case 2: { sfRating2.Precision = Precision.Exact; sfRating2.TooltipPrecision = 1; break; } } ratingValue = Convert.ToString(sfRating2.Value); ratingItemCount = sfRating2.ItemCount; ratingCount = Convert.ToString(ratingItemCount); ratingResult = " " + ratingValue + "/" + ratingCount; showValue.Text = ratingResult; } public void itemCountEntry_Changed(object c, TextChangedEventArgs e) { if (e.NewTextValue.Length > 0) { sfRating2.ItemCount = int.Parse(e.NewTextValue); } ratingItemCount = sfRating2.ItemCount; ratingCount = Convert.ToString(ratingItemCount); if (sfRating2.Value > ratingItemCount) { ratingValue = "0"; } else { ratingValue = Convert.ToString(sfRating2.Value); } ratingResult = " " + ratingValue + "/" + ratingCount; showValue.Text = ratingResult; } } } <file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/DropDownMenu.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using UIKit; using CoreGraphics; using System; using System.Threading.Tasks; namespace SampleBrowser { /// <summary> /// Drop down list changed handler. /// </summary> public delegate void DropDownMenuItemChangedHandler(int itemIndex, DropDownMenuItem listItem); /// <summary> /// Drop down list. /// </summary> public class DropDownMenu: UIView { /// <summary> /// Occurs when drop down list changed. /// </summary> public event DropDownMenuItemChangedHandler DropDownMenuItemChanged; private UIView container; private UITableView table; private DropDownMenuItem[] m_ListItems; private DropDownDataSource m_Source; private bool m_isOpened; private UIColor m_TextColor; /// <summary> /// Gets or sets the opacity. /// </summary> /// <value>The opacity.</value> public float Opacity { get { return this.Layer.Opacity; } set { this.Layer.Opacity = value; } } public bool IsOpened { get { return m_isOpened; } set { m_isOpened = value; } } public override CGRect Frame { get { return base.Frame; } set { base.Frame = value; } } /// <summary> /// Gets or sets the width of the border. /// </summary> /// <value>The width of the border.</value> public nfloat BorderWidth { get { return this.Layer.BorderWidth; } set { this.Layer.BorderWidth = value; } } /// <summary> /// Gets or sets the color of the border. /// </summary> /// <value>The color of the border.</value> public CGColor BorderColor { get { return this.Layer.BorderColor; } set { this.Layer.BorderColor = value; } } /// <summary> /// Gets or sets the color of the text. /// </summary> /// <value>The color of the text.</value> public UIColor TextColor { get { return m_TextColor != null ? m_TextColor : UIColor.Black; } set { if (value != null) { m_TextColor = value; if (m_Source == null) { InitTableAndSource(); } m_Source.TextColor = value; } } } /// <summary> /// Gets or sets the drop down top inset. Default is 60 /// </summary> /// <value>The drop down top inset.</value> public nfloat DropDownTopInset{ get; set; } /// <summary> /// Brings the DropDownMenu to view. /// </summary> public void Open() { table.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); this.container.Add(this); m_isOpened = true; } /// <summary> /// Removes the DropDownMenu from view. /// </summary> public void Close() { table.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); this.RemoveFromSuperview(); m_isOpened = false; } /// <summary> /// Initializes a new instance of the <see cref="DropDownList"/> class. /// </summary> /// <param name="listItems">List items.</param> public DropDownMenu (UIView view, DropDownMenuItem[] listItems) { this.container = view; this.m_ListItems = listItems; InitializeEffects (); } private void InitializeEffects(){ Layer.Frame = this.Frame; Layer.Opacity = 1; Layer.CornerRadius = 10; ClipsToBounds = true; } private void InitTableAndSource () { if (m_Source == null) { m_Source = new DropDownDataSource(m_ListItems, this.m_TextColor); m_Source.DropDownMenuItemChanged += DropDownMenuItemChangedMethod; table = new UITableView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height)); if (DropDownTopInset == 0) DropDownTopInset = 60; table.ContentInset = new UIEdgeInsets(0, 0, 0, 0); table.Source = m_Source; this.Add(table); } } private void DropDownMenuItemChangedMethod(int index, DropDownMenuItem item) { if (DropDownMenuItemChanged != null) { DropDownMenuItemChanged(index, item); } } } } <file_sep>/Forms/Schedule/Schedule/Samples/ViewCustomization/ViewModel/CustomizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Customization View Model class. /// </summary> [Preserve(AllMembers = true)] public class CustomizationViewModel : INotifyPropertyChanged { #region Properties /// <summary> /// schedule appointments /// </summary> private ScheduleAppointment conference, medical, systemTroubleShoot, birthday, medical2, conference2, systemTroubleShoot2, birthday2, medical3, systemTroubleShoot3, conference4, medical4, systemTroubleShoot4, birthday4, conference5, medical5, systemTroubleShoot5, birthday5; #region HeaderLabelValue /// <summary> /// header label value /// </summary> private string headerLabelValue = DateTime.Today.Date.ToString("dd, MMMM yyyy"); #endregion #endregion Properties #region Constructor /// <summary> /// Initializes a new instance of the <see cref="CustomizationViewModel" /> class /// </summary> public CustomizationViewModel() { this.Appointments = new ScheduleAppointmentCollection(); this.conference = new ScheduleAppointment(); this.conference.Subject = "Conference"; this.conference.StartTime = DateTime.Now.Date.AddHours(10); this.conference.EndTime = DateTime.Now.Date.AddHours(12); this.conference.Color = Color.FromHex("#FFD80073"); this.systemTroubleShoot = new ScheduleAppointment(); this.systemTroubleShoot.Subject = "System Troubleshoot"; this.systemTroubleShoot.StartTime = DateTime.Now.Date.AddDays(1).AddHours(9); this.systemTroubleShoot.EndTime = DateTime.Now.Date.AddDays(1).AddHours(11); this.systemTroubleShoot.Color = Color.FromHex("#FF00ABA9"); this.systemTroubleShoot.IsAllDay = true; this.medical = new ScheduleAppointment(); this.medical.Subject = "Checkup"; this.medical.StartTime = DateTime.Now.Date.AddDays(2).AddHours(10); this.medical.EndTime = DateTime.Now.Date.AddDays(2).AddHours(12); this.medical.Color = Color.FromHex("#FFA2C139"); this.birthday = new ScheduleAppointment(); this.birthday.Subject = "Jeni's Birthday"; this.birthday.StartTime = DateTime.Now.Date.AddDays(3).AddHours(9); this.birthday.EndTime = DateTime.Now.Date.AddDays(3).AddHours(11); this.birthday.Color = Color.FromHex("#FF1BA1E2"); this.birthday.IsAllDay = true; this.conference2 = new ScheduleAppointment(); this.conference2.Subject = "Conference"; this.conference2.StartTime = DateTime.Now.Date.AddDays(11).AddHours(10); this.conference2.EndTime = DateTime.Now.Date.AddDays(11).AddHours(12); this.conference2.Color = Color.FromHex("#FFD80073"); this.systemTroubleShoot2 = new ScheduleAppointment(); this.systemTroubleShoot2.Subject = "System Troubleshoot"; this.systemTroubleShoot2.StartTime = DateTime.Now.Date.AddDays(15).AddHours(9); this.systemTroubleShoot2.EndTime = DateTime.Now.Date.AddDays(15).AddHours(11); this.systemTroubleShoot2.Color = Color.FromHex("#FF00ABA9"); this.systemTroubleShoot2.IsAllDay = true; this.medical2 = new ScheduleAppointment(); this.medical2.Subject = "Checkup"; this.medical2.StartTime = DateTime.Now.Date.AddDays(18).AddHours(10); this.medical2.EndTime = DateTime.Now.Date.AddDays(18).AddHours(12); this.medical2.Color = Color.FromHex("#FFA2C139"); this.birthday2 = new ScheduleAppointment(); this.birthday2.Subject = "Jeni's Birthday"; this.birthday2.StartTime = DateTime.Now.Date.AddDays(20).AddHours(9); this.birthday2.EndTime = DateTime.Now.Date.AddDays(20).AddHours(11); this.birthday2.Color = Color.FromHex("#FF1BA1E2"); this.birthday2.IsAllDay = true; this.systemTroubleShoot3 = new ScheduleAppointment(); this.systemTroubleShoot3.Subject = "System Troubleshoot"; this.systemTroubleShoot3.StartTime = DateTime.Now.Date.AddDays(24).AddHours(9); this.systemTroubleShoot3.EndTime = DateTime.Now.Date.AddDays(24).AddHours(11); this.systemTroubleShoot3.Color = Color.FromHex("#FF00ABA9"); this.systemTroubleShoot3.IsAllDay = true; this.medical3 = new ScheduleAppointment(); this.medical3.Subject = "Checkup"; this.medical3.StartTime = DateTime.Now.Date.AddDays(27).AddHours(10); this.medical3.EndTime = DateTime.Now.Date.AddDays(27).AddHours(12); this.medical3.Color = Color.FromHex("#FFA2C139"); this.conference4 = new ScheduleAppointment(); this.conference4.Subject = "Conference"; this.conference4.StartTime = DateTime.Now.Date.AddMonths(1).AddHours(10); this.conference4.EndTime = DateTime.Now.Date.AddMonths(1).AddHours(12); this.conference4.Color = Color.FromHex("#FFD80073"); this.systemTroubleShoot4 = new ScheduleAppointment(); this.systemTroubleShoot4.Subject = "System Troubleshoot"; this.systemTroubleShoot4.StartTime = DateTime.Now.Date.AddMonths(1).AddDays(4).AddHours(9); this.systemTroubleShoot4.EndTime = DateTime.Now.Date.AddMonths(1).AddDays(4).AddHours(11); this.systemTroubleShoot4.Color = Color.FromHex("#FF00ABA9"); this.systemTroubleShoot4.IsAllDay = true; this.medical4 = new ScheduleAppointment(); this.medical4.Subject = "Checkup"; this.medical4.StartTime = DateTime.Now.Date.AddMonths(1).AddDays(7).AddHours(10); this.medical4.EndTime = DateTime.Now.Date.AddMonths(1).AddDays(7).AddHours(12); this.medical4.Color = Color.FromHex("#FFA2C139"); this.birthday4 = new ScheduleAppointment(); this.birthday4.Subject = "Jeni's Birthday"; this.birthday4.StartTime = DateTime.Now.Date.AddMonths(1).AddDays(11).AddHours(9); this.birthday4.EndTime = DateTime.Now.Date.AddMonths(1).AddDays(11).AddHours(11); this.birthday4.Color = Color.FromHex("#FF1BA1E2"); this.birthday4.IsAllDay = true; this.conference5 = new ScheduleAppointment(); this.conference5.Subject = "Conference"; this.conference5.StartTime = DateTime.Now.Date.AddMonths(-1).AddHours(10); this.conference5.EndTime = DateTime.Now.Date.AddMonths(-1).AddHours(12); this.conference5.Color = Color.FromHex("#FFD80073"); this.systemTroubleShoot5 = new ScheduleAppointment(); this.systemTroubleShoot5.Subject = "System Troubleshoot"; this.systemTroubleShoot5.StartTime = DateTime.Now.Date.AddMonths(-1).AddDays(3).AddHours(9); this.systemTroubleShoot5.EndTime = DateTime.Now.Date.AddMonths(-1).AddDays(3).AddHours(11); this.systemTroubleShoot5.Color = Color.FromHex("#FF00ABA9"); this.systemTroubleShoot5.IsAllDay = true; this.medical5 = new ScheduleAppointment(); this.medical5.Subject = "Checkup"; this.medical5.StartTime = DateTime.Now.Date.AddMonths(-1).AddDays(6).AddHours(10); this.medical5.EndTime = DateTime.Now.Date.AddMonths(-1).AddDays(6).AddHours(12); this.medical5.Color = Color.FromHex("#FFA2C139"); this.birthday5 = new ScheduleAppointment(); this.birthday5.Subject = "Jeni's Birthday"; this.birthday5.StartTime = DateTime.Now.Date.AddMonths(-1).AddDays(9).AddHours(9); this.birthday5.EndTime = DateTime.Now.Date.AddMonths(-1).AddDays(9).AddHours(11); this.birthday5.Color = Color.FromHex("#FF1BA1E2"); this.birthday5.IsAllDay = true; this.Appointments.Add(this.conference); this.Appointments.Add(this.systemTroubleShoot); this.Appointments.Add(this.medical); this.Appointments.Add(this.birthday); this.Appointments.Add(this.conference2); this.Appointments.Add(this.systemTroubleShoot2); this.Appointments.Add(this.medical2); this.Appointments.Add(this.birthday2); this.Appointments.Add(this.medical3); this.Appointments.Add(this.systemTroubleShoot3); this.Appointments.Add(this.conference4); this.Appointments.Add(this.systemTroubleShoot4); this.Appointments.Add(this.medical4); this.Appointments.Add(this.birthday4); this.Appointments.Add(this.conference5); this.Appointments.Add(this.systemTroubleShoot5); this.Appointments.Add(this.medical5); this.Appointments.Add(this.birthday5); } #endregion Constructor /// <summary> /// Property changed event handler /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets schedule appointment /// </summary> public static ScheduleAppointment ScheduleAppointment { get; set; } /// <summary> /// Gets or sets month cell item /// </summary> public static MonthCellItem MonthCellItem { get; set; } /// <summary> /// Gets or sets appointments /// </summary> public ScheduleAppointmentCollection Appointments { get; set; } /// <summary> /// Gets or sets Header label value /// </summary> public string HeaderLabelValue { get { return this.headerLabelValue; } set { this.headerLabelValue = value; this.RaiseOnPropertyChanged("HeaderLabelValue"); } } #region Property Changed Event /// <summary> /// Invoke method when property changed /// </summary> /// <param name="propertyName">property name</param> private void RaiseOnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }<file_sep>/Forms/TreeView/TreeView/Samples/GettingStarted/GettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.TreeView; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public partial class GettingStarted : SampleView { public GettingStarted() { InitializeComponent(); } } public class TreeViewGettingStartedBehavior : Behavior<SampleView> { #region Fields private Syncfusion.XForms.TreeView.SfTreeView TreeView; private Picker animationPicker; private Picker expanderPositionPicker; #endregion #region Overrides protected override void OnAttachedTo(SampleView bindable) { TreeView = bindable.FindByName<Syncfusion.XForms.TreeView.SfTreeView>("treeView"); animationPicker = bindable.FindByName<Picker>("enableAnimation"); animationPicker.Items.Add("False"); animationPicker.Items.Add("True"); animationPicker.SelectedIndex = 1; animationPicker.SelectedIndexChanged += EnableAnimation_SelectedIndexChanged; expanderPositionPicker = bindable.FindByName<Picker>("expanderPosition"); expanderPositionPicker.Items.Add("Start"); expanderPositionPicker.Items.Add("End"); expanderPositionPicker.SelectedIndex = 0; expanderPositionPicker.SelectedIndexChanged += ExpanderPosition_SelectedIndexChanged; base.OnAttachedTo(bindable); } private void EnableAnimation_SelectedIndexChanged(object sender, EventArgs e) { if (animationPicker.SelectedIndex == 0) TreeView.IsAnimationEnabled = false; else if (animationPicker.SelectedIndex == 1) TreeView.IsAnimationEnabled = true; } private void ExpanderPosition_SelectedIndexChanged(object sender, EventArgs e) { if (expanderPositionPicker.SelectedIndex == 0) TreeView.ExpanderPosition = ExpanderPosition.Start; else if (expanderPositionPicker.SelectedIndex == 1) TreeView.ExpanderPosition = ExpanderPosition.End; } #endregion } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/ImageConverter.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ImageConverter.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; [Preserve(AllMembers = true)] /// <summary> /// Converter for returning the required image source. /// </summary> public class ImageConverter : IValueConverter { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double? data; #region IValueConverter implementation /// <param name="value">The value to convert.</param> /// <param name="targetType">The type to which to convert the value.</param> /// <param name="parameter">A parameter to use during the conversion.</param> /// <param name="culture">The culture to use during the conversion.</param> /// <summary>Implement this method to convert <paramref name="value" /> to <paramref name="targetType" /> by using <paramref name="parameter" /> and <paramref name="culture" />.</summary> /// <returns>To be added.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var assembly = Assembly.GetAssembly(Application.Current.GetType()); this.data = value as double?; if (this.data != null && this.data > 0) { if (parameter is Label) { var label = parameter as Label; label.FontFamily = "./Assets/Fonts/#SB Icons"; label.TextColor = Color.FromRgb(76, 175, 80); return "\ue727"; } return new FontImageSource { Glyph = "\ue727", FontFamily = (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.macOS) ? "SB Icons" : Device.RuntimePlatform == Device.Android ? "SB Icons.ttf#" : "SB Icons.ttf#SB Icons", Color = Color.FromRgb(76, 175, 80) }; } else { if (parameter is Label) { var label = parameter as Label; label.FontFamily = "./Assets/Fonts/#SB Icons"; label.TextColor = Color.FromRgb(239, 83, 80); return "\ue729"; } return new FontImageSource { Glyph = "\ue729", FontFamily = (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.macOS) ? "SB Icons" : Device.RuntimePlatform == Device.Android ? "SB Icons.ttf#" : "SB Icons.ttf#SB Icons", Color = Color.FromRgb(239, 83, 80) }; } } /// <param name="value">The value to convert.</param> /// <param name="targetType">The type to which to convert the value.</param> /// <param name="parameter">A parameter to use during the conversion.</param> /// <param name="culture">The culture to use during the conversion.</param> /// <summary> Implement this method to convert <paramref name="value" /> back from <paramref name="targetType" /> by using <paramref name="parameter" /> and <paramref name="culture" />.</summary> /// <returns> To be added.</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return this.data; } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/RangeBarChart/RangeBarViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class RangeBarViewModel { public ObservableCollection<ChartDataModel> RangeBarData { get; set; } public RangeBarViewModel() { RangeBarData = new ObservableCollection<ChartDataModel>() { new ChartDataModel("Jumbo", 70238), new ChartDataModel("FHA", 99595), new ChartDataModel("VA", 156398), new ChartDataModel("USDA", 256396), new ChartDataModel("Const", 356398), new ChartDataModel("Total", 459937) }; } } }<file_sep>/Forms/ComboBox/ComboBox/Samples/GettingStartedSample/GettingStartedWPFSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.ComboBox; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfComboBox { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class GettingStartedWPFSample : SampleView, INotifyPropertyChanged { public ObservableCollection<string> Source1 { get; set; } public ObservableCollection<string> Source2 { get; set; } public ObservableCollection<string> Source3 { get; set; } private string watermark = "Search Here"; public string Watermark { get { return watermark; } set { watermark = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Watermark")); } } } private int textSize = 17; public int TextSize { get { return textSize; } set { textSize = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("TextSize")); } } } private bool isEditableComboBox = false; public bool IsEditableComboBox { get { return isEditableComboBox; } set { isEditableComboBox = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("IsEditableComboBox")); } } } private bool isIgnoreDiacritic = false; public bool IsIgnoreDiacritic { get { return isIgnoreDiacritic; } set { isIgnoreDiacritic = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("IsIgnoreDiacritic")); } } } public new event PropertyChangedEventHandler PropertyChanged; public GettingStartedWPFSample() { InitializeComponent(); Source1 = new ContactsInfoRepository().GetSizeDetails(); Source2 = new ContactsInfoRepository().GetResolutionDetails(); Source3 = new ContactsInfoRepository().GetOrientationDetails(); this.BindingContext = this; optionLayout.BindingContext = this; PickerMethod(); } protected override void OnSizeAllocated(double width, double height) { comboBox3.SuggestionBoxPlacement = SuggestionBoxPlacement.Bottom; base.OnSizeAllocated(width, height); } private void PickerMethod() { ColorPicker.SelectedIndex = 0; BackColorPicker.SelectedIndex = 0; SizePicker.SelectedIndex = 2; ComboBoxModePicker.SelectedIndex = 0; SizePicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (SizePicker.SelectedIndex) { case 0: { TextSize = 13; } break; case 1: { TextSize = 15; } break; case 2: { TextSize = 17; } break; } }; } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/Model/BookInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class BookInfo : INotifyPropertyChanged { public BookInfo () { } #region private variables private int bookID; private int customerID; private string firstName; private string lastName; private int price; private string bookName; private string country; #endregion #region Public Properties public int CustomerID { get { return customerID; } set { this.customerID = value; RaisePropertyChanged ("CustomerID"); } } public int BookID { get { return bookID; } set { this.bookID = value; RaisePropertyChanged ("BookID"); } } public string FirstName { get { return this.firstName; } set { this.firstName = value; RaisePropertyChanged ("FirstName"); } } public string LastName { get { return this.lastName; } set { this.lastName = value; RaisePropertyChanged ("LastName"); } } public string BookName { get { return bookName; } set { this.bookName = value; RaisePropertyChanged ("BookName"); } } public int Price { get { return price; } set { this.price = value; RaisePropertyChanged ("Price"); } } public string Country { get { return country; } set { this.country = value; RaisePropertyChanged ("Country"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged (String name) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (name)); } #endregion } } <file_sep>/Forms/Maps/Maps/Samples/DataLabels/DataLabels.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfMaps.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] public partial class DataLabels : SampleView { public DataLabels() { InitializeComponent(); smartLabelPicker.SelectedIndex = 1; smartLabelPicker.SelectedIndexChanged += smartLabelPicker_SelectedIndexChanged; intersectActionPicker.SelectedIndex = 0; intersectActionPicker.SelectedIndexChanged += intersectActionPicker_SelectedIndexChanged; } private void smartLabelPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (smartLabelPicker.SelectedIndex) { case 0: layer.DataLabelSettings.SmartLabelMode = IntersectAction.None; break; case 1: layer.DataLabelSettings.SmartLabelMode = IntersectAction.Trim; break; case 2: layer.DataLabelSettings.SmartLabelMode = IntersectAction.Hide; break; } } private void intersectActionPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (intersectActionPicker.SelectedIndex) { case 0: layer.DataLabelSettings.IntersectionAction = IntersectAction.None; break; case 1: layer.DataLabelSettings.IntersectionAction = IntersectAction.Trim; break; case 2: layer.DataLabelSettings.IntersectionAction = IntersectAction.Hide; break; } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Presentation/ChartsPresentation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Presentation; using Syncfusion.OfficeChart; using System.Collections.Generic; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using System.Xml; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class ChartsPresentation : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UILabel label1; UILabel label2; UIButton button; public ChartsPresentation() { label = new UILabel(); label1 = new UILabel(); label2 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to create charts in PowerPoint slides using Presentation library."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(0, 10, frameRect.Location.X + frameRect.Size.Width, 120); } else { label.Frame = new CGRect(frameRect.Location.X, 10, frameRect.Size.Width, 120); } this.AddSubview(label); label2.Frame = frameRect; label2.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label2.Text = "Please click the Generate Presentation button to save and view the generated PowerPoint Presentation."; label2.Font = UIFont.SystemFontOfSize(15); label2.Lines = 0; label2.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label2.Font = UIFont.SystemFontOfSize(18); label2.Frame = new CGRect(0, 190, frameRect.Location.X + frameRect.Size.Width, 50); } else { label2.Frame = new CGRect(frameRect.Location.X, 190, frameRect.Size.Width, 50); } this.AddSubview(label2); button.SetTitle("Generate Presentation", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 290, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 260, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { MemoryStream stream = new MemoryStream(); //Opens the existing presentation stream. using (IPresentation presentation = Syncfusion.Presentation.Presentation.Create()) { ISlide slide = presentation.Slides.Add(SlideLayoutType.TitleOnly); IParagraph paragraph = ((IShape)slide.Shapes[0]).TextBody.Paragraphs.Add(); //Apply center alignment to the paragraph paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; //Add slide title ITextPart textPart = paragraph.AddTextPart("Northwind Management Report"); textPart.Font.Color = ColorObject.FromArgb(46, 116, 181); //Get chart data from xml file List<ProductDetails> Products = LoadXMLData(); //Add a new chart to the presentation slide IPresentationChart chart = slide.Charts.AddChart(44.64, 133.2, 870.48, 380.16); //Set chart type chart.ChartType = OfficeChartType.Pie; //Set chart title chart.ChartTitle = "Best Selling Products"; //Set chart properties font name and size chart.ChartTitleArea.FontName = "Calibri (Body)"; chart.ChartTitleArea.Size = 14; for (int i = 0; i < Products.Count; i++) { ProductDetails product = Products[i]; chart.ChartData.SetValue(i + 2, 1, product.ProductName); chart.ChartData.SetValue(i + 2, 2, product.Sum); } //Create a new chart series with the name “Sales” AddSeriesForChart(chart); //Setting the font size of the legend. chart.Legend.TextArea.Size = 14; //Setting background color chart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); chart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); chart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 11, 1]; //Saves the presentation instance to the stream. presentation.Save(stream); } stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("ChartsPresentation.pptx", "application/mspowerpoint", stream); } } #region Helper Methods /// <summary> /// Gets list of product details from an XML file /// </summary> /// <returns></returns> private List<ProductDetails> LoadXMLData() { List<ProductDetails> Products = new List<ProductDetails>(); ProductDetails productDetails; Assembly assembly = Assembly.GetExecutingAssembly(); Stream productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.Presentation.Templates.Products.xml"); XmlReader reader = XmlReader.Create(productXMLStream); string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Products": while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "SNO": reader.Read(); serailNo = reader.Value; break; case "ProductName": reader.Read(); productName = reader.Value; break; case "Sum": reader.Read(); sum = reader.Value; productDetails = new ProductDetails(int.Parse(serailNo), productName, decimal.Parse(sum)); Products.Add(productDetails); break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Products") break; } break; } } } return Products; } /// <summary> /// Adds the series for the chart. /// </summary> /// <param name="chart">Represents the chart instance from the presentation.</param> private void AddSeriesForChart(IPresentationChart chart) { //Add a series for the chart. IOfficeChartSerie series = chart.Series.Add("Sales"); series.Values = chart.ChartData[2, 2, 11, 2]; //Setting data label series.DataPoints.DefaultDataPoint.DataLabels.IsValue = true; series.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside; series.DataPoints.DefaultDataPoint.DataLabels.Size = 14; } #endregion HelperMethods public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } #region Helper class /// <summary> /// Specifies the Product details /// </summary> public class ProductDetails { #region fields private int m_serialNo; private string m_productName; private decimal m_sum; #endregion #region properties /// <summary> /// Gets or sets the serial number of the product. /// </summary> public int SNO { get { return m_serialNo; } set { m_serialNo = value; } } /// <summary> /// Gets or sets the name of the product. /// </summary> public string ProductName { get { return m_productName; } set { m_productName = value; } } /// <summary> /// Gets or sets the sum value of the product. /// </summary> public decimal Sum { get { return m_sum; } set { m_sum = value; } } #endregion #region Constructor /// <summary> /// Constructor for the ProductDetails to create a new instance. /// </summary> /// <param name="serialNumber">Represents the serial number of the product.</param> /// <param name="productName">Represents the product name.</param> /// <param name="sum">Represents the sum value of the product.</param> public ProductDetails(int serialNumber, string productName, decimal sum) { SNO = serialNumber; ProductName = productName; Sum = Math.Round(sum, 3); } #endregion } #endregion } <file_sep>/Android/SampleBrowser/Samples/DataSource/Model/ContactsList.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using Android.Graphics; namespace SampleBrowser { public class ContactsLists : ObservableCollection<Contacts> { public ContactsLists() { Random r = new Random(); foreach (var cusName in customerNames) { var contact = new Contacts(cusName, r.Next(720, 799).ToString() + " - " + r.Next(3010, 3999).ToString()); contact.ContactColor = Color.Rgb(r.Next(40, 255), r.Next(40, 255), r.Next(40, 255)); this.Add(contact); } } private string[] customerNames = new string[] { "Kyle", "Gina", "Irene", "Katie", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Brenda", "Danielle", "Fiona", "Howard", "Jack", "Larry", "Holly", "Jennifer", "Liz", "Pete", "Steve", "Vince", "Zeke", "Aiden", "Jackson", "Mason", "Liam", "Jacob", "Jayden", "Ethan", "Noah", "Lucas", "Logan", "Caleb", "Caden", "Jack", "Ryan", "Connor", "Michael", "Elijah", "Brayden", "Benjamin", "Nicholas", "Alexander", "William", "Matthew", "James", "Landon", "Nathan", "Dylan", "Evan", "Luke", "Andrew", "Gabriel", "Gavin", "Joshua", "Owen", "Daniel", "Carter", "Tyler", "Cameron", "Christian", "Wyatt", "Henry", "Eli", "Joseph", "Max", "Isaac", "Samuel", "Anthony", "Grayson", "Zachary", "David", "Christopher", "John", "Isaiah", "Levi", "Jonathan", "Oliver", "Chase", "Cooper", "Tristan", "Colton", "Austin", "Colin", "Charlie", "Dominic", "Parker", "Hunter", "Thomas", "Alex", "Ian", "Jordan", "Cole", "Julian", "Aaron", "Carson", "Miles", "Blake", "Brody", "Adam", "Sebastian", "Adrian", "Nolan", "Sean", "Riley", "Bentley", "Xavier", "Hayden", "Jeremiah", "Jason", "Jake", "Asher", "Micah", "Jace", "Brandon", "Josiah", "Hudson", "Nathaniel", "Bryson", "Ryder", "Justin", "Bryce", }; } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/TechnicalIndicators.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; namespace SampleBrowser { public class TechnicalIndicators : SamplePage { SfChart chart; List<String> adapter; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.SetPadding(0, 10, 0, 0); chart.Behaviors.Add(new ChartTrackballBehavior()); DateTimeAxis dateTimeAxis = new DateTimeAxis(); dateTimeAxis.LabelStyle.LabelFormat = "MM/yyyy"; chart.PrimaryAxis = dateTimeAxis; NumericalAxis numericalAxis = new NumericalAxis(); chart.SecondaryAxis = numericalAxis; HiLoOpenCloseSeries candleSeries = new HiLoOpenCloseSeries(); candleSeries.ItemsSource = MainPage.GetTechnicalIndicatorData(); candleSeries.XBindingPath = "XValue"; candleSeries.Open = "Open"; candleSeries.Close = "Close"; candleSeries.High = "High"; candleSeries.Low = "Low"; candleSeries.EnableAnimation = true; candleSeries.Name = "Series"; chart.Series.Add(candleSeries); SimpleMovingAverageIndicator sMA = new SimpleMovingAverageIndicator(); sMA.SeriesName = "Series"; sMA.XBindingPath = "XValue"; sMA.Open = "Open"; sMA.Close = "Close"; sMA.High = "High"; sMA.Low = "Low"; sMA.EnableAnimation = true; chart.TechnicalIndicators.Add(sMA); TextView labelDisplayMode = new TextView(context); labelDisplayMode.TextSize = 20; labelDisplayMode.Text = "Technical Indicator type"; Spinner selectLabelMode = new Spinner(context,SpinnerMode.Dialog); adapter = new List<String>() {"Simple Moving Average Indicator", "Average True Indicator", "Exponential Moving Averge Indicator", "Momentum Indicator", "Accumulation Distribution Indicator", "RSI Indicator", "Triangular Moving Average Indicator", "MACD Indicator", "Stochastic Indicator", "Bollinger Band Indicator" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += SelectLabelMode_ItemSelected; LinearLayout linearLayout = new LinearLayout(context); linearLayout.SetPadding(20, 0, 20, 30); linearLayout.SetBackgroundColor(Color.Rgb(236, 235, 242)); linearLayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); linearLayout.Orientation = Orientation.Vertical; linearLayout.SetBackgroundColor(Color.White); linearLayout.AddView(selectLabelMode); linearLayout.AddView(chart); return linearLayout; } private void SelectLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter[e.Position]; if (selectedItem.Equals("Accumulation Distribution Indicator")) { chart.TechnicalIndicators.RemoveAt(0); AccumulationDistributionIndicator accumulationDistribution = new AccumulationDistributionIndicator(); NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; accumulationDistribution.YAxis = numericalAxis; accumulationDistribution.SeriesName = "Series"; accumulationDistribution.XBindingPath = "XValue"; accumulationDistribution.Open = "Open"; accumulationDistribution.Close = "Close"; accumulationDistribution.High = "High"; accumulationDistribution.Low = "Low"; chart.TechnicalIndicators.Add(accumulationDistribution); } else if (selectedItem.Equals("Average True Indicator")) { chart.TechnicalIndicators.RemoveAt(0); AverageTrueIndicator aTR = new AverageTrueIndicator(); NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; aTR.YAxis = numericalAxis; aTR.Period = 14; aTR.SeriesName = "Series"; aTR.XBindingPath = "XValue"; aTR.Open = "Open"; aTR.Close = "Close"; aTR.High = "High"; aTR.Low = "Low"; chart.TechnicalIndicators.Add(aTR); } else if (selectedItem.Equals("Exponential Moving Averge Indicator")) { chart.TechnicalIndicators.RemoveAt(0); ExponentialMovingAverageIndicator eMA = new ExponentialMovingAverageIndicator(); NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; eMA.YAxis = numericalAxis; eMA.Period = 14; eMA.SeriesName = "Series"; eMA.XBindingPath = "XValue"; eMA.Open = "Open"; eMA.Close = "Close"; eMA.High = "High"; eMA.Low = "Low"; chart.TechnicalIndicators.Add(eMA); } else if (selectedItem.Equals("Momentum Indicator")) { chart.TechnicalIndicators.RemoveAt(0); MomentumIndicator momentum = new MomentumIndicator(); NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; momentum.YAxis = numericalAxis; momentum.SeriesName = "Series"; momentum.XBindingPath = "XValue"; momentum.Open = "Open"; momentum.Close = "Close"; momentum.High = "High"; momentum.Low = "Low"; momentum.Period = 14; chart.TechnicalIndicators.Add(momentum); } else if (selectedItem.Equals("Simple Moving Average Indicator")) { chart.TechnicalIndicators.RemoveAt(0); SimpleMovingAverageIndicator sMA = new SimpleMovingAverageIndicator(); sMA.SeriesName = "Series"; sMA.XBindingPath = "XValue"; sMA.Open = "Open"; sMA.Close = "Close"; sMA.High = "High"; sMA.Low = "Low"; sMA.Period = 14; chart.TechnicalIndicators.Add(sMA); } else if (selectedItem.Equals("RSI Indicator")) { chart.TechnicalIndicators.RemoveAt(0); RSIIndicator rSI = new RSIIndicator(); NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; rSI.YAxis = numericalAxis; rSI.Period = 14; rSI.SeriesName = "Series"; rSI.XBindingPath = "XValue"; rSI.Open = "Open"; rSI.Close = "Close"; rSI.High = "High"; rSI.Low = "Low"; chart.TechnicalIndicators.Add(rSI); } else if (selectedItem.Equals("Triangular Moving Average Indicator")) { chart.TechnicalIndicators.RemoveAt(0); TriangularMovingAverageIndicator tMA = new TriangularMovingAverageIndicator(); NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; tMA.YAxis = numericalAxis; tMA.Period = 14; tMA.SeriesName = "Series"; tMA.XBindingPath = "XValue"; tMA.Open = "Open"; tMA.Close = "Close"; tMA.High = "High"; tMA.Low = "Low"; chart.TechnicalIndicators.Add(tMA); } else if (selectedItem.Equals("MACD Indicator")) { chart.TechnicalIndicators.RemoveAt(0); MACDIndicator mACD = new MACDIndicator(); NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; mACD.YAxis = numericalAxis; mACD.SeriesName = "Series"; mACD.XBindingPath = "XValue"; mACD.Open = "Open"; mACD.Close = "Close"; mACD.High = "High"; mACD.Low = "Low"; mACD.ShortPeriod = 2; mACD.LongPeriod = 10; mACD.Trigger = 14; chart.TechnicalIndicators.Add(mACD); } else if (selectedItem.Equals("Stochastic Indicator")) { chart.TechnicalIndicators.RemoveAt(0); StochasticIndicator stochastic = new StochasticIndicator(); NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; stochastic.YAxis = numericalAxis; stochastic.SeriesName = "Series"; stochastic.XBindingPath = "XValue"; stochastic.Open = "Open"; stochastic.Close = "Close"; stochastic.High = "High"; stochastic.Low = "Low"; stochastic.Period = 14; stochastic.KPeriod = 5; stochastic.DPeriod = 6; chart.TechnicalIndicators.Add(stochastic); } else if (selectedItem.Equals("Bollinger Band Indicator")) { chart.TechnicalIndicators.RemoveAt(0); BollingerBandIndicator bB = new BollingerBandIndicator(); bB.Period = 14; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; //bB.YAxis = numericalAxis; bB.SeriesName = "Series"; bB.XBindingPath = "XValue"; bB.Open = "Open"; bB.Close = "Close"; bB.High = "High"; bB.Low = "Low"; chart.TechnicalIndicators.Add(bB); } } } }<file_sep>/Forms/TextInputLayout/TextInputLayout/Samples/SignUpView/SignUpViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using AutoComplete = Syncfusion.SfAutoComplete.XForms.SfAutoComplete; using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; using System.Windows.Input; using Xamarin.Forms; namespace SampleBrowser.SfTextInputLayout { public class SignUpViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private bool enableHintAlwaysFloated; public bool EnableHintAlwaysFloated { get { return enableHintAlwaysFloated; } set { enableHintAlwaysFloated = value; NotifyPropertyChanged(); } } private string notes; public string Notes { get { return notes; } set { notes = value; NotifyPropertyChanged(); } } private string dateOfBirth; public string DateOfBirth { get { return dateOfBirth; } set { dateOfBirth = value; NotifyPropertyChanged(); } } private string mail; public string Mail { get { return mail; } set { mail = value; HasError = false; NotifyPropertyChanged(); } } private string password; public string Password { get { return password; } set { password = value; IsEnabled = password.Length >= 5; IsPasswordEmpty = false; NotifyPropertyChanged(); } } private string phoneNumber; public string PhoneNumber { get { return phoneNumber; } set { phoneNumber = value; IsMobileNumberEmpty = false; NotifyPropertyChanged(); } } private string name; public string Name { get { return name; } set { name = value; IsNameEmpty = false; NotifyPropertyChanged(); } } private string gender; public string Gender { get { return gender; } set { gender = value; IsGenderEmpty = false; NotifyPropertyChanged(); } } private string address; public string Address { get { return address; } set { address = value; IsAddressEmpty = false; NotifyPropertyChanged(); } } private List<string> state; public List<string> State { get { return state; } set { state = value; NotifyPropertyChanged(); } } private string selectedState; public string SelectedState { get { return selectedState; } set { selectedState = value; IsStateEmpty = false; NotifyPropertyChanged(); } } private DateTime dateTime = new DateTime(1990, 01, 01); public DateTime DateTime { get { return dateTime; } set { if (value != dateTime) { dateTime = value; DateOfBirth = dateTime.Month + "/" + dateTime.Day + "/" + dateTime.Year; NotifyPropertyChanged(); } } } private bool hasError; public bool HasError { get { return hasError; } set { hasError = value; NotifyPropertyChanged(); } } private string confirmPassword; public string ConfirmPassword { get { return confirmPassword; } set { confirmPassword = value; IsConfirmPasswordEmpty = false; NotifyPropertyChanged(); } } private bool isNameEmpty; public bool IsNameEmpty { get { return isNameEmpty; } set { isNameEmpty = value; NotifyPropertyChanged(); } } private bool isGenderEmpty; public bool IsGenderEmpty { get { return isGenderEmpty; } set { isGenderEmpty = value; NotifyPropertyChanged(); } } private bool isAddressEmpty; public bool IsAddressEmpty { get { return isAddressEmpty; } set { isAddressEmpty = value; NotifyPropertyChanged(); } } private bool isStateEmpty; public bool IsStateEmpty { get { return isStateEmpty; } set { isStateEmpty = value; NotifyPropertyChanged(); } } private bool isMobileNumberEmpty; public bool IsMobileNumberEmpty { get { return isMobileNumberEmpty; } set { isMobileNumberEmpty = value; NotifyPropertyChanged(); } } private bool isPasswordEmpty; public bool IsPasswordEmpty { get { return isPasswordEmpty; } set { isPasswordEmpty = value; NotifyPropertyChanged(); } } private bool isConfirmPasswordEmpty; public bool IsConfirmPasswordEmpty { get { return isConfirmPasswordEmpty; } set { isConfirmPasswordEmpty = value; NotifyPropertyChanged(); } } private bool isEnabled; public bool IsEnabled { get { return isEnabled; } set { isEnabled = value; NotifyPropertyChanged(nameof(IsEnabled)); } } private List<int> fontSizeCollection = new List<int> { 12, 14, 16 }; public List<int> FontSizeCollection => fontSizeCollection; private int containerLabelFontSize = 16; public int ContainerLabelFontSize { get { return containerLabelFontSize; } set { containerLabelFontSize = value; NotifyPropertyChanged(); } } private int selectedFontSize = 2; public int SelectedFontSize { get { return selectedFontSize; } set { selectedFontSize = value; NotifyPropertyChanged(); ContainerLabelFontSize = FontSizeCollection[selectedFontSize]; } } List<FontAttributes> fontAttributeCollection = new List<FontAttributes> { FontAttributes.None, FontAttributes.Bold, FontAttributes.Italic }; public List<FontAttributes> FontAttributeCollection => fontAttributeCollection; private FontAttributes containerLabelFontAttribute; public FontAttributes ContainerLabelFontAttribute { get { return containerLabelFontAttribute; } set { containerLabelFontAttribute = value; NotifyPropertyChanged(); } } private int selectedFontAttribute; public int SelectedFontAttribute { get { return selectedFontAttribute; } set { selectedFontAttribute = value; NotifyPropertyChanged(); ContainerLabelFontAttribute = FontAttributeCollection[selectedFontAttribute]; } } List<string> fontFamilyCollection = new List<string> { "Default", "Lobster-Regular" }; public List<string> FontFamilyCollection => fontFamilyCollection; private string containerLabelFontFamily; public string ContainerLabelFontFamily { get { return containerLabelFontFamily; } set { containerLabelFontFamily = value; NotifyPropertyChanged(); } } private int selectedFontFamily; public int SelectedFontFamily { get { return selectedFontFamily; } set { selectedFontFamily = value; NotifyPropertyChanged(); ContainerLabelFontFamily = FontFamilyCollection[selectedFontFamily]; } } public ICommand ResetCommand { get; private set; } public ICommand SubmitCommand { get; private set; } public SignUpViewModel() { SubmitCommand = new Command<string>(SubmitButtonClicked); ResetCommand = new Command<AutoComplete>(ResetButtonClicked); State = new List<string>(); State.Add("Alabama"); State.Add("Alaska"); State.Add("Arizona"); State.Add("California"); State.Add("Colorado"); State.Add("Delaware"); State.Add("Florida"); State.Add("Georgia"); State.Add("Hawaii"); State.Add("Lowa"); State.Add("Maine"); State.Add("MaryLand"); State.Add("Montana"); State.Add("Nevada"); State.Add("New Jersey"); State.Add("New Mexico"); State.Add("New York"); State.Add("Washington"); } private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// This method will be called whenever reset button is clicked /// </summary> /// <param name="obj">The object</param> private void ResetButtonClicked(object obj) { Notes = string.Empty; Mail = string.Empty; DateOfBirth = string.Empty; Name = string.Empty; Gender = string.Empty; PhoneNumber = string.Empty; Address = string.Empty; ConfirmPassword = string.Empty; Password = string.Empty; SelectedState = string.Empty; } /// <summary> /// This method will be called whenever submit button is clicked /// </summary> /// <param name="obj">The object</param> private void SubmitButtonClicked(object obj) { IsNameEmpty = string.IsNullOrEmpty(Name); IsGenderEmpty = string.IsNullOrEmpty(Gender); IsMobileNumberEmpty = string.IsNullOrEmpty(PhoneNumber); IsAddressEmpty = string.IsNullOrEmpty(Address); IsPasswordEmpty = string.IsNullOrEmpty(Password); IsStateEmpty = string.IsNullOrEmpty(SelectedState); if (!string.IsNullOrEmpty(Password)) { IsPasswordEmpty = Password.Length < 5; IsConfirmPasswordEmpty = !Password.Equals(ConfirmPassword); } if (string.IsNullOrEmpty(Mail) || !mail.Contains("@") || !mail.Contains(".")) { HasError = true; } else if (!IsNameEmpty && !IsMobileNumberEmpty && !IsAddressEmpty && !IsStateEmpty && !isPasswordEmpty && !IsConfirmPasswordEmpty && !IsGenderEmpty) { Application.Current.MainPage.DisplayAlert("Success", "Your account has been created successfully", "Ok"); } } } }<file_sep>/Android/SampleBrowser/Samples/Presentation/SlideTransition.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public partial class SlideTransitionPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to create slide transition effects in PowerPoint presentation."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Presentation"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Transition.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Create the transition effects on slides CreateTransition(presentation); MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("SlideTransitionSample.pptx", "application/powerpoint", stream, m_context); } } #region Create Transition private void CreateTransition(IPresentation presentation) { //Get the first slide from the presentation ISlide slide1 = presentation.Slides[0]; // Add the 'Wheel' transition effect to the first slide slide1.SlideTransition.TransitionEffect = TransitionEffect.Wheel; // Get the second slide from the presentation ISlide slide2 = presentation.Slides[1]; // Add the 'Checkerboard' transition effect to the second slide slide2.SlideTransition.TransitionEffect = TransitionEffect.Checkerboard; // Add the subtype to the transition effect slide2.SlideTransition.TransitionEffectOption = TransitionEffectOption.Across; // Apply the value to transition mouse on click parameter slide2.SlideTransition.TriggerOnClick = true; // Get the third slide from the presentation ISlide slide3 = presentation.Slides[2]; // Add the 'Orbit' transition effect for slide slide3.SlideTransition.TransitionEffect = TransitionEffect.Orbit; // Add the speed for transition slide3.SlideTransition.Speed = TransitionSpeed.Fast; // Get the fourth slide from the presentation ISlide slide4 = presentation.Slides[3]; // Add the 'Uncover' transition effect to the slide slide4.SlideTransition.TransitionEffect = TransitionEffect.Uncover; // Apply the value to advance on time for slide slide4.SlideTransition.TriggerOnTimeDelay = true; // Assign the advance on time value slide4.SlideTransition.TimeDelay = 5; // Get the fifth slide from the presentation ISlide slide5 = presentation.Slides[4]; // Add the 'PageCurlDouble' transition effect to the slide slide5.SlideTransition.TransitionEffect = TransitionEffect.PageCurlDouble; // Add the duration value for the transition effect slide5.SlideTransition.Duration = 5; } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Rating/Rating_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Util; using System; using System.Collections.Generic; using Android.Content; using Android.Views; using Android.Widget; using Com.Syncfusion.Rating; using Android.Content.Res; using Android.Graphics; using Android.Views.InputMethods; namespace SampleBrowser { public class Rating_Tab : SamplePage { /********************************* **Local Varabile Inizialization** *********************************/ LinearLayout pageLayout, columnLayout, imageLayout, contentLayout, propertylayout; LinearLayout textLayout, timeLayout, valueLayout; LinearLayout descriptionLayout, ratingLayout, padLayout; TextView title, movieLabel, time, description, dummyLabel2, dummyLabel, ratingLable, showLable; FrameLayout frame; double actionBarHeight, navigationBarHeight, totalHeight; int percisionPosition = 0, toolTipSpinnerPosition = 0, itemCountPosition = 5; ImageView imageView; SfRating sfRating, sfRating1; SfRatingSettings sfRatingSettings, sfRatingSetings1; ArrayAdapter<String> precisionAdapter, placementAdapter; Precision precisionPosition = Precision.Standard; TooltipPlacement toolTipPosition = TooltipPlacement.None; EditText itemCountEntry; int constCount = 5, height, width; Context con,context1; Spinner precisionSpinner, toolTipSpinner; public override View GetSampleContent(Context con1) { con = con1; InitialLayout(); TitleLayout(); ImageLayout(); //Non Editable Rating ratingLayout = new LinearLayout(con); ratingLayout.SetPadding(5, 2, 0, 0); sfRatingSettings = new SfRatingSettings(); sfRating1 = new SfRating(con); sfRating1.ItemSize = 33; sfRating1.Precision = Precision.Exact; sfRating1.Value = 3.5; sfRating1.ReadOnly = true; sfRating1.ItemSpacing = 0; sfRating1.TooltipPlacement = TooltipPlacement.None; sfRatingSettings.RatedFill = Color.ParseColor("#fbd10a"); sfRatingSettings.UnRatedFill = Color.ParseColor("#cdcccb"); sfRatingSettings.RatedStrokeWidth = 0; sfRatingSettings.UnRatedStrokeWidth = 0; sfRating1.RatingSettings = sfRatingSettings; sfRating1.LayoutParameters = new ViewGroup.LayoutParams((int)(400 * con.Resources.DisplayMetrics.Density), (int)(33 * con.Resources.DisplayMetrics.Density)); ratingLayout.AddView(sfRating1); textLayout.AddView(ratingLayout); contentLayout.AddView(textLayout); DescriptionLayout(); //Editable Rating sfRatingSetings1 = new SfRatingSettings(); sfRatingSetings1.RatedStroke = Color.ParseColor("#2095f2"); sfRating = new SfRating(con); sfRating.ItemSize = 53; sfRating.ItemSpacing = 33; sfRating.ItemCount = 5; sfRating.TooltipPrecision = 1; sfRating.Value = 3; sfRating.RatingSettings = sfRatingSetings1; sfRating.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(55 * con.Resources.DisplayMetrics.Density)); padLayout.AddView(dummyLabel); padLayout.AddView(sfRating); pageLayout.AddView(padLayout); ValueLayout(); ShowLabelLayout(); return pageLayout; } private void InitialLayout() { frame = new FrameLayout(con); totalHeight = con.Resources.DisplayMetrics.HeightPixels; TypedValue tv = new TypedValue(); if (con.Theme.ResolveAttribute(Android.Resource.Attribute.ActionBarSize, tv, true)) { actionBarHeight = TypedValue.ComplexToDimensionPixelSize(tv.Data, con.Resources.DisplayMetrics); } navigationBarHeight = getNavigationBarHeight(con); totalHeight = totalHeight - navigationBarHeight - actionBarHeight; height = con.Resources.DisplayMetrics.HeightPixels / 2; width = con.Resources.DisplayMetrics.WidthPixels / 2; //pageLayout pageLayout = new LinearLayout(con); pageLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.Top | GravityFlags.CenterHorizontal); pageLayout.Orientation = Android.Widget.Orientation.Vertical; } private void TitleLayout() { //title title = new TextView(con); title.TextSize = 25; title.SetTextColor(Color.ParseColor("#282828")); title.Text = "Movie Rating"; title.SetPadding(30, 40, 0, 40); pageLayout.AddView(title); //columnLayout columnLayout = new LinearLayout(con); columnLayout.Orientation = Android.Widget.Orientation.Horizontal; columnLayout.SetPadding(0, 10, 0, 0); } private void ImageLayout() { //image Layout imageLayout = new LinearLayout(con); imageView = new ImageView(con); imageView.SetScaleType(ImageView.ScaleType.FitXy); imageView.SetImageResource(Resource.Drawable.movie); FrameLayout.LayoutParams layoutParams1 = new FrameLayout.LayoutParams(width, (height * 2) / 3+250, GravityFlags.Center); imageView.SetPadding(30, 10, 10, 0); imageLayout.AddView(imageView, layoutParams1); imageLayout.SetGravity(GravityFlags.Center); //Content Layout contentLayout = new LinearLayout(con); contentLayout.Orientation = Android.Widget.Orientation.Vertical; contentLayout.SetPadding(10, 5, 20, 0); movieLabel = new TextView(con); movieLabel.TextSize = 16; movieLabel.SetTextColor(Color.ParseColor("#282828")); movieLabel.Text = "The walk ( 2015 )"; contentLayout.AddView(movieLabel); //Text Layout textLayout = new LinearLayout(con); textLayout.Orientation = Android.Widget.Orientation.Horizontal; textLayout.SetPadding(0, 5, 0, 0); time = new TextView(con); time.TextSize = 9; time.SetTextColor(Color.ParseColor("#282828")); time.Text = "PG | 2 h 20 min "; textLayout.AddView(time); } private void DescriptionLayout() { //Description description = new TextView(con); descriptionLayout = new LinearLayout(con); descriptionLayout.SetPadding(0, 0, 0, 0); description.TextSize = 10; description.SetTextColor(Color.ParseColor("#282828")); description.SetLineSpacing(6, 2); description.Text = "In 1973, French street performer <NAME> is trying to make a living in Paris with juggling acts and wire walking, much to the chagrin of his father. During one performance, he eats a hard candy which was given to him by an audience member and injures his tooth. He visits the dentist and, while in the waiting room, sees a picture in a magazine of the Twin Towers in New York City. He analyzes the photo and decides to make it his mission to walk a tightrope between the two buildings. Meanwhile, he is evicted from his parents' house by his father, citing his lack of income and the fact that he's a street performer. Philippe returns to the circus that inspired him to wire walk as a child and practices in the big top after hours, but is caught by Papa Rudy, whom he impresses with his juggling skills. "; description.SetPadding(0, 0, 20, 0); descriptionLayout.AddView(description); contentLayout.AddView(descriptionLayout); contentLayout.LayoutParameters = new ViewGroup.LayoutParams(width, (height * 2) / 3+250); columnLayout.AddView(imageLayout); columnLayout.AddView(contentLayout); pageLayout.AddView(columnLayout); //Time Layout timeLayout = new LinearLayout(con); timeLayout.SetPadding(30, 35, 30, 0); FrameLayout.LayoutParams separatorparams = new FrameLayout.LayoutParams(width * 2, 2, GravityFlags.Center); SeparatorView separatorView = new SeparatorView(con, width * 2); separatorView.separatorColor = Color.ParseColor("#a5a5a5"); timeLayout.AddView(separatorView, separatorparams); pageLayout.AddView(timeLayout); //Dummy Label dummyLabel2 = new TextView(con); dummyLabel2.TextSize = 15; dummyLabel2.SetPadding(30, 28, 0, 50); dummyLabel2.SetTextColor(Color.ParseColor("#282828")); dummyLabel2.Text = "Rate"; pageLayout.AddView(dummyLabel2); //padLayout padLayout = new LinearLayout(con); padLayout.Orientation = Android.Widget.Orientation.Horizontal; dummyLabel = new TextView(con); dummyLabel.Text = " "; } private void ValueLayout() { //Value Layout valueLayout = new LinearLayout(con); valueLayout.Orientation = Android.Widget.Orientation.Horizontal; valueLayout.SetPadding(30, 50, 0, 50); ratingLable = new TextView(con); ratingLable.TextSize = 10; ratingLable.SetTextColor(Color.ParseColor("#282828")); ratingLable.Text = "Rating : "; valueLayout.AddView(ratingLable); //sfRating Value Changed Listener sfRating.ValueChanged += (object sender, ValueChangedEventArgs e) => { if (!e.Value.ToString().Equals("")) { //valueString = e.P1.ToString (); UpdateText(e.Value); } }; } private void ShowLabelLayout() { //Show Label showLable = new TextView(con); showLable.TextSize = 10; showLable.SetTextColor(Color.ParseColor("#282828")); UpdateText(sfRating.Value); valueLayout.AddView(showLable); pageLayout.AddView(valueLayout); } private void UpdateText(double rateValue) { int tempIntValue = (int)rateValue; float tempFloatValue = (float)rateValue; float diffenceValue = tempFloatValue - tempIntValue; String changeValue; if (diffenceValue == 0) changeValue = tempIntValue.ToString(); else { String valueString = String.Format("{0:0.#}", tempFloatValue); changeValue = valueString; } showLable.Text = changeValue + " / " + sfRating.ItemCount; } //Apply Changes Method public void ApplyChanges() { sfRating.Precision = precisionPosition; sfRating.TooltipPlacement = toolTipPosition; sfRating.ItemCount = constCount; sfRating.Value = 3; if (sfRating.Value > constCount) sfRating.Value = 0; UpdateText(sfRating.Value); base.OnApplyChanges(); } public override View GetPropertyWindowLayout(Android.Content.Context context) { context1 = context; propertylayout = new LinearLayout(context1); propertylayout.SetPadding(0, 30, 0, 0); propertylayout.Orientation = Android.Widget.Orientation.Vertical; PrecisionLayout(); TooltipLayout(); ItemCountLayout(); return propertylayout; } private void PrecisionLayout() { //Precision TextView precisionLabel = new TextView(context1); precisionLabel.SetPadding(0,0,0,20); precisionLabel.TextSize = 20; precisionLabel.Text = "Precision"; //Precision Spinner precisionSpinner = new Spinner(context1, SpinnerMode.Dialog); precisionSpinner.SetGravity(GravityFlags.Left); //Precision List List<String> precisionList = new List<String>(); precisionList.Add("Standard"); precisionList.Add("Half"); precisionList.Add("Exact"); //precision Adapter precisionAdapter = new ArrayAdapter<String>(context1, Android.Resource.Layout.SimpleSpinnerItem, precisionList); precisionAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //precisionSpinner ItemSelected Listener precisionSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = precisionAdapter.GetItem(e.Position); percisionPosition = e.Position; if (selectedItem.Equals("Standard")) { precisionPosition = Precision.Standard; } if (selectedItem.Equals("Half")) { precisionPosition = Precision.Half; } if (selectedItem.Equals("Exact")) { precisionPosition = Precision.Exact; } ApplyChanges(); }; precisionSpinner.Adapter = precisionAdapter; precisionSpinner.SetSelection(percisionPosition); precisionSpinner.SetPadding(0, 0, 0, 20); //precisionLayout LinearLayout precisionLayout = new LinearLayout(context1); precisionLayout.SetPadding(0,0,0,50); precisionLayout.Orientation = Android.Widget.Orientation.Vertical; precisionLayout.AddView(precisionLabel); precisionLayout.AddView(precisionSpinner); propertylayout.AddView(precisionLayout); } private void TooltipLayout() { //ToolTip TextView tooltipLabel = new TextView(context1); tooltipLabel.TextSize = 20; tooltipLabel.SetPadding(0,50,0,20); tooltipLabel.Text = "Tooltip Placement"; //ToolTip Spinner toolTipSpinner = new Spinner(context1, SpinnerMode.Dialog); toolTipSpinner.SetGravity(GravityFlags.Left); //Placement List List<String> placementList = new List<String>(); placementList.Add("None"); placementList.Add("TopLeft"); placementList.Add("BottomRight"); //Placement Adapter placementAdapter = new ArrayAdapter<String>(context1, Android.Resource.Layout.SimpleSpinnerItem, placementList); placementAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //ToolTip Spinner Item Selected Listener toolTipSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = placementAdapter.GetItem(e.Position); toolTipSpinnerPosition = e.Position; if (selectedItem.Equals("None")) { toolTipPosition = TooltipPlacement.None; } if (selectedItem.Equals("TopLeft")) { toolTipPosition = TooltipPlacement.TopLeft; } if (selectedItem.Equals("BottomRight")) { toolTipPosition = TooltipPlacement.BottomRight; } ApplyChanges(); }; toolTipSpinner.Adapter = placementAdapter; toolTipSpinner.SetSelection(toolTipSpinnerPosition); //toolTipLayout LinearLayout toolTipLayout = new LinearLayout(context1); toolTipLayout.Orientation = Android.Widget.Orientation.Vertical; toolTipLayout.SetPadding(0, 0, 0, 50); toolTipLayout.AddView(tooltipLabel); toolTipLayout.AddView(toolTipSpinner); propertylayout.AddView(toolTipLayout); } private void ItemCountLayout() { //ItemCount TextView itemLabel = new TextView(context1); itemLabel.Text = "Item Count"; itemLabel.SetPadding(0,0,40,20); itemLabel.Gravity = GravityFlags.CenterVertical; itemLabel.TextSize = 20; itemCountEntry = new EditText(context1); itemCountEntry.Gravity = GravityFlags.Left; itemCountEntry.Text = itemCountPosition.ToString(); itemCountEntry.TextSize = 16; itemCountEntry.InputType = Android.Text.InputTypes.ClassPhone; itemCountEntry.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (itemCountEntry.Text.Length > 0) try { constCount = Convert.ToInt32(e.Text.ToString()); } catch (Exception) { constCount = 1; } itemCountPosition = constCount; ApplyChanges(); }; //itemCountLayout LinearLayout itemCountLayout = new LinearLayout(context1); itemCountLayout.SetPadding(0,0,0,50); itemCountLayout.Orientation = Android.Widget.Orientation.Vertical; itemCountLayout.AddView(itemLabel); itemCountLayout.AddView(itemCountEntry); propertylayout.AddView(itemCountLayout); } private int getNavigationBarHeight(Android.Content.Context con) { int navBarHeight = 0; int resourceId = con.Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navBarHeight = con.Resources.GetDimensionPixelSize(resourceId); } return navBarHeight; } } } <file_sep>/Forms/XlsIO/XlsIO/Samples/ImportXMLPage/ImportXMLPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XlsIO; using Xamarin.Forms; namespace SampleBrowser.XlsIO { /// <summary> /// This class is used to import XML data into Excel workbook. /// </summary> public partial class ImportXMLPage : SampleView { public ImportXMLPage() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP)) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } internal void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; //Initializing Workbook //A new workbook is created.[Equivalent to creating a new workbook in MS Excel] //The new workbook will have 1 worksheets IWorkbook workbook = application.Workbooks.Create(1); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = null; #if COMMONSB fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.customers.xml"); #else fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.customers.xml"); #endif // Import the XML contents to worksheet XlsIOExtensions exten = new XlsIOExtensions(); exten.ImportXML(fileStream, sheet, 1, 1, true); // Apply style for header IStyle headerStyle = sheet[1, 1, 1, sheet.UsedRange.LastColumn].CellStyle; headerStyle.Font.Bold = true; headerStyle.Font.Color = ExcelKnownColors.Brown; headerStyle.Font.Size = 10; // Resize columns sheet.Columns[0].ColumnWidth = 11; sheet.Columns[1].ColumnWidth = 30.5; sheet.Columns[2].ColumnWidth = 20; sheet.Columns[3].ColumnWidth = 25.6; sheet.Columns[6].ColumnWidth = 10.5; sheet.Columns[4].ColumnWidth = 40; sheet.Columns[5].ColumnWidth = 25.5; sheet.Columns[7].ColumnWidth = 9.6; sheet.Columns[8].ColumnWidth = 15; sheet.Columns[9].ColumnWidth = 15; // Saving workbook and disposing objects workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("ImportXML.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("ImportXML.xlsx", "application/msexcel", stream); } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/StackingBar100.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { [Activity(Label = "100% Stacked Bars")] public class StackingBar100 : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Sales Comparison"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis categoryAxis = new CategoryAxis(); categoryAxis.ShowMajorGridLines = false; categoryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; categoryAxis.LabelPlacement = LabelPlacement.BetweenTicks; chart.PrimaryAxis = categoryAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; numericalAxis.Minimum = 0; numericalAxis.Maximum = 100; numericalAxis.Interval = 20; numericalAxis.LineStyle.StrokeWidth = 0; numericalAxis.MajorTickStyle.TickSize = 0; numericalAxis.LabelStyle.LabelFormat = "#'%'"; chart.SecondaryAxis = numericalAxis; StackingBar100Series stackingBar100Series = new StackingBar100Series(); stackingBar100Series.EnableAnimation = true; stackingBar100Series.Label = "Apple"; stackingBar100Series.ItemsSource = MainPage.GetStackedBar100Data1(); stackingBar100Series.XBindingPath = "XValue"; stackingBar100Series.YBindingPath = "YValue"; StackingBar100Series stackingBar100Series1 = new StackingBar100Series(); stackingBar100Series1.EnableAnimation = true; stackingBar100Series1.Label = "Orange"; stackingBar100Series1.ItemsSource = MainPage.GetStackedBar100Data2(); stackingBar100Series1.XBindingPath = "XValue"; stackingBar100Series1.YBindingPath = "YValue"; StackingBar100Series stackingBar100Series2 = new StackingBar100Series(); stackingBar100Series2.EnableAnimation = true; stackingBar100Series2.Label = "Wastage"; stackingBar100Series2.ItemsSource = MainPage.GetStackedBar100Data3(); stackingBar100Series2.XBindingPath = "XValue"; stackingBar100Series2.YBindingPath = "YValue"; chart.Series.Add(stackingBar100Series); chart.Series.Add(stackingBar100Series1); chart.Series.Add(stackingBar100Series2); stackingBar100Series.TooltipEnabled = true; stackingBar100Series1.TooltipEnabled = true; stackingBar100Series2.TooltipEnabled = true; stackingBar100Series.EnableAnimation = true; stackingBar100Series1.EnableAnimation = true; stackingBar100Series2.EnableAnimation = true; return chart; } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/ContextMenu.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content.Res; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Syncfusion.Android.PopupLayout; using Syncfusion.SfDataGrid; using System.Drawing; using Android.Content; using static Android.App.ActionBar; using System.ComponentModel; namespace SampleBrowser { public class ContextMenu : SamplePage { #region Private Field //Source Initializing private SfDataGrid sfGrid; private SfPopupLayout sfPopupLayout; private ContextMenuModel itemViewModel; private string currentColumn; //Button field private Button sortAscendingButton; private Button sortDescendingButton; private Button clearSortingButton; private Button groupColumnButton; private Button clearGroupingButton; //Image field ImageView sortAscendingImage; ImageView sortDescendingImage; ImageView clearSortingImage; ImageView groupColumnImage; ImageView clearGroupingImage; //Initial values private int initialValue = 20; private int initialPoppupHeight = 200; private int initialPoppupWidth = 200; private int gridHeight; private int imagesHeight; private double displayDensity; #endregion #region Methods public override Android.Views.View GetSampleContent(Android.Content.Context context) { // Initializing grid with required properties this.sfGrid = new SfDataGrid(context); this.sfGrid.AutoGenerateColumns = true; this.itemViewModel = new ContextMenuModel(); this.sfGrid.ItemsSource = itemViewModel.OrderInfo; this.sfPopupLayout = new SfPopupLayout(context); //Calculation for the image and gridHeight this.displayDensity = (sfPopupLayout.Resources.DisplayMetrics.Density); this.imagesHeight = (int)(initialValue * displayDensity); this.gridHeight = (int)(198.5 * displayDensity) / 5; //Initializing SfPoplayout with required properties this.InitializePopLayout(context); //Initializing the layout to be displayed inside popup this.InitializingContextMenuLayout(context); this.sfGrid.GridLongPressed += SfGrid_GridLongPressed; //RootView is Poplayout so sfgrid view added as child to poppup this.sfPopupLayout.Content = this.sfGrid; return sfPopupLayout; } private void InitializePopLayout(Context context) { this.sfPopupLayout.PopupView.AnimationMode = AnimationMode.Fade; this.sfPopupLayout.PopupView.AnimationDuration = 300; this.sfPopupLayout.PopupView.ShowCloseButton = false; this.sfPopupLayout.PopupView.ShowFooter = false; this.sfPopupLayout.PopupView.ShowHeader = false; this.sfPopupLayout.PopupView.WidthRequest = initialPoppupWidth; this.sfPopupLayout.PopupView.HeightRequest = initialPoppupHeight; } private void InitializingContextMenuLayout(Context context) { LinearLayout contextMenu = new LinearLayout(context); contextMenu.Orientation = Android.Widget.Orientation.Vertical; #region Image declaring this.sortAscendingImage = new ImageView(context); this.sortAscendingImage.SetImageResource(Resource.Drawable.Sort_Ascending_Icons); this.sortDescendingImage = new ImageView(context); this.sortDescendingImage.SetImageResource(Resource.Drawable.Sort_descending_Icons); this.clearSortingImage = new ImageView(context); this.clearSortingImage.SetImageResource(Resource.Drawable.Clear_sorting_Icon); this.clearSortingImage.Alpha = .2f; this.groupColumnImage = new ImageView(context); this.groupColumnImage.SetImageResource(Resource.Drawable.Grouping_Icon); this.clearGroupingImage = new ImageView(context); this.clearGroupingImage.SetImageResource(Resource.Drawable.Clear_grouping_icon); this.clearGroupingImage.Alpha = .2f; #endregion #region Button this.sortAscendingButton = CreateButton("Sort Ascending", context); this.sortDescendingButton = CreateButton("Sort Descending", context); this.clearSortingButton = CreateButton("Clear Sorting", context); this.groupColumnButton = CreateButton("Group this Column", context); this.clearGroupingButton = CreateButton("Clear Grouping", context); #endregion #region Seperator View View seperatorView = new View(context); seperatorView.SetBackgroundColor(Android.Graphics.Color.Gray); seperatorView.Alpha = .3f; #endregion #region GridLayout With Button and Image GridLayout ascendingGrid = CreateGridWithViews(context, sortAscendingButton, sortAscendingImage); GridLayout descendigGrid = CreateGridWithViews(context, sortDescendingButton, sortDescendingImage); GridLayout clearSortingGrid = CreateGridWithViews(context, clearSortingButton, clearSortingImage); GridLayout groupingGrid = CreateGridWithViews(context, groupColumnButton, groupColumnImage); GridLayout ClearGroupingGrid = CreateGridWithViews(context, clearGroupingButton, clearGroupingImage); #endregion contextMenu.AddView(ascendingGrid, ViewGroup.LayoutParams.MatchParent, gridHeight); contextMenu.AddView(descendigGrid, ViewGroup.LayoutParams.MatchParent, gridHeight); contextMenu.AddView(clearSortingGrid, ViewGroup.LayoutParams.MatchParent, gridHeight); contextMenu.AddView(seperatorView, ViewGroup.LayoutParams.MatchParent, (int)(1.5 * displayDensity)); contextMenu.AddView(groupingGrid, ViewGroup.LayoutParams.MatchParent, gridHeight); contextMenu.AddView(ClearGroupingGrid, ViewGroup.LayoutParams.MatchParent, gridHeight); this.sfPopupLayout.PopupView.ContentView = contextMenu; } private void SfGrid_GridLongPressed(object sender, GridLongPressedEventArgs e) { this.currentColumn = this.sfGrid.Columns[e.RowColumnIndex.ColumnIndex].MappingName; this.sfPopupLayout.ShowAtTouchPoint(); } private GridLayout CreateGridWithViews(Context context, Button bundleButton, ImageView bundleImage) { GridLayout gridView = new GridLayout(context); gridView.AlignmentMode = GridAlign.Bounds; gridView.ColumnCount = 2; gridView.Orientation = GridOrientation.Horizontal; gridView.UseDefaultMargins = true; gridView.AddView(bundleImage, this.imagesHeight, this.imagesHeight); gridView.AddView(bundleButton); return gridView; } private Button CreateButton(String content, Context context) { Button optionButton = new Button(context); optionButton.SetBackgroundColor(Android.Graphics.Color.Transparent); optionButton.SetPadding(0, 0, 20, 0); optionButton.Text = content; optionButton.TextSize = 16; optionButton.Gravity = GravityFlags.Left; optionButton.LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent); optionButton.Click += OptionButton_Click; if (content.Equals("Clear Sorting") || content.Equals("Clear Grouping")) { optionButton.Alpha = .2f; } return optionButton; } private void OptionButton_Click(object sender, EventArgs e) { var buttonName = (sender as Button).Text; switch (buttonName) { case "Sort Ascending": case "Sort Descending": case "Clear Sorting": this.sfGrid.SortColumnDescriptions.Clear(); if (!(buttonName == "Clear Sorting")) { // Sorting is applied this.sfGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = this.currentColumn, SortDirection = (buttonName == "Sort Ascending") ? ListSortDirection.Ascending : ListSortDirection.Descending }); } ApplyAlphaToSorting(buttonName); break; case "Group this Column": case "Clear Grouping": { if (sfGrid.GroupColumnDescriptions.Count == 0) { // Grouping is applied sfGrid.GroupColumnDescriptions.Add(new GroupColumnDescription() { ColumnName = this.currentColumn }); } else { // Clears the Grouping this.sfGrid.GroupColumnDescriptions.Clear(); if (this.sfGrid.SortColumnDescriptions.Count > 0) { this.sfGrid.SortColumnDescriptions.Clear(); ApplyAlphaToSorting("Clear Sorting"); } } ApplyAlphaToGrouping(); break; } } this.sfPopupLayout.IsOpen = false; } private void ApplyAlphaToSorting(string buttonName) { this.sortAscendingImage.Alpha = buttonName == "Sort Ascending" ? .2f : 1f; this.sortAscendingButton.Alpha = buttonName == "Sort Ascending" ? .2f : 1f; this.sortDescendingImage.Alpha = buttonName == "Sort Descending" ? .2f : 1f; this.sortDescendingButton.Alpha = buttonName == "Sort Descending" ? .2f : 1f; this.clearSortingImage.Alpha = this.sfGrid.SortColumnDescriptions.Count > 0 ? 1f : .4f; this.clearSortingButton.Alpha = this.sfGrid.SortColumnDescriptions.Count > 0 ? 1f : .4f; } private void ApplyAlphaToGrouping() { this.groupColumnButton.Enabled = this.sfGrid.GroupColumnDescriptions.Count > 0 ? false : true; this.groupColumnButton.Alpha = this.sfGrid.GroupColumnDescriptions.Count > 0 ? .2f : 1; this.groupColumnImage.Alpha = this.sfGrid.GroupColumnDescriptions.Count > 0 ? .2f : 1; this.clearGroupingImage.Alpha = this.sfGrid.GroupColumnDescriptions.Count > 0 ? 1f : .2f; this.clearGroupingButton.Alpha = this.sfGrid.GroupColumnDescriptions.Count > 0 ? 1f : .2f; } #endregion #region Dispose public override void Destroy() { this.sfPopupLayout.Dispose(); sfGrid = null; itemViewModel = null; } #endregion } }<file_sep>/Forms/DataGrid/DataGrid.WPF/MainWindow.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core.WPF; using Syncfusion.ListView.XForms.WPF; using Syncfusion.SfDataGrid.XForms.WPF; using Xamarin.Forms; using Xamarin.Forms.Platform.WPF; namespace SampleBrowser.SfDataGrid.WPF { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : FormsApplicationPage { public MainWindow() { InitializeComponent(); Forms.Init(); CoreSampleBrowser.Init(); SfDataGridRenderer.Init(); SfListViewRenderer.Init(); LoadApplication(new SfDataGrid.App()); } } } <file_sep>/Android/SampleBrowser/Samples/DataForm/DataFormGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.Android.DataForm; using Android.Graphics; using Android.Views.InputMethods; using System.ComponentModel; namespace SampleBrowser { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] public class DataFormGettingStarted : SamplePage { private SfDataForm dataForm; private Context context; private Button transferButton; public override View GetSampleContent(Context context) { this.context = context; //// Get our button from the layout resource, //// and attach an event to it var dataFormParentViewLayout = new LinearLayout(context); dataFormParentViewLayout.Orientation = Orientation.Vertical; var titlebarLayout = LayoutInflater.From(context).Inflate(Resource.Layout.TitleBarLayout, null); titlebarLayout = titlebarLayout.FindViewById<RelativeLayout>(Resource.Id.titleRelativeLayout); dataForm = new SfDataForm(context); dataForm.AutoGeneratingDataFormItem += DataForm_AutoGeneratingDataFormItem; dataForm.RegisterEditor("AccountType", "DropDown"); dataForm.LabelPosition = LabelPosition.Top; dataForm.CommitMode = CommitMode.LostFocus; dataForm.ValidationMode = ValidationMode.Explicit; dataForm.DataObject = new RecipientInfo(); (dataForm.DataObject as INotifyPropertyChanged).PropertyChanged += DataFormGettingStarted_PropertyChanged; transferButton = titlebarLayout.FindViewById<Button>(Resource.Id.label); transferButton.Text = "TRANSFER MONEY"; transferButton.SetBackgroundColor(Color.ParseColor("#2196F3")); transferButton.SetTextColor(Color.ParseColor("#FFFFFF")); transferButton.Click += Label_Click; dataFormParentViewLayout.AddView(dataForm); dataForm.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent, 1.0f); dataFormParentViewLayout.AddView(titlebarLayout, new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, 150)); return dataFormParentViewLayout; } private void DataFormGettingStarted_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName.Equals("AccountNumber")) { var value = (string)sender.GetType().GetProperty("AccountNumber1").GetValue(sender); if (!string.IsNullOrEmpty(value)) { dataForm.Validate("AccountNumber1"); } } else if (e.PropertyName.Equals("AccountNumber1")) { var value = (string)sender.GetType().GetProperty("AccountNumber").GetValue(sender); if (!string.IsNullOrEmpty(value)) { dataForm.Validate("AccountNumber"); } } } private void DataForm_AutoGeneratingDataFormItem(object sender, AutoGeneratingDataFormItemEventArgs e) { if (e.DataFormItem != null) { if (e.DataFormItem.Name.Equals("AccountNumber") || e.DataFormItem.Name.Equals("AccountNumber1")) { (e.DataFormItem as DataFormTextItem).InputType = Android.Text.InputTypes.ClassNumber; } else if (e.DataFormItem.Name.Equals("Email")) { (e.DataFormItem as DataFormTextItem).InputType = Android.Text.InputTypes.TextVariationEmailAddress; } else if (e.DataFormItem.Name.Equals("SWIFT")) { (e.DataFormItem as DataFormTextItem).InputType = Android.Text.InputTypes.TextFlagCapCharacters; } } } private void Label_Click(object sender, EventArgs e) { var isValid = dataForm.Validate(); dataForm.Commit(); if (!isValid) { Toast.MakeText(context, "Please enter valid details", ToastLength.Long).Show(); return; } Toast.MakeText(context, "Money Transferred", ToastLength.Long).Show(); dataForm.IsReadOnly = true; transferButton.Enabled = false; } public override void Destroy() { if(this.dataForm != null) { (this.dataForm.DataObject as INotifyPropertyChanged).PropertyChanged -= DataFormGettingStarted_PropertyChanged; this.dataForm.AutoGeneratingDataFormItem -= DataForm_AutoGeneratingDataFormItem; this.dataForm.Dispose(); this.dataForm = null; } if (this.transferButton != null) { this.transferButton.Dispose(); this.transferButton = null; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/LogarithmicAxis.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Drawing; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class LogarithmicAxis : SampleView { public LogarithmicAxis() { SFChart chart = new SFChart (); chart.PrimaryAxis = new SFCategoryAxis (){ Interval = NSObject.FromObject(1)}; chart.PrimaryAxis.Title.Text = new NSString ("Years"); SFLogarithmicAxis yAxis = new SFLogarithmicAxis (); yAxis.ShowMinorGridLines = true; yAxis.MinorTicksPerInterval = 5; yAxis.Title.Text = new NSString ("Profit"); chart.SecondaryAxis = yAxis; chart.Title.Text = new NSString ("Business Growth"); chart.Title.EdgeInsets = new UIEdgeInsets (10, 5, 10, 5); chart.EdgeInsets = new UIEdgeInsets(-3, 5, 5, 10); chart.Delegate = new ChartDollarDelegate (); ChartViewModel dataModel = new ChartViewModel (); SFLineSeries series = new SFLineSeries(); series.ItemsSource = dataModel.LogarithmicData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.EnableAnimation = true; chart.Series.Add(series); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } } public class ChartDollarDelegate : SFChartDelegate { public override NSString GetFormattedAxisLabel (SFChart chart, NSString label, NSObject value, SFAxis axis) { if (axis == chart.SecondaryAxis) { String formattedLabel = "$" + label.ToString (); label = new NSString (formattedLabel); return label; } return label; } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Model/DealerInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DealerInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties and notifies clients that a property value has changed. /// </summary> public class DealerInfo : INotifyPropertyChanged { #region private variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int productNo; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int productID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string dealerName; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private bool isOnline; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int productprice; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string dealerImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DateTime shippedDate; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string shipCity; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string shipCountry; #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the value of DealerImage and notifies user when value gets changed /// </summary> public string DealerImage { get { return this.dealerImage; } set { this.dealerImage = value; this.RaisePropertyChanged("DealerImage"); } } /// <summary> /// Gets or sets the value of ProductID and notifies user when value gets changed /// </summary> public int ProductID { get { return this.productID; } set { this.productID = value; this.RaisePropertyChanged("ProductID"); } } /// <summary> /// Gets or sets the value of DealerName and notifies user when value gets changed /// </summary> public string DealerName { get { return this.dealerName; } set { this.dealerName = value; this.RaisePropertyChanged("DealerName"); } } /// <summary> /// Gets or sets a value indicating whether property value IsOnline was true or false and notifies user when value gets changed /// </summary> public bool IsOnline { get { return this.isOnline; } set { this.isOnline = value; this.RaisePropertyChanged("IsOnline"); } } /// <summary> /// Gets or sets the value of ProductPrice and notifies user when value gets changed /// </summary> public int ProductPrice { get { return this.productprice; } set { this.productprice = value; this.RaisePropertyChanged("ProductPrice"); } } /// <summary> /// Gets or sets the value of ProductNo and notifies user when value gets changed /// </summary> public int ProductNo { get { return this.productNo; } set { this.productNo = value; this.RaisePropertyChanged("ProductNo"); } } /// <summary> /// Gets or sets the value of ShippedDate and notifies user when value gets changed /// </summary> public DateTime ShippedDate { get { return this.shippedDate; } set { this.shippedDate = value; this.RaisePropertyChanged("ShippedDate"); } } /// <summary> /// Gets or sets the value of ShipCountry and notifies user when value gets changed /// </summary> public string ShipCountry { get { return this.shipCountry; } set { this.shipCountry = value; this.RaisePropertyChanged("ShipCountry"); } } /// <summary> /// Gets or sets the value of ShipCity and notifies user when value gets changed /// </summary> public string ShipCity { get { return this.shipCity; } set { this.shipCity = value; this.RaisePropertyChanged("ShipCity"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type of name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Forms/TimePicker/TimePicker/ViewModel/TimePickerAlarmObjectViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Pickers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; namespace SampleBrowser.SfTimePicker { #region TimePickerAlarmObjectViewModel class /// <summary> /// TimePicker AlarmObject ViewModel class /// </summary> public class TimePickerAlarmObjectViewModel : INotifyPropertyChanged { #region Members /// <summary> /// Alarm object collection field /// </summary> private ObservableCollection<TimePickerAlarmObject> alarms = new ObservableCollection<TimePickerAlarmObject>(); /// <summary> /// Selected Item field /// </summary> private TimePickerAlarmObject selectedItem; /// <summary> /// Indicates Picker is open or closed. /// </summary> private bool isPickerOpen; /// <summary> /// Update based on picker SelectedTime /// </summary> private TimeSpan selectedTime; /// <summary> /// Update current time field /// </summary> private string time; /// <summary> /// Update current time field /// </summary> private string meridian; /// <summary> /// Indicates column header is shown or not /// </summary> private bool showColumnHeader = true; /// <summary> /// Indicates header is shown or not /// </summary> private bool showHeader = true; /// <summary> /// TimeFormat collection field /// </summary> private ObservableCollection<TimeFormat> timeFormatcollections; /// <summary> /// Update header text /// </summary> private string headerText = "Time Picker"; /// <summary> /// Selected Time Fomrat /// </summary> private TimeFormat selectedTimeFomrat; #endregion #region Properties /// <summary> /// Gets or sets a value to show the column header /// </summary> public bool ShowColumnHeader { get { return showColumnHeader; } set { showColumnHeader = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the SelectedTimeFomrat /// </summary> public TimeFormat SelectedTimeFomrat { get { return selectedTimeFomrat; } set { selectedTimeFomrat = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets a value to show the header /// </summary> public bool ShowHeader { get { return showHeader; } set { showHeader = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the header text /// </summary> public string HeaderText { get { return headerText; } set { headerText = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the time format collection /// </summary> public ObservableCollection<TimeFormat> TimeFormatcollections { get { return timeFormatcollections; } set { timeFormatcollections = value; this.NotifyPropertyChanged(); } } /// <summary> /// Collection of Alarm object to listview itemsource /// </summary> public ObservableCollection<TimePickerAlarmObject> Alarms { get { return alarms; } set { alarms = value; this.NotifyPropertyChanged(); } } /// <summary> /// Selected item of listview /// </summary> public TimePickerAlarmObject SelectedItem { get { return selectedItem; } set { selectedItem = value; if(value !=null) { this.SelectedTime = value.TimeValue; this.IsPickerOpen = true; } this.NotifyPropertyChanged(); } } /// <summary> /// Update based on TimePicker SelectedTime /// </summary> public TimeSpan SelectedTime { get { return selectedTime; } set { selectedTime = value; this.NotifyPropertyChanged(); } } /// <summary> /// To indicate picker is open or closed /// </summary> public bool IsPickerOpen { get { return isPickerOpen; } set { isPickerOpen = value; if (!value) this.SelectedItem = null; this.NotifyPropertyChanged(); } } /// <summary> /// To update the current time /// </summary> public string Time { get { return time; } set { time = value; this.NotifyPropertyChanged(); } } /// <summary> /// To get set the Meridian /// </summary> public string Meridian { get { return meridian; } set { meridian = value; this.NotifyPropertyChanged(); } } #endregion #region Command /// <summary> /// Add commamd field /// </summary> private ICommand addCommand; /// <summary> /// Gets or sets the value of the command. /// </summary> public ICommand AddCommand { get { return addCommand; } set { addCommand = value; } } /// <summary> /// Ok commamd field /// </summary> private ICommand okCommand; /// <summary> /// Indicates whether the Add button is clicked or not /// </summary> private bool isAddClicked; /// <summary> /// Gets or sets the value of the command. /// </summary> public ICommand OkCommand { get { return okCommand; } set { okCommand = value; } } /// <summary> /// Cancel commamd field /// </summary> private ICommand cancelCommand; /// <summary> /// Gets or sets the value of the command. /// </summary> public ICommand CancelCommand { get { return cancelCommand; } set { cancelCommand = value; } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="TimePickerAlarmObjectViewModel"/> class. /// </summary> public TimePickerAlarmObjectViewModel() { this.GetDefaultAlarms(); this.AddCommand = new Command(AddNewAlarmItem); this.OkCommand = new Command(AddOkCommand); this.CancelCommand = new Command(AddCancelCommand); this.SetCurrentTime(); } #endregion #region NotifyPropertyChanged /// <summary> /// Property changed event handler. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Notify when the property is changed /// </summary> /// <param name="propertyName"></param> private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Methods /// <summary> /// Set collection of TimePickerAlarmObject for listview /// </summary> public void GetDefaultAlarms() { this.Alarms.Add(new TimePickerAlarmObject() { IsOn = false, TimeValue = new TimeSpan(3, 15, 00) }); this.Alarms.Add(new TimePickerAlarmObject() { IsOn = true, TimeValue = new TimeSpan(3, 45, 00) }); this.Alarms.Add(new TimePickerAlarmObject() { IsOn = false, TimeValue = new TimeSpan(4, 10, 00) }); this.Alarms.Add(new TimePickerAlarmObject() { IsOn = true, TimeValue = new TimeSpan(4, 30, 00) }); this.Alarms.Add(new TimePickerAlarmObject() { IsOn = false, TimeValue = new TimeSpan(6, 15, 00) }); this.TimeFormatcollections = new ObservableCollection<TimeFormat>() { TimeFormat.HH_mm, TimeFormat.HH_mm_ss, TimeFormat.hh_mm_ss_tt, TimeFormat.hh_mm_tt, TimeFormat.H_mm, TimeFormat.H_mm_ss, TimeFormat.h_mm_ss_tt, TimeFormat.h_mm_tt }; this.SelectedTimeFomrat = this.TimeFormatcollections[1]; } /// <summary> /// Add new Alarm item when selecting Add icon. /// </summary> public void AddNewAlarmItem() { this.SelectedTime = new TimeSpan(DateTime.Now.Hour, DateTime.Now.Minute, 0); this.IsPickerOpen = true; isAddClicked = true; } /// <summary> /// Add ok command method. /// </summary> public void AddOkCommand() { if(SelectedItem!=null) SelectedItem.IsOn = true; if (this.SelectedItem != null && this.SelectedTime != null) { this.SelectedItem.TimeValue = this.SelectedTime; } if (isAddClicked) { this.SetAlarmValue(); isAddClicked = false; } } /// <summary> /// Add cancel command method. /// </summary> public void AddCancelCommand() { isAddClicked = false; } /// <summary> /// Add new items when ok button clicked. /// </summary> public void SetAlarmValue() { this.Alarms.Add(new TimePickerAlarmObject() { TimeValue = this.SelectedTime, IsOn = true}); } /// <summary> /// Update current time /// </summary> public async void SetCurrentTime() { while (true) { await Task.Delay(200); this.Time = DateTime.Now.ToString("h:mm").ToUpper(); this.Meridian = DateTime.Now.ToString("tt").ToUpper(); } } #endregion } #endregion #region TimePickerTimeSpanToTextConverter class public class TimePickerTimeSpanToTextConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string format; string hourValue = (value).ToString().Substring(0,2); string minuteValue = (value).ToString().Substring(3, 2); string formatedText = (value).ToString().Remove(5); int val = int.Parse(hourValue); if (val >= 12) { if (val > 12) hourValue = (int.Parse(hourValue) - 12).ToString(); format = hourValue + ":" + minuteValue + " PM"; } else { format = formatedText.ToString() + " AM"; } return format; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } #endregion #region TimePickerBoolToColor class public class TimePickerBoolToColor : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return Color.Accent; else return Color.Gray; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } #endregion #region TimePickerBoolToText class public class TimePickerBoolToText : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return "Off"; TimeSpan diffTimeSpan = (TimeSpan)value; return this.GetTimeString(diffTimeSpan.Hours, diffTimeSpan.Minutes, diffTimeSpan.Seconds); } public string GetTimeString(int hour, int minute, int second) { if (hour < 0) hour = -hour; if (minute < 0) minute = -minute; if (second < 0) second = -second; string textValue = "Alarm in "; if (hour <= 0) { if (minute > 1) { textValue += minute.ToString() + " Minutes"; } else if (minute == 1) { textValue += "1 Minute"; } if (second > 1) { textValue += second.ToString() + " Seconds"; } else { textValue += second.ToString() + " Second"; } } else { if (hour == 1) { textValue += "1 Hour "; } else { textValue += hour.ToString() + " Hours "; } if(minute>1) { textValue += minute.ToString() + " Minutes"; } else { textValue += minute.ToString() + " Minute"; } } return textValue; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } #endregion } <file_sep>/iOS/SampleBrowser/Samples/PopupLayout/Popup Customizations/Model And ViewModel/TicketBookingInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; namespace SampleBrowser { public class TicketBookingInfo { public string MovieName { get; set; } public string Cast { get; set; } public UIImage MovieImage { get; set; } public UIImage InfoImage { get; set; } public string Timing1 { get; set; } public string Timing2 { get; set; } public string TheaterName { get; set; } public string TheaterLocation { get; set; } } } <file_sep>/iOS/SampleBrowser/Samples/Schedule/ScheduleLocale/ScheduleLocalViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; namespace SampleBrowser { internal class ScheduleLocalViewModel { internal ScheduleLocalViewModel() { } internal List<string> EnglishCollection { get; set; } internal void SetEnglishCollectionSubjects() { EnglishCollection = new List<string>(); EnglishCollection.Add("GoToMeeting"); EnglishCollection.Add("Business Meeting"); EnglishCollection.Add("Conference"); EnglishCollection.Add("Project Status Discussion"); EnglishCollection.Add("Auditing"); EnglishCollection.Add("Client Meeting"); EnglishCollection.Add("Generate Report"); EnglishCollection.Add("Target Meeting"); EnglishCollection.Add("General Meeting"); EnglishCollection.Add("Pay House Rent"); EnglishCollection.Add("Car Service"); EnglishCollection.Add("Medical Check Up"); EnglishCollection.Add("Wedding Anniversary"); EnglishCollection.Add("Sam's Birthday"); EnglishCollection.Add("Jenny's Birthday"); EnglishCollection.Add("Master Checkup"); EnglishCollection.Add("Hospital"); EnglishCollection.Add("Phone Bill Payment"); EnglishCollection.Add("Project Plan"); EnglishCollection.Add("Auditing"); EnglishCollection.Add("Client Meeting"); EnglishCollection.Add("Generate Report"); EnglishCollection.Add("Target Meeting"); EnglishCollection.Add("General Meeting"); EnglishCollection.Add("Play Golf"); EnglishCollection.Add("Car Service"); EnglishCollection.Add("Medical Check Up"); EnglishCollection.Add("Mary's Birthday"); EnglishCollection.Add("John's Birthday"); EnglishCollection.Add("Micheal's Birthday"); } internal List<string> FrenchCollection { get; set; } internal void SetFrenchCollectionSubjects() { FrenchCollection = new List<string>(); FrenchCollection.Add("aller ‡ la rÈunion"); FrenchCollection.Add("Un rendez-vous d'affaire"); FrenchCollection.Add("ConfÈrence"); FrenchCollection.Add("Discussion Projet de Statut"); FrenchCollection.Add("audit"); FrenchCollection.Add("RÈunion du client"); FrenchCollection.Add("gÈnÈrer un rapport"); FrenchCollection.Add("RÈunion cible"); FrenchCollection.Add("AssemblÈe gÈnÈrale"); FrenchCollection.Add("<NAME>"); FrenchCollection.Add("Service automobile"); FrenchCollection.Add("Visite mÈdicale"); FrenchCollection.Add("Anniversaire de mariage"); FrenchCollection.Add("Anniversaire de Sam"); FrenchCollection.Add("Anniversaire de Jenny"); FrenchCollection.Add("Checkup Master"); FrenchCollection.Add("HÙpital"); FrenchCollection.Add("TÈlÈphone paiement de factures"); FrenchCollection.Add("Plan de projet"); FrenchCollection.Add("audit"); FrenchCollection.Add("RÈunion du client"); FrenchCollection.Add("gÈnÈrer un rapport"); FrenchCollection.Add("RÈunion cible"); FrenchCollection.Add("AssemblÈe gÈnÈrale"); FrenchCollection.Add("<NAME>"); FrenchCollection.Add("Service automobile"); FrenchCollection.Add("Visite mÈdicale"); FrenchCollection.Add("Anniversaire de Marie"); FrenchCollection.Add("Anniversaire de John"); FrenchCollection.Add("Anniversaire de Micheal"); } internal List<string> SpanishCollection { get; set; } internal void SetSpanishCollectionSubjects() { SpanishCollection = new List<string>(); SpanishCollection.Add("Ir a la reuniÛn"); SpanishCollection.Add("ReuniÛn de negocios"); SpanishCollection.Add("Conferencia"); SpanishCollection.Add("SituaciÛn del proyecto DiscusiÛn"); SpanishCollection.Add("AuditorÌa"); SpanishCollection.Add("ReuniÛn Cliente"); SpanishCollection.Add("Generar informe"); SpanishCollection.Add("ReuniÛn Target"); SpanishCollection.Add("ReuniÛn general"); SpanishCollection.Add("Pago Casa Alquilar"); SpanishCollection.Add("Servicio de auto"); SpanishCollection.Add("RevisiÛn mÈdica"); SpanishCollection.Add("Aniversario de bodas"); SpanishCollection.Add("CumpleaÒos de Sam"); SpanishCollection.Add("El cumpleaÒos de Jenny"); SpanishCollection.Add("Chequeo Maestro"); SpanishCollection.Add("el Hospital"); SpanishCollection.Add("TelÈfono pago de facturas"); SpanishCollection.Add("Plan de proyecto"); SpanishCollection.Add("AuditorÌa"); SpanishCollection.Add("ReuniÛn Cliente"); SpanishCollection.Add("Generar informe"); SpanishCollection.Add("ReuniÛn Target"); SpanishCollection.Add("ReuniÛn general"); SpanishCollection.Add("Jugar golf"); SpanishCollection.Add("Servicio de auto"); SpanishCollection.Add("RevisiÛn mÈdica"); SpanishCollection.Add("CumpleaÒos de MarÌa"); SpanishCollection.Add("<NAME>Òos"); SpanishCollection.Add("El cumpleaÒos de Micheal"); } internal List<string> ChineseCollection { get; set; } internal void SetChineseCollectionSubjects() { ChineseCollection = new List<string>(); ChineseCollection.Add("进入会议"); ChineseCollection.Add("商务会议"); ChineseCollection.Add("会议"); ChineseCollection.Add("项目状态讨论"); ChineseCollection.Add("审计"); ChineseCollection.Add("客户会议"); ChineseCollection.Add("生成报告"); ChineseCollection.Add("目标会议"); ChineseCollection.Add("大会"); ChineseCollection.Add("支付房租"); ChineseCollection.Add("汽车服务"); ChineseCollection.Add("体格检查"); ChineseCollection.Add("结婚纪念日"); ChineseCollection.Add("萨姆的生日"); ChineseCollection.Add("珍妮的生日"); ChineseCollection.Add("主诊"); ChineseCollection.Add("医院"); ChineseCollection.Add("电话缴费"); ChineseCollection.Add("项目计划"); ChineseCollection.Add("审计"); ChineseCollection.Add("客户会议"); ChineseCollection.Add("生成报告"); ChineseCollection.Add("目标会议"); ChineseCollection.Add("大会"); ChineseCollection.Add("打高尔夫球"); ChineseCollection.Add("汽车服务"); ChineseCollection.Add("体格检查"); ChineseCollection.Add("玛丽的生日"); ChineseCollection.Add("约翰的生日"); ChineseCollection.Add("迈克尔的生日"); } // adding colors collection internal List<UIColor> ColorCollection { get; set; } internal void SetColors() { ColorCollection = new List<UIColor>(); ColorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); ColorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); ColorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); ColorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); ColorCollection.Add(UIColor.FromRGB(0xF0, 0x96, 0x09)); ColorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); ColorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); ColorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); ColorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); ColorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); ColorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); ColorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); ColorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); ColorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); ColorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); } } }<file_sep>/Android/SampleBrowser/Samples/TreeView/Helper/CustomAdapter/SelectionAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.Android.TreeView; namespace SampleBrowser { public class SelectionAdapter : TreeViewAdapter { public SelectionAdapter() { } protected override void UpdateContentView(View view, TreeViewItemInfoBase itemInfo) { var textView = view as TextView; if (textView != null) { textView.Text = (itemInfo.Node.Content as Countries).Name; } } } }<file_sep>/Forms/ProgressBar/ProgressBar/Samples/Circular/CircularRangeColors.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.ProgressBar; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfProgressBar { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CircularRangeColors : SampleView { public CircularRangeColors () { InitializeComponent (); this.RangeColorProgressBar.AnimationDuration = 2000; } private void RangeColorProgressBar_ValueChanged(object sender, ProgressValueEventArgs e) { if (e.Progress.Equals(100)) { this.RangeColorProgressBar.SetProgress(0, 0, Easing.Linear); } if (e.Progress.Equals(0)) { this.RangeColorProgressBar.Progress = 100; } } } }<file_sep>/Android/SampleBrowser/Samples/RangeSlider/SeparatorView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public class SeparatorView : View { float ScreenWidth; public SeparatorView (Context context,float width) : base (context) { Initialize (width); } public SeparatorView (Context context, IAttributeSet attrs) : base (context, attrs) { //Initialize (); } public SeparatorView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) { //Initialize (); } void Initialize (float width) { ScreenWidth = width; this.LayoutParameters=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); } public Color separatorColor= Color.LightGray; protected override void OnDraw (Android.Graphics.Canvas canvas) { base.OnDraw (canvas); Paint pnt=new Paint(); pnt.Color = separatorColor; pnt.StrokeWidth = 5; canvas.DrawLine(0,0,this.ScreenWidth,0,pnt); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Spline.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class Spline : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "NC Weather Report"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis categoryaxis = new CategoryAxis(); categoryaxis.LabelPlacement = LabelPlacement.BetweenTicks; categoryaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Minimum = 0; numericalaxis.Maximum = 40; numericalaxis.Interval = 10; numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.TickSize = 0; numericalaxis.LabelStyle.LabelFormat = "##.##" + (char)0x00B0 + "C"; chart.SecondaryAxis = numericalaxis; SplineSeries splineSeries1 = new SplineSeries(); splineSeries1.ItemsSource = MainPage.GetSplineData1(); splineSeries1.XBindingPath = "XValue"; splineSeries1.YBindingPath = "YValue"; splineSeries1.Label = "Max Temp"; splineSeries1.DataMarker.ShowMarker = true; splineSeries1.DataMarker.MarkerWidth = 10; splineSeries1.DataMarker.MarkerHeight = 10; splineSeries1.DataMarker.MarkerColor = Color.White; splineSeries1.DataMarker.MarkerStrokeColor = Color.ParseColor("#00bdae"); splineSeries1.DataMarker.MarkerStrokeWidth = 2; splineSeries1.LegendIcon = ChartLegendIcon.SeriesType; splineSeries1.TooltipEnabled = true; splineSeries1.StrokeWidth = 3; SplineSeries splineSeries2 = new SplineSeries(); splineSeries2.ItemsSource = MainPage.GetSplineData2(); splineSeries2.XBindingPath = "XValue"; splineSeries2.YBindingPath = "YValue"; splineSeries2.Label = "Avg Temp"; splineSeries2.DataMarker.ShowMarker = true; splineSeries2.DataMarker.MarkerWidth = 10; splineSeries2.DataMarker.MarkerHeight = 10; splineSeries2.DataMarker.MarkerColor = Color.White; splineSeries2.DataMarker.MarkerStrokeColor = Color.ParseColor("#404041"); splineSeries2.DataMarker.MarkerStrokeWidth = 2; splineSeries2.LegendIcon = ChartLegendIcon.SeriesType; splineSeries2.TooltipEnabled = true; splineSeries2.StrokeWidth = 3; SplineSeries splineSeries3 = new SplineSeries(); splineSeries3.ItemsSource = MainPage.GetSplineData3(); splineSeries3.XBindingPath = "XValue"; splineSeries3.YBindingPath = "YValue"; splineSeries3.Label = "Min Temp"; splineSeries3.DataMarker.ShowMarker = true; splineSeries3.DataMarker.MarkerWidth = 10; splineSeries3.DataMarker.MarkerHeight = 10; splineSeries3.DataMarker.MarkerColor = Color.White; splineSeries3.DataMarker.MarkerStrokeColor = Color.ParseColor("#357CD2"); splineSeries3.DataMarker.MarkerStrokeWidth = 2; splineSeries3.LegendIcon = ChartLegendIcon.SeriesType; splineSeries3.TooltipEnabled = true; splineSeries3.StrokeWidth = 3; splineSeries1.EnableAnimation = true; splineSeries2.EnableAnimation = true; splineSeries3.EnableAnimation = true; chart.Series.Add(splineSeries1); chart.Series.Add(splineSeries2); chart.Series.Add(splineSeries3); return chart; } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/DataMarkerCustomization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class DataMarkerCustomization : SamplePage { SfChart chart; LineSeries lineSeries1, lineSeries2; float density; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Population of India (2013 - 2016)"; chart.SetBackgroundColor(Color.White); chart.ColorModel.ColorPalette = ChartColorPalette.Natural; density = context.Resources.DisplayMetrics.Density; CategoryAxis categoryaxis = new CategoryAxis(); categoryaxis.ShowMajorGridLines = false; categoryaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; categoryaxis.PlotOffset = 30; categoryaxis.AxisLineOffset = 30; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Minimum = 900; numericalaxis.Maximum = 1300; numericalaxis.Interval = 80; numericalaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; numericalaxis.Title.Text = "Population"; chart.SecondaryAxis = numericalaxis; lineSeries1 = new LineSeries(); lineSeries1.ItemsSource = MainPage.GetDataMarkerData1(); lineSeries1.XBindingPath = "XValue"; lineSeries1.YBindingPath = "YValue"; lineSeries1.EnableAnimation = true; lineSeries1.Label = "Male"; lineSeries1.DataMarker.ShowLabel = true; lineSeries1.DataMarkerLabelCreated += LineSeries1_DataMarkerLabelCreated; lineSeries1.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Center; lineSeries1.DataMarker.LabelStyle.OffsetY = -18; lineSeries1.DataMarker.ShowMarker = true; lineSeries1.DataMarker.MarkerColor = Color.White; lineSeries1.DataMarker.MarkerHeight = 6; lineSeries1.DataMarker.MarkerWidth = 6; lineSeries1.DataMarker.MarkerStrokeWidth = 2; lineSeries1.DataMarker.MarkerStrokeColor = Color.ParseColor("#00BDAE"); chart.Series.Add(lineSeries1); lineSeries2 = new LineSeries(); lineSeries2.ItemsSource = MainPage.GetDataMarkerData2(); lineSeries2.XBindingPath = "XValue"; lineSeries2.YBindingPath = "YValue"; lineSeries2.EnableAnimation = true; lineSeries2.Label = "Female"; lineSeries2.DataMarker.ShowLabel = true; lineSeries2.DataMarkerLabelCreated += LineSeries2_DataMarkerLabelCreated; lineSeries2.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Center; lineSeries2.DataMarker.LabelStyle.OffsetY = 18; lineSeries2.DataMarker.ShowMarker = true; lineSeries2.DataMarker.MarkerColor = Color.White; lineSeries2.DataMarker.MarkerHeight = 6; lineSeries2.DataMarker.MarkerWidth = 6; lineSeries2.DataMarker.MarkerStrokeWidth = 2; lineSeries2.DataMarker.MarkerStrokeColor = Color.ParseColor("#404041"); chart.Series.Add(lineSeries2); return chart; } private void LineSeries1_DataMarkerLabelCreated(object sender, ChartSeries.DataMarkerLabelCreatedEventArgs e) { LinearLayout layout = new LinearLayout(chart.Context); layout.SetBackgroundColor(Color.ParseColor("#00BDAE")); layout.SetPadding(3, 3, 3, 3); TextView text = new TextView(chart.Context); ImageView image = new ImageView(chart.Context); image.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams((int)(20 * density), (int)(20 * density))); image.SetImageResource(Resource.Drawable.Male); text.Text = e.DataMarkerLabel.Label + "M"; text.SetTextColor(Color.White); layout.AddView(image); layout.AddView(text); e.DataMarkerLabel.View = layout; } private void LineSeries2_DataMarkerLabelCreated(object sender, ChartSeries.DataMarkerLabelCreatedEventArgs e) { LinearLayout layout = new LinearLayout(chart.Context); layout.SetBackgroundColor(Color.ParseColor("#404041")); layout.SetPadding(3, 3, 3, 3); TextView text = new TextView(chart.Context); ImageView image = new ImageView(chart.Context); image.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams((int)(20 * density), (int)(20 * density))); image.SetImageResource(Resource.Drawable.Female); text.Text = e.DataMarkerLabel.Label + "M"; text.SetTextColor(Color.White); layout.AddView(image); layout.AddView(text); e.DataMarkerLabel.View = layout; } } }<file_sep>/Android/SampleBrowser/Samples/DataSource/Helper/CustomAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.DataSource; using System.Collections.Specialized; using Android.Graphics; namespace SampleBrowser { public class CustomAdapter : BaseAdapter<object> { private DataSource dataSource; private Context context; public CustomAdapter(DataSource dataSource, Context cntxt) : base() { this.dataSource = dataSource; this.dataSource.SourcePropertyChanged += DataSource_RecordPropertyChanged; this.dataSource.SourceCollectionChanged += DataSource_SourceCollectionChanged; this.dataSource.FilterChanged += DataSource_FilterChanged; context = cntxt; } private void DataSource_FilterChanged(object sender, NotifyCollectionChangedEventArgs e) { this.NotifyDataSetChanged(); } private void DataSource_SourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { this.NotifyDataSetChanged(); } private void DataSource_RecordPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { this.NotifyDataSetChanged(); } public override int Count { get { return dataSource.DisplayItems.Count; } } public override long GetItemId(int position) { return position; } public override object this[int index] { get { return this.dataSource.DisplayItems[index]; } } public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; // re-use an existing view, if one is available // otherwise create a new one if (this[position] is BookDetails) { if (view == null) { view = new GettingStartedTemplate(this.context); } view.SetBackgroundColor(Color.Transparent); (view as GettingStartedTemplate).UpdateValue(this[position]); } return view; } protected override void Dispose(bool disposing) { base.Dispose(disposing); this.dataSource.Dispose(); this.dataSource = null; } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/LiveUpdate.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Drawing; using System.Threading; using System.Threading.Tasks; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class LiveUpdate : SampleView { SFChart chart; SFFastLineSeries series; SFFastLineSeries series1; ChartViewModel dataModel; bool isDisappeared = false; public LiveUpdate() { chart = new SFChart(); SFNumericalAxis primaryAxis = new SFNumericalAxis(); primaryAxis.ShowMajorGridLines = false; chart.PrimaryAxis = primaryAxis; SFNumericalAxis secondaryAxis = new SFNumericalAxis(); secondaryAxis.ShowMajorGridLines = false; secondaryAxis.Minimum = NSObject.FromObject(-1.5); secondaryAxis.Maximum = NSObject.FromObject(1.5); secondaryAxis.Interval = NSObject.FromObject(0.5); chart.SecondaryAxis = secondaryAxis; dataModel = new ChartViewModel(); series = new SFFastLineSeries(); series.ItemsSource = dataModel.liveData1; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; chart.Series.Add(series); series1 = new SFFastLineSeries(); series1.ItemsSource = dataModel.liveData2; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; chart.Series.Add(series1); chart.ColorModel.Palette = SFChartColorPalette.Natural; this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } async void UpdateData() { await Task.Delay(10); if (!isDisappeared) { (chart.Series[0].ItemsSource as ObservableCollection<ChartDataModel>).RemoveAt(0); (chart.Series[0].ItemsSource as ObservableCollection<ChartDataModel>).Add(new ChartDataModel(dataModel.wave1, Math.Sin(dataModel.wave1 * (Math.PI / 180.0)))); dataModel.wave1++; (chart.Series[1].ItemsSource as ObservableCollection<ChartDataModel>).RemoveAt(0); (chart.Series[1].ItemsSource as ObservableCollection<ChartDataModel>).Add(new ChartDataModel(dataModel.wave1, Math.Sin(dataModel.wave2 * (Math.PI / 180.0)))); dataModel.wave2++; UpdateData(); } } protected override void Dispose(bool disposing) { isDisappeared = disposing; base.Dispose(disposing); } public override void ViewWillAppear() { isDisappeared = false; UpdateData(); base.ViewWillAppear(); } public override void ViewWillDisappear() { isDisappeared = true; base.ViewWillDisappear(); } } }<file_sep>/Forms/DataGrid/README.md The data grid control for Xamarin is a high-performance grid component that helps display and manipulate large amounts of data in a tabular format. Its rich feature set includes functionalities like data-binding, sorting, grouping, editing, filtering, swiping, dragging, resizing, loading more items, pull-to-refresh, and exporting to Excel and PDF file formats. The following samples are available for data grid to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Getting Started](DataGrid/Samples/GridGettingStarted) | This sample showcases a simple DataGrid with ObservableCollection as the data source. | | [Sorting](DataGrid/Samples/Sorting) | This sample showcases the sorting capabilities of data in DataGrid that allows you to sort against one or more columns and also provides tri-state sorting functionality. | | [Custom Sorting](DataGrid/Samples/CustomSorting) | This sample showcases the custom sorting capabilities in DataGrid that enables you to implement custom sorting logic when conventional sorting techniques does not meet the requirement. | | [Filtering](DataGrid/Samples/Filtering) | This sample showcases the filtering capabilities of data in DataGrid. | | [Frozen Row](DataGrid/Samples/FrozenRow) | This sample showcases the freeze panes capability of DataGrid which provides support to freeze rows at the top of the view. | | [Cell Template](DataGrid/Samples/CellTemplate) | This sample showcases the template column feature of DataGrid which provides support for loading templates to the column. | | [Grouping](DataGrid/Samples/Grouping) | This sample showcases the grouping capabilities of data in DataGrid that allows you to group by one or more columns with option to expand/collapse the groups. | | [Custom Grouping](DataGrid/Samples/Custom Grouping) | This sample showcases the custom grouping capabilities in DataGrid that enables you to implement custom grouping logic when conventional techniques does not meet the requirement. | | [Selection](DataGrid/Samples/Selection) | This sample showcases the selection capability of DataGrid which provides selection mode options like single, multiple, single-deselect and none. | | [Editing](DataGrid/Samples/Editing) | This sample showcases the editing capabilities of DataGrid which provides support to edit GridTextColumn, GridNumericColumn, GridPickerColumn and GridDateTimeColumn. | | [Resizing](DataGrid/Samples/Resizing) | This sample showcases the resizing capabilities of DataGrid which provides resizing mode options like on-moved and on-touch-up. | | [Grid Columns](DataGrid/Samples/GridColumns) | This sample showcases the different types of columns available in the DataGrid that provides support for rendering text, image and switch in the column cells. | | [Drag And Drop](DataGrid/Samples/DragAndDrop) | This sample showcases the column and row drag and drop capabilities of DataGrid which provide user flexibility when interacting with the grid rows and grid columns. | | [Context Menu](DataGrid/Samples/ContextMenu) | This sample showcases the context menu behavior for the DataGrid using our popup layout control which provides options to group and sort a column and to clear sorting and grouping. | | [Unbound Column](DataGrid/Samples/UnBoundColumn) | This sample showcases the unbound column capability of DataGrid. Unbound columns are extra columns that do not belong to the data source. | | [Conditional Styling](DataGrid/Samples/ConditionalFormatting) | This sample showcases the conditional styling capabilities of the DataGrid based on which individual cells and rows in the grid can be styles based on conditions. | | [Styles](DataGrid/Samples/Styles) | This sample showcases the styling capabilities of DataGrid. Styling allows you to change the visual appearance of the DataGrid and its inner elements. | | [Auto Row Height](DataGrid/Samples/AutoRowHeight) | This sample showcases the auto row height feature of DataGrid which renders grid rows based on its content to improve the readability and occurs on-demand basis. | | [Diagonal Scrolling](DataGrid/Samples/DiagonalScrolling) | This sample showcases the diagonal scrolling feature of DataGrid which enables to scroll the grid diagonally in all directions. | | [Load More](DataGrid/Samples/LoadMore) | This sample showcases the load more capability of DataGrid that allows you to load a subset of data to the bound data source using built-in UI. | | [Pull To Refresh](DataGrid/Samples/PullToRefresh) | This sample showcases the pull-to-refresh capability of DataGrid which allows you to refresh the data source upon pull-to-refresh action. | | [Paging](DataGrid/Samples/Paging) | This sample showcases the paging capabilities of DataGrid using our DataPager control which allows you to load the data from the data source in an efficient way. | | [Swiping](DataGrid/Samples/Swiping) | This sample showcases the swiping capabilities of DataGrid which allow you to load swipe views and associate them with custom actions. | | [Rendering Dynamic Data](DataGrid/Samples/RenderingDynamicData) | This sample illustrates the real time updates capabilibilies of the DataGrid by frequent updates that occur in random cells across the grid by keeping processor usage to a minimum. | | [Exporting](DataGrid/Samples/Exporting) | This sample showcases the excel and pdf exporting capabilities of DataGrid. DataGrid also provides you various customization options for exporting. |<file_sep>/iOS/SampleBrowser/Samples/Calculate/FunctionsLibrary.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using Foundation; using CoreAnimation; using Syncfusion.Calculate; namespace SampleBrowser { public partial class FunctionsLibrary : SampleView { #region Fields FunctionsLibraryView functionsLibraryView; #endregion #region Constructor public FunctionsLibrary () { functionsLibraryView = new FunctionsLibraryView(); this.AddSubview (functionsLibraryView); } #endregion #region Methods public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } protected override void Dispose (bool disposing) { functionsLibraryView.Dispose (); base.Dispose (disposing); } #endregion } public class CalcData : ICalcData { public event ValueChangedEventHandler ValueChanged; public CalcData() { } Dictionary<string, object> values = new Dictionary<string, object>(); public object GetValueRowCol(int row, int col) { object value = null; var key = RangeInfo.GetAlphaLabel(col) + row; this.values.TryGetValue(key, out value); return value; } public void SetValueRowCol(object value, int row, int col) { var key = RangeInfo.GetAlphaLabel(col) + row; if (!values.ContainsKey(key)) values.Add(key, value); else if (values.ContainsKey(key) && values[key] != value) values[key] = value; } public void WireParentObject() { } private void OnValueChanged(int row, int col, string value) { if (ValueChanged != null) ValueChanged(this, new ValueChangedEventArgs(row, col, value)); } } } <file_sep>/Android/SampleBrowser/Samples/PDFViewer/BookmarkToolbar.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.Graphics.Drawables; using Android.Graphics.Drawables.Shapes; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Syncfusion.Pdf.Interactive; using Syncfusion.Pdf.Parsing; namespace SampleBrowser { internal class BookmarkToolbar : LinearLayout { private Button backToViewerButton; LinearLayout bookmarkLayout; internal ListView bookmarkView; internal LinearLayout bookmarkTitle; internal CustomToolBarPdfViewerDemo sampleView; internal BookmarkListAdapter listAdapter; internal PdfLoadedDocument bookmarkLoadedDocument; internal Typeface bookmarkFont; Button bookmarkCloseButton; internal BookmarkToolbar(Context context, CustomToolBarPdfViewerDemo sampleView) :base(context) { this.sampleView = sampleView; bookmarkFont = sampleView.bookmarkFont; var inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService); bookmarkLayout = (LinearLayout)inflater.Inflate(Resources.GetLayout(Resource.Layout.bookmarkAndroidToolbar), this, true); backToViewerButton = bookmarkLayout.FindViewById<Button>(Resource.Id.backToViewerButton); bookmarkCloseButton = bookmarkLayout.FindViewById<Button>(Resource.Id.bookmarkCloseButton); bookmarkTitle = bookmarkLayout.FindViewById<LinearLayout>(Resource.Id.bookmarkTitleBar); if (sampleView.IsDeviceTablet) { bookmarkTitle.LayoutParameters.Height = (int)(47 * Resources.DisplayMetrics.Density); backToViewerButton.Visibility = ViewStates.Invisible; bookmarkCloseButton.Click += M_bookmarkCloseButton_Click; bookmarkCloseButton.Typeface = sampleView.font; } else { bookmarkCloseButton.Visibility = ViewStates.Invisible; bookmarkTitle.LayoutParameters.Height = (int)(60 * Resources.DisplayMetrics.Density); backToViewerButton.Click += BackToViewerButton_Click; backToViewerButton.Typeface = sampleView.bookmarkFont; } bookmarkView = bookmarkLayout.FindViewById<ListView>(Resource.Id.bookmarkListView); listAdapter = new BookmarkListAdapter(context,this, Resources.DisplayMetrics.Density); bookmarkView.Adapter = listAdapter; SetBackgroundColor(Color.White); } private void M_bookmarkCloseButton_Click(object sender, EventArgs e) { sampleView.CollapseBookmarkToolbar(); } internal void ClearBookmark() { listAdapter.bookmarkList.Clear(); } internal void PopulateInitialBookmarkList() { listAdapter.bookmarkList.Clear(); PdfBookmarkBase bookmarkBase = bookmarkLoadedDocument.Bookmarks; for (int i = 0; i < bookmarkBase.Count; i++) listAdapter.bookmarkList.Add(new CustomBookmark(bookmarkBase[i], false)); listAdapter.NotifyDataSetChanged(); } private void BackToViewerButton_Click(object sender, EventArgs e) { if(!sampleView.IsDeviceTablet) sampleView.CollapseBookmarkToolbar(); } } internal class BookmarkListAdapter : BaseAdapter<CustomBookmark>, View.IOnClickListener { internal List<CustomBookmark> bookmarkList; Activity context; Typeface bookmarkFont; BookmarkToolbar bookmarkToolbar; float density; List<PdfBookmark> navigationQueue = new List<PdfBookmark>(); internal BookmarkListAdapter(Context context, BookmarkToolbar bookmarkToolbar, float density) { this.bookmarkToolbar = bookmarkToolbar; this.context = context as Activity; this.density = density; bookmarkList = new List<CustomBookmark>(); bookmarkFont = bookmarkToolbar.bookmarkFont; } public override CustomBookmark this[int position] { get { return bookmarkList[position]; } } public override int Count { get { return bookmarkList.Count; } } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { CustomBookmark item = bookmarkList[position]; View view = convertView; if (view == null) view = context.LayoutInflater.Inflate(Resource.Layout.bookmarkListViewRow, null); view.SetOnClickListener(this); view.Tag = item; TextView textView = view.FindViewById<TextView>(Resource.Id.bookmarkTitle); textView.Text= item.Bookmark.Title; textView.SetWidth((int)(bookmarkToolbar.Width - 94 * density)); CustomButton expandButton = view.FindViewById<CustomButton>(Resource.Id.expandBookmarkButton); expandButton.Click += ExpandButton_Click; expandButton.Typeface = bookmarkFont; if (!item.IsExpandButtonVisible) expandButton.Visibility = ViewStates.Invisible; else expandButton.Visibility = ViewStates.Visible; expandButton.Bookmark = item.Bookmark; CustomButton backButton = view.FindViewById<CustomButton>(Resource.Id.backToParentBookmarkButton); backButton.Click += BackButton_Click; backButton.Typeface = bookmarkFont; if (!item.IsBackToParentButtonVisible) backButton.Visibility = ViewStates.Invisible; else backButton.Visibility = ViewStates.Visible; backButton.Bookmark = item.Bookmark; return view; } public void OnClick(View v) { PdfBookmark bookmark = ((CustomBookmark)v.Tag).Bookmark; bookmarkToolbar.sampleView.pdfViewerControl.GoToBookmark(bookmark); if (!bookmarkToolbar.sampleView.IsDeviceTablet) bookmarkToolbar.sampleView.CollapseBookmarkToolbar(); } private void BackButton_Click(object sender, EventArgs e) { bookmarkList.Clear(); if (navigationQueue.Count < 2) { for (int i = 0; i < bookmarkToolbar.bookmarkLoadedDocument.Bookmarks.Count; i++) bookmarkList.Add(new CustomBookmark(bookmarkToolbar.bookmarkLoadedDocument.Bookmarks[i], false)); NotifyDataSetChanged(); if (navigationQueue.Count != 0) navigationQueue.RemoveAt(navigationQueue.Count - 1); } else { PdfBookmark parentBookmark = navigationQueue[navigationQueue.Count - 2]; navigationQueue.RemoveAt(navigationQueue.Count - 2); UpdateBookmarkList(parentBookmark); } } internal void UpdateBookmarkList(PdfBookmark bookmark) { bookmarkList.Clear(); bookmarkList.Add(new CustomBookmark(bookmark, true)); for (int i = 0; i < bookmark.Count; i++) bookmarkList.Add(new CustomBookmark(bookmark[i], false)); NotifyDataSetChanged(); } private void ExpandButton_Click(object sender, EventArgs e) { PdfBookmark bookmark = (sender as CustomButton).Bookmark; navigationQueue.Add(bookmark); UpdateBookmarkList(bookmark); } } internal class CustomButton : Button { internal PdfBookmark Bookmark; public CustomButton(Context context, IAttributeSet attributeSet):base(context, attributeSet) { } } internal class CustomBookmark : Java.Lang.Object { public PdfBookmark Bookmark { get; set; } internal CustomBookmark(PdfBookmark bookmark, bool isBackToParentButtonVisible) { Bookmark = bookmark; IsBackToParentButtonVisible = isBackToParentButtonVisible; } public bool IsExpandButtonVisible { get { return Bookmark.Count != 0 && !IsBackToParentButtonVisible; } } public bool IsBackToParentButtonVisible { get; set; } } }<file_sep>/Forms/Chart/Chart/Samples/StackedColumn100Chart/StackedColumn100SeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class StackedColumn100SeriesViewModel { public ObservableCollection<ChartDataModel> StackedColumnData1 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData2 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData3 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData4 { get; set; } public StackedColumn100SeriesViewModel() { StackedColumnData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 900), new ChartDataModel("2007", 544), new ChartDataModel("2008", 880), new ChartDataModel("2009", 675) }; StackedColumnData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 190), new ChartDataModel("2007", 226), new ChartDataModel("2008", 194), new ChartDataModel("2009", 250) }; StackedColumnData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 250), new ChartDataModel("2007", 145), new ChartDataModel("2008", 190), new ChartDataModel("2009", 220) }; StackedColumnData4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 150), new ChartDataModel("2007", 120), new ChartDataModel("2008", 115), new ChartDataModel("2009", 125) }; } } }<file_sep>/iOS/SampleBrowser/Samples/TreeView/Helpers/TreeViewPickerModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; namespace SampleBrowser { public class TreeViewPickerModel : UIPickerViewModel { private readonly IList<string> values; public event EventHandler<TreeViewPickerChangedEventArgs> PickerChanged; public TreeViewPickerModel(IList<string> values) { this.values = values; } public override nint GetComponentCount(UIPickerView picker) { return 1; } public override nint GetRowsInComponent(UIPickerView picker, nint component) { return values.Count; } public override string GetTitle(UIPickerView picker, nint row, nint component) { return values[(int)row]; } public override nfloat GetRowHeight(UIPickerView picker, nint component) { return 30f; } public override void Selected(UIPickerView picker, nint row, nint component) { if (this.PickerChanged != null) { this.PickerChanged(this, new TreeViewPickerChangedEventArgs { SelectedValue = values[(int)row] }); } } } public class TreeViewPickerChangedEventArgs : EventArgs { public string SelectedValue { get; set; } } }<file_sep>/Forms/PopupLayout/README.md The pop-up control layout lets you display an alert message with options to customize and load any desired view inside the control. The following samples are available for pop-up to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Popup Getting Started](PopupLayout/Samples/PopupGettingStarted) | This sample showcases the default rendering of popup layout with relative positioning, center postioning and rendering at touch point of screen with options to customize the built-in layout and animation types. | | [OnBoard Helps](PopupLayout/Samples/OnBoardHelps) | This sample show case the usage of popup layout as on-board help views with different customized animations. | | [Details View](PopupLayout/Samples/DetailsView)| This sample showcases the usage of popup layout in the contact list for displaying available options relatively below the tapped user data. | | [Popup Customizations](PopupLayout/Samples/PopupCustomizations)| This sample showcases the various layouts of the popup layout with built-in animatation that comes in handy in a sleek ticket booking app. |<file_sep>/Forms/TextInputLayout/TextInputLayout/Samples/SignUpView/FontSizeConverter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XForms.TextInputLayout; using System.Collections.Generic; using System.Globalization; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfTextInputLayout { /// <summary> /// Converter to convert the font size by decreasing the actual size to 75 percentage. /// </summary> public class FontSizeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { double fontSize = 0f; if (value == null) return null; if (double.TryParse(value.ToString(), out fontSize)) { fontSize = fontSize * 0.75; } return fontSize; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } } <file_sep>/Forms/PDF/PDF/Samples/ZugFerd/InvoiceType.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Syncfusion.ZugFerd { /// <summary> /// Invoice Type /// </summary> public enum InvoiceType { Unknown = 0, Invoice = 380, Correction = 1380, CreditNote = 381, DebitNote = 383, SelfBilledInvoice = 389 } } <file_sep>/Forms/Cards/Cards/Samples/CardLayout/CardLayoutViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Text; using Xamarin.Forms; namespace SampleBrowser.Cards { public class CardLayoutViewModel { internal ObservableCollection<CardData> Data = new ObservableCollection<CardData>(); public CardLayoutViewModel() { this.AddData(); } private void AddData() { Data.Add(new CardData { Name = "<NAME>ather Sofa", Price = 99.50, Rating = "4.9", Offer = "5% Offer", ImagePath = "BlackSofa.jpg" , Description = "Warranty covers up to 5 years. This frame’s special feature is its bookcase headboard." }); Data.Add(new CardData { Name = "Wooden Standing Drawer", Price = 199.50, Rating = "3.9", Offer = "50% Offer", ImagePath = "TVShelf.jpg", Description = "\"This versatile wardrobe strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves." }); Data.Add(new CardData { Name = "Semi-Cotton <NAME>", Price = 299.50, Rating = "2.9", Offer = "25% Offer", ImagePath = "GraySofa.jpg", Description = "This sofa’s frame is made of engineered wood, which is stable and climate-resistant. Protected with a scratch-resistant finish." }); Data.Add(new CardData { Name = "Dining Chair", Price = 399.50, Rating = "4.9", Offer = "15% Offer", ImagePath = "DiningTable.jpg", Description = "Made of plywood to reduce weight and costs, these end tables still look like solid cherry." }); Data.Add(new CardData { Name = "<NAME>", Price = 99.50, Rating = "3.9", Offer = "35% Offer", ImagePath = "AngleSofa.jpg", Description = "Lightweight but sturdy, this nightstand is made of particleboard with a maple veneer or painted white." }); } } } <file_sep>/Forms/XlsIO/XlsIO.iOS/AppDelegate.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="AppDelegate.cs" company=" Syncfusion Inc."> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> #endregion namespace SampleBrowser.XlsIO.IOS { using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; /// <summary> /// The UIApplicationDelegate for the application. This class is responsible for launching the User /// Interface of the application, as well as listening (and optionally responding) to application /// events from iOS. /// </summary> [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { /// <summary> /// This method is invoked when the application has loaded and is ready to run. In this method /// you should instantiate the window, load the UI into it and then make the window visible. /// You have 17 seconds to return from this method, or iOS will terminate your application. /// </summary> /// <param name="app">parameter of UIApplication</param> /// <param name="options">parameter of NSDictionary</param> /// <returns>Return the boolean value.</returns> public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); Syncfusion.SfDataGrid.XForms.iOS.SfDataGridRenderer.Init(); Syncfusion.SfNumericTextBox.XForms.iOS.SfNumericTextBoxRenderer.Init(); Syncfusion.ListView.XForms.iOS.SfListViewRenderer.Init(); Syncfusion.XForms.iOS.Buttons.SfRadioButtonRenderer.Init(); SampleBrowser.Core.iOS.CoreSampleBrowser.Init(UIScreen.MainScreen.Bounds, app.StatusBarFrame.Size.Height); this.LoadApplication(new App()); return base.FinishedLaunching(app, options); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/GradientChart.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Android.Graphics; using Com.Syncfusion.Charts; using Android.Views; namespace SampleBrowser { public class GradientChart : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Oxygen Level"; chart.SetBackgroundColor(Color.White); chart.ColorModel.ColorPalette = ChartColorPalette.Custom; ChartGradientColor gradientColor = new ChartGradientColor() { StartPoint = new PointF(0.5f, 1), EndPoint = new PointF(0.5f, 0) }; ChartGradientStop stopColor1 = new ChartGradientStop() { Color = Color.White, Offset = 0 }; ChartGradientStop stopColor2 = new ChartGradientStop() { Color = Color.ParseColor("#FF0080DF"), Offset = 1 }; gradientColor.GradientStops.Add(stopColor1); gradientColor.GradientStops.Add(stopColor2); ChartGradientColorCollection gradientColorsCollection = new ChartGradientColorCollection() { gradientColor }; chart.ColorModel.CustomGradientColors = gradientColorsCollection; DateTimeAxis primaryAxis = new DateTimeAxis(); primaryAxis.PlotOffset = 6; primaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; primaryAxis.ShowMinorGridLines = false; primaryAxis.ShowMajorGridLines = false; primaryAxis.LabelStyle.LabelFormat = "MMM dd"; chart.PrimaryAxis = primaryAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Maximum = 50; numericalAxis.Interval = 5; numericalAxis.LabelStyle.LabelFormat = "#'%'"; chart.SecondaryAxis = numericalAxis; SplineAreaSeries splineAreaSeries = new SplineAreaSeries(); splineAreaSeries.ItemsSource = MainPage.GetGradientData(); splineAreaSeries.XBindingPath = "Date"; splineAreaSeries.YBindingPath = "High"; splineAreaSeries.StrokeColor = Color.ParseColor("#FF0080DF"); splineAreaSeries.StrokeWidth = 2; splineAreaSeries.DataMarker.ShowLabel = true; splineAreaSeries.DataMarker.MarkerWidth = 8; splineAreaSeries.DataMarker.MarkerHeight = 8; splineAreaSeries.DataMarker.MarkerColor = Color.White; splineAreaSeries.DataMarker.MarkerStrokeColor = Color.ParseColor("#FF0080DF"); splineAreaSeries.DataMarker.MarkerStrokeWidth = 2; splineAreaSeries.DataMarker.ShowMarker = true; splineAreaSeries.DataMarker.LabelStyle.OffsetY = -10; splineAreaSeries.DataMarker.LabelStyle.BackgroundColor = Color.ParseColor("#FF0080DF"); splineAreaSeries.DataMarker.LabelStyle.LabelFormat = "#.#'%'"; chart.Series.Add(splineAreaSeries); return chart; } } }<file_sep>/Forms/ProgressBar/ProgressBar/Samples/Circular/CircularRadiusCustomization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfProgressBar { using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.ProgressBar; using Xamarin.Forms; public partial class CircularRadiusCustomization : SampleView { private bool isDisposed; public CircularRadiusCustomization() { InitializeComponent(); this.TrackOutsideProgressBar.AnimationDuration = 2000; this.FilledIndicatorProgressBar.AnimationDuration = 2000; this.ThinTrackStyle.AnimationDuration = 2000; this.TrackInsideProgressBar.AnimationDuration = 0; #pragma warning disable CS4014 this.SetTrackInsideProgress(); #pragma warning restore CS4014 } public void Dispose(bool disposing) { TrackOutsideProgressBar?.Dispose(disposing); FilledIndicatorProgressBar?.Dispose(disposing); TrackInsideProgressBar?.Dispose(disposing); ThinTrackStyle?.Dispose(disposing); } public override void OnDisappearing() { isDisposed = true; this.Dispose(true); } private void TrackOutsideProgressBar_ValueChanged(object sender, ProgressValueEventArgs e) { if (e.Progress.Equals(100)) { this.TrackOutsideProgressBar.SetProgress(0, 0, Easing.Linear); } if (e.Progress.Equals(0)) { this.TrackOutsideProgressBar.Progress = 100; } } private void FilledIndicatorProgressBar_ValueChanged(object sender, ProgressValueEventArgs e) { if (e.Progress.Equals(100)) { this.FilledIndicatorProgressBar.SetProgress(0, 0, Easing.Linear); } if (e.Progress.Equals(0)) { this.FilledIndicatorProgressBar.Progress = 100; } } private void ThinTrackStyle_ValueChanged(object sender, ProgressValueEventArgs e) { if (e.Progress.Equals(100)) { this.ThinTrackStyle.SetProgress(0, 0, Easing.Linear); } if (e.Progress.Equals(0)) { this.ThinTrackStyle.Progress = 100; } } private async Task SetTrackInsideProgress() { double progress = 0; while (progress < 100) { if (isDisposed) { break; } this.TrackInsideProgressBar.Progress = progress += 0.25; this.TrackInsideProgressBarProgressLabel.Text = (int)progress + "%"; await Task.Delay(50); } this.TrackInsideProgressBar.SetProgress(0, 0, Easing.Linear); if (!this.isDisposed) { await SetTrackInsideProgress(); } } } }<file_sep>/Android/SampleBrowser/Samples/SfMaskedEdit/SfMaskedEditText_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Views.InputMethods; using Android.Widget; using Syncfusion.Android.MaskedEdit; namespace SampleBrowser { class SfMaskedEditText_Tab { SfMaskedEdit sfToAccount, sfDesc, amountMask, emailMask, phoneMask; TextView erroToAccount, errotextAmount, errotextEmail, errotextPhone; Context context; LinearLayout propertylayout ,linear; AlertDialog.Builder resultsDialog; FrameLayout propertyFrameLayout, buttomButtonLayout, frame; int totalWidth; Button propertyButton; TextView closeLabel; SfMaskedEditProperties maskProperties; InputValidationMode validationMask= InputValidationMode.KeyPress; CultureInfo currentCulute = new CultureInfo("en-us"); /// <summary> /// Contain the close button visibility details /// </summary> ClearButtonVisibilityMode clearButtonVisibility; bool hidePrompt; char currentPrompt='_'; double actionBarHeight, navigationBarHeight, totalHeight; LinearLayout proprtyOptionsLayout; ScrollView propPageScrollView ,mainPageScrollView; public SfMaskedEditText_Tab() { maskProperties = new SfMaskedEditProperties(this); } #region Properties internal LinearLayout ProprtyOptionsLayout { get { return proprtyOptionsLayout; } set { proprtyOptionsLayout = value; } } internal InputValidationMode ValidationMask { get { return validationMask; } set { validationMask = value; } } internal char CurrentPrompt { get { return currentPrompt; } set { currentPrompt = value; } } internal CultureInfo CurrentCulture { get { return currentCulute; } set { currentCulute = value; } } /// <summary> /// Gets or Set the close button visibility. /// </summary> internal ClearButtonVisibilityMode ClearButtonVisibility { get { return clearButtonVisibility; } set { clearButtonVisibility = value; } } internal bool HidePrompt { get { return hidePrompt; } set { hidePrompt = value; } } #endregion private void InitialMethod() { frame = new FrameLayout(context); totalHeight = context.Resources.DisplayMetrics.HeightPixels; TypedValue tv = new TypedValue(); if (context.Theme.ResolveAttribute(Android.Resource.Attribute.ActionBarSize, tv, true)) { actionBarHeight = TypedValue.ComplexToDimensionPixelSize(tv.Data, context.Resources.DisplayMetrics); } navigationBarHeight = getNavigationBarHeight(context); totalHeight = totalHeight - navigationBarHeight - actionBarHeight; } private int getNavigationBarHeight(Android.Content.Context con) { int navBarHeight = 0; int resourceId = con.Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navBarHeight = con.Resources.GetDimensionPixelSize(resourceId); } return navBarHeight; } public View GetSampleContent(Context con) { context = con; InitialMethod(); ScrollView scroll = new ScrollView(con); bool isTablet = SfMaskedEditText.IsTabletDevice(con); linear= new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(12, 12, 12, 12); TextView headLabel = new TextView(con); headLabel.TextSize = 30; headLabel.SetTextColor(Color.ParseColor("#262626")); headLabel.Typeface = Typeface.DefaultBold; headLabel.Text = "Funds Transfer"; linear.AddView(headLabel); TextView fundTransferLabelSpacing = new TextView(con); fundTransferLabelSpacing.SetHeight(40); linear.AddView(fundTransferLabelSpacing); TextView textToAccount = new TextView(con); textToAccount.SetTextColor(Color.ParseColor("#6d6d72")); textToAccount.TextSize = 18; textToAccount.Typeface = Typeface.Default; textToAccount.Text = "To Account"; textToAccount.SetPadding(0, 0, 0, 10); linear.AddView(textToAccount); sfToAccount = new SfMaskedEdit(con); sfToAccount.Mask = "0000 0000 0000 0000"; sfToAccount.Gravity = GravityFlags.Start; sfToAccount.ValidationMode = InputValidationMode.KeyPress; sfToAccount.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfToAccount.Hint = "1234 1234 1234 1234"; sfToAccount.FocusChange += SfToAccount_FocusChange; sfToAccount.SetHintTextColor(Color.LightGray); linear.AddView(sfToAccount); erroToAccount = new TextView(con); erroToAccount.SetTextColor(Color.Red); erroToAccount.TextSize = 14; erroToAccount.Typeface = Typeface.Default; linear.AddView(erroToAccount); TextView textDesc = new TextView(con); textDesc.Text = "Description"; textDesc.Typeface = Typeface.Default; textDesc.SetPadding(0, 30, 0, 10); textDesc.TextSize = 18; linear.AddView(textDesc); sfDesc = new SfMaskedEdit(con); sfDesc.Mask = ""; sfDesc.Gravity = GravityFlags.Start; sfDesc.ValidationMode = InputValidationMode.KeyPress; sfDesc.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; sfDesc.Hint = "Enter description"; sfDesc.FocusChange += SfToAccount_FocusChange; sfDesc.SetHintTextColor(Color.LightGray); linear.AddView(sfDesc); TextView textAmount = new TextView(con); textAmount.Text = "Amount"; textAmount.Typeface = Typeface.Default; textAmount.SetPadding(0, 30, 0, 10); textAmount.TextSize = 18; linear.AddView(textAmount); amountMask = new SfMaskedEdit(con); amountMask.Mask = "$ 0,000.00"; amountMask.Gravity = GravityFlags.Start; amountMask.ValidationMode = InputValidationMode.KeyPress; amountMask.ValueMaskFormat = MaskFormat.IncludePromptAndLiterals; amountMask.Hint = "$ 3,874.00"; amountMask.FocusChange += SfToAccount_FocusChange; amountMask.SetHintTextColor(Color.LightGray); linear.AddView(amountMask); errotextAmount = new TextView(con); errotextAmount.SetTextColor(Color.Red); errotextAmount.TextSize = 12; errotextAmount.Typeface = Typeface.Default; linear.AddView(errotextAmount); TextView textEmail = new TextView(con); textEmail.Text = "Email ID"; textEmail.Typeface = Typeface.Default; textEmail.SetPadding(0, 30, 0, 10); textEmail.TextSize = 18; linear.AddView(textEmail); emailMask = new SfMaskedEdit(con); emailMask.Mask = @"\w+@\w+\.\w+"; emailMask.MaskType = MaskType.RegEx; emailMask.Gravity = GravityFlags.Start; emailMask.ValidationMode = InputValidationMode.KeyPress; emailMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; emailMask.Hint = "<EMAIL>"; emailMask.FocusChange += SfToAccount_FocusChange; emailMask.SetHintTextColor(Color.LightGray); linear.AddView(emailMask); errotextEmail = new TextView(con); errotextEmail.SetTextColor(Color.Red); errotextEmail.TextSize = 12; errotextEmail.Typeface = Typeface.Default; linear.AddView(errotextEmail); TextView textPhone = new TextView(con); textPhone.Text = "Mobile Number "; textPhone.Typeface = Typeface.Default; textPhone.SetPadding(0, 30, 0, 10); textPhone.TextSize = 18; linear.AddView(textPhone); phoneMask = new SfMaskedEdit(con); phoneMask.Mask = "+1 000 000 0000"; phoneMask.Gravity = GravityFlags.Start; phoneMask.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; phoneMask.ValidationMode = InputValidationMode.KeyPress; phoneMask.Hint = "+1 323 339 3392"; phoneMask.FocusChange += SfToAccount_FocusChange; phoneMask.SetHintTextColor(Color.LightGray); linear.AddView(phoneMask); errotextPhone = new TextView(con); errotextPhone.SetTextColor(Color.Red); errotextPhone.TextSize = 12; errotextPhone.Typeface = Typeface.Default; linear.AddView(errotextPhone); TextView transferButtonSpacing = new TextView(con); transferButtonSpacing.SetHeight(30); Button transferButton = new Button(con); transferButton.SetWidth(ActionBar.LayoutParams.MatchParent); transferButton.SetHeight(40); transferButton.Text = "TRANSFER MONEY"; transferButton.SetTextColor(Color.White); transferButton.SetBackgroundColor(Color.Rgb(72, 178, 224)); transferButton.Click += (object sender, EventArgs e) => { if (string.IsNullOrEmpty(sfToAccount.Text) || string.IsNullOrEmpty(sfDesc.Text) || string.IsNullOrEmpty(amountMask.Text) || string.IsNullOrEmpty(emailMask.Text) || string.IsNullOrEmpty(phoneMask.Text)) { resultsDialog.SetMessage("Please fill all the required data!"); } else if((sfToAccount.HasError || sfDesc.HasError || amountMask.HasError || emailMask.HasError || phoneMask.HasError)) { resultsDialog.SetMessage("Please enter valid details"); } else { resultsDialog.SetMessage(string.Format("Amount of {0} has been transferred successfully!", amountMask.Value)); sfToAccount.Value = string.Empty; sfDesc.Value = string.Empty; amountMask.Value = string.Empty; emailMask.Value = string.Empty; phoneMask.Value = string.Empty; } resultsDialog.Create().Show(); }; linear.AddView(transferButtonSpacing); linear.AddView(transferButton); TextView transferAfterButtonSpacing = new TextView(con); transferAfterButtonSpacing.SetHeight(60); linear.AddView(transferAfterButtonSpacing); sfToAccount.ValueChanged += SfToAccount_ValueChanged; sfToAccount.MaskInputRejected += SfToAccount_MaskInputRejected; amountMask.ValueChanged += AmountMask_ValueChanged; amountMask.MaskInputRejected += AmountMask_MaskInputRejected; emailMask.ValueChanged += EmailMask_ValueChanged; emailMask.MaskInputRejected += EmailMask_MaskInputRejected; phoneMask.ValueChanged += PhoneMask_ValueChanged; phoneMask.MaskInputRejected += PhoneMask_MaskInputRejected; linear.Touch += (object sender, View.TouchEventArgs e) => { if (sfToAccount.IsFocused || sfDesc.IsFocused || amountMask.IsFocused || emailMask.IsFocused ||phoneMask.IsFocused) { Rect outRect = new Rect(); sfToAccount.GetGlobalVisibleRect(outRect); sfDesc.GetGlobalVisibleRect(outRect); amountMask.GetGlobalVisibleRect(outRect); emailMask.GetGlobalVisibleRect(outRect); phoneMask.GetGlobalVisibleRect(outRect); if (!outRect.Contains((int)e.Event.RawX, (int)e.Event.RawY)) { sfToAccount.ClearFocus(); sfDesc.ClearFocus(); amountMask.ClearFocus(); emailMask.ClearFocus(); phoneMask.ClearFocus(); } } hideSoftKeyboard((Activity)con); }; //results dialog resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetTitle("Status"); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); frame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); frame.SetBackgroundColor(Color.White); frame.SetPadding(10, 10, 10, 10); //scrollView1 mainPageScrollView = new ScrollView(con); mainPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.7), GravityFlags.Top | GravityFlags.CenterHorizontal); mainPageScrollView.AddView(linear); frame.AddView(mainPageScrollView); //buttomButtonLayout buttomButtonLayout = new FrameLayout(con); buttomButtonLayout.SetBackgroundColor(Color.Transparent); buttomButtonLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1), GravityFlags.Bottom | GravityFlags.CenterHorizontal); //propertyButton propertyButton = new Button(con); propertyButton.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Bottom | GravityFlags.CenterHorizontal); propertyButton.Text = "OPTIONS"; propertyButton.Gravity = GravityFlags.Start; propertyFrameLayout = new FrameLayout(con); propertyFrameLayout.SetBackgroundColor(Color.Rgb(236, 236, 236)); propertyFrameLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.3), GravityFlags.CenterHorizontal); propertyFrameLayout.AddView(GetPropertyLayout(con)); //propertyButton Click Listener propertyButton.Click += (object sender, EventArgs e) => { buttomButtonLayout.RemoveAllViews(); propertyFrameLayout.RemoveAllViews(); propPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.3), GravityFlags.Bottom | GravityFlags.CenterHorizontal); mainPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.7), GravityFlags.Top | GravityFlags.CenterHorizontal); propertyFrameLayout.AddView(GetPropertyLayout(con)); }; //scrollView propPageScrollView = new ScrollView(con); propPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.3), GravityFlags.Bottom | GravityFlags.CenterHorizontal); propPageScrollView.AddView(propertyFrameLayout); frame.AddView(propPageScrollView); frame.AddView(buttomButtonLayout); frame.FocusableInTouchMode = true; return frame; } private void PhoneMask_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { errotextPhone.Text = GetRejectionHintText(e.RejectionHint); } private void PhoneMask_ValueChanged(object sender, ValueChangedEventArgs e) { errotextPhone.Text = ""; } private void EmailMask_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { errotextEmail.Text = GetRejectionHintText(e.RejectionHint); } private void EmailMask_ValueChanged(object sender, ValueChangedEventArgs e) { errotextEmail.Text = ""; } private void AmountMask_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { errotextAmount.Text = GetRejectionHintText(e.RejectionHint); } private void AmountMask_ValueChanged(object sender, ValueChangedEventArgs e) { errotextAmount.Text = ""; } private void SfToAccount_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { erroToAccount.Text = GetRejectionHintText(e.RejectionHint); } private void SfToAccount_ValueChanged(object sender, ValueChangedEventArgs e) { erroToAccount.Text = ""; } private string GetRejectionHintText(MaskedTextResultHint hint) { string hintText = string.Empty; switch (hint) { case MaskedTextResultHint.AlphanumericCharacterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.DigitExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.LetterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.SignedDigitExpected: hintText = "Invalid character!"; break; //case MaskedTextResultHint.UnavailableEditPosition: // hintText = "Invalid typed character!"; // break; } return hintText; } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); inputMethodManager.HideSoftInputFromWindow(activity.CurrentFocus.WindowToken, 0); } public void OnApplyChanges() { sfToAccount.HidePromptOnLeave = hidePrompt; sfToAccount.ValidationMode = validationMask; sfToAccount.PromptChar = currentPrompt; sfToAccount.Culture = currentCulute; sfToAccount.ClearButtonVisibility = clearButtonVisibility; sfDesc.HidePromptOnLeave = hidePrompt; sfDesc.ValidationMode = validationMask; sfDesc.PromptChar = currentPrompt; sfDesc.Culture = currentCulute; sfDesc.ClearButtonVisibility = clearButtonVisibility; amountMask.HidePromptOnLeave = hidePrompt; amountMask.ValidationMode = validationMask; amountMask.Culture = currentCulute; amountMask.PromptChar = currentPrompt; amountMask.ClearButtonVisibility = clearButtonVisibility; emailMask.HidePromptOnLeave = hidePrompt; emailMask.ValidationMode = validationMask; emailMask.PromptChar = currentPrompt; emailMask.Culture = currentCulute; emailMask.ClearButtonVisibility = clearButtonVisibility; phoneMask.HidePromptOnLeave = hidePrompt; phoneMask.ValidationMode = validationMask; phoneMask.PromptChar = currentPrompt; phoneMask.Culture = currentCulute; phoneMask.ClearButtonVisibility = clearButtonVisibility; } private void SfToAccount_FocusChange(object sender, View.FocusChangeEventArgs e) { if ((sender as EditText).IsFocused) { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); mainPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); propPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.003), GravityFlags.Bottom | GravityFlags.CenterHorizontal); buttomButtonLayout.AddView(propertyButton); } } FrameLayout topProperty; private void OptionViewLayout() { /**************** **Options View** ****************/ TextView propertyLabel = new TextView(context); propertyLabel.SetTextColor(Color.ParseColor("#282828")); propertyLabel.Gravity = GravityFlags.CenterVertical; propertyLabel.TextSize = 18; propertyLabel.SetPadding(0, 10, 0, 10); propertyLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.Left | GravityFlags.CenterHorizontal); propertyLabel.Text = " " + "OPTIONS"; //CloseLabel closeLabel = new TextView(context); closeLabel.SetBackgroundColor(Color.Transparent); closeLabel.Gravity = GravityFlags.CenterVertical; closeLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLabel.SetBackgroundResource(Resource.Drawable.sfclosebutton); //CloseLayout FrameLayout closeLayout = new FrameLayout(context); closeLayout.SetBackgroundColor(Color.Transparent); closeLayout.SetPadding(0, 10, 0, 10); closeLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLayout.AddView(closeLabel); //TopProperty topProperty = new FrameLayout(context); topProperty.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); topProperty.SetBackgroundColor(Color.Rgb(230, 230, 230)); topProperty.AddView(propertyLabel); topProperty.AddView(closeLayout); //topProperty Touch Event topProperty.Touch += (object sendar, View.TouchEventArgs e) => { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); mainPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); propPageScrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent,(int)(totalHeight * 0.0003)); }; proprtyOptionsLayout = new LinearLayout(context); proprtyOptionsLayout.Orientation = Android.Widget.Orientation.Vertical; //SpaceText TextView spaceText1 = new TextView(context); spaceText1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText1); } public View GetPropertyLayout(Android.Content.Context context) { totalWidth = (context.Resources.DisplayMetrics.WidthPixels); propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; OptionViewLayout(); maskProperties.ValidationLayout(context, propertylayout, false); maskProperties.CultureLayout(context, propertylayout, false); maskProperties.CloseButtonVisibilityLayout(context, propertylayout, false); maskProperties.HideLayout(context, propertylayout, false); maskProperties.PromptLayout(context, propertylayout, false); TextView spaceLabel = new TextView(context); spaceLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent); LinearLayout layout1 = new LinearLayout(context); layout1.Orientation = Android.Widget.Orientation.Horizontal; layout1.AddView(spaceLabel); layout1.AddView(ProprtyOptionsLayout); propertylayout.AddView(topProperty); propertylayout.AddView(layout1); propertylayout.SetBackgroundColor(Color.Rgb(240, 240, 240)); return propertylayout; } } }<file_sep>/Forms/ListView/ListView/Samples/LoadMore/Helpers/Converters.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class InverseZeroVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is int && (int)value > 0) return true; return false; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [Preserve(AllMembers = true)] public class ZeroVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is int && (int)value <= 0) return true; return false; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [Preserve(AllMembers = true)] public class TotalItemsCountConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is int && (int)value <= 1) return value + " Item |"; return value + " Items |"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [Preserve(AllMembers = true)] public class CurrencyFormatConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var d = (double)value; return string.Format("${0:0.00}", d); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Android/SampleBrowser/Samples/Calculate/CalcQuick.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Views.InputMethods; using Syncfusion.Calculate; namespace SampleBrowser { public class CalcQuick : SamplePage, IDisposable { #region Fields private CalcQuickBase calcQuickBase; private ScrollView scrollView; private EditText editTextA; private EditText editTextB; private EditText editTextC; private TextViewExt result1; private TextViewExt result2; private TextViewExt result3; private TextView textA; private TextView textB; private TextView textC; private Context context; #endregion #region Methods public override View GetSampleContent(Context context) { this.context = context; CreateCalcQuickDesign(context); return scrollView; } private void CreateCalcQuickDesign(Context context) { int width = context.Resources.DisplayMetrics.WidthPixels; var density = context.Resources.DisplayMetrics.Density; InitializeCalcQuick(); scrollView = new ScrollView(context); scrollView.SetPadding(10, 10, 10, 20); LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; linearLayout.Focusable = true; linearLayout.FocusableInTouchMode = true; LinearLayout linearLayout1 = new LinearLayout(context); linearLayout1.Orientation = Orientation.Vertical; TextView titleText = new TextView(context) { Text = "CalcQuick Calculation", TextAlignment = TextAlignment.Center, Gravity = GravityFlags.Center, TextSize = 30 }; titleText.SetTypeface(null, TypefaceStyle.Bold); titleText.SetWidth(width); titleText.SetHeight((int)(50 * density)); TextView descText = new TextView(context) { Text = "This sample demonstrates the calculation via keys and expressions using CalcQuick.", TextAlignment = TextAlignment.TextStart, Gravity = GravityFlags.FillHorizontal, TextSize = 12 }; descText.SetPadding(0, 10, 0, 0); descText.SetWidth(width); descText.SetHeight((int)(40 * density)); linearLayout1.AddView(titleText); linearLayout1.AddView(descText); LinearLayout linearLayout2 = new LinearLayout(context); LinearLayout linearLayout3 = new LinearLayout(context); LinearLayout linearLayout4 = new LinearLayout(context); linearLayout2.Orientation = Orientation.Horizontal; linearLayout3.Orientation = Orientation.Horizontal; linearLayout4.Orientation = Orientation.Horizontal; linearLayout2.SetPadding(0, 30, 0, 0); linearLayout3.SetPadding(0, 25, 0, 0); linearLayout4.SetPadding(0, 25, 0, 0); textA = CreateTextView(context, "Key A", 15); textA.SetWidth((int)(width * 0.5)); textA.SetHeight((int)(20 * density)); textB = CreateTextView(context, "Key B", 15); textB.SetWidth((int)(width * 0.5)); textB.SetHeight((int)(20 * density)); textC = CreateTextView(context, "Key C", 15); textC.SetWidth((int)(width * 0.5)); textC.SetHeight((int)(20 * density)); editTextA = CreateEditText(context, calcQuickBase["A"]); editTextA.SetWidth(width - (int)(width * 0.5)); editTextA.SetHeight((int)(20 * density)); editTextA.SetSingleLine(true); editTextB = CreateEditText(context, calcQuickBase["B"]); editTextB.SetWidth(width - (int)(width * 0.5)); editTextB.SetHeight((int)(20 * density)); editTextB.SetSingleLine(true); editTextC = CreateEditText(context, calcQuickBase["C"]); editTextC.SetWidth(width - (int)(width * 0.5)); editTextC.SetHeight((int)(20 * density)); editTextC.SetSingleLine(true); linearLayout2.AddView(textA); linearLayout3.AddView(textB); linearLayout4.AddView(textC); linearLayout2.AddView(editTextA); linearLayout3.AddView(editTextB); linearLayout4.AddView(editTextC); LinearLayout linearLayout5 = new LinearLayout(context); linearLayout5.SetPadding(0, 15, 0, 0); Button compute = new Button(context); compute.Text = "Compute"; compute.Click += Compute_Click; compute.SetWidth(width); compute.SetHeight((int)(20 * density)); linearLayout5.AddView(compute); LinearLayout linearLayout6 = new LinearLayout(context); LinearLayout linearLayout7 = new LinearLayout(context); LinearLayout linearLayout8 = new LinearLayout(context); LinearLayout linearLayout9 = new LinearLayout(context); linearLayout6.Orientation = Orientation.Horizontal; linearLayout7.Orientation = Orientation.Horizontal; linearLayout8.Orientation = Orientation.Horizontal; linearLayout9.Orientation = Orientation.Horizontal; linearLayout6.SetPadding(0, 40, 0, 0); linearLayout7.SetPadding(0, 60, 0, 0); linearLayout8.SetPadding(0, 60, 0, 0); linearLayout9.SetPadding(0, 60, 0, 0); TextView expTitle = CreateTextView(context, "Expressions", 22); expTitle.SetTypeface(null, TypefaceStyle.Bold); expTitle.SetWidth(width); expTitle.SetHeight((int)(30 * density)); TextView expression1 = CreateTextView(context, "Sum([A],[B],[C])", 15); expression1.SetWidth((int)(width * 0.5)); expression1.SetHeight((int)(20 * density)); TextView expression2 = CreateTextView(context, "PI()*([A]^2)", 15); expression2.SetWidth((int)(width * 0.5)); expression2.SetHeight((int)(20 * density)); TextView expression3 = CreateTextView(context, "Concatenate([A],[B],[C])", 15); expression3.SetWidth((int)(width * 0.5)); expression2.SetHeight((int)(20 * density)); result1 = CreateTextViewExt(context, calcQuickBase["Exp1"]); result1.SetWidth(width - (int)(width * 0.5)); result1.SetHeight((int)(20 * density)); result1.SetSingleLine(true); result2 = CreateTextViewExt(context, calcQuickBase["Exp2"]); result2.SetWidth(width - (int)(width * 0.5)); result2.SetHeight((int)(20 * density)); result2.SetSingleLine(true); result3 = CreateTextViewExt(context, calcQuickBase["Exp3"]); result3.SetWidth(width - (int)(width * 0.5)); result3.SetHeight((int)(20 * density)); result3.SetSingleLine(true); linearLayout6.AddView(expTitle); linearLayout7.AddView(expression1); linearLayout8.AddView(expression2); linearLayout9.AddView(expression3); linearLayout7.AddView(result1); linearLayout8.AddView(result2); linearLayout9.AddView(result3); linearLayout.AddView(linearLayout1); linearLayout.AddView(linearLayout2); linearLayout.AddView(linearLayout3); linearLayout.AddView(linearLayout4); linearLayout.AddView(linearLayout5); linearLayout.AddView(linearLayout6); linearLayout.AddView(linearLayout7); linearLayout.AddView(linearLayout8); linearLayout.AddView(linearLayout9); linearLayout.Touch += (object sender, View.TouchEventArgs e) => { if (e.Event.Action == MotionEventActions.Up) { ClearFocus(); } }; scrollView.AddView(linearLayout); } private void Compute_Click(object sender, EventArgs e) { calcQuickBase["A"] = editTextA.Text; calcQuickBase["B"] = editTextB.Text; calcQuickBase["C"] = editTextC.Text; calcQuickBase.SetDirty(); result1.Text = calcQuickBase["Exp1"]; result2.Text = calcQuickBase["Exp2"]; result3.Text = calcQuickBase["Exp3"]; ClearFocus(); } private void InitializeCalcQuick() { calcQuickBase = new CalcQuickBase(); calcQuickBase["A"] = "25"; calcQuickBase["B"] = "50"; calcQuickBase["C"] = "10"; calcQuickBase["Exp1"] = "=Sum([A],[B],[C])"; calcQuickBase["Exp2"] = "=PI()*([A]^2)"; calcQuickBase["Exp3"] = "=Concatenate([A],[B],[C])"; } private TextView CreateTextView(Context context, string text, int size) { return new TextView(context) { Text = text, Gravity = GravityFlags.Start, TextSize = size }; } private EditText CreateEditText(Context context, string text) { return new EditText(context) { Text = text, TextSize = 15 }; } private TextViewExt CreateTextViewExt(Context context, string text) { return new TextViewExt(context) { Text = text, TextSize = 15 }; } private void ClearFocus() { if (editTextA.IsFocused || editTextB.IsFocused || editTextC.IsFocused) { editTextA.ClearFocus(); editTextB.ClearFocus(); editTextC.ClearFocus(); } Activity activity = (Activity)context; InputMethodManager inputMethodManager = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); if (activity.CurrentFocus != null) { inputMethodManager.HideSoftInputFromWindow(activity.CurrentFocus.WindowToken, 0); } } public override void Destroy() { scrollView = null; calcQuickBase.Dispose(); calcQuickBase = null; editTextA = null; editTextB = null; editTextC = null; result1 = null; result2 = null; result3 = null; textA = null; textB = null; textC = null; context = null; base.Destroy(); } public void Dispose() { if (scrollView != null) { scrollView.Dispose(); scrollView = null; } if (calcQuickBase != null) { calcQuickBase.Dispose(); calcQuickBase = null; } if (editTextA != null) { editTextA.Dispose(); editTextA = null; } if (editTextB != null) { editTextB.Dispose(); editTextB = null; } if (editTextC != null) { editTextC.Dispose(); editTextC = null; } if (result1 != null) { result1.Dispose(); result1 = null; } if (result2 != null) { result2.Dispose(); result2 = null; } if (result3 != null) { result3.Dispose(); result3 = null; } if (textA != null) { textA.Dispose(); textA = null; } if (textB != null) { textB.Dispose(); textB = null; } if (textC != null) { textC.Dispose(); textC = null; } } #endregion } public class TextViewExt : TextView { private Paint paintBorder; public TextViewExt(Context context) : base(context) { paintBorder = new Paint(PaintFlags.AntiAlias); paintBorder.Color = Color.Black; paintBorder.TextAlign = Android.Graphics.Paint.Align.Center; paintBorder.SetStyle(Android.Graphics.Paint.Style.FillAndStroke); } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); canvas.DrawLine(0, this.Height, this.Width, this.Height, paintBorder); } } }<file_sep>/Forms/Barcode/Barcode/Samples/DataMatrix/DataMatrix.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfBarcode.XForms; using Xamarin.Forms; using SampleBrowser.Core; using Xamarin.Forms.Internals; namespace SampleBrowser.SfBarcode { [Preserve(AllMembers = true)] public partial class DataMatrix : SampleView { public DataMatrix() { InitializeComponent(); DataMatrixSettings settings = new DataMatrixSettings(); settings.XDimension = 8; this.barcode10.SymbologySettings = settings; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/PDF/ZugFerd.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif using System.Xml; using System.Linq; using Syncfusion.Pdf.Grid; using Syncfusion.Pdf.Interactive; using Syncfusion.ZugFerd; using System.Collections.Generic; namespace SampleBrowser { public partial class ZugFerd : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label1; UIButton button ; RectangleF TotalPriceCellBounds = RectangleF.Empty; RectangleF QuantityCellBounds = RectangleF.Empty; public ZugFerd() { label1 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label1.Frame = frameRect; label1.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label1.Text = "This sample demonstrates how to create ZUGFeRD PDF invoice using Essential PDF."; label1.Font = UIFont.SystemFontOfSize(15); label1.Lines = 0; label1.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label1.Font = UIFont.SystemFontOfSize(18); label1.Frame = new CGRect(0, 12, frameRect.Location.X + frameRect.Size.Width, 50); } else { label1.Frame = new CGRect(frameRect.Location.X, 12, frameRect.Size.Width, 50); } this.AddSubview(label1); button.SetTitle("Generate PDF", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 70, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 70, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { //Create ZugFerd invoice PDF PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B); document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic; CreateZugFerdInvoicePDF(document); //Create ZugFerd Xml attachment file Stream zugferdXmlStream = CreateZugFerdXML(); //Creates an attachment. PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXmlStream); attachment.Relationship = PdfAttachmentRelationship.Alternative; attachment.ModificationDate = DateTime.Now; attachment.Description = "Adventure Invoice"; attachment.MimeType = "application/xml"; document.Attachments.Add(attachment); MemoryStream stream = new MemoryStream(); //Save the PDF document. document.Save(stream); //Close the PDF document. document.Close(); stream.Position = 0; if (stream != null) { SaveiOS iosSave = new SaveiOS(); iosSave.Save("ZugFerd.pdf", "application/pdf", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } public Stream CreateZugFerdXML() { //Create ZugFerd Invoice ZugFerdInvoice invoice = new ZugFerdInvoice("2058557939", new DateTime(2013, 6, 5), CurrencyCodes.USD); //Set ZugFerdProfile to ZugFerdInvoice invoice.Profile = ZugFerdProfile.Basic; //Add buyer details invoice.Buyer = new UserDetails { ID = "Abraham_12", Name = "<NAME>", ContactName = "Swearegin", City = "United States, California", Postcode = "9920", Country = CountryCodes.US, Street = "9920 BridgePointe Parkway" }; //Add seller details invoice.Seller = new UserDetails { ID = "Adventure_123", Name = "AdventureWorks", ContactName = "Adventure support", City = "Austin,TX", Postcode = "", Country = CountryCodes.US, Street = "800 Interchange Blvd" }; IEnumerable<Product> products = GetProductReport(); float total = 0; foreach (var product in products) { invoice.AddProduct(product); total += product.Total; } invoice.TotalAmount = total; MemoryStream ms = new MemoryStream(); //Save ZugFerd Xml return invoice.Save(ms); } /// <summary> /// Create ZugFerd Invoice Pdf /// </summary> /// <param name="document"></param> /// <returns></returns> public PdfDocument CreateZugFerdInvoicePDF(PdfDocument document) { //Add page to the PDF PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; //Create border color PdfColor borderColor = Syncfusion.Drawing.Color.FromArgb(255, 142, 170, 219); //Get the page width and height float pageWidth = page.GetClientSize().Width; float pageHeight = page.GetClientSize().Height; //Set the header height float headerHeight = 90; PdfColor lightBlue = Syncfusion.Drawing.Color.FromArgb(255, 91, 126, 215); PdfBrush lightBlueBrush = new PdfSolidBrush(lightBlue); PdfColor darkBlue = Syncfusion.Drawing.Color.FromArgb(255, 65, 104, 209); PdfBrush darkBlueBrush = new PdfSolidBrush(darkBlue); PdfBrush whiteBrush = new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255)); Stream fontStream = typeof(ZugFerd).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.arial.ttf"); PdfTrueTypeFont headerFont = new PdfTrueTypeFont(fontStream, 30, PdfFontStyle.Regular); PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 18, PdfFontStyle.Regular); PdfTrueTypeFont arialBoldFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold); //Create string format. PdfStringFormat format = new PdfStringFormat(); format.Alignment = PdfTextAlignment.Center; format.LineAlignment = PdfVerticalAlignment.Middle; float y = 0; float x = 0; //Set the margins of address. float margin = 30; //Set the line space float lineSpace = 7; PdfPen borderPen = new PdfPen(borderColor, 1f); //Draw page border graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight)); PdfGrid grid = new PdfGrid(); grid.DataSource = GetProductReport(); #region Header //Fill the header with light Brush graphics.DrawRectangle(lightBlueBrush, new RectangleF(0, 0, pageWidth, headerHeight)); string title = "INVOICE"; SizeF textSize = headerFont.MeasureString(title); RectangleF headerTotalBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight); graphics.DrawString(title, headerFont, whiteBrush, new RectangleF(0, 0, textSize.Width + 50, headerHeight), format); graphics.DrawRectangle(darkBlueBrush, headerTotalBounds); graphics.DrawString("$" + GetTotalAmount(grid).ToString(), arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight + 10), format); arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular); format.LineAlignment = PdfVerticalAlignment.Bottom; graphics.DrawString("Amount", arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight / 2 - arialRegularFont.Height), format); #endregion SizeF size = arialRegularFont.MeasureString("Invoice Number: 2058557939"); y = headerHeight + margin; x = (pageWidth - margin) - size.Width; graphics.DrawString("Invoice Number: 2058557939", arialRegularFont, PdfBrushes.Black, new PointF(x, y)); size = arialRegularFont.MeasureString("Date :" + DateTime.Now.ToString("dddd dd, MMMM yyyy")); x = (pageWidth - margin) - size.Width; y += arialRegularFont.Height + lineSpace; graphics.DrawString("Date: " + DateTime.Now.ToString("dddd dd, MMMM yyyy"), arialRegularFont, PdfBrushes.Black, new PointF(x, y)); y = headerHeight + margin; x = margin; graphics.DrawString("<NAME>:", arialRegularFont, PdfBrushes.Black, new PointF(x, y)); y += arialRegularFont.Height + lineSpace; graphics.DrawString("<NAME>,", arialRegularFont, PdfBrushes.Black, new PointF(x, y)); y += arialRegularFont.Height + lineSpace; graphics.DrawString("United States, California, San Mateo,", arialRegularFont, PdfBrushes.Black, new PointF(x, y)); y += arialRegularFont.Height + lineSpace; graphics.DrawString("9920 BridgePointe Parkway,", arialRegularFont, PdfBrushes.Black, new PointF(x, y)); y += arialRegularFont.Height + lineSpace; graphics.DrawString("9365550136", arialRegularFont, PdfBrushes.Black, new PointF(x, y)); #region Grid grid.Columns[0].Width = 110; grid.Columns[1].Width = 150; grid.Columns[2].Width = 110; grid.Columns[3].Width = 70; grid.Columns[4].Width = 100; for (int i = 0; i < grid.Headers.Count; i++) { grid.Headers[i].Height = 20; for (int j = 0; j < grid.Columns.Count; j++) { PdfStringFormat pdfStringFormat = new PdfStringFormat(); pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle; pdfStringFormat.Alignment = PdfTextAlignment.Left; if (j == 0 || j == 2) grid.Headers[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1); grid.Headers[i].Cells[j].StringFormat = pdfStringFormat; grid.Headers[i].Cells[j].Style.Font = arialBoldFont; } grid.Headers[0].Cells[0].Value = "Product Id"; } for (int i = 0; i < grid.Rows.Count; i++) { grid.Rows[i].Height = 23; for (int j = 0; j < grid.Columns.Count; j++) { PdfStringFormat pdfStringFormat = new PdfStringFormat(); pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle; pdfStringFormat.Alignment = PdfTextAlignment.Left; if (j == 0 || j == 2) grid.Rows[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1); grid.Rows[i].Cells[j].StringFormat = pdfStringFormat; grid.Rows[i].Cells[j].Style.Font = arialRegularFont; } } grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5); grid.BeginCellLayout += Grid_BeginCellLayout; PdfGridLayoutResult result = grid.Draw(page, new PointF(0, y + 40)); y = result.Bounds.Bottom + lineSpace; format = new PdfStringFormat(); format.Alignment = PdfTextAlignment.Center; RectangleF bounds = new RectangleF(QuantityCellBounds.X, y, QuantityCellBounds.Width, QuantityCellBounds.Height); page.Graphics.DrawString("Grand Total:", arialBoldFont, PdfBrushes.Black, bounds, format); bounds = new RectangleF(TotalPriceCellBounds.X, y, TotalPriceCellBounds.Width, TotalPriceCellBounds.Height); page.Graphics.DrawString(GetTotalAmount(grid).ToString(), arialBoldFont, PdfBrushes.Black, bounds); #endregion borderPen.DashStyle = PdfDashStyle.Custom; borderPen.DashPattern = new float[] { 3, 3 }; graphics.DrawLine(borderPen, new PointF(0, pageHeight - 100), new PointF(pageWidth, pageHeight - 100)); y = pageHeight - 100 + margin; size = arialRegularFont.MeasureString("800 Interchange Blvd."); x = pageWidth - size.Width - margin; graphics.DrawString("800 Interchange Blvd.", arialRegularFont, PdfBrushes.Black, new PointF(x, y)); y += arialRegularFont.Height + lineSpace; size = arialRegularFont.MeasureString("Suite 2501, Austin, TX 78721"); x = pageWidth - size.Width - margin; graphics.DrawString("Suite 2501, Austin, TX 78721", arialRegularFont, PdfBrushes.Black, new PointF(x, y)); y += arialRegularFont.Height + lineSpace; size = arialRegularFont.MeasureString("Any Questions? <EMAIL>"); x = pageWidth - size.Width - margin; graphics.DrawString("Any Questions? <EMAIL>", arialRegularFont, PdfBrushes.Black, new PointF(x, y)); return document; } private void Grid_BeginCellLayout(object sender, PdfGridBeginCellLayoutEventArgs args) { PdfGrid grid = sender as PdfGrid; if (args.CellIndex == grid.Columns.Count - 1) { TotalPriceCellBounds = args.Bounds; } else if (args.CellIndex == grid.Columns.Count - 2) { QuantityCellBounds = args.Bounds; } } private IEnumerable<Product> GetProductReport() { List<Product> collection = new List<Product>(); Stream xmlStream = typeof(ZugFerd).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.InvoiceProductList.xml"); XmlReader reader = XmlReader.Create(xmlStream); while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "ProductDetails": Product product = new Product(); while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Productid": reader.Read(); product.ProductID = reader.Value; break; case "Product": reader.Read(); product.productName = reader.Value; break; case "Price": reader.Read(); product.Price = float.Parse(reader.Value); break; case "Quantity": reader.Read(); product.Quantity = int.Parse(reader.Value); break; case "Total": reader.Read(); product.Total = float.Parse(reader.Value); break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "ProductDetails") { collection.Add(product); break; } } break; } } } return collection.AsEnumerable<Product>(); } /// <summary> /// Get the Total amount of purcharsed items /// </summary> /// <param name="grid"></param> /// <returns></returns> private float GetTotalAmount(PdfGrid grid) { float Total = 0f; for (int i = 0; i < grid.Rows.Count; i++) { string cellValue = grid.Rows[i].Cells[grid.Columns.Count - 1].Value.ToString(); float result; Total += float.TryParse(cellValue, out result) ? result : 0; } return Total; } } } <file_sep>/Forms/AutoComplete/AutoComplete/Samples/MultiSelect/ContactsInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfAutoComplete { [Preserve(AllMembers = true)] public class ContactsInfoRepository { #region Fields private Random random = new Random(); #endregion #region Constructor public ContactsInfoRepository() { } #endregion #region Get Contacts Details public ObservableCollection<ContactsInfo> GetContactDetails() { ObservableCollection<ContactsInfo> customerDetails = new ObservableCollection<ContactsInfo>(); for (int i = 0; i < CustomerNames.Count(); i++) { var details = new ContactsInfo() { ContactType = contactType[random.Next(0, 5)], ContactName = CustomerNames[i], ContactNumber = CustomerNames[i].Replace(" ", "") + "@outlook.com", ContactImage = "People_Circle" + (i % 30) + ".png", }; customerDetails.Add(details); } return customerDetails; } #endregion #region Contacts Information string[] contactType = new string[] { "Green.jpg", "Gray.jpg", "Yellow.jpg", "Red.jpg", "Orange_Shape.jpg" }; string[] CustomerNames = new string[] { "Kyle", "Victoriya", "Clara", "Ellie", "Gabriella", "Alexander", "Nora", "Lucy", "Sebastian", "Arianna", "Sarah", "Kaylee", "Jacob", "Adriana", "Ethan", "Finley", "Daleyza", "Leila", "Jayden", "Mckenna", "Jacqueline", "Brynn", "Sawyer", "Liam", "Rosalie", "Maci", "Mason", "Jackson", "Miranda", "Talia", "Shelby", "Haven", "Yaretzi", "Zariah", "Karla", "Zeke", "Cassandra", "Pearl", "Aiden", "Irene", "Zelda", "Wren", "Vince", "Yamileth", "Steve", "Belen", "Briley", "Jada", "Holly", "Jaden" }; #endregion } } <file_sep>/Android/SampleBrowser/Samples/PDF/DigitalSignature.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Java.IO; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.IO; using Syncfusion.Pdf.Parsing; using System.Threading.Tasks; using Syncfusion.Pdf; using System.Reflection; using Syncfusion.Pdf.Security; using Syncfusion.Drawing; using AndroidX.Core.Content; namespace SampleBrowser { public partial class DigitalSignature : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how a PDF document can be secured with certificates and signed with either standard or author signatures. Now added the support for Elliptic Curve Digital Signature Algorithm (ECDSA) to sign the PDF document."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Sign and Email"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { //Get the stream from the document. Stream docStream = typeof(Booklet).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.SalesOrderDetail.pdf"); //Load the PDF document into the loaded document object. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream); //Get the certificate stream from .pfx file. Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.PDF.pfx"); //Create PdfCertificate using certificate stream and password. PdfCertificate pdfCert = new PdfCertificate(certificateStream, "syncfusion"); //Add certificate to document first page. PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCert, "Signature"); signature.Bounds = new RectangleF(5, 5, 300, 300); MemoryStream stream = new MemoryStream(); //Save the PDF document loadedDocument.Save(stream); //Close the PDF document loadedDocument.Close(true); if (stream != null) { stream.Position=0; ComposeMail("DigitalSignature.pdf", null, "Signing the document", "Syncfusion", stream); } } public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream filestream) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) file.Delete(); try { FileOutputStream outs = new FileOutputStream(file); outs.Write(filestream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } Intent email = new Intent(Android.Content.Intent.ActionSend); var uri = FileProvider.GetUriForFile(this.m_context, Application.Context.PackageName + ".provider", file); //file.SetReadable(true, true); email.PutExtra(Android.Content.Intent.ExtraSubject, subject); email.PutExtra(Intent.ExtraStream, uri); email.SetType("application/pdf"); MainActivity.BaseActivity.StartActivity(email); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/LinearGauge/LinearGaugeAnnotation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif using Syncfusion.SfGauge.iOS; namespace SampleBrowser { public class LinearGaugeAnnotation : SampleView { SFLinearGauge linearGauge; static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; linearGauge.Frame = new CGRect(0, -30, this.Frame.Size.Width, this.Frame.Size.Height + 30); } base.LayoutSubviews(); } public LinearGaugeAnnotation() { this.BackgroundColor = UIColor.White; linearGauge = new SFLinearGauge(); linearGauge.BackgroundColor = UIColor.White; linearGauge.Header = new SFLinearLabel(); SFLinearGaugeAnnotation annotation1 = new SFLinearGaugeAnnotation(); annotation1.ScaleValue = 15; annotation1.ViewMargin = new CGPoint(0, 30); UIImageView image1 = new UIImageView(); image1.Frame = new CGRect(0, 0, 30, 30); image1.Image = UIImage.FromBundle("Low.png"); annotation1.View = image1; SFLinearGaugeAnnotation annotation2 = new SFLinearGaugeAnnotation(); annotation2.ScaleValue = 45; annotation2.ViewMargin = new CGPoint(0, 30); UIImageView image2 = new UIImageView(); image2.Frame = new CGRect(0, 0, 30, 30); image2.Image = UIImage.FromBundle("Moderate.png"); annotation2.View = image2; SFLinearGaugeAnnotation annotation3 = new SFLinearGaugeAnnotation(); annotation3.ScaleValue = 75; annotation3.ViewMargin = new CGPoint(0, 30); UIImageView image3 = new UIImageView(); image3.Frame = new CGRect(0, 0, 30, 30); image3.Image = UIImage.FromBundle("High.png"); annotation3.View = image3; SFLinearGaugeAnnotation annotation4 = new SFLinearGaugeAnnotation(); annotation4.ScaleValue = 15; annotation4.HorizontalViewAlignment = ViewAlignment.Center; annotation4.ViewMargin = new CGPoint(0, 80); UILabel label1 = new UILabel(); label1.Frame = new CGRect(0, 0, 30, 30); label1.Text = "Low"; label1.Font = UIFont.FromName("Helvetica", 12f); label1.TextColor = UIColor.FromRGB(48, 179, 45); annotation4.View = label1; SFLinearGaugeAnnotation annotation5 = new SFLinearGaugeAnnotation(); annotation5.ScaleValue = 45; annotation5.HorizontalViewAlignment = ViewAlignment.Center; annotation5.ViewMargin = new CGPoint(0, 80); UILabel label2 = new UILabel(); label2.Text = "Moderate"; label2.Frame = new CGRect(0, 0, 60, 50); label2.Font = UIFont.FromName("Helvetica", 12f); label2.TextColor = UIColor.FromRGB(255, 221, 0); annotation5.View = label2; SFLinearGaugeAnnotation annotation6 = new SFLinearGaugeAnnotation(); annotation6.ScaleValue = 75; annotation6.HorizontalViewAlignment = ViewAlignment.Center; annotation6.ViewMargin = new CGPoint(0, 80); UILabel label3 = new UILabel(); label3.Text = "High"; label3.Frame = new CGRect(0, 0, 30, 30); label3.Font = UIFont.FromName("Helvetica", 12f); label3.TextColor = UIColor.FromRGB(240, 62, 62); annotation6.View = label3; SFLinearGaugeAnnotation annotation7 = new SFLinearGaugeAnnotation(); annotation7.ScaleValue = 45; annotation7.HorizontalViewAlignment = ViewAlignment.Center; annotation7.ViewMargin = new CGPoint(0, -80); UILabel label4 = new UILabel(); label4.Frame = new CGRect(0, 0, 130, 175); label4.Text = "CPU Utilization"; //label4.Font = UIFont.FromName("Helvetica", 14f); label4.TextColor = UIColor.Black; annotation7.View = label4; linearGauge.Annotations.Add(annotation1); linearGauge.Annotations.Add(annotation2); linearGauge.Annotations.Add(annotation3); linearGauge.Annotations.Add(annotation4); linearGauge.Annotations.Add(annotation5); linearGauge.Annotations.Add(annotation6); linearGauge.Annotations.Add(annotation7); SFLinearScale scale = new SFLinearScale(); scale.Minimum = 0; scale.Maximum = 90; scale.ShowScaleLabel = false; scale.MinorTicksPerInterval = 0; scale.ScaleBarSize = 13; scale.ShowTicks = false; scale.ScaleBarColor = UIColor.Clear; SFLinearTickSettings major = new SFLinearTickSettings(); major.Length = 0; scale.MajorTickSettings = major; SFLinearRange range1 = new SFLinearRange(); range1.StartValue = 0; range1.EndValue = 30; range1.StartWidth = 60; range1.EndWidth = 60; range1.Color = UIColor.FromRGB(48, 179, 45); scale.Ranges.Add(range1); SFLinearRange range2 = new SFLinearRange(); range2.StartValue = 30; range2.EndValue = 60; range2.StartWidth = 60; range2.EndWidth = 60; range2.Color = UIColor.FromRGB(255, 221, 0); scale.Ranges.Add(range2); SFLinearRange range3 = new SFLinearRange(); range3.StartValue = 60; range3.EndValue = 90; range3.StartWidth = 60; range3.EndWidth = 60; range3.Color = UIColor.FromRGB(240, 62, 62); scale.Ranges.Add(range3); linearGauge.Scales.Add(scale); this.AddSubview(linearGauge); } } } <file_sep>/Android/SampleBrowser/Samples/RadialMenu/RoundButton.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Java.Lang; namespace SampleBrowser { internal class RoundButton : View ,View.IOnClickListener { internal Color fillColor; DoodleDraw doodleDraw; internal RoundButton(Context context,float height,float width,Color color,DoodleDraw doodle) : base(context) { SetWillNotDraw(false); this.height = height; this.width = width; fillColor = color; doodleDraw = doodle; Initialize(); } public RoundButton(Context context, IAttributeSet attrs) : base(context, attrs) { } public RoundButton(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { } RectF circle; internal void Initialize() { this.SetOnClickListener(this); circle = new RectF(0, 0, width, height); Invalidate(); } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); Paint buttonPaint = new Paint(PaintFlags.AntiAlias); if (circle != null) { buttonPaint.AntiAlias = true; buttonPaint.SetStyle(Paint.Style.Fill); buttonPaint.Color = fillColor; buttonPaint.Dither = true; canvas.DrawRoundRect(circle, 360, 360, buttonPaint); } } public void OnClick(View v) { if (doodleDraw != null) doodleDraw.drawColor = (v as RoundButton).fillColor; } float width, height; } } <file_sep>/Android/SampleBrowser/Samples/NavigationDrawer/readme.md The `SfNavigationDrawer` is a panel menu that comes out from the edge of the window and allows to have the contents in a hidden panel. It can be shown by swiping from any of the four screen edges or by demand. The following samples is available for navigation drawer to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](NavigationDrawer.cs)| It demonstrates that built-in drawer animations and positions in different sides.| <file_sep>/Forms/ListView/ListView/Samples/AutoFitContent/Model/BookInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewBookInfoRepository { #region Constructor public ListViewBookInfoRepository() { } #endregion #region Properties internal ObservableCollection<ListViewBookInfo> GetBookInfo() { var bookInfo = new ObservableCollection<ListViewBookInfo>(); for (int i = 0; i < BookNames.Count(); i++) { var book = new ListViewBookInfo() { BookName = BookNames[i], BookDescription = BookDescriptions[i], BookAuthor = BookAuthers[i], AuthorImage = "Book" + i + ".png" }; bookInfo.Add(book); } return bookInfo; } #endregion #region BookInfo string[] BookNames = new string[] { "Neural Networks Using C#", "C# Code Contracts", "Machine Learning Using C#", "Object-Oriented Programming in C#", "Visual Studio Code", "Android Programming", "iOS Succinctly", "Visual Studio 2015", "Xamarin.Forms", "Windows Store Apps", ".NET Core Succinctly", "Assembly Language", "SQL Server for C# Developers", "Entity Framework Code First", "Localization for .NET", "Developing Windows Services", "Data Structures", "Objective-C", "SciPy Programming", "Visual Studio 2017" }; string[] BookDescriptions = new string[] { "Neural networks are an exciting field of software development used to calculate outputs from input data.", "Code Contracts provide a way to convey code assumptions in your .NET applications. In C# Code Contracts Succinctly, author <NAME> explains how to use Code Contracts to validate logical correctness in code, how they can be integrated with abstract classes and interfaces, and even how they can be used to make writing documentation less painful.", "In Machine Learning Using C# Succinctly, you’ll learn several different approaches to applying machine learning to data analysis and prediction problems.", "Object-oriented programming is the de facto programming paradigm for many programming languages. Object-Oriented Programming in C# Succinctly provides an introduction to OOP for C# developers.", "Visual Studio Code is a powerful tool for editing code and serves as a complete environment for end-to-end programming. <NAME> Visual Studio Code Succinctly will guide readers to mastery of this valuable tool so that they can make full use of its features.", "<NAME> provides a useful overview of the Android application lifecycle.", "iOS Succinctly is for developers looking to step into the sometimes frightening world of iPhone and iPad app development. Written as the companion to Objective-C Succinctly, this e-book guides you from creating a simple, single page application to managing assets in a complex, multi-scene application.", "Microsoft Visual Studio 2015 is the new version of the widely-used integrated development environment for building modern, high-quality applications for a number of platforms such as Windows, the web, the cloud, and mobile devices.", "With the fragmented landscape of mobile device platforms, tools for creating cross-platform apps have sprung up as varied and numerous as apps themselves.", "Windows Store apps present a radical shift in Windows development.", "With .NET Core, cross-platform develop is easier and backward compatibility is no problem. Author <NAME> guides you through the fundamentals of .NET Core in his latest book, .NET Core Succinctly. Within its pages you will learn to harness this open-source, cloud-optimized port of the .NET Framework for modern apps. ", "Assembly language is as close to writing machine code as you can get without writing in pure hexadecimal.", "Developers of C# applications with a SQL Server database can learn to connect to a database using classic ADO.NET and look at different methods of developing databases using the Entity Framework.", "Follow author <NAME> as he introduces the newest development mode for Entity Framework, Code First.", "Learn to write applications that support different languages and cultures, with an emphasis on .NET development. With the help of author <NAME>, Localization for .NET Succinctly will help you become an effective developer in the global community. ", "Learn the basics of Windows Services and how to develop and deploy basic apps.", "Data Structures is your concise guide to skip lists, hash tables, heaps, priority queues, AVL trees, and B-trees.", "Objective-C Succinctly is the only book you need for getting started with Objective-C—the primary language beneath all Mac, iPad, and iPhone apps.", "James McCaffrey’s SciPy Programming Succinctly offers readers a quick, thorough grounding in knowledge of the Python open source extension SciPy. The SciPy library, accompanied by its interdependent NumPy, offers Python programmers advanced functions that work with arrays and matrices. Each section presents a complete sample program for programmers to experiment with, carefully chosen examples to best illustrate each function, and resources for further learning.", "The release of Visual Studio 2017 is another critical element in Microsoft’s pivot to the “any developer, any platform, any device”." }; string[] BookAuthers = new string[] { "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" }; #endregion } } <file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/DataGridPullToRefresh/DataGridPullToRefreshBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DataGridPullToRefreshBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Core; using Syncfusion.SfDataGrid.XForms; using Syncfusion.SfPullToRefresh.XForms; using Syncfusion.XForms.Themes; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the DataGridPullToRefreshBehaviors samples /// </summary> public class DataGridPullToRefreshBehaviors : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfPullToRefresh pullToRefresh; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt transitionType; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DataGridPullToRefreshViewModel viewModel; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type parameter named as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.viewModel = new DataGridPullToRefreshViewModel(); bindAble.BindingContext = this.viewModel; this.pullToRefresh = bindAble.FindByName<SfPullToRefresh>("pullToRefresh"); this.dataGrid = bindAble.FindByName<SfDataGrid>("dataGrid"); this.transitionType = bindAble.FindByName<PickerExt>("transitionType"); this.dataGrid.ItemsSource = this.viewModel.OrdersInfo; this.transitionType.Items.Add("SlideOnTop"); this.transitionType.Items.Add("Push"); this.transitionType.SelectedIndex = 0; this.transitionType.SelectedIndexChanged += this.OnSelectionChanged; this.pullToRefresh.Refreshing += this.PullToRefresh_Refreshing; this.pullToRefresh.Pulling += this.PullToRefresh_Pulling; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type parameter named as bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.transitionType.SelectedIndexChanged -= this.OnSelectionChanged; this.pullToRefresh.Refreshing -= this.PullToRefresh_Refreshing; this.pullToRefresh = null; this.dataGrid = null; this.transitionType = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Fired when pullToRefresh View is refreshed /// </summary> /// <param name="sender">PullToRefresh_Refreshing event sender</param> /// <param name="e">PullToRefresh_Refreshing event args</param> private async void PullToRefresh_Refreshing(object sender, EventArgs e) { this.pullToRefresh.IsRefreshing = true; await Task.Delay(1200); this.viewModel.ItemsSourceRefresh(); this.pullToRefresh.IsRefreshing = false; } /// <summary> /// Fired when pullToRefresh View is pulling /// </summary> /// <param name="sender">PullToRefresh_Pulling event sender</param> /// <param name="e">PullToRefresh_Pulling event args</param> private void PullToRefresh_Pulling(object sender, PullingEventArgs e) { ICollection<ResourceDictionary> mergedDictionaries = null; #if COMMONSB var parent = (sender as SfPullToRefresh).Parent; while (parent != null) { if (parent is ThemesPage) { mergedDictionaries = (parent as Page).Resources.MergedDictionaries; break; } parent = parent.Parent; } #else mergedDictionaries = (((sender as SfPullToRefresh).Parent as Grid).Parent as SampleView).Resources.MergedDictionaries; #endif var darkTheme = (mergedDictionaries != null) ? mergedDictionaries.OfType<DarkTheme>().FirstOrDefault() : null; if (darkTheme != null) { typeof(SfPullToRefresh).GetRuntimeProperties().FirstOrDefault(propertyName => propertyName.Name == "HasShadow").SetValue(this.pullToRefresh, false); } else { typeof(SfPullToRefresh).GetRuntimeProperties().FirstOrDefault(propertyName => propertyName.Name == "HasShadow").SetValue(this.pullToRefresh, true); } mergedDictionaries = null; } /// <summary> /// Fired when selected index is changed /// </summary> /// <param name="sender">OnSelectionChanged sender</param> /// <param name="e">OnSelectionChanged event args e</param> private void OnSelectionChanged(object sender, EventArgs e) { if (this.transitionType.SelectedIndex == 0) { this.pullToRefresh.TransitionMode = TransitionType.SlideOnTop; } else { this.pullToRefresh.TransitionMode = TransitionType.Push; } } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/SalesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SalesViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for Sales class. /// </summary> public class SalesViewModel { #region Field [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<SalesByDate> dailySalesDetails = null; #endregion #region Constructor /// <summary> /// Initializes a new instance of the SalesViewModel class. /// </summary> public SalesViewModel() { } #endregion #region ItemsSource /// <summary> /// Gets the value of DailySalesDetails /// </summary> public ObservableCollection<SalesByDate> DailySalesDetails { get { if (this.dailySalesDetails == null) { return new SalesRepository().GetSalesDetailsByDay(5); } else { return this.dailySalesDetails; } } } #endregion } } <file_sep>/Forms/Presentation/Presentation/Samples/Images/Images.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using SampleBrowser.Core; namespace SampleBrowser.Presentation { public partial class Images : SampleView { public Images() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { //if (!SampleBrowser.App.isUWP) { this.Description.FontSize = 13.5; } //else //{ // this.Description.FontSize = 13.5; // this.Content_2.FontSize = 13.5; //} this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Images.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Images.pptx"; #endif Assembly assembly = typeof(Images).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); #region Slide1 ISlide slide1 = presentation.Slides[0]; IShape shape1 = (IShape)slide1.Shapes[0]; shape1.Left = 1.27 * 72; shape1.Top = 0.56 * 72; shape1.Width = 9.55 * 72; shape1.Height = 5.4 * 72; ITextBody textFrame = shape1.TextBody; IParagraphs paragraphs = textFrame.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Left; ITextParts textParts = paragraph.TextParts; textParts.Add(); ITextPart textPart = textParts[0]; textPart.Text = "Essential Presentation "; textPart.Font.CapsType = TextCapsType.All; textPart.Font.FontName = "Calibri Light (Headings)"; textPart.Font.FontSize = 80; textPart.Font.Color = ColorObject.Black; #endregion #region Slide2 ISlide slide2 = presentation.Slides.Add(SlideLayoutType.ContentWithCaption); slide2.Background.Fill.FillType = FillType.Solid; slide2.Background.Fill.SolidFill.Color = ColorObject.White; //Adds shape in slide shape1 = (IShape)slide2.Shapes[0]; shape1.Left = 0.47 * 72; shape1.Top = 1.15 * 72; shape1.Width = 3.5 * 72; shape1.Height = 4.91 * 72; ITextBody textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe IParagraphs paragraphs1 = textFrame1.Paragraphs; IParagraph paragraph1 = paragraphs1.Add(); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Left; ITextPart textpart1 = paragraph1.AddTextPart(); textpart1.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph2 = paragraphs1.Add(); paragraph2.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph2.AddTextPart(); textpart1.Text = "Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph3 = paragraphs1.Add(); paragraph3.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph3.AddTextPart(); textpart1.Text = "Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph4 = paragraphs1.Add(); paragraph4.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph4.AddTextPart(); textpart1.Text = "Lorem tortor neque, purus taciti quis id. Elementum integer orci accumsan minim phasellus vel."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); slide2.Shapes.RemoveAt(1); slide2.Shapes.RemoveAt(1); //Adds picture in the shape resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.tablet.jpg"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.tablet.jpg"; #endif assembly = typeof(Images).GetTypeInfo().Assembly; fileStream = assembly.GetManifestResourceStream(resourcePath); slide2.Shapes.AddPicture(fileStream, 5.18 * 72, 1.15 * 72, 7.3 * 72, 5.31 * 72); fileStream.Dispose(); #endregion MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("ImagesSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("ImagesSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } } } <file_sep>/Android/SampleBrowser/Samples/Schedule/AgendaView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Schedule; using Com.Syncfusion.Schedule.Enums; using Java.Util; using Android.Graphics; namespace SampleBrowser { public class AgendaView : SamplePage, IDisposable { public AgendaView() { } private SfSchedule sfSchedule; public override View GetSampleContent(Context context) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; //creating instance for Schedule sfSchedule = new SfSchedule(context); sfSchedule.ScheduleView = ScheduleView.MonthView; MonthViewSettings month = new MonthViewSettings(); month.ShowAppointmentsInline = false; month.ShowAgendaView = true; sfSchedule.MonthViewSettings = month; //set the appointment collection GetAppointments(); sfSchedule.ItemsSource = appointmentCollection; linearLayout.AddView(sfSchedule); return linearLayout; } private List<string> subjectCollection = new List<string>(); private List<string> colorCollection = new List<string>(); private List<Calendar> startTimeCollection = new List<Calendar>(); private List<Calendar> endTimeCollection = new List<Calendar>(); private ScheduleAppointmentCollection appointmentCollection; //Creating appointments for ScheduleAppointmentCollection private void GetAppointments() { appointmentCollection = new ScheduleAppointmentCollection(); SetColors(); RandomNumbers(); SetSubjects(); SetStartTime(); SetEndTime(); var count = 0; for (int i = 0; i < 30; i++) { var scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[count]); scheduleAppointment.Subject = subjectCollection[count]; if (i < 10 && i >= 0) { scheduleAppointment.StartTime = startTimeCollection[count]; scheduleAppointment.EndTime = endTimeCollection[count]; count++; } else if (i < 20 && i >= 10) { var date = (Calendar)startTimeCollection[count].Clone(); var month = date.Get(CalendarField.Month); if (month == 12) { month = 1; } else { month = month + 1; } date.Set(CalendarField.Month, month); var endDate = (Calendar)endTimeCollection[count].Clone(); endDate.Set(CalendarField.Month, month); scheduleAppointment.StartTime = date; scheduleAppointment.EndTime = endDate; count++; } else if (i < 30 && i >= 20) { var date = (Calendar)startTimeCollection[count].Clone(); var month = date.Get(CalendarField.Month); if (month == 1) { month = 12; } else { month = month - 1; } date.Set(CalendarField.Month, month); var endDate = (Calendar)endTimeCollection[count].Clone(); endDate.Set(CalendarField.Month, month); scheduleAppointment.StartTime = date; scheduleAppointment.EndTime = endDate; count++; } if (count >= 10) { count = 0; } appointmentCollection.Add(scheduleAppointment); } } private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); } // adding colors collection private void SetColors() { colorCollection = new List<String>(); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FF339933"); colorCollection.Add("#FF00ABA9"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF339933"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF00ABA9"); } private List<int> randomNums = new List<int>(); private void RandomNumbers() { randomNums = new List<int>(); Java.Util.Random rand = new Java.Util.Random(); for (int i = 0; i < 10; i++) { int randomNum = rand.NextInt((15 - 9) + 1) + 9; randomNums.Add(randomNum); } } // adding StartTime collection private void SetStartTime() { startTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -5; i < 5; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count], 0, 0); startTimeCollection.Add(startTime); count++; } } // adding EndTime collection private void SetEndTime() { endTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -5; i < 5; i++) { Calendar endTime = (Calendar)currentDate.Clone(); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count] + 1, 0, 0); endTimeCollection.Add(endTime); count++; } } public void Dispose() { if (sfSchedule != null) { sfSchedule.Dispose(); sfSchedule = null; } } } }<file_sep>/Forms/Chart/Chart/Samples/HistogramChart/HistogramChart.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class HistogramChart : SampleView { public HistogramChart() { InitializeComponent(); if (Device.RuntimePlatform == Device.WPF) { Chart.ChartPadding = new Thickness(0, 0, 0, 10); } } } public class TooltipConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is List<object>) { return (value as List<object>).Count.ToString(); } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } public class TooltipLabelConverter : IValueConverter { int interval = 20; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is List<object>) { var data = value as List<object>; int x = 0; int index = (int)(data[0] as ChartDataModel).Value / interval; x = interval * index; string text = x.ToString() + "-" + (x + interval).ToString() + " : "; return text; } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } }<file_sep>/Forms/Chat/Chat/Samples/ViewModel/FlightBookingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Chat; using System.Collections.ObjectModel; using System.ComponentModel; namespace SampleBrowser.SfChat { /// <summary> /// A view model for flight booking sample. /// </summary> public class FlightBookingViewModel : INotifyPropertyChanged { /// <summary> /// current user of chat. /// </summary> private Author currentUser; /// <summary> /// bot author. /// </summary> private Author bot; /// <summary> /// Indicates the typing indicator visibility. /// </summary> private bool showTypingIndicator; /// <summary> /// used to check network connection state. /// </summary> private bool isConnectionnotEstablished; /// <summary> /// Chat typing indicator. /// </summary> private ChatTypingIndicator typingIndicator; /// <summary> /// chat conversation messages. /// </summary> private ObservableCollection<object> messages; /// <summary> /// used to define busy indicator visible state. /// </summary> private bool showBusyIndicator; /// <summary> /// Initializes a new instance of the <see cref="FlightBookingViewModel"/> class. /// </summary> public FlightBookingViewModel() { this.Messages = new ObservableCollection<object>(); this.Bot = new Author() { Name = "Barry", Avatar = "ChatRobot.png" }; this.ShowBusyIndicator = true; this.IsConnectionNotEstablished = false; this.BotService = new BotService(this); this.TypingIndicator = new ChatTypingIndicator(); this.TypingIndicator.Authors.Add(this.Bot); this.TypingIndicator.AvatarViewType = AvatarViewType.Image; this.TypingIndicator.Text = "Barry is typing ..."; this.CurrentUser = new Author() { Name = "Nancy", Avatar = "People_Circle16.png" }; } /// <summary> /// Gets or sets the Chat typing indicator value. /// </summary> public ChatTypingIndicator TypingIndicator { get { return this.typingIndicator; } set { this.typingIndicator = value; RaisePropertyChanged("TypingIndicator"); } } /// <summary> /// Gets or sets the message conversation. /// </summary> public ObservableCollection<object> Messages { get { return this.messages; } set { this.messages = value; } } /// <summary> /// Gets or sets the value indicating whether the typing indicator is visible or not. /// </summary> public bool ShowTypingIndicator { get { return this.showTypingIndicator; } set { this.showTypingIndicator = value; RaisePropertyChanged("ShowTypingIndicator"); } } /// <summary> /// Gets or sets the value indicating whether the busy indicator is visible or not. /// </summary> public bool ShowBusyIndicator { get { return this.showBusyIndicator; } set { this.showBusyIndicator = value; RaisePropertyChanged("ShowBusyIndicator"); } } /// <summary> /// Gets or sets the value indicating whether the internet connection is established or not. /// </summary> public bool IsConnectionNotEstablished { get { return this.isConnectionnotEstablished; } set { this.isConnectionnotEstablished = value; RaisePropertyChanged("IsConnectionNotEstablished"); } } /// <summary> /// Gets or sets the current user. /// </summary> public Author CurrentUser { get { return this.currentUser; } set { this.currentUser = value; RaisePropertyChanged("CurrentUser"); } } /// <summary> /// Get or sets the bot author. /// </summary> public Author Bot { get { return this.bot; } set { this.bot = value; RaisePropertyChanged("Bot"); } } /// <summary> /// Gets or sets the bot service. /// </summary> internal BotService BotService { get; set; } /// <summary> /// Property changed handler. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Occurs when property is changed. /// </summary> /// <param name="propName">changed property name</m> public void RaisePropertyChanged(string propName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } } } <file_sep>/Forms/DataForm/DataForm/Samples/ContactForm/ViewModel/ContactListViewModel.cs #region Copyright // <copyright file="ContactListViewModel.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using SampleBrowser.Core; using Syncfusion.ListView.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; /// <summary> /// Represents the view model of the list view in the contact forms. /// </summary> [Preserve(AllMembers = true)] public class ContactListViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// Represents a dynamic data collection of the contact information. /// </summary> private ObservableCollection<ContactInfo> contactsInfo; /// <summary> /// Represents the selected item of the contact information. /// </summary> private ContactInfo selectedItem; /// <summary> /// Represents a value indicating whether to refresh the layout. /// </summary> private bool refreshLayout = false; /// <summary> /// Represents a value indicating whether visible or not. /// </summary> private bool isVisible; /// <summary> /// Represents a value indicating whether the contact is new. /// </summary> private bool isNewContact; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ContactListViewModel"/> class. /// </summary> public ContactListViewModel() { this.GenerateSource(100); this.isVisible = true; this.RefreshCommand = new Command<object>(this.OnRefreshLayout); this.AddCommand = new Command<object>(this.OnAdd); this.BackCommand = new Command<object>(this.OnBack); this.EditAndDoneCommand = new Command<object>(this.OnEditAndDone); } #endregion /// <summary> /// Represents the method that will handle when a property is changed on a component. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Properties /// <summary> /// Gets or sets the contact information of the customer. /// </summary> public ObservableCollection<ContactInfo> ContactsInfo { get { return this.contactsInfo; } set { this.contactsInfo = value; } } /// <summary> /// Gets or sets the selected item in the contacts view. /// </summary> public ContactInfo SelectedItem { get { return this.selectedItem; } set { this.selectedItem = value; this.OnPropertyChanged("SelectedItem"); } } /// <summary> /// Gets or sets an ICommand implementation wrapping a refresh action. /// </summary> public Command<object> RefreshCommand { get; set; } /// <summary> /// Gets or sets an ICommand implementation wrapping a add action. /// </summary> public Command<object> AddCommand { get; set; } /// <summary> /// Gets or sets an ICommand implementation wrapping a edit and done action. /// </summary> public Command<object> BackCommand { get; set; } /// <summary> /// Gets or sets an ICommand implementation wrapping a edit and done action. /// </summary> public Command<object> EditAndDoneCommand { get; set; } /// <summary> /// Gets or sets a value indicating whether visible or not. /// </summary> public bool IsVisible { get { return this.isVisible; } set { this.isVisible = value; this.OnPropertyChanged("IsVisible"); } } /// <summary> /// Gets or sets a value indicating whether the contact is new. /// </summary> internal bool IsNewContact { get { return this.isNewContact; } set { this.isNewContact = value; this.OnPropertyChanged("IsNewContact"); } } /// <summary> /// Gets or sets a value indicating whether to refresh the layout. /// </summary> internal bool RefreshLayout { get { return this.refreshLayout; } set { this.refreshLayout = value; } } #endregion #region ItemSource /// <summary> /// Generates the source of the contact information repository. /// </summary> /// <param name="count">Represents the number of elements.</param> public void GenerateSource(int count) { ContactsInfoRepository contactRepository = new ContactsInfoRepository(); this.contactsInfo = contactRepository.GetContactDetails(count); } #endregion /// <summary> /// Occurs when property value is changed. /// </summary> /// <param name="propertyName">Represents the proeprty name.</param> private void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } /// <summary> /// Occurs when layout is refreshed. /// </summary> /// <param name="dataForm">DataForm object.</param> private void OnRefreshLayout(object dataForm) { this.refreshLayout = true; this.IsVisible = false; var dataFormLayout = dataForm as Syncfusion.XForms.DataForm.SfDataForm; dataFormLayout.RefreshLayout(); var grid = dataFormLayout.Parent as Grid; grid.RowDefinitions[2].Height = 0; } /// <summary> /// Occurs when new item is added in list view. /// </summary> /// <param name="listView">List view object.</param> private void OnAdd(object listView) { var sflistView = listView as Syncfusion.ListView.XForms.SfListView; var contactInfo = new ContactInfo() { ContactImage = new FontImageSource() { Glyph = "\ue72a", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.Black, } }; var viewModel = sflistView.BindingContext as ContactListViewModel; viewModel.SelectedItem = contactInfo as ContactInfo; this.refreshLayout = true; this.IsNewContact = true; sflistView.Navigation.PushAsync(new DataFormPage() { BindingContext = sflistView.BindingContext, Title = "Contact Form" }); } /// <summary> /// Occurs when back is pressed. /// </summary> /// <param name="grid">The corresponding layout object.</param> private void OnBack(object grid) { var dataFormGrid = grid as Grid; var dataForm = dataFormGrid.FindByName<Syncfusion.XForms.DataForm.SfDataForm>("dataForm"); var navigation = dataForm.Navigation; dataForm = null; navigation.PopAsync(); } /// <summary> /// Occurs after editing is done. /// </summary> /// <param name="grid">The corresponding layout object.</param> private void OnEditAndDone(object grid) { var dataFormGrid = grid as Grid; var dataForm = dataFormGrid.FindByName<Syncfusion.XForms.DataForm.SfDataForm>("dataForm"); var editButton = dataFormGrid.FindByName<Button>("editButton"); var contactLabel = dataFormGrid.FindByName<Button>("contactLabel"); if (dataForm.IsReadOnly) { dataForm.IsReadOnly = false; editButton.Text = "Done"; } else { var isValid = dataForm.Validate(); if (!isValid) { App.Current.MainPage.DisplayAlert("Alert", "Please enter valid details", "Ok"); return; } if (contactLabel.Text == "Add Contact") { var viewModel = dataForm.BindingContext as ContactListViewModel; viewModel.ContactsInfo.Add(viewModel.SelectedItem); } editButton.Text = "Edit"; dataForm.Commit(); dataForm.IsReadOnly = true; var navigation = dataForm.Navigation; dataForm = null; navigation.PopAsync(); } } } }<file_sep>/Forms/DatePicker/DatePicker/ViewModel/DatePickerTaskObject.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; namespace SampleBrowser.SfDatePicker { #region DatePickerTaskObject class /// <summary> /// DatePickerTaskObject Class /// </summary> public class DatePickerTaskObject : INotifyPropertyChanged { #region Members /// <summary> /// date Value /// </summary> private DateTime dateValue; /// <summary> /// description /// </summary> private string description; #endregion #region Properties /// <summary> /// Gets or sets the value for the Date Value /// </summary> public DateTime DateValue { get { return dateValue; } set { dateValue = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the value for the Description /// </summary> public string Description { get { return description; } set { description = value; this.NotifyPropertyChanged(); } } #endregion #region NotifyPropertyChanged /// <summary> /// Property changed event /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Notify Property Changed method /// </summary> /// <param name="propertyName">string value</param> private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } #endregion } <file_sep>/Forms/TreeMap/TreeMap/Samples/TreeMapCustomization/TreeMapCustomizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeMap { [Preserve(AllMembers = true)] public class OlymicMedalsViewModel { public ObservableCollection<OlympicMedals> OlympicMedalsDetails { get; set; } public OlymicMedalsViewModel() { this.OlympicMedalsDetails = new ObservableCollection<OlympicMedals>(); this.OlympicMedalsDetails.Add(new OlympicMedals { Country = "US", GameName = "Swimming", GoldMedals = 16, SilverMedals = 9, BronzeMedals = 6, TotalMedals = 31, ImageName = "\ue71f" }); this.OlympicMedalsDetails.Add(new OlympicMedals { Country = "US", GameName = "Track and Field", GoldMedals = 9, SilverMedals = 13, BronzeMedals = 7, TotalMedals = 29, ImageName = "\ue70f" }); this.OlympicMedalsDetails.Add(new OlympicMedals { Country = "US", GameName = "Gymnastics", GoldMedals = 3, SilverMedals = 1, BronzeMedals = 2, TotalMedals = 6, ImageName = "\ue700" }); this.OlympicMedalsDetails.Add(new OlympicMedals { Country = "US", GameName = "Boxing", GoldMedals = 1, SilverMedals = 0, BronzeMedals = 1, TotalMedals = 2, ImageName = "\ue724" }); this.OlympicMedalsDetails.Add(new OlympicMedals { Country = "US", GameName = "Cycling", GoldMedals = 1, SilverMedals = 2, BronzeMedals = 1, TotalMedals = 4, ImageName = "\ue701" }); this.OlympicMedalsDetails.Add(new OlympicMedals { Country = "US", GameName = "Shooting", GoldMedals = 3, SilverMedals = 0, BronzeMedals = 1, TotalMedals = 4, ImageName = "\ue70d" }); this.OlympicMedalsDetails.Add(new OlympicMedals { Country = "US", GameName = "Wrestling", GoldMedals = 2, SilverMedals = 0, BronzeMedals = 2, TotalMedals = 4, ImageName = "\ue702" }); this.OlympicMedalsDetails.Add(new OlympicMedals { Country = "US", GameName = "Diving", GoldMedals = 1, SilverMedals = 1, BronzeMedals = 2, TotalMedals = 4, ImageName = "\ue705" }); } } } <file_sep>/Forms/ImageEditor/ImageEditor.iOS/FileStore.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using Photos; using System.Collections.Generic; using SampleBrowser.SfImageEditor.iOS; using Xamarin.Forms; [assembly: Dependency(typeof(FileToStream))] namespace SampleBrowser.SfImageEditor.iOS { public class FileStore : IFileStore { public string GetFilePath() { return "image.png"; } } public class FileToStream : IFileToStream { Dictionary<string, Stream> dictionary = new Dictionary<string, Stream>(); byte[] byteArray; public void LoadSampleStream(string filename,SerializationModel model ) { try { string[] str = filename.Split('/'); PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null); PHAsset asset = assetResult.firstObject as PHAsset; Stream stream= new MemoryStream(); PHImageManager.DefaultManager.RequestImageData(asset, null, (data, dataUti, orientation, info) => { byteArray = data.ToArray(); Stream streamm = new MemoryStream(byteArray); dictionary.Add(filename, streamm); model.Location = filename; }); } catch (Exception) { } } public Stream LoadSampleStream(string fileName) { if (dictionary != null) { Stream imageStream = new MemoryStream(byteArray); return imageStream; } else return null; } } } <file_sep>/Android/SampleBrowser/Samples/Presentation/Charts.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using Syncfusion.OfficeChart; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Xml; namespace SampleBrowser { public partial class ChartsPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to create a pie chart in PowerPoint presentation."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Presentation"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { MemoryStream stream = new MemoryStream(); //Opens the existing presentation stream. using (IPresentation presentation = Syncfusion.Presentation.Presentation.Create()) { ISlide slide = presentation.Slides.Add(SlideLayoutType.TitleOnly); IParagraph paragraph = ((IShape)slide.Shapes[0]).TextBody.Paragraphs.Add(); //Apply center alignment to the paragraph paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; //Add slide title ITextPart textPart = paragraph.AddTextPart("Northwind Management Report"); textPart.Font.Color = ColorObject.FromArgb(46, 116, 181); //Get chart data from xml file List<ProductDetails> Products = LoadXMLData(); //Add a new chart to the presentation slide IPresentationChart chart = slide.Charts.AddChart(44.64, 133.2, 870.48, 380.16); //Set chart type chart.ChartType = OfficeChartType.Pie; //Set chart title chart.ChartTitle = "Best Selling Products"; //Set chart properties font name and size chart.ChartTitleArea.FontName = "Calibri (Body)"; chart.ChartTitleArea.Size = 14; for (int i = 0; i < Products.Count; i++) { ProductDetails product = Products[i]; chart.ChartData.SetValue(i + 2, 1, product.ProductName); chart.ChartData.SetValue(i + 2, 2, product.Sum); } //Create a new chart series with the name “Sales” AddSeriesForChart(chart); //Setting the font size of the legend. chart.Legend.TextArea.Size = 14; //Setting background color chart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); chart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); chart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 11, 1]; //Saves the presentation instance to the stream. presentation.Save(stream); } stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("Charts.pptx", "application/powerpoint", stream, m_context); } } #region Helper Methods /// <summary> /// Gets list of product details from an XML file /// </summary> /// <returns></returns> private List<ProductDetails> LoadXMLData() { List<ProductDetails> Products = new List<ProductDetails>(); ProductDetails productDetails; Assembly assembly = Assembly.GetExecutingAssembly(); Stream productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.Presentation.Templates.Products.xml"); XmlReader reader = XmlReader.Create(productXMLStream); string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Products": while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "SNO": reader.Read(); serailNo = reader.Value; break; case "ProductName": reader.Read(); productName = reader.Value; break; case "Sum": reader.Read(); sum = reader.Value; productDetails = new ProductDetails(int.Parse(serailNo), productName, decimal.Parse(sum)); Products.Add(productDetails); break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Products") break; } break; } } } return Products; } /// <summary> /// Adds the series for the chart. /// </summary> /// <param name="chart">Represents the chart instance from the presentation.</param> private void AddSeriesForChart(IPresentationChart chart) { //Add a series for the chart. IOfficeChartSerie series = chart.Series.Add("Sales"); series.Values = chart.ChartData[2, 2, 11, 2]; //Setting data label series.DataPoints.DefaultDataPoint.DataLabels.IsValue = true; series.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside; series.DataPoints.DefaultDataPoint.DataLabels.Size = 14; } #endregion HelperMethods } #region Helper class /// <summary> /// Specifies the Product details /// </summary> public class ProductDetails { #region fields private int m_serialNo; private string m_productName; private decimal m_sum; #endregion #region properties /// <summary> /// Gets or sets the serial number of the product. /// </summary> public int SNO { get { return m_serialNo; } set { m_serialNo = value; } } /// <summary> /// Gets or sets the name of the product. /// </summary> public string ProductName { get { return m_productName; } set { m_productName = value; } } /// <summary> /// Gets or sets the sum value of the product. /// </summary> public decimal Sum { get { return m_sum; } set { m_sum = value; } } #endregion #region Constructor /// <summary> /// Constructor for the ProductDetails to create a new instance. /// </summary> /// <param name="serialNumber">Represents the serial number of the product.</param> /// <param name="productName">Represents the product name.</param> /// <param name="sum">Represents the sum value of the product.</param> public ProductDetails(int serialNumber, string productName, decimal sum) { SNO = serialNumber; ProductName = productName; Sum = Math.Round(sum, 3); } #endregion } #endregion } <file_sep>/Android/SampleBrowser/Samples/PDFViewer/StampSelectionView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { internal class StampSelectionView : FrameLayout { FrameLayout root; LinearLayout linear, stampTitle, bottomBar; Button backButton, closeButton; TextView title; ImageButton approved, notApproved, draft, expired, confidential; CustomToolBarPdfViewerDemo mainPage; internal bool isShowing; internal StampSelectionView(Context context, CustomToolBarPdfViewerDemo mainPage) : base(context) { this.mainPage = mainPage; LayoutInflater inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService); root = (FrameLayout)inflater.Inflate(Resources.GetLayout(Resource.Layout.StampViewList), this, true); linear = root.FindViewById<LinearLayout>(Resource.Id.linearView); backButton = root.FindViewById<Button>(Resource.Id.backButton); stampTitle = root.FindViewById<LinearLayout>(Resource.Id.stampTitlebar); bottomBar = root.FindViewById<LinearLayout>(Resource.Id.bottomBar); closeButton = root.FindViewById<Button>(Resource.Id.closeBtn); closeButton.Click += CloseButton_Click; closeButton.SetBackgroundColor(Color.Transparent); closeButton.SetTextColor(mainPage.fontColor); backButton.Typeface = mainPage.bookmarkFont; backButton.Click += BackButton_Click; title = root.FindViewById<TextView>(Resource.Id.title); linear.SetBackgroundColor(Color.White); if (mainPage.IsDeviceTablet) { LayoutParams newParams = new LayoutParams(600, 350); newParams.Gravity = GravityFlags.Center; backButton.Visibility = ViewStates.Gone; LayoutParams titleLayoutParams = new LayoutParams(LayoutParams.MatchParent, LayoutParams.WrapContent); titleLayoutParams.Gravity = GravityFlags.Center; title.LayoutParameters = titleLayoutParams; linear.LayoutParameters = newParams; title.SetTextColor(Color.Black); title.Text = "Choose Stamp"; } else { bottomBar.Visibility = ViewStates.Invisible; stampTitle.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 150); title.SetTextColor(mainPage.fontColor); } approved = root.FindViewById<ImageButton>(Resource.Id.approved); approved.SetBackgroundColor(Color.Transparent); approved.Click += StampChosen; notApproved = root.FindViewById<ImageButton>(Resource.Id.notapproved); notApproved.SetBackgroundColor(Color.Transparent); notApproved.Click += StampChosen; draft = root.FindViewById<ImageButton>(Resource.Id.draft); draft.SetBackgroundColor(Color.Transparent); draft.Click += StampChosen; expired = root.FindViewById<ImageButton>(Resource.Id.expired); expired.SetBackgroundColor(Color.Transparent); expired.Click += StampChosen; confidential = root.FindViewById<ImageButton>(Resource.Id.confidential); confidential.SetBackgroundColor(Color.Transparent); confidential.Click += StampChosen; } private void CloseButton_Click(object sender, EventArgs e) { mainPage.m_bottomToolbars.Visibility = ViewStates.Visible; mainPage.m_topToolbars.Visibility = ViewStates.Visible; Hide(); } private void StampChosen(object sender, EventArgs e) { ImageView stamp = new ImageView(Context); ImageButton button = sender as ImageButton; if (button == approved) stamp.SetImageResource(Resource.Drawable.Approved); else if (button == notApproved) stamp.SetImageResource(Resource.Drawable.NotApproved); else if (button == draft) stamp.SetImageResource(Resource.Drawable.Draft); else if (button == confidential) stamp.SetImageResource(Resource.Drawable.Confidential); else if (button == expired) stamp.SetImageResource(Resource.Drawable.Expired); stamp.SetAdjustViewBounds(false); stamp.SetScaleType(ImageView.ScaleType.FitXy); stamp.Layout(100, 100, 300, 60); mainPage.pdfViewerControl.AddStamp(stamp, mainPage.pdfViewerControl.PageNumber); mainPage.m_bottomToolbars.Visibility = ViewStates.Visible; mainPage.m_topToolbars.Visibility = ViewStates.Visible; Hide(); } private void Hide() { if (mainPage.IsDeviceTablet) mainPage.popup.Dismiss(); else (Parent as LinearLayout).RemoveView(this); isShowing = false; } private void BackButton_Click(object sender, EventArgs e) { mainPage.m_bottomToolbars.Visibility = ViewStates.Visible; mainPage.m_topToolbars.Visibility = ViewStates.Visible; Hide(); } } }<file_sep>/Forms/PDF/PDF/Samples/HtmlTextElement/HtmlTextElement.Xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Xamarin.Forms; using System.IO; using SampleBrowser.Core; using System.Reflection; namespace SampleBrowser.PDF { public partial class HtmlTextElement : SampleView { public HtmlTextElement() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { PdfDocument doc = new PdfDocument(); //Add a page PdfPage page = doc.Pages.Add(); PdfSolidBrush brush = new PdfSolidBrush(Syncfusion.Drawing.Color.Black); PdfPen pen = new PdfPen(Syncfusion.Drawing.Color.Black, 1f); //Create font PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 11.5f); PdfFont heading = new PdfStandardFont(PdfFontFamily.TimesRoman, 12, PdfFontStyle.Bold); font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f); page.Graphics.DrawString("Create, Read, and Edit PDF Files from C#, VB.NET", heading, PdfBrushes.Black, new RectangleF(0, 0, page.GetClientSize().Width, 20), new PdfStringFormat(PdfTextAlignment.Center)); string longText = "The <b> Syncfusion Essential PDF </b> is a feature-rich and high-performance .NET PDF library that allows you to add robust PDF functionalities to any .NET application." + "It allows you to create, read, and edit PDF documents programmatically without Adobe dependencies. This library also offers functionality to <font color='#0000F8'> merge, split, stamp, form-fill, compress, and secure PDF files.</font>" + "<br/><br/><font color='#FF3440'><b>1. Secure your PDF with advanced encryption, digital signatures, and redaction.</b></font>" + "<br/><br/><font color='#FF9E4D'><b>2. Extract text and images from your PDF files.</b></font>" + "<br/><br/><font color='#4F6200'><b>3. Top features: forms, tables, barcodes; stamp, split, and merge PDFs.</b></font>"; //Rendering HtmlText PdfHTMLTextElement richTextElement = new PdfHTMLTextElement(longText, font, brush); // Formatting Layout PdfLayoutFormat format = new PdfLayoutFormat(); format.Layout = PdfLayoutType.OnePage; //Drawing htmlString richTextElement.Draw(page, new RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height), format); MemoryStream stream = new MemoryStream(); //Save the PDF document. doc.Save(stream); //Close the PDF document. doc.Close(); stream.Position = 0; if ( Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("HtmlTextElement.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("HtmlTextElement.pdf", "application/pdf", stream); } } } <file_sep>/iOS/SampleBrowser/Samples/Schedule/AppointmentEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using nuint = System.Int32; using System.Drawing; #endif namespace SampleBrowser { public class AppointmentEditor : SampleView { private SFSchedule schedule; private static UIView editor; private static UIButton buttonCancel; private static UIButton buttonSave; private static UITextView labelSubject; private static UITextView labelLocation; private static UILabel labelStarts; private static UILabel labelEnds; private static UIButton buttonStartDate; private static UIButton buttonEndDate; private static UIDatePicker pickerStartDate; private static UIDatePicker pickerEndDate; private static UIButton doneButton; private static ScheduleAppointment selectedAppointment; private static int indexOfAppointment; //UITapGestureRecognizer tapGesture; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public AppointmentEditor() { schedule = new SFSchedule(); editor = new UIView(); schedule.CellTapped += Schedule_ScheduleTapped; schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; schedule.ItemsSource = CreateAppointments(); CreateEditor(); this.AddSubview(schedule); schedule.Hidden = false; editor.Hidden = true; this.AddSubview(editor); // control = this; } private void Schedule_ScheduleTapped(object sender, CellTappedEventArgs e) { editor.Hidden = false; schedule.Hidden = true; indexOfAppointment = -1; if (e.ScheduleAppointment != null) { for (int i = 0; i < (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>).Count; i++) { if ((schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[i] == e.ScheduleAppointment) { indexOfAppointment = int.Parse(i.ToString()); break; } } selectedAppointment = e.ScheduleAppointment; labelSubject.Text = selectedAppointment.Subject; labelLocation.Text = selectedAppointment.Location; String startDate = DateTime.Parse(selectedAppointment.StartTime.ToString()).ToString(); buttonStartDate.SetTitle(startDate, UIControlState.Normal); pickerStartDate.SetDate(selectedAppointment.StartTime, true); String endDate = DateTime.Parse(selectedAppointment.EndTime.ToString()).ToString(); buttonEndDate.SetTitle(endDate, UIControlState.Normal); pickerEndDate.SetDate(selectedAppointment.EndTime, true); editor.EndEditing(true); } else { List<UIColor> colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); labelSubject.Text = "Subject"; labelLocation.Text = "Location"; String startDate = DateTime.Parse(e.Date.ToString()).ToString(); pickerStartDate.SetDate(e.Date, true); buttonStartDate.SetTitle(startDate, UIControlState.Normal); String endDate = DateTime.Parse(e.Date.AddSeconds(3600).ToString()).ToString(); pickerEndDate.SetDate(e.Date.AddSeconds(3600), true); buttonEndDate.SetTitle(endDate, UIControlState.Normal); } } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = new CGRect(Frame.X, 0, Frame.Width, Frame.Height); } nfloat yMargin = nfloat.Parse((this.Frame.Height * 0.1).ToString()); nfloat xMargin = nfloat.Parse((this.Frame.Width * 0.1).ToString()); nfloat elementWidth = nfloat.Parse((this.Frame.Width - (xMargin * 2)).ToString()); buttonCancel.Frame = new CGRect(20, yMargin, 200, 30); buttonSave.Frame = new CGRect(this.Frame.Width - 220, yMargin, 200, 30); labelSubject.Frame = new CGRect(xMargin, yMargin * 2, elementWidth, 30); labelLocation.Frame = new CGRect(xMargin, yMargin * 3, elementWidth, 30); labelStarts.Frame = new CGRect(xMargin, yMargin * 4, elementWidth, 30); buttonStartDate.Frame = new CGRect(xMargin, yMargin * 5, elementWidth, 30); labelEnds.Frame = new CGRect(xMargin, yMargin * 6, elementWidth, 30); buttonEndDate.Frame = new CGRect(xMargin, yMargin * 7, elementWidth, 30); pickerStartDate.Frame = new CGRect(xMargin, yMargin * 4, elementWidth, 200); pickerEndDate.Frame = new CGRect(xMargin, yMargin * 4, elementWidth, 200); doneButton.Frame = new CGRect(xMargin, yMargin * 4, elementWidth, 30); base.LayoutSubviews(); } private void CreateEditor() { buttonCancel = new UIButton(); buttonSave = new UIButton(); labelSubject = new UITextView(); labelLocation = new UITextView(); labelEnds = new UILabel(); labelStarts = new UILabel(); buttonStartDate = new UIButton(); buttonEndDate = new UIButton(); pickerStartDate = new UIDatePicker(); pickerEndDate = new UIDatePicker(); doneButton = new UIButton(); //cancel button buttonCancel.SetTitle("Cancel", UIControlState.Normal); buttonCancel.SetTitleColor(UIColor.Blue, UIControlState.Normal); buttonCancel.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; buttonCancel.TouchUpInside += (object sender, EventArgs e) => { editor.Hidden = true; schedule.Hidden = false; editor.EndEditing(true); }; //save button buttonSave.SetTitle("Save", UIControlState.Normal); buttonSave.SetTitleColor(UIColor.Blue, UIControlState.Normal); buttonSave.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; buttonSave.TouchUpInside += (object sender, EventArgs e) => { if (indexOfAppointment != -1) { (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(indexOfAppointment.ToString())].Subject = (NSString)labelSubject.Text; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(indexOfAppointment.ToString())].Location = (NSString)labelLocation.Text; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(indexOfAppointment.ToString())].StartTime = pickerStartDate.Date; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(indexOfAppointment.ToString())].EndTime = pickerEndDate.Date; } else { ScheduleAppointment appointment = new ScheduleAppointment(); appointment.Subject = (NSString)labelSubject.Text; appointment.Location = (NSString)labelLocation.Text; appointment.StartTime = pickerStartDate.Date; appointment.EndTime = pickerEndDate.Date; appointment.AppointmentBackground = UIColor.FromRGB(0xA2, 0xC1, 0x39); (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>).Add(appointment); } editor.Hidden = true; schedule.Hidden = false; schedule.ReloadData(); editor.EndEditing(true); }; //subject label labelSubject.TextColor = UIColor.Black; labelSubject.TextAlignment = UITextAlignment.Left; labelSubject.Layer.CornerRadius = 8; labelSubject.Layer.BorderWidth = 2; labelSubject.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //location label labelLocation.TextColor = UIColor.Black; labelLocation.TextAlignment = UITextAlignment.Left; labelLocation.Layer.CornerRadius = 8; labelLocation.Layer.BorderWidth = 2; labelLocation.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //starts time labelStarts.Text = "Start Time :"; labelStarts.TextColor = UIColor.Black; buttonStartDate.SetTitle("Start time", UIControlState.Normal); buttonStartDate.SetTitleColor(UIColor.Blue, UIControlState.Normal); buttonStartDate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; buttonStartDate.TouchUpInside += (object sender, EventArgs e) => { pickerStartDate.Hidden = false; doneButton.Hidden = false; labelEnds.Hidden = true; buttonEndDate.Hidden = true; buttonStartDate.Hidden = true; labelStarts.Hidden = true; editor.EndEditing(true); }; //end time labelEnds.Text = "End Time :"; labelEnds.TextColor = UIColor.Black; //end date buttonEndDate.SetTitle("End time", UIControlState.Normal); buttonEndDate.SetTitleColor(UIColor.Blue, UIControlState.Normal); buttonEndDate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; buttonEndDate.TouchUpInside += (object sender, EventArgs e) => { pickerEndDate.Hidden = false; doneButton.Hidden = false; labelEnds.Hidden = true; buttonEndDate.Hidden = true; buttonStartDate.Hidden = true; labelStarts.Hidden = true; editor.EndEditing(true); }; //date and time pickers pickerStartDate.Hidden = true; pickerEndDate.Hidden = true; //done button doneButton.SetTitle("Done", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Blue, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += (object sender, EventArgs e) => { pickerStartDate.Hidden = true; pickerEndDate.Hidden = true; doneButton.Hidden = true; labelEnds.Hidden = false; buttonEndDate.Hidden = false; buttonStartDate.Hidden = false; labelStarts.Hidden = false; String _sDate = DateTime.Parse(pickerStartDate.Date.ToString()).ToString(); buttonStartDate.SetTitle(_sDate, UIControlState.Normal); String _eDate = DateTime.Parse(pickerEndDate.Date.ToString()).ToString(); buttonEndDate.SetTitle(_eDate, UIControlState.Normal); editor.EndEditing(true); }; buttonCancel.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 10, 100, 30); buttonSave.Frame = new CGRect(100, this.Frame.Y + 10, 300, 30); labelSubject.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 50, 300, 30); labelLocation.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 90, 300, 30); labelStarts.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 140, 300, 30); buttonStartDate.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, 300, 30); labelEnds.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 220, 300, 30); buttonEndDate.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 260, 300, 30); pickerStartDate.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, 300, 30); pickerEndDate.Frame = new CGRect(100, this.Frame.Y + 180, 300, 30); pickerEndDate.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, 300, 30); doneButton.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, 300, 30); doneButton.Hidden = true; editor.Add(buttonCancel); editor.Add(buttonSave); editor.Add(labelSubject); editor.Add(labelLocation); editor.Add(labelStarts); editor.Add(buttonStartDate); editor.Add(labelEnds); editor.Add(buttonEndDate); editor.Add(pickerEndDate); editor.Add(pickerStartDate); editor.Add(doneButton); } private ObservableCollection<ScheduleAppointment> CreateAppointments() { NSDate today = new NSDate(); SetColors(); SetSubjects(); ObservableCollection<ScheduleAppointment> appCollection = new ObservableCollection<ScheduleAppointment>(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)subjectCollection[i]; appointment.AppointmentBackground = colorCollection[i]; appCollection.Add(appointment); } return appCollection; } private List<String> subjectCollection; private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); } // adding colors collection private List<UIColor> colorCollection; private void SetColors() { colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0xF0, 0x96, 0x09)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); } } }<file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/AlertViewDelegate.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Foundation; using Syncfusion.SfPdfViewer.iOS; using UIKit; namespace SampleBrowser { internal class AlertViewDelegate : UIAlertViewDelegate { SfPdfViewer pdfviewer; UIAlertView uiAlertView; UIAlertView alert; NSObject nsObject; public AlertViewDelegate(SfPdfViewer pdfviewerControl) { pdfviewer = pdfviewerControl; } public override bool ShouldEnableFirstOtherButton(UIAlertView alertView) { return alertView.GetTextField(0).Text.Length > 0; } public override void Clicked(UIAlertView alertview, nint buttonIndex) { uiAlertView = alertview; if (buttonIndex != alertview.CancelButtonIndex) { alertview.GetTextField(0).ResignFirstResponder(); int pageNum = 0; if (int.TryParse(alertview.GetTextField(0).Text, out pageNum) && pageNum > 0 && (pageNum <= pdfviewer.PageCount)) { pdfviewer.GoToPage(pageNum); } else { alert = new UIAlertView(); alert.AlertViewStyle = UIAlertViewStyle.Default; alert.AddButton("OK"); alert.Title = "Invalid Page Number"; } } nsObject=NSNotificationCenter.DefaultCenter.AddObserver((NSString)"UIKeyboardDidHideNotification", KeyboardDidHide); } void KeyboardDidHide(NSNotification obj) { int input = 0; if (!(int.TryParse(uiAlertView.GetTextField(0).Text, out input) && input > 0 && (input <= pdfviewer.PageCount))) { if (alert != null) { alert.Show(); } } NSNotificationCenter.DefaultCenter.RemoveObserver(nsObject); } public override void Presented(UIAlertView alertView) { UITextRange textRange = alertView.GetTextField(0).SelectedTextRange; alertView.GetTextField(0).SelectAll(null); alertView.GetTextField(0).SelectedTextRange = textRange; } } } <file_sep>/Forms/Presentation/Presentation/Samples/Charts/Charts.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using Syncfusion.OfficeChart; using System.Xml.Linq; using SampleBrowser.Core; namespace SampleBrowser.Presentation { [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public partial class Charts : SampleView { public Charts() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { MemoryStream stream = new MemoryStream(); //Create a Presentation instance using (IPresentation presentation = Syncfusion.Presentation.Presentation.Create()) { //Add a blank slide to the Presentation ISlide slide = presentation.Slides.Add(SlideLayoutType.TitleOnly); //Add a empty paragraph to the slide IParagraph paragraph = ((IShape)slide.Shapes[0]).TextBody.Paragraphs.Add(); //Apply center alignment to the paragraph paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; //Add slide title ITextPart textPart = paragraph.AddTextPart("Northwind Management Report"); textPart.Font.Color = ColorObject.FromArgb(46, 116, 181); //Get chart data from xml file List<ProductDetails> Products = LoadXMLData(); //Add a new chart to the presentation slide IPresentationChart chart = slide.Charts.AddChart(44.64, 133.2, 870.48, 380.16); //Set chart type chart.ChartType = OfficeChartType.Pie; //Set chart title chart.ChartTitle = "Best Selling Products"; //Set chart properties font name and size chart.ChartTitleArea.FontName = "Calibri (Body)"; chart.ChartTitleArea.Size = 14; //Itterate and set the values to chart for (int i = 0; i < Products.Count; i++) { ProductDetails product = Products[i]; chart.ChartData.SetValue(i + 2, 1, product.ProductName); chart.ChartData.SetValue(i + 2, 2, product.Sum); } //Create a new chart series with the name �Sales� AddSeriesForChart(chart); //Set the font size of the legend. chart.Legend.TextArea.Size = 14; //Set the color formatting to the chart chart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); chart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); chart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 11, 1]; //Save the presentation instance to a stream. presentation.Save(stream); } stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("ChartsSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("ChartsSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } #region Helper Methods /// <summary> /// Gets list of product details from an XML file /// </summary> /// <returns></returns> private List<ProductDetails> LoadXMLData() { XDocument productXml; List<ProductDetails> Products = new List<ProductDetails>(); ProductDetails productDetails; //Load XML file Assembly assembly = typeof(Charts).GetTypeInfo().Assembly; Stream productXMLStream=null; #if COMMONSB productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.Presentation.Samples.Templates.Products.xml"); #else productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Presentation.Samples.Templates.Products.xml"); #endif productXml = XDocument.Load(productXMLStream); //Get list of product details IEnumerable<XElement> productElements = from product in productXml.Descendants("Product") select product; string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; foreach (XElement element in productElements) { foreach (XElement child in element.Descendants()) { var childElement = element.Element(child.Name); if (childElement != null) { string value = childElement.Value; string elementName = child.Name.ToString(); switch (elementName) { case "SNO": serailNo = value; break; case "ProductName": productName = value; break; case "Sum": sum = value; break; } } } productDetails = new ProductDetails(int.Parse(serailNo), productName, decimal.Parse(sum)); Products.Add(productDetails); } return Products; } /// <summary> /// Adds the series for the chart. /// </summary> /// <param name="chart">Represents the chart instance from the presentation.</param> private void AddSeriesForChart(IPresentationChart chart) { //Add a series for the chart. IOfficeChartSerie series = chart.Series.Add("Sales"); series.Values = chart.ChartData[2, 2, 11, 2]; //Setting data label series.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside; series.DataPoints.DefaultDataPoint.DataLabels.Size = 14; series.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true; } #endregion HelperMethods } #region Helper class /// <summary> /// Specifies the Product details /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public class ProductDetails { #region fields private int m_serialNo; private string m_productName; private decimal m_sum; #endregion #region properties /// <summary> /// Gets or sets the serial number of the product. /// </summary> public int SNO { get { return m_serialNo; } set { m_serialNo = value; } } /// <summary> /// Gets or sets the name of the product. /// </summary> public string ProductName { get { return m_productName; } set { m_productName = value; } } /// <summary> /// Gets or sets the sum value of the product. /// </summary> public decimal Sum { get { return m_sum; } set { m_sum = value; } } #endregion #region Constructor /// <summary> /// Constructor for the ProductDetails to create a new instance. /// </summary> /// <param name="serialNumber">Represents the serial number of the product.</param> /// <param name="productName">Represents the product name.</param> /// <param name="sum">Represents the sum value of the product.</param> public ProductDetails(int serialNumber, string productName, decimal sum) { SNO = serialNumber; ProductName = productName; Sum = Math.Round(sum, 3); } #endregion } #endregion } <file_sep>/iOS/SampleBrowser/Resources/Samples/Popup/TicketInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using UIKit; namespace SampleBrowser { public class TicketInfoRepository { public TicketInfoRepository() { } #region GetTicketDetails public ObservableCollection<TicketBookingInfo> GetDetails() { ObservableCollection<TicketBookingInfo> ticketDetails = new ObservableCollection<TicketBookingInfo>(); return PopulateList(ticketDetails); } #endregion private ObservableCollection<TicketBookingInfo> PopulateList(ObservableCollection<TicketBookingInfo> items) { items = new ObservableCollection<TicketBookingInfo>(); items.Add(new TicketBookingInfo() { TheaterName = "ABC Cinemas Dolby Atmos", TheaterLocation = "No.15, 12th Main Road, Sector 1", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "10:00 AM", Timing2 = "4:00 PM", MovieName = "A-Team", Cast = "<NAME> | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie1.png") }); items.Add(new TicketBookingInfo() { TheaterName = "XYZ Theater 4K Dolby Atmos", TheaterLocation = "No.275, 3rd Cross Road,Area 27", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "11:00 AM", Timing2 = "6:00 PM", MovieName = "Conjuring 2", Cast = "Vera Farmiga | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie2.png") }); items.Add(new TicketBookingInfo() { TheaterName = "QWERTY Theater", TheaterLocation = "No.275, 3rd Cross Road,Sector North", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "10:30 AM", MovieName = "Insidious 2", Cast = "<NAME> | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie3.png") }); items.Add(new TicketBookingInfo() { TheaterName = "FYI Cinemas 4K", TheaterLocation = "No.15, 12th Main Road,Sector South", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "3:00 PM", MovieName = "Safe House", Cast = "<NAME> | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie4.png") }); items.Add(new TicketBookingInfo() { TheaterName = "The Cinemas Dolby Digital", TheaterLocation = "No.275, 3rd Cross Road,Layout 71", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "2:30 PM", Timing2 = "9:00 PM", MovieName = "Run All Night", Cast = "Liam Neeson | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie5.png") }); items.Add(new TicketBookingInfo() { TheaterName = "SF Theater Dolby Atmos RDX", TheaterLocation = "North West Layout", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "1:30 PM", Timing2 = "6:00 PM", MovieName = "Source Code", Cast = "<NAME> | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie6.png") }); items.Add(new TicketBookingInfo() { TheaterName = "Grid Cinemas 4K Dolby Atmos", TheaterLocation = "No.15, 12th Main Road,Area 33", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "3:30 PM", MovieName = "Clash Of The Titans", Cast = "Gemma Arteron | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie7.png") }); items.Add(new TicketBookingInfo() { TheaterName = "Grand Theater", TheaterLocation = "No.275, 3rd Cross Road,South Sector", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "6:00 PM", MovieName = "A Walk Among The TombStones", Cast = "Liam Neeson | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie8.png") }); items.Add(new TicketBookingInfo() { TheaterName = "Layout Cinemas Dolby Atmos RDX", TheaterLocation = "No.15, 12th Main Road,Area 152", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "6:00 PM", Timing2 = "10:30 PM", MovieName = "Unkown", Cast = "Liam Neeson | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie9.png") }); items.Add(new TicketBookingInfo() { TheaterName = "Xamarin Cinemas Dolby Atmos RDX", TheaterLocation = "No.275, 3rd Cross Road,Sector 77", InfoImage = UIImage.FromBundle("Images/Popup_info.png"), Timing1 = "2:30 PM", Timing2 = "6:30 PM", MovieName = "A-Team", Cast = "<NAME> | <NAME>", MovieImage = UIImage.FromBundle("Images/Popup_Movie10.png") }); return items; } } }<file_sep>/Forms/RadioButton/RadioButton/Samples/RadioButton/RadioButton.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SampleBrowser.Core; namespace SampleBrowser.SfRadioButton { public partial class RadioButton : SampleView { public RadioButton() { InitializeComponent(); if (Device.RuntimePlatform == Device.Android) frame.BackgroundColor = Color.Transparent; if (Device.RuntimePlatform == Device.WPF || Device.RuntimePlatform == Device.UWP) { buttn.HeightRequest = 50; buttn.WidthRequest = 300; buttn.HorizontalOptions = LayoutOptions.Center; buttn.VerticalOptions = LayoutOptions.Center; } if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { frame.BackgroundColor = Color.White; lineFrame.BackgroundColor = Color.White; frame.HasShadow = true; lineFrame.HasShadow = false; #pragma warning disable 618 frame.OutlineColor = Color.FromHex("29000000"); lineFrame.OutlineColor = Color.FromHex("29000000"); #pragma warning restore 618 } if (Device.Idiom == TargetIdiom.Tablet) { frame.Margin = new Thickness(45, 89, 45, 0); headerText.Margin = new Thickness(0, 50, 0, 0); headerText.FontSize = 30; amountlabl.FontSize = 22; amt.FontSize = 22; paymentmodelbl.FontSize = 22; debit.FontSize = 20; credit.FontSize = 20; netbanking.FontSize = 20; buttn.FontSize = 25; lineFrame.HeightRequest = 2; lineFrame.Margin = new Thickness(25, 25, 25, 0); amtStack.Margin = new Thickness(25, 25, 25, 0); amountlabl.Margin = new Thickness(0, 20 , 0, 0); amt.Margin = new Thickness(0, 20, 0, 0); radioGroup.Margin = new Thickness(0, 35, 0, 0); paymentmodelbl.Margin = new Thickness(25, 0, 0, 0); debit.Margin = new Thickness(25, 30, 0, 0); credit.Margin = new Thickness(25, 30, 0, 45); netbanking.Margin = new Thickness(25, 30, 0, 0); } } private void Buttn_Clicked(object sender, EventArgs e) { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("", "Payment Successfull !", "Ok"); debit.IsChecked = false; credit.IsChecked = false; netbanking.IsChecked = false; buttn.IsEnabled = false; if (Device.RuntimePlatform == Device.WPF) { buttn.TextColor = Color.Black; } } private void paymentMode_StateChanged(object sender, Syncfusion.XForms.Buttons.StateChangedEventArgs eventArgs) { buttn.IsEnabled = true; if (Device.RuntimePlatform == Device.WPF) { buttn.TextColor = Color.White; } } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/CellTemplate/CellTemplateBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CellTemplateBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Editing samples /// </summary> public class CellTemplateBehavior : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Grid myGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Grid transparent; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Grid customView; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of bindAble</param> protected async override void OnAttachedTo(SampleView bindAble) { var assembly = Assembly.GetAssembly(Application.Current.GetType()); await Task.Delay(200); this.customView = bindAble.FindByName<Grid>("customLayout"); this.transparent = bindAble.FindByName<Grid>("transparent"); this.myGrid = new Grid(); this.myGrid.VerticalOptions = LayoutOptions.FillAndExpand; this.myGrid.HorizontalOptions = LayoutOptions.FillAndExpand; this.myGrid.RowDefinitions = new RowDefinitionCollection { new RowDefinition { Height = new GridLength(1.1, GridUnitType.Star) }, new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, }; this.myGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); this.myGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1.8, GridUnitType.Star) }); this.myGrid.Children.Add( new Image() { Opacity = 1.0, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Source = "EditIllustration.png" }, 1, 1); this.myGrid.BackgroundColor = Color.Transparent; this.myGrid.GestureRecognizers.Add(new TapGestureRecognizer() { Command = new Command(this.Collapse) }); this.customView.Children.Add(this.myGrid); base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">A sampleView type of bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.myGrid = null; this.transparent = null; this.customView = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Used this method for removing the child element of CustomView /// </summary> private void Collapse() { this.myGrid.IsEnabled = false; this.myGrid.IsVisible = false; this.transparent.IsVisible = false; this.customView.Children.Remove(this.myGrid); this.customView.Children.Remove(this.transparent); } } } <file_sep>/Android/SampleBrowser/Samples/TreeView/Helper/CustomAdapter/NodeImageAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Views; using Android.Widget; using Syncfusion.Android.TreeView; namespace SampleBrowser { public class NodeImageAdapter : TreeViewAdapter { public NodeImageAdapter() { } protected override View CreateContentView(TreeViewItemInfoBase itemInfo) { var gridView = new NodeImageView(TreeView.Context); return gridView; } protected override void UpdateContentView(View view, TreeViewItemInfoBase itemInfo) { var grid = view as NodeImageView; var treeViewNode = itemInfo.Node; if (grid != null) { var icon = grid.GetChildAt(0) as ImageView; if (icon != null) { var imageID = (treeViewNode.Content as FileManager).ImageIcon; icon.SetImageResource(imageID); } var label1 = grid.GetChildAt(1) as ContentLabel; if (label1 != null) { label1.Text = (treeViewNode.Content as FileManager).FileName.ToString(); } } } } }<file_sep>/Forms/Chart/Chart/Samples/StackedLineChart/StackedLineChartViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace SampleBrowser.SfChart { public class StackedLineChartViewModel { public ObservableCollection<ChartDataModel> StackedLineData1 { get; set; } public ObservableCollection<ChartDataModel> StackedLineData2 { get; set; } public ObservableCollection<ChartDataModel> StackedLineData3 { get; set; } public ObservableCollection<ChartDataModel> StackedLineData4 { get; set; } public StackedLineChartViewModel() { StackedLineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 55), new ChartDataModel("Transport", 33), new ChartDataModel("Medical", 43), new ChartDataModel("Clothes", 32), new ChartDataModel("Books", 56), new ChartDataModel("Others", 23) }; StackedLineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 40), new ChartDataModel("Transport", 45), new ChartDataModel("Medical", 23), new ChartDataModel("Clothes", 54), new ChartDataModel("Books", 18), new ChartDataModel("Others", 54) }; StackedLineData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 45), new ChartDataModel("Transport", 54), new ChartDataModel("Medical", 20), new ChartDataModel("Clothes", 23), new ChartDataModel("Books", 43), new ChartDataModel("Others", 33) }; StackedLineData4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 48), new ChartDataModel("Transport", 28), new ChartDataModel("Medical", 34), new ChartDataModel("Clothes", 54), new ChartDataModel("Books", 55), new ChartDataModel("Others", 56) }; } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/VerticalChart.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Java.Lang; using Com.Syncfusion.Charts.Enums; using System.Threading.Tasks; using System.Collections.ObjectModel; namespace SampleBrowser { public class VerticalChart : SamplePage { ObservableCollection<DataPoint> datas1; SfChart sfChart; int count = 0; public override View GetSampleContent(Context context) { datas1 = new ObservableCollection<DataPoint>(); sfChart = new SfChart(context); sfChart.ColorModel.ColorPalette = ChartColorPalette.Natural; sfChart.Title.Text ="Seismograph analysis of a country"; sfChart.Title.TextSize = 15; sfChart.Legend.Visibility = Visibility.Visible; sfChart.Legend.ToggleSeriesVisibility = true; NumericalAxis primaryAxis = new NumericalAxis(); primaryAxis.Title.Text ="Time (s)"; primaryAxis.ShowMajorGridLines = false; sfChart.PrimaryAxis = primaryAxis; NumericalAxis numericalAxis = new NumericalAxis() { Minimum = -15, Maximum = 15, }; numericalAxis.Title.Text ="Velocity (m/s)"; numericalAxis.ShowMajorGridLines = false; sfChart.SecondaryAxis = numericalAxis; FastLineSeries fastLineSeries = new FastLineSeries(); fastLineSeries.ItemsSource = datas1; fastLineSeries.XBindingPath = "XValue"; fastLineSeries.YBindingPath = "YValue"; fastLineSeries.Label="Indonesia"; fastLineSeries.Transposed = true; sfChart.Series.Add(fastLineSeries); Random random = new Random(); for (int i = 1; i < 50; i++) { datas1.Add(new DataPoint(i, random.Next(-3, 3))); } UpdateData(); return sfChart; } private async void UpdateData() { bool isFlag = true; while (isFlag) { await Task.Delay(10); count = count + 1; Random random = new Random(); int index = datas1.Count(); if (count > 350) { isFlag =false; } else if (count > 300) { datas1.Add(new DataPoint(index, random.Next(0, 0))); } else if (count > 250) { datas1.Add(new DataPoint(index, random.Next(-2, 1))); } else if (count > 180) { datas1.Add(new DataPoint(index,random.Next(-3, 2))); } else if (count > 100) { datas1.Add(new DataPoint(index,random.Next(-7, 6))); } else { datas1.Add(new DataPoint(index, random.Next(-9, 9))); } index++; } } } }<file_sep>/Android/SampleBrowser/Samples/DocIO/FormatTable.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.OfficeChart; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using System.IO; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Webkit; using Android.App; using Android.OS; namespace SampleBrowser { public partial class FormatTable : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to format the tables in the Word document using Essential DocIO."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { // Create a new document. WordDocument document = new WordDocument(); // Adding a new section to the document. IWSection section = document.AddSection(); section.PageSetup.Margins.All = 50; section.PageSetup.DifferentFirstPage = true; IWTextRange textRange; IWParagraph paragraph = section.AddParagraph(); #region Table Cell Spacing. // -------------------------------------------- // Table Cell Spacing. // -------------------------------------------- paragraph.AppendText("Table Cell spacing...").CharacterFormat.FontSize = 14; section.AddParagraph(); paragraph = section.AddParagraph(); WTextBody textBody = section.Body; // Adding a new Table to the textbody. IWTable table = textBody.AddTable(); table.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single; table.TableFormat.Paddings.All = 5.4f; RowFormat format = new RowFormat(); format.Paddings.All = 5; format.CellSpacing = 2; format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash; format.IsBreakAcrossPages = true; table.ResetCells(25, 5, format, 90); IWTextRange text; table.Rows[0].IsHeader = true; for (int i = 0; i < table.Rows[0].Cells.Count; i++) { paragraph = table[0, i].AddParagraph() as WParagraph; paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; text = paragraph.AppendText(string.Format("Header {0}", i + 1)); text.CharacterFormat.FontName = "Calibri"; text.CharacterFormat.FontSize = 10; text.CharacterFormat.Bold = true; text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(0, 21, 84); table[0, i].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(203, 211, 226); } for (int i = 1; i < table.Rows.Count; i++) { for (int j = 0; j < 5; j++) { paragraph = table[i, j].AddParagraph() as WParagraph; paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; text = paragraph.AppendText(string.Format("Cell {0} , {1}", i, j + 1)); text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(242, 151, 50); text.CharacterFormat.Bold = true; if (i % 2 != 1) table[i, j].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(231, 235, 245); else table[i, j].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(246, 249, 255); } } //table.TableFormat.IsAutoResized = true; (table as WTable).AutoFit(AutoFitType.FitToContent); #endregion Table Cell Spacing. #region Nested Table // -------------------------------------------- // Nested Table. // -------------------------------------------- section.AddParagraph(); paragraph = section.AddParagraph(); paragraph.ParagraphFormat.PageBreakBefore = true; paragraph.AppendText("Nested Table...").CharacterFormat.FontSize = 14; section.AddParagraph(); paragraph = section.AddParagraph(); textBody = section.Body; // Adding a new Table to the textbody. table = textBody.AddTable(); format = new RowFormat(); format.Paddings.All = 5; format.CellSpacing = 2.5f; format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash; table.ResetCells(5, 3, format, 100); for (int i = 0; i < table.Rows[0].Cells.Count; i++) { paragraph = table[0, i].AddParagraph() as WParagraph; paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; text = paragraph.AppendText(string.Format("Header {0}", i + 1)); text.CharacterFormat.FontName = "Calibri"; text.CharacterFormat.FontSize = 10; text.CharacterFormat.Bold = true; text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(0, 21, 84); table[0, i].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(242, 151, 50); } table[0, 2].Width = 200; for (int i = 1; i < table.Rows.Count; i++) { for (int j = 0; j < 3; j++) { paragraph = table[i, j].AddParagraph() as WParagraph; paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; if ((i == 2) && (j == 2)) { text = paragraph.AppendText("Nested Table"); } else { text = paragraph.AppendText(string.Format("Cell {0} , {1}", i, j + 1)); } if ((j == 2)) table[i, j].Width = 200; text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(242, 151, 50); text.CharacterFormat.Bold = true; } } // Adding a nested Table. IWTable nestTable = table[2, 2].AddTable(); format = new RowFormat(); format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash; format.HorizontalAlignment = RowAlignment.Center; nestTable.ResetCells(3, 3, format, 45); for (int i = 0; i < nestTable.Rows.Count; i++) { for (int j = 0; j < 3; j++) { paragraph = nestTable[i, j].AddParagraph() as WParagraph; paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; nestTable[i, j].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(231, 235, 245); text = paragraph.AppendText(string.Format("Cell {0} , {1}", i, j + 1)); text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Black; text.CharacterFormat.Bold = true; } } (nestTable as WTable).AutoFit(AutoFitType.FitToContent); (table as WTable).AutoFit(AutoFitType.FitToWindow); #endregion Nested Table MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Docx); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("FormatTable.docx", "application/msword", stream, m_context); } } } } <file_sep>/Android/SampleBrowser/Samples/PullToRefresh/ListView/CustomBaseAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.SfPullToRefresh; using System.Threading.Tasks; using System.Collections.ObjectModel; using Java.Lang; using Android.Graphics; namespace SampleBrowser { public class CustomBaseAdapter : BaseAdapter { Activity context; ObservableCollection<Mail> items; private Random random; public CustomBaseAdapter(Activity activity, ObservableCollection<Mail> inboxItems) { context = activity; items = inboxItems; random = new Random(); } public override int Count { get { return items.Count; } } public override long GetItemId(int position) { return position; } public override Java.Lang.Object GetItem(int position) { return null; } public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = context.LayoutInflater.Inflate(Resource.Layout.ListViewTemplate, null); } var image = view.FindViewById<CircleViewOfTemplate>(Resource.Id.imageView); var senderLabel = view.FindViewById<TextView>(Resource.Id.sender); var subjectLabel = view.FindViewById<TextView>(Resource.Id.subject); var detailLabel = view.FindViewById<TextView>(Resource.Id.details); var date = view.FindViewById<TextView>(Resource.Id.date); senderLabel.TextSize = 18; subjectLabel.TextSize = 14; detailLabel.TextSize = 12; date.TextSize = 12; senderLabel.Text = items[position].Sender; subjectLabel.Text = items[position].Subject; detailLabel.Text = items[position].Details; image.Text = senderLabel.Text[0].ToString(); image.backgroundColor = items[position].BackgroundColor; image.Invalidate(); return view; } } }<file_sep>/Forms/TextInputLayout/TextInputLayout.WPF/MainWindow.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.WPF.TextInputLayout; using Xamarin.Forms; using Xamarin.Forms.Platform.WPF; namespace SampleBrowser.SfTextInputLayout.WPF { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : FormsApplicationPage { public MainWindow() { InitializeComponent(); Forms.Init(); Core.WPF.CoreSampleBrowser.Init(); SfTextInputLayoutRenderer.Init(); Syncfusion.ListView.XForms.WPF.SfListViewRenderer.Init(); LoadApplication(new SfTextInputLayout.App()); } } } <file_sep>/Android/SampleBrowser/Samples/SparkLine/SparkLine.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Syncfusion.SfSparkline.Android; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace SampleBrowser { public class SparkLine : SamplePage { SfAreaSparkline areaSparLine; SfLineSparkline lineSparkLine; SfColumnSparkline columnSparkLine; SfWinLossSparkline winLossSparkLine; public override View GetSampleContent(Context context) { var AreaData = new List<SparklineModel> { new SparklineModel {Value = 0.8}, new SparklineModel {Value = 1.8}, new SparklineModel {Value = 1.3}, new SparklineModel {Value = 1.1}, new SparklineModel {Value = 1.6}, new SparklineModel {Value = 2.0}, new SparklineModel {Value = 1.7}, new SparklineModel {Value = 2.3}, new SparklineModel {Value = 2.7}, new SparklineModel {Value = 2.3}, new SparklineModel {Value = 1.9}, new SparklineModel {Value = 1.4}, new SparklineModel {Value = 1.2}, new SparklineModel {Value = 0.8}, }; var LineData = new List<SparklineModel> { new SparklineModel {Value = 1.1}, new SparklineModel {Value = 0.9}, new SparklineModel {Value = 1.1}, new SparklineModel {Value = 1.3}, new SparklineModel {Value = 1.1}, new SparklineModel {Value = 1.8}, new SparklineModel {Value = 2.1}, new SparklineModel {Value = 2.3}, new SparklineModel {Value = 1.7}, new SparklineModel {Value = 1.5}, new SparklineModel {Value = 2.5}, new SparklineModel {Value = 1.9}, new SparklineModel {Value = 1.3}, new SparklineModel {Value = 0.9}, }; var ColumnData = new List<SparklineModel> { new SparklineModel {Value = 34}, new SparklineModel {Value = -12}, new SparklineModel {Value = 43}, new SparklineModel {Value = 66}, new SparklineModel {Value = 26}, new SparklineModel {Value = 10} }; var WinLossData = new List<SparklineModel> { new SparklineModel {Value = 34}, new SparklineModel {Value = 23}, new SparklineModel {Value = -31}, new SparklineModel {Value = 0}, new SparklineModel {Value = 26}, new SparklineModel {Value = 44} }; float width = context.Resources.DisplayMetrics.WidthPixels; float height = context.Resources.DisplayMetrics.HeightPixels; LayoutInflater layoutInflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService); View view = layoutInflater.Inflate(Resource.Layout.SfSparkline, null); lineSparkLine = new SfLineSparkline(context); columnSparkLine = new SfColumnSparkline(context); areaSparLine = new SfAreaSparkline(context); winLossSparkLine = new SfWinLossSparkline(context); int layoutPadding = 30; int topPadding = 80; TextView lineSparkLineLabel = new TextView(context); lineSparkLineLabel.Text = "Line"; lineSparkLineLabel.SetPadding(0, topPadding, 0, 0); lineSparkLineLabel.Typeface = Typeface.Create((Typeface)null, TypefaceStyle.Bold); lineSparkLineLabel.Gravity = GravityFlags.Center; TextView columnSparkLineLabel = new TextView(context); columnSparkLineLabel.Text = "Column"; columnSparkLineLabel.SetPadding(0, topPadding, 0, 0); columnSparkLineLabel.Typeface = Typeface.Create((Typeface)null, TypefaceStyle.Bold); columnSparkLineLabel.Gravity = GravityFlags.Center; TextView areaSparLineLabel = new TextView(context); areaSparLineLabel.Text = "Area"; areaSparLineLabel.SetPadding(0, topPadding, 0, 0); areaSparLineLabel.Typeface = Typeface.Create((Typeface)null, TypefaceStyle.Bold); areaSparLineLabel.Gravity = GravityFlags.Center; TextView winLossSparkLineLabel = new TextView(context); winLossSparkLineLabel.Text = "WinLoss"; winLossSparkLineLabel.SetPadding(0, topPadding, 0, 0); winLossSparkLineLabel.Typeface = Typeface.Create((Typeface)null, TypefaceStyle.Bold); winLossSparkLineLabel.Gravity = GravityFlags.Center; RelativeLayout lineSparkLineLayout = view.FindViewById<RelativeLayout>(Resource.Id.lineSparkLineLayout); lineSparkLineLayout.SetPadding(0, layoutPadding, 0, 0); lineSparkLineLayout.SetGravity(GravityFlags.Center); var lineParams = new RelativeLayout.LayoutParams((int)width / 2, (int)height / 10); lineParams.AddRule(LayoutRules.AlignParentTop); lineSparkLine.LayoutParameters = lineParams; var lineLabelParams = new RelativeLayout.LayoutParams((int)width / 2, (int)height); lineLabelParams.AddRule(LayoutRules.AlignBaseline, lineSparkLine.Id); lineSparkLineLabel.LayoutParameters = lineLabelParams; lineSparkLineLayout.AddView(lineSparkLine, lineParams); lineSparkLineLayout.AddView(lineSparkLineLabel, lineLabelParams); RelativeLayout columnSparkLineLayout = view.FindViewById<RelativeLayout>(Resource.Id.columnSparkLineLayout); columnSparkLineLayout.SetPadding(0, layoutPadding, 0, 0); columnSparkLineLayout.SetGravity(GravityFlags.Center); var columnParams = new RelativeLayout.LayoutParams((int)width / 2, (int)height / 10); columnParams.AddRule(LayoutRules.AlignParentTop); columnSparkLine.LayoutParameters = columnParams; var columnLabelParams = new RelativeLayout.LayoutParams((int)width / 2, (int)height); columnLabelParams.AddRule(LayoutRules.Below, columnSparkLine.Id); columnSparkLineLabel.LayoutParameters = columnLabelParams; columnSparkLineLayout.AddView(columnSparkLine, columnParams); columnSparkLineLayout.AddView(columnSparkLineLabel, columnLabelParams); RelativeLayout areaSparLineLayout = view.FindViewById<RelativeLayout>(Resource.Id.areaSparLineLayout); areaSparLineLayout.SetPadding(0, layoutPadding, 0, 0); areaSparLineLayout.SetGravity(GravityFlags.Center); var areaParams = new RelativeLayout.LayoutParams((int)width / 2, (int)height / 10); areaParams.AddRule(LayoutRules.AlignParentTop); areaSparLine.LayoutParameters = areaParams; var areaLabelParams = new RelativeLayout.LayoutParams((int)width / 2, (int)height); areaLabelParams.AddRule(LayoutRules.Below, areaSparLine.Id); areaSparLineLabel.LayoutParameters = areaLabelParams; areaSparLineLayout.AddView(areaSparLine, areaParams); areaSparLineLayout.AddView(areaSparLineLabel, areaLabelParams); RelativeLayout winLossSparkLineLayout = view.FindViewById<RelativeLayout>(Resource.Id.winLossSparkLineLayout); winLossSparkLineLayout.SetPadding(0, layoutPadding, 0, 0); winLossSparkLineLayout.SetGravity(GravityFlags.Center); var winLossParams = new RelativeLayout.LayoutParams((int)width / 2, (int)height / 10); winLossParams.AddRule(LayoutRules.AlignParentTop); winLossSparkLine.LayoutParameters = winLossParams; var winLossLabelParams = new RelativeLayout.LayoutParams((int)width / 2, (int)height); winLossLabelParams.AddRule(LayoutRules.Below, winLossSparkLine.Id); winLossSparkLineLabel.LayoutParameters = winLossLabelParams; winLossSparkLineLayout.AddView(winLossSparkLine, winLossParams); winLossSparkLineLayout.AddView(winLossSparkLineLabel, winLossLabelParams); lineSparkLine.ItemsSource = LineData; lineSparkLine.YBindingPath = "Value"; lineSparkLine.Marker.Visibility = ViewStates.Visible; columnSparkLine.ItemsSource = ColumnData; columnSparkLine.YBindingPath = "Value"; areaSparLine.ItemsSource = AreaData; areaSparLine.YBindingPath = "Value"; areaSparLine.Marker.Visibility = ViewStates.Visible; winLossSparkLine.ItemsSource = WinLossData; winLossSparkLine.YBindingPath = "Value"; return view; } } public class SparklineModel { public double Value { get; set; } } }<file_sep>/Forms/PDF/PDF/Samples/Encryption/Encryption.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Interactive; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Security; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.PDF { public partial class Encryption : SampleView { public Encryption() { InitializeComponent(); this.keysize.Items.Add("128 Bit"); this.keysize.Items.Add("256 Bit"); this.keysize.Items.Add("256 Revision 6"); this.Algorithms.Items.Add("RC4"); this.Algorithms.Items.Add("AES"); this.Options.Items.Add("Encrypt all contents"); this.Options.Items.Add("Encrypt all contents except metadata"); this.Options.Items.Add("Encrypt only attachments"); this.keysize.SelectedIndex = 1; this.Algorithms.SelectedIndex = 1; this.Options.SelectedIndex = 0; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } public void OnButtonClicked(object sender, EventArgs e) { //Create new PDF document. PdfDocument document = new PdfDocument(); //Add page to the PDF document. PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; //Create font object. PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Bold); PdfBrush brush = PdfBrushes.Black; PdfForm form = document.Form; //Document security PdfSecurity security = document.Security; if (this.Algorithms.Items[this.Algorithms.SelectedIndex] == "AES") { security.Algorithm = PdfEncryptionAlgorithm.AES; if (this.keysize.SelectedIndex == 0) { security.KeySize = PdfEncryptionKeySize.Key128Bit; } else if (this.keysize.SelectedIndex == 1) { security.KeySize = PdfEncryptionKeySize.Key256Bit; } else if (this.keysize.SelectedIndex == 2) { security.KeySize = PdfEncryptionKeySize.Key256BitRevision6; } } else if(this.Algorithms.Items[this.Algorithms.SelectedIndex] == "RC4") { security.Algorithm = PdfEncryptionAlgorithm.RC4; if (this.keysize.SelectedIndex == 0) { security.KeySize = PdfEncryptionKeySize.Key40Bit; } else if (this.keysize.SelectedIndex == 1) { security.KeySize = PdfEncryptionKeySize.Key128Bit; } } if (this.Options.Items[this.Options.SelectedIndex] == "Encrypt all contents") { security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents; } else if (this.Options.Items[this.Options.SelectedIndex] == "Encrypt all contents except metadata") { security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata; } else if (this.Options.Items[this.Options.SelectedIndex] == "Encrypt only attachments") { //Read the file #if COMMONSB Stream file = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Products.xml"); #else Stream file = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Products.xml"); #endif //Creates an attachment PdfAttachment attachment = new PdfAttachment("Products.xml", file); attachment.ModificationDate = DateTime.Now; attachment.Description = "About Syncfusion"; attachment.MimeType = "application/txt"; //Adds the attachment to the document document.Attachments.Add(attachment); security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments; } security.OwnerPassword = "<PASSWORD>"; security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint; security.UserPassword = "<PASSWORD>"; string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" + "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm); if (this.Algorithms.SelectedIndex == 1) { if(this.keysize.SelectedIndex == 2) text += String.Format("\n\nRevision: {0}", "Revision 6"); else if (this.keysize.SelectedIndex == 1) text += String.Format("\n\nRevision: {0}", "Revision 5"); } graphics.DrawString("Document is Encrypted with following settings", font, brush, PointF.Empty); font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Bold); graphics.DrawString(text, font, brush, new PointF(0, 40)); MemoryStream stream = new MemoryStream(); //Save the PDF document. document.Save(stream); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Secured.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("Secured.pdf", "application/pdf", stream); } void OnItemSelected(object sender, EventArgs e) { this.Options.SelectedIndex = 0; if (this.Algorithms.SelectedIndex == 0) { this.keysize.Items.Clear(); this.keysize.Items.Add("40 Bit"); this.keysize.Items.Add("128 Bit"); this.keysize.SelectedIndex = 0; this.Options.IsEnabled = false; } else if (this.Algorithms.SelectedIndex == 1) { this.keysize.Items.Clear(); this.keysize.Items.Add("128 Bit"); this.keysize.Items.Add("256 Bit"); this.keysize.Items.Add("256 Revision 6"); this.keysize.SelectedIndex = 0; this.Options.IsEnabled = true; } } void OnOptionSelected(object sender, EventArgs e) { if (this.Options.SelectedIndex == 2) { this.OwnerPassword.IsVisible = false; } else { this.OwnerPassword.IsVisible = true; } } } } <file_sep>/Forms/PDF/PDF/Samples/ZugFerd/CountryCodes.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Syncfusion.ZugFerd { /// <summary> /// Country codes /// </summary> public enum CountryCodes { US, AX, AL, DZ, AS, AD, } } <file_sep>/Forms/SunburstChart/SunburstChart/Samples/Selection/Selection.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; using Syncfusion.SfSunburstChart.XForms; namespace SampleBrowser.SfSunburstChart { [Preserve(AllMembers = true)] public partial class Selection : SampleView { public Selection() { InitializeComponent(); selectionMode.SelectedIndex = 0; selectionType.SelectedIndex = 0; sunburstChart.SelectionChanged += SunburstChart_SelectionChanged; if (Device.Idiom == TargetIdiom.Tablet || Device.Idiom == TargetIdiom.Desktop) { if (Device.RuntimePlatform != Device.UWP) { if (legend.LabelStyle == null) legend.LabelStyle = new SunburstLegendLabelStyle(); legend.LabelStyle.FontSize = 16; } title.FontSize = 20; } else { if (Device.RuntimePlatform != Device.UWP) { if (legend.LabelStyle == null) legend.LabelStyle = new SunburstLegendLabelStyle(); legend.LabelStyle.FontSize = 14; } dataLabel.FontSize = 10; } } private void SunburstChart_SelectionChanged(object sender, Syncfusion.SfSunburstChart.XForms.SelectionChangedEventArgs e) { if (e.SelectedSegment != null) { stackLayout.IsVisible = true; if(!e.IsSelected) { stackLayout.IsVisible = false; } if (e.SelectedSegment.CurrentLevel == 0) { countryLabel.Text = "Continent: " + e.SelectedSegment.Category; populationLabel.Text = "Population: " + e.SelectedSegment.Value; } else if (e.SelectedSegment.CurrentLevel == 1) { countryLabel.Text = "Country: " + e.SelectedSegment.Category; populationLabel.Text = "Population: " + e.SelectedSegment.Value; } else { countryLabel.Text = "State: " + e.SelectedSegment.Category; populationLabel.Text = "Population: " + e.SelectedSegment.Value; } } } private void selectionMode_SelectedIndexChanged(object sender, EventArgs e) { var picker = sender as Picker; if (picker.SelectedIndex == 0) sunburstChart.SelectionSettings.SelectionDisplayMode = SelectionDisplayMode.HighlightByOpacity; else if (picker.SelectedIndex == 1) sunburstChart.SelectionSettings.SelectionDisplayMode = SelectionDisplayMode.HighlightByColor; else if (picker.SelectedIndex == 2) sunburstChart.SelectionSettings.SelectionDisplayMode = SelectionDisplayMode.HighlightByStrokeColor; } private void selectionType_SelectedIndexChanged(object sender, EventArgs e) { var picker = sender as Picker; if (picker.SelectedIndex == 0) sunburstChart.SelectionSettings.SelectionType = SelectionType.Child; else if (picker.SelectedIndex == 1) sunburstChart.SelectionSettings.SelectionType = SelectionType.Group; else if (picker.SelectedIndex == 2) sunburstChart.SelectionSettings.SelectionType = SelectionType.Parent; else if (picker.SelectedIndex == 3) sunburstChart.SelectionSettings.SelectionType = SelectionType.Single; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/AutoRowHeight/AutoRowHeightBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "AutoRowHeightBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the AutoRowHeight sample. /// </summary> public class AutoRowHeightBehaviors : Behavior<Syncfusion.SfDataGrid.XForms.SfDataGrid> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">DataGrid type of bindAble</param> protected override void OnAttachedTo(Syncfusion.SfDataGrid.XForms.SfDataGrid bindAble) { this.dataGrid = bindAble; this.dataGrid.GridViewCreated += this.DataGrid_GridViewCreated; this.dataGrid.QueryRowHeight += this.DataGrid_QueryRowHeight; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">DataGrid type of bindAble parameter</param> protected override void OnDetachingFrom(Syncfusion.SfDataGrid.XForms.SfDataGrid bindAble) { this.dataGrid.GridViewCreated -= this.DataGrid_GridViewCreated; this.dataGrid.QueryRowHeight -= this.DataGrid_QueryRowHeight; this.dataGrid = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Fired when DataGrid view is created. /// </summary> /// <param name="sender">DataGrid_GridViewCreated sender</param> /// <param name="e">GridViewCreatedEventArgs parameter e</param> private void DataGrid_GridViewCreated(object sender, GridViewCreatedEventArgs e) { if (Device.Idiom != TargetIdiom.Phone) { GridTextColumn serialNumberColumn = new GridTextColumn(); serialNumberColumn.MappingName = "SNo"; serialNumberColumn.HeaderText = "S.No"; serialNumberColumn.ColumnSizer = ColumnSizer.Auto; serialNumberColumn.HeaderFontAttribute = FontAttributes.Bold; serialNumberColumn.HeaderTextAlignment = TextAlignment.Start; serialNumberColumn.TextAlignment = TextAlignment.End; GridTextColumn releaseDataColumn = new GridTextColumn(); releaseDataColumn.MappingName = "DateOfRelease"; releaseDataColumn.HeaderText = "Release Date"; releaseDataColumn.Padding = 5; releaseDataColumn.ColumnSizer = ColumnSizer.Auto; releaseDataColumn.HeaderFontAttribute = FontAttributes.Bold; releaseDataColumn.HeaderTextAlignment = TextAlignment.Start; releaseDataColumn.TextAlignment = TextAlignment.Start; if (Device.RuntimePlatform == Device.Android || (Device.RuntimePlatform == Device.iOS)) { serialNumberColumn.HeaderCellTextSize = 14; serialNumberColumn.CellTextSize = 14; serialNumberColumn.Padding = new Thickness(16, 12, 8, 12); releaseDataColumn.HeaderCellTextSize = 14; releaseDataColumn.CellTextSize = 14; releaseDataColumn.Padding = new Thickness(8, 12, 8, 12); } else { serialNumberColumn.HeaderCellTextSize = 12; serialNumberColumn.CellTextSize = 12; serialNumberColumn.Padding = new Thickness(8, 12, 8, 16); releaseDataColumn.HeaderCellTextSize = 12; releaseDataColumn.CellTextSize = 12; releaseDataColumn.Padding = new Thickness(8, 12, 8, 16); } this.dataGrid.Columns.Insert(0, serialNumberColumn); this.dataGrid.Columns.Insert(4, releaseDataColumn); } } /// <summary> /// Fired when a row comes in to View /// </summary> /// <param name="sender">DataGrid_QueryRowHeight sender</param> /// <param name="e">QueryRowHeightEventArgs parameter e</param> private void DataGrid_QueryRowHeight(object sender, QueryRowHeightEventArgs e) { double height = SfDataGridHelpers.GetRowHeight(this.dataGrid, e.RowIndex); if (e.RowIndex > 0) { if (height > 35) { e.Height = height; e.Handled = true; } } } } }<file_sep>/Android/SampleBrowser/Samples/AutoComplete/ToleratingTyposSample/ToleratingTyposSamplePage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Util; using System; using Android.Views; using SampleBrowser; using Android.Widget; using Com.Syncfusion.Autocomplete; using Android.Graphics; using System.Collections.Generic; using System.Collections.ObjectModel; namespace SampleBrowser { public class ToleratingTyposSamplePage : SamplePage { LinearLayout mainLayout; int width,height; double density; ListView myList; UserData userData; MyCustomListAdapter myCustomListAdapter; public List<User> ListSource { get; set; } public override View GetPropertyWindowLayout(Android.Content.Context context) { return null; } public override View GetSampleContent(Android.Content.Context con) { userData = new UserData(); width = con.Resources.DisplayMetrics.WidthPixels; height = con.Resources.DisplayMetrics.HeightPixels; density = con.Resources.DisplayMetrics.Density; mainLayout = new LinearLayout(con); mainLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); mainLayout.Orientation = Orientation.Vertical; mainLayout.SetGravity(GravityFlags.Center); mainLayout.SetPadding(0,20,0,0); SearchCountryMethod(con); AutoCompleteMethod(con); SearchLabelMethod(con); ListViewMethod(con); return mainLayout; } private void SearchCountryMethod(Android.Content.Context con) { TextView textView = new TextView(con); textView.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.95), (int)(30 * density)); textView.Hint = "Search by Country"; textView.TextSize = 18; mainLayout.AddView(textView); } private void AutoCompleteMethod(Android.Content.Context con) { SfAutoComplete toleratingAutoComplete = new SfAutoComplete(con); toleratingAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.95), (int)(50)); toleratingAutoComplete.SetGravity(GravityFlags.Start); toleratingAutoComplete.DataSource =new Countrylist().Country; toleratingAutoComplete.Filter = AutoCompleteSearch; toleratingAutoComplete.SuggestionMode = SuggestionMode.Custom; toleratingAutoComplete.DropDownItemHeight = 40; toleratingAutoComplete.MaximumDropDownHeight = 150; toleratingAutoComplete.Watermark = "Search Here"; CustomAutoCompleteAdapter customAdapter = new CustomAutoCompleteAdapter(); customAdapter.autoComplete1 = toleratingAutoComplete; toleratingAutoComplete.Adapter = customAdapter; ListSource =userData.Users; myCustomListAdapter = new MyCustomListAdapter(ListSource); toleratingAutoComplete.SelectionChanged += (sender, e) => { int valueCount = 0; if (e.Value == null || e.Value.ToString() == "") valueCount = 0; else valueCount=100000; foreach (var item in ListSource) { item.Count = random.Next(valueCount).ToString(); } myCustomListAdapter.NotifyDataSetChanged(); }; mainLayout.AddView(toleratingAutoComplete); } Random random = new Random(); ToleratingTyposHelper helper = new ToleratingTyposHelper(); public bool AutoCompleteSearch(object value1, object value2) { var string1 = value1.ToString().ToLower(); var string2 = value2.ToString().ToLower(); if (string1.Length > 0 && string2.Length > 0) if (string1[0] != string2[0]) return false; var originalString1 = string.Empty; var originalString2 = string.Empty; if (string1.Length < string2.Length) { originalString2 = string2.Remove(string1.Length); originalString1 = string1; } if (string2.Length < string1.Length) { return false; } if (string2.Length == string1.Length) { originalString1 = string1; originalString2 = string2; } bool IsMatchSoundex = helper.ProcessOnSoundexAlgorithmn(originalString1) == helper.ProcessOnSoundexAlgorithmn(originalString2); int Distance = helper.GetDamerauLevenshteinDistance(originalString1, originalString2); if (IsMatchSoundex || Distance <= 4) return true; else return false; //int matchValue = 0; //var allWords = value2.ToString().ToLower().Split(' '); //var keys = value1.ToString().ToLower().Split(' '); //foreach (var item in allWords) //{ // foreach (var key in keys) // { // var itemValue = item; // if (item.Length > key.Length) // { // itemValue = item.Remove(key.Length); // } // if (key == "" || item == "") // continue; // if ((helper.ProcessOnSoundexAlgorithmn(key) == helper.ProcessOnSoundexAlgorithmn(itemValue))) // matchValue++; // if ((helper.ProcessOnSoundexAlgorithmn(key) == helper.ProcessOnSoundexAlgorithmn(item))) // matchValue++; // } //} //int keysCount = 0; //if (matchValue >= keysCount) // return true; //return false; } private void SearchLabelMethod(Android.Content.Context con) { TextView textViewHeight = new TextView(con); textViewHeight.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.95), (int)(40 * density)); mainLayout.AddView(textViewHeight); TextView textView = new TextView(con); textView.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.95), (int)(30 * density)); textView.Hint = "Search Results"; textView.TextSize = 15; mainLayout.AddView(textView); } private void ListViewMethod(Android.Content.Context con) { myList = new ListView(con); myList.LayoutParameters=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(height - (300 * density))); myList.FastScrollEnabled = true; myList.Adapter = myCustomListAdapter; LinearLayout listViewLayout = new LinearLayout(con); listViewLayout.SetPadding(20,10,20,10); listViewLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); listViewLayout.AddView(myList); mainLayout.AddView(listViewLayout); } } public class ToleratingTyposHelper { public ToleratingTyposHelper() { soundexTerms.Add("aeiouhyw"); soundexTerms.Add("bfpv"); soundexTerms.Add("cgikqsxz"); soundexTerms.Add("dt"); soundexTerms.Add("l"); soundexTerms.Add("mn"); soundexTerms.Add("r"); } List<string> soundexTerms = new List<string>(); /// <summary> /// Based on Soundex Algorithmn and DL Distance Algorithmn /// </summary> /// <returns>The matching.</returns> /// <param name="value1">Value1.</param> /// <param name="value2">Value2.</param> public int IsMatching(string value1, string value2) { var val1 = ProcessOnSoundexAlgorithmn(value1); var val2 = ProcessOnSoundexAlgorithmn(value2); return CalcualteDistance(val1, val2); } public int GetMinValue(int[] value) { int minValue = 0; foreach (var item in value) { if (item < minValue) minValue = item; } return minValue; } public int GetDamerauLevenshteinDistance(string source, string target) { var bounds = new { Height = source.Length + 1, Width = target.Length + 1 }; int[,] matrix = new int[bounds.Height, bounds.Width]; for (int height = 0; height < bounds.Height; height++) { matrix[height, 0] = height; }; for (int width = 0; width < bounds.Width; width++) { matrix[0, width] = width; }; for (int height = 1; height < bounds.Height; height++) { for (int width = 1; width < bounds.Width; width++) { int cost = (source[height - 1] == target[width - 1]) ? 0 : 1; int insertion = matrix[height, width - 1] + 1; int deletion = matrix[height - 1, width] + 1; int substitution = matrix[height - 1, width - 1] + cost; int distance = Math.Min(insertion, Math.Min(deletion, substitution)); if (height > 1 && width > 1 && source[height - 1] == target[width - 2] && source[height - 2] == target[width - 1]) { distance = Math.Min(distance, matrix[height - 2, width - 2] + cost); } matrix[height, width] = distance; } } return matrix[bounds.Height - 1, bounds.Width - 1]; } /// <summary> /// DL Algorithmn Implementation /// </summary> /// <returns>The distance.</returns> /// <param name="value1">Value1.</param> /// <param name="value2">Value2.</param> public int CalcualteDistance(string value1, string value2) { int lengthValue1 = value1.Length; int lengthValue2 = value2.Length; var matrix = new int[lengthValue1 + 1, lengthValue2 + 1]; for (int i = 0; i <= lengthValue1; i++) matrix[i, 0] = i; for (int j = 0; j <= lengthValue2; j++) matrix[0, j] = j; for (int i = 1; i <= lengthValue1; i++) { for (int j = 1; j <= lengthValue2; j++) { int cost = value2[j - 1] == value1[i - 1] ? 0 : 1; var vals = new int[] { matrix[i - 1, j] + 1, matrix[i, j - 1] + 1, matrix[i - 1, j - 1] + cost }; matrix[i, j] = GetMinValue(vals); if (i > 1 && j > 1 && value1[i - 1] == value2[j - 2] && value1[i - 2] == value2[j - 1]) matrix[i, j] = Math.Min(matrix[i, j], matrix[i - 2, j - 2] + cost); } } return matrix[lengthValue1, lengthValue2]; } /// <summary> /// Soundex Algorithmn Implementation /// </summary> /// <returns>The on soundex algorithmn.</returns> /// <param name="value1">Value1.</param> /// <param name="moreAccuracy">If set to <c>true</c> more accuracy.</param> public string ProcessOnSoundexAlgorithmn(string value1, bool moreAccuracy = true) { string stringValue = string.Empty; foreach (var item in value1.ToLower()) { for (int i = 0; i < soundexTerms.Count; i++) { if (soundexTerms[i].Contains(item.ToString())) { stringValue += i.ToString(); continue; } } } if (stringValue.Length > 0) { if (moreAccuracy) { stringValue = stringValue.Insert(0, value1[0].ToString()); stringValue = stringValue.Replace("0", ""); } } return stringValue; } } internal class CustomAutoCompleteAdapter : AutoCompleteAdapter { internal SfAutoComplete autoComplete1; public Android.Views.View GetView(Com.Syncfusion.Autocomplete.SfAutoComplete autoComplete, string text, int index) { GC.Collect(); LinearLayout linearLayout = new LinearLayout(autoComplete.Context); linearLayout.SetPadding((int)(3 * autoComplete.GetDensity()),(int)(3 * autoComplete.GetDensity()),(int)(3 * autoComplete.GetDensity()),(int)(3 * autoComplete.GetDensity())); linearLayout.LayoutParameters = new ViewGroup.LayoutParams(autoComplete.LayoutParameters.Width, autoComplete.LayoutParameters.Height); linearLayout.Orientation = Orientation.Horizontal; TextView imageView = new TextView(autoComplete.Context); Typeface tf = Typeface.CreateFromAsset(autoComplete.Context.Assets, "icon.ttf"); imageView.Text = "A"; imageView.SetPadding((int)(3 * autoComplete.GetDensity()), (int)(3 * autoComplete.GetDensity()), (int)(3 * autoComplete.GetDensity()), 0); imageView.Typeface = tf; imageView.TextSize = 18; imageView.Gravity = GravityFlags.Center; imageView.TextAlignment = TextAlignment.Center; TextView textView = new TextView(autoComplete.Context); textView.SetPadding((int)(3 * autoComplete.GetDensity()),0,0,0); textView.Text = text; textView.TextSize = 18; textView.Gravity = GravityFlags.Center; textView.TextAlignment = TextAlignment.Center; linearLayout.AddView(imageView); linearLayout.AddView(textView); return linearLayout; } } } <file_sep>/Forms/DataForm/DataForm/Samples/ContactForm/Helpers/DataFormLayoutManagerExt.cs #region Copyright // <copyright file="DataFormLayoutManagerExt.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syncfusion.XForms.DataForm; using Xamarin.Forms; using DataForm = Syncfusion.XForms.DataForm.SfDataForm; /// <summary> /// Represents a class that used to customize the DataForm. /// </summary> public class DataFormLayoutManagerExt : DataFormLayoutManager { /// <summary> /// Initializes a new instance of the <see cref="DataFormLayoutManagerExt"/> class. /// </summary> /// <param name="dataform">DataForm control helps editing the data fields of any data object.</param> public DataFormLayoutManagerExt(DataForm dataform) : base(dataform) { } /// <summary> /// Gets left start offset for editor. /// </summary> /// <param name="dataFormItem">DataFormItem of the editor.</param> /// <returns>Returns left padding for editor.</returns> protected override int GetLeftPaddingForEditor(DataFormItem dataFormItem) { return 0; } /// <summary> /// Gets left start offset for label. /// </summary> /// <param name="dataFormItem">DataFormItem of the editor.</param> /// <returns>Returns left padding value for label.</returns> protected override int GetLeftPaddingForLabel(DataFormItem dataFormItem) { if (dataFormItem.Name.Equals("SaveTo")) { return 60; } return base.GetLeftPaddingForLabel(dataFormItem); } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/StackingBar.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class StackingBar : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "Sales Comparison"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis PrimaryAxis = new CategoryAxis(); PrimaryAxis.ShowMajorGridLines = false; PrimaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; PrimaryAxis.LabelPlacement = LabelPlacement.BetweenTicks; chart.PrimaryAxis = PrimaryAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; numericalAxis.Minimum = -20; numericalAxis.Maximum = 60; numericalAxis.Interval = 20; numericalAxis.LineStyle.StrokeWidth = 0; numericalAxis.MajorTickStyle.TickSize = 0; numericalAxis.LabelStyle.LabelFormat = "#'%'"; chart.SecondaryAxis = numericalAxis; StackingBarSeries stackingBarSeries = new StackingBarSeries(); stackingBarSeries.EnableAnimation = true; stackingBarSeries.Label = "Apple"; stackingBarSeries.ItemsSource = MainPage.GetStackedBarData1(); stackingBarSeries.XBindingPath = "XValue"; stackingBarSeries.YBindingPath = "YValue"; stackingBarSeries.LegendIcon = ChartLegendIcon.SeriesType; StackingBarSeries stackingBarSeries1 = new StackingBarSeries(); stackingBarSeries1.EnableAnimation = true; stackingBarSeries1.Label = "Orange"; stackingBarSeries1.ItemsSource = MainPage.GetStackedBarData2(); stackingBarSeries1.XBindingPath = "XValue"; stackingBarSeries1.YBindingPath = "YValue"; stackingBarSeries1.LegendIcon = ChartLegendIcon.SeriesType; StackingBarSeries stackingBarSeries2 = new StackingBarSeries(); stackingBarSeries2.EnableAnimation = true; stackingBarSeries2.Label = "Wastage"; stackingBarSeries2.ItemsSource = MainPage.GetStackedBarData3(); stackingBarSeries2.XBindingPath = "XValue"; stackingBarSeries2.YBindingPath = "YValue"; stackingBarSeries2.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingBarSeries); chart.Series.Add(stackingBarSeries1); chart.Series.Add(stackingBarSeries2); stackingBarSeries.TooltipEnabled = true; stackingBarSeries1.TooltipEnabled = true; stackingBarSeries2.TooltipEnabled = true; stackingBarSeries.EnableAnimation = true; stackingBarSeries1.EnableAnimation = true; stackingBarSeries2.EnableAnimation = true; return chart; } } } <file_sep>/Forms/AutoComplete/AutoComplete/Samples/Performance/Performance.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public partial class Performance : SampleView, INotifyPropertyChanged { public ObservableCollection<String> AllWords { get; set; } private IEnumerable<object> filteredCollection; public IEnumerable<object> FilteredCollection { get { return filteredCollection; } set { if (value != null) { filteredCollection = value; var searchTime = "(" + DateTime.Now.Subtract(searchStart).TotalSeconds.ToString().Remove(5) + " Sec)"; filtercount = 0; this.SearchTime.Text = searchTime; foreach (var item in filteredCollection) { filtercount++; } if (filtercount > 0) { this.SearchedItem.Text = filtercount.ToString("#,#", CultureInfo.InvariantCulture); } else { this.SearchedItem.Text = "0"; } getLoadMoreButton(); //if (SearchedItem.Text !="0") //{ // Device.StartTimer(TimeSpan.FromMilliseconds(200), () => // { // return CanAnimate(); // }); //} RaisePropertyChanged("FilteredCollection"); } } } int filtercount = 0; int count = 1; public bool CanAnimate() { if (count > 27) { count = 0; return false; } if ((count++ % 5) == 0) this.SearchedItem.TextColor = this.SearchTime.TextColor = Color.White; else this.SearchedItem.TextColor = this.SearchTime.TextColor = Color.Black; return true; } private bool isToggled = false; public bool IsToggled { get { return isToggled; } set { isToggled = value; this.loadedItem.Text = "Disable load more for on-demand loading"; if (isToggled) { autoComplete.MaximumSuggestion = 10; } else { autoComplete.MaximumSuggestion = 0; } getLoadMoreButton(); RaisePropertyChanged("IsToggled"); } } private void getLoadMoreButton() { if (IsToggled && filtercount > 0) { this.loadMoreButton.IsVisible = true; } else { this.loadMoreButton.IsVisible = false; } } #region INotifyPropertyChanged implementation public new event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion public Performance() { InitializeComponent(); this.BindingContext = this; searchStart = DateTime.Now; IsToggled = false; if (Device.RuntimePlatform == Device.UWP) { AutocompleteRow.Height = 45; } } DateTime searchStart = DateTime.Now; private void auto_ValueChanged(object sender, Syncfusion.SfAutoComplete.XForms.ValueChangedEventArgs e) { if (e.Value != "") { FilteredCollection = null; } this.SearchedItem.Text = this.SearchTime.Text = "0"; searchStart = DateTime.Now; } private void LoadMore_Clicked(object sender, EventArgs e) { searchStart = DateTime.Now; this.autoComplete.LoadMore(); } private async void Load_Clicked(object sender, EventArgs e) { (sender as Button).IsVisible = false; await LoadItems(); } private Task<object> LoadItems() { AllWords = new ObservableCollection<string>(); var assembly = typeof(ViewModel3).GetTypeInfo().Assembly; System.IO.Stream stream = null; #if COMMONSB stream = assembly.GetManifestResourceStream("SampleBrowser.Samples.AutoComplete.words.txt"); #else stream = assembly.GetManifestResourceStream("SampleBrowser.SfAutoComplete.words.txt"); #endif string text = ""; using (var reader = new System.IO.StreamReader(stream)) { text = reader.ReadToEnd(); } string[] splittedwords = text.Split('\n'); for (int i = 0; i < 100000; i++) { AllWords.Add(splittedwords[i]); } var startTime = DateTime.Now; this.autoComplete.DataSource = AllWords; var load = DateTime.Now.Subtract(startTime).TotalSeconds.ToString() + " Sec"; this.SearchedLoadedItem.Text = AllWords.Count.ToString("#,#", CultureInfo.InvariantCulture); return Task.FromResult<object>(null); } } } <file_sep>/Forms/DataForm/DataForm/Samples/Themes/Model/EmployeeInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using Syncfusion.XForms.DataForm; using System.ComponentModel.DataAnnotations; namespace SampleBrowser.SfDataForm { public enum Gender { /// <summary> /// The male. /// </summary> Male, /// <summary> /// The female. /// </summary> Female } public enum Marital { /// <summary> /// The single. /// </summary> Single, /// <summary> /// The unmarried. /// </summary> Married } public class EmployeeInfo : INotifyPropertyChanged { /// <summary> /// The employee identifier. /// </summary> private string employeeID; /// <summary> /// The first name. /// </summary> private string firstName; /// <summary> /// The last name. /// </summary> private string lastName; /// <summary> /// The gender. /// </summary> private Gender gender; /// <summary> /// Represents the birth date of the employee. /// </summary> private DateTime dateofBirth = new DateTime(1995,05,14); /// <summary> /// The name of the father. /// </summary> private string fatherName; /// <summary> /// The name of the mother. /// </summary> private string motherName; /// <summary> /// The marital status. /// </summary> private Marital maritalStatus; /// <summary> /// Represents the email field of the employee. /// </summary> private string email; /// <summary> /// The address. /// </summary> private string address; /// <summary> /// The department. /// </summary> private string department; /// <summary> /// The team. /// </summary> private string team; /// <summary> /// The reporting person. /// </summary> private string reportingPerson; /// <summary> /// The name of the manager. /// </summary> private string managerName; /// <summary> /// The designation. /// </summary> private string designation; /// <summary> /// The date joined. /// </summary> private DateTime dateJoined = DateTime.Now.AddYears(-2); public EmployeeInfo() { } /// <summary> /// Gets or sets the employee identifier. /// </summary> /// <value>The employee identifier.</value> [Display(ShortName = "Employee ID")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your employee id.")] public string EmployeeID { get { return this.employeeID; } set { this.employeeID = value; this.RaisePropertyChanged("EmployeeID"); } } /// <summary> /// Gets or sets the first name of employee. /// </summary> /// <value>The first name.</value> [Display(ShortName = "First Name")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your first name.")] public string FirstName { get { return this.firstName; } set { this.firstName = value; this.RaisePropertyChanged("FirstName"); } } /// <summary> /// Gets or sets the last name of employee. /// </summary> /// <value>The last name.</value> [Display(ShortName = "Last Name")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your last name.")] public string LastName { get { return this.lastName; } set { this.lastName = value; this.RaisePropertyChanged("LastName"); } } /// <summary> /// Gets or sets the gender of employee. /// </summary> /// <value>The gender.</value> [Display(ShortName = "Gender")] public Gender Gender { get { return this.gender; } set { this.gender = value; this.RaisePropertyChanged("Gender"); } } /// <summary> /// Gets or sets the dateof birth of employee. /// </summary> /// <value>The dateof birth.</value> [Display(ShortName = "Date of Birth")] public DateTime DateofBirth { get { return this.dateofBirth; } set { this.dateofBirth = value; this.RaisePropertyChanged("DateofBirth"); } } /// <summary> /// Gets or sets the name of the father of employee. /// </summary> /// <value>The name of the father.</value> [Display(ShortName = "Father's Name")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your father's name.")] public string FatherName { get { return this.fatherName; } set { this.fatherName = value; this.RaisePropertyChanged("FatherName"); } } /// <summary> /// Gets or sets the name of the mother of employee. /// </summary> /// <value>The name of the mother.</value> [Display(ShortName = "Mother's Name")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your mother's name.")] public string MotherName { get { return this.motherName; } set { this.motherName = value; this.RaisePropertyChanged("MotherName"); } } /// <summary> /// Gets or sets the marital status of employee. /// </summary> /// <value>The marital status.</value> [Display(ShortName = "Marital Status")] public Marital MaritalStatus { get { return this.maritalStatus; } set { this.maritalStatus = value; this.RaisePropertyChanged("MaritalStatus"); } } /// <summary> /// Gets or sets the address of employee. /// </summary> /// <value>The address.</value> [Display(ShortName = "Address")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your address.")] [DataType(DataType.MultilineText)] public string Address { get { return this.address; } set { this.address = value; this.RaisePropertyChanged("Address"); } } /// <summary> /// Gets or sets the department of employee. /// </summary> /// <value>The department.</value> [Display(ShortName = "Department")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your department.")] public string Department { get { return this.department; } set { this.department = value; this.RaisePropertyChanged("Department"); } } /// <summary> /// Gets or sets the team name of employee. /// </summary> /// <value>The team.</value> [Display(ShortName = "Team")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your team name.")] public string Team { get { return this.team; } set { this.team = value; this.RaisePropertyChanged("Team"); } } /// <summary> /// Gets or sets the name of reporting person. /// </summary> /// <value>The reporting person.</value> [Display(ShortName = "Reporting Person")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your reporting person name.")] public string ReportingPerson { get { return this.reportingPerson; } set { this.reportingPerson = value; this.RaisePropertyChanged("ReportingPerson"); } } /// <summary> /// Gets or sets the name of the manager of employee. /// </summary> /// <value>The name of the manager.</value> [Display(ShortName = "Manager Name")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your manager name.")] public string ManagerName { get { return this.managerName; } set { this.managerName = value; this.RaisePropertyChanged("ManagerName"); } } /// <summary> /// Gets or sets the email identifier. /// </summary> /// <value>The email identifier.</value> [Display(ShortName = "Email")] [EmailAddress(ErrorMessage = "Please enter a valid e-mail id.")] public string EmailID { get { return this.email; } set { this.email = value; this.RaisePropertyChanged("EmailID"); } } /// <summary> /// Gets or sets the designation of employee. /// </summary> /// <value>The designation.</value> [Display(ShortName = "Designation")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter your designation.")] public string Designation { get { return this.designation; } set { this.designation = value; this.RaisePropertyChanged("Designation"); } } /// <summary> /// Gets or sets the date joined. /// </summary> /// <value>The date joined.</value> [Display(ShortName = "Date Joined")] public DateTime DateJoined { get { return this.dateJoined; } set { this.dateJoined = value; this.RaisePropertyChanged("DateJoined"); } } /// <summary> /// Occurs when property changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Occurs when propery value is changed. /// </summary> /// <param name="name">Property name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } } } <file_sep>/Android/SampleBrowser/Samples/Schedule/ScheduleAppointmentEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Widget; using Android.Views; using Android.Content; using Android.Graphics; using Android.App; using Android.OS; using System.Collections.ObjectModel; using Com.Syncfusion.Schedule; using Com.Syncfusion.Schedule.Enums; using System.Collections.Generic; using Java.Util; using Java.Text; using Android.Util; using Android.Views.InputMethods; using Android.Graphics.Drawables; namespace SampleBrowser { public class ScheduleAppointmentEditor : IDisposable { #region Properties and variables private Context con; private EditText subjectInput, locationInput; private Switch allDaySwitch; private SfSchedule sfSchedule; private Spinner endTimeZonePicker, startTimeZonePicker; private TextView startDateName, startTimeName, endDateName, endTimeName; private SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy", Locale.Us); private SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm aa", Locale.Us); public LinearLayout EditorLayout { get; set; } public ScheduleAppointment SelectedAppointment { get; set; } private Calendar selectedDate; private Calendar startTime; private Calendar endTime; private DisplayMetrics density; #endregion #region Constructor public ScheduleAppointmentEditor(Context context, SfSchedule schedule) { con = context; sfSchedule = schedule; density = con.Resources.DisplayMetrics; EditorLayout = new LinearLayout(context); EditorLayout.Orientation = Orientation.Vertical; EditorLayout.SetBackgroundColor(Color.White); EditorLayout.SetPaddingRelative(30, 30, 30, 30); AddInputControls(); } internal Button SaveButton { get; set; } internal Button CancelButton { get; set; } internal ScrollView ScrollView { get; set; } #endregion #region Methods private void AddInputControls() { var padding = 30; ScrollView = new ScrollView(con); ScrollView.ScrollTo(0, 0); var inputControlLayout = new LinearLayout(con); inputControlLayout.Orientation = Orientation.Vertical; subjectInput = new EditText(con); subjectInput.Gravity = GravityFlags.Fill; subjectInput.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, density.HeightPixels / 12); subjectInput.SetTextColor(Color.Black); subjectInput.Hint = "Event name"; subjectInput.TextSize = 30; subjectInput.SetLines(1); subjectInput.KeyPress += (object sender, View.KeyEventArgs e) => { e.Handled = false; if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter) { InputMethodManager inputmanager = (InputMethodManager)con.GetSystemService(Context.InputMethodService); inputmanager.HideSoftInputFromWindow(subjectInput.WindowToken, 0); e.Handled = true; } }; inputControlLayout.AddView(subjectInput); locationInput = new EditText(con); locationInput.SetTextColor(Color.Black); locationInput.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, density.HeightPixels / 12); locationInput.Gravity = GravityFlags.Fill; locationInput.SetMinimumHeight(80); locationInput.SetLines(1); locationInput.TextSize = 18; locationInput.Hint = "Location"; locationInput.KeyPress += (object sender, View.KeyEventArgs e) => { e.Handled = false; if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter) { InputMethodManager inputmanager = (InputMethodManager)con.GetSystemService(Context.InputMethodService); inputmanager.HideSoftInputFromWindow(subjectInput.WindowToken, 0); e.Handled = true; } }; inputControlLayout.AddView(locationInput); LinearLayout timeLayout = new LinearLayout(con); timeLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); timeLayout.Orientation = Orientation.Vertical; TextView startTimeLabel = new TextView(con); startTimeLabel.Text = "FROM"; startTimeLabel.Gravity = GravityFlags.CenterVertical; startTimeLabel.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, density.HeightPixels / 12); startTimeLabel.TextSize = 18; timeLayout.AddView(startTimeLabel); //startTime row LinearLayout minuteLayout = new LinearLayout(con); minuteLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, density.HeightPixels / 12); minuteLayout.Orientation = Orientation.Horizontal; startDateName = new TextView(con); startDateName.Text = (sfSchedule.VisibleDates as IList<Calendar>).ToString(); startDateName.TextSize = 18; startDateName.SetPadding(0, 0, density.WidthPixels / 4, 0); startDateName.SetTextColor(Color.Black); minuteLayout.AddView(startDateName); startTimeName = new TextView(con); startTimeName.Text = (sfSchedule.VisibleDates as IList<Calendar>).ToString(); startTimeName.TextSize = 18; startTimeName.SetTextColor(Color.Black); minuteLayout.AddView(startTimeName); timeLayout.AddView(minuteLayout); TextView startTimeZoneLabel = new TextView(con); startTimeZoneLabel.Text = "Start Time Zone"; startTimeZoneLabel.TextSize = 18; startTimeZoneLabel.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, density.HeightPixels / 13); startTimeZoneLabel.SetTextColor(Color.Black); startTimeZonePicker = new Spinner(con, SpinnerMode.Dialog); startTimeZonePicker.SetMinimumHeight(60); startTimeZonePicker.SetBackgroundColor(Color.LightGray); startTimeZonePicker.DropDownWidth = 600; startTimeZonePicker.SetGravity(GravityFlags.Center); timeLayout.AddView(startTimeZoneLabel); timeLayout.AddView(startTimeZonePicker); ArrayAdapter<string> dataAdapter = new ArrayAdapter<string>(con, Android.Resource.Layout.SimpleSpinnerItem, TimeZoneCollection.TimeZoneList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); startTimeZonePicker.Adapter = dataAdapter; startTimeZonePicker.ItemSelected += StartTimeZone_Spinner_ItemSelected; //endTime label row TextView endTimeLabel = new TextView(con); endTimeLabel.Text = "TO"; endTimeLabel.Gravity = GravityFlags.CenterVertical; endTimeLabel.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, density.HeightPixels / 11); endTimeLabel.TextSize = 18; timeLayout.AddView(endTimeLabel); //endTime row LinearLayout minuteToLayout = new LinearLayout(con); minuteToLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, density.HeightPixels / 12); minuteToLayout.Orientation = Orientation.Horizontal; endDateName = new TextView(con); endDateName.SetRawInputType(Android.Text.InputTypes.DatetimeVariationTime); endDateName.SetTextColor(Color.Black); endDateName.SetPadding(0, 0, density.WidthPixels / 4, 0); endDateName.Text = (sfSchedule.VisibleDates as IList<Calendar>).ToString(); endDateName.TextSize = 18; minuteToLayout.AddView(endDateName); endTimeName = new TextView(con); endTimeName.Text = (sfSchedule.VisibleDates as IList<Calendar>).ToString(); endTimeName.SetTextColor(Color.Black); endTimeName.TextSize = 18; minuteToLayout.AddView(endTimeName); timeLayout.AddView(minuteToLayout); TextView endTimeZoneLabel = new TextView(con); endTimeZoneLabel.Text = "End Time Zone"; endTimeZoneLabel.TextSize = 18; endTimeZoneLabel.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, density.HeightPixels / 13); endTimeZoneLabel.SetTextColor(Color.Black); endTimeZonePicker = new Spinner(con, SpinnerMode.Dialog); endTimeZonePicker.SetMinimumHeight(60); endTimeZonePicker.SetBackgroundColor(Color.LightGray); endTimeZonePicker.DropDownWidth = 600; endTimeZonePicker.SetGravity(GravityFlags.Center); timeLayout.AddView(endTimeZoneLabel); timeLayout.AddView(endTimeZonePicker); ArrayAdapter<string> endTimeZoneAdapter = new ArrayAdapter<string>(con, Android.Resource.Layout.SimpleSpinnerItem, TimeZoneCollection.TimeZoneList); endTimeZoneAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); endTimeZonePicker.Adapter = endTimeZoneAdapter; endTimeZonePicker.ItemSelected += EndTimeZone_Spinner_ItemSelected; inputControlLayout.AddView(timeLayout); var allDaylayout = new LinearLayout(con); allDaylayout.SetPadding(0, 10, 0, 0); allDaylayout.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, density.HeightPixels / 12); allDaylayout.Orientation = Orientation.Horizontal; TextView allDayLabel = new TextView(con); allDayLabel.Text = "All Day"; allDayLabel.TextSize = 18; allDayLabel.Gravity = GravityFlags.CenterVertical; allDayLabel.LayoutParameters = new ViewGroup.LayoutParams((density.WidthPixels / 2) - padding, LinearLayout.LayoutParams.MatchParent); allDayLabel.SetTextColor(Color.Black); allDaySwitch = new Switch(con); allDaySwitch.Checked = false; allDaySwitch.LayoutParameters = new ViewGroup.LayoutParams((density.WidthPixels / 2) - padding, LinearLayout.LayoutParams.MatchParent); allDaySwitch.Gravity = GravityFlags.CenterVertical; allDaySwitch.CheckedChange += AllDaySwitch_CheckedChange; allDaylayout.AddView(allDayLabel); allDaylayout.AddView(allDaySwitch); inputControlLayout.AddView(allDaylayout); var buttonlayout = new LinearLayout(con); buttonlayout.SetPadding(0, 10, 0, 0); buttonlayout.Orientation = Orientation.Horizontal; CancelButton = new Button(con); CancelButton.SetBackgroundColor(Color.LightGray); CancelButton.SetPadding(0, 10, 30, 10); CancelButton.LayoutParameters = new ViewGroup.LayoutParams((density.WidthPixels / 2) - padding, LinearLayout.LayoutParams.MatchParent); CancelButton.Text = "Cancel"; CancelButton.TextSize = 15; CancelButton.SetTextColor(Color.Black); buttonlayout.AddView(CancelButton); SaveButton = new Button(con); SaveButton.SetBackgroundColor(Color.ParseColor("#2196F3")); SaveButton.SetPadding(0, 10, 30, 10); SaveButton.LayoutParameters = new ViewGroup.LayoutParams((density.WidthPixels / 2) - padding, LinearLayout.LayoutParams.MatchParent); SaveButton.Text = "Save"; SaveButton.TextSize = 15; SaveButton.SetTextColor(Color.White); buttonlayout.AddView(SaveButton); inputControlLayout.AddView(buttonlayout); ScrollView.AddView(inputControlLayout); EditorLayout.AddView(ScrollView); HookEvents(); } private void AllDaySwitch_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { this.DisableChid(); } else { this.EnableChid(); } if (SelectedAppointment != null) { SelectedAppointment.IsAllDay = e.IsChecked; } } private void StartTimeZone_Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; if ((e.Parent.GetChildAt(0) as TextView) != null) { (e.Parent.GetChildAt(0) as TextView).TextSize = 18; } string selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); if (selectedItem != "Default" && SelectedAppointment != null) { SelectedAppointment.StartTimeZone = selectedItem; } } private void EndTimeZone_Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; if ((e.Parent.GetChildAt(0) as TextView) != null) { (e.Parent.GetChildAt(0) as TextView).TextSize = 18; } string selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); if (selectedItem != "Default" && SelectedAppointment != null) { SelectedAppointment.EndTimeZone = selectedItem; } } public void UpdateEditor(ScheduleAppointment appointment, Calendar date) { SelectedAppointment = appointment; selectedDate = date; if (appointment != null) { subjectInput.Text = appointment.Subject.ToString(); locationInput.Text = appointment.Location; startDateName.Text = dateFormat.Format(appointment.StartTime.Time); startTimeName.Text = timeFormat.Format(appointment.StartTime.Time); endDateName.Text = dateFormat.Format(appointment.EndTime.Time); endTimeName.Text = timeFormat.Format(appointment.EndTime.Time); startTime = appointment.StartTime; endTime = appointment.EndTime; allDaySwitch.Checked = appointment.IsAllDay; if (appointment.IsAllDay) { this.DisableChid(); } else { this.EnableChid(); } } else { subjectInput.Text = ""; startDateName.Text = dateFormat.Format(date.Time); startTimeName.Text = timeFormat.Format(date.Time) + " "; Calendar endTime1 = (Calendar)date.Clone(); endTime1.Add(CalendarField.Hour, 1); endDateName.Text = dateFormat.Format(endTime1.Time); endTimeName.Text = timeFormat.Format(endTime1.Time) + " "; startTime = date; endTime = endTime1; allDaySwitch.Checked = false; this.EnableChid(); } } /// <summary> /// Disable the time and timezone spinner while slecte the non all day appointment. /// </summary> private void DisableChid() { startTimeName.Text = "12:00 AM"; endTimeName.Text = "12:00 AM"; startTimeName.SetTextColor(Color.Gray); endTimeName.SetTextColor(Color.Gray); startTimeName.Enabled = false; startTimeName.Clickable = false; endTimeName.Enabled = false; endTimeName.Clickable = false; startTimeZonePicker.Enabled = false; startTimeZonePicker.Clickable = false; endTimeZonePicker.Enabled = false; endTimeZonePicker.Clickable = false; } /// <summary> /// Enable the time and timezone spinner while slecte the non all day appointment. /// </summary> private void EnableChid() { if (SelectedAppointment != null) { endTimeName.Text = timeFormat.Format(SelectedAppointment.EndTime.Time); startTimeName.Text = timeFormat.Format(SelectedAppointment.StartTime.Time); } else if (selectedDate != null) { startTimeName.Text = timeFormat.Format(selectedDate.Time) + " "; Calendar endTime = (Calendar)selectedDate.Clone(); endTime.Add(CalendarField.Hour, 1); endTimeName.Text = timeFormat.Format(endTime.Time) + " "; } startTimeName.SetTextColor(Color.Black); endTimeName.SetTextColor(Color.Black); startTimeName.Enabled = true; startTimeName.Clickable = true; endTimeName.Enabled = true; endTimeName.Clickable = true; startTimeZonePicker.Enabled = true; startTimeZonePicker.Clickable = true; endTimeZonePicker.Enabled = true; endTimeZonePicker.Clickable = true; } private void HookEvents() { startDateName.Click += StartDateName_Click; startTimeName.Click += StartTimeName_Click; endDateName.Click += EndDateName_Click; endTimeName.Click += EndTimeName_Click; CancelButton.Click += CancelButton_Click; SaveButton.Click += SaveButton_Click; } private void StartTimePickerCallback(object sender, TimePickerDialog.TimeSetEventArgs e) { Calendar modifiedTime = Calendar.Instance; modifiedTime.Set(CalendarField.HourOfDay, e.HourOfDay); modifiedTime.Set(CalendarField.Minute, e.Minute); startTimeName.Text = timeFormat.Format(modifiedTime.Time); startTime.Set(CalendarField.HourOfDay, e.HourOfDay); startTime.Set(CalendarField.Minute, e.Minute); endTime.Set(CalendarField.HourOfDay, e.HourOfDay + 1); endTime.Set(CalendarField.Minute, e.Minute); endTimeName.Text = timeFormat.Format(endTime.Time); startTimeName.Text = timeFormat.Format(modifiedTime.Time); } private void EndTimePickerCallback(object sender, TimePickerDialog.TimeSetEventArgs e) { Calendar modifiedTime = Calendar.Instance; modifiedTime.Set(CalendarField.HourOfDay, e.HourOfDay); modifiedTime.Set(CalendarField.Minute, e.Minute); endTimeName.Text = timeFormat.Format(modifiedTime.Time); endTime.Set(CalendarField.HourOfDay, e.HourOfDay); endTime.Set(CalendarField.Minute, e.Minute); endTimeName.Text = timeFormat.Format(modifiedTime.Time); } private void StartDatePickerCallback(object sender, DatePickerDialog.DateSetEventArgs e) { Calendar modifiedDate = Calendar.Instance; modifiedDate.Set(CalendarField.DayOfMonth, e.DayOfMonth); modifiedDate.Set(CalendarField.Month, e.Month); modifiedDate.Set(CalendarField.Year, e.Year); startDateName.Text = dateFormat.Format(modifiedDate.Time); startTimeName.Text = timeFormat.Format(modifiedDate.Time); Calendar startDatePickerDate = Calendar.Instance; startDatePickerDate.Set(CalendarField.DayOfMonth, e.DayOfMonth); startDatePickerDate.Set(CalendarField.Month, e.Month); startDatePickerDate.Set(CalendarField.Year, e.Year); startTime = (Calendar)startDatePickerDate.Clone(); startDateName.Text = dateFormat.Format(modifiedDate.Time); } private void EndDatePickerCallback(object sender, DatePickerDialog.DateSetEventArgs e) { Calendar modifiedDate = Calendar.Instance; modifiedDate.Set(CalendarField.DayOfMonth, e.DayOfMonth); modifiedDate.Set(CalendarField.Month, e.Month); modifiedDate.Set(CalendarField.Year, e.Year); endDateName.Text = dateFormat.Format(modifiedDate.Time); endTimeName.Text = timeFormat.Format(modifiedDate.Time); Calendar endDatePickerDate = Calendar.Instance; endDatePickerDate.Set(CalendarField.DayOfMonth, e.DayOfMonth); endDatePickerDate.Set(CalendarField.Month, e.Month); endDatePickerDate.Set(CalendarField.Year, e.Year); endTime = (Calendar)endDatePickerDate.Clone(); endDateName.Text = dateFormat.Format(modifiedDate.Time); } #endregion #region Events private void StartDateName_Click(object sender, EventArgs e) { DatePickerDialog datePickerDialog = new DatePickerDialog( con, StartDatePickerCallback, startTime.Get(CalendarField.Year), startTime.Get(CalendarField.Month), startTime.Get(CalendarField.DayOfMonth)); datePickerDialog.Show(); } private void StartTimeName_Click(object sender, EventArgs e) { TimePickerDialog timePicker = new TimePickerDialog( con, StartTimePickerCallback, startTime.Get(CalendarField.HourOfDay), startTime.Get(CalendarField.Minute), false); timePicker.Show(); } private void EndDateName_Click(object sender, EventArgs e) { DatePickerDialog datePickerDialog = new DatePickerDialog( con, EndDatePickerCallback, endTime.Get(CalendarField.Year), endTime.Get(CalendarField.Month), endTime.Get(CalendarField.DayOfMonth)); datePickerDialog.Show(); } private void EndTimeName_Click(object sender, EventArgs e) { TimePickerDialog timePicker = new TimePickerDialog( con, EndTimePickerCallback, endTime.Get(CalendarField.HourOfDay), endTime.Get(CalendarField.Minute), false); timePicker.Show(); } private void SaveButton_Click(object sender, EventArgs e) { if (SelectedAppointment == null) { SelectedAppointment = new ScheduleAppointment(); } SelectedAppointment.Subject = subjectInput.Text; SelectedAppointment.Location = locationInput.Text; SelectedAppointment.StartTime = (Calendar)startTime.Clone(); SelectedAppointment.EndTime = (Calendar)endTime.Clone(); SelectedAppointment.IsAllDay = allDaySwitch.Checked; EditorLayout.Visibility = ViewStates.Invisible; } private void CancelButton_Click(object sender, EventArgs e) { EditorLayout.Visibility = ViewStates.Invisible; } public void Dispose() { if (subjectInput != null) { subjectInput.Dispose(); subjectInput = null; } if (locationInput != null) { locationInput.Dispose(); locationInput = null; } if (allDaySwitch != null) { allDaySwitch.CheckedChange -= AllDaySwitch_CheckedChange; allDaySwitch.Dispose(); allDaySwitch = null; } if (endTimeZonePicker != null) { endTimeZonePicker.ItemSelected -= EndTimeZone_Spinner_ItemSelected; endTimeZonePicker.Dispose(); endTimeZonePicker = null; } if (startTimeZonePicker != null) { startTimeZonePicker.ItemSelected -= StartTimeZone_Spinner_ItemSelected; startTimeZonePicker.Dispose(); startTimeZonePicker = null; } if (startDateName != null) { startDateName.Click -= StartDateName_Click; startDateName.Dispose(); startDateName = null; } if (startTimeName != null) { startTimeName.Click -= StartTimeName_Click; startTimeName.Dispose(); startTimeName = null; } if (endDateName != null) { endDateName.Click -= EndDateName_Click; endDateName.Dispose(); endDateName = null; } if (endTimeName != null) { endTimeName.Click -= EndTimeName_Click; endTimeName.Dispose(); endTimeName = null; } if (dateFormat != null) { dateFormat.Dispose(); dateFormat = null; } if (timeFormat != null) { timeFormat.Dispose(); timeFormat = null; } } #endregion } }<file_sep>/Forms/Chart/Chart/Samples/StackedBarChart/StackedBarSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class StackedBarSeriesViewModel { public ObservableCollection<ChartDataModel> StackedBarData1 { get; set; } public ObservableCollection<ChartDataModel> StackedBarData2 { get; set; } public ObservableCollection<ChartDataModel> StackedBarData3 { get; set; } public StackedBarSeriesViewModel() { StackedBarData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 12), new ChartDataModel("Apr", 15.5), new ChartDataModel("May", 20), new ChartDataModel("Jun", 24), }; StackedBarData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 11), new ChartDataModel("Apr", 16), new ChartDataModel("May", 21), new ChartDataModel("Jun", 25), }; StackedBarData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", -1), new ChartDataModel("Feb", -1.5), new ChartDataModel("Mar", -2), new ChartDataModel("Apr", -2.5), new ChartDataModel("May", -3), new ChartDataModel("Jun", -3.5), }; } } }<file_sep>/Forms/TabView/TabView/Samples/TabViewGettingStarted/ViewModel/TabDataViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System.Collections.ObjectModel; namespace SampleBrowser.SfTabView { internal class TabDataViewModel { internal ObservableCollection<TabData> Data = new ObservableCollection<TabData>(); internal ObservableCollection<string> Categories = new ObservableCollection<string>(); private ObservableCollection<string> NamesCollection = new ObservableCollection<string>(); private ObservableCollection<double> PriceCollection = new ObservableCollection<double>(); private ObservableCollection<string> OffersCollection = new ObservableCollection<string>(); private ObservableCollection<string> RatingCollection = new ObservableCollection<string>(); private ObservableCollection<string> ImageCollection = new ObservableCollection<string>(); private ObservableCollection<string> DescriptionCollection = new ObservableCollection<string>(); private int index = 0; public TabDataViewModel() { this.SetTabViewDataValuess(); this.AddTabData(); } private void SetTabViewDataValuess() { this.SetCategories(); this.SetNames(); this.SetPrices(); this.SetOffers(); this.SetRatings(); this.SetImages(); this.SetDescription(); } private void AddTabData() { index = 0; foreach (var category in Categories) { for (int j = 0; j < 5; j++) { Data.Add(new TabData { Category = category, Name = NamesCollection[index], Price = PriceCollection[index], Rating = RatingCollection[index], Offer = OffersCollection[index], ImagePath = ImageCollection[index], Description = DescriptionCollection[index] }); index++; } } } private void SetCategories() { Categories.Add("Furniture"); Categories.Add("Clothing"); Categories.Add("Shoes"); Categories.Add("Fruits"); Categories.Add("Toys"); } private void SetNames() { NamesCollection.Add("Leather Black Sofa"); NamesCollection.Add("Wooden Standing Drawer"); NamesCollection.Add("Semi Fabric Sofa"); NamesCollection.Add("Dinning Chair"); NamesCollection.Add("Fabric White Sofa"); NamesCollection.Add("Long Sleeve Cotton Shirt"); NamesCollection.Add("Denim Jeans"); NamesCollection.Add("Short Sleeve T-Shirt"); NamesCollection.Add("Casual Shirt Semi-Fit"); NamesCollection.Add("Classic Slim Fit Suit"); NamesCollection.Add("Light weight Shoes"); NamesCollection.Add("Trendy Grey Shoes"); NamesCollection.Add("Classic Formal Shoes"); NamesCollection.Add("White Sporty Shoes"); NamesCollection.Add("Trendy Brown Shoes"); NamesCollection.Add("Orange"); NamesCollection.Add("Blueberries (Imported)"); NamesCollection.Add("Apple"); NamesCollection.Add("Strawberry"); NamesCollection.Add("Banana"); NamesCollection.Add("Warriors"); NamesCollection.Add("Robots"); NamesCollection.Add("Mario collections"); NamesCollection.Add("Train simulation"); NamesCollection.Add("Icecream Truck"); } private void SetPrices() { PriceCollection.Add(99.50); PriceCollection.Add(299.40); PriceCollection.Add(149.90); PriceCollection.Add(129.40); PriceCollection.Add(199.50); PriceCollection.Add(9.50); PriceCollection.Add(7.97); PriceCollection.Add(4.55); PriceCollection.Add(5.97); PriceCollection.Add(18.47); PriceCollection.Add(25.11); PriceCollection.Add(20.21); PriceCollection.Add(11.29); PriceCollection.Add(35.75); PriceCollection.Add(74.32); PriceCollection.Add(59.11); PriceCollection.Add(12.44); PriceCollection.Add(16.37); PriceCollection.Add(29.45); PriceCollection.Add(29.97); PriceCollection.Add(43.11); PriceCollection.Add(2.44); PriceCollection.Add(6.37); PriceCollection.Add(9.45); PriceCollection.Add(9.97); } private void SetRatings() { RatingCollection.Add("3.9"); RatingCollection.Add("4.1"); RatingCollection.Add("4.4"); RatingCollection.Add("3.7"); RatingCollection.Add("4.5"); RatingCollection.Add("4.7"); RatingCollection.Add("4.2"); RatingCollection.Add("3.5"); RatingCollection.Add("3.9"); RatingCollection.Add("4.1"); RatingCollection.Add("4.9"); RatingCollection.Add("4.1"); RatingCollection.Add("4.5"); RatingCollection.Add("4.3"); RatingCollection.Add("4.1"); RatingCollection.Add("4.4"); RatingCollection.Add("3.9"); RatingCollection.Add("3.7"); RatingCollection.Add("4.3"); RatingCollection.Add("4.1"); RatingCollection.Add("4.5"); RatingCollection.Add("3.9"); RatingCollection.Add("4.1"); RatingCollection.Add("4.9"); RatingCollection.Add("4.1"); } private void SetDescription() { DescriptionCollection.Add("Warrenty coverred upto 5 years.Its specialty is its bookcase headboard which serves as an easy access to users.Bring a new member into your family.Delivered in non - assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight."); DescriptionCollection.Add("Warrenty coverred upto 5 years.Its specialty is its bookcase headboard which serves as an easy access to users.Bring a new member into your family.Delivered in non - assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight."); DescriptionCollection.Add("High quality material has been used. Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight."); DescriptionCollection.Add("High quality material has been used. Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight."); DescriptionCollection.Add("High quality material has been used. Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); } private void SetOffers() { OffersCollection.Add("5% Offer"); OffersCollection.Add("1% Offer"); OffersCollection.Add("10% Offer"); OffersCollection.Add("15% Offer"); OffersCollection.Add("20% Offer"); OffersCollection.Add("5% Offer"); OffersCollection.Add("10% Offer"); OffersCollection.Add("15% Offer"); OffersCollection.Add("20% Offer"); OffersCollection.Add("15% Offer"); OffersCollection.Add("5% Offer"); OffersCollection.Add("10% Offer"); OffersCollection.Add("10% Offer"); OffersCollection.Add("10% Offer"); OffersCollection.Add("20% Offer"); OffersCollection.Add("30% Offer"); OffersCollection.Add("15% Offer"); OffersCollection.Add("20% Offer"); OffersCollection.Add("35% Offer"); OffersCollection.Add("10% Offer"); OffersCollection.Add("5% Offer"); OffersCollection.Add("15% Offer"); OffersCollection.Add("20% Offer"); OffersCollection.Add("15% Offer"); OffersCollection.Add("10% Offer"); } private void SetImages() { ImageCollection.Add("BlackSofa.jpg"); ImageCollection.Add("TVShelf.jpg"); ImageCollection.Add("GraySofa.jpg"); ImageCollection.Add("Chair.jpg"); ImageCollection.Add("AngleSofa.jpg"); ImageCollection.Add("Whiteshirt.jpg"); ImageCollection.Add("Shirt.jpg"); ImageCollection.Add("Tshirt.jpg"); ImageCollection.Add("Redcoat.jpg"); ImageCollection.Add("Silvercoat.jpg"); ImageCollection.Add("Canvas.jpg"); ImageCollection.Add("Graycanvas.jpg"); ImageCollection.Add("Boots.jpg"); ImageCollection.Add("Blackshoe.jpg"); ImageCollection.Add("Leather.jpg"); ImageCollection.Add("Orange.jpg"); ImageCollection.Add("Blueberry.jpg"); ImageCollection.Add("Apple.jpg"); ImageCollection.Add("Strawberry.jpg"); ImageCollection.Add("Banana.jpg"); ImageCollection.Add("Friends_Toy.jpg"); ImageCollection.Add("Robot.jpg"); ImageCollection.Add("Mario.jpg"); ImageCollection.Add("Train.jpg"); ImageCollection.Add("Van.jpg"); } } } <file_sep>/Forms/TreeMap/TreeMap/Samples/Hierarchical/HierarchicalModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeMap { [Preserve(AllMembers = true)] public class CountrySale { public string Name { get; set; } private double _sales = 0; public double Sales { get { return _sales; } set { if (_sales != value) { _sales = value; } } } private double _expense = 0; public double Expense { get { return _expense; } set { if (_expense != value) { _expense = value; } } } public ObservableCollection<RegionSale> RegionalSales { get; set; } public CountrySale() { this.RegionalSales = new ObservableCollection<RegionSale>(); } } public class RegionSale { public string Name { get; set; } public string Country { get; set; } private double _sales = 0; public double Sales { get { return _sales; } set { if (_sales != value) { _sales = value; } } } public double Expense { get; set; } } } <file_sep>/Forms/RangeSlider/RangeSlider/Samples/Orientation/Orientation.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfRangeSlider.XForms; using Xamarin.Forms; namespace SampleBrowser.SfRangeSlider { public partial class Orientation : SampleView { public Orientation() { InitializeComponent(); sfRangeSlider1.LabelFormat = "{0:N0}db"; sfRangeSlider2.LabelFormat = "{0:N0}db"; sfRangeSlider3.LabelFormat = "{0:N0}db"; hertzLabel.HorizontalTextAlignment = TextAlignment.Center; //decibelLabel.HorizontalTextAlignment = TextAlignment.Center; //hertzLabel1.HorizontalTextAlignment = TextAlignment.Center; //decibelLabel1.HorizontalTextAlignment = TextAlignment.Center; //hertzLabel2.HorizontalTextAlignment = TextAlignment.Center; //decibelLabel2.HorizontalTextAlignment = TextAlignment.Center; DeviceChanges(); if (App.Current.MainPage != null && App.Current.MainPage.Visual == VisualMarker.Material) { this.SetMaterialValues(sfRangeSlider1); this.SetMaterialValues(sfRangeSlider2); this.SetMaterialValues(sfRangeSlider3); } } void DeviceChanges() { if ((Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone)) { sfRangeSlider1.KnobColor = sfRangeSlider2.KnobColor = sfRangeSlider3.KnobColor = Color.Black; if (Device.Idiom == TargetIdiom.Phone) { EqualizerLabel.HeightRequest = 40; sfRangeSlider1.WidthRequest = 140; sfRangeSlider2.WidthRequest = 140; sfRangeSlider3.WidthRequest = 140; SecondSlider.Margin = new Thickness(-80, 0, 0, 0); ThirdSlider.Margin = new Thickness(-90, 0, 0, 0); MainRangeSlider.Margin = new Thickness(0, -50, 0, 0); } if (Device.Idiom == TargetIdiom.Desktop) { sfRangeSlider1.WidthRequest = 130; sfRangeSlider2.WidthRequest = 130; sfRangeSlider3.WidthRequest = 130; } } else { hertzLabel.FontSize = 20; hertzLabel.Text = "60 Hz"; hertzLabel.HeightRequest = 24; hertzLabel.VerticalTextAlignment = TextAlignment.Center; hertzLabel.TextColor = Color.FromRgb(109, 109, 114); hertzLabel.HorizontalTextAlignment = TextAlignment.Center; hertzLabel1.FontSize = 20; hertzLabel1.Text = "170 Hz"; hertzLabel1.HeightRequest = 24; hertzLabel1.VerticalTextAlignment = TextAlignment.Center; hertzLabel1.TextColor = Color.FromRgb(109, 109, 114); hertzLabel1.HorizontalTextAlignment = TextAlignment.Center; hertzLabel2.FontSize = 20; hertzLabel2.Text = "310 Hz"; hertzLabel2.HeightRequest = 24; hertzLabel2.VerticalTextAlignment = TextAlignment.Center; hertzLabel2.TextColor = Color.FromRgb(109, 109, 114); hertzLabel2.HorizontalTextAlignment = TextAlignment.Center; } if (Device.RuntimePlatform == Device.Android) { SecondSlider.Margin = new Thickness(-30, 0, 0, 0); ThirdSlider.Margin = new Thickness(-30, 0, 0, 0); sfRangeSlider1.HorizontalOptions = LayoutOptions.Center; sfRangeSlider2.HorizontalOptions = LayoutOptions.Center; sfRangeSlider3.HorizontalOptions = LayoutOptions.Center; sfRangeSlider1.WidthRequest = 90; sfRangeSlider2.WidthRequest = 90; sfRangeSlider3.WidthRequest = 90; } if (Device.RuntimePlatform == Device.UWP) { sfRangeSlider1.TrackThickness = sfRangeSlider2.TrackThickness = sfRangeSlider3.TrackThickness = 8; sfRangeSlider1.TrackCornerRadius = sfRangeSlider2.TrackCornerRadius = sfRangeSlider3.TrackCornerRadius = 5; } if (Device.RuntimePlatform == Device.iOS) { sfRangeSlider1.TrackSelectionColor = Color.Transparent; sfRangeSlider2.TrackSelectionColor = Color.Transparent; sfRangeSlider3.TrackSelectionColor = Color.Transparent; sfRangeSlider1.TrackThickness = 10; sfRangeSlider2.TrackThickness = 10; sfRangeSlider3.TrackThickness = 10; sfRangeSlider1.ShowValueLabel = true; sfRangeSlider2.ShowValueLabel = true; sfRangeSlider3.ShowValueLabel = true; if (Device.Idiom == TargetIdiom.Phone) { sfRangeSlider1.WidthRequest = 90; sfRangeSlider2.WidthRequest = 90; sfRangeSlider3.WidthRequest = 90; sfRangeSlider1.Margin = new Thickness(5, 0, 0, 0); sfRangeSlider2.Margin = new Thickness(5, 0, 0, 0); sfRangeSlider3.Margin = new Thickness(5, 0, 0, 0); sfRangeSlider1.HeightRequest = 300; sfRangeSlider2.HeightRequest = 300; sfRangeSlider3.HeightRequest = 300; if (App.Current.MainPage != null) { if (App.Current.MainPage.Visual != VisualMarker.Material) { sfRangeSlider1.KnobColor = Color.White; sfRangeSlider2.KnobColor = Color.White; sfRangeSlider3.KnobColor = Color.White; } } else { sfRangeSlider1.KnobColor = Color.White; sfRangeSlider2.KnobColor = Color.White; sfRangeSlider3.KnobColor = Color.White; } MainRangeSlider.VerticalOptions = LayoutOptions.FillAndExpand; } else if (Device.Idiom == TargetIdiom.Tablet) { sfRangeSlider1.WidthRequest = 90; sfRangeSlider2.WidthRequest = 90; sfRangeSlider3.WidthRequest = 90; sfRangeSlider1.HeightRequest = 600; sfRangeSlider2.HeightRequest = 600; sfRangeSlider3.HeightRequest = 600; if (App.Current.MainPage != null) { if (App.Current.MainPage.Visual != VisualMarker.Material) { sfRangeSlider1.KnobColor = Color.White; sfRangeSlider2.KnobColor = Color.White; sfRangeSlider3.KnobColor = Color.White; } } else { sfRangeSlider1.KnobColor = Color.White; sfRangeSlider2.KnobColor = Color.White; sfRangeSlider3.KnobColor = Color.White; } MainRangeSlider.VerticalOptions = LayoutOptions.FillAndExpand; } } else if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { sfRangeSlider1.WidthRequest = 120; sfRangeSlider2.WidthRequest = 120; sfRangeSlider3.WidthRequest = 120; sfRangeSlider1.HeightRequest = 600; sfRangeSlider2.HeightRequest = 600; sfRangeSlider3.HeightRequest = 600; sfRangeSlider1.KnobColor = Color.Gray; sfRangeSlider2.KnobColor = Color.Gray; sfRangeSlider3.KnobColor = Color.Gray; sfRangeSlider1.TrackSelectionColor = Color.Gray; sfRangeSlider2.TrackSelectionColor = Color.Gray; sfRangeSlider3.TrackSelectionColor = Color.Gray; } else if (Device.RuntimePlatform == Device.UWP && Device.Idiom != TargetIdiom.Tablet) { MainRangeSlider.HeightRequest = 450; sfRangeSlider1.ShowValueLabel = false; sfRangeSlider2.ShowValueLabel = false; sfRangeSlider3.ShowValueLabel = false; sfRangeSlider1.TrackSelectionColor = sfRangeSlider2.TrackSelectionColor = sfRangeSlider3.TrackSelectionColor = Color.Gray; sfRangeSlider1.TrackColor = sfRangeSlider2.TrackColor = sfRangeSlider3.TrackColor = Color.Gray; } sfRangeSlider1.ValueChanging += (object sender, ValueEventArgs e) => { double f = Math.Round(e.Value, 1); hertzLabel.Text = (f + 12) * 100 + " Hz"; }; sfRangeSlider2.ValueChanging += (object sender, ValueEventArgs e) => { double f = Math.Round(e.Value, 1); hertzLabel1.Text = (f + 12) * 100 + " Hz"; }; sfRangeSlider3.ValueChanging += (object sender, ValueEventArgs e) => { double f = Math.Round(e.Value, 1); hertzLabel2.Text = (f + 12) * 100 + "Hz"; }; if ((Device.Idiom == TargetIdiom.Tablet) && (Device.RuntimePlatform != Device.iOS)) { MainRangeSlider.HorizontalOptions = LayoutOptions.Center; MainRangeSlider.Padding = new Thickness(10, 40, 0, 0); FirstSlider.Padding = new Thickness(10, 40, 40, 0); SecondSlider.Padding = new Thickness(10, 40, 40, 0); ThirdSlider.Padding = new Thickness(10, 40, 40, 0); } else if (Device.RuntimePlatform != Device.iOS) { MainRangeSlider.HorizontalOptions = LayoutOptions.Center; MainRangeSlider.Padding = new Thickness(0, 20, 0, 0); FirstSlider.Padding = new Thickness(0, 20, 40, 0); SecondSlider.Padding = new Thickness(0, 20, 40, 0); ThirdSlider.Padding = new Thickness(0, 20, 40, 0); } } public View getContent() { return this.Content; } /// <summary> /// Set the color values for material /// </summary> /// <param name="rangeSlider"></param> private void SetMaterialValues(Syncfusion.SfRangeSlider.XForms.SfRangeSlider rangeSlider) { if (Device.RuntimePlatform != Device.UWP) { rangeSlider.LabelColor = Color.FromRgba(0, 0, 0, 200); } } } } <file_sep>/Forms/PDF/PDF/Samples/GettingStartedPDF/GettingStartedPDF.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Interactive; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.PDF { public partial class GettingStartedPDF : SampleView { PdfDocument doc; PdfPage page; Syncfusion.Drawing.Color gray = Syncfusion.Drawing.Color.FromArgb(255, 77, 77, 77); Syncfusion.Drawing.Color black = Syncfusion.Drawing.Color.FromArgb(255, 0, 0, 0); Syncfusion.Drawing.Color white = Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255); Syncfusion.Drawing.Color violet = Syncfusion.Drawing.Color.FromArgb(255, 151, 108, 174); public GettingStartedPDF() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { //Create new PDF document. doc = new PdfDocument(); //Set margin. doc.PageSettings.Margins.All = 0; //Add page to the PDF document. page = doc.Pages.Add(); //Create graphics instance. PdfGraphics g = page.Graphics; //Create font object PdfFont headerFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 35); PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16); g.DrawRectangle(new PdfSolidBrush(gray), new RectangleF(0, 0, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height)); g.DrawRectangle(new PdfSolidBrush(black), new RectangleF(0, 0, page.Graphics.ClientSize.Width, 130)); g.DrawRectangle(new PdfSolidBrush(white), new RectangleF(0, 400, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height - 450)); g.DrawString("Syncfusion", headerFont, new PdfSolidBrush(violet), new PointF(10, 20)); g.DrawRectangle(new PdfSolidBrush(violet), new RectangleF(10, 63, 155, 35)); g.DrawString("File Formats", subHeadingFont, new PdfSolidBrush(black), new PointF(45, 70)); PdfLayoutResult result = HeaderPoints("Optimized for usage in a server environment where spread and low memory usage in critical.", 15); result = HeaderPoints("Proven, reliable platform thousands of users over the past 10 years.", result.Bounds.Bottom + 15); result = HeaderPoints("Microsoft Excel, Word, Presentation, PDF and PDF Viewer.", result.Bounds.Bottom + 15); result = HeaderPoints("Why start from scratch? Rely on our dependable solution frameworks.", result.Bounds.Bottom + 15); result = BodyContent("Deployment-ready framework tailored to your needs.", result.Bounds.Bottom + 45); result = BodyContent("Enable your applications to read and write file formats documents easily.", result.Bounds.Bottom + 25); result = BodyContent("Solutions available for web, desktop, and mobile applications.", result.Bounds.Bottom + 25); result = BodyContent("Backed by our end-to-end product maintenance infrastructure.", result.Bounds.Bottom + 25); result = BodyContent("The quickest path from concept to delivery.", result.Bounds.Bottom + 25); PdfPen redPen = new PdfPen(PdfBrushes.Red, 2); g.DrawLine(redPen, new PointF(40, result.Bounds.Bottom + 92), new PointF(40, result.Bounds.Bottom + 145)); float headerBulletsXposition = 40; //Create text element to draw continously. PdfTextElement txtElement = new PdfTextElement("The Experts"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 90, 450, 200)); PdfPen violetPen = new PdfPen(PdfBrushes.Violet, 2); g.DrawLine(violetPen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 92), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 145)); txtElement = new PdfTextElement("Accurate Estimates"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 90, 450, 200)); txtElement = new PdfTextElement("A substantial number of .NET reporting applications use our frameworks."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200)); txtElement = new PdfTextElement("Given our expertise, you can expect estimates to be accurate."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200)); PdfPen greenPen = new PdfPen(PdfBrushes.Green, 2); g.DrawLine(greenPen, new PointF(40, result.Bounds.Bottom + 32), new PointF(40, result.Bounds.Bottom + 85)); txtElement = new PdfTextElement("No-Hassle Licensing"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 30, 450, 200)); PdfPen bluePen = new PdfPen(PdfBrushes.Blue, 2); g.DrawLine(bluePen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 32), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 85)); txtElement = new PdfTextElement("About Syncfusion"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 30, 450, 200)); txtElement = new PdfTextElement("No royalties, run time, or server deployment fees means no surprises."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200)); txtElement = new PdfTextElement("Syncfusion offers over 1,000 components and frameworks for mobile, web, and desktop development."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200)); #if COMMONSB Stream imgStream = typeof(GettingStartedPDF).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Xamarin_bannerEdit.jpg"); #else Stream imgStream = typeof(GettingStartedPDF).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Xamarin_bannerEdit.jpg"); #endif g.DrawImage(PdfImage.FromStream(imgStream), 180, 630, 280, 150); g.DrawString("All trademarks mentioned belong to their owners.", new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic), PdfBrushes.White, new PointF(10, g.ClientSize.Height - 30)); //Create text web link annotation. PdfTextWebLink linkAnnot = new PdfTextWebLink(); linkAnnot.Url = "http://www.syncfusion.com"; linkAnnot.Text = "www.syncfusion.com"; linkAnnot.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic); linkAnnot.Brush = PdfBrushes.White; linkAnnot.DrawTextWebLink(page, new PointF(g.ClientSize.Width - 100, g.ClientSize.Height - 30)); MemoryStream stream = new MemoryStream(); //Save the PDF document doc.Save(stream); //Close the PDF document doc.Close(true); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("GettingStarted.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("GettingStarted.pdf", "application/pdf", stream); } private PdfLayoutResult BodyContent(string text, float yPosition) { float headerBulletsXposition = 35; PdfTextElement txtElement = new PdfTextElement("3"); txtElement.Font = new PdfStandardFont(PdfFontFamily.ZapfDingbats, 16); txtElement.Brush = new PdfSolidBrush(violet); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; txtElement.Draw(page, new RectangleF(headerBulletsXposition, yPosition, 320, 100)); txtElement = new PdfTextElement(text); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 17); txtElement.Brush = new PdfSolidBrush(white); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; PdfLayoutResult result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 25, yPosition, 450, 130)); return result; } private PdfLayoutResult HeaderPoints(string text, float yPosition) { float headerBulletsXposition = 220; PdfTextElement txtElement = new PdfTextElement("l"); txtElement.Font = new PdfStandardFont(PdfFontFamily.ZapfDingbats, 10); txtElement.Brush = new PdfSolidBrush(violet); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; txtElement.Draw(page, new RectangleF(headerBulletsXposition, yPosition, 300, 100)); txtElement = new PdfTextElement(text); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11); txtElement.Brush = new PdfSolidBrush(white); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; PdfLayoutResult result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 20, yPosition, 320, 100)); return result; } } } <file_sep>/Forms/Chat/Chat/Samples/LoadMore/LoadMoreBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfChat { using SampleBrowser.Core; using Syncfusion.XForms.BadgeView; using Syncfusion.XForms.Chat; using System; using System.Collections.Specialized; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the flight booking sample. /// </summary> public class LoadMoreBehavior : Behavior<SampleView> { /// <summary> /// flight booking view model. /// </summary> private LoadMoreViewModel viewModel; /// <summary> /// sfChat control instance. /// </summary> private SfChat sfChat; /// <summary> /// load more behavior picker. /// </summary> private PickerExt LoadMorePicker; /// <summary> /// sfBadgeView control instance. /// </summary> private SfBadgeView sfBadgeView; /// <summary> /// sfBadgeView badge settings instance. /// </summary> private BadgeSetting badgeSetting; /// <summary> /// The page that hosts the load more sameple. /// </summary> private SampleView sampleView; /// <summary> /// The main view that contains the SfChat instance. /// </summary> private LoadMoreView loadMoreView; /// <summary> /// Tap recognizer for badge view. /// </summary> private TapGestureRecognizer tap; /// <summary> /// Method will be called when the view is attached to the window /// </summary> /// <param name="bindable">SampleView type parameter as bindable</param> protected override void OnAttachedTo(SampleView bindable) { this.sampleView = bindable; tap = new TapGestureRecognizer(); tap.Tapped += ScrollToBottom; this.LoadMorePicker = bindable.FindByName<PickerExt>("LoadMoreBehaviorPicker"); this.LoadMorePicker.Items.Add("Manual"); this.LoadMorePicker.Items.Add("Auto"); this.LoadMorePicker.SelectedIndexChanged += LoadMoreSelectedIndexChanged; this.InitViews(bindable); base.OnAttachedTo(bindable); } private void InitViews(View sampleView = null) { if (sampleView != null) { this.loadMoreView = sampleView.FindByName<LoadMoreView>("LoadMoreView"); this.sfChat = loadMoreView.FindByName<SfChat>("sfChat"); this.viewModel = loadMoreView.FindByName<LoadMoreViewModel>("viewModel"); this.InitBadgeView(loadMoreView.FindByName<SfBadgeView>("ScrollDown")); this.sfChat.Scrolled += ChatScrolled; } else { this.loadMoreView = new LoadMoreView(); this.sfChat = loadMoreView.FindByName<SfChat>("sfChat"); this.viewModel = loadMoreView.FindByName<LoadMoreViewModel>("viewModel"); this.InitBadgeView(loadMoreView.FindByName<SfBadgeView>("ScrollDown")); this.sfChat.Scrolled += ChatScrolled; } } /// <summary> /// Initializes the badge view. /// </summary> private void InitBadgeView(SfBadgeView badgeView) { this.sfBadgeView = badgeView; this.sfBadgeView.GestureRecognizers.Add(tap); badgeSetting = new BadgeSetting(); badgeSetting.BadgeType = BadgeType.Primary; badgeSetting.BadgePosition = BadgePosition.TopLeft; badgeSetting.Offset = new Point(1, 3); sfBadgeView.BadgeSettings = badgeSetting; } /// <summary> /// Raised when the image button tapped. /// </summary> /// <param name="sender">The object as sender.</param> /// <param name="e">EventArgs as e.</param> private void ScrollToBottom(object sender, EventArgs e) { this.sfChat.ScrollToMessage(sfChat.Messages[sfChat.Messages.Count - 1]); } /// <summary> /// Raised when the chat scrolled. /// </summary> /// <param name="sender">The object as sender.</param> /// <param name="e">ChatScrolledEventArgs as e.</param> private void ChatScrolled(object sender, ChatScrolledEventArgs e) { sfChat.CanAutoScrollToBottom = e.IsBottomReached; viewModel.IsVisible = !e.IsBottomReached; } /// <summary> /// Triggers while selected Index was changed, used to set a Load More Behavior /// </summary> /// <param name="sender">OnSelectionChanged event sender</param> /// <param name="e">EventArgs e</param> private void LoadMoreSelectedIndexChanged(object sender, EventArgs e) { if (this.LoadMorePicker.SelectedIndex == 0) { if (this.sfChat.LoadMoreBehavior != Syncfusion.ListView.XForms.LoadMoreOption.Manual) { this.Dispose(); this.sampleView.Content = null; this.InitViews(); this.sampleView.Content = this.loadMoreView; this.viewModel.LoadMoreBehavior = Syncfusion.ListView.XForms.LoadMoreOption.Manual; } } else if (this.LoadMorePicker.SelectedIndex == 1) { if (this.sfChat.LoadMoreBehavior != Syncfusion.ListView.XForms.LoadMoreOption.Auto) { this.Dispose(); this.sampleView.Content = null; this.InitViews(); this.sampleView.Content = this.loadMoreView; this.viewModel.LoadMoreBehavior = Syncfusion.ListView.XForms.LoadMoreOption.Auto; } } } /// <summary> /// Disposes the created instances. /// </summary> private void Dispose() { this.sfChat.Scrolled -= ChatScrolled; if (this.sfChat != null) { this.sfChat.Dispose(); this.sfChat = null; } if (this.viewModel != null) { this.viewModel = null; } } /// <summary> /// Method will be called when the view is detached from window /// </summary> /// <param name="bindable">SampleView type of bindAble parameter</param> protected override void OnDetachingFrom(SampleView bindable) { this.LoadMorePicker.SelectedIndexChanged -= LoadMoreSelectedIndexChanged; this.Dispose(); this.tap.Tapped -= ScrollToBottom; this.tap = null; base.OnDetachingFrom(bindable); } } } <file_sep>/Forms/DataForm/DataForm/Samples/DynamicFormPage/Helper/SfDataFormDynamicFormBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.DataForm; using Syncfusion.XForms.DataForm.Editors; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Text; using Xamarin.Forms; using Syncfusion.XForms.ComboBox; namespace SampleBrowser.SfDataForm { /// <summary> /// Represents the behavior of the data form getting started sample. /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public class SfDataFormDynamicFormBehavior : Behavior<Syncfusion.XForms.DataForm.SfDataForm> { /// <summary> /// DataForm control to edit the data fields of any data object /// </summary> private Syncfusion.XForms.DataForm.SfDataForm dataForm; /// <summary> /// Attaches to the superclass and then calls the OnAttachedTo method on this object. /// </summary> /// <param name="bindable">The bindable object to which the behavior was attached.</param> protected override void OnAttachedTo(Syncfusion.XForms.DataForm.SfDataForm bindable) { this.dataForm = bindable; this.dataForm.SourceProvider = new SourceProviderExt(); this.dataForm.ColumnCount = 4; dataForm.RegisterEditor("Team", "DropDown"); dataForm.RegisterEditor("Trackhours", "Switch"); dataForm.RegisterEditor("Country", "AutoComplete"); dataForm.RegisterEditor("EcommerceCountry", "AutoComplete"); dataForm.RegisterEditor("OrganizationCountry", "AutoComplete"); dataForm.AutoGeneratingDataFormItem += DataForm_AutoGeneratingDataFormItem; base.OnAttachedTo(bindable); } /// <summary> /// Occurs during the auto generation of the data form item. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Data form item event arguments.</param> private void DataForm_AutoGeneratingDataFormItem(object sender, AutoGeneratingDataFormItemEventArgs e) { if(e.DataFormItem != null) { if (e.DataFormItem.Name.Equals("Trackhours")) { e.DataFormItem.LayoutOptions = LayoutType.Default; } else if (e.DataFormItem.Name.Equals("CCV")) { var maskedItem = e.DataFormItem as DataFormMaskedEditTextItem; maskedItem.Mask = "000"; maskedItem.PromptChar = '*'; maskedItem.KeyBoard = Keyboard.Numeric; } else if (e.DataFormItem.Name.Equals("CardNumber")) { var maskedItem = e.DataFormItem as DataFormMaskedEditTextItem; maskedItem.Mask = "0000-0000-0000-0000"; maskedItem.KeyBoard = Keyboard.Numeric; } else if (e.DataFormItem.Name.Equals("ExpirationDate")) { var maskedItem = e.DataFormItem as DataFormMaskedEditTextItem; maskedItem.Mask = "00/00"; maskedItem.KeyBoard = Keyboard.Numeric; } else if (e.DataFormItem.Name.Equals("EmployeeZip") || e.DataFormItem.Name.Equals("Zip") || e.DataFormItem.Name.Equals("ZipCode")) { var maskedItem = e.DataFormItem as DataFormMaskedEditTextItem; maskedItem.Mask = "000000"; maskedItem.PromptChar = '_'; maskedItem.KeyBoard = Keyboard.Numeric; } else if (e.DataFormItem.Name.Equals("Code")) { var maskedItem = e.DataFormItem as DataFormMaskedEditTextItem; maskedItem.Mask = "000"; maskedItem.PromptChar = '_'; maskedItem.KeyBoard = Keyboard.Numeric; } else if (e.DataFormItem.Name.Equals("PhoneNumber") || e.DataFormItem.Name.Equals("Phone")) { var item = (e.DataFormItem as DataFormMaskedEditTextItem); item.Mask = "+(00)0000000000"; item.KeyBoard = Keyboard.Telephone; } else if (e.DataFormItem.Name.Equals("ContactEmail")) { var textItem = e.DataFormItem as DataFormTextItem; textItem.KeyBoard = Keyboard.Email; } else if (e.DataFormItem.Name.Equals("Country") || e.DataFormItem.Name.Equals("EcommerceCountry") || e.DataFormItem.Name.Equals("OrganizationCountry")) { var autoCompleteItem = e.DataFormItem as DataFormAutoCompleteItem; autoCompleteItem.TextHighlightMode = Syncfusion.XForms.DataForm.OccurrenceMode.FirstOccurrence; autoCompleteItem.HighlightedTextColor = Color.Red; } if (this.dataForm.DataObject is EmployeeForm) { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { OutlineCornerRadius = 30, ReserveSpaceForAssistiveLabels = false, ShowHelperText = false, }; e.DataFormItem.HintLabelStyle = new LabelStyle() { FontSize = 18 }; } else { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { ReserveSpaceForAssistiveLabels = false, ShowHelperText = false }; } if(e.DataFormItem.Name.Equals("OrganizationName") || e.DataFormItem.Name.Equals("AddressLine1") || e.DataFormItem.Name.Equals("AddressLine2") || (e.DataFormItem.Name.Equals("ContactEmail") || (e.DataFormItem.Name.Equals("OrganizationCountry")))) { e.DataFormItem.ColumnSpan = 4; } } } /// <summary> /// Calls the OnDetachingFrom method and then detaches from the superclass. /// </summary> /// <param name="bindable">The bindable object from which the behavior was detached.</param> protected override void OnDetachingFrom(Syncfusion.XForms.DataForm.SfDataForm bindable) { base.OnDetachingFrom(bindable); dataForm.AutoGeneratingDataFormItem -= DataForm_AutoGeneratingDataFormItem; this.dataForm = null; } } } <file_sep>/Forms/AutoComplete/AutoComplete/Samples/AutoComplete/AutoComplete.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public partial class AutoComplete : SampleView { public AutoComplete() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Phone || Device.RuntimePlatform == Device.UWP) { AutoComplete_Default autocomplete = new AutoComplete_Default(); this.Content = autocomplete.getContent(); this.PropertyView = autocomplete.getPropertyView(); } else if (Device.Idiom == TargetIdiom.Tablet) { AutoComplete_Tablet autocompleteTab = new AutoComplete_Tablet(); this.Content = autocompleteTab.Content; this.PropertyView = autocompleteTab.getPropertyView(); } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Calendar/CalendarViews_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfCalendar.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class CalendarViews_Mobile : SampleView { SFCalendar calendar; private string selectedType; UILabel label_calendarView; UIButton button_calendarView = new UIButton (); UIButton doneButton=new UIButton(); UIPickerView picker_calendarView; public UIView option=new UIView(); public CalendarViews_Mobile () { calendar= new SFCalendar (); calendar.ViewMode = SFCalendarViewMode.SFCalendarViewModeMonth; calendar.HeaderHeight = 40; //calendar.Appointments = CreateAppointments (); this.AddSubview (calendar); this.optionView(); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; option.Frame = new CGRect (0, 90, Frame.Width, Frame.Height); label_calendarView.Frame = new CGRect (this.Frame.X + 10, this.Frame.Y - 20, this.Frame.Size.Width - 20, 30); button_calendarView.Frame = new CGRect (this.Frame.X + 10, this.Frame.Y + 20, this.Frame.Size.Width - 20, 30); picker_calendarView.Frame = new CGRect (this.Frame.X, this.Frame.Size.Height/4, this.Frame.Size.Width , this.Frame.Size.Height/3); doneButton.Frame = new CGRect(0, this.Frame.Size.Height/4, this.Frame.Size.Width, 40); } base.LayoutSubviews (); } void ShowPicker1 (object sender, EventArgs e) { doneButton.Hidden = false; picker_calendarView.Hidden = false; button_calendarView.Hidden = true; label_calendarView.Hidden = true; } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; picker_calendarView.Hidden = true; button_calendarView.Hidden = false; label_calendarView.Hidden = false; } private void SelectedIndexChanged1(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; if (selectedType == "Month View") { calendar.ViewMode = SFCalendarViewMode.SFCalendarViewModeMonth; } else if (selectedType == "Year View") { calendar.ViewMode = SFCalendarViewMode.SFCalendarViewModeYear; } button_calendarView.SetTitle(selectedType.ToString(),UIControlState.Normal); } private readonly IList<string> _calendarViewsCollection = new List<string> { "Month View", "Year View", }; public void optionView() { //Calendar View this.OptionView = new UIView(); //Intializing configurationc controls picker_calendarView = new UIPickerView(); label_calendarView = new UILabel(); button_calendarView = new UIButton(); picker_calendarView = new UIPickerView(); //Picker PickerModel model = new PickerModel (_calendarViewsCollection); picker_calendarView.Model = model; label_calendarView.Text = "View Mode: "; label_calendarView.TextColor = UIColor.Black; label_calendarView.TextAlignment = UITextAlignment.Left; //ViewModeButton button_calendarView.SetTitle ("Month View", UIControlState.Normal); button_calendarView.SetTitleColor (UIColor.Black, UIControlState.Normal); button_calendarView.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_calendarView.Layer.CornerRadius = 8; button_calendarView.Layer.BorderWidth = 2; button_calendarView.TouchUpInside += ShowPicker1; button_calendarView.Layer.BorderColor = UIColor.FromRGB (246, 246, 246).CGColor; //DoneButton doneButton.SetTitle ("Done\t", UIControlState.Normal); doneButton.SetTitleColor (UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB (246, 246, 246); model.PickerChanged += SelectedIndexChanged1; picker_calendarView.ShowSelectionIndicator = true; picker_calendarView.Hidden = true; //settings frame size for sub views //adding subviews to the option view this.option.AddSubview (label_calendarView); this.option.AddSubview (button_calendarView); this.option.AddSubview (picker_calendarView); this.option.AddSubview (doneButton); } } } <file_sep>/Forms/CheckBox/readme.md The check box is a selection control that allows users to select one or more options from a set. The three states of check box are checked, unchecked, and indeterminate. | Sample | Description | | ------ | ----------- | | [Online food order](CheckBox/Samples/CheckBox) |This sample demonstrates the three states of checkbox in a Xamarin Forms application.|<file_sep>/Android/SampleBrowser/Samples/Maps/OSM.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Com.Syncfusion.Maps; using Android.Widget; using Android.OS; using Android.Graphics; using Com.Syncfusion.Sfbusyindicator; using Android.Net; using Android.Content; using Android.Views; using Com.Syncfusion.Carousel; using System.Collections.Generic; using Android.Util; namespace SampleBrowser { public class OSM : SamplePage { SfMaps maps; Handler handler; Context sampleContext; FrameLayout mainGrid; FrameLayout childGrid; int rowCount = 0; int columnCount = 0; double previousWidth; double previousHeight; float density; ImageryLayer layer; /// <summary> /// Gets or sets the padding value to provide gap between the items from the selected item. /// </summary> private float carouselGap; public OSM() { carouselGap = 30; } public override Android.Views.View GetSampleContent(Android.Content.Context context) { LinearLayout layout = new LinearLayout(context); density = context.Resources.DisplayMetrics.Density; sampleContext = context; layout.LayoutParameters = new Android.Views.ViewGroup.LayoutParams(Android.Views.ViewGroup.LayoutParams.MatchParent, Android.Views.ViewGroup.LayoutParams.MatchParent); layout.Orientation = Orientation.Vertical; layout.LayoutChange += Layout_LayoutChange1; handler = new Handler(); AddGridView(); SfBusyIndicator sfBusyIndicator = new SfBusyIndicator(context); sfBusyIndicator.IsBusy = true; sfBusyIndicator.AnimationType = Com.Syncfusion.Sfbusyindicator.Enums.AnimationTypes.SlicedCircle; sfBusyIndicator.ViewBoxWidth = 50; sfBusyIndicator.ViewBoxHeight = 50; sfBusyIndicator.TextColor = Color.ParseColor("#779772"); layout.AddView(sfBusyIndicator); TextView textView = new TextView(context); textView.TextSize = 16; textView.SetPadding(10, 20, 10, 0); handler = new Handler(); textView.Text = "Since this application requires network connection, Please check your network connection."; textView.LayoutParameters = new Android.Views.ViewGroup.LayoutParams(Android.Views.ViewGroup.LayoutParams.WrapContent, Android.Views.ViewGroup.LayoutParams.WrapContent); if (IsOnline()) { Java.Lang.Runnable run = new Java.Lang.Runnable(() => { layout.RemoveView(sfBusyIndicator); layout.AddView(mainGrid); }); handler.PostDelayed(run, 100); } else { Java.Lang.Runnable run = new Java.Lang.Runnable(() => { layout.RemoveView(sfBusyIndicator); layout.AddView(textView); }); handler.PostDelayed(run, 100); } return layout; } private void Layout_LayoutChange1(object sender, View.LayoutChangeEventArgs e) { var layout = sender as LinearLayout; if (childGrid != null && childGrid.ChildCount > 0 && previousWidth == layout.Width && previousHeight == layout.Height) return; if (layout != null) { InitializeChildGrid(); if (layout.Height > 0) { double row = layout.Height / 512; if (Math.Ceiling(row) <= 0) row = 1; else row = Math.Ceiling(row); rowCount = (int)row + 1; previousHeight = layout.Height; } if (layout.Width > 0) { double column = layout.Width / 512; if (Math.Ceiling(column) <= 0) column = 1; else column = Math.Ceiling(column); columnCount = (int)column + 1; previousWidth = layout.Width; } for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columnCount; j++) { ImageView image = new ImageView(sampleContext); image.SetImageResource(Resource.Drawable.grid); image.SetMinimumHeight((int)(512 * density)); image.SetMinimumWidth((int)(512 * density)); image.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); image.LayoutParameters.Height = (int)(512 * density); image.LayoutParameters.Width = (int)(512 * density); image.SetPadding(0, 0, 0, 0); image.SetX(i * (512 * density)); image.SetY(j * (512 * density)); childGrid.AddView(image); } } childGrid.SetClipChildren(false); } } public bool IsOnline() { ConnectivityManager connectivityManager = (ConnectivityManager)sampleContext.GetSystemService(Context.ConnectivityService); NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo; var isConnected = networkInfo == null ? false : networkInfo.IsConnected; return isConnected; } void AddGridView() { InitializeChildGrid(); mainGrid = new FrameLayout(sampleContext); mainGrid.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); mainGrid.AddView(childGrid); maps = new SfMaps(sampleContext); maps.ZoomLevel = 4; maps.MinZoom = 4; maps.MaxZoom = 10; maps.LayoutParameters = new Android.Views.ViewGroup.LayoutParams(Android.Views.ViewGroup.LayoutParams.MatchParent, Android.Views.ViewGroup.LayoutParams.MatchParent); layer = new ImageryLayer(); layer.GeoCoordinates = new PointF(27.1751f, 78.0421f); PopulationMarker marker1 = new PopulationMarker(sampleContext); marker1.Latitude = 20.6843f; marker1.Longitude = -88.5678f; layer.Markers.Add(marker1); PopulationMarker marker2 = new PopulationMarker(sampleContext); marker2.Latitude = -13.1631f; marker2.Longitude = -72.5450f; layer.Markers.Add(marker2); PopulationMarker marker3 = new PopulationMarker(sampleContext); marker3.Latitude = -22.9519f; marker3.Longitude = -43.2106f; layer.Markers.Add(marker3); PopulationMarker marker4 = new PopulationMarker(sampleContext); marker4.Latitude = 41.8902; marker4.Longitude = 12.4922; layer.Markers.Add(marker4); PopulationMarker marker5 = new PopulationMarker(sampleContext); marker5.Latitude = 30.3285; marker5.Longitude = 35.4444; layer.Markers.Add(marker5); PopulationMarker marker6 = new PopulationMarker(sampleContext); marker6.Latitude = 27.1751; marker6.Longitude = 78.0421; layer.Markers.Add(marker6); PopulationMarker marker7 = new PopulationMarker(sampleContext); marker7.Latitude = 40.4319; marker7.Longitude = 116.5704; layer.Markers.Add(marker7); maps.Adapter = new MarkerAdapter(sampleContext); maps.Layers.Add(layer); mainGrid.AddView(maps); mainGrid.SetClipChildren(false); List<int> arrayList = new List<int>(); arrayList.Add(Resource.Drawable.Mexico); arrayList.Add(Resource.Drawable.Peru); arrayList.Add(Resource.Drawable.Christ); arrayList.Add(Resource.Drawable.Colosseum); arrayList.Add(Resource.Drawable.Petra); arrayList.Add(Resource.Drawable.TajMahal); arrayList.Add(Resource.Drawable.China_wall); List<string> descriptionList = new List<string>(); descriptionList.Add("Mayan ruins on Mexico's Yucatan Peninsula. It was one of the largest Maya cities, thriving from around A.D. 600 to 1200."); descriptionList.Add("An inca citadel built in the mid-1400s. It was not widely known until the early 20th century."); descriptionList.Add("An enormous statue of Jesus Christ with open arms. A symbol of Christianity across the world, the statue has also become a cultural icon of both Rio de Janeiro and Brazil."); descriptionList.Add("Built between A.D. 70 and 80. It is one of the most popular touristattractions in Europe."); descriptionList.Add("It is a historic and archaeological city in southern Jordan. Petra lies around Jabal Al-Madbah in a basin surrounded by mountains which form the eastern flank of the Arabah valley that runs from the Dead Sea to the Gulf of Aqaba."); descriptionList.Add("It is an ivory-white marble mausoleum on the southern bank of the river Yamuna in the Indian city of Agra."); descriptionList.Add("The Great Wall of China is a series of fortifications that were built across the historical northern borders of ancient Chinese states and Imperial China as protection against various nomadic groups from the Eurasian Steppe."); List<string> headerList = new List<string>(); headerList.Add("<NAME>, Mexico"); headerList.Add("<NAME>"); headerList.Add("Chirst the Redeemer, Brazil"); headerList.Add("Colosseum, Rome"); headerList.Add("Petra, Jordan"); headerList.Add("<NAME>, India"); headerList.Add("Great wall of China, China"); DisplayMetrics displayMetrics = sampleContext.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels; float screenHeight = displayMetrics.HeightPixels; var density = displayMetrics.Density; LinearLayout layout = new LinearLayout(sampleContext); layout.Orientation = Orientation.Horizontal; layout.SetPadding(0, 0, 0, 10); layout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); layout.SetVerticalGravity(GravityFlags.Bottom); var itemWidth = screenWidth * 0.7; SfCarousel carousel = new SfCarousel(sampleContext); carousel.RotationAngle = 0; carousel.ItemWidth = (int)itemWidth; carousel.ItemHeight = (int)(110 * sampleContext.Resources.DisplayMetrics.Density); carousel.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, carousel.ItemHeight); carousel.SelectedIndex = 5; carousel.SelectedItemOffset = (int)(carousel.ItemWidth / 2) - (int)(carouselGap * density); List<SfCarouselItem> dataSource = new List<SfCarouselItem>(); for (int i = 0; i <= 6; i++) { LinearLayout linearLayout = new LinearLayout(sampleContext); linearLayout.SetBackgroundColor(Color.White); linearLayout.Orientation = Orientation.Horizontal; linearLayout.SetBackgroundResource((Resource.Drawable.carousel_corner_radius)); linearLayout.LayoutParameters = new Android.Views.ViewGroup.LayoutParams((int)itemWidth, (int)carousel.ItemHeight); var width = (int)(0.6f * itemWidth); LinearLayout layout1 = new LinearLayout(sampleContext); layout1.Orientation = Orientation.Vertical; layout1.LayoutParameters = new Android.Views.ViewGroup.LayoutParams((int)width, (int)carousel.ItemHeight); layout1.SetPadding(15, 15, 15, 15); TextView textView = new TextView(sampleContext); textView.Text = headerList[i]; textView.SetTypeface(Typeface.Default, TypefaceStyle.Bold); textView.TextAlignment = TextAlignment.TextStart; textView.LayoutParameters = new Android.Views.ViewGroup.LayoutParams(width - 30, ViewGroup.LayoutParams.WrapContent); layout1.AddView(textView); textView = new TextView(sampleContext); textView.Text = descriptionList[i]; textView.SetMaxLines(3); textView.Ellipsize = Android.Text.TextUtils.TruncateAt.End; textView.TextAlignment = TextAlignment.TextStart; textView.SetPadding(0, 10, 0, 0); textView.LayoutParameters = new Android.Views.ViewGroup.LayoutParams(width - 30, ViewGroup.LayoutParams.WrapContent); layout1.AddView(textView); linearLayout.AddView(layout1); SfCarouselItem sfCarouselItem = new SfCarouselItem(sampleContext); width = (int)(0.4f * itemWidth); LinearLayout layout2 = new LinearLayout(sampleContext); layout2.SetPadding(10, 15, 15, 15); layout2.LayoutParameters = new Android.Views.ViewGroup.LayoutParams(width, carousel.ItemHeight); ImageView imageView = new ImageView(sampleContext); imageView.SetBackgroundResource((Resource.Drawable.carousel_corner_radius)); imageView.SetImageResource(arrayList[i]); imageView.SetScaleType(ImageView.ScaleType.FitXy); imageView.ClipToOutline = true; layout2.AddView(imageView); linearLayout.AddView(layout2); sfCarouselItem.ContentView = linearLayout; dataSource.Add(sfCarouselItem); } carousel.DataSource = dataSource; carousel.SelectionChanged += Carousel_SelectionChanged; layout.AddView(carousel); mainGrid.AddView(layout); LinearLayout linear = new LinearLayout(sampleContext); linear.Orientation = Orientation.Horizontal; linear.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); linear.SetHorizontalGravity(GravityFlags.End); linear.SetVerticalGravity(GravityFlags.Bottom); TextView textView1 = new TextView(sampleContext); textView1.Text = "©"; textView1.SetBackgroundColor(Color.White); textView1.SetTextColor(Color.Black); textView1.SetPadding(2, 2, 2, 2); linear.AddView(textView1); TextView textView2 = new TextView(sampleContext); textView2.Text = "OpenStreetMap contributors."; textView2.SetTextColor(Color.DeepSkyBlue); textView2.SetPadding(0, 2, 3, 2); textView2.SetBackgroundColor(Color.White); textView2.Clickable = true; textView2.Click += TextView2_Click; linear.AddView(textView2); mainGrid.AddView(linear); } private void Carousel_SelectionChanged(object sender, SelectionChangedEventArgs e) { int index = e.SfCarousel.SelectedIndex; if (index == 0) { layer.GeoCoordinates = new PointF(20.6843f, -88.5678f); } else if (index == 1) { layer.GeoCoordinates = new PointF(-13.1631f, -72.5450f); } else if (index == 2) { layer.GeoCoordinates = new PointF(-22.9519f, -43.2106f); } else if (index == 3) { layer.GeoCoordinates = new PointF(41.8902f, 12.4922f); } else if (index == 4) { layer.GeoCoordinates = new PointF(30.3285f, 35.4444f); } else if (index == 5) { layer.GeoCoordinates = new PointF(27.1751f, 78.0421f); } else if (index == 6) { layer.GeoCoordinates = new PointF(40.4319f, 116.5704f); } } private void TextView2_Click(object sender, EventArgs e) { var uri = Android.Net.Uri.Parse("https://www.openstreetmap.org/copyright"); var intent = new Intent(Intent.ActionView, uri); sampleContext.StartActivity(intent); } void InitializeChildGrid() { if (childGrid == null) { childGrid = new FrameLayout(sampleContext); childGrid.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); childGrid.SetClipChildren(false); } } } }<file_sep>/Forms/NavigationDrawer/NavigationDrawer/Samples/NavigationDrawer_Main/NavigationDrawer_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.ListView.XForms; using Syncfusion.SfNavigationDrawer.XForms; using System; using System.Collections.ObjectModel; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfNavigationDrawer { public partial class NavigationDrawer_Default : SampleView { ObservableCollection<Message> messageContent = new ObservableCollection<Message>(); MenuCollectionViewModel vm; public NavigationDrawer_Default() { InitializeComponent(); vm = new MenuCollectionViewModel(); navigationDrawer.ContentView = new Archive_Default(vm.MenuCollection[0].MessageContent, "Inbox"); navigationDrawer.ContentView.BackgroundColor = Color.White; this.listView.ItemsSource = vm.MenuCollection; for (int i = 0; i < 7; i++) { messageContent.Add(vm.MenuCollection[0].MessageContent[i]); } this.listView1.ItemsSource = messageContent; if (Device.RuntimePlatform == Device.iOS) { if (Device.Idiom == TargetIdiom.Phone) { apiNameLabel.FontSize = 12; defaultDrawerLabel.FontSize = 12; secondaryDrawerLabel.FontSize = 12; transitionLabel.FontSize = 12; positionLabel.FontSize = 12; defaultTransitionPicker.WidthRequest = 101; transitionPicker.WidthRequest = 101; defaultPositionPicker.WidthRequest = 101; positionPicker.WidthRequest = 101; } navigationDrawer.DrawerWidth = (float)(Core.SampleBrowser.ScreenWidth); navigationDrawer.DrawerHeight = (float)(Core.SampleBrowser.ScreenHeight); navigationDrawer.DrawerHeaderHeight = 150; } else { secondaryDrawer.DrawerWidth = (float)(Core.SampleBrowser.ScreenWidth * 0.8); defaultDrawer.DrawerWidth = (float)(Core.SampleBrowser.ScreenWidth * 0.8); } if (Device.Idiom == TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP || (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone))) { userImage.VerticalOptions = LayoutOptions.Center; navigationDrawer.DrawerWidth = (float)(Core.SampleBrowser.ScreenWidth * 0.8); navigationDrawer.Margin = new Thickness(-2, 0, -2, 0); } //navigationDrawer.DrawerHeight = (float)(Core.SampleBrowser.ScreenHeight * 0.6); loadPropertyView(); } void Handle_QueryItemSize(object sender, Syncfusion.ListView.XForms.QueryItemSizeEventArgs e) { if (e.ItemIndex == 0 || e.ItemIndex == 3) { e.ItemSize = 105; e.Handled = true; } } void Handle_ItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e) { var tempListView = sender as Syncfusion.ListView.XForms.SfListView; for (int i = 0; i < 8; i++) { var tempItem = (listView.ItemsSource as ObservableCollection<MenuCollectionModel>)[i]; if ((e.ItemData as MenuCollectionModel) != tempItem) { tempItem.FontColor = Color.FromHex("#8e8e92"); } } var temp = e.ItemData as MenuCollectionModel; temp.FontColor = Color.FromHex("#007ad0"); navigationDrawer.ContentView = new Archive_Default(temp.MessageContent, (e.ItemData as MenuCollectionModel).MenuItem).Content; if (Device.RuntimePlatform == Device.iOS) navigationDrawer.IsOpen = false; else navigationDrawer.ToggleDrawer(); } void Handle_ItemTapped1(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e) { var tempListView = sender as Syncfusion.ListView.XForms.SfListView; for (int i = 0; i < 8; i++) { var tempItem = (listView1.ItemsSource as ObservableCollection<MenuCollectionModel>)[i]; if ((e.ItemData as MenuCollectionModel) != tempItem) { tempItem.FontColor = Color.FromHex("#8e8e92"); } } var temp = e.ItemData as MenuCollectionModel; temp.FontColor = Color.FromHex("#007ad0"); navigationDrawer.ContentView = new Archive_Default(temp.MessageContent, (e.ItemData as MenuCollectionModel).MenuItem).Content; if (Device.RuntimePlatform == Device.iOS) navigationDrawer.IsOpen = false; else navigationDrawer.ToggleSecondaryDrawer(); } void loadPropertyView() { optionLayout.Padding = new Thickness(0, 0, 10, 0); transitionPicker.Items.Add("SlideOnTop"); transitionPicker.Items.Add("Push"); transitionPicker.Items.Add("Reveal"); transitionPicker.SelectedIndex = 0; transitionPicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (transitionPicker.SelectedIndex) { case 0: { navigationDrawer.SecondaryDrawerSettings.Transition = Transition.SlideOnTop; } break; case 1: { navigationDrawer.SecondaryDrawerSettings.Transition = Transition.Push; } break; case 2: { navigationDrawer.SecondaryDrawerSettings.Transition = Transition.Reveal; } break; } }; defaultTransitionPicker.Items.Add("SlideOnTop"); defaultTransitionPicker.Items.Add("Push"); defaultTransitionPicker.Items.Add("Reveal"); defaultTransitionPicker.SelectedIndex = 0; defaultTransitionPicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (defaultTransitionPicker.SelectedIndex) { case 0: { navigationDrawer.DefaultDrawerSettings.Transition = Transition.SlideOnTop; } break; case 1: { navigationDrawer.DefaultDrawerSettings.Transition = Transition.Push; } break; case 2: { navigationDrawer.DefaultDrawerSettings.Transition = Transition.Reveal; } break; } }; positionPicker.Items.Add("Left"); positionPicker.Items.Add("Right"); positionPicker.Items.Add("Top"); positionPicker.Items.Add("Bottom"); positionPicker.SelectedIndex = 1; positionPicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (positionPicker.SelectedIndex) { case 0: { navigationDrawer.SecondaryDrawerSettings.Position = Position.Left; } break; case 1: { navigationDrawer.SecondaryDrawerSettings.Position = Position.Right; } break; case 2: { navigationDrawer.SecondaryDrawerSettings.Position = Position.Top; } break; case 3: { navigationDrawer.SecondaryDrawerSettings.Position = Position.Bottom; } break; } }; defaultPositionPicker.Items.Add("Left"); defaultPositionPicker.Items.Add("Right"); defaultPositionPicker.Items.Add("Top"); defaultPositionPicker.Items.Add("Bottom"); defaultPositionPicker.SelectedIndex = 0; defaultPositionPicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (defaultPositionPicker.SelectedIndex) { case 0: { navigationDrawer.DefaultDrawerSettings.Position = Position.Left; } break; case 1: { navigationDrawer.DefaultDrawerSettings.Position = Position.Right; } break; case 2: { navigationDrawer.DefaultDrawerSettings.Position = Position.Top; } break; case 3: { navigationDrawer.DefaultDrawerSettings.Position = Position.Bottom; } break; } }; } public View getContent() { return this.Content; } public View getPropertyView() { return this.PropertyView; } } } <file_sep>/Forms/DataForm/DataForm/Samples/ContactForm/Helpers/ListViewBehavior.cs #region Copyright // <copyright file="ListViewBehavior.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.ListView.XForms; using Xamarin.Forms; /// <summary> /// User defined behaviour to respond arbitrary conditions and events of ListView. /// </summary> public class ListViewBehavior : Behavior<Syncfusion.ListView.XForms.SfListView> { /// <summary> /// A layout which represents the list view of the contact form. /// </summary> private Syncfusion.ListView.XForms.SfListView listView; /// <summary> /// Attaches to the superclass and then calls the OnAttachedTo method on this object. /// </summary> /// <param name="bindable">The bindable object to which the behavior was attached.</param> protected override void OnAttachedTo(Syncfusion.ListView.XForms.SfListView bindable) { this.listView = bindable; this.listView.ItemTapped += this.OnItemTapped; base.OnAttachedTo(bindable); } /// <summary> /// Calls the OnDetachingFrom method and then detaches from the superclass. /// </summary> /// <param name="bindable">The bindable object from which the behavior was detached.</param> protected override void OnDetachingFrom(BindableObject bindable) { this.listView.ItemTapped -= this.OnItemTapped; base.OnDetachingFrom(bindable); } /// <summary> /// Determines when an item is tapped in the list view /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Item tapped event arguments.</param> private void OnItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e) { (this.listView.BindingContext as ContactListViewModel).SelectedItem = e.ItemData as ContactInfo; this.listView.Navigation.PushAsync(new DataFormPage() { BindingContext = this.listView.BindingContext, Title = "Contact Form" }); } } } <file_sep>/Android/SampleBrowser/Samples/Schedule/ScheduleGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Java.Util; using Com.Syncfusion.Schedule.Enums; using Com.Syncfusion.Schedule; using Android.Runtime; namespace SampleBrowser { [Preserve(AllMembers = true)] public class ScheduleGettingStarted : SamplePage, IDisposable { /// <summary> /// Variable for Schedule /// </summary> private SfSchedule schedule; /// <summary> /// Custom appointment variable /// </summary> private Meeting meeting; /// <summary> /// Custom appointment collection /// </summary> private ObservableCollection<Meeting> appointmentCollection; /// <summary> /// Spinner to select schedule view /// </summary> private Spinner spinner; /// <summary> /// Option view to change schedule view /// </summary> private LinearLayout propertyLayout; public ScheduleGettingStarted() { } public override View GetSampleContent(Context context) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; schedule = new SfSchedule(context); propertyLayout = new LinearLayout(context); propertyLayout = SetOptionPage(context); // Schedule custom appointment mapping AppointmentMapping mapping = new AppointmentMapping(); mapping.StartTime = "From"; mapping.EndTime = "To"; mapping.Subject = "EventName"; mapping.IsAllDay = "IsAllDay"; mapping.MinHeight = "MinimumHeight"; mapping.Color = "Color"; schedule.AppointmentMapping = mapping; schedule.ScheduleView = ScheduleView.WeekView; schedule.MonthViewSettings.ShowAppointmentsInline = true; GetAppointments(); schedule.ItemsSource = appointmentCollection; schedule.LayoutParameters = new FrameLayout.LayoutParams( LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); linearLayout.AddView(schedule); return linearLayout; } /// <summary> /// Custom appointment subject collection /// </summary> private List<string> eventCollection; /// <summary> /// Custom appointment start time collection /// </summary> private List<Calendar> fromCollection; /// <summary> /// Custom appointment end time collection /// </summary> private List<Calendar> toCollection; /// <summary> /// Custom appointment color collection /// </summary> private List<string> colorCollection; /// <summary> /// Collection of random numbers to get start time and end time /// </summary> private List<int> randomNumbers; /// <summary> /// Gets the appointments collection /// </summary> private void GetAppointments() { appointmentCollection = new ObservableCollection<Meeting>(); SetEventCollection(); RandomNumbers(); SetFromCollection(); SetToCollection(); SetColorCollection(); for (int i = 0; i < 15; i++) { meeting = new Meeting(); meeting.Color = Color.ParseColor(colorCollection[i]); meeting.EventName = eventCollection[i]; meeting.From = fromCollection[i]; // To create all day appointments if (i % 6 == 0 && i != 0) { meeting.IsAllDay = true; } // To create two days span appointment if (i % 5 == 0 && i != 0) { toCollection[i] = (Calendar)fromCollection[i].Clone(); var date = toCollection[i].Get(CalendarField.DayOfMonth) + 2; toCollection[i].Set(CalendarField.DayOfMonth, date); } // To create 24 hour span appointments if (i % 7 == 0) { toCollection[i] = (Calendar)fromCollection[i].Clone(); var hour = toCollection[i].Get(CalendarField.Hour) + 23; var min = toCollection[i].Get(CalendarField.Minute) + 59; toCollection[i].Set(CalendarField.Hour, hour); toCollection[i].Set(CalendarField.Minute, min); } // To create minimum height appointments if (eventCollection[i].Contains("alert")) { toCollection[i] = (Calendar)fromCollection[i].Clone(); meeting.MinimumHeight = 50; } meeting.To = toCollection[i]; appointmentCollection.Add(meeting); } } /// <summary> /// Gets the random numbers to get start time and end time /// </summary> private void RandomNumbers() { randomNumbers = new List<int>(); Java.Util.Random rand = new Java.Util.Random(); for (int i = 0; i < 20; i++) { int randomNum = rand.NextInt((15 - 9) + 1) + 9; randomNumbers.Add(randomNum); } } /// <summary> /// Sets the color collection for custom appointment /// </summary> private void SetColorCollection() { colorCollection = new List<string>(); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); } /// <summary> /// Sets the end time for custom appointments /// </summary> private void SetToCollection() { toCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -10; i < 10; i++) { Calendar to = (Calendar)currentDate.Clone(); to.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNumbers[count] + 2, 0, 0); toCollection.Add(to); count++; } } /// <summary> /// Sets the start time collection for custom appointments /// </summary> private void SetFromCollection() { fromCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -10; i < 10; i++) { Calendar from = (Calendar)currentDate.Clone(); from.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNumbers[count], 0, 0); fromCollection.Add(from); count++; } } /// <summary> /// Sets the subject collection for custom appointment /// </summary> private void SetEventCollection() { eventCollection = new List<string>(); eventCollection.Add("General Meeting"); eventCollection.Add("Plan Execution"); eventCollection.Add("Project Plan"); eventCollection.Add("Consulting"); eventCollection.Add("Performance Check"); eventCollection.Add("Yoga Therapy"); eventCollection.Add("Plan Execution"); eventCollection.Add("Project Plan"); eventCollection.Add("Consulting"); eventCollection.Add("Performance Check"); eventCollection.Add("Work log alert"); eventCollection.Add("Birthday wish alert"); eventCollection.Add("Task due date"); eventCollection.Add("Status mail"); eventCollection.Add("Start sprint alert"); } /// <summary> /// Sets the option page to change schedule view /// </summary> /// <param name="context">Context of this view</param> /// <returns>Option layout</returns> private LinearLayout SetOptionPage(Context context) { TextView scheduleType_txtBlock = new TextView(context); scheduleType_txtBlock.Text = "Schedule View"; scheduleType_txtBlock.TextSize = 20; scheduleType_txtBlock.SetPadding(0, 0, 0, 10); scheduleType_txtBlock.SetTextColor(Color.Black); LinearLayout layout = new LinearLayout(context); layout.SetPadding(15, 15, 15, 20); layout.Orientation = Android.Widget.Orientation.Vertical; layout.SetBackgroundColor(Color.White); spinner = new Spinner(context, SpinnerMode.Dialog); spinner.SetMinimumHeight(60); spinner.SetBackgroundColor(Color.Gray); spinner.DropDownWidth = 500; layout.AddView(scheduleType_txtBlock); layout.AddView(spinner); List<string> list = new List<string>(); list.Add("Week View"); list.Add("Day View"); list.Add("Work Week View"); list.Add("Month View"); ArrayAdapter<string> dataAdapter = new ArrayAdapter<string>(context, Android.Resource.Layout.SimpleSpinnerItem, list); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); spinner.Adapter = dataAdapter; spinner.ItemSelected += Spinner_ItemSelected; return layout; } /// <summary> /// Event occurs when item selected in the spinner to change schedule view /// </summary> /// <param name="sender">Sender of the event</param> /// <param name="e">Arguments of the event</param> private void Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { if (e.Position == 0) { schedule.ScheduleView = ScheduleView.WeekView; } else if (e.Position == 1) { schedule.ScheduleView = ScheduleView.DayView; } else if (e.Position == 2) { schedule.ScheduleView = ScheduleView.WorkWeekView; } else if (e.Position == 3) { schedule.ScheduleView = ScheduleView.MonthView; } } /// <summary> /// Adds the property layout to the view /// </summary> /// <param name="context">Context of the view</param> /// <returns>Property layout</returns> public override View GetPropertyWindowLayout(Context context) { return propertyLayout; } public void Dispose() { if (schedule != null) { schedule.Dispose(); schedule = null; } if (propertyLayout != null) { propertyLayout.Dispose(); propertyLayout = null; } if (spinner != null) { spinner.ItemSelected -= Spinner_ItemSelected; spinner.Dispose(); spinner = null; } } } /// <summary> /// Custom appointment class /// </summary> [Preserve(AllMembers = true)] public class Meeting { /// <summary> /// Gets or sets the Event name for the meeting /// </summary> public string EventName { get; set; } /// <summary> /// Gets or sets the From time for the meeting /// </summary> public Calendar From { get; set; } /// <summary> /// Gets or sets the To time for the meeting /// </summary> public Calendar To { get; set; } /// <summary> /// Gets or sets the color for the meeting /// </summary> public int Color { get; set; } /// <summary> /// Gets or sets the minimum height for the meeting /// </summary> public double MinimumHeight { get; set; } /// <summary> /// Gets or sets a value to indicate whether the meeting is all day or not /// </summary> public bool IsAllDay { get; set; } } }<file_sep>/Forms/Chips/Chips/Helpers/Behaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XForms.Buttons; using Xamarin.Forms; namespace SampleBrowser.Chips { /// <summary> /// Add chip to existing chips. /// </summary> public class EntryBehavior : Behavior<Entry> { #region fields /// <summary> /// The input chip group. /// </summary> private SfChipGroup inputChipGroup; #endregion #region Fields /// <summary> /// Gets or sets the input chip group. /// </summary> /// <value>The input chip group.</value> public SfChipGroup InputChipGroup { get { return inputChipGroup; } set { inputChipGroup = value; } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.Chips.EntryBehavior"/> class. /// </summary> public EntryBehavior() { } #endregion #region Methods /// <summary> /// On the attached property. /// </summary> /// <param name="bindable">Bindable.</param> protected override void OnAttachedTo(Entry entry) { base.OnAttachedTo(entry); entry.Completed += (object sender, EventArgs e) => { if (inputChipGroup != null && !string.IsNullOrEmpty(entry.Text)) { ChipViewModel viewModel = entry.BindingContext as ChipViewModel; if (viewModel != null) { if (viewModel.SelectedItem.ToString() == "Television") { viewModel.televisionItems.Add(entry.Text); } else if(viewModel.SelectedItem.ToString() == "Washer") { viewModel.washserItems.Add(entry.Text); } else if(viewModel.SelectedItem.ToString() == "Air Conditioner") { viewModel.airConditionerItems.Add(entry.Text); } } entry.Text = string.Empty; entry.Placeholder = "Type a brand"; } if (string.IsNullOrEmpty(entry.Text)) { entry.Unfocus(); } }; } /// <summary> /// On the detaching from. /// </summary> /// <param name="bindable">Bindable.</param> protected override void OnDetachingFrom(Entry bindable) { base.OnDetachingFrom(bindable); } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/CircularGauge/CircularGaugeSample.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfGauge.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using System.Drawing; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class CircularGaugeSample : SampleView { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } #region View lifecycle SFCircularGauge gauge; SFNeedlePointer needlePointer; UISlider slider; UIView option = new UIView(); public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } if (Utility.IsIPad) { gauge.Frame = new CGRect(50, 50, (float)this.Frame.Width - 100, (float)this.Frame.Height - 100); } else { gauge.Frame = new CGRect(10, 10, (float)this.Frame.Width - 20, (float)this.Frame.Height - 20); } base.LayoutSubviews(); } public CircularGaugeSample() { gauge = new SFCircularGauge(); gauge.Scales.Add(new SFCircularScale()); ObservableCollection<SFCircularScale> scales = new ObservableCollection<SFCircularScale>(); SFCircularScale scale = new SFCircularScale(); scale.StartValue = 0; scale.EndValue = 100; scale.Interval = 10; //scale.StartAngle = 35; // scale.SweepAngle = 320; scale.RimWidth = 5; scale.ShowTicks = false; scale.ShowLabels = true; scale.RimColor = UIColor.FromRGB(224, 224, 224); scale.LabelColor = UIColor.Black; scale.LabelOffset = 0.8f; scale.MinorTicksPerInterval = 0; ObservableCollection<SFCircularPointer> pointers = new ObservableCollection<SFCircularPointer>(); needlePointer = new SFNeedlePointer(); needlePointer.Value = 60; needlePointer.Color = UIColor.FromRGB(117, 117, 117); needlePointer.KnobRadius = 12; needlePointer.KnobColor = UIColor.FromRGB(117, 117, 117); needlePointer.Width = 3; needlePointer.LengthFactor = 0.6f; needlePointer.PointerType = SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle; scale.Pointers.Add(needlePointer); scales.Add(scale); gauge.Scales = scales; this.AddSubview(gauge); CreateOptionView(); this.OptionView = option; } private void CreateOptionView() { slider = new UISlider(); slider.Frame = new CGRect(5, 50, 320, 60); slider.MinValue = 0f; slider.MaxValue = 100f; slider.Value = 60f; slider.ValueChanged += (object sender, EventArgs e) => { needlePointer.Value = slider.Value; }; UILabel text1 = new UILabel(); text1.Text = "Change Pointer Value"; text1.TextAlignment = UITextAlignment.Left; text1.TextColor = UIColor.Black; text1.Frame = new CGRect(10, 25, 320, 40); text1.Font = UIFont.FromName("Helvetica", 14f); this.option.AddSubview(text1); this.option.AddSubview(slider); } protected override void Dispose(bool disposing) { //gauge.Scales[0].Pointers.Clear(); //gauge.Scales.Clear(); //gauge.Dispose(); base.Dispose(disposing); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/DocIO/WordToHTML.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Webkit; using Android.App; using Android.OS; namespace SampleBrowser { public partial class WordToHTML : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to convert the Word document into HTML file."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly (); // Creating a new document. WordDocument document = new WordDocument (); Stream inputStream = assembly.GetManifestResourceStream ("SampleBrowser.Samples.DocIO.Templates.WordtoHTML.doc"); //Open the Word document to convert document.Open (inputStream, FormatType.Doc); //Export the Word document to HTML file MemoryStream stream = new MemoryStream (); HTMLExport htmlExport = new HTMLExport (); htmlExport.SaveAsXhtml (document, stream); document.Close (); //Set the stream to start position to read the content as string stream.Position = 0; StreamReader reader = new StreamReader (stream); string htmlString = reader.ReadToEnd (); Intent i = new Intent (m_context, typeof(WebViewActivity)); i.PutExtra ("HtmlString", htmlString); m_context.StartActivity (i); } } } <file_sep>/Android/SampleBrowser/Samples/Presentation/ModifyAnimation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public partial class ModifyAnimationPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to modify the animation in PowerPoint presentation."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Input Template"; button1.Click += OnInpTemplateButtonClicked; linear.AddView(button1); Button button2 = new Button(con); button2.Text = "Generate Presentation"; button2.Click += OnButtonClicked; linear.AddView(button2); return linear; } void OnInpTemplateButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.ShapeWithAnimation.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); fileStream.Dispose(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("InputTemplate.pptx", "application/powerpoint", stream, m_context); } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.ShapeWithAnimation.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Modify the existing animation ModifyAppliedAnimation(presentation); MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("ModifyAnimationSample.pptx", "application/powerpoint", stream, m_context); } } #region Modify Animation private void ModifyAppliedAnimation(IPresentation presentation) { //Get the slide from the presentation ISlide slide = presentation.Slides[0]; //Access the animation sequence to modify effects ISequence sequence = slide.Timeline.MainSequence; //Change the animation effect of the first effect IEffect loopEffect = sequence[0]; loopEffect.Type = EffectType.Bounce; } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Carousel/LoadMore_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Com.Syncfusion.Carousel; using static Android.App.ActionBar; namespace SampleBrowser { public class CarouselAdapter : ICarouselAdapter { Context myComtext; ObservableCollection<CarouselPropertyClass> myList = new ObservableCollection<CarouselPropertyClass>(); public CarouselAdapter(Context context, ObservableCollection<CarouselPropertyClass> k) { myComtext = context; myList = k; } public View GetItemView(SfCarousel carousel, int index) { double density1; int width1, height1; List<int> imageID = new List<int>(); width1 = myComtext.Resources.DisplayMetrics.WidthPixels; height1 = myComtext.Resources.DisplayMetrics.HeightPixels; density1 = myComtext.Resources.DisplayMetrics.Density; FrameLayout linear = new FrameLayout(myComtext); linear.SetBackgroundColor(Color.White); linear.LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent, (int)(110 * density1)); var item = myList[index]; TextView Srcimage = new TextView(myComtext); Srcimage.Text = (myList[index] as CarouselPropertyClass).Unicode; Srcimage.Typeface = Typeface.CreateFromAsset(myComtext.Assets, "CarouselIcon.ttf"); Srcimage.SetTextColor((myList[index] as CarouselPropertyClass).ItemColor); Srcimage.TextSize = 40; Srcimage.SetWidth((int)(110 * density1)); Srcimage.SetHeight((int)(110 * density1)); Srcimage.TextAlignment = TextAlignment.Center; Srcimage.Gravity = GravityFlags.Center; linear.AddView(Srcimage); return linear; } } public class LoadMore_Mobile : SamplePage { Context context; SfCarousel carousel; SfCarousel carousel1; SfCarousel carousel2; double density; int width, height; LinearLayout mainLayout; CarouselPropertyClass carouselObj; CarouselModel modelObj; public override View GetPropertyWindowLayout(Android.Content.Context context) { return null; } public override View GetSampleContent(Context context1) { context = context1; width = context1.Resources.DisplayMetrics.WidthPixels; height = context1.Resources.DisplayMetrics.HeightPixels; density = context1.Resources.DisplayMetrics.Density; carousel = new SfCarousel(context); carousel1 = new SfCarousel(context); carousel2 = new SfCarousel(context); carouselObj = new CarouselPropertyClass(); modelObj = new CarouselModel(); carousel.AllowLoadMore = true; carousel.LoadMoreItemsCount = 2; carousel1.AllowLoadMore = true; carousel1.LoadMoreItemsCount = 2; carousel2.AllowLoadMore = true; carousel2.LoadMoreItemsCount = 2; TextView text = new TextView(context1) { TextAlignment = TextAlignment.Center, Text = "Load More...", TextSize = 10, Typeface = Typeface.DefaultBold, Gravity = GravityFlags.Center }; text.SetBackgroundColor(Color.White); TextView text1 = new TextView(context1) { TextAlignment = TextAlignment.Center, Text = "Load More...", TextSize = 10, Typeface = Typeface.DefaultBold, Gravity = GravityFlags.Center }; text1.SetBackgroundColor(Color.White); TextView text2 = new TextView(context1) { TextAlignment = TextAlignment.Center, Text = "Load More...", TextSize = 10, Typeface = Typeface.DefaultBold, Gravity = GravityFlags.Center }; text2.SetBackgroundColor(Color.White); carousel.LoadMoreView = text; carousel1.LoadMoreView = text1; carousel2.LoadMoreView = text2; carousel.ItemsSource = modelObj.ApplicationCollection; carousel.ItemSpacing = 80; carousel1.ItemsSource = modelObj.TransportCollection; carousel1.ItemSpacing = 80; carousel2.ItemsSource = modelObj.OfficeCollection; carousel2.ItemSpacing = 80; carousel.ViewMode = ViewMode.Linear; carousel1.ViewMode = ViewMode.Linear; carousel2.ViewMode = ViewMode.Linear; if (context.Resources.DisplayMetrics.Density > 1.5) { carousel.ItemHeight = Convert.ToInt32(110 * context.Resources.DisplayMetrics.Density); carousel.ItemWidth = Convert.ToInt32(110 * context.Resources.DisplayMetrics.Density); carousel1.ItemHeight = Convert.ToInt32(110 * context.Resources.DisplayMetrics.Density); carousel1.ItemWidth = Convert.ToInt32(110 * context.Resources.DisplayMetrics.Density); carousel2.ItemHeight = Convert.ToInt32(110 * context.Resources.DisplayMetrics.Density); carousel2.ItemWidth = Convert.ToInt32(110 * context.Resources.DisplayMetrics.Density); } carousel.LayoutParameters = new LayoutParams(LinearLayout.LayoutParams.MatchParent, (int)(120 * density)); carousel1.LayoutParameters = new LayoutParams(LinearLayout.LayoutParams.MatchParent, (int)(120 * density)); carousel2.LayoutParameters = new LayoutParams(LinearLayout.LayoutParams.MatchParent, (int)(120 * density)); mainLayout = new LinearLayout(context); mainLayout.Orientation = Orientation.Vertical; mainLayout.SetGravity(GravityFlags.CenterHorizontal); mainLayout.SetBackgroundColor(Color.Rgb(249, 249, 249)); mainLayout.LayoutParameters = new LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); carousel.Adapter = new CarouselAdapter(context1, modelObj.ApplicationCollection); carousel1.Adapter = new CarouselAdapter(context1, modelObj.TransportCollection); carousel2.Adapter = new CarouselAdapter(context1, modelObj.OfficeCollection); HeaderMethod(context); mainLayout.AddView(carousel); HeaderMethod1(context); mainLayout.AddView(carousel1); HeaderMethod2(context); mainLayout.AddView(carousel2); return mainLayout; } private void HeaderMethod(Android.Content.Context con) { LinearLayout hearderLayout = new LinearLayout(con); hearderLayout.LayoutParameters = new LinearLayout.LayoutParams((int)width, (int)(30 * density)); hearderLayout.SetBackgroundColor(Color.Rgb(249, 249, 249)); hearderLayout.SetPadding(30, 12, 270, 5); TextView attachText = new TextView(con); attachText.Text = "Application"; attachText.SetTextColor(Color.Rgb(51, 51, 51)); attachText.SetHeight((int)(24 * density)); attachText.TextSize = 18; attachText.Typeface = Typeface.DefaultBold; attachText.TextAlignment = TextAlignment.TextStart; attachText.Gravity = GravityFlags.Left; hearderLayout.AddView(attachText); mainLayout.AddView(hearderLayout); } private void HeaderMethod1(Android.Content.Context con) { LinearLayout hearderLayout = new LinearLayout(con); hearderLayout.LayoutParameters = new LinearLayout.LayoutParams((int)width, (int)(30 * density)); hearderLayout.SetBackgroundColor(Color.Rgb(249, 249, 249)); hearderLayout.SetPadding(30, 12, 270, 5); TextView attachText = new TextView(con); attachText.Text = "Food"; attachText.SetTextColor(Color.Rgb(51, 51, 51)); attachText.SetHeight((int)(24 * density)); attachText.TextSize = 18; attachText.Typeface = Typeface.DefaultBold; attachText.TextAlignment = TextAlignment.TextStart; attachText.Gravity = GravityFlags.Left; hearderLayout.AddView(attachText); mainLayout.AddView(hearderLayout); } private void HeaderMethod2(Android.Content.Context con) { LinearLayout hearderLayout = new LinearLayout(con); hearderLayout.LayoutParameters = new LinearLayout.LayoutParams((int)width, (int)(30 * density)); hearderLayout.SetBackgroundColor(Color.Rgb(249, 249, 249)); hearderLayout.SetPadding(30, 12, 270, 5); TextView attachText = new TextView(con); attachText.Text = "Banking"; attachText.SetTextColor(Color.Rgb(51, 51, 51)); attachText.SetHeight((int)(24 * density)); attachText.TextSize = 18; attachText.Typeface = Typeface.DefaultBold; attachText.TextAlignment = TextAlignment.TextStart; attachText.Gravity = GravityFlags.Left; hearderLayout.AddView(attachText); mainLayout.AddView(hearderLayout); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Styles/Red.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; namespace SampleBrowser { public class Red : DataGridStyle { public Red () { } public override UIColor GetHeaderBackgroundColor () { return UIColor.FromRGB (190, 93, 93); } public override UIColor GetHeaderForegroundColor() { return UIColor.FromRGB(255, 255, 255); } public override UIColor GetAlternatingRowBackgroundColor () { return UIColor.FromRGB (255, 235, 237); } public override UIColor GetSelectionBackgroundColor () { return UIColor.FromRGB (229, 115, 115); } public override UIColor GetSelectionForegroundColor () { return UIColor.FromRGB (255, 255, 255); } public override UIColor GetCaptionSummaryRowBackgroundColor () { return UIColor.FromRGB (224, 224, 224); } public override UIColor GetCaptionSummaryRowForegroundColor () { return UIColor.FromRGB (51, 51, 51); } public override UIColor GetBorderColor () { return UIColor.FromRGB (180, 180, 180); } } } <file_sep>/Android/SampleBrowser/Samples/TreeMap/Hierarchical.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Views; using Android.Graphics; using Com.Syncfusion.Treemap; using System.Collections.Generic; using Android.Widget; using Com.Syncfusion.Treemap.Enums; using Android.Content; using System.Collections.ObjectModel; using Org.Json; namespace SampleBrowser { public class Hierarchical : SamplePage { SfTreeMap tree; Toast currentToast; public Hierarchical () { } public override View GetSampleContent (Context context) { var margin = context.Resources.DisplayMetrics.Density * 20; tree = new SfTreeMap (context); tree.WeightValuePath = "Sales"; currentToast = new Toast(context); DesaturationColorMapping desat = new DesaturationColorMapping (); desat.Color = Color.ParseColor ("#41B8C4"); desat.From = 1; desat.To = 0.2; tree.ColorValuePath = "Expense"; tree.LeafItemColorMapping = desat; tree.HighlightOnSelection = true; tree.SelectionMode = SelectionMode.Single; TreeMapHierarchicalLevel level = new TreeMapHierarchicalLevel() { ChildPadding=4, ShowHeader = true, HeaderHeight = 20, HeaderPath = "Name", ChildStrokeColor=Color.Gray ,ChildStrokeWidth=1, ChildPath = "RegionalSales" }; level.HeaderStyle = new Style() { TextColor = Color.Gray, TextSize = 16 }; level.ChildBackgroundColor =Color.White; tree.Levels.Add (level); tree.LeafItemSettings = new LeafItemSetting (){ ShowLabels = true, Gap = 5, StrokeColor = Color.White, StrokeWidth = 2 }; tree.LeafItemSettings.LabelStyle = new Style () {Margin= new Margin(margin/2,margin,0,0), TextSize = 18, TextColor = Color.White }; tree.LeafItemSettings.LabelPath ="Name"; tree.DataSource = GetDataSource (); //tree.TreeMapSelected += (object sender, SfTreeMap.TreeMapSelectedEventArgs e) => //{ // JSONObject data = (JSONObject)e.P0; // if (data != null) // { // if (currentToast != null) // { // currentToast.Cancel(); // } // currentToast = Toast.MakeText(context,"Country -"+ data.Get("Name") + "\n" + "Sales -$"+ data.Get("Sales"), ToastLength.Short); currentToast.Show(); // } //}; return tree; } JSONArray GetDataSource() { JSONArray regional1 = new JSONArray (); regional1.Put (getJsonObject1 ("United States", "New York", 2353, 2000)); regional1.Put(getJsonObject1("United States", "Los Angeles", 3453, 3000)); regional1.Put(getJsonObject1("United States", "San Francisco", 8456, 8000)); regional1.Put(getJsonObject1("United States", "Chicago", 6785, 7000)); regional1.Put(getJsonObject1("United States", "Miami", 7045, 6000)); JSONArray regional2 = new JSONArray (); regional2.Put (getJsonObject1 ("Canada", "Toronto", 7045, 7000)); regional2.Put(getJsonObject1("Canada", "Vancouver", 4352, 4000)); regional2.Put(getJsonObject1("Canada", "Winnipeg", 7843, 7500)); JSONArray regional3 = new JSONArray (); regional3.Put (getJsonObject1 ("Mexico", "Mexico City", 7843, 6500)); regional3.Put(getJsonObject1("Mexico", "Cancun", 6683, 6000)); regional3.Put(getJsonObject1("Mexico", "Acapulco", 2454, 2000)); JSONArray array = new JSONArray (); array.Put(getJsonObject("United States",98456, 87000,regional1)); array.Put(getJsonObject("Canada",43523, 40000,regional2)); array.Put(getJsonObject("Mexico",45634, 46000,regional3)); return array; } JSONObject getJsonObject(String name,double expense,double sales, JSONArray regionalSale) { JSONObject obj = new JSONObject (); obj.Put ("Name", name); obj.Put ("Expense", expense); obj.Put ("Sales", sales); obj.Put("RegionalSales",regionalSale); return obj; } JSONObject getJsonObject1(String country,String name,double expense,double sales) { JSONObject obj = new JSONObject (); obj.Put ("Country", country); obj.Put ("Name", name); obj.Put ("Expense", expense); obj.Put("Sales",sales); return obj; } }} <file_sep>/iOS/SampleBrowser/Resources/Samples/AutoComplete/Diacritics_Sense.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfAutoComplete.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Diacritics_Sense : SampleView { NSMutableArray diacriticsList = new NSMutableArray(); SFAutoComplete diacriticsAutoComplete; public Diacritics_Sense() { this.addingdiacriticsList(); diacriticsAutoComplete = new SFAutoComplete(); diacriticsAutoComplete.AutoCompleteSource = diacriticsList; diacriticsAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeContains; diacriticsAutoComplete.Watermark = (NSString)"Search Text"; diacriticsAutoComplete.MaxDropDownHeight = 200; diacriticsAutoComplete.AutoCompleteMode = SFAutoCompleteAutoCompleteMode.SFAutoCompleteAutoCompleteModeSuggest; diacriticsAutoComplete.IgnoreDiacritic = false; this.AddSubview(diacriticsAutoComplete); } private void addingdiacriticsList() { diacriticsList.Add((NSString)"Whât is thé wéâthér tódây ? "); diacriticsList.Add((NSString)"Hów tó bóók my flight?"); diacriticsList.Add((NSString)"Whéré is my lócâtión?"); diacriticsList.Add((NSString)"Is bânk ópén tódây?"); diacriticsList.Add((NSString)"Why sky is blué?"); diacriticsList.Add((NSString)"Gét mé sóméthing"); diacriticsList.Add((NSString)"List óf hólidâys"); diacriticsList.Add((NSString)"Diréct mé tó hómé"); diacriticsList.Add((NSString)"Hów tó gâin wéight?"); diacriticsList.Add((NSString)"Hów tó drâw ân éléphânt?"); diacriticsList.Add((NSString)"Whéré cân I buy â câmérâ?"); diacriticsList.Add((NSString)"Guidé mé âll thé wây"); diacriticsList.Add((NSString)"Hów tó mâké â câké?"); diacriticsList.Add((NSString)"Sây, Hélló Wórld!"); diacriticsList.Add((NSString)"Hów tó mâké â róbót?"); diacriticsList.Add((NSString)"Cónnéct Móbilé tó TV?"); diacriticsList.Add((NSString)"Whât timé nów in Indiâ?"); diacriticsList.Add((NSString)"Whó is whó in thé wórld?"); diacriticsList.Add((NSString)"Hów cân I léârn Tâmil?"); diacriticsList.Add((NSString)"Hów cân I léârn Jâpânésé?"); diacriticsList.Add((NSString)"Hów tó réâch néârést âirpórt?"); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { diacriticsAutoComplete.Frame = new CGRect(40, 30, view.Frame.Width - 80, 40); } else { diacriticsAutoComplete.Frame = new CGRect(20, 30, view.Frame.Width - 40, 40); } } base.LayoutSubviews(); } } } <file_sep>/Forms/AutoComplete/AutoComplete/Samples/CustomSearchPage/CustomModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public class CustomModel { public string Name { get; set; } public string Tag { get; set; } public string Unicode { get; set; } public Color BackColor { get; set; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Filtering/FilteringBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "FilteringBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.Data.Extensions; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Filtering samples /// </summary> public class FilteringBehaviors : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private FilteringViewModel viewModel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt optionsList; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt columnsList; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SearchBarExt filterText; /// <summary> /// Triggers while columns selection was changed /// </summary> /// <param name="sender">OnColumnsSelectionChanged event sender</param> /// <param name="e">OnColumnsSelectionChanged event args</param> public void OnColumnsSelectionChanged(object sender, EventArgs e) { Picker newPicker = (Picker)sender; this.viewModel.SelectedColumn = newPicker.Items[newPicker.SelectedIndex]; if (this.viewModel.SelectedColumn == "All Columns") { this.viewModel.SelectedCondition = "Contains"; this.optionsList.IsVisible = false; this.OnFilterChanged(); } else { this.optionsList.IsVisible = true; foreach (var prop in typeof(BookInfo).GetProperties()) { if (prop.Name == this.viewModel.SelectedColumn) { if (prop.PropertyType == typeof(string)) { this.optionsList.Items.Clear(); this.optionsList.Items.Add("Contains"); this.optionsList.Items.Add("Equals"); this.optionsList.Items.Add("NotEquals"); if (this.viewModel.SelectedCondition == "Equals") { this.optionsList.SelectedIndex = 1; } else if (this.viewModel.SelectedCondition == "NotEquals") { this.optionsList.SelectedIndex = 2; } else { this.optionsList.SelectedIndex = 0; } } else { this.optionsList.Items.Clear(); this.optionsList.Items.Add("Equals"); this.optionsList.Items.Add("NotEquals"); if (this.viewModel.SelectedCondition == "Equals") { this.optionsList.SelectedIndex = 0; } else { this.optionsList.SelectedIndex = 1; } } } } } } /// <summary> /// Triggers while filter options are changed. /// </summary> /// <param name="sender">OnFilterOptionsChanged event sender</param> /// <param name="e">OnFilterOptionsChanged event args e</param> public void OnFilterOptionsChanged(object sender, EventArgs e) { Picker newPicker = (Picker)sender; if (newPicker.SelectedIndex >= 0) { this.viewModel.SelectedCondition = newPicker.Items[newPicker.SelectedIndex]; if (this.filterText.Text != null) { this.OnFilterChanged(); } } } /// <summary> /// Triggers while filter text was changed /// </summary> /// <param name="sender">OnFilterTextChanged event sender</param> /// <param name="e">OnFilterTextChanged event args e</param> public void OnFilterTextChanged(object sender, TextChangedEventArgs e) { if (e.NewTextValue == null) { this.viewModel.FilterText = string.Empty; } else { this.viewModel.FilterText = e.NewTextValue; } } /// <summary> /// Refreshes the filter. /// </summary> public void OnFilterChanged() { if (this.dataGrid.View != null) { this.dataGrid.View.Filter = this.viewModel.FilerRecords; this.dataGrid.View.RefreshFilter(); } } /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.viewModel = new FilteringViewModel(); this.dataGrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); bindAble.BindingContext = this.viewModel; this.optionsList = bindAble.FindByName<PickerExt>("OptionsList"); this.columnsList = bindAble.FindByName<PickerExt>("ColumnsList"); this.filterText = bindAble.FindByName<SearchBarExt>("filterText"); this.optionsList.Items.Add("Equals"); this.optionsList.Items.Add("NotEquals"); this.optionsList.Items.Add("Contains"); this.columnsList.Items.Add("All Columns"); this.columnsList.Items.Add("CustomerID"); this.columnsList.Items.Add("BookID"); this.columnsList.Items.Add("FirstName"); this.columnsList.Items.Add("LastName"); this.columnsList.Items.Add("BookName"); this.columnsList.SelectedIndex = 0; this.viewModel.Filtertextchanged = this.OnFilterChanged; this.filterText.TextChanged += this.OnFilterTextChanged; this.columnsList.SelectedIndexChanged += this.OnColumnsSelectionChanged; this.optionsList.SelectedIndexChanged += this.OnFilterOptionsChanged; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type of bindAble parameter</param> protected override void OnDetachingFrom(SampleView bindAble) { this.optionsList.SelectedIndexChanged -= this.OnFilterOptionsChanged; this.columnsList.SelectedIndexChanged -= this.OnColumnsSelectionChanged; this.filterText.TextChanged -= this.OnFilterTextChanged; this.dataGrid = null; this.optionsList = null; this.columnsList = null; this.filterText = null; base.OnDetachingFrom(bindAble); } } } <file_sep>/Forms/SegmentedControl/SegmentedControl.Android/Renderer/Renderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Android.Views; using SampleBrowser.SegmentedControl; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using View = Android.Views.View; [assembly: ExportRenderer(typeof(ViewCell), typeof(CustomListView))] namespace SampleBrowser.SegmentedControl { public class CustomListView : ViewCellRenderer { protected override View GetCellCore(Cell segmentitem, View segmentConverterView, ViewGroup parent, Context context) { var listviewCell = base.GetCellCore(segmentitem, segmentConverterView, parent, context); var SegmentlistView = parent as Android.Widget.ListView; if (SegmentlistView != null) { SegmentlistView.SetSelector(Android.Resource.Color.Transparent); SegmentlistView.CacheColorHint = Android.Graphics.Color.Transparent; } return listviewCell; } } }<file_sep>/Forms/SegmentedControl/SegmentedControl/Samples/SegmentCustomization/ViewModel/CustomizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using Syncfusion.XForms.Buttons; using Xamarin.Forms; namespace SampleBrowser.SegmentedControl { public class CustomizationViewModel { #region Properties /// <summary> /// Get or set the Backlight for the device screen /// </summary> public ObservableCollection<SfSegmentItem> BackLightCollection { get; set; } /// <summary> /// Display the different font icons used inside the /// </summary> public ObservableCollection<SfSegmentItem> IconCollection { get; set; } /// <summary> /// Collection which hold the font icon and text /// </summary> public ObservableCollection<SfSegmentItem> Image_textCollection { get; set; } /// <summary> /// Collection which hold the font icon and text /// </summary> public ObservableCollection<SfSegmentItem> TextCollection { get; set; } /// <summary> /// Collection which have the different colors. /// </summary> public ObservableCollection<SfSegmentItem> PrimaryColors { get; set; } #endregion #region Constructor /// <summary> /// Constructor of customization view class /// </summary> public CustomizationViewModel() { var fontFamily = "SegmentIcon.ttf"; if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB fontFamily = "/Assets/Fonts/SegmentIcon.ttf#segment2"; #else if (Core.SampleBrowser.IsIndividualSB) { fontFamily = "/Assets/Fonts/SegmentIcon.ttf#segment2"; } else { fontFamily = $"ms-appx:///SampleBrowser.SfSegmentedControl.UWP/Assets/Fonts/SegmentIcon.ttf#segment2"; } #endif } else if (Device.RuntimePlatform == Device.iOS) { fontFamily = "segment2"; } else if (Device.RuntimePlatform == Device.WPF) { fontFamily = "Assets/Fonts/SegmentIcon.ttf#segment2"; } var SegoeFontFamily = "Segoe_MDL2_Assets.ttf"; if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB SegoeFontFamily = "/Assets/Fonts/Segoe_MDL2_Assets.ttf#Segoe MDL2 Assets"; #else if (Core.SampleBrowser.IsIndividualSB) { SegoeFontFamily = "/Assets/Fonts/Segoe_MDL2_Assets.ttf#Segoe MDL2 Assets"; } else { SegoeFontFamily = $"ms-appx:///SampleBrowser.SfSegmentedControl.UWP/Assets/Fonts/Segoe_MDL2_Assets.ttf#Segoe MDL2 Assets"; } #endif } else if (Device.RuntimePlatform == Device.iOS) { SegoeFontFamily = "Segoe MDL2 Assets"; } else if (Device.RuntimePlatform == Device.WPF) { SegoeFontFamily = "/Assets/Fonts/Segoe_MDL2_Assets.ttf#Segoe MDL2 Assets"; } BackLightCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem() { Text = "Backlight On", FontColor = Color.White }, new SfSegmentItem() { Text = "Backlight Off", FontColor = Color.White } }; IconCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "1", FontIconFontColor=Color.FromHex("#04ACAC"), FontIconFontSize=18, FontIconFontFamily = fontFamily }, new SfSegmentItem(){IconFont = "2", FontIconFontColor=Color.FromHex("#04ACAC"), FontIconFontSize=18, FontIconFontFamily = fontFamily}, new SfSegmentItem(){IconFont = "3", FontIconFontColor=Color.FromHex("#04ACAC"), FontIconFontSize=18, FontIconFontFamily = fontFamily}, new SfSegmentItem(){IconFont = "4", FontIconFontColor=Color.FromHex("#04ACAC"),FontIconFontSize=18, FontIconFontFamily = fontFamily}, new SfSegmentItem(){IconFont = "5", FontIconFontColor=Color.FromHex("#04ACAC"),FontIconFontSize=18, FontIconFontFamily = fontFamily}, }; Image_textCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "6", FontIconFontColor=Color.FromHex("#FFFFFF"), FontColor=Color.FromHex("#FFFFFF"), Text="Day", FontIconFontSize=18, FontIconFontFamily = fontFamily}, new SfSegmentItem(){IconFont = "6", FontIconFontColor=Color.FromHex("#FFFFFF"), FontColor=Color.FromHex("#FFFFFF"), Text="Week",FontIconFontSize=18, FontIconFontFamily = fontFamily}, new SfSegmentItem(){IconFont = "6", FontIconFontColor=Color.FromHex("#FFFFFF"), FontColor=Color.FromHex("#FFFFFF"), Text="Month", FontIconFontSize=18, FontIconFontFamily = fontFamily}, }; TextCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "6", Text="Day", FontIconFontSize=18, FontIconFontFamily = fontFamily}, new SfSegmentItem(){IconFont = "6", Text="Week",FontIconFontSize=18, FontIconFontFamily = fontFamily}, new SfSegmentItem(){IconFont = "6", Text="Month", FontIconFontSize=18, FontIconFontFamily = fontFamily}, }; PrimaryColors = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#32318E"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#2F7DC0"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#953376"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#B33F3F"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#F1973F"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#C9D656"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#008D7F"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, }; } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/ScheduleView/ScheduleEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using CoreGraphics; using Foundation; using Syncfusion.SfSchedule.iOS; using UIKit; namespace SampleBrowser { public class ScheduleEditor { internal UIView Editor; internal UIButton button_cancel, button_save, done_button, timezoneButton, doneButton, button_startDate, button_endDate, startTimeZoneButton, endTimeZoneButton; internal UITextView label_subject, label_location; internal UILabel label_starts, label_ends, startTimeZoneLabel, endTimeZoneLabel, allDaylabel, timezoneLabel; internal UISwitch allDaySwitch; internal UIPickerView startTimeZonePicker, endTimeZonePicker, timeZonePicker; internal UIDatePicker picker_startDate, picker_endDate; internal UIScrollView scrollView; private SFSchedule schedule; private ScheduleViews scheduleViews; public ScheduleEditor(SFSchedule sfSchedule, ScheduleViews scheduleView) { this.schedule = sfSchedule; this.scheduleViews = scheduleView; Editor = new UIView(); Editor.BackgroundColor = UIColor.White; } internal void CreateOptionWindow() { if (timezoneButton == null) { timezoneButton = new UIButton(); timezoneButton.Layer.BorderWidth = 2; timezoneButton.Layer.CornerRadius = 4; timezoneButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; timezoneButton.SetTitle("Default", UIControlState.Normal); timezoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); } if (timezoneLabel == null) { timezoneLabel = new UILabel(); timezoneLabel.Text = "Time Zone"; timezoneLabel.TextColor = UIColor.Black; } if (timeZonePicker == null) { timeZonePicker = new UIPickerView(); timeZonePicker.Hidden = true; } if (doneButton == null) { doneButton = new UIButton(); doneButton.Hidden = true; doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.BackgroundColor = UIColor.LightGray; doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; } timezoneButton.TouchUpInside += (object sender, EventArgs e) => { timeZonePicker.Hidden = false; doneButton.Hidden = false; }; doneButton.TouchUpInside += (object sender, EventArgs e) => { timeZonePicker.Hidden = true; doneButton.Hidden = true; }; SchedulePickerModel model = new SchedulePickerModel(TimeZoneCollection.TimeZoneList); model.PickerChanged += (sender, e) => { if (e.SelectedValue != "Default") { schedule.TimeZone = e.SelectedValue; } timezoneButton.SetTitle(e.SelectedValue, UIControlState.Normal); }; timeZonePicker.Model = model; timeZonePicker.ShowSelectionIndicator = true; if (Utility.IsIpad) { timezoneLabel.Frame = new CGRect(0, 0, 320, 30); timezoneButton.Frame = new CGRect(0, timezoneLabel.Frame.Bottom, 320, 30); doneButton.Frame = new CGRect(0, timezoneButton.Frame.Bottom, 320, 30); timeZonePicker.Frame = new CGRect(0, doneButton.Frame.Bottom, 320, 200); } } internal void CreateEditor() { button_cancel = new UIButton(); button_save = new UIButton(); label_subject = new UITextView(); label_location = new UITextView(); label_ends = new UILabel(); label_starts = new UILabel(); button_startDate = new UIButton(); button_endDate = new UIButton(); startTimeZoneLabel = new UILabel(); endTimeZoneLabel = new UILabel(); startTimeZoneButton = new UIButton(); endTimeZoneButton = new UIButton(); picker_startDate = new UIDatePicker(); picker_endDate = new UIDatePicker(); done_button = new UIButton(); scrollView = new UIScrollView(); startTimeZonePicker = new UIPickerView(); endTimeZonePicker = new UIPickerView(); allDaySwitch = new UISwitch(); allDaylabel = new UILabel(); scrollView.BackgroundColor = UIColor.White; label_subject.Font = UIFont.SystemFontOfSize(14); label_location.Font = UIFont.SystemFontOfSize(14); label_starts.Font = UIFont.SystemFontOfSize(15); label_ends.Font = UIFont.SystemFontOfSize(15); startTimeZoneLabel.Font = UIFont.SystemFontOfSize(15); endTimeZoneLabel.Font = UIFont.SystemFontOfSize(15); allDaylabel.Font = UIFont.SystemFontOfSize(15); startTimeZoneButton.Font = UIFont.SystemFontOfSize(15); endTimeZoneButton.Font = UIFont.SystemFontOfSize(15); button_startDate.Font = UIFont.SystemFontOfSize(15); button_endDate.Font = UIFont.SystemFontOfSize(15); button_cancel.BackgroundColor = UIColor.FromRGB(229, 229, 229); button_cancel.Font = UIFont.SystemFontOfSize(15); button_save.Font = UIFont.SystemFontOfSize(15); button_save.BackgroundColor = UIColor.FromRGB(33, 150, 243); button_cancel.Layer.CornerRadius = 6; button_save.Layer.CornerRadius = 6; button_startDate.Layer.CornerRadius = 6; button_endDate.Layer.CornerRadius = 6; startTimeZoneLabel.Text = "Start Time Zone"; startTimeZoneLabel.TextColor = UIColor.Black; endTimeZoneLabel.Text = "End Time Zone"; endTimeZoneLabel.TextColor = UIColor.Black; allDaylabel.Text = "All Day"; allDaylabel.TextColor = UIColor.Black; allDaySwitch.On = false; allDaySwitch.OnTintColor = UIColor.FromRGB(33, 150, 243); allDaySwitch.ValueChanged += AllDaySwitch_ValueChanged; startTimeZoneButton.SetTitle("Default", UIControlState.Normal); startTimeZoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); startTimeZoneButton.Layer.BorderWidth = 2; startTimeZoneButton.Layer.CornerRadius = 4; startTimeZoneButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; startTimeZoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; startTimeZoneButton.TouchUpInside += (object sender, EventArgs e) => { startTimeZonePicker.Hidden = false; done_button.Hidden = false; allDaylabel.Hidden = true; allDaySwitch.Hidden = true; button_cancel.Hidden = true; button_save.Hidden = true; endTimeZoneLabel.Hidden = true; endTimeZoneButton.Hidden = true; Editor.EndEditing(true); }; endTimeZoneButton.SetTitle("Default", UIControlState.Normal); endTimeZoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); endTimeZoneButton.Layer.BorderWidth = 2; endTimeZoneButton.Layer.CornerRadius = 4; endTimeZoneButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; endTimeZoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; endTimeZoneButton.TouchUpInside += (object sender, EventArgs e) => { endTimeZonePicker.Hidden = false; done_button.Hidden = false; allDaylabel.Hidden = true; allDaySwitch.Hidden = true; button_cancel.Hidden = true; button_save.Hidden = true; endTimeZoneLabel.Hidden = true; endTimeZoneButton.Hidden = true; Editor.EndEditing(true); }; //cancel button button_cancel.SetTitle("Cancel", UIControlState.Normal); button_cancel.SetTitleColor(UIColor.FromRGB(59, 59, 59), UIControlState.Normal);// UIColor.FromRGB(59, 59, 59); button_cancel.TouchUpInside += (object sender, EventArgs e) => { Editor.Hidden = true; schedule.Hidden = false; Editor.EndEditing(true); scheduleViews.headerView.Hidden = false; }; //save button button_save.SetTitle("Save", UIControlState.Normal); button_save.SetTitleColor(UIColor.White, UIControlState.Normal); button_save.TouchUpInside += (object sender, EventArgs e) => { scheduleViews.headerView.Hidden = false; if (scheduleViews.indexOfAppointment != -1) { (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.indexOfAppointment.ToString())].Subject = (NSString)label_subject.Text; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.indexOfAppointment.ToString())].Location = (NSString)label_location.Text; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.indexOfAppointment.ToString())].StartTime = picker_startDate.Date; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.indexOfAppointment.ToString())].EndTime = picker_endDate.Date; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[int.Parse(scheduleViews.indexOfAppointment.ToString())].IsAllDay = allDaySwitch.On; } else { ScheduleAppointment appointment = new ScheduleAppointment(); appointment.Subject = (NSString)label_subject.Text; appointment.Location = (NSString)label_location.Text; appointment.StartTime = picker_startDate.Date; appointment.EndTime = picker_endDate.Date; appointment.AppointmentBackground = UIColor.FromRGB(0xA2, 0xC1, 0x39); appointment.IsAllDay = allDaySwitch.On; (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>).Add(appointment); } Editor.Hidden = true; schedule.Hidden = false; schedule.ReloadData(); Editor.EndEditing(true); }; //subject label label_subject.TextColor = UIColor.Black; label_subject.TextAlignment = UITextAlignment.Left; label_subject.Layer.CornerRadius = 8; label_subject.Layer.BorderWidth = 2; label_subject.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //location label label_location.TextColor = UIColor.Black; label_location.TextAlignment = UITextAlignment.Left; label_location.Layer.CornerRadius = 8; label_location.Layer.BorderWidth = 2; label_location.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //starts time label_starts.Text = "Start Time"; label_starts.TextColor = UIColor.Black; button_startDate.SetTitle("Start time", UIControlState.Normal); button_startDate.Layer.BorderWidth = 2; button_startDate.Layer.CornerRadius = 4; button_startDate.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; button_startDate.SetTitleColor(UIColor.Black, UIControlState.Normal); button_startDate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_startDate.TouchUpInside += (object sender, EventArgs e) => { picker_startDate.Hidden = false; done_button.Hidden = false; allDaylabel.Hidden = true; allDaySwitch.Hidden = true; button_cancel.Hidden = true; button_save.Hidden = true; endTimeZoneLabel.Hidden = true; endTimeZoneButton.Hidden = true; Editor.EndEditing(true); }; //end time label_ends.Text = "End Time"; label_ends.TextColor = UIColor.Black; //end date button_endDate.SetTitle("End time", UIControlState.Normal); button_endDate.SetTitleColor(UIColor.Black, UIControlState.Normal); button_endDate.Layer.BorderWidth = 2; button_endDate.Layer.CornerRadius = 4; button_endDate.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; button_endDate.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_endDate.TouchUpInside += (object sender, EventArgs e) => { picker_endDate.Hidden = false; done_button.Hidden = false; allDaylabel.Hidden = true; allDaySwitch.Hidden = true; button_cancel.Hidden = true; button_save.Hidden = true; endTimeZoneLabel.Hidden = true; endTimeZoneButton.Hidden = true; Editor.EndEditing(true); }; //date and time pickers picker_startDate.Hidden = true; picker_endDate.Hidden = true; startTimeZonePicker.Hidden = true; endTimeZonePicker.Hidden = true; done_button.Hidden = true; //done button done_button.SetTitle("Done", UIControlState.Normal); done_button.SetTitleColor(UIColor.Blue, UIControlState.Normal); done_button.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; done_button.TouchUpInside += (object sender, EventArgs e) => { picker_startDate.Hidden = true; picker_endDate.Hidden = true; startTimeZonePicker.Hidden = true; endTimeZonePicker.Hidden = true; done_button.Hidden = true; label_ends.Hidden = false; button_endDate.Hidden = false; button_startDate.Hidden = false; label_starts.Hidden = false; endTimeZoneLabel.Hidden = false; startTimeZoneLabel.Hidden = false; allDaylabel.Hidden = false; allDaySwitch.Hidden = false; startTimeZoneButton.Hidden = false; endTimeZoneButton.Hidden = false; button_cancel.Hidden = false; button_save.Hidden = false; String _sDate = DateTime.Parse((picker_startDate.Date.ToString())).ToString(); button_startDate.SetTitle(_sDate, UIControlState.Normal); String _eDate = DateTime.Parse((picker_endDate.Date.ToString())).ToString(); button_endDate.SetTitle(_eDate, UIControlState.Normal); Editor.EndEditing(true); }; SchedulePickerModel model = new SchedulePickerModel(TimeZoneCollection.TimeZoneList); model.PickerChanged += (sender, e) => { if (e.SelectedValue != "Default" && scheduleViews.selectedAppointment != null) scheduleViews.selectedAppointment.StartTimeZone = e.SelectedValue; startTimeZoneButton.SetTitle(e.SelectedValue, UIControlState.Normal); }; SchedulePickerModel model2 = new SchedulePickerModel(TimeZoneCollection.TimeZoneList); model2.PickerChanged += (sender, e) => { if (e.SelectedValue != "Default" && scheduleViews.selectedAppointment != null) scheduleViews.selectedAppointment.EndTimeZone = e.SelectedValue; endTimeZoneButton.SetTitle(e.SelectedValue, UIControlState.Normal); }; startTimeZonePicker.Model = model; endTimeZonePicker.Model = model2; startTimeZonePicker.ShowSelectionIndicator = true; endTimeZonePicker.ShowSelectionIndicator = true; scrollView.Add(label_subject); scrollView.Add(label_location); scrollView.Add(label_starts); scrollView.Add(button_startDate); scrollView.Add(startTimeZoneLabel); scrollView.Add(startTimeZoneButton); scrollView.Add(label_ends); scrollView.Add(button_endDate); scrollView.Add(endTimeZoneLabel); scrollView.Add(endTimeZoneButton); scrollView.Add(startTimeZonePicker); scrollView.Add(endTimeZonePicker); scrollView.Add(picker_endDate); scrollView.Add(picker_startDate); scrollView.Add(done_button); scrollView.Add(allDaylabel); scrollView.Add(allDaySwitch); scrollView.Add(button_cancel); scrollView.Add(button_save); Editor.Add(scrollView); } internal void EditorFrameUpdate() { var childHeight = 30; if (Utility.IsIpad) { childHeight = 40; } var padding = 20; label_subject.Frame = new CGRect(scrollView.Frame.X, scrollView.Frame.Y, scrollView.Frame.Size.Width - padding, childHeight); label_location.Frame = new CGRect(scrollView.Frame.X, label_subject.Frame.Bottom + 10, scrollView.Frame.Size.Width - padding, childHeight); label_starts.Frame = new CGRect(scrollView.Frame.X, label_location.Frame.Bottom, scrollView.Frame.Size.Width - padding, childHeight); button_startDate.Frame = new CGRect(scrollView.Frame.X, label_starts.Frame.Bottom, scrollView.Frame.Size.Width - padding, childHeight); startTimeZoneLabel.Frame = new CGRect(scrollView.Frame.X, button_startDate.Frame.Bottom, scrollView.Frame.Size.Width - padding, childHeight); startTimeZoneButton.Frame = new CGRect(scrollView.Frame.X, startTimeZoneLabel.Frame.Bottom, scrollView.Frame.Size.Width - padding, childHeight); label_ends.Frame = new CGRect(scrollView.Frame.X, startTimeZoneButton.Frame.Bottom, scrollView.Frame.Size.Width - padding, childHeight); button_endDate.Frame = new CGRect(scrollView.Frame.X, label_ends.Frame.Bottom, scrollView.Frame.Size.Width - padding, childHeight); endTimeZoneLabel.Frame = new CGRect(scrollView.Frame.X, button_endDate.Frame.Bottom, scrollView.Frame.Size.Width - padding, childHeight); endTimeZoneButton.Frame = new CGRect(scrollView.Frame.X, endTimeZoneLabel.Frame.Bottom, scrollView.Frame.Size.Width - padding, childHeight); allDaylabel.Frame = new CGRect(scrollView.Frame.X, endTimeZoneButton.Frame.Bottom + 10, scrollView.Frame.Size.Width / 2 - padding, childHeight); allDaySwitch.Frame = new CGRect(allDaylabel.Frame.Right, endTimeZoneButton.Frame.Bottom + 10, scrollView.Frame.Size.Width / 2 - padding, childHeight); button_cancel.Frame = new CGRect(scrollView.Frame.X, allDaySwitch.Frame.Bottom + 10, scrollView.Frame.Size.Width / 2 - padding, childHeight); button_save.Frame = new CGRect(button_cancel.Frame.Right + 10, allDaySwitch.Frame.Bottom + 10, scrollView.Frame.Size.Width / 2 - padding, childHeight); picker_startDate.Frame = new CGRect(scrollView.Frame.X, button_endDate.Frame.Bottom, scrollView.Frame.Size.Width - padding, 200); picker_endDate.Frame = new CGRect(scrollView.Frame.X, button_endDate.Frame.Bottom, scrollView.Frame.Size.Width - padding, 200); startTimeZonePicker.Frame = new CGRect(scrollView.Frame.X, button_endDate.Frame.Bottom, scrollView.Frame.Size.Width - padding, 200); endTimeZonePicker.Frame = new CGRect(scrollView.Frame.X, button_endDate.Frame.Bottom, scrollView.Frame.Size.Width - padding, 200); done_button.Frame = new CGRect(scrollView.Frame.X, button_endDate.Frame.Bottom, scrollView.Frame.Size.Width - padding, childHeight); scrollView.ContentSize = new CGSize(scrollView.Frame.Size.Width - padding, button_cancel.Frame.Bottom); } internal void Disablechild() { startTimeZoneButton.UserInteractionEnabled = false; startTimeZoneButton.SetTitleColor(UIColor.Gray, UIControlState.Normal); endTimeZoneButton.UserInteractionEnabled = false; endTimeZoneButton.SetTitleColor(UIColor.Gray, UIControlState.Normal); } internal void EnableChild() { startTimeZoneButton.UserInteractionEnabled = true; startTimeZoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); endTimeZoneButton.UserInteractionEnabled = true; endTimeZoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); } private void AllDaySwitch_ValueChanged(object sender, EventArgs e) { if ((sender as UISwitch).On) { this.Disablechild(); } else { this.EnableChild(); } if (scheduleViews.selectedAppointment != null) { scheduleViews.selectedAppointment.IsAllDay = (sender as UISwitch).On; } } } }<file_sep>/iOS/SampleBrowser/Samples/Presentation/OLEObject.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Presentation; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class OLEObject : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; UIButton button2; public OLEObject() { label1 = new UILabel(); label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; button2 = new UIButton(UIButtonType.System); button2.TouchUpInside += OnInsertOleButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to insert and extract a OLE Object in PowerPoint presentation."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width , 50); } else { label.Frame = new CGRect (frameRect.Location.X, 5, frameRect.Size.Width , 70); } this.AddSubview (label); button.SetTitle("Open Embedded File",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect (0, 65, frameRect.Location.X + frameRect.Size.Width , 10); } else { button.Frame = new CGRect (frameRect.Location.X, 70, frameRect.Size.Width , 10); } this.AddSubview (button); button2.SetTitle("Create Presentation", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button2.Frame = new CGRect(0, 105, frameRect.Location.X + frameRect.Size.Width, 10); } else { button2.Frame = new CGRect(frameRect.Location.X, 110, frameRect.Size.Width, 10); } this.AddSubview(button2); } void OnInsertOleButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); //New Instance of PowerPoint is Created.[Equivalent to launching MS PowerPoint with no slides]. IPresentation presentation = Syncfusion.Presentation.Presentation.Create(); ISlide slide = presentation.Slides.Add(SlideLayoutType.TitleOnly); IShape titleShape = slide.Shapes[0] as IShape; titleShape.Left = 0.65 * 72; titleShape.Top = 0.24 * 72; titleShape.Width = 11.5 * 72; titleShape.Height = 1.45 * 72; titleShape.TextBody.AddParagraph("Ole Object"); titleShape.TextBody.Paragraphs[0].Font.Bold = true; titleShape.TextBody.Paragraphs[0].HorizontalAlignment = HorizontalAlignmentType.Left; IShape heading = slide.Shapes.AddTextBox(100, 100, 100, 100); heading.Left = 0.84 * 72; heading.Top = 1.65 * 72; heading.Width = 2.23 * 72; heading.Height = 0.51 * 72; heading.TextBody.AddParagraph("MS Word Object"); heading.TextBody.Paragraphs[0].Font.Italic = true; heading.TextBody.Paragraphs[0].Font.Bold = true; heading.TextBody.Paragraphs[0].Font.FontSize = 18; string mswordPath = "SampleBrowser.Samples.Presentation.Templates.OleTemplate.docx"; //Get the word file as stream Stream wordStream = assembly.GetManifestResourceStream(mswordPath); string imagePath = "SampleBrowser.Samples.Presentation.Templates.OlePicture.png"; //Image to be displayed, This can be any image Stream imageStream = assembly.GetManifestResourceStream(imagePath); IOleObject oleObject = slide.Shapes.AddOleObject(imageStream, "Word.Document.12", wordStream); //Set size and position of the ole object oleObject.Left = 4.53 * 72; oleObject.Top = 0.79 * 72; oleObject.Width = 4.26 * 72; oleObject.Height = 5.92 * 72; //Set DisplayAsIcon as true, to open the embedded document in separate (default) application. oleObject.DisplayAsIcon = true; MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("InsertOLEObject.pptx", "application/mspowerpoint", stream); } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.EmbeddedOleObject.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Presentation.Open(fileStream); //Gets the first slide of the Presentation ISlide slide = presentation.Slides[0]; //Gets the Ole Object of the slide IOleObject oleObject = slide.Shapes[2] as IOleObject; //Gets the file data of embedded Ole Object. byte[] array = oleObject.ObjectData; //Gets the file Name of OLE Object string outputFile = oleObject.FileName; MemoryStream stream = new MemoryStream(array); presentation.Close(); stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save (outputFile, "application/msword", stream); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/Forms/DocIO/DocIO/Samples/XMLMapping/XMLMapping.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.Core; using System.IO; using System.Reflection; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Xamarin.Forms; namespace SampleBrowser.DocIO { /// <summary> /// A sample view that can be used on XMLMapping. /// </summary> public partial class XMLMapping : SampleView { /// <summary> /// Constructor for XMLMapping. /// </summary> public XMLMapping() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { //if (!SampleBrowser.DocIO.App.isUWP) //{ // this.Content_1.FontSize = 18.5; // } // else // { this.Content_1.FontSize = 13.5; // } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } /// <summary> /// Button click event for XMLMapping. /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event args</param> private void OnButtonClicked(object sender, EventArgs e) { #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif // Load Template document stream. Stream inputStream = typeof(XMLMapping).GetTypeInfo().Assembly.GetManifestResourceStream(rootPath + "Employees.xml"); // Create a new document. WordDocument document = new WordDocument(); //Add a section & a paragraph in the empty document. document.EnsureMinimal(); //Loads XML file into the customXML part of the Word document. CustomXMLPart docIOxmlPart = new CustomXMLPart(document); docIOxmlPart.Load(inputStream); //Insert content controls and maps Employees details to it. InsertAndMapEmployees(document, "EmployeesList", docIOxmlPart); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Docx); document.Close(); if (Device.RuntimePlatform == Device.UWP) DependencyService.Get<ISaveWindowsPhone>() .Save("XMLMapping.docx", "application/msword", stream); else DependencyService.Get<ISave>().Save("XMLMapping.docx", "application/msword", stream); } /// <summary> /// Insert and Maps CustomXMLPart to content control based on XPath. /// </summary> /// <param name="paragraph">Paragraph instance to append content control.</param> /// <param name="XPath">XPath of the CustomXMLNode to be mapped</param> /// <param name="custXMLPart">CustomXMLPart of the CustomXMLNode</param> private void MapCustomXMLPart(IWParagraph paragraph, string XPath, CustomXMLPart custXMLPart) { IInlineContentControl contentControl = paragraph.AppendInlineContentControl(ContentControlType.Text); contentControl.ContentControlProperties.XmlMapping.SetMapping(XPath, string.Empty, custXMLPart); } /// <summary> /// Inserts content control and maps the employees details to it. /// </summary> /// <param name="document">Word document instance.</param> /// <param name="xmlRootPath">Custom XML root Xpath.</param> /// <param name="docIOxmlPart">CustomXMLPart instance.</param> private void InsertAndMapEmployees(WordDocument document, string xmlRootPath, CustomXMLPart docIOxmlPart) { //Retrieving CustomXMLNode from xmlRootPath. CustomXMLNode parentNode = docIOxmlPart.SelectSingleNode(xmlRootPath); int empIndex = 1; foreach (CustomXMLNode employeeNode in parentNode.ChildNodes) { if (employeeNode.HasChildNodes()) { //Adds new paragraph to the section IWParagraph paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.BackColor = Syncfusion.Drawing.Color.Gray; IWTextRange textrange = paragraph.AppendText("Employee"); textrange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; textrange.CharacterFormat.Bold = true; textrange.CharacterFormat.FontSize = 14; //Insert content controls and maps Employee details to it. InsertAndMapEmployee(document, employeeNode, xmlRootPath, docIOxmlPart, empIndex); } empIndex++; } } /// <summary> /// Inserts content control and maps the employee details to it. /// </summary> /// <param name="document">Word document instance.</param> /// <param name="employeesNode">CustomXMLNode of employee.</param> /// <param name="rootXmlPath">Custom XML root Xpath.</param> /// <param name="docIOxmlPart">CustomXMLPart instance.</param> /// <param name="empIndex">Current employee index.</param> private void InsertAndMapEmployee(WordDocument document, CustomXMLNode employeesNode, string rootXmlPath, CustomXMLPart docIOxmlPart, int empIndex) { //Column names of Employee element. string[] employeesDetails = { "FirstName", "LastName", "Employee ID", "Extension", "Address", "City", "Country" }; int empChildIndex = 0; int customerIndex = 1; // Append current empolyee XPath with root XPath. string empPath = "/" + rootXmlPath + "/Employees[" + empIndex + "]/"; // Iterating child elements of Employee foreach (CustomXMLNode employeeChild in employeesNode.ChildNodes) { IWParagraph paragraph = document.LastParagraph; if (employeeChild.HasChildNodes()) { //Insert a content controls and maps Customer details to it. InsertAndMapCustomer(document, employeeChild, docIOxmlPart, empPath, customerIndex); customerIndex++; } else { if (empChildIndex != 1) { //Insert a content controls and maps Employee details other than Customer details to it. paragraph = document.LastSection.AddParagraph(); if (empChildIndex == 0) paragraph.AppendText("Name: "); else paragraph.AppendText(employeesDetails[empChildIndex] + ": "); } else paragraph.AppendText(" "); MapCustomXMLPart(paragraph, empPath + employeesDetails[empChildIndex].Replace(" ",""), docIOxmlPart); } empChildIndex++; } } /// <summary> /// Insert a content controls and maps Customer details to it. /// </summary> /// <param name="document">Word document instance.</param> /// <param name="customerNode">CustomXMLNode of customer.</param> /// <param name="docIOxmlPart">CustomXMLPart instance.</param> /// <param name="empPath">Current employee index.</param> /// <param name="custIndex">Current customer index.</param> private void InsertAndMapCustomer(WordDocument document, CustomXMLNode customerNode, CustomXMLPart docIOxmlPart, string empPath, int custIndex) { //Column names of Customer element. string[] customersDetails = { "Customer ID", "Employee ID", "Company Name", "Contact Name", "City", "Country" }; document.LastSection.AddParagraph(); //Adds new paragraph to the section IWParagraph paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.BackColor = Syncfusion.Drawing.Color.Green; paragraph.ParagraphFormat.LeftIndent = 72; IWTextRange textrange = paragraph.AppendText("Customers"); textrange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; textrange.CharacterFormat.Bold = true; textrange.CharacterFormat.FontSize = 14; int orderIndex = 1; int custChild = 0; bool isFirstOrder = true; string customerXpath = empPath + "Customers[" + custIndex + "]/"; foreach (CustomXMLNode customerChild in customerNode.ChildNodes) { if (customerChild.HasChildNodes()) { //Insert a content controls and maps Orders details to it. InsertAndMapOrders(document, customerChild, docIOxmlPart, customerXpath, orderIndex, isFirstOrder); document.LastSection.AddParagraph(); isFirstOrder = false; orderIndex++; } else { //Insert a content controls and maps Customer details other than Order details to it. paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.LeftIndent = 72; paragraph.AppendText(customersDetails[custChild] + ": "); MapCustomXMLPart(paragraph, customerXpath + customersDetails[custChild].Replace(" ", ""), docIOxmlPart); } custChild++; } } /// <summary> /// Insert a content controls and maps Orders details to it. /// </summary> /// <param name="document">Word document instance.</param> /// <param name="orderNode">CustomXMLNode of order.</param> /// <param name="docIOxmlPart">CustomXMLPart instance.</param> /// <param name="custPath">Current customer index</param> /// <param name="orderIndex">Current order index</param> /// <param name="isFirst">Indicates whether it is the first order of the customer.</param> private void InsertAndMapOrders(WordDocument document, CustomXMLNode orderNode, CustomXMLPart docIOxmlPart, string custPath, int orderIndex, bool isFirst) { //Column names of order element. string[] ordersDetails = { "Order ID", "Customer ID", "Order Date", "Shipped Date", "Required Date" }; IWParagraph paragraph = null; IWTextRange textrange = null; if (isFirst) { document.LastSection.AddParagraph(); //Adds new paragraph to the section paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.BackColor = Syncfusion.Drawing.Color.Red; paragraph.ParagraphFormat.LeftIndent = 128; textrange = paragraph.AppendText("Orders"); textrange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; textrange.CharacterFormat.Bold = true; textrange.CharacterFormat.FontSize = 14; } int orderChildIndex = 0; string customerXpath = custPath + "Orders[" + orderIndex + "]/"; foreach (CustomXMLNode orderChild in orderNode.ChildNodes) { //Adds new paragraph to the section paragraph = document.LastSection.AddParagraph(); paragraph.ParagraphFormat.LeftIndent = 128; paragraph.AppendText(ordersDetails[orderChildIndex] + ": "); MapCustomXMLPart(paragraph, customerXpath + "/" + ordersDetails[orderChildIndex].Replace(" ", ""), docIOxmlPart); orderChildIndex++; } } } } <file_sep>/Android/SampleBrowser/Samples/ImageEditor/ImageEditorCustomization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Syncfusion.SfImageEditor.Android; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Content; using Android.Content.PM; using Android.Graphics.Drawables; using Android.Views; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; using Android.Content.Res; using Android.Util; namespace SampleBrowser { public class ImageEditorCustomization : SamplePage { internal static Activity Activity { get; set; } View view { get; set; } public static Bitmap Image { get; set; } Context con { get; set; } public static String Name; SfImageEditor editor; bool isRect, isText, isPath = false; string location = ""; Share share; EditText editText; object Settings; void Editor_ItemSelected(object sender, ItemSelectedEventArgs e) { Settings = e.Settings; } public override Android.Views.View GetSampleContent(Android.Content.Context context) { var deviceDensity = (int)context.Resources.DisplayMetrics.Density; // Set our view from the "main" layout resource var layoutInflater = LayoutInflater.From(context); view = layoutInflater.Inflate(Resource.Layout.EditorCustomization, null); FrameLayout mainLayout = view.FindViewById<FrameLayout> (Resource.Id.CustomizationMain); editor = new SfImageEditor(context); editor.Bitmap = BitmapFactory.DecodeResource(context.Resources, Resource.Drawable.Customize); editor.ItemSelected += Editor_ItemSelected; editor.ToolbarSettings.IsVisible = false; editor.SetBackgroundColor(Color.Black); editor.ToolbarSettings.SubItemToolbarHeight = 0; var bottomview = layoutInflater.Inflate(Resource.Layout.BottomView, mainLayout, true); var topview = layoutInflater.Inflate(Resource.Layout.TopView, mainLayout, true); var rightview = layoutInflater.Inflate(Resource.Layout.RightView, mainLayout, true); //Bottom View------------------------------------ var bottomView = bottomview.FindViewById<LinearLayout>(Resource.Id.bottomView); bottomView.SetGravity(GravityFlags.Bottom); var bParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent, 50 * deviceDensity, GravityFlags.Bottom); bottomView.SetBackgroundColor(Color.Transparent); bParams.SetMargins(0, 0, 0, 10 * deviceDensity); bottomView.LayoutParameters = bParams; //Top View------------------------------------ var topView = topview.FindViewById<LinearLayout>(Resource.Id.topView); var tParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent, 50 * deviceDensity, GravityFlags.Top); tParams.SetMargins(0, 10 * deviceDensity, 0, 0); topView.LayoutParameters = tParams; //Right View------------------------------------ var rightView = rightview.FindViewById<LinearLayout>(Resource.Id.rightView); var rParams = new FrameLayout.LayoutParams(65 * deviceDensity, FrameLayout.LayoutParams.MatchParent, GravityFlags.Right); rParams.SetMargins(0, 250, 0, 250); rightView.SetBackgroundColor(Color.Transparent); rightView.SetPadding(0, 0, 15 * deviceDensity, 15 * deviceDensity); rightView.LayoutParameters = rParams; rightView.Visibility = ViewStates.Invisible; topView.Visibility = ViewStates.Invisible; mainLayout.RemoveAllViews(); (mainLayout.Parent as ViewGroup)?.RemoveAllViews(); mainLayout.AddView(editor); mainLayout.AddView(topView); mainLayout.AddView(bottomView); mainLayout.AddView(rightView); Button dummyLayout = new Button(context); dummyLayout.SetBackgroundColor(Color.Transparent); dummyLayout.Alpha = 0.5F; mainLayout.AddView(dummyLayout); dummyLayout.Click += (sender, e) => { topView.Visibility = ViewStates.Visible; dummyLayout.Visibility = ViewStates.Invisible; }; //Top view var reset = topView.FindViewById<ImageButton>(Resource.Id.resetButton); var undo = topView.FindViewById<ImageButton>(Resource.Id.undoButton); var rect = topView.FindViewById<ImageButton>(Resource.Id.rectButton); var text = topView.FindViewById<ImageButton>(Resource.Id.textButton); var path = topView.FindViewById<ImageButton>(Resource.Id.pathButton); reset.Click += (sender, e) => { if (editor.IsImageEdited) { editor.Reset(); } rightView.Visibility = ViewStates.Invisible; topView.Visibility = ViewStates.Invisible; dummyLayout.Visibility = ViewStates.Visible; isPath = false; isText = false; isRect = false; }; undo.Click += (sender, e) => { if (editor.IsImageEdited) { editor.Undo(); } }; rect.Click += (sender, e) => { isPath = false; isText = false; isRect = true; AddShapes(); rightView.Visibility = ViewStates.Visible; }; text.Click += (sender, e) => { isPath = false; isRect = false; isText = true; AddShapes(); rightView.Visibility = ViewStates.Visible; }; path.Click += (sender, e) => { isPath = true; isRect = false; isText = false; rightView.Visibility = ViewStates.Visible; editor.AddShape(); }; // colorLayout var firstBut = rightview.FindViewById<Button>(Resource.Id.firstButton); var secondBut = rightview.FindViewById<Button>(Resource.Id.secondButton); var thirdBut = rightview.FindViewById<Button>(Resource.Id.thirdButton); var fourthBut = rightview.FindViewById<Button>(Resource.Id.fourthButton); var fifthBut = rightview.FindViewById<Button>(Resource.Id.fifthButton); var sixthBut = rightview.FindViewById<Button>(Resource.Id.sixthButton); var seventhBut = rightview.FindViewById<Button>(Resource.Id.seventhButton); var eightBut = rightview.FindViewById<Button>(Resource.Id.eightButton); var ninthBut = rightview.FindViewById<Button>(Resource.Id.ninthButton); var tenthBut = rightview.FindViewById<Button>(Resource.Id.tenthButton); firstBut.Click += (sender, e) => { var color = Color.ParseColor("#4472c4"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; secondBut.Click += (sender, e) => { var color = Color.ParseColor("#ed7d31"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; thirdBut.Click += (sender, e) => { var color = Color.ParseColor("#ffc000"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; fourthBut.Click += (sender, e) => { var color = Color.ParseColor("#70ad47"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; fifthBut.Click += (sender, e) => { var color = Color.ParseColor("#5b9bd5"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; sixthBut.Click += (sender, e) => { var color = Color.ParseColor("#c1c1c1"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; seventhBut.Click += (sender, e) => { var color = Color.ParseColor("#6f6fe2"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; eightBut.Click += (sender, e) => { var color = Color.ParseColor("#e269ae"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; ninthBut.Click += (sender, e) => { var color = Color.ParseColor("#9e480e"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; tenthBut.Click += (sender, e) => { var color = Color.ParseColor("#997300"); setting(Settings, color); if (isPath) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Path, new PenSettings() { Color = color }); } }; //Share var share = bottomView.FindViewById<ImageButton>(Resource.Id.sharecustomization); editText = bottomView.FindViewById<EditText>(Resource.Id.captionText); share.Click += async (sender, e) => { await ShareImageAsync(); }; return mainLayout; } void setting(object Settings,Color color) { if (isPath) return; if (Settings is TextSettings) (Settings as TextSettings).Color = color; else if(Settings is PenSettings) (Settings as PenSettings).Color = color; } public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = System.Math.Sqrt(System.Math.Pow(screenWidth, 2) + System.Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } async Task ShareImageAsync() { editor.Save(); editor.ImageSaving += (sender, e) => { e.Cancel = false; }; editor.ImageSaved += (sender, e) => { location = e.Location; }; await DelayActionAsync(2500, Sharing); } public async Task DelayActionAsync(int delay, Action action) { await Task.Delay(delay); action(); } void Sharing() { share = new Share(); share.Show("Title", string.IsNullOrEmpty(editText.Text) ? "Message" : editText.Text.ToString(), location); } void AddShapes() { if (isRect) { editor.AddShape(Syncfusion.SfImageEditor.Android.ShapeType.Rectangle, new PenSettings()); isRect = true; isText = false; isPath = false; } else if (isText) { editor.AddText("Enter Text", new TextSettings()); isRect = false; isText = true; isPath = false; } } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Styles/Purple.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Purple.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Derived from DataGridStyle to add the custom styles /// </summary> public class Purple : DataGridStyle { /// <summary> /// Initializes a new instance of the Purple class. /// </summary> public Purple() { } /// <summary> /// Overrides this method to write a custom style for header background color /// </summary> /// <returns>Returns From H e x Color</returns> public override Color GetHeaderBackgroundColor() { return Color.FromHex("#83538B"); } /// <summary> /// Overrides this method to write a custom style for header foreground color /// </summary> /// <returns>Returns From H e x Color</returns> public override Color GetHeaderForegroundColor() { return Color.FromRgb(255, 255, 255); } /// <summary> /// Overrides this method to write a custom style for selection background color /// </summary> /// <returns>Returns given Color</returns> public override Color GetSelectionBackgroundColor() { return Color.FromRgb(149, 117, 205); } /// <summary> /// Overrides this method to write a custom style for selection foreground color /// </summary> /// <returns>Returns given Color</returns> public override Color GetSelectionForegroundColor() { return Color.FromRgb(255, 255, 255); } /// <summary> /// Overrides this method to write a custom style for alternate row background color /// </summary> /// <returns>Returns given Color</returns> public override Color GetAlternatingRowBackgroundColor() { return Color.FromRgb(237, 231, 246); } /// <summary> /// Overrides this method to write a custom style for alternate row foreground color /// </summary> /// <returns>Returns given Color</returns> public override Color GetRecordForegroundColor() { return Color.FromRgb(0, 0, 0); } /// <summary> /// Overrides this method to write a Grid line visibility /// </summary> /// <returns>Returns GridLinesVisibility Horizontal</returns> public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Horizontal; } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Styles/Green.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Graphics; using Syncfusion.SfDataGrid; namespace SampleBrowser { public class Green : DataGridStyle { public Green () { } public override Color GetHeaderBackgroundColor() { return Color.ParseColor("#5C8A5E"); } public override Color GetHeaderForegroundColor() { return Color.ParseColor("#FFFFFF"); } public override Color GetRecordForegroundColor() { return Color.ParseColor("#000000"); } public override Color GetAlternatingRowBackgroundColor() { return Color.ParseColor("#E8F5E9"); } public override Color GetSelectionBackgroundColor() { return Color.ParseColor("#81C784"); } public override Color GetSelectionForegroundColor() { return Color.ParseColor("#FFFFFF"); } public override Color GetCaptionSummaryRowBackgroundColor () { return Color.Rgb (224, 224, 224); } public override Color GetCaptionSummaryRowForegroundColor () { return Color.Rgb (51, 51, 51); } public override Color GetBorderColor () { return Color.Rgb (180, 180, 180); } public override int GetHeaderSortIndicatorDown () { return Resource.Drawable.SortingDown; } public override int GetHeaderSortIndicatorUp () { return Resource.Drawable.SortingUp; } public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Horizontal; } } } <file_sep>/Android/SampleBrowser/Samples/AutoComplete/ToleratingTyposSample/User.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.Content; using Android.Graphics.Drawables; using Android.Views; using Android.Widget; using System.Linq; namespace SampleBrowser { public class User { public string count = "0"; public string Text { get; set; } public string Image { get; set; } public string Count { get { return "About " + count + " results"; } set { count = value; } } public override string ToString() { return Text + " " + Count; } } public class MyCustomListAdapter : BaseAdapter<User> { List<User> users; ImageManager imageManager; public MyCustomListAdapter(List<User> users) { this.users = users; imageManager = new ImageManager(); } public override User this[int position] { get { return users[position]; } } public override int Count { get { return users.Count; } } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { var view = convertView; if (view == null) { view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.userRow, parent, false); var photo = view.FindViewById<ImageView>(Resource.Id.photoImageView); var name = view.FindViewById<TextView>(Resource.Id.nameTextView); name.TextSize = 14; var department = view.FindViewById<TextView>(Resource.Id.departmentTextView); view.Tag = new ViewHolder() { Image = photo, Text = name, Count = department }; } var holder = (ViewHolder)view.Tag; holder.Image.SetImageDrawable(imageManager.Get(parent.Context, users[position].Image)); holder.Text.Text = users[position].Text; holder.Count.Text = users[position].Count; return view; } } public class ImageManager { Dictionary<string, Drawable> cache = new Dictionary<string, Drawable>(); public Drawable Get(Context context, string url) { if (!cache.ContainsKey(url)) { var drawable = Drawable.CreateFromStream(context.Assets.Open(url), null); cache.Add(url, drawable); } return cache[url]; } } public class UserData { public List<User> Users { get; private set; } public UserData() { var temp = new List<User>(); AddUser(temp, "General", "all.png", "0"); AddUser(temp, "Maps", "Maps.png", "0"); AddUser(temp, "Images", "Picture.png", "0"); AddUser(temp, "News", "Newspaper.png", "0"); AddUser(temp, "Video", "Media.png", "0"); AddUser(temp, "Music", "Music.png", "0"); AddUser(temp, "Books", "Book.png", "0"); AddUser(temp, "Flight", "Aeroplane.png", "0"); AddUser(temp, "Quick Search", "Spaceship.png", "0"); Users = temp.ToList(); } void AddUser(List<User> users, string name, string image, string count) { users.Add(new User() { Text = name, Count = count, Image = image, }); //users.Add(new User() //{ // Text = "d<NAME>", // Count = "Xamarin Android & Xamarin Forms Development", // Image = "Image4.png", //}); } } public class ViewHolder : Java.Lang.Object { public ImageView Image { get; set; } public TextView Text { get; set; } public TextView Count { get; set; } } } <file_sep>/Android/SampleBrowser/Samples/Maps/Drilldown.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Com.Syncfusion.Maps; using Org.Json; using System.Collections.Generic; using Android.Graphics; using Android.Widget; using Android.OS; using Com.Syncfusion.Sfbusyindicator; using Com.Syncfusion.Sfbusyindicator.Enums; using System.Collections.ObjectModel; namespace SampleBrowser { public class Drilldown : SamplePage { SfMaps maps; Handler handler; TextView text; TextView text1; TextView text2; TextView text3; LinearLayout layout; ShapeFileLayer layer; LinearLayout linearLayout; LinearLayout linearLayout1; public override Android.Views.View GetSampleContent(Android.Content.Context context) { handler = new Handler(); layout = new LinearLayout(context); linearLayout1 = new LinearLayout(context); linearLayout = new LinearLayout(context); linearLayout.Visibility = Android.Views.ViewStates.Invisible; text = new TextView(context); text.TextSize = 16; text.SetPadding(10, 20, 0, 0); text.SetHeight(90); text.Text = "WorldMap"; text.SetTextColor(Color.Blue); text.Click += Text_Click; linearLayout.AddView(text); text3 = new TextView(context); text3.TextSize = 16; text3.SetPadding(10, 20, 0, 0); text3.Text = "Click on a shape to drill"; text3.TextAlignment = Android.Views.TextAlignment.Center; linearLayout1.AddView(text3); text1 = new TextView(context); text1.Text = ">>"; text1.SetPadding(10, 20, 0, 0); linearLayout.AddView(text1); text2 = new TextView(context); linearLayout.AddView(text2); layout.Orientation = Orientation.Vertical; maps = new SfMaps(context); maps.EnableZooming = false; layer = new ShapeFileLayer(); layer.Uri = "world-map.shp"; layer.EnableSelection = true; layer.ShapeIdTableField = "admin"; layer.ShapeIdPath = "country"; layer.DataSource = GetDataSource(); layer.ShapeSettings.ShapeColorValuePath = "continent"; layer.ShapeSelected += (object sender, ShapeFileLayer.ShapeSelectedEventArgs e) => { JSONObject data = (JSONObject)e.P0; if (data != null) { var dat = data.Get("continent").ToString(); text2.Text = dat; linearLayout.Visibility = Android.Views.ViewStates.Visible; linearLayout1.Visibility = Android.Views.ViewStates.Invisible; if (dat == "South America") { maps.BaseMapIndex = 1; layer.ShapeSettings.SelectedShapeColor = Color.ParseColor("#9C3367"); } else if (dat == "North America") { maps.BaseMapIndex = 2; layer.ShapeSettings.SelectedShapeColor = Color.ParseColor("#C13664"); } else if (dat == "Europe") { maps.BaseMapIndex = 3; layer.ShapeSettings.SelectedShapeColor = Color.ParseColor("#622D6C"); } else if (dat == "Africa") { maps.BaseMapIndex = 4; layer.ShapeSettings.SelectedShapeColor = Color.ParseColor("#80306A"); } else if (dat == "Australia") { maps.BaseMapIndex = 5; layer.ShapeSettings.SelectedShapeColor = Color.ParseColor("#2A2870"); } else if (dat == "Asia") { maps.BaseMapIndex = 6; layer.ShapeSettings.SelectedShapeColor = Color.ParseColor("#462A6D"); } } }; SetColorMapping(layer.ShapeSettings); CustomMarker mapMarker = new CustomMarker(context); mapMarker.Label = "Asia"; mapMarker.Latitude = 63.34303378997662; mapMarker.Longitude = 102.07617561287645; layer.Markers.Add(mapMarker); CustomMarker mapMarker1 = new CustomMarker(context); mapMarker1.Label = "Australia"; mapMarker1.Latitude = -25.74775493367931; mapMarker1.Longitude = 136.80451417932431; layer.Markers.Add(mapMarker1); CustomMarker mapMarker2 = new CustomMarker(context); mapMarker2.Label = "Africa"; mapMarker2.Latitude = 19.025302093442327; mapMarker2.Longitude = 15.157534554671087; layer.Markers.Add(mapMarker2); CustomMarker mapMarker3 = new CustomMarker(context); mapMarker3.Label = "North America"; mapMarker3.Latitude = 59.88893689676585; mapMarker3.Longitude = -109.3359375; layer.Markers.Add(mapMarker3); CustomMarker mapMarker4 = new CustomMarker(context); mapMarker4.Label = "Europe"; mapMarker4.Latitude = 47.95121990866204; mapMarker4.Longitude = 18.468749999999998; layer.Markers.Add(mapMarker4); CustomMarker mapMarker5 = new CustomMarker(context); mapMarker5.Label = "South America"; mapMarker5.Latitude = -6.64607562172573; mapMarker5.Longitude = -55.54687499999999; layer.Markers.Add(mapMarker5); maps.Layers.Add(layer); ShapeFileLayer layer1 = new ShapeFileLayer(); layer1.ShapeIdPath = "country"; layer1.ShapeIdTableField = "admin"; layer1.Uri = "south-america.shp"; layer1.ShapeSettings.ShapeFill = Color.ParseColor("#9C3367"); maps.Layers.Add(layer1); ShapeFileLayer layer2 = new ShapeFileLayer(); layer2.ShapeIdPath = "country"; layer2.ShapeIdTableField = "admin"; layer2.Uri = "north-america.shp"; layer2.ShapeSettings.ShapeFill = Color.ParseColor("#C13664"); maps.Layers.Add(layer2); ShapeFileLayer layer3 = new ShapeFileLayer(); layer3.ShapeIdPath = "country"; layer3.ShapeIdTableField = "admin"; layer3.Uri = "europe.shp"; layer3.ShapeSettings.ShapeFill = Color.ParseColor("#622D6C"); maps.Layers.Add(layer3); ShapeFileLayer layer4 = new ShapeFileLayer(); layer4.ShapeIdPath = "country"; layer4.ShapeIdTableField = "admin"; layer4.Uri = "africa.shp"; layer4.ShapeSettings.ShapeFill = Color.ParseColor("#80306A"); maps.Layers.Add(layer4); ShapeFileLayer layer5 = new ShapeFileLayer(); layer5.ShapeIdPath = "country"; layer5.ShapeIdTableField = "admin"; layer5.Uri = "australia.shp"; layer5.ShapeSettings.ShapeFill = Color.ParseColor("#2A2870"); maps.Layers.Add(layer5); ShapeFileLayer layer6 = new ShapeFileLayer(); layer6.ShapeIdPath = "country"; layer6.ShapeIdTableField = "admin"; layer6.Uri = "asia.shp"; layer6.ShapeSettings.ShapeFill = Color.ParseColor("#462A6D"); maps.Layers.Add(layer6); SfBusyIndicator sfBusyIndicator = new SfBusyIndicator(context); sfBusyIndicator.IsBusy = true; sfBusyIndicator.AnimationType = AnimationTypes.SlicedCircle; sfBusyIndicator.ViewBoxWidth = 50; sfBusyIndicator.ViewBoxHeight = 50; sfBusyIndicator.TextColor = Color.ParseColor("#779772"); layout.AddView(sfBusyIndicator); Java.Lang.Runnable run = new Java.Lang.Runnable(() => { layout.RemoveView(sfBusyIndicator); layout.AddView(linearLayout); layout.AddView(linearLayout1); layout.AddView(maps); }); handler.PostDelayed(run, 100); return layout; } private void Text_Click(object sender, EventArgs e) { maps.BaseMapIndex = 0; linearLayout.Visibility = Android.Views.ViewStates.Invisible; linearLayout1.Visibility = Android.Views.ViewStates.Visible; } JSONArray GetDataSource() { JSONArray array = new JSONArray(); array.Put(getJsonObject("Afghanistan", "Asia")); array.Put(getJsonObject("Angola", "Africa")); array.Put(getJsonObject("Albania", "Europe")); array.Put(getJsonObject("United Arab Emirates", "Asia")); array.Put(getJsonObject("Argentina", "South America")); array.Put(getJsonObject("Armenia", "Asia")); array.Put(getJsonObject("French Southern and Antarctic Lands", "Seven seas (open ocean)")); array.Put(getJsonObject("Australia", "Australia")); array.Put(getJsonObject("Austria", "Europe")); array.Put(getJsonObject("Azerbaijan", "Asia")); array.Put(getJsonObject("Burundi", "Africa")); array.Put(getJsonObject("Belgium", "Europe")); array.Put(getJsonObject("Benin", "Africa")); array.Put(getJsonObject("Burkina Faso", "Africa")); array.Put(getJsonObject("Bangladesh", "Asia")); array.Put(getJsonObject("Bulgaria", "Europe")); array.Put(getJsonObject("The Bahamas", "North America")); array.Put(getJsonObject("Bosnia and Herzegovina", "Europe")); array.Put(getJsonObject("Belarus", "Europe")); array.Put(getJsonObject("Belize", "North America")); array.Put(getJsonObject("Bolivia", "South America")); array.Put(getJsonObject("Brazil", "South America")); array.Put(getJsonObject("Brunei", "Asia")); array.Put(getJsonObject("Bhutan", "Asia")); array.Put(getJsonObject("Botswana", "Africa")); array.Put(getJsonObject("Central African Republic", "Africa")); array.Put(getJsonObject("Canada", "North America")); array.Put(getJsonObject("Switzerland", "Europe")); array.Put(getJsonObject("Chile", "South America")); array.Put(getJsonObject("China", "Asia")); array.Put(getJsonObject("Ivory Coast", "Africa")); array.Put(getJsonObject("Cameroon", "Africa")); array.Put(getJsonObject("Democratic Republic of the Congo", "Africa")); array.Put(getJsonObject("Republic of Congo", "Africa")); array.Put(getJsonObject("Colombia", "South America")); array.Put(getJsonObject("Costa Rica", "North America")); array.Put(getJsonObject("Cuba", "North America")); array.Put(getJsonObject("Northern Cyprus", "Asia")); array.Put(getJsonObject("Cyprus", "Asia")); array.Put(getJsonObject("Czech Republic", "Europe")); array.Put(getJsonObject("Germany", "Europe")); array.Put(getJsonObject("Djibouti", "Africa")); array.Put(getJsonObject("Denmark", "Europe")); array.Put(getJsonObject("Dominican Republic", "North America")); array.Put(getJsonObject("Algeria", "Africa")); array.Put(getJsonObject("Ecuador", "South America")); array.Put(getJsonObject("Egypt", "Africa")); array.Put(getJsonObject("Eritrea", "Africa")); array.Put(getJsonObject("Spain", "Europe")); array.Put(getJsonObject("Estonia", "Europe")); array.Put(getJsonObject("Ethiopia", "Africa")); array.Put(getJsonObject("Finland", "Europe")); array.Put(getJsonObject("Fiji", "Australia")); array.Put(getJsonObject("Falkland Islands", "South America")); array.Put(getJsonObject("France", "Europe")); array.Put(getJsonObject("Gabon", "Africa")); array.Put(getJsonObject("United Kingdom", "Europe")); array.Put(getJsonObject("Georgia", "Asia")); array.Put(getJsonObject("Ghana", "Africa")); array.Put(getJsonObject("Guinea", "Africa")); array.Put(getJsonObject("Gambia", "Africa")); array.Put(getJsonObject("Guinea Bissau", "Africa")); array.Put(getJsonObject("Equatorial Guinea", "Africa")); array.Put(getJsonObject("Greece", "Europe")); array.Put(getJsonObject("Greenland", "North America")); array.Put(getJsonObject("Guatemala", "North America")); array.Put(getJsonObject("Guyana", "South America")); array.Put(getJsonObject("Honduras", "North America")); array.Put(getJsonObject("Croatia", "Europe")); array.Put(getJsonObject("Haiti", "North America")); array.Put(getJsonObject("Hungary", "Europe")); array.Put(getJsonObject("Indonesia", "Asia")); array.Put(getJsonObject("India", "Asia")); array.Put(getJsonObject("Ireland", "Europe")); array.Put(getJsonObject("Iran", "Asia")); array.Put(getJsonObject("Iraq", "Asia")); array.Put(getJsonObject("Iceland", "Europe")); array.Put(getJsonObject("Israel", "Asia")); array.Put(getJsonObject("Italy", "Europe")); array.Put(getJsonObject("Jamaica", "North America")); array.Put(getJsonObject("Jordan", "Asia")); array.Put(getJsonObject("Japan", "Asia")); array.Put(getJsonObject("Kazakhstan", "Asia")); array.Put(getJsonObject("Kenya", "Africa")); array.Put(getJsonObject("Kyrgyzstan", "Asia")); array.Put(getJsonObject("Cambodia", "Asia")); array.Put(getJsonObject("South Korea", "Asia")); array.Put(getJsonObject("Kosovo", "Europe")); array.Put(getJsonObject("Kuwait", "Asia")); array.Put(getJsonObject("Laos", "Asia")); array.Put(getJsonObject("Lebanon", "Asia")); array.Put(getJsonObject("Liberia", "Africa")); array.Put(getJsonObject("Libya", "Africa")); array.Put(getJsonObject("Sri Lanka", "Asia")); array.Put(getJsonObject("Lesotho", "Africa")); array.Put(getJsonObject("Lithuania", "Europe")); array.Put(getJsonObject("Luxembourg", "Europe")); array.Put(getJsonObject("Latvia", "Europe")); array.Put(getJsonObject("Morocco", "Africa")); array.Put(getJsonObject("Moldova", "Europe")); array.Put(getJsonObject("Madagascar", "Africa")); array.Put(getJsonObject("Mexico", "North America")); array.Put(getJsonObject("Macedonia", "Europe")); array.Put(getJsonObject("Mali", "Africa")); array.Put(getJsonObject("Myanmar", "Asia")); array.Put(getJsonObject("Montenegro", "Europe")); array.Put(getJsonObject("Mongolia", "Asia")); array.Put(getJsonObject("Mozambique", "Africa")); array.Put(getJsonObject("Mauritania", "Africa")); array.Put(getJsonObject("Malawi", "Africa")); array.Put(getJsonObject("Malaysia", "Asia")); array.Put(getJsonObject("Namibia", "Africa")); array.Put(getJsonObject("New Caledonia", "Australia")); array.Put(getJsonObject("Niger", "Africa")); array.Put(getJsonObject("Nigeria", "Africa")); array.Put(getJsonObject("Nicaragua", "North America")); array.Put(getJsonObject("Netherlands", "Europe")); array.Put(getJsonObject("Norway", "Europe")); array.Put(getJsonObject("Nepal", "Asia")); array.Put(getJsonObject("New Zealand", "Australia")); array.Put(getJsonObject("Oman", "Asia")); array.Put(getJsonObject("Pakistan", "Asia")); array.Put(getJsonObject("Panama", "North America")); array.Put(getJsonObject("Peru", "South America")); array.Put(getJsonObject("Philippines", "Asia")); array.Put(getJsonObject("Papua New Guinea", "Australia")); array.Put(getJsonObject("Poland", "Europe")); array.Put(getJsonObject("Puerto Rico", "North America")); array.Put(getJsonObject("North Korea", "Asia")); array.Put(getJsonObject("Portugal", "Europe")); array.Put(getJsonObject("Paraguay", "South America")); array.Put(getJsonObject("Palestine", "Asia")); array.Put(getJsonObject("Qatar", "Asia")); array.Put(getJsonObject("Romania", "Europe")); array.Put(getJsonObject("Russia", "Asia")); array.Put(getJsonObject("Rwanda", "Africa")); array.Put(getJsonObject("Western Sahara", "Africa")); array.Put(getJsonObject("Saudi Arabia", "Asia")); array.Put(getJsonObject("Sudan", "Africa")); array.Put(getJsonObject("South Sudan", "Africa")); array.Put(getJsonObject("Senegal", "Africa")); array.Put(getJsonObject("Solomon Islands", "Australia")); array.Put(getJsonObject("Sierra Leone", "Africa")); array.Put(getJsonObject("El Salvador", "North America")); array.Put(getJsonObject("Somaliland", "Africa")); array.Put(getJsonObject("Somalia", "Africa")); array.Put(getJsonObject("Republic of Serbia", "Europe")); array.Put(getJsonObject("Suriname", "South America")); array.Put(getJsonObject("Slovakia", "Europe")); array.Put(getJsonObject("Slovenia", "Europe")); array.Put(getJsonObject("Sweden", "Europe")); array.Put(getJsonObject("Swaziland", "Africa")); array.Put(getJsonObject("Syria", "Asia")); array.Put(getJsonObject("Chad", "Africa")); array.Put(getJsonObject("Togo", "Africa")); array.Put(getJsonObject("Thailand", "Asia")); array.Put(getJsonObject("Tajikistan", "Asia")); array.Put(getJsonObject("Turkmenistan", "Asia")); array.Put(getJsonObject("East Timor", "Asia")); array.Put(getJsonObject("Trinidad and Tobago", "North America")); array.Put(getJsonObject("Tunisia", "Africa")); array.Put(getJsonObject("Turkey", "Asia")); array.Put(getJsonObject("Taiwan", "Asia")); array.Put(getJsonObject("United Republic of Tanzania", "Africa")); array.Put(getJsonObject("Uganda", "Africa")); array.Put(getJsonObject("Ukraine", "Europe")); array.Put(getJsonObject("Uruguay", "South America")); array.Put(getJsonObject("United States of America", "North America")); array.Put(getJsonObject("Uzbekistan", "Asia")); array.Put(getJsonObject("Venezuela", "South America")); array.Put(getJsonObject("Vietnam", "Asia")); array.Put(getJsonObject("Vanuatu", "Australia")); array.Put(getJsonObject("Yemen", "Asia")); array.Put(getJsonObject("South Africa", "Africa")); array.Put(getJsonObject("Zambia", "Africa")); array.Put(getJsonObject("Zimbabwe", "Africa")); return array; } JSONObject getJsonObject(String name, String type) { JSONObject obj = new JSONObject(); obj.Put("country", name); obj.Put("continent", type); return obj; } void SetColorMapping(ShapeSetting setting) { List<ColorMapping> colorMappings = new List<ColorMapping>(); EqualColorMapping colorMapping2 = new EqualColorMapping(); colorMapping2.Value = "North America"; colorMapping2.Color = Color.ParseColor("#C13664"); colorMappings.Add(colorMapping2); EqualColorMapping colorMapping3 = new EqualColorMapping(); colorMapping3.Value = "South America"; colorMapping3.Color = Color.ParseColor("#9C3367"); colorMappings.Add(colorMapping3); EqualColorMapping colorMapping4 = new EqualColorMapping(); colorMapping4.Value = "Africa"; colorMapping4.Color = Color.ParseColor("#80306A"); colorMappings.Add(colorMapping4); EqualColorMapping colorMapping1 = new EqualColorMapping(); colorMapping1.Value = "Europe"; colorMapping1.Color = Color.ParseColor("#622D6C"); colorMappings.Add(colorMapping1); EqualColorMapping colorMapping5 = new EqualColorMapping(); colorMapping5.Value = "Asia"; colorMapping5.Color = Color.ParseColor("#462A6D"); colorMappings.Add(colorMapping5); EqualColorMapping colorMapping6 = new EqualColorMapping(); colorMapping6.Value = "Australia"; colorMapping6.Color = Color.ParseColor("#2A2870"); colorMappings.Add(colorMapping6); setting.ColorMapping = colorMappings; } } public class CustomMarker : MapMarker { Android.Content.Context context; public CustomMarker(Android.Content.Context con) { context = con; } public override void DrawMarker(PointF p0, Canvas p1) { float density = context.Resources.DisplayMetrics.Density / 1.5f; Paint paint = new Paint(); paint.Color = Color.ParseColor("#bee8a2"); paint.TextSize = 15 * density; var labels = Label.Split(' ', '\t'); for (int i = 0; i < labels.Length; i++) { p1.DrawText(labels[i], (float)p0.X - (paint.TextSize * density), (float)p0.Y + density, paint); p0.Y += paint.TextSize; } } } }<file_sep>/Forms/ListView/ListView/Samples/SortingFiltering/Helper/Behaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DataSource; using Syncfusion.ListView.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.Core; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] #region SortingFilteringBehavior public class SfListViewSortingFilteringBehavior:Behavior<SampleView> { #region Fields private Syncfusion.ListView.XForms.SfListView ListView; private SortingFilteringViewModel sortingFilteringViewModel; private Grid sortImageParent; private SearchBar searchBar = null; private Grid headerGrid; private Grid seachbar_Grid; #endregion #region Overrides protected override void OnAttachedTo(SampleView bindable) { ListView = bindable.FindByName<Syncfusion.ListView.XForms.SfListView>("listView"); sortingFilteringViewModel = new SortingFilteringViewModel(); ListView.BindingContext = sortingFilteringViewModel; ListView.ItemsSource = sortingFilteringViewModel.Items; headerGrid = bindable.FindByName<Grid>("headerGrid"); headerGrid.BindingContext = sortingFilteringViewModel; seachbar_Grid = bindable.FindByName<Grid>("seachbar_Grid"); if (Device.RuntimePlatform == Device.UWP) seachbar_Grid.Padding = new Thickness(5, 5, 0, 5); sortImageParent = bindable.FindByName<Grid>("sortImageParent"); var SortImageTapped = new TapGestureRecognizer() { Command = new Command(SortImageTapped_Tapped) }; sortImageParent.GestureRecognizers.Add(SortImageTapped); if (Device.RuntimePlatform == Device.iOS) sortImageParent.BackgroundColor = Color.FromHex("#C9C8CE"); else if(Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.UWP) sortImageParent.BackgroundColor = Color.FromHex("#E4E4E4"); searchBar = bindable.FindByName<SearchBar>("filterText"); if (Device.RuntimePlatform == Device.macOS) searchBar.PlaceholderColor = Color.Transparent; searchBar.WidthRequest = Core.SampleBrowser.ScreenWidth - sortImageParent.Width; searchBar.TextChanged += SearchBar_TextChanged; base.OnAttachedTo(bindable); } protected override void OnDetachingFrom(SampleView bindable) { ListView = null; sortImageParent = null; searchBar = null; searchBar.TextChanged -= SearchBar_TextChanged; base.OnDetachingFrom(bindable); } #endregion #region Events private void SearchBar_TextChanged(object sender, TextChangedEventArgs e) { searchBar = (sender as SearchBar); if (ListView.DataSource != null) { ListView.DataSource.Filter = FilterContacts; ListView.DataSource.RefreshFilter(); } ListView.RefreshView(); } private void SortImageTapped_Tapped() { if (sortingFilteringViewModel.SortingOptions == ListViewSortOptions.Descending) sortingFilteringViewModel.SortingOptions = ListViewSortOptions.None; else if (sortingFilteringViewModel.SortingOptions == ListViewSortOptions.None) sortingFilteringViewModel.SortingOptions = ListViewSortOptions.Ascending; else if (sortingFilteringViewModel.SortingOptions == ListViewSortOptions.Ascending) sortingFilteringViewModel.SortingOptions = ListViewSortOptions.Descending; ListView.DataSource.SortDescriptors.Clear(); if (sortingFilteringViewModel.SortingOptions != ListViewSortOptions.None) { ListView.DataSource.SortDescriptors.Add(new SortDescriptor() { PropertyName = "Title", Direction = sortingFilteringViewModel.SortingOptions == ListViewSortOptions.Ascending ? ListSortDirection.Ascending : ListSortDirection.Descending }); } ListView.RefreshView(); } #endregion #region Methods private bool FilterContacts(object obj) { if (searchBar == null || searchBar.Text == null) return true; var taskInfo = obj as TaskInfo; return (taskInfo.Title.ToLower().Contains(searchBar.Text.ToLower()) || taskInfo.Description.ToLower().Contains(searchBar.Text.ToLower())); } #endregion } #endregion } <file_sep>/Forms/ListView/ListView/Samples/Selection/Model/MusiqInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class Musiqnfo : INotifyPropertyChanged { #region Fields private string songTitle; private string songAuther; private string songSize; private bool isSelected; #endregion #region Properties /// <summary> /// Gets or sets a value that indicates song title. /// </summary> public string SongTitle { get { return songTitle; } set { songTitle = value; this.RaisePropertyChanged("SongTitle"); } } /// <summary> /// Gets or sets the value that indicates the song auther. /// </summary> public string SongAuther { get { return songAuther; } set { songAuther = value; this.RaisePropertyChanged("SongAuther"); } } /// <summary> /// Gets or sets a value that indicates song size. /// </summary> public string SongSize { get { return songSize; } set { songSize = value; this.RaisePropertyChanged("SongSize"); } } public bool IsSelected { get { return isSelected; } set { isSelected = value; RaisePropertyChanged("IsSelected"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Forms/AutoComplete/AutoComplete/Samples/Delimiter/DelimiterSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public partial class DelimiterSample : SampleView { List<string> countryList; public DelimiterSample() { InitializeComponent(); AddListItems(); autocomplete.DataSource = countryList; InitializeDelimiterpicker(); InitializeBackgroundPicker(); InitializeBorderPicker(); } public Color GetColor(int index) { Color selectedColor = Color.Black; switch (index) { case 0: { selectedColor = Color.Violet; } break; case 1: { selectedColor = Color.Indigo; } break; case 2: { selectedColor = Color.Blue; } break; case 3: { selectedColor = Color.Green; } break; case 4: { selectedColor = Color.Yellow; } break; case 5: { selectedColor = Color.Orange; } break; case 6: { selectedColor = Color.Red; } break; } return selectedColor; } public void InitializeBorderPicker() { Borderpicker.Items.Add("Violet"); Borderpicker.Items.Add("Indigo"); Borderpicker.Items.Add("Blue"); Borderpicker.Items.Add("Green"); Borderpicker.Items.Add("Yellow"); Borderpicker.Items.Add("Orange"); Borderpicker.Items.Add("Red"); Borderpicker.SelectedIndex = 0; Borderpicker.SelectedIndexChanged += (object sender, EventArgs e) => { var selectedValue = GetColor(Borderpicker.SelectedIndex); this.autocomplete.TextColor = selectedValue; this.autocomplete.DropDownTextColor = selectedValue; this.autocomplete.BorderColor = selectedValue; this.autocomplete.ClearButtonColor = selectedValue; Footerlabel.TextColor = Headerlabel.TextColor = selectedValue; }; } public void InitializeBackgroundPicker() { BackgroundColorPicker.Items.Add("Violet"); BackgroundColorPicker.Items.Add("Indigo"); BackgroundColorPicker.Items.Add("Blue"); BackgroundColorPicker.Items.Add("Green"); BackgroundColorPicker.Items.Add("Yellow"); BackgroundColorPicker.Items.Add("Orange"); BackgroundColorPicker.Items.Add("Red"); BackgroundColorPicker.SelectedIndex = 0; BackgroundColorPicker.SelectedIndexChanged += (object sender, EventArgs e) => { var selectedValue = GetColor(BackgroundColorPicker.SelectedIndex); this.autocomplete.DropDownBackgroundColor = selectedValue; this.autocomplete.BackgroundColor = selectedValue; }; } public void InitializeDelimiterpicker() { delimiterpicker.Items.Add(","); delimiterpicker.Items.Add("#"); delimiterpicker.Items.Add("*"); delimiterpicker.SelectedIndex = 0; delimiterpicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (delimiterpicker.SelectedIndex) { case 0: { autocomplete.Delimiter = ","; } break; case 1: { autocomplete.Delimiter = "#"; } break; case 2: { autocomplete.Delimiter = "*"; } break; } }; } void Handle_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e) { //if (autocomplete != null) // autocomplete.IsClearButtonVisible = e.Value; } void Handle_ValueChanged(object sender, Xamarin.Forms.ValueChangedEventArgs e) { var item = (sender as Slider).AutomationId.ToString(); if (item == "Height") { var heightValue = (int)(e.NewValue + 20) * 2; this.autocomplete.DropDownHeaderViewHeight = this.autocomplete.DropDownFooterViewHeight = autocomplete.HeightRequest = autocomplete.DropDownItemHeight = heightValue + 10; Headerlabel.FontSize = Footerlabel.FontSize = autocomplete.TextSize = autocomplete.DropDownTextSize = heightValue / 2; } else if (item == "CornerRadius") autocomplete.DropDownCornerRadius = e.NewValue; else if (item == "ItemsHeight") autocomplete.DropDownCornerRadius = e.NewValue * 2; } private double cornerRadius = 0; public double CornerRadius { get { return cornerRadius; } set { cornerRadius = value; RaisePropertyChanged("CornerRadius"); } } #region INotifyPropertyChanged implementation public new event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion void AddListItems() { countryList = new List<string>(); countryList.Add("Afghanistan"); countryList.Add("Akrotiri"); countryList.Add("Albania"); countryList.Add("Algeria"); countryList.Add("American Samoa"); countryList.Add("Andorra"); countryList.Add("Angola"); countryList.Add("Anguilla"); countryList.Add("Antarctica"); countryList.Add("Antigua and Barbuda"); countryList.Add("Argentina"); countryList.Add("Armenia"); countryList.Add("Aruba"); countryList.Add("Ashmore and Cartier Islands"); countryList.Add("Australia"); countryList.Add("Austria"); countryList.Add("Azerbaijan"); countryList.Add("Bahamas, The"); countryList.Add("Bahrain"); countryList.Add("Bangladesh"); countryList.Add("Barbados"); countryList.Add("Bassas da India"); countryList.Add("Belarus"); countryList.Add("Belgium"); countryList.Add("Belize"); countryList.Add("Benin"); countryList.Add("Bermuda"); countryList.Add("Bhutan"); countryList.Add("Bolivia"); countryList.Add("Bosnia and Herzegovina"); countryList.Add("Botswana"); countryList.Add("Bouvet Island"); countryList.Add("Brazil"); countryList.Add("British Indian Ocean Territory"); countryList.Add("British Virgin Islands"); countryList.Add("Brunei"); countryList.Add("Bulgaria"); countryList.Add("Burkina Faso"); countryList.Add("Burma"); countryList.Add("Burundi"); countryList.Add("Cambodia"); countryList.Add("Cameroon"); countryList.Add("Canada"); countryList.Add("Cape Verde"); countryList.Add("Cayman Islands"); countryList.Add("Central African Republic"); countryList.Add("Chad"); countryList.Add("Chile"); countryList.Add("China"); countryList.Add("Christmas Island"); countryList.Add("Clipperton Island"); countryList.Add("Cocos (Keeling) Islands"); countryList.Add("Colombia"); countryList.Add("Comoros"); countryList.Add("Congo"); countryList.Add("Congo, Republic of the"); countryList.Add("Cook Islands"); countryList.Add("Coral Sea Islands"); countryList.Add("Costa Rica"); countryList.Add("Cote d'Ivoire"); countryList.Add("Croatia"); countryList.Add("Cuba"); countryList.Add("Cyprus"); countryList.Add("Czech Republic"); countryList.Add("Denmark"); countryList.Add("Dhekelia"); countryList.Add("Djibouti"); countryList.Add("Dominica"); countryList.Add("Dominican Republic"); countryList.Add("Ecuador"); countryList.Add("Egypt"); countryList.Add("El Salvador"); countryList.Add("Equatorial Guinea"); countryList.Add("Eritrea"); countryList.Add("Estonia"); countryList.Add("Ethiopia"); countryList.Add("Europa Island"); countryList.Add("Falkland Islands"); countryList.Add("Faroe Islands"); countryList.Add("Fiji"); countryList.Add("Finland"); countryList.Add("France"); countryList.Add("French Guiana"); countryList.Add("French Polynesia"); countryList.Add("French Southern and Antarctic Lands"); countryList.Add("Gabon"); countryList.Add("The Gambia"); countryList.Add("Gaza Strip"); countryList.Add("Georgia"); countryList.Add("Germany"); countryList.Add("Ghana"); countryList.Add("Gibraltar"); countryList.Add("Glorioso Islands"); countryList.Add("Greece"); countryList.Add("Greenland"); countryList.Add("Grenada"); countryList.Add("Guadeloupe"); countryList.Add("Guam"); countryList.Add("Guatemala"); countryList.Add("Guernsey"); countryList.Add("Guinea"); countryList.Add("Guinea-Bissau"); countryList.Add("Guyana"); countryList.Add("Haiti"); countryList.Add("Heard Island and McDonald Islands"); countryList.Add("Holy See"); countryList.Add("Honduras"); countryList.Add("Hong Kong"); countryList.Add("Hungary"); countryList.Add("Iceland"); countryList.Add("India"); countryList.Add("Indonesia"); countryList.Add("Iran"); countryList.Add("Iraq"); countryList.Add("Ireland"); countryList.Add("Isle of Man"); countryList.Add("Israel"); countryList.Add("Italy"); countryList.Add("Jamaica"); countryList.Add("Jan Mayen"); countryList.Add("Japan"); countryList.Add("Jersey"); countryList.Add("Jordan"); countryList.Add("Juan de Nova Island"); countryList.Add("Kazakhstan"); countryList.Add("Kenya"); countryList.Add("Kiribati"); countryList.Add("Korea, North"); countryList.Add("Korea, South"); countryList.Add("Kuwait"); countryList.Add("Kyrgyzstan"); countryList.Add("Laos"); countryList.Add("Latvia"); countryList.Add("Lebanon"); countryList.Add("Lesotho"); countryList.Add("Liberia"); countryList.Add("Libya"); countryList.Add("Liechtenstein"); countryList.Add("Lithuania"); countryList.Add("Luxembourg"); countryList.Add("Macau"); countryList.Add("Macedonia"); countryList.Add("Madagascar"); countryList.Add("Malawi"); countryList.Add("Malaysia"); countryList.Add("Maldives"); countryList.Add("Mali"); countryList.Add("Malta"); countryList.Add("Marshall Islands"); countryList.Add("Martinique"); countryList.Add("Mauritania"); countryList.Add("Mauritius"); countryList.Add("Mayotte"); countryList.Add("Mexico"); countryList.Add("Micronesia"); countryList.Add("Moldova"); countryList.Add("Monaco"); countryList.Add("Mongolia"); countryList.Add("Montserrat"); countryList.Add("Morocco"); countryList.Add("Mozambique"); countryList.Add("Namibia"); countryList.Add("Nauru"); countryList.Add("Navassa Island"); countryList.Add("Nepal"); countryList.Add("Netherlands"); countryList.Add("Netherlands Antilles"); countryList.Add("New Caledonia"); countryList.Add("New Zealand"); countryList.Add("Nicaragua"); countryList.Add("Niger"); countryList.Add("Nigeria"); countryList.Add("Niue"); countryList.Add("Norfolk Island"); countryList.Add("Northern Mariana Islands"); countryList.Add("Norway"); countryList.Add("Oman"); countryList.Add("Pakistan"); countryList.Add("Palau"); countryList.Add("Panama"); countryList.Add("Papua New Guinea"); countryList.Add("Paracel Islands"); countryList.Add("Paraguay"); countryList.Add("Peru"); countryList.Add("Philippines"); countryList.Add("Pitcairn Islands"); countryList.Add("Poland"); countryList.Add("Portugal"); countryList.Add("Puerto Rico"); countryList.Add("Qatar"); countryList.Add("Reunion"); countryList.Add("Romania"); countryList.Add("Russia"); countryList.Add("Rwanda"); countryList.Add("Saint Helena"); countryList.Add("Saint Kitts and Nevis"); countryList.Add("Saint Lucia"); countryList.Add("Saint Pierre and Miquelon"); countryList.Add("Saint Vincent"); countryList.Add("Samoa"); countryList.Add("San Marino"); countryList.Add("Sao Tome and Principe"); countryList.Add("Saudi Arabia"); countryList.Add("Senegal"); countryList.Add("Serbia and Montenegro"); countryList.Add("Seychelles"); countryList.Add("Sierra Leone"); countryList.Add("Singapore"); countryList.Add("Slovakia"); countryList.Add("Slovenia"); countryList.Add("Solomon Islands"); countryList.Add("Somalia"); countryList.Add("South Africa"); countryList.Add("South Georgia"); countryList.Add("Spain"); countryList.Add("Spratly Islands"); countryList.Add("Sri Lanka"); countryList.Add("Sudan"); countryList.Add("Suriname"); countryList.Add("Svalbard"); countryList.Add("Swaziland"); countryList.Add("Sweden"); countryList.Add("Switzerland"); countryList.Add("Syria"); countryList.Add("Taiwan"); countryList.Add("Tajikistan"); countryList.Add("Tanzania"); countryList.Add("Thailand"); countryList.Add("Timor-Leste"); countryList.Add("Togo"); countryList.Add("Tokelau"); countryList.Add("Tonga"); countryList.Add("Trinidad and Tobago"); countryList.Add("Tromelin Island"); countryList.Add("Tunisia"); countryList.Add("Turkey"); countryList.Add("Turkmenistan"); countryList.Add("Turks and Caicos Islands"); countryList.Add("Tuvalu"); countryList.Add("Uganda"); countryList.Add("Ukraine"); countryList.Add("United Arab Emirates"); countryList.Add("United Kingdom"); countryList.Add("United States"); countryList.Add("Uruguay"); countryList.Add("Uzbekistan"); countryList.Add("Vanuatu"); countryList.Add("Venezuela"); countryList.Add("Vietnam"); countryList.Add("Virgin Islands"); countryList.Add("Wake Island"); countryList.Add("Wallis and Futuna"); countryList.Add("West Bank"); countryList.Add("Western Sahara"); countryList.Add("Yemen"); countryList.Add("Zambia"); countryList.Add("Zimbabwe"); } } } <file_sep>/Forms/CircularGauge/CircularGauge/Samples/PointerDragging/PointerDragging.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfGauge.XForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfCircularGauge { [Preserve(AllMembers = true)] public partial class PointerDragging : SampleView { public PointerDragging() { InitializeComponent(); header.Text = "08"+ " h" + " 00" + " min"; } private void Pointer2_ValueChanging(object sender, Syncfusion.SfGauge.XForms.PointerValueChangingEventArgs e) { var context = (sender as MarkerPointer).BindingContext as PointerViewModel; if (e.NewValue <= context.FirstMarkerValue || Math.Abs(e.NewValue - context.SecondMarkerValue) > (1 + pointer2.StepFrequency)) { e.Cancel = true; } } private void Pointer1_ValueChanging(object sender, Syncfusion.SfGauge.XForms.PointerValueChangingEventArgs e) { var context = (sender as MarkerPointer).BindingContext as PointerViewModel; if (e.NewValue >= context.SecondMarkerValue || Math.Abs(e.NewValue - context.FirstMarkerValue) > (1 + pointer1.StepFrequency)) { e.Cancel = true; } } private void Pointer1_ValueChanged(object sender, Syncfusion.SfGauge.XForms.PointerValueChangedEventArgs e) { var context = (sender as Syncfusion.SfGauge.XForms.MarkerPointer).BindingContext as PointerViewModel; context.FirstMarkerValue = e.Value; double value = Math.Abs(context.FirstMarkerValue - context.SecondMarkerValue); CalculateTimeDifference(value); } private void Pointer2_ValueChanged(object sender, Syncfusion.SfGauge.XForms.PointerValueChangedEventArgs e) { var context = (sender as Syncfusion.SfGauge.XForms.MarkerPointer).BindingContext as PointerViewModel; context.SecondMarkerValue = e.Value; double value = Math.Abs(context.SecondMarkerValue - pointer1.Value); CalculateTimeDifference(value); } private void CalculateTimeDifference(double value) { int hour = Convert.ToInt32(Math.Floor(value)); float digit = hour / 10f; bool isHourSingleDigit = digit >= 1 ? false : true; var min = Math.Floor((value - hour) * 60); digit = (float)min / 10f; bool isMinuteSingleDigit = digit >= 1 ? false : true; string hourValue = isHourSingleDigit ? "0" + hour.ToString() : hour.ToString(); string minutesValue = isMinuteSingleDigit ? "0" + min.ToString() : min.ToString(); header.Text = hourValue + " h " + minutesValue + " min"; } private void gauge_SizeChanged(object sender, EventArgs e) { var gauge = (sender as Syncfusion.SfGauge.XForms.SfCircularGauge); var viewModel = gauge.BindingContext as PointerViewModel; var minSize = Math.Min(gauge.Bounds.Width, gauge.Bounds.Height); var radius = minSize / 2; var scale = gauge.Scales[0]; viewModel.PointerSize = radius * Math.Abs (scale.ScaleEndOffset - scale.ScaleStartOffset); } private void frequency_slider_ValueChanged(object sender, Xamarin.Forms.ValueChangedEventArgs e) { double stepValue = 0.2; var newStep = Math.Round(e.NewValue / stepValue); (sender as Slider).Value = newStep * stepValue; } } }<file_sep>/Forms/DatePicker/DatePicker/Samples/DatePickerCustomization/DatePickerCustomization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfDatePicker { /// <summary> /// Date Picker Customization class /// </summary> public partial class DatePickerCustomization : SampleView { /// <summary> /// DatePickerCustomization /// </summary> public DatePickerCustomization() { InitializeComponent(); if (Device.RuntimePlatform == Device.iOS) { CustomizePicker.BackgroundColor = Color.FromHex("#FAFAFA"); CustomizePicker.ColumnHeaderBackgroundColor = Color.FromHex("#FAFAFA"); CustomizePicker.HeaderBackgroundColor = Color.FromHex("#FAFAFA"); } if (Device.RuntimePlatform == Device.UWP) { layoutRoot.HorizontalOptions = LayoutOptions.Center; layoutRootGrid.WidthRequest = 500; } } } }<file_sep>/iOS/SampleBrowser/Controllers/ChartSamplesViewController.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Foundation; using CoreGraphics; using System.Linq; namespace SampleBrowser { public class ChartSamplesViewController : UIViewController { #region fields private bool codeVisible, firstTimeLoad = true; private UIBarButtonItem codeViewButton; private UIView customTab, selectedTabHighlightView; private float customTabHeight = 50; private string[] featureSamples, typeSamples; private UICollectionView featuresCollectionView, typesCollectionView; private UICollectionViewFlowLayout featuresLayout, typesLayout; private UILabel featuresTextLabel, typesTextLabel; private SampleView featureSampleView, typeSampleView; private CGRect featuresRect, typesRect; #endregion #region ctor public ChartSamplesViewController() { } #endregion #region properties public UIButton DeselectedButton { get; set; } public UIButton DeselectedButtonX { get; set; } public bool IsTypesSampleView { get; set; } = true; public NSString ControlName { get; set; } public NSString Features { get; set; } public string FeaturesSampleNameToLoad { get; set; } public NSMutableArray FeaturesCollections { get; set; } public NSIndexPath FeaturesIndexPath { get; set; } public NSString Types { get; set; } public string TypesSampleNameToLoad { get; set; } public NSMutableArray TypesCollections { get; set; } public NSIndexPath TypesIndexPath { get; set; } #endregion #region methods public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); codeVisible = false; this.NavigationItem.Title = ControlName; this.NavigationController.SetNavigationBarHidden(false, false); } public override void ViewDidLoad() { base.ViewDidLoad(); this.View.BackgroundColor = UIColor.White; codeViewButton = new UIBarButtonItem(); codeViewButton.Image = UIImage.FromBundle("Controls/Tags/Viewcode"); codeViewButton.Style = UIBarButtonItemStyle.Plain; codeViewButton.Target = this; codeViewButton.Clicked += ViewCode; this.NavigationItem.SetRightBarButtonItem(codeViewButton, true); TypesIndexPath = FeaturesIndexPath = NSIndexPath.FromRowSection(0, 0); this.LoadTabView(); this.PrepareSamplesList(); this.LoadSample(); this.LoadCollectionView(); if (IsTypesSampleView) { featureSampleView = new SampleView(); featuresCollectionView.Hidden = true; featureSampleView.Hidden = true; } } public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); nfloat width = this.View.Frame.Size.Width, height = this.View.Frame.Size.Height; customTab.Frame = new CGRect(0, 64, width, customTabHeight); if (IsTypesSampleView) { selectedTabHighlightView.Frame = new CGRect(0, customTabHeight - 5, width / 2, 5); } else { selectedTabHighlightView.Frame = new CGRect(this.View.Frame.Size.Width / 2, customTabHeight - 5, this.View.Frame.Size.Width / 2, 5); } typesRect = new CGRect(0, 0, width / 2, customTabHeight); featuresRect = new CGRect(width / 2, 0, width / 2, customTabHeight); typesTextLabel.Frame = typesRect; featuresTextLabel.Frame = featuresRect; typeSampleView.Frame = new CGRect(0, 66 + customTabHeight, this.View.Frame.Width, this.View.Frame.Height - 66 - 50 - customTabHeight); typesCollectionView.Frame = new CGRect(0, height - 50, width, 50); featuresCollectionView.Frame = new CGRect(0, height - 50, width, 50); featureSampleView.Frame = new CGRect(0, 66 + customTabHeight, this.View.Frame.Width, this.View.Frame.Height - 66 - 50 - customTabHeight); } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); if (TypesIndexPath != null && IsTypesSampleView) { var cell = typesCollectionView.CellForItem(TypesIndexPath); if (cell != null) { DeselectedButton = (UIButton)cell.ViewWithTag(500); DeselectedButtonX = (UIButton)cell.ViewWithTag(510); } typesCollectionView.SelectItem(TypesIndexPath, true, UICollectionViewScrollPosition.CenteredHorizontally); } } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); if (this.IsMovingFromParentViewController) { if (!codeVisible) { if (typeSampleView != null) { if (typeSampleView.OptionView != null) { typeSampleView.OptionView.RemoveFromSuperview(); typeSampleView.OptionView.Dispose(); typeSampleView.OptionView = null; } typeSampleView.RemoveFromSuperview(); typeSampleView.Dispose(); typeSampleView = null; } if (featureSampleView != null) { if (featureSampleView.OptionView != null) { featureSampleView.OptionView.RemoveFromSuperview(); featureSampleView.OptionView.Dispose(); featureSampleView.OptionView = null; } featureSampleView.RemoveFromSuperview(); featureSampleView.Dispose(); featureSampleView = null; } if (featuresCollectionView != null) { featuresCollectionView.Dispose(); featuresCollectionView = null; } if (typesCollectionView != null) { typesCollectionView.Dispose(); typesCollectionView = null; } Utility.DisposeEx(this.View); this.Dispose(); } } } public void LoadSample() { string[] samples = IsTypesSampleView ? typeSamples : featureSamples; NSIndexPath indexPath = IsTypesSampleView ? TypesIndexPath : FeaturesIndexPath; string sampleNameToLoad = samples[(nuint)indexPath.Row + 1]; SampleView sampleView = IsTypesSampleView ? typeSampleView : featureSampleView; if (sampleView != null && sampleView.IsDescendantOfView(this.View)) { sampleView.ViewWillDisappear(); foreach (UIView view in sampleView.Subviews) { view.RemoveFromSuperview(); view.Dispose(); } sampleView.RemoveFromSuperview(); sampleView.Dispose(); } ControlName = new NSString("Chart"); this.Title = "Chart"; if (sampleNameToLoad == "100% Stacked Area") { sampleNameToLoad = "StackingArea100"; } else if (sampleNameToLoad == "100% Stacked Column") { sampleNameToLoad = "StackingColumn100"; } else if (sampleNameToLoad == "100% Stacked Line") { sampleNameToLoad = "StackingLine100"; } else if (sampleNameToLoad == "100% Stacked Bar") { sampleNameToLoad = "StackingBar100"; } else if (sampleNameToLoad == "Box Plot") { sampleNameToLoad = "BoxAndWhisker"; } sampleNameToLoad = sampleNameToLoad.Replace(" ", string.Empty); string classname = "SampleBrowser." + sampleNameToLoad; Type sampleClass = Type.GetType(classname); if (sampleClass != null) { if (IsTypesSampleView) { typeSampleView = Activator.CreateInstance(sampleClass) as SampleView; typeSampleView.RemoveFromSuperview(); this.View.AddSubview(typeSampleView); typeSampleView.ViewWillAppear(); TypesSampleNameToLoad = sampleNameToLoad; } else { featureSampleView = Activator.CreateInstance(sampleClass) as SampleView; featureSampleView.RemoveFromSuperview(); this.View.AddSubview(featureSampleView); featureSampleView.ViewWillAppear(); FeaturesSampleNameToLoad = sampleNameToLoad; } } } private void LoadCollectionView() { featuresLayout = new UICollectionViewFlowLayout(); featuresLayout.ScrollDirection = UICollectionViewScrollDirection.Horizontal; featuresCollectionView = new UICollectionView(CGRect.Empty, featuresLayout); featuresCollectionView.DataSource = new FeatureSamplesDataSource(FeaturesCollections, this); featuresCollectionView.Delegate = new ChartSamplesDelegate(FeaturesCollections); featuresCollectionView.BackgroundColor = Utility.BackgroundColor; featuresCollectionView.Hidden = true; UINib featureNib = UINib.FromName("TextCell", null); featuresCollectionView.RegisterNibForCell(featureNib, "textReuseCell"); this.View.AddSubview(featuresCollectionView); typesLayout = new UICollectionViewFlowLayout(); typesLayout.ScrollDirection = UICollectionViewScrollDirection.Horizontal; typesCollectionView = new UICollectionView(CGRect.Empty, typesLayout); typesCollectionView.DataSource = new TypeSamplesDataSource(TypesCollections, this); typesCollectionView.Delegate = new ChartSamplesDelegate(TypesCollections); typesCollectionView.BackgroundColor = Utility.BackgroundColor; featuresCollectionView.Hidden = true; UINib typeNib = UINib.FromName("TextCell", null); typesCollectionView.RegisterNibForCell(typeNib, "textReuseCell"); this.View.AddSubview(typesCollectionView); } private void LoadTabView() { typeSamples = ((string)Types).Split(','); featureSamples = ((string)Features).Split(','); customTab = new UIView(); customTab.BackgroundColor = UIColor.FromRGB(0, 123.0f / 255.0f, 229.0f / 255.0f); selectedTabHighlightView = new UIView(); selectedTabHighlightView.BackgroundColor = UIColor.FromRGB(1.0f, 198.0f / 255.0f, 66.0f / 255.0f); typesTextLabel = new UILabel(); typesTextLabel.TextColor = UIColor.White; typesTextLabel.Text = typeSamples[0]; typesTextLabel.TextAlignment = UITextAlignment.Center; typesTextLabel.Font = Utility.TitleFont; featuresTextLabel = new UILabel(); featuresTextLabel.TextColor = UIColor.White; featuresTextLabel.Text = featureSamples[0]; featuresTextLabel.TextAlignment = UITextAlignment.Center; featuresTextLabel.Font = Utility.TitleFont; customTab.AddSubview(selectedTabHighlightView); customTab.AddSubview(typesTextLabel); customTab.AddSubview(featuresTextLabel); UITapGestureRecognizer singleFingerTap = new UITapGestureRecognizer(); singleFingerTap.AddTarget(() => HandleSingleTap(singleFingerTap)); customTab.AddGestureRecognizer(singleFingerTap); this.View.AddSubview(customTab); } private void PrepareSamplesList() { NSMutableArray typesCollections = new NSMutableArray(); NSMutableArray featuresCollections = new NSMutableArray(); for (nuint i = 0; i < FeaturesCollections.Count; i++) { Control control = FeaturesCollections.GetItem<Control>(i); if (typeSamples.Contains(control.Name)) { typesCollections.Add(control); } else if (featureSamples.Contains(control.Name)) { featuresCollections.Add(control); } } TypesCollections = typesCollections; FeaturesCollections = featuresCollections; } private void HandleSingleTap(UITapGestureRecognizer gesture) { CGPoint point = gesture.LocationInView(customTab); if (typesRect.Contains(point)) { featuresCollectionView.Hidden = true; typesCollectionView.Hidden = false; typeSampleView.Hidden = false; featureSampleView.Hidden = true; IsTypesSampleView = true; selectedTabHighlightView.Frame = new CGRect(0, customTabHeight - 5, this.View.Frame.Size.Width / 2, 5); typeSampleView.ViewWillAppear(); featureSampleView.ViewWillDisappear(); } else if (featuresRect.Contains(point)) { typesCollectionView.Hidden = true; featuresCollectionView.Hidden = false; typeSampleView.Hidden = true; featureSampleView.Hidden = false; IsTypesSampleView = false; selectedTabHighlightView.Frame = new CGRect(this.View.Frame.Size.Width / 2, customTabHeight - 5, this.View.Frame.Size.Width / 2, 5); if (firstTimeLoad) { LoadSample(); firstTimeLoad = false; } else { featureSampleView.ViewWillAppear(); typeSampleView.ViewWillDisappear(); } } } private void ViewCode(object sender, EventArgs args) { CodeViewController viewController = new CodeViewController(); viewController.ControlName = ControlName; viewController.SampleName = IsTypesSampleView ? TypesSampleNameToLoad : FeaturesSampleNameToLoad; codeVisible = true; this.NavigationItem.BackBarButtonItem = new UIBarButtonItem("Back", UIBarButtonItemStyle.Plain, null); this.NavigationController.PushViewController(viewController, true); } #endregion } }<file_sep>/Android/SampleBrowser/Samples/Diagram/NodeContent.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Syncfusion.SfDiagram.Android; namespace SampleBrowser { public partial class NodeAnnotation : SamplePage { SfDiagram diagram; private const float DefaultToolbarHeight = 0f; private Context m_context; public override View GetSampleContent(Context context) { m_context = context; //Initialize the SfDiagram and set its background color. diagram = new SfDiagram(context); diagram.EnableSelection = false; diagram.BackgroundColor = Color.White; //Initialize the nodes and set its properties. var node1 = DrawNode(280 * 2 * MainActivity.Factor, 140 * 2 * MainActivity.Factor, 175 * 2 * MainActivity.Factor, 70 * 2 * MainActivity.Factor, ShapeType.RoundedRectangle); node1.Style.StrokeBrush = new SolidBrush(Color.Rgb(206, 98, 9)); node1.Annotations.Add(new Annotation() { Content = FlowDiagram.CreateLabel(context, "Establish Project" + "\n" + "and Team", (int)node1.Width, Color.White), HorizontalAlignment = HorizontalAlignment.Center }); diagram.AddNode(node1); var node2 = DrawNode(280 * 2 * MainActivity.Factor, node1.OffsetY + (140 * 2 * MainActivity.Factor), 175 * 2 * MainActivity.Factor, 70 * 2 * MainActivity.Factor, ShapeType.RoundedRectangle); node2.Style.StrokeBrush = new SolidBrush(Color.Rgb(206, 98, 9)); node2.Style.Brush = new LinearGradientBrush(0, 30, 150, 30, new Color[] { Color.Rgb(255, 130, 0), Color.Rgb(255, 37, 0) }, null, GradientDrawingOptions.Clamp); node2.Style.StrokeWidth = 0; node2.Annotations.Add(new Annotation() { Content = FlowDiagram.CreateLabel(context, "Define Scope", (int)node2.Width, Color.White), HorizontalAlignment = HorizontalAlignment.Center }); diagram.AddNode(node2); var node3 = DrawNode(280 * 2 * MainActivity.Factor, node2.OffsetY + (140 * 2 * MainActivity.Factor), 175 * 2 * MainActivity.Factor, 70 * 2 * MainActivity.Factor, ShapeType.RoundedRectangle); node3.Style.StrokeBrush = new SolidBrush(Color.Rgb(206, 98, 9)); node3.Style.StrokeStyle = StrokeStyle.Dashed; node3.Annotations.Add(new Annotation() { Content = FlowDiagram.CreateLabel(context, "Analyze process As-Is", (int)node3.Width, Color.White), HorizontalAlignment = HorizontalAlignment.Center }); diagram.AddNode(node3); var node4 = DrawNode(280 * 2 * MainActivity.Factor, node3.OffsetY + (140 * 2 * MainActivity.Factor), 175 * 2 * MainActivity.Factor, 70 * 2 * MainActivity.Factor, ShapeType.RoundedRectangle); node4.Style.StrokeBrush = new SolidBrush(Color.Rgb(206, 98, 9)); node4.Style.StrokeWidth = 0; node4.Annotations.Add(new Annotation() { Content = FlowDiagram.CreateLabel(context, "Identify" + "\n" + "opportunities" + "\n" + "for improvement", (int)node4.Width, Color.White), HorizontalAlignment = HorizontalAlignment.Center }); diagram.AddNode(node4); var node5 = DrawNode(280 * 2 * MainActivity.Factor, node4.OffsetY + (140 * 2 * MainActivity.Factor), 175 * 2 * MainActivity.Factor, 70 * 2 * MainActivity.Factor, ShapeType.RoundedRectangle); node5.Style.StrokeBrush = new SolidBrush(Color.Rgb(206, 98, 9)); node5.Style.StrokeWidth = 0; node5.Annotations.Add(new Annotation() { Content = FlowDiagram.CreateLabel(context, "Design and" + "\n" + "implement improved" + "\n" + "processess", (int)node5.Width, Color.White), HorizontalAlignment = HorizontalAlignment.Center }); diagram.AddNode(node5); var node6 = DrawCustomShape(53 * 2, 155 * 2); node6.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.5, IsVisible = false }); diagram.AddNode(node6); var labelnode6 = new Node(context); labelnode6.OffsetX = 37.5f * 2 * MainActivity.Factor; labelnode6.OffsetY = 200 * 2 * MainActivity.Factor; labelnode6.Width = 80 * 2 * MainActivity.Factor; labelnode6.Height = 35 * 2 * MainActivity.Factor; labelnode6.Annotations.Add(new Annotation() { Content = "Sponsor", FontSize = 28 * MainActivity.Factor, HorizontalAlignment = HorizontalAlignment.Center }); labelnode6.Style = new Style() { StrokeBrush = new SolidBrush(Color.Transparent), Brush = new SolidBrush(Color.Transparent) }; diagram.AddNode(labelnode6); var node7 = DrawCustomShape(53 * 2, 497 * 2); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0, IsVisible = false }); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.3, IsVisible = false }); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.6, IsVisible = false }); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 1, IsVisible = false }); diagram.AddNode(node7); var labelnode7 = new Node(context); labelnode7.OffsetX = 55 * 2 * MainActivity.Factor; labelnode7.OffsetY = 545 * 2 * MainActivity.Factor; labelnode7.Width = 60 * 2 * MainActivity.Factor; labelnode7.Height = 50 * 2 * MainActivity.Factor; labelnode7.Annotations.Add(new Annotation() { Content = "Domain Experts", FontSize = 28 * MainActivity.Factor, HorizontalAlignment = HorizontalAlignment.Center }); labelnode7.Style = new Style() { StrokeBrush = new SolidBrush(Color.Transparent), Brush = new SolidBrush(Color.Transparent) }; diagram.AddNode(labelnode7); var node8 = DrawCustomShape(590 * 2, 155 * 2); node8.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.5, IsVisible = false }); diagram.AddNode(node8); var labelnode8 = new Node(context); labelnode8.OffsetX = 590.5f * 2 * MainActivity.Factor; labelnode8.OffsetY = 200 * 2 * MainActivity.Factor; labelnode8.Width = 78 * 2 * MainActivity.Factor; labelnode8.Height = 49 * 2 * MainActivity.Factor; labelnode8.Annotations.Add(new Annotation() { Content = "Project Manager", FontSize = 28 * MainActivity.Factor, HorizontalAlignment = HorizontalAlignment.Center }); labelnode8.Style = new Style() { StrokeBrush = new SolidBrush(Color.Transparent), Brush = new SolidBrush(Color.Transparent) }; diagram.AddNode(labelnode8); var node9 = DrawCustomShape(590 * 2, 497 * 2); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0, IsVisible = false }); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.3, IsVisible = false }); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.6, IsVisible = false }); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 1, IsVisible = false }); diagram.AddNode(node9); var labelnode9 = new Node(context); labelnode9.OffsetX = 591 * 2 * MainActivity.Factor; labelnode9.OffsetY = 550 * 2 * MainActivity.Factor; labelnode9.Width = 65 * 2 * MainActivity.Factor; labelnode9.Height = 39 * 2 * MainActivity.Factor; labelnode9.Annotations.Add(new Annotation() { Content = "Business Analyst", FontSize = 28 * MainActivity.Factor, HorizontalAlignment = HorizontalAlignment.Center }); labelnode9.Style = new Style() { StrokeBrush = new SolidBrush(Color.Transparent), Brush = new SolidBrush(Color.Transparent) }; diagram.AddNode(labelnode9); diagram.AddConnector(DrawConnector(node1, node2, node1.Ports[2], node2.Ports[0], SegmentType.OrthoSegment, Color.Rgb(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, Color.Rgb(127, 132, 133), Color.Rgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node2, node3, node2.Ports[2], node3.Ports[0], SegmentType.OrthoSegment, Color.Rgb(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, Color.Rgb(127, 132, 133), Color.Rgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node3, node4, node3.Ports[2], node4.Ports[0], SegmentType.OrthoSegment, Color.Rgb(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, Color.Rgb(127, 132, 133), Color.Rgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node4, node5, node4.Ports[2], node5.Ports[0], SegmentType.OrthoSegment, Color.Rgb(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, Color.Rgb(127, 132, 133), Color.Rgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node6, node1, node6.Ports[0], node1.Ports[3], SegmentType.StraightSegment, Color.Rgb(127, 132, 133), StrokeStyle.Dashed, DecoratorType.Filled45Arrow, Color.Rgb(127, 132, 133), Color.Rgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node8, node1, node8.Ports[0], node1.Ports[1], SegmentType.StraightSegment, Color.Rgb(127, 132, 133), StrokeStyle.Dashed, DecoratorType.Filled45Arrow, Color.Rgb(127, 132, 133), Color.Rgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node7, node2, node7.Ports[0], node2.Ports[3], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Square, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node7, node3, node7.Ports[1], node3.Ports[3], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Square, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node7, node4, node7.Ports[2], node4.Ports[3], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Square, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node7, node5, node7.Ports[3], node5.Ports[3], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Square, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node9, node2, node9.Ports[0], node2.Ports[1], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Circle, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node9, node3, node9.Ports[1], node3.Ports[1], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Circle, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node9, node4, node9.Ports[2], node4.Ports[1], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Circle, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node9, node5, node9.Ports[3], node5.Ports[1], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Circle, Color.Black, Color.Black, 6)); diagram.Loaded += Diagram_Loaded; return diagram; } private void Diagram_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); } public override void Destroy() { if (diagram != null) diagram.Dispose(); base.Destroy(); } //Creates the Node with Specified input Node DrawNode(float x, float y, float w, float h, ShapeType shape) { var node = new Node(m_context); node.OffsetX = x; node.OffsetY = y; node.Width = w; node.Height = h; node.ShapeType = shape; node.Style.StrokeWidth = 1 * 2 * MainActivity.Factor; node.CornerRadius = 30 * 2 * MainActivity.Factor; node.Style.Brush = new SolidBrush(Color.Rgb(255, 129, 0)); node.Ports.Add(new Port() { NodeOffsetX = 0.5, NodeOffsetY = 0, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.5, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 0.5, NodeOffsetY = 1, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.5, IsVisible = false }); return node; } Node DrawCustomShape(float x, float y) { var node = new Node(m_context); node.OffsetX = x * MainActivity.Factor; node.OffsetY = y * MainActivity.Factor; node.Width = 50 * 2 * MainActivity.Factor; node.Height = 40 * 2 * MainActivity.Factor; SfGraphics grap = new SfGraphics(); Pen stroke = new Pen(); stroke.Brush = new SolidBrush(Color.Transparent); stroke.StrokeWidth = 3 * MainActivity.Factor; stroke.StrokeBrush = new SolidBrush(Color.Rgb(24, 161, 237)); grap.DrawEllipse(stroke, new System.Drawing.Rectangle(10, 0, 20, 20)); grap.DrawArc(stroke, 0, 20, 40, 40, 180, 180); node.UpdateSfGraphics(grap); return node; } Connector DrawConnector(Node Src, Node Trgt, Port srcport, Port trgtport, SegmentType type, Color strokeColor, StrokeStyle style, DecoratorType decorator, Color fillColor, Color strokeFill, float sw) { var Conn = new Connector(m_context, Src, Trgt); Conn.SourcePort = srcport; Conn.TargetPort = trgtport; Conn.SegmentType = type; Conn.TargetDecoratorType = decorator; Conn.TargetDecoratorStyle.Fill = fillColor; Conn.TargetDecoratorStyle.StrokeColor = strokeFill; Conn.Style.StrokeWidth = 1 * 2 * MainActivity.Factor; Conn.Style.StrokeBrush = new SolidBrush(strokeColor); Conn.Style.StrokeStyle = style; Conn.TargetDecoratorStyle.Size = sw; Conn.TargetDecoratorStyle.StrokeWidth = 2 * 2 * MainActivity.Factor; return Conn; } } }<file_sep>/Forms/ComboBox/ComboBox/Samples/GettingStartedSample/GettingStartedSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using SampleBrowser.Core; using Syncfusion.XForms.ComboBox; using Xamarin.Forms; namespace SampleBrowser.SfComboBox { public partial class GettingStartedSample : SampleView, INotifyPropertyChanged { public ObservableCollection<string> Source1 { get; set; } public ObservableCollection<string> Source2 { get; set; } public ObservableCollection<string> Source3 { get; set; } private string watermark = "Search Here"; public string Watermark { get { return watermark; } set { watermark = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Watermark")); } } } private int textSize = 17; public int TextSize { get { return textSize; } set { textSize = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("TextSize")); } } } private bool isEditableComboBox = true; public bool IsEditableComboBox { get { return isEditableComboBox; } set { isEditableComboBox = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("IsEditableComboBox")); } } } private bool isIgnoreDiacritic = false; public bool IsIgnoreDiacritic { get { return isIgnoreDiacritic; } set { isIgnoreDiacritic = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("IsIgnoreDiacritic")); } } } private bool isSelectAllOnFocus = false; public bool IsSelectAllOnFocus { get { return isSelectAllOnFocus; } set { isSelectAllOnFocus = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("IsSelectAllOnFocus")); } } } public new event PropertyChangedEventHandler PropertyChanged; public GettingStartedSample() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { layoutRoot.HorizontalOptions = LayoutOptions.Center; layoutRoot.WidthRequest = 300; } Source1 = new ContactsInfoRepository().GetSizeDetails(); Source2 = new ContactsInfoRepository().GetResolutionDetails(); Source3 = new ContactsInfoRepository().GetOrientationDetails(); this.BindingContext = this; optionLayout.BindingContext = this; PickerMethod(); } private void PickerMethod() { ColorPicker.SelectedIndex = 0; BackColorPicker.SelectedIndex = 0; SizePicker.SelectedIndex = 2; ComboBoxModePicker.SelectedIndex = 0; SizePicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (SizePicker.SelectedIndex) { case 0: { TextSize = 13; } break; case 1: { TextSize = 15; } break; case 2: { TextSize = 17; } break; } }; SugesstionPlacementPicker.SelectedIndex = 0; SugesstionPlacementPicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (SugesstionPlacementPicker.SelectedIndex) { case 0: { comboBox1.SuggestionBoxPlacement = SuggestionBoxPlacement.Auto; comboBox2.SuggestionBoxPlacement = SuggestionBoxPlacement.Auto; comboBox3.SuggestionBoxPlacement = SuggestionBoxPlacement.Auto; } break; case 1: { comboBox1.SuggestionBoxPlacement = SuggestionBoxPlacement.Top; comboBox2.SuggestionBoxPlacement = SuggestionBoxPlacement.Top; comboBox3.SuggestionBoxPlacement = SuggestionBoxPlacement.Top; } break; case 2: { comboBox1.SuggestionBoxPlacement = SuggestionBoxPlacement.Bottom; comboBox2.SuggestionBoxPlacement = SuggestionBoxPlacement.Bottom; comboBox3.SuggestionBoxPlacement = SuggestionBoxPlacement.Bottom; } break; } }; } } public class booltofontConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return FontAttributes.Bold; return FontAttributes.None; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class booltocolorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return Color.Black; return Color.Gray; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class ComboBoxImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { if (value is string) { if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB return value; #else if (SampleBrowser.Core.SampleBrowser.IsIndividualSB) return value; else return "SampleBrowser.SfComboBox.UWP\\" + value; #endif } } } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class StringToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { if (value.ToString() == "Black") return Color.Black; else if (value.ToString() == "Blue") return Color.Blue; else if (value.ToString() == "Red") return Color.Red; else if (value.ToString() == "Yellow") return Color.Yellow; } return Color.Black; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class StringToColorConverter2 : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { if (value.ToString() == "Transparent") return Color.Transparent; else if (value.ToString() == "Blue") return Color.FromHex("#7838f7"); else if (value.ToString() == "Red") return Color.FromHex("#f24864"); else if (value.ToString() == "Yellow") return Color.FromHex("#e6f954"); } return Color.Transparent; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class StringToComboBoxModeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { if (value.ToString() == "Suggest") return Syncfusion.XForms.ComboBox.ComboBoxMode.Suggest; else if (value.ToString() == "SuggestAppend") return Syncfusion.XForms.ComboBox.ComboBoxMode.SuggestAppend; else if (value.ToString() == "Append") return Syncfusion.XForms.ComboBox.ComboBoxMode.Append; } return Syncfusion.XForms.ComboBox.ComboBoxMode.Suggest; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/BusyIndicator/PickerModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class PickerModel : UIPickerViewModel { private readonly IList<string> values; public event EventHandler<PickerChangedEventArgs> PickerChanged; public PickerModel(IList<string> values) { this.values = values; } public override nint GetComponentCount (UIPickerView picker) { return 1; } public override nint GetRowsInComponent (UIPickerView picker, nint component) { return values.Count; } public override string GetTitle (UIPickerView picker, nint row, nint component) { return values[(int)row]; } public override nfloat GetRowHeight (UIPickerView picker, nint component) { return 30f; } public override void Selected (UIPickerView picker, nint row, nint component) { if (this.PickerChanged != null) { this.PickerChanged(this, new PickerChangedEventArgs{SelectedValue = values[(int)row]}); } } } } <file_sep>/Forms/Picker/Picker/Samples/PickerGettingStarted/PickerGettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.ComponentModel; using Xamarin.Forms; namespace SampleBrowser.SfPicker { public class PickerGettingStartedViewModel : INotifyPropertyChanged { private ObservableCollection<object> source; private bool isShowHeader = true; private bool isShowColumnHeader = false; private bool isEnableAutoReverse = false; private bool isEnableBorderColor = false; private int selectedIndex = 2; private string headerText = "SELECT A COLOR"; private ObservableCollection<string> columnHeaderTextCollection; public event PropertyChangedEventHandler PropertyChanged; public PickerGettingStartedViewModel() { source = new ObservableCollection<object>(); source.Add("Yellow"); source.Add("Green"); source.Add("Navy"); source.Add("Orange"); source.Add("Lime"); source.Add("Purple"); source.Add("Pink"); source.Add("Red"); source.Add("Gray"); if (Device.RuntimePlatform != Device.Android && Device.RuntimePlatform != Device.UWP) headerText = "Select a Color"; columnHeaderTextCollection = new ObservableCollection<string>(); if (Device.RuntimePlatform == Device.Android) { columnHeaderTextCollection.Add("COLORS"); } else { columnHeaderTextCollection.Add("Colors"); } } public ObservableCollection<object> Source { get { return source; } set { source = value; } } public ObservableCollection<string> ColumnHeaderTextCollection { get { return columnHeaderTextCollection; } set { columnHeaderTextCollection = value; } } public bool IsShowHeader { get { return isShowHeader; } set { isShowHeader = value; OnPropertyChanged("IsShowHeader"); } } public bool IsShowColumnHeader { get { return isShowColumnHeader; } set { isShowColumnHeader = value; OnPropertyChanged("IsShowColumnHeader"); } } public bool IsEnableAutoReverse { get { return isEnableAutoReverse; } set { isEnableAutoReverse = value; OnPropertyChanged("IsEnableAutoReverse"); } } public bool IsEnableBorderColor { get { return isEnableBorderColor; } set { isEnableBorderColor = value; OnPropertyChanged("IsEnableBorderColor"); } } public string HeaderText { get { return headerText; } set { headerText = value; OnPropertyChanged("HeaderText"); } } public int SelectedIndex { get { return selectedIndex; } set { selectedIndex = value; OnPropertyChanged("SelectedIndex"); } } void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/InkAnnotationHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Reflection; using CoreGraphics; using Syncfusion.SfPdfViewer.iOS; using UIKit; namespace SampleBrowser { public class InkAnnotationHelper { CustomToolbar parent; TextMarkupAnnotationHelper textmarkupHelper; AnnotationHelper annotHelper; internal const float DefaultToolbarHeight = 50f; CGColor separatorgray = UIColor.FromRGBA(red: 0.86f, green: 0.86f, blue: 0.86f, alpha: 1.0f).CGColor; public InkAnnotationHelper(CustomToolbar customtoolbar) { parent = customtoolbar; } public InkAnnotationHelper(TextMarkupAnnotationHelper helper, CustomToolbar customtoolbar) { textmarkupHelper = helper; parent = customtoolbar; } public InkAnnotationHelper(AnnotationHelper annottoolbar, CustomToolbar customtoolbar) { annotHelper = annottoolbar; parent = customtoolbar; } internal void PdfViewerControl_InkSelected(object sender, InkSelectedEventArgs args) { if (!args.IsSignature) parent.annotation = sender as InkAnnotation; else parent.annotation = sender as HandwrittenSignature; if (parent.inkAnnotationToolbar != null) { parent.inkAnnotationToolbar.RemoveFromSuperview(); } parent.annotationFrame = parent.Frame; parent.annotationFrame.Height = DefaultToolbarHeight; parent.annotationFrame.Y = parent.parentView.Frame.Height - parent.annotationFrame.Height + 4; parent.inkAnnotationToolbar.Frame = parent.annotationFrame; parent.inkAnnotationToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); parent.toolbarBackbutton.Frame = new CGRect(15, 7, 35, 35); parent.toolbarBackbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.toolbarBackbutton.TouchUpInside += parent.ToolbarBackbutton_TouchUpInside; parent.toolbarBackbutton.Font = parent.highFont; parent.toolbarBackbutton.SetTitle("\ue708", UIControlState.Normal); parent.toolbarBackbutton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.inkAnnotationToolbar.Add(parent.toolbarBackbutton); parent.inkButton.Frame = new CGRect(65, 7, 35, 35); parent.inkButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkButton.Font = parent.highFont; parent.inkButton.SetTitle("\ue704", UIControlState.Normal); parent.inkButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.inkAnnotationToolbar.Add(parent.inkButton); parent.inkThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 55, 7, 30, 30); parent.inkThicknessButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkThicknessButton.Font = parent.highFont; parent.inkThicknessButton.SetTitle("\ue722", UIControlState.Normal); parent.inkThicknessButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.inkAnnotationToolbar.Add(parent.inkThicknessButton); parent.inkColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 100, 7, 30, 30); parent.inkColorButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; if (!args.IsSignature) parent.inkColorButton.BackgroundColor = (sender as InkAnnotation).Settings.Color; else parent.inkColorButton.BackgroundColor = (sender as HandwrittenSignature).Settings.Color; parent.inkAnnotationToolbar.Add(parent.inkColorButton); if (parent.annotation != null) { parent.toolbarBackbutton.RemoveFromSuperview(); parent.isOpacityNeeded = true; parent.inkThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 100, 7, 35, 35); parent.inkAnnotationToolbar.Add(parent.inkThicknessButton); parent.inkColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 150, 7, 35, 35); parent.inkAnnotationToolbar.Add(parent.inkColorButton); parent.inkdeleteButton.Frame = new CGRect(parent.parentView.Frame.Width - 55, 7, 35, 35); parent.inkdeleteButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkdeleteButton.TouchUpInside += InkdeleteButton_TouchUpInside; parent.inkdeleteButton.Font = parent.highFont; parent.inkdeleteButton.SetTitle("\ue714", UIControlState.Normal); parent.inkdeleteButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.inkAnnotationToolbar.Add(parent.inkdeleteButton); } parent.inkAnnotationToolbar = parent.UpdateToolbarBorder(parent.inkAnnotationToolbar, parent.annotationFrame); parent.Add(parent.inkAnnotationToolbar); } internal void PdfViewerControl_InkDeselected(object sender, InkDeselectedEventArgs args) { parent.annotation = null; parent.inkAnnotationToolbar.RemoveFromSuperview(); parent.inkdeleteButton.RemoveFromSuperview(); parent.inkAnnotationToolbar.RemoveFromSuperview(); parent.thicknessToolbar.RemoveFromSuperview(); parent.colorToolbar.RemoveFromSuperview(); parent.opacityPanel.RemoveFromSuperview(); parent.isOpacityNeeded = false; } internal void PdfViewerControl_CanUndoInkModified(object sender, CanUndoInkModifiedEventArgs args) { if (args.CanUndoInk) { parent.inkUndoButton.SetTitle("\ue70a", UIControlState.Normal); parent.inkUndoButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); } else { parent.inkUndoButton.SetTitle("\ue70a", UIControlState.Normal); parent.inkUndoButton.SetTitleColor(UIColor.LightGray, UIControlState.Normal); } } internal void PdfViewerControl_CanRedoInkModified(object sender, CanRedoInkModifiedEventArgs args) { if (args.CanRedoInk) { parent.inkRedoButton.SetTitle("\ue716", UIControlState.Normal); parent.inkRedoButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); } else { parent.inkRedoButton.SetTitle("\ue716", UIControlState.Normal); parent.inkRedoButton.SetTitleColor(UIColor.LightGray, UIControlState.Normal); } } internal void InkdeleteButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.RemoveAnnotation(parent.annotation); parent.annotHelper.RemoveAllToolbars(false); } internal void InkUndoButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.UndoInk(); } internal void InkRedoButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.RedoInk(); } internal void InkConfirmButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.EndInkSession(true); parent.pdfViewerControl.AnnotationMode = AnnotationMode.None; parent.annotHelper.RemoveAllToolbars(false); parent.Add(parent.annotationToolbar); } internal void InkAnnotationButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.AnnotationMode = AnnotationMode.Ink; parent.isOpacityNeeded = true; parent.annotationFrame = parent.Frame; parent.annotationFrame.Height = DefaultToolbarHeight; parent.annotationFrame.Y = parent.parentView.Frame.Height - parent.annotationFrame.Height + 4; parent.inkAnnotationToolbar.Frame = parent.annotationFrame; parent.inkAnnotationToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); parent.toolbarBackbutton.Frame = new CGRect(15, 7, 35, 35); parent.toolbarBackbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.toolbarBackbutton.TouchUpInside += parent.ToolbarBackbutton_TouchUpInside; parent.toolbarBackbutton.Font = parent.highFont; parent.toolbarBackbutton.SetTitle("\ue708", UIControlState.Normal); parent.toolbarBackbutton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.inkAnnotationToolbar.Add(parent.toolbarBackbutton); parent.inkButton.Frame = new CGRect(65, 7, 35, 35); parent.inkButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkButton.Font = parent.highFont; parent.inkButton.SetTitle("\ue704", UIControlState.Normal); parent.inkButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.inkAnnotationToolbar.Add(parent.inkButton); parent.inkThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 55, 7, 30, 30); parent.inkThicknessButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkThicknessButton.Font = parent.highFont; parent.inkThicknessButton.SetTitle("\ue722", UIControlState.Normal); parent.inkThicknessButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.inkAnnotationToolbar.Add(parent.inkThicknessButton); parent.inkColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 100, 7, 30, 30); parent.inkColorButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkColorButton.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Ink.Color; parent.inkAnnotationToolbar.Add(parent.inkColorButton); CreateInkSessionToolbar(); parent.inkAnnotationToolbar = parent.UpdateToolbarBorder(parent.inkAnnotationToolbar, parent.annotationFrame); parent.Add(parent.inkAnnotationToolbar); } internal void CreateInkSessionToolbar() { parent.toolBarFrame = parent.Frame; parent.toolBarFrame.Height = DefaultToolbarHeight; parent.toolBarFrame.Y = 0; parent.inkAnnotationSessionToolbar.Frame = parent.toolBarFrame; parent.inkAnnotationSessionToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); parent.inkAnnotationSessionToolbar.AutoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.inkUndoButton.Frame = new CGRect(parent.parentView.Frame.Width / 2 - 25, 7, 35, 35); else parent.inkUndoButton.Frame = new CGRect(130, 7, 35, 35); parent.inkUndoButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkUndoButton.TouchUpInside += InkUndoButton_TouchUpInside; ; ; parent.inkUndoButton.Font = parent.highFont; parent.inkUndoButton.SetTitle("\ue70a", UIControlState.Normal); parent.inkUndoButton.SetTitleColor(UIColor.LightGray, UIControlState.Normal); parent.inkAnnotationSessionToolbar.Add(parent.inkUndoButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.inkRedoButton.Frame = new CGRect(parent.parentView.Frame.Width / 2 + 10, 7, 35, 35); else parent.inkRedoButton.Frame = new CGRect(175, 7, 35, 35); parent.inkRedoButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkRedoButton.TouchUpInside += InkRedoButton_TouchUpInside; parent.inkRedoButton.Font = parent.highFont; parent.inkRedoButton.SetTitle("\ue716", UIControlState.Normal); parent.inkRedoButton.SetTitleColor(UIColor.LightGray, UIControlState.Normal); parent.inkAnnotationSessionToolbar.Add(parent.inkRedoButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.inkConfirmButton.Frame = new CGRect(parent.parentView.Frame.Width - 50, 7, 35, 35); else parent.inkConfirmButton.Frame = new CGRect(parent.parentView.Frame.Width - 50, 7, 35, 35); parent.inkConfirmButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkConfirmButton.TouchUpInside += InkConfirmButton_TouchUpInside; parent.inkConfirmButton.Font = parent.highFont; parent.inkConfirmButton.SetTitle("\ue715", UIControlState.Normal); parent.inkConfirmButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.inkAnnotationSessionToolbar.Add(parent.inkConfirmButton); parent.Add(parent.inkAnnotationSessionToolbar); } internal void InkThicknessButton_TouchUpInside(object sender, EventArgs e) { parent.isColorSelected = false; parent.opacityPanel.RemoveFromSuperview(); parent.colorToolbar.RemoveFromSuperview(); parent.thicknessBar.RemoveFromSuperview(); parent.sliderValue.RemoveFromSuperview(); if (!parent.isThicknessTouched) { parent.opacityFrame = parent.Frame; parent.opacityFrame.Height = DefaultToolbarHeight; parent.opacityFrame.Y = parent.parentView.Frame.Height - (DefaultToolbarHeight + parent.opacityFrame.Height - 4); parent.thicknessToolbar.Frame = parent.opacityFrame; parent.thicknessToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); ThicknessView(); parent.isThicknessTouched = true; } else { parent.thicknessToolbar.RemoveFromSuperview(); parent.isThicknessTouched = false; } } internal void ThicknessBar_TouchUpInside(object sender, EventArgs e) { int value = (int)(sender as UISlider).Value; if (parent.annotation != null) { if (parent.annotation is InkAnnotation) (parent.annotation as InkAnnotation).Settings.Thickness = value; else if (parent.annotation is HandwrittenSignature) (parent.annotation as HandwrittenSignature).Settings.Thickness = value; } else { parent.pdfViewerControl.AnnotationSettings.HandwrittenSignature.Thickness = value; parent.pdfViewerControl.AnnotationSettings.Ink.Thickness = value; } if (parent.annotation != null && parent.annotation is ShapeAnnotation) { (parent.annotation as ShapeAnnotation).Settings.Thickness = value; } parent.sliderValue.Text = value.ToString(); } internal void OpacitySlider_TouchUpInside(object sender, EventArgs e) { float value = (sender as UISlider).Value; if (parent.annotation != null) { if (parent.annotation is ShapeAnnotation) { (parent.annotation as ShapeAnnotation).Settings.Opacity = value; } else if (parent.annotation is InkAnnotation) (parent.annotation as InkAnnotation).Settings.Opacity = value; else if (parent.annotation is HandwrittenSignature) (parent.annotation as HandwrittenSignature).Settings.Opacity = value; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) parent.pdfViewerControl.AnnotationSettings.Ink.Opacity = value; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) parent.pdfViewerControl.AnnotationSettings.Circle.Settings.Opacity = value; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.Opacity = value; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) parent.pdfViewerControl.AnnotationSettings.Line.Settings.Opacity = value; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.Opacity = value; else if(parent.pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) parent.pdfViewerControl.AnnotationSettings.HandwrittenSignature.Opacity = value; parent.opacitySliderValue.Text = ((int)(value * 100)).ToString() + "%"; } internal void OpacitySlider_TouchUpOutside(object sender, EventArgs e) { float value = (sender as UISlider).Value; if (parent.annotation != null) { if (parent.annotation is ShapeAnnotation) { (parent.annotation as ShapeAnnotation).Settings.Opacity = value; } else if (parent.annotation is InkAnnotation) (parent.annotation as InkAnnotation).Settings.Opacity = value; else if (parent.annotation is HandwrittenSignature) (parent.annotation as HandwrittenSignature).Settings.Opacity = value; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) parent.pdfViewerControl.AnnotationSettings.Ink.Opacity = value; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.HandwrittenSignature) parent.pdfViewerControl.AnnotationSettings.HandwrittenSignature.Opacity = value; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) parent.pdfViewerControl.AnnotationSettings.Circle.Settings.Opacity = value; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.Opacity = value; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) parent.pdfViewerControl.AnnotationSettings.Line.Settings.Opacity = value; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.Opacity = value; parent.opacitySliderValue.Text = ((int)(value * 100)).ToString() + "%"; } internal void ThicknessView() { parent.AutoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth; parent.BoldBtn1.AutoresizingMask = UIViewAutoresizing.All; parent.BoldBtn2.AutoresizingMask = UIViewAutoresizing.All; parent.BoldBtn3.AutoresizingMask = UIViewAutoresizing.All; parent.BoldBtn4.AutoresizingMask = UIViewAutoresizing.All; parent.BoldBtn5.AutoresizingMask = UIViewAutoresizing.All; parent.BoldColorBtn1.AutoresizingMask = UIViewAutoresizing.All; parent.BoldColorBtn2.AutoresizingMask = UIViewAutoresizing.All; parent.BoldColorBtn3.AutoresizingMask = UIViewAutoresizing.All; parent.BoldColorBtn4.AutoresizingMask = UIViewAutoresizing.All; parent.BoldColorBtn5.AutoresizingMask = UIViewAutoresizing.All; CreateThicknessToolbar(); } internal void BoldColorBtn1_TouchUpInside(object sender, EventArgs e) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { parent.pdfViewerControl.AnnotationSettings.Ink.Thickness = 1; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.pdfViewerControl.AnnotationSettings.FreeText.TextSize = 4; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.Thickness = 1; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { parent.pdfViewerControl.AnnotationSettings.Circle.Settings.Thickness = 1; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { parent.pdfViewerControl.AnnotationSettings.Line.Settings.Thickness = 1; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.Thickness = 1; } } if (parent.annotation != null) { if (parent.annotation is InkAnnotation) (parent.annotation as InkAnnotation).Settings.Thickness = 1; else if (parent.annotation is HandwrittenSignature) (parent.annotation as HandwrittenSignature).Settings.Thickness = 1; else if (parent.annotation is FreeTextAnnotation) { (parent.annotation as FreeTextAnnotation).Settings.TextSize = 4; } else if (parent.annotation is ShapeAnnotation) { (parent.annotation as ShapeAnnotation).Settings.Thickness = 1; } } parent.thicknessToolbar.RemoveFromSuperview(); parent.isThicknessTouched = false; } internal void BoldColorBtn2_TouchUpInside(object sender, EventArgs e) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { parent.pdfViewerControl.AnnotationSettings.Ink.Thickness = 2; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.pdfViewerControl.AnnotationSettings.FreeText.TextSize = 8; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.Thickness = 2; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { parent.pdfViewerControl.AnnotationSettings.Circle.Settings.Thickness = 2; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { parent.pdfViewerControl.AnnotationSettings.Line.Settings.Thickness = 2; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.Thickness = 2; } } if (parent.annotation != null) { if (parent.annotation is InkAnnotation) (parent.annotation as InkAnnotation).Settings.Thickness = 2; else if (parent.annotation is HandwrittenSignature) (parent.annotation as HandwrittenSignature).Settings.Thickness = 2; else if (parent.annotation is FreeTextAnnotation) { (parent.annotation as FreeTextAnnotation).Settings.TextSize = 8; } else if (parent.annotation is ShapeAnnotation) { (parent.annotation as ShapeAnnotation).Settings.Thickness = 2; } } parent.thicknessToolbar.RemoveFromSuperview(); parent.isThicknessTouched = false; } internal void BoldColorBtn3_TouchUpInside(object sender, EventArgs e) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { parent.pdfViewerControl.AnnotationSettings.Ink.Thickness = 4; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.pdfViewerControl.AnnotationSettings.FreeText.TextSize = 12; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.Thickness = 4; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { parent.pdfViewerControl.AnnotationSettings.Circle.Settings.Thickness = 4; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { parent.pdfViewerControl.AnnotationSettings.Line.Settings.Thickness = 4; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.Thickness = 4; } } if (parent.annotation != null) { if (parent.annotation is InkAnnotation) (parent.annotation as InkAnnotation).Settings.Thickness = 4; else if (parent.annotation is HandwrittenSignature) (parent.annotation as HandwrittenSignature).Settings.Thickness = 4; else if (parent.annotation is FreeTextAnnotation) { (parent.annotation as FreeTextAnnotation).Settings.TextSize = 12; } else if (parent.annotation is ShapeAnnotation) { (parent.annotation as ShapeAnnotation).Settings.Thickness = 4; } } parent.thicknessToolbar.RemoveFromSuperview(); parent.isThicknessTouched = false; } internal void BoldColorBtn4_TouchUpInside(object sender, EventArgs e) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { parent.pdfViewerControl.AnnotationSettings.Ink.Thickness = 6; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.pdfViewerControl.AnnotationSettings.FreeText.TextSize = 16; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.Thickness = 6; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { parent.pdfViewerControl.AnnotationSettings.Circle.Settings.Thickness = 6; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { parent.pdfViewerControl.AnnotationSettings.Line.Settings.Thickness = 6; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.Thickness = 6; } } if (parent.annotation != null) { if (parent.annotation is InkAnnotation) (parent.annotation as InkAnnotation).Settings.Thickness = 6; else if (parent.annotation is HandwrittenSignature) (parent.annotation as HandwrittenSignature).Settings.Thickness = 6; else if (parent.annotation is FreeTextAnnotation) { (parent.annotation as FreeTextAnnotation).Settings.TextSize = 16; } else if (parent.annotation is ShapeAnnotation) { (parent.annotation as ShapeAnnotation).Settings.Thickness = 6; } } parent.thicknessToolbar.RemoveFromSuperview(); parent.isThicknessTouched = false; } internal void BoldColorBtn5_TouchUpInside(object sender, EventArgs e) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { parent.pdfViewerControl.AnnotationSettings.Ink.Thickness = 10; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.pdfViewerControl.AnnotationSettings.FreeText.TextSize = 20; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.Thickness = 8; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { parent.pdfViewerControl.AnnotationSettings.Circle.Settings.Thickness = 8; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { parent.pdfViewerControl.AnnotationSettings.Line.Settings.Thickness = 8; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.Thickness = 8; } } if (parent.annotation != null) { if (parent.annotation is InkAnnotation) (parent.annotation as InkAnnotation).Settings.Thickness = 10; else if (parent.annotation is InkAnnotation) (parent.annotation as InkAnnotation).Settings.Thickness = 4; else if (parent.annotation is FreeTextAnnotation) { (parent.annotation as FreeTextAnnotation).Settings.TextSize = 20; } else if (parent.annotation is ShapeAnnotation) { (parent.annotation as ShapeAnnotation).Settings.Thickness = 10; } } parent.thicknessToolbar.RemoveFromSuperview(); parent.isThicknessTouched = false; } internal void CreateThicknessToolbar() { float x = 0; x = (float)(parent.Frame.Width - 310) / 2; parent.AutoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth; parent.BoldBtn1.Frame = new CGRect(x, 7, 54, 30); parent.BoldBtn1.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.BoldBtn1.BackgroundColor = UIColor.White; parent.BoldBtn1.Layer.BorderWidth = 1; parent.BoldBtn1.Layer.BorderColor = separatorgray; parent.thicknessToolbar.AddSubview(parent.BoldBtn1); parent.BoldColorBtn1.Frame = new CGRect((x + 9), 21, 36, 1); if (parent.annotation != null) { if (parent.annotation is InkAnnotation) parent.BoldColorBtn1.BackgroundColor = (parent.annotation as InkAnnotation).Settings.Color; else if (parent.annotation is HandwrittenSignature) parent.BoldColorBtn1.BackgroundColor = (parent.annotation as HandwrittenSignature).Settings.Color; else if (parent.annotation is FreeTextAnnotation) { parent.BoldColorBtn1.BackgroundColor = (parent.annotation as FreeTextAnnotation).Settings.TextColor; } else if (parent.annotation is ShapeAnnotation) { if (parent.shapeView == AnnotationMode.Arrow) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn1.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Rectangle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn1.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Circle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn1.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Line) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn1.BackgroundColor = color; } } } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) parent.BoldColorBtn1.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Ink.Color; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.BoldColorBtn1.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.FreeText.TextColor; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn1.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn1.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn1.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn1.BackgroundColor = color; } } parent.BoldColorBtn1.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.thicknessToolbar.AddSubview(parent.BoldColorBtn1); parent.BoldBtn2.Frame = new CGRect((x + 64), 7, 54, 30); parent.BoldBtn2.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.BoldBtn2.BackgroundColor = UIColor.White; parent.BoldBtn2.Layer.BorderWidth = 1; parent.BoldBtn2.Layer.BorderColor = separatorgray; parent.thicknessToolbar.AddSubview(parent.BoldBtn2); parent.BoldColorBtn2.Frame = new CGRect((x + 73), 21, 36, 2); if (parent.annotation != null) { if (parent.annotation is InkAnnotation) parent.BoldColorBtn2.BackgroundColor = (parent.annotation as InkAnnotation).Settings.Color; else if (parent.annotation is HandwrittenSignature) parent.BoldColorBtn2.BackgroundColor = (parent.annotation as HandwrittenSignature).Settings.Color; else if (parent.annotation is FreeTextAnnotation) { parent.BoldColorBtn2.BackgroundColor = (parent.annotation as FreeTextAnnotation).Settings.TextColor; } else if (parent.annotation is ShapeAnnotation) { if (parent.shapeView == AnnotationMode.Arrow) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn2.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Rectangle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn2.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Circle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn2.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Line) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn2.BackgroundColor = color; } } } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) parent.BoldColorBtn2.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Ink.Color; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.BoldColorBtn2.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.FreeText.TextColor; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { parent.BoldColorBtn2.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { parent.BoldColorBtn2.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { parent.BoldColorBtn2.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { parent.BoldColorBtn2.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor; } } parent.BoldColorBtn2.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.thicknessToolbar.AddSubview(parent.BoldColorBtn2); parent.BoldBtn3.Frame = new CGRect((x + 128), 7, 54, 30); parent.BoldBtn3.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.BoldBtn3.BackgroundColor = UIColor.White; parent.BoldBtn3.Layer.BorderWidth = 1; parent.BoldBtn3.Layer.BorderColor = separatorgray; parent.thicknessToolbar.AddSubview(parent.BoldBtn3); parent.BoldColorBtn3.Frame = new CGRect((x + 137), 20, 36, 4); if (parent.annotation != null) { if (parent.annotation is InkAnnotation) parent.BoldColorBtn3.BackgroundColor = (parent.annotation as InkAnnotation).Settings.Color; else if (parent.annotation is HandwrittenSignature) parent.BoldColorBtn3.BackgroundColor = (parent.annotation as HandwrittenSignature).Settings.Color; else if (parent.annotation is FreeTextAnnotation) { parent.BoldColorBtn3.BackgroundColor = (parent.annotation as FreeTextAnnotation).Settings.TextColor; } else if (parent.annotation is ShapeAnnotation) { if (parent.shapeView == AnnotationMode.Arrow) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn3.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Rectangle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn3.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Circle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn3.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Line) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn3.BackgroundColor = color; } } } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) parent.BoldColorBtn3.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Ink.Color; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.BoldColorBtn3.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.FreeText.TextColor; } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line || parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn3.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn3.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn3.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn3.BackgroundColor = color; } } parent.BoldColorBtn3.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.thicknessToolbar.AddSubview(parent.BoldColorBtn3); parent.BoldBtn4.Frame = new CGRect((x + 192), 7, 54, 30); parent.BoldBtn4.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.BoldBtn4.BackgroundColor = UIColor.White; parent.BoldBtn4.Layer.BorderWidth = 1; parent.BoldBtn4.Layer.BorderColor = separatorgray; parent.thicknessToolbar.AddSubview(parent.BoldBtn4); parent.BoldColorBtn4.Frame = new CGRect((x + 201), 19, 36, 6); if (parent.annotation != null) { if (parent.annotation is InkAnnotation) parent.BoldColorBtn4.BackgroundColor = (parent.annotation as InkAnnotation).Settings.Color; else if (parent.annotation is HandwrittenSignature) parent.BoldColorBtn4.BackgroundColor = (parent.annotation as HandwrittenSignature).Settings.Color; else if (parent.annotation is FreeTextAnnotation) { parent.BoldColorBtn4.BackgroundColor = (parent.annotation as FreeTextAnnotation).Settings.TextColor; } else if (parent.annotation is ShapeAnnotation) { if (parent.shapeView == AnnotationMode.Arrow) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn4.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Rectangle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn4.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Circle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn4.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Line) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn4.BackgroundColor = color; } } } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) parent.BoldColorBtn4.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Ink.Color; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.BoldColorBtn4.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.FreeText.TextColor; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn4.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn4.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn4.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn4.BackgroundColor = color; } parent.BoldColorBtn4.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.thicknessToolbar.AddSubview(parent.BoldColorBtn4); parent.BoldBtn5.Frame = new CGRect((x + 256), 7, 54, 30); parent.BoldBtn5.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.BoldBtn5.BackgroundColor = UIColor.White; parent.BoldBtn5.Layer.BorderWidth = 1; parent.BoldBtn5.Layer.BorderColor = separatorgray; parent.thicknessToolbar.AddSubview(parent.BoldBtn5); if (parent.annotation != null) { if (parent.annotation is InkAnnotation) parent.BoldColorBtn5.BackgroundColor = (parent.annotation as InkAnnotation).Settings.Color; else if (parent.annotation is HandwrittenSignature) parent.BoldColorBtn5.BackgroundColor = (parent.annotation as HandwrittenSignature).Settings.Color; else if (parent.annotation is FreeTextAnnotation) { parent.BoldColorBtn5.BackgroundColor = (parent.annotation as FreeTextAnnotation).Settings.TextColor; } else if (parent.annotation is ShapeAnnotation) { if (parent.shapeView == AnnotationMode.Arrow) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn5.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Rectangle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn5.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Circle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn5.BackgroundColor = color; } else if (parent.shapeView == AnnotationMode.Line) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn5.BackgroundColor = color; } } } if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) parent.BoldColorBtn5.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.Ink.Color; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.FreeText) { parent.BoldColorBtn5.BackgroundColor = parent.pdfViewerControl.AnnotationSettings.FreeText.TextColor; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn5.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn5.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn5.BackgroundColor = color; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) { nfloat r, g, b, a; parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.BoldColorBtn5.BackgroundColor = color; } parent.BoldColorBtn5.Frame = new CGRect((x + 265), 18, 36, 8); parent.BoldColorBtn5.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.thicknessToolbar.AddSubview(parent.BoldColorBtn5); parent.Add(parent.thicknessToolbar); } internal void Opacitybutton_TouchUpInside(object sender, EventArgs e) { parent.isThicknessTouched = false; parent.opacitySlider.RemoveFromSuperview(); parent.opacitySliderValue.RemoveFromSuperview(); parent.opacityFrame = parent.Frame; parent.opacityFrame.Height = DefaultToolbarHeight + 16; parent.opacityFrame.Y = parent.parentView.Frame.Height - (DefaultToolbarHeight + (parent.colorFrame.Height * 2) + 10); parent.opacityFrame.Width = parent.parentView.Frame.Width; parent.opacityPanel.Frame = parent.opacityFrame; parent.opacityPanel.BackgroundColor = UIColor.FromRGB(249, 249, 249); parent.opacitySlider = new UISlider(); parent.opacitySlider.Frame = new CGRect(5, 0, parent.opacityFrame.Width - 54, parent.opacityFrame.Height); parent.opacitySlider.MinValue = 0; parent.opacitySlider.MaxValue = 1; parent.opacitySlider.Continuous = true; parent.opacityPanel.Add(parent.opacitySlider); if (parent.annotation != null) { if (parent.annotation is ShapeAnnotation) { parent.opacitySlider.Value = (float)(parent.annotation as ShapeAnnotation).Settings.Opacity; } else if (parent.annotation is InkAnnotation) parent.opacitySlider.Value = (parent.annotation as InkAnnotation).Settings.Opacity; else if (parent.annotation is HandwrittenSignature) parent.opacitySlider.Value = (parent.annotation as HandwrittenSignature).Settings.Opacity; } else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) parent.opacitySlider.Value = parent.pdfViewerControl.AnnotationSettings.Ink.Opacity; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Rectangle) parent.opacitySlider.Value = (float)parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.Opacity; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Circle) parent.opacitySlider.Value = (float)parent.pdfViewerControl.AnnotationSettings.Circle.Settings.Opacity; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Line) parent.opacitySlider.Value = (float)parent.pdfViewerControl.AnnotationSettings.Line.Settings.Opacity; else if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Arrow) parent.opacitySlider.Value = (float)parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.Opacity; parent.opacitySlider.TouchUpInside += OpacitySlider_TouchUpInside; parent.opacitySlider.TouchUpOutside += OpacitySlider_TouchUpOutside; parent.opacitySliderValue = new UILabel(); parent.opacitySliderValue.Frame = new CGRect(parent.opacityFrame.Width - 45, 0, 55, parent.opacityFrame.Height); parent.opacitySliderValue.Text = ((int)(parent.opacitySlider.Value * 100)).ToString() + "%"; parent.opacityPanel.Add(parent.opacitySliderValue); parent.opacityPanel.Layer.BorderColor = new CGColor(0.2f, 0.2f); parent.opacityPanel.Layer.BorderWidth = 1; if (!parent.isOpacitySelected) { parent.Add(parent.opacityPanel); parent.isOpacitySelected = true; } else { parent.opacityPanel.RemoveFromSuperview(); parent.isOpacitySelected = false; } } } } <file_sep>/Forms/Schedule/README.md The Schedule control is used to schedule and manage the appointments through an intuitive user interface to plan and manage the events or appointments in an efficient way. | Sample | Description | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| | Getting Started | Showcases a simple schedule with data source displayed in day, workweek, week, and month views. | | Day view Configuration | Showcases the separation of working and non-working hours with different colors and date navigation capability of schedule with blocking timeslots in day, week, and workweek views. | | Appointment Editor | Showcases date navigation capability with appointment editing such as start time, end time, subject, time zone, and more. | | Recurring Appointments | Showcases the recurring appointments. | | View Customization | Showcases the customization of month cell and appointment through templates. | | Agenda View | Showcases the agenda view support of schedule where specific date appointments can be viewed below the month view. | | Time table | Showcases the working hours with blocking timeslots.| | Drag and Drop | Showcases the capability of rescheduling appointment through drag-and-drop operations. | | Localization | Showcases the localization support of schedule. | | Load On Demand | Showcases the on-demand data processing for better performance while loading large amounts of data. |<file_sep>/Forms/DataGrid/DataGrid/Samples/Styles/LoadMoreViewStyle.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "LoadMoreViewStyle.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Derived from DataGridStyle to add the custom styles /// </summary> public class LoadMoreViewStyle : DataGridStyle { /// <summary> /// Initializes a new instance of the LoadMoreViewStyle class. /// </summary> public LoadMoreViewStyle() { } /// <summary> /// Overrides this method to write a Grid line visibility /// </summary> /// <returns>Returns GridLinesVisibility Horizontal</returns> public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Horizontal; } /// <summary> /// Overrides this method to write a custom style for LoadMoreView background color /// </summary> /// <returns>Returns From H e x Color</returns> public override Color GetLoadMoreViewBackgroundColor() { return Color.FromHex("#E0E0E0 "); } /// <summary> /// Overrides this method to write a custom style for LoadMoreView foreground color /// </summary> /// <returns>Returns From H e x Color</returns> public override Color GetLoadMoreViewForegroundColor() { return Color.FromHex(" #000000"); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Axis/Category.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Com.Syncfusion.Navigationdrawer; namespace SampleBrowser { public class Category : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Internet Users - 2016"; chart.Title.TextSize = 15; CategoryAxis dateTimeAxis = new CategoryAxis(); dateTimeAxis.LabelPlacement = LabelPlacement.BetweenTicks; dateTimeAxis.ShowMajorGridLines = false; dateTimeAxis.LabelStyle.WrappedLabelAlignment = ChartAxisLabelAlignment.Center; dateTimeAxis.LabelStyle.MaxWidth = 40; dateTimeAxis.LabelStyle.TextColor = Color.Black; chart.PrimaryAxis = dateTimeAxis; var numericalAxis = new NumericalAxis(); numericalAxis.Minimum = 0; numericalAxis.Maximum = 70; numericalAxis.Visibility = Visibility.Gone; numericalAxis.ShowMajorGridLines = false; numericalAxis.ShowMinorGridLines = false; chart.SecondaryAxis = numericalAxis; ColumnSeries columnSeries = new ColumnSeries(); columnSeries.EnableAnimation = true; columnSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; columnSeries.ItemsSource = Data.GetCategoryData(); columnSeries.XBindingPath = "XValue"; columnSeries.YBindingPath = "YValue"; columnSeries.DataMarker.ShowLabel = true; columnSeries.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Outer; columnSeries.DataMarker.LabelStyle.LabelFormat = "#.#'M'"; chart.Series.Add(columnSeries); return chart; } } }<file_sep>/iOS/SampleBrowser/Samples/Sunburst/readme.md The sunburst chart control visualizes hierarchical data using a concentric circle layout. The innermost circle represents the root level in the hierarchy. Its rich feature set includes functionalities like data binding, legends, animations, data labels, selection, tooltips, and drill-down. The following samples are available for sunburst chart to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Getting Started](SunburstChart.cs)| The sunburst chart control visualizes hierarchical data using a concentric circle layout. This sample shows how to add sunburst chart with its levels based on underlying value. Animation and tooltip feature has used in this sample. | | [Drill down](DrillDown.cs)| This sample shows how to add drill down functionalizes in a sunburst chart. | | [Selection](SunburstSelection.cs)| This sample shows how to apply varies types of selection mode in a sunburst chart. | <file_sep>/Forms/PDF/PDF/Samples/CompressExistingPDF/CompressExistingPDF.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Pdf; using System; using System.IO; using Xamarin.Forms; using System.Reflection; using SampleBrowser.Core; using Syncfusion.Pdf.Parsing; namespace SampleBrowser.PDF { public partial class CompressExistingPDF : SampleView { public CompressExistingPDF() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } private void ButtonView_Click(object sender, EventArgs e) { #if COMMONSB Stream documentStream = typeof(RemoveImage).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.jQuery_Succinctly.pdf"); #else Stream documentStream = typeof(RemoveImage).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.jQuery_Succinctly.pdf"); #endif MemoryStream stream = new MemoryStream(); documentStream.CopyTo(stream); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("CompressionTemplate.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("CompressionTemplate.pdf", "application/pdf", stream); } void OnButtonClicked(object sender, EventArgs e) { #if COMMONSB Stream documentStream = typeof(CompressExistingPDF).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.jQuery_Succinctly.pdf"); #else Stream documentStream = typeof(CompressExistingPDF).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.jQuery_Succinctly.pdf"); #endif //Load the PDF document from stream. PdfLoadedDocument document = new PdfLoadedDocument(documentStream); //Initialize new instance of PdfCompressionOptions class. PdfCompressionOptions options = new PdfCompressionOptions(); //set the compress images based on the image quality. options.CompressImages = true; options.ImageQuality = 50; //Enable the optimize font option options.OptimizeFont = true; //Enable the optimize page contents. options.OptimizePageContents = true; //Set to remove the metadata information. options.RemoveMetadata = true; //Assign the compression option to the document document.Compress(options); MemoryStream stream = new MemoryStream(); //Saves the PDF to the memory stream. document.Save(stream); //Close the PDF document document.Close(true); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("CompressExistingPDF.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("CompressExistingPDF.pdf", "application/pdf", stream); } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Formatting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Views; using System.Globalization; using Android.Graphics; namespace SampleBrowser { public class Formatting:SamplePage { SfDataGrid sfGrid; FormattingViewModel viewmodel; public override Android.Views.View GetSampleContent (Android.Content.Context context) { GridImageColumn customerImageColumn = new GridImageColumn(); customerImageColumn.MappingName = "CustomerImage"; customerImageColumn.HeaderText = "Image"; GridSwitchColumn isOpenColumn = new GridSwitchColumn(); isOpenColumn.MappingName = "IsOpen"; isOpenColumn.HeaderText = "Is Open"; GridTextColumn customerIdColumn = new GridTextColumn (); customerIdColumn.MappingName = "CustomerID"; customerIdColumn.HeaderText = "Customer ID"; customerIdColumn.TextAlignment = GravityFlags.Center; GridTextColumn branchNoColumn = new GridTextColumn (); branchNoColumn.MappingName = "BranchNo"; branchNoColumn.HeaderText = "Branch No"; branchNoColumn.TextAlignment = GravityFlags.Center; GridTextColumn currentColumn = new GridTextColumn (); currentColumn.MappingName = "Current"; currentColumn.Format = "C"; currentColumn.CultureInfo = new CultureInfo ("en-US"); currentColumn.TextAlignment = GravityFlags.Center; GridTextColumn customerNameColumn = new GridTextColumn (); customerNameColumn.MappingName = "CustomerName"; customerNameColumn.HeaderText = "Customer Name"; customerNameColumn.TextAlignment = GravityFlags.CenterVertical; GridTextColumn savingsColumn = new GridTextColumn (); savingsColumn.MappingName = "Savings"; savingsColumn.Format = "C"; savingsColumn.CultureInfo = new CultureInfo ("en-US"); savingsColumn.TextAlignment = GravityFlags.Center; sfGrid = new SfDataGrid (context); sfGrid.AutoGenerateColumns = false; sfGrid.SelectionMode = SelectionMode.Single; sfGrid.RowHeight = 70; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; sfGrid.Columns.Add (customerImageColumn); sfGrid.Columns.Add (customerIdColumn); sfGrid.Columns.Add (branchNoColumn); sfGrid.Columns.Add (currentColumn); sfGrid.Columns.Add (customerNameColumn); sfGrid.Columns.Add (savingsColumn); sfGrid.Columns.Add (isOpenColumn); viewmodel = new FormattingViewModel (); sfGrid.ItemsSource = viewmodel.BankInfo; return sfGrid; } public override void Destroy () { sfGrid.Dispose (); sfGrid = null; this.viewmodel.Dispose (); this.viewmodel = null; } } } <file_sep>/iOS/SampleBrowser/Samples/NumericTextBox/NumericTextBox_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfNumericTextBox.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class NumericTextBox_Mobile : SampleView { UIPickerView culturePicker; UILabel titleLabel, descriptionLabel, formulaLabel, principalLabel, interestRateLabel, termLabel, interestLabel, cultureLabel, allowNullLabel, allowDefaultDecimal; UISwitch allowSwitch, allowDecimalSwitch; UIButton cultureDoneButton, cultureButton; private string cultureSelectedType; SfNumericTextBox principalNumericTextBox; SfNumericTextBox interestRateNumericTextBox; SfNumericTextBox periodNumericTextBox; SfNumericTextBox outputNumericTextBox; public UIView option = new UIView(); private readonly IList<string> cultureList = new List<string>(); public void optionView() { this.option.AddSubview(allowNullLabel); this.option.AddSubview(allowSwitch); this.option.AddSubview(allowDefaultDecimal); this.option.AddSubview(allowDecimalSwitch); this.option.AddSubview(cultureLabel); this.option.AddSubview(cultureDoneButton); this.option.AddSubview(culturePicker); this.option.AddSubview(cultureButton); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; this.OptionView.Frame = view.Frame; this.option.Frame = new CGRect(0, 70, Frame.Width, Frame.Height); principalNumericTextBox.Frame = new CGRect(15, 130, view.Frame.Width - 50, 50); interestRateNumericTextBox.Frame = new CGRect(15, 220, view.Frame.Width - 50, 50); periodNumericTextBox.Frame = new CGRect(15, 310, view.Frame.Width - 50, 50); outputNumericTextBox.Frame = new CGRect(15, 400, view.Frame.Width - 50, 50); titleLabel.Frame = new CGRect(15, 10, this.Frame.Size.Width - 20, 30); descriptionLabel.Frame = new CGRect(15, 50, this.Frame.Size.Width - 20, 20); formulaLabel.Frame = new CGRect(15, 70, this.Frame.Size.Width - 20, 20); principalLabel.Frame = new CGRect(15, 100, this.Frame.Size.Width - 20, 30); interestRateLabel.Frame = new CGRect(15, 190, this.Frame.Size.Width - 15, 30); termLabel.Frame = new CGRect(15, 280, this.Frame.Size.Width - 15, 30); interestLabel.Frame = new CGRect(15, 370, this.Frame.Size.Width - 20, 30); cultureLabel.Frame = new CGRect(15, 40, this.Frame.Size.Width - 20, 40); cultureButton.Frame = new CGRect(10, 80, this.Frame.Size.Width - 20, 40); allowNullLabel.Frame = new CGRect(15, 140, this.Frame.Size.Width - 20, 40); allowSwitch.Frame = new CGRect(250, 140, this.Frame.Size.Width - 20, 40); allowDefaultDecimal.Frame = new CGRect(15, 180, this.Frame.Size.Width - 20, 40); allowDecimalSwitch.Frame = new CGRect(250, 180, this.Frame.Size.Width - 20, 40); culturePicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 20, this.Frame.Size.Width, this.Frame.Size.Height / 3); cultureDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 20, this.Frame.Size.Width, 40); } this.optionView(); base.LayoutSubviews(); } static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public NumericTextBox_Mobile() { this.OptionView = new UIView(); //cultureList this.cultureList.Add((NSString)"United States"); this.cultureList.Add((NSString)"United Kingdom"); this.cultureList.Add((NSString)"Japan"); this.cultureList.Add((NSString)"France"); this.cultureList.Add((NSString)"Italy"); //principalNumericTextBox principalNumericTextBox = new SfNumericTextBox(); principalNumericTextBox.Watermark = "Enter Principal"; principalNumericTextBox.AllowNull = true; principalNumericTextBox.MaximumNumberDecimalDigits = 2; principalNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; principalNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnKeyFocus; principalNumericTextBox.FormatString = "c"; principalNumericTextBox.Layer.BorderWidth = 1f; principalNumericTextBox.Value = 1000; principalNumericTextBox.CultureInfo = new NSLocale("en_US"); principalNumericTextBox.AllowDefaultDecimalDigits = true; this.AddSubview(principalNumericTextBox); //interestRateNumericTextBox interestRateNumericTextBox = new SfNumericTextBox(); interestRateNumericTextBox.Watermark = "Enter RI"; interestRateNumericTextBox.AllowNull = true; interestRateNumericTextBox.MaximumNumberDecimalDigits = 1; interestRateNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; interestRateNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnKeyFocus; interestRateNumericTextBox.FormatString = @"p"; interestRateNumericTextBox.ClearButtonMode = UITextFieldViewMode.WhileEditing; interestRateNumericTextBox.Value = 0.2f; interestRateNumericTextBox.Layer.BorderWidth = 1f; interestRateNumericTextBox.CultureInfo = new NSLocale("en_US"); interestRateNumericTextBox.AllowDefaultDecimalDigits = true; this.AddSubview(interestRateNumericTextBox); //periodNumericTextBox periodNumericTextBox = new SfNumericTextBox(); periodNumericTextBox.Watermark = @"Enter Years"; periodNumericTextBox.AllowNull = true; periodNumericTextBox.MaximumNumberDecimalDigits = 0; periodNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; periodNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnKeyFocus; periodNumericTextBox.FormatString = @"years"; periodNumericTextBox.Value = 20; periodNumericTextBox.Layer.BorderWidth = 1f; periodNumericTextBox.CultureInfo = new NSLocale("en_US"); this.AddSubview(periodNumericTextBox); //outputNumericTextBox outputNumericTextBox = new SfNumericTextBox(); outputNumericTextBox.Watermark = @"Enter a number"; outputNumericTextBox.AllowNull = true; outputNumericTextBox.MaximumNumberDecimalDigits = 0; outputNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; outputNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnLostFocus; outputNumericTextBox.FormatString = @"c"; outputNumericTextBox.Value = 2000; outputNumericTextBox.Enabled = false; outputNumericTextBox.Layer.BorderWidth = 1f; outputNumericTextBox.TextColor = UIColor.Gray; outputNumericTextBox.CultureInfo = new NSLocale("en_US"); this.AddSubview(outputNumericTextBox); principalNumericTextBox.ValueChanged += Box_ValueChanged; periodNumericTextBox.ValueChanged += Box_ValueChanged; interestRateNumericTextBox.ValueChanged += Box_ValueChanged; mainPageDesign(); } void Box_ValueChanged(object sender, ValueEventArgs e) { outputNumericTextBox.Value = Convert.ToDecimal(principalNumericTextBox.Value) * Convert.ToDecimal(interestRateNumericTextBox.Value) * Convert.ToDecimal(periodNumericTextBox.Value); } public void mainPageDesign() { //titleLabell titleLabel = new UILabel(); titleLabel.TextColor = UIColor.Black; titleLabel.BackgroundColor = UIColor.Clear; titleLabel.Text = @"Simple Interest Calculator"; titleLabel.TextAlignment = UITextAlignment.Left; titleLabel.Font = UIFont.FromName("Helvetica", 22f); this.AddSubview(titleLabel); //descriptionLabell descriptionLabel = new UILabel(); descriptionLabel.TextColor = UIColor.Black; descriptionLabel.BackgroundColor = UIColor.Clear; descriptionLabel.Text = @"The formula for finding simple interest is:"; descriptionLabel.TextAlignment = UITextAlignment.Left; descriptionLabel.Font = UIFont.FromName("Helvetica", 14f); this.AddSubview(descriptionLabel); //formulaLabell formulaLabel = new UILabel(); formulaLabel.TextColor = UIColor.Black; formulaLabel.BackgroundColor = UIColor.Clear; formulaLabel.Text = @"Amount = Principal * Rate * Time"; formulaLabel.Font = UIFont.ItalicSystemFontOfSize(14f); formulaLabel.TextAlignment = UITextAlignment.Left; this.AddSubview(formulaLabel); //principalLabell principalLabel = new UILabel(); principalLabel.TextColor = UIColor.Black; principalLabel.BackgroundColor = UIColor.Clear; principalLabel.Text = @"Principal"; principalLabel.TextAlignment = UITextAlignment.Left; principalLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(principalLabel); //interestRateLabell interestRateLabel = new UILabel(); interestRateLabel.TextColor = UIColor.Black; interestRateLabel.BackgroundColor = UIColor.Clear; interestRateLabel.Text = @"Interest Rate"; interestRateLabel.TextAlignment = UITextAlignment.Left; interestRateLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(interestRateLabel); //termLabell termLabel = new UILabel(); termLabel.TextColor = UIColor.Black; termLabel.BackgroundColor = UIColor.Clear; termLabel.Text = @"Term (in years)"; termLabel.TextAlignment = UITextAlignment.Left; termLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(termLabel); //interestLabell interestLabel = new UILabel(); interestLabel.TextColor = UIColor.Black; interestLabel.BackgroundColor = UIColor.Clear; interestLabel.Text = @"Amount"; interestLabel.TextAlignment = UITextAlignment.Left; interestLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(interestLabel); //allowNullLabell allowNullLabel = new UILabel(); allowNullLabel.TextColor = UIColor.Black; allowNullLabel.BackgroundColor = UIColor.Clear; allowNullLabel.Text = @"Allow Null"; allowNullLabel.TextAlignment = UITextAlignment.Left; allowNullLabel.Font = UIFont.FromName("Helvetica", 16f); //allowDefaultDecimal allowDefaultDecimal = new UILabel(); allowDefaultDecimal.TextColor = UIColor.Black; allowDefaultDecimal.BackgroundColor = UIColor.Clear; allowDefaultDecimal.Text = @"Allow Default Decimal Digits"; allowDefaultDecimal.TextAlignment = UITextAlignment.Left; allowDefaultDecimal.Font = UIFont.FromName("Helvetica", 16f); //allowSwitchh allowSwitch = new UISwitch(); allowSwitch.ValueChanged += allowNullToggleChanged; allowSwitch.On = true; //allowDecimalSwitchh allowDecimalSwitch = new UISwitch(); allowDecimalSwitch.ValueChanged += AllowDecimalSwitch_ValueChanged; allowDecimalSwitch.On = true; //cultureLabell cultureLabel = new UILabel(); cultureLabel.TextColor = UIColor.Black; cultureLabel.BackgroundColor = UIColor.Clear; cultureLabel.Text = @"Culture"; cultureLabel.TextAlignment = UITextAlignment.Left; cultureLabel.Font = UIFont.FromName("Helvetica", 16f); // this.OptionView.AddSubview(cultureLabel); //cultureButtonn cultureButton = new UIButton(); cultureButton.SetTitle("United States", UIControlState.Normal); cultureButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; cultureButton.BackgroundColor = UIColor.Clear; cultureButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureButton.Hidden = false; cultureButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; cultureButton.Layer.BorderWidth = 4; cultureButton.Layer.CornerRadius = 8; cultureButton.TouchUpInside += ShowCulturePicker; //culturePickerr PickerModel culturePickermodel = new PickerModel(this.cultureList); culturePickermodel.PickerChanged += (sender, e) => { this.cultureSelectedType = e.SelectedValue; cultureButton.SetTitle(cultureSelectedType, UIControlState.Normal); if (cultureSelectedType == "United States") { principalNumericTextBox.CultureInfo = new NSLocale("en_US"); interestRateNumericTextBox.CultureInfo = new NSLocale("en_US"); periodNumericTextBox.CultureInfo = new NSLocale("en_US"); outputNumericTextBox.CultureInfo = new NSLocale("en_US"); } else if (cultureSelectedType == "United Kingdom") { principalNumericTextBox.CultureInfo = new NSLocale("en_UK"); interestRateNumericTextBox.CultureInfo = new NSLocale("en_UK"); periodNumericTextBox.CultureInfo = new NSLocale("en_UK"); outputNumericTextBox.CultureInfo = new NSLocale("en_UK"); } else if (cultureSelectedType == "Japan") { principalNumericTextBox.CultureInfo = new NSLocale("ja_JP"); interestRateNumericTextBox.CultureInfo = new NSLocale("ja_JP"); periodNumericTextBox.CultureInfo = new NSLocale("ja_JP"); outputNumericTextBox.CultureInfo = new NSLocale("ja_JP"); } else if (cultureSelectedType == "France") { principalNumericTextBox.CultureInfo = new NSLocale("fr_FR"); interestRateNumericTextBox.CultureInfo = new NSLocale("fr_FR"); periodNumericTextBox.CultureInfo = new NSLocale("fr_FR"); outputNumericTextBox.CultureInfo = new NSLocale("fr_FR"); } else if (cultureSelectedType == "Italy") { principalNumericTextBox.CultureInfo = new NSLocale("it_IT"); interestRateNumericTextBox.CultureInfo = new NSLocale("it_IT"); periodNumericTextBox.CultureInfo = new NSLocale("it_IT"); outputNumericTextBox.CultureInfo = new NSLocale("it_IT"); } }; culturePicker = new UIPickerView(); culturePicker.ShowSelectionIndicator = true; culturePicker.Hidden = true; culturePicker.Model = culturePickermodel; culturePicker.BackgroundColor = UIColor.White; //cultureDoneButtonn cultureDoneButton = new UIButton(); cultureDoneButton.SetTitle("Done\t", UIControlState.Normal); cultureDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; cultureDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); cultureDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureDoneButton.Hidden = true; cultureDoneButton.TouchUpInside += HideCulturePicker; this.BackgroundColor = UIColor.White; } private void AllowDecimalSwitch_ValueChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { principalNumericTextBox.AllowDefaultDecimalDigits = true; interestRateNumericTextBox.AllowDefaultDecimalDigits = true; } else { principalNumericTextBox.AllowDefaultDecimalDigits = false; interestRateNumericTextBox.AllowDefaultDecimalDigits = false; } } void ShowCulturePicker(object sender, EventArgs e) { cultureDoneButton.Hidden = false; culturePicker.Hidden = false; this.BecomeFirstResponder(); } void HideCulturePicker(object sender, EventArgs e) { cultureDoneButton.Hidden = true; culturePicker.Hidden = true; this.BecomeFirstResponder(); } private void allowNullToggleChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { principalNumericTextBox.AllowNull = true; interestRateNumericTextBox.AllowNull = true; periodNumericTextBox.AllowNull = true; outputNumericTextBox.AllowNull = true; } else { principalNumericTextBox.AllowNull = false; interestRateNumericTextBox.AllowNull = false; periodNumericTextBox.AllowNull = false; outputNumericTextBox.AllowNull = false; } } public override void TouchesBegan(NSSet touches, UIEvent evt) { this.EndEditing(true); } } } <file_sep>/Forms/PdfViewer/PdfViewer/Samples/Helper/FontMappingHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfPdfViewer { public class FontMappingHelper { public static string ContinuousPage = Device.RuntimePlatform == Device.Android ? "\uE700" : Device.RuntimePlatform == Device.iOS ? "\uE705" : "\uE705"; public static string PageByPage = Device.RuntimePlatform == Device.Android ? "\uE701" : Device.RuntimePlatform == Device.iOS ? "\uE703" : "\uE703"; public static string Bookmark = Device.RuntimePlatform == Device.Android ? "\uE700" : Device.RuntimePlatform == Device.iOS ? "\uE701" : "\uE703"; internal static string BookmarkForward = "\uE704"; internal static string BookmarkBackward = "\uE709"; internal static string Bookmark_Default = "\uE703"; internal static string Bookmark_Custom = "\uE702"; internal static string Bookmark_Add = "\uE700"; internal static string DeleteBookmark = "\uE704"; internal static string RenameBookmark = "\uE705"; public static string ShowFile = Device.RuntimePlatform == Device.Android ? "\uE705" : Device.RuntimePlatform == Device.iOS ? "\uE71d" : "\uE720"; public static string Back = Device.RuntimePlatform == Device.Android ? "\uE700" : Device.RuntimePlatform == Device.iOS ? "\uE71c" : "\uE70d"; public static string Search = Device.RuntimePlatform == Device.Android ? "\uE708" : Device.RuntimePlatform == Device.iOS ? "\uE719" : "\uE71c"; public static string Save = Device.RuntimePlatform == Device.Android ? "\uE70a" : Device.RuntimePlatform == Device.iOS ? "\uE718" : "\uE705"; public static string Undo = Device.RuntimePlatform == Device.Android ? "\uE70c" : Device.RuntimePlatform == Device.iOS ? "\uE70a" : "\uE71f"; public static string Underline = Device.RuntimePlatform == Device.Android ? "\uE70d" : Device.RuntimePlatform == Device.iOS ? "\uE70c" : "\uE721"; public static string Redo = Device.RuntimePlatform == Device.Android ? "\uE70f" : Device.RuntimePlatform == Device.iOS ? "\uE716" : "\uE706"; public static string StrikeThrough = Device.RuntimePlatform == Device.Android ? "\uE711" : Device.RuntimePlatform == Device.iOS ? "\uE71e" : "\uE709"; public static string Highlight = Device.RuntimePlatform == Device.Android ? "\uE715" : Device.RuntimePlatform == Device.iOS ? "\uE710" : "\uE70c"; public static string Squiggly = Device.RuntimePlatform == Device.Android ? "\uE704" : Device.RuntimePlatform == Device.iOS ? "\uE711" : "\uE703"; public static string Select = Device.RuntimePlatform == Device.Android ? "\uE71c" : Device.RuntimePlatform == Device.iOS ? "\uE715" : "\uE70b"; public static string Ink = Device.RuntimePlatform == Device.Android ? "\uE71d" : Device.RuntimePlatform == Device.iOS ? "\uE704" : "\uE704"; public static string Delete = Device.RuntimePlatform == Device.Android ? "\uE71e" : Device.RuntimePlatform == Device.iOS ? "\uE714" : "\uE718"; public static string Annotation = Device.RuntimePlatform == Device.Android ? "\uE720" : Device.RuntimePlatform == Device.iOS ? "\uE706" : "\uE708"; public static string Previous = Device.RuntimePlatform == Device.Android ? "\uE70b" : Device.RuntimePlatform == Device.iOS ? "\uE708" : "\uE70f"; public static string Next = Device.RuntimePlatform == Device.Android ? "\uE721" : Device.RuntimePlatform == Device.iOS ? "\uE70b" : "\uE700"; public static string Close = Device.RuntimePlatform == Device.Android ? "\uE70e" : Device.RuntimePlatform == Device.iOS ? "\uE70f" : "\uE701"; public static string SearchBack = Device.RuntimePlatform == Device.Android ? "\uE713" : Device.RuntimePlatform == Device.iOS ? "\uE71b" : "\uE702"; public static string TextMarkup = Device.RuntimePlatform == Device.Android ? "\uE719" : Device.RuntimePlatform == Device.iOS ? "\uE70e" : "\uE719"; public static string Thickness = Device.RuntimePlatform == Device.Android ? "\uE722" : Device.RuntimePlatform == Device.iOS ? "\uE722" : "\uE722"; public static string FontSize = Device.RuntimePlatform == Device.Android ? "\uE700" : Device.RuntimePlatform == Device.iOS ? "\uE700" : "\uE700"; public static string Transparent = Device.RuntimePlatform == Device.Android ? "\uE71a" : Device.RuntimePlatform == Device.iOS ? "\uE71a" : "\uE707"; public static string EditText = Device.RuntimePlatform == Device.Android ? "\uE71f" : Device.RuntimePlatform == Device.iOS ? "\uE700" : "\uE71A"; public static string EditTextFont = Device.RuntimePlatform == Device.Android ? "\uE71f" : Device.RuntimePlatform == Device.iOS ? "\uE700" : "\uE71A"; public static string Stamp = Device.RuntimePlatform == Device.Android ? "\uE703" : Device.RuntimePlatform == Device.iOS ? "\uE701" : "\uE705"; public static string Shape = Device.RuntimePlatform == Device.Android ? "\uE709" : Device.RuntimePlatform == Device.iOS ? "\uE721" : "\uE712"; public static string Polyline = "\uE700"; public static string Cloud = Device.RuntimePlatform == Device.Android ? "\uE700" : "\uE701"; public static string Polygon = Device.RuntimePlatform == Device.Android ? "\uE712" : Device.RuntimePlatform == Device.iOS ? "\uE70D" : "\uE715"; public static string Rectangle = Device.RuntimePlatform == Device.Android ? "\uE710" : Device.RuntimePlatform == Device.iOS ? "\uE705" : "\uE70e"; public static string Circle = Device.RuntimePlatform == Device.Android ? "\uE714" : Device.RuntimePlatform == Device.iOS ? "\uE71f" : "\uE717"; public static string Line = Device.RuntimePlatform == Device.Android ? "\uE703" : Device.RuntimePlatform == Device.iOS ? "\uE717" : "\uE71b"; public static string Arrow = Device.RuntimePlatform == Device.Android ? "\uE701" : Device.RuntimePlatform == Device.iOS ? "\uE712" : "\uE70a"; public static string Edit = Device.RuntimePlatform == Device.iOS ? "\uE720" : Device.RuntimePlatform == Device.Android ? "\uE71d" : "\uE710"; public static string Signature = Device.RuntimePlatform == Device.Android ? "\uE701" : Device.RuntimePlatform == Device.iOS ? "\uE702" : "\uE700"; public static string PageUp = "\uE723"; public static string Moreoptions= Device.RuntimePlatform == Device.iOS ? "\uE702" : Device.RuntimePlatform == Device.Android ? "\uE714" : "\uE710"; internal static string Print = Device.RuntimePlatform == Device.iOS ? "\uE700" : Device.RuntimePlatform == Device.Android ? "\uE701" : "\uE700"; public static string PageDown = "\uE722"; public static string EditTextFontFamily = Device.RuntimePlatform == Device.Android ? "Font size Font.ttf" : Device.RuntimePlatform == Device.iOS ? "Font size Font" : "/Assets/Fonts/Font size Font.ttf#Font size Font"; public static string TextPath = Device.RuntimePlatform == Device.Android ? "PdfViewer_Text_font.ttf" : Device.RuntimePlatform == Device.iOS ? "PdfViewer_Text_font" : "/Assets/Fonts/PdfViewer_Text_font.ttf#PdfViewer_Text_font"; public static string FontFamily = Device.RuntimePlatform == Device.Android ? "Final_PDFViewer_Android_FontUpdate.ttf" : Device.RuntimePlatform == Device.iOS ? "Final_PDFViewer_IOS_FontUpdate" : "/Assets/Fonts/Final_PDFViewer_UWP_FontUpdate.ttf#Final_PDFViewer_UWP_FontUpdate"; public static string BookmarkFont = Device.RuntimePlatform == Device.Android ? "PdfViewer_FONT.ttf" : Device.RuntimePlatform == Device.iOS ? "PdfViewer_FONT" : "/Assets/Fonts/PdfViewer_FONT.ttf#PdfViewer_FONT"; public static string CustomBookmarkFont = Device.RuntimePlatform == Device.Android ? "Xamarin_Bookmark_Icon.ttf" : Device.RuntimePlatform == Device.iOS ? "Xamarin_Bookmark_Icon" : "/Assets/Fonts/Xamarin_Bookmark_Icon.ttf#Xamarin_Bookmark_Icon"; public static string printFont = Device.RuntimePlatform == Device.iOS ? "Font Print" : Device.RuntimePlatform == Device.Android ? "Font Print.ttf" : "/Assets/Fonts/Font Print.ttf#Font Print"; public static string MoreOptionsFont = Device.RuntimePlatform == Device.Android ? "PDFViewer_Android.ttf" : Device.RuntimePlatform == Device.iOS ? "Final_PDFViewer_IOS_FontUpdate" : "/Assets/Fonts/PdfViewer_FONT.ttf#PdfViewer_FONT"; public static string SignatureFont = Device.RuntimePlatform == Device.Android ? "Signature_PDFViewer_FONT.ttf" : Device.RuntimePlatform == Device.iOS ? "Signature_PDFViewer_FONT" : "/Assets/Fonts/Signature_PDFViewer_FONT.ttf#Signature_PDFViewer_FONT"; public static string StampFont = Device.RuntimePlatform == Device.Android ? "Font Text edit stamp.ttf" : Device.RuntimePlatform == Device.iOS ? "Font Text edit stamp" : "/Assets/Fonts/Font Text edit stamp.ttf#Font Text edit stamp"; public static string ViewModeFont = Device.RuntimePlatform == Device.Android ? "Android Page icons.ttf" : Device.RuntimePlatform == Device.iOS ? "Font Page icons" : "/Assets/Fonts/Font Page icons.ttf#Font Page icons"; public static string CloudFont = Device.RuntimePlatform == Device.Android ? "Font Poly Cloud icon.ttf" : Device.RuntimePlatform == Device.iOS ? "Font Poly Cloud icon" : "/Assets/Fonts/Font Poly Cloud icon.ttf#Font Poly Cloud icon"; public static string PolylineFont = Device.RuntimePlatform == Device.Android ? "Polyline_Font.ttf" : Device.RuntimePlatform == Device.iOS ? "xama" : "/Assets/Fonts/xama.ttf#xama"; public static string PopupFont = Device.RuntimePlatform == Device.Android ? "Popup Font.ttf" : Device.RuntimePlatform == Device.iOS ? "font" : "/Assets/Fonts/Popup Font.ttf#font"; public static string Popup = "\uE70B"; public static string Comment = "\uE70A"; public static string Note = "\uE703"; public static string Key = "\uE702"; public static string Help = "\uE701"; public static string Paragraph = "\uE705"; public static string NewParagraph = "\uE704"; public static string Insert = "\uE709"; public static string EditPopup = "\uE700"; public static string EraserFont = Device.RuntimePlatform == Device.Android ? "Xamarin_Eraser.ttf" : Device.RuntimePlatform == Device.iOS ? "Xamarin_Eraser" : "/Assets/Fonts/Xamarin_Eraser.ttf#Xamarin_Eraser"; public static string Eraser = "\uE700"; } } <file_sep>/Forms/XlsIO/XlsIO.iOS/QLPreviewItemFileSystem.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="QLPreviewItemFileSystem.cs" company=" Syncfusion Inc."> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> #endregion namespace SampleBrowser.XlsIO.IOS { using System; using System.Diagnostics.CodeAnalysis; using System.IO; using Foundation; using QuickLook; [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed.")] /// <summary> /// This class used the specialized view for previewing an item. /// </summary> public class QLPreviewItemFileSystem : QLPreviewItem { /// <summary> /// Used to assign the file name and file path. /// </summary> private string fileName, filePath; /// <summary> /// Initializes a new instance of the <see cref="QLPreviewItemFileSystem" /> class. /// </summary> /// <param name="ql_FileName">fileName represents the name of file.</param> /// <param name="ql_FilePath">filePath represents the path of file</param> public QLPreviewItemFileSystem(string ql_FileName, string ql_FilePath) { this.fileName = ql_FileName; this.filePath = ql_FilePath; } /// <summary> /// override ItemTitle with fileName field. /// </summary> public override string ItemTitle { get { return this.fileName; } } /// <summary> /// override ItemUrl with filePath field. /// </summary> public override NSUrl ItemUrl { get { return NSUrl.FromFilename(this.filePath); } } } [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Reviewed.")] /// <summary> /// This class used the specialized view for previewing an item. /// </summary> public class QLPreviewItemBundle : QLPreviewItem { /// <summary> /// Used to assign the file name and file path. /// </summary> private string fileName, filePath; /// <summary> /// Initializes a new instance of the <see cref="QLPreviewItemBundle"/> class. /// </summary> /// <param name="ql_FileName">fileName represents the name of file.</param> /// <param name="ql_filePath">filePath represents the path of file</param> public QLPreviewItemBundle(string ql_FileName, string ql_filePath) { this.fileName = ql_FileName; this.filePath = ql_filePath; } /// <summary> /// override ItemTitle with _fileName field. /// </summary> public override string ItemTitle { get { return this.fileName; } } /// <summary> /// override ItemUrl with _filePath field. /// </summary> public override NSUrl ItemUrl { get { var documents = NSBundle.MainBundle.BundlePath; var lib = Path.Combine(documents, this.filePath); var url = NSUrl.FromFilename(lib); return url; } } } }<file_sep>/Forms/Presentation/Presentation.UWP/SaveWindows.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Windows.Storage; using Windows.Storage.Pickers; using SampleBrowser; using SampleBrowser.Presentation.UWP; using Xamarin.Forms.Platform.UWP; using Windows.ApplicationModel.Email; [assembly: Dependency(typeof(SaveWindows))] [assembly: Dependency(typeof(MailService))] [assembly: ExportRenderer(typeof(Image), typeof(SfImageRenderer))] namespace SampleBrowser.Presentation.UWP { class SaveWindows: ISaveWindowsPhone { public async Task Save(string filename, string contentType, MemoryStream stream) { if (Device.Idiom != TargetIdiom.Desktop) { StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile outFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (Stream outStream = await outFile.OpenStreamForWriteAsync()) { outStream.Write(stream.ToArray(), 0, (int)stream.Length); } if (contentType != "application/html") await Windows.System.Launcher.LaunchFileAsync(outFile); } else { StorageFile storageFile = null; FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.Desktop; savePicker.SuggestedFileName = filename; switch (contentType) { case "application/vnd.openxmlformats-officedocument.presentationml.presentation": savePicker.FileTypeChoices.Add("PowerPoint Presentation", new List<string>() { ".pptx", }); break; case "application/msexcel": savePicker.FileTypeChoices.Add("Excel Files", new List<string>() { ".xlsx", }); break; case "application/msword": savePicker.FileTypeChoices.Add("Word Document", new List<string>() { ".docx" }); break; case "application/pdf": savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string>() { ".pdf" }); break; case "application/html": savePicker.FileTypeChoices.Add("HTML Files", new List<string>() { ".html" }); break; case "image/png": savePicker.FileTypeChoices.Add("Png Image", new List<string>() { ".png" }); break; case "image/jpeg": savePicker.FileTypeChoices.Add("Jpeg Image", new List<string>() { ".jpeg" }); break; } storageFile = await savePicker.PickSaveFileAsync(); if (storageFile == null) return; using (Stream outStream = await storageFile.OpenStreamForWriteAsync()) { if (outStream.CanSeek) outStream.SetLength(0); outStream.Write(stream.ToArray(), 0, (int)stream.Length); outStream.Flush(); outStream.Dispose(); } stream.Flush(); stream.Dispose(); await Windows.System.Launcher.LaunchFileAsync(storageFile); } } } internal class SfImageRenderer : ImageRenderer { public SfImageRenderer() { } protected override void Dispose(bool disposing) { this.Element.PropertyChanged -= OnElementPropertyChanged; base.Dispose(false); } } public class MailService : IMailService { public async void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream documentStream) { var emailMessage = new EmailMessage { Subject = subject, Body = messagebody }; StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile outFile = await local.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (Stream outStream = await outFile.OpenStreamForWriteAsync()) { outStream.Write(documentStream.ToArray(), 0, (int)documentStream.Length); } emailMessage.Attachments.Add(new EmailAttachment(fileName, outFile)); await EmailManager.ShowComposeNewEmailAsync(emailMessage); } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/Model/TicketInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "TicketInfoRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Xamarin.Forms; /// <summary> /// A class used to assign collection values for a Model properties /// </summary> public class TicketInfoRepository { #region GetTicketDetails /// <summary> /// Used to get added ItemsSource details /// </summary> /// <returns>returns added ticketDetails</returns> public ObservableCollection<TicketBookingInfo> GetDetails() { var ticketDetails = new ObservableCollection<TicketBookingInfo>(); return this.PopulateList(ticketDetails); } #endregion /// <summary> /// Used to add ItemsSource details /// </summary> /// <param name="items">observable collection type parameter named as items</param> /// <returns>returns the added items</returns> private ObservableCollection<TicketBookingInfo> PopulateList(ObservableCollection<TicketBookingInfo> items) { items = new ObservableCollection<TicketBookingInfo>(); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movie1.jpg", TheaterName = "ABC Cinemas Dolby Atmos", TheaterLocation = "No.15, 12th Main Road, Sector 1", Timing1 = "10:00 AM", Timing2 = "4:00 PM", MovieName = "AB-Team", Cast = "<NAME> | <NAME>" }); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movie2.jpg", TheaterName = "XYZ Theater 4K Dolby Atmos", TheaterLocation = "No.275, 3rd Cross Road, Area 27", Timing1 = "11:00 AM", Timing2 = "6:00 PM", MovieName = "Configuring 2", Cast = "Vera Farmiga | <NAME>" }); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movie3.jpg", TheaterName = "QWERTY Theater", TheaterLocation = "No.275, 3rd Cross Road, Sector North", Timing1 = "10:30 AM", MovieName = "Inside 2", Cast = "<NAME> | <NAME>" }); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movie4.jpg", TheaterName = "FYI Cinemas 4K", TheaterLocation = "No.15, 12th Main Road, Sector South", Timing1 = "3:00 PM", MovieName = "Safest House", Cast = "<NAME> | <NAME>" }); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movie5.jpg", TheaterName = "The Cinemas Dolby Digital", TheaterLocation = "No.275, 3rd Cross Road, Layout 71", Timing1 = "2:30 PM", Timing2 = "9:00 PM", MovieName = "Run All Day", Cast = "<NAME>on | <NAME>" }); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movie6.jpg", TheaterName = "SF Theater Dolby Atmos RDX", TheaterLocation = "North West Layout", Timing1 = "1:30 PM", Timing2 = "6:00 PM", MovieName = "<NAME>", Cast = "<NAME> | <NAME>" }); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movies7.jpg", TheaterName = "PVS Cinemas 4K Dolby Atmos", TheaterLocation = "No.15, 12th Main Road, Area 33", Timing1 = "3:30 PM", MovieName = "Clash Of The Queens", Cast = "Gemma Arteron | <NAME>" }); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movies8.jpg", TheaterName = "Grand Theater", TheaterLocation = "No.275, 3rd Cross Road, South Sector", Timing1 = "6:00 PM", MovieName = "A Run Among The TombStones", Cast = "Liam Neeson | <NAME>" }); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movies9.jpg", TheaterName = "Orion Cinemas Dolby Atmos RDX", TheaterLocation = "No.15, 12th Main Road, Area 152", Timing1 = "6:00 PM", Timing2 = "10:30 PM", MovieName = "Unkown Source", Cast = "Liam Neeson | <NAME>" }); items.Add(new TicketBookingInfo { MovieImage = "Popup_Movies10.jpg", TheaterName = "Elite Cinemas Dolby Atmos RDX", TheaterLocation = "No.275, 3rd Cross Road, Sector 77", Timing1 = "2:30 PM", Timing2 = "6:30 PM", MovieName = "AB-Team", Cast = "<NAME> | <NAME>" }); return items; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DocIO/MailMerge.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using System.Collections.Generic; #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class MailMerge : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton button; public MailMerge() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to create a letter format document by filling the data using Mail merge functionality of DocIO."; label.Lines = 0; label.Font = UIFont.SystemFontOfSize(15); label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 70); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 70); } this.AddSubview(label); button.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(5, 90, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 90, frameRect.Size.Width, 10); } button.TouchUpInside += OnButtonClicked; this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Creating a new document. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Letter Formatting.docx"); //Open Template document document.Open(inputStream, FormatType.Word2013); inputStream.Dispose(); List<Customer> source = new List<Customer>(); source.Add(new Customer("ALFKI", "<NAME>", "<NAME>", "Sales Representative", "Obere Str. 57", "Berlin", "12209", "Germany", "030-0074321", "030-0076545")); //source.Add(new Customer("ANATR", "<NAME>", "<NAME>", "Owner", "Avda. de la Constitución 2222", "México D.F.", "05021", "Mexico", "(5) 555-4729", "(5) 555-3745")); document.MailMerge.Execute(source); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("MailMerge.docx", "application/msword", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Frame; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } public class Customer { #region fields string m_customerID; string m_companyName; string m_contactName; string m_contactTitle; string m_address; string m_city; string m_postalCode; string m_country; string m_phone; string m_fax; #endregion #region properties public string CustomerID { get { return m_customerID; } set { m_customerID = value; } } public string CompanyName { get { return m_companyName; } set { m_companyName = value; } } public string ContactName { get { return m_contactName; } set { m_contactName = value; } } public string ContactTitle { get { return m_contactTitle; } set { m_contactTitle = value; } } public string Address { get { return m_address; } set { m_address = value; } } public string City { get { return m_city; } set { m_city = value; } } public string PostalCode { get { return m_postalCode; } set { m_postalCode = value; } } public string Country { get { return m_country; } set { m_country = value; } } public string Phone { get { return m_phone; } set { m_phone = value; } } public string Fax { get { return m_fax; } set { m_fax = value; } } #endregion #region constructor public Customer() { } public Customer(string customerID, string companyName, string contactName, string contactTitle, string address, string city, string postalCode, string country, string phone, string fax) { m_customerID = customerID; m_companyName = companyName; m_contactName = contactName; m_contactTitle = contactTitle; m_address = address; m_city = city; m_postalCode = postalCode; m_country = country; m_phone = phone; m_fax = fax; } #endregion } }<file_sep>/Forms/Rotator/Rotator/Samples/Rotator/Rotator.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using Xamarin.Forms; namespace SampleBrowser.SfRotator { public partial class Rotator : SampleView { public Rotator() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Phone || Device.RuntimePlatform == Device.UWP) { Rotator_Default rotator = new Rotator_Default(); this.Content = rotator.getContent(); this.PropertyView = rotator.getPropertyView(); } else if (Device.Idiom == TargetIdiom.Tablet) { Rotator_TabletView rotator_tab = new Rotator_TabletView(); this.Content = rotator_tab.getContent(); this.PropertyView = rotator_tab.getPropertyView(); } } } } <file_sep>/iOS/SampleBrowser/Samples/DataForm/Model/RecipientInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; using System.ComponentModel; namespace SampleBrowser { public enum AccountType { Savings, Current, Overdraft, CashCredit, LoanAccount, NRE, CardPayment } [Preserve (AllMembers = true)] class RecipientInfo : INotifyPropertyChanged, IDataErrorInfo { #region Fields private string accountNumber; private string accountNumber1; private string email; private double? amount = null; private string name; private string swift; private string password; private AccountType accountType; Regex emailRegex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); #endregion #region Constructor public RecipientInfo() { } #endregion #region Public Properties [Display(ShortName = "Account No.")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter account number.")] public string AccountNumber { get { return this.accountNumber; } set { if (value != AccountNumber) { this.accountNumber = value; RaisePropertyChanged("AccountNumber"); } } } [Display(ShortName = "Re-Enter Account No.")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please re-enter the account number.")] public string AccountNumber1 { get { return this.accountNumber1; } set { if (value != AccountNumber1) { this.accountNumber1 = value; RaisePropertyChanged("AccountNumber1"); } } } [Display(ShortName = "Account Type")] public AccountType AccountType { get { return accountType; } set { accountType = value; RaisePropertyChanged("AccountType"); } } [Display(Order = 0, ShortName = "SWIFT Code", Prompt = "Enter 8 or 11 upper case letters")] [RegularExpression("^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$", ErrorMessage = "SWIFT code should be 8 or 11 upper case letters.")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the SWIFT code.")] public string SWIFT { get { return this.swift; } set { this.swift = value; RaisePropertyChanged("SWIFT"); } } [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the name.")] public string Name { get { return this.name; } set { this.name = value; RaisePropertyChanged("Name"); } } [Display(ShortName = "Email ID")] public string Email { get { return email; } set { email = value; this.RaisePropertyChanged("Email"); } } [Display(ShortName = "Transfer amount")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the amount.")] public double? Amount { get { return amount; } set { amount = value; RaisePropertyChanged("Amount"); } } [Display(ShortName = "Transaction password", Prompt = "Enter password")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the password.")] [DataType(DataType.Password)] public string Password { get { return this.password; } set { this.password = value; RaisePropertyChanged("Password"); } } #endregion public void RaisePropertyChanged(string propName) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } public event PropertyChangedEventHandler PropertyChanged; [Display(AutoGenerateField = false)] public string Error { get { return string.Empty; } } public string this[string columnName] { get { if (columnName == "AccountNumber" && !string.IsNullOrEmpty(AccountNumber)) { var accountNumberLength = AccountNumber.ToString().Length; if (accountNumberLength > 10 || accountNumberLength < 5) return "Account number length should be between 5 to 10."; } else if (columnName == "AccountNumber1" && !string.IsNullOrEmpty(AccountNumber1)) { var accountNumberLength = AccountNumber1.ToString().Length; if (AccountNumber1 != AccountNumber) return "Account numbers do not match."; else if (accountNumberLength > 10 || accountNumberLength < 5) return "Account number length should be between 5 to 10."; } else if (columnName == "Amount") { if (Amount <= 0) return "Amount should be more than zero."; } else if (columnName == "Email") { if (string.IsNullOrEmpty(Email)) return string.Empty; return !(emailRegex.IsMatch(Email)) ? "Email ID not in correct format." : null; } else if (columnName == "Password") { if (string.IsNullOrEmpty(Password)) return string.Empty; if (Password != "<PASSWORD>") return "Password is incorrect"; } return string.Empty; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/PDF/Conformance.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Interactive; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class Conformance : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label1; UILabel conformanceLevellabel; UIButton button ; private readonly IList<string> layoutList = new List<string>(); string selectedLayout; UIButton layoutDoneButton; UIButton layoutButton; UIPickerView layoutPicker; public Conformance() { this.layoutList.Add((NSString)"PDF/A-1b"); this.layoutList.Add((NSString)"PDF/A-2b"); this.layoutList.Add((NSString)"PDF/A-3b"); label1 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; layoutDoneButton = new UIButton(); layoutButton = new UIButton(); conformanceLevellabel = new UILabel(); layoutPicker = new UIPickerView(); this.AddSubview(layoutButton); this.AddSubview(layoutPicker); this.AddSubview(layoutDoneButton); selectedLayout = "PDF/A-1b"; } void LoadAllowedTextsLabel() { label1.Frame = frameRect; label1.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label1.Text = "This sample demonstrates various PDF conformance support in Essential PDF. Essential PDF provides support for PDF/A-1b, PDF/A-2b, and PDF/A-3b conformance."; label1.Font = UIFont.SystemFontOfSize(15); label1.Lines = 0; label1.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label1.Font = UIFont.SystemFontOfSize(18); label1.Frame = new CGRect(0, 12, frameRect.Location.X + frameRect.Size.Width, 50); } else { label1.Frame = new CGRect(frameRect.Location.X, 12, frameRect.Size.Width, 50); } this.AddSubview(label1); #region Conformance Level Label if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { conformanceLevellabel.Font = UIFont.SystemFontOfSize(18); conformanceLevellabel.Frame = new CGRect(10, 45, frameRect.Location.X + frameRect.Size.Width - 20, 50); layoutButton.Frame = new CGRect(10, 95, frameRect.Location.X + frameRect.Size.Width - 20, 50); } else { conformanceLevellabel.Frame = new CGRect(10, 50, frameRect.Location.X + frameRect.Size.Width - 20, 50); layoutButton.Frame = new CGRect(10, 100, frameRect.Location.X + frameRect.Size.Width - 20, 50); } //filter Label conformanceLevellabel.TextColor = UIColor.Black; conformanceLevellabel.BackgroundColor = UIColor.Clear; conformanceLevellabel.Text = "Select Conformance Level Option :"; conformanceLevellabel.TextAlignment = UITextAlignment.Left; conformanceLevellabel.Font = UIFont.FromName("Helvetica", 16f); //filter button layoutButton.SetTitle("PDF/A-1b", UIControlState.Normal); layoutButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; layoutButton.BackgroundColor = UIColor.Clear; layoutButton.SetTitleColor(UIColor.Black, UIControlState.Normal); layoutButton.Hidden = false; layoutButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; layoutButton.Layer.BorderWidth = 4; layoutButton.Layer.CornerRadius = 8; layoutButton.Font = UIFont.FromName("Helvetica", 16f); layoutButton.TouchUpInside += ShowFilterPicker; #endregion #region Layout Picker //filterpicker PickerModel filterPickermodel = new PickerModel(this.layoutList); filterPickermodel.PickerChanged += (sender, e) => { this.selectedLayout = e.SelectedValue; layoutButton.SetTitle(selectedLayout, UIControlState.Normal); }; layoutPicker.ShowSelectionIndicator = true; layoutPicker.Hidden = true; layoutPicker.Model = filterPickermodel; layoutPicker.BackgroundColor = UIColor.White; layoutDoneButton.SetTitle("Done\t", UIControlState.Normal); layoutDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; layoutDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); layoutDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); layoutDoneButton.Hidden = true; layoutDoneButton.TouchUpInside += HideFilterPicker; layoutPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 20, this.Frame.Size.Width, this.Frame.Size.Height / 3); layoutDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 20, this.Frame.Size.Width, 40); #endregion button.SetTitle("Generate PDF", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 70, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 70, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { PdfDocument document = null; int index = layoutList.IndexOf(selectedLayout); if (index == 0) { //Create a new PDF document document = new PdfDocument(PdfConformanceLevel.Pdf_A1B); } else if (index == 1) { document = new PdfDocument(PdfConformanceLevel.Pdf_A2B); } else if (index == 2) { document = new PdfDocument(PdfConformanceLevel.Pdf_A3B); Stream imgStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Products.xml"); PdfAttachment attachment = new PdfAttachment("PDF_A.xml", imgStream); attachment.Relationship = PdfAttachmentRelationship.Alternative; attachment.ModificationDate = DateTime.Now; attachment.Description = "PDF_A"; attachment.MimeType = "application/xml"; document.Attachments.Add(attachment); } PdfPage page = document.Pages.Add(); //Create font Stream arialFontStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.arial.ttf"); Stream imageStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.AdventureCycle.jpg"); PdfFont font = new PdfTrueTypeFont(arialFontStream, 14); //Create PDF graphics for the page. PdfGraphics graphics = page.Graphics; //Load the image from the disk. PdfImage img = PdfImage.FromStream(imageStream); //Draw the image in the specified location and size. graphics.DrawImage(img, new RectangleF(150, 30, 200, 100)); PdfTextElement textElement = new PdfTextElement("Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based," + " is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, " + "European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional" + " sales teams are located throughout their market base.") { Font = font }; PdfLayoutResult layoutResult = textElement.Draw(page, new RectangleF(0, 150, page.GetClientSize().Width, page.GetClientSize().Height)); MemoryStream stream = new MemoryStream(); //Save the PDF dcoument. document.Save(stream); //Close the PDF document. document.Close(); stream.Position = 0; if (stream != null) { SaveiOS iosSave = new SaveiOS(); iosSave.Save("PDF_Ab.pdf", "application/pdf", stream); } } void ShowFilterPicker(object sender, EventArgs e) { layoutDoneButton.Hidden = false; layoutPicker.Hidden = false; this.BecomeFirstResponder(); } void HideFilterPicker(object sender, EventArgs e) { layoutDoneButton.Hidden = true; layoutPicker.Hidden = true; this.BecomeFirstResponder(); layoutButton.Hidden = false; } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } } <file_sep>/Forms/Calendar/Calendar/Samples/CalendarGettingStarted/Views/CalendarGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="Configuration_Default.xaml.cs" company="Syncfusion"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfCalendar { using System; using System.Collections.Generic; using SampleBrowser.Core; using Syncfusion.SfCalendar.XForms; using Xamarin.Forms; /// <summary> /// Configuration Default /// </summary> public partial class CalendarGettingStarted : SampleView { /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.SfCalendar.CalendarGettingStarted"/> class. /// </summary> public CalendarGettingStarted() { this.InitializeComponent(); } } } <file_sep>/Android/SampleBrowser/Samples/PopupLayout/Popup Customizations/PopupCustomizations.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Syncfusion.Android.PopupLayout; using Android.Graphics.Drawables; using System.Threading.Tasks; using Android.Util; namespace SampleBrowser { public class PopupCustomizations : SamplePage { SfPopupLayout initialPopup; SfPopupLayout animationPopup; FrameLayout mainView; List<TableItem> items; internal static ListView movieList; ListView theatreList; LinearLayout dateSelectionView; LinearLayout dateView; internal static RelativeLayout secondPage; TextView dayLabel; TextView dateLabel; Context cont; float density; bool pageExited = false; public override View GetSampleContent(Context context) { cont = context; density = cont.Resources.DisplayMetrics.Density; CreateMainView(); CreateMovieSelectionPage(); CreateDateSelectionPage(); (context as AllControlsSamplePage).ActionBar.CustomView.SetBackgroundColor(Color.DarkGray); (context as AllControlsSamplePage).ActionBar.SetBackgroundDrawable(new ColorDrawable(Color.DarkGray)); TheaterAdapter.counter = 0; return mainView; } private void CreateDateSelectionPage() { secondPage = new RelativeLayout(cont); LinearLayout secondPageContent = new LinearLayout(cont); secondPageContent.Orientation = Orientation.Vertical; secondPage.Id = 2; TouchObserverView rel = new TouchObserverView(cont); rel.Alpha = 0.8f; rel.ViewAttachedToWindow += async delegate { for (int i = 0; i < 3; i++) { if (pageExited) return; if (TheaterAdapter.counter == 0) { rel.Visibility = ViewStates.Visible; CreateAnimationPopup(); animationPopup.Show(10, 0); TheaterAdapter.counter++; await Task.Delay(700); } else if (TheaterAdapter.counter == 1) { animationPopup.Dismiss(); await Task.Delay(700); rel.Visibility = ViewStates.Visible; var image = new ImageView(cont); animationPopup.PopupView.AnimationMode = AnimationMode.SlideOnLeft; image.SetImageResource(Resource.Drawable.Popup_TheatrInfo); animationPopup.PopupView.ContentView = image; animationPopup.Show((int)(cont.Resources.DisplayMetrics.WidthPixels / density - 40), 135); TheaterAdapter.counter++; await Task.Delay(700); } else if (TheaterAdapter.counter == 2) { animationPopup.Dismiss(); await Task.Delay(700); rel.Visibility = ViewStates.Visible; var image = new ImageView(cont); animationPopup.PopupView.AnimationMode = AnimationMode.SlideOnTop; image.SetImageResource(Resource.Drawable.Popup_SelectSeats); animationPopup.PopupView.ContentView = image; animationPopup.Show(10, 80); TheaterAdapter.counter++; await Task.Delay(700); rel.Visibility = ViewStates.Gone; animationPopup.StaysOpen = false; animationPopup.Dismiss(); } if (TheaterAdapter.counter >= 4) { animationPopup.StaysOpen = false; animationPopup.Dismiss(); } } animationPopup.StaysOpen = false; rel.Visibility = ViewStates.Gone; animationPopup.Dismiss(); TheaterAdapter.counter = 0; }; dateSelectionView = new LinearLayout(cont); dateSelectionView.Orientation = Orientation.Horizontal; dateSelectionView.AddView(CreateDateView(0, 0), cont.Resources.DisplayMetrics.WidthPixels / 7, ViewGroup.LayoutParams.MatchParent); dateSelectionView.AddView(CreateDateView(1), cont.Resources.DisplayMetrics.WidthPixels / 7, ViewGroup.LayoutParams.MatchParent); dateSelectionView.AddView(CreateDateView(2), cont.Resources.DisplayMetrics.WidthPixels / 7, ViewGroup.LayoutParams.MatchParent); dateSelectionView.AddView(CreateDateView(3), cont.Resources.DisplayMetrics.WidthPixels / 7, ViewGroup.LayoutParams.MatchParent); dateSelectionView.AddView(CreateDateView(4), cont.Resources.DisplayMetrics.WidthPixels / 7, ViewGroup.LayoutParams.MatchParent); dateSelectionView.AddView(CreateDateView(5), cont.Resources.DisplayMetrics.WidthPixels / 7, ViewGroup.LayoutParams.MatchParent); dateSelectionView.AddView(CreateDateView(6), cont.Resources.DisplayMetrics.WidthPixels / 7, ViewGroup.LayoutParams.MatchParent); theatreList = new ListView(cont); PopulateTheatreList(); theatreList.Adapter = new TheaterAdapter((cont as AllControlsSamplePage), items, mainView); theatreList.ItemClick += MovieList_ItemClick; theatreList.ViewDetachedFromWindow += TheatreList_ViewDetachedFromWindow; secondPageContent.AddView(dateSelectionView, ViewGroup.LayoutParams.MatchParent, (int)(62 * density)); secondPageContent.AddView(theatreList, ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); secondPage.AddView(secondPageContent, ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); secondPage.AddView(rel, ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); rel.SetBackgroundColor(Color.Black); } private void TheatreList_ViewDetachedFromWindow(object sender, View.ViewDetachedFromWindowEventArgs e) { if (animationPopup != null) { animationPopup.Dismiss(); animationPopup.Visibility = ViewStates.Gone; } pageExited = true; } public override void Destroy() { base.Destroy(); theatreList.ViewDetachedFromWindow -= TheatreList_ViewDetachedFromWindow; dateView.Click -= DateView_Click; movieList.ViewAttachedToWindow -= ListViewLoaded; movieList.ViewDetachedFromWindow -= MovieList_ViewDetachedFromWindow; movieList.ItemClick -= MovieList_ItemClick; } private void CreateAnimationPopup() { var image = new ImageView(cont); image.SetImageResource(Resource.Drawable.Popup_DateSelected); animationPopup = new SfPopupLayout(cont); animationPopup.PopupView.AnimationMode = AnimationMode.Zoom; animationPopup.PopupView.ShowHeader = false; animationPopup.PopupView.ShowFooter = false; animationPopup.PopupView.ContentView = image; animationPopup.PopupView.HeightRequest = 200; animationPopup.PopupView.WidthRequest = 200; animationPopup.PopupView.SetBackgroundColor(Color.Transparent); animationPopup.PopupView.SetBackgroundColor(Color.Transparent); animationPopup.PopupView.ContentView.SetBackgroundColor(Color.Transparent); animationPopup.PopupView.PopupStyle.BorderColor = Color.Transparent; } private void PopulateTheatreList() { items = new List<TableItem>(); items.Add(new TableItem() { Heading = "ABC Cinemas Dolby Atmos", SubHeading = "No.15, 12th Main Road, Sector 1", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="10:00 AM",Timing2="4:00 PM" }); items.Add(new TableItem() { Heading = "XYZ Theater 4K Dolby Atmos", SubHeading = "No.275, 3rd Cross Road,Area 27", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="11:00 AM",Timing2="6:00 PM" }); items.Add(new TableItem() { Heading = "QWERTY Theater", SubHeading = "No.275, 3rd Cross Road,Sector North", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="10:30 AM"}); items.Add(new TableItem() { Heading = "FYI Cinemas 4K", SubHeading = "No.15, 12th Main Road,Sector South", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="3:00 PM" ,}); items.Add(new TableItem() { Heading = "The Cinemas Dolby Digital", SubHeading = "No.275, 3rd Cross Road,Layout 71", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="2:30 PM" ,Timing2="9:00 PM"}); items.Add(new TableItem() { Heading = "SF Theater Dolby Atmos RDX", SubHeading = "North West Layout", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="1:30 PM" ,Timing2="6:00 PM"}); items.Add(new TableItem() { Heading = "Grid Cinemas 4K Dolby Atmos", SubHeading = "No.15, 12th Main Road,Area 33", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="3:30 PM"}); items.Add(new TableItem() { Heading = "Grand Theater", SubHeading = "No.275, 3rd Cross Road,South Sector", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="6:00 PM"}); items.Add(new TableItem() { Heading = "Layout Cinemas Dolby Atmos RDX", SubHeading = "No.15, 12th Main Road,Area 152", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="6:00 PM" ,Timing2="10:30 PM"}); items.Add(new TableItem() { Heading = "Xamarin Cinemas Dolby Atmos RDX", SubHeading = "No.275, 3rd Cross Road,Sector 77", ImageResourceId = Resource.Drawable.Popup_Info, Timing1="2:30 PM" ,Timing2="6:30 PM" }); } private LinearLayout CreateDateView(int date, object selected = null) { dateView = new LinearLayout(cont); if (selected == null) dateView.SetBackgroundColor(Color.White); else dateView.SetBackgroundColor(Color.ParseColor("#007CEE")); dateView.Click += DateView_Click; dateView.Orientation = Orientation.Vertical; dayLabel = new TextView(cont); dayLabel.SetBackgroundColor(Color.Transparent); dayLabel.Text = DateTime.Now.AddDays(date).DayOfWeek.ToString().Substring(0, 3).ToUpper(); if (selected == null) dayLabel.SetTextColor(Color.Argb(54, 00, 00, 00)); else dayLabel.SetTextColor(Color.White); dayLabel.SetTypeface(Typeface.DefaultBold, TypefaceStyle.Bold); dayLabel.SetTextSize(Android.Util.ComplexUnitType.Dip, 12); dayLabel.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; dateLabel = new TextView(cont); dateLabel.SetBackgroundColor(Color.Transparent); dateLabel.Text = DateTime.Now.AddDays(date).Day.ToString(); dateLabel.TextAlignment = TextAlignment.Center; if (selected == null) dateLabel.SetTextColor(Color.Black); else dateLabel.SetTextColor(Color.White); dateLabel.SetTextSize(Android.Util.ComplexUnitType.Dip, 14); dateLabel.SetTypeface(Typeface.DefaultBold, TypefaceStyle.Bold); dateLabel.Gravity = GravityFlags.CenterHorizontal; dateView.AddView(dayLabel, ViewGroup.LayoutParams.MatchParent, (int)(31 * density)); dateView.AddView(dateLabel, ViewGroup.LayoutParams.MatchParent, (int)(31 * density)); return dateView; } private void DateView_Click(object sender, EventArgs e) { for (int i = 0; i < ((sender as LinearLayout).Parent as LinearLayout).ChildCount; i++) { // Remove selection color to other date views (((sender as LinearLayout).Parent as LinearLayout).GetChildAt(i) as LinearLayout).SetBackgroundColor(Color.White); ((((sender as LinearLayout).Parent as LinearLayout).GetChildAt(i) as LinearLayout).GetChildAt(0) as TextView).SetTextColor(Color.Argb(54, 00, 00, 00)); ((((sender as LinearLayout).Parent as LinearLayout).GetChildAt(i) as LinearLayout).GetChildAt(1) as TextView).SetTextColor(Color.Black); } ((sender as LinearLayout).GetChildAt(0) as TextView).SetTextColor(Color.White); ((sender as LinearLayout).GetChildAt(1) as TextView).SetTextColor(Color.White); (sender as LinearLayout).SetBackgroundColor(Color.ParseColor("#007CEE")); } private void CreateMovieSelectionPage() { movieList = new ListView(cont); movieList.ViewAttachedToWindow += ListViewLoaded; movieList.ViewDetachedFromWindow += MovieList_ViewDetachedFromWindow; movieList.Id = 1; PopulateMovieList(); movieList.Adapter = new MovieAdapter((cont as AllControlsSamplePage), items, mainView); movieList.ItemClick += MovieList_ItemClick; mainView.AddView(movieList); } private void MovieList_ViewDetachedFromWindow(object sender, View.ViewDetachedFromWindowEventArgs e) { if (initialPopup != null) { initialPopup.Dispose(); initialPopup = null; } } private void ListViewLoaded(object sender, View.ViewAttachedToWindowEventArgs e) { DisplayInitialPopup(); } private void CreateMainView() { mainView = new FrameLayout(cont); } private void PopulateMovieList() { items = new List<TableItem>(); items.Add(new TableItem() { Heading = "Longest Run", SubHeading = "<NAME> | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie1 }); items.Add(new TableItem() { Heading = "AA-Team", SubHeading = "<NAME> | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie2}); items.Add(new TableItem() { Heading = "Configuring 2", SubHeading = "Vera Farmigan | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie3}); items.Add(new TableItem() { Heading = "Inside Us 2", SubHeading = "<NAME> | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie4}); items.Add(new TableItem() { Heading = "Safer House", SubHeading = "<NAME> | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie5}); items.Add(new TableItem() { Heading = "Run All Day", SubHeading = "<NAME> | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie6}); items.Add(new TableItem() { Heading = "Code Red", SubHeading = "<NAME> | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie7}); items.Add(new TableItem() { Heading = "Clash Of The Dragons", SubHeading = "<NAME> | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie8}); items.Add(new TableItem() { Heading = "A Run Among The TombStones", SubHeading = "<NAME> | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie9}); items.Add(new TableItem() { Heading = "Error 404", SubHeading = "<NAME> | <NAME>", ImageResourceId = Resource.Drawable.Popup_Movie10}); } private void MovieList_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { var backbutton = ((((this.cont as AllControlsSamplePage).SettingsButton.Parent as RelativeLayout).GetChildAt(1) as LinearLayout).GetChildAt(0) as RelativeLayout).GetChildAt(0); backbutton.Click += backbutton_Click; } private void backbutton_Click(object sender, EventArgs e) { var child = this.mainView.GetChildAt(0); if (child.Id == 2) { this.mainView.RemoveView(child); if (this.mainView.IndexOfChild(PopupCustomizations.movieList) == -1) this.mainView.AddView(movieList); } } internal void DisplayInitialPopup() { if (pageExited) return; initialPopup = new SfPopupLayout(cont); initialPopup.PopupView.AppearanceMode = AppearanceMode.OneButton; initialPopup.PopupView.ShowFooter = true; initialPopup.PopupView.ShowCloseButton = false; initialPopup.PopupView.HeaderTitle = "Book tickets !"; initialPopup.PopupView.AcceptButtonText = "OK"; initialPopup.PopupView.PopupStyle.HeaderTextSize = 16; initialPopup.StaysOpen = true; TextView messageView = new TextView(this.cont); messageView.Text = "Click on the book button to start booking tickets"; messageView.SetTextColor(Color.Black); messageView.SetBackgroundColor(Color.White); messageView.TextSize = 14; initialPopup.PopupView.ContentView = messageView; initialPopup.PopupView.ContentView.SetPadding((int)(10 * density), (int)(10 * density), (int)(10 * density), (int)(10 * density)); initialPopup.PopupView.PopupStyle.CornerRadius = 3; initialPopup.PopupView.HeightRequest = 180; initialPopup.Show(); } } internal class TouchObserverView : View { public TouchObserverView(Context context) : base(context) { } public TouchObserverView(Context context, IAttributeSet attrs) : base(context, attrs) { } public TouchObserverView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { } public TouchObserverView(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes) { } protected TouchObserverView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } public override bool OnTouchEvent(MotionEvent e) { return true; } } }<file_sep>/Forms/DataForm/DataForm/Samples/DynamicFormPage/Helper/DynamicFormBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; using SampleBrowser.Core; using DataForm = Syncfusion.XForms.DataForm.SfDataForm; using Syncfusion.XForms.DataForm; using ComboBox = Syncfusion.XForms.ComboBox.SfComboBox; using Syncfusion.XForms.ComboBox; using SelectionChangedEventArgs = Syncfusion.XForms.ComboBox.SelectionChangedEventArgs; namespace SampleBrowser.SfDataForm { [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public class DynamicFormBehavior : Behavior<SampleView> { /// <summary> /// DataForm control to edit the data fields of any data object /// </summary> DataForm dataForm; /// <summary> /// ComboBox control to choose the data forms to view. /// </summary> ComboBox sfComboBox; /// <summary> /// Attaches to the superclass and then calls the OnAttachedTo method on this object. /// </summary> /// <param name="bindable">The bindable object to which the behavior was attached.</param> protected override void OnAttachedTo(SampleView bindable) { base.OnAttachedTo(bindable); sfComboBox = bindable.FindByName<ComboBox>("combo"); sfComboBox.SelectionChanged += SfComboBox_SelectionChanged; sfComboBox.SelectedItem = "Organization Form"; dataForm = bindable.FindByName<DataForm>("dataForm"); this.dataForm.LayoutManager = new DataFormLayoutCustomization(this.dataForm); } /// <summary> /// Occurs when selected item of the ComboBox is changed. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Event arguments of selectionchanged event.</param> private void SfComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.Value.Equals("Organization Form")) { dataForm.ContainerBackgroundColor = Color.Default; dataForm.ContainerType = ContainerType.Outlined; dataForm.DataObject = new OrganizationForm(); dataForm.ShowHelperText = true; } else if (e.Value.Equals("Employee Form")) { dataForm.ContainerBackgroundColor = Color.FromHex("#F3F7FF"); dataForm.ContainerType = ContainerType.Outlined; dataForm.DataObject = new EmployeeForm(); dataForm.ShowHelperText = false; } else { dataForm.ContainerBackgroundColor = Color.Default; dataForm.ContainerType = ContainerType.Filled; dataForm.DataObject = new Ecommerce(); dataForm.ShowHelperText = true; } } /// <summary> /// Calls the OnDetachingFrom method and then detaches from the superclass. /// </summary> /// <param name="bindable">The bindable object from which the behavior was detached.</param> protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); sfComboBox.SelectionChanged -= SfComboBox_SelectionChanged; dataForm = null; sfComboBox = null; } } internal class DataFormLayoutCustomization : DataFormLayoutManager { /// <summary> /// Initializes a new instance of the <see cref="DataFormLayoutManagerExt"/> class. /// </summary> /// <param name="dataform">DataForm control helps editing the data fields of any data object.</param> internal DataFormLayoutCustomization(DataForm dataform) : base(dataform) { } /// <summary> /// Gets left start offset for label. /// </summary> /// <param name="dataFormItem">DataFormItem of the label.</param> /// <returns>Returns left padding value for label.</returns> protected override int GetLeftPaddingForLabel(DataFormItem dataFormItem) { if (dataFormItem.Name.Equals("Trackhours")) { return Device.RuntimePlatform == Device.iOS ? 30 : Device.RuntimePlatform == Device.Android ? 30 : 40; } return base.GetLeftPaddingForLabel(dataFormItem); } /// <summary> /// Gets left start offset for editor. /// </summary> /// <param name="dataFormItem">DataFormItem of the editor.</param> /// <returns>Returns left padding value for editor.</returns> protected override int GetLeftPaddingForEditor(DataFormItem dataFormItem) { if (dataFormItem.Name.Equals("Trackhours")) { return Device.RuntimePlatform == Device.iOS ? 100 : Device.RuntimePlatform == Device.Android ? 100 : 150; } return base.GetLeftPaddingForEditor(dataFormItem); } } } <file_sep>/Forms/Chart/Chart/Samples/SemiPieChart/SemiPieSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class SemiPieSeriesViewModel { public ObservableCollection<ChartDataModel> SemiCircularData { get; set; } public SemiPieSeriesViewModel() { SemiCircularData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Product A", 14), new ChartDataModel("Product B", 54), new ChartDataModel("Product C", 23), new ChartDataModel("Product D", 53) }; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/ZoomingandPanning.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using CoreAnimation; #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class ZoomingandPanning : SampleView { SFChart chart; UILabel label; public ZoomingandPanning() { chart = new SFChart(); chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.Title.Text = new NSString("World Countries Details"); SFNumericalAxis primary = new SFNumericalAxis(); primary.ShowMajorGridLines = false; chart.PrimaryAxis = primary; chart.PrimaryAxis.Title.Text = new NSString("Literacy Rate"); SFNumericalAxis secondary = new SFNumericalAxis(); secondary.ShowMajorGridLines = false; secondary.Minimum = new NSNumber(-500); secondary.Maximum = new NSNumber(700); chart.SecondaryAxis = secondary; chart.SecondaryAxis.Title.Text = new NSString("GDP Growth Rate"); ChartViewModel dataModel = new ChartViewModel(); SFScatterSeries series = new SFScatterSeries(); series.ItemsSource = dataModel.ScatterDataZoomPan; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; chart.Series.Add(series); label = new UILabel(); label.Text = "Pinch to zoom or double tap and drag to select a region to zoom in"; label.Font = UIFont.FromName("Helvetica", 12f); label.TextAlignment = UITextAlignment.Center; label.LineBreakMode = UILineBreakMode.WordWrap; label.Lines = 2; label.BackgroundColor = UIColor.FromRGB(249, 249, 249); label.TextColor = UIColor.FromRGB(79, 86, 91); chart.AddChartBehavior(new SFChartZoomPanBehavior() { EnableSelectionZooming = true }); this.AddSubview(chart); CALayer topLine = new CALayer(); topLine.Frame = new CGRect(0, 0, UIScreen.MainScreen.ApplicationFrame.Width, 0.5); topLine.BackgroundColor = UIColor.FromRGB(178, 178, 178).CGColor; label.Layer.AddSublayer(topLine); this.AddSubview(label); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view == chart) chart.Frame = new CGRect(0, 0, Frame.Width, Frame.Height - 48); else if (view == label) label.Frame = new CGRect(0, Frame.Height - 32, Frame.Width, 40); else view.Frame = Frame; } base.LayoutSubviews(); } } }<file_sep>/Forms/NavigationDrawer/NavigationDrawer/Samples/NavigationDrawer_Main/NavigationDrawer_Main.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfNavigationDrawer { public partial class NavigationDrawer_Main : SampleView { public NavigationDrawer_Main() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Phone) { NavigationDrawer_Default navigationdrawer = new NavigationDrawer_Default(); this.Content = navigationdrawer.getContent(); this.PropertyView = navigationdrawer.getPropertyView(); if (Device.RuntimePlatform != Device.iOS) this.Padding = new Thickness(2, 0, 2, 0); } else if (Device.Idiom == TargetIdiom.Tablet || Device.Idiom == TargetIdiom.Desktop) { NavigationDrawer_Tablet autocompleteTab = new NavigationDrawer_Tablet(); this.Content = autocompleteTab.getContent(); this.PropertyView = autocompleteTab.getPropertyView(); if (Device.RuntimePlatform == Device.iOS) this.Padding = new Thickness(-15, -20, -10, 0); } } } } <file_sep>/Forms/Presentation/Presentation/Samples/HeaderAndFooter/HeaderAndFooter.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using SampleBrowser.Core; namespace SampleBrowser.Presentation { public partial class HeaderFooter : SampleView { public HeaderFooter() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { //if (!SampleBrowser.App.isUWP) { this.Description.FontSize = 13.5; } //else //{ // this.Description.FontSize = 13.5; // this.Content_2.FontSize = 13.5; //} this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.HeaderFooter.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.HeaderFooter.pptx"; #endif Assembly assembly = typeof(WriteProtection).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a existing PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Add footers into all the PowerPoint slides. foreach (ISlide slide in presentation.Slides) { //Enable a date and time footer in slide. slide.HeadersFooters.DateAndTime.Visible = true; //Enable a footer in slide. slide.HeadersFooters.Footer.Visible = true; //Sets the footer text. slide.HeadersFooters.Footer.Text = "Footer"; //Enable a slide number footer in slide. slide.HeadersFooters.SlideNumber.Visible = true; } //Add header into first slide notes page. //Add a notes slide to the slide. INotesSlide notesSlide = presentation.Slides[0].AddNotesSlide(); //Enable a header in notes slide. notesSlide.HeadersFooters.Header.Visible = true; //Sets the header text. notesSlide.HeadersFooters.Header.Text = "Header"; MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("HeaderFooterSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("HeaderFooterSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/FilterViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace SampleBrowser { public class FilterViewModel : INotifyPropertyChanged { public FilterViewModel() { this.SetRowstoGenerate(100); } #region Filtering internal delegate void FilterChanged(); internal FilterChanged filtertextchanged; #region Fields private string filtertext; private string selectedcolumn = "All Columns"; private string selectedcondition = "Equals"; #endregion #region Property public string FilterText { get { return filtertext; } set { filtertext = value; OnFilterTextChanged(); RaisePropertyChanged("FilterText"); } } public string SelectedCondition { get { return selectedcondition; } set { selectedcondition = value; } } public string SelectedColumn { get { return selectedcolumn; } set { selectedcolumn = value; } } #endregion void OnFilterTextChanged() { filtertextchanged(); } private bool MakeStringFilter(BookInfo o, string option, string condition) { var value = o.GetType().GetProperty(option); var exactValue = value.GetValue(o, null); exactValue = exactValue.ToString().ToLower(); string text = FilterText.ToLower(); var methods = typeof(string).GetMethods(); if (methods.Any()) { if (condition == "Contains") { var methodInfo = methods.FirstOrDefault(method => method.Name == condition); bool result1 = (bool)methodInfo.Invoke(exactValue, new object[] { text }); return result1; } else if (exactValue.ToString() == text.ToString()) { bool result1 = String.Equals(exactValue.ToString(), text.ToString()); if (condition == "Equals") return result1; else if (condition == "NotEquals") return false; } else if (condition == "Not Equals") { return true; } return false; } else return false; } private bool MakeNumericFilter(BookInfo o, string option, string condition) { var value = o.GetType().GetProperty(option); var exactValue = value.GetValue(o, null); double res; bool checkNumeric = double.TryParse(exactValue.ToString(), out res); if (checkNumeric) { switch (condition) { case "Equals": try { if (exactValue.ToString() == FilterText) { if (Convert.ToDouble(exactValue) == (Convert.ToDouble(FilterText))) return true; } } catch (Exception e) { Console.WriteLine(e); } break; case "Not Equals": try { if (Convert.ToDouble(FilterText) != Convert.ToDouble(exactValue)) return true; } catch (Exception e) { Console.WriteLine(e); } break; } } return false; } public bool FilerRecords(object o) { double res; bool checkNumeric = double.TryParse(FilterText, out res); var item = o as BookInfo; if (item != null && FilterText.Equals("")) { return true; } else { if (item != null) { if (checkNumeric && !SelectedColumn.Equals("All Columns") && SelectedCondition != "Contains") { bool result = MakeNumericFilter(item, SelectedColumn, SelectedCondition); return result; } else if (SelectedColumn.Equals("All Columns")) { if (item.BookName.ToLower().Contains(FilterText.ToLower()) || item.Country.ToLower().Contains(FilterText.ToLower()) || item.FirstName.ToString().ToLower().Contains(FilterText.ToLower()) || item.LastName.ToString().ToLower().Contains(FilterText.ToLower()) || item.CustomerID.ToString().ToLower().Contains(FilterText.ToLower()) || item.Price.ToString().ToLower().Contains(FilterText.ToLower()) || item.BookID.ToString().ToLower().Contains(FilterText.ToLower())) return true; return false; } else { // if (SelectedCondition == null || SelectedCondition.Equals("NotEquals") || SelectedCondition.Equals("Equals")) // SelectedCondition = "Contains"; bool result = MakeStringFilter(item, SelectedColumn, SelectedCondition); return result; } } } return false; } #endregion #region ItemsSource private List<BookInfo> bookInfo; public List<BookInfo> BookInfo { get { return bookInfo; } set { this.bookInfo = value; } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { BookRepository bookrepository = new BookRepository(); bookInfo = bookrepository.GetBookDetails(count); } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/NavigationDrawer/MainPageView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfNavigationDrawer.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class MainPageView : UIView { public UIView content; UIView background; UITableView maintable; public string[] tableItems; public string[] contentItems; UILabel headerContentLabel; UILabel textBlockLabel1; public MainPageView (CGRect bounds) { headerContentLabel = new UILabel (); this.BackgroundColor = UIColor.FromRGB(49,173,225); this.Frame = new CGRect (0, 0, bounds.Width, bounds.Height); content =new UIView(new CGRect(0,0,this.Frame.Width,this.Frame.Height)); background=new UIView(new CGRect(0,50,this.Frame.Width,this.Frame.Height+72)); background.BackgroundColor = UIColor.White; setvalue1 (0); this.Add(background); background.Add(content); headerContentLabel.Frame =new CGRect ((bounds.Width/2)-100, 10, 200, 30); headerContentLabel.Text="Home"; headerContentLabel.TextColor = UIColor.White; headerContentLabel.TextAlignment = UITextAlignment.Center; this.AddSubview (headerContentLabel); } public MainPageView () { } public void setvalue1(int index) { foreach(UIView sub in this.Subviews) { if(sub==content) sub.RemoveFromSuperview(); } content.RemoveFromSuperview (); content =new UIView(new CGRect(0,0,this.Frame.Width,this.Frame.Height)); if (index == 0) { headerContentLabel.Text = "Home"; content.BackgroundColor = UIColor.White; textBlockLabel1 = new UILabel (); textBlockLabel1.Frame = new CGRect (15, 10, content.Frame.Width-20, 300); textBlockLabel1.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus. Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet. Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula. Lorem tortor neque, purus taciti quis id. Elementum integer orci accumsan minim phasellus vel."; textBlockLabel1.LineBreakMode = UILineBreakMode.WordWrap; textBlockLabel1.TextAlignment = UITextAlignment.Justified; textBlockLabel1.Lines = 0; textBlockLabel1.Font = UIFont.FromName ("Helvetica", 15f); content.AddSubview (textBlockLabel1); } else if (index == 1) { headerContentLabel.Text = "Profile"; content.BackgroundColor = UIColor.White; UILabel usernameLabel = new UILabel (); usernameLabel.Frame =new CGRect ((this.Frame.Width/2), 20, 200, 30); usernameLabel.Text="<NAME>"; usernameLabel.TextAlignment = UITextAlignment.Left; content.AddSubview (usernameLabel); UILabel userageLabel = new UILabel (); userageLabel.Frame =new CGRect ((this.Frame.Width/2), 45, 200, 30); userageLabel.Text="Age 30"; userageLabel.Font = UIFont.FromName ("Helvetica", 18f); userageLabel.TextAlignment = UITextAlignment.Left; content.AddSubview (userageLabel); UILabel emptyLabel = new UILabel (); emptyLabel.Frame =new CGRect (10, 120, this.Frame.Width-20, 1); emptyLabel.BackgroundColor = UIColor.Gray; content.AddSubview (emptyLabel); UIImageView userImgLabel=new UIImageView(); userImgLabel.Frame =new CGRect ((this.Frame.Width/2)-100, 10, 80, 80); userImgLabel.Image = new UIImage ("Images/User.png"); content.Add (userImgLabel); UILabel commentLabel = new UILabel (); commentLabel.Frame =new CGRect (20, 130, this.Frame.Width-40, 200); commentLabel.Text="It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout." + " The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters. \n\nWhen looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters." + "\n\n <NAME>"; commentLabel.Font = UIFont.FromName ("Helvetica", 15f); commentLabel.LineBreakMode = UILineBreakMode.WordWrap; commentLabel.Lines = 0; content.AddSubview (commentLabel); }else if (index == 2) { headerContentLabel.Text = "Inbox"; maintable = new UITableView (new CGRect (0, 0, this.Frame.Width, this.Frame.Height)); // defaults to Plain style if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { tableItems = new string[] { "John", "Caster", "Joey", "Xavier", "Gonzalez", "Rodriguez", "Ruben" ,"Keven","Walton"}; contentItems = new string[] {"Hi John, See you at 7AM", "Hi Caster, See you at 9AM", "Hi Joey, See you at 11AM", "Hi Xavier, See you at 12PM", "Hi Gonzalez, See you at 1PM", "Hi Rodriguez, See you at 2PM", "Hi Ruben, See you at 4PM","Hi Keven, See you at 5PM","Hi Walton, See you at 7PM" }; } else { tableItems = new string[] { "John", "Caster", "Joey", "Xavier", "Gonzalez", "Rodriguez", "Ruben" }; contentItems = new string[] {"Hi John, See you at 10AM", "Hi Caster, See you at 11AM", "Hi Joey, See you at 1PM", "Hi Xavier, See you at 2PM", "Hi Gonzalez, See you at 3PM", "Hi Rodriguez, See you at 4PM", "Hi Ruben, See you at 6PM" }; } TableSource tablesource = new TableSource (tableItems, contentItems); tablesource.customise = true; maintable.Source = tablesource; content.Add (maintable); } else if (index == 3) { headerContentLabel.Text = "Outbox"; maintable = new UITableView (new CGRect (0, 0, this.Frame.Width, this.Frame.Height)); // defaults to Plain style if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { tableItems = new string[] { "John", "Caster", "Joey", "Xavier", "Gonzalez", "Rodriguez", "Ruben" ,"Keven","Walton"}; contentItems = new string[] {"Hi John, See you at 7AM", "Hi Caster, See you at 9AM", "Hi Joey, See you at 11AM", "Hi Xavier, See you at 12PM", "Hi Gonzalez, See you at 1PM", "Hi Rodriguez, See you at 2PM", "Hi Ruben, See you at 4PM","Hi Keven, See you at 5PM","Hi Walton, See you at 7PM" }; } else { tableItems = new string[] { "John", "Caster", "Joey", "Xavier", "Gonzalez", "Rodriguez", "Ruben" }; contentItems = new string[] {"Hi John, See you at 10AM", "Hi Caster, See you at 11AM", "Hi Joey, See you at 1PM", "Hi Xavier, See you at 2PM", "Hi Gonzalez, See you at 3PM", "Hi Rodriguez, See you at 4PM", "Hi Ruben, See you at 6PM" }; } TableSource tablesource = new TableSource (tableItems, contentItems); tablesource.customise = true; maintable.Source = tablesource; content.Add (maintable); }else if (index == 4) { headerContentLabel.Text = "Sent"; maintable = new UITableView (new CGRect (0, 0, this.Frame.Width, this.Frame.Height)); // defaults to Plain style if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { tableItems = new string[] { "John", "Caster", "Joey", "Xavier", "Gonzalez", "Rodriguez", "Ruben" ,"Keven","Walton"}; contentItems = new string[] {"Hi John, See you at 7AM", "Hi Caster, See you at 9AM", "Hi Joey, See you at 11AM", "Hi Xavier, See you at 12PM", "Hi Gonzalez, See you at 1PM", "Hi Rodriguez, See you at 2PM", "Hi Ruben, See you at 4PM","Hi Keven, See you at 5PM","Hi Walton, See you at 7PM" }; } else { tableItems = new string[] { "John", "Caster", "Joey", "Xavier", "Gonzalez", "Rodriguez", "Ruben" }; contentItems = new string[] {"Hi John, See you at 10AM", "Hi Caster, See you at 11AM", "Hi Joey, See you at 1PM", "Hi Xavier, See you at 2PM", "Hi Gonzalez, See you at 3PM", "Hi Rodriguez, See you at 4PM", "Hi Ruben, See you at 6PM" }; } TableSource tablesource = new TableSource (tableItems, contentItems); tablesource.customise = true; maintable.Source = tablesource; content.Add (maintable); } else if (index == 5) { headerContentLabel.Text = "Trash"; maintable = new UITableView (new CGRect (0, 0, this.Frame.Width, this.Frame.Height)); // defaults to Plain style if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { tableItems = new string[] { "John", "Caster", "Joey", "Xavier", "Gonzalez", "Rodriguez", "Ruben" ,"Keven","Walton"}; contentItems = new string[] {"Hi John, See you at 7AM", "Hi Caster, See you at 9AM", "Hi Joey, See you at 11AM", "Hi Xavier, See you at 12PM", "Hi Gonzalez, See you at 1PM", "Hi Rodriguez, See you at 2PM", "Hi Ruben, See you at 4PM","Hi Keven, See you at 5PM","Hi Walton, See you at 7PM" }; } else { tableItems = new string[] { "John", "Caster", "Joey", "Xavier", "Gonzalez", "Rodriguez", "Ruben" }; contentItems = new string[] {"Hi John, See you at 10AM", "Hi Caster, See you at 11AM", "Hi Joey, See you at 1PM", "Hi Xavier, See you at 2PM", "Hi Gonzalez, See you at 3PM", "Hi Rodriguez, See you at 4PM", "Hi Ruben, See you at 6PM" }; } TableSource tablesource = new TableSource (tableItems, contentItems); tablesource.customise = true; maintable.Source = tablesource; content.Add (maintable); } background.Add(content); } } }<file_sep>/iOS/SampleBrowser/Samples/Barcode/readme.md Barcode provides a perfect approach to encode texts by using the supported symbol types that comprises one dimensional and two dimensional barcodes. The basic structure of a barcode consists of one or more data characters, optionally one or two check characters, a start pattern as well as a stop pattern. The following samples are available for Barcode control to demonstrate the functionalities of each feature: | Sample | Description | | ------ | ----------- | | [QR Barcode](QRBarcode.cs) | QR Code is a two dimensional symbology that is used in automotive industry. | | [DataMatrix Barcode](DataMatrixBarcode.cs) | DataMatrix symbology is widely used in printed media such as labels and letters. | | [CodaBar Barcode](CodaBarBarcode.cs) | Codabar is a discrete numeric symbology that is used in libraries and information processing applications. | | [Code11 Barcode](Code11Barcode.cs) | Code11 symbology is used mainly for labeling the telecommunications equipment. | | [Upc Barcode](UpcBarcode.cs) | Upc barcode is mainly used for coding pharmaceuticals, cosmetics and dietetics. | | [Code32 Barcode](Code32Barcode.cs) | Code32 is mainly used for coding pharmaceuticals, cosmetics and dietetics. | | [Code39 Barcode](Code39Barcode.cs) | Code39 is a symbology of Barcode that encodes alphanumeric characters into a series of bars. | | [Code39 Extended Barcode](Code39ExtendedBarcode.cs) | Code39 extended symbology is an extended version of Code39 that supports full ASCII character set. | | [Code93 Barcode](Code93Barcode.cs) | Code93 represents the full ASCII character set by using the combination of 2 characters. | | [Code93 Extended Barcode](Code93ExtendedBarcode.cs) | Code93 extended is designed to complement and improve upon Code 39. | | [Code128A Barcode](Code128ABarcode.cs) | Code128A includes all the standard upper case alphanumeric characters, punctuation, and special characters. | | [Code128B Barcode](Code128BBarcode.cs) | Code128B includes all the standard upper and lower case alphanumeric characters, punctuation and special characters. | | [Code128C Barcode](Code128CBarcode.cs) | Code128C includes a set of 100 digit pairs from 00 to 99 inclusive, as well as three special characters. |<file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/DataVirtualizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DataVirtualizationViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for DataVirtualization sample. /// </summary> public class DataVirtualizationViewModel { #region Field [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private VirtualizingCollectionView viewSource; #endregion /// <summary> /// Initializes a new instance of the DataVirtualizationViewModel class. /// </summary> public DataVirtualizationViewModel() { var repository = new EmployeeInfoRepository(); this.viewSource = new GridVirtualizingCollectionView(repository.GetEmployeesDetails(100000)); } #region ItemsSource /// <summary> /// Gets or sets the value of ViewSource /// </summary> public VirtualizingCollectionView ViewSource { get { return this.viewSource; } set { this.viewSource = value; } } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DocIO/NestedMailMerge.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using System.Collections.Generic; #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using System.Data; using System.Collections; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class NestedMailMerge : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton button; public NestedMailMerge() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to create a letter format document by filling the data using Mail merge functionality of DocIO."; label.Lines = 0; label.Font = UIFont.SystemFontOfSize(15); label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 70); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 70); } this.AddSubview(label); button.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(5, 90, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 90, frameRect.Size.Width, 10); } button.TouchUpInside += OnButtonClicked; this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Creating a new document. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Template_Letter.doc"); //Open Template document document.Open(inputStream, FormatType.Word2013); inputStream.Dispose(); inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Employees.xml"); DataSet ds = new DataSet(); ds.ReadXml(inputStream); ArrayList commands = new ArrayList(); //DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE) DictionaryEntry entry = new DictionaryEntry("Employees", string.Empty); commands.Add(entry); // To retrive customer details System.Data.DataTable table = ds.Tables["Customers"]; string relation = table.ParentRelations[0].ChildColumns[0].ColumnName + " = %Employees." + table.ParentRelations[0].ParentColumns[0].ColumnName + "%"; entry = new DictionaryEntry("Customers", relation); commands.Add(entry); // To retrieve order details table = ds.Tables["Orders"]; relation = table.ParentRelations[0].ChildColumns[0].ColumnName + " = %Customers." + table.ParentRelations[0].ParentColumns[0].ColumnName + "%"; entry = new DictionaryEntry("Orders", relation); commands.Add(entry); //Executes nested Mail merge using explicit relational data. document.MailMerge.ExecuteNestedGroup(ds, commands); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("MailMerge.docx", "application/msword", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Frame; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Forms/PdfViewer/PdfViewer.UWP/Renderer/SfFontButtonRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.SfPdfViewer; using SampleBrowser.SfPdfViewer.UWP.Renderer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; [assembly: ExportRenderer(typeof(SfFontButton), typeof(SfFontButtonRenderer))] namespace SampleBrowser.SfPdfViewer.UWP.Renderer { public class SfFontButtonRenderer : ButtonRenderer { public Thickness Padding { get; set; } protected override void OnElementChanged(ElementChangedEventArgs<Button> e) { base.OnElementChanged(e); if (e.OldElement == null) { var nativeButton = (Xamarin.Forms.Button)e.NewElement; Control.Padding = new Windows.UI.Xaml.Thickness(0, 0, 0, 0); } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/ProgressBar/Linear.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Threading.Tasks; using CoreGraphics; using Syncfusion.iOS.ProgressBar; using UIKit; namespace SampleBrowser { public class Linear : SampleView { SfLinearProgressBar linearDeterminate; SfLinearProgressBar linearSegment; SfLinearProgressBar linearRangeColors; SfLinearProgressBar linearRangeColorsWithGradient; SfLinearProgressBar linearCornerRadius; SfLinearProgressBar linearBuffer; SfLinearProgressBar linearPadding; SfLinearProgressBar linearSegmentedCornerRadius; SfLinearProgressBar linearIndeterminate; UILabel linearDeterminateLable; UILabel linearSegmentLable; UILabel linearRangeColorsLabel; UILabel linearRangeColorsWithGradientLabel; UILabel linearCornerRadiusLabel; UILabel linearBufferLabel; UILabel linearPaddingLabel; UILabel linearSegmentedCornerRadiusLabel; UILabel linearIndeterminateLabel; bool isDispose = false; private UILabel GetLabel(string text) { return new UILabel() { Text = text, TextAlignment = UITextAlignment.Left, Font = UIFont.FromName("HelveticaNeue", 13f) }; } public Linear() { this.linearDeterminateLable = this.GetLabel("Determinate"); this.linearIndeterminateLabel = this.GetLabel("Indeterminate"); this.linearCornerRadiusLabel = this.GetLabel("Corner radius"); this.linearRangeColorsLabel = this.GetLabel("Range color"); this.linearRangeColorsWithGradientLabel = this.GetLabel("Gradient"); this.linearPaddingLabel = this.GetLabel("Padding"); this.linearBufferLabel = this.GetLabel("Buffer"); this.linearSegmentLable = this.GetLabel("Segment"); this.linearSegmentedCornerRadiusLabel = this.GetLabel("Segment with corner radius"); // Determinate progress bar. this.linearDeterminate = new SfLinearProgressBar { Progress = 75, }; // Indeterminate progress bar. linearIndeterminate = new SfLinearProgressBar { IsIndeterminate = true }; // Progres bar with corner radius. this.linearCornerRadius = new SfLinearProgressBar { Progress = 100, AnimationDuration=2000, CornerRadius = 10, }; this.linearCornerRadius.ValueChanged += this.ProgressBar_ValueChanged; // Progress bar with padding. this.linearPadding = new SfLinearProgressBar { Progress = 100, AnimationDuration=2000, IndicatorPadding = new UIEdgeInsets(1, 1, 1, 1), CornerRadius = 10, }; this.linearPadding.ValueChanged += this.ProgressBar_ValueChanged; var rangeColorCollection = new RangeColorCollection { new RangeColor{ Color = UIColor.FromRGB(54,187,225), Start = 0, End = 25 }, new RangeColor{ Color = UIColor.FromRGB(154,237,225), Start = 25, End = 50 }, new RangeColor{ Color = UIColor.FromRGB(225,220,40), Start = 50, End = 75 }, new RangeColor{ Color = UIColor.FromRGB(225,94,13), Start = 75, End = 100 } }; // Progress bar with range colors customization. this.linearRangeColors = new SfLinearProgressBar { Progress = 100, AnimationDuration=2000, RangeColors = rangeColorCollection, }; this.linearRangeColors.ValueChanged += this.ProgressBar_ValueChanged; var gradianRangeColorCollection = new RangeColorCollection { new RangeColor{ IsGradient = true, Color = UIColor.FromRGB(233, 236, 247), Start = 0, End = 20 }, new RangeColor{ IsGradient = true, Color = UIColor.FromRGB(160, 217, 239), Start = 20, End = 40 }, new RangeColor{ IsGradient = true, Color = UIColor.FromRGB(98, 193, 229), Start = 40, End = 60 }, new RangeColor{ IsGradient = true, Color = UIColor.FromRGB(32, 167, 219), Start = 60, End = 80 }, new RangeColor{ IsGradient = true, Color = UIColor.FromRGB(8, 150, 197), Start = 80, End = 100 } }; // Progress bar with gradient range colors. this.linearRangeColorsWithGradient = new SfLinearProgressBar { Progress = 100, AnimationDuration=2000, RangeColors = gradianRangeColorCollection, }; this.linearRangeColorsWithGradient.ValueChanged += this.ProgressBar_ValueChanged; // Progress bar with secondary progress. this.linearBuffer = new SfLinearProgressBar { AnimationDuration = 2000, SecondaryAnimationDuration = 1000, Progress = 100, SecondaryProgress = 100, }; // Progress bar with segments. this.linearSegment = new SfLinearProgressBar { Progress = 75, SegmentCount = 4 }; // Segmented progress bar with corner radius. this.linearSegmentedCornerRadius = new SfLinearProgressBar { Progress = 100, CornerRadius = 10, SegmentCount = 4, GapWidth = 7, AnimationDuration=2000, }; this.linearSegmentedCornerRadius.ValueChanged += this.ProgressBar_ValueChanged; AddSubview(this.linearDeterminate); AddSubview(this.linearIndeterminate); AddSubview(this.linearCornerRadius); AddSubview(this.linearRangeColors); AddSubview(this.linearRangeColorsWithGradient); AddSubview(this.linearPadding); AddSubview(this.linearBuffer); AddSubview(this.linearSegment); AddSubview(this.linearSegmentedCornerRadius); AddSubview(this.linearDeterminateLable); AddSubview(this.linearIndeterminateLabel); AddSubview(this.linearCornerRadiusLabel); AddSubview(this.linearRangeColorsLabel); AddSubview(this.linearRangeColorsWithGradientLabel); AddSubview(this.linearPaddingLabel); AddSubview(this.linearBufferLabel); AddSubview(this.linearSegmentLable); AddSubview(this.linearSegmentedCornerRadiusLabel); } public override void LayoutSubviews() { base.LayoutSubviews(); this.linearPadding.Frame = new CGRect(20, 10, this.Frame.Size.Width - 40, this.Frame.Size.Height - 20); nfloat X = 20; nfloat Y = 40; nfloat height = this.Frame.Size.Height / 18; nfloat width = this.Frame.Size.Width - 40; this.linearDeterminateLable.Frame = new CGRect(X, Y, width, 15); this.linearDeterminate.Frame = new CGRect(X, Y + this.linearDeterminateLable.Frame.Size.Height + 10, width, height); Y = Y + this.linearDeterminate.Frame.Size.Height + 20; this.linearBufferLabel.Frame = new CGRect(X, Y, width, 15); this.linearBuffer.Frame = new CGRect(X, Y + this.linearBufferLabel.Frame.Size.Height + 10, width, height); Y = Y + this.linearBuffer.Frame.Size.Height + 20; this.linearIndeterminateLabel.Frame = new CGRect(X, Y, width, 15); this.linearIndeterminate.Frame = new CGRect(X, Y + this.linearIndeterminateLabel.Frame.Size.Height + 10, width, height); Y = Y + this.linearSegment.Frame.Size.Height + 20; this.linearCornerRadiusLabel.Frame = new CGRect(X, Y, width, 15); this.linearCornerRadius.Frame = new CGRect(X, Y + this.linearCornerRadiusLabel.Frame.Size.Height + 10, width, height); Y = Y + this.linearCornerRadius.Frame.Size.Height + 20; this.linearPaddingLabel.Frame = new CGRect(X, Y, width, 15); this.linearPadding.Frame = new CGRect(X, Y + this.linearPaddingLabel.Frame.Size.Height + 10, width, height); Y = Y + this.linearPadding.Frame.Size.Height + 20; this.linearRangeColorsLabel.Frame = new CGRect(X, Y, width, 15); this.linearRangeColors.Frame = new CGRect(X, Y + this.linearRangeColorsLabel.Frame.Size.Height + 10, width, height); Y = Y + this.linearRangeColors.Frame.Size.Height + 20; this.linearRangeColorsWithGradientLabel.Frame = new CGRect(X, Y, width, 15); this.linearRangeColorsWithGradient.Frame = new CGRect(X, Y + this.linearRangeColorsWithGradientLabel.Frame.Size.Height + 10, width, height); Y = Y + this.linearRangeColorsWithGradient.Frame.Size.Height + 20; this.linearSegmentLable.Frame = new CGRect(X, Y, width, 15); this.linearSegment.Frame = new CGRect(X, Y + this.linearSegmentLable.Frame.Size.Height + 10, width, height); Y = Y + this.linearSegment.Frame.Size.Height + 20; this.linearSegmentedCornerRadiusLabel.Frame = new CGRect(X, Y, width, 15); this.linearSegmentedCornerRadius.Frame = new CGRect(X, Y + this.linearSegmentedCornerRadiusLabel.Frame.Size.Height + 10, width, height); Y = Y + this.linearSegmentedCornerRadius.Frame.Size.Height + 20; } private async void ProgressBar_ValueChanged(object sender, ProgressValueEventArgs e) { SfLinearProgressBar progressbar = sender as SfLinearProgressBar; if (e.Progress.Equals(100)) { progressbar.Progress = 0; progressbar.AnimationDuration = 1; } if (e.Progress.Equals(0)) { progressbar.AnimationDuration = 2000; progressbar.Progress = 100; } } protected override void Dispose(bool disposing) { isDispose = disposing; base.Dispose(disposing); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/ScheduleGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; using Foundation; using UIKit; using CoreGraphics; using SampleBrowser; namespace SampleBrowser { class ScheduleGettingStarted : SampleView { /// <summary> /// Variable for schedule /// </summary> private SFSchedule schedule; /// <summary> /// Collection of custom appointment /// </summary> private AppointmentCollection appointmentCollection; /// <summary> /// Collection of schedule views to show in picker /// </summary> private readonly IList<string> scheduleViews = new List<string>(); /// <summary> /// Selected view variable to indicate the view selection in picker /// </summary> private string selectedView; /// <summary> /// Schedule view picker to show the option menu to choose schedule view /// </summary> UIPickerView scheduleViewPicker = new UIPickerView(); /// <summary> /// Label to display the title of option menu /// </summary> UILabel label = new UILabel(); /// <summary> /// Button to display the first option in picker /// </summary> UIButton button = new UIButton(); /// <summary> /// Text button to display the done and close the picker /// </summary> UIButton textButton = new UIButton(); /// <summary> /// Initialize a new instance of the class <see cref="ScheduleGettingStarted"/> class /// </summary> public ScheduleGettingStarted() { schedule = new SFSchedule(); label.Text = "Schedule View"; label.TextColor = UIColor.Black; this.AddSubview(label); textButton.SetTitle("WeekView", UIControlState.Normal); textButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; textButton.BackgroundColor = UIColor.Clear; textButton.SetTitleColor(UIColor.Black, UIControlState.Normal); textButton.Hidden = false; textButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; textButton.Layer.BorderWidth = 4; textButton.Layer.CornerRadius = 8; textButton.TouchUpInside += ShowPicker; this.AddSubview(textButton); button.SetTitle("Done\t", UIControlState.Normal); button.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; button.BackgroundColor = UIColor.FromRGB(240, 240, 240); button.SetTitleColor(UIColor.Black, UIControlState.Normal); button.Hidden = true; button.TouchUpInside += HidePicker; appointmentCollection = new AppointmentCollection(); schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; schedule.MonthViewSettings.ShowAppointmentsInline = true; // Custom appointment mapping AppointmentMapping mapping = new AppointmentMapping(); mapping.Subject = "EventName"; mapping.StartTime = "From"; mapping.EndTime = "To"; mapping.AppointmentBackground = "color"; mapping.Location = "Organizer"; mapping.IsAllDay = "isAllDay"; mapping.MinHeight = "MinimumHeight"; schedule.AppointmentMapping = mapping; schedule.ItemsSource = appointmentCollection.GetAppointments(); this.AddSubview(schedule); this.scheduleViews.Add((NSString)"Week View"); this.scheduleViews.Add((NSString)"Day View"); this.scheduleViews.Add((NSString)"Work Week View"); this.scheduleViews.Add((NSString)"Month View"); SchedulePickerModel model = new SchedulePickerModel(this.scheduleViews); // Event occurs when the item picked in the picker model.PickerChanged += (sender, e) => { this.selectedView = e.SelectedValue; textButton.SetTitle(selectedView, UIControlState.Normal); if (selectedView == "Day View") { schedule.ScheduleView = SFScheduleView.SFScheduleViewDay; } else if (selectedView == "Week View") { schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; } else if (selectedView == "Work Week View") { schedule.ScheduleView = SFScheduleView.SFScheduleViewWorkWeek; } else if (selectedView == "Month View") { schedule.ScheduleView = SFScheduleView.SFScheduleViewMonth; } }; scheduleViewPicker.ShowSelectionIndicator = true; scheduleViewPicker.Hidden = true; scheduleViewPicker.Model = model; scheduleViewPicker.BackgroundColor = UIColor.White; this.OptionView = new UIView(); } /// <summary> /// Event to hide the picker when an required item selected /// </summary> /// <param name="sender">Sender of the event</param> /// <param name="e">Arguments of the event</param> private void HidePicker(object sender, EventArgs e) { button.Hidden = false; scheduleViewPicker.Hidden = true; this.BecomeFirstResponder(); } /// <summary> /// Event to show the picker when it needs /// </summary> /// <param name="sender">Sender of the event</param> /// <param name="e">Arguments of the event</param> private void ShowPicker(object sender, EventArgs e) { button.Hidden = false; scheduleViewPicker.Hidden = false; this.BecomeFirstResponder(); } /// <summary> /// Updates the frame to child /// </summary> public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view is SFSchedule) { view.Frame = new CGRect(this.Frame.X, 0, Frame.Size.Width, (Frame.Size.Height)); string deviceType = UIDevice.CurrentDevice.Model; if (deviceType == "iPhone" || deviceType == "iPod touch") { label.Frame = new CGRect(15, 10, this.Frame.Size.Width - 20, 40); textButton.Frame = new CGRect(10, label.Frame.Size.Height + label.Frame.Y, this.Frame.Size.Width - 20, 40); button.Frame = new CGRect(this.Frame.X + 10, textButton.Frame.Y + textButton.Frame.Size.Height, this.Frame.Size.Width - 20, 30); scheduleViewPicker.Frame = new CGRect(0, button.Frame.Y + button.Frame.Size.Height, this.Frame.Size.Width, 100); } else { schedule.WeekViewSettings.WorkStartHour = 7; schedule.WeekViewSettings.WorkEndHour = 18; label.Frame = new CGRect(15, 10, this.Frame.Size.Width - 20, 30); textButton.Frame = new CGRect(10, 40, this.Frame.Size.Width / 2.5, 30); button.Frame = new CGRect(this.Frame.X + 10, 80, this.Frame.Size.Width / 2.5, 30); scheduleViewPicker.Frame = new CGRect(0, 100, this.Frame.Size.Width / 2.5, 200); } } } base.LayoutSubviews(); this.CreateOptionView(); } /// <summary> /// Creates option view to show the picker /// </summary> private void CreateOptionView() { this.OptionView.AddSubview(label); this.OptionView.AddSubview(textButton); this.OptionView.AddSubview(scheduleViewPicker); this.OptionView.AddSubview(button); } } }<file_sep>/Forms/ListView/ListView/Samples/GettingStarted/Model/ShoppingRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ShoppingCategoryInfoRepository { #region Constructor public ShoppingCategoryInfoRepository() { } #endregion #region Properties internal ObservableCollection<ListViewShoppingCategoryInfo> GetCategoryInfo() { var categoryInfo = new ObservableCollection<ListViewShoppingCategoryInfo>(); for (int i = 0; i < CategoryNames.Count(); i++) { var info = new ListViewShoppingCategoryInfo() { CategoryName = CategoryNames[i], CategoryDescription = CategoryDescriptions[i], CategoryImage = CategoryImages[i] }; categoryInfo.Add(info); } return categoryInfo; } #endregion #region CategoryInfo string[] CategoryNames = new string[] { "Fashion", "Electronics", "Home & Kitchen", "Sports & Health", "Kids", "Books", "Footware", "Mobile & Accesories", "FlowerGiftCakes", "Watches", "Jewellery", "Food", "Perfumes", "Movies & Music", "Cameras & Optics" }; string[] CategoryImages = new string[] { "Shopping.jpg", "Electronics.jpg", "DiningTable.jpg", "Sports_Health.jpg", "NaughtyBoy.jpg", "Novels.jpg", "Graycanvas.jpg", "Mobile.jpg", "FlowerGiftCakes.jpg", "Watches.jpg", "Jewellery.jpg", "Food.jpg", "Perfumes.jpg", "BrownGuitar.jpg", "Cameras.png" }; string[] CategoryDescriptions = new string[] { "Latest fashion trends in online shopping for branded Shoes, Clothing, Dresses, Handbags, Watches, Home decor for Men & Women...", "Shop variety of electronics like Mobiles, Laptops, Tablets, Cameras, Gaming Consoles, TVs, LEDs, Music Systems & much more...", "Purchase Home & Kitchen accessories like Cookware, Home Cleaning, Furniture, Dining Accessories, Showcase accessories etc ...", "Buy accessories for Badminton, Cricket, Football, Swimming, Sports shoes, Tennis, Gym, Volleyball, hockey at lowest price...", "Shop for clothing for Boys, Girls and Babies. Explore the range of Tops, Tees, Jeans, Shirts, Trousers, Skirts, Body Suits...", "Purchase various books with Book titles with across various categories at lowest price. Read books online and download as pdf...", "Buy Footwear for Men, Women & Kids with collection of Formal Shoes, Slippers, Casual Shoes, Sandals and more with best price...", "Buy branded Mobile Phones, SmartPhones, Tablets and mobile accessories are Bluetooth, Headsets, MemoryCards, Charger & Covers etc...", "Buy different Flowers, Gifts & Cakes in online shopping. Birthday Gifts, Anniversary Gifts, MothersDay Gifts, Flowers and Cakes etc...", "Latest range of trendy branded, Digital watches & Analog watches, Digital Steel Watch, Digital LED Watches for Men's and Women's...", "Buy Jewellery for Men, Women and Children from brands like Gitanjali, Tara, Orra, Sia Art Jewellery, Addons, Ayesha, Peora etc...", "Shop from a wide range of best quality Fruits, Vegetables, Health Food, Indian Grocery, Pulses, Cereals, Noodles, Foods etc...", "Choose the best branded Perfume like Azzaro, Davidoff, CK, Axes, Good Morning, <NAME>, Jaguar, <NAME> & Antonio etc...", "Buy variety of Movies & TV Blu-ray in different languages and Musics in variety of formats like audio CD, DVD, MP3, VCD etc...", "Purchase variety of Cameras like Tamron, Sigma, Nikon, Sony, and Canon at best prices and SLRs, Lenses and Optics accessories..." }; #endregion } } <file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/PullToRefreshDemo Helper/PullableContentView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using CoreGraphics; namespace SampleBrowser { public class PullableContentView : UIView { BaseView baseView; CustomScroll customScroll; UILabel label; public PullableContentView(BaseView baseview, CustomScroll customscroll, UILabel lable) : base() { baseView = baseview; customScroll = customscroll; label = lable; this.AddSubview(baseview); this.AddSubview(customscroll); this.AddSubview(lable); } public override void LayoutSubviews() { base.LayoutSubviews(); label.Frame = new CGRect(0, 20, this.Frame.Width, 50); baseView.Frame = new CGRect(0, (Frame.Height / 4), Frame.Width, Frame.Height / 2); customScroll.Frame = new CGRect(0, this.Frame.Height - 150, this.Frame.Width, 150); } } }<file_sep>/iOS/SampleBrowser/Samples/LinearGauge/ScaleandPointers.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion 
using System;
using System.Collections.Generic;
using System.Drawing; #if __UNIFIED__
using Foundation;
using UIKit;
using CoreGraphics;

#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
using nint = System.Int32;
using nuint = System.Int32;
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using nfloat = System.Single;
#endif
using Syncfusion.SfGauge.iOS;
namespace SampleBrowser
{
 public class ScaleandPointers:SampleView
 {
 SFLinearGauge linearGauge;
 SFLinearScale scale;
 UIPickerView opposed;
 UIPickerView rangeCap;
 UIPickerView markerShape;
 UIView option = new UIView();
 SFSymbolPointer pointer;
 SFBarPointer pointer1;

 static bool UserInterfaceIdiomIsPhone
 {
 get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; }
 }

 #region View lifecycle
 public override void LayoutSubviews()
 {
 foreach (var view in this.Subviews)
 {
 view.Frame = Bounds;
 linearGauge.Frame = new CGRect(0, -20, this.Frame.Size.Width, this.Frame.Size.Height + 20);
 }
 
 base.LayoutSubviews();
 }
 public ScaleandPointers()
 {
 opposed = new UIPickerView();
 rangeCap = new UIPickerView();
 markerShape = new UIPickerView();

 //LinearGauge
 this.BackgroundColor = UIColor.White;

 linearGauge = new SFLinearGauge();
 linearGauge.BackgroundColor = UIColor.White;
 linearGauge.Header = new SFLinearLabel();


 scale = new SFLinearScale();
 scale.Minimum = 0;
 scale.Maximum = 100;
 scale.Interval = 10;
 scale.CornerRadius = 20;
 scale.CornerRadiusType = CornerRadiusType.End;
 scale.ScaleBarSize = 40;
 scale.LabelColor = UIColor.FromRGB(66, 66, 66);
 scale.LabelFont = UIFont.FromName("Helvetica", 14f);
 scale.MinorTicksPerInterval = 1;
 scale.MinorTickSettings.Length = 8;
 scale.ScaleBarColor = UIColor.FromRGB(224,233,249);

 SFLinearTickSettings major = new SFLinearTickSettings();
 major.Thickness = 1f;
 major.Length = 10;
 major.Color = UIColor.FromRGB(158, 158, 158);
 scale.MajorTickSettings = major;


 pointer = new SFSymbolPointer();
 pointer.SymbolPosition = SymbolPointerPosition.Away;
 pointer.Thickness = 12;
 pointer.Value = 30;
 pointer.Color = UIColor.FromRGB(91, 134, 229);
 pointer.MarkerShape = MarkerShape.Triangle;
 scale.Pointers.Add(pointer);

 pointer1 = new SFBarPointer();
 pointer1.Value = 75;
 pointer1.CornerRadiusValue = 15;
 pointer1.CornerRadiusType = CornerRadiusType.End;
 pointer1.Thickness = 30;

 GaugeGradientStop color1 = new GaugeGradientStop();
 color1.Value = 0;
 color1.Color = UIColor.FromRGB(54, 209, 220);
 pointer1.GradientStops.Add(color1);

 GaugeGradientStop color2 = new GaugeGradientStop();
 color2.Value = 75;
 color2.Color = UIColor.FromRGB(91, 134, 229);
 pointer1.GradientStops.Add(color2);

 scale.Pointers.Add(pointer1);

 linearGauge.Scales.Add(scale);

 this.AddSubview(linearGauge);
 CreateOptionView();
 this.OptionView = option;
 }

 private void CreateOptionView()
 {

 UILabel text1 = new UILabel();
 text1.Text = "Opposite position";
 text1.TextAlignment = UITextAlignment.Left;
 text1.TextColor = UIColor.Black;
 text1.Frame = new CGRect(10, 10, 320, 40);
 text1.Font = UIFont.FromName("Helvetica", 14f);

 List<string> position = new List<string> { "True", "False" };
 var picker = new OpposedPickerModel(position);

 opposed.Model = picker;
 opposed.SelectedRowInComponent(0); opposed.Frame = new CGRect(10, 50, 200, 40);
 picker.ValueChanged += (sender, e) => { if (picker.SelectedValue == "True") scale.OpposedPosition = true; else if (picker.SelectedValue == "False") scale.OpposedPosition = false; }; UILabel text2 = new UILabel(); text2.Text = "Range Cap";
 text2.TextAlignment = UITextAlignment.Left;
 text2.TextColor = UIColor.Black;
 text2.Frame = new CGRect(10, 90, 320, 40); text2.Font = UIFont.FromName("Helvetica", 14f); List<string> position1 = new List<string> { "Start", "End", "Both", "None" }; var picker1 = new RangePickerModel(position1); rangeCap.Model = picker1; rangeCap.Frame = new CGRect(10, 140, 200, 40); picker1.ValueChanged += (sender, e) => { if (picker1.SelectedValue == "Start")
 { pointer1.CornerRadiusType = CornerRadiusType.Start; scale.CornerRadiusType = CornerRadiusType.Start;
 } else if (picker1.SelectedValue == "End")
 {
 pointer1.CornerRadiusType = CornerRadiusType.End; scale.CornerRadiusType = CornerRadiusType.End;
 } else if (picker1.SelectedValue == "Both")
 {
 pointer1.CornerRadiusType = CornerRadiusType.Both; scale.CornerRadiusType = CornerRadiusType.Both;
 } else if (picker1.SelectedValue == "None")
 {
 pointer1.CornerRadiusType = CornerRadiusType.None; scale.CornerRadiusType = CornerRadiusType.None;
 } }; UILabel text3 = new UILabel(); text3.Text = "Marker Shape";
 text3.TextAlignment = UITextAlignment.Left;
 text3.TextColor = UIColor.Black;
 text3.Frame = new CGRect(10, 180, 320, 40); text3.Font = UIFont.FromName("Helvetica", 14f); List<string> position2 = new List<string> { "Triangle", "Inverted Triangle", "Circle", "Diamond", "Rectangle", "Image" }; var picker2 = new MarkerPickerModel(position2); markerShape.Model = picker2;
 markerShape.SelectedRowInComponent(0);
 markerShape.Frame = new CGRect(10, 220, 250, 40); picker2.ValueChanged += (sender, e) => { if (picker2.SelectedValue == "Triangle") pointer.MarkerShape = MarkerShape.Triangle; else if (picker2.SelectedValue == "Inverted Triangle") pointer.MarkerShape = MarkerShape.InvertedTriangle; else if (picker2.SelectedValue == "Circle") pointer.MarkerShape = MarkerShape.Circle; else if (picker2.SelectedValue == "Diamond")
 pointer.MarkerShape = MarkerShape.Diamond; else if (picker2.SelectedValue == "Rectangle")
 pointer.MarkerShape = MarkerShape.Rectangle; else if (picker2.SelectedValue == "Image") {
 pointer.MarkerShape = MarkerShape.Image; pointer.ImageSource = "location.png"; } };

 this.option.AddSubview(text1);
 this.option.AddSubview(opposed); this.option.AddSubview(text2); this.option.AddSubview(rangeCap); this.option.AddSubview(text3); this.option.AddSubview(markerShape); }

 #endregion
 }

 public class OpposedPickerModel : UIPickerViewModel
 {
 List<string> position;
 public EventHandler ValueChanged;
 public string SelectedValue;

 public OpposedPickerModel(List<string> position)
 {
 this.position = position;
 }

 public override nint GetRowsInComponent(UIPickerView pickerView, nint component)
 {
 return position.Count;
 }

 public override nint GetComponentCount(UIPickerView pickerView)
 {
 return 1;
 } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; ;
 } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component)
 {
 var position1 = position[(int)row];
 SelectedValue = position1;
 ValueChanged?.Invoke(null, null);
 }
 } public class RangePickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public RangePickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; ; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); }
 } public class MarkerPickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public MarkerPickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; ; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); } }
}
<file_sep>/iOS/SampleBrowser/Samples/Diagram/Connectors.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using CoreGraphics; using Foundation; using Syncfusion.SfDiagram.iOS; using UIKit; namespace SampleBrowser { public class Connectors : SampleView { SfDiagram diagram = new SfDiagram(); UIPickerView selectionPicker1; UILabel connectorStyle; UIButton connectorStyleButton = new UIButton(); UILabel connectorSize; UIButton doneButton = new UIButton(); internal UIView HeaderBar = new UIView(); UIButton straight; UIButton curve; UIButton ortho; UIButton plus; UIButton minus; UILabel sizeindicator; UIImageView plusimg; UIImageView minusimg; DiagramView diagramView = new DiagramView(); public Connectors() { HeaderBar.BackgroundColor = UIColor.FromRGB(245, 245, 245); var label = new UILabel(); label.Text = "Connector Types: "; label.TextColor = UIColor.Black; label.BackgroundColor = UIColor.Clear; label.TextAlignment = UITextAlignment.Center; string deviceType = UIDevice.CurrentDevice.Model; int offsetX; int space; if (deviceType == "iPhone" || deviceType == "iPod touch") { offsetX = 150; space = 10; } else { offsetX = 180; space = 40; } label.Frame = new CGRect(0, 0, offsetX, 60); HeaderBar.AddSubview(label); offsetX += space; straight = AddButton(offsetX, "Images/Diagram/CSStraight.png"); straight.TouchUpInside += Straight_TouchUpInside; HeaderBar.AddSubview(straight); offsetX += space + 40; curve = AddButton(offsetX, "Images/Diagram/CSCurve.png"); curve.TouchUpInside += Curve_TouchUpInside; ; HeaderBar.AddSubview(curve); offsetX += space + 40; ortho = AddButton(offsetX, "Images/Diagram/CSOrtho.png"); ortho.TouchUpInside += Ortho_TouchUpInside; ortho.BackgroundColor = UIColor.FromRGB(30, 144, 255); HeaderBar.AddSubview(ortho); selectionPicker1 = new UIPickerView(); this.OptionView = new UIView(); PickerModel model = new PickerModel(verticalOrientationlist); selectionPicker1.Model = model; connectorStyle = new UILabel(); connectorStyle.Text = "Connector Style"; connectorStyle.TextColor = UIColor.Black; connectorStyle.TextAlignment = UITextAlignment.Left; connectorSize = new UILabel(); connectorSize.Text = "Connector Size"; connectorSize.TextColor = UIColor.Black; connectorSize.TextAlignment = UITextAlignment.Left; //Represent the vertical button connectorStyleButton = new UIButton(); connectorStyleButton.SetTitle("Default", UIControlState.Normal); connectorStyleButton.SetTitleColor(UIColor.Black, UIControlState.Normal); connectorStyleButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; connectorStyleButton.Layer.CornerRadius = 8; connectorStyleButton.Layer.BorderWidth = 2; connectorStyleButton.TouchUpInside += ShowPicker1; connectorStyleButton.BackgroundColor = UIColor.LightGray; connectorStyleButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; plus = new UIButton(); plus.BackgroundColor = UIColor.White; plus.Layer.CornerRadius = 8; plus.Layer.BorderWidth = 0.5f; plus.TouchUpInside += Plus_TouchUpInside; plusimg = new UIImageView(); plusimg.Image = UIImage.FromBundle("Images/Diagram/CSplus.png"); plus.AddSubview(plusimg); minus = new UIButton(); minus.BackgroundColor = UIColor.White; minus.Layer.CornerRadius = 8; minus.Layer.BorderWidth = 0.5f; minus.TouchUpInside += Minus_TouchUpInside; minusimg = new UIImageView(); minusimg.Image = UIImage.FromBundle("Images/Diagram/CSsub.png"); minus.AddSubview(minusimg); sizeindicator = new UILabel(); sizeindicator.Text = width.ToString(); sizeindicator.BackgroundColor = UIColor.Clear; sizeindicator.TextColor = UIColor.Black; sizeindicator.TextAlignment = UITextAlignment.Center; //Represent the button doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(246, 246, 246); selectionPicker1.ShowSelectionIndicator = true; selectionPicker1.Hidden = true; ObservableCollection<EmployeeDetail> employees = new ObservableCollection<EmployeeDetail>(); employees.Add(new EmployeeDetail() { Name = "Elizabeth", EmpId = "1", ParentId = "", Designation = "CEO" }); employees.Add(new EmployeeDetail() { Name = "Christina", EmpId = "2", ParentId = "1", Designation = "Manager" }); employees.Add(new EmployeeDetail() { Name = "Yang", EmpId = "3", ParentId = "1", Designation = "Manager" }); employees.Add(new EmployeeDetail() { Name = "Yoshi", EmpId = "4", ParentId = "2", Designation = "Team Lead" }); employees.Add(new EmployeeDetail() { Name = "Yoshi", EmpId = "5", ParentId = "2", Designation = "Co-ordinator" }); employees.Add(new EmployeeDetail() { Name = "Philip", EmpId = "6", ParentId = "4", Designation = "Developer" }); employees.Add(new EmployeeDetail() { Name = "Philip", EmpId = "7", ParentId = "4", Designation = "Testing Engineer" }); employees.Add(new EmployeeDetail() { Name = "Roland", EmpId = "8", ParentId = "3", Designation = "Team Lead" }); employees.Add(new EmployeeDetail() { Name = "Yoshi", EmpId = "9", ParentId = "3", Designation = "Co-ordinator" }); employees.Add(new EmployeeDetail() { Name = "Yuonne", EmpId = "10", ParentId = "8", Designation = "Developer" }); employees.Add(new EmployeeDetail() { Name = "Philip", EmpId = "10", ParentId = "8", Designation = "Testing Engineer" }); //Initializes the DataSourceSettings diagram.DataSourceSettings = new DataSourceSettings() { DataSource = employees, Id = "EmpId", ParentId = "ParentId" }; //Initializes the Layout DirectedTreeLayout treelayout = new DirectedTreeLayout() { HorizontalSpacing = 80, VerticalSpacing = 50, TreeOrientation = TreeOrientation.TopToBottom }; diagram.LayoutManager = new LayoutManager() { Layout = treelayout }; diagram.IsReadOnly = true; diagram.BeginNodeRender += Diagram_BeginNodeRender; diagram.Loaded += Diagram_Loaded; HeaderBar.Frame = new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, 60); diagramView.Frame = new CGRect(0, 70, UIScreen.MainScreen.Bounds.Width + 40, UIScreen.MainScreen.Bounds.Height - HeaderBar.Frame.Height); diagramView.BackgroundColor = UIColor.Clear; diagram.Layer.BorderColor = UIColor.Clear.CGColor; diagram.Layer.BorderWidth = 0; diagramView.AddSubview(diagram); diagramView.MarginTop = HeaderBar.Frame.Height; this.AddSubview(diagramView); this.AddSubview(HeaderBar); model.PickerChanged += SelectedIndexChanged; for (int i = 0; i < diagram.Connectors.Count; i++) { diagram.Connectors[i].TargetDecoratorType = DecoratorType.None; } foreach (var view in this.Subviews) { connectorStyle.Frame = new CGRect(this.Frame.X + 10, 0, PopoverSize.Width - 20, 30); connectorStyleButton.Frame = new CGRect(this.Frame.X + 10, 40, PopoverSize.Width - 20, 30); connectorSize.Frame = new CGRect(this.Frame.X + 10, 80, PopoverSize.Width - 20, 30); plus.Frame = new CGRect(this.Frame.X + 60, 120, 30, 30); plusimg.Frame = new CGRect(0, 0, 30, 30); minus.Frame = new CGRect(this.Frame.X + 160, 120, 30, 30); minusimg.Frame = new CGRect(0, 0, 30, 30); sizeindicator.Frame = new CGRect(this.Frame.X + 110, 120, 30, 30); selectionPicker1.Frame = new CGRect(0, PopoverSize.Height / 2, PopoverSize.Width, PopoverSize.Height / 3); doneButton.Frame = new CGRect(0, PopoverSize.Height / 2.5, PopoverSize.Width, 40); } optionView(); diagram.ContextMenuSettings.Visibility = false; } int width = 2; void Plus_TouchUpInside(object sender, EventArgs e) { if (width < 5) { width = (int)diagram.Connectors[0].Style.StrokeWidth + 1; sizeindicator.Text = width.ToString(); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeWidth += 1; } } void Minus_TouchUpInside(object sender, EventArgs e) { if (width > 1) { width = (int)diagram.Connectors[0].Style.StrokeWidth - 1; sizeindicator.Text = width.ToString(); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeWidth -= 1; } } void HidePicker(object sender, EventArgs e) { doneButton.Hidden = true; selectionPicker1.Hidden = true; } private void SelectedIndexChanged(object sender, PickerChangedEventArgs e) { //this.selectedType = selectedorientation + e.SelectedValue; if (e.SelectedValue == "Default") { for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeStyle = StrokeStyle.Default; } else if (e.SelectedValue == "Dashed") { for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeStyle = StrokeStyle.Dashed; } else if (e.SelectedValue == "Dotted") { for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeStyle = StrokeStyle.Dotted; } } public override void LayoutSubviews() { base.LayoutSubviews(); diagramView.LayoutSubviews(); diagram.LayoutSubviews(); HeaderBar.Frame = new CGRect(0, 0, Frame.Width, 60); } public void optionView() { this.OptionView.AddSubview(connectorStyle); this.OptionView.AddSubview(connectorStyleButton); this.OptionView.AddSubview(connectorSize); this.OptionView.AddSubview(plus); this.OptionView.AddSubview(minus); this.OptionView.AddSubview(sizeindicator); this.OptionView.AddSubview(selectionPicker1); this.OptionView.AddSubview(doneButton); } private void ShowPicker1(object sender, EventArgs e) { (sender as UIButton).BackgroundColor = UIColor.LightGray; doneButton.Hidden = false; selectionPicker1.Hidden = false; } private UIButton AddButton(int v1, string v2) { UIButton straight = new UIButton(); straight.BackgroundColor = UIColor.White; straight.TouchUpInside += Straight_TouchUpInside; straight.Frame = new CGRect(v1, 10, 40, 40); straight.Layer.CornerRadius = 20; straight.Layer.BorderColor = UIColor.Black.CGColor; straight.Layer.BorderWidth = 1.5f; UIImageView img = new UIImageView(); img.Frame = new CGRect(10, 10, 20, 20); img.BackgroundColor = UIColor.Clear; img.Image = UIImage.FromBundle(v2); straight.AddSubview(img); return straight; } private readonly IList<string> verticalOrientationlist = new List<string> { "Default", "Dashed", "Dotted" }; private void Diagram_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); } private void Diagram_BeginNodeRender(object sender, BeginNodeRenderEventArgs args) { var node = args.Item; node.Width = 144; node.Height = 60; node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 0; if ((node.Content as EmployeeDetail).Designation == "Manager") node.Style.Brush = new SolidBrush(UIColor.FromRGB(23, 132, 206)); else if ((node.Content as EmployeeDetail).Designation == "CEO") { node.Style.Brush = new SolidBrush(UIColor.FromRGB(201, 32, 61)); } else if ((node.Content as EmployeeDetail).Designation == "Team Lead" || (node.Content as EmployeeDetail).Designation == "Co-ordinator") node.Style.Brush = new SolidBrush(UIColor.FromRGB(4, 142, 135)); else node.Style.Brush = new SolidBrush(UIColor.FromRGB(206, 98, 9)); node.Annotations.Add(new Annotation() { Content = (node.Content as EmployeeDetail).Designation, FontSize = 15, TextBrush = new SolidBrush(UIColor.White) }); } void Straight_TouchUpInside(object sender, EventArgs e) { (sender as UIButton).BackgroundColor = UIColor.FromRGB(30, 144, 255); ((sender as UIButton).Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSStraight1"); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].SegmentType = SegmentType.StraightSegment; curve.BackgroundColor = UIColor.White; ortho.BackgroundColor = UIColor.White; (curve.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSCurve"); (ortho.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSOrtho"); } void Ortho_TouchUpInside(object sender, EventArgs e) { (sender as UIButton).BackgroundColor = UIColor.FromRGB(30, 144, 255); ((sender as UIButton).Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSOrtho1"); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].SegmentType = SegmentType.OrthoSegment; curve.BackgroundColor = UIColor.White; (curve.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSCurve"); straight.BackgroundColor = UIColor.White; (straight.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSStraight"); } void Curve_TouchUpInside(object sender, EventArgs e) { (sender as UIButton).BackgroundColor = UIColor.FromRGB(30, 144, 255); ((sender as UIButton).Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSCurve1"); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].SegmentType = SegmentType.CurveSegment; straight.BackgroundColor = UIColor.White; ortho.BackgroundColor = UIColor.White; (ortho.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSOrtho"); (straight.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSStraight"); } } //Connector_Employee Business Object [Preserve(AllMembers = true)] public class EmployeeDetail { public string ParentId { get; set; } public string Name { get; set; } public string Designation { get; set; } public string EmpId { get; set; } } //Connector_Employee Collection public class Employees : System.Collections.ObjectModel.ObservableCollection<EmployeeDetail> { } public class DiagramView : UIView { internal nfloat MarginTop; public DiagramView() { } public override void LayoutSubviews() { base.LayoutSubviews(); this.Frame = new CGRect(Frame.X, Frame.Y, (float)this.Superview.Frame.Width, (float)this.Superview.Frame.Height - MarginTop); } } }<file_sep>/Android/SampleBrowser/Samples/LinearGauge/LinearGauge.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Util; using System; using Android.Views; using Com.Syncfusion.Gauges.SfLinearGauge; using Android.Widget; using Android.Content; using Android.OS; using Android.Runtime; using System.Collections.ObjectModel; using Android.Graphics; namespace SampleBrowser { public class LinearGauge : SamplePage { public static int pointervalue = 10; public override View GetSampleContent(Android.Content.Context con) { /**************** **Linear Gauge** ****************/ SfLinearGauge linearGauge = new SfLinearGauge(con); ObservableCollection<LinearScale> scales = new ObservableCollection<LinearScale>(); ObservableCollection<LinearPointer> pointers = new ObservableCollection<LinearPointer>(); ObservableCollection<LinearRange> ranges = new ObservableCollection<LinearRange>(); linearGauge.SetX(0); linearGauge.SetY(0); linearGauge.SetBackgroundColor(Color.Rgb(255, 255, 255)); linearGauge.SetOrientation(SfLinearGauge.Orientation.Horizontal); //OuterScale LinearScale outerScale = new LinearScale(); outerScale.Minimum = 0; outerScale.Maximum = 100; outerScale.ScaleBarSize = 2; outerScale.Interval = 10; outerScale.ScaleBarColor = Android.Graphics.Color.ParseColor("#9e9e9e"); outerScale.MinorTicksPerInterval = 4; outerScale.LabelFontSize = 14; outerScale.LabelColor = Color.ParseColor("#424242"); outerScale.OpposedPosition = true; //OuterScale MajorTicksSettings LinearTickSettings outerScale_majorTicksSettings = new LinearTickSettings(); outerScale_majorTicksSettings.Color = Color.ParseColor("#9E9E9E");// outerScale_majorTicksSettings.Length = 30; outerScale_majorTicksSettings.StrokeWidth = 1.5; outerScale.MajorTickSettings = outerScale_majorTicksSettings; //OuterScale MinorTicksSettings LinearTickSettings outerScale_minorTicksSettings = new LinearTickSettings(); outerScale_minorTicksSettings.Color = Color.ParseColor("#9E9E9E"); outerScale_minorTicksSettings.Length = 15; outerScale_minorTicksSettings.StrokeWidth = 0.9; outerScale.MinorTickSettings = outerScale_minorTicksSettings; //Symbol Pointer SymbolPointer outerScale_needlePointer = new SymbolPointer(); outerScale_needlePointer.SymbolPosition = SymbolPointerPosition.Away; outerScale_needlePointer.Value = pointervalue; outerScale_needlePointer.StrokeWidth = 12; outerScale_needlePointer.Color = Color.ParseColor("#9E9E9E"); outerScale_needlePointer.MarkerShape = MarkerShape.Triangle; pointers.Add(outerScale_needlePointer); outerScale.Pointers = pointers; scales.Add(outerScale); linearGauge.Scales = scales; //Linear Gauge Layout LinearLayout linearGaugeLayout = new LinearLayout(con); linearGaugeLayout.SetBackgroundColor(Color.Rgb(255, 255, 255)); linearGaugeLayout.AddView(linearGauge); return linearGaugeLayout; } } } <file_sep>/Forms/Cards/Cards/Samples/CardLayout/CardLayout.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.Cards; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.Cards { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CardLayout : SampleView { CardLayoutViewModel viewModel = new CardLayoutViewModel(); public CardLayout() { InitializeComponent(); var childCount = cardLayout.Children.Count; for (int i = 0; i < childCount; i++) { cardLayout.Children[i].BindingContext = viewModel.Data[i]; } if (Device.RuntimePlatform == Device.UWP) { stackLayout.Padding = 15; } } private void OnPaddingChanged(object sender, ValueChangedEventArgs e) { var horizontalPadding = e.NewValue; cardLayout.Padding = new Thickness(horizontalPadding, 5, horizontalPadding, 5); paddingLabel.Text = "Padding : " + Math.Round(e.NewValue).ToString(); } private void OnSelectionChanged(object sender, Syncfusion.XForms.Buttons.SelectionChangedEventArgs e) { var direction = e.Index == 0 ? CardSwipeDirection.Left : CardSwipeDirection.Right; if (cardLayout.SwipeDirection != direction) { cardLayout.SwipeDirection = direction; } } protected override void OnSizeAllocated(double width, double height) { if (Device.RuntimePlatform == Device.UWP || Device.Idiom == TargetIdiom.Tablet) { var padding = width / 4; cardLayout.Padding = new Thickness(padding, 5, padding, 5); Slider.IsVisible = false; paddingLabel.IsVisible = false; } base.OnSizeAllocated(width, height); } } }<file_sep>/Android/SampleBrowser/Samples/Diagram/Connectors.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Syncfusion.SfDiagram.Android; using System.Collections.Generic; using System.IO; using System.Reflection; namespace SampleBrowser { public partial class Connectors : SamplePage { SfDiagram diagram; private Context m_context; private float currentDensity; private LinearLayout buttons; private TextView label; public override View GetSampleContent(Context context) { m_context = context; currentDensity = m_context.Resources.DisplayMetrics.Density; //Initialize the SfDiagram and set its background color. diagram = new SfDiagram(context); diagram.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); diagram.IsReadOnly = true; ObservableCollection<Employee> employees = new ObservableCollection<Employee>(); employees.Add(new Employee() { Name = "Elizabeth", EmpId = "1", ParentId = "", Designation = "CEO" }); employees.Add(new Employee() { Name = "Christina", EmpId = "2", ParentId = "1", Designation = "Manager" }); employees.Add(new Employee() { Name = "Yang", EmpId = "3", ParentId = "1", Designation = "Manager" }); employees.Add(new Employee() { Name = "Yoshi", EmpId = "4", ParentId = "2", Designation = "Team Lead" }); employees.Add(new Employee() { Name = "Yoshi", EmpId = "5", ParentId = "2", Designation = "Co-ordinator" }); employees.Add(new Employee() { Name = "Philip", EmpId = "6", ParentId = "4", Designation = "Developer" }); employees.Add(new Employee() { Name = "Philip", EmpId = "7", ParentId = "4", Designation = "Testing Engineer" }); employees.Add(new Employee() { Name = "Roland", EmpId = "8", ParentId = "3", Designation = "Team Lead" }); employees.Add(new Employee() { Name = "Yoshi", EmpId = "9", ParentId = "3", Designation = "Co-ordinator" }); employees.Add(new Employee() { Name = "Yuonne", EmpId = "10", ParentId = "8", Designation = "Developer" }); employees.Add(new Employee() { Name = "Philip", EmpId = "10", ParentId = "8", Designation = "Testing Engineer" }); //Initializes the DataSourceSettings diagram.DataSourceSettings = new DataSourceSettings() { DataSource = employees, Id = "EmpId", ParentId = "ParentId" }; //Initializes the Layout DirectedTreeLayout treelayout = new DirectedTreeLayout() { HorizontalSpacing = 80, VerticalSpacing = 50 * currentDensity, TreeOrientation = TreeOrientation.TopToBottom }; diagram.LayoutManager = new LayoutManager() { Layout = treelayout }; diagram.BeginNodeRender += Diagram_BeginNodeRender; diagram.Loaded += Diagram_Loaded; LinearLayout linearLayout = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Vertical }; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); layoutParams.TopMargin = 25 * (int)MainActivity.Factor; linearLayout.LayoutParameters = layoutParams; LinearLayout typesBar = new LinearLayout(context); typesBar.SetBackgroundColor(Color.Rgb(245, 245, 245)); layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); typesBar.SetMinimumHeight(200 * (int)MainActivity.Factor); typesBar.SetPadding(0, 10 * (int)MainActivity.Factor, 0, 10 * (int)MainActivity.Factor); TextView selectText = new TextView(context) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent), Text = "Connector Types:", TextAlignment = TextAlignment.Gravity, Gravity = GravityFlags.Center | GravityFlags.CenterVertical, TextSize = 15 * MainActivity.Factor }; int width = (int)(context.Resources.DisplayMetrics.WidthPixels - context.Resources.DisplayMetrics.Density); selectText.SetMinimumWidth((int)(width * 0.4 * MainActivity.Factor)); ImageButtonView straightButton = new ImageButtonView(context); straightButton.Click += ButtonTouch; straightButton.ImageId = "DiagramStraight"; straightButton.LayoutParameters = new ViewGroup.LayoutParams(180 * (int)MainActivity.Factor, 180 * (int)MainActivity.Factor); ImageView straightImage = new ImageView(context); var imageId = straightButton.ImageId + ".png"; if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); straightImage.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } straightImage.Layout((int)(40 * MainActivity.Factor), (int)(40 * MainActivity.Factor), (int)(110 * MainActivity.Factor), (int)(110 * MainActivity.Factor)); straightButton.AddView(straightImage); ImageButtonView curveButton = new ImageButtonView(context); curveButton.Click += ButtonTouch; curveButton.ImageId = "DiagramCurve"; curveButton.LayoutParameters = new ViewGroup.LayoutParams(180 * (int)MainActivity.Factor, 180 * (int)MainActivity.Factor); ImageView curveImage = new ImageView(context); imageId = curveButton.ImageId + ".png"; if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); curveImage.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } curveImage.Layout((int)(40 * MainActivity.Factor), (int)(40 * MainActivity.Factor), (int)(110 * MainActivity.Factor), (int)(110 * MainActivity.Factor)); curveButton.AddView(curveImage); ImageButtonView edgeButton = new ImageButtonView(context); edgeButton.Click += ButtonTouch; edgeButton.LayoutParameters = new ViewGroup.LayoutParams(180 * (int)MainActivity.Factor, 180 * (int)MainActivity.Factor); edgeButton.ImageId = "DiagramEdge"; ImageView edgeImage = new ImageView(context); imageId = edgeButton.ImageId + ".png"; if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); edgeImage.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } edgeImage.Layout((int)(40 * MainActivity.Factor), (int)(40 * MainActivity.Factor), (int)(110 * MainActivity.Factor), (int)(110 * MainActivity.Factor)); edgeButton.AddView(edgeImage); buttons = new LinearLayout(context); buttons.SetMinimumWidth((int)(width - width * 0.4 * MainActivity.Factor)); buttons.SetBackgroundColor(Color.Transparent); buttons.AddView(straightButton); TextView view = new TextView(context); view.SetWidth(30 * (int)MainActivity.Factor); view.SetBackgroundColor(Color.Transparent); buttons.AddView(view); buttons.AddView(curveButton); view = new TextView(context); view.SetWidth(30 * (int)MainActivity.Factor); view.SetBackgroundColor(Color.Transparent); buttons.AddView(view); buttons.AddView(edgeButton); typesBar.AddView(selectText); typesBar.AddView(buttons); linearLayout.AddView(typesBar); linearLayout.AddView(diagram); for (int i = 0; i < diagram.Connectors.Count; i++) { diagram.Connectors[i].TargetDecoratorType = DecoratorType.None; diagram.Connectors[i].Style.StrokeWidth = 1; } return linearLayout; } private void Diagram_BeginNodeRender(object sender, BeginNodeRenderEventArgs args) { var node = args.Item; node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 0; if ((node.Content as Employee).Designation == "Manager") node.Style.Brush = new SolidBrush(Color.Rgb(23, 132, 206)); else if ((node.Content as Employee).Designation == "CEO") node.Style.Brush = new SolidBrush(Color.Rgb(201, 32, 61)); else if ((node.Content as Employee).Designation == "Team Lead" || (node.Content as Employee).Designation == "Co-ordinator") node.Style.Brush = new SolidBrush(Color.Rgb(4, 142, 135)); else node.Style.Brush = new SolidBrush(Color.Rgb(206, 98, 9)); node.Width = 144 * MainActivity.Factor; node.Height = 60 * MainActivity.Factor; AnnotationCollection annotations = new AnnotationCollection(node); annotations.Add(new Annotation() { Content = (node.Content as Employee).Designation, FontSize = 14 * MainActivity.Factor, TextBrush = new SolidBrush(Color.White) }); node.Annotations = annotations; } private void ButtonTouch(object sender, EventArgs e) { ImageButtonView button = (ImageButtonView)sender; for (int i = 0; i < buttons.ChildCount; i++) { ImageButtonView imageButton = buttons.GetChildAt(i) as ImageButtonView; if (imageButton == null || imageButton.ImageId.TrimEnd('1').Equals(button.ImageId.TrimEnd('1'))) continue; else if (imageButton.ImageId.EndsWith("1", StringComparison.InvariantCulture)) { imageButton.ImageId = imageButton.ImageId.TrimEnd('1'); ImageView image = imageButton.GetChildAt(0) as ImageView; string imageId = imageButton.ImageId + ".png"; if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); image.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } imageButton.SetWillNotDraw(true); imageButton.SetWillNotDraw(false); } } if (!button.ImageId.EndsWith("1", StringComparison.InvariantCulture)) { SegmentType type = SegmentType.OrthoSegment; switch (button.ImageId) { case "DiagramStraight": type = SegmentType.StraightSegment; break; case "DiagramCurve": type = SegmentType.CurveSegment; break; } foreach (Connector connector in diagram.Connectors) connector.SegmentType = type; button.ImageId = button.ImageId + "1"; ImageView image = button.GetChildAt(0) as ImageView; string imageId = button.ImageId + ".png"; if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); image.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } button.SetWillNotDraw(true); button.SetWillNotDraw(false); } } internal static MemoryStream LoadResource(string name) { MemoryStream aMem = new MemoryStream(); var assm = Assembly.GetExecutingAssembly(); var path = string.Format("SampleBrowser.Resources.drawable.{0}", name); var aStream = assm.GetManifestResourceStream(path); aStream.CopyTo(aMem); return aMem; } internal class ImageButtonView : ViewGroup { internal ImageButtonView(Context context) : base(context) { SetBackgroundColor(Color.Transparent); } public string ImageId { get; internal set; } protected override void OnDraw(Canvas canvas) { Paint strokePaint = new Paint(); strokePaint.SetStyle(Paint.Style.Stroke); strokePaint.StrokeWidth = 5 * MainActivity.Factor; strokePaint.Color = Color.Black; canvas.DrawCircle(Width / 2, Height / 2, Width / 3, strokePaint); Paint fillPaint = new Paint(); if (ImageId.EndsWith("1")) fillPaint.Color = Color.Rgb(30, 144, 255); else fillPaint.Color = Color.White; fillPaint.SetStyle(Paint.Style.Fill); canvas.DrawCircle(Width / 2, Height / 2, Width / 3, fillPaint); base.OnDraw(canvas); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { } } public override View GetPropertyWindowLayout(Context context) { LinearLayout gridLinearLayout = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Vertical }; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); layoutParams.TopMargin = 25; gridLinearLayout.LayoutParameters = layoutParams; gridLinearLayout.SetBackgroundResource(Resource.Drawable.LinearLayout_Border); int width = (int)(context.Resources.DisplayMetrics.WidthPixels - context.Resources.DisplayMetrics.Density) / 3; LinearLayout linearLayout4 = new LinearLayout(context); linearLayout4.Orientation = Android.Widget.Orientation.Horizontal; linearLayout4.SetPadding(0, (int)(10 * currentDensity), 0, 0); TextView selectText = new TextView(context) { Text = "Connector Style", Gravity = GravityFlags.Start, TextSize = 5 * currentDensity }; selectText.SetWidth((int)(width * 0.4 * currentDensity)); Spinner spinner = new Spinner(context, SpinnerMode.Dialog); spinner.SetMinimumHeight((int)(20 * currentDensity)); spinner.SetBackgroundColor(Color.Gray); spinner.DropDownWidth = (int)(200 * currentDensity); List<string> list = new List<string>(); list.Add("Default"); list.Add("Dashed"); list.Add("Dotted"); ArrayAdapter<string> dataAdapter = new ArrayAdapter<string>(context, Android.Resource.Layout.SimpleSpinnerItem, list); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); spinner.Adapter = dataAdapter; spinner.ItemSelected += sType_spinner_ItemSelected; spinner.SetGravity(GravityFlags.Start); spinner.SetMinimumWidth(width - (int)(width * 0.4)); linearLayout4.AddView(selectText); linearLayout4.AddView(spinner); LinearLayout linearLayout3 = new LinearLayout(context); linearLayout3.SetPadding(0, (int)(10 * currentDensity), 0, 0); linearLayout3.SetMinimumHeight((int)(40 * currentDensity)); TextView connectorSize = new TextView(context) { Text = "Connector Size", Gravity = GravityFlags.CenterVertical, TextSize = 5 * currentDensity }; connectorSize.SetMinimumHeight((int)(40 * currentDensity)); connectorSize.SetWidth((int)(width * 0.4 * currentDensity)); LinearLayout plusMinus = new LinearLayout(context); plusMinus.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent); plusMinus.SetMinimumWidth(width - (int)(width * 0.4)); ImageButton minusButton = new ImageButton(context); minusButton.SetMinimumHeight((int)(40 * currentDensity)); minusButton.Click += MinusButton_Click; string imageId = "diagramsub.png"; if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); minusButton.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } plusMinus.AddView(minusButton); label = new TextView(context); label.Text = "1"; label.TextAlignment = TextAlignment.Center; label.Gravity = GravityFlags.Center; label.SetMinimumHeight((int)(40 * currentDensity)); label.SetWidth((int)(40 * currentDensity)); plusMinus.AddView(label); ImageButton plusButton = new ImageButton(context); imageId = "diagramplus.png"; plusButton.Click += PlusButton_Click; plusButton.SetMinimumHeight((int)(40 * currentDensity)); if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); plusButton.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } plusMinus.AddView(plusButton); linearLayout3.AddView(connectorSize); linearLayout3.AddView(plusMinus); gridLinearLayout.AddView(linearLayout4); gridLinearLayout.AddView(linearLayout3); return gridLinearLayout; } private void PlusButton_Click(object sender, EventArgs e) { int value = int.Parse(label.Text); if (value < 5) { foreach (Connector connector in diagram.Connectors) connector.Style.StrokeWidth = (value + 1) * MainActivity.Factor; label.Text = (value + 1).ToString(); } } private void MinusButton_Click(object sender, EventArgs e) { int value = int.Parse(label.Text); if (value > 1) { foreach (Connector connector in diagram.Connectors) connector.Style.StrokeWidth = (value - 1) * MainActivity.Factor; label.Text = (value - 1).ToString(); } } void sType_spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; string selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); StrokeStyle strokeStyle = StrokeStyle.Default; switch (selectedItem) { case "Default": strokeStyle = StrokeStyle.Default; break; case "Dashed": strokeStyle = StrokeStyle.Dashed; break; case "Dotted": strokeStyle = StrokeStyle.Dotted; break; } foreach (Connector connector in diagram.Connectors) { connector.Style.StrokeStyle = strokeStyle; } } void sType_spinner_ItemSelected1(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; string selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); int strokeWidth = int.Parse(selectedItem); if (strokeWidth > 0) { foreach (Connector connector in diagram.Connectors) { connector.Style.StrokeWidth = strokeWidth; } } } private Connector AddConnector(Node sourceNode, Node targetNode) { var c1 = new Connector(m_context); c1.SourceNode = sourceNode; c1.TargetNode = targetNode; c1.Style.StrokeWidth = 1 * currentDensity; c1.Style.StrokeBrush = new SolidBrush(Color.Rgb(127, 132, 133)); c1.TargetDecoratorType = DecoratorType.None; return c1; } Node AddNode(int x, int y, string text, Color nodeColor) { Node node = new Node(m_context); node = new Node(x * MainActivity.Factor, y * MainActivity.Factor, 144 * MainActivity.Factor, 108 * MainActivity.Factor, m_context); node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 1; node.Style.Brush = new SolidBrush(nodeColor); node.Style.StrokeBrush = new SolidBrush(Color.Rgb(127, 132, 133)); node.Annotations.Add(new Annotation() { Content = text, FontSize = 20 * MainActivity.Factor, TextBrush = new SolidBrush(Color.White) }); return node; } public override void Destroy() { if (diagram != null) diagram.Dispose(); base.Destroy(); } private void Diagram_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); } //Creates the Node with Specified input Node DrawNode(float x, float y, float w, float h, ShapeType shape) { var node = new Node(m_context); node.OffsetX = x; node.OffsetY = y; node.Width = w; node.Height = h; node.ShapeType = shape; node.Style.StrokeWidth = 1 * 2 * MainActivity.Factor; node.CornerRadius = 30 * 2 * MainActivity.Factor; node.Style.Brush = new SolidBrush(Color.Rgb(255, 129, 0)); node.Ports.Add(new Port() { NodeOffsetX = 0.5, NodeOffsetY = 0, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.5, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 0.5, NodeOffsetY = 1, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.5, IsVisible = false }); return node; } Node DrawCustomShape(float x, float y) { var node = new Node(m_context); node.OffsetX = x * MainActivity.Factor; node.OffsetY = y * MainActivity.Factor; node.Width = 50 * 2 * MainActivity.Factor; node.Height = 40 * 2 * MainActivity.Factor; SfGraphics grap = new SfGraphics(); Pen stroke = new Pen(); stroke.Brush = new SolidBrush(Color.Transparent); stroke.StrokeWidth = 3 * MainActivity.Factor; stroke.StrokeBrush = new SolidBrush(Color.Rgb(24, 161, 237)); grap.DrawEllipse(stroke, new System.Drawing.Rectangle(10, 0, 20, 20)); grap.DrawArc(stroke, 0, 20, 40, 40, 180, 180); node.UpdateSfGraphics(grap); return node; } Connector DrawConnector(Node Src, Node Trgt, Port srcport, Port trgtport, SegmentType type, Color strokeColor, StrokeStyle style, DecoratorType decorator, Color fillColor, Color strokeFill, float sw) { var Conn = new Connector(m_context, Src, Trgt); Conn.SourcePort = srcport; Conn.TargetPort = trgtport; Conn.SegmentType = type; Conn.TargetDecoratorType = decorator; Conn.TargetDecoratorStyle.Fill = fillColor; Conn.TargetDecoratorStyle.StrokeColor = strokeFill; Conn.Style.StrokeWidth = 1 * 2 * MainActivity.Factor; Conn.Style.StrokeBrush = new SolidBrush(strokeColor); Conn.Style.StrokeStyle = style; Conn.TargetDecoratorStyle.Size = sw; Conn.TargetDecoratorStyle.StrokeWidth = 2 * 2 * MainActivity.Factor; return Conn; } public class Employee { public string ParentId { get; set; } public string Name { get; set; } public string Designation { get; set; } public string EmpId { get; set; } } } }<file_sep>/Android/SampleBrowser/Samples/ImageEditor/SerializedTemplate.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Syncfusion.SfImageEditor.Android; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Content; using Android.Content.PM; using Android.Graphics.Drawables; using Android.Views; using System.Collections.Generic; using System.Linq; using Android.Support.V4.Widget; using System.Threading.Tasks; using System.IO; using Android.Content.Res; using System.Text; namespace SampleBrowser { public class SerializedTemplate : SamplePage { internal static Activity Activity { get; set; } View view { get; set; } public static Bitmap Image { get; set; } ImageButton imageview1; ImageButton imageview2; ImageButton imageview3; Context con { get; set; } public static String Name; public override Android.Views.View GetSampleContent(Android.Content.Context context) { con = context; LayoutInflater layoutInflater = LayoutInflater.From(context); view = layoutInflater.Inflate(Resource.Layout.ImageEditorSerialization, null); imageview1 = view.FindViewById<ImageButton>(Resource.Id.banner1); imageview2 = view.FindViewById<ImageButton>(Resource.Id.banner2); imageview3 = view.FindViewById<ImageButton>(Resource.Id.banner3); imageview1.Click += pictureOnClick1; imageview2.Click += pictureOnClick2; imageview3.Click += pictureOnClick3; return view; } public void pictureOnClick1(object sender, EventArgs e) { Name = "Coffee"; Activity = con as Activity; Activity?.StartActivity(typeof(ImageEditorActivity)); Image = ((BitmapDrawable)imageview1.Drawable).Bitmap; } public void pictureOnClick2(object sender, EventArgs e) { Name = "Food"; Activity = con as Activity; Activity?.StartActivity(typeof(ImageEditorActivity)); Image = ((BitmapDrawable)imageview2.Drawable).Bitmap; } public void pictureOnClick3(object sender, EventArgs e) { Name = "Syncfusion"; Activity = con as Activity; Activity?.StartActivity(typeof(ImageEditorActivity)); Image = ((BitmapDrawable)imageview3.Drawable).Bitmap; } [Activity(Label = "SfImageEditor", ScreenOrientation = ScreenOrientation.Portrait, Icon = "@drawable/icon")] public class ImageEditorActivity : Activity { View view { get; set; } LinearLayout contentView { get; set; } private DrawerLayout mDrawerLayout; List<TableItem> tableItems = new List<TableItem>(); ListView listView; SfImageEditor editor; Share share; string location = ""; string content; ViewModel viewModel; AssetManager assets; protected override void OnCreate(Bundle savedInstanceState) { viewModel = new ViewModel(); LayoutInflater layoutInflater = LayoutInflater.From(this); view = layoutInflater.Inflate(Resource.Layout.EditorSerializationMain, null); SetContentView(view); LinearLayout mainLayout = FindViewById<LinearLayout> (Resource.Id.ContentView); listView = FindViewById<ListView>(Resource.Id.right_drawer); mDrawerLayout = (DrawerLayout) FindViewById(Resource.Id.drawer_layout); tableItems.Add(new TableItem() { ImageResourceId = viewModel.ModelList[0].Name,ImageName ="Coffee"}); tableItems.Add(new TableItem() { ImageResourceId = viewModel.ModelList[1].Name,ImageName ="Food"}); tableItems.Add(new TableItem() { ImageResourceId = viewModel.ModelList[2].Name,ImageName ="Syncfusion"}); listView.Adapter = new HomeScreenAdapter(this, tableItems); listView.ItemClick += OnListItemClick; editor = new SfImageEditor(this); editor.ImageSaving+= Editor_ImageSaving; editor.Bitmap = SerializedTemplate.Image; assets = this.Assets; LoadStream(); DelayActionAsync(500, LoadStreamToEditor); //Add ToolBar items HeaderToolBarItem item1 = new HeaderToolBarItem(); item1.Text = "Settings"; item1.Icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.sett); HeaderToolBarItem item2 = new HeaderToolBarItem(); item2.Text = "Share"; item2.Icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.share); HeaderToolBarItem item3 = new HeaderToolBarItem(); item3.Icon = BitmapFactory.DecodeResource(Resources, Resource.Drawable.info_24); editor.ToolbarSettings.ToolbarItems.Add(item1); editor.ToolbarSettings.ToolbarItems.Add(item2); editor.ToolbarSettings.ToolbarItems.Add(item3); editor.ToolbarSettings.ToolbarItemSelected += (sender, e) => { if (e.Toolbar is HeaderToolBarItem) { var text = (e.Toolbar as HeaderToolBarItem).Text; if (e.Toolbar is HeaderToolBarItem) { if ((e.Toolbar as HeaderToolBarItem).Text == "Share") { ShareImage(); } if ((e.Toolbar as HeaderToolBarItem).Text == "Settings") { mDrawerLayout.OpenDrawer(listView); } if ((text != "Reset" && text != "undo" && text != "redo" && text != "Save" && text != "Settings" && text != "Share")) { string strin = "ImageEditor allows you to serialize and deserialize any custom edits(Shapes,Text,Path) over an image. In this sample we have deserialized some custom edits and loaded in to the editor."; AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.SetTitle("About this sample"); alert.SetMessage(strin.ToString()); alert.SetNegativeButton("Ok", (senderAlert, args) => { }); Dialog dialog = alert.Create(); dialog.Show(); } } } }; mainLayout.AddView(editor); base.OnCreate(savedInstanceState); } void LoadStreamToEditor() { for (int i = 0; i < viewModel.ModelList.Count(); i++) { if (SerializedTemplate.Name == viewModel.ModelList[i].ImageName) { using (StreamReader sr = new StreamReader(assets.Open(viewModel.ModelList[i].Imagestream))) { content = sr.ReadToEnd(); byte[] byteArray = Encoding.ASCII.GetBytes(content); MemoryStream stream = new MemoryStream(byteArray); editor.LoadAsJson(stream); viewModel.ModelList[i].Strm = stream; } } } } void LoadStream() { for (int i = 0; i < viewModel.ModelList.Count(); i++) { using (StreamReader sr = new StreamReader(assets.Open(viewModel.ModelList[i].Imagestream))) { content = sr.ReadToEnd(); byte[] byteArray = Encoding.ASCII.GetBytes(content); MemoryStream stream = new MemoryStream(byteArray); viewModel.ModelList[i].Strm = stream; } } } void Editor_ImageSaving(object sender, ImageSavingEventArgs e) { for (int i = 0; i < viewModel.ModelList.Count(); i++) { if (SerializedTemplate.Name == viewModel.ModelList[i].ImageName) { var stream= editor.GetSerializedObject(); viewModel.ModelList[i].Strm=stream; } } } void ShareImage() { editor.Save(); editor.ImageSaving+= (sender, e) => { e.Cancel = false; }; editor.ImageSaved+= (sender, e) => { location = e.Location; }; DelayActionAsync(2500, Sharing); } public async Task DelayActionAsync(int delay, Action action) { await Task.Delay(delay); action(); } void Sharing() { share = new Share(); share.Show("Share", "Message", location); } protected void OnListItemClick(object sender, Android.Widget.AdapterView.ItemClickEventArgs e) { var listView = sender as ListView; var t = tableItems[e.Position]; editor.Bitmap = BitmapFactory.DecodeResource(Resources, t.ImageResourceId); for (int i = 0; i < viewModel.ModelList.Count(); i++) { if (t.ImageResourceId == viewModel.ModelList[i].Name) { Stream str = viewModel.ModelList[i].Strm; editor.LoadAsJson(str); SerializedTemplate.Name = t.ImageName; } } mDrawerLayout.CloseDrawer(listView); } } public class TableItem { public int ImageResourceId { get; set; } public int Name { get; set; } public string ImageName { get; set; } } public class HomeScreenAdapter : BaseAdapter<TableItem> { List<TableItem> items; Activity context; public HomeScreenAdapter(Activity context, List<TableItem> items) : base() { this.context = context; this.items = items; } public override long GetItemId(int position) { return position; } public override TableItem this[int position] { get { return items[position]; } } public override int Count { get { return items.Count; } } public override View GetView(int position, View convertView, ViewGroup parent) { var item = items[position]; View view = convertView; if (view == null) // no view to re-use, create new view = context.LayoutInflater.Inflate(Resource.Layout.CustomListView, null); view.FindViewById<ImageView>(Resource.Id.Image).SetImageResource(item.ImageResourceId); return view; } } } //public class Share //{ // private readonly Context _context; // public Share() // { // _context = Application.Context; // } // public Task Show(string title, string message, string filePath) // { // var extension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower(); // var contentType = string.Empty; // switch (extension) // { // case "pdf": // contentType = "application/pdf"; // break; // case "png": // contentType = "image/png"; // break; // case "jpg": // contentType = "image/jpg"; // break; // default: // contentType = "application/octetstream"; // break; // } // var intent = new Intent(Intent.ActionSend); // intent.SetType(contentType); // intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + filePath)); // intent.PutExtra(Intent.ExtraText, message ?? string.Empty); // intent.PutExtra(Intent.ExtraSubject, title ?? string.Empty); // var chooserIntent = Intent.CreateChooser(intent, title ?? string.Empty); // chooserIntent.SetFlags(ActivityFlags.ClearTop); // chooserIntent.SetFlags(ActivityFlags.NewTask); // _context.StartActivity(chooserIntent); // return Task.FromResult(true); // } //} } <file_sep>/Forms/Diagram/Diagram/Samples/NodeContent/NodeContent.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfDiagram.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfDiagram { public partial class NodeContent : SampleView { public NodeContent() { InitializeComponent(); if (Device.RuntimePlatform == Device.Android) Xamarin.Forms.DependencyService.Get<IText>().GenerateFactor(); //set background color diagram.PageSettings.PageBackGround = Color.White; if (Device.RuntimePlatform == Device.UWP) { diagram.PageSettings.PageWidth = 1600; diagram.PageSettings.PageHeight = double.NaN; diagram.BackgroundColor = Color.White; } diagram.IsReadOnly = true; diagram.EnableSelectors = false; //NodeCollection nodes = new NodeCollection(); var node1 = DrawNode(((float)(280)) * DiagramUtility.factor, 150 * DiagramUtility.factor, 165 * DiagramUtility.factor, 50 * DiagramUtility.factor, ShapeType.RoundedRectangle); node1.Style.StrokeBrush = new SolidBrush(Color.FromRgb(206, 98, 9)); node1.Annotations.Add(new Annotation() { Content = "Establish Project and Team", TextBrush = new SolidBrush(Color.White), FontSize = 10 * DiagramUtility.factor });// CreateLabel("Establish Project and Team", 12) }); diagram.AddNode(node1); var node2 = DrawNode(((float)(280)) * DiagramUtility.factor, (float)(node1.OffsetY + (90 * DiagramUtility.factor)), 165 * DiagramUtility.factor, 50 * DiagramUtility.factor, ShapeType.RoundedRectangle); node2.Style.StrokeBrush = new SolidBrush(Color.FromRgb(206, 98, 9)); if (Device.RuntimePlatform == Device.UWP) { node2.Style.Brush = new SolidBrush(Color.FromRgb(255, 129, 0)); } else node2.Style.Brush = new Syncfusion.SfDiagram.XForms.LinearGradientBrush(0, 30, 150, 30, new Color[] { Color.FromRgb(255, 130, 0), Color.FromRgb(255, 37, 0) }); node2.Style.StrokeWidth = 0; node2.Annotations.Add(new Annotation() { Content = "Define Scope", TextBrush = new SolidBrush(Color.White), FontSize = 10 * DiagramUtility.factor });// Content = CreateLabel("Define Scope", 12) }); diagram.AddNode(node2); var node3 = DrawNode(((float)(280)) * DiagramUtility.factor, (float)(node2.OffsetY + (90 * DiagramUtility.factor)), 165 * DiagramUtility.factor, 50 * DiagramUtility.factor, ShapeType.RoundedRectangle); node3.Style.StrokeBrush = new SolidBrush(Color.FromRgb(206, 98, 9)); node3.Style.StrokeStyle = StrokeStyle.Dashed; node3.Annotations.Add(new Annotation() { Content = "Analyze process As-Is", TextBrush = new SolidBrush(Color.White), FontSize = 10 * DiagramUtility.factor });// Content = CreateLabel("Analyze process As-Is", 12) }); diagram.AddNode(node3); var node4 = DrawNode(((float)(280)) * DiagramUtility.factor, (float)(node3.OffsetY + (90 * DiagramUtility.factor)), 165 * DiagramUtility.factor, 50 * DiagramUtility.factor, ShapeType.RoundedRectangle); node4.Style.StrokeBrush = new SolidBrush(Color.FromRgb(206, 98, 9)); node4.Style.StrokeWidth = 0; node4.Annotations.Add(new Annotation() { Content = "Identify Opportunities", VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, TextBrush = new SolidBrush(Color.White), FontSize = 10 * DiagramUtility.factor });// Content = CreateLabel("Identify opportunities for improvement", 12) }); diagram.AddNode(node4); var node5 = DrawNode(((float)(280)) * DiagramUtility.factor, (float)(node4.OffsetY + (90 * DiagramUtility.factor)), 165 * DiagramUtility.factor, 50 * DiagramUtility.factor, ShapeType.RoundedRectangle); node5.Style.StrokeBrush = new SolidBrush(Color.FromRgb(206, 98, 9)); node5.Style.StrokeWidth = 0; node5.Annotations.Add(new Annotation() { Content = "Design and Implement", TextBrush = new SolidBrush(Color.White), FontSize = 10 * DiagramUtility.factor });// Content = CreateLabel("Design and implement improved processess", 12) }); diagram.AddNode(node5); var node6 = DrawCustomShape(53, 153.22f); node6.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.5, IsVisible = false }); diagram.AddNode(node6); Node labelnode6 = null; if (Device.RuntimePlatform == Device.Android) { labelnode6 = new Node(37 * DiagramUtility.factor, 200 * DiagramUtility.factor, 80 * DiagramUtility.factor, 35 * DiagramUtility.factor); labelnode6.Annotations.Add(new Annotation() { Content = "Sponsor", FontSize = 16 * DiagramUtility.factor, HorizontalAlignment = HorizontalAlignment.Center }); } else { labelnode6 = new Node(33.5f * DiagramUtility.factor, 195 * DiagramUtility.factor, 80 * DiagramUtility.factor, 35 * DiagramUtility.factor); labelnode6.Annotations.Add(new Annotation() { Content = "Sponsor", FontSize = 10 * DiagramUtility.factor, }); } labelnode6.Style = new Syncfusion.SfDiagram.XForms.Style() { StrokeBrush = new SolidBrush(Color.Transparent), Brush = new SolidBrush(Color.Transparent) }; diagram.AddNode(labelnode6); var node7 = DrawCustomShape(53, 347); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0, IsVisible = false }); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.3, IsVisible = false }); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.6, IsVisible = false }); node7.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 1, IsVisible = false }); diagram.AddNode(node7); Node labelnode7 = null; if (Device.RuntimePlatform == Device.Android) { labelnode7 = new Node(50 * DiagramUtility.factor, 395 * DiagramUtility.factor, 60 * DiagramUtility.factor, 50 * DiagramUtility.factor); labelnode7.Annotations.Add(new Annotation() { Content = "Domain Experts", FontSize = 15 * DiagramUtility.factor, HorizontalAlignment = HorizontalAlignment.Center }); } else { labelnode7 = new Node(55 * DiagramUtility.factor, 393 * DiagramUtility.factor, 60 * DiagramUtility.factor, 50 * DiagramUtility.factor); labelnode7.Annotations.Add(new Annotation() { Content = "Domain Experts", FontSize = 10 * DiagramUtility.factor, }); } labelnode7.Style = new Syncfusion.SfDiagram.XForms.Style() { StrokeBrush = new SolidBrush(Color.Transparent), Brush = new SolidBrush(Color.Transparent) }; diagram.AddNode(labelnode7); var node8 = DrawCustomShape(590, 153.22f); node8.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.5, IsVisible = false }); diagram.AddNode(node8); Node labelnode8 = null; if (Device.RuntimePlatform == Device.Android) { labelnode8 = new Node(590.5f * DiagramUtility.factor, 205 * DiagramUtility.factor, 65 * DiagramUtility.factor, 39 * DiagramUtility.factor); labelnode8.Annotations.Add(new Annotation() { Content = "Project Manager", FontSize = 15 * DiagramUtility.factor, HorizontalAlignment = HorizontalAlignment.Center }); } else { labelnode8 = new Node(590.5f * DiagramUtility.factor, 200 * DiagramUtility.factor, 65 * DiagramUtility.factor, 39 * DiagramUtility.factor); labelnode8.Annotations.Add(new Annotation() { Content = "Project Manager", FontSize = 10 * DiagramUtility.factor, }); } labelnode8.Style = new Syncfusion.SfDiagram.XForms.Style() { StrokeBrush = new SolidBrush(Color.Transparent), Brush = new SolidBrush(Color.Transparent) }; diagram.AddNode(labelnode8); var node9 = DrawCustomShape(590, 347); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0, IsVisible = false }); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.3, IsVisible = false }); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.6, IsVisible = false }); node9.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 1, IsVisible = false }); diagram.AddNode(node9); Node labelnode9 = null; if (Device.RuntimePlatform == Device.Android) { labelnode9 = new Node(589 * DiagramUtility.factor, 399.5f * DiagramUtility.factor, 62 * DiagramUtility.factor, 39 * DiagramUtility.factor); labelnode9.Annotations.Add(new Annotation() { Content = "Business Analyst", FontSize = 15 * DiagramUtility.factor, HorizontalAlignment = HorizontalAlignment.Center }); } else { labelnode9 = new Node(591 * DiagramUtility.factor, 398.5f * DiagramUtility.factor, 65 * DiagramUtility.factor, 39 * DiagramUtility.factor); labelnode9.Annotations.Add(new Annotation() { Content = "Business Analyst", FontSize = 10 * DiagramUtility.factor, }); } labelnode9.Style = new Syncfusion.SfDiagram.XForms.Style() { StrokeBrush = new SolidBrush(Color.Transparent), Brush = new SolidBrush(Color.Transparent) }; diagram.AddConnector(DrawConnector(node1, node2, node1.Ports[2], node2.Ports[0], SegmentType.OrthoSegment, Color.FromRgb(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, Color.FromRgb(127, 132, 133), Color.FromRgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node2, node3, node2.Ports[2], node3.Ports[0], SegmentType.OrthoSegment, Color.FromRgb(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, Color.FromRgb(127, 132, 133), Color.FromRgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node3, node4, node3.Ports[2], node4.Ports[0], SegmentType.OrthoSegment, Color.FromRgb(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, Color.FromRgb(127, 132, 133), Color.FromRgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node4, node5, node4.Ports[2], node5.Ports[0], SegmentType.OrthoSegment, Color.FromRgb(127, 132, 133), StrokeStyle.Default, DecoratorType.Filled45Arrow, Color.FromRgb(127, 132, 133), Color.FromRgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node6, node1, node6.Ports[0], node1.Ports[3], SegmentType.StraightSegment, Color.FromRgb(127, 132, 133), StrokeStyle.Dashed, DecoratorType.Filled45Arrow, Color.FromRgb(127, 132, 133), Color.FromRgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node8, node1, node8.Ports[0], node1.Ports[1], SegmentType.StraightSegment, Color.FromRgb(127, 132, 133), StrokeStyle.Dashed, DecoratorType.Filled45Arrow, Color.FromRgb(127, 132, 133), Color.FromRgb(127, 132, 133), 8)); diagram.AddConnector(DrawConnector(node7, node2, node7.Ports[0], node2.Ports[3], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Square, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node7, node3, node7.Ports[1], node3.Ports[3], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Square, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node7, node4, node7.Ports[2], node4.Ports[3], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Square, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node7, node5, node7.Ports[3], node5.Ports[3], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Square, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node9, node2, node9.Ports[0], node2.Ports[1], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Circle, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node9, node3, node9.Ports[1], node3.Ports[1], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Circle, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node9, node4, node9.Ports[2], node4.Ports[1], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Circle, Color.Black, Color.Black, 6)); diagram.AddConnector(DrawConnector(node9, node5, node9.Ports[3], node5.Ports[1], SegmentType.StraightSegment, Color.Black, StrokeStyle.Default, DecoratorType.Circle, Color.Black, Color.Black, 6)); diagram.AddNode(labelnode9); diagram.Loaded += Diagram_Loaded; } private void Diagram_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); } Node DrawNode(float x, float y, float w, float h, ShapeType shape) { var node = new Node(); node.OffsetX = x; node.OffsetY = y; node.Width = w; node.Height = h; node.ShapeType = shape; node.Style.StrokeWidth = 1 * DiagramUtility.factor; node.Style.Brush = new SolidBrush(Color.FromRgb(255, 129, 0)); node.Ports.Add(new Port() { NodeOffsetX = 0.5, NodeOffsetY = 0, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 1, NodeOffsetY = 0.5, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 0.5, NodeOffsetY = 1, IsVisible = false }); node.Ports.Add(new Port() { NodeOffsetX = 0, NodeOffsetY = 0.5, IsVisible = false }); return node; } Connector DrawConnector(Node Src, Node Trgt, Port srcport, Port trgtport, SegmentType type, Color strokeColor, StrokeStyle style, DecoratorType decorator, Color fillColor, Color strokeFill, float sw) { var Conn = new Connector(); Conn.SourceNode = Src; Conn.TargetNode = Trgt; Conn.SourcePort = srcport; Conn.TargetPort = trgtport; Conn.SegmentType = type; Conn.TargetDecoratorType = decorator; Conn.TargetDecoratorStyle.Fill = fillColor; Conn.TargetDecoratorStyle.Stroke = strokeFill; Conn.Style.StrokeWidth = 1 * DiagramUtility.factor; Conn.Style.StrokeBrush = new SolidBrush(strokeColor); Conn.Style.StrokeStyle = style; Conn.TargetDecoratorStyle.Width = sw * DiagramUtility.factor; Conn.TargetDecoratorStyle.StrokeThickness = 1 * DiagramUtility.factor; return Conn; } Node DrawCustomShape(float x, float y) { var node = new Node(); if (Device.RuntimePlatform == Device.Android) { node.Width = 50 * DiagramUtility.factor; node.Height = 40 * DiagramUtility.factor; } else node.Width = node.Height = 40 * DiagramUtility.factor; node.OffsetX = x * DiagramUtility.factor; node.OffsetY = y * DiagramUtility.factor; if (Device.RuntimePlatform == Device.UWP) { node.Style.Brush = new SolidBrush(Color.Transparent); node.Style.StrokeBrush = new SolidBrush(Color.FromRgb(24, 161, 237)); node.Style.StrokeWidth = 3 * DiagramUtility.factor; } SfGraphicsPath sfpath4 = new SfGraphicsPath(); SfGraphics grap = new SfGraphics(); Pen stroke = new Pen(); stroke.Brush = new SolidBrush(Color.Transparent); stroke.StrokeWidth = 3; stroke.StrokeBrush = new SolidBrush(Color.FromRgb(24, 161, 237)); grap.DrawEllipse(stroke, new Rectangle(10, 0, 20, 20)); if (Device.RuntimePlatform == Device.UWP) grap.DrawArc(stroke, 0, 20, 40, 40, 0, 180); else grap.DrawArc(stroke, 0, 20, 40, 40, 180, 180); node.UpdateSfGraphics(grap); return node; } StackLayout CreateLabel(string text, int Size) { StackLayout contentLayout = new StackLayout() { WidthRequest = 150, HeightRequest = 45, Orientation = StackOrientation.Vertical }; var label = new Label(); label.WidthRequest = 150; label.HeightRequest = 45; label.VerticalTextAlignment = TextAlignment.Center; label.HorizontalTextAlignment = TextAlignment.Center; label.Text = text; label.FontSize = Size; label.TextColor = Color.White; contentLayout.Children.Add(label); return contentLayout; } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/SplineRangeArea.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class SplineRangeArea : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Product Price Comparison"; chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; chart.SetBackgroundColor(Color.White); CategoryAxis categoryaxis = new CategoryAxis(); categoryaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; categoryaxis.ShowMajorGridLines = false; categoryaxis.LabelStyle.MarginTop = 10; categoryaxis.MajorTickStyle.TickSize = 10; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Minimum = 5; numericalaxis.Maximum = 55; numericalaxis.Interval = 5; numericalaxis.ShowMajorGridLines = false; numericalaxis.ShowMinorGridLines = false; chart.SecondaryAxis = numericalaxis; SplineRangeAreaSeries series = new SplineRangeAreaSeries(); series.EnableAnimation = true; series.ItemsSource = MainPage.GetSplineRangeArea1(); series.XBindingPath = "XValue"; series.High = "High"; series.Low = "Low"; series.Label = "Product A"; series.TooltipEnabled = true; series.EnableAnimation = true; chart.Series.Add(series); SplineRangeAreaSeries series1 = new SplineRangeAreaSeries(); series1.EnableAnimation = true; series1.ItemsSource = MainPage.GetSplineRangeArea2(); series1.XBindingPath = "XValue"; series1.High = "High"; series1.Low = "Low"; series1.Label = "Product B"; series1.TooltipEnabled = true; series1.EnableAnimation = true; chart.Series.Add(series1); return chart; } } } <file_sep>/Android/SampleBrowser/Samples/NavigationDrawer/RoundedImageView.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Android.Widget; using Android.Graphics; using Android.Graphics.Drawables; using Android.Util; namespace SampleBrowser { public class RoundedImageView :ImageView { int width; public RoundedImageView (Context context,int _width, int _height) : base (context) { width = _width; } public RoundedImageView (Context context, IAttributeSet attrs) : base (context, attrs) { } public RoundedImageView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) { } protected override void OnDraw (Canvas canvas) { Drawable drawable = Drawable; if (drawable == null) { return; } if (Width == 0 || Height == 0) { return; } Bitmap b = ((BitmapDrawable) drawable).Bitmap; Bitmap bitmap = b.Copy(Bitmap.Config.Argb8888, true); int w = width; Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w); canvas.DrawBitmap(roundBitmap, 0, 0, null); } public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) { Bitmap finalBitmap; if (bitmap.Width != radius || bitmap.Height!= radius) finalBitmap = Bitmap.CreateScaledBitmap(bitmap, radius, radius, false); else finalBitmap = bitmap; Bitmap output = Bitmap.CreateBitmap(finalBitmap.Width, finalBitmap.Height, Bitmap.Config.Argb8888); Canvas canvas = new Canvas(output); Paint paint = new Paint(); Rect rect = new Rect(0, 0, finalBitmap.Width, finalBitmap.Height); paint.AntiAlias=true; paint.FilterBitmap=true; paint.Dither=true; canvas.DrawARGB(0, 0, 0, 0); paint.Color=Color.ParseColor("#BAB399"); canvas.DrawCircle(finalBitmap.Width / 2 + 0.7f, finalBitmap.Height / 2 + 0.7f, finalBitmap.Width / 2 + 0.1f, paint); paint.SetXfermode(new PorterDuffXfermode(PorterDuff.Mode.SrcIn)); canvas.DrawBitmap(finalBitmap, rect, rect, paint); return output; } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/ViewModel/OnBoardHelpsViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "OnBoardHelpsViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A ViewModel for OnBoardHelps sample. /// </summary> public class OnBoardHelpsViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// Holds the instance of the repository. /// </summary> private OrderInfoRepository order; /// <summary> /// Backing field for OrdersInfo collection. /// </summary> private ObservableCollection<OrderInfo> ordersInfo; /// <summary> /// Backing field for the DeleteCommand. /// </summary> private Command<OrderInfo> deleteCommand; /// <summary> /// Backing field for the CurrentRotatorItemIndex. /// </summary> private int currentRotatorItemIndex; /// <summary> /// Backing field for the NextLabelVisibility. /// </summary> private bool nextLabelVisibility; /// <summary> /// Backing field for the OkLabelVisibility. /// </summary> private bool labelOkVisibility; /// <summary> /// Backing field for the OverlayVisibility. /// </summary> private bool overlayVisibility; /// <summary> /// Backing field for the popupVisibility. /// </summary> private bool popupIsOpen; #endregion #region Constructor /// <summary> /// Initializes a new instance of the OnBoardHelpsViewModel class. /// </summary> public OnBoardHelpsViewModel() { this.SetRowstoGenerate(100); this.DeleteCommand = new Command<OrderInfo>(this.DeleteRowData); this.SetBindingImageSource(); this.ChangeRotatorItem = new Command(this.SelectNextRotatorItem); this.CurrentRotatorItemIndex = 0; this.NextLabelVisibility = true; this.OkLabelVisibility = false; this.OverlayVisibility = true; this.OverlayColor = Color.FromRgba(0, 0, 0, 0.7); } #endregion #region Events /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Properties /// <summary> /// Gets or sets the Command that is executed when Delete is clicked. /// </summary> public Command<OrderInfo> DeleteCommand { get { return this.deleteCommand; } set { this.deleteCommand = value; this.RaisePropertyChanged("DeleteCommand"); } } /// <summary> /// Gets or sets the source for the HandSymbol Image for drag and drop illustration. /// </summary> public string HandSymbolImage { get; set; } /// <summary> /// Gets or sets the source for the layout image for drag and drop illustration. /// </summary> public string DragAndDropLayoutImage { get; set; } /// <summary> /// Gets or sets the source for the Editing illustration Image. /// </summary> public string EditingIllustrationImage { get; set; } /// <summary> /// Gets or sets the source for the Resizing illustration Image. /// </summary> public string ResizingIllustrationImage { get; set; } /// <summary> /// Gets or sets the source for the Swiping illustration Image. /// </summary> public string SwipingIllustrationImage { get; set; } /// <summary> /// Gets or sets the command for changing the rotator item. /// </summary> public Command ChangeRotatorItem { get; set; } /// <summary> /// Gets or sets the background color for the Overlay. /// </summary> public Color OverlayColor { get; set; } /// <summary> /// Gets or sets the current item's index in the rotator. /// </summary> public int CurrentRotatorItemIndex { get { return this.currentRotatorItemIndex; } set { this.currentRotatorItemIndex = value; this.RaisePropertyChanged("CurrentRotatorItemIndex"); } } /// <summary> /// Gets or sets a value indicating whether next label should be visible or not. /// </summary> public bool NextLabelVisibility { get { return this.nextLabelVisibility; } set { this.nextLabelVisibility = value; this.RaisePropertyChanged("NextLabelVisibility"); } } /// <summary> /// Gets or sets a value indicating whether ok label should be visible or not. /// </summary> public bool OkLabelVisibility { get { return this.labelOkVisibility; } set { this.labelOkVisibility = value; this.RaisePropertyChanged("OkLabelVisibility"); } } /// <summary> /// Gets or sets a value indicating whether overlay should be visible or not. /// </summary> public bool OverlayVisibility { get { return this.overlayVisibility; } set { this.overlayVisibility = value; this.RaisePropertyChanged("OverlayVisibility"); } } /// <summary> /// Gets or sets a value indicating whether popup is open or not. /// </summary> public bool PopupIsOpen { get { return this.popupIsOpen; } set { this.popupIsOpen = value; this.RaisePropertyChanged("PopupIsOpen"); } } #region ItemsSource /// <summary> /// Gets or sets the OrdersInfo and notifies when user value gets changed. /// </summary> public ObservableCollection<OrderInfo> OrdersInfo { get => this.ordersInfo; set { this.ordersInfo = value; this.RaisePropertyChanged("OrdersInfo"); } } #endregion #endregion #region ItemSource Generator /// <summary> /// Generates Rows with given count /// </summary> /// <param name="count">integer type of parameter named as count</param> public void SetRowstoGenerate(int count) { this.order = new OrderInfoRepository(); this.ordersInfo = this.order.GetOrderDetails(count); } #endregion #region Private Methods /// <summary> /// Deletes the row data. /// </summary> /// <param name="bindingObject">The binding object.</param> private void DeleteRowData(OrderInfo bindingObject) { this.OrdersInfo.Remove(bindingObject); } /// <summary> /// Sets the ImageSource for the Images. /// </summary> private void SetBindingImageSource() { this.HandSymbolImage = "HandSymbol.png"; this.EditingIllustrationImage = "EditIllustration.png"; this.ResizingIllustrationImage = "ResizingIllustration.png"; this.SwipingIllustrationImage = "SwipeIllustration.png"; this.DragAndDropLayoutImage = "DragAndDropIllustration.png"; } /// <summary> /// Selects the next item in the rotator. /// </summary> private void SelectNextRotatorItem() { if (this.CurrentRotatorItemIndex < 2) { this.CurrentRotatorItemIndex++; } else if (this.CurrentRotatorItemIndex == 2) { this.NextLabelVisibility = false; this.OkLabelVisibility = true; this.CurrentRotatorItemIndex++; } else { this.OkLabelVisibility = false; this.OverlayVisibility = false; this.PopupIsOpen = false; } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/DetailsView/DetailsView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DetailsView.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using Core; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; [Preserve(AllMembers = true)] [XamlCompilation(XamlCompilationOptions.Compile)] /// <summary> /// A sampleView that contains the DetailsView sample. /// </summary> public partial class DetailsView : SampleView { /// <summary> /// Initializes a new instance of the DetailsView class. /// </summary> public DetailsView() { this.InitializeComponent(); } /// <summary> /// You can override this method while View was disappear from window /// </summary> public override void OnDisappearing() { base.OnDisappearing(); if (this.listView != null) { this.listView.Dispose(); this.listView = null; } if (this.notificationPopup != null) { this.notificationPopup.Dispose(); this.notificationPopup = null; } if (this.popUp != null) { this.popUp.Dispose(); this.popUp = null; } } } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/Model/TicketBookingInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "TicketBookingInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Xamarin.Forms; /// <summary> /// A class contains Properties and Notifies that a property value has changed /// </summary> public class TicketBookingInfo { /// <summary> /// Gets or sets the MovieName /// </summary> public string MovieName { get; set; } /// <summary> /// Gets or sets the Cast /// </summary> public string Cast { get; set; } /// <summary> /// Gets or sets the MovieImage /// </summary> public string MovieImage { get; set; } /// <summary> /// Gets or sets the Timing1 /// </summary> public string Timing1 { get; set; } /// <summary> /// Gets or sets the Timing2 /// </summary> public string Timing2 { get; set; } /// <summary> /// Gets or sets the TheaterName /// </summary> public string TheaterName { get; set; } /// <summary> /// Gets or sets the TheaterLocation /// </summary> public string TheaterLocation { get; set; } } }<file_sep>/Forms/PDF/PDF/Samples/TableFeatures/TableFeatures.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Grid; using Syncfusion.Pdf.Interactive; using Syncfusion.Pdf.Tables; using System.Reflection; using Xamarin.Forms; using System.IO; using System.Xml.Linq; using SampleBrowser.Core; namespace SampleBrowser.PDF { public partial class TableFeatures : SampleView { public TableFeatures() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } PdfPen borderPen; PdfPen transparentPen; float cellSpacing = 7f; float margin = 40f; PdfFont smallFont; PdfLightTable pdfLightTable = null; void OnButtonClicked(object sender, EventArgs e) { #region Field Definitions //Load product data. IEnumerable<Products> products = DataProvider.GetProducts(); //Create a new PDF standard font PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 8f); smallFont = new PdfStandardFont(font, 5f); PdfFont bigFont = new PdfStandardFont(font, 16f); //Create a new PDF solid brush PdfBrush orangeBrush = new PdfSolidBrush(new PdfColor(247, 148, 29)); PdfBrush grayBrush = new PdfSolidBrush(new PdfColor(170, 171, 171)); //Create a new PDF pen borderPen = new PdfPen(PdfBrushes.DarkGray, .3f); borderPen.LineCap = PdfLineCap.Square; transparentPen = new PdfPen(PdfBrushes.Transparent, .3f); transparentPen.LineCap = PdfLineCap.Square; # endregion //Create a new PDF document PdfDocument document = new PdfDocument(); //Set the margins document.PageSettings.Margins.All = 0; # region Footer //Create a new footer template PdfPageTemplateElement footer = new PdfPageTemplateElement(new RectangleF(new PointF(0, document.PageSettings.Height - 40), new SizeF(document.PageSettings.Width, 40))); footer.Graphics.DrawRectangle(new PdfSolidBrush(new PdfColor(77, 77, 77)), footer.Bounds); footer.Graphics.DrawString("http://www.syncfusion.com", font, grayBrush, new PointF(footer.Width - (footer.Width / 4), 15)); footer.Graphics.DrawString("Copyright © 2001 - 2017 Syncfusion Inc.", font, grayBrush, new PointF(0, 15)); //Add the footer template at the bottom of the page document.Template.Bottom = footer; # endregion //Add a new PDF page PdfPage page = document.Pages.Add(); page.Graphics.DrawRectangle(orangeBrush, new RectangleF(PointF.Empty, new SizeF(page.Graphics.ClientSize.Width, margin))); //Draw the text to the PDF page page.Graphics.DrawString("Essential Studio File Formats Edition", bigFont, PdfBrushes.White, new PointF(10, 10)); # region PdfLightTable //Create a PDF light table pdfLightTable = new PdfLightTable(); pdfLightTable.DataSource = products; pdfLightTable.Style.DefaultStyle.BorderPen = transparentPen; for (int i = 0; i < pdfLightTable.Columns.Count; i++) { if (i % 2 == 0) pdfLightTable.Columns[i].Width = 16.5f; } pdfLightTable.Style.CellSpacing = cellSpacing; pdfLightTable.BeginRowLayout += new BeginRowLayoutEventHandler(pdfLightTable_BeginRowLayout); pdfLightTable.BeginCellLayout += new BeginCellLayoutEventHandler(pdfLightTable_BeginCellLayout); pdfLightTable.Style.DefaultStyle.Font = font; PdfLayoutResult result = pdfLightTable.Draw(page, new RectangleF(new PointF(margin, 70), new SizeF(page.Graphics.ClientSize.Width - (2 * margin), page.Graphics.ClientSize.Height - margin))); # endregion page.Graphics.DrawString("What You Get with Syncfusion", bigFont, orangeBrush, new PointF(margin, result.Bounds.Bottom + 50)); # region PdfGrid //Create a new PDF grid PdfGrid pdfGrid = new PdfGrid(); IEnumerable<Report> report = DataProvider.GetReport(); pdfGrid.DataSource = report; pdfGrid.Headers.Clear(); pdfGrid.Columns[0].Width = 80; pdfGrid.Style.Font = font; pdfGrid.Style.CellSpacing = 15f; for (int i = 0; i < pdfGrid.Rows.Count; i++) { if (i % 2 == 0) { PdfGridCell cell = pdfGrid.Rows[i].Cells[0]; cell.RowSpan = 2; cell.Value = ""; cell = pdfGrid.Rows[i].Cells[1]; cell.Style.Font = bigFont; } for (int j = 0; j < pdfGrid.Columns.Count; j++) { pdfGrid.Rows[i].Cells[j].Style.Borders.All = transparentPen; } } //Create a PDF grid layout format PdfGridLayoutFormat gridLayoutFormat = new PdfGridLayoutFormat(); //Set pagination gridLayoutFormat.Layout = PdfLayoutType.Paginate; //Draw the grid to the PDF document pdfGrid.Draw(page, new RectangleF(new PointF(margin, result.Bounds.Bottom + 75), new SizeF(page.Graphics.ClientSize.Width - (2 * margin), page.Graphics.ClientSize.Height - margin)), gridLayoutFormat); #endregion MemoryStream stream = new MemoryStream(); //Save the PDF document document.Save(stream); //Close the PDF document document.Close(true); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("TableFeatures.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("TableFeatures.pdf", "application/pdf", stream); } # region PdfLightTable Events void pdfLightTable_BeginRowLayout(object sender, BeginRowLayoutEventArgs args) { if (args.RowIndex % 2 == 0) args.MinimalHeight = 20; else args.MinimalHeight = 30; } void pdfLightTable_BeginCellLayout(object sender, BeginCellLayoutEventArgs args) { if (args.RowIndex > -1 && args.CellIndex > -1) { float x = args.Bounds.X; float y = args.Bounds.Y; float width = args.Bounds.Right; float height = args.Bounds.Bottom; if (args.Value == "dummy") { args.Skip = true; return; } if (args.CellIndex % 2 == 0 && !string.IsNullOrEmpty(args.Value)) { args.Skip = true; } if (args.Value.Contains("http")) { args.Skip = true; // Create the Text Web Link PdfTextWebLink textLink = new PdfTextWebLink(); textLink.Url = args.Value; textLink.Text = "Know more..."; textLink.Brush = PdfBrushes.Black; textLink.Font = smallFont; textLink.DrawTextWebLink(args.Graphics, new PointF(args.Bounds.X + 2 * args.Bounds.Width / 3, args.Bounds.Y)); } # region Draw manual borders if (args.RowIndex % 3 == 0)//top { if (args.CellIndex % 2 == 0) width += cellSpacing; args.Graphics.DrawLine(borderPen, new PointF(x, y), new PointF(width, y)); } else if (args.RowIndex % 3 == 2)//bottom { if (args.CellIndex % 2 == 0) width += cellSpacing; args.Graphics.DrawLine(borderPen, new PointF(x, height), new PointF(width, height)); } if (args.CellIndex % 2 == 0)//left { if (args.RowIndex % 3 != 2) height += cellSpacing; args.Graphics.DrawLine(borderPen, new PointF(x, y), new PointF(x, height)); } else if (args.CellIndex % 2 != 0)//right { if (args.RowIndex % 3 != 2) height += cellSpacing; args.Graphics.DrawLine(borderPen, new PointF(width, y), new PointF(width, height)); } # endregion } } # endregion } internal sealed class DataProvider { public static IEnumerable<Products> GetProducts() { #if COMMONSB Stream xmlStream = typeof(TableFeatures).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Products.xml"); #else Stream xmlStream = typeof(TableFeatures).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Products.xml"); #endif using (StreamReader reader = new StreamReader(xmlStream, true)) { return XElement.Parse(reader.ReadToEnd()) .Elements("Products") .Select(c => new Products { Image1 = c.Element("Image1").Value, Description1 = c.Element("Description1").Value, Image2 = c.Element("Image2").Value, Description2 = c.Element("Description2").Value, Image3 = (c.Element("Image3") != null) ? c.Element("Image3").Value : "dummy", Description3 = (c.Element("Description3") != null) ? c.Element("Description3").Value : "dummy", }); } } public static IEnumerable<Report> GetReport() { #if COMMONSB Stream xmlStream = typeof(TableFeatures).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Report.xml"); #else Stream xmlStream = typeof(TableFeatures).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Report.xml"); #endif using (StreamReader reader = new StreamReader(xmlStream, true)) { return XElement.Parse(reader.ReadToEnd()) .Elements("Report") .Select(c => new Report { Image = c.Element("Image").Value, Description = c.Element("Description").Value, }); } } } #region Products public class Products { public string Image1 { get; set; } public string Description1 { get; set; } public string Image2 { get; set; } public string Description2 { get; set; } public string Image3 { get; set; } public string Description3 { get; set; } } #endregion #region Report public class Report { public string Image { get; set; } public string Description { get; set; } } #endregion } <file_sep>/Forms/Diagram/Diagram.Droid/CodeviewerDependency.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Text; using SampleBrowser; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.IO; using Xamarin.Forms; using System; [assembly: Dependency(typeof(SampleBrowser.SfDiagram.Droid.Text))] namespace SampleBrowser.SfDiagram.Droid { class Text : IText { public object GetTextView(string name , float width) { TextView labelAnnotation = new TextView(Android.App.Application.Context); labelAnnotation.Text = name; labelAnnotation.SetTextSize(Android.Util.ComplexUnitType.Px, 14 * DiagramUtility.factor); labelAnnotation.Gravity = Android.Views.GravityFlags.Center; labelAnnotation.SetTextColor(Android.Graphics.Color.White); labelAnnotation.Typeface = Android.Graphics.Typeface.Create(".SF UI Text", Android.Graphics.TypefaceStyle.Normal); int widthMeasureSpec = Android.Views.View.MeasureSpec.MakeMeasureSpec( (int)width, Android.Views.MeasureSpecMode.AtMost); int heightMeasureSpec = Android.Views.View.MeasureSpec.MakeMeasureSpec( 0, Android.Views.MeasureSpecMode.Unspecified); labelAnnotation.Measure(widthMeasureSpec, heightMeasureSpec); labelAnnotation.Left = labelAnnotation.Top = 0; labelAnnotation.Bottom = labelAnnotation.MeasuredHeight; labelAnnotation.Right = labelAnnotation.MeasuredWidth; return labelAnnotation; } public void GenerateFactor() { DiagramUtility.currentDensity = Android.App.Application.Context.Resources.DisplayMetrics.Density; } } }<file_sep>/Android/SampleBrowser/Samples/SegmentedView/readme.md The `SfSegmentedControl` lets users choose from a linear set of two or more segments, each functioning as a button. The following sample is available for segmented control to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](SegmentViewGettingStarted.cs)| It demonstrates the following functionalities of segmented control like displaying the segments with text, font icons and handling the selection on segmented items.| <file_sep>/Android/SampleBrowser/Samples/Calendar/CalendarLocalization/CalendarLocalization_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Java.Util; using Com.Syncfusion.Calendar; using Com.Syncfusion.Calendar.Enums; using Com.Syncfusion.Navigationdrawer; using Android.Graphics; namespace SampleBrowser { public class CalendarLocalization_Mobile : IDisposable { /********************************* **Local Variable Inizialisation** *********************************/ private Java.Util.Locale localinfo = new Java.Util.Locale("zn", "CH"); private ArrayAdapter<String> dataAdapter; private LinearLayout propertylayout; private SeparatorView separate; private LinearLayout.LayoutParams layoutParams1; private Spinner cultureSpinner; private TextView culturetxt; private FrameLayout mainView; private SfCalendar calendar; private Context context; private int width; public View GetSampleContent(Context context) { /************ **Calendar** ************/ calendar = new SfCalendar(context); calendar.ViewMode = ViewMode.MonthView; calendar.ShowEventsInline = false; calendar.HeaderHeight = 100; calendar.Locale = new Java.Util.Locale("zh", "CN"); MonthViewLabelSetting labelSettings = new MonthViewLabelSetting(); labelSettings.DateLabelSize = 14; MonthViewSettings monthViewSettings = new MonthViewSettings(); monthViewSettings.MonthViewLabelSetting = labelSettings; monthViewSettings.SelectedDayTextColor = Color.Black; monthViewSettings.TodayTextColor = Color.ParseColor("#1B79D6"); monthViewSettings.InlineBackgroundColor = Color.ParseColor("#E4E8ED"); monthViewSettings.WeekDayBackgroundColor = Color.ParseColor("#F7F7F7"); calendar.MonthViewSettings = monthViewSettings; //main View mainView = new FrameLayout(context); mainView.AddView(calendar); return mainView; } public View GetPropertyWindowLayout(Context context1) { context = context1; width = context.Resources.DisplayMetrics.WidthPixels / 2; CultureLayout(); /****************** **propertylayout** ******************/ propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; propertylayout.AddView(culturetxt); propertylayout.AddView(cultureSpinner); // propertylayout.AddView(separate, layoutParams1); propertylayout.SetPadding(20, 10, 10, 10); return propertylayout; } private void CultureLayout() { /*********** **Culture** ***********/ culturetxt = new TextView(context); culturetxt.TextSize = 20; culturetxt.Text = "Culture"; //Culture List List<String> cultureList = new List<String>(); cultureList.Add("Chinese"); cultureList.Add("Spanish"); cultureList.Add("English"); cultureList.Add("French"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, cultureList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //Culture Spinner cultureSpinner = new Spinner(context, SpinnerMode.Dialog); cultureSpinner.Adapter = dataAdapter; //Culture Item Selected Listener cultureSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Chinese")) { localinfo = Java.Util.Locale.China; //new Java.Util.Locale("en","US"); } if (selectedItem.Equals("Spanish")) { localinfo = new Java.Util.Locale("es", "AR"); } if (selectedItem.Equals("English")) { localinfo = Java.Util.Locale.Us; } if (selectedItem.Equals("French")) { localinfo = Java.Util.Locale.France; } }; //separate separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); //Layout Params layoutParams1 = new LinearLayout.LayoutParams(width * 2, 5); layoutParams1.SetMargins(0, 20, 0, 0); } /************************ **Apply Changes Method** ************************/ public void OnApplyChanges() { calendar.Locale = localinfo; } public void Dispose() { if (calendar != null) { calendar.Dispose(); calendar = null; } if (mainView != null) { mainView.Dispose(); mainView = null; } if (culturetxt != null) { culturetxt.Dispose(); culturetxt = null; } if (cultureSpinner != null) { cultureSpinner.Dispose(); cultureSpinner = null; } if (layoutParams1 != null) { layoutParams1.Dispose(); layoutParams1 = null; } if (separate != null) { separate.Dispose(); separate = null; } if (propertylayout != null) { propertylayout.Dispose(); propertylayout = null; } if (dataAdapter != null) { dataAdapter.Dispose(); dataAdapter = null; } if (localinfo != null) { localinfo.Dispose(); localinfo = null; } } } }<file_sep>/Forms/DocIO/DocIO/Samples/MarkdownToWord/MarkdownToWord.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using SampleBrowser.Core; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Xamarin.Forms; using Syncfusion.Office; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; namespace SampleBrowser.DocIO { public partial class MarkdownToWord : SampleView { public MarkdownToWord() { InitializeComponent(); this.docxButton.IsChecked = true; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.FontSize = 13.5; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = typeof(MarkdownToWord).GetTypeInfo().Assembly; #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif Stream inputStream = assembly.GetManifestResourceStream(rootPath + "MarkdownToWord.md"); // Loads the stream into Word Document. WordDocument document = new WordDocument(inputStream, Syncfusion.DocIO.FormatType.Markdown); string filename = ""; string contenttype = ""; MemoryStream outputStream = new MemoryStream(); if (this.pdfButton.IsChecked != null && (bool)this.pdfButton.IsChecked) { filename = "MarkdownToWord.pdf"; contenttype = "application/pdf"; DocIORenderer renderer = new DocIORenderer(); PdfDocument pdfDoc = renderer.ConvertToPDF(document); pdfDoc.Save(outputStream); pdfDoc.Close(); } else if(this.htmlButton.IsChecked != null && (bool)this.htmlButton.IsChecked) { filename = "MarkdownToWord.html"; contenttype = "application/html"; document.Save(outputStream, FormatType.Html); } else { filename = "MarkdownToWord.docx"; contenttype = "application/msword"; document.Save(outputStream, FormatType.Docx); } document.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save(filename, contenttype, outputStream); else Xamarin.Forms.DependencyService.Get<ISave>().Save(filename, contenttype, outputStream); if (contenttype == "application/html" && !(Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP)) { //Set the stream to start position to read the content as string outputStream.Position = 0; StreamReader reader = new StreamReader(outputStream); string htmlString = reader.ReadToEnd(); //Set the HtmlWebViewSource to the html string HtmlWebViewSource html = new HtmlWebViewSource(); html.Html = htmlString; //Create the web view control to view the web page WebView view = new WebView(); view.Source = html; ContentPage webpage = new ContentPage(); webpage.Content = view; this.Content.Navigation.PushAsync(webpage); } } } } <file_sep>/Android/SampleBrowser/Samples/Diagram/README.md The diagram control is used to create different types of diagrams such as flowcharts, use case diagrams, workflow process diagrams, organizational chart, mind map, and so on. Diagram can also be exported as JSON and image formats (.PNG & .JPG). The following samples are available for diagram to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Organization Chart](OrganizationChart.cs) | This sample demonstrate how to create organizational chart and customization of the nodes using template. | | [Mind map](MindMap.cs) | This sample demonstrate the creation and customization of the mind map diagram. | | [Flow Diagram](FlowDiagram.cs) | This sample demonstrate how to create a simple flow diagram and also includes grid line & snap to grid features. | | [Node Customization](NodeContent.cs) | This sample demonstrate that nodes can be customized with your own customized design using template property. | | [Connectors](Connectors.cs) | This sample demonstrate the three types of connectors available in the diagram control. |<file_sep>/Forms/Chart/Chart/Samples/RangeColumnChart/RangeSeriesBaseModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfChart { public class RangeSeriesBaseModel { public string Name { get; set; } public double High { get; set; } public double Low { get; set; } public RangeSeriesBaseModel(string name, double high, double low) { Name = name; High = high; Low = low; } } }<file_sep>/Android/SampleBrowser/Common/Fragments/ChartFragment.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.App; using Android.Graphics; using Android.Views; using Android.Widget; using Android.OS; using AndroidX.RecyclerView.Widget; namespace SampleBrowser { public class ChartFragment : Fragment { #region fields private FrameLayout sampleView; private SampleModel selectedSample; private AllControlsSamplePage allControlsSamplePage; private List<SampleModel> chartSamples; #endregion #region ctor public ChartFragment(List<SampleModel> samples, AllControlsSamplePage activity) { chartSamples = samples; allControlsSamplePage = activity; if (chartSamples.Count > 0) { selectedSample = chartSamples[0]; } } #endregion #region methods public override void OnViewCreated(View view, Bundle savedInstanceState) { sampleView = (FrameLayout)view.FindViewById(Resource.Id.SampleView); var layoutManager = new LinearLayoutManager(allControlsSamplePage, LinearLayoutManager.Horizontal, false); var recyclerView = view.FindViewById<RecyclerView>(Resource.Id.horizontal_RecyclerView); recyclerView.SetLayoutManager(layoutManager); var selectedIndex = chartSamples.IndexOf(selectedSample); var adapter = new RecyclerViewAdapter(chartSamples); adapter.ItemClick += Adapter_ItemClick; recyclerView.SetAdapter(adapter); RefreshSample(selectedSample); if (selectedIndex > 0) { new Handler().PostDelayed(() => recyclerView.FindViewHolderForLayoutPosition(selectedIndex).ItemView.PerformClick(), 100); } } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.Inflate(Resource.Layout.TypesLayout, null); } private void Adapter_ItemClick(object sender, ListViewSelectionChangedEventArgs e) { var index = e.SelectedIndex; TextView selectedItem = e.SelectedItem, prevSelectedItem = e.PreviousSelectedItem; if (selectedItem.Text != prevSelectedItem?.Text) { selectedSample = chartSamples[index]; RefreshSample(selectedSample); } selectedItem?.SetTextColor(Color.ParseColor("#0277F5")); prevSelectedItem?.SetTextColor(Color.Black); } private void RefreshSample(SampleModel selectedSample) { SamplePage samplePage; bool isClassExists = Type.GetType("SampleBrowser." + selectedSample.Name) != null; if (isClassExists) { var handle = Activator.CreateInstance(null, "SampleBrowser." + selectedSample.Name); samplePage = (SamplePage)handle.Unwrap(); sampleView.RemoveAllViews(); if (allControlsSamplePage.CurrentSamplePage != null) { allControlsSamplePage.CurrentSamplePage.Destroy(); } allControlsSamplePage.CurrentSamplePage = samplePage; sampleView.AddView(samplePage.GetSampleContent(View.Context)); allControlsSamplePage.SettingsButton.Visibility = samplePage.GetPropertyWindowLayout(allControlsSamplePage) != null ? ViewStates.Visible : ViewStates.Invisible; } } #endregion } }<file_sep>/Android/SampleBrowser/Samples/LinearGauge/Ranges.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfLinearGauge; namespace SampleBrowser { public class Ranges : SamplePage { public static int pointervalue = 35; LinearLayout range1Layout, range2Layout, range3Layout; SfLinearGauge linearGauge1, linearGauge2, linearGauge3; Context context; public override View GetSampleContent(Android.Content.Context con) { context = con; RangeLayout1(); RangeLayout2(); RangeLayout3(); //Main View LinearLayout mainLinearGaugeLayout = GetView(con); ScrollView mainView = new ScrollView(con); mainView.AddView(mainLinearGaugeLayout); return mainView; } private void RangeLayout1() { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenHeight = displayMetrics.HeightPixels; /**************** **Linear Gauge** ****************/ linearGauge1 = new SfLinearGauge(context); ObservableCollection<LinearScale> scales = new ObservableCollection<LinearScale>(); ObservableCollection<LinearPointer> pointers = new ObservableCollection<LinearPointer>(); ObservableCollection<LinearRange> ranges = new ObservableCollection<LinearRange>(); linearGauge1.SetX(0); linearGauge1.SetY(0); linearGauge1.SetBackgroundColor(Color.Rgb(255, 255, 255)); linearGauge1.SetOrientation(SfLinearGauge.Orientation.Horizontal); //OuterScale LinearScale outerScale = new LinearScale(); outerScale.Minimum = 0; outerScale.Maximum = 100; outerScale.Interval = 25; outerScale.LabelOffset = 15; outerScale.ScaleBarColor = Color.Transparent; outerScale.MinorTicksPerInterval = 0; outerScale.LabelFontSize = 14; outerScale.LabelColor = Color.ParseColor("#424242"); outerScale.ShowTicks = false; //Symbol Pointer SymbolPointer outerScale_needlePointer = new SymbolPointer(); outerScale_needlePointer.SymbolPosition = SymbolPointerPosition.Far; outerScale_needlePointer.Value = pointervalue; outerScale_needlePointer.StrokeWidth = 10; outerScale_needlePointer.Color = Color.Black; outerScale_needlePointer.MarkerShape = MarkerShape.InvertedTriangle; pointers.Add(outerScale_needlePointer); outerScale.Pointers = pointers; //Symbol Range LinearRange range = new LinearRange(); range.StartWidth = 20; range.EndWidth = 20; range.Color = Color.ParseColor("#1A237E"); range.StartValue = 0; range.EndValue = 25; ranges.Add(range); //Symbol Range1 LinearRange range1 = new LinearRange(); range1.StartWidth = 20; range1.EndWidth = 20; range1.Color = Color.ParseColor("#283593"); range1.StartValue = 25; range1.EndValue = 50; ranges.Add(range1); //Symbol Range2 LinearRange range2 = new LinearRange(); range2.StartWidth = 20; range2.EndWidth = 20; range2.Color = Color.ParseColor("#3F51B5"); range2.StartValue = 50; range2.EndValue = 75; ranges.Add(range2); //Symbol Range3 LinearRange range3 = new LinearRange(); range3.StartWidth = 20; range3.EndWidth = 20; range3.Color = Color.ParseColor("#5C6BC0"); range3.StartValue = 75; range3.EndValue = 100; ranges.Add(range3); outerScale.Ranges = ranges; scales.Add(outerScale); linearGauge1.Scales = scales; linearGauge1.LayoutParameters = (new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, (int)(screenHeight / 4))); //Range Layout range1Layout = new LinearLayout(context); range1Layout.SetGravity(GravityFlags.Center); range1Layout.AddView(linearGauge1); } private void RangeLayout2() { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenHeight = displayMetrics.HeightPixels; /**************** **Linear Gauge** ****************/ linearGauge2 = new SfLinearGauge(context); ObservableCollection<LinearScale> scales = new ObservableCollection<LinearScale>(); ObservableCollection<LinearPointer> pointers = new ObservableCollection<LinearPointer>(); ObservableCollection<LinearRange> ranges = new ObservableCollection<LinearRange>(); linearGauge2.SetX(0); linearGauge2.SetY(0); linearGauge2.SetBackgroundColor(Color.Rgb(255, 255, 255)); linearGauge2.SetOrientation(SfLinearGauge.Orientation.Horizontal); //OuterScale LinearScale outerScale = new LinearScale(); outerScale.Minimum = 0; outerScale.Maximum = 100; outerScale.Interval = 25; outerScale.ScaleBarColor = Color.Transparent; outerScale.MinorTicksPerInterval = 0; outerScale.LabelFontSize = 14; outerScale.LabelOffset = 23; outerScale.LabelColor = Color.ParseColor("#424242"); outerScale.ShowTicks = false; //Symbol Pointer SymbolPointer outerScale_needlePointer = new SymbolPointer(); outerScale_needlePointer.SymbolPosition = SymbolPointerPosition.Far; outerScale_needlePointer.Value = pointervalue; outerScale_needlePointer.StrokeWidth = 10; outerScale_needlePointer.Color = Color.Black; outerScale_needlePointer.MarkerShape = MarkerShape.InvertedTriangle; pointers.Add(outerScale_needlePointer); outerScale.Pointers = pointers; //Symbol Range LinearRange range = new LinearRange(); range.StartWidth = 10; range.EndWidth = 15; range.Color = Color.ParseColor("#6de500"); range.StartValue = 0; range.EndValue = 25; ranges.Add(range); //Symbol Range1 LinearRange range1 = new LinearRange(); range1.StartWidth = 15; range1.EndWidth = 20; range1.Color = Color.ParseColor("#53ad00"); range1.StartValue = 25; range1.EndValue = 50; ranges.Add(range1); //Symbol Range2 LinearRange range2 = new LinearRange(); range2.StartWidth = 20; range2.EndWidth = 25; range2.Color = Color.ParseColor("#009148"); range2.StartValue = 50; range2.EndValue = 75; ranges.Add(range2); //Symbol Range3 LinearRange range3 = new LinearRange(); range3.StartWidth = 25; range3.EndWidth = 30; range3.Color = Color.ParseColor("#026623"); range3.StartValue = 75; range3.EndValue = 100; ranges.Add(range3); outerScale.Ranges = ranges; scales.Add(outerScale); linearGauge2.Scales = scales; linearGauge2.LayoutParameters = (new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, (int)screenHeight / 4)); //Range Layout range2Layout = new LinearLayout(context); range2Layout.SetGravity(GravityFlags.Center); range2Layout.AddView(linearGauge2); } private void RangeLayout3() { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenHeight = displayMetrics.HeightPixels; /**************** **Linear Gauge** ****************/ linearGauge3 = new SfLinearGauge(context); ObservableCollection<LinearScale> scales = new ObservableCollection<LinearScale>(); ObservableCollection<LinearPointer> pointers = new ObservableCollection<LinearPointer>(); ObservableCollection<LinearRange> ranges = new ObservableCollection<LinearRange>(); linearGauge3.SetX(0); linearGauge3.SetY(0); linearGauge3.SetBackgroundColor(Color.Rgb(255, 255, 255)); linearGauge3.SetOrientation(SfLinearGauge.Orientation.Horizontal); //OuterScale LinearScale outerScale = new LinearScale(); outerScale.LabelFontSize = 14; outerScale.Interval = 25; outerScale.LabelOffset = 15; outerScale.ScaleBarSize = 20; outerScale.ScaleBarColor = Color.Transparent; outerScale.LabelColor = Color.ParseColor("#424242"); outerScale.ShowTicks = false; //Symbol Pointer SymbolPointer outerScale_needlePointer = new SymbolPointer(); outerScale_needlePointer.SymbolPosition = SymbolPointerPosition.Far; outerScale_needlePointer.Value = pointervalue; outerScale_needlePointer.StrokeWidth = 10; outerScale_needlePointer.Color = Color.Black; outerScale_needlePointer.MarkerShape = MarkerShape.InvertedTriangle; pointers.Add(outerScale_needlePointer); outerScale.Pointers = pointers; //Symbol Range LinearRange range = new LinearRange(); range.StartWidth = 20; range.EndWidth = 20; range.StartValue = 0; range.EndValue = 100; ranges.Add(range); outerScale.Ranges = ranges; range.GradientStops = new ObservableCollection<GaugeGradientStop>() { new GaugeGradientStop() { Value = 0, Color = Color.ParseColor("#FFF9C2C3") }, new GaugeGradientStop() { Value = 100, Color = Color.ParseColor("#FFD91D71") } }; scales.Add(outerScale); linearGauge3.Scales = scales; linearGauge3.LayoutParameters = (new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, (int)screenHeight / 4)); //Range Layout range3Layout = new LinearLayout(context); range3Layout.SetGravity(GravityFlags.Center); range3Layout.AddView(linearGauge3); } private LinearLayout GetView(Context con) { //Ranges Layout LinearLayout rangesLayout = new LinearLayout(con); rangesLayout.Orientation = Orientation.Vertical; rangesLayout.AddView(range1Layout); rangesLayout.AddView(range2Layout); rangesLayout.AddView(range3Layout); rangesLayout.SetGravity(GravityFlags.Center); //Main Layout LinearLayout mainLayout = new LinearLayout(con); mainLayout.AddView(rangesLayout); mainLayout.SetBackgroundColor(Color.White); mainLayout.SetGravity(GravityFlags.Center); return mainLayout; } } }<file_sep>/iOS/SampleBrowser/Samples/DataGrid/Model/EmployeeInfoRespository.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class EmployeeInfoRespository { public EmployeeInfoRespository() { PopulateData(); } Random r = new Random(); Dictionary<string, string> loginID = new Dictionary<string, string>(); Dictionary<string, string> gender = new Dictionary<string, string>(); public ObservableCollection<Employee> GetEmployeesDetails(int count) { var employees = new ObservableCollection<Employee>(); for (var i = 1; i < count; i++) { employees.Add(GetEmployee(i)); } return employees; } public Employee GetEmployee(int i) { var name = employeeName[r.Next(employeeName.Count() - 1)]; return new Employee() { EmployeeID = 1000 + i, Name = name, ContactID = r.Next(1001, 2000), Gender = gender[name], Title = title[r.Next(title.Count() - 1)], BirthDate = new DateTime(r.Next(1975, 1985), r.Next(1, 12), r.Next(1, 28)), SickLeaveHours = r.Next(15, 70), Salary = new decimal(Math.Round(r.NextDouble() * 6000.5, 2)) }; } private void PopulateData() { gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Male"); gender.Add("<NAME>", "Female"); loginID.Add("<NAME>", "sean2"); loginID.Add("<NAME>", "phyllis0"); loginID.Add("<NAME>", "marvin0"); loginID.Add("<NAME>", "michael10"); loginID.Add("<NAME>", "cecil0"); loginID.Add("<NAME>", "oscar0"); loginID.Add("<NAME>", "sandra1"); loginID.Add("<NAME>", "selena0"); loginID.Add("<NAME>", "emilio0"); loginID.Add("<NAME>", "maxwell0"); loginID.Add("<NAME>", "mae0"); loginID.Add("<NAME>", "ramona0"); loginID.Add("<NAME>", "sabria0"); loginID.Add("<NAME>", "hannah0"); loginID.Add("<NAME>", "kyley0"); loginID.Add("<NAME>", "tom1"); loginID.Add("<NAME>", "thomas1"); loginID.Add("<NAME>", "john6"); loginID.Add("<NAME>", "chris3"); loginID.Add("<NAME>", "teresa0"); loginID.Add("<NAME>", "john7"); loginID.Add("<NAME>", "robert2"); loginID.Add("<NAME>", "stephen1"); loginID.Add("<NAME>", "phillip0"); loginID.Add("<NAME>", "gustavo0"); loginID.Add("<NAME>", "catherine0"); loginID.Add("<NAME>", "kim2"); loginID.Add("<NAME>", "humberto0"); loginID.Add("<NAME>", "pilar1"); loginID.Add("<NAME>", "frances0"); loginID.Add("<NAME>", "margaret0"); loginID.Add("<NAME>", "carla0"); loginID.Add("<NAME>", "jay1"); loginID.Add("<NAME>", "ronald0"); loginID.Add("<NAME>", "samuel0"); loginID.Add("<NAME>", "james2"); loginID.Add("<NAME>", "robert1"); loginID.Add("<NAME>", "françois1"); loginID.Add("<NAME>", "kim3"); loginID.Add("<NAME>", "lili0"); loginID.Add("<NAME>", "amy1"); loginID.Add("<NAME>", "anna0"); loginID.Add("<NAME>", "milton0"); loginID.Add("<NAME>", "paul2"); loginID.Add("<NAME>", "gregory0"); loginID.Add("<NAME>", "jphillip0"); loginID.Add("<NAME>", "michelle0"); loginID.Add("<NAME>", "daniel0"); loginID.Add("<NAME>", "cory0"); loginID.Add("<NAME>", "james3"); } private string[] title = new string[] { "Marketing Assistant", "Engineering Manager", "Senior Tool Designer", "Tool Designer", "Marketing Manager", "Production Supervisor - WC60", "Production Technician - WC10", "Design Engineer", "Production Technician - WC10", "Design Engineer", "Vice President of Engineering", "Production Technician - WC10", "Production Supervisor - WC50", "Production Technician - WC10", "Production Supervisor - WC60", "Production Technician - WC10", "Production Supervisor - WC60", "Production Technician - WC10", "Production Technician - WC30", "Production Control Manager", "Production Technician - WC45", "Production Technician - WC45", "Production Technician - WC30", "Production Supervisor - WC10", "Production Technician - WC20", "Production Technician - WC40", "Network Administrator", "Production Technician - WC50", "Human Resources Manager", "Production Technician - WC40", "Production Technician - WC30", "Production Technician - WC30", "Stocker", "Shipping and Receiving Clerk", "Production Technician - WC50", "Production Technician - WC60", "Production Supervisor - WC50", "Production Technician - WC20", "Production Technician - WC45", "Quality Assurance Supervisor", "Information Services Manager", "Production Technician - WC50", "Master Scheduler", "Production Technician - WC40", "Marketing Specialist", "Recruiter", "Production Technician - WC50", "Maintenance Supervisor", "Production Technician - WC30", }; private string[] employeeName = new string[] { "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" }; } } <file_sep>/Forms/Schedule/Schedule/Samples/AgendaView/Behaviors/AgendaViewBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// AgendaView Behavior class. /// </summary> internal class AgendaViewBehavior : Behavior<SampleView> { /// <summary> /// Gets or Sets schedule instance. /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule schedule; /// <summary> /// Begins when the behavior attached to the view. /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(SampleView bindable) { base.OnAttachedTo(bindable); bindable.SizeChanged += Bindable_SizeChanged; this.schedule = bindable.Content.FindByName<Syncfusion.SfSchedule.XForms.SfSchedule>("schedule"); } /// <summary> /// Begins when the behavior attached to the view. /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); bindable.SizeChanged -= Bindable_SizeChanged; this.schedule = null; } /// <summary> /// Method to set the agenda view height /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void Bindable_SizeChanged(object sender, EventArgs e) { var height = (sender as SampleView).Content.Height; if (Device.RuntimePlatform == "Android") { this.schedule.MonthViewSettings.AgendaViewHeight = height * 0.6; } else { this.schedule.MonthViewSettings.AgendaViewHeight = height * 0.35; } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/ScheduleViews.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; using System.Collections.ObjectModel; using Foundation; using UIKit; using CoreGraphics; namespace SampleBrowser { public class ScheduleViews : SampleView { public static SFSchedule schedule; internal ScheduleAppointment selectedAppointment; internal int indexOfAppointment; internal UIView headerView = new UIView(); private UIButton headerButton = new UIButton(); private UIButton moveToDate = new UIButton(); private static UILabel monthText = new UILabel(); private UIButton editorView = new UIButton(); private ScheduleViewModel viewModel = new ScheduleViewModel(); public static UITableView tableView = new UITableView(); public ScheduleEditor scheduleEditor; public ScheduleViews() { schedule = new SFSchedule(); scheduleEditor = new ScheduleEditor(schedule, this); schedule.AppointmentsForDate += Schedule_AppointmentsForDate; schedule.AppointmentsFromDate += Schedule_AppointmentsFromDate; schedule.CellTapped += Schedule_CellTapped; schedule.CellDoubleTapped += Schedule_DoubleTapped; schedule.VisibleDatesChanged += Schedule_VisibleDatesChanged; schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; schedule.ItemsSource = viewModel.CreateAppointments(); scheduleEditor.CreateEditor(); this.OptionView = new UIView(); schedule.HeaderHeight = 0; schedule.ViewHeaderHeight = 50; schedule.Hidden = false; scheduleEditor.Editor.Hidden = true; } private void Schedule_CellTapped(object sender, CellTappedEventArgs e) { if (schedule.ScheduleView == SFScheduleView.SFScheduleViewMonth) { schedule.ScheduleView = SFScheduleView.SFScheduleViewDay; schedule.MoveToDate(e.Date); schedule.Hidden = false; scheduleEditor.Editor.Hidden = true; headerView.Hidden = false; } } private void Schedule_VisibleDatesChanged(object sender, VisibleDatesChangedEventArgs e) { int CurrentVisibleMonth = 0; if (schedule.ScheduleView == SFScheduleView.SFScheduleViewMonth) { CurrentVisibleMonth = 8; } else { CurrentVisibleMonth = 0; } NSDate date = e.VisibleDates.GetItem<NSDate>((nuint)CurrentVisibleMonth); NSDateFormatter dateFormat = new NSDateFormatter(); dateFormat.DateFormat = "MMMM YYYY"; string monthName = dateFormat.ToString(date); monthText.Text = monthName; tableView.Hidden = true; } private void Schedule_DoubleTapped(object sender, CellTappedEventArgs e) { //base.didSelectDate (schedule, selectedDate, appointments); scheduleEditor.Editor.Hidden = false; headerView.Hidden = true; schedule.Hidden = true; indexOfAppointment = -1; tableView.Hidden = true; if (e.ScheduleAppointment != null) { for (int i = 0; i < (schedule.ItemsSource as ObservableCollection<ScheduleAppointment>).Count; i++) { if ((schedule.ItemsSource as ObservableCollection<ScheduleAppointment>)[i] == e.ScheduleAppointment) { indexOfAppointment = int.Parse(i.ToString()); break; } } selectedAppointment = (e.ScheduleAppointment); scheduleEditor.label_subject.Text = selectedAppointment.Subject; scheduleEditor.label_location.Text = selectedAppointment.Location; String _sDate = DateTime.Parse((selectedAppointment.StartTime.ToString())).ToString(); scheduleEditor.button_startDate.SetTitle(_sDate, UIControlState.Normal); scheduleEditor.picker_startDate.SetDate(selectedAppointment.StartTime, true); String _eDate = DateTime.Parse((selectedAppointment.EndTime.ToString())).ToString(); scheduleEditor.button_endDate.SetTitle(_eDate, UIControlState.Normal); scheduleEditor.picker_endDate.SetDate(selectedAppointment.EndTime, true); scheduleEditor.allDaySwitch.On = selectedAppointment.IsAllDay; if(scheduleEditor.allDaySwitch.On) { scheduleEditor.Disablechild(); } else { scheduleEditor.EnableChild(); } scheduleEditor.Editor.EndEditing(true); } else { List<UIColor> colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); scheduleEditor.label_subject.Text = "Subject"; scheduleEditor.label_location.Text = "Location"; String _sDate = DateTime.Parse((e.Date.ToString())).ToString(); scheduleEditor.picker_startDate.SetDate(e.Date, true); scheduleEditor.button_startDate.SetTitle(_sDate, UIControlState.Normal); String _eDate = DateTime.Parse((e.Date.AddSeconds(3600).ToString())).ToString(); scheduleEditor.picker_endDate.SetDate(e.Date.AddSeconds(3600), true); scheduleEditor.button_endDate.SetTitle(_eDate, UIControlState.Normal); scheduleEditor.allDaySwitch.On = false; this.scheduleEditor.EnableChild(); } } private void Schedule_AppointmentsFromDate(object sender, AppointmentsFromDateEventArgs e) { NSCalendar calendar = NSCalendar.CurrentCalendar; NSDateComponents components = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, e.EndDate); components.Hour = 23; components.Minute = 59; components.Second = 59; NSDate rangeEndDateWithTime = calendar.DateFromComponents(components); NSPredicate predicate = NSPredicate.FromFormat(@"(startTime <= %@) AND (startTime >= %@)", rangeEndDateWithTime, e.StartDate); } private void Schedule_AppointmentsForDate(object sender, AppointmentsForDateEventArgs e) { NSCalendar calendar = NSCalendar.CurrentCalendar; NSDateComponents components = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, (NSDate)e.Date); components.Hour = 23; components.Minute = 59; components.Second = 59; NSDate rangeEndDateWithTime = calendar.DateFromComponents(components); NSPredicate predicate = NSPredicate.FromFormat(@"(startTime <= %@) AND (startTime >= %@)", rangeEndDateWithTime, (NSDate)e.Date); } private void CreateOptionView() { scheduleEditor.CreateOptionWindow(); scheduleEditor.timezoneLabel.Frame = new CGRect(0, 0, this.Frame.Size.Width, 30); scheduleEditor.timezoneButton.Frame = new CGRect(0, scheduleEditor.timezoneLabel.Frame.Bottom, this.Frame.Size.Width, 30); scheduleEditor.doneButton.Frame = new CGRect(0, scheduleEditor.timezoneButton.Frame.Bottom, this.Frame.Size.Width, 30); scheduleEditor.timeZonePicker.Frame = new CGRect(0, scheduleEditor.doneButton.Frame.Bottom, this.Frame.Size.Width, 200); this.OptionView.AddSubview(scheduleEditor.timezoneLabel); this.OptionView.AddSubview(scheduleEditor.timezoneButton); this.OptionView.AddSubview(scheduleEditor.doneButton); this.OptionView.AddSubview(scheduleEditor.timeZonePicker); } protected override void Dispose(bool disposing) { if (disposing) { if (schedule != null) { schedule.AppointmentsForDate -= Schedule_AppointmentsForDate; schedule.AppointmentsFromDate -= Schedule_AppointmentsFromDate; schedule.CellTapped -= Schedule_CellTapped; schedule.CellDoubleTapped -= Schedule_DoubleTapped; schedule.VisibleDatesChanged -= Schedule_VisibleDatesChanged; schedule.Dispose(); schedule = null; } if (moveToDate != null) { moveToDate.TouchUpInside -= MoveToDate_TouchUpInside; moveToDate.Dispose(); moveToDate = null; } if (headerButton != null) { headerButton.TouchUpInside -= HeaderButton_TouchUpInside; headerButton.Dispose(); headerButton = null; } if (editorView != null) { editorView.TouchUpInside -= EditorView_TouchUpInside; editorView.Dispose(); editorView = null; } } base.Dispose(disposing); } private void EditorView_TouchUpInside(object sender, EventArgs e) { scheduleEditor.Editor.Hidden = false; schedule.Hidden = true; headerView.Hidden = true; tableView.Hidden = true; NSDate today = new NSDate(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); NSDate startDate = calendar.DateFromComponents(components); scheduleEditor.label_subject.Text = "Subject"; scheduleEditor.label_location.Text = "Location"; String _sDate = DateTime.Parse((startDate.ToString())).ToString(); scheduleEditor.picker_startDate.SetDate(startDate, true); scheduleEditor.button_startDate.SetTitle(_sDate, UIControlState.Normal); String _eDate = DateTime.Parse((startDate.AddSeconds(3600).ToString())).ToString(); scheduleEditor.picker_endDate.SetDate(startDate.AddSeconds(3600), true); scheduleEditor.button_endDate.SetTitle(_eDate, UIControlState.Normal); } private void MoveToDate_TouchUpInside(object sender, EventArgs e) { tableView.Hidden = true; NSDate today = new NSDate(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); NSDate startDate = calendar.DateFromComponents(components); schedule.MoveToDate(startDate); } private void HeaderButton_TouchUpInside(object sender, EventArgs e) { tableView.Hidden = false; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = new CGRect(Frame.X, 0, Frame.Width, Frame.Height); } CreateOptionView(); scheduleEditor.Editor.Frame = new CGRect(0, 0, this.Frame.Size.Width, this.Frame.Size.Height); scheduleEditor.scrollView.Frame = new CGRect(scheduleEditor.Editor.Frame.X + 10, scheduleEditor.Editor.Frame.Y + 10, scheduleEditor.Editor.Frame.Size.Width - 10, scheduleEditor.Editor.Frame.Size.Height); scheduleEditor.EditorFrameUpdate(); UIImageView image1 = new UIImageView(); UIImageView image2 = new UIImageView(); UIImageView image3 = new UIImageView(); moveToDate = new UIButton(); editorView = new UIButton(); monthText = new UILabel(); headerView = new UIView(); headerView.BackgroundColor = UIColor.FromRGB(214, 214, 214); NSDate today = new NSDate(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); NSDate startDate = calendar.DateFromComponents(components); NSDateFormatter dateFormat = new NSDateFormatter(); dateFormat.DateFormat = "MMMM YYYY"; string monthName = dateFormat.ToString(startDate); monthText.Text = monthName; monthText.TextColor = UIColor.Black; monthText.TextAlignment = UITextAlignment.Left; moveToDate.AddSubview(image2); headerButton.AddSubview(image1); editorView.AddSubview(image3); string[] tableItems = new string[] { "Day", "Week", "WorkWeek", "Month" }; tableView = new UITableView(); tableView.Frame = new CGRect(0, 0, this.Frame.Size.Width / 2, 60.0f * 4); tableView.Hidden = true; tableView.Source = new ScheduleTableSource(tableItems); string deviceType = UIDevice.CurrentDevice.Model; if (deviceType == "iPhone" || deviceType == "iPod touch") { image1.Frame = new CGRect(0, 0, 60, 60); image1.Image = UIImage.FromFile("black-09.png"); image2.Frame = new CGRect(0, 0, 60, 60); image2.Image = UIImage.FromFile("black-11.png"); image3.Frame = new CGRect(0, 0, 60, 60); image3.Image = UIImage.FromFile("black-10.png"); headerView.Frame = new CGRect(0, 0, this.Frame.Size.Width, 50); moveToDate.Frame = new CGRect((this.Frame.Size.Width / 6) + (this.Frame.Size.Width / 2), -10, this.Frame.Size.Width / 8, 50); editorView.Frame = new CGRect((this.Frame.Size.Width / 6) + (this.Frame.Size.Width / 6) + (this.Frame.Size.Width / 2), -10, this.Frame.Size.Width / 8, 50); headerButton.Frame = new CGRect(-10, -10, this.Frame.Size.Width / 8, 50); monthText.Frame = new CGRect(this.Frame.Size.Width / 8, -10, this.Frame.Size.Width / 2, 60); schedule.Frame = new CGRect(0, 50, this.Frame.Size.Width, this.Frame.Size.Height - 50); } else { schedule.DayViewSettings.WorkStartHour = 7; schedule.DayViewSettings.WorkEndHour = 18; schedule.WeekViewSettings.WorkStartHour = 7; schedule.WeekViewSettings.WorkEndHour = 18; schedule.WorkWeekViewSettings.WorkStartHour = 7; schedule.WorkWeekViewSettings.WorkEndHour = 18; image1.Frame = new CGRect(0, 0, 80, 80); image1.Image = UIImage.FromFile("black-09.png"); image2.Frame = new CGRect(0, 0, 80, 80); image2.Image = UIImage.FromFile("black-11.png"); image3.Frame = new CGRect(0, 0, 80, 80); image3.Image = UIImage.FromFile("black-10.png"); headerView.Frame = new CGRect(0, 0, this.Frame.Size.Width, 60); moveToDate.Frame = new CGRect((this.Frame.Size.Width / 5) + (this.Frame.Size.Width / 2) + (this.Frame.Size.Width / 8), -10, this.Frame.Size.Width / 8, 50); editorView.Frame = new CGRect((this.Frame.Size.Width / 5) + (this.Frame.Size.Width / 5) + (this.Frame.Size.Width / 2), -10, this.Frame.Size.Width / 8, 50); headerButton.Frame = new CGRect(0, -10, this.Frame.Size.Width / 8, 50); monthText.Frame = new CGRect(this.Frame.Size.Width / 8, 5, this.Frame.Size.Width / 2, 50); schedule.Frame = new CGRect(0, 60, this.Frame.Size.Width, this.Frame.Size.Height - 60); } moveToDate.TouchUpInside += MoveToDate_TouchUpInside; headerButton.TouchUpInside += HeaderButton_TouchUpInside; editorView.TouchUpInside += EditorView_TouchUpInside; headerView.AddSubview(moveToDate); headerView.AddSubview(editorView); headerView.AddSubview(monthText); headerView.AddSubview(headerButton); this.AddSubview(schedule); this.AddSubview(headerView); this.AddSubview(scheduleEditor.Editor); this.AddSubview(tableView); base.LayoutSubviews(); } } } <file_sep>/Android/SampleBrowser/Samples/Maps/BubbleVisualization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Com.Syncfusion.Maps; using Android.Graphics; using Org.Json; using Android.Widget; using Com.Syncfusion.Sfbusyindicator; using Com.Syncfusion.Sfbusyindicator.Enums; using Android.OS; using Android.Views; using Android.Content; namespace SampleBrowser { public class BubbleVisualization : SamplePage { SfMaps maps; Handler handler; public override Android.Views.View GetSampleContent(Android.Content.Context context) { handler = new Handler(); LinearLayout layout = new LinearLayout(context); layout.Orientation = Orientation.Vertical; TextView textView = new TextView(context); textView.TextSize = 16; textView.SetPadding(10, 20, 0, 0); textView.SetHeight(90); textView.Text = "Top 40 countries population"; layout.AddView(textView); textView.Gravity = Android.Views.GravityFlags.Top; maps = new SfMaps(context); ShapeFileLayer layer = new ShapeFileLayer(); layer.ShowItems = true; layer.Uri = "world1.shp"; layer.DataSource = GetDataSource(); layer.ShapeIdPath = "Country"; layer.ShowItems = true; layer.ShapeIdTableField = "NAME"; layer.ShapeSettings = new ShapeSetting(); layer.ShapeSettings.ShapeFill = Color.LightGray; BubbleMarkerSetting marker = new BubbleMarkerSetting(); marker.ValuePath = "Population"; marker.ColorValuePath = "Population"; BubbleCustomTooltipSetting tooltipSetting = new BubbleCustomTooltipSetting(context); tooltipSetting.ShowTooltip = true; tooltipSetting.ValuePath = "Country"; marker.TooltipSettings = tooltipSetting; RangeColorMapping rangeColorMapping = new RangeColorMapping(); rangeColorMapping.Color = Color.ParseColor("#2E769F"); rangeColorMapping.To = 1400000000; rangeColorMapping.From = 325000000; rangeColorMapping.LegendLabel = "Above 4%"; marker.ColorMapping.Add(rangeColorMapping); RangeColorMapping rangeColorMapping1 = new RangeColorMapping(); rangeColorMapping1.Color = Color.ParseColor("#D84444"); rangeColorMapping1.To = 325000000; rangeColorMapping1.From = 180000000; rangeColorMapping1.LegendLabel = "4% - 2%"; marker.ColorMapping.Add(rangeColorMapping1); RangeColorMapping rangeColorMapping2 = new RangeColorMapping(); rangeColorMapping2.Color = Color.ParseColor("#816F28"); rangeColorMapping2.To = 180000000; rangeColorMapping2.From = 100000000; rangeColorMapping2.LegendLabel = "2% - 1%"; marker.ColorMapping.Add(rangeColorMapping2); RangeColorMapping rangeColorMapping3 = new RangeColorMapping(); rangeColorMapping3.Color = Color.ParseColor("#7F38A0"); rangeColorMapping3.To = 100000000; rangeColorMapping3.From = 5000000; rangeColorMapping3.LegendLabel = "Below 1%"; marker.ColorMapping.Add(rangeColorMapping3); layer.BubbleMarkerSetting = marker; LegendSetting legendSetting = new LegendSetting(); legendSetting.ShowLegend = true; legendSetting.LegendType = LegendType.Bubbles; legendSetting.IconHeight = 15; legendSetting.IconWidth = 15; legendSetting.LegendPosition = new Point(50, 5); legendSetting.HorizontalAlignment = HorizontalAlignment.Center; layer.LegendSetting = legendSetting; maps.Layers.Add(layer); SfBusyIndicator sfBusyIndicator = new SfBusyIndicator(context); sfBusyIndicator.IsBusy = true; sfBusyIndicator.AnimationType = AnimationTypes.SlicedCircle; sfBusyIndicator.ViewBoxWidth = 50; sfBusyIndicator.ViewBoxHeight = 50; sfBusyIndicator.TextColor = Color.ParseColor("#779772"); layout.AddView(sfBusyIndicator); Java.Lang.Runnable run = new Java.Lang.Runnable(() => { layout.RemoveView(sfBusyIndicator); layout.AddView(maps); }); handler.PostDelayed(run, 100); return layout; } public JSONArray GetDataSource() { var array = new JSONArray(); array.Put(new JSONObject().Put("Country", "China").Put("Population", 1393730000).Put("Percent", 18.2)); array.Put(new JSONObject().Put("Country", "India").Put("Population", 1336180000).Put("Percent", 17.5)); array.Put(new JSONObject().Put("Country", "United States").Put("Population", 327726000).Put("Percent", 4.29)); array.Put(new JSONObject().Put("Country", "Indonesia").Put("Population", 265015300).Put("Percent", 3.47)); array.Put(new JSONObject().Put("Country", "Pakistan").Put("Population", 209503000).Put("Percent", 2.78)); array.Put(new JSONObject().Put("Country", "Brazil").Put("Population", 201795000).Put("Percent", 2.74)); array.Put(new JSONObject().Put("Country", "Nigeria").Put("Population", 197306006).Put("Percent", 2.53)); array.Put(new JSONObject().Put("Country", "Bangladesh").Put("Population", 165086000).Put("Percent", 2.16)); array.Put(new JSONObject().Put("Country", "Russia").Put("Population", 146877088).Put("Percent", 1.92)); array.Put(new JSONObject().Put("Country", "Japan").Put("Population", 126490000).Put("Percent", 1.66)); array.Put(new JSONObject().Put("Country", "Mexico").Put("Population", 124737789).Put("Percent", 1.63)); array.Put(new JSONObject().Put("Country", "Ethiopia").Put("Population", 107534882).Put("Percent", 1.41)); array.Put(new JSONObject().Put("Country", "Philippines").Put("Population", 106375000).Put("Percent", 1.39)); array.Put(new JSONObject().Put("Country", "Egypt").Put("Population", 97459100).Put("Percent", 1.27)); array.Put(new JSONObject().Put("Country", "Vietnam").Put("Population", 94660000).Put("Percent", 1.24)); array.Put(new JSONObject().Put("Country", "Germany").Put("Population", 82740900).Put("Percent", 1.08)); array.Put(new JSONObject().Put("Country", "Iran").Put("Population", 81737800).Put("Percent", 1.07)); array.Put(new JSONObject().Put("Country", "Turkey").Put("Population", 80810525).Put("Percent", 1.06)); array.Put(new JSONObject().Put("Country", "Thailand").Put("Population", 69183173).Put("Percent", 0.91)); array.Put(new JSONObject().Put("Country", "France").Put("Population", 67297000).Put("Percent", 0.88)); array.Put(new JSONObject().Put("Country", "United Kingdom").Put("Population", 66040229).Put("Percent", 0.86)); array.Put(new JSONObject().Put("Country", "Italy").Put("Population", 60436469).Put("Percent", 0.79)); array.Put(new JSONObject().Put("Country", "South Africa").Put("Population", 57725600).Put("Percent", 0.76)); array.Put(new JSONObject().Put("Country", "Colombia").Put("Population", 49918600).Put("Percent", 0.65)); array.Put(new JSONObject().Put("Country", "Spain").Put("Population", 46659302).Put("Percent", 0.61)); array.Put(new JSONObject().Put("Country", "Argentina").Put("Population", 44494502).Put("Percent", 0.58)); array.Put(new JSONObject().Put("Country", "Poland").Put("Population", 38433600).Put("Percent", 0.5)); array.Put(new JSONObject().Put("Country", "Canada").Put("Population", 37206700).Put("Percent", 0.48)); array.Put(new JSONObject().Put("Country", "Saudi Arabia").Put("Population", 33413660).Put("Percent", 0.44)); array.Put(new JSONObject().Put("Country", "Malaysia").Put("Population", 32647000).Put("Percent", 0.42)); array.Put(new JSONObject().Put("Country", "Nepal").Put("Population", 29218867).Put("Percent", 0.38)); array.Put(new JSONObject().Put("Country", "Australia").Put("Population", 25015400).Put("Percent", 0.32)); array.Put(new JSONObject().Put("Country", "Kazakhstan").Put("Population", 18253300).Put("Percent", 0.24)); array.Put(new JSONObject().Put("Country", "Cambodia").Put("Population", 16069921).Put("Percent", 0.21)); array.Put(new JSONObject().Put("Country", "Belgium").Put("Population", 11414214).Put("Percent", 0.15)); array.Put(new JSONObject().Put("Country", "Greece").Put("Population", 10768193).Put("Percent", 0.14)); array.Put(new JSONObject().Put("Country", "Sweden").Put("Population", 10171524).Put("Percent", 0.13)); array.Put(new JSONObject().Put("Country", "Somalia").Put("Population", 15181925).Put("Percent", 0.12)); array.Put(new JSONObject().Put("Country", "Austria").Put("Population", 8830487).Put("Percent", 0.12)); array.Put(new JSONObject().Put("Country", "Bulgaria").Put("Population", 7050034).Put("Percent", 0.092)); return array; } } public class BubbleCustomTooltipSetting : TooltipSetting { Context context; public BubbleCustomTooltipSetting(Context con) { context = con; } public override View GetView(object shapeData) { LinearLayout layout = new LinearLayout(context); LinearLayout.LayoutParams linearlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layout.Orientation = Orientation.Vertical; layout.LayoutParameters = linearlayoutParams; layout.SetGravity(GravityFlags.CenterHorizontal); TextView topLabel = new TextView(context); topLabel.Text = ((JSONObject)shapeData).GetString("Country"); topLabel.TextSize = 12; topLabel.SetTextColor(Color.ParseColor("#FFFFFF")); topLabel.Gravity = GravityFlags.CenterHorizontal; TextView bottoLabel = new TextView(context); bottoLabel.Text = ((JSONObject)shapeData).GetString("Percent") + "%"; bottoLabel.TextSize = 12; bottoLabel.SetTextColor(Color.ParseColor("#FFFFFF")); bottoLabel.Gravity = GravityFlags.CenterHorizontal; layout.AddView(topLabel); layout.AddView(bottoLabel); return layout; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Popup/PopupCustomizations.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Syncfusion.SfDataGrid; using Syncfusion.iOS.PopupLayout; using UIKit; namespace SampleBrowser { public class PopupCustomizations : SampleView { #region Fields internal static SfDataGrid datagrid; TicketBookingViewModel viewModel; SfPopupLayout initialPopup; UIView mainView; #endregion public PopupCustomizations() { CreateMainView(); CreateDataGrid(); this.AddSubview(mainView); } private void CreateMainView() { mainView = new UIView(); } private void CreateDataGrid() { datagrid = new SfDataGrid(); viewModel = new TicketBookingViewModel(); datagrid.AutoGenerateColumns = false; datagrid.ColumnSizer = ColumnSizer.Star; datagrid.RowHeight = 117; datagrid.GridLoaded += datagrid_GridLoaded; GridTextColumn movieList = new GridTextColumn(); movieList.HeaderText = "Movies List"; movieList.HeaderTextAlignment = UIKit.UITextAlignment.Center; movieList.UserCellType = typeof(MovieTile); datagrid.Columns.Add(movieList); datagrid.ItemsSource = viewModel.TheaterInformation; mainView.AddSubview(datagrid); } private void datagrid_GridLoaded(object sender, GridLoadedEventArgs e) { DisplayInitialPopup(); } private void DisplayInitialPopup() { initialPopup = new SfPopupLayout(); initialPopup.PopupView.AppearanceMode = AppearanceMode.OneButton; initialPopup.PopupView.PopupStyle.HeaderBackgroundColor = UIColor.White; initialPopup.PopupView.FooterHeight = initialPopup.PopupView.FooterHeight - 10; initialPopup.PopupView.ShowFooter = true; initialPopup.PopupView.ShowCloseButton = false; initialPopup.PopupView.HeaderTitle = "Book tickets !"; initialPopup.PopupView.AcceptButtonText = "OK"; initialPopup.StaysOpen = true; UILabel messageView = new UILabel(); messageView.Text = "Click on the book button to start booking tickets"; messageView.TextColor = UIColor.Black; messageView.LineBreakMode = UILineBreakMode.WordWrap; messageView.Lines = 5; messageView.TextAlignment = UITextAlignment.Center; messageView.BackgroundColor = UIColor.White; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { initialPopup.PopupView.PopupStyle.HeaderFontSize = 14; messageView.Font = UIFont.PreferredCaption1; initialPopup.PopupView.Frame = new CGRect(-1, -1, (UIScreen.MainScreen.ApplicationFrame.Width / 10) * 8, 180); } else { initialPopup.PopupView.PopupStyle.HeaderFontSize = 20; messageView.Font = UIFont.PreferredBody; initialPopup.PopupView.Frame = new CGRect(-1, -1, -1, 200); } initialPopup.PopupView.ContentView = messageView; initialPopup.Show(); } public override void LayoutSubviews() { base.LayoutSubviews(); mainView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); datagrid.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); } } } <file_sep>/Forms/Picker/Picker/Samples/PickerGettingStarted/PickerHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Xamarin.Forms; namespace SampleBrowser.SfPicker { public static class PickerHelper { static Dictionary<string, Color> colors = new Dictionary<string, Color>(); public static Color GetColor(object color) { colors.Clear(); colors.Add("Yellow", Color.Yellow); colors.Add("Green", Color.Green); colors.Add("Orange", Color.Orange); colors.Add("Lime", Color.Lime); colors.Add("Purple", Color.Purple); colors.Add("Pink", Color.Pink); colors.Add("Black", Color.Black); colors.Add("Navy", Color.Navy); colors.Add("Red", Color.Red); colors.Add("Gray", Color.Gray); return colors[color.ToString()]; } } } <file_sep>/Forms/CheckBox/CheckBox/Samples/CheckBox/CheckBox.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfCheckBox { public partial class CheckBox : SampleView { private bool skip = false; public object NonCheckBox { get; private set; } public CheckBox() { InitializeComponent(); selectAll.StateChanged += SelectAll1_StateChanged; if (Device.Idiom == TargetIdiom.Tablet || Device.Idiom == TargetIdiom.Desktop) { movieImage.HeightRequest = 270; frame.Margin = new Thickness(25, 25, 25, 0); if (Device.Idiom == TargetIdiom.Tablet) { selectAll.FontSize = grilledChicken.FontSize = chickenTikka.FontSize = 20; chickenSausage.FontSize = beef.FontSize = 20; } title.FontSize = 22; title.Margin = new Thickness(0, 20, 0, 10); selectAll.Margin = new Thickness(0, 20, 0, 0); grilledChicken.Margin = new Thickness(0, 30, 0, 0); chickenTikka.Margin = new Thickness(0, 30, 0, 0); chickenSausage.Margin = new Thickness(0, 30, 0, 0); beef.Margin = new Thickness(0, 30, 0, 30); } if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { frame.BackgroundColor = Color.White; frame.HasShadow = true; #pragma warning disable 618 frame.OutlineColor = Color.FromHex("29000000"); #pragma warning restore 618 } if (Device.RuntimePlatform == Device.WPF || Device.RuntimePlatform == Device.UWP) { if(Device.RuntimePlatform == Device.UWP) frame.HeightRequest = 680; else frame.HeightRequest = 600; frame.WidthRequest = 380; frame.HorizontalOptions = LayoutOptions.Center; frame.VerticalOptions = LayoutOptions.Center; button.HeightRequest = 50; button.WidthRequest = 410; button.HorizontalOptions = LayoutOptions.Center; button.VerticalOptions = LayoutOptions.Center; } } private void Button_Clicked(object sender, EventArgs e) { bool? temp = ValidateNonVegToopings(); if (!temp.HasValue || (temp.HasValue && temp.Value)) { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("", "Your order has been placed successfully !", "Ok"); selectAll.IsChecked = false; } if (Device.RuntimePlatform == Device.WPF) { button.TextColor = Color.Black; } } private void NonvegToppingsChanged(object sender, Syncfusion.XForms.Buttons.StateChangedEventArgs eventArgs) { if (!skip) { skip = true; selectAll.IsChecked = ValidateNonVegToopings(); if (!selectAll.IsChecked.HasValue || (selectAll.IsChecked.HasValue && selectAll.IsChecked.Value)) { button.IsEnabled = true; if (Device.RuntimePlatform == Device.WPF) { button.TextColor = Color.White; } } else { button.IsEnabled = false; } skip = false; } } private void SelectAll1_StateChanged(object sender, Syncfusion.XForms.Buttons.StateChangedEventArgs eventArgs) { if (!skip) { skip = true; grilledChicken.IsChecked = chickenTikka.IsChecked = chickenSausage.IsChecked = beef.IsChecked = eventArgs.IsChecked.Value; button.IsEnabled = eventArgs.IsChecked.Value; skip = false; if (Device.RuntimePlatform == Device.WPF) button.TextColor = Color.Black; } } private void NonCheckBox_StateChanged(object sender, Syncfusion.XForms.Buttons.StateChangedEventArgs eventArgs) { grilledChicken.IsVisible = chickenTikka.IsVisible = chickenSausage.IsVisible = beef.IsVisible = eventArgs.IsChecked.Value; if (!eventArgs.IsChecked.Value) { selectAll.IsChecked = false; grilledChicken.IsChecked = chickenTikka.IsChecked = chickenSausage.IsChecked = beef.IsChecked = false; } } private bool? ValidateNonVegToopings() { if (grilledChicken.IsChecked.Value && chickenTikka.IsChecked.Value && chickenSausage.IsChecked.Value && beef.IsChecked.Value) return true; else if (!grilledChicken.IsChecked.Value && !chickenTikka.IsChecked.Value && !chickenSausage.IsChecked.Value && !beef.IsChecked.Value) return false; else return null; } } }<file_sep>/Android/SampleBrowser/Samples/TabView/View/TabContentListAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Java.Util; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Java.Lang; namespace SampleBrowser { internal class TabContentListAdapter : BaseAdapter<TabData> { private IEnumerable<TabData> list; public TabContentListAdapter(IEnumerable<TabData> _list) { list = _list; } public override TabData this[int position] { get { return list.ToList<TabData>()[position]; } } public override int Count { get { return list.ToList<TabData>().Count; } } public override long GetItemId(int position) { return position; } int currentApiVersion = (int)Build.VERSION.SdkInt; public override View GetView(int position, View convertView, ViewGroup parent) { var context = parent.Context; var item = list.ToList<TabData>()[position]; var mainLayout = new GridLayout(context); var nameLabel = new TextView(context); nameLabel.TextSize = 20; nameLabel.SetLines(2); nameLabel.LayoutParameters = new ViewGroup.LayoutParams(((context.Resources.DisplayMetrics.WidthPixels / 2 - 85) / 3) * 2, 170); nameLabel.Text = item.Name; if (IsTabletDevice(context)) { nameLabel.TextSize = 30; nameLabel.SetLines(1); nameLabel.LayoutParameters = new ViewGroup.LayoutParams(360, 120); } var imageView = new ImageView(context); var imageID = Application.Context.Resources.GetIdentifier(item.ImagePath.Replace(".jpeg", "").Replace(".jpg", ""), "drawable", Application.Context.PackageName); imageView.SetImageResource(imageID); imageView.SetPadding(10, 40, 20, 20); imageView.LayoutParameters = new ViewGroup.LayoutParams(640, 540); imageView.SetScaleType(ImageView.ScaleType.FitXy); if (IsTabletDevice(context)) { imageView.LayoutParameters = new ViewGroup.LayoutParams(500, 500); } var priceLabel = new TextView(context); priceLabel.LayoutParameters = new ViewGroup.LayoutParams(170, 90); priceLabel.SetTextColor(Color.Rgb(128, 207, 53)); priceLabel.TextSize = 15; priceLabel.Text = "$" + item.Price; if (IsTabletDevice(context)) { priceLabel.LayoutParameters = new ViewGroup.LayoutParams(150, 120); priceLabel.TextSize = 20; } var description = new TextView(context); description.LayoutParameters = new ViewGroup.LayoutParams(context.Resources.DisplayMetrics.WidthPixels / 2 - 130, 300); if (!IsTabletDevice(context)) description.SetPadding(0, -8, 10, 0); description.SetTextColor(Color.Rgb(134, 134, 134)); description.TextSize = 10; if (!IsTabletDevice(context)) description.SetLines(10); description.Text = item.Description; if (IsTabletDevice(context)) { description.SetLines(10); description.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 300); description.SetPadding(0, 0, 10, 0); description.TextSize = 15; } var offerLabel = new TextView(context); offerLabel.SetTextColor(Color.Rgb(128, 207, 53)); offerLabel.TextSize = 15; offerLabel.Text = item.Offer + "% Offer"; offerLabel.LayoutParameters = new ViewGroup.LayoutParams(200, 90); if (IsTabletDevice(context)) { offerLabel.TextSize = 20; offerLabel.LayoutParameters = new ViewGroup.LayoutParams(250, 120); } var ratingLabel = new TextView(context); ratingLabel.SetBackgroundColor(Color.Rgb(77, 146, 223)); ratingLabel.Text = "*" + item.Rating; ratingLabel.TextSize = 13; ratingLabel.TextAlignment = TextAlignment.TextEnd; ratingLabel.Gravity = GravityFlags.Right; ratingLabel.SetTextColor(Color.White); if (IsTabletDevice(context)) { ratingLabel.TextSize = 20; ratingLabel.Gravity = GravityFlags.Center; ratingLabel.LayoutParameters = new ViewGroup.LayoutParams(60, 50); } var detailsLayout = new GridLayout(context); detailsLayout.ColumnCount = 2; detailsLayout.LayoutParameters = new ViewGroup.LayoutParams(context.Resources.DisplayMetrics.WidthPixels / 2 - 100, 90); detailsLayout.SetPadding(0, 10, 10, 10); detailsLayout.AddView(priceLabel); detailsLayout.AddView(offerLabel); detailsLayout.SetBackgroundColor(Color.White); if (IsTabletDevice(context)) { detailsLayout.LayoutParameters = new ViewGroup.LayoutParams(context.Resources.DisplayMetrics.WidthPixels / 2 - 100, 100); } var headerGrid = new GridLayout(context); headerGrid.LayoutParameters = new ViewGroup.LayoutParams(context.Resources.DisplayMetrics.WidthPixels / 2 - 100, 170); headerGrid.SetPadding(0, 10, 10, 10); headerGrid.ColumnCount = 2; headerGrid.RowCount = 1; headerGrid.AddView(nameLabel); headerGrid.AddView(ratingLabel); if (IsTabletDevice(context)) { headerGrid.LayoutParameters = new ViewGroup.LayoutParams(800, 100); } var subGrid = new GridLayout(context); subGrid.LayoutParameters = new ViewGroup.LayoutParams(context.Resources.DisplayMetrics.WidthPixels / 2 - 100, 600); subGrid.SetPadding(10, 0, 10, 0); subGrid.ColumnCount = 1; subGrid.RowCount = 3; if (IsTabletDevice(context)) { subGrid.LayoutParameters = new ViewGroup.LayoutParams(500, 500); subGrid.SetPadding(10, 30, 10, 0); } subGrid.AddView(headerGrid); subGrid.AddView(detailsLayout); subGrid.AddView(description); if (currentApiVersion <= 19) { mainLayout.LayoutParameters = new AbsListView.LayoutParams(context.Resources.DisplayMetrics.WidthPixels, 600); } else { mainLayout.LayoutParameters = new ViewGroup.LayoutParams(context.Resources.DisplayMetrics.WidthPixels, 600); } if (IsTabletDevice(context)) { mainLayout.LayoutParameters = new ViewGroup.LayoutParams(context.Resources.DisplayMetrics.WidthPixels, 500); } mainLayout.SetPadding(20, 20, 20, 0); mainLayout.ColumnCount = 2; mainLayout.RowCount = 1; mainLayout.AddView(imageView); mainLayout.AddView(subGrid); mainLayout.SetBackgroundColor(Color.White); return mainLayout; } public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = Java.Lang.Math.Sqrt(Java.Lang.Math.Pow(screenWidth, 2) + Java.Lang.Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } } } <file_sep>/Android/SampleBrowser/Samples/DataSource/Helper/ContactsAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.DataSource; using System.Collections.Specialized; using Java.Lang; using Android.Graphics; using Syncfusion.DataSource.Extensions; namespace SampleBrowser { public class ContactsAdapter : BaseAdapter<object>, ISectionIndexer { private DataSource dataSource; private Context context; private Dictionary<string, int> alphaIndex; private Dictionary<string, int> decendingAlphaIndex; private string[] sections; private string[] decendingSection; private Java.Lang.Object[] sectionsObjects; private Java.Lang.Object[] decendingSectionsObjects; public ContactsAdapter(DataSource dataSource, Context cntxt) : base() { this.dataSource = dataSource; this.dataSource.DisplayItems.CollectionChanged += DisplayItems_CollectionChanged; context = cntxt; alphaIndex = new Dictionary<string, int>(); for (int i = 0; i < this.Count; i++) { var key = (this[i] as Contacts).ContactName[0].ToString(); if (!alphaIndex.ContainsKey(key)) { alphaIndex.Add(key, i); } } sections = new string[alphaIndex.Keys.Count]; alphaIndex.Keys.CopyTo(sections, 0); sectionsObjects = new Java.Lang.Object[sections.Length]; for (int i = 0; i < sections.Length; i++) { sectionsObjects[i] = new Java.Lang.String(sections[i]); } } private void DisplayItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset && this.dataSource.SortDescriptors.Count > 0 && this.dataSource.SortDescriptors[0].Direction == Syncfusion.DataSource.ListSortDirection.Descending) { if (decendingAlphaIndex == null) { decendingAlphaIndex = new Dictionary<string, int>(); for (int i = 0; i < this.Count; i++) { var key = (this[i] as Contacts).ContactName[0].ToString(); if (!decendingAlphaIndex.ContainsKey(key)) { decendingAlphaIndex.Add(key, i); } } decendingSection = new string[decendingAlphaIndex.Keys.Count]; decendingAlphaIndex.Keys.CopyTo(decendingSection, 0); decendingSectionsObjects = new Java.Lang.Object[decendingSection.Length]; for (int i = 0; i < sections.Length; i++) { decendingSectionsObjects[i] = new Java.Lang.String(decendingSection[i]); } } } this.NotifyDataSetChanged(); } public override int Count { get { return dataSource.DisplayItems.Count; } } public override long GetItemId(int position) { return position; } public override object this[int index] { get { return this.dataSource.DisplayItems[index]; } } public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; var contacttemplate = view as ConctactTemplate; if (this[position] is Contacts) { if (view == null || contacttemplate == null) { view = new ConctactTemplate(this.context); } view.SetBackgroundColor(Color.Transparent); (view as ConctactTemplate).UpdateValue(this[position]); } else if (this[position] is GroupResult) { GroupResult group = (GroupResult)this[position]; if (view == null || contacttemplate != null) { var textView = new TextView(this.context); textView.SetBackgroundColor(Color.Rgb(217, 217, 217)); textView.Gravity = GravityFlags.CenterVertical; textView.TextSize = 18; textView.SetTypeface(Typeface.DefaultBold, TypefaceStyle.Bold); textView.SetPadding((int)(15 * context.Resources.DisplayMetrics.Density), 0, 0, 0); textView.SetMinimumHeight((int)(40 * context.Resources.DisplayMetrics.Density)); textView.Text = group.Key.ToString(); view = textView; } else { (view as TextView).Text = group.Key.ToString(); } } return view; } protected override void Dispose(bool disposing) { base.Dispose(disposing); this.dataSource.Dispose(); this.dataSource = null; } public Java.Lang.Object[] GetSections() { if (dataSource.SortDescriptors[0].Direction == Syncfusion.DataSource.ListSortDirection.Ascending) { return sectionsObjects; } else { return decendingSectionsObjects; } } public int GetPositionForSection(int section) { if (dataSource.SortDescriptors[0].Direction == Syncfusion.DataSource.ListSortDirection.Ascending) { return alphaIndex[sections[section]]; } else { return decendingAlphaIndex[decendingSection[section]]; } } public int GetSectionForPosition(int position) { // this method isn't called in this example, but code is provided for completeness int prevSection = 0; for (int i = 0; i < sections.Length; i++) { if (GetPositionForSection(i) > position) { break; } prevSection = i; } return prevSection; } } }<file_sep>/Android/SampleBrowser/Samples/Barcode/Codabar.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Com.Syncfusion.Barcode; using Com.Syncfusion.Barcode.Enums; namespace SampleBrowser { public class Codabar : SamplePage { SfBarcode barcode; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 16; text1.Typeface = Typeface.DefaultBold; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "Allowed Characters"; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView text2 = new TextView(con); text2.TextSize = 14; text2.Text = "0-9, -, $,:, /, dot(.), +"; text2.SetTextColor(Color.ParseColor("#3F3F3F")); text2.SetPadding(5, 5, 5, 5); LinearLayout text2Layout = new LinearLayout(con); LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent); text2Layout.LayoutParameters = parms; text2Layout.AddView(text2); linear.AddView(text2Layout); LinearLayout barcodeLayout = new LinearLayout(con); barcodeLayout.SetPadding(0, 10, 0, 5); LinearLayout.LayoutParams parms1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent); barcodeLayout.LayoutParameters = parms1; barcode = new SfBarcode(con); barcode.Text = "$52675:14-98"; Typeface fontFamily = Typeface.Create("helvetica", TypefaceStyle.Bold); barcode.TextFont = fontFamily; barcode.SetBackgroundColor(Color.ParseColor("#F2F2F2")); barcode.Symbology = BarcodeSymbolType.Codabar; barcode.TextSize = 20; CodabarSettings setting = new CodabarSettings(); setting.BarHeight = 120; setting.NarrowBarWidth = 3; barcode.SymbologySettings = setting; barcodeLayout.AddView(barcode); linear.AddView(barcodeLayout); return linear; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/ImageEditor/BannerTypes.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using System.Threading; using CoreGraphics; using Syncfusion.SfImageEditor.iOS; using UIKit; using System.Reflection; using Foundation; using Photos; namespace SampleBrowser { public class BannerTypes : SampleView { UINavigationController navigationController; public BannerTypes() { } public override void MovedToSuperview() { base.MovedToSuperview(); var view = Superview; var window = UIApplication.SharedApplication.KeyWindow; navigationController = window.RootViewController as UINavigationController; } public override void LayoutSubviews() { base.LayoutSubviews(); UIView mainView = new UIView(); nfloat TotalWidth = Frame.Width - 10; mainView.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); int padding = 3; /*------Header Label-------*/ UILabel label = new UILabel(new CGRect(20, 50, TotalWidth, 25)); label.BackgroundColor = UIColor.Clear; label.Font = UIFont.SystemFontOfSize(25); label.TextAlignment = UITextAlignment.Left; label.TextColor = UIColor.Gray; label.Text = "Banner Types"; UIButton imageView1 = new UIButton(new CGRect(padding, 100, (TotalWidth / 3) - padding, 150)); imageView1.SetImage(UIImage.FromBundle("Images/ImageEditor/dashboard.jpg"), UIControlState.Normal); imageView1.ImageView.ContentMode = UIViewContentMode.ScaleToFill; imageView1.Layer.BorderColor = UIColor.LightGray.CGColor; imageView1.Layer.BorderWidth = 0.5f; imageView1.TouchDown += (sender, e) => { navigationController.PushViewController(new BannerViewController(imageView1.CurrentImage, 0), false); }; mainView.AddSubview(imageView1); UIButton imageView2 = new UIButton(new CGRect((TotalWidth / 3) + (1 * padding), 100, (TotalWidth / 3) - padding, 150)); imageView2.SetImage(UIImage.FromBundle("Images/ImageEditor/succinity.png"), UIControlState.Normal); imageView2.ImageView.ContentMode = UIViewContentMode.ScaleToFill; imageView2.Layer.BorderColor = UIColor.LightGray.CGColor; imageView2.Layer.BorderWidth = 0.5f; mainView.AddSubview(imageView2); imageView2.TouchDown += (sender, e) => { navigationController.PushViewController(new BannerViewController(imageView2.CurrentImage, 1), false); }; UIButton imageView3 = new UIButton(new CGRect((2 * (TotalWidth / 3)) + (1 * padding), 100, (TotalWidth / 3) - padding, 150)); imageView3.SetImage(UIImage.FromBundle("Images/ImageEditor/twitter.jpeg"), UIControlState.Normal); imageView3.ImageView.ContentMode = UIViewContentMode.ScaleToFill; imageView3.Layer.BorderColor = UIColor.LightGray.CGColor; imageView3.Layer.BorderWidth = 0.5f; imageView3.TouchDown += (sender, e) => { navigationController.PushViewController(new BannerViewController(imageView3.CurrentImage, 2), false); }; mainView.AddSubview(imageView3); AddSubview(label); AddSubview(mainView); } } public class BannerViewController : UIViewController { UIImage _image; public BannerViewController(UIImage image, int index) { _image = image; selectedIndex = index; } SfImageEditor sfImageEditor; UIViewController presentController; UIView CropSelectionMenu; int selectedIndex = 0; public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); presentController = GetVisibleViewController(); sfImageEditor = new SfImageEditor(new CGRect(View.Frame.Location.X, 60, View.Frame.Size.Width, View.Frame.Size.Height - 60)); sfImageEditor.ToolBarSettings.ToolbarItems.Clear(); sfImageEditor.ToolBarSettings.ToolbarItems.Add(new FooterToolbarItem() { Text = "Banner Types", SubItems = new System.Collections.Generic.List<ToolbarItem>() { new ToolbarItem(){Text="Facebook Post"}, new ToolbarItem(){Text="Facebook Cover"}, new ToolbarItem(){Text="Twitter Cover"}, new ToolbarItem(){Text="Twitter Post"}, new ToolbarItem(){Text="YouTubeChannel Cover"} } }); sfImageEditor.ToolBarSettings.ToolbarItems.Add(new CustomHeader() { HeaderName = "Share", Icon = UIImage.FromBundle("Images/ImageEditor/share.png") }); sfImageEditor.ToolBarSettings.ToolbarItemSelected += ToolbarItemSelected; sfImageEditor.ImageSaved += ImageEditor_ImageSaved; sfImageEditor.Image = _image; this.View.AddSubview(sfImageEditor); CropSelectionMenu = new UIView(new CGRect(0, 60, View.Frame.Width, 50)); CropSelectionMenu.BackgroundColor = UIColor.White; UIButton okButton = new UIButton(new CGRect(0, 0, View.Frame.Width / 2, 50)); okButton.SetTitle("OK", UIControlState.Normal); okButton.SetTitleColor(UIColor.Black, UIControlState.Normal); okButton.TouchDown += (sender, e) => { sfImageEditor.Crop(); CropSelectionMenu.Hidden = true; }; CropSelectionMenu.AddSubview(okButton); UIButton cancelButton = new UIButton(new CGRect(View.Frame.Width / 2, 0, View.Frame.Width / 2, 50)); cancelButton.SetTitle("Cancel", UIControlState.Normal); cancelButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cancelButton.TouchDown += (sender, e) => { sfImageEditor.ToggleCropping(); CropSelectionMenu.Hidden = true; }; CropSelectionMenu.Hidden = true; CropSelectionMenu.AddSubview(cancelButton); View.AddSubview(CropSelectionMenu); } void ToolbarItemSelected(object sender, ToolbarItemSelectedEventArgs e) { if (e.ToolbarItem is ToolbarItem) { var toolitem = e.ToolbarItem as ToolbarItem; if (!(toolitem is HeaderToolbarItem)) { CropSelectionMenu.Hidden = false; } if (toolitem is HeaderToolbarItem) sfImageEditor.Save(); else if (toolitem.Text == "Facebook Post") sfImageEditor.ToggleCropping(1200, 900); else if (toolitem.Text == "Facebook Cover") sfImageEditor.ToggleCropping(851, 315); else if (toolitem.Text == "Twitter Cover") sfImageEditor.ToggleCropping(1500, 500); else if (toolitem.Text == "Twitter Post") sfImageEditor.ToggleCropping(1024, 512); else if (toolitem.Text == "YouTubeChannel Cover") sfImageEditor.ToggleCropping(2560, 1440); else if (toolitem.Text == "Banner Types") sfImageEditor.ToggleCropping(1200, 900); } } void ImageEditor_ImageSaved(object sender, ImageSavedEventArgs e) { string[] str = e.Location.Split('/'); PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null); PHAsset asset = assetResult.firstObject as PHAsset; Stream stream = null; PHImageManager.DefaultManager.RequestImageData(asset, null, async (data, dataUti, orientation, info) => { UIImage newImage = new UIImage(data); var items = new NSObject[] { newImage }; var activityController = new UIActivityViewController(items, null); NSString[] excludedActivityTypes = null; if (excludedActivityTypes != null && excludedActivityTypes.Length > 0) activityController.ExcludedActivityTypes = excludedActivityTypes; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { if (activityController.PopoverPresentationController != null) { activityController.PopoverPresentationController.SourceView = presentController.View; } } await presentController.PresentViewControllerAsync(activityController, true); }); } internal static UIViewController GetVisibleViewController() { var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController; if (rootController.PresentedViewController == null) return rootController; if (rootController.PresentedViewController is UINavigationController) { return ((UINavigationController)rootController.PresentedViewController).TopViewController; } if (rootController.PresentedViewController is UITabBarController) { return ((UITabBarController)rootController.PresentedViewController).SelectedViewController; } return rootController.PresentedViewController; } } public class CustomHeader : HeaderToolbarItem { public string HeaderName { get; set; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/SwipingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SwipingViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for Swiping sample. /// </summary> public class SwipingViewModel : INotifyPropertyChanged { #region Field [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private OrderInfoRepository order; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<OrderInfo> ordersInfo; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Random random = new Random(); #endregion /// <summary> /// Initializes a new instance of the SwipingViewModel class. /// </summary> public SwipingViewModel() { this.SetRowstoGenerate(100); } #region ItemsSource /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the value of OrdersInfo and notifies user when value gets changed /// </summary> public ObservableCollection<OrderInfo> OrdersInfo { get { return this.ordersInfo; } set { this.ordersInfo = value; this.RaisePropertyChanged("OrdersInfo"); } } #endregion #region ItemSource Generator /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">generates row count</param> public void SetRowstoGenerate(int count) { this.order = new OrderInfoRepository(); this.ordersInfo = this.order.GetOrderDetails(count); } #endregion /// <summary> /// Used to add more records in View while call this method /// </summary> internal void ItemsSourceRefresh() { var count = this.random.Next(1, 6); for (int i = 11000; i < 11000 + count; i++) { int val = i + this.random.Next(100, 150); this.OrdersInfo.Insert(0, this.order.RefreshItemsource(val)); } } #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">String type of parameter name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } } <file_sep>/Forms/Diagram/Diagram/Samples/FlowDiagram/FlowDiagram.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Xamarin.Forms; using Syncfusion.SfDiagram.XForms; using SampleBrowser.Core; namespace SampleBrowser.SfDiagram { public partial class FlowDiagram : SampleView { private int size = 12; public FlowDiagram() { InitializeComponent(); diagram.ContextMenuSettings.Visibility = false; if (Device.RuntimePlatform == Device.Android) Xamarin.Forms.DependencyService.Get<IText>().GenerateFactor(); diagram.PageSettings.PageBackGround = Color.White; if (Device.RuntimePlatform == Device.UWP) { diagram.PageSettings.PageWidth = 1600; diagram.PageSettings.PageHeight = double.NaN; diagram.BackgroundColor = Color.White; } //For iOS int Y = 60; //Create Node Node n1 = DrawNode(130, 80, 160, 55, ShapeType.Ellipse, "New idea identified"); n1.Style.Brush = new SolidBrush(Color.FromRgb(49, 162, 255)); n1.Style.StrokeBrush = new SolidBrush(Color.FromRgb(23, 132, 206)); Y += 120; Node n2 = DrawNode(130, Y, 160, 55, ShapeType.RoundedRectangle, "Meeting With Board"); if (Device.RuntimePlatform == Device.UWP) { n2.ShapeType = ShapeType.Rectangle; } n2.Style.Brush = new SolidBrush(Color.FromRgb(49, 162, 255)); n2.Style.StrokeBrush = new SolidBrush(Color.FromRgb(23, 132, 206)); Y += 120; Node n3 = DrawNode(135, Y, 150, 150, ShapeType.Diamond, "Board decides to proceed"); n3.Style.Brush = new SolidBrush(Color.FromRgb(0, 194, 192)); n3.Style.StrokeBrush = new SolidBrush(Color.FromRgb(4, 142, 135)); Y += 150; Node n4 = DrawNode(135, Y + 50, 150, 150, ShapeType.Diamond, "Write specification document"); n4.Style.Brush = new SolidBrush(Color.FromRgb(0, 194, 192)); n4.Style.StrokeBrush = new SolidBrush(Color.FromRgb(14, 142, 135)); Y += 150; Node n5 = DrawNode(130, Y + 100, 160, 55, ShapeType.Ellipse, "Implement and deliver"); n5.Style.Brush = new SolidBrush(Color.FromRgb(49, 162, 255)); n5.Style.StrokeBrush = new SolidBrush(Color.FromRgb(23, 132, 206)); Y = (int)(n3.OffsetY / DiagramUtility.factor); int X = (int)(n3.OffsetX / DiagramUtility.factor) + 350; Node n6 = DrawNode(X - 100, Y + 48, 160, 55, ShapeType.RoundedRectangle, "Reject and report the reason"); if (Device.RuntimePlatform == Device.UWP) { n6.ShapeType = ShapeType.Rectangle; } n6.Style.Brush = new SolidBrush(Color.FromRgb(239, 75, 93)); n6.Style.StrokeBrush = new SolidBrush(Color.FromRgb(201, 32, 61)); Y = (int)(n6.OffsetY / DiagramUtility.factor) + 150; X = (int)(n6.OffsetX / DiagramUtility.factor); Node n7 = DrawNode(X, Y + 50, 160, 55, ShapeType.RoundedRectangle, "Hire new resources"); if (Device.RuntimePlatform == Device.UWP) { n7.ShapeType = ShapeType.Rectangle; } n7.Style.Brush = new SolidBrush(Color.FromRgb(239, 75, 93)); n7.Style.StrokeBrush = new SolidBrush(Color.FromRgb(201, 32, 61)); //Add node to the diagram diagram.AddNode(n1); diagram.AddNode(n2); diagram.AddNode(n3); diagram.AddNode(n4); diagram.AddNode(n5); diagram.AddNode(n6); diagram.AddNode(n7); //Create Connector Connector c1 = new Connector(); c1.SourceNode = n1; c1.TargetNode = n2; diagram.AddConnector(c1); Connector c2 = new Connector(); c2.SourceNode = n2; c2.TargetNode = n3; diagram.AddConnector(c2); Connector c3 = new Connector(); c3.SourceNode = n3; c3.TargetNode = n4; Annotation annotation3 = new Annotation(); annotation3.Content = "Yes"; annotation3.FontSize = 12 * DiagramUtility.factor; annotation3.TextBrush = new SolidBrush(Color.Black); c3.Annotations.Add(annotation3); diagram.AddConnector(c3); Connector c4 = new Connector(); c4.SourceNode = n4; c4.TargetNode = n5; c4.Annotations.Add(new Annotation() { Content = "Yes", FontSize = 12 * DiagramUtility.factor, TextBrush = new SolidBrush(Color.Black) }); diagram.AddConnector(c4); Connector c5 = new Connector(); c5.SourceNode = n3; c5.TargetNode = n6; c5.Annotations.Add(new Annotation() { Content = "No", FontSize = 12 * DiagramUtility.factor, TextBrush = new SolidBrush(Color.Black) }); diagram.AddConnector(c5); Connector c6 = new Connector(); c6.SourceNode = n4; c6.TargetNode = n7; diagram.AddConnector(c6); c6.Annotations.Add(new Annotation() { Content = "No", FontSize = 12 * DiagramUtility.factor, TextBrush = new SolidBrush(Color.Black) }); for (int i = 0; i < diagram.Connectors.Count; i++) { diagram.Connectors[i].TargetDecoratorStyle.StrokeThickness = 2 * DiagramUtility.currentDensity; diagram.Connectors[i].Style.StrokeWidth = 1 * DiagramUtility.currentDensity; } Content = diagram; diagram.ConnectorClicked += Diagram_ConnectorClicked; diagram.Loaded += Diagram_Loaded; diagram.EnableTextEditing = false; } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.RuntimePlatform == Device.Android) { diagram.WidthRequest = width; diagram.HeightRequest = height; } if (Device.RuntimePlatform == Device.iOS) { diagram.PageSettings.PageWidth = width; diagram.PageSettings.PageHeight = height; } } private void Diagram_Loaded(object sender) { HideSelectors(); } private void HideSelectors() { diagram.ShowSelectorHandle(false, SelectorPosition.SourcePoint); diagram.ShowSelectorHandle(false, SelectorPosition.TargetPoint); diagram.ShowSelectorHandle(false, SelectorPosition.Rotator); diagram.ShowSelectorHandle(false, SelectorPosition.TopLeft); diagram.ShowSelectorHandle(false, SelectorPosition.TopRight); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleLeft); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleRight); diagram.ShowSelectorHandle(false, SelectorPosition.BottomCenter); diagram.ShowSelectorHandle(false, SelectorPosition.BottomLeft); diagram.ShowSelectorHandle(false, SelectorPosition.BottomRight); diagram.ShowSelectorHandle(false, SelectorPosition.TopCenter); } private void Diagram_ConnectorClicked(object sender, ConnectorClickedEventArgs args) { diagram.ClearSelection(); } private void PageSettingColor_SelectedIndexChanged(object sender, EventArgs e) { } //Creates the Node with Specified input private Node DrawNode(float x, float y, float w, float h, ShapeType shape, string annotation) { var node = new Node(); node.Style.StrokeWidth = 1; if (Device.RuntimePlatform == Device.Android) { node.OffsetX = x * DiagramUtility.factor; node.OffsetY = y * DiagramUtility.factor; node.Width = w * DiagramUtility.factor; node.Height = h * DiagramUtility.factor; } else { node.OffsetX = x; node.OffsetY = y; node.Width = w; node.Height = h; } node.ShapeType = shape; if (Device.RuntimePlatform == Device.Android) { var textView = Xamarin.Forms.DependencyService.Get<IText>().GetTextView(annotation, node.Width); node.Annotations.Add(new Annotation() { Content = textView, TextBrush = new SolidBrush(Color.White), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, FontSize = 10 * DiagramUtility.currentDensity, }); } else { node.Annotations.Add(new Annotation() { Content = annotation, TextBrush = new SolidBrush(Color.FromRgb(255, 255, 255)), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, FontSize = 10 * DiagramUtility.factor, }); } return node; } void ShowGrid_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e) { if (ShowGridSwitch.IsToggled) { diagram.PageSettings.ShowGrid = true; diagram.PageSettings.GridColor = Color.FromHex("#E6E6E6"); if (Device.RuntimePlatform == Device.Android) { diagram.PageSettings.GridSize = int.Parse(GridtThickness.Text) * DiagramUtility.currentDensity; } else diagram.PageSettings.GridSize = int.Parse(GridtThickness.Text); ValidateColor(fillStack, diagram.PageSettings.GridColor); } else if (!ShowGridSwitch.IsToggled) { diagram.PageSettings.ShowGrid = false; diagram.PageSettings.GridColor = Color.Transparent; ValidateColor(fillStack, diagram.PageSettings.GridColor); } } void SnapToGrid_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e) { if (SnapToGridSwitch.IsToggled) { diagram.PageSettings.SnapToGrid = true; } else if (!SnapToGridSwitch.IsToggled) diagram.PageSettings.SnapToGrid = false; } void ChangeColor(object sender, EventArgs e) { if ( ShowGridSwitch.IsToggled) { diagram.PageSettings.GridColor = (sender as Button).BackgroundColor; ValidateColor(fillStack,diagram.PageSettings.GridColor); } } void ValidateColor(StackLayout Stack, Color ColorToCheck) { for (int i = 0; i < Stack.Children.Count; i++) { for (int j = 0; j < (Stack.Children[i] as StackLayout).Children.Count; j++) { if (((Stack.Children[i] as StackLayout).Children[j] as Button).BackgroundColor == ColorToCheck) { ((Stack.Children[i] as StackLayout).Children[j] as Button).BorderColor = Color.Blue; } else ((Stack.Children[i] as StackLayout).Children[j] as Button).BorderColor = Color.Transparent; } } } private void OnGridSizePlus(object sender, EventArgs e) { if(ShowGridSwitch.IsToggled) { if (size < 20) { size++; if (Device.RuntimePlatform == Device.Android) { diagram.PageSettings.GridSize = size * (1 * DiagramUtility.currentDensity); } else diagram.PageSettings.GridSize = size; GridtThickness.Text = size.ToString(); } } } private void OnGridSizeSubtract(object sender, EventArgs e) { if (ShowGridSwitch.IsToggled) { if (size > 5) { size--; if (Device.RuntimePlatform == Device.Android) { diagram.PageSettings.GridSize = size * (1 * DiagramUtility.currentDensity); } else diagram.PageSettings.GridSize = size; GridtThickness.Text = size.ToString(); } } } //To Set Color void UpdateColor(Color SelectedColor, String StackName, StackLayout button) { diagram.PageSettings.GridColor = SelectedColor; } } }<file_sep>/Forms/Chart/Chart/Samples/VerticalChart/VerticalChart.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class VerticalChart : SampleView { public VerticalChart() { InitializeComponent(); VerticalChartViewModel viewModel = chart.BindingContext as VerticalChartViewModel; viewModel.LoadVerticalData(); viewModel.StartTimer(); } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if ((Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS)) { if (height > 0 && width > 0) { if (height > width) { fastlineseries.StrokeWidth = 2; chart.Legend.DockPosition = LegendPlacement.Bottom; } else { fastlineseries.StrokeWidth = 1; chart.Legend.DockPosition = LegendPlacement.Right; } } } } } }<file_sep>/Forms/Schedule/Schedule/Samples/RecursiveAppointments/ViewModel/RecurrenceViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Recurrence View Model class /// </summary> [Preserve(AllMembers = true)] public class RecurrenceViewModel { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="RecurrenceViewModel" /> class. /// </summary> public RecurrenceViewModel() { this.CreateRecurrsiveAppointments(); } #endregion Constructor #region Properties /// <summary> /// Gets or sets recursive appointment collection /// </summary> public ScheduleAppointmentCollection RecursiveAppointmentCollection { get; set; } #endregion Properties #region creating RecurrsiveAppointments /// <summary> /// recursive appointments /// </summary> ////creating RecurrsiveAppointments private void CreateRecurrsiveAppointments() { this.RecursiveAppointmentCollection = new ScheduleAppointmentCollection(); //Recurrence Appointment 1 ScheduleAppointment alternativeDayAppointment = new ScheduleAppointment(); DateTime currentDate = DateTime.Now; DateTime startTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 9, 0, 0); DateTime endTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 10, 0, 0); alternativeDayAppointment.StartTime = startTime; alternativeDayAppointment.EndTime = endTime; alternativeDayAppointment.Color = Color.FromHex("#FFA2C139"); alternativeDayAppointment.Subject = "Scrum meeting"; RecurrenceProperties recurrencePropertiesForAlternativeDay = new RecurrenceProperties(); recurrencePropertiesForAlternativeDay.RecurrenceType = RecurrenceType.Daily; recurrencePropertiesForAlternativeDay.Interval = 2; recurrencePropertiesForAlternativeDay.RecurrenceRange = RecurrenceRange.Count; recurrencePropertiesForAlternativeDay.RecurrenceCount = 10; alternativeDayAppointment.RecurrenceRule = DependencyService.Get<IRecurrenceBuilder>().RRuleGenerator(recurrencePropertiesForAlternativeDay, alternativeDayAppointment.StartTime, alternativeDayAppointment.EndTime); this.RecursiveAppointmentCollection.Add(alternativeDayAppointment); //Recurrence Appointment 2 ScheduleAppointment weeklyAppointment = new ScheduleAppointment(); DateTime startTime1 = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 11, 0, 0); DateTime endTime1 = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 12, 0, 0); weeklyAppointment.StartTime = startTime1; weeklyAppointment.EndTime = endTime1; weeklyAppointment.Color = Color.FromHex("#FFD80073"); weeklyAppointment.Subject = "Weekly product development status"; RecurrenceProperties recurrencePropertiesForWeeklyAppointment = new RecurrenceProperties(); recurrencePropertiesForWeeklyAppointment.RecurrenceType = RecurrenceType.Weekly; recurrencePropertiesForWeeklyAppointment.RecurrenceRange = RecurrenceRange.Count; recurrencePropertiesForWeeklyAppointment.Interval = 1; recurrencePropertiesForWeeklyAppointment.WeekDays = WeekDays.Monday; recurrencePropertiesForWeeklyAppointment.RecurrenceCount = 10; weeklyAppointment.RecurrenceRule = DependencyService.Get<IRecurrenceBuilder>().RRuleGenerator(recurrencePropertiesForWeeklyAppointment, weeklyAppointment.StartTime, weeklyAppointment.EndTime); this.RecursiveAppointmentCollection.Add(weeklyAppointment); //Recurrence Appointment 3 ScheduleAppointment lastWeekOfMonth = new ScheduleAppointment(); DateTime startTime2 = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 11, 0, 0); DateTime endTime2 = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, 12, 0, 0); lastWeekOfMonth.StartTime = startTime2; lastWeekOfMonth.EndTime = endTime2; lastWeekOfMonth.Color = Color.Red; lastWeekOfMonth.Subject = "Retrospective Meeting"; RecurrenceProperties recurrencePropertiesForLastWeekOfMonth = new RecurrenceProperties(); recurrencePropertiesForLastWeekOfMonth.RecurrenceType = RecurrenceType.Monthly; recurrencePropertiesForLastWeekOfMonth.RecurrenceRange = RecurrenceRange.Count; recurrencePropertiesForLastWeekOfMonth.Interval = 1; recurrencePropertiesForLastWeekOfMonth.Week = -1; recurrencePropertiesForLastWeekOfMonth.DayOfWeek=5; recurrencePropertiesForLastWeekOfMonth.RecurrenceCount = 10; lastWeekOfMonth.RecurrenceRule = DependencyService.Get<IRecurrenceBuilder>().RRuleGenerator(recurrencePropertiesForLastWeekOfMonth, lastWeekOfMonth.StartTime, lastWeekOfMonth.EndTime); this.RecursiveAppointmentCollection.Add(lastWeekOfMonth); } #endregion creating RecurrsiveAppointments } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/RangeBar.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Android.Views; using Com.Syncfusion.Charts; using Android.Graphics; namespace SampleBrowser { public class RangeBar : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Pipeline Volume"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); CategoryAxis categoryaxis = new CategoryAxis(); categoryaxis.ShowMajorGridLines = false; categoryaxis.LabelStyle.TextColor = Color.Black; categoryaxis.LineStyle.StrokeWidth = 0; categoryaxis.LabelStyle.TextSize = 11; categoryaxis.MajorTickStyle.TickSize = 0; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Visibility = Visibility.Gone; numericalaxis.ShowMajorGridLines = false; numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.TickSize = 0; numericalaxis.LabelStyle.LabelFormat = "$#,###"; chart.SecondaryAxis = numericalaxis; RangeColumnSeries rangeColumnSeries = new RangeColumnSeries(); rangeColumnSeries.ItemsSource = MainPage.GetRangeBarData(); rangeColumnSeries.XBindingPath = "XValue"; rangeColumnSeries.High = "YValue"; rangeColumnSeries.Low = string.Empty; rangeColumnSeries.Transposed = true; rangeColumnSeries.DataMarker.ShowLabel = true; rangeColumnSeries.DataMarker.LabelStyle.LabelFormat = "$#,###"; rangeColumnSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; chart.Series.Add(rangeColumnSeries); return chart; } } } <file_sep>/Forms/DataForm/DataForm/Samples/ContactForm/View/DataFormPage.xaml.cs #region Copyright // <copyright file="DataFormPage.xaml.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; /// <summary> /// Represents a simple data form sample view. /// </summary> [XamlCompilation(XamlCompilationOptions.Compile)] [Preserve(AllMembers = true)] public partial class DataFormPage : ContentPage { /// <summary> /// Initializes a new instance of the <see cref="DataFormPage"/> class. /// </summary> public DataFormPage() { this.InitializeComponent(); } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/CustomGrouping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Syncfusion.Data; using Syncfusion.SfDataGrid; namespace SampleBrowser { public class CustomGrouping : SamplePage { #region Fields SfDataGrid sfGrid; SalesInfoViewModel viewModel; #endregion #region Override Methods public override View GetSampleContent(Context context) { sfGrid = new SfDataGrid (context); viewModel = new SalesInfoViewModel (); sfGrid.SelectionMode = SelectionMode.Single; sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = viewModel.DailySalesDetails; sfGrid.AllowSorting = true; sfGrid.AllowGroupExpandCollapse = true; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; sfGrid.SortComparers.Add(new SortComparer() { Comparer = new CustomSortComparer(), PropertyName = "Total" }); sfGrid.GroupColumnDescriptions.Add (new GroupColumnDescription () { ColumnName = "Total", Converter = new GroupDataTimeConverter() }); //TableSummary codes GridTableSummaryRow summaryRow = new GridTableSummaryRow(); summaryRow.Title = "Total items:{Total} items"; summaryRow.ShowSummaryInRow = true; summaryRow.Position = Position.Bottom; GridSummaryColumn summaryColumn = new GridSummaryColumn(); summaryColumn.Name = "Total"; summaryColumn.MappingName = "Name"; summaryColumn.Format = "{Count}"; summaryColumn.SummaryType = Syncfusion.Data.SummaryType.CountAggregate; summaryRow.SummaryColumns.Add(summaryColumn); sfGrid.TableSummaryRows.Add(summaryRow); return sfGrid; } public override void Destroy() { sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; sfGrid.Dispose(); sfGrid = null; viewModel = null; } #endregion #region CallBacks private void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "Name") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "QS1") { e.Column.HeaderText = "Sales in Quarter1"; } else if (e.Column.MappingName == "QS2") { e.Column.HeaderText = "Sales in Quarter2"; } else if (e.Column.MappingName == "QS3") { e.Column.HeaderText = "Sales in Quarter3"; } else if (e.Column.MappingName == "QS4") { e.Column.HeaderText = "Sales in Quarter4"; } else if (e.Column.MappingName == "Total") { e.Column.HeaderText = "Total Sales in Year"; } } #endregion } }<file_sep>/iOS/SampleBrowser/Samples/RadialMenu/RadialMenuGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Syncfusion.SfRadialMenu.iOS; using UIKit; using System.Linq; namespace SampleBrowser { public class RadialMenuGettingStarted : SampleView { SfRadialMenu radialMenu; String[] layer = new string[] { "\uE701", "\uE702", "\uEA8F", "\uE706", "\uEBAA","\uE7E8"}; String[] wifi = new string[] { "\uEC3B", "\uEC3A", "\uEC39", "\uEC38", "\uEC37" }; String[] battery = new string[] { "\uEBB8","\uEBBC","\uEBC0" }; String[] brightness = new string[] { "\uEC8A", "\uEC8A", "\uE706" }; String[] profile = new string[] { "\uE7ED", "\uE877", "\uEA8F" }; String[] power = new string[] { "\uE708", "\uE777", "\uE7E8" }; UILabel eventLog; UISwitch enableRotation, isDragEnabled; UIView option = new UIView(); UILabel rimSizeLabel, enableRotationLabel, isDragEnabledLabel; UISlider rimSizeSlider; UITableView table; string[] tableItems; public RadialMenuGettingStarted() { eventLog = new UILabel(); eventLog.Lines = 0; eventLog.Text = "Event Log :"; eventLog.BackgroundColor = UIColor.White; eventLog.LineBreakMode = UILineBreakMode.WordWrap; table = new UITableView(this.Bounds); // defaults to Plain style tableItems = new string[100]; Add(eventLog); table.Source = new TableSourceCollection(tableItems); Add(table); radialMenu = new SfRadialMenu(); CGRect apprect = UIScreen.MainScreen.Bounds; radialMenu.Position = new CGPoint(apprect.Width / 2, 100); radialMenu.RimColor = UIColor.FromRGB(230, 230, 230); radialMenu.CenterButtonRadius = 30; radialMenu.RimRadius = 80; radialMenu.CenterButtonText = "\uE713"; radialMenu.CenterButtonBackText = "\uE72B"; radialMenu.CenterButtonIconFont = UIFont.FromName("Segoe MDL2 Assets", 30); radialMenu.CenterButtonTextColor = UIColor.White; radialMenu.CenterButtonBorderColor = UIColor.White; radialMenu.CenterButtonBorderThickness = 4; radialMenu.OuterRimColor = UIColor.FromRGB(124, 201, 255); radialMenu.RimActiveColor = UIColor.FromRGB(0, 191, 255); radialMenu.CenterButtonBackgroundColor = UIColor.FromRGB(153, 153, 153); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { radialMenu.CenterButtonRadius = 50; radialMenu.RimRadius = 160; radialMenu.EnableCenterButtonAnimation = false; radialMenu.CenterButtonIconFont = UIFont.FromName("Segoe MDL2 Assets", 60); } radialMenu.Opening += RadialMenu_Opening; radialMenu.Closed += RadialMenu_Closed; radialMenu.CenterButtonTapped += RadialMenu_CenterButtonTapped; for (int i = 0; i < 6; i++) { SfRadialMenuItem item = new SfRadialMenuItem() {IconFont = UIFont.FromName("Segoe MDL2 Assets",20), FontIcon=layer[i]}; item.ItemTapped+= Item_ItemTapped; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) item.IconFont = UIFont.FromName("Segoe MDL2 Assets", 30); item.Tag = 100 + i; radialMenu.Items.Add(item); } for (int i = 0; i < 4; i++) { SfRadialMenuItem item = new SfRadialMenuItem() { IconFont = UIFont.FromName("Segoe MDL2 Assets", 20), FontIcon = wifi[i] }; item.ItemTapped += Item_ItemTapped1; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) item.IconFont = UIFont.FromName("Segoe MDL2 Assets", 30); radialMenu.Items[0].Items.Add(item); } for (int i = 0; i < 4; i++) { SfRadialMenuItem item = new SfRadialMenuItem() { IconFont = UIFont.FromName("Segoe MDL2 Assets", 20), FontIcon = wifi[i] }; item.ItemTapped += Item_ItemTapped2; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) item.IconFont = UIFont.FromName("Segoe MDL2 Assets", 30); radialMenu.Items[1].Items.Add(item); } for (int i = 0; i < 3; i++) { SfRadialMenuItem item = new SfRadialMenuItem() { IconFont = UIFont.FromName("Segoe MDL2 Assets", 20), FontIcon = profile[i] }; item.ItemTapped += Item_ItemTapped3; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) item.IconFont = UIFont.FromName("Segoe MDL2 Assets", 30); radialMenu.Items[2].Items.Add(item); } for (int i = 0; i < 3; i++) { SfRadialMenuItem item = new SfRadialMenuItem() { IconFont = UIFont.FromName("Segoe MDL2 Assets", 20), FontIcon = brightness[i] }; item.ItemTapped += Item_ItemTapped4; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) item.IconFont = UIFont.FromName("Segoe MDL2 Assets", 30); radialMenu.Items[3].Items.Add(item); } for (int i = 0; i < 3; i++) { SfRadialMenuItem item = new SfRadialMenuItem() { IconFont = UIFont.FromName("Segoe MDL2 Assets", 20), FontIcon = battery[i] }; item.ItemTapped += Item_ItemTapped5; radialMenu.Items[4].Items.Add(item); } for (int i = 0; i < 3; i++) { SfRadialMenuItem item = new SfRadialMenuItem() { IconFont = UIFont.FromName("Segoe MDL2 Assets", 20), FontIcon = power[i] }; item.ItemTapped += Item_ItemTapped6; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) item.IconFont = UIFont.FromName("Segoe MDL2 Assets", 30); radialMenu.Items[5].Items.Add(item); } this.Add(radialMenu); addOptionView(); this.OptionView = option; } int i = 0; void RadialMenu_CenterButtonTapped(object sender, EventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = "Menu button has been tapped"; table.ReloadData(); i++; } void RadialMenu_Closed(object sender, EventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = "Menu has been closed"; table.ReloadData(); i++; } void RadialMenu_Opening(object sender, RadialMenuEventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = "Menu has been opened"; table.ReloadData(); i++; } void Item_ItemTapped(object sender, EventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } if((sender as SfRadialMenuItem).Tag == 100) tableItems[i] = "Navigated to WIFI signals"; else if((sender as SfRadialMenuItem).Tag == 101) tableItems[i]="Navigated to BlueTooth Signals"; else if ((sender as SfRadialMenuItem).Tag == 102) tableItems[i] = "Navigated to Profile settings"; else if ((sender as SfRadialMenuItem).Tag == 103) tableItems[i] = "Navigated to Brightness settings"; else if ((sender as SfRadialMenuItem).Tag == 104) tableItems[i] = "Navigated to Battery saver options"; else if ((sender as SfRadialMenuItem).Tag == 105) tableItems[i] = "Navigated to Power options"; table.ReloadData(); i++; } void Item_ItemTapped1(object sender, EventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = "WIFI signal has been activated"; table.ReloadData(); i++; } void Item_ItemTapped2(object sender, EventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = "BlueTooth signal has been activated"; table.ReloadData(); i++; } void Item_ItemTapped3(object sender, EventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = "Profile settings has been changed"; table.ReloadData(); i++; } void Item_ItemTapped4(object sender, EventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = "Device brightness has been changed"; table.ReloadData(); i++; } void Item_ItemTapped5(object sender, EventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = "Battery Saver activated"; table.ReloadData(); i++; } void Item_ItemTapped6(object sender, EventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = "Power options has been tapped"; table.ReloadData(); i++; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { eventLog.Frame = new CGRect(16, Frame.Height - 250, Frame.Width, 30); table.Frame = new CGRect(0,Frame.Height-220,Frame.Width-18,200); rimSizeLabel.Frame = new CGRect(10, 20, Frame.Width-20, 30); rimSizeSlider.Frame = new CGRect(10, 70, Frame.Width - 20, 30); enableRotationLabel.Frame = new CGRect(10, 120, Frame.Width - 20, 30); enableRotation.Frame = new CGRect(Frame.Width-60, 120, 50, 30); isDragEnabledLabel.Frame = new CGRect(10, 170, Frame.Width - 20, 30); isDragEnabled.Frame = new CGRect(Frame.Width - 60, 170, 50, 30); } else { radialMenu.Position = new CGPoint(Frame.Width / 2, Frame.Height/4); eventLog.Frame = new CGRect(16, Frame.Height/2, Frame.Width, 30); table.Frame = new CGRect(0, Frame.Height/2+30, Frame.Width - 18, Frame.Height/2-50); rimSizeLabel.Frame = new CGRect(10, 30, PopoverSize.Width - 20, 30); rimSizeSlider.Frame = new CGRect(10, 80, PopoverSize.Width - 20, 30); enableRotationLabel.Frame = new CGRect(10, 130, PopoverSize.Width - 20, 30); enableRotation.Frame = new CGRect(PopoverSize.Width - 60, 130, 50, 30); isDragEnabledLabel.Frame = new CGRect(10, 180, PopoverSize.Width - 20, 30); isDragEnabled.Frame = new CGRect(PopoverSize.Width - 60, 180, 50, 30); } } base.LayoutSubviews(); } void addOptionView() { loadOptionView(); this.option.AddSubview(rimSizeLabel); this.option.AddSubview(rimSizeSlider); this.option.AddSubview(enableRotationLabel); this.option.AddSubview(enableRotation); this.option.AddSubview(isDragEnabledLabel); this.option.AddSubview(isDragEnabled); } void loadOptionView() { //menuButtonSize rimSizeLabel = new UILabel(); rimSizeLabel.Text = "Rim Radius"; rimSizeLabel.TextColor = UIColor.Black; rimSizeLabel.TextAlignment = UITextAlignment.Left; rimSizeSlider = new UISlider(); rimSizeSlider.MinValue = 80f; rimSizeSlider.MaxValue = 160f; rimSizeSlider.Value = 80f; rimSizeSlider.ValueChanged += (object sender, EventArgs e) => { radialMenu.RimRadius = rimSizeSlider.Value; }; //enableRotationLabel enableRotationLabel = new UILabel(); enableRotationLabel.Text = "Rotation Enabled"; enableRotationLabel.TextColor = UIColor.Black; enableRotationLabel.TextAlignment = UITextAlignment.Left; //enableRotation enableRotation = new UISwitch(); enableRotation.On = true; enableRotation.ValueChanged += (sender, e) => { if (((UISwitch)sender).On) radialMenu.EnableRotation = true; else radialMenu.EnableRotation = false; }; //isDragEnabledLabel isDragEnabledLabel = new UILabel(); isDragEnabledLabel.Text = "Drag Enabled"; isDragEnabledLabel.TextColor = UIColor.Black; isDragEnabledLabel.TextAlignment = UITextAlignment.Left; //isDragEnabled isDragEnabled = new UISwitch(); isDragEnabled.On = true; isDragEnabled.ValueChanged += (sender, e) => { if (((UISwitch)sender).On) radialMenu.IsDragEnabled = true; else radialMenu.IsDragEnabled = false; }; } } } <file_sep>/Forms/Chart/Chart/Samples/DataPointSelection/DataPointSelection.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using System.Collections.Generic; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class DataPointSelection : SampleView { double sumOfTotalSeries1 = 0; double sumOfTotalSeries2 = 0; IList<ChartDataModel> datapoint; IList<ChartDataModel> datapoint1; public DataPointSelection() { InitializeComponent(); picker.SelectedIndex = 0; datapoint = (column.ItemsSource as IList<ChartDataModel>); datapoint1 = (column1.ItemsSource as IList<ChartDataModel>); foreach (var data in datapoint) { sumOfTotalSeries1 += data.Value; } foreach (var data in datapoint1) { sumOfTotalSeries2 += data.Value; } if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { secondaryAxisLabelStyle.LabelFormat = "$0"; } else { secondaryAxisLabelStyle.LabelFormat = "$##.##"; } if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.macOS || Device.RuntimePlatform == Device.WPF) { productA.HorizontalOptions = LayoutOptions.EndAndExpand; productA.Margin = new Thickness(0, 0, 10, 0); productB.HorizontalOptions = LayoutOptions.StartAndExpand; productB.Margin = new Thickness(10, 0, 0, 0); } } private void chart_SelectionChanged(object sender, ChartSelectionEventArgs e) { var series = e.SelectedSeries; if (series == null) return; if (Chart.EnableSeriesSelection) { productA.IsVisible = false; productB.IsVisible = false; seriesSelection.IsVisible = true; if (column.IsSelected) { seriesSelection.Text = series.Label + " | Total Sales : $" + sumOfTotalSeries1; return; } else if (column1.IsSelected) { seriesSelection.Text = series.Label + " | Total Sales : $" + sumOfTotalSeries2; return; } seriesSelection.Text = "Tap on a bar segment to select a series"; } else { productA.IsVisible = true; productB.IsVisible = true; seriesSelection.IsVisible = false; var selectedindex = e.SelectedDataPointIndex; var seriesIndex = Chart.Series.IndexOf(e.SelectedSeries); if (selectedindex < 0) { if (seriesIndex == 0) productA.Text = "Tap on a bar segment"; else productB.Text = "Tap on a bar segment"; return; } else { if (seriesIndex == 0) { var x = datapoint[selectedindex].Name; var y = datapoint[selectedindex].Value; productA.Text = "Month : " + x + ", Sales : $" + y; } else if (seriesIndex == 1) { var x = datapoint1[selectedindex].Name; var y = datapoint1[selectedindex].Value; productB.Text = "Month : " + x + ", Sales : $" + y; } } } } private void selectedIndex_Changed(object sender, System.EventArgs e) { int index = picker.SelectedIndex; productA.IsVisible = false; productB.IsVisible = false; seriesSelection.IsVisible = true; if (index == 0) { seriesSelection.Text = "Tap on a bar segment to select a data point"; Chart.EnableSeriesSelection = false; } else if(index == 1) { seriesSelection.Text = "Tap on a bar segment to select a series"; Chart.EnableSeriesSelection = true; } } } }<file_sep>/iOS/SampleBrowser/Samples/Schedule/ScheduleView/ScheduleViewsViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Foundation; using Syncfusion.SfSchedule.iOS; using UIKit; namespace SampleBrowser { public class ScheduleViewModel { internal ObservableCollection<ScheduleAppointment> CreateAppointments() { NSDate today = new NSDate(); SetColors(); SetSubjects(); ObservableCollection<ScheduleAppointment> appCollection = new ObservableCollection<ScheduleAppointment>(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)subjectCollection[i]; appointment.AppointmentBackground = colorCollection[i]; if (i == 2 || i == 4) { appointment.IsAllDay = true; } appCollection.Add(appointment); } NSDateComponents startDateComponents = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); startDateComponents.Minute = 0; startDateComponents.Second = 0; // Minimum Height Appointments for (int i = 0; i < 5; i++) { startDateComponents.Hour = randomNumber.Next(9, 18); NSDate startDate = calendar.DateFromComponents(startDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = startDate; startDateComponents.Day = startDateComponents.Day + 1; appointment.Subject = (NSString)minTimeSubjectCollection[i]; appointment.AppointmentBackground = colorCollection[randomNumber.Next(0, 14)]; // Setting Mininmum Appointment Height for Schedule Appointments appointment.MinHeight = 25; appCollection.Add(appointment); } return appCollection; } private List<String> subjectCollection; private List<String> minTimeSubjectCollection; private List<UIColor> colorCollection; private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); // MinimumHeight Appointment Subjects minTimeSubjectCollection = new List<string>(); minTimeSubjectCollection.Add("Work log alert"); minTimeSubjectCollection.Add("Birthday wish alert"); minTimeSubjectCollection.Add("Task due date"); minTimeSubjectCollection.Add("Status mail"); minTimeSubjectCollection.Add("Start sprint alert"); } // adding colors collection private void SetColors() { colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0xF0, 0x96, 0x09)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); } } public static class TimeZoneCollection { public static IList<string> TimeZoneList { get; set; } = new List<string>() { "Default", "AUS Central Standard Time", "AUS Eastern Standard Time", "Afghanistan Standard Time", "Alaskan Standard Time", "Arab Standard Time", "Arabian Standard Time", "Arabic Standard Time", "Argentina Standard Time", "Atlantic Standard Time", "Azerbaijan Standard Time", "Azores Standard Time", "Bahia Standard Time", "Bangladesh Standard Time", "Belarus Standard Time", "Canada Central Standard Time", "Cape Verde Standard Time", "Caucasus Standard Time", "Cen. Australia Standard Time", "Central America Standard Time", "Central Asia Standard Time", "Central Brazilian Standard Time", "Central Europe Standard Time", "Central European Standard Time", "Central Pacific Standard Time", "Central Standard Time", "China Standard Time", "Dateline Standard Time", "E. Africa Standard Time", "E. Australia Standard Time", "E. South America Standard Time", "Eastern Standard Time", "Egypt Standard Time", "Ekaterinburg Standard Time", "FLE Standard Time", "Fiji Standard Time", "GMT Standard Time", "GTB Standard Time", "Georgian Standard Time", "Greenland Standard Time", "Greenwich Standard Time", "Hawaiian Standard Time", "India Standard Time", "Iran Standard Time", "Israel Standard Time", "Jordan Standard Time", "Kaliningrad Standard Time", "Korea Standard Time", "Libya Standard Time", "Line Islands Standard Time", "Magadan Standard Time", "Mauritius Standard Time", "Middle East Standard Time", "Montevideo Standard Time", "Morocco Standard Time", "Mountain Standard Time", "Mountain Standard Time (Mexico)", "Myanmar Standard Time", "N. Central Asia Standard Time", "Namibia Standard Time", "Nepal Standard Time", "New Zealand Standard Time", "Newfoundland Standard Time", "North Asia East Standard Time", "North Asia Standard Time", "Pacific SA Standard Time", "Pacific Standard Time", "Pacific Standard Time (Mexico)", "Pakistan Standard Time", "Paraguay Standard Time", "Romance Standard Time", "Russia Time Zone 10", "Russia Time Zone 11", "Russia Time Zone 3", "Russian Standard Time", "SA Eastern Standard Time", "SA Pacific Standard Time", "SA Western Standard Time", "SE Asia Standard Time", "Samoa Standard Time", "Singapore Standard Time", "South Africa Standard Time", "Sri Lanka Standard Time", "Syria Standard Time", "Taipei Standard Time", "Tasmania Standard Time", "Tokyo Standard Time", "Tonga Standard Time", "Turkey Standard Time", "US Eastern Standard Time", "US Mountain Standard Time", "UTC", "UTC+12", "UTC-02", "UTC-11", "Ulaanbaatar Standard Time", "Venezuela Standard Time", "Vladivostok Standard Time", "W. Australia Standard Time", "W. Central Africa Standard Time", "W. Europe Standard Time", "West Asia Standard Time", "West Pacific Standard Time", "Yakutsk Standard Time" }; } public class SchedulePickerModel : UIPickerViewModel { private readonly IList<string> values; public event EventHandler<SchedulePickerChangedEventArgs> PickerChanged; public SchedulePickerModel(IList<string> values) { this.values = values; } #if __UNIFIED__ public override nint GetComponentCount(UIPickerView picker) { return 1; } public override nint GetRowsInComponent(UIPickerView picker, nint component) { return values.Count; } public override string GetTitle(UIPickerView picker, nint row, nint component) { return values[(int)row]; } public override nfloat GetRowHeight(UIPickerView picker, nint component) { return 30f; } public override void Selected(UIPickerView picker, nint row, nint component) { if (this.PickerChanged != null) { this.PickerChanged(this, new SchedulePickerChangedEventArgs { SelectedValue = values[(int)row] }); } } #else public override int GetComponentCount(UIPickerView picker) { return 1; } public override int GetRowsInComponent(UIPickerView picker, int component) { return values.Count; } public override string GetTitle(UIPickerView picker, int row, int component) { return values[(int)row]; } public override nfloat GetRowHeight(UIPickerView picker, int component) { return 30f; } public override void Selected(UIPickerView picker, int row, int component) { if (this.PickerChanged != null) { this.PickerChanged(this, new SchedulePickerChangedEventArgs { SelectedValue = values[(int)row] }); } } #endif } public class SchedulePickerChangedEventArgs : EventArgs { public string SelectedValue { get; set; } } public class ScheduleTableSource : UITableViewSource { private string[] tableItems; private string cellIdentifier = "TableCell"; public ScheduleTableSource(string[] items) { tableItems = items; } public override nint RowsInSection(UITableView tableview, nint section) { int i = tableItems.Length; return (nint)i; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { switch (indexPath.Row) { case 0: ScheduleViews.Schedule.ScheduleView = SFScheduleView.SFScheduleViewDay; ScheduleViews.TableView.Hidden = true; break; case 1: ScheduleViews.Schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; ScheduleViews.TableView.Hidden = true; break; case 2: ScheduleViews.Schedule.ScheduleView = SFScheduleView.SFScheduleViewWorkWeek; ScheduleViews.TableView.Hidden = true; break; case 3: ScheduleViews.Schedule.ScheduleView = SFScheduleView.SFScheduleViewMonth; ScheduleViews.TableView.Hidden = true; break; } } public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath) { return 60.0f; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier); string item = tableItems[indexPath.Row]; if (cell == null) { cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier); } cell.TextLabel.Text = item; return cell; } } }<file_sep>/Forms/Chart/Chart/Samples/RangeColumnChart/RangeColumnSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class RangeColumnSeriesViewModel { public ObservableCollection<RangeSeriesBaseModel> RangeColumnData1 { get; set; } public ObservableCollection<RangeSeriesBaseModel> RangeColumnData2 { get; set; } public RangeColumnSeriesViewModel() { RangeColumnData1 = new ObservableCollection<RangeSeriesBaseModel> { new RangeSeriesBaseModel("Sun", 10.8, 3.1), new RangeSeriesBaseModel("Mon", 14.4, 5.7), new RangeSeriesBaseModel("Tue", 16.9, 8.4), new RangeSeriesBaseModel("Wed", 19.2, 10.6), new RangeSeriesBaseModel("Thu", 16.1, 8.5), new RangeSeriesBaseModel("Fri", 12.5, 6.0), new RangeSeriesBaseModel("Sat", 6.9, 1.5) }; RangeColumnData2 = new ObservableCollection<RangeSeriesBaseModel> { new RangeSeriesBaseModel("Sun", 9.8, 2.5), new RangeSeriesBaseModel("Mon", 11.4, 4.7), new RangeSeriesBaseModel("Tue", 14.4, 6.4), new RangeSeriesBaseModel("Wed", 17.2, 9.6), new RangeSeriesBaseModel("Thu", 15.1, 7.5), new RangeSeriesBaseModel("Fri", 10.5, 3.0), new RangeSeriesBaseModel("Sat", 7.9, 1.2) }; } } }<file_sep>/iOS/SampleBrowser/Samples/AutoComplete/ToleratingTypos_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Foundation; using Syncfusion.SfAutoComplete.iOS; using UIKit; namespace SampleBrowser { public class ToleratingTypos_Tablet : SampleView { UILabel headerlabel; SfAutoComplete countryAutoComplete; UILabel searchresults; NSMutableArray countryList = new NSMutableArray(); string[] tableItems; string[] imageItems; UITableView tableView; ToleratingTyposHelper helper; public ToleratingTypos_Tablet() { headerlabel = new UILabel(); headerlabel.Text = "Search by Countries"; headerlabel.TextColor = UIColor.Black; headerlabel.TextAlignment = UITextAlignment.Left; this.AddSubview(headerlabel); countryAutoComplete = new SfAutoComplete(); CountryCollection(); countryAutoComplete.Watermark = (NSString)"Search Here"; countryAutoComplete.MaxDropDownHeight = 100; countryAutoComplete.FilterItemChanged += CountryAutoComplete_FilterItemChanged; this.AddSubview(countryAutoComplete); List<string> items = new List<string>(); items.Add("India"); items.Add("Iran"); items.Add("Iraq"); items.Add("Indonesia"); countryAutoComplete.DataSource = items; countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeCustom; searchresults = new UILabel(); searchresults.Text = "Search Results"; searchresults.TextColor = UIColor.Gray; searchresults.TextAlignment = UITextAlignment.Left; this.AddSubview(searchresults); tableView = new UITableView(); tableItems = new string[] { "General", "Maps", "News", "Video", "Music", "Books", "Flight", "Quick Search" }; imageItems = new string[] { "all.png", "Maps1.png", "Newspaper.png", "Media.png", "Music.png", "Book.png", "Aeroplane.png", "Picture.png" }; ToleratingTypoTableView tableViewSource = new ToleratingTypoTableView(tableItems, imageItems); tableView.Source = tableViewSource; this.AddSubview(tableView); countryAutoComplete.SelectionChanged += (object sender, SelectionEventArgs e) => { if ((sender as SfAutoComplete).SelectedIndex != -1) { tableViewSource.initial = true; tableViewSource.random = new Random().Next(10000, 99999); tableView.ReloadData(); } if ((sender as SfAutoComplete).SelectedIndex == -1) { tableViewSource.initial = false; tableViewSource.random = 0; tableView.ReloadData(); } }; countryAutoComplete.TextChanged += (object sender, TextEventArgs e) => { tableViewSource.initial = false; tableViewSource.random = 0; tableView.ReloadData(); }; helper = new ToleratingTyposHelper(); } bool CountryAutoComplete_FilterItemChanged(object sender, FilterItemEventArgs e) { object value1 = e.Text; object value2 = e.Item; var string1 = value1.ToString().ToLower(); var string2 = value2.ToString().ToLower(); if (string1.Length > 0 && string2.Length > 0) if (string1[0] != string2[0]) return false; var originalString1 = string.Empty; var originalString2 = string.Empty; if (string1.Length < string2.Length) { originalString2 = string2.Remove(string1.Length); originalString1 = string1; } if (string2.Length < string1.Length) { return false; } if (string2.Length == string1.Length) { originalString1 = string1; originalString2 = string2; } bool IsMatchSoundex = helper.ProcessOnSoundexAlgorithmn(originalString1) == helper.ProcessOnSoundexAlgorithmn(originalString2); int Distance = helper.GetDamerauLevenshteinDistance(originalString1, originalString2); if (IsMatchSoundex || Distance <= 4) return true; else return false; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { headerlabel.Frame = new CGRect(10, 10, view.Frame.Width - 20, 30); countryAutoComplete.Frame = new CGRect(10, 40, view.Frame.Width - 20, 40); searchresults.Frame = new CGRect(10, 90, this.Frame.Width, 30); tableView.Frame = new CGRect(10, 130, this.Frame.Width - 20, this.Frame.Height - 160); } } private void CountryCollection() { countryList.Add((NSString)"Afghanistan"); countryList.Add((NSString)"Akrotiri"); countryList.Add((NSString)"Albania"); countryList.Add((NSString)"Algeria"); countryList.Add((NSString)"American Samoa"); countryList.Add((NSString)"Andorra"); countryList.Add((NSString)"Angola"); countryList.Add((NSString)"Anguilla"); countryList.Add((NSString)"Antarctica"); countryList.Add((NSString)"Antigua and Barbuda"); countryList.Add((NSString)"Argentina"); countryList.Add((NSString)"Armenia"); countryList.Add((NSString)"Aruba"); countryList.Add((NSString)"Ashmore and Cartier Islands"); countryList.Add((NSString)"Australia"); countryList.Add((NSString)"Austria"); countryList.Add((NSString)"Azerbaijan"); countryList.Add((NSString)"Bahamas, The"); countryList.Add((NSString)"Bahrain"); countryList.Add((NSString)"Bangladesh"); countryList.Add((NSString)"Barbados"); countryList.Add((NSString)"Bassas da India"); countryList.Add((NSString)"Belarus"); countryList.Add((NSString)"Belgium"); countryList.Add((NSString)"Belize"); countryList.Add((NSString)"Benin"); countryList.Add((NSString)"Bermuda"); countryList.Add((NSString)"Bhutan"); countryList.Add((NSString)"Bolivia"); countryList.Add((NSString)"Bosnia and Herzegovina"); countryList.Add((NSString)"Botswana"); countryList.Add((NSString)"Bouvet Island"); countryList.Add((NSString)"Brazil"); countryList.Add((NSString)"British Indian Ocean Territory"); countryList.Add((NSString)"British Virgin Islands"); countryList.Add((NSString)"Brunei"); countryList.Add((NSString)"Bulgaria"); countryList.Add((NSString)"Burkina Faso"); countryList.Add((NSString)"Burma"); countryList.Add((NSString)"Burundi"); countryList.Add((NSString)"Cambodia"); countryList.Add((NSString)"Cameroon"); countryList.Add((NSString)"Canada"); countryList.Add((NSString)"Cape Verde"); countryList.Add((NSString)"Cayman Islands"); countryList.Add((NSString)"Central African Republic"); countryList.Add((NSString)"Chad"); countryList.Add((NSString)"Chile"); countryList.Add((NSString)"China"); countryList.Add((NSString)"Christmas Island"); countryList.Add((NSString)"Clipperton Island"); countryList.Add((NSString)"Cocos (Keeling) Islands"); countryList.Add((NSString)"Colombia"); countryList.Add((NSString)"Comoros"); countryList.Add((NSString)"Congo"); countryList.Add((NSString)"Congo, Republic of the"); countryList.Add((NSString)"Cook Islands"); countryList.Add((NSString)"Coral Sea Islands"); countryList.Add((NSString)"Costa Rica"); countryList.Add((NSString)"Cote d'Ivoire"); countryList.Add((NSString)"Croatia"); countryList.Add((NSString)"Cuba"); countryList.Add((NSString)"Cyprus"); countryList.Add((NSString)"Czech Republic"); countryList.Add((NSString)"Denmark"); countryList.Add((NSString)"Dhekelia"); countryList.Add((NSString)"Djibouti"); countryList.Add((NSString)"Dominica"); countryList.Add((NSString)"Dominican Republic"); countryList.Add((NSString)"Ecuador"); countryList.Add((NSString)"Egypt"); countryList.Add((NSString)"El Salvador"); countryList.Add((NSString)"Equatorial Guinea"); countryList.Add((NSString)"Eritrea"); countryList.Add((NSString)"Estonia"); countryList.Add((NSString)"Ethiopia"); countryList.Add((NSString)"Europa Island"); countryList.Add((NSString)"Falkland Islands"); countryList.Add((NSString)"Faroe Islands"); countryList.Add((NSString)"Fiji"); countryList.Add((NSString)"Finland"); countryList.Add((NSString)"France"); countryList.Add((NSString)"French Guiana"); countryList.Add((NSString)"French Polynesia"); countryList.Add((NSString)"French Southern and Antarctic Lands"); countryList.Add((NSString)"Gabon"); countryList.Add((NSString)"Gambia, The"); countryList.Add((NSString)"Gaza Strip"); countryList.Add((NSString)"Georgia"); countryList.Add((NSString)"Germany"); countryList.Add((NSString)"Ghana"); countryList.Add((NSString)"Gibraltar"); countryList.Add((NSString)"Glorioso Islands"); countryList.Add((NSString)"Greece"); countryList.Add((NSString)"Greenland"); countryList.Add((NSString)"Grenada"); countryList.Add((NSString)"Guadeloupe"); countryList.Add((NSString)"Guam"); countryList.Add((NSString)"Guatemala"); countryList.Add((NSString)"Guernsey"); countryList.Add((NSString)"Guinea"); countryList.Add((NSString)"Guinea-Bissau"); countryList.Add((NSString)"Guyana"); countryList.Add((NSString)"Haiti"); countryList.Add((NSString)"Heard Island and McDonald Islands"); countryList.Add((NSString)"Holy See"); countryList.Add((NSString)"Honduras"); countryList.Add((NSString)"Hong Kong"); countryList.Add((NSString)"Hungary"); countryList.Add((NSString)"Iceland"); countryList.Add((NSString)"India"); countryList.Add((NSString)"Indonesia"); countryList.Add((NSString)"Iran"); countryList.Add((NSString)"Iraq"); countryList.Add((NSString)"Ireland"); countryList.Add((NSString)"Isle of Man"); countryList.Add((NSString)"Israel"); countryList.Add((NSString)"Italy"); countryList.Add((NSString)"Jamaica"); countryList.Add((NSString)"Jan Mayen"); countryList.Add((NSString)"Japan"); countryList.Add((NSString)"Jersey"); countryList.Add((NSString)"Jordan"); countryList.Add((NSString)"Juan de Nova Island"); countryList.Add((NSString)"Kazakhstan"); countryList.Add((NSString)"Kenya"); countryList.Add((NSString)"Kiribati"); countryList.Add((NSString)"Korea, North"); countryList.Add((NSString)"Korea, South"); countryList.Add((NSString)"Kuwait"); countryList.Add((NSString)"Kyrgyzstan"); countryList.Add((NSString)"Laos"); countryList.Add((NSString)"Latvia"); countryList.Add((NSString)"Lebanon"); countryList.Add((NSString)"Lesotho"); countryList.Add((NSString)"Liberia"); countryList.Add((NSString)"Libya"); countryList.Add((NSString)"Liechtenstein"); countryList.Add((NSString)"Lithuania"); countryList.Add((NSString)"Luxembourg"); countryList.Add((NSString)"Macau"); countryList.Add((NSString)"Macedonia"); countryList.Add((NSString)"Madagascar"); countryList.Add((NSString)"Malawi"); countryList.Add((NSString)"Malaysia"); countryList.Add((NSString)"Maldives"); countryList.Add((NSString)"Mali"); countryList.Add((NSString)"Malta"); countryList.Add((NSString)"Marshall Islands"); countryList.Add((NSString)"Martinique"); countryList.Add((NSString)"Mauritania"); countryList.Add((NSString)"Mauritius"); countryList.Add((NSString)"Mayotte"); countryList.Add((NSString)"Mexico"); countryList.Add((NSString)"Micronesia"); countryList.Add((NSString)"Moldova"); countryList.Add((NSString)"Monaco"); countryList.Add((NSString)"Mongolia"); countryList.Add((NSString)"Montserrat"); countryList.Add((NSString)"Morocco"); countryList.Add((NSString)"Mozambique"); countryList.Add((NSString)"Namibia"); countryList.Add((NSString)"Nauru"); countryList.Add((NSString)"Navassa Island"); countryList.Add((NSString)"Nepal"); countryList.Add((NSString)"Netherlands"); countryList.Add((NSString)"Netherlands Antilles"); countryList.Add((NSString)"New Caledonia"); countryList.Add((NSString)"New Zealand"); countryList.Add((NSString)"Nicaragua"); countryList.Add((NSString)"Niger"); countryList.Add((NSString)"Nigeria"); countryList.Add((NSString)"Niue"); countryList.Add((NSString)"Norfolk Island"); countryList.Add((NSString)"Northern Mariana Islands"); countryList.Add((NSString)"Norway"); countryList.Add((NSString)"Oman"); countryList.Add((NSString)"Pakistan"); countryList.Add((NSString)"Palau"); countryList.Add((NSString)"Panama"); countryList.Add((NSString)"Papua New Guinea"); countryList.Add((NSString)"Paracel Islands"); countryList.Add((NSString)"Paraguay"); countryList.Add((NSString)"Peru"); countryList.Add((NSString)"Philippines"); countryList.Add((NSString)"Pitcairn Islands"); countryList.Add((NSString)"Poland"); countryList.Add((NSString)"Portugal"); countryList.Add((NSString)"Puerto Rico"); countryList.Add((NSString)"Qatar"); countryList.Add((NSString)"Reunion"); countryList.Add((NSString)"Romania"); countryList.Add((NSString)"Russia"); countryList.Add((NSString)"Rwanda"); countryList.Add((NSString)"Saint Helena"); countryList.Add((NSString)"Saint Kitts and Nevis"); countryList.Add((NSString)"Saint Lucia"); countryList.Add((NSString)"Saint Pierre and Miquelon"); countryList.Add((NSString)"Saint Vincent"); countryList.Add((NSString)"Samoa"); countryList.Add((NSString)"San Marino"); countryList.Add((NSString)"Sao Tome and Principe"); countryList.Add((NSString)"Saudi Arabia"); countryList.Add((NSString)"Senegal"); countryList.Add((NSString)"Serbia and Montenegro"); countryList.Add((NSString)"Seychelles"); countryList.Add((NSString)"Sierra Leone"); countryList.Add((NSString)"Singapore"); countryList.Add((NSString)"Slovakia"); countryList.Add((NSString)"Slovenia"); countryList.Add((NSString)"Solomon Islands"); countryList.Add((NSString)"Somalia"); countryList.Add((NSString)"South Africa"); countryList.Add((NSString)"South Georgia"); countryList.Add((NSString)"Spain"); countryList.Add((NSString)"Spratly Islands"); countryList.Add((NSString)"Sri Lanka"); countryList.Add((NSString)"Sudan"); countryList.Add((NSString)"Suriname"); countryList.Add((NSString)"Svalbard"); countryList.Add((NSString)"Swaziland"); countryList.Add((NSString)"Sweden"); countryList.Add((NSString)"Switzerland"); countryList.Add((NSString)"Syria"); countryList.Add((NSString)"Taiwan"); countryList.Add((NSString)"Tajikistan"); countryList.Add((NSString)"Tanzania"); countryList.Add((NSString)"Thailand"); countryList.Add((NSString)"Timor-Leste"); countryList.Add((NSString)"Togo"); countryList.Add((NSString)"Tokelau"); countryList.Add((NSString)"Tonga"); countryList.Add((NSString)"Trinidad and Tobago"); countryList.Add((NSString)"Tromelin Island"); countryList.Add((NSString)"Tunisia"); countryList.Add((NSString)"Turkey"); countryList.Add((NSString)"Turkmenistan"); countryList.Add((NSString)"Turks and Caicos Islands"); countryList.Add((NSString)"Tuvalu"); countryList.Add((NSString)"Uganda"); countryList.Add((NSString)"Ukraine"); countryList.Add((NSString)"United Arab Emirates"); countryList.Add((NSString)"United Kingdom"); countryList.Add((NSString)"United States"); countryList.Add((NSString)"Uruguay"); countryList.Add((NSString)"Uzbekistan"); countryList.Add((NSString)"Vanuatu"); countryList.Add((NSString)"Venezuela"); countryList.Add((NSString)"Vietnam"); countryList.Add((NSString)"Virgin Islands"); countryList.Add((NSString)"Wake Island"); countryList.Add((NSString)"Wallis and Futuna"); countryList.Add((NSString)"West Bank"); countryList.Add((NSString)"Western Sahara"); countryList.Add((NSString)"Yemen"); countryList.Add((NSString)"Zambia"); countryList.Add((NSString)"Zimbabwe"); } } } <file_sep>/Android/SampleBrowser/Samples/Presentation/Slides.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Xml; namespace SampleBrowser { public partial class SlidesPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to create a slide with predefined layouts, like Microsoft PowerPoint."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Presentation"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Slides.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); #region Slide1 ISlide slide1 = presentation.Slides[0]; IShape shape1 = slide1.Shapes[0] as IShape; shape1.Left = 108; shape1.Top = 139.68; shape1.Width = 743.04; shape1.Height = 144; ITextBody textFrame1 = shape1.TextBody; IParagraphs paragraphs1 = textFrame1.Paragraphs; IParagraph paragraph1 = paragraphs1.Add(); paragraphs1[0].IndentLevelNumber = 0; AddParagraphData(paragraph1, "ESSENTIAL PRESENTATION", "Calibri", 48, true); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center; slide1.Shapes.RemoveAt(1); #endregion #region Slide2 ISlide slide2 = presentation.Slides.Add(SlideLayoutType.SectionHeader); shape1 = slide2.Shapes[0] as IShape; shape1.Left = 55; shape1.Top = 23; shape1.Width = 573; shape1.Height = 71; textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe paragraphs1 = textFrame1.Paragraphs; paragraph1 = paragraphs1.Add(); AddParagraphData(paragraph1, "Slide with simple text", "Calibri", 40, false); paragraphs1[0].HorizontalAlignment = HorizontalAlignmentType.Left; IShape shape2 = slide2.Shapes[1] as IShape; shape2.Left = 87; shape2.Top = 119; shape2.Width = 725; shape2.Height = 355; ITextBody textFrame2 = shape2.TextBody; //Instance to hold paragraphs in textframe IParagraphs paragraphs2 = textFrame2.Paragraphs; //Add paragrpah text IParagraph paragraph_1 = paragraphs2.Add(); AddParagraphData(paragraph_1, "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.", "Calibri", 15, false); IParagraph paragraph_2 = paragraphs2.Add(); AddParagraphData(paragraph_2, "In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group.", "Calibri", 15, false); #endregion #region Slide3 slide2 = presentation.Slides.Add(SlideLayoutType.TwoContent); shape1 = slide2.Shapes[0] as IShape; shape1.Left = 26; shape1.Top = 37; shape1.Width = 815; shape1.Height = 76; //Adds textframe in shape textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe paragraphs1 = textFrame1.Paragraphs; paragraphs1.Add(); paragraph1 = paragraphs1[0]; AddParagraphData(paragraph1, "Slide with Image", "Calibri", 44, false); //Adds shape in slide shape2 = slide2.Shapes[1] as IShape; shape2.Left = 578; shape2.Top = 141; shape2.Width = 316; shape2.Height = 326; textFrame2 = shape2.TextBody; //Instance to hold paragraphs in textframe paragraphs2 = textFrame2.Paragraphs; IParagraph paragraph2 = paragraphs2.Add(); AddParagraphData(paragraph2, "The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases.", "Calibri", 16, false); IParagraph paragraph3 = paragraphs2.Add(); AddParagraphData(paragraph3, "Using Northwind, you can become familiar with how a relational database is structured and how the database objects work together to help you enter, store, manipulate, and print your data.", "Calibri", 16, false); IParagraph paragraph4 = paragraphs2.Add(); // AddParagraphData(paragraph4, ref textpart1, "While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.", "Calibri", 16); IShape shape3 = (IShape)slide2.Shapes[2]; slide2.Shapes.RemoveAt(2); //Adds picture in the shape resourcePath = "SampleBrowser.Samples.Presentation.Templates.tablet.jpg"; assembly = Assembly.GetExecutingAssembly(); fileStream = assembly.GetManifestResourceStream(resourcePath); IPicture picture1 = slide2.Shapes.AddPicture(fileStream, 58, 141, 477, 318); fileStream.Close(); #endregion #region Slide4 ISlide slide4 = presentation.Slides.Add(SlideLayoutType.TwoContent); shape1 = slide4.Shapes[0] as IShape; shape1.Left = 37; shape1.Top = 24; shape1.Width = 815; shape1.Height = 76; textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe paragraphs1 = textFrame1.Paragraphs; paragraphs1.Add(); paragraph1 = paragraphs1[0]; AddParagraphData(paragraph1, "Slide with Table", "Calibri", 44, false); shape2 = slide4.Shapes[1] as IShape; slide4.Shapes.Remove(shape2); ITable table = (ITable)slide4.Shapes.AddTable(6, 6, 58, 154, 823, 273); table.Rows[0].Height = 61.2; table.Rows[1].Height = 30; table.Rows[2].Height = 61; table.Rows[3].Height = 61; table.Rows[4].Height = 61; table.Rows[5].Height = 61; table.HasBandedRows = true; table.HasHeaderRow = true; table.HasBandedColumns = false; table.BuiltInStyle = BuiltInTableStyle.MediumStyle2Accent1; ICell cell1 = table.Rows[0].Cells[0]; textFrame2 = cell1.TextBody; paragraph2 = textFrame2.Paragraphs.Add(); paragraph2.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart2 = paragraph2.AddTextPart(); textPart2.Text = "ID"; ICell cell2 = table.Rows[0].Cells[1]; ITextBody textFrame3 = cell2.TextBody; paragraph3 = textFrame3.Paragraphs.Add(); paragraph3.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart3 = paragraph3.AddTextPart(); textPart3.Text = "Company Name"; ICell cell3 = table.Rows[0].Cells[2]; ITextBody textFrame4 = cell3.TextBody; paragraph4 = textFrame4.Paragraphs.Add(); paragraph4.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart4 = paragraph4.AddTextPart(); textPart4.Text = "Contact Name"; ICell cell4 = table.Rows[0].Cells[3]; ITextBody textFrame5 = cell4.TextBody; IParagraph paragraph5 = textFrame5.Paragraphs.Add(); paragraph5.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart5 = paragraph5.AddTextPart(); textPart5.Text = "Address"; ICell cell5 = table.Rows[0].Cells[4]; ITextBody textFrame6 = cell5.TextBody; IParagraph paragraph6 = textFrame6.Paragraphs.Add(); paragraph6.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart6 = paragraph6.AddTextPart(); textPart6.Text = "City"; ICell cell6 = table.Rows[0].Cells[5]; ITextBody textFrame7 = cell6.TextBody; IParagraph paragraph7 = textFrame7.Paragraphs.Add(); paragraph7.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart7 = paragraph7.AddTextPart(); textPart7.Text = "Country"; //Add data in table AddTableData(cell1, table, textFrame1, paragraph1); slide4.Shapes.RemoveAt(1); #endregion MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("Charts.pptx", "application/powerpoint", stream, m_context); } } void AddTableData(ICell cell1, ITable table, ITextBody textFrame1, IParagraph paragraph1) { Dictionary<string, Dictionary<string, string>> products = LoadXMLData(); int count = 0; for (int i = 1; i <= 5; i++) { for (int j = 0; j <= 5; j++) { cell1 = table.Rows[i].Cells[j]; textFrame1 = cell1.TextBody; paragraph1 = textFrame1.Paragraphs.Add(); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textpart1 = paragraph1.AddTextPart(); textpart1.Text = products.Values.ToList()[0].Values.ToList()[count]; count++; } } } void AddParagraphData(IParagraph paragraph, string text, string fontname, int fontsize, bool isBolt) { ITextPart textpart = paragraph.AddTextPart(); paragraph.HorizontalAlignment = HorizontalAlignmentType.Left; textpart.Text = text; textpart.Font.FontName = fontname; textpart.Font.FontSize = fontsize; textpart.Font.Color = ColorObject.Black; textpart.Font.Bold = isBolt; } private Dictionary<string, Dictionary<string, string>> LoadXMLData() { Dictionary<string, Dictionary<string, string>> Products = new Dictionary<string, Dictionary<string, string>>(); Assembly assembly = Assembly.GetExecutingAssembly(); Stream productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.Presentation.Templates.SlideTableData.xml"); XmlReader reader = XmlReader.Create(productXMLStream); string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; string cell; while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Products": Dictionary<string, string> Cell_Value = new Dictionary<string, string>(); while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Product": while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Cell": while (reader.Read()) { cell = reader.Name; if (reader.IsStartElement()) { cell = reader.Name; while (reader.Read()) { if (reader.IsStartElement()) { if (reader.Name == "Value") { reader.Read(); reader.MoveToContent(); Cell_Value.Add(cell, reader.Value); } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == cell) { break; } } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Cell") { break; } } break; case "ProductName": reader.Read(); reader.MoveToContent(); productName = reader.Value; break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Product") { break; } } break; } Products.Add(productName, Cell_Value); Cell_Value = new Dictionary<string, string>(); } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Products") break; } break; } } } return Products; } } } <file_sep>/Android/SampleBrowser/Samples/SegmentedView/SegementViewViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using Android.Graphics; using Syncfusion.Android.Buttons; namespace SampleBrowser { public class SegementViewViewModel { internal ObservableCollection<SfSegmentItem> SizeCollection; internal ObservableCollection<SfSegmentItem> EntertainCollection = new ObservableCollection<SfSegmentItem>(); internal ObservableCollection<string> ClothTypeCollection = new ObservableCollection<string>(); internal ObservableCollection<SfSegmentItem> PrimaryColors = new ObservableCollection<SfSegmentItem>(); public SegementViewViewModel(Android.Content.Context con) { ClothTypeCollection.Add("Formals"); ClothTypeCollection.Add("Casuals"); ClothTypeCollection.Add("Trendy"); Typeface tf = Typeface.CreateFromAsset(con.Assets, "Segmented.ttf"); Typeface colorfontFamily = Typeface.CreateFromAsset(con.Assets, "SegmentIcon.ttf"); SizeCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "A", Text="XS", FontIconTypeface = tf,FontColor=Color.ParseColor("#3F3F3F")}, new SfSegmentItem(){IconFont = "A", Text="S",FontColor=Color.ParseColor("#3F3F3F")}, new SfSegmentItem(){IconFont = "A", Text="M",FontColor=Color.ParseColor("#3F3F3F")}, new SfSegmentItem(){IconFont = "A", Text="L",FontColor=Color.ParseColor("#3F3F3F")}, new SfSegmentItem(){IconFont = "A", Text="XL",FontColor=Color.ParseColor("#3F3F3F")}, }; EntertainCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "A", FontIconFontColor=Color.ParseColor("#233a7e"), FontIconTypeface = tf}, new SfSegmentItem(){IconFont = "A", FontIconFontColor=Color.ParseColor("#7e8188"), FontIconTypeface = tf}, new SfSegmentItem(){IconFont = "A", FontIconFontColor=Color.ParseColor("#292639"), FontIconTypeface = tf}, new SfSegmentItem(){IconFont = "A", FontIconFontColor=Color.ParseColor("#11756d"), FontIconTypeface = tf}, new SfSegmentItem(){IconFont = "A", FontIconFontColor=Color.ParseColor("#6e0022"), FontIconTypeface = tf}, }; PrimaryColors = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "7", FontIconFontColor=Color.ParseColor("#32318E"), Text="Square",FontIconFontSize=32, FontIconTypeface = colorfontFamily}, new SfSegmentItem(){IconFont = "7", FontIconFontColor=Color.ParseColor("#2F7DC0"), Text="Square",FontIconFontSize=32, FontIconTypeface = colorfontFamily}, new SfSegmentItem(){IconFont = "7", FontIconFontColor=Color.ParseColor("#953376"), Text="Square",FontIconFontSize=32, FontIconTypeface = colorfontFamily}, new SfSegmentItem(){IconFont = "7", FontIconFontColor=Color.ParseColor("#B33F3F"), Text="Square",FontIconFontSize=32, FontIconTypeface = colorfontFamily}, new SfSegmentItem(){IconFont = "7", FontIconFontColor=Color.ParseColor("#F1973F"), Text="Square",FontIconFontSize=32, FontIconTypeface = colorfontFamily}, new SfSegmentItem(){IconFont = "7", FontIconFontColor=Color.ParseColor("#C9D656"), Text="Square",FontIconFontSize=32, FontIconTypeface = colorfontFamily}, new SfSegmentItem(){IconFont = "7", FontIconFontColor=Color.ParseColor("#008D7F"), Text="Square",FontIconFontSize=32, FontIconTypeface = colorfontFamily}, }; } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Axis/AutoScrolling.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Java.Util; using System; using System.Threading.Tasks; using System.Collections.ObjectModel; namespace SampleBrowser { public class AutoScrolling : SamplePage { private readonly ObservableCollection<DataPoint> data = new ObservableCollection<DataPoint>(); private int count; private System.Random random; private SfChart chart; public override View GetSampleContent(Context context) { random = new System.Random(); LoadData(); chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.PrimaryAxis = new DateTimeAxis { AutoScrollingDelta = 5, AutoScrollingDeltaType = DateTimeDeltaType.Seconds }; chart.PrimaryAxis.LabelStyle.LabelFormat = "HH:mm:ss"; var axis = new NumericalAxis {Minimum = 0, Maximum = 100}; chart.SecondaryAxis = axis; var columnSeries = new ColumnSeries { ItemsSource = data }; columnSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; columnSeries.XBindingPath = "Date"; columnSeries.YBindingPath = "YValue"; chart.Series.Add(columnSeries); chart.Behaviors.Add(new ChartZoomPanBehavior {ScrollingEnabled = true, ZoomingEnabled = false}); UpdateData(); var label = new TextView(context); label.SetPadding(5, 5, 5, 5); label.Text = "In this demo, a data point is being added every 500 milliseconds." + " The Chart is then automatically scrolled to display the fixed range of data points at the end." + " You can also pan to view previous data points. In this sample the delta value is 5 seconds."; var layout = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Vertical }; var layoutLabel = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Horizontal, LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent) }; layoutLabel.SetHorizontalGravity(GravityFlags.CenterHorizontal); layoutLabel.AddView(label); layout.AddView(layoutLabel); layout.AddView(chart); return layout; } DateTime dateTime = DateTime.Now; private void LoadData() { for (var i = 0; i < 2; i++) { data.Add(new DataPoint(dateTime, random.Next(0, 100))); dateTime = dateTime.AddMilliseconds(500); count++; } count = data.Count; } private async void UpdateData() { while (true) { await Task.Delay(500); data.Add(new DataPoint(dateTime, random.Next(0, 100))); dateTime = dateTime.AddMilliseconds(500); count++; } } public override void OnApplyChanges() { base.OnApplyChanges(); } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/UnboundColumn.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using System.Globalization; using System.Linq; using Android.Content; using Android.Content.Res; using Syncfusion.GridCommon.ScrollAxis; using System.Collections.ObjectModel; using Syncfusion.SfDataGrid; namespace SampleBrowser { public class UnboundColumn : SamplePage { SfDataGrid sfGrid; SalesInfoViewModel viewModel; public override Android.Views.View GetSampleContent(Android.Content.Context context) { LinearLayout linear = new LinearLayout(context); linear.Orientation = Android.Widget.Orientation.Vertical; sfGrid = new SfDataGrid(context); sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; sfGrid.SelectionMode = SelectionMode.Multiple; viewModel = new SalesInfoViewModel(); sfGrid.AutoGenerateColumns = false; sfGrid.ItemsSource = viewModel.DailySalesDetails; sfGrid.AllowResizingColumn = true; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; sfGrid.CellRenderers.Remove("Unbound"); sfGrid.CellRenderers.Add("Unbound", new UnboundColumnRenderer()); sfGrid.Alpha = 0.87f; sfGrid.SelectedIndex = 3; sfGrid.GridStyle = new UnboundRowstyle(); sfGrid.ColumnSizer = ColumnSizer.Star; sfGrid.UnboundRows.Add(new GridUnboundRow() {Position = UnboundRowsPosition.FixedBottom }); sfGrid.QueryUnboundRow += SfGrid_QueryUnboundRow; sfGrid.QueryRowHeight += SfGrid_QueryRowHeight; sfGrid.SelectionChanged += SfGrid_SelectionChanged; if(MainActivity.IsTablet) { this.sfGrid.UnboundRows.Insert(0, new GridUnboundRow() { Position = UnboundRowsPosition.FixedTop }); this.sfGrid.UnboundRows.Insert(0, new GridUnboundRow() { Position = UnboundRowsPosition.Top }); } GridTextColumn EmployeeName = new GridTextColumn(); EmployeeName.HeaderText = "Employee"; EmployeeName.TextAlignment = GravityFlags.CenterVertical | GravityFlags.Left; EmployeeName.HeaderTextAlignment = GravityFlags.CenterVertical | GravityFlags.Left; EmployeeName.HeaderCellTextSize = 12; EmployeeName.MappingName = "Name"; EmployeeName.LoadUIView = true; sfGrid.Columns.Add(EmployeeName); GridTextColumn QS1 = new GridTextColumn(); QS1.LoadUIView = true; QS1.HeaderText = "2015"; QS1.Format = "C"; QS1.LineBreakMode = LineBreakMode.NoWrap; QS1.HeaderTextAlignment = GravityFlags.CenterVertical | GravityFlags.Left; QS1.HeaderCellTextSize = 12; QS1.TextAlignment = GravityFlags.CenterVertical | GravityFlags.Right; QS1.MappingName = "QS1"; if (MainActivity.IsTablet) { sfGrid.Columns.Add(QS1); } GridTextColumn QS2 = new GridTextColumn(); QS2.LoadUIView = true; QS2.HeaderText = "2016"; QS2.Format = "C"; QS2.LineBreakMode = LineBreakMode.NoWrap; QS2.HeaderTextAlignment = GravityFlags.CenterVertical | GravityFlags.Left; QS2.HeaderCellTextSize = 12; QS2.TextAlignment = GravityFlags.CenterVertical | GravityFlags.Right; QS2.MappingName = "QS2"; sfGrid.Columns.Add(QS2); GridTextColumn QS3 = new GridTextColumn(); QS3.LoadUIView = true; QS3.HeaderText = "2017"; QS3.Format = "C"; QS3.LineBreakMode = LineBreakMode.NoWrap; QS3.HeaderTextAlignment = GravityFlags.CenterVertical | GravityFlags.Left; QS3.HeaderCellTextSize = 12; QS3.TextAlignment = GravityFlags.CenterVertical | GravityFlags.Right; QS3.MappingName = "QS3"; sfGrid.Columns.Add(QS3); GridUnboundColumn Total = new GridUnboundColumn(); Total.TextAlignment = GravityFlags.Right | GravityFlags.CenterVertical; if (MainActivity.IsTablet) { Total.Expression = "(QS1 + QS2 + QS3 )"; } else { Total.Expression = "(QS2 + QS3)"; } Total.Format = "C"; Total.LineBreakMode = LineBreakMode.NoWrap; Total.HeaderText = "Total"; Total.HeaderTextAlignment = GravityFlags.Left | GravityFlags.CenterVertical; Total.HeaderCellTextSize = 12; Total.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); Total.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); Total.TextAlignment = GravityFlags.Center; Total.MappingName = "Total"; Total.LoadUIView = true; sfGrid.Columns.Add(Total); linear.AddView(sfGrid); return linear; } private void SfGrid_SelectionChanged(object sender, GridSelectionChangedEventArgs e) { this.sfGrid.InvalidateUnboundRow(this.sfGrid.UnboundRows[this.sfGrid.UnboundRows.Count - 1]); } private void SfGrid_QueryRowHeight(object sender, QueryRowHeightEventArgs e) { e.Height = 60 * Resources.System.DisplayMetrics.Density; if (this.sfGrid.IsUnboundRow(e.RowIndex)) { e.Height = 70 * Resources.System.DisplayMetrics.Density; } e.Handled = true; } private void SfGrid_QueryUnboundRow(object sender, GridUnboundRowEventArgs e) { if (e.GridUnboundRow != null) { if (e.UnboundAction == UnboundActions.QueryData) { if (e.GridUnboundRow.Position == UnboundRowsPosition.FixedTop) { double sum = 0; if (e.RowColumnIndex.ColumnIndex == 0) { e.Value = "Total sales by year"; } else if (e.RowColumnIndex.ColumnIndex == 1) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS1; e.Value = sum; } } else if (e.RowColumnIndex.ColumnIndex == 2) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS2; e.Value = sum; } } else if (e.RowColumnIndex.ColumnIndex == 3) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS3; e.Value = sum; } } else if (e.RowColumnIndex.ColumnIndex == 4) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS1 + this.viewModel.DailySalesDetails[i].QS2 + this.viewModel.DailySalesDetails[i].QS3; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } } else if (e.GridUnboundRow.Position == UnboundRowsPosition.Top) { double sum = 0; if (e.RowColumnIndex.ColumnIndex == 0) { e.Value = "Average by year"; } else if (e.RowColumnIndex.ColumnIndex == 1) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS1; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } else if (e.RowColumnIndex.ColumnIndex == 2) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS2; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } else if (e.RowColumnIndex.ColumnIndex == 3) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS3; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } else if (e.RowColumnIndex.ColumnIndex == 4) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS1 + this.viewModel.DailySalesDetails[i].QS2 + this.viewModel.DailySalesDetails[i].QS3; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } } else if (e.GridUnboundRow.Position == UnboundRowsPosition.FixedBottom) { double sum = 0; if (e.RowColumnIndex.ColumnIndex == 0) { e.Value = "Sum of selection"; } else if (e.RowColumnIndex.ColumnIndex == 1) { if (this.sfGrid.SelectedItems.Count > 0) { for (int i = 0; i < this.sfGrid.SelectedItems.Count; i++) { e.Value = sum += this.sfGrid.SelectedItems[i] != null ? (this.sfGrid.SelectedItems[i] as SalesByDate).QS2 : 0; } } else { e.Value = null; } } else if (e.RowColumnIndex.ColumnIndex == 2) { if (this.sfGrid.SelectedItems.Count > 0) { for (int i = 0; i < this.sfGrid.SelectedItems.Count; i++) { e.Value = sum += this.sfGrid.SelectedItems[i] != null ? (this.sfGrid.SelectedItems[i] as SalesByDate).QS3 : 0; } } else { e.Value = null; } } else if (e.RowColumnIndex.ColumnIndex == 3) { if (this.sfGrid.SelectedItems.Count > 0) { for (int i = 0; i < this.sfGrid.SelectedItems.Count; i++) { if(MainActivity.IsTablet) { e.Value = sum += this.sfGrid.SelectedItems[i] != null ? (this.sfGrid.SelectedItems[i] as SalesByDate).QS1 + (this.sfGrid.SelectedItems[i] as SalesByDate).QS2 + (this.sfGrid.SelectedItems[i] as SalesByDate).QS3 : 0; } else { e.Value = sum += this.sfGrid.SelectedItems[i] != null ? (this.sfGrid.SelectedItems[i] as SalesByDate).QS2 + (this.sfGrid.SelectedItems[i] as SalesByDate).QS3 : 0; } } } else { e.Value = null; } } } e.Handled = true; } } } public override void OnApplyChanges() { base.OnApplyChanges(); } public override void Destroy() { sfGrid.Dispose(); sfGrid = null; viewModel = null; } } public class UnboundColumnRenderer: GridUnboundCellTextBoxRenderer { public UnboundColumnRenderer() { } public override void OnInitializeDisplayView(DataColumnBase dataColumn, TextView view) { base.OnInitializeDisplayView(dataColumn, view); view.SetBackgroundColor(Color.Rgb(225, 245, 254)); } protected override void OnLayout(RowColumnIndex rowColumnIndex, View view, int left, int top, int right, int bottom) { base.OnLayout(rowColumnIndex, view, left, top, right, bottom); view.SetPadding((int)(0.5 *Resources.System.DisplayMetrics.Density), (int)(0.5 * Resources.System.DisplayMetrics.Density), (int)(0.5 * Resources.System.DisplayMetrics.Density), (int)(0.5 * Resources.System.DisplayMetrics.Density)); } } public class UnboundRowstyle : DefaultStyle { public UnboundRowstyle() { } public override Color GetUnboundRowBackgroundColor() { return Color.Rgb(225, 245, 254); } } } <file_sep>/Forms/Chat/Chat/Samples/LoadMore/LoadMore.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.Chat; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfChat { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class LoadMore : SampleView { private LoadMoreViewModel loadMoreViewModel; public LoadMore() { InitializeComponent(); } public override void OnDisappearing() { base.OnDisappearing(); loadMoreViewModel = this.LoadMoreView.BindingContext as LoadMoreViewModel; loadMoreViewModel.IsDisposed = true; loadMoreViewModel.AuthorsCollection.Clear(); loadMoreViewModel.AuthorMessageDataBase.Clear(); loadMoreViewModel.Messages.Clear(); this.Behaviors.Clear(); LoadMoreView.Dispose(); } } }<file_sep>/Forms/Schedule/Schedule/Samples/ViewCustomization/Behaviors/MonthCellDateBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Month Cell Date Behavior class /// </summary> public class MonthCellDateBehavior : Behavior<Label> { /// <summary> /// bindable /// </summary> /// <param name="bindable"></param> protected override void OnAttachedTo(Label bindable) { base.OnAttachedTo(bindable); if (CustomizationViewModel.MonthCellItem == null) { return; } if (CustomizationViewModel.MonthCellItem.IsLeadingDay || CustomizationViewModel.MonthCellItem.IsTrailingDay) { bindable.TextColor = Color.Gray; } else { bindable.TextColor = Color.Black; } } } }<file_sep>/Forms/ComboBox/ComboBox/Samples/TimeComboBox/TimeComboBox.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using SampleBrowser.Core; using System.Linq; using Xamarin.Forms; using System.Globalization; using System.Text; using System.Threading.Tasks; namespace SampleBrowser.SfComboBox { public partial class TimeComboBox : SampleView, INotifyPropertyChanged { public TimeComboBox() { InitializeComponent(); Source = new ViewModelComboBox().GetCountryDetails(); Source1 = new ViewModelComboBox().GetColor(); this.BindingContext = this; comboBox.SelectedItem = Source[0]; comboBox1.SelectedItem = Source1[1]; } public ObservableCollection<ModelComboBox> Source { get; set; } public ObservableCollection<ModelComboBox> Source1 { get; set; } public ModelComboBox selectedItem; public ModelComboBox SelectedItem { get { return selectedItem; } set { selectedItem = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem")); } } } public ModelComboBox selectedItem1; public ModelComboBox SelectedItem1 { get { return selectedItem1; } set { selectedItem1 = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem1")); } } } public new event PropertyChangedEventHandler PropertyChanged; } public class ViewModelComboBox { List<Color> Colors = new List<Color>(); public string countryTime; //public int UTC; public ViewModelComboBox() { Colors.Add(Color.LightGray); Colors.Add(Color.SkyBlue); Colors.Add(Color.Green); Colors.Add(Color.RosyBrown); Colors.Add(Color.Lime); Colors.Add(Color.Pink); Colors.Add(Color.Gold); Colors.Add(Color.BlueViolet); Colors.Add(Color.LawnGreen); Colors.Add(Color.Violet); Colors.Add(Color.Tomato); Colors.Add(Color.Orange); Colors.Add(Color.MediumVioletRed); Colors.Add(Color.Plum); Colors.Add(Color.Purple); Colors.Add(Color.CornflowerBlue); Colors.Add(Color.RosyBrown); Colors.Add(Color.RoyalBlue); Colors.Add(Color.OrangeRed); Colors.Add(Color.Orchid); Colors.Add(Color.ForestGreen); Colors.Add(Color.Gray); Colors.Add(Color.Red); Colors.Add(Color.Brown); Colors.Add(Color.Purple); Colors.Add(Color.CornflowerBlue); Colors.Add(Color.GreenYellow); Colors.Add(Color.RoyalBlue); Colors.Add(Color.OrangeRed); Colors.Add(Color.Orchid); Colors.Add(Color.ForestGreen); Colors.Add(Color.Gray); Colors.Add(Color.DeepPink); Colors.Add(Color.Brown); } public ObservableCollection<ModelComboBox> GetCountryDetails() { ObservableCollection<ModelComboBox> countryDetails = new ObservableCollection<ModelComboBox>(); for (int i = 0; i < country.Count(); i++) { var details = new ModelComboBox() { Country = country[i], CountryUTC = countryUTC[i], Time = time[i], }; countryDetails.Add(details); } return countryDetails; } public ObservableCollection<ModelComboBox> GetColor() { ObservableCollection<ModelComboBox> color = new ObservableCollection<ModelComboBox>(); string space = " "; for (int i = 0; i < 15; i++) { space += space; var details = new ModelComboBox() { Color = Colors[i], Country = space, }; color.Add(details); } return color; } string[] country = new string[] { "International Date Line West", "Coordinated Universal Time-11", "Aleutian Islands", "Hawaii", "Marquesas Islands", "Alaska", "Coordinated Universal Time-09", "Baja California", "Coordinated Universal Time-08", "PacificTime(US & Canada)", "Arizona", "Chihuahua,La Paz, Mazatlan", "Mountain Time (Us & Canada)", "Centeral America", "Centera Time (US & Canada)", "Easter Island", "Guadalajara, Mexico City,Monterrey", "Saskatchewan", "Bogota,Lima,Quito,Rio Branco", "Chetumal", "Eastern Time (US & Canada)", "Haiti", "Havana", "Indiana (East)", "Asuncion", "Atlantic Time (Canada)", "Caracas", "Cuiaba", "Georgetown,LaPaz, Manaus, San Juan", "Santiago", "Turks and Caicos", "Newfoundland", "Araguaina", "Brasilia", "Cayenne, Fortaleza", "City of Buenos Aires", "GreenLand", "Montevideo", "Punta Arenas", "Saint Pierre and Miquelon", "Salvador", "Coordinated Universal Time-02", "Azores", "Cabo Verde Is", "Coordinated Universal Time", "Casablanca", "Dublin, Edinburgh, Lisbon, London", "<NAME>", "Asterdam, Berlin, Rome", "Belgrade, Prague", "Brussels, Madrid, Paris", "Sarajevo, Zagreb", "West Central Africa", "Windhoek", "Amman", "Athens, Bucharest", "Beirut", "Cairo", "Chisinau", "Damascus", "Gaza, Hebron", "<NAME>", "Helsinki, Riga, Sofia", "Jerusalem", "Kaliningrad", "Tripoli", "Baghdad", "Istanbul", "Kuwait", "Minsk", "Moscow", "Nairobi", "Tehran", "<NAME>", "Astrakhan, Ulyanovsk", "Baku", "Samara", "Port Louis", "Saratov", "Tbilisi", "Yerevan", "Kabul", "Ashgabat,Tashkent", "Ekaterinburg", "Karachi, Islamabad", "Chennai, Kolkata, Mumbai, New Delhi", "<NAME>ura", "Kathmandu", "Astana", "Dhaka", "Omsk", "Yagon (Rangoon)", "Bangkok, Hanoi, Jakarata", "Barnaul, Gorno-Altaysk", "Hovd", "Krasnoyarsk", "Novosibirsk", "Tomsk", "Beijing, HongKong", "Irkutsk", "kuala Lumpur, Singapore", "Perth", "Taipei", "Ulaanbaatar", "Pyongyang", "Eucla", "Chita", "Osaka, Tokyo", "Seoul", "Yakutsk", "Adelaide", "Darwin", "Brisbane", "Melbourne,Sydney", "Guam, Port Moresby", "HoBart", "Vladivostok", "Lord Howe Island", "Bougainville Island", "Chokurdakh", "Magadan", "Norfolk Island", "Sakhalin", "Solomon Is., New Caledonia", "Anadyr", "Auckland, Wellington", "Coordinated Universal Time+12", "Fiji", "Chatham Islands", "Coordinated Universal Time+13", "Nuku'alofa", "Samoa", "kiritimati Island", }; string[] countryUTC = new string[] { "UTC-12:00", "UTC-11:00", "UTC-10:00", "UTC-10:00", "UTC-09:30", "UTC-09:00", "UTC-09:00", "UTC-08:00", "UTC-08:00", "UTC-08:00", "UTC-07:00", "UTC-07:00", "UTC-07:00", "UTC-06:00", "UTC-06:00", "UTC-06:00", "UTC-06:00", "UTC-06:00", "UTC-05:00", "UTC-05:00", "UTC-05:00", "UTC-05:00", "UTC-05:00", "UTC-05:00", "UTC-04:00", "UTC-04:00", "UTC-04:00", "UTC-04:00", "UTC-04:00", "UTC-04:00", "UTC-04:00", "UTC-03:30", "UTC-03:00", "UTC-03:00", "UTC-03:00", "UTC-03:00", "UTC-03:00", "UTC-03:00", "UTC-03:00", "UTC-03:00", "UTC-03:00", "UTC-02:00", "UTC-01:00", "UTC-01:00", "UTC+00:00", "UTC+00:00", "UTC+00:00", "UTC+00:00", "UTC+01:00", "UTC+01:00", "UTC+01:00", "UTC+01:00", "UTC+01:00", "UTC+01:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+02:00", "UTC+03:00", "UTC+03:00", "UTC+03:00", "UTC+03:00", "UTC+03:00", "UTC+03:00", "UTC+03:30", "UTC+04:00", "UTC+04:00", "UTC+04:00", "UTC+04:00", "UTC+04:00", "UTC+04:00", "UTC+04:00", "UTC+04:00", "UTC+04:30", "UTC+05:00", "UTC+05:00", "UTC+05:00", "UTC+05:30", "UTC+05:30", "UTC+05:45", "UTC+06:00", "UTC+06:00", "UTC+06:00", "UTC+06:30", "UTC+07:00", "UTC+07:00", "UTC+07:00", "UTC+07:00", "UTC+07:00", "UTC+07:00", "UTC+08:00", "UTC+08:00", "UTC+08:00", "UTC+08:00", "UTC+08:00", "UTC+08:00", "UTC+08:30", "UTC+08:30", "UTC+09:00", "UTC+09:00", "UTC+09:00", "UTC+09:00", "UTC+09:30", "UTC+09:30", "UTC+10:00", "UTC+10:00", "UTC+10:00", "UTC+10:00", "UTC+10:00", "UTC+10:30", "UTC+11:00", "UTC+11:00", "UTC+11:00", "UTC+11:00", "UTC+11:00", "UTC+11:00", "UTC+12:00", "UTC+12:00", "UTC+12:00", "UTC+12:00", "UTC+12:45", "UTC+13:00", "UTC+13:00", "UTC+13:00", "UTC+14:00", }; double[] time = new double[] { -12, -11, -10, -10, -09.30, -09, -09, -08, -08, -08, -07, -07, -07, -06, -06, -06, -06, -06, -05, -05, -05, -05, -05, -05, -04, -04, -04, -04, -04, -04, -04, -03.30, -03, -03, -03, -03, -03, -03, -03, -03, -03, -02, -01, -01, +00, +00, +00, +00, +01, +01, +01, +01, +01, +01, +02, +02, +02, +02, +02, +02, +02, +02, +02, +02, +02, +02, +03, +03, +03, +03, +03, +03, +03.30, +04, +04, +04, +04, +04, +04, +04, +04, +04.30, +05, +05, +05, +05.30, +05.30, +05.45, +06, +06, +06, +06.30, +07, +07, +07, +07, +07, +07, +08, +08, +08, +08, +08, +08, +08.30, +08.30, +09, +09, +09, +09, +09.30, +09.30, +10, +10, +10, +10, +10, +10.30, +11, +11, +11, +11, +11, +11, +12, +12, +12, +12, +12.45, +13, +13, +13, +14, }; } public class ModelComboBox : INotifyPropertyChanged { private string country; private string countryUTC; private double time; private Color color; private string countryTime; public ModelComboBox() { Device.StartTimer(new TimeSpan(0, 0, 0, 0, 1000), TimerElapsed); } private bool TimerElapsed() { Device.BeginInvokeOnMainThread(() => { DateTime dt = timecal(DateTime.Now.TimeOfDay.ToString().Split('.')[0], Time); CountryTime = dt.TimeOfDay.ToString().Split('.')[0]; }); return true; } DateTime timecal(string IndiaTime, double timeDifference) { int td, tdh; var tdHours = (int)Math.Truncate(timeDifference); var tdMin = ((timeDifference - tdHours) * 100); var utcHours = (int)TimeZoneInfo.Local.BaseUtcOffset.Hours; var utcMin = (int)TimeZoneInfo.Local.BaseUtcOffset.Minutes; if (utcHours > tdHours) { tdh = (int)tdHours - utcHours; tdMin = (int)(tdMin - utcMin); td = (tdh * 60) + (int)tdMin; } else { tdh = (int)tdHours - utcHours; tdMin = (int)(tdMin - utcMin); td = (tdh * 60) + (int)tdMin; } string[] array1 = IndiaTime.Split(':'); int timeinMinutes = Convert.ToInt32(array1[0]) * 60 + Convert.ToInt32(array1[1]); timeinMinutes = timeinMinutes + td; int minutes = Math.Abs(timeinMinutes % 60); int hour = Math.Abs(timeinMinutes / 60); if (hour >= 24) hour = Math.Abs(hour - 24); String finalTime = Convert.ToString(hour) + ":" + Convert.ToString(minutes) + ":" + Convert.ToString(DateTime.Now.Second); DateTime time = Convert.ToDateTime(finalTime); return time; } public string CountryTime { get { return countryTime; } set { countryTime = value; RaisePropertyChanged("CountryTime"); } } public string Country { get { return this.country; } set { this.country = value; RaisePropertyChanged("Country"); } } public string CountryUTC { get { return this.countryUTC; } set { this.countryUTC = value; RaisePropertyChanged("CountryUTC"); } } public double Time { get { return time; } set { this.time = value; RaisePropertyChanged("Time"); } } public Color Color { get { return color; } set { this.color = value; RaisePropertyChanged("Color"); } } public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } } <file_sep>/iOS/SampleBrowser/Samples/Presentation/HeaderAndFooterPresentation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Presentation; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class HeaderAndFooterPresentation : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; public HeaderAndFooterPresentation() { label1 = new UILabel(); label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to insert a header and footer in a PowerPoint Presentation."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width , 50); } else { label.Frame = new CGRect (frameRect.Location.X, 5, frameRect.Size.Width , 70); } this.AddSubview (label); button.SetTitle("Generate Presentation",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect (0, 65, frameRect.Location.X + frameRect.Size.Width , 10); } else { button.Frame = new CGRect (frameRect.Location.X, 70, frameRect.Size.Width , 10); } this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.HeaderFooter.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Create an instance for PowerPoint IPresentation presentation = Presentation.Open(fileStream); //Add footers into all the PowerPoint slides. foreach (ISlide slide in presentation.Slides) { //Enable a date and time footer in slide. slide.HeadersFooters.DateAndTime.Visible = true; //Enable a footer in slide. slide.HeadersFooters.Footer.Visible = true; //Sets the footer text. slide.HeadersFooters.Footer.Text = "Footer"; //Enable a slide number footer in slide. slide.HeadersFooters.SlideNumber.Visible = true; } //Add header into first slide notes page. //Add a notes slide to the slide. INotesSlide notesSlide = presentation.Slides[0].AddNotesSlide(); //Enable a header in notes slide. notesSlide.HeadersFooters.Header.Visible = true; //Sets the header text. notesSlide.HeadersFooters.Header.Text = "Header"; MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("HeaderFooterPresentation.pptx", "application/mspowerpoint", stream); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/Forms/Maps/Maps/Samples/OSM/OSM.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfMaps.XForms; using System; using System.Collections.ObjectModel; using System.Net; using System.Reflection; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] //[XamlCompilation(XamlCompilationOptions.Compile)] public partial class OSM : SampleView { Label label; Grid childGrid; StackLayout stack; ViewModel viewModel; ImageryLayer layer; Syncfusion.SfMaps.XForms.SfMaps maps; Syncfusion.SfCarousel.XForms.SfCarousel carousel; /// <summary> /// Gets or sets the padding value to provide gap between the items from the selected item. /// </summary> private int carouselItemGap; public OSM() { InitializeComponent(); carouselItemGap = 30; viewModel = new ViewModel(); this.SizeChanged += OSM_SizeChanged; IsConnectedToNetwork(); } private void OSM_SizeChanged(object sender, EventArgs e) { InitializeChildGrid(); if (Height > 0) { var row = Height / 512; if (Math.Ceiling(row) <= 0) row = 1; else row = Math.Ceiling(row); for (int i = 0; i < row; i++) { var rowDefinition = new RowDefinition() { Height = 500 }; childGrid.RowDefinitions.Add(rowDefinition); } } if (Width > 0) { if (carousel != null) { if (Device.RuntimePlatform == Device.Android) { carousel.ItemWidth = (int)(Width * 0.75f); } else if (Device.RuntimePlatform == Device.iOS) { carousel.ItemWidth = (int)(Width * 0.7f); } else { carousel.ItemWidth = (int)(Width * 0.5f); carousel.Offset = (int)(Width * 0.15f); } carousel.SelectedItemOffset = (int)(carousel.ItemWidth / 2) - carouselItemGap; } var column = Width / 512; if (Math.Ceiling(column) <= 0) column = 1; else column = Math.Ceiling(column); for (int i = 0; i < column; i++) { var columnDefinition = new ColumnDefinition() { Width = 500 }; childGrid.ColumnDefinitions.Add(columnDefinition); } } if (childGrid.Children.Count > 0) childGrid.Children.Clear(); { for (int i = 0; i < childGrid.RowDefinitions.Count; i++) { for (int j = 0; j < childGrid.ColumnDefinitions.Count; j++) { Image image = new Image(); image.Source = "grid.png"; image.HeightRequest = 512; image.WidthRequest = 512; image.HorizontalOptions = LayoutOptions.FillAndExpand; image.VerticalOptions = LayoutOptions.FillAndExpand; if (Device.RuntimePlatform != Device.Android) image.Margin = new Thickness(-5); childGrid.Children.Add(image, j, i); } } } childGrid.IsClippedToBounds = true; } void IsConnectedToNetwork() { var current = Connectivity.NetworkAccess; if (current == NetworkAccess.Internet) { AddContent(); } else { label = new Label(); label.Margin = new Thickness(10, 0, 5, 0); label.Text = "Since this application requires network connection, please check your network connection."; label.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)); label.TextColor = Color.Black; label.HorizontalOptions = LayoutOptions.Center; label.VerticalOptions = LayoutOptions.Center; this.Content = label; } } void AddContent() { InitializeChildGrid(); mainGrid.HorizontalOptions = LayoutOptions.FillAndExpand; mainGrid.VerticalOptions = LayoutOptions.FillAndExpand; mainGrid.BackgroundColor = Color.FromRgb(249, 245, 237); mainGrid.Children.Add(childGrid); maps = new Syncfusion.SfMaps.XForms.SfMaps(); layer = new ImageryLayer(); layer.GeoCoordinates = new Point(27.1751, 78.0421); maps.MaxZoom = 8; maps.MinZoom = 4; layer.DistanceType = DistanceType.KiloMeter; if (Device.RuntimePlatform == Device.Android) { layer.Radius = 1500; } else { layer.Radius = 500; } //layer.MarkerTemplate = mainGrid.Resources["markerTemplate"] as DataTemplate; CustomMarker marker = new CustomMarker(); marker.Latitude = "20.6843"; marker.Longitude = "-88.5678"; marker.Location = "Mexico"; layer.Markers.Add(marker); marker = new CustomMarker(); marker.Location = "Peru"; marker.Latitude = "-13.1631"; marker.Longitude = "-72.5450"; layer.Markers.Add(marker); marker = new CustomMarker(); marker.Location = "Brazil"; marker.Latitude = "-22.9519"; marker.Longitude = "-43.2106"; layer.Markers.Add(marker); marker = new CustomMarker(); marker.Location = "Rome"; marker.Latitude = "41.8902"; marker.Longitude = "12.4922"; layer.Markers.Add(marker); marker = new CustomMarker(); marker.Location = "Jordan"; marker.Latitude = "30.3285"; marker.Longitude = "35.4444"; layer.Markers.Add(marker); marker = new CustomMarker(); marker.Location = "India"; marker.Latitude = "27.1751"; marker.Longitude = "78.0421"; layer.Markers.Add(marker); marker = new CustomMarker(); marker.Location = "China"; marker.Latitude = "40.4319"; marker.Longitude = "116.5704"; layer.Markers.Add(marker); MapMarkerSetting markerSettings = new MapMarkerSetting(); markerSettings.IconSize = 20; markerSettings.IconColor = Color.FromHex("#FF2196ef"); markerSettings.TooltipSettings.TooltipTemplate = mainGrid.Resources["toolTipTemplate"] as DataTemplate; markerSettings.TooltipSettings.ShowTooltip = true; markerSettings.TooltipSettings.FontSize = 15; layer.MarkerSettings = markerSettings; maps.Layers.Add(layer); mainGrid.Children.Add(maps); carousel = new Syncfusion.SfCarousel.XForms.SfCarousel(); carousel.RotationAngle = 0; if (Device.RuntimePlatform == Device.UWP) { carousel.HeightRequest = 150; carousel.ItemHeight = 150; } else { carousel.HeightRequest = 125; carousel.ItemHeight = 125; } carousel.VerticalOptions = LayoutOptions.EndAndExpand; carousel.Margin = new Thickness(0, 0, 0, 5); carousel.ItemTemplate= mainGrid.Resources["carouselTemplate"] as DataTemplate; carousel.SelectionChanged += Carousel_SelectionChanged; carousel.ItemsSource = viewModel.RotatorItems; carousel.SelectedIndex = 5; mainGrid.Children.Add(carousel); stack = new StackLayout(); stack.Orientation = StackOrientation.Horizontal; stack.BackgroundColor = Color.White; stack.HorizontalOptions = LayoutOptions.EndAndExpand; stack.VerticalOptions = LayoutOptions.End; Label label1 = new Label(); label1.FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)); label1.Text = "©"; label1.Margin = new Thickness(2); stack.Children.Add(label1); Label label2 = new Label(); label2.Margin = new Thickness(0, 2, 3, 2); label2.FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)); label2.Text = "OpenStreetMap contributors."; label2.TextColor = Color.DeepSkyBlue; Uri uri = new Uri("https://www.openstreetmap.org/copyright"); label2.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(() => Launcher.OpenAsync(uri)) }); stack.Children.Add(label2); mainGrid.Children.Add(stack); } private void Carousel_SelectionChanged(object sender, Syncfusion.SfCarousel.XForms.SelectionChangedEventArgs e) { int index = carousel.SelectedIndex; if (index == 0) { layer.GeoCoordinates = new Point(20.6843, -88.5678); } else if (index == 1) { layer.GeoCoordinates = new Point(-13.1631, -72.5450); } else if (index == 2) { layer.GeoCoordinates = new Point(-22.9519, -43.2106); } else if (index == 3) { layer.GeoCoordinates = new Point(41.8902, 12.4922); } else if (index == 4) { layer.GeoCoordinates = new Point(30.3285, 35.4444); } else if (index == 5) { layer.GeoCoordinates = new Point(27.1751, 78.0421); } else if (index == 6) { layer.GeoCoordinates = new Point(40.4319, 116.5704); } } void InitializeChildGrid() { if (childGrid == null) { childGrid = new Grid(); childGrid.HorizontalOptions = LayoutOptions.FillAndExpand; childGrid.VerticalOptions = LayoutOptions.FillAndExpand; } } } public class Model { private ImageSource image; private string description; private string title; private int index; public int SelectedIndex { get { return index; } set { index = value; } } public ImageSource Image { get { return image; } set { image = value; } } public string Description { get { return description; } set { description = value; } } public string Title { get { return title; } set { title = value; } } } public class ViewModel { public ObservableCollection<Model> RotatorItems { get; set; } public ViewModel() { RotatorItems = new ObservableCollection<Model>(); RotatorItems.Add(new Model() { Title = "<NAME>, Mexico", SelectedIndex = 0, Image = "Mexico.jpg", Description = "Mayan ruins on Mexico's Yucatan Peninsula. It was one of the largest Maya cities, thriving from around A.D. 600 to 1200." }) ; RotatorItems.Add(new Model() { Title = "<NAME>, Peru", SelectedIndex = 1, Image = "Peru.jpg", Description = "An inca citadel built in the mid-1400s. It was not widely known until the early 20th century." }); RotatorItems.Add(new Model() { Title = "Christ the Redeemer, Brazil", SelectedIndex = 2, Image = "Christ.jpg", Description = "An enormous statue of Jesus Christ with open arms. A symbol of Christianity across the world, the statue has also become a cultural icon of both Rio de Janeiro and Brazil." }); RotatorItems.Add(new Model() { Title = "Colosseum, Rome", SelectedIndex = 3, Image = "Colosseum.jpg", Description = "Built between A.D. 70 and 80. It is one of the most popular touristattractions in Europe." }); RotatorItems.Add(new Model() { Title = "Petra, Jordan", SelectedIndex = 4, Image = "Petra.jpg", Description = "It is a historic and archaeological city in southern Jordan. Petra lies around Jabal Al-Madbah in a basin surrounded by mountains which form the eastern flank of the Arabah valley that runs from the Dead Sea to the Gulf of Aqaba." }); RotatorItems.Add(new Model() { Title = "<NAME>, India", SelectedIndex = 5, Image = "TajMahal.jpg", Description = "It is an ivory-white marble mausoleum on the southern bank of the river Yamuna in the Indian city of Agra." }); RotatorItems.Add(new Model() { Title = "Great wall of China, China", SelectedIndex = 6, Image = "China_wall.jpg", Description = "The Great Wall of China is a series of fortifications that were built across the historical northern borders of ancient Chinese states and Imperial China as protection against various nomadic groups from the Eurasian Steppe." }); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Diagram/NodeAnnotation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using CoreGraphics; using Syncfusion.SfDiagram.iOS; using UIKit; namespace SampleBrowser { public partial class NodeAnnotation : SampleView { SfDiagram diagram; public NodeAnnotation() { //Initialize sfdiagram diagram = new SfDiagram(); } public override void LayoutSubviews() { base.LayoutSubviews(); //Set diagram width and height diagram.Width = (float)Frame.Width; diagram.Height = (float)Frame.Height; diagram.EnableSelectors = false; //Create Node Node n1 = DrawNode(270, 165, 100, 60); n1.Style.Brush = new SolidBrush(UIColor.White); n1.Annotations.Add(new Annotation() { Content = "NODE" }); diagram.AddNode(n1); Node n2 = DrawNode(50, (float)141.5, 110, 110); n2.Style.Brush = new SolidBrush(UIColor.White); n2.Style.StrokeWidth = 3; var img = new UIImageView(UIImage.FromBundle("Images/Diagram/emp.png")); img.Frame = new CGRect(n2.Style.StrokeWidth/2,n2.Style.StrokeWidth/2, n2.Width-n2.Style.StrokeWidth, n2.Height-n2.Style.StrokeWidth); n2.Annotations.Add(new Annotation() { Content = img }); diagram.AddNode(n2); Node n3 = DrawNode(50, 300, 230, 140); n3.ShapeType = ShapeType.RoundedRectangle; n3.CornerRadius = 8; n3.Style.Brush = new SolidBrush(UIColor.FromRGB(58, 179, 255)); n3.Style.StrokeBrush =new SolidBrush( UIColor.FromRGB(0,117,168)); n3.Style.StrokeWidth = 3; //To defines the button properties var button = new UIButton(); button.Frame = new CGRect(60, 100, 110, 30); button.SetTitle("View Profile", UIControlState.Normal); button.SetTitleColor(UIColor.White, UIControlState.Normal); button.Layer.CornerRadius = 5; button.Layer.BorderWidth = 2; button.Layer.BorderColor = UIColor.White.CGColor; button.Font = UIFont.BoldSystemFontOfSize(10); //Create new uiimageview var emp = new UIImageView(UIImage.FromBundle("Images/Diagram/Paul.png")); emp.Frame = new CGRect(14, 14, 70, 70); //Defines the lable for node var label = new UILabel() { Text = "<NAME> \n Business Analyst", TextColor = UIColor.White, Font = UIFont.FromName(".SF UI Text", 12), LineBreakMode = UILineBreakMode.WordWrap, Lines = 0, Frame = new CGRect(95, -25, n3.Width, n3.Height) }; //Add annotation to the node. n3.Annotations.Add(new Annotation() { Content = label }); n3.Annotations.Add(new Annotation() { Content = button }); n3.Annotations.Add(new Annotation() { Content = emp }); diagram.AddNode(n3); Node n4 = DrawNode(390, 300, 140, 140); n4.Style.StrokeWidth = 0; n4.Style.Brush = new SolidBrush(UIColor.FromRGB(69, 179, 157)); var txt = new UILabel() { Text = "CONTENT SHAPE", Font = UIFont.FromName("ArialMT", 14), TextAlignment= UITextAlignment.Center }; txt.Frame = new CGRect(2, 45, n4.Width, n4.Height); var contentShape = new Shape(n4); n4.Annotations.Add(new Annotation() { Content = contentShape }); n4.Annotations.Add(new Annotation() { Content = txt }); diagram.AddNode(n4); //Create Connector Connector c1 = new Connector(n1, n2); c1.SegmentType = SegmentType.StraightSegment; diagram.AddConnector(c1); Connector c2 = new Connector(n1, n3); c2.SegmentType = SegmentType.StraightSegment; diagram.AddConnector(c2); Connector c3 = new Connector(n1, n4); c3.SegmentType = SegmentType.StraightSegment; diagram.AddConnector(c3); this.AddSubview(diagram); } //Creates the Node with Specified input Node DrawNode(float x, float y, float w, float h) { var node = new Node(); node.OffsetX = x; node.OffsetY = y; node.Width = w; node.Height = h; return node; } //Create Node's Annotation UILabel CreateLabel(string text, nfloat width, nfloat height) { var label = new UILabel() { Text = text, TextColor = UIColor.Black, Font = UIFont.FromName(".SF UI Text", 13), LineBreakMode = UILineBreakMode.WordWrap, Lines = 0, Frame = new CGRect(0, 0, width, height) }; return label; } /// <summary> /// Class to render custom shape /// </summary> class Shape : UIView { public Shape(Node node) { Frame = new CGRect(node.Width/2-25, node.Height/2-40, 50, 50); BackgroundColor = UIColor.Clear; } public override void Draw(CGRect rect) { base.Draw(rect); using (CGContext g = UIGraphics.GetCurrentContext()) { var sample = new CGPath(); sample.AddLines(new CGPoint[] { new CGPoint(Frame.Width/2, 0),new CGPoint(Frame.Width/2.8, Frame.Height/2.5), new CGPoint(0, Frame.Height/2.5), new CGPoint(Frame.Width/3.5, Frame.Height/1.75), new CGPoint(Frame.Width/7, Frame.Height), new CGPoint(Frame.Width/2, Frame.Height/1.4), new CGPoint(Frame.Width/1.2, Frame.Height), new CGPoint(Frame.Width/1.4, Frame.Height/1.75), new CGPoint(Frame.Width, Frame.Height/2.5), new CGPoint(Frame.Width/1.6, Frame.Height/2.5), new CGPoint(Frame.Width/2, 0) }); g.AddPath(sample); UIColor.White.SetStroke(); UIColor.White.SetFill(); g.DrawPath(CGPathDrawingMode.FillStroke); } } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Trendlines.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using CoreAnimation; #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; using CoreGraphics; using Syncfusion.SfChart.iOS; using UIKit; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Trendlines : SampleView { private SFSplineSeries splineSeries2; private SFSplineSeries splineSeries1; private SFChartTrendline powerTrendline; private SFChartTrendline linearTrendline; private readonly List<string> Types = new List<string> { "Linear", "Exponential", "Logarithmic", "Power", "Polynomial" }; UIPickerView picker; private SFChart chart; private SFChart chart1; private UIButton typeTextButton; private UIButton doneButton; public Trendlines() { chart = GetCurrencyDevationChart(); chart1 = GetMeterDevationChart(); chart.Hidden = false; chart1.Hidden = true; picker = new UIPickerView(); var pickerModel = new TypePickerViewmodel(Types); picker.Model = pickerModel; picker.Hidden = true; pickerModel.ValueChanged += PickerModel_ValueChanged; doneButton = new UIButton(); typeTextButton = new UIButton(); doneButton.SetTitle("Done" + "\t", UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.TouchUpInside += delegate { picker.Hidden = true; doneButton.Hidden = true; this.BecomeFirstResponder(); }; typeTextButton.SetTitle("Linear", UIControlState.Normal); typeTextButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; typeTextButton.SetTitleColor(UIColor.Black, UIControlState.Normal); typeTextButton.TouchUpInside += delegate { picker.Hidden = false; doneButton.Hidden = false; this.BecomeFirstResponder(); }; typeTextButton.BackgroundColor = UIColor.Clear; typeTextButton.Layer.BorderWidth = 2.0f; typeTextButton.Layer.BorderColor = UIColor.FromRGB(240.0f / 255.0f, 240.0f / 255.0f, 240.0f / 255.0f).CGColor; typeTextButton.Layer.CornerRadius = 8.0f; picker.BackgroundColor = UIColor.FromRGB(240f / 255.0f, 240f / 255.0f, 240f / 255.0f); doneButton.BackgroundColor = UIColor.FromRGB(240f / 255.0f, 240f / 255.0f, 240f / 255.0f); doneButton.Hidden = true; chart1.Legend.Visible = true; AddSubview(chart); AddSubview(chart1); AddSubview(picker); AddSubview(typeTextButton); AddSubview(doneButton); } void PickerModel_ValueChanged(object sender, EventArgs e) { var selectedValue = ((TypePickerViewmodel)sender).SelectedValue; if (selectedValue == "Power") { typeTextButton.SetTitle("Power", UIControlState.Normal); chart1.Hidden = false; chart.Hidden = true; } else { if (selectedValue == "Linear") { typeTextButton.SetTitle("Linear", UIControlState.Normal); linearTrendline.Type = SFTrendlineType.Linear; linearTrendline.Label = "Linear"; } else if (selectedValue == "Exponential") { typeTextButton.SetTitle("Exponential", UIControlState.Normal); linearTrendline.Label = "Exponential"; linearTrendline.Type = SFTrendlineType.Exponential; } else if (selectedValue == "Logarithmic") { typeTextButton.SetTitle("Logarithmic", UIControlState.Normal); linearTrendline.Label = "Logarithmic"; linearTrendline.Type = SFTrendlineType.Logarithmic; } else if (selectedValue == "Polynomial") { typeTextButton.SetTitle("Polynomial", UIControlState.Normal); linearTrendline.Label = "Polynomial"; linearTrendline.Type = SFTrendlineType.Polynomial; } if (chart.Hidden) { chart.Hidden = false; chart1.Hidden = true; } } } private SFChart GetMeterDevationChart() { var sfchart = new SFChart(); sfchart.Title.Text = "Distance Measurement"; sfchart.Legend.Visible = true; sfchart.Legend.DockPosition = SFChartLegendPosition.Top; sfchart.Legend.IconHeight = 14; sfchart.Legend.IconWidth = 14; sfchart.ColorModel.Palette = SFChartColorPalette.Natural; SFNumericalAxis numericalaxis = new SFNumericalAxis(); numericalaxis.AxisLineStyle.LineWidth = 0; numericalaxis.MajorTickStyle.LineWidth = 0; numericalaxis.Title.Text = new Foundation.NSString("Meters"); sfchart.SecondaryAxis = numericalaxis; SFNumericalAxis primaryAxis = new SFNumericalAxis(); primaryAxis.ShowMajorGridLines = false; primaryAxis.Title.Text = new Foundation.NSString("Seconds"); primaryAxis.ShowMinorGridLines = false; sfchart.PrimaryAxis = primaryAxis; splineSeries2 = new SFSplineSeries(); splineSeries2.ItemsSource = ChartViewModel.GetTrendlineDataSource2(); splineSeries2.XBindingPath = "XValue"; splineSeries2.YBindingPath = "YValue"; splineSeries2.Label = "Rupees"; splineSeries2.LegendIcon = SFChartLegendIcon.SeriesType; splineSeries2.DataMarker.ShowMarker = true; splineSeries2.DataMarker.ShowLabel = false; splineSeries2.DataMarker.MarkerHeight = 5; splineSeries2.DataMarker.MarkerWidth = 5; splineSeries2.DataMarker.MarkerBorderWidth = 2; splineSeries2.DataMarker.MarkerBorderColor = UIColor.FromName("#00bdae"); splineSeries2.Trendlines = new ChartTrendlineCollection(); powerTrendline = new SFChartTrendline() { Type = SFTrendlineType.Power, LineColor = UIColor.FromRGB(201, 23, 97), LegendIcon = SFChartLegendIcon.SeriesType, Label = "Power" }; splineSeries2.Trendlines.Add(powerTrendline); sfchart.Series.Add(splineSeries2); return sfchart; } private SFChart GetCurrencyDevationChart() { var sfchart = new SFChart(); sfchart.Title.Text = "1 USD to INR from 1977 to 2019"; sfchart.Legend.Visible = true; sfchart.Legend.DockPosition = SFChartLegendPosition.Top; sfchart.Legend.IconHeight = 14; sfchart.Legend.IconWidth = 14; sfchart.ColorModel.Palette = SFChartColorPalette.Natural; sfchart.Delegate = new AxisLabelFormatter(); SFNumericalAxis numericalaxis = new SFNumericalAxis(); numericalaxis.AxisLineStyle.LineWidth = 0; numericalaxis.MajorTickStyle.LineWidth = 0; numericalaxis.Title.Text = new Foundation.NSString("Rupees against Dollars"); sfchart.SecondaryAxis = numericalaxis; SFDateTimeAxis primaryAxis = new SFDateTimeAxis(); primaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; primaryAxis.ShowMajorGridLines = false; primaryAxis.IntervalType = SFChartDateTimeIntervalType.Years; primaryAxis.Interval = new NSNumber(8); primaryAxis.Title.Text = new Foundation.NSString("Years"); primaryAxis.ShowMinorGridLines = false; sfchart.PrimaryAxis = primaryAxis; splineSeries1 = new SFSplineSeries(); splineSeries1.XBindingPath = "XValue"; splineSeries1.YBindingPath = "YValue"; splineSeries1.ItemsSource = ChartViewModel.GetTrendlineDataSource1(); splineSeries1.Label = "Rupees"; splineSeries1.LegendIcon = SFChartLegendIcon.SeriesType; splineSeries1.DataMarker.ShowMarker = true; splineSeries1.DataMarker.ShowLabel = false; splineSeries1.DataMarker.MarkerHeight = 5; splineSeries1.DataMarker.MarkerWidth = 5; splineSeries1.DataMarker.MarkerWidth = 2; splineSeries1.DataMarker.MarkerBorderColor = UIColor.FromName("#00bdae"); splineSeries1.Trendlines = new ChartTrendlineCollection(); linearTrendline = new SFChartTrendline() { Type = SFTrendlineType.Linear, LineColor = UIColor.FromRGB(201, 23, 97), LegendIcon = SFChartLegendIcon.SeriesType, Label = "Linear", PolynomialOrder = 3, }; splineSeries1.Trendlines.Add(linearTrendline); sfchart.Series.Add(splineSeries1); return sfchart; } public override void LayoutSubviews() { base.LayoutSubviews(); chart.Frame = new CGRect(this.Bounds.X, this.Bounds.Y + 40, this.Bounds.Width, this.Bounds.Height - 40); chart1.Frame = new CGRect(this.Bounds.X, this.Bounds.Y + 40, this.Bounds.Width, this.Bounds.Height - 40); typeTextButton.Frame = new CGRect(10, Bounds.Y, Frame.Size.Width - 20, 40); if (Utility.IsIPad) { doneButton.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 253, Frame.Size.Width, 35); picker.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 260, Frame.Size.Width, 260); } else { doneButton.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 143, Frame.Size.Width, 35); picker.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 150, Frame.Size.Width, 150); } } public class TypePickerViewmodel : UIPickerViewModel { public List<string> Types; public EventHandler ValueChanged; public string SelectedValue; public TypePickerViewmodel(List<string> types) { this.Types = types; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return Types.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return Types[(int)row]; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var type = Types[(int)row]; SelectedValue = type; ValueChanged?.Invoke(this, null); } } class AxisLabelFormatter : SFChartDelegate { public override NSString GetFormattedAxisLabel(SFChart chart, NSString label, NSObject value, SFAxis axis) { if (axis == chart.SecondaryAxis) { String formattedLabel = "₹" + label; label = new NSString(formattedLabel); return label; } return label; } } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/StepLine.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Android.Graphics; namespace SampleBrowser { public class StepLine : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Unemployment Rates 1975-2010"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.ColorModel.ColorPalette = ChartColorPalette.Natural; chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.ToggleSeriesVisibility = true; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; numericalAxis.Minimum = 1975; numericalAxis.Maximum = 2010; numericalAxis.Interval = 5; numericalAxis.ShowMajorGridLines = false; numericalAxis.PlotOffset = 10; numericalAxis.AxisLineOffset = 10; numericalAxis.MajorTickStyle.TickSize = 10; chart.PrimaryAxis = numericalAxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Minimum = 0; numericalaxis.Maximum = 20; numericalaxis.Interval = 5; numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.TickSize = 0; numericalaxis.LabelStyle.LabelFormat = "#'%'"; chart.SecondaryAxis = numericalaxis; StepLineSeries stepLineSeries1 = new StepLineSeries(); stepLineSeries1.ItemsSource = MainPage.GetStepLineData1(); stepLineSeries1.XBindingPath = "XValue"; stepLineSeries1.YBindingPath = "YValue"; stepLineSeries1.Label = "China"; stepLineSeries1.DataMarker.ShowMarker = true; stepLineSeries1.DataMarker.MarkerColor = Color.White; stepLineSeries1.DataMarker.MarkerWidth = 10; stepLineSeries1.DataMarker.MarkerHeight = 10; stepLineSeries1.DataMarker.MarkerStrokeColor = Color.ParseColor("#00bdae"); stepLineSeries1.DataMarker.MarkerStrokeWidth = 2; stepLineSeries1.LegendIcon = ChartLegendIcon.SeriesType; stepLineSeries1.StrokeWidth = 3; stepLineSeries1.TooltipEnabled = true; StepLineSeries stepLineSeries2 = new StepLineSeries(); stepLineSeries2.ItemsSource = MainPage.GetStepLineData2(); stepLineSeries2.XBindingPath = "XValue"; stepLineSeries2.YBindingPath = "YValue"; stepLineSeries2.Label = "Australia"; stepLineSeries2.DataMarker.ShowMarker = true; stepLineSeries2.DataMarker.MarkerColor = Color.White; stepLineSeries2.DataMarker.MarkerWidth = 10; stepLineSeries2.DataMarker.MarkerHeight = 10; stepLineSeries2.DataMarker.MarkerStrokeColor = Color.ParseColor("#404041"); stepLineSeries2.DataMarker.MarkerStrokeWidth = 2; stepLineSeries2.LegendIcon = ChartLegendIcon.SeriesType; stepLineSeries2.StrokeWidth = 3; stepLineSeries2.TooltipEnabled = true; stepLineSeries1.EnableAnimation = true; stepLineSeries2.EnableAnimation = true; chart.Series.Add(stepLineSeries1); chart.Series.Add(stepLineSeries2); return chart; } } }<file_sep>/Forms/Sparkline/Sparkline/Samples/Sparkline/Sparkline.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSparkline { [Preserve(AllMembers = true)] public partial class Sparkline : SampleBrowser.Core.SampleView { public Sparkline() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Phone) { var sparkline_phone = new Sparkline_Phone(); Content = sparkline_phone.getContent(); PropertyView = sparkline_phone.getPropertyView(); } else if (Device.RuntimePlatform == Device.UWP || Device.Idiom == TargetIdiom.Tablet) { var sparkline_windows = new Spark_Windows(); Content = sparkline_windows.getContent(); PropertyView = sparkline_windows.getPropertyView(); } } } }<file_sep>/Forms/CircularGauge/CircularGauge/Samples/CircularGaugeAnnotation/CircularGaugeAnnotation.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using SyncXForms = Syncfusion.SfGauge.XForms; using Xamarin.Forms; using Xamarin.Forms.Xaml; using System.Collections.ObjectModel; using Xamarin.Forms.Internals; namespace SampleBrowser.SfCircularGauge { [Preserve(AllMembers = true)] public partial class CircularGaugeAnnotation : SampleView { private SyncXForms.SfCircularGauge annotation1 { get; set; } private SyncXForms.SfCircularGauge annotation2 { get; set; } private Label labelAnnotation1 { get; set; } private Label labelAnnotation2 { get; set; } private Label labelAnnotation3 { get; set; } private bool isUpdate = false; public CircularGaugeAnnotation() { InitializeComponent(); this.SizeChanged += AnnotationSample_SizeChanged; } private void AnnotationSample_SizeChanged(object sender, EventArgs e) { Padding = 15; labelAnnotation1 = new Label { Text = "", FontSize = 14, HeightRequest = 25, WidthRequest = 75, TextColor = Color.Black, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center }; labelAnnotation2 = new Label { Text = "", FontSize = 12, HeightRequest = 20, WidthRequest = 35, TextColor = Color.Black, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center }; labelAnnotation3 = new Label { Text = "", FontSize = 12, HeightRequest = 20, WidthRequest = 35, TextColor = Color.Black, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center }; Grid grid1 = new Grid(); Grid grid2 = new Grid(); Grid grid3 = new Grid(); grid1.Children.Add(labelAnnotation1); grid2.Children.Add(labelAnnotation2); grid3.Children.Add(labelAnnotation3); var minSize = Math.Min(Gauge.Bounds.Height, Gauge.Bounds.Width); var annotationSize = minSize / 5.0; annotation1 = new SyncXForms.SfCircularGauge { HeightRequest = annotationSize, WidthRequest = annotationSize, Annotations = new SyncXForms.CircularGaugeAnnotationCollection { new SyncXForms.GaugeAnnotation { View = grid2, Angle = 270, Offset = .5 } }, Scales = new ObservableCollection<SyncXForms.Scale> { new SyncXForms.Scale { StartAngle = 270, SweepAngle = 360, ShowLabels = false, StartValue = 0, EndValue = 60, Interval = 5, RimColor = Color.FromRgb(237, 238, 239), Ranges = new ObservableCollection<Syncfusion.SfGauge.XForms.Range> { new Syncfusion.SfGauge.XForms.Range {StartValue = 0, EndValue = 30, Color = Color.Gray, InnerStartOffset = 0.925, OuterStartOffset = 1, InnerEndOffset = 0.925, OuterEndOffset = 1}, }, MajorTickSettings = new SyncXForms.TickSettings { Color = Color.Black, StartOffset = 1, EndOffset = .85, Thickness = 2 }, MinorTickSettings = new SyncXForms.TickSettings { Color = Color.Black, StartOffset = 1, EndOffset = .90, Thickness = 0.5 }, Pointers = new ObservableCollection<SyncXForms.Pointer> { new SyncXForms.NeedlePointer { Type = SyncXForms.PointerType.Triangle, KnobRadius = 4, Thickness = 3, EnableAnimation = false, KnobColor = Color.Black, Color = Color.Black } } } } }; annotation1.Parent = this; annotation2 = new SyncXForms.SfCircularGauge { HeightRequest = annotationSize, WidthRequest = annotationSize, Annotations = new SyncXForms.CircularGaugeAnnotationCollection { new SyncXForms.GaugeAnnotation { View = grid3, Angle = 270, Offset = .5 } }, Scales = new ObservableCollection<SyncXForms.Scale> { new SyncXForms.Scale { StartAngle = 270, SweepAngle = 360, StartValue = 0, EndValue = 60, Interval = 5, ShowLabels = false, RimColor = Color.FromRgb(237, 238, 239), Ranges = new ObservableCollection<Syncfusion.SfGauge.XForms.Range> { new Syncfusion.SfGauge.XForms.Range {StartValue = 0, EndValue = 30, Color = Color.Gray, InnerStartOffset = 0.925, OuterStartOffset = 1, InnerEndOffset = 0.925, OuterEndOffset = 1}, }, MajorTickSettings = new SyncXForms.TickSettings { Color = Color.Black, StartOffset = 1, EndOffset = .85, Thickness = 2 }, MinorTickSettings = new SyncXForms.TickSettings { Color = Color.Black, StartOffset = 1, EndOffset = .90, Thickness = 0.5 }, Pointers = new ObservableCollection<SyncXForms.Pointer> { new SyncXForms.NeedlePointer { Type = SyncXForms.PointerType.Triangle, KnobRadius = 4, Thickness = 3, EnableAnimation = false, KnobColor = Color.Black, Color = Color.Black } } } } }; annotation2.Parent = this; Gauge = new SyncXForms.SfCircularGauge() { Annotations = new SyncXForms.CircularGaugeAnnotationCollection { new SyncXForms.GaugeAnnotation { View = annotation1, Angle = 90, Offset = GetOffsetValue(.5,.5,.6) }, new SyncXForms.GaugeAnnotation { View = grid1, Angle = 00, Offset = 0.45 }, new SyncXForms.GaugeAnnotation { View = annotation2, Angle = 180, Offset = GetOffsetValue(.5, .5, .6) }, }, Scales = new ObservableCollection<SyncXForms.Scale> { new SyncXForms.Scale { StartValue = 0, EndValue = 12, Interval = 1, MinorTicksPerInterval = 4, RimColor = Color.FromRgb(237, 238, 239), LabelColor = Color.Gray, LabelOffset = GetOffsetValue(.8, .8, .875), ScaleEndOffset = .925, StartAngle = 270, SweepAngle = 360, LabelFontSize = 14, ShowFirstLabel = false, MinorTickSettings = new SyncXForms.TickSettings { Color = Color.Black, StartOffset = 1, EndOffset = .95, Thickness = 1 }, MajorTickSettings = new SyncXForms.TickSettings { Color = Color.Black, StartOffset = 1, EndOffset = .9, Thickness = 3 }, Ranges = new ObservableCollection<Syncfusion.SfGauge.XForms.Range> { new SyncXForms.Range {StartValue = 0, EndValue = 3, Color= Color.Gray, InnerStartOffset = 0.925, OuterStartOffset = 1, InnerEndOffset = 0.925, OuterEndOffset = 1}, }, Pointers = new ObservableCollection<SyncXForms.Pointer> { new SyncXForms.NeedlePointer { EnableAnimation = false, KnobRadius = 6, LengthFactor = .75, KnobColor = Color.White, Color = Color.Black, Thickness = 3.5, KnobStrokeColor = Color.Black, KnobStrokeWidth = 5 , TailLengthFactor = 0.25, TailColor = Color.Black}, new SyncXForms.NeedlePointer { EnableAnimation = false, KnobRadius = 6, LengthFactor = .4, KnobColor = Color.White, Color = Color.Black, Thickness = 5, Type = SyncXForms.PointerType.Triangle }, new SyncXForms.NeedlePointer { EnableAnimation = false, KnobRadius = 6, LengthFactor = .65, KnobColor = Color.White, Color =Color.Black, Thickness = 5, Type = SyncXForms.PointerType.Triangle }, } } } }; isUpdate = true; DynamicUpdate(); this.Content = Gauge; } private double GetOffsetValue(double ios, double android, double uwp) { switch (Device.RuntimePlatform) { case Device.iOS: return ios; case Device.Android: return android; default: return uwp; } } private async void DynamicUpdate() { while (isUpdate && Gauge != null && Gauge.Scales.Count > 0) { var dataTime = DateTime.Now; var hour = (double)dataTime.Hour; hour = hour > 12 ? hour % 12 : hour; var min = (double)dataTime.Minute; var sec = (double)dataTime.Second; Gauge.Scales[0].Pointers[0].Value = sec / 5; Gauge.Scales[0].Pointers[1].Value = hour + min / 60; Gauge.Scales[0].Pointers[2].Value = min / 5 + (sec / 60 * .2); annotation1.Scales[0].Pointers[0].Value = sec; annotation2.Scales[0].Pointers[0].Value = min + sec / 60; var meridiem = dataTime.Hour > 12 ? "PM" : "AM"; labelAnnotation1.Text = hour.ToString() + " : " + min.ToString() + " " + meridiem; labelAnnotation2.Text = sec.ToString() + " S"; labelAnnotation3.Text = min.ToString() + " M"; await Task.Delay(1000); } } public override void OnDisappearing() { base.OnDisappearing(); this.SizeChanged -= AnnotationSample_SizeChanged; isUpdate = false; if (annotation1 != null && annotation1.Parent != null) { annotation1.Parent = null; annotation1 = null; } if (annotation1 != null && annotation2.Parent != null) { annotation2.Parent = null; annotation2 = null; } if (Gauge != null) this.Gauge = null; if (this.Content != null) this.Content = null; } } } <file_sep>/Android/SampleBrowser/Samples/DocIO/EmployeeList_MailMerge.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using System.Data; namespace SampleBrowser { public partial class EmployeeList_MailMerge : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to create an employee report using Mail merge functionality of Essential DocIO."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Creating a new document. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.EmployeesReportDemo.doc"); //Open Template document document.Open(inputStream, FormatType.Word2013); inputStream.Dispose(); DataTable table = GetDataTable(); //Uses the mail merge events handler for image fields document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_ProductImage); document.MailMerge.ExecuteGroup(table); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("EmployeeReport.docx", "application/msword", stream, m_context); } } /// <summary> /// Gets the Employees record in DataTable format /// </summary> /// <returns></returns> private DataTable GetDataTable() { //Data source DataSet ds = new DataSet(); ds.Tables.Add(); //Defining columns ds.Tables[0].TableName = "Employees"; ds.Tables[0].Columns.Add("Photo"); ds.Tables[0].Columns.Add("FirstName"); ds.Tables[0].Columns.Add("LastName"); ds.Tables[0].Columns.Add("Title"); ds.Tables[0].Columns.Add("Address"); ds.Tables[0].Columns.Add("City"); ds.Tables[0].Columns.Add("Region"); ds.Tables[0].Columns.Add("Country"); ds.Tables[0].Columns.Add("PostalCode"); ds.Tables[0].Columns.Add("HomePhone"); ds.Tables[0].Columns.Add("Extension"); ds.Tables[0].Columns.Add("BirthDate"); //Set values. DataRow row; row = ds.Tables["Employees"].NewRow(); row["Photo"] = "SampleImage.png"; row["FirstName"] = "Nancy"; row["LastName"] = "Davolio"; row["Title"] = "Sales Representative"; row["Address"] = "507 - 20th Ave. E.Apt. 2A"; row["City"] = "Seattle"; row["Region"] = "WA"; row["Country"] = "USA"; row["PostalCode"] = "98122"; row["HomePhone"] = "(206) 555-9857"; row["Extension"] = "5467"; row["BirthDate"] = "08-12-1948 12:00:00 AM"; ds.Tables["Employees"].Rows.Add(row); row = ds.Tables["Employees"].NewRow(); row["Photo"] = "SampleImage.png"; row["FirstName"] = "Andrew"; row["LastName"] = "Fuller"; row["Title"] = "Vice President, Sales"; row["Address"] = "507 - 20th Ave. E.Apt. 2A"; row["City"] = "Tacoma"; row["Region"] = "WA"; row["Country"] = "USA"; row["PostalCode"] = "98401"; row["HomePhone"] = "(206) 555-9842"; row["Extension"] = "3457"; row["BirthDate"] = "19-02-1952 12:00:00 AM"; ds.Tables["Employees"].Rows.Add(row); row = ds.Tables["Employees"].NewRow(); row["Photo"] = "SampleImage.png"; row["FirstName"] = "Janet"; row["LastName"] = "Leverling"; row["Title"] = "Sales Representative"; row["Address"] = "722 Moss Bay Blvd"; row["City"] = "Kirkland"; row["Region"] = "WA"; row["Country"] = "USA"; row["PostalCode"] = "98033"; row["HomePhone"] = "(206) 555-3412"; row["Extension"] = "3355"; row["BirthDate"] = "30-08-1963 12:00:00 AM"; ds.Tables["Employees"].Rows.Add(row); DataTable table = ds.Tables["Employees"]; return table; } /// <summary> /// Execute the MergeImageFieldEvent to merge the images to corresponding image fields /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void MergeField_ProductImage(object sender, MergeImageFieldEventArgs args) { Assembly assembly = Assembly.GetExecutingAssembly(); string rootPath = "SampleBrowser.Samples.DocIO.Templates."; //Binds image from file system during mail merge if (args.FieldName == "Photo") { string ProductFileName = args.FieldValue.ToString(); Stream inputStream = assembly.GetManifestResourceStream(rootPath + ProductFileName); args.ImageStream = inputStream; } } } } <file_sep>/Android/SampleBrowser/Samples/Schedule/Customization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Views; using Android.Content; using Android.Widget; using Com.Syncfusion.Schedule; using Com.Syncfusion.Schedule.Enums; using System.Collections.Generic; using Android.Graphics; using Java.Util; using Android.Graphics.Drawables; using Java.Text; namespace SampleBrowser { public class Customization : SamplePage, IDisposable { public Customization() { } /// <summary> /// Initialize schedule. /// </summary> private SfSchedule sfSchedule; /// <summary> /// Initialize context. /// </summary> private Context context; /// <summary> /// Initialize button. /// </summary> private Button customView; public override View GetSampleContent(Context context) { this.context = context; LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; //creating instance for Schedule sfSchedule = new SfSchedule(context); HeaderStyle headerStyle = new HeaderStyle(); headerStyle.BackgroundColor = Color.Argb(255, 214, 214, 214); headerStyle.TextColor = Color.Black; ViewHeaderStyle viewHeader = new ViewHeaderStyle(); viewHeader.BackgroundColor = Color.Argb(255, 28, 28, 28); viewHeader.DayTextColor = Color.Argb(255, 238, 199, 43); viewHeader.DateTextColor = Color.Argb(255, 238, 199, 43); sfSchedule.HeaderStyle = headerStyle; DayViewSettings dayViewSettings = new DayViewSettings(); dayViewSettings.TimeSlotBorderStrokeWidth = 2; dayViewSettings.VerticalLineStrokeWidth = 0; dayViewSettings.VerticalLineColor = Color.Transparent; dayViewSettings.TimeSlotBorderColor = Color.LightGray; dayViewSettings.NonWorkingHoursTimeSlotBorderColor = Color.LightGray; sfSchedule.DayViewSettings = dayViewSettings; Button button = new Button(context); button.Text = "+ New event"; button.SetTextColor(Color.White); button.Gravity = GravityFlags.Left; button.SetBackgroundColor(Color.Rgb(0, 122, 255)); sfSchedule.SelectionView = button; //set the appointment collection GetAppointments(); sfSchedule.ItemsSource = appointmentCollection; sfSchedule.AppointmentViewLayout = ViewLayoutOptions.Overlay; sfSchedule.MonthCellLoaded += SfSchedule_MonthCellLoaded; sfSchedule.LayoutParameters = new FrameLayout.LayoutParams( LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); sfSchedule.AppointmentLoaded += SfSchedule_AppointmentLoaded; sfSchedule.CellTapped += SfSchedule_ScheduleTapped; linearLayout.AddView(sfSchedule); return linearLayout; } private TextView currentSelectedView; private void SfSchedule_ScheduleTapped(object sender, CellTappedEventArgs e) { if (currentSelectedView != null) { currentSelectedView.SetBackgroundColor(Color.ParseColor("#A237B3E6")); } } private void SfSchedule_AppointmentLoaded(object sender, AppointmentLoadedEventArgs e) { customView = new Button(context); customView.Text = e.Appointment.Subject; customView.TextAlignment = TextAlignment.Gravity; customView.Gravity = GravityFlags.CenterHorizontal; customView.SetTextColor(Color.White); customView.SetPadding(10, 20, 10, 20); if (customView.Text == "B'Day Party") { customView.SetCompoundDrawablesWithIntrinsicBounds(0, Resource.Drawable.family, 0, 0); customView.SetBackgroundColor(Color.ParseColor("#FFA2C139")); } else if (customView.Text == "Medical Checkup") { customView.SetCompoundDrawablesWithIntrinsicBounds(0, Resource.Drawable.hospital, 0, 0); customView.SetBackgroundColor(Color.ParseColor("#FFD80073")); } else { customView.SetCompoundDrawablesWithIntrinsicBounds(0, Resource.Drawable.team, 0, 0); customView.SetBackgroundColor(Color.ParseColor("#FF1BA1E2")); } e.View = customView; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void FrameLayout_Click(object sender, EventArgs e) { currentSelectedView = sender as TextView; currentSelectedView.SetBackgroundColor(Color.ParseColor("#58FAF4")); } private void SfSchedule_MonthCellLoaded(object sender, MonthCellLoadedEventArgs e) { Calendar calendar = e.Calendar; FrameLayout frameLayout = new FrameLayout(context); if (calendar != null) { GradientDrawable gradientDrawable = new GradientDrawable( GradientDrawable.Orientation.TopBottom, new int[] { 255, 0 }); //0xFF616261 gradientDrawable.SetCornerRadius(0f); TextView monthCellText = new TextView(context); String text = new SimpleDateFormat("dd").Format(calendar.Time); monthCellText.Text = text; if ((calendar.Get(CalendarField.DayOfWeek) == Calendar.Sunday) || (calendar.Get(CalendarField.DayOfWeek) == Calendar.Saturday)) { monthCellText.SetTextColor(Color.Red); } else { monthCellText.SetTextColor(Color.Black); } if ((calendar.Get(CalendarField.Year) == Calendar.Instance.Get(CalendarField.Year)) && (calendar.Get(CalendarField.Month) == Calendar.Instance.Get(CalendarField.Month) && (calendar.Get(CalendarField.DayOfMonth) == Calendar.Instance.Get(CalendarField.DayOfMonth)))) { monthCellText.SetTextColor(Color.LightBlue); } monthCellText.TextSize = 18; monthCellText.Gravity = GravityFlags.CenterHorizontal; monthCellText.SetPadding(0, 10, 0, 0); LinearLayout layout = new LinearLayout(context); Button appDot = new Button(context); LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); params1.SetMargins(0, 80, 0, 0); appDot.LayoutParameters = params1; GradientDrawable appDotDrawable = new GradientDrawable(); appDotDrawable.SetColor(255); appDotDrawable.SetCornerRadius(15); appDotDrawable.SetStroke(0, Color.Red); layout.SetGravity(GravityFlags.CenterHorizontal); appDot.Background = appDotDrawable; appDot.LayoutParameters = new ViewGroup.LayoutParams(10, 10); layout.Orientation = Orientation.Vertical; View line = new View(context); line.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 1); line.SetBackgroundColor(Color.Gray); layout.AddView(line); layout.AddView(monthCellText); if (e.Appointments != null && e.Appointments.Count > 0) { layout.AddView(appDot); } frameLayout.AddView(layout); } e.View = frameLayout; } private List<string> subjectCollection = new List<string>(); private List<string> colorCollection = new List<string>(); private List<Calendar> startTimeCollection = new List<Calendar>(); private List<Calendar> endTimeCollection = new List<Calendar>(); private ScheduleAppointmentCollection appointmentCollection; //Creating appointments for ScheduleAppointmentCollection private void GetAppointments() { appointmentCollection = new ScheduleAppointmentCollection(); SetColors(); RandomNumbers(); SetSubjects(); SetStartTime(); SetEndTime(); for (int i = 0; i < 3; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[i]); scheduleAppointment.Subject = subjectCollection[i]; scheduleAppointment.StartTime = startTimeCollection[i]; scheduleAppointment.EndTime = endTimeCollection[i]; appointmentCollection.Add(scheduleAppointment); } } private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("B'Day Party"); subjectCollection.Add("Medical Checkup"); subjectCollection.Add("Conference"); } // adding colors collection private void SetColors() { colorCollection = new List<String>(); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); } private List<int> randomNums = new List<int>(); private void RandomNumbers() { randomNums = new List<int>(); Java.Util.Random rand = new Java.Util.Random(); for (int i = 0; i < 3; i++) { int randomNum = rand.NextInt((11 - 9) + 1) + 9; randomNums.Add(randomNum); } } // adding StartTime collection private void SetStartTime() { startTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; for (int i = 0; i < 3; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[i], 0, 0); startTimeCollection.Add(startTime); } } // adding EndTime collection private void SetEndTime() { endTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; for (int i = 0; i < 3; i++) { Calendar endTime = (Calendar)currentDate.Clone(); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[i] + 2, 0, 0); endTimeCollection.Add(endTime); } } public void OnItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; String selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); if (selectedItem.Equals("Day View")) { sfSchedule.ScheduleView = ScheduleView.DayView; } else if (selectedItem.Equals("Month View")) { sfSchedule.ScheduleView = ScheduleView.MonthView; } } public void OnNothingSelected(object sender, AdapterView.ItemSelectedEventArgs e) { sfSchedule.ScheduleView = ScheduleView.WeekView; } public ScheduleAppointment P2 { get; set; } public View P1 { get; set; } public void Dispose() { if (sfSchedule != null) { sfSchedule.MonthCellLoaded -= SfSchedule_MonthCellLoaded; sfSchedule.AppointmentLoaded -= SfSchedule_AppointmentLoaded; sfSchedule.CellTapped -= SfSchedule_ScheduleTapped; sfSchedule.Dispose(); sfSchedule = null; } if (customView != null) { customView.Dispose(); customView = null; } } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/Swiping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.SfDataGrid; using Android.Graphics; using System.Threading.Tasks; using Android.Util; using Android.Views.InputMethods; using Android.Content.Res; namespace SampleBrowser { public class Swiping : SamplePage { SfDataGrid sfGrid; FrameLayout parentLayout; SwipingViewModel viewModel; int swipedRowIndex; TextView optionHeading; TextView col1; TextView col2; TextView col3; TextView col4; EditText orderIDText; EditText customerIDText; EditText employeeIDText; EditText nameText; Button save; Button cancel; LinearLayout editor; LinearLayout body; LinearLayout bodyRow1; LinearLayout bodyRow2; LinearLayout bodyRow3; LinearLayout bodyRow4; LinearLayout optionView; LinearLayout bottom; SwipeView leftSwipeView; SwipeView rightSwipeView; LinearLayout editView; LinearLayout deleteView; private int swipedRowindex; public override Android.Views.View GetSampleContent(Android.Content.Context context) { parentLayout = new FrameLayout(context); optionHeading = new TextView(context); optionHeading.Gravity = GravityFlags.CenterHorizontal; body = new LinearLayout(context); optionView = new LinearLayout(context); optionView.SetBackgroundColor(Color.Gray); editor = new LinearLayout(context); bottom = new LinearLayout(context); bodyRow1 = new LinearLayout(context); bodyRow1.Orientation = Android.Widget.Orientation.Horizontal; bodyRow1.SetGravity(GravityFlags.CenterHorizontal); bodyRow2 = new LinearLayout(context); bodyRow2.Orientation = Android.Widget.Orientation.Horizontal; bodyRow2.SetGravity(GravityFlags.CenterHorizontal); bodyRow3 = new LinearLayout(context); bodyRow3.Orientation = Android.Widget.Orientation.Horizontal; bodyRow3.SetGravity(GravityFlags.CenterHorizontal); bodyRow4 = new LinearLayout(context); bodyRow4.Orientation = Android.Widget.Orientation.Horizontal; bodyRow4.SetGravity(GravityFlags.CenterHorizontal); col1 = new TextView(context); col1.Text = "Order ID"; col2 = new TextView(context); col2.Text = "Customer ID"; col3 = new TextView(context); col3.Text = "Employee ID"; col4 = new TextView(context); col4.Text = "Name"; orderIDText = new EditText(context); orderIDText.Gravity = GravityFlags.Start; customerIDText = new EditText(context); employeeIDText = new EditText(context); nameText = new EditText(context); save = new Button(context); save.Click += save_Click; cancel = new Button(context); cancel.Click += cancel_Click; editView = new LinearLayout(context); editView.TextAlignment = TextAlignment.Center; editView.Orientation = Android.Widget.Orientation.Horizontal; editView.Click += editView_Click; deleteView = new LinearLayout(context); deleteView.TextAlignment = TextAlignment.Center; deleteView.Orientation = Android.Widget.Orientation.Horizontal; deleteView.Click += swipeViewImage_Click; ImageView editImage = new ImageView(context); editImage.SetImageResource(Resource.Drawable.Edit); editImage.SetBackgroundColor(Color.ParseColor("#42A5F5")); editImage.SetPadding((int)(10 * Resources.System.DisplayMetrics.Density), 0, 0, 0); TextView edit = new TextView(context); edit.Text = "EDIT"; edit.TextAlignment = TextAlignment.Center; edit.Gravity = GravityFlags.Center; edit.SetTextColor(Color.White); //edit.SetPadding((int)(16 * Resources.System.DisplayMetrics.Density), 0, (int)(16 * Resources.System.DisplayMetrics.Density), 0); edit.SetBackgroundColor(Color.ParseColor("#42A5F5")); ImageView deleteImage = new ImageView(context); deleteImage.SetImageResource(Resource.Drawable.Delete); deleteImage.SetBackgroundColor(Color.ParseColor("#EF5350")); deleteImage.SetPadding((int)(5 * Resources.System.DisplayMetrics.Density), 0, 0, 0); TextView delete = new TextView(context); delete.Text = "DELETE"; delete.TextAlignment = TextAlignment.Center; delete.Gravity = GravityFlags.Center; //delete.SetPadding((int)(14 * Resources.System.DisplayMetrics.Density), 0, (int)(10 * Resources.System.DisplayMetrics.Density), (int)(14 * Resources.System.DisplayMetrics.Density)); delete.SetTextColor(Color.White); delete.SetBackgroundColor(Color.ParseColor("#EF5350")); viewModel = new SwipingViewModel(); viewModel.SetRowstoGenerate(100); sfGrid = new SfDataGrid(context); sfGrid.AutoGenerateColumns = false; sfGrid.ItemsSource = (viewModel.OrdersInfo); sfGrid.AllowSwiping = true; sfGrid.RowHeight = 70; sfGrid.ColumnSizer = ColumnSizer.Star; DisplayMetrics metrics = context.Resources.DisplayMetrics; int width = metrics.WidthPixels; sfGrid.MaxSwipeOffset = (int)(100 * metrics.Density); leftSwipeView = new SwipeView(context); rightSwipeView = new SwipeView(context); editView.AddView(editImage, (int)(30 * Resources.System.DisplayMetrics.Density), (int)sfGrid.RowHeight); editView.AddView(edit, sfGrid.MaxSwipeOffset - 30, (int)sfGrid.RowHeight); deleteView.AddView(deleteImage, (int)(30 * Resources.System.DisplayMetrics.Density), (int)sfGrid.RowHeight); deleteView.AddView(delete, sfGrid.MaxSwipeOffset - 30, (int)sfGrid.RowHeight); leftSwipeView.AddView(editView, sfGrid.MaxSwipeOffset, (int)sfGrid.RowHeight); rightSwipeView.AddView(deleteView, sfGrid.MaxSwipeOffset, (int)sfGrid.RowHeight); sfGrid.LeftSwipeView = leftSwipeView; sfGrid.RightSwipeView = rightSwipeView; sfGrid.SwipeEnded += sfGrid_SwipeEnded; sfGrid.SwipeStarted += sfGrid_SwipeStarted; GridTextColumn CustomerID = new GridTextColumn(); CustomerID.MappingName = "CustomerID"; CustomerID.HeaderText = "Customer ID"; GridTextColumn OrderID = new GridTextColumn(); OrderID.MappingName = "OrderID"; OrderID.HeaderText = "Order ID"; OrderID.TextMargin = new Thickness(16, 0, 0, 0); OrderID.HeaderTextMargin= new Thickness(16, 0, 0, 0); GridTextColumn EmployeeID = new GridTextColumn(); EmployeeID.MappingName = "EmployeeID"; EmployeeID.HeaderText = "Employee ID"; GridTextColumn Name = new GridTextColumn(); Name.MappingName = "FirstName"; Name.HeaderText = "Name"; sfGrid.Columns.Add(OrderID); sfGrid.Columns.Add(CustomerID); sfGrid.Columns.Add(EmployeeID); sfGrid.Columns.Add(Name); sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; parentLayout.AddView(sfGrid); editor.SetBackgroundColor(Color.White); editor.Orientation = Android.Widget.Orientation.Vertical; optionHeading.Text = "EDIT DETAILS"; optionHeading.SetTypeface(null, TypefaceStyle.Bold); optionHeading.Gravity = GravityFlags.Center; bodyRow1.AddView(col1, (int)(100 * sfGrid.Resources.DisplayMetrics.Density), (int)(50 * sfGrid.Resources.DisplayMetrics.Density)); bodyRow1.AddView(orderIDText, (int)(100 * sfGrid.Resources.DisplayMetrics.Density), ViewGroup.LayoutParams.WrapContent); bodyRow2.AddView(col2, (int)(100 * sfGrid.Resources.DisplayMetrics.Density), (int)(50 * sfGrid.Resources.DisplayMetrics.Density)); bodyRow2.AddView(customerIDText, (int)(100 * sfGrid.Resources.DisplayMetrics.Density), ViewGroup.LayoutParams.WrapContent); bodyRow3.AddView(col3, (int)(100 * sfGrid.Resources.DisplayMetrics.Density), (int)(50 * sfGrid.Resources.DisplayMetrics.Density)); bodyRow3.AddView(employeeIDText, (int)(100 * sfGrid.Resources.DisplayMetrics.Density), ViewGroup.LayoutParams.WrapContent); bodyRow4.AddView(col4, (int)(100 * sfGrid.Resources.DisplayMetrics.Density), (int)(50 * sfGrid.Resources.DisplayMetrics.Density)); bodyRow4.AddView(nameText, (int)(100 * sfGrid.Resources.DisplayMetrics.Density), ViewGroup.LayoutParams.WrapContent); body.Orientation = Android.Widget.Orientation.Vertical; body.SetGravity(GravityFlags.CenterHorizontal); body.AddView(bodyRow1); body.AddView(bodyRow2); body.AddView(bodyRow3); body.AddView(bodyRow4); save.Text = "Save"; cancel.Text = "Cancel"; bottom.Orientation = Android.Widget.Orientation.Horizontal; bottom.AddView(save); bottom.AddView(cancel); bottom.SetGravity(GravityFlags.Center); editor.AddView(optionHeading); editor.AddView(body); editor.AddView(bottom); optionView.AddView(editor, ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); if (parentLayout.ChildCount == 1) parentLayout.AddView(optionView, 1); parentLayout.GetChildAt(0).Visibility = ViewStates.Visible; parentLayout.GetChildAt(1).Visibility = ViewStates.Invisible; return parentLayout; } void cancel_Click(object sender, EventArgs e) { parentLayout.GetChildAt(1).Visibility = ViewStates.Invisible; parentLayout.GetChildAt(0).Visibility = ViewStates.Visible; // issue fix for XAMARINANDROID-1603 Keyboard will not get collapsed after editing a row in swiping. HideKeyBoard(); } void save_Click(object sender, EventArgs e) { parentLayout.GetChildAt(1).Visibility = ViewStates.Invisible; parentLayout.GetChildAt(0).Visibility = ViewStates.Visible; commitValues(); // issue fix for XAMARINANDROID-1603 Keyboard will not get collapsed after editing a row in swiping. HideKeyBoard(); } void editView_Click(object sender, EventArgs e) { parentLayout.GetChildAt(1).Visibility = ViewStates.Visible; parentLayout.GetChildAt(0).Visibility = ViewStates.Invisible; initializeTextFields(); } private void commitValues() { if (swipedRowindex > 0) { var swipedRowData = this.viewModel.OrdersInfo[this.swipedRowindex - 1]; swipedRowData.OrderID = this.orderIDText.Text; swipedRowData.CustomerID = this.customerIDText.Text; swipedRowData.EmployeeID = this.employeeIDText.Text; swipedRowData.FirstName = this.nameText.Text; } } /// <summary> /// HidesKeyboard /// </summary> private void HideKeyBoard() { var inputView = parentLayout.GetChildAt(1); using (InputMethodManager inputMethodManager = (InputMethodManager)inputView.Context.GetSystemService(Context.InputMethodService)) { inputMethodManager.HideSoftInputFromWindow(inputView.WindowToken, HideSoftInputFlags.None); } } private void initializeTextFields() { if (swipedRowindex > 0) { var swipedRowData = this.viewModel.OrdersInfo[this.swipedRowindex - 1]; orderIDText.Text = swipedRowData.OrderID; this.customerIDText.Text = swipedRowData.CustomerID; this.employeeIDText.Text = swipedRowData.EmployeeID; this.nameText.Text = swipedRowData.FirstName; } } void sfGrid_SwipeStarted(object sender, SwipeStartedEventArgs e) { swipedRowIndex = e.RowIndex; orderIDText.Text = (e.RowData as OrderInfo).OrderID; customerIDText.Text = (e.RowData as OrderInfo).CustomerID; employeeIDText.Text = (e.RowData as OrderInfo).EmployeeID; nameText.Text = (e.RowData as OrderInfo).FirstName; } private void sfGrid_SwipeEnded(object sender, SwipeEndedEventArgs e) { swipedRowindex = e.RowIndex; } void swipeViewImage_Click(object sender, EventArgs e) { viewModel.OrdersInfo.RemoveAt(swipedRowindex - 1); } public override void Destroy() { sfGrid.Dispose(); sfGrid = null; viewModel = null; } } }<file_sep>/Forms/PdfViewer/PdfViewer/Samples/PDFViewerCustomToolbar/PDFViewerCustomToolbar.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfPdfViewer.XForms; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfPdfViewer { [Preserve(AllMembers = true)] public partial class PDFViewerCustomToolbar : SampleView { private bool m_isPageSwitched = false; public PDFViewerCustomToolbar() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Phone) { Content = new PDFViewerCustomToolbar_Phone(); } else if(Device.Idiom == TargetIdiom.Tablet) { Content = new PDFViewerCustomToolbar_Tablet(); } else if(Device.Idiom == TargetIdiom.Desktop) { Content = new PDFViewerCustomToolbar_Desktop(); } m_isPageSwitched = true; } public override void OnAppearing() { if (Device.RuntimePlatform == Device.Android) { if (Device.Idiom == TargetIdiom.Phone) { (Content as PDFViewerCustomToolbar_Phone).RefreshPageAfterSleep(m_isPageSwitched); } else if (Device.Idiom == TargetIdiom.Tablet) { (Content as PDFViewerCustomToolbar_Tablet).RefreshPageAfterSleep(m_isPageSwitched); } } } public override void OnDisappearing() { if (Device.RuntimePlatform == Device.Android) { if (Device.Idiom == TargetIdiom.Phone) { (Content as PDFViewerCustomToolbar_Phone).CollectGC(); } else if (Device.Idiom == TargetIdiom.Tablet) { (Content as PDFViewerCustomToolbar_Tablet).CollectGC(); } m_isPageSwitched = false; } } } } <file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/ShapeAnnotationHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Reflection; using CoreGraphics; using Syncfusion.SfPdfViewer.iOS; using Syncfusion.SfRangeSlider.iOS; using UIKit; namespace SampleBrowser { class ShapeAnnotationHelper { CustomToolbar parent; TextMarkupAnnotationHelper textmarkupHelper; AnnotationHelper annotHelper; internal const float DefaultToolbarHeight = 50f; CGColor separatorgray = UIColor.FromRGBA(red: 0.86f, green: 0.86f, blue: 0.86f, alpha: 1.0f).CGColor; internal UIButton editButton = new UIButton(); internal UIButton shapeButton = new UIButton(); internal const float DefaultEditToolbarHeight = 50f; public ShapeAnnotationHelper(CustomToolbar customtoolbar) { parent = customtoolbar; } public ShapeAnnotationHelper(TextMarkupAnnotationHelper helper, CustomToolbar customtoolbar) { textmarkupHelper = helper; parent = customtoolbar; } public ShapeAnnotationHelper(AnnotationHelper annottoolbar, CustomToolbar customtoolbar) { annotHelper = annottoolbar; parent = customtoolbar; } internal void PdfViewerControl_ShapeAnnotationSelected(object sender, ShapeAnnotationSelectedEventArgs args) { parent.annotation = sender as ShapeAnnotation; parent.shapeView = args.AnnotationType; if (args.AnnotationType == AnnotationMode.Arrow) { parent.arrowToolbar = CreateSeparateAnnotationToolbar(parent.arrowToolbar, parent.arrowEnable, "\ue712", true, (parent.annotation as ShapeAnnotation).Settings.StrokeColor); parent.isOpacityNeeded = true; parent.textToolbarBackButton.RemoveFromSuperview(); parent.Add(parent.arrowToolbar); } if (args.AnnotationType == AnnotationMode.Line) { parent.lineToolbar = CreateSeparateAnnotationToolbar(parent.lineToolbar, parent.lineEnable, "\ue717", true, (parent.annotation as ShapeAnnotation).Settings.StrokeColor); parent.isOpacityNeeded = true; parent.textToolbarBackButton.RemoveFromSuperview(); parent.Add(parent.lineToolbar); } if (args.AnnotationType == AnnotationMode.Rectangle) { parent.rectangleToolbar = CreateSeparateAnnotationToolbar(parent.rectangleToolbar, parent.rectangleEnable, "\ue705", true, (parent.annotation as ShapeAnnotation).Settings.StrokeColor); parent.isOpacityNeeded = true; parent.textToolbarBackButton.RemoveFromSuperview(); parent.Add(parent.rectangleToolbar); } if (args.AnnotationType == AnnotationMode.Circle) { parent.circleToolbar = CreateSeparateAnnotationToolbar(parent.circleToolbar, parent.circleEnable, "\ue71f", true, (parent.annotation as ShapeAnnotation).Settings.StrokeColor); parent.isOpacityNeeded = true; parent.textToolbarBackButton.RemoveFromSuperview(); parent.Add(parent.circleToolbar); } } internal void PdfViewerControl_ShapeAnnotationDeselected(object sender, ShapeAnnotationDeselectedEventArgs args) { parent.annotation = null; parent.isOpacityNeeded = false; if (args.AnnotationType == AnnotationMode.Rectangle) { parent.rectangleToolbar.RemoveFromSuperview(); } else if (args.AnnotationType == AnnotationMode.Circle) { parent.circleToolbar.RemoveFromSuperview(); } else if (args.AnnotationType == AnnotationMode.Line) { parent.lineToolbar.RemoveFromSuperview(); } else if (args.AnnotationType == AnnotationMode.Arrow) { parent.arrowToolbar.RemoveFromSuperview(); } parent.colorToolbar.RemoveFromSuperview(); parent.shapeAnnotationToolbar.RemoveFromSuperview(); parent.isAnnotationToolbarVisible = false; parent.thicknessToolbar.RemoveFromSuperview(); parent.opacityPanel.RemoveFromSuperview(); } internal void ShapeAnnotationButton_TouchUpInside(object sender, EventArgs e) { parent.isOpacityNeeded = true; parent.annotationFrame = parent.Frame; parent.annotationFrame.Height = DefaultToolbarHeight; parent.annotationFrame.Y = parent.parentView.Frame.Height - parent.annotationFrame.Height + 4; parent.shapeAnnotationToolbar.Frame = parent.annotationFrame; parent.shapeAnnotationToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.toolbarBackbutton.Frame = new CGRect(15, 7, 35, 35); else parent.toolbarBackbutton.Frame = new CGRect(5, 7, 35, 35); parent.toolbarBackbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.toolbarBackbutton.TouchUpInside += ToolbarBackbutton_TouchUpInside; parent.toolbarBackbutton.Font = parent.highFont; parent.toolbarBackbutton.SetTitle("\ue708", UIControlState.Normal); parent.toolbarBackbutton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.shapeAnnotationToolbar.Add(parent.toolbarBackbutton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.rectangleAnnotationButton.Frame = new CGRect((240), 7, 35, 35); else parent.rectangleAnnotationButton.Frame = new CGRect((75), 7, 35, 35); parent.rectangleAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.rectangleAnnotationButton.TouchUpInside += RectangleAnnotationButton_TouchUpInside; parent.rectangleAnnotationButton.Font = parent.highFont; parent.rectangleAnnotationButton.SetTitle("\ue705", UIControlState.Normal); parent.rectangleAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.shapeAnnotationToolbar.Add(parent.rectangleAnnotationButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.circleAnnotationButton.Frame = new CGRect((parent.annotationToolbar.Frame.Width - 100) / 2, 7, 35, 35); else parent.circleAnnotationButton.Frame = new CGRect(145, 7, 35, 35); parent.circleAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.circleAnnotationButton.TouchUpInside += CircleAnnotationButton_TouchUpInside; parent.circleAnnotationButton.Font = parent.highFont; parent.circleAnnotationButton.SetTitle("\ue71f", UIControlState.Normal); parent.circleAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.shapeAnnotationToolbar.Add(parent.circleAnnotationButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.lineAnnotationButton.Frame = new CGRect((parent.annotationToolbar.Frame.Width + 100) / 2, 7, 35, 35); else parent.lineAnnotationButton.Frame = new CGRect(215, 7, 35, 35); parent.lineAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.lineAnnotationButton.TouchUpInside += LineAnnotationButton_TouchUpInside; parent.lineAnnotationButton.Font = parent.highFont; parent.lineAnnotationButton.SetTitle("\ue717", UIControlState.Normal); parent.lineAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.shapeAnnotationToolbar.Add(parent.lineAnnotationButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.arrowAnnotationButton.Frame = new CGRect((parent.annotationToolbar.Frame.Width - 250), 7, 35, 35); else parent.arrowAnnotationButton.Frame = new CGRect(275, 7, 35, 35); parent.arrowAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.arrowAnnotationButton.TouchUpInside += ArrowAnnotationButton_TouchUpInside; parent.arrowAnnotationButton.Font = parent.highFont; parent.arrowAnnotationButton.SetTitle("\ue712", UIControlState.Normal); parent.arrowAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.shapeAnnotationToolbar.Add(parent.arrowAnnotationButton); parent.shapeAnnotationToolbar = parent.UpdateToolbarBorder(parent.shapeAnnotationToolbar, parent.annotationFrame); parent.Add(parent.shapeAnnotationToolbar); } private void RectangleAnnotationButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.AnnotationMode = AnnotationMode.Rectangle; parent.isOpacityNeeded = true; parent.shapeAnnotationToolbar.RemoveFromSuperview(); parent.isAnnotationToolbarVisible = true; parent.shapeDeleteButton.RemoveFromSuperview(); parent.shapeThicknessButton.RemoveFromSuperview(); parent.shapeColorButton.RemoveFromSuperview(); parent.rectangleToolbar = CreateSeparateAnnotationToolbar(parent.rectangleToolbar, parent.rectangleEnable, "\ue705", false, parent.pdfViewerControl.AnnotationSettings.Rectangle.Settings.StrokeColor); parent.Add(parent.rectangleToolbar); } private void CircleAnnotationButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.AnnotationMode = AnnotationMode.Circle; parent.isOpacityNeeded = true; parent.shapeAnnotationToolbar.RemoveFromSuperview(); parent.isAnnotationToolbarVisible = true; parent.shapeDeleteButton.RemoveFromSuperview(); parent.shapeThicknessButton.RemoveFromSuperview(); parent.shapeColorButton.RemoveFromSuperview(); parent.circleToolbar = CreateSeparateAnnotationToolbar(parent.circleToolbar, parent.circleEnable, "\ue71f", false, parent.pdfViewerControl.AnnotationSettings.Circle.Settings.StrokeColor); parent.Add(parent.circleToolbar); } private void LineAnnotationButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.AnnotationMode = AnnotationMode.Line; parent.isOpacityNeeded = true; parent.shapeAnnotationToolbar.RemoveFromSuperview(); parent.isAnnotationToolbarVisible = true; parent.shapeDeleteButton.RemoveFromSuperview(); parent.shapeThicknessButton.RemoveFromSuperview(); parent.shapeColorButton.RemoveFromSuperview(); parent.lineToolbar = CreateSeparateAnnotationToolbar(parent.lineToolbar, parent.lineEnable, "\ue717", false, parent.pdfViewerControl.AnnotationSettings.Line.Settings.StrokeColor); parent.Add(parent.lineToolbar); } private void ArrowAnnotationButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.AnnotationMode = AnnotationMode.Arrow; parent.isOpacityNeeded = true; parent.shapeAnnotationToolbar.RemoveFromSuperview(); parent.isAnnotationToolbarVisible = true; parent.shapeDeleteButton.RemoveFromSuperview(); parent.shapeThicknessButton.RemoveFromSuperview(); parent.shapeColorButton.RemoveFromSuperview(); parent.arrowToolbar = CreateSeparateAnnotationToolbar(parent.arrowToolbar, parent.arrowEnable, "\ue712", false, parent.pdfViewerControl.AnnotationSettings.Arrow.Settings.StrokeColor); parent.Add(parent.arrowToolbar); } internal UIView CreateSeparateAnnotationToolbar(UIView separateToolbar, UIButton enableLabel, string imageName, bool isSelected, UIColor colorButtonColor) { parent.isOpacityNeeded = true; parent.separateAnnotationFrame = parent.Frame; parent.separateAnnotationFrame.Height = DefaultToolbarHeight; parent.separateAnnotationFrame.Y = parent.parentView.Frame.Height - parent.separateAnnotationFrame.Height + 4; separateToolbar.Frame = parent.separateAnnotationFrame; separateToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); enableLabel.Frame = new CGRect(65, 7, 35, 35); enableLabel.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; enableLabel.Font = parent.highFont; enableLabel.SetTitle(imageName, UIControlState.Normal); enableLabel.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); separateToolbar.Add(enableLabel); parent.IsSelected = isSelected; if (!isSelected) { parent.textToolbarBackButton.Frame = new CGRect(parent.parentView.Frame.Width - 45, 7, 35, 35); parent.textToolbarBackButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.textToolbarBackButton.TouchUpInside += ToolbarBackbutton_TouchUpInside; parent.textToolbarBackButton.Font = parent.highFont; parent.textToolbarBackButton.SetTitle("\ue715", UIControlState.Normal); parent.textToolbarBackButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); separateToolbar.Add(parent.textToolbarBackButton); parent.shapeColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 95, 7, 30, 30); parent.shapeThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 155, 7, 30, 30); } else { parent.shapeDeleteButton.Frame = new CGRect(parent.parentView.Frame.Width - 45, 7, 35, 35); parent.shapeDeleteButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.shapeDeleteButton.TouchUpInside += DeleteButton_TouchUpInside; ; parent.shapeDeleteButton.Font = parent.highFont; parent.shapeDeleteButton.SetTitle("\ue714", UIControlState.Normal); parent.shapeDeleteButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); separateToolbar.Add(parent.shapeDeleteButton); parent.shapeColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 95, 7, 30, 30); parent.shapeThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 155, 7, 30, 30); } parent.shapeThicknessButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.shapeThicknessButton.Font = parent.highFont; parent.shapeThicknessButton.SetTitle("\ue722", UIControlState.Normal); parent.shapeThicknessButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); separateToolbar.Add(parent.shapeThicknessButton); parent.shapeColorButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; nfloat r, g, b, a; colorButtonColor.GetRGBA(out r, out g, out b, out a); UIColor color = new UIColor(r, g, b, (nfloat)1); parent.shapeColorButton.BackgroundColor = color; separateToolbar.Add(parent.shapeColorButton); separateToolbar = parent.UpdateToolbarBorder(separateToolbar, parent.separateAnnotationFrame); return separateToolbar; } private void ToolbarBackbutton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.AnnotationMode = AnnotationMode.None; parent.isOpacityNeeded = false; parent.textAnnotationToolbar.RemoveFromSuperview(); parent.colorToolbar.RemoveFromSuperview(); parent.highlightToolbar.RemoveFromSuperview(); parent.editStampAnnotationToolbar.RemoveFromSuperview(); parent.strikeOutToolbar.RemoveFromSuperview(); parent.underlineToolbar.RemoveFromSuperview(); parent.opacityPanel.RemoveFromSuperview(); parent.inkAnnotationSessionToolbar.RemoveFromSuperview(); parent.textAnnotationToolbar.RemoveFromSuperview(); parent.inkAnnotationToolbar.RemoveFromSuperview(); parent.annotationToolbar.RemoveFromSuperview(); parent.thicknessToolbar.RemoveFromSuperview(); parent.editTextAnnotationToolbar.RemoveFromSuperview(); parent.lineToolbar.RemoveFromSuperview(); parent.arrowToolbar.RemoveFromSuperview(); parent.circleToolbar.RemoveFromSuperview(); parent.rectangleToolbar.RemoveFromSuperview(); parent.shapeAnnotationToolbar.RemoveFromSuperview(); parent.isAnnotationToolbarVisible = false; parent.isColorSelected = false; parent.isThicknessTouched = false; parent.isOpacityNeeded = false; parent.Add(parent.shapeAnnotationToolbar); parent.isColorSelected = false; parent.opacityPanel.RemoveFromSuperview(); parent.toolbarBackbutton.RemoveFromSuperview(); } private void DeleteButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.RemoveAnnotation(parent.annotation); parent.annotHelper.RemoveAllToolbars(false); } } }<file_sep>/iOS/SampleBrowser/Samples/DataSource/Helper/OptionView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using System; using System.Collections.Generic; using System.Text; using UIKit; using Syncfusion.DataSource; namespace SampleBrowser { public partial class DataSourceOptionsView : UIView { private DataSourceGettingStartedViewModel filtermodel; private UITableView table; private UISearchBar bar; private UITableView filterconditiontable; List<string> items; DataSourceGettingStarted ParentView; static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public DataSourceOptionsView() { items = new List<string>(); table = new UITableView(); filterconditiontable = new UITableView(); table.SectionIndexTrackingBackgroundColor = UIColor.FromRGB(0, 121, 255); filterconditiontable.AllowsSelection = true; this.AddSubview(filterconditiontable); this.AddSubview(table); } public DataSourceOptionsView(DataSourceGettingStartedViewModel model, UISearchBar bar, DataSourceGettingStarted parentView) : this() { this.ParentView = parentView; this.filtermodel = model; var columnnames = filtermodel.BookInfo.GetType().GetGenericArguments()[0].GetProperties(); this.bar = bar; foreach (var propety in columnnames) { items.Add(propety.Name); } table.Source = new ColumnOptionsTableSource(items); filterconditiontable.Source = new DataSourceFilterOptionsTableSource(new List<string>() { "Contains", "Equals", "Not Equals" }); this.AddSubview(filterconditiontable); this.AddSubview(table); } public override void RemoveFromSuperview() { base.RemoveFromSuperview(); filtermodel.SelectedColumn = (table.Source as ColumnOptionsTableSource).selectedItem; filtermodel.SelectedCondition = (filterconditiontable.Source as DataSourceFilterOptionsTableSource).selecteditem; if (filtermodel.SelectedColumn != null && filtermodel.SelectedCondition != null) { this.bar.Placeholder = "Search " + filtermodel.SelectedColumn + " with " + filtermodel.SelectedCondition; if (this.bar.Text != "") this.ParentView.OnFilterChanged(); } else if ((filtermodel.SelectedColumn != null && filtermodel.SelectedCondition == null) || (filtermodel.SelectedColumn == null && filtermodel.SelectedCondition != null)) { var alert = UIAlertController.Create("Error", "Should Select Both ColumnName and Condition Type", UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null)); UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(alert, true, null); } } public override void LayoutSubviews() { table.Frame = (new CGRect(0, 0, this.Frame.Width, (this.Frame.Height / 2) + 13)); filterconditiontable.Frame = (new CGRect(0, table.Bounds.Bottom + 2, this.Frame.Width, this.Frame.Height)); base.LayoutSubviews(); } } public class SortingPickerModel : UIPickerViewModel { string[] array = new string[]{"Ascending", "Descending"}; DataSource dataSource; UITableView tableView; public SortingPickerModel(DataSource datasource, UITableView tableview) { dataSource = datasource; tableView = tableview; } public override nint GetComponentCount (UIPickerView pickerView) { return 1; } public override nint GetRowsInComponent (UIPickerView pickerView, nint component) { return 2; } public override string GetTitle (UIPickerView pickerView, nint row, nint component) { return array[row]; } public override void Selected (UIPickerView pickerView, nint row, nint component) { dataSource.SortDescriptors.Clear (); if (row == 0) dataSource.SortDescriptors.Add (new SortDescriptor ("ContactName", Syncfusion.DataSource.ListSortDirection.Ascending)); else dataSource.SortDescriptors.Add (new SortDescriptor ("ContactName", Syncfusion.DataSource.ListSortDirection.Descending)); tableView.ReloadData (); } public override UIView GetView (UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel (); label.Font = UIFont.SystemFontOfSize (14f); label.Text = array [row]; label.TextAlignment = UITextAlignment.Center; return label; } } public enum StackOrientation { Vertical, Horizontal } public class StackLayout : UIView { public StackOrientation Orientation { get; set;} public StackLayout() { } public override void LayoutSubviews () { nfloat x = 0; nfloat y = 0; foreach (var child in this.Subviews) { if (this.Orientation == StackOrientation.Horizontal) { child.Frame = new CGRect (0, 0, child.Frame.Width, this.Frame.Height); x = child.Frame.Width + 5; } else if (this.Orientation == StackOrientation.Vertical) { child.Frame = new CGRect (0, 0, this.Frame.Width, child.Frame.Height); y = child.Frame.Width + 5; } } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Pyramid.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class Pyramid : SamplePage { SfChart chart; List<String> overflowMode; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Food Comparison Chart"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.OverflowMode = ChartLegendOverflowMode.Wrap; PyramidSeries pyramid = new PyramidSeries(); pyramid.XBindingPath = "XValue"; pyramid.YBindingPath = "YValue"; pyramid.ItemsSource = MainPage.GetPyramidData(); pyramid.ColorModel.ColorPalette = ChartColorPalette.Natural; pyramid.TooltipEnabled = true; pyramid.StrokeWidth = 1; pyramid.StrokeColor = Color.White; chart.Series.Add(pyramid); ChartTooltipBehavior tooltipBehavior = new ChartTooltipBehavior(); tooltipBehavior.LabelFormat = "##.## cal"; chart.Behaviors.Add(tooltipBehavior); Spinner selectLabelMode = new Spinner(context, SpinnerMode.Dialog); overflowMode = new List<String>() { "Wrap", "Scroll" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, overflowMode); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += SelectLabelMode_ItemSelected; LinearLayout linearLayout = new LinearLayout(context); linearLayout.SetPadding(20, 0, 20, 30); linearLayout.SetBackgroundColor(Color.Rgb(236, 235, 242)); linearLayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); linearLayout.Orientation = Orientation.Vertical; linearLayout.SetBackgroundColor(Color.White); linearLayout.AddView(selectLabelMode); linearLayout.AddView(chart); return linearLayout; } private void SelectLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = overflowMode[e.Position]; if (selectedItem.Equals("Wrap")) { chart.Legend.OverflowMode = Com.Syncfusion.Charts.ChartLegendOverflowMode.Wrap; } else if (selectedItem.Equals("Scroll")) { chart.Legend.OverflowMode = Com.Syncfusion.Charts.ChartLegendOverflowMode.Scroll; } } } }<file_sep>/Forms/Rotator/Rotator/Samples/RotatorViewModel.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser { internal class RotatorViewModel { public RotatorViewModel() { if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { ImageCollection.Add(new RotatorModel("Duck0.png")); ImageCollection.Add(new RotatorModel("Duck1.png")); ImageCollection.Add(new RotatorModel("Duck2.png")); ImageCollection.Add(new RotatorModel("Duck3.png")); ImageCollection.Add(new RotatorModel("Duck4.png")); ImageCollection.Add(new RotatorModel("Duck5.png")); } } private List<RotatorModel> imageCollection = new List<RotatorModel>(); public List<RotatorModel> ImageCollection { get { return imageCollection; } set { imageCollection = value; } } } } <file_sep>/iOS/SampleBrowser/Samples/NavigationDrawer/NavigationDrawer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfNavigationDrawer.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class NavigationDrawer : SampleView { private string selectedType; UILabel positionLabel,transitionLabel; UIButton positionbutton = new UIButton (); UILabel usernameLabel; UIButton transitionbutton = new UIButton (); UIButton doneButton=new UIButton(); UIPickerView selectionPicker1, selectionPicker2; public UITableView table; public string[] tableItems; UIView HeaderView; UIImageView userImg; static public SFNavigationDrawer sideMenuController; static public MainPageView mainView; private readonly IList<string> positionAlignmentlist = new List<string> { "Left", "Right", "Top", "Bottom" }; private readonly IList<string> transitionAlignmentList = new List<string> { "SlideOnTop", "Reveal", "Push" }; public NavigationDrawer () { selectionPicker1 = new UIPickerView (); selectionPicker2 = new UIPickerView (); this.OptionView = new UIView (); PickerModel model = new PickerModel (positionAlignmentlist); selectionPicker1.Model = model; PickerModel model1 = new PickerModel (transitionAlignmentList); selectionPicker2.Model = model1; positionLabel = new UILabel (); positionbutton = new UIButton (); transitionbutton = new UIButton (); transitionLabel = new UILabel (); positionLabel.Text = "Position"; positionLabel.TextColor = UIColor.Black; positionLabel.TextAlignment = UITextAlignment.Left; transitionLabel.Text = "Transition"; transitionLabel.TextColor = UIColor.Black; transitionLabel.TextAlignment = UITextAlignment.Left; positionbutton.SetTitle("Left",UIControlState.Normal); positionbutton.SetTitleColor(UIColor.Black,UIControlState.Normal); positionbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; positionbutton.Layer.CornerRadius = 8; positionbutton.Layer.BorderWidth = 2; positionbutton.TouchUpInside += ShowPicker1; positionbutton.Layer.BorderColor =UIColor.FromRGB(246,246,246).CGColor; transitionbutton.SetTitle("SlideOnTop",UIControlState.Normal); transitionbutton.SetTitleColor(UIColor.Black,UIControlState.Normal); transitionbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; transitionbutton.Layer.CornerRadius = 8; transitionbutton.Layer.BorderWidth = 2; transitionbutton.TouchUpInside += ShowPicker2; transitionbutton.Layer.BorderColor =UIColor.FromRGB(246,246,246).CGColor; doneButton.SetTitle("Done\t",UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black,UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(246,246,246); model.PickerChanged += SelectedIndexChanged; model1.PickerChanged += SelectedIndexChanged1; selectionPicker1.ShowSelectionIndicator = true; selectionPicker1.Hidden = true; selectionPicker2.ShowSelectionIndicator = true; selectionPicker2.Hidden = true; // this.AddSubview (this); } public override void LayoutSubviews () { //NavigationDrawer initialize sideMenuController = new SFNavigationDrawer (); sideMenuController.DrawerHeaderHeight = 100; mainView = new MainPageView(this.Frame); UIButton menubutton=new UIButton(); menubutton.Frame =new CGRect (10, 10, 30, 30); menubutton.SetBackgroundImage (new UIImage ("Images/menu.png"), UIControlState.Normal); mainView.AddSubview (menubutton); sideMenuController.ContentView = mainView; sideMenuController.DrawerWidth = (int)((UIScreen.MainScreen.Bounds.Size.Width * 60) / 100); sideMenuController.DrawerHeight = (int)((UIScreen.MainScreen.Bounds.Size.Height * 60) / 100); mainView.Frame = new CGRect (0, 0, UIScreen.MainScreen.Bounds.Size.Width, UIScreen.MainScreen.Bounds.Size.Height); //Menu Page Design table = new UITableView(new CGRect(0, 0, this.Frame.Width, this.Frame.Height)); // defaults to Plain style tableItems = new string[] {"Home","Profile","Inbox","Outbox","Sent Items","Trash"}; TableSource tablesource = new TableSource(tableItems); tablesource.customise = false; table.Source = tablesource; this.BackgroundColor = UIColor.FromRGB(63,134,246); HeaderView = new UIView (); HeaderView.Frame = new CGRect (0, 0, this.Frame.Width, 100); HeaderView.BackgroundColor = UIColor.FromRGB (49, 173, 225); UIView centerview = new UIView (); centerview.Frame = new CGRect (0, 100, this.Frame.Width, 500); centerview.Add (table); usernameLabel = new UILabel (); usernameLabel.Frame =new CGRect ((sideMenuController.DrawerWidth/2)-50, 70, this.Frame.Width, 30); usernameLabel.Text="<NAME>"; usernameLabel.TextColor = UIColor.White; usernameLabel.TextAlignment = UITextAlignment.Left; HeaderView.AddSubview (usernameLabel); userImg=new UIImageView(); userImg.Frame =new CGRect ((sideMenuController.DrawerWidth/2)-25, 15, 50, 50); userImg.Image = new UIImage ("Images/User.png"); HeaderView.AddSubview (userImg); sideMenuController.DrawerHeaderView = HeaderView; sideMenuController.DrawerContentView = centerview; sideMenuController.Position = SFNavigationDrawerPosition.SFNavigationDrawerPositionLeft; this.AddSubview (sideMenuController); menubutton.TouchDown+= (object sender, System.EventArgs e) => { sideMenuController.ToggleDrawer(); }; foreach (var view in this.Subviews) { sideMenuController.Frame = new CGRect(0,0,this.Frame.Width,this.Frame.Height); positionLabel.Frame = new CGRect (this.Frame.X +10, 0, PopoverSize.Width - 20, 30); positionbutton.Frame=new CGRect(this.Frame.X +10, 40, PopoverSize.Width - 20, 30); transitionLabel.Frame = new CGRect (this.Frame.X +10, 90, PopoverSize.Width - 20, 30); transitionbutton.Frame=new CGRect(this.Frame.X +10,130, PopoverSize.Width - 20, 30); selectionPicker1.Frame = new CGRect (0, PopoverSize.Height/2, PopoverSize.Width, PopoverSize.Height/3); selectionPicker2.Frame = new CGRect (0, PopoverSize.Height/2, PopoverSize.Width , PopoverSize.Height/3); doneButton.Frame = new CGRect (0, PopoverSize.Height/2.5, PopoverSize.Width, 40); } this.optionView (); } public void optionView() { this.OptionView.AddSubview (positionLabel); this.OptionView.AddSubview (positionbutton); this.OptionView.AddSubview (transitionLabel); this.OptionView.AddSubview (transitionbutton); this.OptionView.AddSubview (selectionPicker1); this.OptionView.AddSubview (selectionPicker2); this.OptionView.AddSubview (doneButton); } void ShowPicker1 (object sender, EventArgs e) { doneButton.Hidden = false; selectionPicker1.Hidden = false; selectionPicker2.Hidden = true; transitionbutton.Hidden = false; } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; selectionPicker2.Hidden = true; selectionPicker1.Hidden = true; transitionbutton.Hidden = false; } void ShowPicker2 (object sender, EventArgs e) { doneButton.Hidden = false; selectionPicker1.Hidden = true; selectionPicker2.Hidden = false; transitionbutton.Hidden = false; } private void SelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; positionbutton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Left") { sideMenuController.Position = SFNavigationDrawerPosition.SFNavigationDrawerPositionLeft; } else if (selectedType == "Top") { sideMenuController.Position = SFNavigationDrawerPosition.SFNavigationDrawerPositionTop; } else if (selectedType == "Bottom") { sideMenuController.Position = SFNavigationDrawerPosition.SFNavigationDrawerPositionBottom; } else { sideMenuController.Position=SFNavigationDrawerPosition.SFNavigationDrawerPositionRight; } } private void SelectedIndexChanged1(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; transitionbutton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "SlideOnTop") { sideMenuController.Transition = SFNavigationDrawerTransition.SFNavigationDrawerTransitionSlideOnTop; } else if (selectedType == "Reveal") { sideMenuController.Transition = SFNavigationDrawerTransition.SFNavigationDrawerTransitionReveal; } else{ sideMenuController.Transition = SFNavigationDrawerTransition.SFNavigationDrawerTransitionPush; } } } } <file_sep>/Forms/XlsIO/XlsIO/Samples/FindAndReplacePage/FindAndReplacePage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XlsIO; using Xamarin.Forms; namespace SampleBrowser.XlsIO { /// <summary> /// This class is used to find and replace a value within the worksheet. /// </summary> public partial class FindAndReplacePage : SampleView { public FindAndReplacePage() { InitializeComponent(); this.picker.Items.Add("Berlin"); this.picker.Items.Add("8000"); this.picker.Items.Add("Representative"); this.picker.SelectedIndex = 0; if (Device.Idiom != TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP)) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGetInputTemplate.HorizontalOptions = LayoutOptions.Start; Error.HorizontalOptions = LayoutOptions.Start; Error.VerticalOptions = LayoutOptions.Center; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnGetInputTemplate.VerticalOptions = LayoutOptions.Center; this.btnGetInputTemplate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; Error.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; Error.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGetInputTemplate.VerticalOptions = LayoutOptions.Center; } Error.Text = string.Empty; Error.TextColor = Color.Red; } internal void ReplaceTextChanged(object sender, TextChangedEventArgs e) { Error.Text = string.Empty; } internal void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; // Initializing Workbook Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = null; #if COMMONSB fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ReplaceOptions.xlsx"); #else fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ReplaceOptions.xlsx"); #endif IWorkbook workbook = application.Workbooks.Open(fileStream); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; int replaceIndex = this.picker.SelectedIndex; string replaceText; switch (replaceIndex) { default: case 0: replaceText = "Berlin"; break; case 1: replaceText = "8000"; break; case 2: replaceText = "Representative"; break; } ExcelFindOptions option = ExcelFindOptions.None; if (switch1.IsToggled) { option |= ExcelFindOptions.MatchCase; } if (switch2.IsToggled) { option |= ExcelFindOptions.MatchEntireCellContent; } MemoryStream stream = null; try { if (entry.Text != null && entry.Text != string.Empty) { sheet.Replace(replaceText, entry.Text, option); } stream = new MemoryStream(); workbook.SaveAs(stream); } catch (Exception ex) { string exception = ex.ToString(); Error.Text = "Given string is invalid."; } workbook.Version = ExcelVersion.Excel2013; workbook.Close(); excelEngine.Dispose(); if (stream != null) { if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("FindAndReplace.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("FindAndReplace.xlsx", "application/msexcel", stream); } } } internal void OnButtonClicked1(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; // Initializing Workbook Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = null; #if COMMONSB fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ReplaceOptions.xlsx"); #else fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ReplaceOptions.xlsx"); #endif IWorkbook workbook = application.Workbooks.Open(fileStream); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.xlsx", "application/msexcel", stream); } } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/IncrementalLoading.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Views; using System.Globalization; using Android.Graphics; namespace SampleBrowser { public class IncrementalLoading:SamplePage { SfDataGrid sfGrid; IncrementalLoadingViewModel viewModel; public override Android.Views.View GetSampleContent (Android.Content.Context context) { sfGrid = new SfDataGrid (context); sfGrid.SelectionMode = SelectionMode.Single; viewModel = new IncrementalLoadingViewModel (context); sfGrid.GridStyle.AlternatingRowColor = Color.Rgb (206, 206, 206); sfGrid.ItemsSource = viewModel.GridSource; sfGrid.AutoGeneratingColumn += GridAutoGeneratingColumns; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; return sfGrid; } public override Android.Views.View GetPropertyWindowLayout (Android.Content.Context context) { return base.GetPropertyWindowLayout (context); } void GridAutoGeneratingColumns (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "OrderID"; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; } else if (e.Column.MappingName == "OrderDate") { e.Column.HeaderText = "Order Date"; e.Column.Format = "d"; } else if (e.Column.MappingName == "RequiredDate") { e.Column.HeaderText = "Required Date"; e.Column.Format = "d"; } else if (e.Column.MappingName == "ShippedDate") { e.Column.HeaderText = "Shipped Date"; e.Column.Format = "d"; } else if (e.Column.MappingName == "ShipVia") { e.Column.HeaderText = "Ship Via"; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); } else if (e.Column.MappingName == "ShipName") { e.Column.HeaderText = "Ship Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ShipAddress") { e.Column.HeaderText = "Ship Address"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ShipRegion") { e.Column.HeaderText = "Ship Region"; } else if (e.Column.MappingName == "ShipPostalCode") { e.Column.HeaderText = "Ship Postal Code"; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Order_Details") { e.Column.HeaderText = "Order Details"; e.Column.TextAlignment = GravityFlags.CenterVertical; } } public override void Destroy () { this.sfGrid.AutoGeneratingColumn -= GridAutoGeneratingColumns; this.sfGrid.Dispose (); this.sfGrid = null; this.viewModel.Dispose(); this.viewModel = null; } } } <file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/PullToRefreshView/Model/WeatherDataRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "WeatherDataRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class used to assign collection values for a Model properties /// </summary> public class WeatherDataRepository { } }<file_sep>/Forms/Calendar/Calendar/Samples/Themes/Behaviors/CalendarThemesBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using SampleBrowser.Core; using Syncfusion.SfCalendar.XForms; using Xamarin.Forms; namespace SampleBrowser.SfCalendar { internal class CalendarThemesBehavior : Behavior<SampleView> { private Syncfusion.SfCalendar.XForms.SfCalendar calendar; private Grid grid; private double calendarWidth = 500; private int padding = 50; protected override void OnAttachedTo(SampleView bindable) { base.OnAttachedTo(bindable); this.calendar = bindable.Content.FindByName<Syncfusion.SfCalendar.XForms.SfCalendar>("calendar"); this.grid = bindable.Content.FindByName<Grid>("grid"); if (Device.RuntimePlatform == "UWP") { this.grid.HorizontalOptions = LayoutOptions.Center; this.grid.WidthRequest = this.calendarWidth; bindable.SizeChanged += this.Bindable_SizeChanged; } } private void Bindable_SizeChanged(object sender, EventArgs e) { var sampleView = sender as SampleView; if (sampleView.Width < this.calendarWidth + padding) { this.grid.WidthRequest = sampleView.Width - padding; } } protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); if (Device.RuntimePlatform == "UWP") { bindable.SizeChanged -= this.Bindable_SizeChanged; } this.grid = null; this.calendar = null; } } }<file_sep>/Forms/Switch/Switch/Samples/GettingStartedSample/View/GettingStartedSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.Buttons; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: ExportFont("switch.ttf", Alias = "Switch")] namespace SampleBrowser.SfSwitch { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class GettingStartedSample : SampleView { #region Members private ObservableCollection<AppModel> listCollection = new ObservableCollection<AppModel>(); private bool canNotify; #endregion #region properties /// <summary> /// Collection which contains the items that will be enabled and disabled by the segment control to display on the main segment control. /// </summary> public ObservableCollection<AppModel> ListCollection { get { return listCollection; } set { listCollection = value; } } public bool CanNotify { get { return canNotify; } set { if (canNotify != value) { canNotify = value; raisepropertyChanged("CanNotify"); } } } #endregion #region Constructor /// <summary> /// Token constructor /// </summary> public GettingStartedSample() { InitializeComponent(); if (Device.RuntimePlatform == Device.iOS) { switchRow.Height = 70; } if (Device.Idiom == TargetIdiom.Desktop) { MainGrid.VerticalOptions = LayoutOptions.Start; MainGrid.HorizontalOptions = LayoutOptions.Start; MainGrid.HeightRequest = 500; MainGrid.WidthRequest = 500; } ListCollection.Add(new AppModel(this) { Name = "Facebook", IconColor = Color.FromHex("FF355088"), Icon = "F", CanNotify = true }); ListCollection.Add(new AppModel(this) { Name = "Twitter", IconColor = Color.FromHex("FF1192DF"), Icon = "T", CanNotify = false }); ListCollection.Add(new AppModel(this) { Name = "YouTube", IconColor = Color.FromHex("FFD41D1F"), Icon = "Y", CanNotify = true }); ListCollection.Add(new AppModel(this) { Name = "Instagram", IconColor = Color.FromHex("FFE1306C"), Icon = "I", CanNotify = false }); ListCollection.Add(new AppModel(this) { Name = "Gmail", IconColor = Color.FromHex("FFE9594E"), Icon = "Z", CanNotify = true }); ListCollection.Add(new AppModel(this) { Name = "LinkedIn", IconColor = Color.FromHex("FF0172B6"), Icon = "L", CanNotify = true }); ListCollection.Add(new AppModel(this) { Name = "Skype", IconColor = Color.FromHex("FF1EA5DD"), Icon = "S", CanNotify = true }); this.BindingContext = this; } #endregion #region Methods /// <summary> /// Handles the item tapped. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> private void Handle_ItemTapped(object sender, Xamarin.Forms.ItemTappedEventArgs e) { (sender as ListView).SelectedItem = null; } #endregion #region PropertyChanged public event PropertyChangedEventHandler propertyChanged; private void raisepropertyChanged(string property) { if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(property)); } } #endregion #region Dispose /// <summary> /// Dispose method /// </summary> public void Dispose() { } #endregion bool? oldValue = null; private async void AllAppSwitch_StateChanged(object sender, SwitchStateChangedEventArgs e) { if (!setAllAppsSwitchState) { return; } else { if (allAppSwitch.IsOn == null) { allAppSwitch.IsOn = oldValue; } } await Task.Delay(1); if (this.allAppSwitch.IsOn == true) { foreach (var appModel in this.ListCollection) { appModel.CanNotify = true; } } else if (this.allAppSwitch.IsOn == false) { foreach (var appModel in this.ListCollection) { appModel.CanNotify = false; } } oldValue = this.allAppSwitch.IsOn; } bool setAllAppsSwitchState = true; private async void SfSwitch_StateChanged(object sender, SwitchStateChangedEventArgs e) { setAllAppsSwitchState = false; bool hasTrue = false; bool hasFalse = false; foreach (var appModel in this.ListCollection) { if (appModel.CanNotify == true) { hasTrue = true; } if (appModel.CanNotify == false) { hasFalse = true; } } if (hasFalse && hasTrue) { this.allAppSwitch.AllowIndeterminateState = true; this.allAppSwitch.IsOn = null; } else if (hasFalse && !hasTrue) { this.allAppSwitch.AllowIndeterminateState = false; this.allAppSwitch.IsOn = false; } else if (!hasFalse && hasTrue) { this.allAppSwitch.AllowIndeterminateState = false; this.allAppSwitch.IsOn = true; } await Task.Delay(250); setAllAppsSwitchState = true; } } #region App Model /// <summary> /// Model class for the tokens /// </summary> public class AppModel : INotifyPropertyChanged { #region Members private bool? canNotify; private String name; private String icon; private Color iconColor; private Color selectedColor = Color.FromHex("#E4E4E4"); private Color capColor = Color.FromHex("#C2C1C1"); private ObservableCollection<SfSegmentItem> dataCollection = new ObservableCollection<SfSegmentItem>(); private GettingStartedSample tokensObject; #endregion #region Properties /// <summary> /// Get or set the name for the items present in the list. /// </summary> public String Name { get { return name; } set { name = value; raisepropertyChanged("Name"); } } /// <summary> /// get or set the icons inside the listview /// </summary> public String Icon { get { return icon; } set { icon = value; raisepropertyChanged("Icon"); } } /// <summary> /// Get or set the color for the icons used inside the listview. /// </summary> public Color IconColor { get { return iconColor; } set { iconColor = value; raisepropertyChanged("IconColor"); } } public bool? CanNotify { get { return canNotify; } set { if (canNotify != value) { canNotify = value; raisepropertyChanged("CanNotify"); } } } /// <summary> /// Data collection for the items used inside the listview /// </summary> public ObservableCollection<SfSegmentItem> DataCollection { get { return dataCollection; } set { dataCollection = value; } } #endregion #region Constructor /// <summary> /// Constructor initialising for the App model class /// </summary> /// <param name="tokens"></param> public AppModel(GettingStartedSample tokens) { tokensObject = tokens; } #endregion #region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void raisepropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } #endregion } #endregion /// <summary> /// To get the platformm specfic path for font icon. /// </summary> public class SwitchConverter : IValueConverter { /// <summary> /// Converts default value to font value /// </summary> /// <param name="value">the value</param> /// <param name="targetType">the targetType</param> /// <param name="parameter">the parameter</param> /// <param name="culture">the culture</param> /// <returns>convert value</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (Device.RuntimePlatform == "Android") { if (parameter != null && parameter is string) return "switch.ttf#" + parameter.ToString(); else return "switch.ttf"; } else if (Device.RuntimePlatform == "iOS") { return "switch"; } else { #if COMMONSB return "/Assets/Fonts/switch.ttf#switch"; #else if (Core.SampleBrowser.IsIndividualSB) { return "/Assets/Fonts/switch.ttf#switch"; } else { return $"ms-appx:///SampleBrowser.SfSegmentedControl.UWP/Assets/Fonts/switch.ttf#switch"; } #endif } } /// <summary> /// Converts the font back to its default form /// </summary> /// <param name="value">the value</param> /// <param name="targetType">the targetType</param> /// <param name="parameter">the parameter</param> /// <param name="culture">the culture</param> /// <returns>convert back value</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }<file_sep>/Forms/GradientView/GradientView/App.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "App.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfGradientView { using System; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; [Preserve(AllMembers = true)] public partial class App : Application { public App() { InitializeComponent(); var page = Core.SampleBrowser.GetMainPage("SfGradientView", "SampleBrowser.SfGradientView"); this.MainPage = page; } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Column.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Drawing; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Column : SampleView { SFChart chart; public Column() { chart = new SFChart(); chart.Title.Text = new NSString("Olympic Medal Counts"); chart.ColorModel.Palette = SFChartColorPalette.Natural; SFCategoryAxis primary = new SFCategoryAxis(); primary.LabelPlacement = SFChartLabelPlacement.BetweenTicks; primary.Title.Text = new NSString("Countries"); chart.PrimaryAxis = primary; chart.SecondaryAxis = new SFNumericalAxis(); chart.SecondaryAxis.Title.Text = new NSString("Medals"); chart.SecondaryAxis.Minimum = new NSNumber(0); chart.SecondaryAxis.Maximum = new NSNumber(80); chart.SecondaryAxis.Interval = new NSNumber(20); ChartViewModel dataModel = new ChartViewModel(); SFColumnSeries series1 = new SFColumnSeries(); series1.ItemsSource = dataModel.ColumnData1; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.EnableTooltip = true; series1.Label = "Gold"; series1.EnableAnimation = true; chart.Series.Add(series1); SFColumnSeries series2 = new SFColumnSeries(); series2.ItemsSource = dataModel.ColumnData2; series2.XBindingPath = "XValue"; series2.YBindingPath = "YValue"; series2.EnableTooltip = true; series2.Label = "Silver"; series2.EnableAnimation = true; chart.Series.Add(series2); chart.Legend.Visible = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; this.AddSubview(chart); chart.AddChartBehavior(new SFChartZoomPanBehavior()); this.OptionView = new UIView(); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } this.CreateOptionView(); base.LayoutSubviews(); } private void CreateOptionView() { UILabel spacingLbl = new UILabel(); spacingLbl.Text = "Spacing:"; spacingLbl.TextAlignment = UITextAlignment.Left; spacingLbl.Font = UIFont.FromName("Helvetica", 14f); UILabel widthLbl = new UILabel(); widthLbl.Text = "SegmentWidth:"; widthLbl.TextAlignment = UITextAlignment.Left; widthLbl.Font = UIFont.FromName("Helvetica", 14f); UILabel spacing = new UILabel(); spacing.Text = "0.0"; spacing.Font = UIFont.FromName("Helvetica", 14f); UILabel width = new UILabel(); width.Text = "0.8"; width.Font = UIFont.FromName("Helvetica", 14f); UISlider spacingSlider = new UISlider(); spacingSlider.MinValue = 0.0f; spacingSlider.MaxValue = 1.0f; spacingSlider.Value = 0.0f; spacingSlider.ValueChanged += (object sender, EventArgs e) => { (chart.SeriesAtIndex(0) as SFColumnSeries).Spacing = (float)spacingSlider.Value; (chart.SeriesAtIndex(1) as SFColumnSeries).Spacing = (float)spacingSlider.Value; decimal value = decimal.Parse(spacingSlider.Value.ToString()); spacing.Text = value.ToString("0.00"); }; UISlider widthSlider = new UISlider(); widthSlider.MinValue = 0.0f; widthSlider.MaxValue = 1.0f; widthSlider.Value = 0.8f; widthSlider.ValueChanged += (object sender, EventArgs e) => { (chart.SeriesAtIndex(0) as SFColumnSeries).Width = (float)widthSlider.Value; (chart.SeriesAtIndex(1) as SFColumnSeries).Width = (float)widthSlider.Value; decimal value = decimal.Parse(widthSlider.Value.ToString()); width.Text = value.ToString("0.00"); }; if (Utility.IsIpad) { spacingLbl.Frame = new CGRect(10, 25, 80, 40); spacing.Frame = new CGRect(spacingLbl.Frame.Size.Width, 25, 50, 40); widthLbl.Frame = new CGRect(10, 130, 120, 40); width.Frame = new CGRect(widthLbl.Frame.Size.Width, 130, 50, 40); spacingSlider.Frame = new RectangleF(10, 50, (float)PopoverSize.Width - 20, 60); widthSlider.Frame = new RectangleF(10, 155, (float)PopoverSize.Width - 20, 60); } else { spacingLbl.Frame = new CGRect(10, 25, 80, 40); spacing.Frame = new CGRect(spacingLbl.Frame.Size.Width, 25, 50, 40); widthLbl.Frame = new CGRect(10, 130, 120, 40); width.Frame = new CGRect(widthLbl.Frame.Size.Width, 130, 50, 40); spacingSlider.Frame = new RectangleF(10, 50, (float)this.Frame.Width - 20, 60); widthSlider.Frame = new RectangleF(10, 155, (float)this.Frame.Width - 20, 60); } this.OptionView.AddSubview(spacingLbl); this.OptionView.AddSubview(widthLbl); this.OptionView.AddSubview(spacing); this.OptionView.AddSubview(width); this.OptionView.AddSubview(spacingSlider); this.OptionView.AddSubview(widthSlider); } } }<file_sep>/Forms/Rating/Rating/Samples/Rating/Rating_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfRating.XForms; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfRating { public partial class Rating_Default : SampleView { SfRatingSettings sfRatingSettings, sfsecondRatingSettings; int ratingItemCount; String ratingValue, ratingCount, ratingResult; public Rating_Default() { InitializeComponent(); //Rating Settings sfRatingSettings = new SfRatingSettings(); sfRatingSettings.RatedFill = Color.FromHex("#fbd10a"); sfRatingSettings.UnRatedFill = Color.White; sfRatingSettings.RatedStroke = Color.FromHex("#fbd10a"); sfRatingSettings.RatedStrokeWidth = 1; sfRatingSettings.UnRatedStrokeWidth = 1; sfRating1.RatingSettings = sfRatingSettings; //Rating Settings sfsecondRatingSettings = new SfRatingSettings(); sfsecondRatingSettings.UnRatedFill = Color.White; sfsecondRatingSettings.RatedStrokeWidth = 1; sfsecondRatingSettings.UnRatedStrokeWidth = 1; sfRating2.RatingSettings = sfsecondRatingSettings; Grid.SetColumn(movieImage, 0); Grid.SetColumn(descStack, 1); Grid.SetRow(title, 0); Grid.SetRow(mainGrid, 1); Grid.SetRow(bottomStack, 2); sfRating1.TooltipPlacement = TooltipPlacement.None; sfRating2.TooltipPlacement = TooltipPlacement.None; sfRating2.ValueChanged += ValueChanged; ratingValueLayout.Padding = new Thickness(0, 30, 0, 0); if (Device.RuntimePlatform == Device.Android) { sfRating2.ItemSize = 10; description.FontSize = 12; } if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { sfRating1.ItemSize = 10; sfRating2.ItemSize = 20; description.FontSize = 11; description.Text = "In 1973, French street performer <NAME> is trying to make a living in Paris with juggling acts and wire walking, much to the chagrin of his father."; ratingValueLayout.Padding = new Thickness(0, 10, 0, 0); } getRating(); GetOptionPage(); } void ValueChanged(object sender, ValueEventArgs e) { ratingValue = Convert.ToString(Math.Round(e.Value, 1)); ratingItemCount = sfRating2.ItemCount; ratingCount = Convert.ToString(ratingItemCount); ratingResult = " " + ratingValue + "/" + ratingCount; showValue.Text = ratingResult; } private void GetOptionPage() { Grid.SetColumn(toolTipLabel, 0); Grid.SetColumn(toolTipPlacementOption, 1); Grid.SetColumn(itemCountLabel, 0); Grid.SetColumn(itemCount, 1); precisionPicker.Items.Add("Standard"); precisionPicker.Items.Add("Half"); precisionPicker.Items.Add("Exact"); precisionPicker.SelectedIndex = 0; precisionPicker.SelectedIndexChanged += precisionPicker_SelectedIndexChanged; itemCount.ValueChanged += (object sender,Syncfusion.SfNumericUpDown.XForms.ValueEventArgs e) => { Decimal temp = Convert.ToDecimal(e.Value); int count = (int)temp; sfRating2.ItemCount = count; ratingItemCount = sfRating2.ItemCount; ratingCount = Convert.ToString(ratingItemCount); if (sfRating2.Value > ratingItemCount) { sfRating2.Value = 0; ratingValue = "0"; } else { ratingValue = Convert.ToString(sfRating2.Value); } ratingResult = " " + ratingValue + "/" + ratingCount; showValue.Text = ratingResult; }; toolTipPlacementOption.Toggled += toggleStateChanged; toolTipPlacementOption.IsToggled = false; toolTipPlacementOption.HorizontalOptions = LayoutOptions.End; if (Device.RuntimePlatform == Device.iOS) { column1.Width = 120; column2.Width = 180; description.FontSize = 12; toolTipPlacementOption.VerticalOptions = LayoutOptions.Start; itemCountLabel.VerticalOptions = LayoutOptions.Center; toolTipLabel.VerticalOptions = LayoutOptions.End; optionLayout.Spacing = 0; optionLayout.Padding = new Thickness(0, 0, 10, 0); Label dummyLabel = new Label(); optionLayout.Children.Insert(3, dummyLabel); } else if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { sampleLayout.Padding = new Thickness(10, 0, 10, 0); descStack.Padding = new Thickness(0, 0, 10, 0); optionLayout.Padding = new Thickness(10, 0, 10, 0); } if (Device.RuntimePlatform == "UWP" && (Device.Idiom == TargetIdiom.Phone)) { precisionPicker.HeightRequest = 40; } } void precisionPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (precisionPicker.SelectedIndex) { case 0: { sfRating2.Precision = Precision.Standard; ratingValue = Convert.ToString(Math.Round(sfRating2.Value)); sfRating2.TooltipPrecision = 0; break; } case 1: { sfRating2.Precision = Precision.Half; float ratingvalue = (float)sfRating2.Value; if (Math.Round(sfRating2.Value) != sfRating2.Value) { if(Math.Round(sfRating2.Value)> sfRating2.Value) { ratingValue = Convert.ToString(Math.Round(sfRating2.Value)- 0.5); } else { ratingValue = Convert.ToString(Math.Round(sfRating2.Value) + 0.5); } } else { ratingValue = Convert.ToString(Math.Round(sfRating2.Value)); } sfRating2.TooltipPrecision = 1; break; } case 2: { sfRating2.Precision = Precision.Exact; sfRating2.TooltipPrecision = 1; var decimalvalue = Math.Round(sfRating2.Value, 2); ratingValue = Convert.ToString(decimalvalue); break; } } ratingItemCount = sfRating2.ItemCount; ratingCount = Convert.ToString(ratingItemCount); ratingResult = " " + ratingValue + "/" + ratingCount; showValue.Text = ratingResult; } void toggleStateChanged(object sender, ToggledEventArgs e) { if (e.Value) sfRating2.TooltipPlacement = TooltipPlacement.TopLeft; else sfRating2.TooltipPlacement = TooltipPlacement.None; } void getRating() { if (Device.RuntimePlatform == Device.Android) { sfRating1.ItemSize = 17; sfRating2.ItemSize = 30; sfRating2.ItemSpacing = 5; } else if (Device.RuntimePlatform == Device.iOS) { movieImage.VerticalOptions = LayoutOptions.Start; movieImage.HeightRequest = 260; description.Text = "In 1973, French street performer <NAME> is trying to make a living in Paris with juggling acts and wire walking. He visits the dentist and, while in the waiting room, sees a picture in a magazine of the Twin Towers in New York City.\n"; sfRating1.ItemSize = 15; sfRating2.ItemSize = 30; sfRating2.ItemSpacing = 10; sfRating2.ItemCount = 5; sfRating1.WidthRequest = sfRating1.ItemCount * sfRating1.ItemSize; sfRating1.HeightRequest = sfRating1.ItemSize; sfRating2.HeightRequest = sfRating2.ItemSize; } else if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { itemCount.HeightRequest = 40; if ((Device.Idiom != TargetIdiom.Tablet) && Device.Idiom != TargetIdiom.Desktop) { sfRating1.HeightRequest = 40; sfRating2.HeightRequest = 40; time.HorizontalOptions = LayoutOptions.Start; //description.HeightRequest = 80; description.VerticalOptions = LayoutOptions.FillAndExpand; description.LineBreakMode = LineBreakMode.WordWrap; precisionPicker.HeightRequest = 90; } } } public View getContent() { return this.Content; } public View getPropertyView() { return this.PropertyView; } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/DetailsView/DetailsViewBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DetailsViewBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using Core; using Syncfusion.ListView.XForms; using Syncfusion.ListView.XForms.Control.Helpers; using Syncfusion.XForms.PopupLayout; using Xamarin.Forms; using ItemTappedEventArgs = Syncfusion.ListView.XForms.ItemTappedEventArgs; /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the DetailsView samples /// </summary> public class DetailsViewBehaviors : Behavior<SampleView> { /// <summary> /// Holds the instance of the ListView. /// </summary> private SfListView listview; /// <summary> /// Holds the instance of the PopupLayout. /// </summary> private SfPopupLayout popupLayout; /// <summary> /// Initializes a new instance of the DetailsViewBehaviors class. /// </summary> public DetailsViewBehaviors() { } /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type parameter bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { (bindAble.Resources["NotificationPopUp"] as SfPopupLayout).Show(); this.listview = bindAble.FindByName<SfListView>("listView"); this.listview.ItemTapped += this.ListView_ItemTapped; this.popupLayout = bindAble.FindByName<SfPopupLayout>("popUp"); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type parameter named as bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { base.OnDetachingFrom(bindAble); this.listview.ItemTapped -= this.ListView_ItemTapped; this.popupLayout = null; } /// <summary> /// Fired when listView item is tapped. /// </summary> /// <param name="sender">ItemTapped Event sender</param> /// <param name="e">ItemTappedEventArgs event args e</param> private void ListView_ItemTapped(object sender, ItemTappedEventArgs e) { if (e.ItemType != ItemType.Record) { return; } var itemIndex = (this.listview.BindingContext as ContactsViewModel).Contactsinfo.IndexOf(e.ItemData as ContactInfo); var visibleLine = this.listview.GetVisualContainer().ScrollRows.GetVisibleLineAtLineIndex(itemIndex); var point = this.listview.Y + visibleLine.ClippedOrigin + visibleLine.Size; if (point + 140 <= this.listview.Height + 25) { this.popupLayout.Show( this.listview.X, this.listview.Y + visibleLine.ClippedOrigin + visibleLine.ClippedSize + this.GetRelativeYPoint("top")); } else { this.popupLayout.Show(this.listview.X, point - this.GetRelativeYPoint("bottom")); } } /// <summary> /// Used to gets the relative point depends on the platform /// </summary> /// <param name="position">string type of desired position</param> /// <returns>returns desired position</returns> private double GetRelativeYPoint(string position) { if (Device.RuntimePlatform == Device.Android) { return position == "top" ? 40 : 200; } if (Device.RuntimePlatform == Device.iOS) { return position == "top" ? 35 : 207; } if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Desktop) { return position == "top" ? 85 : 155; } return position == "top" ? 0 : 240; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Styles/CellTemplateStyle.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CellTemplateStyle.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Derived from DataGridStyle to add the custom styles /// </summary> public class CellTemplateStyle : DataGridStyle { /// <summary> /// Overrides this method to write a custom style for selection background color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetSelectionBackgroundColor() { return Color.FromHex("#cce5fa"); } /// <summary> /// Overrides this method to write a custom style for selection foreground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetSelectionForegroundColor() { return Color.Black; } } } <file_sep>/Forms/Carousel/Carousel/Model/CarouselModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Input; using Xamarin.Forms; namespace SampleBrowser.SfCarousel { /// <summary> /// Carousel model. /// </summary> public class CarouselModel : INotifyPropertyChanged { #region private properties /// <summary> /// The image. /// </summary> private string image; /// <summary> /// The name. /// </summary> private string name; /// <summary> /// The close command. /// </summary> private ICommand closeCommand; /// <summary> /// The color of the item. /// </summary> private Color itemColor; /// <summary> /// /// </summary> private string checkValue = "C"; /// <summary> /// The grid visible. /// </summary> private bool gridVisible = false; /// <summary> /// The tap command. /// </summary> private ICommand tapCommand; #endregion #region Public properties /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name { get { return name; } set { name = value.ToString().Replace("-WF", ""); } } /// <summary> /// Gets or sets the close command. /// </summary> /// <value>The close command.</value> public ICommand CloseCommand { set { closeCommand = value; } get { return closeCommand; } } /// <summary> /// Gets or sets the color of the item. /// </summary> /// <value>The color of the item.</value> public Color ItemColor { get { return itemColor; } set { itemColor = value; RaisePropertyChanged("ItemColor"); } } /// <summary> /// Gets or sets the color of the item. /// </summary> /// <value>The color of the item.</value> public string CheckValue { get { return checkValue; } set { checkValue = value; RaisePropertyChanged("CheckValue"); } } /// <summary> /// Gets or sets the tag. /// </summary> /// <value>The tag.</value> public string Tag { get; set; } /// <summary> /// Gets or sets the unicode. /// </summary> /// <value>The unicode.</value> public string Unicode { get; set; } /// <summary> /// Gets or sets the name of the watch. /// </summary> /// <value>The name of the watch.</value> public string ImageName { get { return image; } set { image = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:SampleBrowser.SfCarousel.CarouselModel"/> grid visible. /// </summary> /// <value><c>true</c> if grid visible; otherwise, <c>false</c>.</value> public bool GridVisible { get { return gridVisible; } set { gridVisible = value; RaisePropertyChanged("GridVisible"); } } /// <summary> /// Gets or sets the tap command. /// </summary> /// <value>The tap command.</value> public ICommand TapCommand { set { tapCommand = value; } get { return tapCommand; } } /// <summary> /// Occurs when property changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.SfCarousel.CarouselModel"/> class. /// </summary> /// <param name="imagestr">Imagestr.</param> public CarouselModel(string imagestr) { ImageName = imagestr; } /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.SfCarousel.CarouselModel"/> class. /// </summary> public CarouselModel() { TapCommand = new Command<Object>(TappedEvent); CloseCommand = new Command<Object>(CloseCommandAction); } #endregion #region raised event public void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion #region tap event action /// <summary> /// Closes the command action. /// </summary> /// <param name="s">S.</param> private void CloseCommandAction(Object s) { (s as Grid).IsVisible = false; } /// <summary> /// Tappeds the event. /// </summary> /// <param name="s">S.</param> private void TappedEvent(Object s) { ItemColor = (Color)s; } #endregion } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Model/BookRepository.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; namespace SampleBrowser { public class BookRepository { public BookRepository () { } #region private variables private Random random = new Random (); #endregion #region GetBookDetails public List<BookInfo> GetBookDetails (int count) { List<BookInfo> bookDetails = new List<BookInfo> (); for (int i = 1; i <= count; i++) { var ord = new BookInfo () { CustomerID = i, BookID = BookID [random.Next (8)], BookName = BookNames [random.Next (5)], Country = Country [random.Next (8)], Price = random.Next (30, 200), FirstName = FirstNames [random.Next (7)], LastName = LastNames [random.Next (9)], }; bookDetails.Add (ord); } return bookDetails; } #endregion #region DataSource string[] BookNames = new string[] { "<NAME>", "Money", "The Information", "The BottleFactory", "<NAME>", "Molloy", "<NAME>", "A Good Man", "The History Man", "The Horse", "Chocolate", "<NAME>", "<NAME>", "Caprice", "Towards the End ", "Polygots", "Death Soul", "Charade", "Changing places", "Under the Net", "Fire Flies", }; int[] BookID = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; string[] Country = new string[] { "India", "Europe", "America", "Europe", "Pakistan", "England", "France", "Bangladesh", "Argentina", "Austria", "Belgium", "Brazil", "Canada", "Denmark", "Finland", "France", "Germany", "Ireland", "Italy", "Mexico", "Norway", "Poland", "Portugal", "Spain", "Sweden", "Switzerland", "UK", "USA", "Venezuela" }; string[] FirstNames = new string[] { "Kyle", "Gina", "Irene", "Katie", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Brenda", "Danielle", "Fiona", "Howard", "Jack", "Larry", "Holly", "Jennifer", "Liz", "Pete", "Steve", "Vince", "Zeke" }; string[] LastNames = new string[] { "Adams", "Crowley", "Ellis", "Gable", "Irvine", "Keefe", "Mendoza", "Owens", "Rooney", "Waddell", "Thomas", "Betts", "Doran", "Fitzgerald", "Holmes", "Jefferson", "Landry", "Newberry", "Perez", "Spencer", "Vargas", "Grimes", "Edwards", "Stark", "Cruise", "Fitz", "Chief", "Blanc", "Perry", "Stone", "Williams", "Lane", "Jobs" }; #endregion } } <file_sep>/Android/SampleBrowser/Samples/Diagram/FlowDiagram.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Android.Graphics; using Android.Util; using Android.Views; using Android.Widget; using Syncfusion.SfDiagram.Android; using System.Collections.Generic; using System.IO; using System.Reflection; namespace SampleBrowser { public partial class FlowDiagram : SamplePage { SfDiagram diagram; private TextView label; private Switch snapToGridSwitch; private LinearLayout scrollLayout; internal static float currentDensity = 1; public override View GetSampleContent(Context context) { currentDensity = context.Resources.DisplayMetrics.Density; //Initialize the SfDiagram instance and set background. diagram = new SfDiagram(context); diagram.ContextMenuSettings.Visibility = false; diagram.BackgroundColor = Color.White; diagram.EnableTextEditing = false; //Create nodes and set the offset, size and other properties. Node n1 = new Node(context); n1.ShapeType = ShapeType.RoundedRectangle; n1.CornerRadius = 90 * MainActivity.Factor; n1.OffsetX = 185 * MainActivity.Factor; n1.OffsetY = 80 * MainActivity.Factor; n1.Width = 320 * MainActivity.Factor; n1.Height = 110 * MainActivity.Factor; n1.Style.Brush = new SolidBrush(Color.Rgb(49, 162, 255)); n1.Style.StrokeBrush = new SolidBrush(Color.Rgb(23, 132, 206)); TextView content1 = CreateLabel(context, "New idea identified", (int)n1.Width, Color.Rgb(255, 255, 255)); n1.Annotations.Add(new Annotation() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Content = content1 }); diagram.AddNode(n1); Node n2 = new Node(context); n2.OffsetX = 185 * MainActivity.Factor; n2.OffsetY = 280 * MainActivity.Factor; n2.Width = 320 * MainActivity.Factor; n2.Height = 110 * MainActivity.Factor; n2.ShapeType = ShapeType.RoundedRectangle; n2.CornerRadius = 15 * MainActivity.Factor; n2.Style.Brush = new SolidBrush(Color.Rgb(49, 162, 255)); n2.Style.StrokeBrush = new SolidBrush(Color.Rgb(23, 132, 206)); TextView content2 = CreateLabel(context, "Meeting With Boards", (int)n2.Width, Color.Rgb(255, 255, 255)); n2.Annotations.Add(new Annotation() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Content = content2 }); diagram.AddNode(n2); Node n3 = new Node(context); n3.ShapeType = ShapeType.Diamond; n3.OffsetX = 195 * MainActivity.Factor; n3.OffsetY = 480 * MainActivity.Factor; n3.Width = 300 * MainActivity.Factor; n3.Height = 300 * MainActivity.Factor; n3.Style.Brush = new SolidBrush(Color.Rgb(0, 194, 192)); n3.Style.StrokeBrush = new SolidBrush(Color.Rgb(4, 142, 135)); TextView content3 = CreateLabel(context, "Board decides" + "\n" + "whether to" + "\n" + "proceed", (int)n3.Width, Color.Rgb(255, 255, 255)); n3.Annotations.Add(new Annotation() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Content = content3 }); diagram.AddNode(n3); Node n4 = new Node(context); n4.ShapeType = ShapeType.Diamond; n4.OffsetX = 195 * MainActivity.Factor; n4.OffsetY = 870 * MainActivity.Factor; n4.Width = 300 * MainActivity.Factor; n4.Height = 300 * MainActivity.Factor; n4.Style.Brush = new SolidBrush(Color.Rgb(0, 194, 192)); n4.Style.StrokeBrush = new SolidBrush(Color.Rgb(4, 142, 135)); TextView content4 = CreateLabel(context, "Find Project" + "\n" + "Manager, write" + "\n" + "specification", (int)n4.Width, Color.Rgb(255, 255, 255)); n4.Annotations.Add(new Annotation() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Content = content4 }); diagram.AddNode(n4); Node n5 = new Node(context); n5.Style.Brush = new SolidBrush(Color.Rgb(49, 162, 255)); n5.Style.StrokeBrush = new SolidBrush(Color.Rgb(23, 132, 206)); n5.OffsetX = 185 * MainActivity.Factor; n5.OffsetY = 1260 * MainActivity.Factor; n5.Width = 320 * MainActivity.Factor; n5.Height = 110 * MainActivity.Factor; n5.ShapeType = ShapeType.RoundedRectangle; n5.CornerRadius = 90 * MainActivity.Factor; TextView content5 = CreateLabel(context, "Implement and deliver", (int)n5.Width, Color.Rgb(255, 255, 255)); n5.Annotations.Add(new Annotation() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Content = content5 }); diagram.AddNode(n5); Node n6 = new Node(context); n6.Style.Brush = new SolidBrush(Color.Rgb(239, 75, 93)); n6.Style.StrokeBrush = new SolidBrush(Color.Rgb(201, 32, 61)); n6.OffsetX = 674 * MainActivity.Factor; n6.OffsetY = 575 * MainActivity.Factor; n6.Width = 320 * MainActivity.Factor; n6.Height = 110 * MainActivity.Factor; n6.ShapeType = ShapeType.RoundedRectangle; n6.CornerRadius = 15 * MainActivity.Factor; TextView content6 = CreateLabel(context, "Reject and report the reason", (int)n6.Width, Color.Rgb(255, 255, 255)); n6.Annotations.Add(new Annotation() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Content = content6 }); diagram.AddNode(n6); Node n7 = new Node(context); n7.Style.Brush = new SolidBrush(Color.Rgb(239, 75, 93)); n7.Style.StrokeBrush = new SolidBrush(Color.Rgb(201, 32, 61)); n7.OffsetX = 674 * MainActivity.Factor; n7.OffsetY = 965.599f * MainActivity.Factor; n7.Width = 320 * MainActivity.Factor; n7.Height = 110 * MainActivity.Factor; n7.ShapeType = ShapeType.RoundedRectangle; n7.CornerRadius = 15 * MainActivity.Factor; TextView content7 = CreateLabel(context, "Hire new resources", (int)n7.Width, Color.Rgb(255, 255, 255)); n7.Annotations.Add(new Annotation() { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Content = content7 }); diagram.AddNode(n7); //Create connector with its source and target node. Connector c1 = new Connector(context, n1, n2); diagram.AddConnector(c1); Connector c2 = new Connector(context, n2, n3); diagram.AddConnector(c2); Connector c3 = new Connector(context, n3, n4); //Create label for the connector. c3.Annotations.Add(new Annotation() { Content = "Yes", HorizontalAlignment = HorizontalAlignment.Left, FontSize = 20 * MainActivity.Factor, TextBrush = new SolidBrush(Color.Rgb(127, 132, 133)) }); diagram.AddConnector(c3); Connector c4 = new Connector(context, n4, n5); c4.Annotations.Add(new Annotation() { Content = "Yes", HorizontalAlignment = HorizontalAlignment.Left, FontSize = 20 * MainActivity.Factor, TextBrush = new SolidBrush(Color.Rgb(127, 132, 133)) }); diagram.AddConnector(c4); diagram.IsReadOnly = false; Connector c5 = new Connector(context, n3, n6); c5.Annotations.Add(new Annotation() { Content = "No", FontSize = 20 * MainActivity.Factor, TextBrush = new SolidBrush(Color.Rgb(127, 132, 133)) }); diagram.AddConnector(c5); Connector c6 = new Connector(context, n4, n7); c6.Annotations.Add(new Annotation() { Content = "No", FontSize = 20 * MainActivity.Factor, TextBrush = new SolidBrush(Color.Rgb(127, 132, 133)) }); diagram.AddConnector(c6); //Set the stroke color for the connector. for (int i = 0; i < diagram.Connectors.Count; i++) { //Diagram.Connectors[i].TargetDecoratorType = DecoratorType.None; diagram.Connectors[i].Style.StrokeBrush = new SolidBrush(Color.Rgb(127, 132, 133)); diagram.Connectors[i].TargetDecoratorStyle.Fill = (Color.Rgb(127, 132, 133)); diagram.Connectors[i].TargetDecoratorStyle.StrokeColor = (Color.Rgb(127, 132, 133)); diagram.Connectors[i].TargetDecoratorStyle.StrokeWidth = 4 * MainActivity.Factor; diagram.Connectors[i].TargetDecoratorStyle.Size = 14 * MainActivity.Factor; diagram.Connectors[i].Style.StrokeWidth = 2 * MainActivity.Factor; } //Set the stroke size for node. for (int i = 0; i < diagram.Nodes.Count; i++) { diagram.Nodes[i].Style.StrokeWidth = 1; } diagram.Loaded += Diagram_Loaded; diagram.ConnectorClicked += Diagram_ConnectorClicked; diagram.PageSettings.GridSize = 12 * currentDensity; diagram.PageSettings.GridColor = Color.Rgb(230, 230, 230); return diagram; } private void Diagram_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); HideSelectors(); } private void HideSelectors() { diagram.ShowSelectorHandle(false, SelectorPosition.SourcePoint); diagram.ShowSelectorHandle(false, SelectorPosition.TargetPoint); diagram.ShowSelectorHandle(false, SelectorPosition.Rotator); diagram.ShowSelectorHandle(false, SelectorPosition.TopLeft); diagram.ShowSelectorHandle(false, SelectorPosition.TopRight); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleLeft); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleRight); diagram.ShowSelectorHandle(false, SelectorPosition.BottomCenter); diagram.ShowSelectorHandle(false, SelectorPosition.BottomLeft); diagram.ShowSelectorHandle(false, SelectorPosition.BottomRight); diagram.ShowSelectorHandle(false, SelectorPosition.TopCenter); } private void Diagram_ConnectorClicked(object sender, ConnectorClickedEventArgs args) { diagram.ClearSelection(); } public override void Destroy() { if (diagram != null) diagram.Dispose(); base.Destroy(); } public override View GetPropertyWindowLayout(Context context) { LinearLayout gridLinearLayout = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Vertical }; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); layoutParams.TopMargin = (int)(25 * currentDensity); gridLinearLayout.LayoutParameters = layoutParams; gridLinearLayout.SetBackgroundResource(Resource.Drawable.LinearLayout_Border); int width = (int)(context.Resources.DisplayMetrics.WidthPixels - context.Resources.DisplayMetrics.Density) / 3; LinearLayout linearLayout4 = new LinearLayout(context); linearLayout4.Orientation = Android.Widget.Orientation.Vertical; linearLayout4.SetMinimumHeight((int)(70 * currentDensity)); linearLayout4.SetMinimumWidth(width); TextView selectText = new TextView(context) { Text = "Grid Color", Gravity = GravityFlags.Start, TextSize = 5 * currentDensity }; selectText.SetMinimumHeight((int)(20 * currentDensity)); selectText.SetWidth((int)(width * 0.4 * currentDensity)); HorizontalScrollView horizontalScroll = new HorizontalScrollView(context); horizontalScroll.SetPadding(0, (int)(10 * currentDensity), 0, (int)(10 * currentDensity)); horizontalScroll.FillViewport = true; horizontalScroll.HorizontalScrollBarEnabled = true; horizontalScroll.SetMinimumHeight((int)(60 * currentDensity)); horizontalScroll.Layout(0, (int)(20 * currentDensity), (int)(80 * currentDensity * 14), (int)(60 * currentDensity)); scrollLayout = new LinearLayout(context); scrollLayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); horizontalScroll.AddView(scrollLayout); AddColors(); linearLayout4.AddView(selectText); linearLayout4.AddView(horizontalScroll); LinearLayout linearLayout1 = new LinearLayout(context); linearLayout1.SetPadding(0, (int)(10 * currentDensity), 0, (int)(10 * currentDensity)); linearLayout1.SetMinimumHeight((int)(30 * currentDensity)); TextView showGrid = new TextView(context) { Text = "Show Grid", Gravity = GravityFlags.Start, TextSize = 5 * currentDensity }; showGrid.SetMinimumHeight((int)(20 * currentDensity)); showGrid.SetWidth((int)(width * 0.4 * currentDensity)); Switch showGridSwitch = new Switch(context); showGridSwitch.CheckedChange += ShowGridSwitch_CheckedChange; showGridSwitch.Gravity = GravityFlags.Right; showGridSwitch.SetMinimumHeight((int)(20 * currentDensity)); showGridSwitch.SetWidth((int)(width * 0.4 * currentDensity)); linearLayout1.AddView(showGrid); linearLayout1.AddView(showGridSwitch); LinearLayout linearLayout2 = new LinearLayout(context); linearLayout2.SetPadding(0, (int)(10 * currentDensity), 0, (int)(10 * currentDensity)); linearLayout2.SetMinimumHeight((int)(30 * currentDensity)); TextView snapToGrid = new TextView(context) { Text = "Snap To Grid", Gravity = GravityFlags.Start, TextSize = 5 * currentDensity }; snapToGrid.SetMinimumHeight((int)(20 * currentDensity)); snapToGrid.SetWidth((int)(width * 0.4 * currentDensity)); snapToGridSwitch = new Switch(context); snapToGridSwitch.Enabled = false; snapToGridSwitch.CheckedChange += SnapToGridSwitch_CheckedChange; snapToGridSwitch.Gravity = GravityFlags.Right; snapToGridSwitch.SetMinimumHeight((int)(20 * currentDensity)); snapToGridSwitch.SetWidth((int)(width * 0.4 * currentDensity)); linearLayout2.AddView(snapToGrid); linearLayout2.AddView(snapToGridSwitch); LinearLayout linearLayout3 = new LinearLayout(context); linearLayout3.SetPadding(0, (int)(10 * currentDensity), 0, (int)(10 * currentDensity)); linearLayout3.SetMinimumHeight((int)(60 * currentDensity)); TextView connectorSize = new TextView(context) { Text = "Size", Gravity = GravityFlags.CenterVertical, TextSize = 5 * currentDensity }; connectorSize.SetMinimumHeight((int)(20 * currentDensity)); connectorSize.SetWidth((int)(width * 0.4 * currentDensity)); LinearLayout plusMinus = new LinearLayout(context); plusMinus.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent); plusMinus.SetMinimumHeight((int)(40 * currentDensity)); plusMinus.SetMinimumWidth((int)((width - (int)(width * 0.4)) * currentDensity)); ImageButton minusButton = new ImageButton(context); minusButton.SetMinimumHeight((int)(20 * currentDensity)); minusButton.Click += MinusButton_Click; string imageId = "diagramsub.png"; if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); minusButton.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } plusMinus.AddView(minusButton); label = new TextView(context); label.Text = "12"; label.TextAlignment = TextAlignment.Center; label.Gravity = GravityFlags.Center; label.SetMinimumHeight((int)(60 * currentDensity)); label.SetWidth((int)(50 * currentDensity)); plusMinus.AddView(label); ImageButton plusButton = new ImageButton(context); imageId = "diagramplus.png"; plusButton.Click += PlusButton_Click; plusButton.TextAlignment = TextAlignment.ViewEnd; if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); plusButton.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } plusMinus.AddView(plusButton); linearLayout3.AddView(connectorSize); linearLayout3.AddView(plusMinus); gridLinearLayout.AddView(linearLayout4); gridLinearLayout.AddView(linearLayout1); gridLinearLayout.AddView(linearLayout2); gridLinearLayout.AddView(linearLayout3); return gridLinearLayout; } private void AddColors() { AddColor(Color.Red); AddColor(Color.Orange); AddColor(Color.Green); AddColor(Color.Blue); AddColor(Color.Purple); AddColor(Color.Aqua); AddColor(Color.Fuchsia); AddColor(Color.Gray); AddColor(Color.Lime); AddColor(Color.Maroon); AddColor(Color.Navy); AddColor(Color.Olive); AddColor(Color.Silver); AddColor(Color.Teal); } private void AddColor(Color color) { ColorCircle colorCircle = new ColorCircle(diagram.Context, color); colorCircle.Click += ColorCircle_Click; colorCircle.LayoutParameters = new ViewGroup.LayoutParams((int)(60 * currentDensity), (int)(60 * currentDensity)); scrollLayout.AddView(colorCircle); } private void ColorCircle_Click(object sender, EventArgs e) { if (!diagram.PageSettings.ShowGrid) return; ColorCircle circle = (ColorCircle)sender; diagram.PageSettings.GridColor = circle.m_color; circle.Selected = true; circle.SetWillNotDraw(true); circle.SetWillNotDraw(false); for (int i = 0; i < scrollLayout.ChildCount; i++) { ColorCircle colorCircle = scrollLayout.GetChildAt(i) as ColorCircle; if (colorCircle.m_color.ToString().Equals(circle.m_color.ToString())) continue; else if (colorCircle.Selected) { colorCircle.Selected = false; colorCircle.SetWillNotDraw(true); colorCircle.SetWillNotDraw(false); } } } private void SnapToGridSwitch_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { diagram.PageSettings.SnapToGrid = e.IsChecked; } private void ShowGridSwitch_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { diagram.PageSettings.ShowGrid = e.IsChecked; snapToGridSwitch.Enabled = e.IsChecked; if (!e.IsChecked) { for (int i = 0; i < scrollLayout.ChildCount; i++) { ColorCircle circle = scrollLayout.GetChildAt(i) as ColorCircle; if (circle.Selected) { circle.Selected = false; circle.SetWillNotDraw(true); circle.SetWillNotDraw(false); } } diagram.PageSettings.SnapToGrid = false; snapToGridSwitch.Checked = false; } } internal class ColorCircle : ViewGroup { internal Color m_color; internal ColorCircle(Context context, Color color) : base(context) { SetBackgroundColor(Color.Transparent); m_color = color; } internal new bool Selected { get; set; } protected override void OnLayout(bool changed, int l, int t, int r, int b) { } protected override void OnDraw(Canvas canvas) { Paint strokePaint = new Paint(); strokePaint.SetStyle(Paint.Style.Stroke); strokePaint.StrokeWidth = 5 * currentDensity; Paint fillPaint = new Paint(); fillPaint.Color = m_color; if (Selected) { strokePaint.Color = Color.Rgb(30, 144, 255); strokePaint.StrokeWidth = 5 * currentDensity; } else strokePaint.Color = Color.White; fillPaint.SetStyle(Paint.Style.Fill); canvas.DrawCircle(Width / 2, Height / 2, Width / 3, strokePaint); canvas.DrawCircle(Width / 2, Height / 2, Width / 3, fillPaint); base.OnDraw(canvas); } } internal static MemoryStream LoadResource(string name) { MemoryStream aMem = new MemoryStream(); var assm = Assembly.GetExecutingAssembly(); var path = string.Format("SampleBrowser.Resources.drawable.{0}", name); var aStream = assm.GetManifestResourceStream(path); aStream.CopyTo(aMem); return aMem; } private void PlusButton_Click(object sender, EventArgs e) { int value = int.Parse(label.Text); if (value < 20) { diagram.PageSettings.GridSize = (value + 1) * currentDensity; label.Text = (value + 1).ToString(); } } private void MinusButton_Click(object sender, EventArgs e) { int value = int.Parse(label.Text); if (value > 5) { diagram.PageSettings.GridSize = (value - 1) * currentDensity; label.Text = (value - 1).ToString(); } } internal static TextView CreateLabel(Context context, string text, int width, Color color) { //Create a text view and assign its properties. TextView label = new TextView(context); label.Typeface = Typeface.Create(".SF UI Text", TypefaceStyle.Normal); label.SetText(text, TextView.BufferType.Normal); label.SetTextSize(ComplexUnitType.Px, 28 * MainActivity.Factor); label.Gravity = GravityFlags.Center; int widthMeasureSpec = View.MeasureSpec.MakeMeasureSpec( (int)width, MeasureSpecMode.AtMost); int heightMeasureSpec = View.MeasureSpec.MakeMeasureSpec( 0, MeasureSpecMode.Unspecified); label.Measure(widthMeasureSpec, heightMeasureSpec); label.Left = label.Top = 0; label.Bottom = label.MeasuredHeight; label.Right = label.MeasuredWidth; label.SetTextColor(color); return label; } } }<file_sep>/Forms/ListView/ListView/Samples/LoadMore/Model/Product.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class Product : INotifyPropertyChanged { private int quantity = 0; private double totalPrice = 0; public string Name { get; set; } public string Image { get; set; } public string Weight { get; set; } public double Price { get; set; } public int Quantity { get { return quantity; } set { if (quantity != value) { quantity = value; TotalPrice = quantity * Price; RaisePropertyChanged("Quantity"); } } } public double TotalPrice { get { return totalPrice; } set { if (totalPrice != value) { totalPrice = value; RaisePropertyChanged("TotalPrice"); } } } private void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; } } <file_sep>/iOS/SampleBrowser/DataSource/ChartSampleDataSource.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Foundation; using UIKit; namespace SampleBrowser { public class TypeSamplesDataSource : UICollectionViewDataSource { #region fields private NSMutableArray samplesCollections; private ChartSamplesViewController controller; #endregion #region ctor public TypeSamplesDataSource(NSMutableArray collections, ChartSamplesViewController controller) { samplesCollections = collections; this.controller = controller; } #endregion #region methods public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { UICollectionViewCell cell = (UICollectionViewCell)collectionView.DequeueReusableCell("textReuseCell", indexPath); cell.BackgroundColor = UIColor.Clear; UIButton label = (UIButton)cell.ViewWithTag(500); UIButton labelX = (UIButton)cell.ViewWithTag(510); labelX.TouchUpInside += (sender, e) => { if (controller.TypesIndexPath != indexPath) { HighlightCell(label, labelX, collectionView, indexPath); } }; label.TouchUpInside += (sender, e) => { if (controller.TypesIndexPath != indexPath) { HighlightCell(label, labelX, collectionView, indexPath); } }; label.SetTitle(string.Empty, UIControlState.Normal); labelX.SetTitle(string.Empty, UIControlState.Normal); Control item = samplesCollections.GetItem<Control>((nuint)indexPath.Row); NSString sampleName = item.Name; NSString dispName = item.DisplayName; dispName = string.IsNullOrEmpty(dispName) ? sampleName : dispName; UIImageView tag = (UIImageView)cell.ViewWithTag(502); if (item.Tag == "NEW") { label.SetTitle(dispName, UIControlState.Normal); tag.Image = UIImage.FromBundle("Controls/Tags/x_new.png"); } else if (item.Tag == "UPDATED") { label.SetTitle(dispName, UIControlState.Normal); tag.Image = UIImage.FromBundle("Controls/Tags/x_update.png"); } else { labelX.SetTitle(dispName, UIControlState.Normal); tag.Image = null; } label.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); labelX.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); label.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Highlighted); labelX.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Highlighted); if (indexPath.Row == (int)controller.TypesIndexPath.Row) { label.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); labelX.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); } return cell; } public override nint GetItemsCount(UICollectionView collectionView, nint section) { return (nint)samplesCollections.Count; } public void HighlightCell(UIButton label, UIButton labelX, UICollectionView collectionView, NSIndexPath indexPath) { if (controller.TypesIndexPath != indexPath) { foreach (UICollectionViewCell collectionViewCell in collectionView.VisibleCells) { UIButton label1 = (UIButton)collectionViewCell.ViewWithTag(500); UIButton label2 = (UIButton)collectionViewCell.ViewWithTag(510); label1.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); label2.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); } if (controller.DeselectedButton != null) { controller.DeselectedButton.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); controller.DeselectedButtonX.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); } collectionView.SelectItem(indexPath, true, UICollectionViewScrollPosition.CenteredHorizontally); controller.TypesIndexPath = indexPath; controller.DeselectedButton = label; controller.DeselectedButtonX = labelX; controller.LoadSample(); label.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); labelX.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); } } #endregion } public class FeatureSamplesDataSource : UICollectionViewDataSource { #region fields private NSMutableArray samplesCollections; private ChartSamplesViewController controller; #endregion #region ctor public FeatureSamplesDataSource(NSMutableArray collections, ChartSamplesViewController controller) { samplesCollections = collections; this.controller = controller; } #endregion #region methods public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { UICollectionViewCell cell = (UICollectionViewCell)collectionView.DequeueReusableCell("textReuseCell", indexPath); cell.BackgroundColor = UIColor.Clear; UIButton label = (UIButton)cell.ViewWithTag(500); UIButton labelX = (UIButton)cell.ViewWithTag(510); labelX.TouchUpInside += (sender, e) => { if (controller.FeaturesIndexPath != indexPath) { HighlightCell(label, labelX, collectionView, indexPath); } }; label.TouchUpInside += (sender, e) => { if (controller.FeaturesIndexPath != indexPath) { HighlightCell(label, labelX, collectionView, indexPath); } }; label.SetTitle(string.Empty, UIControlState.Normal); labelX.SetTitle(string.Empty, UIControlState.Normal); Control item = samplesCollections.GetItem<Control>((nuint)indexPath.Row); NSString sampleName = item.Name; NSString dispName = item.DisplayName; dispName = string.IsNullOrEmpty(dispName) ? sampleName : dispName; UIImageView tag = (UIImageView)cell.ViewWithTag(502); if (item.Tag == "NEW") { label.SetTitle(dispName, UIControlState.Normal); tag.Image = UIImage.FromBundle("Controls/Tags/x_new.png"); } else if (item.Tag == "UPDATED") { label.SetTitle(dispName, UIControlState.Normal); tag.Image = UIImage.FromBundle("Controls/Tags/x_update.png"); } else { labelX.SetTitle(dispName, UIControlState.Normal); tag.Image = null; } label.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); labelX.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); label.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Highlighted); labelX.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Highlighted); if (indexPath.Row == (int)controller.TypesIndexPath.Row) { label.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); labelX.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); } return cell; } public override nint GetItemsCount(UICollectionView collectionView, nint section) { return (nint)samplesCollections.Count; } public void HighlightCell(UIButton label, UIButton labelX, UICollectionView collectionView, NSIndexPath indexPath) { if (controller.FeaturesIndexPath != indexPath) { foreach (UICollectionViewCell collectionViewCell in collectionView.VisibleCells) { UIButton label1 = (UIButton)collectionViewCell.ViewWithTag(500); UIButton label2 = (UIButton)collectionViewCell.ViewWithTag(510); label1.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); label2.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); } collectionView.SelectItem(indexPath, true, UICollectionViewScrollPosition.CenteredHorizontally); controller.FeaturesIndexPath = indexPath; controller.LoadSample(); label.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); labelX.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); } } #endregion } public class ChartSamplesDelegate : UICollectionViewDelegateFlowLayout { #region fields private NSMutableArray samplesCollections; #endregion #region ctor public ChartSamplesDelegate(NSMutableArray collections) { samplesCollections = collections; } #endregion #region methods public override CGSize GetSizeForItem(UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath) { Control control = samplesCollections.GetItem<Control>((nuint)indexPath.Row); NSString sampleName = control.Name; NSString dispName = control.DisplayName; NSString name = string.IsNullOrEmpty(dispName) ? sampleName : dispName; UIStringAttributes attribs = new UIStringAttributes { Font = UIFont.SystemFontOfSize(15) }; CGSize size = name.GetSizeUsingAttributes(attribs); if (string.IsNullOrEmpty(control.Tag)) { return new CGSize(size.Width + 20, 50); } else { return new CGSize(size.Width + 40, 50); } } #endregion } }<file_sep>/Forms/TabView/TabView/Samples/CustomView/CustomView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XForms.TabView; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SampleBrowser.Core; using System.Collections.ObjectModel; using System.Linq; using System.Globalization; namespace SampleBrowser.SfTabView { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CustomView : SampleView { TapGestureRecognizer tabGesture; public CustomView() { InitializeComponent(); this.BindingContext = new ViewModelCustomTab(); //if(Device.RuntimePlatform == "iOS") //this.ReadCountLabel.WidthRequest = this.ReadCountLabel.HeightRequest = 20; SfTabItem item = new SfTabItem(); //this.refreshButton.TextColor = Color.Transparent; //this.refreshButton.Clicked += RefreshButton_Clicked; //this.uwprefreshIndicator.VerticalOptions = LayoutOptions.End; //if(Device.RuntimePlatform == Device.UWP) //{ // this.uwprefreshIndicator.IsVisible = true; // this.uwprefreshIndicator.IsRunning = true; // this.refreshIndicator.IsVisible = false; // this.refreshIndicator.IsRunning = false; //} //else //{ // this.uwprefreshIndicator.IsVisible = false; // this.uwprefreshIndicator.IsRunning = false; // this.refreshIndicator.IsVisible = true; // this.refreshIndicator.IsRunning = true; //} //Device.StartTimer(TimeSpan.FromMilliseconds(5000), () => //{ // if (Device.RuntimePlatform != Device.UWP) // { // this.refreshIndicator.IsVisible = false; // this.refreshIndicator.IsRunning = false; // } // else // { // this.uwprefreshIndicator.IsVisible = false; // this.uwprefreshIndicator.IsRunning = false; // } // this.refreshButton.TextColor = Color.FromHex("#FF00AFF0"); // return false; //}); tabGesture = new TapGestureRecognizer(); tabGesture.Tapped += TabGesture_Tapped; ContactsHeader.GestureRecognizers.Add(tabGesture); ChatsHeader.GestureRecognizers.Add(tabGesture); } void TabGesture_Tapped(object sender, EventArgs e) { if(sender is Grid) { simTab.SelectedIndex = (sender as Grid).StyleId == "ChatsHeader" ? 0 : 1; } } private void RefreshButton_Clicked(object sender, EventArgs e) { //if (Device.RuntimePlatform != Device.UWP) //{ // this.refreshIndicator.IsVisible = true; // this.refreshIndicator.IsRunning = true; //} //else //{ // this.refreshIndicator.IsVisible = false; // this.uwprefreshIndicator.IsVisible = true; // this.uwprefreshIndicator.IsRunning = true; //} //this.refreshButton.TextColor = Color.Transparent; //Device.StartTimer(TimeSpan.FromMilliseconds(2500), () => //{ // if (Device.RuntimePlatform != Device.UWP) // { // this.refreshIndicator.IsVisible = false; // this.refreshIndicator.IsRunning = false; // } // else // { // this.uwprefreshIndicator.IsVisible = false; // this.uwprefreshIndicator.IsRunning = false; // } // this.refreshButton.TextColor = Color.FromHex("#FF00AFF0"); // Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Alert", "Contacts are up to date", "OK"); // return false; //}); } } public class CustomViewConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (Device.RuntimePlatform == "Android") { if (parameter != null && parameter is string) return "NestedTab.ttf#" + parameter.ToString(); else return "NestedTab.ttf"; } else if (Device.RuntimePlatform == "iOS") { return "NestedTab"; } else { #if COMMONSB return "/Assets/Fonts/NestedTab.ttf#NestedTab"; #else if (Core.SampleBrowser.IsIndividualSB) { return "/Assets/Fonts/NestedTab.ttf#NestedTab"; } else { return $"ms-appx:///SampleBrowser.SfTabView.UWP/Assets/Fonts/NestedTab.ttf#NestedTab"; // "SampleBrowser.SfTabView.UWP\\Assets/Fonts/NestedTab.ttf#NestedTab"; } #endif } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }<file_sep>/Forms/ListView/ListView/Samples/Selection/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Syncfusion.ListView.XForms; using Xamarin.Forms.Internals; using System.Reflection; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewSelectionViewModel : INotifyPropertyChanged { #region Fields private ObservableCollection<Musiqnfo> musicInfo; private string headerInfo; private string titleInfo; private bool isVisible; #endregion #region Constructor public ListViewSelectionViewModel() { GenerateSource(); titleInfo = "Music Library"; headerInfo = ""; } #endregion #region Properties public ObservableCollection<Musiqnfo> MusicInfo { get { return musicInfo; } set { this.musicInfo = value; } } public string TitleInfo { get { return titleInfo; } set { if (titleInfo != value) { titleInfo = value; OnPropertyChanged("TitleInfo"); } } } public bool IsVisible { get { return isVisible; } set { if (isVisible != value) { isVisible = value; OnPropertyChanged("IsVisible"); } } } public string HeaderInfo { get { return headerInfo; } set { if (headerInfo != value) { headerInfo = value; OnPropertyChanged("HeaderInfo"); } } } #endregion #region Generate Source private void GenerateSource() { MusiqInfoRepository musiqinfo = new MusiqInfoRepository(); musicInfo = musiqinfo.GetMusiqInfo(); } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Forms/DataForm/DataForm/Samples/DynamicFormPage/Model/EmployeeForm.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.DataForm; using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using Xamarin.Forms.Internals; using System.ComponentModel.DataAnnotations; namespace SampleBrowser.SfDataForm { /// <summary> /// Represents the Employee information of the data form dynamic forms sample. /// </summary> [Preserve(AllMembers = true)] public class EmployeeForm : INotifyPropertyChanged { #region Fields /// <summary> /// Represents the name of the employee information. /// </summary> private string name; /// <summary> /// Represents the last name of the employee information. /// </summary> private string lastname; /// <summary> /// Represents the phone number of the employee information. /// </summary> private string phonenumber; /// <summary> /// Represents the country of the employee information. /// </summary> private string country; /// <summary> /// Represents the address of the employee information. /// </summary> private string employeeAddress; /// <summary> /// Represents the city of the employee information. /// </summary> private string city; /// <summary> /// Represents the first zip of the employee information. /// </summary> private string employeeZip; /// <summary> /// Represents the team of the employee information. /// </summary> private string team; /// <summary> /// Represents the track hours of the employee information. /// </summary> private bool trackhours; /// <summary> /// Represents the type here of the employee information. /// </summary> private string typehere; #endregion public EmployeeForm() { } /// <summary> /// Represents the method that will handle when a property is changed on a component. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the name field. /// </summary> [DisplayOptions(ColumnSpan = 4 , ShowLabel = false)] [Display(Prompt ="Enter name")] public string Name { get { return this.name; } set { this.name = value; this.RaisePropertyChanged("Name"); } } /// <summary> /// Gets or sets the last name field. /// </summary> [DisplayOptions(ColumnSpan = 4 , ShowLabel = false)] [Display(Prompt = "Enter last name")] public string LastName { get { return this.lastname; } set { this.lastname = value; this.RaisePropertyChanged("LastName"); } } /// <summary> /// Gets or sets the phone number field. /// </summary> [DisplayOptions(ColumnSpan = 4 , ShowLabel = false)] [Display(Prompt = "Enter phone number")] [DataType(DataType.PhoneNumber)] public string PhoneNumber { get { return this.phonenumber; } set { this.phonenumber = value; this.RaisePropertyChanged("PhoneNumber"); } } /// <summary> /// Gets or sets the country field. /// </summary> [DisplayOptions(ColumnSpan = 4, ShowLabel = false)] [Display(Prompt = "Enter country")] public string Country { get { return this.country; } set { this.country = value; this.RaisePropertyChanged("Country"); } } /// <summary> /// Gets or sets the address field. /// </summary> [DisplayOptions(ColumnSpan = 4 , ShowLabel = false)] [Display(Prompt = "Enter address")] [DataType(DataType.MultilineText)] public string EmployeeAddress { get { return this.employeeAddress; } set { this.employeeAddress = value; this.RaisePropertyChanged("EmployeeAddress"); } } /// <summary> /// Gets or sets the city field. /// </summary> [DisplayOptions(ColumnSpan = 2, ShowLabel = false)] [Display(Prompt = "Enter city")] public string City { get { return this.city; } set { this.city = value; this.RaisePropertyChanged("City"); } } /// <summary> /// Gets or sets the zip1 field. /// </summary> [DataType(DataType.PhoneNumber)] [Display(Prompt = " Enter zip")] [DisplayOptions(ColumnSpan = 2 , ShowLabel = false)] public string EmployeeZip { get { return this.employeeZip; } set { this.employeeZip = value; this.RaisePropertyChanged("EmployeeZip"); } } /// <summary> /// Gets or sets the team field. /// </summary> [DisplayOptions(ColumnSpan = 4 , ShowLabel = false)] [Display(Prompt = "Enter team name")] public string Team { get { return this.team; } set { this.team = value; this.RaisePropertyChanged("Team"); } } /// <summary> /// Gets or sets the track hours field. /// </summary> [DisplayOptions(ColumnSpan = 4)] [Display(ShortName = "Track hours")] public bool Trackhours { get { return this.trackhours; } set { this.trackhours = value; this.RaisePropertyChanged("Trackhours"); } } /// <summary> /// Gets or sets the type here field. /// </summary> [DisplayOptions(ColumnSpan = 4 , ShowLabel = false)] [Display(Prompt = "Enter your comments")] [DataType(DataType.MultilineText)] public string Typehere { get { return typehere; } set { typehere = value; this.RaisePropertyChanged("Typehere"); } } #endregion private void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/UnboundColumn.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Syncfusion.SfDataGrid; using Syncfusion.SfDataGrid.Renderers; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using UIKit; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] class UnboundColumn : SampleView { #region Fields SfDataGrid SfGrid; SalesInfoViewModel viewModel; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public UnboundColumn() { this.SfGrid = new SfDataGrid(); this.viewModel = new SalesInfoViewModel(); this.SfGrid.ColumnSizer = ColumnSizer.Star; this.SfGrid.AutoGenerateColumns = false; this.SfGrid.ItemsSource = viewModel.DailySalesDetails; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.SelectionMode = SelectionMode.Multiple; this.SfGrid.SelectedIndex = 3; this.SfGrid.AllowResizingColumn = true; this.SfGrid.GridStyle = new UnboundRowStyle(); SfGrid.CellRenderers.Remove("Unbound"); SfGrid.CellRenderers.Add("Unbound", new UnboundColumnRenderer()); SfGrid.UnboundRows.Add(new GridUnboundRow() { Position = UnboundRowsPosition.FixedBottom }); SfGrid.QueryUnboundRow += SfGrid_QueryUnboundRow; SfGrid.SelectionChanged += SfGrid_SelectionChanged; SfGrid.QueryRowHeight += SfGrid_QueryRowHeight; GridTextColumn EmployeeName = new GridTextColumn(); EmployeeName.HeaderText = "Employee"; EmployeeName.TextAlignment = UITextAlignment.Left; EmployeeName.HeaderTextAlignment = UITextAlignment.Center; EmployeeName.HeaderCellTextSize = 12; EmployeeName.MappingName = "Name"; SfGrid.Columns.Add(EmployeeName); GridTextColumn QS1 = new GridTextColumn(); QS1.HeaderText = "2015"; QS1.Format = "C"; QS1.HeaderTextAlignment = UITextAlignment.Center; QS1.HeaderCellTextSize = 12; QS1.TextAlignment = UITextAlignment.Right; QS1.MappingName = "QS1"; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.SfGrid.UnboundRows.Insert(0, new GridUnboundRow() { Position = UnboundRowsPosition.FixedTop }); this.SfGrid.UnboundRows.Insert(0, new GridUnboundRow() { Position = UnboundRowsPosition.Top }); SfGrid.Columns.Add(QS1); } GridTextColumn QS2 = new GridTextColumn(); QS2.HeaderText = "2016"; QS2.Format = "C"; QS2.HeaderTextAlignment = UITextAlignment.Center; QS2.HeaderCellTextSize = 12; QS2.TextAlignment = UITextAlignment.Right; QS2.MappingName = "QS2"; SfGrid.Columns.Add(QS2); GridTextColumn QS3 = new GridTextColumn(); QS3.HeaderText = "2017"; QS3.Format = "C"; QS3.HeaderTextAlignment = UITextAlignment.Center; QS3.HeaderCellTextSize = 12; QS3.TextAlignment = UITextAlignment.Right; QS3.MappingName = "QS3"; SfGrid.Columns.Add(QS3); GridUnboundColumn Total = new GridUnboundColumn(); Total.TextAlignment = UITextAlignment.Center; if (UserInterfaceIdiomIsPhone) { Total.Expression = "(QS2 + QS3)"; } else { Total.Expression = "(QS1 + QS2 + QS3 )"; } Total.Format = "C"; Total.HeaderText = "Total"; Total.HeaderTextAlignment = UITextAlignment.Center; Total.HeaderCellTextSize = 12; Total.TextAlignment = UITextAlignment.Center; Total.MappingName = "Total"; SfGrid.Columns.Add(Total); foreach (GridColumn column in SfGrid.Columns) { if (UserInterfaceIdiomIsPhone) SfGrid.ColumnSizer = ColumnSizer.None; else SfGrid.ColumnSizer = ColumnSizer.Star; } this.AddSubview(SfGrid); } private void SfGrid_QueryRowHeight(object sender, QueryRowHeightEventArgs e) { if (SfGrid.IsUnboundRow(e.RowIndex)) { e.Height = 70; e.Handled = true; } } private void SfGrid_SelectionChanged(object sender, GridSelectionChangedEventArgs e) { this.SfGrid.InvalidateUnboundRow(this.SfGrid.UnboundRows[this.SfGrid.UnboundRows.Count - 1]); } private void SfGrid_QueryUnboundRow(object sender, GridUnboundRowEventArgs e) { if (e.GridUnboundRow != null) { if (e.UnboundAction == UnboundActions.QueryData) { if (e.GridUnboundRow.Position == UnboundRowsPosition.FixedTop) { double sum = 0; if (e.RowColumnIndex.ColumnIndex == 0) { e.Value = "Total sales by year"; } else if (e.RowColumnIndex.ColumnIndex == 1) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS1; e.Value = sum; } } else if (e.RowColumnIndex.ColumnIndex == 2) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS2; e.Value = sum; } } else if (e.RowColumnIndex.ColumnIndex == 3) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS3; e.Value = sum; } } else if (e.RowColumnIndex.ColumnIndex == 4) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS1 + this.viewModel.DailySalesDetails[i].QS2 + this.viewModel.DailySalesDetails[i].QS3; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } } else if (e.GridUnboundRow.Position == UnboundRowsPosition.Top) { double sum = 0; if (e.RowColumnIndex.ColumnIndex == 0) { e.Value = "Average by year"; } else if (e.RowColumnIndex.ColumnIndex == 1) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS1; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } else if (e.RowColumnIndex.ColumnIndex == 2) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS2; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } else if (e.RowColumnIndex.ColumnIndex == 3) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS3; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } else if (e.RowColumnIndex.ColumnIndex == 4) { for (int i = 0; i < this.viewModel.DailySalesDetails.Count; i++) { sum += this.viewModel.DailySalesDetails[i].QS1 + this.viewModel.DailySalesDetails[i].QS2 + this.viewModel.DailySalesDetails[i].QS3; e.Value = sum / this.viewModel.DailySalesDetails.Count; } } } else if (e.GridUnboundRow.Position == UnboundRowsPosition.FixedBottom) { double sum = 0; if (e.RowColumnIndex.ColumnIndex == 0) { e.Value = "Sum of selection"; } else if (e.RowColumnIndex.ColumnIndex == 1) { if (this.SfGrid.SelectedItems.Count > 0) { for (int i = 0; i < this.SfGrid.SelectedItems.Count; i++) { e.Value = sum += this.SfGrid.SelectedItems[i] != null ? (this.SfGrid.SelectedItems[i] as SalesByDate).QS2 : 0; } } else { e.Value = null; } } else if (e.RowColumnIndex.ColumnIndex == 2) { if (this.SfGrid.SelectedItems.Count > 0) { for (int i = 0; i < this.SfGrid.SelectedItems.Count; i++) { e.Value = sum += this.SfGrid.SelectedItems[i] != null ? (this.SfGrid.SelectedItems[i] as SalesByDate).QS3 : 0; } } else { e.Value = null; } } else if (e.RowColumnIndex.ColumnIndex == 3) { if (this.SfGrid.SelectedItems.Count > 0) { for (int i = 0; i < this.SfGrid.SelectedItems.Count; i++) { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { e.Value = sum += this.SfGrid.SelectedItems[i] != null ? (this.SfGrid.SelectedItems[i] as SalesByDate).QS1 + (this.SfGrid.SelectedItems[i] as SalesByDate).QS2 + (this.SfGrid.SelectedItems[i] as SalesByDate).QS3 : 0; } else { e.Value = sum += this.SfGrid.SelectedItems[i] != null ? (this.SfGrid.SelectedItems[i] as SalesByDate).QS2 + (this.SfGrid.SelectedItems[i] as SalesByDate).QS3 : 0; } } } else { e.Value = null; } } } e.Handled = true; } } } public override void LayoutSubviews() { this.SfGrid.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { if (disposing) { if (SfGrid != null) { SfGrid.Dispose(); SfGrid = null; } base.Dispose(disposing); } } } public class UnboundColumnRenderer : GridUnboundCellTextBoxRenderer { public UnboundColumnRenderer() { } public override void OnInitializeDisplayView(DataColumnBase dataColumn, UILabel view) { base.OnInitializeDisplayView(dataColumn, view); var gridcell = dataColumn.GetType().GetRuntimeProperties().FirstOrDefault(x => x.Name.Equals("Element")).GetValue(dataColumn); (gridcell as UIView).BackgroundColor = UIColor.FromRGB(225, 245, 254); } } public class UnboundRowStyle : DefaultStyle { public UnboundRowStyle() { } public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Both; } public override UIColor GetUnboundRowBackgroundColor() { return UIColor.FromRGB(225, 245, 254); } } } <file_sep>/iOS/SampleBrowser/Samples/PopupLayout/Details View/DetailsView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreAnimation; using CoreGraphics; using Foundation; using Syncfusion.DataSource; using System; using System.Collections.Generic; using System.Reflection; using System.Text; using UIKit; using Syncfusion.iOS.PopupLayout; using System.Threading.Tasks; namespace SampleBrowser { public class DetailsView : SampleView { #region Fields UITableView tableView; ContatsViewModel viewModel; DataSource sfDataSource; SfPopupLayout initialPopup; #endregion #region Constructor public DetailsView() { tableView = new UITableView(); tableView.RowHeight = 70; tableView.SeparatorColor = UIColor.Clear; tableView.EstimatedRowHeight = 70; tableView.AllowsSelection = false; viewModel = new ContatsViewModel(); sfDataSource = new DataSource(); sfDataSource.Source = viewModel.ContactsList; tableView.Source = new PopupTableViewSource(sfDataSource); tableView.ContentInset = new UIEdgeInsets(-30, 0, 0 ,0); tableView.BackgroundColor = UIColor.FromRGB(244, 244, 244); tableView.SectionHeaderHeight = 50; tableView.ScrollEnabled = true; DisplayInitialPopup(); this.AddSubview(tableView); } private void DisplayInitialPopup() { initialPopup = new SfPopupLayout(); initialPopup.PopupView.AppearanceMode = AppearanceMode.OneButton; initialPopup.PopupView.PopupStyle.HeaderBackgroundColor = UIColor.White; initialPopup.PopupView.FooterHeight = initialPopup.PopupView.FooterHeight - 10; initialPopup.PopupView.ShowFooter = true; initialPopup.PopupView.ShowCloseButton = false; initialPopup.PopupView.HeaderTitle = "Notification !"; initialPopup.PopupView.AcceptButtonText = "OK"; initialPopup.StaysOpen = true; UILabel messageView = new UILabel(); messageView.Text = "Click on the contact tile to view the options"; messageView.TextColor = UIColor.Black; messageView.LineBreakMode = UILineBreakMode.WordWrap; messageView.Lines = 5; messageView.TextAlignment = UITextAlignment.Center; messageView.BackgroundColor = UIColor.White; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { initialPopup.PopupView.PopupStyle.HeaderFontSize = 14; messageView.Font = UIFont.PreferredCaption1; initialPopup.PopupView.Frame = new CGRect(-1, -1, (UIScreen.MainScreen.ApplicationFrame.Width / 10) * 8, 180); } else { initialPopup.PopupView.PopupStyle.HeaderFontSize = 20; messageView.Font = UIFont.PreferredBody; initialPopup.PopupView.Frame = new CGRect(-1, -1, -1, 200); } initialPopup.PopupView.ContentView = messageView; initialPopup.Show(); } #endregion #region Override Methods public override void LayoutSubviews() { tableView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } #endregion } public class PopupTableViewSource : UITableViewSource { #region Field DataSource dataSource; #endregion #region Constructor public PopupTableViewSource(DataSource sfDataSource) { dataSource = sfDataSource; } #endregion #region implemented abstract members of UITableViewDataSource public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath) { var item = dataSource.DisplayItems[indexPath.Row]; if (item is Contacts) { PopupContactCell cell = tableView.DequeueReusableCell("TableCell") as PopupContactCell; if (cell == null) cell = new PopupContactCell(); cell.UpdateValue(item); return cell; } return new UITableViewCell(); } public override nint RowsInSection(UITableView tableView, nint section) { return (nint)dataSource.DisplayItems.Count; } public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath) { return tableView.RowHeight; } public override UIView GetViewForHeader(UITableView tableView, nint section) { var mainView = new UIView(); var view = new UILabel(); mainView.Layer.AddSublayer(new CALayer()); mainView.Layer.Frame = tableView.Frame; mainView.Layer.Sublayers[0].BackgroundColor = UIColor.FromRGB(244, 244, 244).CGColor; mainView.Layer.Sublayers[0].Frame = new CGRect(0, 0, 15, 50); view.Frame = new CGRect(15, 20, tableView.Frame.Width - 15, 50); view.BackgroundColor = UIColor.FromRGB(244, 244, 244); view.Text = "Today"; view.TextColor = UIColor.FromRGB(0, 0, 0); mainView.AddSubview(view); return mainView; } #endregion } public class PopupContactCell : UITableViewCell { #region Field private UIImageView imageView1; private UIImageView imageView2; private UILabel Label1; private UILabel Label2; private UILabel Label3; private UILabel Label4; internal static UILabel currentLabel; UILabel overlayTags; SfPopupLayout detailsPopup; #endregion #region Constructor public PopupContactCell() { this.AutosizesSubviews = false; this.BackgroundColor = UIColor.FromRGB(255, 255, 255); Label1 = CreateLabel(Label1); Label1.Font = UIFont.FromName("Helvetica Neue", 15); Label2 = CreateLabel(Label2); Label2.TextColor = UIColor.LightGray; imageView1 = new UIImageView(); imageView2 = new UIImageView() { Alpha = 0.54f }; Label3 = new UILabel() { BackgroundColor = UIColor.FromRGB(244, 244, 244) }; Label4 = new UILabel() { BackgroundColor = UIColor.FromRGB(244, 244, 244) }; SelectionStyle = UITableViewCellSelectionStyle.Blue; this.AddSubviews(new UIView[] { Label3, imageView1, Label1, Label2, imageView2, Label4 }); this.Layer.AddSublayer(new CALayer()); } #endregion #region Private Method private UILabel CreateLabel(UILabel label) { label = new UILabel(); label.TextColor = UIColor.Black; label.TextAlignment = UITextAlignment.Left; label.LineBreakMode = UILineBreakMode.CharacterWrap; label.Font = UIFont.FromName("Helvetica Neue", 11); return label; } Random r = new Random(); public void UpdateValue(object obj) { var contact = obj as Contacts; Label1.Text = contact.ContactName; Label2.Text = contact.ContactNumber; imageView1.Image = UIImage.FromBundle("Images/PopupImage" + r.Next(1, 10) + ".png"); imageView2.Image = UIImage.FromBundle("Images/Popup_CallerImage.png"); } #endregion #region override public override void LayoutSubviews() { this.Layer.Frame = this.Frame; this.Layer.Sublayers[0].BackgroundColor = UIColor.FromRGB(244, 244, 244).CGColor; this.Layer.Sublayers[0].Frame = new CGRect(0, 0, this.Frame.Width, 10); nfloat y = 0; foreach (var subview in this.Subviews) { if (subview is UILabel && !(subview == imageView1) && subview != Label3 && subview != Label4) { subview.Frame = new CoreGraphics.CGRect(imageView1.Frame.Right + 20, y + 20, (this.Frame.Width - imageView1.Frame.Right - 85), this.Frame.Height / 3); y += subview.Frame.Height; } else if (subview == imageView1) { subview.Frame = new CGRect(Label3.Frame.Right + 10, 23, 33, 35); } else if (subview is UIImageView && subview == imageView2) { subview.Frame = new CoreGraphics.CGRect(Label1.Frame.Right + 20, 28, 25, this.Frame.Height - 48); } else if (subview == Label3) { subview.Frame = new CGRect(0, 0, 10, this.Frame.Height); } else if (subview == Label4) { subview.Frame = new CGRect(imageView2.Frame.Right + 10, 0, 16, this.Frame.Height); } } } public override void TouchesEnded(NSSet touches, UIEvent evt) { base.TouchesEnded(touches, evt); foreach (var view in this.Subviews) { if (view == Label1) { currentLabel = Label1; break; } } DisplayDetailsPopup(); } private void DisplayDetailsPopup() { detailsPopup = new SfPopupLayout(); detailsPopup.PopupView.BackgroundColor = UIColor.FromRGB(255, 255, 255); detailsPopup.PopupView.PopupStyle.BorderThickness = 5; detailsPopup.PopupView.ShowHeader = false; detailsPopup.PopupView.ShowFooter = false; detailsPopup.PopupView.Frame = new CGRect(-1, -1, this.Frame.Width - Label4.Frame.Width - 5, 150); detailsPopup.PopupView.ContentView = GetCustomPopupView(); // In iPhone the parent is directly UITableView but in iPOD and iPAD the immedidate super view is not UITableView. Hence checked superview based on condition. if ((this.Frame.Bottom + detailsPopup.PopupView.Frame.Height) - (UIDevice.CurrentDevice.Model == "iPhone" ? (this.Superview as UITableView).ContentOffset.Y : (this.Superview.Superview as UITableView).ContentOffset.Y) +10 <= this.Superview.Frame.Bottom) { detailsPopup.ShowRelativeToView(this, RelativePosition.AlignBottom, 10, 0); } else { detailsPopup.ShowRelativeToView(this, RelativePosition.AlignTop, 10, 0); } } private UIView GetCustomPopupView() { UIImageView imageView1; UIImageView imageView2; UIImageView imageView3; UILabel label1; UILabel label2; UILabel label3; UIView view1; UIView view2; UIView view3; UIView mainView; var height = detailsPopup.PopupView.Frame.Height / 3; imageView1 = new UIImageView(); imageView1.Image = UIImage.FromBundle("Images/Popup_SendMessage.png"); imageView1.Alpha = 0.54f; imageView1.Frame = new CGRect(10, 15, 20, 20); label1 = new UILabel(); label1.Text = "Send Message"; var tapGesture1 = new UITapGestureRecognizer(DisplayToast) { NumberOfTapsRequired = 1 }; label1.AddGestureRecognizer(tapGesture1); label1.TextColor = UIColor.FromRGB(0, 0, 0); label1.Alpha = 0.54f; label1.Tag = 11; label1.UserInteractionEnabled = true; label1.Frame = new CGRect(50, 13, this.Frame.Width, 20); view1 = new UIView(); view1.AddSubview(imageView1); view1.AddSubview(label1); view1.Frame = new CGRect(10, 0, this.Frame.Width, height); imageView2 = new UIImageView(); imageView2.Image = UIImage.FromBundle("Images/Popup_BlockContact.png"); imageView2.Alpha = 0.54f; imageView2.Frame = new CGRect(10, 13, 22, 22); label2 = new UILabel(); label2.Text = "Block/report contact"; label2.TextColor = UIColor.FromRGB(0, 0, 0); label2.UserInteractionEnabled = true; var tapGesture2 = new UITapGestureRecognizer(DisplayToast) { NumberOfTapsRequired = 1 }; label2.AddGestureRecognizer(tapGesture2); label2.Alpha = 0.54f; label2.Tag = 22; label2.Frame = new CGRect(50, 13, this.Frame.Width, 20); view2 = new UIView(); view2.AddSubview(imageView2); view2.AddSubview(label2); view2.Frame = new CGRect(10, height, this.Frame.Width, height); imageView3 = new UIImageView(); imageView3.Image = UIImage.FromBundle("Images/Popup_ContactInfo.png"); imageView3.Alpha = 0.54f; imageView3.Frame = new CGRect(10, 13, 22, 22); label3 = new UILabel(); label3.Text = "Contact Details"; label3.UserInteractionEnabled = true; label3.TextColor = UIColor.FromRGB(0, 0, 0); var tapGesture3 = new UITapGestureRecognizer(DisplayToast) { NumberOfTapsRequired = 1 }; label3.AddGestureRecognizer(tapGesture3); label3.Alpha = 0.54f; label3.Tag = 33; label3.Frame = new CGRect(50, 13, this.Frame.Width, 20); view3 = new UIView(); view3.AddSubview(imageView3); view3.AddSubview(label3); view3.Frame = new CGRect(10, height * 2, this.Frame.Width, height); mainView = new UIView(); mainView.BackgroundColor = UIColor.FromRGB(255, 255, 255); mainView.AddSubview(view1); mainView.AddSubview(view2); mainView.AddSubview(view3); return mainView; } async void DisplayToast(UITapGestureRecognizer tasture) { overlayTags = new UILabel(); overlayTags.Hidden = false; if(tasture.View.Tag == 11) overlayTags.Text = "Message sent"; else if(tasture.View.Tag == 22) overlayTags.Text = "Contact blocked"; else if(tasture.View.Tag == 33) overlayTags.Text = "No outgoing call history"; overlayTags.Layer.CornerRadius = 20f; overlayTags.TextColor = UIColor.White; overlayTags.TextAlignment = UITextAlignment.Center; overlayTags.ClipsToBounds = true; //overlayTags.Alpha = 0.0f; overlayTags.Font = UIFont.SystemFontOfSize(14); overlayTags.BackgroundColor = UIColor.FromRGB(101.0f / 255.0f, 101.0f / 255.0f, 101.0f / 255.0f); overlayTags.Layer.ZPosition = 1000; UIApplication.SharedApplication.KeyWindow.RootViewController.View.AddSubview(overlayTags); overlayTags.Frame = new CGRect((UIScreen.MainScreen.Bounds.Width / 2) - 100, UIScreen.MainScreen.Bounds.Height - 70, 200, 40); UIView.Animate(0.5, 0, UIViewAnimationOptions.CurveLinear, () => { overlayTags.Alpha = 1.0f; }, () => { UIView.Animate(3.0, () => { overlayTags.Alpha = 0.0f; }); } ); detailsPopup.IsOpen = false; await Task.Delay(700); overlayTags.RemoveFromSuperview(); } #endregion } } <file_sep>/Forms/RichTextEditor/RichTextEditor.Android/RTECustomEntryRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Content.Res; using Android.Graphics.Drawables; using Android.OS; using Android.Runtime; using Android.Text; using Android.Views; using Android.Widget; using SampleBrowser.SfRichTextEditor; using SampleBrowser.SfRichTextEditor.Droid; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(RTECustomEntry), typeof(RTECustomEntryRenderer))] namespace SampleBrowser.SfRichTextEditor.Droid { public class RTECustomEntryRenderer : EntryRenderer { public RTECustomEntryRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { GradientDrawable gd = new GradientDrawable(); gd.SetColor(global::Android.Graphics.Color.Transparent); this.Control.Background = gd; this.Control.SetRawInputType(InputTypes.TextFlagNoSuggestions); Control.SetHintTextColor(ColorStateList.ValueOf(global::Android.Graphics.Color.ParseColor("#595959"))); } } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/FrozenView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Text; using Syncfusion.SfDataGrid; using Android.Graphics; using System.Globalization; using Syncfusion.GridCommon.ScrollAxis; using Android.Content.Res; namespace SampleBrowser { public class FrozenView : SamplePage { #region Fields SfDataGrid sfGrid; FrozenViewViewModel viewModel; View frozenView; RelativeLayout relativeLayout; #endregion #region Override Methods public override View GetSampleContent(Context context) { sfGrid = new SfDataGrid(context); viewModel = new FrozenViewViewModel (); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = viewModel.Products; sfGrid.SelectionMode = SelectionMode.Single; sfGrid.FrozenRowsCount = 2; sfGrid.FrozenColumnsCount = 1; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; sfGrid.GridLoaded += DataGrid_GridLoaded; frozenView = new View(context); frozenView.SetBackgroundColor(Color.ParseColor("#757575")); relativeLayout = new RelativeLayout(context); relativeLayout.AddView(sfGrid); relativeLayout.AddView(frozenView, ViewGroup.LayoutParams.MatchParent, (int)(1 * Resources.System.DisplayMetrics.Density)); return relativeLayout; } private void DataGrid_GridLoaded(object sender, GridLoadedEventArgs e) { var point = sfGrid.RowColumnIndexToPoint(new RowColumnIndex(sfGrid.FrozenRowsCount, 0)); frozenView.SetX(point.X); frozenView.SetY(point.Y + (int)sfGrid.RowHeight); } public override void Destroy() { sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; sfGrid.Dispose(); sfGrid = null; viewModel = null; } #endregion #region CallBacks private void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "SupplierID") { e.Column.HeaderText = "Supplier ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "ProductID") { e.Column.HeaderText = "Product ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "ProductName") { e.Column.HeaderText = "Product Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Quantity") { e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "UnitPrice") { e.Column.HeaderText = "Unit Price"; e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); } else if (e.Column.MappingName == "UnitsInStock") { e.Column.HeaderText = "Units In Stock"; e.Column.TextAlignment = GravityFlags.Center; } } #endregion } }<file_sep>/Forms/SignaturePad/SignaturePad/Samples/SignaturePadGettingStarted/View/SignatureImagePage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.Pdf.Parsing; using Syncfusion.SfPdfViewer.XForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfSignaturePad { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SignatureImagePage : ContentPage , INotifyPropertyChanged { /// <summary> /// m_pdfDocumentStream /// </summary> private Stream m_pdfDocumentStream; /// <summary> /// filePath /// </summary> string filePath = string.Empty; /// <summary> /// currentDocument /// </summary> string currentDocument = "FormFillingDocument"; /// <summary> /// Signimage /// </summary> Image Signimage = new Image(); /// <summary> /// PdfDocumentStream /// </summary> public Stream PdfDocumentStream { get { return m_pdfDocumentStream; } set { m_pdfDocumentStream = value; NotifyPropertyChanged("PdfDocumentStream"); } } /// <summary> /// SignatureImagePage /// </summary> /// <param name="image">image</param> public SignatureImagePage(ImageSource imagesource) { InitializeComponent(); BindingContext = this; pdfViewerControl.IsToolbarVisible = false; pdfViewerControl.DocumentLoaded += PdfViewerControl_DocumentLoaded; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfSignaturePad."; #endif Signimage.WidthRequest = 200; Signimage.HeightRequest = 150; Signimage.Source = imagesource; } /// <summary> /// OnAppearing /// </summary> protected override void OnAppearing() { PdfDocumentStream = (typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath + "Assets." + currentDocument + ".pdf")); PdfLoadedDocument ldoc = new PdfLoadedDocument(PdfDocumentStream); if (ldoc.Form != null) { foreach (var field in ldoc.Form.Fields) { if (field is PdfLoadedSignatureField) { (field as PdfLoadedSignatureField).ReadOnly = true; } } } MemoryStream strm = new MemoryStream(); ldoc.Save(strm); pdfViewerControl.LoadDocument(strm); } private async void PdfViewerControl_DocumentLoaded(object sender, EventArgs args) { await Task.Delay(100); if(Device.RuntimePlatform == "Android") pdfViewerControl.AddStamp(Signimage, 1, new Point(250, 850)); else pdfViewerControl.AddStamp(Signimage, 1, new Point(220, 600)); } public event PropertyChangedEventHandler PropertyChangedEvent; private void NotifyPropertyChanged(string propertyName) { if (PropertyChangedEvent != null) { PropertyChangedEvent(this, new PropertyChangedEventArgs(propertyName)); } } } }<file_sep>/iOS/SampleBrowser/Samples/DataSource/DataSourceGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Syncfusion.DataSource; using System; using System.Collections.Generic; using System.Text; using UIKit; namespace SampleBrowser { public class DataSourceGettingStarted : SampleView { #region Field UITableView tableView; DataSource sfDataSource; UISearchBar searchbar; DataSourceOptionsView option; DataSourceGettingStartedViewModel viewModel; #endregion #region Constructor public DataSourceGettingStarted() { tableView = new UITableView(); tableView.RowHeight = 100; tableView.SeparatorColor = UIColor.Clear; tableView.EstimatedRowHeight = 100; viewModel = new DataSourceGettingStartedViewModel(); viewModel.SetRowstoGenerate(100); sfDataSource = new DataSource(); sfDataSource.Source = viewModel.BookInfo; sfDataSource.DisplayItems.CollectionChanged += DisplayItems_CollectionChanged; sfDataSource.LiveDataUpdateMode = Syncfusion.DataSource.LiveDataUpdateMode.AllowDataShaping; sfDataSource.SortDescriptors.Add(new SortDescriptor() { Direction = Syncfusion.DataSource.ListSortDirection.Descending, PropertyName = "BookID", }); tableView.Source = new TableViewSource(sfDataSource); searchbar = new UISearchBar (); searchbar.OnEditingStarted += HandleOnEditingStarted; searchbar.TextChanged += HandleTextChanged; searchbar.CancelButtonClicked += HandleCancelButtonClicked; searchbar.EnablesReturnKeyAutomatically = false; searchbar.Placeholder = "Search in All Columns"; viewModel.filtertextchanged = OnFilterChanged; option = new DataSourceOptionsView (viewModel,searchbar,this); this.OptionView = option; this.AddSubview(searchbar); this.AddSubview(this.tableView); } private void DisplayItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { tableView.ReloadData(); } #endregion internal void OnFilterChanged() { if (this.sfDataSource != null) { sfDataSource.Filter = viewModel.FilerRecords; sfDataSource.RefreshFilter(); } } void HandleCancelButtonClicked(object sender, EventArgs e) { searchbar.ResignFirstResponder(); searchbar.SetShowsCancelButton(false, true); } void HandleTextChanged(object sender, UISearchBarTextChangedEventArgs e) { viewModel.FilterText = e.SearchText; } void HandleOnEditingStarted(object sender, EventArgs e) { searchbar.SetShowsCancelButton(true, true); } public override void LayoutSubviews() { searchbar.Frame = (new CGRect(0, 0, this.Frame.Width, 40)); if (UIDevice.CurrentDevice.CheckSystemVersion(7, 1)) { searchbar.SizeToFit(); this.tableView.Frame = new CGRect(0, searchbar.Bounds.Height, this.Frame.Width, this.Frame.Height - 44); } else { searchbar.SizeToFit(); this.tableView.Frame = new CGRect(0, searchbar.Bounds.Height, this.Frame.Width, this.Frame.Height - 44); } base.LayoutSubviews(); } } } <file_sep>/Forms/Chat/Chat.iOS/Main.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Main.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1649:FileHeaderFileNameDocumentationMustMatchTypeName", Justification = "Reviewed.")] [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed.")] namespace SampleBrowser.SfChat.iOS { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Foundation; using UIKit; /// <summary> /// Main class for Loading application in IOS platform. /// </summary> public class Application { /// <summary> /// This is the main entry point of the application. /// </summary> /// <param name="args">main entry point of the application args </param> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1400:AccessModifierMustBeDeclared", Justification = "Reviewed.")] static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } } <file_sep>/iOS/SampleBrowser/Utility/UIMarginLabel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Drawing; using CoreGraphics; using UIKit; namespace SampleBrowser { internal class UIMarginLabel : UILabel { #region ctor public UIMarginLabel() { } #endregion #region properties public UIEdgeInsets Insets { get; set; } #endregion #region methods public override void DrawText(CGRect rect) { base.DrawText(Insets.InsetRect(rect)); } #endregion } }<file_sep>/Forms/RichTextEditor/RichTextEditor/Samples/CustomToolbar/CustomToolbar.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.RichTextEditor; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using CustomItem = Syncfusion.XForms.Buttons; namespace SampleBrowser.SfRichTextEditor { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CustomToolbar : SampleView { CustomItem.SfButton readOnlyButton; CustomItem.SfButton emojiButton; Button emojiButtonIOS; public CustomToolbar() { InitializeComponent(); RTE.Text = "<p>Hi,<br><br>The rich text editor component is WYSIWYG (\"what you see is what you get\") editor that provides the best user experience to create and update the content.</p>"; AddCustomToolbarItems(); } private void AddCustomToolbarItems() { ObservableCollection<object> collection = new ObservableCollection<object>(); collection.Add(ToolbarOptions.Bold); collection.Add(ToolbarOptions.Italic); collection.Add(ToolbarOptions.Underline); collection.Add(ToolbarOptions.Strikethrough); collection.Add(ToolbarOptions.NumberList); collection.Add(ToolbarOptions.BulletList); if (Device.RuntimePlatform != Device.iOS) { readOnlyButton = new CustomItem.SfButton(); readOnlyButton.BackgroundColor = Color.Transparent; readOnlyButton.TextColor = Color.FromHex("#DE333333"); if (Device.RuntimePlatform == Device.Android) { readOnlyButton.HeightRequest = 44; readOnlyButton.FontFamily = "Text edit 2.ttf#"; readOnlyButton.Text = "\ue702"; } else if (Device.RuntimePlatform == Device.UWP) { readOnlyButton.FontFamily = "Text edit 2.ttf#Text edit 2"; readOnlyButton.Text = "\ue700"; } readOnlyButton.FontSize = 18; readOnlyButton.Clicked += ReadOnlyButton_Clicked; collection.Add(readOnlyButton); emojiButton = CreateButton("\U0001F642"); emojiButton.VerticalTextAlignment = TextAlignment.Center; emojiButton.Clicked += EmojiButton_Clicked; if (Device.RuntimePlatform == Device.UWP) { emojiButton.BorderColor = Color.Transparent; } collection.Add(emojiButton); } else { Button readonlyButtonIOS = new Button(); readonlyButtonIOS.FontFamily = "Text edit 2"; readonlyButtonIOS.Text = "\ue700"; readonlyButtonIOS.TextColor = Color.FromHex("#DE333333"); readonlyButtonIOS.Clicked += ReadonlyButtonIOS_Clicked; ; collection.Add(readonlyButtonIOS); emojiButtonIOS = new Button(); emojiButtonIOS.Text = "\U0001F642"; emojiButtonIOS.Clicked += EmojiButtonIOS_Clicked; collection.Add(emojiButtonIOS); } RTE.ToolbarItems = collection; } private void ReadonlyButtonIOS_Clicked(object sender, EventArgs e) { RTE.ReadOnly = !RTE.ReadOnly; emojiButtonIOS.IsEnabled = !RTE.ReadOnly; if (RTE.ReadOnly) { emojiButtonIOS.Opacity = 0.5; (sender as Button).Text = "\ue701"; } else { emojiButtonIOS.Opacity = 1; (sender as Button).Text = "\ue700"; } } private void EmojiButtonIOS_Clicked(object sender, EventArgs e) { RTE.InsertHTMLText("&#128522;"); } CustomItem.SfButton CreateButton(string text) { CustomItem.SfButton button = new CustomItem.SfButton(); if (Device.RuntimePlatform == Device.Android) { button.HeightRequest = 44; } button.BackgroundColor = Color.Transparent; button.TextColor = Color.FromHex("#DE333333"); if (Device.RuntimePlatform == Device.Android) { button.FontFamily = "android"; button.FontSize = 18; } else if (Device.RuntimePlatform == Device.UWP) { button.FontFamily = "V3 Xamarin iOS uwp new.ttf#V3 Xamarin iOS uwp new"; } button.Text = text; return button; } private void EmojiButton_Clicked(object sender, EventArgs e) { RTE.InsertHTMLText("&#128522;"); } private void ReadOnlyButton_Clicked(object sender, EventArgs e) { RTE.ReadOnly = !RTE.ReadOnly; emojiButton.IsEnabled = !RTE.ReadOnly; if (RTE.ReadOnly) { emojiButton.Opacity = 0.5; if (Device.RuntimePlatform == Device.Android) { readOnlyButton.Text = "\ue703"; } else if (Device.RuntimePlatform == Device.UWP) { emojiButton.BorderColor = Color.Default; readOnlyButton.Text = "\ue701"; } } else { emojiButton.Opacity = 1; if (Device.RuntimePlatform == Device.Android) { readOnlyButton.Text = "\ue702"; } else if (Device.RuntimePlatform == Device.UWP) { emojiButton.BorderColor = Color.Transparent; readOnlyButton.Text = "\ue700"; } } } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/PullToRefresh.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.SfDataGrid; using System.Globalization; using System.Threading.Tasks; using Syncfusion.SfPullToRefresh; namespace SampleBrowser { public class PullToRefresh:SamplePage { SfPullToRefresh pullToRefresh; SfDataGrid sfGrid; PullToRefreshViewModel viewModel; public override View GetSampleContent(Context context) { pullToRefresh = new SfPullToRefresh(context); pullToRefresh.Refreshing += Pull_Refreshing; sfGrid = new SfDataGrid(context); sfGrid.HeaderRowHeight = 52; pullToRefresh.RefreshContentThreshold = 52; sfGrid.RowHeight = 48; viewModel = new PullToRefreshViewModel(); sfGrid.SelectionMode = SelectionMode.Single; viewModel.SetRowstoGenerate(100); sfGrid.AutoGenerateColumns = false; sfGrid.ColumnSizer = ColumnSizer.Star; GridGenerateColumns(); sfGrid.ItemsSource = (viewModel.OrdersInfo); sfGrid.AllowResizingColumn = true; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; pullToRefresh.PullableContent = sfGrid; return pullToRefresh; } #region Private Methods void GridGenerateColumns() { sfGrid.Columns.Add(new GridTextColumn() { MappingName = "OrderID", HeaderText = "Order ID" }); sfGrid.Columns.Add(new GridTextColumn() { MappingName = "CustomerID", HeaderText = "Customer ID", TextAlignment = GravityFlags.CenterVertical }); sfGrid.Columns.Add(new GridTextColumn() { MappingName = "Freight", Format = "C", CultureInfo = new CultureInfo("en-US"), TextAlignment = GravityFlags.Center }); sfGrid.Columns.Add(new GridTextColumn() { MappingName = "ShipCity", HeaderText = "Ship City", TextAlignment = GravityFlags.CenterVertical }); } private async void Pull_Refreshing(object sender, RefreshingEventArgs e) { await Task.Delay(4000); if (viewModel != null) { viewModel.ItemsSourceRefresh(); e.Refreshed = true; } } #endregion public override void Destroy() { pullToRefresh.Refreshing -= Pull_Refreshing; viewModel = null; pullToRefresh.Dispose(); pullToRefresh = null; } } }<file_sep>/Forms/BadgeView/BadgeView/Samples/Customization/CustomizationModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace SampleBrowser.SfBadgeView { public class CustomizationModel { /// <summary> /// Gets or sets the image /// </summary> public Color BackgroundColor { get; set; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Kanban/CustomizationKanban.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using Syncfusion.SfKanban.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class CustomizationKanban : SampleView { SfKanban kanban; public CustomizationKanban() { kanban = new SfKanban(); KanbanErrorBarSettings errorBar = new KanbanErrorBarSettings(); errorBar.Height = 2; errorBar.Color = UIColor.FromRGB(179.0f / 255.0f, 71.0f / 255.0f, 36.0f / 255.0f); errorBar.MaxValidationColor = UIColor.FromRGB(211.0f / 255.0f, 51.0f / 255.0f, 54.0f / 255.0f); errorBar.MinValidationColor = UIColor.FromRGB(67.0f / 255.0f, 188.0f / 255.0f, 131.0f / 255.0f); KanbanPlaceholderStyle style = new KanbanPlaceholderStyle(); style.SelectedBackgroundColor = UIColor.FromRGB(250.0f / 255.0f, 199.0f / 255.0f, 173.0f / 255.0f); kanban.PlaceholderStyle = style; KanbanColumn column1 = new KanbanColumn() { Categories = new List<object>() { "Menu" } }; column1.Title = "Menu"; column1.ErrorBarSettings = errorBar; kanban.Columns.Add(column1); KanbanColumn column2 = new KanbanColumn() { Categories = new List<object>() { "Dining", "Delivery" } }; column2.Title = "Order"; column2.ErrorBarSettings = errorBar; kanban.Columns.Add(column2); KanbanColumn column3 = new KanbanColumn() { Categories = new List<object>() { "Ready to Serve" } }; column3.Title = "Ready to Serve"; column3.AllowDrag = false; column3.ErrorBarSettings = errorBar; kanban.Columns.Add(column3); KanbanColumn column4 = new KanbanColumn() { Categories = new List<object>() { "Door Delivery" } }; column4.Title = "Delivery"; column4.AllowDrag = false; column4.ErrorBarSettings = errorBar; kanban.Columns.Add(column4); kanban.ItemsSource = this.ItemsSourceCards(); List<KanbanWorkflow> flows = new List<KanbanWorkflow>(); flows.Add(new KanbanWorkflow("Menu", new List<object>() { "Dining", "Delivery" })); flows.Add(new KanbanWorkflow("Dining", new List<object>() { "Ready to Serve" })); flows.Add(new KanbanWorkflow("Delivery", new List<object>() { "Door Delivery" })); flows.Add(new KanbanWorkflow("Ready to Serve", new List<object>() { })); flows.Add(new KanbanWorkflow("Door Delivery", new List<object>() { })); kanban.Workflows = flows; kanban.DragStart += (object sender, KanbanDragStartEventArgs e) => { if ((e.Data as KanbanModel).Category.ToString() == "Menu") e.KeepItem = true; }; kanban.DragEnd += (object sender, KanbanDragEndEventArgs e) => { if (e.TargetColumn != null && e.SourceColumn.Categories.Contains("Menu")) { e.Cancel = true; e.TargetColumn.InsertItem(CloneModel((e.Data as KanbanModel),e.TargetCategory), e.TargetIndex); } else if (e.TargetColumn != null && e.TargetCategory != null) { (e.Data as KanbanModel).Category = e.TargetCategory; } }; this.AddSubview(kanban); } KanbanModel CloneModel(KanbanModel model, object category) { KanbanModel newModel = new KanbanModel(); newModel.ImageURL = model.ImageURL; newModel.Category = category; newModel.ColorKey = model.ColorKey; newModel.Description = model.Description; newModel.ID = model.ID; newModel.Tags = model.Tags; newModel.Title = model.Title; return newModel; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view == kanban) view.Frame = Bounds; } base.LayoutSubviews(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); kanban.Dispose(); } #region ItemsSource ObservableCollection<KanbanModel> ItemsSourceCards() { ObservableCollection<KanbanModel> cards = new ObservableCollection<KanbanModel>(); cards.Add( new KanbanModel() { ID = 1, Title = "Margherita", ImageURL = "margherita.png", Category = "Menu", Description = "The classic. Fresh tomatoes, garlic, olive oil, and basil. For pizza purists and minimalists only.", Tags = new string[] { "Cheese" } } ); cards.Add( new KanbanModel() { ID = 2, Title = "Double Cheese Margherita", ImageURL = "doublecheesemargherita.png", Category = "Menu", Description = "The minimalist classic with a double helping of cheese", Tags = new string[] { "Cheese" } } ); cards.Add( new KanbanModel() { ID = 3, Title = "Bucolic Pie", ImageURL = "bucolicpie.png", Category = "Menu", Description = "The pizza you daydream about to escape city life. Onions, peppers, and tomatoes. (Note: The “Onions” tag beneath the description in the screenshot is misspelled.)", Tags = new string[] { "Oninons", "Capsicum" } } ); cards.Add( new KanbanModel() { ID = 4, Title = "Bumper Crop", ImageURL = "bumpercrop.png", Category = "Menu", Description = "Can’t get enough veggies? Eat this. Carrots, mushrooms, potatoes, and way more", Tags = new string[] { "Tomato", "Mushroom" } } ); cards.Add( new KanbanModel() { ID = 5, Title = "Spice of Life", ImageURL = "spiceoflife.png", Category = "Menu", Description = "Thrill-seeking, heat-seeking pizza people only. It’s hot. Trust us.", Tags = new string[] { "Corn", "Gherkins" } } ); cards.Add( new KanbanModel() { ID = 6, Title = "Very Nicoise", ImageURL = "verynicoise.png", Category = "Menu", Description = "Anchovies, Dijon vinaigrette, shallots, red peppers, and potatoes.", Tags = new string[] { "Red pepper", "Capsicum" } } ); cards.Add( new KanbanModel() { ID = 7, Title = "Salad Daze", ImageURL = "saladdaze.png", Category = "Menu", Description = "Pretty much salad on a pizza. Broccoli, olives, cherry tomatoes, red onion.", Tags = new string[] { "Onions", "Jalapeno" } } ); cards.Add( new KanbanModel() { ID = 4, Title = "Bumper Crop", ImageURL = "bumpercrop.png", Category = "Ready to Serve", Description = "Can’t get enough veggies? Eat this. Carrots, mushrooms, potatoes, and way more", Tags = new string[] { "Tomato", "Mushroom" } } ); cards.Add( new KanbanModel() { ID = 5, Title = "Spice of Life", ImageURL = "spiceoflife.png", Category = "Ready to Serve", Description = "Thrill-seeking, heat-seeking pizza people only. It’s hot. Trust us.", Tags = new string[] { "Corn", "Gherkins" } } ); cards.Add( new KanbanModel() { ID = 3, Title = "Bucolic Pie", ImageURL = "bucolicpie.png", Category = "Door Delivery", Description = "The pizza you daydream about to escape city life. Onions, peppers, and tomatoes. (Note: The “Onions” tag beneath the description in the screenshot is misspelled.)", Tags = new string[] { "Oninons", "Capsicum" } } ); cards.Add( new KanbanModel() { ID = 6, Title = "Very Nicoise", ImageURL = "verynicoise.png", Category = "Dining", Description = "Anchovies, Dijon vinaigrette, shallots, red peppers, and potatoes.", Tags = new string[] { "Red pepper", "Capsicum" } } ); cards.Add( new KanbanModel() { ID = 2, Title = "Double Cheese Margherita", ImageURL = "doublecheesemargherita.png", Category = "Delivery", Description = "The minimalist classic with a double helping of cheese", Tags = new string[] { "Cheese" } } ); return cards; } #endregion } } <file_sep>/Forms/PDF/PDF/Samples/DigitalSignature/DigitalSignature.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Security; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.PDF { public partial class DigitalSignature : SampleView { public DigitalSignature() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { //Get the stream from the document. #if COMMONSB Stream docStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.SalesOrderDetail.pdf"); #else Stream docStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.SalesOrderDetail.pdf"); #endif //Load the PDF document into the loaded document object. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream); //Get the certificate stream from .pfx file. #if COMMONSB Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.PDF.pfx"); #else Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.PDF.pfx"); #endif //Create PdfCertificate using certificate stream and password. PdfCertificate pdfCert = new PdfCertificate(certificateStream, "<PASSWORD>"); //Add certificate to document first page. PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCert, "Signature"); signature.Bounds = new RectangleF(5, 5, 300, 300); MemoryStream stream = new MemoryStream(); //Save the PDF document loadedDocument.Save(stream); //Close the PDF document loadedDocument.Close(true); stream.Position = 0; //Open in default system viewer. if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<IMailService>().ComposeMail("DigitalSignature.pdf", null, "Signing the document", "Syncfusion", stream); else Xamarin.Forms.DependencyService.Get<IMailService>().ComposeMail("DigitalSignature.pdf", null, "Signing the document", "Syncfusion", stream); } } } <file_sep>/Android/SampleBrowser/Samples/Schedule/DragDrop.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Schedule; using Com.Syncfusion.Schedule.Enums; using Java.Util; using Android.Graphics; using Java.Text; namespace SampleBrowser { /// <summary> /// sample for drag and drop of schedule appointment. /// </summary> public class DragDrop : SamplePage, IDisposable { /// <summary> /// schedule initialization. /// </summary> private SfSchedule sfSchedule; private Context context; public override View GetSampleContent(Context context) { this.context = context; LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; //creating instance for Schedule sfSchedule = new SfSchedule(context); sfSchedule.ScheduleView = ScheduleView.WeekView; sfSchedule.AllowAppointmentDrag = true; sfSchedule.AppointmentDrop += SfSchedule_AppointmentDrop; NonAccessibleBlock nonAccessibleBlock = new NonAccessibleBlock(); //Create new instance of NonAccessibleBlocksCollection NonAccessibleBlocksCollection nonAccessibleBlocksCollection = new NonAccessibleBlocksCollection(); WeekViewSettings weekViewSettings = new WeekViewSettings(); nonAccessibleBlock.StartTime = 13; nonAccessibleBlock.EndTime = 14; nonAccessibleBlock.Text = "LUNCH"; nonAccessibleBlock.Color = Color.Black; nonAccessibleBlocksCollection.Add(nonAccessibleBlock); weekViewSettings.NonAccessibleBlocks = nonAccessibleBlocksCollection; sfSchedule.WeekViewSettings = weekViewSettings; //set the appointment collection GetAppointments(); sfSchedule.ItemsSource = appointmentCollection; linearLayout.AddView(sfSchedule); return linearLayout; } private void DisplayToast(string toastText) { Toast.MakeText(this.context, toastText, ToastLength.Short).Show(); } /// <summary> /// drop event for schedule appointment. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SfSchedule_AppointmentDrop(object sender, AppointmentDropEventArgs e) { e.Cancel = false; if (IsInNonAccessRegion(e.DropTime)) { e.Cancel = true; DisplayToast("Cannot be moved to blocked time slots"); return; } DisplayToast("Moved to " + GetFormattedDroppedTime(e.DropTime)); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private string GetFormattedDroppedTime(Calendar dropTime) { var format = new SimpleDateFormat("EEEE, d MMMM, h:mm a"); var date = format.Format(dropTime.Time); return date.ToString(); } /// <summary> /// check the drop time in non-accessible region. /// </summary> /// <param name="dropTime"></param> /// <returns></returns> private bool IsInNonAccessRegion(Calendar dropTime) { if (this.sfSchedule.WeekViewSettings.NonAccessibleBlocks[0].StartTime == dropTime.Get(CalendarField.HourOfDay) || (this.sfSchedule.WeekViewSettings.NonAccessibleBlocks[0].StartTime - 1 == dropTime.Get(CalendarField.HourOfDay) && dropTime.Get(CalendarField.Minute) > 0)) { return true; } return false; } private List<string> subjectCollection = new List<string>(); private List<string> colorCollection = new List<string>(); private List<Calendar> startTimeCollection = new List<Calendar>(); private List<Calendar> endTimeCollection = new List<Calendar>(); private ScheduleAppointmentCollection appointmentCollection; //Creating appointments for ScheduleAppointmentCollection private void GetAppointments() { appointmentCollection = new ScheduleAppointmentCollection(); SetColors(); RandomNumbers(); SetSubjects(); SetStartTime(); SetEndTime(); for (int i = 0; i < 10; i++) { var scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[i]); scheduleAppointment.Subject = subjectCollection[i]; scheduleAppointment.StartTime = startTimeCollection[i]; scheduleAppointment.EndTime = endTimeCollection[i]; if (i == 2 || i == 4) { scheduleAppointment.IsAllDay = true; } appointmentCollection.Add(scheduleAppointment); } } //adding subject collection private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); } // adding colors collection private void SetColors() { colorCollection = new List<String>(); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FF339933"); colorCollection.Add("#FF00ABA9"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF339933"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF00ABA9"); } private List<int> randomNums = new List<int>(); private void RandomNumbers() { randomNums = new List<int>(); Java.Util.Random rand = new Java.Util.Random(); for (int i = 0; i < 10; i++) { int randomNum = rand.NextInt((15 - 9) + 1) + 9; randomNums.Add(randomNum); } } // adding StartTime collection private void SetStartTime() { startTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -5; i < 5; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count], 0, 0); startTimeCollection.Add(startTime); count++; } } // adding EndTime collection private void SetEndTime() { endTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -5; i < 5; i++) { Calendar endTime = (Calendar)currentDate.Clone(); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count] + 1, 0, 0); endTimeCollection.Add(endTime); count++; } } public void Dispose() { if (sfSchedule != null) { sfSchedule.AppointmentDrop -= SfSchedule_AppointmentDrop; sfSchedule.Dispose(); sfSchedule = null; } } } }<file_sep>/Forms/SegmentedControl/SegmentedControl/Samples/SegmentCustomization/View/SegmentCustomization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.Core; using Syncfusion.XForms.Buttons; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SegmentedEventArgs = Syncfusion.XForms.Buttons.SelectionChangedEventArgs; namespace SampleBrowser.SegmentedControl { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SegmentCustomization : SampleView { #region Memebers /// <summary> /// customization view model initialization /// </summary> private CustomizationViewModel viewModel = new CustomizationViewModel(); #endregion #region Constructor /// <summary> /// Custom view constructor /// </summary> public SegmentCustomization() { InitializeComponent(); this.Backlight.ItemsSource = viewModel.BackLightCollection; this.IconSegment.ItemsSource = viewModel.IconCollection; this.PrimaryColorSegment.ItemsSource = viewModel.PrimaryColors; this.Image_Text.ItemsSource = viewModel.Image_textCollection; if (Device.Idiom == TargetIdiom.Desktop) { BackgroundGrid.VerticalOptions = LayoutOptions.Center; BackgroundGrid.HorizontalOptions = LayoutOptions.Center; BackgroundGrid.BackgroundColor = Color.Transparent; BackgroundGrid.HeightRequest = 500; BackgroundGrid.WidthRequest = 500; ContentGrid.RowDefinitions[0].Height = 100; ContentGrid.RowDefinitions[1].Height = 100; ContentGrid.RowDefinitions[2].Height = 100; MainScrollView.HorizontalOptions = LayoutOptions.Center; } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.Idiom != TargetIdiom.Desktop) { if (width > height) { BackgroundGrid.HeightRequest = width; } else BackgroundGrid.HeightRequest = height; } } #endregion #region Events /// <summary> /// Raised when change the color from segmented control. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Handle_SelectionChanged(object sender, SegmentedEventArgs e) { this.PrimaryColorSegment.SelectionTextColor = viewModel.PrimaryColors[e.Index].FontIconFontColor; } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Backlight_SelectionChanged(object sender, SegmentedEventArgs e) { if (e.Index == 1) { if (Device.RuntimePlatform == Device.UWP) { this.MainGrid.FadeTo(0.75, 250, Easing.Linear); } else this.MainGrid.FadeTo(0.5, 250, Easing.Linear); } else { this.MainGrid.FadeTo(1, 500, Easing.Linear); } } #endregion #region Dispose /// <summary> /// /// </summary> public void Dispose() { throw new NotImplementedException(); } #endregion } } <file_sep>/Forms/TabView/TabView/Samples/CenterButton/Converters.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfTabView { public class booltofontConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return FontAttributes.Bold; return FontAttributes.None; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class booltocolorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return Color.Black; return Color.Gray; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Forms/Chart/Chart/Samples/Legend/Legend.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfChart.XForms; using System; using System.ComponentModel; using System.Globalization; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class Legend : SampleBrowser.Core.SampleView { public Legend() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { if (Device.Idiom != TargetIdiom.Phone) { chart.Legend.DockPosition = LegendPlacement.Right; chart.Margin = new Thickness(200, 0, 200, 0); chart.Legend.MaxWidth = 200; if (Device.RuntimePlatform == Device.WPF) { chart.Legend.ItemMargin = new Thickness(6); } } } else { chart.Legend.StrokeDashArray = new double[] { 3, 3 }; if (Device.RuntimePlatform == Device.macOS) { chart.Legend.ItemMargin = new Thickness(20, 5, 5, 5); } else if (Device.RuntimePlatform == Device.iOS) { chart.Legend.ItemMargin = new Thickness(10, 5, 5, 5); } else { chart.Legend.ItemMargin = new Thickness(5); } } if (Device.RuntimePlatform == Device.macOS || Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { if (Device.RuntimePlatform == Device.macOS) { chart.Legend.OverflowMode = ChartLegendOverflowMode.Scroll; } chart.Legend.DockPosition = LegendPlacement.Right; } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if ((Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS)) { if (height > 0 && width > 0) { if (height > width) { chart.Legend.OverflowMode = ChartLegendOverflowMode.Wrap; chart.Legend.DockPosition = LegendPlacement.Bottom; } else { chart.Title.Margin = new Thickness(0); chart.Legend.DockPosition = LegendPlacement.Right; chart.Legend.OverflowMode = ChartLegendOverflowMode.Scroll; } } } else if (Device.RuntimePlatform == Device.macOS) { if (height > 0 && width > 0) { if (height > width) { stack.Padding = new Thickness(0); } else { double padding = (stack.Width - stack.Height) / 2; stack.Padding = new Thickness(padding / 3, 0, padding / 3, 0); } } }
 } } public class BoolToFontAttributesConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return FontAttributes.Bold; return FontAttributes.None; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }<file_sep>/iOS/SampleBrowser/Samples/DigitalGauge/DigitalGauge.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif using Syncfusion.SfGauge.iOS; namespace SampleBrowser { public class DigitalGauge : SampleView { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } #region View lifecycle public override void LayoutSubviews() { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { if (ObjCRuntime.Runtime.Arch == ObjCRuntime.Arch.SIMULATOR) { foreach (var view in this.Subviews) { view.Frame = Bounds; CGSize sz = this.Frame.Size; nfloat x = sz.Width / 2; segmentSevenGauge.Frame = new CGRect(20, 90, sz.Width - 50, 90); segmentFourteenGauge.Frame = new CGRect(20, 240, sz.Width - 50, 90); segmentSixteenGauge.Frame = new CGRect(20, 380, sz.Width - 50, 90); segmentMatrixGauge.Frame = new CGRect(20, 530, sz.Width - 50, 90); segmentSevenText.Frame = new CGRect(x - 50, 60, 100, 25); segmentFourteenText2.Frame = new CGRect(x - 50, 210, 100, 25); segmentSixteenText3.Frame = new CGRect(x - 50, 350, 100, 25); segmentMatrixText4.Frame = new CGRect(x - 50, 500, this.Frame.Width, 25); } } else { foreach (var view in this.Subviews) { view.Frame = Bounds; CGSize sz = this.Frame.Size; nfloat x = sz.Width / 2; nfloat xPos = sz.Width / 4; segmentSevenGauge.Frame = new CGRect(xPos, 90, sz.Width - 2 * xPos - 25, 90); segmentFourteenGauge.Frame = new CGRect(xPos, 240, sz.Width - 2 * xPos - 25, 90); segmentSixteenGauge.Frame = new CGRect(xPos, 380, sz.Width - 2 * xPos - 25, 90); segmentMatrixGauge.Frame = new CGRect(xPos, 530, sz.Width - 2 * xPos - 25, 90); segmentSevenText.Frame = new CGRect(x - 50, 60, 100, 25); segmentFourteenText2.Frame = new CGRect(x - 50, 210, 100, 25); segmentSixteenText3.Frame = new CGRect(x - 50, 350, 100, 25); segmentMatrixText4.Frame = new CGRect(x - 50, 500, this.Frame.Width, 25); } } } else { foreach (var view in this.Subviews) { view.Frame = Bounds; CGSize sz = this.Frame.Size; nfloat x = sz.Width / 2; segmentSevenGauge.Frame = new CGRect(x - 132, 60, 265, 60); segmentFourteenGauge.Frame = new CGRect(x - 132, 160, 265, 60); segmentSixteenGauge.Frame = new CGRect(x - 132, 260, 265, 60); segmentMatrixGauge.Frame = new CGRect(x - 132, 360, 265, 60); segmentSevenText.Frame = new CGRect(x - 50, 30, 100, 20); segmentFourteenText2.Frame = new CGRect(x - 50, 130, 100, 20); segmentSixteenText3.Frame = new CGRect(x - 50, 230, 100, 20); segmentMatrixText4.Frame = new CGRect(x - 60, 330, this.Frame.Width, 20); } } base.LayoutSubviews(); } SFDigitalGauge segmentMatrixGauge; SFDigitalGauge segmentSevenGauge; SFDigitalGauge segmentFourteenGauge; SFDigitalGauge segmentSixteenGauge; UILabel segmentSevenText, segmentFourteenText2, segmentSixteenText3, segmentMatrixText4; public DigitalGauge() { NSDate date = new NSDate(); NSString currentDateandTime = (NSString)date.ToString(); //SevenSegmentGauge segmentSevenGauge = new SFDigitalGauge(); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { segmentSevenGauge.CharacterHeight = 48; segmentSevenGauge.CharacterWidth = 24; segmentSevenGauge.VerticalPadding = 20; } else { segmentSevenGauge.CharacterHeight = 36; segmentSevenGauge.CharacterWidth = 18; segmentSevenGauge.VerticalPadding = 10; } segmentSevenGauge.SegmentWidth = 3; segmentSevenGauge.CharacterType = SFDigitalGaugeCharacterType.SFDigitalGaugeCharacterTypeSegmentSeven; segmentSevenGauge.StrokeType = SFDigitalGaugeStrokeType.SFDigitalGaugeStrokeTypeTriangleEdge; segmentSevenGauge.Value = currentDateandTime; segmentSevenGauge.DimmedSegmentAlpha = 0.11f; segmentSevenGauge.BackgroundColor = UIColor.FromRGB(248, 248, 248); segmentSevenGauge.CharacterColor = UIColor.FromRGB(20, 108, 237); segmentSevenGauge.DimmedSegmentColor = UIColor.FromRGB(20, 108, 237); //FourteenSegmentGauge segmentFourteenGauge = new SFDigitalGauge(); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { segmentFourteenGauge.CharacterHeight = 48; segmentFourteenGauge.CharacterWidth = 24; segmentFourteenGauge.VerticalPadding = 20; } else { segmentFourteenGauge.CharacterHeight = 36; segmentFourteenGauge.CharacterWidth = 18; segmentFourteenGauge.VerticalPadding = 10; } segmentFourteenGauge.SegmentWidth = 3; segmentFourteenGauge.CharacterType = SFDigitalGaugeCharacterType.SFDigitalGaugeCharacterTypeSegmentFourteen; segmentFourteenGauge.StrokeType = SFDigitalGaugeStrokeType.SFDigitalGaugeStrokeTypeTriangleEdge; segmentFourteenGauge.Value = currentDateandTime; segmentFourteenGauge.DimmedSegmentAlpha = 0.11f; segmentFourteenGauge.BackgroundColor = UIColor.FromRGB(248, 248, 248); segmentFourteenGauge.CharacterColor = UIColor.FromRGB(2, 186, 94); segmentFourteenGauge.DimmedSegmentColor = UIColor.FromRGB(2, 186, 94); //SixteenSegmentGauge segmentSixteenGauge = new SFDigitalGauge(); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { segmentSixteenGauge.CharacterHeight = 48; segmentSixteenGauge.CharacterWidth = 24; segmentSixteenGauge.VerticalPadding = 20; } else { segmentSixteenGauge.CharacterHeight = 36; segmentSixteenGauge.CharacterWidth = 18; segmentSixteenGauge.VerticalPadding = 10; } segmentSixteenGauge.SegmentWidth = 3; segmentSixteenGauge.CharacterType = SFDigitalGaugeCharacterType.SFDigitalGaugeCharacterTypeSegmentSixteen; segmentSixteenGauge.StrokeType = SFDigitalGaugeStrokeType.SFDigitalGaugeStrokeTypeTriangleEdge; segmentSixteenGauge.Value = currentDateandTime; segmentSixteenGauge.DimmedSegmentAlpha = 0.11f; segmentSixteenGauge.BackgroundColor = UIColor.FromRGB(248, 248, 248); segmentSixteenGauge.CharacterColor = UIColor.FromRGB(219, 153, 7); segmentSixteenGauge.DimmedSegmentColor = UIColor.FromRGB(219, 153, 7); //8*8 MatrixSegmentGauge segmentMatrixGauge = new SFDigitalGauge(); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { segmentMatrixGauge.CharacterHeight = 48; segmentMatrixGauge.CharacterWidth = 22; segmentMatrixGauge.VerticalPadding = 20; } else { segmentMatrixGauge.CharacterHeight = 36; segmentMatrixGauge.CharacterWidth = 17; segmentMatrixGauge.VerticalPadding = 10; } segmentMatrixGauge.SegmentWidth = 3; segmentMatrixGauge.CharacterType = SFDigitalGaugeCharacterType.SFDigitalGaugeCharacterTypeEightCrossEightDotMatrix; segmentMatrixGauge.StrokeType = SFDigitalGaugeStrokeType.SFDigitalGaugeStrokeTypeTriangleEdge; segmentMatrixGauge.Value = currentDateandTime; segmentMatrixGauge.DimmedSegmentAlpha = 0.11f; segmentMatrixGauge.BackgroundColor = UIColor.FromRGB(248, 248, 248); segmentMatrixGauge.CharacterColor = UIColor.FromRGB(249, 66, 53); segmentMatrixGauge.DimmedSegmentColor = UIColor.FromRGB(249, 66, 53); //adding to View this.AddSubview(segmentSevenGauge); this.AddSubview(segmentFourteenGauge); this.AddSubview(segmentSixteenGauge); this.AddSubview(segmentMatrixGauge); mainPageDesign(); } public void mainPageDesign() { //segmentSevenTextt segmentSevenText = new UILabel(); segmentSevenText.Text = "7 Segment"; //segmentFourteenText segmentFourteenText2 = new UILabel(); segmentFourteenText2.Text = "14 Segment"; //segmentSixteenText3 segmentSixteenText3 = new UILabel(); segmentSixteenText3.Text = "16 Segment"; //segmentMatrixText4 segmentMatrixText4 = new UILabel(); segmentMatrixText4.Text = "8 X 8 DotMatrix"; //Addign to view this.AddSubview(segmentSevenText); this.AddSubview(segmentFourteenText2); this.AddSubview(segmentSixteenText3); this.AddSubview(segmentMatrixText4); } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Styles/Dark.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; namespace SampleBrowser { public class Dark : DataGridStyle { public Dark () { } public override UIColor GetHeaderBackgroundColor () { return UIColor.FromRGB (33, 33, 33); } public override UIColor GetHeaderForegroundColor () { return UIColor.FromRGB (255, 255, 255); } public override UIColor GetRecordBackgroundColor () { return UIColor.FromRGB (43, 43, 43); } public override UIColor GetRecordForegroundColor () { return UIColor.FromRGB (255, 255, 255); } public override UIColor GetAlternatingRowBackgroundColor () { return UIColor.FromRGB (46, 46, 46); } public override UIColor GetSelectionBackgroundColor () { return UIColor.FromRGB (85, 85, 85); } public override UIColor GetSelectionForegroundColor () { return UIColor.FromRGB (255, 255, 255); } public override UIColor GetCaptionSummaryRowBackgroundColor () { return UIColor.FromRGB (02, 02, 02); } public override UIColor GetCaptionSummaryRowForegroundColor () { return UIColor.FromRGB (255, 255, 255); } public override UIColor GetBorderColor () { return UIColor.FromRGB (81, 83, 82); } // public override int GetHeaderSortIndicatorDown () // { // return Resource.Drawable.SortingDown; // } // // public override int GetHeaderSortIndicatorUp () // { // return Resource.Drawable.SortingUp; // } } } <file_sep>/Forms/Sparkline/Sparkline/Samples/Sparkline/SparklineViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSparkline { [Preserve(AllMembers = true)] public class SparkViewModel { public ObservableCollection<SparklineModel> Datas { get; set; } public ObservableCollection<SparklineModel> ColumnDatas { get; set; } public SparkViewModel() { Datas = new ObservableCollection<SparklineModel>(); ColumnDatas = new ObservableCollection<SparklineModel>(); Datas.Add(new SparklineModel { Performance = 10 }); Datas.Add(new SparklineModel { Performance = 30 }); Datas.Add(new SparklineModel { Performance = 25 }); Datas.Add(new SparklineModel { Performance = 95 }); Datas.Add(new SparklineModel { Performance = 190 }); Datas.Add(new SparklineModel { Performance = 40 }); Datas.Add(new SparklineModel { Performance = 60 }); Datas.Add(new SparklineModel { Performance = 50 }); Datas.Add(new SparklineModel { Performance = 35 }); Datas.Add(new SparklineModel { Performance = 20 }); ColumnDatas.Add(new SparklineModel { YearPerformance = 20 }); ColumnDatas.Add(new SparklineModel { YearPerformance = 10 }); ColumnDatas.Add(new SparklineModel { YearPerformance = -30 }); ColumnDatas.Add(new SparklineModel { YearPerformance = 60 }); ColumnDatas.Add(new SparklineModel { YearPerformance = 10 }); ColumnDatas.Add(new SparklineModel { YearPerformance = 20 }); } } }<file_sep>/Forms/Backdrop/readme.md Backdrop appears behind all other surfaces in an app, displaying contextual and actionable content using back and front view. The following sample is available for backdrop to demonstrate the functionalities of its feature. | Sample | Description | | ------ | ----------- | | [Backdrop](Backdrop/Samples/Backdrop)| Backdrop appears behind all other surfaces in an app, displaying contextual and actionable content using back and front view.This sample represents a getting started example for backdrop. | <file_sep>/Android/SampleBrowser/Samples/SfPicker/Picker.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Android.Util; namespace SampleBrowser { public class Picker: SamplePage { SfPickerDemo mobile; SfPickerDemo_Tab tab; Context contextTablet; public Picker() { } public override Android.Views.View GetSampleContent(Context context) { if (IsTabletDevice(context)) { tab = new SfPickerDemo_Tab(); contextTablet = context; return tab.GetSampleContent(context); } else { mobile = new SfPickerDemo(); return mobile.GetSampleContent(context); } } public override Android.Views.View GetPropertyWindowLayout(Context context) { if (IsTabletDevice(context)) { return tab.GetPropertyWindowLayout(context); } else { return mobile.GetPropertyWindowLayout(context); } } public override void OnApplyChanges() { if (IsTabletDevice(contextTablet)) tab.OnApplyChanges(); else mobile.OnApplyChanges(); } public static bool IsTabletDevice(Android.Content.Context context) { if (context != null) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = Math.Sqrt(Math.Pow(screenWidth, 2) + Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } return false; } } } <file_sep>/iOS/SampleBrowser/Samples/Kanban/readme.md The Kanban control provides an efficient interface to track and visualize different stages in a task or workflow. The following samples are available for Kanban to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Getting Started](GettingStartedKanban.cs) | This sample demonstrates how to bind tasks, configure columns, and define workflows to the kanban control in a Xamarin.iOS application. | | [Customization](CustomizationKanban.cs) | This sample demonstrates how to customize the appearance of placeholder, define workflow, and configure error bar to visualize the work-in-progress validation in kanban control in a Xamarin.iOS application.| <file_sep>/Forms/Diagram/Diagram/Samples/DiagramUtility.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; namespace SampleBrowser.SfDiagram { public class DiagramUtility { public static float factor = 1; private static float m_currentDensity = 1; public static float currentDensity { get { return m_currentDensity; } set { m_currentDensity = value; float staticDensity = 1.5f; factor = m_currentDensity / staticDensity; } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/RangeSlider/Slider.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfRangeSlider.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Slider : SampleView { UIImageView mountImg; SFRangeSlider RangeSliderSample; UILabel opacityLabel; public Slider () { //RangeSlider RangeSliderSample = new SFRangeSlider(); RangeSliderSample.Delegate = new RangeSliderDelegate(); RangeSliderSample.Maximum=100; RangeSliderSample.Minimum=0; RangeSliderSample.Value = 100; RangeSliderSample.RangeStart=0; RangeSliderSample.RangeEnd=100; RangeSliderSample.TickPlacement=SFTickPlacement.SFTickPlacementBottomRight; RangeSliderSample.ValuePlacement=SFValuePlacement.SFValuePlacementBottomRight; RangeSliderSample.TickFrequency=20; RangeSliderSample.ToolTipPlacement = SFToolTipPlacement.SFToolTipPlacementTopLeft; RangeSliderSample.SnapsTo = SFSnapsTo.SFSnapsToNone; RangeSliderSample.ShowRange=false; RangeSliderSample.KnobColor=UIColor.White; RangeSliderSample.TrackSelectionColor=UIColor.FromRGB(66,115,185); RangeSliderSample.TrackColor=UIColor.FromRGB(182,182,182); this.AddSubview (RangeSliderSample); mainPageDesign(); } public void mainPageDesign() { //Image mountImg = new UIImageView(); mountImg.Image = UIImage.FromBundle("Images/mount.png"); //opacityLabel opacityLabel = new UILabel(); opacityLabel.TextColor = UIColor.Black; opacityLabel.Text = "Opacity"; opacityLabel.TextAlignment = UITextAlignment.Left; opacityLabel.Font = UIFont.FromName("Helvetica", 20f); this.AddSubview(mountImg); this.AddSubview(opacityLabel); } public void SetValue(nfloat value) { mountImg.Alpha = value / 100; } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { mountImg.Frame = new CGRect (this.Frame.X + 120, this.Frame.Y, this.Frame.Size.Width - 240, this.Frame.Size.Height / 2); opacityLabel.Frame = new CGRect (this.Frame.X + 120, this.Frame.Y + this.Frame.Size.Height / 2 + 10, this.Frame.Size.Width - 60, 30); RangeSliderSample.Frame = new CGRect (this.Frame.X + 120, this.Frame.Y + this.Frame.Size.Height / 2 + 20, this.Frame.Size.Width - 220, 100); } else { mountImg.Frame = new CGRect (this.Frame.X + 20, this.Frame.Y, this.Frame.Size.Width - 40, this.Frame.Size.Height / 2); opacityLabel.Frame = new CGRect (this.Frame.X + 20, this.Frame.Y + this.Frame.Size.Height / 2 + 10, this.Frame.Size.Width - 40, 30); RangeSliderSample.Frame = new CGRect (this.Frame.X + 10, this.Frame.Y + this.Frame.Size.Height / 2 + 20, this.Frame.Size.Width - 20, 100); } } base.LayoutSubviews (); } } public class RangeSliderDelegate:SFRangeSliderDelegate { public override void ValueChange (SFRangeSlider SFRangeSlider, nfloat value) { (SFRangeSlider.Superview as Slider).SetValue (value); } } public class RangeSliderValueChangedEventArgs : EventArgs { public nfloat imageval {get; set;} } } <file_sep>/Forms/Schedule/Schedule/Samples/AgendaView/ViewModel/AgendaViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Agenda View Model class. /// </summary> internal class AgendaViewModel : INotifyPropertyChanged { /// <summary> /// collecions for meetings. /// </summary> private ObservableCollection<Meeting> meetings; /// <summary> /// selected date meetings. /// </summary> private ObservableCollection<Meeting> selectedDateMeetings; /// <summary> /// selected date. /// </summary> private string selectedDate; /// <summary> /// blackout dates. /// </summary> private ObservableCollection<DateTime> blackoutDates; /// <summary> /// title collection. /// </summary> private ObservableCollection<string> titleCollection = new ObservableCollection<string>(); /// <summary> /// color collection. /// </summary> private List<Color> colorCollection; /// <summary> /// current day meeting. /// </summary> private List<string> currentDayMeetings; /// <summary> /// Initializes a new instance of the <see cref="AgendaViewModel" /> class. /// </summary> public AgendaViewModel() { this.Meetings = new ObservableCollection<Meeting>(); this.AddAppointmentDetails(); this.AddPreBookMeetings(); this.AddBlackouDates(); } /// <summary> /// property changed event. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets meetings. /// </summary> public ObservableCollection<Meeting> Meetings { get { return this.meetings; } set { this.meetings = value; this.RaiseOnPropertyChanged("Meetings"); } } /// <summary> /// Gets or sets selected date meetings. /// </summary> public ObservableCollection<Meeting> SelectedDateMeetings { get { return this.selectedDateMeetings; } set { this.selectedDateMeetings = value; this.RaiseOnPropertyChanged("SelectedDateMeetings"); } } /// <summary> /// Gets or sets selected date. /// </summary> public string SelectedDate { get { return this.selectedDate; } set { this.selectedDate = value; this.RaiseOnPropertyChanged("SelectedDate"); } } /// <summary> /// Gets or sets blackout dates. /// </summary> public ObservableCollection<DateTime> BlackoutDates { get { return this.blackoutDates; } set { this.blackoutDates = value; this.RaiseOnPropertyChanged("BlackoutDates"); } } /// <summary> /// method for add blackout dates /// </summary> private void AddBlackouDates() { this.BlackoutDates = new ObservableCollection<DateTime>(); for (int i = 0; i < 5; i++) { var date = DateTime.Now.Date.AddDays(15).AddDays(i); this.BlackoutDates.Add(date); } } /// <summary> /// adding appointment details. /// </summary> private void AddAppointmentDetails() { this.currentDayMeetings = new List<string>(); this.currentDayMeetings.Add("General Meeting"); this.currentDayMeetings.Add("Plan Execution"); this.currentDayMeetings.Add("Project Plan"); this.currentDayMeetings.Add("Consulting"); this.currentDayMeetings.Add("Support"); this.currentDayMeetings.Add("Development Meeting"); this.currentDayMeetings.Add("Scrum"); this.currentDayMeetings.Add("Project Completion"); this.currentDayMeetings.Add("Release updates"); this.currentDayMeetings.Add("Performance Check"); this.colorCollection = new List<Color>(); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FFF09609")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); } /// <summary> /// method for add pre book meetings. /// </summary> private void AddPreBookMeetings() { var today = DateTime.Now.Date; var random = new Random(); for (int month = -1; month < 2; month++) { for (int day = -5; day < 5; day++) { for (int hour = 9; hour < 18; hour += 5) { var meeting = new Meeting() { From = today.AddMonths(month).AddDays(day).AddHours(hour), To = today.AddMonths(month).AddDays(day).AddHours(hour + 2), EventName = this.currentDayMeetings[random.Next(7)], Color = this.colorCollection[random.Next(10)] }; this.Meetings.Add(meeting); } } } } /// <summary> /// Invoke method when property changed. /// </summary> /// <param name="propertyName">property name</param> private void RaiseOnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/Forms/Schedule/Schedule/Samples/AppointmentEditor/ViewModels/AppointmentEditorViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Appointment Editor View Model class. [Preserve(AllMembers = true)] #region AppointmentEditorViewModel public class AppointmentEditorViewModel : INotifyPropertyChanged { /// <summary> /// current day meetings /// </summary> private List<string> currentDayMeetings; /// <summary> /// minimum time meetings /// </summary> private List<string> minTimeMeetings; /// <summary> /// color collection /// </summary> private List<Color> colorCollection; /// <summary> /// list of meeting /// </summary> private ObservableCollection<Meeting> listOfMeeting; /// <summary> /// header label value /// </summary> private string headerLabelValue = DateTime.Today.Date.ToString("MMMM yyyy"); #region ScheduleType /// <summary> /// schedule type collection /// </summary> private ObservableCollection<ScheduleTypeClass> scheduleTypeCollection = new ObservableCollection<ScheduleTypeClass>(); #endregion /// <summary> /// Initializes a new instance of the <see cref="AppointmentEditorViewModel" /> class. /// </summary> public AppointmentEditorViewModel() { this.ListOfMeeting = new ObservableCollection<Meeting>(); this.InitializeDataForBookings(); this.BookingAppointments(); this.AddScheduleType(); } /// <summary> /// Property changed event handler /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region ListOfMeeting /// <summary> /// Gets or sets list of meeting /// </summary> public ObservableCollection<Meeting> ListOfMeeting { get { return this.listOfMeeting; } set { this.listOfMeeting = value; this.RaiseOnPropertyChanged("ListOfMeeting"); } } #endregion #region HeaderLabelValue /// <summary> /// Gets or sets header label value /// </summary> public string HeaderLabelValue { get { return this.headerLabelValue; } set { this.headerLabelValue = value; this.RaiseOnPropertyChanged("HeaderLabelValue"); } } /// <summary> /// Gets or sets schedule type collection /// </summary> public ObservableCollection<ScheduleTypeClass> ScheduleTypeCollection { get { return this.scheduleTypeCollection; } set { this.scheduleTypeCollection = value; this.RaiseOnPropertyChanged("ScheduleTypeCollection"); } } #endregion /// <summary> /// method for adding schedule types /// </summary> private void AddScheduleType() { this.ScheduleTypeCollection.Add(new ScheduleTypeClass() { ScheduleType = "Day view" }); this.ScheduleTypeCollection.Add(new ScheduleTypeClass() { ScheduleType = "Week view" }); this.ScheduleTypeCollection.Add(new ScheduleTypeClass() { ScheduleType = "Work week view" }); this.ScheduleTypeCollection.Add(new ScheduleTypeClass() { ScheduleType = "Month view" }); this.scheduleTypeCollection.Add(new ScheduleTypeClass() { ScheduleType = "Timeline view" }); } #region BookingAppointments /// <summary> /// Method for booking appointments. /// </summary> private void BookingAppointments() { Random randomTime = new Random(); List<Point> randomTimeCollection = this.GettingTimeRanges(); DateTime date; DateTime dateFrom = DateTime.Now.AddDays(-10); DateTime dateTo = DateTime.Now.AddDays(10); DateTime dateRangeStart = DateTime.Now.AddDays(-3); DateTime dateRangeEnd = DateTime.Now.AddDays(3); for (date = dateFrom; date < dateTo; date = date.AddDays(1)) { if ((DateTime.Compare(date, dateRangeStart) > 0) && (DateTime.Compare(date, dateRangeEnd) < 0)) { for (int additionalAppointmentIndex = 0; additionalAppointmentIndex < 3; additionalAppointmentIndex++) { Meeting meeting = new Meeting(); int hour = randomTime.Next((int)randomTimeCollection[additionalAppointmentIndex].X, (int)randomTimeCollection[additionalAppointmentIndex].Y); meeting.From = new DateTime(date.Year, date.Month, date.Day, hour, 0, 0); meeting.To = meeting.From.AddHours(1); meeting.EventName = this.currentDayMeetings[randomTime.Next(9)]; meeting.Color = this.colorCollection[randomTime.Next(9)]; meeting.IsAllDay = false; meeting.StartTimeZone = string.Empty; meeting.EndTimeZone = string.Empty; this.ListOfMeeting.Add(meeting); } } else { Meeting meeting = new Meeting(); meeting.From = new DateTime(date.Year, date.Month, date.Day, randomTime.Next(9, 11), 0, 0); meeting.To = meeting.From.AddDays(2).AddHours(1); meeting.EventName = this.currentDayMeetings[randomTime.Next(9)]; meeting.Color = this.colorCollection[randomTime.Next(9)]; meeting.IsAllDay = true; meeting.StartTimeZone = string.Empty; meeting.EndTimeZone = string.Empty; this.ListOfMeeting.Add(meeting); } } // Minimum Height Meetings DateTime minDate; DateTime minDateFrom = DateTime.Now.AddDays(-2); DateTime minDateTo = DateTime.Now.AddDays(2); for (minDate = minDateFrom; minDate < minDateTo; minDate = minDate.AddDays(1)) { Meeting meeting = new Meeting(); meeting.From = new DateTime(minDate.Year, minDate.Month, minDate.Day, randomTime.Next(9, 18), 30, 0); meeting.To = meeting.From; meeting.EventName = this.minTimeMeetings[randomTime.Next(0, 4)]; meeting.Color = this.colorCollection[randomTime.Next(0, 10)]; meeting.StartTimeZone = string.Empty; meeting.EndTimeZone = string.Empty; // Setting Mininmum Appointment Height for Schedule Appointments if (Device.RuntimePlatform == "Android") { meeting.MinimumHeight = 50; } else { meeting.MinimumHeight = 25; } this.ListOfMeeting.Add(meeting); } } #endregion BookingAppointments #region GettingTimeRanges /// <summary> /// Method for get timing range. /// </summary> /// <returns>return time collection</returns> private List<Point> GettingTimeRanges() { List<Point> randomTimeCollection = new List<Point>(); randomTimeCollection.Add(new Point(9, 11)); randomTimeCollection.Add(new Point(12, 14)); randomTimeCollection.Add(new Point(15, 17)); return randomTimeCollection; } #endregion GettingTimeRanges #region InitializeDataForBookings /// <summary> /// Method for initialize data bookings. /// </summary> private void InitializeDataForBookings() { this.currentDayMeetings = new List<string>(); this.currentDayMeetings.Add("General Meeting"); this.currentDayMeetings.Add("Plan Execution"); this.currentDayMeetings.Add("Project Plan"); this.currentDayMeetings.Add("Consulting"); this.currentDayMeetings.Add("Performance Check"); this.currentDayMeetings.Add("Yoga Therapy"); this.currentDayMeetings.Add("Plan Execution"); this.currentDayMeetings.Add("Project Plan"); this.currentDayMeetings.Add("Consulting"); this.currentDayMeetings.Add("Performance Check"); // MinimumHeight Appointment Subjects this.minTimeMeetings = new List<string>(); this.minTimeMeetings.Add("Work log alert"); this.minTimeMeetings.Add("Birthday wish alert"); this.minTimeMeetings.Add("Task due date"); this.minTimeMeetings.Add("Status mail"); this.minTimeMeetings.Add("Start sprint alert"); this.colorCollection = new List<Color>(); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); } #endregion InitializeDataForBookings #region Property Changed Event /// <summary> /// Invoke method when property changed /// </summary> /// <param name="propertyName">property name</param> private void RaiseOnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } #endregion #region ScheduleTypeClass /// <summary> /// Schedule Type Class /// </summary> public class ScheduleTypeClass : INotifyPropertyChanged { #region ScheduleType /// <summary> /// schedule type /// </summary> private string scheduleType = " "; /// <summary> /// Gets or sets schedule types /// </summary> public string ScheduleType { get { return this.scheduleType; } set { this.scheduleType = value; this.RaiseOnPropertyChanged("ScheduleType"); } } #endregion /// <summary> /// property changed event handler /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Invoke method when property changed /// </summary> /// <param name="propertyName">property name</param> private void RaiseOnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } #endregion }<file_sep>/iOS/SampleBrowser/Resources/Samples/Presentation/ConnectorsPresentation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Presentation; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class ConnectorsPresentation : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; public ConnectorsPresentation() { label1 = new UILabel(); label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to insert a connectors in a PowerPoint slide."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width , 50); } else { label.Frame = new CGRect (frameRect.Location.X, 5, frameRect.Size.Width , 70); } this.AddSubview (label); button.SetTitle("Generate Presentation",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect (0, 65, frameRect.Location.X + frameRect.Size.Width , 10); } else { button.Frame = new CGRect (frameRect.Location.X, 70, frameRect.Size.Width , 10); } this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { //Create an instance for PowerPoint IPresentation presentation = Presentation.Create(); //Add a blank slide to Presentation ISlide slide = presentation.Slides.Add(SlideLayoutType.Blank); //Add header shape IShape headerTextBox = slide.Shapes.AddTextBox(255.60, 11.35, 315.33, 41.20); //Add a paragraph into the text box IParagraph paragraph = headerTextBox.TextBody.AddParagraph("Flow chart with connector"); //Set the font size of the paragraph paragraph.Font.FontSize = 28; //Add start shape to slide IShape startShape = slide.Shapes.AddShape(AutoShapeType.FlowChartTerminator, 343.69, 79.22, 101.34, 35.86); //Add a paragraph into the start shape text body AddParagraph(startShape, "Start"); //Add alarm shape to slide IShape alarmShape = slide.Shapes.AddShape(AutoShapeType.FlowChartProcess, 343.69, 151.35, 101.34, 44.93); //Add a paragraph into the alarm shape text body AddParagraph(alarmShape, "Alarm Rings"); //Add condition shape to slide IShape conditionShape = slide.Shapes.AddShape(AutoShapeType.FlowChartDecision, 343.69, 239.22, 101.34, 73.98); //Add a paragraph into the condition shape text body AddParagraph(conditionShape, "Ready to Get Up ?"); //Change font size of the paragraph conditionShape.TextBody.Paragraphs[0].Font.FontSize = 12; //Add wake up shape to slide IShape wakeUpShape = slide.Shapes.AddShape(AutoShapeType.FlowChartProcess, 343.69, 356.15, 101.34, 44.93); //Add a paragraph into the wake up shape text body AddParagraph(wakeUpShape, "Wake Up"); //Add end shape to slide IShape endShape = slide.Shapes.AddShape(AutoShapeType.FlowChartTerminator, 343.69, 447.93, 101.34, 35.86); //Add a paragraph into the end shape text body AddParagraph(endShape, "End"); //Add snooze shape to slide IShape snoozeShape = slide.Shapes.AddShape(AutoShapeType.FlowChartProcess, 545.09, 239.22, 101.34, 73.98); //Add a paragraph into the snooze shape text body AddParagraph(snoozeShape, "Hit Snooze button"); //Add relay shape to slide IShape relayShape = slide.Shapes.AddShape(AutoShapeType.FlowChartDelay, 545.09, 151.35, 101.34, 44.93); //Add a paragraph into the relay shape text body AddParagraph(relayShape, "Relay"); //Connect the start shape with alarm shape using connector IConnector connector1 = slide.Shapes.AddConnector(ConnectorType.Straight, startShape, 2, alarmShape, 0); //Set the arrow style for the connector connector1.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the alarm shape with condition shape using connector IConnector connector2 = slide.Shapes.AddConnector(ConnectorType.Straight, alarmShape, 2, conditionShape, 0); //Set the arrow style for the connector connector2.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the condition shape with snooze shape using connector IConnector connector3 = slide.Shapes.AddConnector(ConnectorType.Straight, conditionShape, 3, snoozeShape, 1); //Set the arrow style for the connector connector3.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the snooze shape with relay shape using connector IConnector connector4 = slide.Shapes.AddConnector(ConnectorType.Straight, snoozeShape, 0, relayShape, 2); //Set the arrow style for the connector connector4.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the relay shape with alarm shape using connector IConnector connector5 = slide.Shapes.AddConnector(ConnectorType.Straight, relayShape, 1, alarmShape, 3); //Set the arrow style for the connector connector5.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the condition shape with wake up shape using connector IConnector connector6 = slide.Shapes.AddConnector(ConnectorType.Straight, conditionShape, 2, wakeUpShape, 0); //Set the arrow style for the connector connector6.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the wake up shape with end shape using connector IConnector connector7 = slide.Shapes.AddConnector(ConnectorType.Straight, wakeUpShape, 2, endShape, 0); //Set the arrow style for the connector connector7.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Add No textbox to slide IShape noTextBox = slide.Shapes.AddTextBox(470.97, 250.34, 35.67, 29.08); //Add a paragraph into the text box noTextBox.TextBody.AddParagraph("No"); //Add Yes textbox to slide IShape yesTextBox = slide.Shapes.AddTextBox(394.15, 314.92, 38.23, 29.08); //Add a paragraph into the text box yesTextBox.TextBody.AddParagraph("Yes"); MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("ConnectorsPresentation.pptx", "application/mspowerpoint", stream); } } /// <summary> /// Add a paragraph into the specified shape with specified text /// </summary> /// <param name="shape">Represent the shape</param> /// <param name="text">Represent the text to be added</param> private void AddParagraph(IShape shape, string text) { //Add a paragraph into the specified shape with specified text IParagraph paragraph = shape.TextBody.AddParagraph(text); //Set the vertical alignment as center shape.TextBody.VerticalAlignment = VerticalAlignmentType.Middle; //Set horizontal alignment as center paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; //Set font color as white paragraph.Font.Color = ColorObject.White; } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/TreeView/Helper/CustomView/NodeImageView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using UIKit; using CoreGraphics; namespace SampleBrowser { public class NodeImageView : UIView { #region Fields UILabel label1; UIImageView imageIcon; #endregion #region Constructor public NodeImageView() { label1 = new UILabel(); imageIcon = new UIImageView(); imageIcon.ClipsToBounds = true; this.AddSubview(imageIcon); this.AddSubview(label1); } #endregion #region Methods public override void LayoutSubviews() { this.imageIcon.Frame = new CGRect(0, 0, 40,40); this.label1.Frame = new CGRect(40, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion } }<file_sep>/Android/SampleBrowser/Samples/LinearGauge/readme.md The linear gauge is a data visualization component that helps display numerical values on a linear scale. It has highly customizable features such as scales, pointers, ranges, and annotations. The following samples are available for linear gauge to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Linear Gauge](LinearGauge.cs)| Linear gauge is a visual representation of numerical values of scales in a linear manner. This sample shows default rendering of a linear gauge. | | [Scales and Pointers](ScalesAndPointers.cs)| This sample shows the axis and pointer features in a linear gauge. Axes and pointers can be customized by using various options. | | [Ranges](Ranges.cs)| This sample shows how to highlight a region in an axis by using ranges in a gauge. | | [Annotations](Annotation.cs)| Annotations are used to mark a specific area of interest in a gauge with texts, shapes, or images. This sample shows the CPU utilization of a resource by using annotation feature. | <file_sep>/Android/SampleBrowser/Samples/CircularGauge/PointerDragging.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfCircularGauge; namespace SampleBrowser { public class PointerDragging : SamplePage { MarkerPointer markerPointer1; MarkerPointer markerPointer2; Header header; CircularRange range; double firstMarkerValue = 2; double secondMarkerValue = 10; float deviceDensity; TextView stepFrequencyValue; public override View GetSampleContent(Context context) { deviceDensity = context.Resources.DisplayMetrics.Density; SfCircularGauge sfCircularGauge = new SfCircularGauge(context); ObservableCollection<Header> headers = new ObservableCollection<Header>(); header = new Header(); header.Text = "08" + " h" + " 00" + " min"; header.TextSize = 25; header.TextColor = Color.ParseColor("#FF4500"); header.TextStyle = Typeface.DefaultBold; header.Position = new PointF((float)0.5, (float)0.5); headers.Add(header); sfCircularGauge.Headers = headers; ObservableCollection<CircularScale> circularScales = new ObservableCollection<CircularScale>(); CircularScale scale = new CircularScale(); scale.StartValue = 0; scale.EndValue = 12; scale.Interval = 1; scale.StartAngle = 270; scale.SweepAngle = 360; scale.LabelOffset = 0.67; scale.ScaleStartOffset = 0.9; scale.ScaleEndOffset = 0.8; scale.ShowFirstLabel = false; scale.MinorTicksPerInterval = 4; scale.MajorTickSettings = new TickSetting() { StartOffset = 0.8, EndOffset = 0.72, Width = 2, Color = Color.DarkGray }; scale.MinorTickSettings = new TickSetting() { StartOffset = 0.8, EndOffset = 0.75 }; ObservableCollection<CircularPointer> pointers = new ObservableCollection<CircularPointer>(); markerPointer1 = new MarkerPointer(); markerPointer1.EnableDragging = true; markerPointer1.EnableAnimation = false; markerPointer1.Value = firstMarkerValue; markerPointer1.Color = Color.ParseColor("#F7CE72"); markerPointer1.Offset = 0.9; markerPointer1.MarkerShape = Com.Syncfusion.Gauges.SfCircularGauge.Enums.MarkerShape.Circle; markerPointer1.ValueChanging += MarkerPointer1_ValueChanging; markerPointer1.PointerPositionChangedEvent += MarkerPointer1_PointerPositionChangedEvent; pointers.Add(markerPointer1); markerPointer2 = new MarkerPointer(); markerPointer2.EnableDragging = true; markerPointer2.EnableAnimation = false; markerPointer2.Value = secondMarkerValue; markerPointer2.Color = Color.ParseColor("#F7CE72"); markerPointer2.Offset = 0.9; markerPointer2.MarkerShape = Com.Syncfusion.Gauges.SfCircularGauge.Enums.MarkerShape.Circle; markerPointer2.ValueChanging += MarkerPointer2_ValueChanging; markerPointer2.PointerPositionChangedEvent += MarkerPointer2_PointerPositionChangedEvent; pointers.Add(markerPointer2); markerPointer2.StepFrequency = markerPointer1.StepFrequency = 0.2; range = new CircularRange(); range.StartValue = markerPointer1.Value; range.EndValue = markerPointer2.Value; range.InnerStartOffset = 0.8; range.InnerEndOffset = 0.8; range.OuterStartOffset = 0.9; range.OuterEndOffset = 0.9; range.Color = Color.ParseColor("#E57982"); scale.CircularRanges.Add(range); scale.CircularPointers = pointers; circularScales.Add(scale); sfCircularGauge.CircularScales = circularScales; sfCircularGauge.SetBackgroundColor(Color.White); LinearLayout linearLayout = new LinearLayout(context); linearLayout.AddView(sfCircularGauge); linearLayout.SetPadding(30, 30, 30, 30); linearLayout.SetBackgroundColor(Color.White); linearLayout.LayoutChange += LinearLayout_LayoutChange; return linearLayout; } public override View GetPropertyWindowLayout(Context context) { TextView stepFrequencyText = new TextView(context); stepFrequencyText.Text = "Step Frequency : "; stepFrequencyText.Typeface = Typeface.DefaultBold; stepFrequencyText.SetTextColor(Color.ParseColor("#262626")); stepFrequencyText.TextSize = 20; stepFrequencyValue = new TextView(context); stepFrequencyValue.Text = "0.2"; stepFrequencyValue.Typeface = Typeface.DefaultBold; stepFrequencyValue.SetTextColor(Color.ParseColor("#262626")); stepFrequencyValue.TextSize = 20; LinearLayout stepFrequencyLayout = new LinearLayout(context); stepFrequencyLayout.Orientation = Orientation.Horizontal; stepFrequencyLayout.AddView(stepFrequencyText); stepFrequencyLayout.AddView(stepFrequencyValue); SeekBar stepFrequencySeekBar = new SeekBar(context); stepFrequencySeekBar.Min = 0; stepFrequencySeekBar.Progress = 1; stepFrequencySeekBar.Max = 5; stepFrequencySeekBar.ProgressChanged += StepFrequencySeekBar_ProgressChanged; LinearLayout optionsPage = new LinearLayout(context); optionsPage.Orientation = Orientation.Vertical; optionsPage.AddView(stepFrequencyLayout); optionsPage.AddView(stepFrequencySeekBar); optionsPage.SetPadding(10, 10, 10, 10); optionsPage.SetBackgroundColor(Color.White); return optionsPage; } private void StepFrequencySeekBar_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { SeekBar seekBar = sender as SeekBar; double value = ((double)e.Progress / 10) * 2; markerPointer2.StepFrequency = markerPointer1.StepFrequency = value; stepFrequencyValue.Text = value.ToString(); } private void LinearLayout_LayoutChange(object sender, View.LayoutChangeEventArgs e) { var gauge = (sender as LinearLayout).GetChildAt(0) as SfCircularGauge; if (gauge == null) return; var minSize = Math.Min(gauge.Width, gauge.Height); var radius = (float)minSize / 2; var scale = gauge.CircularScales[0]; if (scale != null) { float pointerSize = (float)(radius * Math.Abs(scale.ScaleStartOffset - scale.ScaleEndOffset)); pointerSize /= deviceDensity; foreach (MarkerPointer pointer in scale.CircularPointers) { if (pointer.MarkerHeight != pointerSize) pointer.MarkerHeight = pointerSize; if (pointer.MarkerWidth != pointerSize) pointer.MarkerWidth = pointerSize; } } } private void MarkerPointer1_PointerPositionChangedEvent(object sender, CircularPointer.PointerPositionChangedEventArgs e) { firstMarkerValue = e.P1.PointerValue; double value = Math.Abs(firstMarkerValue - secondMarkerValue); range.StartValue = firstMarkerValue; range.EndValue = secondMarkerValue; CalculateTimeDifference(value); } private void MarkerPointer2_PointerPositionChangedEvent(object sender, CircularPointer.PointerPositionChangedEventArgs e) { secondMarkerValue = e.P1.PointerValue; double value = Math.Abs(secondMarkerValue - markerPointer1.Value); range.StartValue = firstMarkerValue; range.EndValue = secondMarkerValue; CalculateTimeDifference(value); } private void MarkerPointer2_ValueChanging(object sender, CircularPointer.PointerValueChangingEventArgs e) { if (e.NewValue <= firstMarkerValue || Math.Abs(e.NewValue - secondMarkerValue) > (1 + markerPointer2.StepFrequency)) { e.Cancel = true; } } private void MarkerPointer1_ValueChanging(object sender, CircularPointer.PointerValueChangingEventArgs e) { if (e.NewValue >= secondMarkerValue || Math.Abs(e.NewValue - firstMarkerValue) > (1 + markerPointer1.StepFrequency)) { e.Cancel = true; } } private void CalculateTimeDifference(double value) { int hour = Convert.ToInt32(Math.Floor(value)); float digit = hour / 10f; bool isHourSingleDigit = digit >= 1 ? false : true; var min = Math.Floor((value - hour) * 60); digit = (float)min / 10f; bool isMinuteSingleDigit = digit >= 1 ? false : true; string hourValue = isHourSingleDigit ? "0" + hour.ToString() : hour.ToString(); string minutesValue = isMinuteSingleDigit ? "0" + min.ToString() : min.ToString(); header.Text = hourValue + " h " + minutesValue + " min"; } } }<file_sep>/iOS/SampleBrowser/Samples/Schedule/GettingStarted/ViewModel/AppointmentCollection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Foundation; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using UIKit; namespace SampleBrowser { /// <summary> /// Creates the appointment collection for custom appointments /// </summary> [Preserve(AllMembers = true)] public class AppointmentCollection { /// <summary> /// Custom appointment color collection /// </summary> private List<UIColor> colorCollection; /// <summary> /// Custom appointment subject name collection /// </summary> private List<string> eventCollection; /// <summary> /// Custom appointment start time collection /// </summary> private List<NSDate> fromCollection; /// <summary> /// Custom appointment end time collection /// </summary> private List<NSDate> toCollection; /// <summary> /// Random numbers collection to get the start and end time values /// </summary> private List<int> randomNumbers; /// <summary> /// Custom appointment variables /// </summary> private Meeting meeting; /// <summary> /// Collection for custom appointment /// </summary> private ObservableCollection<Meeting> appointmentCollection; /// <summary> /// Gets the appointment collection /// </summary> /// <returns>Appointment collection</returns> internal ObservableCollection<Meeting> GetAppointments() { NSDate today = new NSDate(); NSCalendar calendar = NSCalendar.CurrentCalendar; appointmentCollection = new ObservableCollection<Meeting>(); SetEventCollection(); RandomNumbers(); SetFromCollection(); SetToCollection(); SetColorCollection(); for (int i = 0; i < 15; i++) { meeting = new Meeting(); meeting.Color = colorCollection[i]; meeting.EventName = (NSString)eventCollection[i]; meeting.From = fromCollection[i]; // To create all day appointments if (i % 6 == 0 && i != 0) { meeting.IsAllDay = true; } // To create two days span appointment if (i % 5 == 0 && i != 0) { toCollection[i] = fromCollection[i]; var dateComponent = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, toCollection[i]); dateComponent.Day = dateComponent.Day + 2; toCollection[i] = calendar.DateFromComponents(dateComponent); } // To create 24 hour span appointments if (i % 7 == 0) { toCollection[i] = fromCollection[i]; var dateComponent = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, toCollection[i]); dateComponent.Hour = dateComponent.Hour + 23; dateComponent.Minute = dateComponent.Minute + 59; toCollection[i] = calendar.DateFromComponents(dateComponent); } // To create minimum height appointments if (eventCollection[i].Contains("alert")) { toCollection[i] = fromCollection[i]; meeting.MinimumHeight = 20; } meeting.To = toCollection[i]; appointmentCollection.Add(meeting); } return appointmentCollection; } /// <summary> /// Creates the random numbers to get start time and end time /// </summary> private void RandomNumbers() { randomNumbers = new List<int>(); Random rand = new Random(); for (int i = 0; i < 20; i++) { int randomNum = rand.Next((15 - 9) + 1) + 9; randomNumbers.Add(randomNum); } } /// <summary> /// Sets the end time collection for custom appointment /// </summary> private void SetToCollection() { toCollection = new List<NSDate>(); int count = 0; for (int i = -10; i < 10; i++) { var today = new NSDate(); NSCalendar calendar = NSCalendar.CurrentCalendar; NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, today); components.Day = components.Day + i; components.Hour = randomNumbers[count] + 2; components.Minute = 0; components.Second = 0; var to = calendar.DateFromComponents(components); toCollection.Add(to); count++; } } /// <summary> /// Sets the start time collection for custom appointments /// </summary> private void SetFromCollection() { fromCollection = new List<NSDate>(); int count = 0; for (int i = -10; i < 10; i++) { var today = new NSDate(); NSCalendar calendar = NSCalendar.CurrentCalendar; NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day | NSCalendarUnit.Hour | NSCalendarUnit.Minute | NSCalendarUnit.Second, today); components.Day = components.Day + i; components.Hour = randomNumbers[count]; components.Minute = 0; components.Second = 0; var from = calendar.DateFromComponents(components); fromCollection.Add(from); count++; } } /// <summary> /// Sets the subject name collection for custom appointments /// </summary> private void SetEventCollection() { eventCollection = new List<String>(); eventCollection.Add("General Meeting"); eventCollection.Add("Plan Execution"); eventCollection.Add("Project Plan"); eventCollection.Add("Consulting"); eventCollection.Add("Performance Check"); eventCollection.Add("Yoga Therapy"); eventCollection.Add("Plan Execution"); eventCollection.Add("Project Plan"); eventCollection.Add("Consulting"); eventCollection.Add("Performance Check"); eventCollection.Add("Work log alert"); eventCollection.Add("Birthday wish alert"); eventCollection.Add("Task due date"); eventCollection.Add("Status mail"); eventCollection.Add("Start sprint alert"); } /// <summary> /// Sets the color collection for custom appointments /// </summary> private void SetColorCollection() { colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0xF0, 0x96, 0x09)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/DealerRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; namespace SampleBrowser { public class DealerRepository { #region private variables private Random random = new Random(); private List<DateTime> OrderedDates; #endregion #region GetDealerDetails private List<DateTime> GetDateBetween(int startYear, int endYear, int count) { List<DateTime> date = new List<DateTime>(); Random d = new Random(1); Random m = new Random(2); Random y = new Random(startYear); for (int i = 0; i < count; i++) { int year = y.Next(startYear, endYear); int month = m.Next(3, 13); int day = d.Next(1, 31); date.Add(new DateTime(year, month, day)); } return date; } public ObservableCollection<DealerInfo> GetDealerDetails(int count) { ObservableCollection<DealerInfo> dealerDetails = new ObservableCollection<DealerInfo>(); this.OrderedDates = GetDateBetween(2000, 2014, count); for (int i = 1; i <= count; i++) { var ord = new DealerInfo() { ProductID = i, ProductNo = ProductNo[random.Next(15)], DealerName = Customers[random.Next(15)], ProductPrice = random.Next(2000, 10000), ShippedDate = this.OrderedDates[i - 1], IsOnline = ((i % random.Next(1, 10) > 2) ? true : false), }; dealerDetails.Add(ord); } return dealerDetails; } #endregion int[] ProductNo = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; internal string[] Customers = new string[] { "Adams", "Crowley", "Ellis", "Gable", "Irvine", "Keefe", "Mendoza", "Owens", "Rooney", "Waddell", "Thomas", "Betts", "Doran", "Fitzgerald", "Holmes", "Jefferson", "Landry", "Newberry", "Perez", "Spencer", "Vargas", "Grimes", "Edwards", "Stark", "Cruise", "Fitz", "Chief", "Blanc", "Perry", "Stone", "Williams", "Lane", "Jobs" }; } }<file_sep>/Forms/Chips/Chips/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Syncfusion.XForms.Border; using Syncfusion.XForms.Buttons; using Xamarin.Forms; namespace SampleBrowser.Chips { /// <summary> /// Represents the view model class for holding binding variables from Chip. /// </summary> public class ChipViewModel : INotifyPropertyChanged { #region properties /// <summary> /// The icon property to hold the chip image. /// </summary> private string icon = "UserContact.png"; /// <summary> /// The property to identify whether left checkbox has been checkde or not. /// </summary> private bool isLeftCheckBox = true; /// <summary> /// The television collection. /// </summary> internal ObservableCollection<string> televisionItems = new ObservableCollection<string>() { "Samsung", "LG" }; /// <summary> /// The washer collection. /// </summary> internal ObservableCollection<string> washserItems = new ObservableCollection<string>() { "Whirlpool", "Kenmore" }; /// <summary> /// The air conditioner collection. /// </summary> internal ObservableCollection<string> airConditionerItems = new ObservableCollection<string>() { "Mitsubishi", "Hitachi" }; /// <summary> /// The choice collection. /// </summary> private List<string> choiceItems = new List<string>() { "Washer", "Television", "Air Conditioner" }; /// <summary> /// The result. /// </summary> private string result = "No results found"; /// <summary> /// The border color of chip. /// </summary> private Color borderColor = Color.Black; /// <summary> /// The background color of chip. /// </summary> private Color backgroundColor = Color.FromHex("#af2463"); /// <summary> /// Represents the text color /// </summary> private Color textColor = Color.White; /// <summary> /// Represents the visibility of image /// </summary> private bool showImage = true; /// <summary> /// Represents the font family /// </summary> private string SegoeFontFamily; /// <summary> /// The border thickness of chip. /// </summary> private double borderThickness = 1; /// <summary> /// The corner radius slider. /// </summary> private double cornerRadiusSlider = 20; /// <summary> /// The corner radius of chip. /// </summary> private Thickness cornerRadius = 20; /// <summary> /// The default corner radius. /// </summary> private double defaultCornerRadius = 20; /// <summary> /// The maximum. /// </summary> private double maximum = 20; /// <summary> /// Represents the border width /// </summary> private double borderWidth = 0; /// <summary> /// The text of chip. /// </summary> private string text = "JAMES"; /// <summary> /// The is show visual. /// </summary> private bool isShowVisual = false; /// <summary> /// The is show. /// </summary> private bool isShow = true; /// <summary> /// The input text. /// </summary> private string inputText = ""; /// <summary> /// The visual mode. /// </summary> private string visualMode = "None"; /// <summary> /// The is shown close button. /// </summary> private bool isShownCloseButton = true; /// <summary> /// The selected item. /// </summary> private object selectedItem = "Television"; /// <summary> /// The selected items. /// </summary> private List<string> selectedItems = new List<string>(); /// <summary>s /// The input collection. /// </summary> private ObservableCollection<string> brands; /// <summary> /// The filter collection. /// </summary> private List<string> filterChips = new List<string>(); /// <summary> /// The action collection. /// </summary> private List<string> actionChips = new List<string>() { "Search by brands", "Search by features" }; /// <summary> /// The action command. /// </summary> private ICommand actionCommand; /// <summary> /// The place holder text. /// </summary> private string placeHolderText = "Type a brand"; /// <summary> /// Gets or sets the primary colors. /// </summary> /// <value>The primary colors.</value> public ObservableCollection<SfSegmentItem> PrimaryColors { get; set; } /// <summary> /// Gets or sets the primary text colors. /// </summary> /// <value>The primary text colors.</value> public ObservableCollection<SfSegmentItem> PrimaryTextColors { get; set; } #endregion #region Fields /// <summary> /// Gets or Sets the image visibility /// </summary> public bool ShowImage { get { return showImage; } set { showImage = value; OnPropertyChanged("ShowImage"); } } /// <summary> /// Gets or Sets the text color /// </summary> public Color TextColor { get { return textColor; } set { textColor = value; OnPropertyChanged("TextColor"); } } /// <summary> /// Gets or sets the icon. /// </summary> /// <value>The chip icon.</value> public string Icon { get { return icon; } set { icon = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:Chip.ViewModel"/> is left check box. /// </summary> /// <value><c>true</c> if is left check box; otherwise, <c>false</c>.</value> public bool IsLeftCheckBox { get { return isLeftCheckBox; } set { isLeftCheckBox = value; this.SliderValue = value == true ? cornerRadius.Left : cornerRadius.Top; OnPropertyChanged("IsLeftCheckBox"); } } /// <summary> /// Gets or sets the color of the border of chip. /// </summary> /// <value>The color of the border of chip.</value> public Color BorderColorProperty { get { return borderColor; } set { borderColor = value; OnPropertyChanged("BorderColorProperty"); } } /// <summary> /// Gets or sets the background color of chip. /// </summary> /// <value>The background color of chip</value> public Color BackgroundColor { get { return backgroundColor; } set { backgroundColor = value; OnPropertyChanged("BackgroundColor"); } } /// <summary> /// Gets or sets the thickness of border. /// </summary> /// <value>The border thickness.</value> public double BorderThickness { get { return borderThickness; } set { borderThickness = value; OnPropertyChanged("BorderThickness"); } } /// <summary> /// Gets or sets the slider value. /// </summary> /// <value>The slider value.</value> public double LeftSliderValue { get { return defaultCornerRadius; } set { defaultCornerRadius = value; CornerRadius = new Thickness(value, cornerRadius.Top, cornerRadius.Right, value); OnPropertyChanged("LeftSliderValue"); } } /// <summary> /// Gets or sets the maximum. /// </summary> /// <value>The maximum.</value> public double Maximum { get { return maximum; } set { maximum = value; OnPropertyChanged("Maximum"); } } /// <summary> /// Gets or sets the slider value. /// </summary> /// <value>The slider value.</value> public double SliderValue { get { return cornerRadiusSlider; } set { cornerRadiusSlider = value; CornerRadius = new Thickness(cornerRadius.Left, value, value, cornerRadius.Bottom); OnPropertyChanged("SliderValue"); } } /// <summary> /// Gets or sets the border width. /// </summary> public double BorderWidth { get { return borderWidth; } set { borderWidth = value; OnPropertyChanged("BorderWidth"); } } /// <summary> /// Gets or sets the corner radius. /// </summary> /// <value>The corner radius.</value> public Thickness CornerRadius { get { return cornerRadius; } set { cornerRadius = value; OnPropertyChanged("CornerRadius"); } } /// <summary> /// Gets or sets the text. /// </summary> /// <value>The text.</value> public string Text { get { return text; } set { text = value; OnPropertyChanged("Text"); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:Chip.ChipViewModel"/> is show. /// </summary> /// <value><c>true</c> if is show; otherwise, <c>false</c>.</value> public bool IsShownIcon { get { return isShow; } set { isShow = value; OnPropertyChanged("IsShownIcon"); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:Chip.ChipViewModel"/> is show visual. /// </summary> /// <value><c>true</c> if is show visual; otherwise, <c>false</c>.</value> public bool IsShownSelection { get { return isShowVisual; } set { isShowVisual = value; OnPropertyChanged("IsShownSelection"); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:Chip.ChipViewModel"/> is show visual. /// </summary> /// <value><c>true</c> if is show visual; otherwise, <c>false</c>.</value> public bool IsShownCloseButton { get { return isShownCloseButton; } set { isShownCloseButton = value; OnPropertyChanged("IsShownCloseButton"); } } /// <summary> /// Gets or sets the visual mode. /// </summary> /// <value>The visual mode.</value> public string VisualMode { get { return visualMode; } set { visualMode = value; OnPropertyChanged("VisualMode"); } } /// <summary> /// Gets or sets the selected item. /// </summary> /// <value>The selected item.</value> public object SelectedItem { get { return selectedItem; } set { selectedItem = value; if (selectedItem != null) { if (!string.IsNullOrEmpty("SelectedItem")) { if (selectedItem.Equals("Television")) { InputItems = televisionItems; FilterItems = new List<string>() { "LED", "LCD", "WIFI", "4K", "Ultra HD" }; InputText = InputItems.Contains("Lenovo") ? "Type a brand" : "Lenovo"; } else if (selectedItem.Equals("Washer")) { InputItems = washserItems; FilterItems = new List<string>() { "Front Load", "Top Load" }; InputText = InputItems.Contains("Maytag") ? "Type a brand" : "Maytag"; } else if (selectedItem.Equals("Air Conditioner")) { InputItems = airConditionerItems; FilterItems = new List<string>() { "Window", "Portable", "Hybrid" }; InputText = InputItems.Contains("Voltas") ? "Type a brand" : "Voltas"; } } selectedItems.Clear(); } Result = "No results found"; OnPropertyChanged("SelectedItem"); } } /// <summary> /// Gets or sets the input text. /// </summary> /// <value>The input text.</value> public string InputText { get { return inputText; } set { inputText = value; OnPropertyChanged("InputText"); } } /// <summary> /// Gets or sets the action command. /// </summary> /// <value>The action command.</value> public ICommand ActionCommand { get { return actionCommand; } set { actionCommand = value; } } /// <summary> /// Gets or sets the place holder text. /// </summary> /// <value>The place holder text.</value> public string PlaceHolderText { get { return placeHolderText; } set { placeHolderText = value; OnPropertyChanged("PlaceHolderText"); } } /// <summary> /// Gets or sets the input collection. /// </summary> /// <value>The input collection.</value> public ObservableCollection<string> InputItems { get { return brands; } set { brands = value; if (brands != null && brands.Count == 0) { filterChips.Clear(); Result = "No results found"; } OnPropertyChanged("InputItems"); } } /// <summary> /// Gets or sets the filter collection. /// </summary> /// <value>The filter collection.</value> public List<string> FilterItems { get { return filterChips; } set { filterChips = value; OnPropertyChanged("FilterItems"); } } /// <summary> /// Gets or sets the action collection. /// </summary> /// <value>The action collection.</value> public List<string> ActionItems { get { return actionChips; } set { actionChips = value; OnPropertyChanged("ActionItems"); } } /// <summary> /// Gets or sets the selected items. /// </summary> /// <value>The selected items.</value> public List<string> SelectedItems { get { return selectedItems; } set { selectedItems = value; OnPropertyChanged("SelectedItems"); } } /// <summary> /// Gets or sets the choice collection. /// </summary> /// <value>The choice collection.</value> public List<string> ChoiceItems { get { return choiceItems; } set { choiceItems = value; OnPropertyChanged("ChoiceItems"); } } /// <summary> /// Gets or sets the result. /// </summary> /// <value>The result.</value> public string Result { get { return result; } set { result = value; OnPropertyChanged("Result"); } } #endregion /// <summary> /// Occurs when property changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// The <see cref=" ChipViewModel" properties changed/> /// </summary> /// <param name="property">Changed Property.</param> public void OnPropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } /// <summary> /// Initializes a new instance of the <see cref="T:Chip.ChipViewModel"/> class. /// </summary> public ChipViewModel() { ActionCommand = new Command(HandleAction); this.SegoeFontFamily = "chip_Segoe MDL2 Assets.ttf"; if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB this.SegoeFontFamily = "/Assets/Fonts/chip_Segoe MDL2 Assets.ttf.ttf#Segoe MDL2 Assets"; #else if (Core.SampleBrowser.IsIndividualSB) { this.SegoeFontFamily = "/Assets/Fonts/chip_Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; } else { this.SegoeFontFamily = $"ms-appx:///SampleBrowser.Chips.UWP/Assets/Fonts/chip_Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; } #endif } else if (Device.RuntimePlatform == Device.iOS) { this.SegoeFontFamily = "Segoe MDL2 Assets"; } this.PrimaryColors = GetSegmentCollection(); this.PrimaryTextColors = GetSegmentTextCollection(); } /// <summary> /// Gets the segment collection. /// </summary> /// <returns>The segment collection.</returns> private ObservableCollection<SfSegmentItem> GetSegmentCollection() { ObservableCollection<SfSegmentItem> segmentColorItems = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#c6c6c6"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#538eed"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#af2463"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#000000"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.Accent, Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily} }; return segmentColorItems; } private ObservableCollection<SfSegmentItem> GetSegmentTextCollection() { ObservableCollection<SfSegmentItem> segmentColorItems = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#ffffff"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#c6c6c6"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#538eed"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#af2463"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#000000"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, }; return segmentColorItems; } /// <summary> /// Handles the action. /// </summary> /// <param name="obj">Object.</param> void HandleAction(object obj) { Result = string.Empty; if (obj.ToString().Equals("Search by brands")) { foreach (var brand in brands) { Result += new Random().Next(1, 5).ToString() + " " + brand.ToString() + " " + selectedItem.ToString() + " found" + "\n"; } } else { if (selectedItems.Count > 0) { foreach (var feature in selectedItems) { foreach (var brand in brands) { Result += new Random().Next(1, 5).ToString() + " " + feature.ToString() + " " + selectedItem.ToString() + " found in " + brand.ToString() + "\n"; } } } else { Result = "No results found."; } } if (Result.Contains("\n")) { Result = Result.Remove(Result.Length - 1); } } } } <file_sep>/Android/SampleBrowser/Samples/TreeView/Helper/CustomViews/NodeImageView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public class NodeImageView : LinearLayout { #region Fields private ContentLabel label1; private ExpanderImage imageIcon; #endregion #region Constructor public NodeImageView(Context context) : base(context) { this.Orientation = Orientation.Horizontal; label1 = new ContentLabel(context); label1.Gravity = GravityFlags.CenterVertical; imageIcon = new ExpanderImage(context); this.AddView(imageIcon); this.AddView(label1); } #endregion #region Methods protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { var density = Resources.DisplayMetrics.Density; var measuredwidth = (int)(40 * density); var measuredheight = (int)(45 * density); var labelwidth = Math.Abs(widthMeasureSpec - measuredwidth); this.label1.SetMinimumHeight(measuredheight); this.label1.SetMinimumWidth(labelwidth); this.imageIcon.SetMinimumHeight(measuredheight); this.imageIcon.SetMinimumWidth(measuredwidth); this.imageIcon.Measure(measuredwidth, measuredheight); this.label1.Measure(labelwidth, measuredheight); base.OnMeasure(widthMeasureSpec, heightMeasureSpec); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { var density = Resources.DisplayMetrics.Density; var measuredwidth = (int)(40 * density); var measuredheight = (int)(45 * density); this.imageIcon.Layout(0, 0, measuredwidth, measuredheight); this.label1.Layout(measuredwidth, 0, Width, measuredheight); } #endregion } internal class ContentLabel : TextView { public ContentLabel(Context context) : base(context) { } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure(widthMeasureSpec, heightMeasureSpec); this.SetMeasuredDimension(widthMeasureSpec, heightMeasureSpec); } protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { base.OnLayout(changed, left, top, right, bottom); } } internal class ExpanderImage : ImageView { public ExpanderImage(Context context) : base(context) { this.SetScaleType(ScaleType.CenterInside); var padding = (int)(5 * Resources.DisplayMetrics.Density); this.SetPadding(padding, padding, padding, padding); } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure(widthMeasureSpec, heightMeasureSpec); this.SetMeasuredDimension(widthMeasureSpec, heightMeasureSpec); } protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { base.OnLayout(changed, left, top, right, bottom); } } }<file_sep>/Forms/CircularGauge/readme.md The circular gauge is a data visualization component that helps display numerical values on a circular scale. It has highly customizable features, such as scales, pointers, ranges, and annotations. The following samples are available for circular gauge to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Circular Gauge](CircularGauge/Samples/CircularGaugeSample.xaml)| A circular gauge is a visual representation of numerical values of scales in a circular manner. In this sample, a scale with needle pointer has been used. | | [Customization](CircularGauge/Samples/CustomizationSample.xaml)| This sample shows how to customize gauge elements. Here a needle and a range pointer are added to show the current value. The gauge’s appearance can be customized by using options in the property setting. | | [Direction Compass](CircularGauge/Samples/DirectionCompass.xaml)| A direction compass has been shown by adding needles and customizing labels to show the direction. | | [Gradient Range](CircularGauge/Samples/GradientRange.xaml)| Gradient Range This samples shows how to apply smooth color transition to a range by specifying different colors based on range values. | | [Pointer Customization](CircularGauge/Samples/Pointers.xaml)| This sample shows how to customize the pointer for a scale in a circular gauge. Gauge supports different types of pointers like marker, image, needle, and range. | | [Multiple Scales](CircularGauge/Samples/MultipleScales.xaml)| This sample shows how to render and configure multiple scales in gauge. Use scale collection to render multiple scales in gauges. Each scale can be customized with its own pointer. | | [Annotation](CircularGauge/Samples/CircularGaugeAnnotation.xaml)| Annotations are used to mark a specific area of interest in gauge with texts, shapes, or images. In this sample, minute and second sub-gauges are achieved using annotation feature. | <file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/PullToRefreshView/PullToRefreshView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PullToRefreshView.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using Core; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A sampleView that contains the PullToRefreshView sample. /// </summary> public partial class PullToRefreshView : SampleView { /// <summary> /// Initializes a new instance of the PullToRefreshView class. /// </summary> public PullToRefreshView() { this.InitializeComponent(); } /// <summary> /// This method is called when the size of the element is set during a layout cycle. This method is called directly /// before the <see cref="Xamarin.Forms.VisualElement.SizeChanged"/> event is emitted. /// </summary> /// <param name="width">The new width of the element.</param> /// <param name="height">The new height of the element.</param> protected override void OnSizeAllocated(double width, double height) { if (Device.RuntimePlatform == Device.iOS) { height -= 100; } base.OnSizeAllocated(width, height); } } }<file_sep>/Forms/TreeView/TreeView/Samples/Selection/Selection.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.TreeView.Engine; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using Xamarin.Forms; namespace SampleBrowser.SfTreeView { public partial class Selection : SampleView { public Selection () { InitializeComponent (); } } public class TreeViewSelectionBehavior : Behavior<SampleView> { #region Fields private Syncfusion.XForms.TreeView.SfTreeView TreeView; private Picker modePicker; #endregion #region Overrides protected override void OnAttachedTo(SampleView bindable) { TreeView = bindable.FindByName<Syncfusion.XForms.TreeView.SfTreeView>("treeView"); modePicker = bindable.FindByName<Picker>("selectionModePicker"); modePicker.Items.Add("Single"); modePicker.Items.Add("SingleDeselect"); modePicker.Items.Add("Multiple"); modePicker.Items.Add("Extended"); modePicker.Items.Add("None"); modePicker.SelectedIndex = 2; modePicker.SelectedIndexChanged += Picker_SelectedIndexChanged; base.OnAttachedTo(bindable); } private void Picker_SelectedIndexChanged(object sender, EventArgs e) { if (modePicker.SelectedIndex == 0) TreeView.SelectionMode = Syncfusion.XForms.TreeView.SelectionMode.Single; else if (modePicker.SelectedIndex == 1) TreeView.SelectionMode = Syncfusion.XForms.TreeView.SelectionMode.SingleDeselect; else if (modePicker.SelectedIndex == 2) TreeView.SelectionMode = Syncfusion.XForms.TreeView.SelectionMode.Multiple; else if (modePicker.SelectedIndex == 3) TreeView.SelectionMode = Syncfusion.XForms.TreeView.SelectionMode.Extended; else if (modePicker.SelectedIndex == 4) TreeView.SelectionMode = Syncfusion.XForms.TreeView.SelectionMode.None; } #endregion } }<file_sep>/Forms/XlsIO/XlsIO/Samples/WorksheetToHTMLPage/WorksheetToHTMLPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using SampleBrowser.Core; using Syncfusion.XlsIO; using Xamarin.Forms; namespace SampleBrowser.XlsIO { /// <summary> /// This class is the conversion of a simple Excel document to HTML file. /// </summary> public partial class WorksheetToHTMLPage : SampleView { public WorksheetToHTMLPage() { InitializeComponent(); this.bookButton.IsChecked = true; if (Device.Idiom != TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP)) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnInput.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInput.VerticalOptions = LayoutOptions.Center; this.btnInput.BackgroundColor = Color.Gray; Grid.SetColumn(this.radioButtons, 3); Grid.SetColumn(this.btnGenerate, 3); Grid.SetColumnSpan(this.btnInput, 2); Grid.SetColumnSpan(this.btnGenerate, 3); } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.FontSize = 13.5; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnInput.VerticalOptions = LayoutOptions.Center; } else if (Device.Idiom == TargetIdiom.Tablet) { if (Device.RuntimePlatform != Device.Android) { Grid.SetColumn(this.radioButtons, 4); Grid.SetColumn(this.btnGenerate, 3); Grid.SetColumnSpan(this.btnInput, 2); Grid.SetColumnSpan(this.btnGenerate, 3); } } } internal void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; #if COMMONSB Stream stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.NorthwindTemplate.xlsx"); #else Stream stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.NorthwindTemplate.xlsx"); #endif IWorkbook workbook = application.Workbooks.Open(stream); IWorksheet worksheet = workbook.Worksheets[0]; MemoryStream htmlStream = new MemoryStream(); string fileName = "Htmlfile.html"; string contentType = "text/html"; if (this.sheetButton.IsChecked != null && (bool)this.sheetButton.IsChecked) { worksheet.SaveAsHtml(htmlStream); } else { workbook.SaveAsHtml(htmlStream); } htmlStream.Position = 0; if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save(fileName, contentType, htmlStream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save(fileName, contentType, htmlStream); } } internal void OnInputButtonClicked(object sender, EventArgs e) { //Load Input Template to memory stream. #if COMMONSB Stream file = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.NorthwindTemplate.xlsx"); #else Stream file = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.NorthwindTemplate.xlsx"); #endif file.Position = 0; MemoryStream stream = new MemoryStream(); file.CopyTo(stream); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.xlsx", "application/msexcel", stream); } } } } <file_sep>/Forms/NumericTextBox/readme.md The numeric text box is an advanced version of entry control that restricts input to numeric values. It also provides a gesture-friendly UI culture that can be configured to display different formats like currency format, scientific format, and more. | Sample | Description | | ------ | ----------- | | [Simple interest](NumericTextBox/Samples) |This sample demonstrates how to calculate simple interest with currency format, percentage format, and custom format using numeric text box in a Xamarin Forms application. Users can change different cultures and also AllowNull properties in the option page.|<file_sep>/Forms/Chart/Chart/Samples/PolarChart/PolarSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class PolarSeriesViewModel { public ObservableCollection<ChartDataModel> PolarData1 { get; set; } public ObservableCollection<ChartDataModel> PolarData2 { get; set; } public ObservableCollection<ChartDataModel> PolarData3 { get; set; } public PolarSeriesViewModel() { PolarData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 4), new ChartDataModel("2001", 3.0), new ChartDataModel("2002", 3.8), new ChartDataModel("2003", 3.4), new ChartDataModel("2004", 3.2), new ChartDataModel("2005", 3.9), }; PolarData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 2.6), new ChartDataModel("2001", 2.8), new ChartDataModel("2002", 2.6), new ChartDataModel("2003", 3), new ChartDataModel("2004", 3.6), new ChartDataModel("2005", 3), }; PolarData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 2.8), new ChartDataModel("2001", 2.5), new ChartDataModel("2002", 2.8), new ChartDataModel("2003", 3.2), new ChartDataModel("2004", 2.9), new ChartDataModel("2005", 2), }; } } }<file_sep>/Forms/XlsIO/XlsIO/Samples/ImportNestedCollectionPage/ImportNestedCollectionPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Collections.ObjectModel; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XlsIO; using Xamarin.Forms; using System.ComponentModel; using System.Xml.Serialization; namespace SampleBrowser.XlsIO { /// <summary> /// This class is used to import data from nested collection to Excel worksheet. /// </summary> public partial class ImportNestedCollectionPage : SampleView { public ImportNestedCollectionPage() { InitializeComponent(); this.Layout.Items.Add("Default"); this.Layout.Items.Add("Merge"); this.Layout.Items.Add("Repeat"); this.Layout.SelectedIndex = 0; //this.Group.Items.Add("Expand"); //this.Group.Items.Add("Collapse at Level"); //this.Group.SelectedIndex = 0; if (Device.Idiom != TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP)) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; this.Content_3.FontSize = 13.5; this.Label1.FontSize = 13.5; this.Label2.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } internal void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2016; IWorkbook workbook = excelEngine.Excel.Workbooks.Create(1); IWorksheet worksheet = workbook.Worksheets[0]; IList<Brands> list = GetVehicleDetails(); ExcelImportDataOptions importDataOptions = new ExcelImportDataOptions(); importDataOptions.FirstRow = 4; if (this.Layout.SelectedIndex == 0) importDataOptions.NestedDataLayoutOptions = ExcelNestedDataLayoutOptions.Default; else if(this.Layout.SelectedIndex == 1) importDataOptions.NestedDataLayoutOptions = ExcelNestedDataLayoutOptions.Merge; else if(this.Layout.SelectedIndex == 2) importDataOptions.NestedDataLayoutOptions = ExcelNestedDataLayoutOptions.Repeat; if (Switch1.IsToggled) { if (ExpandButton.IsChecked.Value) { importDataOptions.NestedDataGroupOptions = ExcelNestedDataGroupOptions.Expand; } else if (CollapseButton.IsChecked.Value) { importDataOptions.NestedDataGroupOptions = ExcelNestedDataGroupOptions.Collapse; if (Level.Text != string.Empty) { importDataOptions.CollapseLevel = int.Parse(Level.Text); } } } worksheet.ImportData(list, importDataOptions); #region Define Styles IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle"); IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle"); pageHeader.Font.FontName = "Calibri"; pageHeader.Font.Size = 16; pageHeader.Font.Bold = true; pageHeader.Color = Syncfusion.Drawing.Color.FromArgb(0, 146, 208, 80); pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Font.Bold = true; tableHeader.Font.FontName = "Calibri"; tableHeader.Color = Syncfusion.Drawing.Color.FromArgb(0, 146, 208, 80); #endregion #region Apply Styles // Apply style for header worksheet["A1:C2"].Merge(); worksheet["A1"].Text = "Automobile Brands in the US"; worksheet["A1"].CellStyle = pageHeader; worksheet["A4:C4"].CellStyle = tableHeader; worksheet["A1:C1"].CellStyle.Font.Bold = true; worksheet.UsedRange.AutofitColumns(); #endregion MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("ImportNestedCollection.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("ImportNestedCollection.xlsx", "application/msexcel", stream); } } internal void OnRadioSelected(object sender, EventArgs e) { this.Level.IsVisible = this.CollapseButton.IsChecked.Value; } private void OnSwitchToggled(object sender, ToggledEventArgs e) { this.GroupGrid.IsVisible = this.Switch1.IsToggled; } #region Helper Methods private IList<Brands> GetVehicleDetails() { XmlSerializer deserializer = new XmlSerializer(typeof(BrandObjects)); Assembly assembly = typeof(App).GetTypeInfo().Assembly; #if COMMONSB string resourcePath = "SampleBrowser.Samples.XlsIO.Samples.Template.ExportData.xml"; #else string resourcePath = "SampleBrowser.XlsIO.Samples.Template.ExportData.xml"; #endif Stream fileStream = assembly.GetManifestResourceStream(resourcePath); TextReader textReader = new StreamReader(fileStream); BrandObjects brands = (BrandObjects)deserializer.Deserialize(textReader); List<Brands> list = new List<Brands>(); string brandName = brands.BrandObject[0].BrandName; string vehicleType = brands.BrandObject[0].VahicleType; string modelName = brands.BrandObject[0].ModelName; Brands brand = new Brands(brandName); brand.VehicleTypes = new List<VehicleTypes>(); VehicleTypes vehicle = new VehicleTypes(vehicleType); vehicle.Models = new List<Model>(); Model model = new Model(modelName); brand.VehicleTypes.Add(vehicle); list.Add(brand); foreach (BrandObject brandObj in brands.BrandObject) { if (brandName == brandObj.BrandName) { if (vehicleType == brandObj.VahicleType) { vehicle.Models.Add(new Model(brandObj.ModelName)); continue; } else { vehicle = new VehicleTypes(brandObj.VahicleType); vehicle.Models = new List<Model>(); vehicle.Models.Add(new Model(brandObj.ModelName)); brand.VehicleTypes.Add(vehicle); vehicleType = brandObj.VahicleType; } continue; } else { brand = new Brands(brandObj.BrandName); vehicle = new VehicleTypes(brandObj.VahicleType); vehicle.Models = new List<Model>(); vehicle.Models.Add(new Model(brandObj.ModelName)); brand.VehicleTypes = new List<VehicleTypes>(); brand.VehicleTypes.Add(vehicle); vehicleType = brandObj.VahicleType; list.Add(brand); brandName = brandObj.BrandName; } } textReader.Close(); return list; } #endregion } #region Helper Class [XmlRootAttribute("BrandObjects")] public class BrandObjects { [XmlElement("BrandObject")] public BrandObject[] BrandObject { get; set; } } public class BrandObject { public string BrandName { get; set; } public string VahicleType { get; set; } public string ModelName { get; set; } } //[Serializable] public class Brands { private string m_brandName; [DisplayNameAttribute("Brand")] public string BrandName { get { return m_brandName; } set { m_brandName = value; } } private IList<VehicleTypes> m_vehicles; public IList<VehicleTypes> VehicleTypes { get { return m_vehicles; } set { m_vehicles = value; } } public Brands(string brandName) { m_brandName = brandName; } } public class VehicleTypes { private string m_vehicle; [DisplayNameAttribute("Vehicle Type")] public string Vehicle { get { return m_vehicle; } set { m_vehicle = value; } } private IList<Model> m_models; public IList<Model> Models { get { return m_models; } set { m_models = value; } } public VehicleTypes(string vehicle) { m_vehicle = vehicle; } } #endregion }<file_sep>/Forms/NumericTextBox/NumericTextBox.iOS/CustomNumericTextBoxRenderer2.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.SfNumericTextBox; using SampleBrowser.SfNumericTextBox.iOS; using Syncfusion.SfNumericTextBox.XForms.iOS; using UIKit; using Xamarin.Forms; [assembly: ExportRenderer(typeof(NumericTextBoxRenderer2), typeof(CustomNumericTextBoxRenderer2))] namespace SampleBrowser.SfNumericTextBox.iOS { public class CustomNumericTextBoxRenderer2 : SfNumericTextBoxRenderer { protected override void OnElementChanged(Xamarin.Forms.Platform.iOS.ElementChangedEventArgs<Syncfusion.SfNumericTextBox.XForms.SfNumericTextBox> e) { base.OnElementChanged(e); if (Control != null) { Control.Layer.CornerRadius = 5; Control.Layer.BorderWidth = 1; Control.ClipsToBounds = true; } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/Customization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class Customization : SampleView { SFSchedule schedule; private readonly IList<string> scheduleTypes = new List<string>(); private string selectedType; UIPickerView scheduleTypePicker = new UIPickerView(); UILabel label = new UILabel(); UIButton button = new UIButton(); UIButton textbutton = new UIButton(); //CGRect rect = new CGRect(); UISegmentedControl customizationSegment = new UISegmentedControl(); //UIView scheduleView = new UIView(); SFHeaderStyle headerStyle; SFViewHeaderStyle viewHeaderStyle; //UIButton headerButton = new UIButton(); //UIButton moveToDate = new UIButton(); //UILabel monthText = new UILabel(); ////UITextView monthText = new UITextView(); //UIButton editorView = new UIButton(); //UIView headerView = new UIView(); //UISegmentedControl segmentControl = new UISegmentedControl(); //UITableView views = new UITableView(); //string[] tableItems = new string[] { }; public Customization() { schedule = new SFSchedule(); label.Text = "Select the Schedule Type"; label.TextColor = UIColor.Black; //this.AddSubview(label); headerStyle = new SFHeaderStyle(); viewHeaderStyle = new SFViewHeaderStyle(); schedule.HeaderHeight = 30; schedule.MonthCellLoaded += Schedule_MonthCellLoaded; schedule.AppointmentLoaded += Schedule_AppointmentLoaded; //schedule.HeaderStyle.BackgroundColor = UIColor.FromRGB(17, 17, 17); //schedule.HeaderStyle.TextColor = UIColor.FromRGB(238, 199, 43); //schedule.DayHeaderStyle.BackgroundColor = UIColor.FromRGB(28, 28, 28); //schedule.DayHeaderStyle.DayTextColor = UIColor.FromRGB(238, 199, 43); ; //schedule.DayHeaderStyle.DateTextColor = UIColor.FromRGB(238, 199, 43); ; textbutton.SetTitle("Day View", UIControlState.Normal); textbutton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; textbutton.BackgroundColor = UIColor.Clear; textbutton.SetTitleColor(UIColor.Black, UIControlState.Normal); textbutton.Hidden = false; textbutton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; textbutton.Layer.BorderWidth = 4; textbutton.Layer.CornerRadius = 8; textbutton.TouchUpInside += ShowPicker; //this.AddSubview(textbutton); button.SetTitle("Done\t", UIControlState.Normal); button.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; button.BackgroundColor = UIColor.FromRGB(240, 240, 240); button.SetTitleColor(UIColor.Black, UIControlState.Normal); button.Hidden = true; button.TouchUpInside += HidePicker; schedule.Appointments = CreateAppointments(); schedule.ScheduleView = SFScheduleView.SFScheduleViewDay; schedule.DayViewSettings = new DayViewSettings(); schedule.DayViewSettings.TimeTextColor = UIColor.FromRGB(168, 168, 173); schedule.DayViewSettings.TimeSlotBorderColor = UIColor.FromRGB(219, 219, 219); schedule.DayViewSettings.NonWorkingHourTimeSlotBorderColor = UIColor.FromRGB(219, 219, 219); UIButton SelectionView = new UIButton(); SelectionView.BackgroundColor = UIColor.FromRGB(0, 122, 255); SelectionView.SetTitle("+ New Event", UIControlState.Normal); schedule.SelectionView = SelectionView; viewHeaderStyle.BackgroundColor = UIColor.FromRGB(247, 247, 247); viewHeaderStyle.DayTextStyle = UIFont.SystemFontOfSize(18); viewHeaderStyle.DayTextColor = UIColor.FromRGB(3, 3, 3); headerStyle.TextPosition = UITextAlignment.Center; headerStyle.TextColor = UIColor.FromRGB(3, 3, 3); schedule.HeaderStyle = headerStyle; schedule.DayHeaderStyle = viewHeaderStyle; schedule.AppointmentViewLayout = SFViewLayoutOptions.Overlay; //control = this; //this.OptionView = new UIView(); this.scheduleTypes.Add((NSString)"Day View"); this.scheduleTypes.Add((NSString)"Month View"); Localization.SchedulePickerModel model = new Localization.SchedulePickerModel(this.scheduleTypes); model.PickerChanged += (sender, e) => { this.selectedType = e.SelectedValue; textbutton.SetTitle(selectedType, UIControlState.Normal); if (selectedType == "Day View") { schedule.ScheduleView = SFScheduleView.SFScheduleViewDay; } else if (selectedType == "Month View") { schedule.ScheduleView = SFScheduleView.SFScheduleViewMonth; } }; scheduleTypePicker.ShowSelectionIndicator = true; scheduleTypePicker.Hidden = true; scheduleTypePicker.Model = model; scheduleTypePicker.BackgroundColor = UIColor.White; } private void Schedule_AppointmentLoaded(object sender, AppointmentLoadedEventArgs e) { if (e.Appointment.Subject == "Checkup") { UIImageView hospitalImage = new UIImageView(); hospitalImage.Image = UIImage.FromFile("Images/Hospital.png"); hospitalImage.Frame = new CGRect(50, 35, 50.0f, 50.0f); UIStackView stackPanel = new UIStackView(); stackPanel.Frame = new CGRect(0, 0, 100, 50); stackPanel.Add(hospitalImage); e.AppointmentStyle.TextStyle = UIFont.FromName(@"Arial", 16); e.AppointmentStyle.TextColor = UIColor.White; e.View = stackPanel; } else { UIImageView familyImage = new UIImageView(); familyImage.Image = UIImage.FromFile("Images/family.png"); familyImage.Frame = new CGRect(50, 35, 50.0f, 30.0f); UIStackView stackPanel = new UIStackView(); stackPanel.Frame = new CGRect(0, 0, 100, 30); stackPanel.Add(familyImage); e.AppointmentStyle.TextStyle = UIFont.FromName(@"Arial", 16); e.AppointmentStyle.TextColor = UIColor.White; e.View = stackPanel; } } private void Schedule_MonthCellLoaded(object sender, MonthCellLoadedEventArgs e) { NSDate date = e.Date; NSDateFormatter dateFormat = new NSDateFormatter(); dateFormat.DateFormat = "EEEE"; string monthName = dateFormat.ToString(date); if (e.IsToday) { e.CellStyle.TextColor = UIColor.FromRGB(238, 199, 43); //monthCellLoadedaded.CellStyle.BackgroundColor = UIColor.Black; } if (((monthName == "Sunday") || (monthName == "Saturday"))) { e.CellStyle.TextColor = UIColor.Red; } if (e.IsPreviousMonthDate) { e.CellStyle.TextColor = UIColor.White; } if (e.IsNextMonthDate) { e.CellStyle.TextColor = UIColor.White; } } protected override void Dispose(bool disposing) { if (disposing) { if (textbutton != null) { textbutton.TouchUpInside -= ShowPicker; textbutton.Dispose(); textbutton = null; } if (button != null) { button.TouchUpInside -= HidePicker; button.Dispose(); button = null; } if (schedule != null) { schedule.MonthCellLoaded -= Schedule_MonthCellLoaded; schedule.AppointmentLoaded -= Schedule_AppointmentLoaded; this.schedule.Dispose(); this.schedule = null; } } base.Dispose(disposing); } void ShowPicker(object sender, EventArgs e) { button.Hidden = false; scheduleTypePicker.Hidden = false; this.BecomeFirstResponder(); } void HidePicker(object sender, EventArgs e) { button.Hidden = true; scheduleTypePicker.Hidden = true; this.BecomeFirstResponder(); } public override void LayoutSubviews() { string deviceType = UIDevice.CurrentDevice.Model; if (deviceType == "iPhone" || deviceType == "iPod touch") { label.Frame = new CGRect(15, 10, this.Frame.Size.Width - 20, 40); textbutton.Frame = new CGRect(10, 50, this.Frame.Size.Width - 20, 40); button.Frame = new CGRect(this.Frame.X + 10, 90, this.Frame.Size.Width - 20, 30); scheduleTypePicker.Frame = new CGRect(0, 120, this.Frame.Size.Width - 20, 150); } else { schedule.DayViewSettings.WorkStartHour = 7; schedule.DayViewSettings.WorkEndHour = 18; label.Frame = new CGRect(15, 10, this.Frame.Size.Width - 20, 40); textbutton.Frame = new CGRect(10, 60, (this.Frame.Size.Width / 2.5), 40); button.Frame = new CGRect(this.Frame.X + 10, 100, (this.Frame.Size.Width / 2.5), 30); scheduleTypePicker.Frame = new CGRect(0, 120, (this.Frame.Size.Width / 2.5), 120); //picker_scheduleView.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 170, (this.Frame.Size.Width / 2.5), 120); } customizationSegment.InsertSegment("Day", 0, false); customizationSegment.InsertSegment("Month", 1, false); customizationSegment.SelectedSegment = 0; customizationSegment.ValueChanged += (sender, e) => { var selectedSegmentId = (sender as UISegmentedControl).SelectedSegment; if (selectedSegmentId == 0) { schedule.ScheduleView = SFScheduleView.SFScheduleViewDay; } else if (selectedSegmentId == 1) { schedule.ScheduleView = SFScheduleView.SFScheduleViewMonth; } }; this.AddSubview(customizationSegment); //} //else //{ // //this.CreateOptionView(); //} //this.CreateOptionView(); schedule.Frame = new CGRect(0, 0, this.Frame.Size.Width, this.Frame.Size.Height); this.AddSubview(schedule); //base.LayoutSubviews(); } private void CreateOptionView() { this.OptionView.AddSubview(label); this.OptionView.AddSubview(textbutton); this.OptionView.AddSubview(scheduleTypePicker); this.OptionView.AddSubview(button); } NSMutableArray CreateAppointments() { NSDate today = new NSDate(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; NSDate startDate = calendar.DateFromComponents(components); // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; appointment.Subject = new NSString("Jeni's B'Day Celebration"); appointment.AppointmentBackground = UIColor.FromRGB(0xA2, 0xC1, 0x39); NSDateComponents components1 = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components1.Hour = 11; components1.Minute = 0; components1.Second = 0; components1.Day = components1.Day + 1; NSDate startDate1 = calendar.DateFromComponents(components1); // Get the year, month, day from the date NSDateComponents endDateComponents1 = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents1.Hour = 13; endDateComponents1.Minute = 30; endDateComponents1.Second = 0; endDateComponents1.Day = endDateComponents1.Day + 1; NSDate endDate1 = calendar.DateFromComponents(endDateComponents1); ScheduleAppointment appointment1 = new ScheduleAppointment(); appointment1.StartTime = startDate1; appointment1.EndTime = endDate1; appointment1.Subject = new NSString("Checkup"); appointment1.AppointmentBackground = UIColor.FromRGB(0xD8, 0x00, 0x73); NSMutableArray appCollection = new NSMutableArray(); appCollection.Add(appointment); appCollection.Add(appointment1); return appCollection; } } } <file_sep>/Android/SampleBrowser/Samples/Calendar/CalendarLocalization/CalendarLocalization_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Java.Util; using Com.Syncfusion.Calendar; using Com.Syncfusion.Calendar.Enums; using Android.Graphics; namespace SampleBrowser { public class CalendarLocalization_Tab : SamplePage, IDisposable { /********************************* **Local Variable Inizialisation** *********************************/ private FrameLayout mainLayout; private SfCalendar calendar; private LinearLayout proprtyOptionsLayout; private ArrayAdapter<String> dataAdapter; private Spinner cultureSpinner; public override View GetSampleContent(Context context) { //mainLayout mainLayout = new FrameLayout(context); calendar = new SfCalendar(context); calendar.ViewMode = ViewMode.MonthView; calendar.HeaderHeight = 100; calendar.ShowEventsInline = false; calendar.Locale = new Java.Util.Locale("zh", "CN"); MonthViewLabelSetting labelSettings = new MonthViewLabelSetting(); labelSettings.DateLabelSize = 14; MonthViewSettings monthViewSettings = new MonthViewSettings(); monthViewSettings.MonthViewLabelSetting = labelSettings; monthViewSettings.SelectedDayTextColor = Color.Black; monthViewSettings.TodayTextColor = Color.ParseColor("#1B79D6"); monthViewSettings.InlineBackgroundColor = Color.ParseColor("#E4E8ED"); monthViewSettings.WeekDayBackgroundColor = Color.ParseColor("#F7F7F7"); calendar.MonthViewSettings = monthViewSettings; mainLayout.AddView(calendar); return mainLayout; } public override View GetPropertyWindowLayout(Context context) { proprtyOptionsLayout = new LinearLayout(context); proprtyOptionsLayout.SetPadding(40, 40, 40, 0); proprtyOptionsLayout.Orientation = Android.Widget.Orientation.Vertical; CultureLayout(context); return proprtyOptionsLayout; } private void CultureLayout(Context context) { //Culture Text TextView cultureLabel = new TextView(context); cultureLabel.TextSize = 20; cultureLabel.SetPadding(0, 0, 0, 50); cultureLabel.Text = "Culture"; cultureSpinner = new Spinner(context, SpinnerMode.Dialog); //Culture List List<String> cultureList = new List<String>(); cultureList.Add("Chinese"); cultureList.Add("Spanish"); cultureList.Add("English"); cultureList.Add("French"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, cultureList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //cultureSpinner cultureSpinner.Adapter = dataAdapter; cultureSpinner.SetSelection(0); //Culture Item Selected Listener cultureSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Chinese")) { calendar.Locale = Java.Util.Locale.China; //new Java.Util.Locale("en","US"); } if (selectedItem.Equals("Spanish")) { calendar.Locale = new Java.Util.Locale("es", "AR"); } if (selectedItem.Equals("English")) { calendar.Locale = Java.Util.Locale.Us; } if (selectedItem.Equals("French")) { calendar.Locale = Java.Util.Locale.France; } }; //cultureLayout LinearLayout cultureLayout = new LinearLayout(context); cultureLayout.Orientation = Android.Widget.Orientation.Vertical; cultureLayout.AddView(cultureLabel); cultureLayout.AddView(cultureSpinner); proprtyOptionsLayout.AddView(cultureLayout); } public void Dispose() { if (calendar != null) { calendar.Dispose(); calendar = null; } if (mainLayout != null) { mainLayout.Dispose(); mainLayout = null; } if (proprtyOptionsLayout != null) { proprtyOptionsLayout.Dispose(); proprtyOptionsLayout = null; } if (dataAdapter != null) { dataAdapter.Dispose(); dataAdapter = null; } if (cultureSpinner != null) { cultureSpinner.Dispose(); cultureSpinner = null; } } } }<file_sep>/Android/SampleBrowser/Samples/Rotator/Rotator_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Android.Content; using Com.Syncfusion.Rotator; using System.Collections; using Android.Graphics; namespace SampleBrowser { public class Rotator_Tab : SamplePage { public Rotator_Tab() { } /********************************* **Local Variable Inizialisation** *********************************/ SfRotator rotator; Context con; Spinner directionSpinner, tabStripSpinner, modeSpinner; ArrayAdapter<String> tabAdapter, directionAdapter, modeAdapter; Context context; LinearLayout proprtyOptionsLayout; public override View GetSampleContent(Android.Content.Context context1) { con = context1; context = context1; //Rotator rotator = new SfRotator(con); rotator.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);//ActionBar.LayoutParameters(ViewGroup.LayoutParams.MATCH_PARENT,height/2); rotator.NavigationStripMode = NavigationStripMode.Dots; rotator.NavigationDirection = NavigationDirection.Horizontal; rotator.NavigationStripPosition = NavigationStripPosition.Bottom; rotator.SelectedIndex = 2; rotator.EnableAutoPlay = false; rotator.SetBackgroundColor(Color.ParseColor("#ececec")); //Images List List<SfRotatorItem> images = new List<SfRotatorItem>(); //Images Id List List<int> imageID = new List<int>(); imageID.Add(Resource.Drawable.movie1); imageID.Add(Resource.Drawable.movie2); imageID.Add(Resource.Drawable.movie3); imageID.Add(Resource.Drawable.movie4); imageID.Add(Resource.Drawable.movie5); SfRotatorItem item; ImageView image; for (int i = 0; i < imageID.Count; i++) { item = new SfRotatorItem(con); image = new ImageView(con); image.SetImageResource(imageID[i]); item.Content = image; images.Add(item); } rotator.DataSource = images; return rotator; } public override View GetPropertyWindowLayout(Context context) { proprtyOptionsLayout = new LinearLayout(context); proprtyOptionsLayout.Orientation = Orientation.Vertical; NavigationDirectionLayout(); StripPositionLayout(); StripModeLayout(); EnableAutoPlayLayout(); return proprtyOptionsLayout; } private void NavigationDirectionLayout() { //Direction Label TextView directionLabel = new TextView(context); directionLabel.Text = "Navigation Direction"; directionLabel.TextSize = 20; directionLabel.SetPadding(0,0,0,50); directionLabel.SetTextColor(Color.Black); directionLabel.Gravity = GravityFlags.Left; //directionSpinner directionSpinner = new Spinner(context,SpinnerMode.Dialog); directionSpinner.SetPadding(0, 0, 0, 0); //Direction List List<String> directionList = new List<String>(); directionList.Add("Horizontal"); directionList.Add("Vertical"); //Direction adapter directionAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, directionList); directionAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //Direction Spinner Item Selected Listener directionSpinner.Adapter = directionAdapter; directionSpinner.SetSelection(0); directionSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = directionAdapter.GetItem(e.Position); if (selectedItem.Equals("Horizontal")) { rotator.NavigationDirection = NavigationDirection.Horizontal; } else if (selectedItem.Equals("Vertical")) { rotator.NavigationDirection = NavigationDirection.Vertical; } }; //directionLayout LinearLayout directionLayout = new LinearLayout(context); directionLayout.Orientation = Android.Widget.Orientation.Vertical; directionLayout.SetPadding(0,0,0,60); directionLayout.AddView(directionLabel); directionLayout.AddView(directionSpinner); proprtyOptionsLayout.AddView(directionLayout); } private void StripPositionLayout() { //Tap Position TextView tabPoitionLabel = new TextView(context); tabPoitionLabel.SetPadding(0,0,0,50); tabPoitionLabel.Text = "Navigation Strip Position"; tabPoitionLabel.Gravity = GravityFlags.Left; tabPoitionLabel.TextSize = 20; tabPoitionLabel.SetTextColor(Color.Black); //tabList List<String> tabList = new List<String>(); tabList.Add("Bottom"); tabList.Add("Top"); tabList.Add("Right"); tabList.Add("Left"); tabStripSpinner = new Spinner(context,SpinnerMode.Dialog); // Tap Adapter tabAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, tabList); tabAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //tabStripSpinner tabStripSpinner.Adapter = tabAdapter; tabStripSpinner.SetSelection(0); tabStripSpinner.SetPadding(0, 0, 0, 0); tabStripSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = tabAdapter.GetItem(e.Position); if (selectedItem.Equals("Bottom")) { rotator.NavigationStripPosition = NavigationStripPosition.Bottom; } else if (selectedItem.Equals("Top")) { rotator.NavigationStripPosition = NavigationStripPosition.Top; } if (selectedItem.Equals("Right")) { rotator.NavigationStripPosition = NavigationStripPosition.Right; } else if (selectedItem.Equals("Left")) { rotator.NavigationStripPosition = NavigationStripPosition.Left; } }; //tabPoitionLayout LinearLayout tabPoitionLayout = new LinearLayout(context); tabPoitionLayout.Orientation = Android.Widget.Orientation.Vertical; tabPoitionLayout.SetPadding(0,0,0,60); tabPoitionLayout.AddView(tabPoitionLabel); tabPoitionLayout.AddView(tabStripSpinner); proprtyOptionsLayout.AddView(tabPoitionLayout); } private void StripModeLayout() { //modeLabel TextView modeLabel = new TextView(context); modeLabel.SetPadding(0,0,0,50); modeLabel.Text = "Navigation Strip Mode"; modeLabel.Gravity = GravityFlags.Left; modeLabel.TextSize = 20; modeLabel.SetTextColor(Color.Black); //Mode List List<String> modeList = new List<String>(); modeList.Add("Dots"); modeList.Add("Thumbnail"); //Mode Spinner Item Selected Listener modeSpinner = new Spinner(context,SpinnerMode.Dialog); modeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = modeAdapter.GetItem(e.Position); if (selectedItem.Equals("Dots")) { rotator.NavigationStripMode = NavigationStripMode.Dots; } else if (selectedItem.Equals("Thumbnail")) { rotator.NavigationStripMode = NavigationStripMode.Thumbnail; } }; //modeAdapter modeAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, modeList); modeAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); modeSpinner.Adapter = modeAdapter; modeSpinner.SetSelection(0); //modeLayout LinearLayout modeLayout = new LinearLayout(context); modeLayout.Orientation = Android.Widget.Orientation.Vertical; modeLayout.SetPadding(0,0,0,60); modeLayout.AddView(modeLabel); modeLayout.AddView(modeSpinner); proprtyOptionsLayout.AddView(modeLayout); } private void EnableAutoPlayLayout() { //autoPlayLabel TextView autoPlayLabel = new TextView(context); autoPlayLabel.SetPadding(0, 0, 0, 50); autoPlayLabel.Text = "Enable AutoPlay"; autoPlayLabel.TextSize = 20; //Auto Play Switch LinearLayout ex = new LinearLayout(context); Switch playSwitch = new Switch(context); playSwitch.Checked = false; playSwitch.Gravity = GravityFlags.End; playSwitch.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { rotator.EnableAutoPlay = e.IsChecked; }; ex.AddView(playSwitch); ex.SetPadding(450,0,0,0); LinearLayout autoPlayLayout = new LinearLayout(context); autoPlayLayout.SetPadding(0,0,0,60); autoPlayLayout.Orientation = Android.Widget.Orientation.Horizontal; autoPlayLayout.AddView(autoPlayLabel); autoPlayLayout.AddView(ex); proprtyOptionsLayout.AddView(autoPlayLayout); } } } <file_sep>/Forms/TreeView/TreeView/Samples/Template/Helper/Converter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public class LabelIsVisibleConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var mailsCount = (int)value; return mailsCount > 0 ? true : false; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } [Preserve(AllMembers = true)] public class FontAttributeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var mailsCount = (int)value; return mailsCount > 0 ? FontAttributes.Bold : FontAttributes.None; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Forms/RadialMenu/RadialMenu/Samples/SlotIndex_RadialMenu/SlotIndex_RadialMenu.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Xamarin.Forms; using SampleBrowser.Core; using System.Globalization; namespace SampleBrowser.SfRadialMenu { public partial class SlotIndex_RadialMenu : SampleView { double height, width; double height1, width1; public SlotIndex_RadialMenu() { InitializeComponent(); if (Device.RuntimePlatform == Device.Android) { height = Core.SampleBrowser.ScreenHeight / 5.1; width = Core.SampleBrowser.ScreenWidth / 2 - radial_Menu.CenterButtonRadius * 1.5; } else if (Device.RuntimePlatform == Device.iOS) { height = Core.SampleBrowser.ScreenHeight / 6 + radial_Menu.CenterButtonRadius; width = Core.SampleBrowser.ScreenWidth / 2 - radial_Menu.CenterButtonRadius * 2; } //else if (Device.RuntimePlatform == Device.Windows) //{ // height = App.ScreenHeight / 5.1; // width = App.ScreenWidth / 2 - radial_Menu.CenterButtonRadius * 1.5; // facebook.Margin = new Thickness(0, 3, 0, 0); // twitter.Margin = new Thickness(0, 3, 0, 0); // google.Margin = new Thickness(0, 3, 0, 0); // if (Device.Idiom == TargetIdiom.Phone) // { // radial_Menu.RimRadius = 130.0; // } //} TapGestureRecognizer facebook_Tap = new TapGestureRecognizer(); facebook_Tap.Tapped += async (object sender, EventArgs e) => { radial_Menu.Close(); var alertResult = await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Alert", "Are you sure you want to share this page in your Facebook account?", null, "OK"); }; facebook.GestureRecognizers.Add(facebook_Tap); TapGestureRecognizer google_Tap = new TapGestureRecognizer(); google_Tap.Tapped += async (object sender, EventArgs e) => { radial_Menu.Close(); var alertResult = await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Alert", "Are you sure you want to share this page in your Google Plus account?", null, "OK"); }; google.GestureRecognizers.Add(google_Tap); TapGestureRecognizer twitter_Tap = new TapGestureRecognizer(); twitter_Tap.Tapped += async (object sender, EventArgs e) => { radial_Menu.Close(); var alertResult = await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Alert", "Are you sure you want to share this page in your Twitter account?", null, "OK"); }; twitter.GestureRecognizers.Add(twitter_Tap); TapGestureRecognizer linkedIn_Tap = new TapGestureRecognizer(); linkedIn_Tap.Tapped += async (object sender, EventArgs e) => { radial_Menu.Close(); var alertResult = await Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Alert", "Are you sure you want to share this page in your LinkedIn account?", null, "OK"); }; linkedIn.GestureRecognizers.Add(linkedIn_Tap); this.SizeChanged += SlotIndex_RadialMenu_SizeChanged; } private void SlotIndex_RadialMenu_SizeChanged(object sender, EventArgs e) { if (this.Height < this.Width) { syncfusionText.Text = "Syncfusion is the enterprise technology partner of choice for software development, delivering a broad range of web, mobile, and desktop controls coupled with a service-oriented approach throughout the entire application lifecycle."; } else { syncfusionText.Text = "Syncfusion is the enterprise technology partner of choice for software development, delivering a broad range of web, mobile, and desktop controls coupled with a service-oriented approach throughout the entire application lifecycle. Syncfusion has established itself as the trusted partner worldwide for use in mission-critical applications. Founded in 2001 and headquartered in Research Triangle Park, N.C., Syncfusion has more than 12,000 customers, including large financial institutions, Fortune 100 companies, and global IT consultancies."; } if (Device.RuntimePlatform == Device.Android) { height1 = this.Height / 2.55; width1 = this.Width / 2 - radial_Menu.CenterButtonRadius * 1.5; } else if (Device.RuntimePlatform == Device.iOS) { height1 = this.Height / 3 + radial_Menu.CenterButtonRadius; width1 = this.Width / 2 - radial_Menu.CenterButtonRadius * 2; } else if (Device.RuntimePlatform == Device.UWP) { height1 = this.Height / 2.55; width1 = this.Width / 2 - radial_Menu.CenterButtonRadius * 1.5; facebook.Margin = new Thickness(0, 3, 0, 0); twitter.Margin = new Thickness(0, 3, 0, 0); google.Margin = new Thickness(0, 3, 0, 0); if (Device.Idiom == TargetIdiom.Desktop) { radial_Menu.RimRadius = 180.0; } if (Device.Idiom == TargetIdiom.Phone) { radial_Menu.RimRadius = 150.0; } } radial_Menu.Point = new Point(width1, height1); } public override void OnDisappearing() { if (Device.RuntimePlatform == Device.UWP) { radial_Menu.Dispose(); } base.OnDisappearing(); } } public class SlotIndexFontConversion : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (Device.RuntimePlatform == Device.Android) { if (parameter != null && parameter is string) return "radialmenu_socialicons.ttf#" + parameter.ToString(); else return "radialmenu_socialicons.ttf"; } else if (Device.RuntimePlatform == Device.iOS) { return "Social"; } else { #if COMMONSB return "radialmenu_socialicons.ttf#Social_Icons"; #else if (Core.SampleBrowser.IsIndividualSB) { return "radialmenu_socialicons.ttf#Social_Icons"; } else { return "SampleBrowser.SfRadialMenu.UWP\\radialmenu_socialicons.ttf#Social_Icons"; } #endif } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }<file_sep>/Forms/Maps/Maps.Android/NetConnection_Droid.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Net; using SampleBrowser.SfMaps.Droid; using System.Threading.Tasks; [assembly: Xamarin.Forms.Dependency(typeof(NetConnection_Droid))] namespace SampleBrowser.SfMaps.Droid { public class NetConnection_Droid : OSMINetwork { public bool IsConnected { get; set; } public async Task CheckNetworkConnection() { var connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService); var activeNetworkInfo = connectivityManager.ActiveNetworkInfo; if (activeNetworkInfo != null && activeNetworkInfo.IsConnectedOrConnecting) { IsConnected = true; } else { IsConnected = false; } await Task.Delay(10); } } }<file_sep>/Forms/Chart/Chart/Samples/SplineAreaChart/SplineAreaSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class SplineAreaSeriesViewModel { public ObservableCollection<ChartDataModel> SplineAreaData1 { get; set; } public ObservableCollection<ChartDataModel> SplineAreaData2 { get; set; } public ObservableCollection<ChartDataModel> SplineAreaData3 { get; set; } public SplineAreaSeriesViewModel() { SplineAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2002, 2.2), new ChartDataModel(2003, 3.4), new ChartDataModel(2004, 2.8), new ChartDataModel(2005, 1.6), new ChartDataModel(2006, 2.3), new ChartDataModel(2007, 2.5), new ChartDataModel(2008, 2.9), new ChartDataModel(2009, 3.8), new ChartDataModel(2010, 1.4), new ChartDataModel(2011, 3.1), }; SplineAreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2002, 2.0), new ChartDataModel(2003, 1.7), new ChartDataModel(2004, 1.8), new ChartDataModel(2005, 2.1), new ChartDataModel(2006, 2.3), new ChartDataModel(2007, 1.7), new ChartDataModel(2008, 1.5), new ChartDataModel(2009, 2.8), new ChartDataModel(2010, 1.5), new ChartDataModel(2011, 2.3), }; SplineAreaData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2002, 0.8), new ChartDataModel(2003, 1.3), new ChartDataModel(2004, 1.1), new ChartDataModel(2005, 1.6), new ChartDataModel(2006, 2.0), new ChartDataModel(2007, 1.7), new ChartDataModel(2008, 2.3), new ChartDataModel(2009, 2.7), new ChartDataModel(2010, 1.1), new ChartDataModel(2011, 2.3), }; } } } <file_sep>/Forms/DataGrid/DataGrid.WPF/SaveWindows.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SaveWindows.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Microsoft.Win32; using SampleBrowser; using SampleBrowser.SfDataGrid.WPF; using Xamarin.Forms; [assembly: Dependency(typeof(SaveWindows))] namespace SampleBrowser.SfDataGrid.WPF { /// <summary> /// A dependency service to save a exported file in WPF /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1400:AccessModifierMustBeDeclared", Justification = "Reviewed.")] class SaveWindows : ISave { /// <summary> /// Used to Save a Exporting file in WPF /// </summary> /// <param name="filename">string type of fileName</param> /// <param name="contentType">string type of contentType</param> /// <param name="stream">string type of stream</param> /// <returns>returns the saved file</returns> public void Save(string filename, string contentType, MemoryStream stream) { string fileType = null; switch (contentType) { case "application/msexcel": fileType = "Excel 97 to 2003 Files(*.xls)|*.xls|Excel 2007 to 2010 Files(*.xlsx)|*.xlsx|Excel 2013 File(*.xlsx)|*.xlsx"; break; case "application/pdf": fileType = "PDF Files(*.pdf)|*.pdf"; break; } SaveFileDialog sfd = new SaveFileDialog { Filter = fileType }; if (sfd.ShowDialog() == true) { using (Stream streams = sfd.OpenFile()) { streams.Write(stream.ToArray(), 0, (int)stream.Length); streams.Flush(); streams.Dispose(); } stream.Flush(); stream.Dispose(); if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) { System.Diagnostics.Process.Start(sfd.FileName); } } } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/GroupingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GroupingViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for Grouping sample. /// </summary> public class GroupingViewModel : Employee { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private List<ProductInfo> productDetails; /// <summary> /// Initializes a new instance of the GroupingViewModel class. /// </summary> public GroupingViewModel() { ProductInfoRepository products = new ProductInfoRepository(); this.ProductDetails = products.GetProductDetails(100); } /// <summary> /// Gets or sets the value of product details and notifies user when value gets changed /// </summary> /// <value>The product details.</value> public List<ProductInfo> ProductDetails { get { return this.productDetails; } set { this.productDetails = value; this.RaisePropertyChanged("ProductDetails"); } } } } <file_sep>/Forms/PdfViewer/PdfViewer.UWP/SaveWindows.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; using Xamarin.Forms; [assembly: Dependency(typeof(SampleBrowser.SfPdfViewer.UWP.SaveWindows))] [assembly: Dependency(typeof(SampleBrowser.SfPdfViewer.UWP.BrowserURI))] namespace SampleBrowser.SfPdfViewer.UWP { public class SaveWindows : ISave { MemoryStream stream; StorageFolder folder; StorageFile file; public string Save(MemoryStream documentStream) { documentStream.Position = 0; stream = documentStream; SaveAsync(); return Path.Combine(ApplicationData.Current.LocalFolder.Path, "SavedDocument.pdf"); } private async void SaveAsync() { folder = ApplicationData.Current.LocalFolder; file = await folder.CreateFileAsync("SavedDocument.pdf", CreationCollisionOption.ReplaceExisting); if (file != null) { Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.ReadWrite); Stream st = fileStream.AsStreamForWrite(); st.SetLength(0); st.Write((stream as MemoryStream).ToArray(), 0, (int)stream.Length); st.Flush(); st.Dispose(); fileStream.Dispose(); } } } public class BrowserURI : IDeviceOpenURI { public void OpenURI(string selectedText) { this.OpenURIAsync(selectedText); } private async void OpenURIAsync(string selectedText) { var uriBing = new Uri($"https://www.google.com/search?q={selectedText}"); await Windows.System.Launcher.LaunchUriAsync(uriBing); } } } <file_sep>/iOS/SampleBrowser/Samples/PDF/DigitalSignature.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf; using Syncfusion.Pdf.Barcode; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Security; using MessageUI; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class DigitalSignature : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label1; UIButton button; public DigitalSignature() { label1 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label1.Frame = frameRect; label1.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label1.Text = "This sample demonstrates how a PDF document can be secured with certificates and signed with either standard or author signatures. Now added the support for Elliptic Curve Digital Signature Algorithm (ECDSA) to sign the PDF document."; label1.Font = UIFont.SystemFontOfSize(15); label1.Lines = 0; label1.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label1.Font = UIFont.SystemFontOfSize(18); label1.Frame = new CGRect(0, 12, frameRect.Location.X + frameRect.Size.Width, 120); } else { label1.Frame = new CGRect(frameRect.Location.X, 12, frameRect.Size.Width, 120); } this.AddSubview(label1); button.SetTitle("Sign and Email", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 150, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 150, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { Stream docStream = typeof(Booklet).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.SalesOrderDetail.pdf"); //Load the PDF document into the loaded document object. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream); //Get the certificate stream from .pfx file. Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.PDF.pfx"); //Create PdfCertificate using certificate stream and password. PdfCertificate pdfCert = new PdfCertificate(certificateStream, "syncfusion"); //Add certificate to document first page. PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCert, "Signature"); signature.Bounds = new Syncfusion.Drawing.RectangleF(5, 5, 300, 300); MemoryStream stream = new MemoryStream(); //Save the PDF document loadedDocument.Save(stream); //Close the PDF document loadedDocument.Close(true); if (stream != null) { stream.Position = 0; ComposeMail("DigitalSignature.pdf", null, "Signing the document", "Syncfusion", stream); } } public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream stream) { if (MFMailComposeViewController.CanSendMail) { var mailer = new MFMailComposeViewController(); mailer.SetMessageBody(messagebody ?? string.Empty, false); mailer.SetSubject(subject ?? subject); mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { }); string exception = string.Empty; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filePath = Path.Combine(path, fileName); try { FileStream fileStream = File.Open(filePath, FileMode.Create); stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { exception = e.ToString(); } finally { } mailer.AddAttachmentData(NSData.FromFile(filePath), GetMimeType(fileName), Path.GetFileName(fileName)); UIViewController vc = UIApplication.SharedApplication.KeyWindow.RootViewController; while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } vc.PresentViewController(mailer, true, null); } else { var alertController = UIAlertController.Create("Email not supported", "Please configure the email to send PDF document", UIAlertControllerStyle.Alert); alertController.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,null)); UIViewController vc = UIApplication.SharedApplication.KeyWindow.RootViewController; while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } vc.PresentViewController(alertController,true,null); } } private string GetMimeType(string filename) { if (string.IsNullOrEmpty(filename)) { return null; } var extension = Path.GetExtension(filename.ToLowerInvariant()); switch (extension) { case "png": return "image/png"; case "doc": return "application/msword"; case "pdf": return "application/pdf"; case "jpeg": case "jpg": return "image/jpeg"; case "zip": case "docx": case "xlsx": case "pptx": return "application/zip"; case "htm": case "html": return "text/html"; } return "application/octet-stream"; } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } } <file_sep>/Forms/Calendar/Calendar/Samples/WeekView/Behaviors/WeekViewBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using SampleBrowser.Core; using Syncfusion.SfCalendar.XForms; using Xamarin.Forms; namespace SampleBrowser.SfCalendar { internal class WeekViewBehavior : Behavior<SampleView> { private Syncfusion.SfCalendar.XForms.SfCalendar calendar; private Grid grid; private double calendarWidth = 500; private int padding = 50; protected override void OnAttachedTo(SampleView bindable) { base.OnAttachedTo(bindable); bindable.SizeChanged += Bindable_SizeChanged; this.calendar = bindable.Content.FindByName<Syncfusion.SfCalendar.XForms.SfCalendar>("calendar"); this.grid = bindable.Content.FindByName<Grid>("grid"); if (Device.RuntimePlatform == "UWP") { this.grid.HorizontalOptions = LayoutOptions.Center; this.grid.WidthRequest = this.calendarWidth; bindable.SizeChanged += this.Bindable_SizeChanged; } this.calendar.InlineViewMode = InlineViewMode.Agenda; this.calendar.MonthViewSettings.SelectionShape = SelectionShape.Circle; if (Device.RuntimePlatform == "UWP") { this.calendar.MaximumEventIndicatorCount = 1; this.calendar.MonthViewSettings.InlineTextColor = Color.Black; this.calendar.MonthViewSettings.DayHeaderTextColor = Color.Black; } if (Device.Idiom == TargetIdiom.Tablet) { if (Device.RuntimePlatform == "Android") { this.calendar.MonthViewSettings.SelectionRadius = 30; } else { this.calendar.MonthViewSettings.SelectionRadius = 20; } } this.calendar.NumberOfWeeksInView = 1; } private void Bindable_SizeChanged(object sender, EventArgs e) { var height = (sender as SampleView).Content.Height; var width = (sender as SampleView).Content.Width; if (Device.RuntimePlatform == "UWP") { var sampleView = sender as SampleView; if (sampleView.Width < this.calendarWidth + padding) { this.grid.WidthRequest = sampleView.Width - padding; } } if (height > width) { switch (Device.RuntimePlatform) { case Device.iOS: if (Device.Idiom == TargetIdiom.Phone) { this.calendar.AgendaViewHeight = height * 0.75; } else { this.calendar.AgendaViewHeight = height * 0.8; } break; case Device.Android: if (Device.Idiom == TargetIdiom.Phone) { var info = Device.Info; var totalHeight = height * info.ScalingFactor; totalHeight = totalHeight - (this.calendar.HeaderHeight * info.ScalingFactor) - (this.calendar.MonthViewSettings.DayHeight * info.ScalingFactor); this.calendar.AgendaViewHeight = (totalHeight - (this.calendar.HeaderHeight * info.ScalingFactor)) / 2; } else { this.calendar.AgendaViewHeight = height * 0.35; } break; case Device.UWP: this.calendar.AgendaViewHeight = height * 0.75; break; } } else { switch (Device.RuntimePlatform) { case Device.iOS: if (Device.Idiom == TargetIdiom.Phone) { this.calendar.AgendaViewHeight = height * 0.5; } else { this.calendar.AgendaViewHeight = width * 0.5; } break; case Device.Android: if (Device.Idiom == TargetIdiom.Phone) { var info = Device.Info; var totalHeight = height * info.ScalingFactor; totalHeight = totalHeight - (this.calendar.HeaderHeight * info.ScalingFactor) - (this.calendar.MonthViewSettings.DayHeight * info.ScalingFactor); this.calendar.AgendaViewHeight = (totalHeight - (50 * info.ScalingFactor)) / 2; } else { this.calendar.AgendaViewHeight = height * 0.25; } break; case Device.UWP: this.calendar.AgendaViewHeight = height * 0.75; break; } } } protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); if (Device.RuntimePlatform == "UWP") { bindable.SizeChanged -= this.Bindable_SizeChanged; } this.grid = null; this.calendar = null; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Numerical.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Drawing; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class NumericalAxis : SampleView { public NumericalAxis() { SFChart chart = new SFChart (); chart.Title.Text = (NSString) "Average Temperature Analysis"; chart.PrimaryAxis = new SFNumericalAxis (){ Interval = NSObject.FromObject(1)}; chart.PrimaryAxis.Title.Text = (NSString) "Year"; chart.SecondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis.Title.Text = (NSString) "Temerature (celsius)"; chart.SecondaryAxis.Minimum = new NSNumber(0); chart.SecondaryAxis.Maximum = new NSNumber(100); ChartViewModel dataModel = new ChartViewModel (); SFColumnSeries series = new SFColumnSeries(); series.ItemsSource = dataModel.NumericData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.ColorModel.Palette = SFChartColorPalette.Natural; series.EnableAnimation = true; chart.Series.Add(series); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } }<file_sep>/Forms/PopupLayout/PopupLayout.Android/MainActivity.cs // ------------------------------------------------------------------------------------ // <copyright file = "MainActivity.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ namespace SampleBrowser.SfPopupLayout.Droid { using System.Diagnostics.CodeAnalysis; using Android.App; using Android.Content.PM; using Android.OS; using Syncfusion.XForms.Android.PopupLayout; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [Activity(Label = "SampleBrowser.SfPopupLayout", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] /// <summary> /// The MainActivity of the Application /// </summary> public class MainActivity : FormsAppCompatActivity { /// <summary> /// Called when the activity is starting /// </summary> /// <param name="bundle">Bundle type parameter named as bundle</param> protected override void OnCreate(Bundle bundle) { FormsAppCompatActivity.TabLayoutResource = Resource.Layout.Tabbar; FormsAppCompatActivity.ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); Forms.Init(this, bundle); SfPopupLayoutRenderer.Init(); this.LoadApplication(new App()); } } }<file_sep>/iOS/SampleBrowser/AppDelegate.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Foundation; using UIKit; namespace SampleBrowser { [Register("AppDelegate")] public class AppDelegate : UIApplicationDelegate { #region properties public override UIWindow Window { get; set; } #endregion #region methods public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { this.Window = new UIWindow(UIScreen.MainScreen.Bounds); NSUserDefaults.StandardUserDefaults.SetString("22.2.5", "VersionNumber"); NSUserDefaults.StandardUserDefaults.Synchronize(); UINavigationController controller = new UINavigationController(new HomeViewController()); UINavigationBar.Appearance.SetTitleTextAttributes(new UITextAttributes() { TextColor = UIColor.White }); controller.NavigationBar.BarTintColor = Utility.ThemeColor; controller.NavigationBar.TintColor = UIColor.White; application.StatusBarHidden = false; application.StatusBarStyle = UIStatusBarStyle.LightContent; var appearance = new UINavigationBarAppearance() { BackgroundColor = UIColor.FromRGB(3.0f / 255.0f, 126.0f / 255.0f, 249.0f / 255.0f), ShadowColor = UIColor.FromRGB(3.0f / 255.0f, 126.0f / 255.0f, 249.0f / 255.0f), }; UINavigationBar.Appearance.StandardAppearance = appearance; UINavigationBar.Appearance.ScrollEdgeAppearance = appearance; this.Window.RootViewController = controller; this.Window.MakeKeyAndVisible(); return true; } public override void OnResignActivation(UIApplication application) { } public override void DidEnterBackground(UIApplication application) { } public override void WillEnterForeground(UIApplication application) { } public override void OnActivated(UIApplication application) { } public override void WillTerminate(UIApplication application) { } #endregion } } <file_sep>/Android/SampleBrowser/Samples/DocIO/EncryptAndDecrypt.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.OfficeChart; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using Syncfusion.Drawing; using System.IO; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Webkit; using Android.App; using Android.OS; namespace SampleBrowser { public partial class EncryptAndDecrypt : SamplePage { private Context m_context; RadioGroup radioGroup; RadioButton encryptDocument; RadioButton decryptDocument; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to encrypt and decrypt the Word document using Essential DocIO."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; LinearLayout radioLinearLayoutVertical = new LinearLayout(con); radioLinearLayoutVertical.Orientation = Orientation.Vertical; radioGroup = new RadioGroup(con); radioGroup.TextAlignment = TextAlignment.Center; radioGroup.Orientation = Orientation.Vertical; encryptDocument = new RadioButton(con); encryptDocument.Text = "Encrypt Document"; radioGroup.AddView(encryptDocument); decryptDocument = new RadioButton(con); decryptDocument.Text = "Decrypt Document"; radioGroup.AddView(decryptDocument); radioGroup.Check(1); radioLinearLayoutVertical.AddView(radioGroup); linear.AddView(radioLinearLayoutVertical); encryptDocument.Checked = true; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button generateButton = new Button(con); generateButton.Text = "Generate"; generateButton.Click += OnButtonClicked; linear.AddView(generateButton); return linear; } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); WordDocument document = null; if (encryptDocument.Checked == true) { //create worddocument instances document = new WordDocument(); document.EnsureMinimal(); // Getting last section of the document. IWSection section = document.LastSection; // Adding a paragraph to the section. IWParagraph paragraph = section.AddParagraph(); // Writing text IWTextRange text = paragraph.AppendText("This document was encrypted with password"); text.CharacterFormat.FontSize = 16f; text.CharacterFormat.FontName = "Bitstream Vera Serif"; // Encrypt the document by giving password document.EncryptDocument("syncfusion"); } else { // Open an existing template document with single section. document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Security Settings.docx"); // Open an existing template document. document.Open(inputStream, FormatType.Docx, "syncfusion"); inputStream.Dispose(); // Getting last section of the document. IWSection section = document.LastSection; // Adding a paragraph to the section. IWParagraph paragraph = section.AddParagraph(); // Writing text IWTextRange text = paragraph.AppendText("\nDemo For Document Decryption with Essential DocIO"); text.CharacterFormat.FontSize = 16f; text.CharacterFormat.FontName = "Bitstream Vera Serif"; text = paragraph.AppendText("\nThis document is Decrypted"); text.CharacterFormat.FontSize = 16f; text.CharacterFormat.FontName = "Bitstream Vera Serif"; } MemoryStream ms = new MemoryStream(); //Set file content type string contentType = null; string fileName = null; //Save the document as docx fileName = "Encrypt and Decrypt.docx"; contentType = "application/msword"; document.Save(ms, FormatType.Docx); document.Dispose(); if (ms != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save(fileName, contentType, ms, m_context); } } } } <file_sep>/Forms/RangeSlider/readme.md The `SfRangeSlider` control provides way to select the range of value within the specified minimum and maximum limits. The range can be selected by moving the Thumb control along a track. The following samples are available for range slider to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](RangeSlider/Samples)|It demonstrates the way to set start and end value of range, tick placement and label placement.| |[Orientation](RangeSlider/Samples)|In that sample, we have 3 range sliders in vertical orientation looks like equalizer and custom labels were used to plot the values.| <file_sep>/Forms/PullToRefresh/PullToRefresh.Android/MainActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "MainActivity.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh.Droid { using System; using Android.App; using Android.Content.PM; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; [Activity(Label = "SampleBrowser.SfPullToRefresh", MainLauncher = false, Theme = "@style/MainTheme", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] /// <summary> /// The MainActivity of the Application /// </summary> public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { /// <summary> /// Gets the MainActivity Type /// </summary> /// <param name="bundle">Bundle type of parameter named as bundle</param> protected override void OnCreate(Bundle bundle) { Xamarin.Forms.Platform.Android.FormsAppCompatActivity.TabLayoutResource = Resource.Layout.Tabbar; Xamarin.Forms.Platform.Android.FormsAppCompatActivity.ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); this.LoadApplication(new App()); } } }<file_sep>/Forms/ImageEditor/ImageEditor/Samples/Serialization/SerializationModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfImageEditor { public class SerializationViewModel : INotifyPropertyChanged { public ObservableCollection<SerializationModel> ModelList { get; set; } public SerializationViewModel() { Assembly assembly = typeof(ImageSerializeModel).GetTypeInfo().Assembly; ModelList = new ObservableCollection<SerializationModel> { #if COMMONSB new SerializationModel { Location = "SampleBrowser.Icons.Editor_CreateNew.png", Strm = null, SelectionImage = ImageSource.FromResource("SampleBrowser.Icons.NotSelected.png", assembly), ImageName = "CreateNew", HorizontalOption = LayoutOptions.Center, VerticalOption = LayoutOptions.Center, Visibility = "false", CreateNewvisibility = "true", Height = 50, BackGround = Color.FromHex("#065DC7"), SelectedImageVisibility = "false" }, new SerializationModel { Location = "SampleBrowser.Icons.EditorChart.jpg", Strm = null, SelectionImage = ImageSource.FromResource("SampleBrowser.Icons.NotSelected.png", assembly), Imagestream = "SampleBrowser.Icons.Chart.txt", ImageName = "Chart", HorizontalOption = LayoutOptions.FillAndExpand, VerticalOption = LayoutOptions.FillAndExpand, Visibility = "true", Height = 50, BackGround = Color.FromHex("#D3D3D3"), CreateNewvisibility = "false", SelectedImageVisibility = "false", SelectedItemThickness = new Thickness(0, 0, 0, 0) }, new SerializationModel { Location = "SampleBrowser.Icons.EditorVenn.jpg", Strm = null, SelectionImage = ImageSource.FromResource("SampleBrowser.Icons.NotSelected.png", assembly), Imagestream = "SampleBrowser.Icons.Venn.txt", ImageName = "Venn Diagram", HorizontalOption = LayoutOptions.FillAndExpand, VerticalOption = LayoutOptions.FillAndExpand, Visibility = "true", Height = 50, BackGround = Color.FromHex("#D3D3D3"), CreateNewvisibility = "false", SelectedImageVisibility = "false", SelectedItemThickness = new Thickness(0, 0, 0, 0) }, new SerializationModel { Location = "SampleBrowser.Icons.EditorFreeHand.jpg", Strm = null, SelectionImage = ImageSource.FromResource("SampleBrowser.Icons.NotSelected.png", assembly), Imagestream = "SampleBrowser.Icons.FreeHand.txt", ImageName = "Freehand", HorizontalOption = LayoutOptions.FillAndExpand, VerticalOption = LayoutOptions.FillAndExpand, Visibility = "true", Height = 50, BackGround = Color.FromHex("#D3D3D3"), CreateNewvisibility = "false", SelectedImageVisibility = "false", SelectedItemThickness = new Thickness(0, 0, 0, 0) }, #else new SerializationModel { Location = "SampleBrowser.SfImageEditor.Icons.Editor_CreateNew.png", Strm = null, SelectionImage = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.NotSelected.png", assembly), ImageName = "CreateNew", HorizontalOption = LayoutOptions.Center, VerticalOption = LayoutOptions.Center, Visibility = "false", CreateNewvisibility = "true", Height = 50, BackGround = Color.FromHex("#065DC7"), SelectedImageVisibility = "false" }, new SerializationModel { Location = "SampleBrowser.SfImageEditor.Icons.EditorChart.jpg", Strm = null, SelectionImage = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.NotSelected.png", assembly), Imagestream = "SampleBrowser.SfImageEditor.Icons.Chart.txt", ImageName = "Chart", HorizontalOption = LayoutOptions.FillAndExpand, VerticalOption = LayoutOptions.FillAndExpand, Visibility = "true", Height = 50, BackGround = Color.FromHex("#D3D3D3"), CreateNewvisibility = "false", SelectedImageVisibility = "false", SelectedItemThickness = new Thickness(0, 0, 0, 0) }, new SerializationModel { Location = "SampleBrowser.SfImageEditor.Icons.EditorVenn.jpg", Strm = null, SelectionImage = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.NotSelected.png", assembly), Imagestream = "SampleBrowser.SfImageEditor.Icons.Venn.txt", ImageName = "Venn Diagram", HorizontalOption = LayoutOptions.FillAndExpand, VerticalOption = LayoutOptions.FillAndExpand, Visibility = "true", Height = 50, BackGround = Color.FromHex("#D3D3D3"), CreateNewvisibility = "false", SelectedImageVisibility = "false", SelectedItemThickness = new Thickness(0, 0, 0, 0) }, new SerializationModel { Location = "SampleBrowser.SfImageEditor.Icons.EditorFreeHand.jpg", Strm = null, SelectionImage = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.NotSelected.png", assembly), Imagestream = "SampleBrowser.SfImageEditor.Icons.FreeHand.txt", ImageName = "Freehand", HorizontalOption = LayoutOptions.FillAndExpand, VerticalOption = LayoutOptions.FillAndExpand, Visibility = "true", Height = 50, BackGround = Color.FromHex("#D3D3D3"), CreateNewvisibility = "false", SelectedImageVisibility = "false", SelectedItemThickness = new Thickness(0, 0, 0, 0) }, #endif }; } public event PropertyChangedEventHandler PropertyChanged; void RaisePropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public class SerializationModel : INotifyPropertyChanged { private ImageSource name; public ImageSource Name { get { return name; } set { name = value; RaisePropertyChanged("Name"); } } public Stream iOSStream; private string _imagestream; public string Imagestream { get { return _imagestream; } set { _imagestream = value; RaisePropertyChanged("Imagestream"); } } private LayoutOptions _horizontalOption; public LayoutOptions HorizontalOption { get { return _horizontalOption; } set { _horizontalOption = value; RaisePropertyChanged("HorizontalOption"); } } private LayoutOptions _verticalOption; public LayoutOptions VerticalOption { get { return _verticalOption; } set { _verticalOption = value; RaisePropertyChanged("VerticalOption"); } } private string _visibility; public string Visibility { get { return _visibility; } set { _visibility = value; RaisePropertyChanged("Visibility"); } } private string _createNewvisibility; public string CreateNewvisibility { get { return _createNewvisibility; } set { _createNewvisibility = value; RaisePropertyChanged("CreateNewvisibility"); } } private Color _backGround; public Color BackGround { get { return _backGround; } set { _backGround = value; RaisePropertyChanged("BackGround"); } } private Stream _stream=null; public Stream Strm { get { return _stream; } set { _stream = value; RaisePropertyChanged("Strm"); } } private string _imageName; public string ImageName { get { return _imageName; } set { _imageName = value; RaisePropertyChanged("ImageName"); } } private int _height; public int Height { get { return _height; } set { _height = value; RaisePropertyChanged("Height"); } } private ImageSource _selectionImage; public ImageSource SelectionImage { get { return _selectionImage; } set { _selectionImage = value; RaisePropertyChanged("SelectionImage"); } } internal void SetLocation(string value) { DependencyService.Get<IFileToStream>().LoadSampleStream(value, this); } private string location = String.Empty; public string Location { get { return location; } set { location = value; RaisePropertyChanged("Location"); } } private string _selectedImageVisibility; public string SelectedImageVisibility { get { return _selectedImageVisibility; } set { _selectedImageVisibility = value; RaisePropertyChanged("SelectedImageVisibility"); } } private Thickness _selectedItemThickness; public Thickness SelectedItemThickness { get { return _selectedItemThickness; } set { _selectedItemThickness = value; RaisePropertyChanged("SelectedItemThickness"); } } public event PropertyChangedEventHandler PropertyChanged; internal void RaisePropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public class ImageEditorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var location = value.ToString(); if(location!=null && location.StartsWith("SampleBrowser")) { Assembly assembly = typeof(ImageSerializeModel).GetTypeInfo().Assembly; return ImageSource.FromResource(location, assembly); } if (!string.IsNullOrEmpty(location) && Device.RuntimePlatform == Device.iOS) return ImageSource.FromStream(() => DependencyService.Get<IFileToStream>().LoadSampleStream(location)); if (!string.IsNullOrEmpty(location) && Device.RuntimePlatform == Device.UWP) return ImageSource.FromStream(() => DependencyService.Get<ICustomViewDependencyService>().GetImageSource(location).Result); return value != null ? ImageSource.FromFile(location) : null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/CustomSortComparer.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CustomSortComparer.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Syncfusion.Data; using Xamarin.Forms; /// <summary> /// A class that compares two object /// </summary> public class CustomSortComparer : IComparer<object>, ISortDirection { /// <summary> /// Initializes a new instance of the CustomSortComparer class. /// </summary> public CustomSortComparer() { } /// <summary> /// Gets or sets the value of SortDirection /// </summary> public Syncfusion.Data.ListSortDirection SortDirection { get; set; } /// <summary> /// Used to compare the x and y value /// </summary> /// <param name="x">object type of comparer x value</param> /// <param name="y">object type of comparer y value</param> /// <returns>sort description</returns> public int Compare(object x, object y) { double namX; double namY; if (x.GetType() == typeof(SalesByDate)) { namX = ((SalesByDate)x).Total; namY = ((SalesByDate)y).Total; } else if (x.GetType() == typeof(Group)) { namX = this.ConverKeyToDouble((string)((Group)x).Key); namY = this.ConverKeyToDouble((string)((Group)y).Key); } else { namX = (double)x; namY = (double)y; } // Objects are compared and return the SortDirection if (namX > namY) { return this.SortDirection == Syncfusion.Data.ListSortDirection.Ascending ? 1 : -1; } else { return this.SortDirection == Syncfusion.Data.ListSortDirection.Ascending ? -1 : 1; } } /// <summary> /// Gets the value for a given key /// </summary> /// <param name="key">string type of key value</param> /// <returns>returns the key value</returns> private double ConverKeyToDouble(string key) { if (key.Equals("<1 K")) { return 0; } else if (key.Equals(">1 K and <5 K")) { return 1; } else if (key.Equals(">5 K and <10 K")) { return 2; } else if (key.Equals(">10 K and <50 K")) { return 3; } else if (key.Equals(">50 K")) { return 5; } else { return 0; } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Axis/Numerical.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class Numerical : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "England vs West Indies"; chart.Title.TextSize = 15; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.ToggleSeriesVisibility = true; CategoryAxis categoryAxis = new CategoryAxis(); categoryAxis.Title.Text = "Death Overs"; categoryAxis.LabelPlacement = LabelPlacement.BetweenTicks; categoryAxis.PlotOffset = 2; categoryAxis.AxisLineOffset = 2; categoryAxis.Interval = 1; chart.PrimaryAxis = categoryAxis; var numericalAxis = new NumericalAxis(); numericalAxis.Minimum = 0; numericalAxis.Maximum = 25; numericalAxis.Interval = 5; numericalAxis.MajorTickStyle.TickSize = 0; numericalAxis.LineStyle.StrokeWidth = 0; chart.SecondaryAxis = numericalAxis; ColumnSeries columnSeries = new ColumnSeries(); columnSeries.EnableAnimation = true; columnSeries.ItemsSource = MainPage.GetNumericalData(); columnSeries.XBindingPath = "XValue"; columnSeries.YBindingPath = "YValue"; columnSeries.LegendIcon = ChartLegendIcon.SeriesType; columnSeries.Label = "England"; columnSeries.DataMarker.ShowLabel = true; columnSeries.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Inner; columnSeries.TooltipEnabled = true; chart.Series.Add(columnSeries); ColumnSeries columnSeries1 = new ColumnSeries(); columnSeries1.EnableAnimation = true; columnSeries1.ItemsSource = MainPage.GetNumericalData1(); columnSeries1.XBindingPath = "XValue"; columnSeries1.YBindingPath = "YValue"; columnSeries1.LegendIcon = ChartLegendIcon.SeriesType; columnSeries1.Label = "West Indies"; columnSeries1.DataMarker.ShowLabel = true; columnSeries1.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Inner; columnSeries1.TooltipEnabled = true; chart.Series.Add(columnSeries1); return chart; } } }<file_sep>/Forms/Chart/Chart/Samples/AutoScrolling/AutoScrollingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using Xamarin.Forms; namespace SampleBrowser.SfChart { public class AutoScrollingViewModel { DateTime time = new DateTime(2017, 01, 01); Random random = new Random(); private int count; internal bool IsDisappear { get; set; } public ObservableCollection<ChartDataModel> data { get; set; } public AutoScrollingViewModel() { data = new ObservableCollection<ChartDataModel>(); IsDisappear = false; } public void LoadData() { for (var i = 0; i < 2; i++) { data.Add(new ChartDataModel(time, random.Next(0, 100))); time = time.AddMilliseconds(500); count++; } count = data.Count; } public bool UpdateData() { if (IsDisappear) return false; data.Add(new ChartDataModel(time, random.Next(0, 100))); time = time.AddMilliseconds(500); count++; return true; } } } <file_sep>/iOS/SampleBrowser/Samples/Maps/TicketBooking.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using UIKit; using Syncfusion.SfMaps.iOS; using Syncfusion.SfBusyIndicator.iOS; using Foundation; using System.Collections.ObjectModel; namespace SampleBrowser { public class TicketBooking : SampleView { UIView view; UILabel label; UIView container; UIView subcontainer; UIView LayoutA; UIView LayoutB; UIView LayoutC; UIView LayoutD; UIButton button1; UIButton button2; UIButton button3; public UIButton button4; UILabel label1; UILabel label2; UILabel label3; UILabel label4; public UILabel label5; public UITextView text1; UIScrollView scrollView; public static SFShapeFileLayer layer; public SFMap maps; public override void LayoutSubviews() { view.Frame = new CGRect(0, 0.0f, Frame.Size.Width, Frame.Size.Height); label.Frame = new CGRect(0f, 0f, Frame.Size.Width, 50); container.Frame = new CGRect(20f, 50f, (Frame.Size.Width / 2)-20, (Frame.Size.Height- (label.Frame.Size.Height+ 30) )); maps.Frame = new CGRect(20f, 20f, (Frame.Size.Width / 2), (Frame.Size.Height - ((label.Frame.Size.Height+70) ))); subcontainer.Frame = new CGRect(Frame.Size.Width / 2, 50f, Frame.Size.Width / 2, Frame.Size.Height - 50f); LayoutA.Frame = new CGRect(0f, (Frame.Size.Height / 4) - 110f, subcontainer.Frame.Width-10f ,20); LayoutB.Frame = new CGRect(0f, (Frame.Size.Height / 4) - 80f, subcontainer.Frame.Width - 10f, 20); LayoutC.Frame = new CGRect(0f, (Frame.Size.Height / 4) - 50f,subcontainer.Frame.Width - 10f, 20); LayoutD.Frame=new CGRect(10f, (Frame.Size.Height/4)-15f, subcontainer.Frame.Width - 10f, 2); button1.Frame = new CGRect(LayoutA.Frame.Width/3, 0f, 20, 20); button2.Frame = new CGRect(LayoutA.Frame.Width / 3, 0f, 20, 20); button3.Frame = new CGRect(LayoutA.Frame.Width / 3, 0f, 20, 20); button4.Frame = new CGRect(20f, (Frame.Size.Height-120), (Frame.Size.Width / 2) - 30f, 30f); label1.Frame= new CGRect((LayoutA.Frame.Width / 3)+(button1.Frame.Width+5f), 0f,Frame.Size.Width-20f , 20f); label2.Frame = new CGRect((LayoutA.Frame.Width / 3) + (button1.Frame.Width + 5f), 0f, Frame.Size.Width - 20f, 20f); label3.Frame = new CGRect((LayoutA.Frame.Width / 3) + (button1.Frame.Width + 5f), 0f, Frame.Size.Width - 20f, 20f); label4.Frame = new CGRect(0f, (Frame.Size.Height/4),subcontainer.Frame.Width , 20f); label5.Frame = new CGRect((subcontainer.Frame.Width/2)-5f, (Frame.Size.Height / 3) , subcontainer.Frame.Width - 10f , 20f); text1.Frame = new CGRect(20f, (Frame.Size.Height / 3) + 30f, subcontainer.Frame.Width - 50f, 100f); scrollView.Frame = new CGRect(20f, (Frame.Size.Height / 3)+30f,subcontainer.Frame.Width - 50f, 30f); SetNeedsDisplay(); } public TicketBooking() { maps = new SFMap(); view = new UIView(); container = new UIView(); subcontainer = new UIView(); LayoutA = new UIView(); LayoutB = new UIView(); LayoutC = new UIView(); LayoutD = new UIView(); button1 = new UIButton(); button2 = new UIButton(); button3 = new UIButton(); button4 = new UIButton(); label1 = new UILabel(); label2 = new UILabel(); label3 = new UILabel(); label4 = new UILabel(); label5 = new UILabel(); text1 = new UITextView(); scrollView = new UIScrollView(); view.BackgroundColor = UIColor.White; NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(0.3), delegate { container.AddSubview(maps); }); view.Frame = new CGRect(0, 0, 300, 400); label = new UILabel(); label.TextAlignment = UITextAlignment.Center; label.Text = "Ticketing System"; label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(0, 0, 300, 40); label.TextColor = UIColor.Black; view.AddSubview(label); //container.BackgroundColor = UIColor.Red; container.Layer.CornerRadius = 5; container.Layer.BorderWidth = 3; container.Layer.BorderColor = UIColor.Gray.CGColor; layer = new SFShapeFileLayer(); layer.ShapeSettings.SelectedShapeColor = UIColor.FromRGB(98, 170, 95); layer.Uri = (NSString)NSBundle.MainBundle.PathForResource("Custom", "shp"); layer.EnableSelection = true; layer.ShapeSettings.SelectedShapeStrokeThickness = 0; layer.DataSource = GetDataSource(); SetColorMapping(layer.ShapeSettings); layer.GeometryType = SFGeometryType.SFGeometryTypePoints; layer.SelectionMode = SFSelectionMode.SFSelectionModeMultiple; layer.ShapeIDPath = (NSString)"SeatNumber"; layer.ShapeSettings.ColorValuePath = (NSString)"SeatNumber"; layer.ShapeSettings.ValuePath = (NSString)"SeatNumber"; layer.ShapeSettings.Fill = UIColor.Gray; layer.ShapeIDTableField = (NSString)"seatno"; layer.ShapeSelectionChanged += BookingSelectionChanged; maps.Layers.Add(layer); container.Add(maps); view.Add(container); subcontainer.BackgroundColor = UIColor.White; subcontainer.Layer.CornerRadius = 5; //LayoutA.BackgroundColor = UIColor.Green; LayoutA.Layer.CornerRadius = 5; button1.BackgroundColor = UIColor.Gray; button1.Layer.CornerRadius = 5; LayoutA.Add(button1); label1.Text = "Available"; label1.Font = UIFont.SystemFontOfSize(12); label1.TextColor = UIColor.Black; LayoutA.Add(label1); subcontainer.Add(LayoutA); //LayoutB.BackgroundColor = UIColor.Purple; LayoutB.Layer.CornerRadius = 5; button2.BackgroundColor = UIColor.FromRGB(98, 170, 95); button2.Layer.CornerRadius = 5; LayoutB.Add(button2); label2.Text = "Selected"; label2.TextColor = UIColor.Black; label2.Font = UIFont.SystemFontOfSize(12); LayoutB.Add(label2); subcontainer.Add(LayoutB); LayoutC.Layer.CornerRadius = 5; button3.BackgroundColor = UIColor.FromRGB(255, 165, 0); button3.Layer.CornerRadius = 5; LayoutC.Add(button3); label3.Text = "Booked"; label3.TextColor = UIColor.Black; label3.Font = UIFont.SystemFontOfSize(12); LayoutC.Add(label3); subcontainer.Add(LayoutC); LayoutD.BackgroundColor = UIColor.Gray; LayoutD.Layer.CornerRadius = 5; subcontainer.Add(LayoutD); label4.Text = "Seats Selected"; label4.TextAlignment = UITextAlignment.Center; label4.TextColor = UIColor.Blue; label4.Font = UIFont.SystemFontOfSize(12); subcontainer.Add(label4); label5.Text = ""; label5.TextAlignment = UITextAlignment.Left; label5.TextColor = UIColor.Black; label5.Font = UIFont.SystemFontOfSize(20); subcontainer.Add(label5); text1.Text = ""; //text1.BackgroundColor = UIColor.Blue; text1.TextAlignment = UITextAlignment.Center; text1.TextColor = UIColor.Black; text1.Font = UIFont.SystemFontOfSize(12); subcontainer.Add(text1); button4.BackgroundColor = UIColor.Clear; button4.Enabled = false; button4.Alpha = (float)0.5; button4.Layer.CornerRadius = 5; button4.Layer.BorderColor = UIColor.Gray.CGColor; button4.Layer.BorderWidth = 2; button4.SetTitle("Clear Selection", UIControlState.Normal); button4.SetTitleColor(UIColor.Red, UIControlState.Normal); button4.TouchDown += (sender, e) => { layer.SelectedItems.Clear(); button4.Enabled = false; button4.Alpha = (float)0.5; label5.Text=" " ; text1.Text = " "; }; subcontainer.Add(button4); view.Add(subcontainer); AddSubview(view); } public void selection(string selectedItems) { text1.Text = selectedItems; } NSMutableArray GetDataSource() { NSMutableArray array = new NSMutableArray(); for (int i = 1; i <= 21; i++) { array.Add(getDictionary("" + i)); } return array; } NSDictionary getDictionary(string seatno) { NSString name1 = (NSString)seatno; object[] objects = new object[1]; object[] keys = new object[1]; keys.SetValue("SeatNumber", 0); objects.SetValue(name1, 0); return NSDictionary.FromObjectsAndKeys(objects, keys); } void SetColorMapping(SFShapeSetting setting) { ObservableCollection<SFMapColorMapping> colorMappings = new ObservableCollection<SFMapColorMapping>(); SFEqualColorMapping colorMapping1 = new SFEqualColorMapping(); colorMapping1.Value = (NSString)"1"; colorMapping1.Color = UIColor.FromRGB(255, 165, 0); colorMappings.Add(colorMapping1); SFEqualColorMapping colorMapping2 = new SFEqualColorMapping(); colorMapping2.Value = (NSString)"2"; colorMapping2.Color = UIColor.FromRGB(255, 165, 0); colorMappings.Add(colorMapping2); SFEqualColorMapping colorMapping3 = new SFEqualColorMapping(); colorMapping3.Value = (NSString)"8"; colorMapping3.Color = UIColor.FromRGB(255, 165, 0); colorMappings.Add(colorMapping3); SFEqualColorMapping colorMapping4 = new SFEqualColorMapping(); colorMapping4.Value = (NSString)"9"; colorMapping4.Color = UIColor.FromRGB(255, 165, 0); colorMappings.Add(colorMapping4); setting.ColorMappings = colorMappings; } void BookingSelectionChanged(object sender, ShapeSelectedEventArgs args) { label5.Text = layer.SelectedItems.Count.ToString(); var selected = layer.SelectedItems; string text = ""; if (layer.SelectedItems.Count == 0) { button4.Enabled = false; button4.Alpha = (float)0.5; } for (int i = 0; i < layer.SelectedItems.Count; i++) { NSObject item = (NSObject)layer.SelectedItems[i]; NSDictionary dic1 = (NSDictionary)item; if ((NSString)(dic1["SeatNumber"]) == "1" || (NSString)(dic1["SeatNumber"]) == "2" || (NSString)(dic1["SeatNumber"]) == "8" || (NSString)(dic1["SeatNumber"]) == "9") { selected.RemoveAt(i); layer.SelectedItems = selected; label5.Text = layer.SelectedItems.Count.ToString(); if (selected.Count == 0) { button4.Enabled = false; button4.Alpha = (float)0.5; } else { if (text.EndsWith(",")) { text = text.Remove(text.Length - 1); } } } else { if (i == layer.SelectedItems.Count - 1) { text += "S" + ((NSString)(dic1["SeatNumber"])); } else { text += "S" + ((NSString)(dic1["SeatNumber"]) + ","); } button4.Enabled = true; button4.Alpha = (float)1; } } selection(text); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Sorting/Sorting.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Sorting.xaml.cs" company="Syncfusion.com"> // Syncfusion.com. All rights reserved. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Globalization; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A sampleView that contains the Sorting sample. /// </summary> public partial class Sorting : SampleView { #region Constructor /// <summary> /// Initializes a new instance of the Sorting class. /// </summary> public Sorting() { this.InitializeComponent(); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Maps/readme.md The maps control is a data visualization component that provides a graphical representation of geographical data. It has highly interactive and customizable features such as zooming, panning, selecting, legends, markers, bubbles, and color mapping. The following samples are available for maps to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Bubble Visualization](BubbleVisualization.cs)| This sample shows how to add bubbles with data labels in maps. | | [Color Mappings](ColorMappings.cs)| This sample shows how to add color mapping based underlying shape values, and highlight the map regions. | | [Data Markers](DataMarkers.cs)| Data markers are used to denote a place with symbols or display messages at a specific latitude and longitude on a map. This sample shows most populous countries’ location by placing markers on the world map. | | [Ticket Booking](TicketBooking.cs)|This sample shows how to add a bus ticket booking system using custom shapes. Selection support has used to book available seats. | | [Open Street Map](OSM.cs)| OpenStreetMap is used to show maps with imagery tiles without shapefiles. This sample explains how to add OSM in maps. | <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Grouping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using CoreGraphics; using System.Globalization; namespace SampleBrowser { public class Grouping:SampleView { #region Fields SfDataGrid SfGrid; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public Grouping () { this.SfGrid = new SfDataGrid (); this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.ItemsSource = new GroupingViewModel ().ProductDetails; this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.AllowGroupExpandCollapse = true; this.SfGrid.AllowResizingColumn = true; // Multi-Grouping this.SfGrid.GroupingMode = GroupingMode.Multiple; this.SfGrid.GroupColumnDescriptions.Add(new GroupColumnDescription() { ColumnName = "Product" }); this.SfGrid.GroupColumnDescriptions.Add(new GroupColumnDescription() { ColumnName = "ProductModel" }); // GroupSummary codes GridGroupSummaryRow groupSummaryRow = new GridGroupSummaryRow(); groupSummaryRow.Title = "Total items:{Total} items"; groupSummaryRow.ShowSummaryInRow = true; GridSummaryColumn groupSummaryColumn = new GridSummaryColumn(); groupSummaryColumn.Name = "Total"; groupSummaryColumn.MappingName = "Product"; groupSummaryColumn.Format = "{Count}"; groupSummaryColumn.SummaryType = Syncfusion.Data.SummaryType.CountAggregate; groupSummaryRow.SummaryColumns.Add(groupSummaryColumn); SfGrid.GroupSummaryRows.Add(groupSummaryRow); //TableSummary codes GridTableSummaryRow summaryRow = new GridTableSummaryRow(); summaryRow.Title = "Total items:{Total} items"; summaryRow.ShowSummaryInRow = true; summaryRow.Position = Position.Bottom; GridSummaryColumn summaryColumn = new GridSummaryColumn(); summaryColumn.Name = "Total"; summaryColumn.MappingName = "ProductID"; summaryColumn.Format = "{Count}"; summaryColumn.SummaryType = Syncfusion.Data.SummaryType.CountAggregate; summaryRow.SummaryColumns.Add(summaryColumn); this.SfGrid.TableSummaryRows.Add(summaryRow); this.AddSubview (SfGrid); } void GridAutoGenerateColumns (object sender, AutoGeneratingColumnEventArgs e) { if (UserInterfaceIdiomIsPhone) e.Column.MaximumWidth = 150; else e.Column.MaximumWidth = 300; if (e.Column.MappingName == "ProductID") { e.Column.HeaderText = "Product ID"; } else if (e.Column.MappingName == "UserRating") { e.Column.HeaderText = "User Rating"; } else if (e.Column.MappingName == "ProductModel") { e.Column.HeaderText = "Product Model"; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Price") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); } else if (e.Column.MappingName == "ShippingDays") { e.Column.HeaderText = "Shipping Days"; } else if (e.Column.MappingName == "ProductType") { e.Column.HeaderText = "Product Type"; e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "Availability") { e.Column.TextMargin = new Thickness(30, 6, 5, 6); } } public override void LayoutSubviews () { if(Utility.IsIpad) { if ((UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.LandscapeLeft) || (UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.LandscapeRight)) this.SfGrid.ColumnSizer = ColumnSizer.Star; else this.SfGrid.ColumnSizer = ColumnSizer.None; } this.SfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews (); } protected override void Dispose(bool disposing) { SfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; SfGrid.Dispose(); base.Dispose(disposing); SfGrid = null; } } } <file_sep>/Android/SampleBrowser/Samples/TreeView/ViewModel/CountriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public class CountriesViewModel { public ObservableCollection<Countries> CountriesInfo { get; set; } public ObservableCollection<object> SelectedCountries { get; set; } public CountriesViewModel() { CountriesInfo = new ObservableCollection<Countries>(); SelectedCountries = new ObservableCollection<object>(); AddStatesAustralia(); AddStatesBrazil(); AddStatesChina(); AddStatesUSA(); AddStatesIndia(); } private void AddStatesAustralia() { var australia = new Countries() { Name = "Australia" }; var nsw = new Countries() { Name = "New South Wales" }; var sydney = new Countries() { Name = "Sydney" }; var canbera = new Countries() { Name = "Canberra" }; var maitland = new Countries() { Name = "Newcastle–Maitland" }; var victoria = new Countries() { Name = "Victoria" }; var melborne = new Countries() { Name = "Melbourne" }; var queensland = new Countries() { Name = "Queensland" }; var brisbane = new Countries() { Name = "Brisbane" }; var westAussie = new Countries() { Name = "West Australia" }; var perth = new Countries() { Name = "Perth" }; var southAussie = new Countries() { Name = "South Australia" }; var aldehide = new Countries() { Name = "Adelaide" }; australia.States = new ObservableCollection<Countries>(); australia.States.Add(nsw); australia.States.Add(victoria); australia.States.Add(queensland); australia.States.Add(westAussie); australia.States.Add(southAussie); nsw.States = new ObservableCollection<Countries>(); nsw.States.Add(sydney); nsw.States.Add(canbera); nsw.States.Add(maitland); victoria.States = new ObservableCollection<Countries>(); victoria.States.Add(melborne); queensland.States = new ObservableCollection<Countries>(); queensland.States.Add(brisbane); westAussie.States = new ObservableCollection<Countries>(); westAussie.States.Add(perth); southAussie.States = new ObservableCollection<Countries>(); southAussie.States.Add(aldehide); CountriesInfo.Add(australia); SelectedCountries.Add(nsw); SelectedCountries.Add(victoria); } private void AddStatesBrazil() { var brazil = new Countries() { Name = "Brazil" }; var saoPaulostate = new Countries() { Name = "São Paulo" }; var saoPaulo = new Countries() { Name = "São Paulo" }; var campinas = new Countries() { Name = "Campinas" }; var sorocaba = new Countries() { Name = "Sorocaba" }; var riodeJanerio = new Countries() { Name = "Rio de Janeiro" }; var gerais = new Countries() { Name = "Minas Gerais" }; var horizonte = new Countries() { Name = "Belo Horizonte" }; var brassilia = new Countries() { Name = "Distrito Federal e Entorno (Brasilia)" }; var ceara = new Countries() { Name = "Ceará" }; var fortaleza = new Countries() { Name = "Fortaleza" }; var caucaia = new Countries() { Name = "Caucaia" }; var parana = new Countries() { Name = "Paraná" }; var curitiba = new Countries() { Name = "Curitiba" }; brazil.States = new ObservableCollection<Countries>(); brazil.States.Add(saoPaulostate); brazil.States.Add(riodeJanerio); brazil.States.Add(gerais); brazil.States.Add(ceara); brazil.States.Add(parana); saoPaulostate.States = new ObservableCollection<Countries>(); saoPaulostate.States.Add(saoPaulo); saoPaulostate.States.Add(campinas); saoPaulostate.States.Add(sorocaba); gerais.States = new ObservableCollection<Countries>(); gerais.States.Add(horizonte); gerais.States.Add(brassilia); ceara.States = new ObservableCollection<Countries>(); ceara.States.Add(fortaleza); ceara.States.Add(caucaia); parana.States = new ObservableCollection<Countries>(); parana.States.Add(curitiba); CountriesInfo.Add(brazil); } private void AddStatesChina() { var china = new Countries() { Name = "China" }; var guangdong = new Countries() { Name = "Guangdong" }; var guanghou = new Countries() { Name = "Guanghou" }; var jingjinji = new Countries() { Name = "Jingjinji" }; var beijing = new Countries() { Name = "Beijing" }; var tianjin = new Countries() { Name = "Tianjin" }; var yangtze = new Countries() { Name = "Yangtze River Delta" }; var shanghai = new Countries() { Name = "Shanghai" }; var chengyu = new Countries() { Name = "Chengyu" }; var chongqing = new Countries() { Name = "Chongqing" }; var zhejiang = new Countries() { Name = "Zhejiang Province" }; var hangzhou = new Countries() { Name = "Hangzhou" }; china.States = new ObservableCollection<Countries>(); china.States.Add(guangdong); china.States.Add(jingjinji); china.States.Add(yangtze); china.States.Add(chengyu); china.States.Add(zhejiang); guangdong.States = new ObservableCollection<Countries>(); guangdong.States.Add(guanghou); jingjinji.States = new ObservableCollection<Countries>(); jingjinji.States.Add(beijing); jingjinji.States.Add(tianjin); yangtze.States = new ObservableCollection<Countries>(); yangtze.States.Add(shanghai); chengyu.States = new ObservableCollection<Countries>(); chengyu.States.Add(chongqing); zhejiang.States = new ObservableCollection<Countries>(); zhejiang.States.Add(hangzhou); CountriesInfo.Add(china); } private void AddStatesUSA() { var usa = new Countries() { Name = "United States of America" }; var newYork = new Countries() { Name = "New York" }; var california = new Countries() { Name = "California" }; var losAngeles = new Countries() { Name = "Los Angeles" }; var sanJose = new Countries() { Name = "San Jose" }; var sanFrancisco = new Countries() { Name = "San Francisco" }; var illinois = new Countries() { Name = "Illinois" }; var chicago = new Countries() { Name = "Chicago" }; var texas = new Countries() { Name = "Texas" }; var houston = new Countries() { Name = "Houston" }; var sanAntonio = new Countries() { Name = "San Antonio" }; var dallas = new Countries() { Name = "Dallas" }; var pennsylvania = new Countries() { Name = "Pennsylvania" }; var philadelphia = new Countries() { Name = "Philadelphia" }; usa.States = new ObservableCollection<Countries>(); usa.States.Add(newYork); usa.States.Add(california); usa.States.Add(illinois); usa.States.Add(texas); usa.States.Add(pennsylvania); california.States = new ObservableCollection<Countries>(); california.States.Add(losAngeles); california.States.Add(sanJose); california.States.Add(sanFrancisco); illinois.States = new ObservableCollection<Countries>(); illinois.States.Add(chicago); texas.States = new ObservableCollection<Countries>(); texas.States.Add(houston); texas.States.Add(sanAntonio); texas.States.Add(dallas); pennsylvania.States = new ObservableCollection<Countries>(); pennsylvania.States.Add(philadelphia); CountriesInfo.Add(usa); } private void AddStatesIndia() { var india = new Countries() { Name = "India" }; var delhi = new Countries() { Name = "Delhi" }; var newDelhi = new Countries() { Name = "New Delhi" }; var maharastra = new Countries() { Name = "Maharashtra" }; var mumbai = new Countries() { Name = "Mumbai" }; var pune = new Countries() { Name = "Pune" }; var westBengal = new Countries() { Name = "West Bengal" }; var kolkatta = new Countries() { Name = "Kolkatta" }; var karnataka = new Countries() { Name = "Karnataka" }; var bangalore = new Countries() { Name = "Bangalore" }; var tamilNadu = new Countries() { Name = "Tamil Nadu" }; var chennai = new Countries() { Name = "Chennai" }; india.States = new ObservableCollection<Countries>(); india.States.Add(delhi); india.States.Add(maharastra); india.States.Add(westBengal); india.States.Add(karnataka); india.States.Add(tamilNadu); delhi.States = new ObservableCollection<Countries>(); delhi.States.Add(newDelhi); maharastra.States = new ObservableCollection<Countries>(); maharastra.States.Add(mumbai); maharastra.States.Add(pune); westBengal.States = new ObservableCollection<Countries>(); westBengal.States.Add(kolkatta); karnataka.States = new ObservableCollection<Countries>(); karnataka.States.Add(bangalore); tamilNadu.States = new ObservableCollection<Countries>(); tamilNadu.States.Add(chennai); CountriesInfo.Add(india); } } }<file_sep>/Forms/Chat/README.md This repository contains the examples for SfChat control.<file_sep>/iOS/SampleBrowser/Samples/DataGrid/Formatting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using System.Globalization; using CoreGraphics; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class Formatting : SampleView { #region Fields SfDataGrid SfGrid; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public Formatting() { SfGrid = new SfDataGrid(); GridImageColumn customerImageColumn = new GridImageColumn(); customerImageColumn.MappingName = "CustomerImage"; customerImageColumn.HeaderText = "Image"; GridSwitchColumn isOpenColumn = new GridSwitchColumn(); isOpenColumn.MappingName = "IsOpen"; isOpenColumn.HeaderText = "Is Open"; isOpenColumn.AllowEditing = true; isOpenColumn.TextAlignment = UITextAlignment.Left; isOpenColumn.TextMargin = new Thickness(30, 16, 5, 6); //GridTextColumn balanceScaleColumn = new GridTextColumn (); //balanceScaleColumn.UserCellType = typeof(LinearGuageCell); //balanceScaleColumn.MappingName = "BalanceScale"; //balanceScaleColumn.HeaderText = "Balance Scale"; //GridTextColumn chartcell = new GridTextColumn (); //chartcell.UserCellType = typeof(LineChartCell); //chartcell.MappingName = "Transactions"; //chartcell.HeaderText = "Transactions"; GridTextColumn customerIdColumn = new GridTextColumn(); customerIdColumn.MappingName = "CustomerID"; customerIdColumn.HeaderText = "Customer ID"; customerIdColumn.TextAlignment = UITextAlignment.Center; GridTextColumn currentColumn = new GridTextColumn(); currentColumn.MappingName = "Current"; currentColumn.Format = "C"; currentColumn.CultureInfo = new CultureInfo("en-US"); currentColumn.TextAlignment = UITextAlignment.Center; GridTextColumn customerNameColumn = new GridTextColumn(); customerNameColumn.MappingName = "CustomerName"; customerNameColumn.HeaderText = "Customer Name"; customerNameColumn.TextMargin = 10; customerNameColumn.TextAlignment = UITextAlignment.Left; GridTextColumn savingsColumn = new GridTextColumn(); savingsColumn.MappingName = "Savings"; savingsColumn.Format = "C"; savingsColumn.CultureInfo = new CultureInfo("en-US"); savingsColumn.TextAlignment = UITextAlignment.Center; SfGrid.Columns.Add(customerImageColumn); //SfGrid.Columns.Add (chartcell); SfGrid.Columns.Add(customerIdColumn); SfGrid.Columns.Add(currentColumn); SfGrid.Columns.Add(customerNameColumn); //SfGrid.Columns.Add (balanceScaleColumn); SfGrid.Columns.Add(isOpenColumn); SfGrid.Columns.Add(savingsColumn); SfGrid.AutoGenerateColumns = false; this.SfGrid.SelectionMode = SelectionMode.Single; SfGrid.ItemsSource = new FormattingViewModel().BankInfo; SfGrid.GridStyle.AlternatingRowColor = UIColor.FromRGB(219, 219, 219); SfGrid.SelectionMode = SelectionMode.Single; SfGrid.HeaderRowHeight = 45; SfGrid.RowHeight = 65; this.AddSubview(SfGrid); } public override void LayoutSubviews() { if (Utility.IsIPad) { this.SfGrid.ColumnSizer = ColumnSizer.LastColumnFill; } this.SfGrid.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { if (disposing) { if (SfGrid != null) { SfGrid.Dispose(); SfGrid = null; } } base.Dispose(disposing); } } } <file_sep>/Forms/ImageEditor/ImageEditor.Android/FileStore.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; namespace SampleBrowser.SfImageEditor.Droid { public class FileStore: IFileStore { [Obsolete] public string GetFilePath() { return Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "image.png"); } } }<file_sep>/Forms/Rotator/readme.md The `SfRotator` is a data control used to display image data and navigate through them. The images can be selected either by Thumbnail or Dots support. The following sample is available for rotator control to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](Rotator/Samples/Rotator)| It shows the way of populating items, customizing the appearance of navigation bar items and the direction of rotation.| <file_sep>/iOS/SampleBrowser/Resources/Samples/Maps/OSM.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfBusyIndicator.iOS; using System; using System.Net; using System.Threading.Tasks; using Syncfusion.SfMaps.iOS; using Foundation; using CoreGraphics; using UIKit; namespace SampleBrowser { public class OSM : SampleView { bool TapGesture_ShouldReceiveTouch(UIGestureRecognizer recognizer, UITouch touch) { if (touch.TapCount == 1) { UIApplication.SharedApplication.OpenUrl(new NSUrl("https://www.openstreetmap.org/copyright")); } return true; } internal SFBusyIndicator busyindicator; UIView view; UIView mainGrid; UIView childGrid; double previousWidth; double previousHeight; CGSize label1Size; CGSize label2Size; UILabel label1; UILabel label2; SFMap maps; UILabel label; public override void LayoutSubviews() { view.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); if (childGrid != null) childGrid.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); if (mainGrid != null) mainGrid.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); if (maps != null) maps.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); if (label1 != null && label2 != null) { label1.Frame = new CGRect(Frame.Size.Width - (label1Size.Width + label2Size.Width) - 4, Frame.Size.Height - label2Size.Height - 4, label1Size.Width + 4, label1Size.Height + 4); label2.Frame = new CGRect(Frame.Size.Width - label2Size.Width - 2, Frame.Size.Height - label2Size.Height - 4, label2Size.Width + 4, label2Size.Height + 4); } if (childGrid != null && childGrid.Subviews.Length > 0 && previousWidth == view.Frame.Size.Width && previousHeight == view.Frame.Size.Height) return; double row =0; double column =0; if (view.Frame.Size.Height > 0) { row = view.Frame.Size.Height / 512; if (Math.Ceiling(row)<= 0) row = 1; else row = Math.Ceiling(row); previousHeight = view.Frame.Size.Height; } if (view.Frame.Size.Width > 0) { column = view.Frame.Size.Width / 512; if (Math.Ceiling(column) <= 0) column = 1; else column = Math.Ceiling(column); previousWidth = view.Frame.Size.Width; } for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { UIImageView image = new UIImageView(); image.Image = UIImage.FromBundle("grid.png"); var xPos = i * 512; var yPos = j * 512; image.Frame = new CGRect(xPos, yPos, 512, 512); childGrid.AddSubview(image); SetNeedsDisplay(); } } childGrid.ClipsToBounds = true; SetNeedsDisplay(); } public OSM() { view = new UIView(); view.Frame = new CGRect(0, 0,300 , 400); AddMainView(); busyindicator = new SFBusyIndicator(); busyindicator.ViewBoxWidth = 75; busyindicator.ViewBoxHeight = 75; busyindicator.Foreground = UIColor.FromRGB(0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; IsConnectedToNetwork(); } async void IsConnectedToNetwork() { bool isConnected = await IsConnected(); if (isConnected) { view.AddSubview(busyindicator); NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(0.3), delegate { maps.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); view.AddSubview(mainGrid); }); } else { label = new UILabel(); label.TextAlignment = UITextAlignment.Center; label.Text = "Since this application requires network connection, " + "Please check your network connection"; label.Font = UIFont.SystemFontOfSize(14); label.Frame = new CGRect(0, 0, 300, 300); label.TextColor = UIColor.Black; label.LineBreakMode = UILineBreakMode.WordWrap; label.Lines = 2; view.AddSubview(label); } AddSubview(view); } async Task<bool> IsConnected() { var webRequest = (HttpWebRequest)WebRequest.Create("https://www.openstreetmap.org"); webRequest.Method = "HEAD"; try { using (var httpResponse = await webRequest.GetResponseAsync() as HttpWebResponse) { if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.OK) return true; return false; } } catch (WebException) { return false; } } void AddMainView() { if (childGrid == null) childGrid = new UIView(); mainGrid = new UIView(); mainGrid.BackgroundColor = UIColor.FromRGB(243, 239, 233); mainGrid.AddSubview(childGrid); maps = new SFMap(); ImageryLayer layer = new ImageryLayer(); maps.Layers.Add(layer); maps.Delegate = new OSMDelegate(this); mainGrid.AddSubview(maps); label1 = new UILabel(); label1.TextColor = UIColor.Black; label1.LayoutMargins = new UIEdgeInsets(2, 2, 3, 2); label1.Font = UIFont.FromName("Helvetica", 12); var text = new NSString("©"); var stringAtribute = new NSDictionary(UIStringAttributeKey.Font, label1.Font, UIStringAttributeKey.ForegroundColor, UIColor.Black); UIStringAttributes strAtr = new UIStringAttributes(stringAtribute); label1.Text = text; label1Size = text.GetSizeUsingAttributes(strAtr); label1.BackgroundColor = UIColor.White; mainGrid.AddSubview(label1); label2 = new UILabel(); label2.TextColor = UIColor.FromRGB(0, 212, 255); label2.LayoutMargins = new UIEdgeInsets(1, 2, 3, 2); label2.Font = UIFont.FromName("Helvetica", 12); var text1 = new NSString("OpenStreetMap contributors."); var stringAtribute1 = new NSDictionary(UIStringAttributeKey.Font, label2.Font, UIStringAttributeKey.ForegroundColor, UIColor.FromRGB(0, 212, 255)); UIStringAttributes strAtr1 = new UIStringAttributes(stringAtribute); label2.Text = text1; label2Size = text1.GetSizeUsingAttributes(strAtr1); label2.BackgroundColor = UIColor.White; label2.UserInteractionEnabled = true; UITapGestureRecognizer tapGesture = new UITapGestureRecognizer(); tapGesture.ShouldReceiveTouch += TapGesture_ShouldReceiveTouch; label2.AddGestureRecognizer(tapGesture); mainGrid.AddSubview(label2); } } public class OSMDelegate : SFMapsDelegate { OSM sample; public OSMDelegate(OSM osm) { sample = osm; } public override void DidLoad(SFMap map) { if (sample.busyindicator != null) { sample.busyindicator.RemoveFromSuperview(); sample.busyindicator = null; } } } } <file_sep>/Forms/EffectsView/EffectsView/Samples/EffectsGettingStarted/GettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.EffectsView; using System; using System.ComponentModel; using System.Globalization; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfEffectsView { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class GettingStarted : SampleView { public GettingStarted() { InitializeComponent(); } private void ApplyRotationEffectButtonClicked(object sender, EventArgs e) { if (RotationEffectsView.Angle == 0) { RotationEffectsView.Angle = 0; RotationEffectsView.ApplyEffects(effects: SfEffects.Rotation); ApplyRotationEffectButton.Text = "Rotate to 180°"; } else { RotationEffectsView.Angle = 180; RotationEffectsView.ApplyEffects(effects: SfEffects.Rotation); ApplyRotationEffectButton.Text = "Rotate to 0°"; } } private void RotationEffectsViewAnimationCompleted(object sender, EventArgs e) { if (RotationEffectsView.Angle == 180) { RotationEffectsView.Angle = 0; ApplyRotationEffectButton.Text = "Rotate to 0°"; } else { RotationEffectsView.Angle = 180; ApplyRotationEffectButton.Text = "Rotate to 180°"; } } private void AnimationCompleted(object sender, EventArgs e) { Syncfusion.XForms.EffectsView.SfEffectsView effectsView = sender as Syncfusion.XForms.EffectsView.SfEffectsView; if (effectsView.ScaleFactor == 0.85) { effectsView.ScaleFactor = 1; } else { effectsView.ScaleFactor = 0.85; } } } public class CustomBorder : Syncfusion.XForms.Border.SfBorder { private bool isPotrait = true; double width; protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint) { if (isPotrait && widthConstraint != double.PositiveInfinity) { width = widthConstraint; isPotrait = false; } return base.OnMeasure(width, heightConstraint); } } public class EffectsViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private double scaleFactorValue = 0.85; public double ScaleFactorValue { get { return scaleFactorValue; } set { if (scaleFactorValue != value) { scaleFactorValue = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ScaleFactorValue")); } } } private double scaleDuration = 150; public double ScaleDuration { get { return scaleDuration; } set { if (scaleDuration != value) { scaleDuration = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ScaleDuration")); } } } private SfEffects touchUpEffectsValue = SfEffects.Scale; public SfEffects TouchUpEffectsValue { get { return touchUpEffectsValue; } set { touchUpEffectsValue = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TouchUpEffectsValue")); } } } public class VisibilityConvertor : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Syncfusion.XForms.EffectsView.SfEffectsView effectsView = parameter as Syncfusion.XForms.EffectsView.SfEffectsView; return effectsView.ScaleFactor == 1; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } }<file_sep>/Forms/Chart/Chart/Samples/BarChart/BarSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class BarSeriesViewModel { public ObservableCollection<ChartDataModel> BarData1 { get; set; } public ObservableCollection<ChartDataModel> BarData2 { get; set; } public BarSeriesViewModel() { BarData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Egg", 2.2), new ChartDataModel("Fish", 2.4), new ChartDataModel("Misc", 3), new ChartDataModel("Tea", 3.1), }; BarData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Egg", 1.2), new ChartDataModel("Fish", 1.3), new ChartDataModel("Misc", 1.5), new ChartDataModel("Tea", 2.2), }; } } }<file_sep>/Forms/TreeView/TreeView/Samples/AutoFitContent/Behavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.TreeView.Engine; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using XFSfTreeView = Syncfusion.XForms.TreeView.SfTreeView; namespace SampleBrowser.SfTreeView { #region AutoFitContentBehavior [Preserve(AllMembers = true)] public class AutoFitTreeViewBehavior : Behavior<Syncfusion.XForms.TreeView.SfTreeView> { private XFSfTreeView TreeView; #region Overrides protected override void OnAttachedTo(XFSfTreeView bindable) { bindable.Loaded += Bindable_Loaded; bindable.QueryNodeSize += TreeView_QueryNodeSize; base.OnAttachedTo(bindable); } private void Bindable_Loaded(object sender, Syncfusion.XForms.TreeView.TreeViewLoadedEventArgs e) { this.TreeView = sender as XFSfTreeView; this.WireEvents(); } private void ChatInfo_ConversationAdded(object sender, ChatEventArgs e) { TreeView.BringIntoView(e.Conversation, true, true, Syncfusion.XForms.TreeView.ScrollToPosition.MakeVisible); } private void WireEvents() { var viewModel = this.TreeView.BindingContext as ChatInfo; viewModel.ConversationAdded += ChatInfo_ConversationAdded; viewModel.ReplyTapped += Conversation_ReplyTapped; viewModel.ReplyAdded += ChatInfo_ReplyAdded; } private void UnWireEvents() { var viewModel = this.TreeView.BindingContext as ChatInfo; viewModel.ConversationAdded -= ChatInfo_ConversationAdded; viewModel.ReplyTapped -= Conversation_ReplyTapped; viewModel.ReplyAdded -= ChatInfo_ReplyAdded; } private void TreeView_QueryNodeSize(object sender, Syncfusion.XForms.TreeView.QueryNodeSizeEventArgs e) { e.Height = e.GetActualNodeHeight(); e.Handled = true; } private void ChatInfo_ReplyAdded(object sender, ChatEventArgs e) { this.TreeView.BringIntoView(e.Conversation.Replies[e.Conversation.Replies.Count - 1], true, true, Syncfusion.XForms.TreeView.ScrollToPosition.MakeVisible); } private void Conversation_ReplyTapped(object sender, ReplyEditEventArgs e) { this.TreeView.BringIntoView(e.Content, true, true, Syncfusion.XForms.TreeView.ScrollToPosition.MakeVisible); } protected override void OnDetachingFrom(XFSfTreeView bindable) { bindable.Loaded -= Bindable_Loaded; bindable.QueryNodeSize -= TreeView_QueryNodeSize; this.UnWireEvents(); base.OnDetachingFrom(bindable); } #endregion } #endregion #region AutoFitContentTriggers public class FocusTriggerAction : TriggerAction<Entry> { protected override async void Invoke(Entry entry) { await Task.Delay(100); entry.Focus(); } } #endregion }<file_sep>/Android/SampleBrowser/Samples/Maps/Sublayer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Maps; using Com.Syncfusion.Sfbusyindicator; using Com.Syncfusion.Sfbusyindicator.Enums; using Org.Json; namespace SampleBrowser { public class Sublayer : SamplePage { SfMaps maps; Handler handler; public override Android.Views.View GetSampleContent(Android.Content.Context context) { handler = new Handler(); LinearLayout layout = new LinearLayout(context); layout.Orientation = Orientation.Vertical; TextView textView = new TextView(context); textView.TextSize = 16; textView.SetPadding(10, 20, 0, 0); textView.SetHeight(90); textView.Text = "Rivers in Australia"; layout.AddView(textView); textView.Gravity = Android.Views.GravityFlags.Top; maps = new SfMaps(context); ShapeFileLayer layer = new ShapeFileLayer(); layer.Uri = "australia.shp"; layer.ShapeSettings.ShapeFill = Color.ParseColor("#ACF9F7"); layer.ShapeSettings.ShapeStrokeThickess = 1; maps.Layers.Add(layer); SubShapeFileLayer subLayer = new SubShapeFileLayer(); subLayer.Uri = "river.shp"; subLayer.ShapeSettings.ShapeFill = Color.ParseColor("#00A8CC"); subLayer.ShapeSettings.ShapeStrokeThickess = 2; layer.SubShapeFileLayers.Add(subLayer); maps.Layers.Add(layer); SfBusyIndicator sfBusyIndicator = new SfBusyIndicator(context); sfBusyIndicator.IsBusy = true; sfBusyIndicator.AnimationType = AnimationTypes.SlicedCircle; sfBusyIndicator.ViewBoxWidth = 50; sfBusyIndicator.ViewBoxHeight = 50; sfBusyIndicator.TextColor = Color.ParseColor("#779772"); layout.AddView(sfBusyIndicator); Java.Lang.Runnable run = new Java.Lang.Runnable(() => { layout.RemoveView(sfBusyIndicator); layout.AddView(maps); }); handler.PostDelayed(run, 100); return layout; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Candle.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32;using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Candle : SampleView { public Candle () { SFChart chart = new SFChart (); chart.Title.Text = new NSString ("Foreign Exchange Rate Analysis"); SFDateTimeAxis primary = new SFDateTimeAxis (); primary.Title.Text = new NSString ("Date"); primary.LabelRotationAngle = -45; chart.PrimaryAxis = primary; chart.SecondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis.Title.Text = new NSString ("Price in Dollar"); chart.SecondaryAxis.Minimum = new NSNumber (0); chart.SecondaryAxis.Maximum = new NSNumber (250); chart.SecondaryAxis.Interval = new NSNumber (50); chart.Delegate = new ChartDollarDelegate (); ChartViewModel dataModel = new ChartViewModel (); SFCandleSeries series = new SFCandleSeries(); series.ItemsSource = dataModel.FinancialData; series.XBindingPath = "XValue"; series.High = "High"; series.Low = "Low"; series.Open = "Open"; series.Close = "Close"; series.EnableTooltip = true; series.BorderWidth = 1; series.EnableAnimation = true; chart.Series.Add(series); chart.AddChartBehavior(new SFChartZoomPanBehavior()); series.ColorModel.Palette = SFChartColorPalette.Natural; this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } } <file_sep>/iOS/SampleBrowser/Samples/Chart/DataPointSelection.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Collections.Generic; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class DataPointSelection : SampleView { SFChart chart; ChartViewModel dataModel; UIPickerView selectionPicker; UIButton doneButton; UIButton selectionTypeTextButton; public DataPointSelection() { selectionPicker = new UIPickerView(); doneButton = new UIButton(); selectionTypeTextButton = new UIButton(); chart = new SFChart(); chart.Title.Text = new NSString("Product Sale 2016"); SFCategoryAxis primary = new SFCategoryAxis(); primary.LabelPlacement = SFChartLabelPlacement.BetweenTicks; primary.Title.Text = new NSString("Month"); chart.PrimaryAxis = primary; chart.SecondaryAxis = new SFNumericalAxis() { ShowMajorGridLines = false }; chart.SecondaryAxis.Title.Text = new NSString("Sales"); dataModel = new ChartViewModel(); SFColumnSeries series = new SFColumnSeries(); series.ItemsSource = dataModel.SelectionData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableDataPointSelection = true; series.EnableAnimation = true; series.Color = UIColor.FromRGBA(0, 189f / 255f, 174f / 255f, 1f); series.SelectedDataPointColor = UIColor.FromRGBA(0, 113f / 255f, 104f / 255f, 1f); chart.Series.Add(series); SFColumnSeries series1 = new SFColumnSeries(); series1.ItemsSource = dataModel.SelectionData1; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.EnableDataPointSelection = true; series1.EnableAnimation = true; series1.Color = UIColor.FromRGBA(0, 132f / 255f, 232f / 255f, 1f); series1.SelectedDataPointColor = UIColor.FromRGBA(0, 79f / 255f, 178f / 255f, 1f); chart.Series.Add(series1); chart.AddChartBehavior(new SFChartSelectionBehavior()); this.AddSubview(chart); selectionTypeTextButton.SetTitle(" Data Point Selection", UIControlState.Normal); selectionTypeTextButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; selectionTypeTextButton.SetTitleColor(UIColor.Black, UIControlState.Normal); selectionTypeTextButton.TouchUpInside += delegate { selectionPicker.Hidden = false; doneButton.Hidden = false; this.BecomeFirstResponder(); }; selectionTypeTextButton.BackgroundColor = UIColor.Clear; selectionTypeTextButton.Layer.BorderWidth = 2.0f; selectionTypeTextButton.Layer.BorderColor = UIColor.FromRGB(240.0f / 255.0f, 240.0f / 255.0f, 240.0f / 255.0f).CGColor; selectionTypeTextButton.Layer.CornerRadius = 8.0f; this.AddSubview(selectionTypeTextButton); selectionPicker.ShowSelectionIndicator = true; selectionPicker.Hidden = true; selectionPicker.Model = new PickerViewModel(chart, selectionTypeTextButton); selectionPicker.BackgroundColor = UIColor.FromRGB(240f / 255.0f, 240f / 255.0f, 240f / 255.0f); selectionPicker.SelectedRowInComponent(0); this.AddSubview(selectionPicker); doneButton.SetTitle("Done" + "\t", UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.TouchUpInside += delegate { selectionPicker.Hidden = true; doneButton.Hidden = true; this.BecomeFirstResponder(); }; doneButton.BackgroundColor = UIColor.FromRGB(240f / 255.0f, 240f / 255.0f, 240f / 255.0f); doneButton.Hidden = true; this.AddSubview(doneButton); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view == chart) { chart.Frame = new CGRect(this.Bounds.X, this.Bounds.Y + 40, this.Bounds.Width, this.Bounds.Height - 40); } else if (view == selectionTypeTextButton) { selectionTypeTextButton.Frame = new CGRect(10, Bounds.Y, Frame.Size.Width - 20, 32); } else if (view == doneButton) { if (Utility.IsIPad) { doneButton.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 253, Frame.Size.Width, 35); } else { doneButton.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 143, Frame.Size.Width, 35); } } else if (view == selectionPicker) { if (Utility.IsIPad) { selectionPicker.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 260, Frame.Size.Width, 260); } else { selectionPicker.Frame = new CGRect(0, Bounds.Y + Frame.Size.Height - 150, Frame.Size.Width, 150); } } else view.Frame = Frame; } base.LayoutSubviews(); } } public class PickerViewModel : UIPickerViewModel { UIButton selectionTypeTextButton; SFChart chart1; public PickerViewModel(SFChart chart, UIButton selectionButton) { selectionTypeTextButton = selectionButton; chart1 = chart; } private readonly IList<string> selectionModes = new List<string> { "Data Point Selection", "Series Selection", }; public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return (nint)selectionModes.Count; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return selectionModes[(int)row]; } public override void Selected(UIPickerView pickerView, nint row, nint component) { selectionTypeTextButton.SetTitle(selectionModes[(int)row], UIControlState.Normal); if (row == 0) { chart1.EnableSeriesSelection = false; } else if (row == 1) { chart1.EnableSeriesSelection = true; } } } }<file_sep>/Android/SampleBrowser/Samples/DocIO/GroupShapes.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.OfficeChart; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using Syncfusion.Drawing; using System.IO; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Webkit; using Android.App; using Android.OS; namespace SampleBrowser { public partial class GroupShapes : SamplePage { private Context m_context; RadioGroup radioGroup; RadioButton docxButton; RadioButton pdfButton; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to create a Word document with Group shapes."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; LinearLayout radioLinearLayout = new LinearLayout(con); radioLinearLayout.Orientation = Orientation.Horizontal; TextView imageType = new TextView(con); imageType.Text = "Save As : "; imageType.TextSize = 19; radioLinearLayout.AddView(imageType); radioGroup = new RadioGroup(con); radioGroup.TextAlignment = TextAlignment.Center; radioGroup.Orientation = Orientation.Horizontal; docxButton = new RadioButton(con); docxButton.Text = "DOCX"; radioGroup.AddView(docxButton); pdfButton = new RadioButton(con); pdfButton.Text = "PDF"; radioGroup.AddView(pdfButton); radioGroup.Check(1); radioLinearLayout.AddView(radioGroup); linear.AddView(radioLinearLayout); docxButton.Checked = true; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button generateButton = new Button(con); generateButton.Text = "Generate"; generateButton.Click += OnButtonClicked; linear.AddView(generateButton); return linear; } void OnButtonClicked(object sender, EventArgs e) { //Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Sets page setup options section.PageSetup.Orientation = PageOrientation.Landscape; section.PageSetup.Margins.All = 72; section.PageSetup.PageSize = new SizeF(792f, 612f); //Adds new paragraph to the section WParagraph paragraph = section.AddParagraph() as WParagraph; //Creates new group shape GroupShape groupShape = new GroupShape(document); //Adds group shape to the paragraph. paragraph.ChildEntities.Add(groupShape); //Create a RoundedRectangle shape with "Management" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(324f, 107.7f, 144f, 45f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(50, 48, 142), "Management", groupShape, document); //Create a BentUpArrow shape to connect with "Development" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(177.75f, 176.25f, 210f, 50f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Sales" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(403.5f, 175.5f, 210f, 50f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a DownArrow shape to connect with "Production" shape CreateChildShape(AutoShapeType.DownArrow, new RectangleF(381f, 153f, 29.25f, 72.5f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a RoundedRectangle shape with "Development" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(135f, 226.45f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(104, 57, 157), "Development", groupShape, document); //Create a RoundedRectangle shape with "Production" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(341f, 226.5f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(149, 50, 118), "Production", groupShape, document); //Create a RoundedRectangle shape with "Sales" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(546.75f, 226.5f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(179, 63, 62), "Sales", groupShape, document); //Create a DownArrow shape to connect with "Software" and "Hardware" shape CreateChildShape(AutoShapeType.DownArrow, new RectangleF(177f, 265.5f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a DownArrow shape to connect with "Series" and "Parts" shape CreateChildShape(AutoShapeType.DownArrow, new RectangleF(383.25f, 265.5f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a DownArrow shape to connect with "North" and "South" shape CreateChildShape(AutoShapeType.DownArrow, new RectangleF(588.75f, 266.25f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Software" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(129.5f, 286.5f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Hardware" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(190.5f, 286.5f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Series" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(336f, 287.25f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Parts" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(397f, 287.25f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "North" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(541.5f, 288f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "South" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(602.5f, 288f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a RoundedRectangle shape with "Software" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(93f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "Software", groupShape, document); //Create a RoundedRectangle shape with "Hardware" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(197.2f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "Hardware", groupShape, document); //Create a RoundedRectangle shape with "Series" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(299.25f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "Series", groupShape, document); //Create a RoundedRectangle shape with "Parts" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(404.2f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "Parts", groupShape, document); //Create a RoundedRectangle shape with "North" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(505.5f, 321.75f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "North", groupShape, document); //Create a RoundedRectangle shape with "South" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(609.7f, 321.75f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "South", groupShape, document); MemoryStream ms = new MemoryStream(); //Set file content type string contentType = null; string fileName = null; if (docxButton.Checked) { fileName = "GroupShapes.docx"; contentType = "application/msword"; document.Save(ms, FormatType.Docx); } else { fileName = "GroupShapes.pdf"; contentType = "application/pdf"; DocIORenderer renderer = new DocIORenderer(); PdfDocument pdfDoc = renderer.ConvertToPDF(document); pdfDoc.Save(ms); pdfDoc.Close(); } document.Dispose(); if (ms != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save(fileName, contentType, ms, m_context); } } /// <summary> /// Create a child shape with its specified properties and add into specified group shape /// </summary> /// <param name="autoShapeType">Represent the AutoShapeType of child shape</param> /// <param name="bounds">Represent the bounds of child shape to be placed</param> /// <param name="rotation">Represent the rotation of child shape</param> /// <param name="flipH">Represent the horizontal flip of child shape</param> /// <param name="flipV">Represent the vertical flip of child shape</param> /// <param name="fillColor">Represent the fill color of child shape</param> /// <param name="text">Represent the text that to be append in child shape</param> /// <param name="groupShape">Represent the group shape to add a child shape</param> /// <param name="wordDocument">Represent the Word document instance</param> private static void CreateChildShape(AutoShapeType autoShapeType, RectangleF bounds, float rotation, bool flipH, bool flipV, Syncfusion.Drawing.Color fillColor, string text, GroupShape groupShape, WordDocument wordDocument) { //Creates new shape to add into group Shape shape = new Shape(wordDocument, autoShapeType); //Sets height and width for shape shape.Height = bounds.Height; shape.Width = bounds.Width; //Sets horizontal and vertical position shape.HorizontalPosition = bounds.X; shape.VerticalPosition = bounds.Y; //Set rotation and flipH for the shape if (rotation != 0) shape.Rotation = rotation; if (flipH) shape.FlipHorizontal = true; if (flipV) shape.FlipVertical = true; //Applies fill color for shape if (fillColor != Syncfusion.Drawing.Color.White) { shape.FillFormat.Fill = true; shape.FillFormat.Color = fillColor; } //Set wrapping style for shape shape.WrapFormat.TextWrappingStyle = TextWrappingStyle.InFrontOfText; //Sets horizontal and vertical origin shape.HorizontalOrigin = HorizontalOrigin.Page; shape.VerticalOrigin = VerticalOrigin.Page; //Sets no line to RoundedRectangle shapes if (autoShapeType == AutoShapeType.RoundedRectangle) shape.LineFormat.Line = false; //Add paragraph for the shape textbody if (text != null) { IWParagraph paragraph = shape.TextBody.AddParagraph(); //Set required textbody alignments shape.TextFrame.TextVerticalAlignment = Syncfusion.DocIO.DLS.VerticalAlignment.Middle; //Set required paragraph alignments paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; IWTextRange textRange = paragraph.AppendText(text); //Applies a required text formatting's textRange.CharacterFormat.FontName = "Calibri"; textRange.CharacterFormat.FontSize = 15; textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; textRange.CharacterFormat.Bold = true; textRange.CharacterFormat.Italic = true; } //Adds the specified shape to group shape groupShape.Add(shape); } } } <file_sep>/README.md # Syncfusion Xamarin examples This repository contains awesome demos of [Syncfusion Xamarin UI controls](https://www.syncfusion.com/products/xamarin?utm_source=github&utm_medium=listing). This is the best place to check our controls to get more insight about the usage of APIs. You can also check our controls by installing the complete Xamarin.Forms sample browser from [ Google Play Store](https://play.google.com/store/apps/details?id=com.syncfusion.samplebrowser) or [Microsoft Store](https://www.microsoft.com/en-in/p/syncfusion-essential-studio-for-xamarin/9nn069tldzf4), in which you can browse the demo for all the controls and view the source code of each sample within the app itself. This section guides you to use the Syncfusion Xamarin examples in your applications. * [Requirements to run the demo](#requirements-to-run-the-demo) * [Repository Structure](#repository-structure) * [License](#license) * [Using the examples](#using-the-examples) * [Controls Catalog](#controls-catalog) * [Support and Feedback](#support-and-feedback) ## <a name="requirements-to-run-the-demo"></a>Requirements to run the demo ## * [Visual Studio 2017](https://visualstudio.microsoft.com/downloads/) or [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac/). * Xamarin add-ons for Visual Studio (available via the Visual Studio installer). ## <a name="repository-structure"></a>Repository Structure ## The <b>"Forms"</b> directory contains the Xamarin.Forms examples for each control such as Charts, DataGrid, etc. All the examples can be deployed in Android, iOS, and UWP platforms. Additionally, Charts, DataGrid, and ListView examples can be deployed in macOS platform also. The <b>"Android/SampleBrowser"</b> directory contains Xamarin.Android sample browser project. Run this project to see the Xamarin.Android examples for all the controls in single application. The <b>"iOS/SampleBrowser"</b> directory contains Xamarin.iOS sample browser project. Run this project to see the Xamarin.iOS examples for all the controls in single application. ## <a name="license"></a>License ## Syncfusion has no liability for any damage or consequence that may arise by the use or viewing of the examples. The examples are for demonstrative purposes and if you choose to use or access the examples you agree to not hold Syncfusion liable, in any form, for any damage that is related to use, accessing or otherwise viewing the examples. By accessing, viewing, or otherwise seeing the examples you acknowledge and agree Syncfusion’s examples will not allow you to seek injunctive relief in any form for any claim related to the sample. If you do not agree to this, do not view, access, utilize or otherwise do anything with Syncfusion’s examples. ## <a name="using-the-examples"></a>Using the examples ## If you download the examples using the "Download ZIP" option then please follow the instructions below **Notes:** * Before you unzip the archive, right-click it, select Properties, and then select Unblock. * Be sure to unzip the entire archive, and not just individual examples. The samples depend on the SharedContent folder in the archive. **To use the Syncfusion Xamarin examples, Syncfusion license key should be registered in examples. Refer [this](https://www.syncfusion.com/kb/9002?utm_source=github&utm_medium=listing) link for more information.** **Reminder:** If you unzip individual examples, they will not build due to references to other portions of the ZIP file that were not unzipped. You must unzip the entire archive if you intend to build the examples. ## Controls Catalog | Xamarin.Forms | Xamarin.Android | Xamarin.iOS | | ------------- | --------------- | ----------- | | <b>GRIDS<b> | <B><center>GRIDS</center><b> | <b><center>GRIDS</center><b> | | [DataGrid](Forms/DataGrid) | [DataGrid](Android/SampleBrowser/Samples/DataGrid) | [DataGrid](iOS/SampleBrowser/Samples/DataGrid) | | <b><center>DATA VISUALIZATION</center></b> | <b><center>DATA VISUALIZATION</center></b> | <b><center>DATA VISUALIZATION</center></b> | | [Bar Code](Forms/Barcode) | [Bar Code](Android/SampleBrowser/Samples/Barcode) | [Bar Code](iOS/SampleBrowser/Samples/Barcode) | | [Charts](Forms/Chart) | [Charts](Android/SampleBrowser/Samples/Chart) | [Charts](iOS/SampleBrowser/Samples/Chart) | | [Circular Gauge](Forms/CircularGauge) | [Circular Gauge](Android/SampleBrowser/Samples/CircularGauge) | [Circular Gauge](iOS/SampleBrowser/Samples/CircularGauge) | | [Diagram](Forms/Diagram)| [Diagram](Android/SampleBrowser/Samples/Diagram) | [Diagram](iOS/SampleBrowser/Samples/Diagram) | | [Digital Gauge](Forms/DigitalGauge) | [Digital Gauge](Android/SampleBrowser/Samples/DigitalGauge) | [Digital Gauge](iOS/SampleBrowser/Samples/DigitalGauge) | | [Linear Gauge](Forms/LinearGauge) | [Linear Gauge](Android/SampleBrowser/Samples/LinearGauge) | [Linear Gauge](iOS/SampleBrowser/Samples/LinearGauge) | | [Maps](Forms/Maps) | [Maps](Android/SampleBrowser/Samples/Maps) | [Maps](iOS/SampleBrowser/Samples/Maps) | | [Range Navigator](Forms/RangeNavigator) | [Range Navigator](Android/SampleBrowser/Samples/RangeNavigator) | [Range Navigator](iOS/SampleBrowser/Samples/RangeNavigator) | | [Sparkline](Forms/Sparkline) | [Sparkline](Android/SampleBrowser/Samples/SparkLine) | [Sparkline](iOS/SampleBrowser/Samples/Sparkline) | | [Sunburst Chart](Forms/SunburstChart) | [Sunburst Chart](Android/SampleBrowser/Samples/Sunburst) | [Sunburst Chart](iOS/SampleBrowser/Samples/Sunburst) | | [Tree Map](Forms/TreeMap) | [Tree Map](Android/SampleBrowser/Samples/TreeMap) | [Tree Map](iOS/SampleBrowser/Samples/TreeMap) | | <b><center>CALENDAR</center><b> | <b><center>CALENDAR</center><b> | <b><center>CALENDAR</center><b> | | [Scheduler](Forms/Schedule) | [Scheduler](Android/SampleBrowser/Samples/Schedule) | [Scheduler](iOS/SampleBrowser/Samples/Schedule) | | [Calendar](Forms/Calendar) | [Calendar](Android/SampleBrowser/Samples/Calendar) | [Calendar](iOS/SampleBrowser/Samples/Calendar) | | <b><center>PROJECT MANAGEMENT</center><b> | <b><center>PROJECT MANAGEMENT</center><b> | <b><center>PROJECT MANAGEMENT</center><b> | | [Kanban](Forms/Kanban) | [Kanban](Android/SampleBrowser/Samples/Kanban) | [Kanban](iOS/SampleBrowser/Samples/Kanban) | | <b><center>NOTIFICATION</center><b> | <b><center>NOTIFICATION</center><b> | <b><center>NOTIFICATION</center><b> | | [Busy Indicator](Forms/BusyIndicator) | [Busy Indicator](Android/SampleBrowser/Samples/BusyIndicator) | [Busy Indicator](iOS/SampleBrowser/Samples/BusyIndicator) | | [Progress Bar](Forms/ProgressBar) | [Progress Bar](Android/SampleBrowser/Samples/ProgressBar) | [Progress Bar](iOS/SampleBrowser/Samples/ProgressBar) | | [Pull To Refresh](Forms/PullToRefresh) | [Pull To Refresh](Android/SampleBrowser/Samples/PullToRefresh) | [Pull To Refresh](iOS/SampleBrowser/Samples/PullToRefresh) | | <b><center>VIEWER/EDITOR</center><b> | <b><center>VIEWER/EDITOR</center><b> | <b><center>VIEWER/EDITOR</center><b> | | [Image Editor](Forms/ImageEditor) | [Image Editor](Android/SampleBrowser/Samples/ImageEditor) | [Image Editor](iOS/SampleBrowser/Samples/ImageEditor) | | [PDF Viewer](Forms/PdfViewer) | [PDF Viewer](Android/SampleBrowser/Samples/PDFViewer) | [PDF Viewer](iOS/SampleBrowser/Samples/PDFViewer) | | <b><center>NAVIGATION</center><b> | <b><center>NAVIGATION</center><b> | <b><center>NAVIGATION</center><b> | | [Navigation Drawer](Forms/NavigationDrawer) | [Navigation Drawer](Android/SampleBrowser/Samples/NavigationDrawer) | [Navigation Drawer](iOS/SampleBrowser/Samples/NavigationDrawer) | | [Radial Menu](Forms/RadialMenu) | [Radial Menu](Android/SampleBrowser/Samples/RadialMenu) | [Radial Menu](iOS/SampleBrowser/Samples/RadialMenu) | | [Rotator](Forms/Rotator) | [Rotator](Android/SampleBrowser/Samples/Rotator) | [Rotator](iOS/SampleBrowser/Samples/Rotator) | | [Tabs](Forms/TabView) | [Tabs](Android/SampleBrowser/Samples/TabView) | [Tabs](iOS/SampleBrowser/Samples/TabView) | | <b><center>LAYOUT</center><b> | <b><center>LAYOUT</center><b> | <b><center>LAYOUT</center><b> | | [Carousel](Forms/Carousel) | [Carousel](Android/SampleBrowser/Samples/Carousel) | [Carousel](iOS/SampleBrowser/Samples/Carousel) | | [ListView](Forms/ListView) | - | - | | [Pop-up](Forms/PopupLayout) | [Pop-up](Android/SampleBrowser/Samples/PopupLayout) | [Pop-up](iOS/SampleBrowser/Samples/PopupLayout) | | <b><center>EDITORS</center><b> | <b><center>EDITORS</center><b> | <b><center>EDITORS</center><b> | | [Autocomplete](Forms/AutoComplete) | [Autocomplete](Android/SampleBrowser/Samples/AutoComplete) | [Autocomplete](iOS/SampleBrowser/Samples/AutoComplete) | | [CheckBox](Forms/CheckBox) | [CheckBox](Android/SampleBrowser/Samples/CheckBox) | [CheckBox](iOS/SampleBrowser/Samples/CheckBox) | | [Combo Box](Forms/ComboBox) | [Combo Box](Android/SampleBrowser/Samples/ComboBox) | [Combo Box](iOS/SampleBrowser/Samples/ComboBox) | | [Data Form](Forms/DataForm) | [Data Form](Android/SampleBrowser/Samples/DataForm) | [Data Form](iOS/SampleBrowser/Samples/DataForm) | | [Masked Text Box](Forms/MaskedEdit) | [Masked Text Box](Android/SampleBrowser/Samples/SfMaskedEdit) | [Masked Text Box](iOS/SampleBrowser/Samples/MaskedEdit) | | [Numeric Text Box](Forms/NumericTextBox) | [Numeric Text Box](Android/SampleBrowser/Samples/NumericTextBox) | [Numeric Text Box](iOS/SampleBrowser/Samples/NumericTextBox) | | [Numeric Up-Down](Forms/NumericUpDown) | [Numeric Up-Down](Android/SampleBrowser/Samples/NumericUpDown) | [Numeric Up-Down](iOS/SampleBrowser/Samples/NumericUpDown) | | [Picker](Forms/Picker) | [Picker](Android/SampleBrowser/Samples/SfPicker) | [Picker](iOS/SampleBrowser/Samples/Picker) | | [Radio Button](Forms/RadioButton) |-| [Radio Button](iOS/SampleBrowser/Samples/RadioButton) | | [Range Slider](Forms/RangeSlider) | [Range Slider](Android/SampleBrowser/Samples/RangeSlider) | [Range Slider](iOS/SampleBrowser/Samples/RangeSlider) | | [Rating](Forms/Rating) | [Rating](Android/SampleBrowser/Samples/Rating) | [Rating](iOS/SampleBrowser/Samples/Rating) | | [Segmented Control](Forms/SegmentedControl) | [Segmented Control](Android/SampleBrowser/Samples/SegmentedView) |[Segmented Control](iOS/SampleBrowser/Samples/SegmentedControl) | | <b><center>FILE FORMATS</center><b> | <b><center>FILE FORMATS</center><b> | <b><center>FILE FORMATS</center><b> | | [Excel](Forms/XlsIO) | [Excel](Android/SampleBrowser/Samples/XlsIO) | [Excel](iOS/SampleBrowser/Samples/XlsIO) | | [PDF](Forms/PDF) | [PDF](Android/SampleBrowser/Samples/PDF) | [PDF](iOS/SampleBrowser/Samples/PDF) | | [Word](Forms/DocIO) |[Word](Android/SampleBrowser/Samples/DocIO) |[Word](iOS/SampleBrowser/Samples/DocIO) | | [PowerPoint](Forms/Presentation) | [PowerPoint](Android/SampleBrowser/Samples/Presentation) |[PowerPoint](iOS/SampleBrowser/Samples/Presentation) | | <b><center>MISCELLANEOUS</center><b> | <b><center>MISCELLANEOUS</center><b> | <b><center>MISCELLANEOUS</center><b> | | [Calculate](Forms/Calculate) | [Calculate](Android/SampleBrowser/Samples/Calculate) | [Calculate](iOS/SampleBrowser/Samples/Calculate) | | [Data Source](Forms/DataSource) | [Data Source](Android/SampleBrowser/Samples/DataSource) | [Data Source](iOS/SampleBrowser/Samples/DataSource) | ## <a name="syncfusion-xamarin-ui-template"></a>Syncfusion Xamarin UI Template ## The Syncfusion item templates extension provides predefined UI designs for Xamarin.Forms. Refer to [Syncfusion Project Templates](https://help.syncfusion.com/xamarin/visual-studio-integration/visual-studio-extensions/item-templates) for more details. ## <a name="support-and-feedback"></a>Support and Feedback ## * If you’re interested in Xamarin development using Syncfusion Xamarin UI components, refer to the below guides that will help you building your own application. * [Xamarin Forms](https://help.syncfusion.com/xamarin/introduction/overview?utm_source=github&utm_medium=listing) * [Xamarin-Android](https://help.syncfusion.com/xamarin-android/introduction/overview?utm_source=github&utm_medium=listing) * [Xamarin-iOS](https://help.syncfusion.com/xamarin-ios/introduction/overview?utm_source=github&utm_medium=listing) * For any other queries, reach our [Syncfusion support team](https://www.syncfusion.com/support/directtrac/incidents/newincident?utm_source=github&utm_medium=listing) or post the queries through the [community forums](https://www.syncfusion.com/forums?utm_source=github&utm_medium=listing). * To renew the subscription, click [here](https://www.syncfusion.com/sales/products?utm_source=github&utm_medium=listing) or contact our sales team at <<EMAIL>>. <p>Copyright © 2001-2023 Syncfusion, Inc. Updated on 2023-07-28 at precisely 13:41:44 EST.</p> <file_sep>/Forms/PDF/PDF.iOS/QLPreviewItemFileSystem.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using QuickLook; using Foundation; using System.IO; namespace SampleBrowser.PDF.iOS { public class QLPreviewItemFileSystem : QLPreviewItem { string _fileName, _filePath; public QLPreviewItemFileSystem(string fileName, string filePath) { _fileName = fileName; _filePath = filePath; } public override string ItemTitle { get { return _fileName; } } public override NSUrl ItemUrl { get { return NSUrl.FromFilename(_filePath); } } } public class QLPreviewItemBundle : QLPreviewItem { string _fileName, _filePath; public QLPreviewItemBundle(string fileName, string filePath) { _fileName = fileName; _filePath = filePath; } public override string ItemTitle { get { return _fileName; } } public override NSUrl ItemUrl { get { var documents = NSBundle.MainBundle.BundlePath; var lib = Path.Combine(documents, _filePath); var url = NSUrl.FromFilename(lib); return url; } } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/Model/EmployeeDetails.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class EmployeeDetails { public EmployeeDetails () { } #region private variables private Random random = new Random (); #endregion #region GetEmployeeDetails public List<EmployeeInfo> GetEmployeeDetails (int count) { List<EmployeeInfo> employeeDetails = new List<EmployeeInfo> (); for (int i = 1; i <= count; i++) { var ord = new EmployeeInfo () { EmployeeID = EmployeeID [random.Next (15)], Name = Customers [random.Next (15)], Age=Age[random.Next(10)], Company = Company [random.Next(10)], Title = Title [random.Next (10)], Salary = Salary[random.Next (13)], Bonus=Bonus[random.Next(7)] }; employeeDetails.Add (ord); } return employeeDetails; } #endregion int[] EmployeeID = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; int[] Salary = new int[] { 256787, 34455, 445545, 234567, 78434555, 93455, 3456674, 34567457, 23424, 655676, 2252459, 34368, 125436, 90558, 648489, 5537383 }; string[] Company = new string[] { "CTS", "TCS", "Infosys", "Amazon", "Aspire", "HP", "HCL", "DELL", "Mphasis", "Accenture", "Syncfusion", "Bally", "Google", "Microsoft", }; string[] Title = new string[] { "Manager ", "Recruiter", "Security", "Supervisor", "Admin", "Admin", "Assistant", "President", "Designer", "Manager", "Marketing", "Stocker", "Clerk" }; string[] Customers = new string[] { "Kyle", "Gina", "Irene", "Katie", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Brenda", "Danielle", "Fiona", "Howard", "Jack", "Larry", "Holly", "Jennifer", "Liz", "Pete", "Steve", "Vince", "Zeke" }; int[] Age = new int[] { 21, 34, 45, 21, 23, 25, 43, 32, 22, 44, 25, 47, 35, 37, 41 }; int[] Bonus = new int[] { 2, 3, 4, 1, 12, 13, 15, 18, 14, 6, 7 }; } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/ReleaseInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ReleaseInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties and notifies clients that a property value has changed. /// </summary> public class ReleaseInfo { #region private variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int sNo; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string platform; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string releaseVersion; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string features; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string description; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string dateOfRelease; #endregion /// <summary> /// Initializes a new instance of the ReleaseInfo class. /// </summary> public ReleaseInfo() { } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the value of SNo and notifies user when value gets changed /// </summary> public int SNo { get { return this.sNo; } set { this.sNo = value; this.RaisePropertyChanged("SNo"); } } /// <summary> /// Gets or sets the value of Platform and notifies user when value gets changed /// </summary> public string Platform { get { return this.platform; } set { this.platform = value; this.RaisePropertyChanged("Platform"); } } /// <summary> /// Gets or sets the value of ReleaseVersion and notifies user when value gets changed /// </summary> public string ReleaseVersion { get { return this.releaseVersion; } set { this.releaseVersion = value; this.RaisePropertyChanged("ReleaseVersion"); } } /// <summary> /// Gets or sets the value of Features and notifies user when value gets changed /// </summary> public string Features { get { return this.features; } set { this.features = value; this.RaisePropertyChanged("Features"); } } /// <summary> /// Gets or sets the value of Description and notifies user when value gets changed /// </summary> public string Description { get { return this.description; } set { this.description = value; this.RaisePropertyChanged("Description"); } } /// <summary> /// Gets or sets the value of DateOfRelease and notifies user when value gets changed /// </summary> public string DateOfRelease { get { return this.dateOfRelease; } set { this.dateOfRelease = value; this.RaisePropertyChanged("DateOfRelease"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type of parameter name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/OrderInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "OrderInfoRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class used to store the item values /// </summary> public class OrderInfoRepository { #region private variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private List<DateTime> orderedDates; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Random random = new Random(); #endregion #region MainGrid DataSource [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] genders = new string[] { "Male", "Female", "Female", "Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male", "Male", "Female", "Female", "Female", "Male", "Male", "Male", "Female", "Female", "Female", "Male", "Male", "Male", "Male" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] firstNames = new string[] { "Kyle", "Gina", "Irene", "Katie", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Brenda", "Danielle", "Fiona", "Howard", "Jack", "Larry", "Holly", "Jennifer", "Liz", "Pete", "Steve", "Vince", "Zeke" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] lastNames = new string[] { "Adams", "Crowley", "Ellis", "Gable", "Irvine", "Keefe", "Mendoza", "Owens", "Rooney", "Waddell", "Thomas", "Betts", "Doran", "Holmes", "Jefferson", "Landry", "Newberry", "Perez", "Spencer", "Vargas", "Grimes", "Edwards", "Stark", "Cruise", "Fitz", "Chief", "Blanc", "Perry", "Stone", "Williams", "Lane", "Jobs" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] customerID = new string[] { "Alfki", "Frans", "Merep", "Folko", "Simob", "Warth", "Vaffe", "Furib", "Seves", "Linod", "Riscu", "Picco", "Blonp", "Welli", "Folig" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] shipCountry = new string[] { "Argentina", "Austria", "Belgium", "Brazil", "Canada", "Denmark", "Finland", "France", "Germany", "Ireland", "Italy", "Mexico", "Norway", "Poland", "Portugal", "Spain", "Sweden", "UK", "USA", }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Dictionary<string, string[]> shipCity = new Dictionary<string, string[]>(); #endregion /// <summary> /// Initializes a new instance of the OrderInfoRepository class. /// </summary> public OrderInfoRepository() { } #region GetOrderDetails /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">integer type of count parameter</param> /// <returns>stored Items Values</returns> public ObservableCollection<OrderInfo> GetOrderDetails(int count) { this.SetShipCity(); this.orderedDates = this.GetDateBetween(2000, 2014, count); ObservableCollection<OrderInfo> orderDetails = new ObservableCollection<OrderInfo>(); for (int i = 10001; i <= count + 10000; i++) { var shipcountry = this.shipCountry[this.random.Next(5)]; var shipcitycoll = this.shipCity[shipcountry]; var ord = new OrderInfo() { OrderID = i.ToString(), CustomerID = this.customerID[this.random.Next(15)], EmployeeID = this.random.Next(1700, 1800).ToString(), FirstName = this.firstNames[this.random.Next(15)], LastName = this.lastNames[this.random.Next(15)], Gender = this.genders[this.random.Next(5)], ShipCountry = shipcountry, ShippingDate = this.orderedDates[i - 10001], Freight = Math.Round(this.random.Next(1000) + this.random.NextDouble(), 2), IsClosed = (i % this.random.Next(1, 10) > 2) ? true : false, ShipCity = shipcitycoll[this.random.Next(shipcitycoll.Length - 1)], }; orderDetails.Add(ord); } return orderDetails; } /// <summary> /// Used this method to add the More Items in View while view was refreshing /// </summary> /// <param name="i">record rows count</param> /// <returns>added Items Value</returns> internal OrderInfo RefreshItemsource(int i) { var ordeshipcity = this.shipCity[this.shipCountry[this.random.Next(0, 5)]]; var order = new OrderInfo() { OrderID = i.ToString(), CustomerID = this.customerID[this.random.Next(15)], EmployeeID = this.random.Next(1700, 1800).ToString(), FirstName = this.firstNames[this.random.Next(15)], LastName = this.lastNames[this.random.Next(15)], Gender = this.genders[this.random.Next(5)], ShipCountry = this.shipCountry[this.random.Next(5)], ShippingDate = DateTime.Now, Freight = Math.Round(this.random.Next(1000) + this.random.NextDouble(), 2), IsClosed = (i % this.random.Next(1, 10) > 5) ? true : false, ShipCity = ordeshipcity[0], }; return order; } /// <summary> /// Generates record rows with given count /// </summary> /// <param name="id">integer type of parameter id</param> /// <returns>returns stored Records value</returns> internal OrderInfo GenerateOrder(int id) { var shipcountry = this.shipCountry[this.random.Next(5)]; var shipcitycoll = this.shipCity[shipcountry]; var order = new OrderInfo() { OrderID = (id + 10000).ToString(), EmployeeID = this.random.Next(1700, 1800).ToString(), CustomerID = this.customerID[this.random.Next(15)], IsClosed = (id % this.random.Next(1, 10) > 5) ? true : false, FirstName = this.firstNames[this.random.Next(15)], LastName = this.lastNames[this.random.Next(15)], Gender = this.genders[this.random.Next(5)], ShipCity = shipcitycoll[this.random.Next(shipcitycoll.Length - 1)], ShipCountry = this.shipCountry[this.random.Next(5)], Freight = Math.Round(this.random.Next(1000) + this.random.NextDouble(), 2), ShippingDate = this.orderedDates[this.random.Next(15)], }; return order; } #endregion /// <summary> /// Used to generate DateTime and returns the value /// </summary> /// <param name="startYear">integer type of parameter startYear</param> /// <param name="endYear">integer type of parameter endYear</param> /// <param name="count">integer type of parameter count</param> /// <returns>returns the generated DateTime</returns> private List<DateTime> GetDateBetween(int startYear, int endYear, int count) { List<DateTime> date = new List<DateTime>(); Random d = new Random(1); Random m = new Random(2); Random y = new Random(startYear); for (int i = 0; i < count; i++) { int year = y.Next(startYear, endYear); int month = m.Next(3, 13); int day = d.Next(1, 31); date.Add(new DateTime(year, month, day)); } return date; } /// <summary> /// This method used to store the string items collections Value /// </summary> private void SetShipCity() { string[] argentina = new string[] { "Rosario" }; string[] austria = new string[] { "Graz", "Salzburg" }; string[] belgium = new string[] { "Bruxelles", "Charleroi" }; string[] brazil = new string[] { "Campinas", "Resende", "Recife", "Manaus" }; string[] canada = new string[] { "Montréal", "Tsawassen", "Vancouver" }; string[] denmark = new string[] { "Århus", "København" }; string[] finland = new string[] { "Helsinki", "Oulu" }; string[] france = new string[] { "Lille", "Lyon", "Marseille", "Nantes", "Paris", "Reims", "Strasbourg", "Toulouse", "Versailles" }; string[] germany = new string[] { "Aachen", "Berlin", "Brandenburg", "Cunewalde", "Frankfurt", "Köln", "Leipzig", "Mannheim", "München", "Münster", "Stuttgart" }; string[] ireland = new string[] { "Cork" }; string[] italy = new string[] { "Bergamo", "Reggio", "Torino" }; string[] mexico = new string[] { "México D.F." }; string[] norway = new string[] { "Stavern" }; string[] poland = new string[] { "Warszawa" }; string[] portugal = new string[] { "Lisboa" }; string[] spain = new string[] { "Barcelona", "Madrid", "Sevilla" }; string[] sweden = new string[] { "Bräcke", "Luleå" }; string[] switzerland = new string[] { "Bern", "Genève" }; string[] uk = new string[] { "Colchester", "Hedge End", "London" }; string[] usa = new string[] { "Albuquerque", "Anchorage", "Boise", "Butte", "Elgin", "Eugene", "Kirkland", "Lander", "Portland", "San Francisco", "Seattle", }; string[] venezuela = new string[] { "Barquisimeto", "Caracas", "<NAME>ita", "San Cristóbal" }; this.shipCity.Add("Argentina", argentina); this.shipCity.Add("Austria", austria); this.shipCity.Add("Belgium", belgium); this.shipCity.Add("Brazil", brazil); this.shipCity.Add("Canada", canada); this.shipCity.Add("Denmark", denmark); this.shipCity.Add("Finland", finland); this.shipCity.Add("France", france); this.shipCity.Add("Germany", germany); this.shipCity.Add("Ireland", ireland); this.shipCity.Add("Italy", italy); this.shipCity.Add("Mexico", mexico); this.shipCity.Add("Norway", norway); this.shipCity.Add("Poland", poland); this.shipCity.Add("Portugal", portugal); this.shipCity.Add("Spain", spain); this.shipCity.Add("Sweden", sweden); this.shipCity.Add("Switzerland", switzerland); this.shipCity.Add("UK", uk); this.shipCity.Add("USA", usa); this.shipCity.Add("Venezuela", venezuela); } } }<file_sep>/Forms/Chart/Chart/Samples/BoxAndWhiskerChart/BoxAndWhiskerSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class BoxAndWhiskerSeriesViewModel { public ObservableCollection<ChartDataModel> BoxWhiskerData { get; set; } public BoxAndWhiskerSeriesViewModel() { BoxWhiskerData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Development", new List<double> { 22, 22, 23, 25, 25, 25, 26, 27, 27, 28, 28, 29, 30, 32, 34, 32, 34, 36, 35, 38 }), new ChartDataModel("Testing", new List<double> { 22, 33, 23, 25, 26, 28, 29, 30, 34, 33, 32, 31, 50 }), new ChartDataModel("HR", new List<double> { 22, 24, 25, 30, 32, 34, 36, 38, 39, 41, 35, 36, 40, 56 }), new ChartDataModel("Finance", new List<double> { 26, 27, 28, 30, 32, 34, 35, 37, 35, 37, 45 }), new ChartDataModel("Sales", new List<double> { 26, 27, 29, 32, 34, 35, 36, 37, 38, 39, 41, 43, 58 }), }; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/AxisCrossing.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using CoreAnimation; #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using CoreGraphics; using Foundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.CoreGraphics; using MonoTouch.UIKit; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif using System.Threading.Tasks; namespace SampleBrowser { public class AxisCrossing : SampleView { public AxisCrossing() { SFChart chart = new SFChart(); chart.Title.Text = new NSString("Profit/loss percentage comparison"); SFCategoryAxis primaryAxis = new SFCategoryAxis(); primaryAxis.Interval = new NSNumber(2); primaryAxis.CrossesAt = 0; primaryAxis.PlotOffset = 7; primaryAxis.ShowMajorGridLines = false; primaryAxis.AxisLineOffset = 7; primaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Fit; primaryAxis.Name = new NSString("XAxis"); primaryAxis.CrossingAxisName = "YAxis"; primaryAxis.ShowMajorGridLines = false; chart.PrimaryAxis = primaryAxis; SFNumericalAxis secondaryAxis = new SFNumericalAxis(); secondaryAxis.Maximum = new NSNumber(-100); secondaryAxis.Minimum = new NSNumber(100); secondaryAxis.Interval = new NSNumber(20); secondaryAxis.CrossesAt = 8; secondaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; secondaryAxis.Name = new NSString("YAxis"); secondaryAxis.CrossingAxisName = "XAxis"; secondaryAxis.ShowMajorGridLines = false; secondaryAxis.ShowMinorGridLines = false; chart.SecondaryAxis = secondaryAxis; ChartViewModel dataModel = new ChartViewModel(); SFScatterSeries series = new SFScatterSeries(); series.ScatterWidth = 15; series.ScatterHeight = 15; series.ItemsSource = dataModel.AxisCrossingData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.ColorModel.Palette = SFChartColorPalette.Natural; series.EnableTooltip = true; chart.Behaviors.Add(new SFChartZoomPanBehavior() { EnableSelectionZooming = false }); chart.Delegate = new CustomDelegate(); chart.Series.Add(series); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } public class CustomDelegate : SFChartDelegate { public override NSString GetFormattedAxisLabel(SFChart chart, NSString label, NSObject value, SFAxis axis) { if (axis == chart.SecondaryAxis) label = (Foundation.NSString)(label + "%"); return label; } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/ViewModel/ContactsViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ContactsViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Xamarin.Forms; /// <summary> /// A ViewModel for Contacts sample. /// </summary> public class ContactsViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// Holds the call time of the contact. /// </summary> private readonly string callTime = "Mobile 11Hrs. ago"; /// <summary> /// Holds the value for referencing different images of the caller. /// </summary> private readonly int counter = 11; /// <summary> /// Holds the data of FeMale CustomerNames. /// </summary> private readonly string[] customerNamesFeMale = { "Kyle", "Katie", "Brenda", "Irene", "Danielle", "Fiona", "Larry", "Jennifer", "Liz", "Pete", "Vince", "Liam ", "Noah ", "Elijah ", "Brayden", "Andrew ", "Gabriel", "Joshua ", "Owen ", "Eli ", "Isaac ", "Isaiah ", "Levi ", "Adrian ", "Nolan ", "Riley ", "Bentley", "Jeremiah", "Jace ", "Brandon", "Josiah ", "Bryce ", "Adam ", "Hayden ", "Chase ", "Austin ", "Colin ", "Cole ", "Julian ", "Sebastian", }; /// <summary> /// Holds the data of Male CustomerNames. /// </summary> private readonly string[] customerNamesMale = { "Gina", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Howard", "Jack", "Holly", "Steve", "Zeke", "Aiden", "Jackson", "Mason ", "Jacob ", "Jayden ", "Ethan ", "Lucas ", "Logan ", "Caleb ", "Caden ", "Jack ", "Ryan ", "Connor ", "Michael", "Benjamin", "Nicholas", "Alexander", "William", "Matthew", "James ", "Landon ", "Nathan ", "Dylan ", "Evan ", "Luke ", "Gavin ", "Daniel ", "Carter ", "Tyler ", "Cameron", "Christian", "Wyatt ", "Henry ", "Joseph ", "Max ", "Samuel ", "Anthony", "Grayson", "Zachary", "David ", "Christopher", "John ", "Jonathan", "Oliver ", "Cooper ", "Tristan", "Colton ", "Charlie", "Dominic", "Parker ", "Hunter ", "Thomas ", "Alex ", "Ian ", "Jordan ", "Aaron ", "Carson ", "Miles ", "Blake ", "Brody ", "Sean ", "Xavier ", "Jason ", "Jake ", "Asher ", "Micah ", "Hudson ", "Nathaniel", "Bryson ", "Ryder ", "Justin ", }; /// <summary> /// Holds the data of FeMale Image. /// </summary> private string[] imageFemale = new string[] { "People_Circle0.png", "People_Circle1.png", "People_Circle2.png", "People_Circle3.png", "People_Circle4.png", "People_Circle6.png", "People_Circle7.png", "People_Circle9.png", "People_Circle10.png", "People_Circle11.png", "People_Circle13.png", "People_Circle15.png", "People_Circle16.png", "People_Circle17.png", "People_Circle19.png", "People_Circle20.png", "People_Circle21.png", "People_Circle22.png", "People_Circle24.png", "People_Circle25.png", }; /// <summary> /// Holds the data of Male Image. /// </summary> private string[] imageMale = new string[] { "People_Circle5.png", "People_Circle8.png", "People_Circle12.png", "People_Circle14.png", "People_Circle18.png", "People_Circle23.png", "People_Circle26.png", "People_Circle27.png", }; #endregion #region Constructor /// <summary> /// Initializes a new instance of the ContactsViewModel class. /// </summary> public ContactsViewModel() { this.Contactsinfo = new ObservableCollection<ContactInfo>(); Random random = new Random(); if (this.counter == 26) { this.counter = 11; } for (int i = 1; i <= 80; i++) { var contact = new ContactInfo(); contact.ContactName = (this.counter % 2 == 0) ? this.customerNamesMale[random.Next(30)] : this.customerNamesFeMale[random.Next(30)]; contact.CallTime = this.callTime; contact.ContactImage = (this.counter % 2 == 0) ? this.imageMale[random.Next(7)] : this.imageFemale[random.Next(15)]; this.Contactsinfo.Add(contact); this.counter++; } this.SetBindingImageSource(); } #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Properties /// <summary> /// Gets or sets the Contacts info value of ObservableCollection of ContactInfo type. /// </summary> public ObservableCollection<ContactInfo> Contactsinfo { get; set; } #endregion #region Interface Member /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name</param> public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion #region Private Methods /// <summary> /// Sets the Source for the images. /// </summary> private void SetBindingImageSource() { } #endregion } }<file_sep>/Forms/TabView/TabView/Samples/NestedTab/Model/ContactsInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTabView { [Preserve(AllMembers = true)] public class ContactsInfo : INotifyPropertyChanged { #region Fields private string contactName; private string contactNo; private string image; private string contactType; private string date; private string message; private bool read = false; private string messageCount; private string dateMonth; #endregion #region Constructor public ContactsInfo() { } #endregion #region Public Properties public string ContactName { get { return this.contactName; } set { this.contactName = value; RaisePropertyChanged("ContactName"); } } public string ContactNumber { get { return contactNo; } set { this.contactNo = value; RaisePropertyChanged("ContactNumber"); } } public string ContactReadType { get { return contactType; } set { this.contactType = value; RaisePropertyChanged("ContactReadType"); } } public string ContactImage { get { return this.image; } set { this.image = value; this.RaisePropertyChanged("ContactImage"); } } public string Message { get { return this.message; } set { this.message = value; this.RaisePropertyChanged("Message"); } } public bool Read { get { return this.read; } set { this.read = value; this.RaisePropertyChanged("Read"); } } public string Date { get { return this.date; } set { this.date = value; this.RaisePropertyChanged("Date"); } } public string DateMonth { get { return this.dateMonth; } set { this.dateMonth = value; this.RaisePropertyChanged("DateMonth"); } } public string MessageCount { get { return this.messageCount; } set { this.messageCount = value; this.RaisePropertyChanged("MessageCount"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Calendar/CalendarGettingStarted/CalendarGettingStarted_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Calendar; using Com.Syncfusion.Calendar.Enums; using Android.Graphics; using Com.Syncfusion.Navigationdrawer; namespace SampleBrowser { public class CalendarGettingStarted_Mobile : IDisposable { /********************************* **Local Variable Inizialisation** *********************************/ private LinearLayout.LayoutParams separatorLayoutParams; private ViewMode viewMode = ViewMode.MonthView; private ArrayAdapter<String> dataAdapter; private SeparatorView separate; private LinearLayout propertylayout; private TextView viewModetxt; private FrameLayout mainView; private SfCalendar calendar; private Spinner modeSpinner; private int width; private Context context; public View GetSampleContent(Context context) { /************ **Calendar** ************/ calendar = new SfCalendar(context); calendar.ShowEventsInline = false; calendar.HeaderHeight = 100; MonthViewLabelSetting labelSettings = new MonthViewLabelSetting(); labelSettings.DateLabelSize = 14; MonthViewSettings monthViewSettings = new MonthViewSettings(); monthViewSettings.MonthViewLabelSetting = labelSettings; monthViewSettings.SelectedDayTextColor = Color.Black; monthViewSettings.TodayTextColor = Color.ParseColor("#1B79D6"); monthViewSettings.InlineBackgroundColor = Color.ParseColor("#E4E8ED"); monthViewSettings.WeekDayBackgroundColor = Color.ParseColor("#F7F7F7"); calendar.MonthViewSettings = monthViewSettings; //main View mainView = new FrameLayout(context); mainView.AddView(calendar); return mainView; } public View GetPropertyWindowLayout(Context context1) { context = context1; width = context.Resources.DisplayMetrics.WidthPixels / 2; ViewModeLayout(); /****************** **propertylayout** ******************/ propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; propertylayout.AddView(viewModetxt); propertylayout.AddView(modeSpinner); //propertylayout.AddView(separate, separatorLayoutParams); propertylayout.SetPadding(10, 10, 10, 10); return propertylayout; } private void ViewModeLayout() { /************ **ViewMode** ************/ viewModetxt = new TextView(context); viewModetxt.TextSize = 20; viewModetxt.Text = "ViewMode"; modeSpinner = new Spinner(context, SpinnerMode.Dialog); //View Mode List List<String> viewModeList = new List<String>(); viewModeList.Add("Month View"); viewModeList.Add("Year View"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, viewModeList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); modeSpinner.Adapter = dataAdapter; //Mode Spinner Item Selected Listener modeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Month View")) { viewMode = ViewMode.MonthView; } if (selectedItem.Equals("Year View")) { viewMode = ViewMode.YearView; } }; //Separator separatorLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); separatorLayoutParams.SetMargins(0, 20, 0, 0); separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); } /************************ **Apply Changes Method** ************************/ public void OnApplyChanges() { calendar.ViewMode = viewMode; } public void Dispose() { if (calendar != null) { calendar.Dispose(); calendar = null; } if (dataAdapter != null) { dataAdapter.Dispose(); dataAdapter = null; } if (modeSpinner != null) { modeSpinner.Dispose(); modeSpinner = null; } if (mainView != null) { mainView.Dispose(); mainView = null; } if (separatorLayoutParams != null) { separatorLayoutParams.Dispose(); separatorLayoutParams = null; } if (separate != null) { separate.Dispose(); separate = null; } if (propertylayout != null) { propertylayout.Dispose(); propertylayout = null; } if (viewModetxt != null) { viewModetxt.Dispose(); viewModetxt = null; } } } }<file_sep>/Forms/Chart/Chart/Samples/ZoomingAndPanning/ZoomingAndPanning.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using Xamarin.Forms; using Syncfusion.SfChart.XForms; namespace SampleBrowser.SfChart { public partial class ZoomingAndPanning : SampleView { public ZoomingAndPanning() { InitializeComponent(); if (Device.RuntimePlatform == Device.macOS || Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { Chart.Legend.OverflowMode = ChartLegendOverflowMode.Scroll; } if (Device.RuntimePlatform != Device.macOS) { zoomPan.EnableDirectionalZooming = true; PropertyView = Resources["stackLayout"] as View; } ////transparentView.Focused += TransparentView_Focused; //var touchGesture = new TapGestureRecognizer(); //touchGesture.Tapped += (sender, e) => // { // transparentView.IsEnabled = false; // transparentView.IsVisible = false; // grid.Children.Remove(transparentView); // transparentView.Opacity = 0; // }; //transparentView.GestureRecognizers.Add(touchGesture); } private void EnableDirectionalZooming_Toggled(object sender, ToggledEventArgs e) { zoomPan.EnableDirectionalZooming = enableDirectionalZooming.IsToggled; } private void EnableSelectionZooming_Toggled(object sender, ToggledEventArgs e) { zoomPan.EnableSelectionZooming = enableSelectionZooming.IsToggled; } //void TransparentView_Focused(object sender, FocusEventArgs e) //{ // transparentView.IsEnabled = false; // transparentView.IsVisible = false; // grid.Children.Remove(transparentView); // transparentView.Opacity = 0; //} } }<file_sep>/Forms/ListView/ListView/Samples/Accordion/Helper/Behavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System.Linq; using Xamarin.Forms; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; using Syncfusion.ListView.XForms.Control.Helpers; namespace SampleBrowser.SfListView { class SfListViewAccordionBehavior : Behavior<SampleView> { #region Fields private Contact tappedItem; private Syncfusion.ListView.XForms.SfListView listview; #endregion #region Override Methods protected override void OnAttachedTo(SampleView bindable) { listview = bindable.FindByName<Syncfusion.ListView.XForms.SfListView>("listView"); listview.ItemTapped += ListView_ItemTapped; } protected override void OnDetachingFrom(BindableObject bindable) { listview.ItemTapped-= ListView_ItemTapped; } #endregion #region Private Methods private void ListView_ItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e) { if (tappedItem != null && tappedItem.IsVisible) { var previousIndex = listview.DataSource.DisplayItems.IndexOf(tappedItem); tappedItem.IsVisible = false; if (Device.RuntimePlatform != Device.macOS) Device.BeginInvokeOnMainThread(() => { listview.RefreshListViewItem(previousIndex, previousIndex, false); }); } if (tappedItem == (e.ItemData as Contact)) { if (Device.RuntimePlatform == Device.macOS) { var previousIndex = listview.DataSource.DisplayItems.IndexOf(tappedItem); Device.BeginInvokeOnMainThread(() => { listview.RefreshListViewItem(previousIndex, previousIndex, false); }); } tappedItem = null; return; } tappedItem = e.ItemData as Contact; tappedItem.IsVisible = true; if (Device.RuntimePlatform == Device.macOS) { var visibleLines = this.listview.GetVisualContainer().ScrollRows.GetVisibleLines(); var firstIndex = visibleLines[visibleLines.FirstBodyVisibleIndex].LineIndex; var lastIndex = visibleLines[visibleLines.LastBodyVisibleIndex].LineIndex; Device.BeginInvokeOnMainThread(() => { listview.RefreshListViewItem(firstIndex, lastIndex, false); }); } else { var currentIndex = listview.DataSource.DisplayItems.IndexOf(e.ItemData); Device.BeginInvokeOnMainThread(() => { listview.RefreshListViewItem(currentIndex, currentIndex, false); }); } } #endregion } } <file_sep>/Forms/Chat/Chat/Samples/Model/FlightBookingModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Microsoft.Bot.Schema; using System.Collections.Generic; namespace SampleBrowser.SfChat { /// <summary> /// A class contains necessary details to book flight. /// </summary> public class FlightBookingModel { /// <summary> /// Gets or sets the Destination country. /// </summary> public string DestinationCountry { get; set; } /// <summary> /// Gets or sets the Destination city. /// </summary> public string DestinationCity { get; set; } /// <summary> /// Gets or sets the airway. /// </summary> public string Airway { get; set; } /// <summary> /// Gets or sets the departure date. /// </summary> public string TravelDate { get; set; } /// <summary> /// Gets or sets the passenger count. /// </summary> public string MembersCount { get; set; } } /// <summary> /// A class contains the conversation details. /// </summary> public class Conversation { /// <summary> /// Gets or sets the conversation id. /// </summary> public string ConversationId { get; set; } /// <summary> /// Gets or sets the token. /// </summary> public string Token { get; set; } /// <summary> /// Gets or sets value indicates the connection expire time. /// </summary> public string Expires_in { get; set; } /// <summary> /// Gets or sets the stream url. /// </summary> public string StreamUrl { get; set; } } /// <summary> /// A class contains the conversation activities and water mark. /// </summary> public class ActivitySet { public List<Activity> Activities { get; set; } public string Watermark { get; set; } } } <file_sep>/Forms/PDF/PDF/Samples/DigitalSignatureValidation/DigitalSignatureValidation.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Security; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.PDF { public partial class DigitalSignatureValidation : SampleView { public DigitalSignatureValidation() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { this.textBlock.IsVisible = true; StringBuilder builder = new StringBuilder(); //Get the stream from the document #if COMMONSB Stream docStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.SignedDocument.pdf"); #else Stream docStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.SignedDocument.pdf"); #endif //Load an existing signed PDF document PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream); //Get signature field PdfLoadedSignatureField lSigFld = loadedDocument.Form.Fields[0] as PdfLoadedSignatureField; //X509Certificate2Collection to check the signer's identity using root certificates X509CertificateCollection collection = new X509CertificateCollection(); //Read the certificate file #if COMMONSB Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.PDF.pfx"); #else Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.PDF.pfx"); #endif byte[] data = new byte[certificateStream.Length]; certificateStream.Read(data, 0, data.Length); //Create new X509Certificate2 with the root certificate X509Certificate2 certificate = new X509Certificate2(data, "<PASSWORD>"); //Add the certificate to the collection collection.Add(certificate); //Validate signature and get the validation result PdfSignatureValidationResult result = lSigFld.ValidateSignature(collection); builder.AppendLine("Signature is " + result.SignatureStatus); builder.AppendLine(); builder.AppendLine("--------Validation Summary--------"); builder.AppendLine(); //Checks whether the document is modified or not bool isModified = result.IsDocumentModified; if (isModified) builder.AppendLine("The document has been altered or corrupted since the signature was applied."); else builder.AppendLine("The document has not been modified since the signature was applied."); //Signature details builder.AppendLine("Digitally signed by " + lSigFld.Signature.Certificate.IssuerName); builder.AppendLine("Valid From : " + lSigFld.Signature.Certificate.ValidFrom); builder.AppendLine("Valid To : " + lSigFld.Signature.Certificate.ValidTo); builder.AppendLine("Signature Algorithm : " + result.SignatureAlgorithm); builder.AppendLine("Hash Algorithm : " + result.DigestAlgorithm); //Revocation validation details builder.AppendLine("OCSP revocation status : " + result.RevocationResult.OcspRevocationStatus); if (result.RevocationResult.OcspRevocationStatus == RevocationStatus.None && result.RevocationResult.IsRevokedCRL) builder.AppendLine("CRL is revoked."); this.textBlock.Text = builder.ToString(); //Close the document loadedDocument.Close(true); } } } <file_sep>/Android/SampleBrowser/Samples/LinearGauge/Annotations.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Content.Res; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfLinearGauge; namespace SampleBrowser { public class Annotations : SamplePage { public static int pointervalue = 35; public override View GetSampleContent(Android.Content.Context con) { /**************** **Linear Gauge** ****************/ SfLinearGauge linearGauge = new SfLinearGauge(con); ObservableCollection<LinearScale> scales = new ObservableCollection<LinearScale>(); ObservableCollection<LinearPointer> pointers = new ObservableCollection<LinearPointer>(); ObservableCollection<LinearRange> ranges = new ObservableCollection<LinearRange>(); linearGauge.SetX(0); linearGauge.SetY(0); linearGauge.SetBackgroundColor(Color.Rgb(255, 255, 255)); linearGauge.SetOrientation(SfLinearGauge.Orientation.Horizontal); var density = con.Resources.DisplayMetrics.Density; //Annotation LinearGaugeAnnotation annotation = new LinearGaugeAnnotation(); annotation.ScaleValue = 15; annotation.ViewMargin = new PointF(0, 30); ImageView imageView = new ImageView(con); imageView.SetImageResource(Resource.Drawable.Low); LinearLayout layout = new LinearLayout(con); layout.LayoutParameters = new LinearLayout.LayoutParams((int)(80 * density), 60); layout.SetGravity(GravityFlags.Center); layout.AddView(imageView); annotation.View = layout; linearGauge.Annotations.Add(annotation); //Annotation1 LinearGaugeAnnotation annotation1 = new LinearGaugeAnnotation(); annotation1.ScaleValue = 45; annotation1.ViewMargin = new PointF(0, 30); ImageView imageView1 = new ImageView(con); imageView1.SetImageResource(Resource.Drawable.Moderate); LinearLayout layout1 = new LinearLayout(con); layout1.LayoutParameters = new LinearLayout.LayoutParams((int)(80 * density), 60); layout1.SetGravity(GravityFlags.Center); layout1.AddView(imageView1); annotation1.View = layout1; linearGauge.Annotations.Add(annotation1); //Annotation2 LinearGaugeAnnotation annotation2 = new LinearGaugeAnnotation(); annotation2.ScaleValue = 75; annotation2.ViewMargin = new PointF(0, 30); ImageView imageView2 = new ImageView(con); imageView2.SetImageResource(Resource.Drawable.High); LinearLayout layout2 = new LinearLayout(con); layout2.LayoutParameters = new LinearLayout.LayoutParams((int)(80 * density), 60); layout2.SetGravity(GravityFlags.Center); layout2.AddView(imageView2); annotation2.View = layout2; linearGauge.Annotations.Add(annotation2); //Annotation3 LinearGaugeAnnotation annotation3 = new LinearGaugeAnnotation(); annotation3.ScaleValue = 15; annotation3.ViewMargin = new PointF(0, 80); TextView text = new TextView(con); text.Text = "Low"; text.SetTextColor(Color.ParseColor("#30b32d")); LinearLayout layout3 = new LinearLayout(con); layout3.LayoutParameters = new LinearLayout.LayoutParams((int)(60 * density), 60); layout3.SetGravity(GravityFlags.Center); layout3.AddView(text); annotation3.View = layout3; linearGauge.Annotations.Add(annotation3); //Annotation4 LinearGaugeAnnotation annotation4 = new LinearGaugeAnnotation(); annotation4.ScaleValue = 45; annotation4.ViewMargin = new PointF(0, 80); TextView text1 = new TextView(con); text1.Text = "Moderate"; text1.SetTextColor(Color.ParseColor("#ffdd00")); LinearLayout layout4 = new LinearLayout(con); layout4.LayoutParameters = new LinearLayout.LayoutParams((int)(90 * density), 60); layout4.SetGravity(GravityFlags.Center); layout4.AddView(text1); annotation4.View = layout4; linearGauge.Annotations.Add(annotation4); //Annotation5 LinearGaugeAnnotation annotation5 = new LinearGaugeAnnotation(); annotation5.ScaleValue = 75; annotation5.ViewMargin = new PointF(0, 80); TextView text2 = new TextView(con); text2.Text = "High"; text2.SetTextColor(Color.ParseColor("#f03e3e")); LinearLayout layout5 = new LinearLayout(con); layout5.LayoutParameters = new LinearLayout.LayoutParams((int)(60 * density), 60); layout5.SetGravity(GravityFlags.Center); layout5.AddView(text2); annotation5.View = layout5; linearGauge.Annotations.Add(annotation5); //Annotation6 LinearGaugeAnnotation annotation6 = new LinearGaugeAnnotation(); annotation6.ScaleValue = 45; annotation6.ViewMargin = new PointF(0, -50); LinearLayout layout6 = new LinearLayout(con); layout6.LayoutParameters = new LinearLayout.LayoutParams((int)(200 * density), 100); layout6.SetGravity(GravityFlags.Center); layout6.AddView(new TextView(con) { Text = "CPU Utilization", TextSize = 20 }); annotation6.View = layout6; linearGauge.Annotations.Add(annotation6); //OuterScale LinearScale outerScale = new LinearScale(); outerScale.Minimum = 0; outerScale.Maximum = 90; outerScale.ShowLabels = false; outerScale.ScaleBarColor = Color.Transparent; outerScale.Offset = -50; outerScale.MinorTicksPerInterval = 1; outerScale.ScaleBarSize = 13; outerScale.ScaleDirection = LinearScaleDirection.Backward; //OuterScale MajorTicksSettings LinearTickSettings outerScale_majorTicksSettings = new LinearTickSettings(); outerScale_majorTicksSettings.Color = Color.Transparent; outerScale_majorTicksSettings.Length = 0; outerScale_majorTicksSettings.StrokeWidth = 1; outerScale.MajorTickSettings = outerScale_majorTicksSettings; //OuterScale MinorTicksSettings LinearTickSettings outerScale_minorTicksSettings = new LinearTickSettings(); outerScale_minorTicksSettings.Color = Color.Transparent; outerScale_minorTicksSettings.Length = 0; outerScale_minorTicksSettings.StrokeWidth = 1; outerScale.MinorTickSettings = outerScale_minorTicksSettings; //Symbol Pointer SymbolPointer outerScale_needlePointer = new SymbolPointer(); outerScale_needlePointer.Value = pointervalue; outerScale_needlePointer.StrokeWidth = 12; outerScale_needlePointer.Color = Color.Red; outerScale_needlePointer.MarkerShape = MarkerShape.InvertedTriangle; pointers.Add(outerScale_needlePointer); outerScale.Pointers = pointers; //Symbol Range LinearRange range = new LinearRange(); range.StartWidth = 60; range.EndWidth = 60; range.Color = Color.ParseColor("#30b32d"); range.StartValue = 0; range.EndValue = 30; ranges.Add(range); //Symbol Range1 LinearRange range1 = new LinearRange(); range1.StartWidth = 60; range1.EndWidth = 60; range1.Color = Color.ParseColor("#ffdd00"); range1.StartValue = 30; range1.EndValue = 60; ranges.Add(range1); //Symbol Range2 LinearRange range2 = new LinearRange(); range2.StartWidth = 60; range2.EndWidth = 60; range2.Color = Color.ParseColor("#f03e3e"); range2.StartValue = 60; range2.EndValue = 90; ranges.Add(range2); outerScale.Ranges = ranges; scales.Add(outerScale); linearGauge.Scales = scales; //Main Gauge Layout LinearLayout mainLinearGaugeLayout = new LinearLayout(con); mainLinearGaugeLayout.Orientation = Android.Widget.Orientation.Vertical; mainLinearGaugeLayout.SetBackgroundColor(Color.Rgb(255, 255, 255)); mainLinearGaugeLayout.SetGravity((GravityFlags)17); //Linear Gauge Layout LinearLayout linearGaugeLayout = new LinearLayout(con); linearGaugeLayout.SetGravity((GravityFlags)17); linearGaugeLayout.SetBackgroundColor(Color.Rgb(255, 255, 255)); mainLinearGaugeLayout.AddView(linearGaugeLayout); mainLinearGaugeLayout.AddView(linearGauge); return mainLinearGaugeLayout; } } }<file_sep>/Forms/Chart/Chart/Samples/VerticalChart/VerticalChartViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfChart { public class VerticalChartViewModel { public ObservableCollection<ChartDataModel> verticalChart { get; set; } private int count; private int index; public VerticalChartViewModel() { verticalChart = new ObservableCollection<ChartDataModel>(); } public void LoadVerticalData() { Random rand = new Random(); for (int j = 11; j < 50; j++) { verticalChart.Add(new ChartDataModel(j, rand.Next(-3, 3))); } index = (int)verticalChart[verticalChart.Count - 1].Value + 1; } private bool UpdateData() { count = count + 1; Random random = new Random(); if (count > 350) { return false; } else if (count > 300) { verticalChart.Add(new ChartDataModel(index, random.Next(0, 0))); } else if (count > 250) { verticalChart.Add(new ChartDataModel(index, random.Next(-2, 1))); } else if (count > 180) { verticalChart.Add(new ChartDataModel(index, random.Next(-3, 2))); } else if (count > 100) { verticalChart.Add(new ChartDataModel(index, random.Next(-7, 6))); } else { verticalChart.Add(new ChartDataModel(index, random.Next(-9, 9))); } index++; return true; } public async void StartTimer() { await Task.Delay(500); Device.StartTimer(new TimeSpan(0, 0, 0, 0, 10), UpdateData); } } } <file_sep>/Android/SampleBrowser/Samples/Schedule/Localization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Com.Syncfusion.Schedule; using Com.Syncfusion.Schedule.Enums; using Android.Views; using Android.Content; using Android.Widget; using System.Collections.Generic; using Android.Graphics; using Java.Util; namespace SampleBrowser { public class Localization : SamplePage, IDisposable { public Localization() { } private SfSchedule sfSchedule; private Spinner spinner; private LinearLayout propertylayout; public override View GetSampleContent(Context context) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; propertylayout = new LinearLayout(context); propertylayout = SetOptionPage(context); //creating instance for Schedule sfSchedule = new SfSchedule(context); sfSchedule.ScheduleView = ScheduleView.WeekView; sfSchedule.Locale = new Locale("fr"); SetFrenchCollectionSubjects(); SetChineseCollectionSubjects(); SetEnglishCollectionSubjects(); SetSpanishCollectionSubjects(); SetColors(); RandomNumbers(); SetStartTime(); SetEndTime(); sfSchedule.LayoutParameters = new FrameLayout.LayoutParams( LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); sfSchedule.ItemsSource = GetFrenchAppointments(); linearLayout.AddView(sfSchedule); return linearLayout; } private LinearLayout SetOptionPage(Context context) { TextView scheduleType_txtBlock = new TextView(context); scheduleType_txtBlock.Text = "Select the Locale"; scheduleType_txtBlock.TextSize = 20; scheduleType_txtBlock.SetPadding(0, 0, 0, 10); scheduleType_txtBlock.SetTextColor(Color.Black); LinearLayout layout = new LinearLayout(context); layout.SetPadding(15, 15, 15, 20); layout.Orientation = Android.Widget.Orientation.Vertical; layout.SetBackgroundColor(Color.White); spinner = new Spinner(context, SpinnerMode.Dialog); spinner.SetMinimumHeight(60); spinner.SetBackgroundColor(Color.Gray); spinner.DropDownWidth = 500; layout.AddView(scheduleType_txtBlock); layout.AddView(spinner); List<string> list = new List<string>(); list.Add("French"); list.Add("Spanish"); list.Add("English"); list.Add("Chinese"); ArrayAdapter<string> dataAdapter = new ArrayAdapter<string>(context, Android.Resource.Layout.SimpleSpinnerItem, list); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); spinner.Adapter = dataAdapter; spinner.ItemSelected += Spinner_ItemSelected; return layout; } private List<string> colorCollection; private List<Calendar> startTimeCollection; private List<Calendar> endTimeCollection; //Creating appointments for ScheduleAppointmentCollection private ScheduleAppointmentCollection GetFrenchAppointments() { ScheduleAppointmentCollection appointmentCollection = new ScheduleAppointmentCollection(); for (int i = 0; i < 10; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[i]); scheduleAppointment.Subject = frenchCollection[i]; scheduleAppointment.StartTime = startTimeCollection[i]; scheduleAppointment.EndTime = endTimeCollection[i]; appointmentCollection.Add(scheduleAppointment); } return appointmentCollection; } //Creating appointments for ScheduleAppointmentCollection private ScheduleAppointmentCollection GetSpanishAppointments() { ScheduleAppointmentCollection appointmentCollection = new ScheduleAppointmentCollection(); for (int i = 0; i < 10; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[i]); scheduleAppointment.Subject = spanishCollection[i]; scheduleAppointment.StartTime = startTimeCollection[i]; scheduleAppointment.EndTime = endTimeCollection[i]; appointmentCollection.Add(scheduleAppointment); } return appointmentCollection; } //Creating appointments for ScheduleAppointmentCollection private ScheduleAppointmentCollection GetEnglishAppointments() { ScheduleAppointmentCollection appointmentCollection = new ScheduleAppointmentCollection(); for (int i = 0; i < 10; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[i]); scheduleAppointment.Subject = englishCollection[i]; scheduleAppointment.StartTime = startTimeCollection[i]; scheduleAppointment.EndTime = endTimeCollection[i]; appointmentCollection.Add(scheduleAppointment); } return appointmentCollection; } //Creating appointments for ScheduleAppointmentCollection private ScheduleAppointmentCollection GetChineseAppointments() { ScheduleAppointmentCollection appointmentCollection = new ScheduleAppointmentCollection(); for (int i = 0; i < 10; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[i]); scheduleAppointment.Subject = chineseCollection[i]; scheduleAppointment.StartTime = startTimeCollection[i]; scheduleAppointment.EndTime = endTimeCollection[i]; appointmentCollection.Add(scheduleAppointment); } return appointmentCollection; } private List<string> englishCollection; private void SetEnglishCollectionSubjects() { englishCollection = new List<string>(); englishCollection.Add("GoToMeeting"); englishCollection.Add("Business Meeting"); englishCollection.Add("Conference"); englishCollection.Add("Project Status Discussion"); englishCollection.Add("Auditing"); englishCollection.Add("Client Meeting"); englishCollection.Add("Generate Report"); englishCollection.Add("Target Meeting"); englishCollection.Add("General Meeting"); englishCollection.Add("Pay House Rent"); englishCollection.Add("Car Service"); englishCollection.Add("Medical Check Up"); englishCollection.Add("Wedding Anniversary"); englishCollection.Add("Sam's Birthday"); englishCollection.Add("Jenny's Birthday"); englishCollection.Add("Master Checkup"); englishCollection.Add("Hospital"); englishCollection.Add("Phone Bill Payment"); englishCollection.Add("Project Plan"); englishCollection.Add("Auditing"); englishCollection.Add("Client Meeting"); englishCollection.Add("Generate Report"); englishCollection.Add("Target Meeting"); englishCollection.Add("General Meeting"); englishCollection.Add("Play Golf"); englishCollection.Add("Car Service"); englishCollection.Add("Medical Check Up"); englishCollection.Add("Mary's Birthday"); englishCollection.Add("John's Birthday"); englishCollection.Add("Micheal's Birthday"); } private List<string> frenchCollection; private void SetFrenchCollectionSubjects() { frenchCollection = new List<string>(); frenchCollection.Add("aller ‡ la rÈunion"); frenchCollection.Add("Un rendez-vous d'affaire"); frenchCollection.Add("ConfÈrence"); frenchCollection.Add("Discussion Projet de Statut"); frenchCollection.Add("audit"); frenchCollection.Add("RÈunion du client"); frenchCollection.Add("gÈnÈrer un rapport"); frenchCollection.Add("RÈunion cible"); frenchCollection.Add("AssemblÈe gÈnÈrale"); frenchCollection.Add("<NAME>"); frenchCollection.Add("Service automobile"); frenchCollection.Add("Visite mÈdicale"); frenchCollection.Add("Anniversaire de mariage"); frenchCollection.Add("Anniversaire de Sam"); frenchCollection.Add("Anniversaire de Jenny"); frenchCollection.Add("Checkup Master"); frenchCollection.Add("HÙpital"); frenchCollection.Add("TÈlÈphone paiement de factures"); frenchCollection.Add("Plan de projet"); frenchCollection.Add("audit"); frenchCollection.Add("RÈunion du client"); frenchCollection.Add("gÈnÈrer un rapport"); frenchCollection.Add("RÈunion cible"); frenchCollection.Add("AssemblÈe gÈnÈrale"); frenchCollection.Add("Jouer au golf"); frenchCollection.Add("Service automobile"); frenchCollection.Add("Visite mÈdicale"); frenchCollection.Add("Anniversaire de Marie"); frenchCollection.Add("Anniversaire de John"); frenchCollection.Add("Anniversaire de Micheal"); } private List<string> spanishCollection; private void SetSpanishCollectionSubjects() { spanishCollection = new List<string>(); spanishCollection.Add("Ir a la reuniÛn"); spanishCollection.Add("ReuniÛn de negocios"); spanishCollection.Add("Conferencia"); spanishCollection.Add("SituaciÛn del proyecto DiscusiÛn"); spanishCollection.Add("AuditorÌa"); spanishCollection.Add("ReuniÛn Cliente"); spanishCollection.Add("Generar informe"); spanishCollection.Add("ReuniÛn Target"); spanishCollection.Add("ReuniÛn general"); spanishCollection.Add("Pago Casa Alquilar"); spanishCollection.Add("Servicio de auto"); spanishCollection.Add("RevisiÛn mÈdica"); spanishCollection.Add("Aniversario de bodas"); spanishCollection.Add("CumpleaÒos de Sam"); spanishCollection.Add("El cumpleaÒos de Jenny"); spanishCollection.Add("Chequeo Maestro"); spanishCollection.Add("el Hospital"); spanishCollection.Add("TelÈfono pago de facturas"); spanishCollection.Add("Plan de proyecto"); spanishCollection.Add("AuditorÌa"); spanishCollection.Add("ReuniÛn Cliente"); spanishCollection.Add("Generar informe"); spanishCollection.Add("ReuniÛn Target"); spanishCollection.Add("ReuniÛn general"); spanishCollection.Add("Jugar golf"); spanishCollection.Add("Servicio de auto"); spanishCollection.Add("RevisiÛn mÈdica"); spanishCollection.Add("CumpleaÒos de MarÌa"); spanishCollection.Add("<NAME>"); spanishCollection.Add("El cumpleaÒos de Micheal"); } private List<string> chineseCollection; private void SetChineseCollectionSubjects() { chineseCollection = new List<string>(); chineseCollection.Add("进入会议"); chineseCollection.Add("商务会议"); chineseCollection.Add("会议"); chineseCollection.Add("项目状态讨论"); chineseCollection.Add("审计"); chineseCollection.Add("客户会议"); chineseCollection.Add("生成报告"); chineseCollection.Add("目标会议"); chineseCollection.Add("大会"); chineseCollection.Add("支付房租"); chineseCollection.Add("汽车服务"); chineseCollection.Add("体格检查"); chineseCollection.Add("结婚纪念日"); chineseCollection.Add("萨姆的生日"); chineseCollection.Add("珍妮的生日"); chineseCollection.Add("主诊"); chineseCollection.Add("医院"); chineseCollection.Add("电话缴费"); chineseCollection.Add("项目计划"); chineseCollection.Add("审计"); chineseCollection.Add("客户会议"); chineseCollection.Add("生成报告"); chineseCollection.Add("目标会议"); chineseCollection.Add("大会"); chineseCollection.Add("打高尔夫球"); chineseCollection.Add("汽车服务"); chineseCollection.Add("体格检查"); chineseCollection.Add("玛丽的生日"); chineseCollection.Add("约翰的生日"); chineseCollection.Add("迈克尔的生日"); } // adding colors collection private void SetColors() { colorCollection = new List<string>(); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); } private List<int> randomNums; private void RandomNumbers() { randomNums = new List<int>(); Java.Util.Random rand = new Java.Util.Random(); for (int i = 0; i < 30; i++) { int randomNum = rand.NextInt((15 - 9) + 1) + 9; randomNums.Add(randomNum); } } // adding StartTime collection private void SetStartTime() { startTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -5; i < 5; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count], 0, 0); startTimeCollection.Add(startTime); count++; } } // adding EndTime collection private void SetEndTime() { endTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -5; i < 5; i++) { Calendar endTime = (Calendar)currentDate.Clone(); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count] + 1, 0, 0); endTimeCollection.Add(endTime); count++; } } //Creating Spinner public override View GetPropertyWindowLayout(Context context) { return propertylayout; } private void Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { if (e.Position == 0) { sfSchedule.Locale = new Locale("fr"); sfSchedule.ItemsSource = GetFrenchAppointments(); } else if (e.Position == 1) { sfSchedule.Locale = new Locale("es"); sfSchedule.ItemsSource = GetSpanishAppointments(); } else if (e.Position == 2) { sfSchedule.Locale = new Locale("en-US"); sfSchedule.ItemsSource = GetEnglishAppointments(); } else if (e.Position == 3) { sfSchedule.Locale = new Locale("zh"); sfSchedule.ItemsSource = GetChineseAppointments(); } } public override void OnApplyChanges() { base.OnApplyChanges(); } public void Dispose() { if (sfSchedule != null) { sfSchedule.Dispose(); sfSchedule = null; } if (spinner != null) { spinner.ItemSelected -= Spinner_ItemSelected; spinner.Dispose(); spinner = null; } if (propertylayout != null) { propertylayout.Dispose(); propertylayout = null; } } } }<file_sep>/Android/SampleBrowser/Samples/TreeView/TreeSelection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Android.Widget; using Syncfusion.Android.TreeView; using Syncfusion.TreeView.Engine; namespace SampleBrowser { public class TreeSelection : SamplePage, IDisposable { private SfTreeView treeView; private CountriesViewModel viewModel; public override Android.Views.View GetSampleContent(Android.Content.Context context) { treeView = new SfTreeView(context, null); viewModel = new CountriesViewModel(); treeView.Indentation = 20; treeView.ExpanderWidth = 40; treeView.ItemHeight = 40; treeView.SelectionMode = SelectionMode.Multiple; treeView.AutoExpandMode = AutoExpandMode.RootNodesExpanded; treeView.ChildPropertyName = "States"; treeView.ItemsSource = viewModel.CountriesInfo; treeView.Adapter = new SelectionAdapter(); treeView.SelectedItems = viewModel.SelectedCountries; return treeView; } public override Android.Views.View GetPropertyWindowLayout(Android.Content.Context context) { Spinner spin = new Spinner(context, SpinnerMode.Dialog); List<String> adapter = new List<String>() { "Single", "Single/Deselect", "Multiple", "None" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerDropDownItem, adapter); spin.Adapter = dataAdapter; TextView txt = new TextView(context); txt.Text = "Choose Selection Mode"; txt.TextSize = 16f; txt.SetPadding(10, 10, 10, 10); spin.SetPadding(10, 10, 10, 10); spin.SetSelection(2); spin.ItemSelected += Spin_ItemSelected; LinearLayout prop = new LinearLayout(context); prop.Orientation = Orientation.Horizontal; prop.AddView(txt); prop.AddView(spin); LinearLayout linear = new LinearLayout(context); linear.Orientation = Orientation.Vertical; linear.AddView(prop); return linear; } private void Spin_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { if (e.Position == 0) { treeView.SelectionMode = SelectionMode.Single; } if (e.Position == 1) { treeView.SelectionMode = SelectionMode.SingleDeselect; } if (e.Position == 2) { treeView.SelectionMode = SelectionMode.Multiple; } if (e.Position == 3) { treeView.SelectionMode = SelectionMode.None; } } public void Dispose() { if (treeView != null) { treeView.Dispose(); treeView = null; } } } }<file_sep>/Forms/Schedule/Schedule/Samples/Resource/Behaviors/ResourceBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Resource Behavior class /// </summary> public class ResourceBehavior : Behavior<SampleView> { /// <summary> /// schedule initialize /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule schedule; /// <summary> /// view picker /// </summary> private Picker viewPicker; /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(SampleView bindable) { if (bindable == null) { return; } base.OnAttachedTo(bindable); this.schedule = bindable.Content.FindByName<Syncfusion.SfSchedule.XForms.SfSchedule>("Schedule"); if (Device.RuntimePlatform == Device.Android) { this.schedule.ViewHeaderStyle.DateFontSize = 24; } this.viewPicker = bindable.FindByName<Picker>("viewPicker"); if (this.viewPicker == null) { return; } this.viewPicker.SelectedIndex = 1; this.viewPicker.SelectedIndexChanged += this.ViewPicker_SelectedIndexChanged; } /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); if (this.viewPicker != null) { this.viewPicker.SelectedIndexChanged -= this.ViewPicker_SelectedIndexChanged; this.viewPicker = null; } if (this.schedule != null) { this.schedule = null; } } /// <summary> /// Method for schedule view selection /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void ViewPicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: this.schedule.ScheduleView = ScheduleView.DayView; break; case 1: this.schedule.ScheduleView = ScheduleView.WeekView; break; case 2: this.schedule.ScheduleView = ScheduleView.WorkWeekView; break; case 3: this.schedule.ScheduleView = ScheduleView.MonthView; break; case 4: this.schedule.ScheduleView = ScheduleView.TimelineView; break; } } } } <file_sep>/Forms/Chart/Chart/Samples/CategoryAxis/CategoryAxisViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using Xamarin.Forms; namespace SampleBrowser.SfChart { public class CategoryAxisViewModel { public ObservableCollection<ChartDataModel> CategoryData1 { get; set; } public ObservableCollection<ChartDataModel> CategoryData2 { get; set; } public CategoryAxisViewModel() { CategoryData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("South Korea", 39), new ChartDataModel("India", 20), new ChartDataModel("China", 65), }; CategoryData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("France", 45), new ChartDataModel("Italy", 16), new ChartDataModel("United Kingdom", 31) }; } } } <file_sep>/Forms/LinearGauge/LinearGauge/Samples/ScaleAndPointers/ScaleAndPointers.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfGauge.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfLinearGauge { [Preserve(AllMembers = true)] public partial class ScaleAndPointers : SampleView { public ScaleAndPointers() { InitializeComponent(); opposedPosition.SelectedIndex = 1; opposedPosition.SelectedIndexChanged += opposedPosition_SelectedIndexChanged; rangeCap.SelectedIndex = 1; rangeCap.SelectedIndexChanged += RangeCap_SelectedIndexChanged; markerShape.SelectedIndex = 0; markerShape.SelectedIndexChanged += MarkerShape_SelectedIndexChanged; } private void MarkerShape_SelectedIndexChanged(object sender, EventArgs e) { var picker = sender as Picker; if(gauge!=null) { switch (picker.SelectedIndex) { case 0: { (gauge.Scales[0].Pointers[1] as SymbolPointer).MarkerShape = MarkerShape.Triangle; } break; case 1: { (gauge.Scales[0].Pointers[1] as SymbolPointer).MarkerShape = MarkerShape.InvertedTriangle; } break; case 2: { (gauge.Scales[0].Pointers[1] as SymbolPointer).MarkerShape = MarkerShape.Circle; } break; case 3: { (gauge.Scales[0].Pointers[1] as SymbolPointer).MarkerShape = MarkerShape.Diamond; } break; case 4: { (gauge.Scales[0].Pointers[1] as SymbolPointer).MarkerShape = MarkerShape.Rectangle; } break; case 5: { (gauge.Scales[0].Pointers[1] as SymbolPointer).MarkerShape = MarkerShape.Image; } break; } } } private void RangeCap_SelectedIndexChanged(object sender, EventArgs e) { var picker = sender as Picker; if(gauge != null) { switch (picker.SelectedIndex) { case 0: { gauge.Scales[0].CornerRadiusType = Syncfusion.SfGauge.XForms.CornerRadiusType.Start; (gauge.Scales[0].Pointers[0] as BarPointer).CornerRadiusType = CornerRadiusType.Start; } break; case 1: { gauge.Scales[0].CornerRadiusType = Syncfusion.SfGauge.XForms.CornerRadiusType.End; (gauge.Scales[0].Pointers[0] as BarPointer).CornerRadiusType = CornerRadiusType.End; } break; case 2: { gauge.Scales[0].CornerRadiusType = CornerRadiusType.Both; (gauge.Scales[0].Pointers[0] as BarPointer).CornerRadiusType = CornerRadiusType.Both; } break; case 3: { gauge.Scales[0].CornerRadiusType = CornerRadiusType.None; (gauge.Scales[0].Pointers[0] as BarPointer).CornerRadiusType = CornerRadiusType.None; } break; default: break; } } } private void opposedPosition_SelectedIndexChanged(object sender, EventArgs e) { var picker = sender as Picker; if (gauge != null) { switch (picker.SelectedIndex) { case 0: gauge.Scales[0].OpposedPosition = true; break; case 1: gauge.Scales[0].OpposedPosition = false; break; default: break; } } } } }<file_sep>/Forms/ParallaxView/ParallaxView/Samples/Weather/WeatherViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfParallaxView { using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A ViewModel for PullToRefresh sample. /// </summary> public class WeatherViewModel : INotifyPropertyChanged { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private readonly Random randomNumber = new Random(); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<WeatherModel> selectedData; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ImageSource parallaxImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ImageSource buildingImage; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ImageSource cloudImage; private string weatherImage; private string[] weatherConditions = new string[] { "Heavy thunder", "Sunny", "Foggy", "Rainy", "Warm", "Cloudy","Snowfall" }; private string[] weatherdegrees = new string[] { "18", "40", "20", "25", "32", "28", "15" }; /// <summary> /// Initializes a new instance of the PullToRefreshViewModel class. /// </summary> public WeatherViewModel() { this.SelectedData = this.GetWeatherData(); Assembly assembly = typeof(WeatherViewModel).GetTypeInfo().Assembly; ParallaxImage = ImageSource.FromFile("pxcloud.png"); } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the value of Selected Data and notifies user when collection value gets changed. /// </summary> public ObservableCollection<WeatherModel> SelectedData { get { return this.selectedData; } set { this.selectedData = value; this.RaisePropertyChanged("SelectedData"); } } /// <summary> /// Generates weather data values /// </summary> /// <returns>data value</returns> private ObservableCollection<WeatherModel> GetWeatherData() { DateTime now = DateTime.Now; Assembly assembly = typeof(WeatherViewModel).GetTypeInfo().Assembly; ObservableCollection<WeatherModel> array = new ObservableCollection<WeatherModel>(); for (int i = 0; i < 7; i++) { now = DateTime.Now.AddDays(i); string date = string.Empty + now.DayOfWeek + ", " + string.Empty + now.ToString("MMMM") + " " + now.Date.Day; var temperature= weatherdegrees[i]; if (i == 0) { weatherImage = "Thunder.png"; } else if (i == 1) { weatherImage = "Sunny.png"; } else if (i == 2) { weatherImage = "Foggy.png"; } else if (i == 3) { weatherImage = "RainyWeather.png"; } else if (i == 4) { weatherImage = "CloudSunny.png"; } else if (i == 5) { weatherImage = "Weather.png"; } else if (i == 6) { weatherImage = "Snowfall.png"; } var weatherDetails = weatherConditions[i]; WeatherModel data = new WeatherModel(date,temperature, weatherImage,weatherDetails); array.Add(data); } return array; } /// <summary> /// Gets or sets the value of ImageName and notifies user when collection value gets changed. /// </summary> public ImageSource ParallaxImage { get { return this.parallaxImage; } set { this.parallaxImage = value; this.RaisePropertyChanged("ParallaxImage"); } } /// <summary> /// Gets or sets the value of ImageName and notifies user when collection value gets changed. /// </summary> public ImageSource BuildingImage { get { return this.buildingImage; } set { this.buildingImage = value; this.RaisePropertyChanged("BuildingImage"); } } /// <summary> /// Gets or sets the value of ImageName and notifies user when collection value gets changed. /// </summary> public ImageSource CloudImage { get { return this.cloudImage; } set { this.cloudImage = value; this.RaisePropertyChanged("CloudImage"); } } #region INotifyPropertyChanged /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name represent propertyName</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } } <file_sep>/Forms/DataGrid/DataGrid.iOS/PreviewControllerDS.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PreviewControllerDS.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed.")] namespace SampleBrowser.SfDataGrid.iOS { using System; using System.Diagnostics.CodeAnalysis; using QuickLook; /// <summary> /// A class that allows a QuickLook.QLPreviewController to preview multiple items. /// </summary> public class PreviewControllerDS : QLPreviewControllerDataSource { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private QLPreviewItem item; /// <summary> /// Initializes a new instance of the PreviewControllerDS class. /// </summary> /// <param name="item">QLPreviewItem type of item</param> public PreviewControllerDS(QLPreviewItem item) { this.item = item; } /// <summary> /// A UIKit.UIViewController that manages the user experience of previewing an item. /// </summary> /// <param name="controller">QLPreviewController type of controller parameter</param> /// <returns>returns the value of n integer type as 1</returns> public override nint PreviewItemCount(QLPreviewController controller) { return (nint)1; } /// <summary> /// Override method to get a item /// </summary> /// <param name="controller">QLPreviewController type of controller parameter</param> /// <param name="index">integer type of parameter index</param> /// <returns>returns PreviewControllerDS item value</returns> public override IQLPreviewItem GetPreviewItem(QLPreviewController controller, nint index) { return this.item; } } }<file_sep>/Forms/Chart/Chart/Samples/RangeAreaChart/RangeAreaSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class RangeAreaSeriesViewModel { public ObservableCollection<RangeSeriesBaseModel> RangeAreaData { get; set; } public ObservableCollection<RangeSeriesBaseModel> RangeAreaData1 { get; set; } public RangeAreaSeriesViewModel() { RangeAreaData = new ObservableCollection<RangeSeriesBaseModel> { new RangeSeriesBaseModel("Jan", 45, 32), new RangeSeriesBaseModel("Feb", 48, 34), new RangeSeriesBaseModel("Mar", 46, 32), new RangeSeriesBaseModel("Apr", 48, 36), new RangeSeriesBaseModel("May", 46, 32), new RangeSeriesBaseModel("Jun", 49, 34) }; RangeAreaData1 = new ObservableCollection<RangeSeriesBaseModel> { new RangeSeriesBaseModel("Jan", 30, 18), new RangeSeriesBaseModel("Feb", 24, 12), new RangeSeriesBaseModel("Mar", 29, 15), new RangeSeriesBaseModel("Apr", 24, 10), new RangeSeriesBaseModel("May", 30, 18), new RangeSeriesBaseModel("Jun", 24, 10) }; } } }<file_sep>/Android/SampleBrowser/Common/Adapters/RecyclerViewViewHolder.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Views; using Android.Widget; using AndroidX.RecyclerView.Widget; namespace SampleBrowser { public class RecyclerViewViewItemHolder : RecyclerView.ViewHolder { #region ctor public RecyclerViewViewItemHolder(View itemView, Action<TextView, int> listener) : base(itemView) { UpdateTagView = itemView.FindViewById<TextView>(Resource.Id.updateImage); SampleNameView = itemView.FindViewById<TextView>(Resource.Id.sampleName); itemView.Click += (sender, e) => listener(SampleNameView, AdapterPosition); } #endregion #region properties internal TextView UpdateTagView { get; set; } internal TextView SampleNameView { get; set; } #endregion } }<file_sep>/Forms/Calendar/Calendar/Samples/CalendarLocalization/ViewModel/LocalizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.ComponentModel; using Syncfusion.SfCalendar.XForms; using Xamarin.Forms; namespace SampleBrowser.SfCalendar { public class LocalizationViewModel : INotifyPropertyChanged { private CalendarEventCollection appointments; public event PropertyChangedEventHandler PropertyChanged; private ObservableCollection<Color> colorCollection; private ObservableCollection<string> meetingSubjectCollection; public CalendarEventCollection Appointments { get { return this.appointments; } set { this.appointments = value; this.OnPropertyChanged("Appointments"); } } private string locale = "zh-CN"; public string Locale { get { return this.locale; } set { this.locale = value; this.OnPropertyChanged("Locale"); } } public LocalizationViewModel() { this.Appointments = new CalendarEventCollection(); this.AddAppointmentDetails(); this.AddAppointments(); } private void AddAppointmentDetails() { meetingSubjectCollection = new ObservableCollection<string>(); if (this.locale == "zh-CN") { meetingSubjectCollection.Add("大会"); meetingSubjectCollection.Add("计划执行"); meetingSubjectCollection.Add("项目计划"); meetingSubjectCollection.Add("咨询"); meetingSubjectCollection.Add("支持"); meetingSubjectCollection.Add("发展会议"); meetingSubjectCollection.Add("争球"); meetingSubjectCollection.Add("项目完成"); meetingSubjectCollection.Add("发布更新"); meetingSubjectCollection.Add("性能检查"); } else if (this.locale == "es-AR") { meetingSubjectCollection.Add("Reunión general"); meetingSubjectCollection.Add("Ejecución del plan"); meetingSubjectCollection.Add("Plan de proyecto"); meetingSubjectCollection.Add("Consultante"); meetingSubjectCollection.Add("Apoyo"); meetingSubjectCollection.Add("Reunión de Desarrollo"); meetingSubjectCollection.Add("Melé"); meetingSubjectCollection.Add("Finalización del proyecto"); meetingSubjectCollection.Add("Actualizaciones de la versión"); meetingSubjectCollection.Add("Control de rendimiento"); } else if (this.locale == "en-US") { meetingSubjectCollection.Add("General Meeting"); meetingSubjectCollection.Add("Plan Execution"); meetingSubjectCollection.Add("Project Plan"); meetingSubjectCollection.Add("Consulting"); meetingSubjectCollection.Add("Support"); meetingSubjectCollection.Add("Development Meeting"); meetingSubjectCollection.Add("Scrum"); meetingSubjectCollection.Add("Project Completion"); meetingSubjectCollection.Add("Release updates"); meetingSubjectCollection.Add("Performance Check"); } else if (this.locale == "fr-CA") { meetingSubjectCollection.Add("Assemblée générale"); meetingSubjectCollection.Add("Exécution du plan"); meetingSubjectCollection.Add("Plan de projet"); meetingSubjectCollection.Add("Consultant"); meetingSubjectCollection.Add("Soutien"); meetingSubjectCollection.Add("Réunion de développement"); meetingSubjectCollection.Add("Scrum"); meetingSubjectCollection.Add("Achèvement du projet"); meetingSubjectCollection.Add("Mise à jour des mises à jour"); meetingSubjectCollection.Add("Contrôle de performance"); } colorCollection = new ObservableCollection<Color>(); colorCollection.Add(Color.FromHex("#FFA2C139")); colorCollection.Add(Color.FromHex("#FFD80073")); colorCollection.Add(Color.FromHex("#FF1BA1E2")); colorCollection.Add(Color.FromHex("#FFE671B8")); colorCollection.Add(Color.FromHex("#FFF09609")); colorCollection.Add(Color.FromHex("#FF339933")); colorCollection.Add(Color.FromHex("#FF00ABA9")); colorCollection.Add(Color.FromHex("#FFE671B8")); colorCollection.Add(Color.FromHex("#FF1BA1E2")); colorCollection.Add(Color.FromHex("#FFD80073")); colorCollection.Add(Color.FromHex("#FFA2C139")); colorCollection.Add(Color.FromHex("#FFA2C139")); colorCollection.Add(Color.FromHex("#FFD80073")); colorCollection.Add(Color.FromHex("#FF339933")); colorCollection.Add(Color.FromHex("#FFE671B8")); colorCollection.Add(Color.FromHex("#FF00ABA9")); } private void AddAppointments() { var today = DateTime.Now.Date; var random = new Random(); for (int month = -1; month < 2; month++) { for (int day = -5; day < 5; day++) { for (int count = 0; count < 1; count++) { var appointment = new CalendarInlineEvent(); appointment.Subject = meetingSubjectCollection[random.Next(7)]; appointment.Color = colorCollection[random.Next(10)]; appointment.StartTime = today.AddMonths(month).AddDays(random.Next(1, 28)).AddHours(random.Next(9, 18)); appointment.EndTime = appointment.StartTime.AddHours(2); this.Appointments.Add(appointment); } } } } private void OnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/Forms/NavigationDrawer/NavigationDrawer/Samples/NavigationDrawer_Main/ArchiveModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.Linq; namespace SampleBrowser { public class CollectionViewModel { public CollectionViewModel() { } private string name; private string date; private string subject; private string description; public string Name { get { return name; } set { name = value; } } public string Date { get { return date; } set { date = value; } } public string Subject { get { return subject; } set { subject = value; } } public string Description { get { return description; } set { description = value; } } } public class ArchiveViewModel { private string title = "Archive"; ObservableCollection<CollectionViewModel> viewCollection; public ObservableCollection<CollectionViewModel> ViewCollection { get { return viewCollection; } set { viewCollection = value; } } public string Title { get { return title; } set { title = value; } } public ArchiveViewModel() { viewCollection = new ObservableCollection<CollectionViewModel>(); for (int i = 0; i < SubjectArray.Count(); i++) { viewCollection.Add(new CollectionViewModel { Name = NameArray[i], Date = MonthArray[i] + " " + (i + 7).ToString(), Subject = SubjectArray[i], Description = DescriptionsArray[i] }); } } string[] NameArray = new string[] { "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" }; string[] MonthArray = new string[] { "Jan", "Jan", "Mar", "Apr", "May", "May", "May", "June", "July", "Sep", "Sep" }; string[] SubjectArray = new string[] { "Happy birthday to an amazing employee!", "Like a vintage auto, your value increases...", "No one could do a better job than...", "GET WELL SOON!!", "A cheery Christmas hold lots of happiness for you!", "BOO!!! Happy Halloween! Happy Halloween!", "Happy Turkey Day!!", "Wishing you Happy St Pat's Day!", "Congratulations on the move!", "Never doubt yourself. You’re always...", "The warmest wishes to a great member of our team...", }; string[] DescriptionsArray = new string[] { "Wishing you great achievements in this career, And I hope that you have a great day today!", "Happy birthday to one of the best and most loyal employees ever!", "No one could do a better job than the job you do. We thank you for sticking with us!", "Card messages aren't my thing. Get well soon!", "Wishing you a happy Christmas. May it be all that you hope it will be! All the best", "Wishing you a killer Halloween, Don't forget to give us treat or else..", "Happy Turkey Day!. Don't forget to give thanks for being so blessed.", "It's all green which means its all good! HAPPY ST PAT'S", "Congratulations! May you find great happiness at your new address.", "Never doubt yourself. You’re always the best! Just continue to be like that!", "Warmest wishes! May your special day be full of good emotions, fun and cheer!" }; } } <file_sep>/Android/SampleBrowser/Samples/ImageEditor/ProfileEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Syncfusion.SfImageEditor.Android; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Content; using Android.Content.PM; using Android.Graphics.Drawables; using Android.Views; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; using Android.Content.Res; using System.Text; namespace SampleBrowser { public class ProfileEditor : SamplePage { internal static Activity Activity { get; set; } View view { get; set; } public static ImageView ImageView { get; set; } Context con { get; set; } public override Android.Views.View GetSampleContent(Android.Content.Context context) { con = context; LayoutInflater layoutInflater = LayoutInflater.From(context); view = layoutInflater.Inflate(Resource.Layout.ImageEditorProfileEditor, null); Button button = view.FindViewById<Button>(Resource.Id.profileEditButton); ImageView = view.FindViewById<ImageView>(Resource.Id.profileImageView); button.Click += Button_Click; button.SetTextColor(Color.White); ListView listView = view.FindViewById<ListView>(Resource.Id.ProfileEditorListView); listView.Adapter = new ProfileEditorAdapter(ProfileFields.Fields); return view; } private void Button_Click(object sender, EventArgs e) { Activity = con as Activity; Activity?.StartActivity(typeof(ProfileEditorActivity)); } [Activity(Label = "SfImageEditor", ScreenOrientation = ScreenOrientation.Portrait, Icon = "@drawable/icon")] public class ProfileEditorActivity : Activity { SfImageEditor imageEditor; protected override void OnCreate(Bundle savedInstanceState) { imageEditor = new SfImageEditor(this); imageEditor.ToolbarSettings.ToolbarItemSelected += OnToolbarItemSelected; imageEditor.ImageSaving += ImageEditor_ImageSaving; imageEditor.ImageLoaded += ImageEditor_ImageLoaded; Android.Graphics.Drawables.BitmapDrawable bd = (Android.Graphics.Drawables.BitmapDrawable)ProfileEditor.ImageView.Drawable; imageEditor.Bitmap = bd.Bitmap; SetContentView(imageEditor); base.OnCreate(savedInstanceState); imageEditor.SetToolbarItemVisibility("Text, Shape, Brightness, Effects, Bradley Hand, Path, 3:1, 3:2, 4:3, 5:4, 16:9, Undo, Redo, Transform", false); // Add the custom tool bar items var item = new FooterToolbarItem() { Text = "Crop", TextHeight = 20, }; imageEditor.ToolbarSettings.ToolbarItems.Add(item); } private async void ImageEditor_ImageLoaded(object sender, ImageLoadedEventArgs e) { await System.Threading.Tasks.Task.Delay(25); imageEditor.ToggleCropping(true, 3); } private void ImageEditor_ImageSaving(object sender, ImageSavingEventArgs e) { e.Cancel = true; Bitmap bitmap = BitmapFactory.DecodeStream(e.Stream); ProfileEditor.ImageView.SetImageBitmap(bitmap); Finish(); } private void OnToolbarItemSelected(object sender, ToolbarItemSelectedEventArgs e) { if(e.ToolbarItem.Text=="Crop") { imageEditor.ToggleCropping(true, 3); e.Cancel = true; } } } public class ProfileEditorAdapter : BaseAdapter<ProfileModel> { List<ProfileModel> fields; public ProfileEditorAdapter(List<ProfileModel> collection) { this.fields = collection; } public override ProfileModel this[int position] { get { return fields[position]; } } public override int Count { get { return fields.Count; } } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { var view = convertView; view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.ImageEditorProfileListViewItem, parent, false); var photo = view.FindViewById<ImageView>(Resource.Id.photoImageView); var field = view.FindViewById<TextView>(Resource.Id.fieldTextView); var content = view.FindViewById<TextView>(Resource.Id.contentTextView); field.Text = fields[position].Field; content.Text = fields[position].Content; photo.SetBackgroundResource(fields[position].Icon); return view; } } public static class ProfileFields { public static List<ProfileModel> Fields { get; private set; } static ProfileFields() { Fields = new List<ProfileModel>(); AddFields(Fields); } static void AddFields(List<ProfileModel> fields) { fields.Add(new ProfileModel() { Field = "Name", Content = "<NAME>", Icon= Resource.Drawable.LabelContactName }); fields.Add(new ProfileModel() { Field = "Email", Content = "<EMAIL>", Icon= Resource.Drawable.Email }); fields.Add(new ProfileModel() { Field = "Phone", Content = "+1-123-456-7890", Icon= Resource.Drawable.Phone }); fields.Add(new ProfileModel() { Field = "Address", Content = "Avenue 2nd street, NW SY", Icon= Resource.Drawable.Address }); } } public class ProfileModel { public int Icon { get; set; } public string Field { get; set; } public string Content { get; set; } } } } <file_sep>/iOS/SampleBrowser/DataSource/AllControlsCollectionSource.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Foundation; using UIKit; namespace SampleBrowser { public class AllControlsCollectionSource : UICollectionViewDataSource { #region ctor public AllControlsCollectionSource(NSArray controls) { this.Controls = controls; } #endregion #region properties public NSArray Controls { get; set; } #endregion #region methods public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { var cell = (UICollectionViewCell)collectionView.DequeueReusableCell("controlCell", indexPath); cell.BackgroundColor = UIColor.White; cell.Layer.BorderWidth = 0.5f; cell.Layer.BorderColor = UIColor.FromRGB(221.0f / 255.0f, 221.0f / 255.0f, 221.0f / 255.0f).CGColor; Control item = Controls.GetItem<Control>((nuint)indexPath.Row); UIImageView imageView = (UIImageView)cell.ViewWithTag(200); imageView.Image = item.Image; imageView.Layer.BorderColor = UIColor.FromRGB(232.0f / 255.0f, 232.0f / 255.0f, 232.0f / 255.0f).CGColor; imageView.Layer.BorderWidth = 0.5f; UILabel lblTitle = (UILabel)cell.ViewWithTag(201); lblTitle.Text = string.IsNullOrEmpty(item.DisplayName) ? item.Name : item.DisplayName; UIImageView tag = (UIImageView)cell.ViewWithTag(205); if (item.Tag == "NEW") { tag.Image = new UIImage("Controls/Tags/new.png"); } else if (item.Tag == "UPDATED") { tag.Image = new UIImage("Controls/Tags/updated.png"); } else if (item.Tag == "PREVIEW") { tag.Image = new UIImage("Controls/Tags/preview.png"); } else { tag.Image = null; } UILabel desc = (UILabel)cell.ViewWithTag(202); desc.Text = item.Description; return cell; } public override nint GetItemsCount(UICollectionView collectionView, nint section) { return (nint)Controls.Count; } #endregion } public class AllControlsCollectionDelegate : UICollectionViewDelegate { #region ctor public AllControlsCollectionDelegate(HomeViewController controller) { this.Controller = controller; } #endregion #region properties public HomeViewController Controller { get; set; } #endregion #region methods public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath) { nuint row = (nuint)indexPath.Row; Control ctrl = Controller.Controls.GetItem<Control>(row); string sampleListPathString = NSBundle.MainBundle.BundlePath + "/plist/SampleList.plist"; NSDictionary sampleDict = new NSDictionary(); sampleDict = NSDictionary.FromFile(sampleListPathString); NSMutableArray dictArray = sampleDict.ValueForKey(new NSString(ctrl.Name)) as NSMutableArray; NSMutableArray collections = new NSMutableArray(); Control contrl = Controller.Controls.GetItem<Control>((nuint)indexPath.Row); for (nuint i = 0; i < dictArray.Count; i++) { NSDictionary dict = dictArray.GetItem<NSDictionary>(i); Control control = new Control { ControlName = ctrl.Name, Name = (NSString)dict.ValueForKey(new NSString("SampleName")), Description = (NSString)dict.ValueForKey(new NSString("Description")) }; NSString imageToLoad = (NSString)dict.ValueForKey(new NSString("Image")); if (imageToLoad != null) { control.Image = UIImage.FromBundle(imageToLoad); } if (dict.ValueForKey(new NSString("IsNew")) != null && dict.ValueForKey(new NSString("IsNew")).ToString().ToUpper() == "YES") { control.Tag = new NSString("NEW"); } else if (dict.ValueForKey(new NSString("IsUpdated")) != null && dict.ValueForKey(new NSString("IsUpdated")).ToString().ToUpper() == "YES") { control.Tag = new NSString("UPDATED"); } else if (dict.ValueForKey(new NSString("IsPreview")) != null && dict.ValueForKey(new NSString("IsPreview")).ToString().ToUpper() == "YES") { control.Tag = new NSString("PREVIEW"); } else { control.Tag = new NSString(string.Empty); } if (dict.ValueForKey(new NSString("DisplayName")) != null) { control.DisplayName = dict.ValueForKey(new NSString("DisplayName")) as NSString; } else { control.DisplayName = new NSString(string.Empty); } collections.Add(control); } this.Controller.NavigationItem.BackBarButtonItem = new UIBarButtonItem("Back", UIBarButtonItemStyle.Plain, null); if (ctrl.Name == "Chart") { ChartSamplesViewController sampleController = new ChartSamplesViewController { FeaturesCollections = collections, ControlName = contrl.Name, Types = contrl.Type1, Features = contrl.Type2 }; Controller.NavigationController.PushViewController(sampleController, true); } else { indexPath = NSIndexPath.FromRowSection(0, 0); SampleViewController controller = new SampleViewController(indexPath) { SamplesCollection = collections, ControlName = contrl.Name }; Controller.NavigationController.PushViewController(controller, true); } } #endregion } }<file_sep>/Forms/ListView/ListView/Samples/GridLayout/Model/GalleryInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewGalleryInfoRepository { #region Constructor public ListViewGalleryInfoRepository() { } #endregion #region GetGalleryInfo internal ObservableCollection<ListViewGalleryInfo> GetGalleryInfo() { var galleryInfo = new ObservableCollection<ListViewGalleryInfo>(); var random = new Random(); for (int i = 1; i <= 30; i++) { var gallery = new ListViewGalleryInfo() { Image = Images[i-1] + ".jpg", ImageTitle = random.Next(1242, 5383) + ".jpg", CreatedDate = GetCreatedDate(i), IsFavorite = i % 2 == 0 || i % 3 == 0 ? true : false }; galleryInfo.Add(gallery); } return galleryInfo; } private string GetCreatedDate(int pos) { if (pos <= 4) return CreatedDates[0]; else if (pos <= 8) return CreatedDates[1]; else if (pos <= 11) return CreatedDates[2]; else if (pos <= 16) return CreatedDates[3]; else if (pos <= 23) return CreatedDates[4]; return CreatedDates[5]; } #endregion #region GelleryInfo string[] CreatedDates = new string[] { "This Week", "Last Week", "Two Weeks Ago", "Three Weeks Ago", "Last Month", "Older", }; string[] Images = new string[] { "DadSon", "Guitar", "Van", "City", "Ladybug", "Minitoys", "Friends", "Spices1", "Chocolate", "Kids", "BrownCat", "Toys", "CollegeGirl", "Radio", "Playing", "Hight", "Train", "Peacock", "Spices2", "IdealHouse", "Calculation", "Dog", "Sports", "Openbook", "Money", "Violin", "Car", "Bell", "Listeningmusic", "Horse", }; #endregion } } <file_sep>/Forms/RangeSlider/RangeSlider/Samples/RangeSlider/RangeSlider_Tablet.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfRangeSlider.XForms; using Xamarin.Forms; namespace SampleBrowser.SfRangeSlider { public partial class RangeSlider_Tablet : SampleView { StackLayout view; Button closeButton; Label placementLabel, emptyLabel, tickLabel; Picker positionPicker1, positionPicker2; Switch toggleButton; bool tooltip = true; int label = 1, tick = 1; public RangeSlider_Tablet() { InitializeComponent(); getPropertiesWindow(); RangeChangeEvent(); DeviceChanges(); if (App.Current.MainPage != null && App.Current.MainPage.Visual == VisualMarker.Material) { this.SetMaterialValues(sfRangeSlider1); this.SetMaterialValues(sfRangeSlider2); } } public void getPropertiesWindow() { view = new StackLayout(); view.HeightRequest = Property_Windows.HeightRequest; view.BackgroundColor = Color.FromRgb(250, 250, 250); StackLayout propertyLayout = new StackLayout(); propertyLayout.Orientation = StackOrientation.Horizontal; propertyLayout.BackgroundColor = Color.FromRgb(230, 230, 230); propertyLayout.Padding = new Thickness(10, 0, 0, 0); TapGestureRecognizer tab = new TapGestureRecognizer(); tab.Tapped += tab_Tapped; propertyLayout.GestureRecognizers.Add(tab); Label propertyLabel = new Label(); propertyLabel.Text = "OPTIONS"; propertyLabel.WidthRequest = 150; propertyLabel.VerticalOptions = LayoutOptions.Center; propertyLabel.HorizontalOptions = LayoutOptions.Start; propertyLabel.FontFamily = "Helvetica"; propertyLabel.FontSize = 18; closeButton = new Button(); if (Device.RuntimePlatform == Device.iOS) { closeButton.Text = "X"; closeButton.TextColor = Color.FromRgb(51, 153, 255); } else if (Device.RuntimePlatform == Device.Android) { closeButton.ImageSource = "cancelsearch.png"; }else{ closeButton.ImageSource = "sfclosebutton.png"; } closeButton.Clicked += Close_Button; closeButton.HorizontalOptions = LayoutOptions.EndAndExpand; propertyLayout.Children.Add(propertyLabel); propertyLayout.Children.Add(closeButton); temp.BackgroundColor = Color.FromRgb(230, 230, 230); closeButton.BackgroundColor = Color.FromRgb(230, 230, 230); Property_Button.BackgroundColor = Color.FromRgb(230, 230, 230); StackLayout placementLayout = new StackLayout(); placementLayout.Orientation = StackOrientation.Horizontal; placementLayout.Padding = new Thickness(40, 0, 0, 20); placementLabel = new Label(); placementLabel.Text = "Tick Placement"; placementLabel.WidthRequest = 250; placementLabel.VerticalOptions = LayoutOptions.Center; placementLabel.HorizontalOptions = LayoutOptions.End; placementLabel.FontFamily = "Helvetica"; placementLabel.FontSize = 16; positionPicker1 = new Picker(); positionPicker1.WidthRequest = 150; positionPicker1.VerticalOptions = LayoutOptions.Center; positionPicker1.HorizontalOptions = LayoutOptions.Start; positionPicker1.Items.Add("TopLeft"); positionPicker1.Items.Add("BottomRight"); positionPicker1.Items.Add("Inline"); positionPicker1.Items.Add("Outside"); positionPicker1.Items.Add("None"); positionPicker1.SelectedIndex = tick; positionPicker1.SelectedIndexChanged += picker1_SelectedIndexChanged; placementLayout.Children.Add(placementLabel); placementLayout.Children.Add(positionPicker1); StackLayout labelLayout = new StackLayout(); labelLayout.Orientation = StackOrientation.Horizontal; labelLayout.Padding = new Thickness(40, 0, 0, 20); tickLabel = new Label(); tickLabel.Text = "Label Placement"; tickLabel.WidthRequest = 250; tickLabel.VerticalOptions = LayoutOptions.Center; tickLabel.HorizontalOptions = LayoutOptions.End; tickLabel.FontFamily = "Helvetica"; tickLabel.FontSize = 16; positionPicker2 = new Picker(); positionPicker2.Items.Add("TopLeft"); positionPicker2.Items.Add("BottomRight"); positionPicker2.SelectedIndex = label; positionPicker2.WidthRequest = 150; positionPicker2.VerticalOptions = LayoutOptions.Center; positionPicker2.HorizontalOptions = LayoutOptions.Start; positionPicker2.SelectedIndexChanged += picker2_SelectedIndexChanged; labelLayout.Children.Add(tickLabel); labelLayout.Children.Add(positionPicker2); StackLayout layoutLabel = new StackLayout(); layoutLabel.Orientation = StackOrientation.Horizontal; layoutLabel.Padding = new Thickness(40, 0, 0, 20); emptyLabel = new Label(); emptyLabel.Text = "Show Label"; emptyLabel.WidthRequest = 250; emptyLabel.HorizontalOptions = LayoutOptions.End; emptyLabel.VerticalOptions = LayoutOptions.Center; emptyLabel.FontFamily = "Helvetica"; emptyLabel.FontSize = 16; toggleButton = new Switch(); toggleButton.Toggled += toggleStateChanged; toggleButton.IsToggled = tooltip; toggleButton.HorizontalOptions = LayoutOptions.Start; toggleButton.VerticalOptions = LayoutOptions.Center; layoutLabel.Children.Add(emptyLabel); layoutLabel.Children.Add(toggleButton); StackLayout emptyLayout = new StackLayout(); emptyLayout.Orientation = StackOrientation.Vertical; emptyLayout.BackgroundColor = Color.FromRgb(250, 250, 250); emptyLayout.Padding = new Thickness(40, 20, 40, 40); if (Device.RuntimePlatform == Device.iOS) emptyLayout.Padding = new Thickness(170, 20, 40, 40); emptyLayout.Children.Add(placementLayout); emptyLayout.Children.Add(labelLayout); emptyLayout.Children.Add(layoutLabel); view.Children.Add(propertyLayout); view.Children.Add(emptyLayout); Property_Windows.Children.Remove(temp); //Property_Windows.Children.Insert(0, view); } void RangeChangeEvent() { TapGestureRecognizer tap_Gestue_Prob = new TapGestureRecognizer(); tap_Gestue_Prob.Tapped += tap_Gestue_Prob_Tapped; temp.GestureRecognizers.Add(tap_Gestue_Prob); sfRangeSlider1.RangeChanging += (object sender, RangeEventArgs e) => { if (Math.Round(e.Start) < 1) { if (Math.Round(e.End) == 12) timeLabel3.Text = "12 AM - " + Math.Round(e.End) + " PM"; else timeLabel3.Text = "12 AM - " + Math.Round(e.End) + " AM"; } else { if (Math.Round(e.End) == 12) timeLabel3.Text = Math.Round(e.Start) + " AM - " + Math.Round(e.End) + " PM"; else timeLabel3.Text = Math.Round(e.Start) + " AM - " + Math.Round(e.End) + " AM"; } if (Math.Round(e.Start) == Math.Round(e.End)) { if (Math.Round(e.Start) < 1) timeLabel3.Text = "12 AM"; else if (Math.Round(e.Start) == 12) timeLabel3.Text = "12 PM"; else timeLabel3.Text = Math.Round(e.Start) + " AM"; } }; sfRangeSlider2.RangeChanging += (object sender, RangeEventArgs e) => { if (Math.Round(e.Start) < 1) { if (Math.Round(e.End) == 12) timeLabel4.Text = "12 AM - " + Math.Round(e.End) + " PM"; else timeLabel4.Text = "12 AM - " + Math.Round(e.End) + " AM"; } else { if (Math.Round(e.End) == 12) timeLabel4.Text = Math.Round(e.Start) + " AM - " + Math.Round(e.End) + " PM"; else timeLabel4.Text = Math.Round(e.Start) + " AM - " + Math.Round(e.End) + " AM"; } if (Math.Round(e.Start) == Math.Round(e.End)) { if (Math.Round(e.Start) < 1) timeLabel4.Text = "12 AM"; else if (Math.Round(e.Start) == 12) timeLabel4.Text = "12 PM"; else timeLabel4.Text = Math.Round(e.Start) + " AM"; } }; } public void Property_Button_Click(object c, EventArgs e) { getPropertiesWindow(); } void picker1_SelectedIndexChanged(object sender, EventArgs e) { switch (positionPicker1.SelectedIndex) { case 0: { sfRangeSlider1.TickPlacement = TickPlacement.TopLeft; sfRangeSlider2.TickPlacement = TickPlacement.TopLeft; tick = 0; break; } case 1: { sfRangeSlider1.TickPlacement = TickPlacement.BottomRight; sfRangeSlider2.TickPlacement = TickPlacement.BottomRight; tick = 1; break; } case 2: { sfRangeSlider1.TickPlacement = TickPlacement.Inline; sfRangeSlider2.TickPlacement = TickPlacement.Inline; tick = 2; break; } case 3: { sfRangeSlider1.TickPlacement = TickPlacement.Outside; sfRangeSlider2.TickPlacement = TickPlacement.Outside; tick = 3; break; } case 4: { sfRangeSlider1.TickPlacement = TickPlacement.None; sfRangeSlider2.TickPlacement = TickPlacement.None; tick = 4; break; } } } void picker2_SelectedIndexChanged(object sender, EventArgs e) { switch (positionPicker2.SelectedIndex) { case 0: { sfRangeSlider1.ValuePlacement = ValuePlacement.TopLeft; sfRangeSlider2.ValuePlacement = ValuePlacement.TopLeft; label = 0; break; } case 1: { sfRangeSlider1.ValuePlacement = ValuePlacement.BottomRight; sfRangeSlider2.ValuePlacement = ValuePlacement.BottomRight; label = 1; break; } } } void DeviceChanges() { if (Device.RuntimePlatform == Device.Android) { timeLabel5.FontSize = 12; timeLabel5.Text = " Time: "; timeLabel5.HeightRequest = 20; timeLabel5.TextColor = Color.FromHex("#939394"); timeLabel6.FontSize = 12; timeLabel6.Text = " Time: "; timeLabel6.HeightRequest = 20; departureLabel.Text = " Departure"; departureLabel.HeightRequest = 20; arrivalLabel.Text = " Arrival"; arrivalLabel.HeightRequest = 20; } else if (Device.RuntimePlatform == Device.iOS) { if (App.Current.MainPage != null) { if (App.Current.MainPage.Visual != VisualMarker.Material) { sfRangeSlider1.KnobColor = Color.White; sfRangeSlider2.KnobColor = Color.White; } } else { sfRangeSlider1.KnobColor = Color.White; sfRangeSlider2.KnobColor = Color.White; } sfRangeSlider1.TrackThickness = 2; sfRangeSlider2.TrackThickness = 2; timeLabel5.FontSize = 12; timeLabel5.Text = " Time: "; timeLabel5.HeightRequest = 20; timeLabel5.TextColor = Color.FromHex("#939394"); timeLabel6.FontSize = 12; timeLabel6.Text = " Time: "; timeLabel6.HeightRequest = 20; timeLabel6.TextColor = Color.FromHex("#939394"); departureLabel.Text = " Departure"; departureLabel.HeightRequest = 20; departureLabel.TextColor = Color.Black; arrivalLabel.Text = " Arrival"; arrivalLabel.HeightRequest = 20; arrivalLabel.TextColor = Color.Black; } else { if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { sfRangeSlider1.KnobColor = Color.Black; sfRangeSlider2.KnobColor = Color.Black; } timeLabel6.FontSize = 12; timeLabel6.Text = "Time: "; timeLabel6.HeightRequest = 20; timeLabel5.FontSize = 12; timeLabel5.Text = "Time: "; timeLabel5.HeightRequest = 20; departureLabel.Text = "Departure"; departureLabel.HeightRequest = 20; arrivalLabel.Text = "Arrival"; arrivalLabel.HeightRequest = 2; } if (Device.RuntimePlatform == Device.Android) { if (positionPicker1 != null && positionPicker2 != null && placementLabel != null && emptyLabel != null) { positionPicker1.BackgroundColor = Color.FromRgb(239, 239, 239); positionPicker2.BackgroundColor = Color.FromRgb(239, 239, 239); } } if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { sampleLayout.Padding = new Thickness(10, 0, 10, 0); sampleLayout1.Padding = new Thickness(0, 0, 10, 0); sampleLayout2.Padding = new Thickness(0, 0, 10, 0); } Property_Button.Clicked += Property_Button_Click; } void toggleStateChanged(object sender, ToggledEventArgs e) { sfRangeSlider1.ShowValueLabel = e.Value; sfRangeSlider2.ShowValueLabel = e.Value; tooltip = e.Value; } void tab_Tapped(object sender, EventArgs e) { closeAction(); } public void closeAction() { view.BackgroundColor = Color.White; Property_Windows.Children.Add(temp); Property_Windows.Children.Remove(view); } void tap_Gestue_Prob_Tapped(object sender, EventArgs e) { getPropertiesWindow(); } public View getContent() { return this.Content; } public void Close_Button(object c, EventArgs e) { closeAction(); } /// <summary> /// Set the color values for material /// </summary> /// <param name="rangeSlider"></param> private void SetMaterialValues(Syncfusion.SfRangeSlider.XForms.SfRangeSlider rangeSlider) { if (Device.RuntimePlatform != Device.UWP) { rangeSlider.LabelColor = Color.FromRgba(0, 0, 0, 200); rangeSlider.TickPlacement = TickPlacement.Inline; } } } } <file_sep>/Forms/Chart/Chart/Samples/MultipleCircle/MultipleCircle.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class MultipleCircle : SampleView { public MultipleCircle() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { if (Device.Idiom != TargetIdiom.Phone) { legend.DockPosition = LegendPlacement.Right; Chart.Margin = new Thickness(200, 0, 200, 0); doughnutSeries.Spacing = 0.5; legend.OverflowMode = ChartLegendOverflowMode.Scroll; } } else if (Device.RuntimePlatform == Device.macOS) { legend.OverflowMode = ChartLegendOverflowMode.Scroll; } List<Color> colors = new List<Color>() { Color.FromHex("47ba9f"), Color.FromHex("e58870"), Color.FromHex("9686c9"), Color.FromHex("e56590") }; colorModel.CustomBrushes = colors; } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { if (height > 0 && width > 0) { if (height > width) { Chart.Legend.DockPosition = LegendPlacement.Bottom; legend.OverflowMode = ChartLegendOverflowMode.Wrap; stack.Orientation = StackOrientation.Horizontal; } else { stack.Orientation = StackOrientation.Vertical; Chart.Title.Margin = new Thickness(0); Chart.Legend.DockPosition = LegendPlacement.Right; legend.OverflowMode = ChartLegendOverflowMode.Scroll; } } } } } public class IndexToItemSourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return value; } return new ObservableCollection<object>() { (value as ChartLegendItem).DataPoint }; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }<file_sep>/iOS/SampleBrowser/Samples/XlsIO/ImportXMLData.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XlsIO; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Xml; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class ImportXMLData : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; public ImportXMLData() { label = new UILabel (); label1 = new UILabel (); button = new UIButton (UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to import XML data into Excel workbook."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); } label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width , 50); this.AddSubview (label); button.SetTitle("Generate Excel",UIControlState.Normal); button.Frame = new CGRect(0, 65, frameRect.Location.X + frameRect.Size.Width , 10); this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook //A new workbook is created.[Equivalent to creating a new workbook in MS Excel] //The new workbook will have 1 worksheets IWorkbook workbook = application.Workbooks.Create(1); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; Assembly assembly = Assembly.GetExecutingAssembly (); Stream fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.customers.xml"); // Import the XML contents to worksheet XlsIOExtensions exten = new XlsIOExtensions(); exten.ImportXML(fileStream, sheet, 1, 1, true); // Apply style for header IStyle headerStyle = sheet[1, 1, 1, sheet.UsedRange.LastColumn].CellStyle; headerStyle.Font.Bold = true; headerStyle.Font.Color = ExcelKnownColors.Brown; headerStyle.Font.Size = 10; // Resize columns sheet.Columns[0].ColumnWidth = 11; sheet.Columns[1].ColumnWidth = 30.5; sheet.Columns[2].ColumnWidth = 20; sheet.Columns[3].ColumnWidth = 25.6; sheet.Columns[6].ColumnWidth = 10.5; sheet.Columns[4].ColumnWidth = 40; sheet.Columns[5].ColumnWidth = 25.5; sheet.Columns[7].ColumnWidth = 9.6; sheet.Columns[8].ColumnWidth = 15; sheet.Columns[9].ColumnWidth = 15; #endregion workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("ImportXML.xlsx", "application/msexcel", stream); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/Android/SampleBrowser/Samples/DocIO/BuiltInStyle.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public partial class BuiltInStyle : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to format the Word document contents with the built-in styles."; text1.SetPadding(5, 5, 5, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { // Creating a new document. WordDocument document = new WordDocument(); WSection section = document.AddSection() as WSection; //Set Margin of the section section.PageSetup.Margins.All = 72; WParagraph para = section.AddParagraph() as WParagraph; section.AddColumn(100, 100); section.AddColumn(100, 100); section.MakeColumnsEqual(); #region Built-in styles # region List Style //List //para = section.AddParagraph() as WParagraph; para.AppendText("This para is written with style List").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.List); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //List5 style para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style List5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.List5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region ListNumber Style //List Number style para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListNumber").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListNumber); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //List Number5 style para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListNumber5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListNumber5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region TOA Heading Style //TOA Heading para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style TOA Heading").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ToaHeading); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion para = section.AddParagraph() as WParagraph; section.BreakCode = SectionBreakCode.NewColumn; # region ListBullet Style //ListBullet para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListBullet").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListBullet); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //ListBullet5 para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListBullet5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListBullet5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region List Continue Style //ListContinue para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListContinue").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListContinue); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); //ListContinue5 para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style ListContinue5").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.ListContinue5); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion # region HTMLSample Style //HtmlSample para = section.AddParagraph() as WParagraph; para.AppendText("\nThis para is written with style HtmlSample").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.HtmlSample); para.AppendText("Google Chrome\n"); para.AppendText("Mozilla Firefox\n"); para.AppendText("Internet Explorer"); # endregion section = document.AddSection() as WSection; section.BreakCode = SectionBreakCode.NoBreak; # region Document Map Style //Docuemnt Map para = section.AddParagraph() as WParagraph; para.AppendText("This para is written with style DocumentMap\n").CharacterFormat.UnderlineStyle = Syncfusion.Drawing.UnderlineStyle.Double; para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.DocumentMap); IWTextRange textrange = para.AppendText("Google Chrome\n"); textrange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; textrange = para.AppendText("Mozilla Firefox\n"); textrange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; textrange = para.AppendText("Internet Explorer"); textrange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; #endregion # region Heading Styles //Heading Styles para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading1); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading2); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading3); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading4); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading5); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading6); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading7); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading8); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); para = section.AddParagraph() as WParagraph; para.ApplyStyle(BuiltinStyle.Heading9); para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString()); # endregion #endregion Built-in styles #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("BuiltInStyle.docx", "application/msword", stream, m_context); } #endregion } } } <file_sep>/Forms/Chart/Chart/Samples/Trendlines/TrendlineViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; namespace SampleBrowser.SfChart { public class TrendlineViewModel :INotifyPropertyChanged { private ObservableCollection<ChartDataModel> dataCollection; public ObservableCollection<ChartDataModel> DataCollection { get { return dataCollection; } set { dataCollection = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("DataCollection")); } } private double interval = 10; public double Interval { get { return interval; } set { interval = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Interval")); } } private ObservableCollection<ChartDataModel> linearDataCollection { get; set; } private ObservableCollection<ChartDataModel> exponentialDataCollection { get; set; } private ObservableCollection<ChartDataModel> logarithmicDataCollection { get; set; } private ObservableCollection<ChartDataModel> polynomialDataCollection { get; set; } public ObservableCollection<ChartDataModel> PowerDataCollection { get; set; } private int selectedIndex = 0; public event PropertyChangedEventHandler PropertyChanged; public int SelectedIndex { get { return selectedIndex; } set { selectedIndex = value; OnIndexChanged(value); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedIndex")); } } private ChartTrendlineType type = ChartTrendlineType.Linear; public ChartTrendlineType TrendlineType { get { return type; } set { if(type != value) { type = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TrendlineType")); } } } private bool isVisible = true; public bool IsVisible { get { return isVisible; } set { if (isVisible != value) { isVisible = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsVisible")); } } } private bool isEnable = false; public bool IsEnable { get { return isEnable; } set { if (isEnable != value) { isEnable = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsEnable")); } } } private string label = "Linear"; public string Label { get { return label; } set { if (label != value) { label = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Label")); } } } private void OnIndexChanged(int value) { IsEnable = false; if (value == 0) { Label = "Linear"; TrendlineType = ChartTrendlineType.Linear; DataCollection = linearDataCollection; Interval = 10; } else if (value == 1) { Label = "Exponential"; TrendlineType = ChartTrendlineType.Exponential; DataCollection = exponentialDataCollection; Interval = 100; } else if (value == 2) { Label = "Logarithmic"; TrendlineType = ChartTrendlineType.Logarithmic; DataCollection = logarithmicDataCollection; Interval = 50; } else if (value == 4) { TrendlineType = ChartTrendlineType.Polynomial; Label = "Polynomial"; DataCollection = polynomialDataCollection; IsEnable = true; Interval = 50; } if (value == 3) { IsVisible = false; } else { IsVisible = true; } } public TrendlineViewModel() { PowerDataCollection = new ObservableCollection<ChartDataModel>(); var date = new DateTime(2019, 03, 01); int x = 20; linearDataCollection = new ObservableCollection<ChartDataModel>(); exponentialDataCollection = new ObservableCollection<ChartDataModel>(); for (int i = 0; i < 8; i++) { linearDataCollection.Add(new ChartDataModel(date, x)); x += 5; date = date.AddMonths(1); } date = new DateTime(2019, 03, 01); x = 250; for (int i = 0; i < 8; i++) { exponentialDataCollection.Add(new ChartDataModel(date, x)); x += 50; date = date.AddMonths(1); } date = new DateTime(2019, 03, 30); logarithmicDataCollection = new ObservableCollection<ChartDataModel>() { new ChartDataModel(date, 98), new ChartDataModel(date.AddMonths(1),110), new ChartDataModel(date.AddMonths(2),200), new ChartDataModel(date.AddMonths(3),250), new ChartDataModel(date.AddMonths(4),289), new ChartDataModel(date.AddMonths(5),300), new ChartDataModel(date.AddMonths(6),310), new ChartDataModel(date.AddMonths(7),330), }; date = new DateTime(2019, 3, 01); polynomialDataCollection = new ObservableCollection<ChartDataModel>() { new ChartDataModel(date, 55), new ChartDataModel(date.AddMonths(1), 135), new ChartDataModel(date.AddMonths(2),128), new ChartDataModel(date.AddMonths(3),120), new ChartDataModel(date.AddMonths(4),135), new ChartDataModel(date.AddMonths(5),98), new ChartDataModel(date.AddMonths(6),120), new ChartDataModel(date.AddMonths(7),85), }; DataCollection = linearDataCollection; PowerDataCollection.Add(new ChartDataModel(1, 10)); PowerDataCollection.Add(new ChartDataModel(2, 50)); PowerDataCollection.Add(new ChartDataModel(3, 80)); PowerDataCollection.Add(new ChartDataModel(4, 110)); PowerDataCollection.Add(new ChartDataModel(5, 180)); PowerDataCollection.Add(new ChartDataModel(6, 220)); PowerDataCollection.Add(new ChartDataModel(7, 300)); PowerDataCollection.Add(new ChartDataModel(8, 370)); } } } <file_sep>/Forms/ParallaxView/ParallaxView/Samples/ParallaxView/ParallaxViewViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.Generic; using System.ComponentModel; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.Reflection; namespace SampleBrowser.SfParallaxView { [Preserve(AllMembers = true)] public class ParallaxViewViewModel : INotifyPropertyChanged { #region Properties internal List<ParallaxViewModel> Items { get; set; } public event PropertyChangedEventHandler PropertyChanged; #region Speed private double speed; public double Speed { get { return speed; } set { speed = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Speed")); } } } #endregion Speed #endregion Properties #region Methods internal List<ParallaxViewModel> GetItemSource() { Items = new List<ParallaxViewModel>() { new ParallaxViewModel() { Name = "Thriller", Author = "<NAME> - 10 Tracks",Tracks="10 Tracks" }, new ParallaxViewModel() { Name = "Like a Prayer", Author = "Madonna - 1 Tracks" ,Tracks="1 Tracks" }, new ParallaxViewModel() { Name = "When Doves Cry", Author = "Prince - 60 Tracks",Tracks="60 Tracks" }, new ParallaxViewModel() { Name = "I Wanna Dance", Author = "<NAME> - 70 Tracks",Tracks="70 Tracks" }, new ParallaxViewModel() { Name = "It’s Gonna Be Me", Author = "N Sync - 10 Tracks",Tracks="10 Tracks" }, new ParallaxViewModel() { Name = "Everybody", Author = "Backstreet Boys - 4 Tracks",Tracks="4 Tracks" }, new ParallaxViewModel() { Name = "Rolling in the Deep", Author = "Adele - 25 Tracks" ,Tracks="25 Tracks" }, new ParallaxViewModel() { Name = "Don’t Stop Believing", Author = "Journey - 10 Tracks" ,Tracks="10 Tracks" }, new ParallaxViewModel() { Name = "<NAME>", Author = "<NAME> - 5 Tracks",Tracks="5 Tracks" }, new ParallaxViewModel() { Name = "Sorry", Author = "<NAME> - 1 Tracks",Tracks="1 Tracks" }, new ParallaxViewModel() { Name = "Firework", Author = "<NAME> - 6 Tracks",Tracks="6 Tracks" }, new ParallaxViewModel() { Name = "The A Team", Author = "<NAME> - 8 Tracks" ,Tracks="8 Tracks"}, new ParallaxViewModel() { Name = "Thriller", Author = "<NAME> - 3 Tracks" ,Tracks="3 Tracks"}, new ParallaxViewModel() { Name = "<NAME>ayer", Author = "Madonna - 40 Tracks" ,Tracks="40 Tracks"}, new ParallaxViewModel() { Name = "When Doves Cry", Author = "Prince - 10 Tracks",Tracks="10 Tracks" }, new ParallaxViewModel() { Name = "I Wanna Dance", Author = "<NAME> - 2 Tracks",Tracks="2 Tracks" }, new ParallaxViewModel() { Name = "It’s Gonna Be Me", Author = "N Sync - 11 Tracks" ,Tracks="11 Tracks"}, new ParallaxViewModel() { Name = "Everybody", Author = "Backstreet Boys - 15 Tracks",Tracks="15 Tracks" }, new ParallaxViewModel() { Name = "Rolling in the Deep", Author = "Adele - 18 Tracks" ,Tracks="18 Tracks"}, new ParallaxViewModel() { Name = "Don’t Stop Believing", Author = "Journey - 35 Tracks",Tracks="35 Tracks" }, }; Assembly assembly = typeof(ParallaxViewViewModel).GetTypeInfo().Assembly; Items[0].Image = ImageSource.FromFile("Singing_round.png"); Items[1].Image = ImageSource.FromFile("Dancing_round.png"); Items[2].Image = ImageSource.FromFile("Drum_round.png"); Items[3].Image = ImageSource.FromFile("Microphone_round.png"); Items[4].Image = ImageSource.FromFile("CassetteTape_round.png"); Items[5].Image = ImageSource.FromFile("ElectronicDrum_round.png"); Items[6].Image = ImageSource.FromFile("PlayingViolin_round.png"); Items[7].Image = ImageSource.FromFile("MusicSheet_round.png"); Items[8].Image = ImageSource.FromFile("Radio_round.png"); Items[9].Image = ImageSource.FromFile("Headset_round.png"); Items[10].Image = ImageSource.FromFile("Listeningmusic_round.png"); Items[11].Image = ImageSource.FromFile("Mic_round.png"); Items[12].Image = ImageSource.FromFile("Singing_round.png"); Items[13].Image = ImageSource.FromFile("Dancing_round.png"); Items[14].Image = ImageSource.FromFile("Drum_round.png"); Items[15].Image = ImageSource.FromFile("Microphone_round.png"); Items[16].Image = ImageSource.FromFile("CassetteTape_round.png"); Items[17].Image = ImageSource.FromFile("ElectronicDrum_round.png"); Items[18].Image = ImageSource.FromFile("PlayingViolin_round.png"); Items[19].Image = ImageSource.FromFile("MusicSheet_round.png"); return Items; } #endregion Methods } } <file_sep>/Android/SampleBrowser/MainActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content; using Android.Widget; using Android.OS; using System.Xml; using System.Collections.Generic; using Android.Telephony; using Android.Content.PM; using Android.Content.Res; using System.Linq; using AndroidX.DrawerLayout.Widget; using AndroidX.Core.View; namespace SampleBrowser { [Activity(Label = "Essential Studio", ScreenOrientation = ScreenOrientation.Portrait, Theme = "@style/PropertyApp", Icon = "@drawable/icon")] public class MainActivity : Activity { #region fields private GridView listView; private LinearLayout drawer; private ImageView imageView; private List<SampleModel> controls; private DrawerLayout drawerLayout; private LinearLayout productpage, documentationPage, whatsNewPage; #endregion #region properties public static Intent SelectedIntent { get; set; } public static MainActivity BaseActivity { get; set; } public static float Factor { get; set; } public static float Density { get; set; } internal static bool IsTablet { get; set; } #endregion #region methods public static bool GetDeviceType(Context context) { return (context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) >= ScreenLayout.SizeLarge; } public override void OnBackPressed() { Finish(); base.OnBackPressed(); } protected void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e) { var intent = new Intent(this, typeof(AllControlsSamplePage)); SelectedIntent = intent; intent.PutExtra("sample", controls[e.Position]); StartActivity(intent); } protected override void OnCreate(Bundle bundle) { Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(string.Empty); float deviceDenstiy = Resources.DisplayMetrics.Density; Density = deviceDenstiy; Factor = deviceDenstiy / 2.55f; base.OnCreate(bundle); ParseXML(); if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { controls.Remove(controls.First(x => x.Title == "PDFViewer")); } SetContentView(Resource.Layout.HomeScreen); ActionBar.Hide(); listView = FindViewById<GridView>(Resource.Id.List); BaseActivity = this; listView.Adapter = new HomeScreenAdapter(this, controls); listView.ItemClick += OnListItemClick; IsTablet = GetDeviceType(this); if (IsTablet) { listView.SetNumColumns(2); } else { listView.SetNumColumns(1); } drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout); drawer = FindViewById<LinearLayout>(Resource.Id.left_drawer); imageView = FindViewById<ImageView>(Resource.Id.navDrawIcon); productpage = FindViewById<LinearLayout>(Resource.Id.productpagelayout); documentationPage = FindViewById<LinearLayout>(Resource.Id.documentlayout); whatsNewPage = FindViewById<LinearLayout>(Resource.Id.whatsnewlayout); var versionText = FindViewById<TextView>(Resource.Id.versionText); versionText.Text = versionText.Text + Resources.GetString(Resource.String.version); drawer.BringToFront(); int width = Resources.DisplayMetrics.WidthPixels * 3 / 4; if (IsTablet) { width = int.Parse((Resources.DisplayMetrics.WidthPixels * 0.5f).ToString()); } drawer.LayoutParameters.Width = (int)width; imageView.Click += delegate { drawerLayout.OpenDrawer(GravityCompat.Start); }; productpage.Click += delegate { GoToUrl("https://www.syncfusion.com/products/xamarin"); }; documentationPage.Click += delegate { GoToUrl("https://help.syncfusion.com/xamarin-android/introduction/overview"); }; whatsNewPage.Click += delegate { GoToUrl("https://www.syncfusion.com/products/whatsnew/xamarin-android"); }; } protected override void OnSaveInstanceState(Bundle outState) { outState.PutInt("tab", this.ActionBar.SelectedNavigationIndex); base.OnSaveInstanceState(outState); } private void GoToUrl(string url) { var intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(url)); StartActivity(intent); } private void ParseXML() { var xtr = Resources.GetXml(Resource.Xml.samplelist); xtr.Read(); bool featuresamplescompleted = false, controlsamplecompleted = false; while (!xtr.EOF && xtr.Name != null) { var groups = new List<SampleModel>(); xtr.Read(); if (xtr.Name == "FeatureSamples" && !xtr.IsStartElement()) { break; } xtr.Read(); while (!featuresamplescompleted) { if (xtr.Name == "Sample" && xtr.IsStartElement()) { var tc = new SampleModel(); SetSample(tc, xtr); xtr.Read(); xtr.Read(); } if (xtr.Name == "FeatureSamples" && !xtr.IsStartElement()) { featuresamplescompleted = true; xtr.Read(); } } if (xtr.Name == "ControlSamples" && xtr.IsStartElement()) { xtr.Read(); while (!controlsamplecompleted) { bool grouped = false; while (!grouped) { if (xtr.Name == "Group" && xtr.IsStartElement()) { var group = new ControlModel(); SetSample(group, xtr); xtr.Read(); var samples = new List<SampleModel>(); var features = new List<SampleModel>(); bool samplescompleted = false, featurescompleted = false; while (!samplescompleted || !featurescompleted) { if (xtr.Name == "Samples" && xtr.IsStartElement()) { xtr.Read(); while (!samplescompleted) { if (xtr.Name == "Sample" && xtr.IsStartElement()) { var tc = new SampleModel(); SetSample(tc, xtr); samples.Add(tc); xtr.Read(); xtr.Read(); } if (xtr.Name == "Samples" && !xtr.IsStartElement()) { samplescompleted = true; xtr.Read(); } } } if (xtr.Name == "Features" && xtr.IsStartElement()) { xtr.Read(); while (!featurescompleted) { if (xtr.Name == "Feature" && xtr.IsStartElement()) { var tc = new SampleModel(); SetSample(tc, xtr); features.Add(tc); xtr.Read(); xtr.Read(); } if (xtr.Name == "Features" && !xtr.IsStartElement()) { featurescompleted = true; xtr.Read(); } } } if (xtr.Name == "Group" && !xtr.IsStartElement()) { grouped = true; groups.Add(group); xtr.Read(); featurescompleted = true; samplescompleted = true; group.Samples = samples; group.Features = features; } if (xtr.Name == "ControlSamples" && !xtr.IsStartElement()) { controlsamplecompleted = true; } } } } } } xtr.Read(); if (xtr.Name == "SampleList" && !xtr.IsStartElement()) { xtr.Read(); } controls = groups; } xtr.Close(); } private static void SetSample(SampleModel sample, XmlReader reader) { reader.MoveToAttribute("Name"); sample.Name = GetValueFromReader(reader); reader.MoveToAttribute("Title"); sample.Title = GetValueFromReader(reader); reader.MoveToAttribute("Description"); sample.Description = GetValueFromReader(reader); reader.MoveToAttribute("Type"); if (reader.Name == "Type") { sample.Type = GetValueFromReader(reader); } reader.MoveToAttribute("ImageId"); if (reader.Name == "ImageId") { sample.ImageId = GetValueFromReader(reader); } } private static string GetValueFromReader(XmlReader reader) { return reader.Value ?? null; } #endregion } }<file_sep>/Forms/TreeView/TreeView/Samples/Selection/Model/CityInfoModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using System.ComponentModel; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public class Country : INotifyPropertyChanged { #region Feilds private bool isSelected; private string name; private ObservableCollection<State> states; #endregion #region Constructor public Country() { } #endregion #region Properties public ObservableCollection<State> States { get { return states; } set { states = value; RaisedOnPropertyChanged("States"); } } public string Name { get { return name; } set { name = value; RaisedOnPropertyChanged("Name"); } } public bool IsSelected { get { return isSelected; } set { isSelected = value; RaisedOnPropertyChanged("IsSelected"); } } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } [Preserve(AllMembers = true)] public class State : INotifyPropertyChanged { #region Feilds private bool isSelected; private string name; private ObservableCollection<City> cities; #endregion #region Constructor public State() { } #endregion #region Properties public ObservableCollection<City> Cities { get { return cities; } set { cities = value; RaisedOnPropertyChanged("States"); } } public string Name { get { return name; } set { name = value; RaisedOnPropertyChanged("Name"); } } public bool IsSelected { get { return isSelected; } set { isSelected = value; RaisedOnPropertyChanged("IsSelected"); } } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } [Preserve(AllMembers = true)] public class City : INotifyPropertyChanged { #region Feilds private bool isSelected; private string name; #endregion #region Constructor public City() { } #endregion #region Properties public string Name { get { return name; } set { name = value; RaisedOnPropertyChanged("Name"); } } public bool IsSelected { get { return isSelected; } set { isSelected = value; RaisedOnPropertyChanged("IsSelected"); } } #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } } <file_sep>/Forms/Schedule/Schedule/Samples/Timetable/ViewModel/TimetableViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Time table View Model class /// </summary> [Preserve(AllMembers = true)] public class TimetableViewModel : INotifyPropertyChanged { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="TimetableViewModel" /> class. /// </summary> public TimetableViewModel() { this.Appointments = new ScheduleAppointmentCollection(); this.InitializingAppointmentData(); NonAccessibleBlocksCollection = new NonAccessibleBlocksCollection(); var lunch = new NonAccessibleBlock(); lunch.StartTime = 12; lunch.EndTime = 13; lunch.Text = "Lunch Break"; NonAccessibleBlocksCollection.Add(lunch); this.NonAccessibleBlocks = NonAccessibleBlocksCollection; } #endregion Constructor #region Properties #region Property Changed Event /// <summary> /// Property changed event handler /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets appointment collection /// </summary> public ScheduleAppointmentCollection Appointments { get; set; } /// <summary> /// Gets or sets subject collection /// </summary> internal List<string> SubjectCollection { get; set; } /// <summary> /// Gets or sets start time collection /// </summary> internal List<DateTime> StartTimeCollection { get; set; } /// <summary> /// Gets or sets end time collection /// </summary> internal List<DateTime> EndTimeCollection { get; set; } /// <summary> /// Gets or sets non accessible blocks collection /// </summary> internal NonAccessibleBlocksCollection NonAccessibleBlocksCollection { get; set; } /// <summary> /// Gets or sets non accessible blocks /// </summary> internal NonAccessibleBlocksCollection NonAccessibleBlocks { get; set; } #endregion Properties /// <summary> /// Initialize the appointment /// </summary> public void InitializingAppointmentData() { this.SetSubjects(); this.SetStartTime(); this.SetEndTime(); } /// <summary> /// subject collection /// </summary> internal void SetSubjects() { this.SubjectCollection = new List<string>(); this.SubjectCollection.Add("Wellness"); this.SubjectCollection.Add("Language Arts"); this.SubjectCollection.Add("Mathematics"); this.SubjectCollection.Add("Social Studies"); this.SubjectCollection.Add("Physical Education"); this.SubjectCollection.Add("Geography"); } /// <summary> /// Start time collection /// </summary> internal void SetStartTime() { //appointment1 this.StartTimeCollection = new List<DateTime>(); var currentDate1 = DateTime.Now.Date; var startTime1 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 9, 1, 0); // appointment2 var startTime2 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 10, 1, 0); //appointment3 var startTime3 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 11, 11, 0); //appointment4 var startTime4 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 13, 1, 0); // appointment5 var startTime5 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 14, 1, 0); // appointment6 var startTime6 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 15, 11, 0); this.StartTimeCollection.Add(startTime1); this.StartTimeCollection.Add(startTime2); this.StartTimeCollection.Add(startTime3); this.StartTimeCollection.Add(startTime4); this.StartTimeCollection.Add(startTime5); this.StartTimeCollection.Add(startTime6); } /// <summary> /// End time collection /// </summary> internal void SetEndTime() { this.EndTimeCollection = new List<DateTime>(); // appointment1 var currentDate1 = DateTime.Now.Date; var endTime1 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 10, 0, 0); // appointment2 var endTime2 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 11, 0, 0); //appointment3 var endTime3 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 12, 0, 0); //appointment4 var endTime4 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 14, 0, 0); // appointment5 var endTime5 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 15, 0, 0); // appointment6 var endTime6 = new DateTime(currentDate1.Year, currentDate1.Month, currentDate1.Day, 16, 0, 0); this.EndTimeCollection.Add(endTime1); this.EndTimeCollection.Add(endTime2); this.EndTimeCollection.Add(endTime3); this.EndTimeCollection.Add(endTime4); this.EndTimeCollection.Add(endTime5); this.EndTimeCollection.Add(endTime6); } /// <summary> /// Color collection /// </summary> /// <param name="subject">subject value</param> /// <returns>color value</returns> internal Color GetColors(string subject) { if (subject == "Wellness") { return Color.FromHex("#FFA2C139"); } else if (subject == "Language Arts") { return Color.FromHex("#FFD80073"); } else if (subject == "Mathematics") { return Color.FromHex("#FFE671B8"); } else if (subject == "Social Studies") { return Color.FromHex("#FF1BA1E2"); } else if (subject == "Physical Education") { return Color.FromHex("#FF00ABA9"); } else { return Color.FromHex("#FF339933"); } } /// <summary> /// Staff collection /// </summary> /// <param name="subject">subject value</param> /// <returns>color value</returns> internal string GetStaff(string subject) { if (subject == "Wellness") { return "Mr. Jamison"; } else if (subject == "Language Arts") { return "Ms. Casey"; } else if (subject == "Mathematics") { return "Mr. Percorino"; } else if (subject == "Social Studies") { return "Ms. Gawade"; } else if (subject == "Physical Education") { return "Mr. Shilling"; } else { return "Mr. <NAME>"; } } /// <summary> /// Invoke method when property changed /// </summary> /// <param name="propertyName">property name</param> private void RaiseOnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }<file_sep>/Forms/Chat/Chat/Samples/FlightBooking/FlightBooking.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfChat { [XamlCompilation(XamlCompilationOptions.Compile)] /// <summary> /// A sampleView that contains the flight booking sample. /// </summary> public partial class FlightBooking : SampleView { /// <summary> /// Initializes a new instance of <see cref="FlightBooking"/>. /// </summary> public FlightBooking() { InitializeComponent(); } /// <summary> /// Raises when <see cref="FlightBooking"/> page disappears. /// </summary> public override void OnDisappearing() { base.OnDisappearing(); this.viewModel.Bot = null; if (this.sfChat != null) { this.sfChat.Dispose(); this.sfChat = null; } if(this.busyindicator != null) { this.busyindicator = null; } } } }<file_sep>/Forms/PdfViewer/PdfViewer.UWP/Renderer/CustomStampEffectUWP.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.SfPdfViewer.UWP; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; using SolidColorBrush = Windows.UI.Xaml.Media.SolidColorBrush; [assembly:ResolutionGroupName("SampleBrowser.SfPdfViewer")] [assembly:ExportEffect(typeof(CustomStampEffect), nameof(CustomStampEffect))] namespace SampleBrowser.SfPdfViewer.UWP { public class CustomStampEffect : PlatformEffect { protected override void OnAttached() { Control.PointerEntered += Control_PointerEntered; Control.PointerExited += Control_PointerExited; } private void Control_PointerExited(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e) { (Control as Border).Background = new SolidColorBrush(Windows.UI.Color.FromArgb(0, 0, 0, 0)); } private void Control_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e) { (Control as Border).Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 233, 233, 233)); } protected override void OnDetached() { } } } <file_sep>/Android/SampleBrowser/Samples/BusyIndicator/BusyIndicator_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.Content; using Android.Views; using Android.Widget; using Com.Syncfusion.Sfbusyindicator; using Android.Graphics; using Com.Syncfusion.Sfbusyindicator.Enums; using Android.Util; namespace SampleBrowser { public class BusyIndicator_Tab : SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ int animationSpinnerPosition = 0, totalWidth = 0; SfBusyIndicator sfBusyIndicator; TextView animationTypeText; Spinner animationSpinner; Context con; Context context1; int width; TextView showBusyText; Spinner showBusySpinner; private void showBusyLayout() { showBusyText = new TextView(context1); showBusyText.TextSize = 20; showBusyText.SetPadding(0,0,0,20); showBusyText.Text = "Animation Types"; showBusySpinner = new Spinner(context1, SpinnerMode.Dialog); //View Mode List List<String> animationList = new List<String>(); animationList.Add("Ball"); animationList.Add("Battery"); animationList.Add("DoubleCircle"); animationList.Add("ECG"); animationList.Add("Globe"); animationList.Add("HorizontalPulsingBox"); animationList.Add("MovieTimer"); animationList.Add("Print"); animationList.Add("Rectangle"); animationList.Add("RollingBall"); animationList.Add("SingleCircle"); animationList.Add("SlicedCircle"); animationList.Add("ZoomingTarget"); animationList.Add("Gear"); //Data Adapter ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context1, Android.Resource.Layout.SimpleSpinnerItem, animationList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); showBusySpinner.Adapter = dataAdapter; //Mode Spinner Item Selected Listener showBusySpinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(animationSpinner_ItemSelected); } public override View GetPropertyWindowLayout(Context context) { context1 = context; width = (context.Resources.DisplayMetrics.WidthPixels) / 2; showBusyLayout(); /****************** **propertylayout** ******************/ //Separator LinearLayout.LayoutParams separatorLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); separatorLayoutParams.SetMargins(0, 20, 0, 0); SeparatorView separate = new SeparatorView(context1, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; propertylayout.AddView(showBusyText); showBusyText.SetPadding(0,10,0,30); propertylayout.AddView(showBusySpinner); return propertylayout; } public override View GetSampleContent(Context con1) { con = con1; //sfBusyIndicator sfBusyIndicator = new SfBusyIndicator(con); sfBusyIndicator.IsBusy = true; sfBusyIndicator.TextColor = Color.Rgb(62, 101, 254); sfBusyIndicator.AnimationType = AnimationTypes.Ball; sfBusyIndicator.ViewBoxWidth = 150; sfBusyIndicator.ViewBoxHeight = 150; sfBusyIndicator.TextSize = 60; sfBusyIndicator.Title = ""; sfBusyIndicator.SetBackgroundColor(Color.Rgb(255, 255, 255)); FrameLayout mainView = new FrameLayout(con); mainView.AddView(sfBusyIndicator); return mainView; } private void AnimationModeLayout() { /********************* **Animation Mode** *********************/ animationSpinner = new Spinner(con,SpinnerMode.Dialog); animationSpinner.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); animationSpinner.SetMinimumHeight(60); animationSpinner.DropDownWidth = 500; animationSpinner.SetSelection(animationSpinnerPosition); animationSpinner.SetBackgroundColor(Color.Gray); //Animation List List<String> animationList = new List<String>(); animationList.Add("Ball"); animationList.Add("Battery"); animationList.Add("DoubleCircle"); animationList.Add("ECG"); animationList.Add("Globe"); animationList.Add("HorizontalPulsingBox"); animationList.Add("MovieTimer"); animationList.Add("Print"); animationList.Add("Rectangle"); animationList.Add("RollingBall"); animationList.Add("SingleCircle"); animationList.Add("SlicedCircle"); animationList.Add("ZoomingTarget"); animationList.Add("Gear"); //Data Adapter ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (con, Android.Resource.Layout.SimpleSpinnerItem, animationList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); animationSpinner.Adapter = dataAdapter; animationSpinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(animationSpinner_ItemSelected); //Animation Text animationTypeText = new TextView(con); animationTypeText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); animationTypeText.TextSize = 15; animationTypeText.Text = "Animation Types"; } /***************************************** **Animation Spinner ItemSelected Method** *****************************************/ private void animationSpinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner animationSpinner = (Spinner)sender; animationSpinnerPosition = e.Position; String selectedItem = animationSpinner.GetItemAtPosition(e.Position).ToString(); if (selectedItem.Equals("Ball")) { sfBusyIndicator.Duration = 1000; sfBusyIndicator.TextColor = Color.ParseColor("#243FD9"); sfBusyIndicator.AnimationType = AnimationTypes.Ball; } else if (selectedItem.Equals("Battery")) { sfBusyIndicator.Duration = 300; sfBusyIndicator.TextColor = Color.ParseColor("#A70015"); sfBusyIndicator.AnimationType = AnimationTypes.Battery; } else if (selectedItem.Equals("DoubleCircle")) { sfBusyIndicator.Duration = 1400; sfBusyIndicator.TextColor = Color.ParseColor("#958C7B"); sfBusyIndicator.AnimationType = AnimationTypes.DoubleCircle; } else if (selectedItem.Equals("ECG")) { sfBusyIndicator.Duration = 1500; sfBusyIndicator.TextColor = Color.ParseColor("#DA901A"); sfBusyIndicator.AnimationType = AnimationTypes.Ecg; } else if (selectedItem.Equals("Globe")) { sfBusyIndicator.Duration = 800; sfBusyIndicator.TextColor = Color.ParseColor("#9EA8EE"); sfBusyIndicator.AnimationType = AnimationTypes.Globe; } else if (selectedItem.Equals("HorizontalPulsingBox")) { sfBusyIndicator.Duration = 500; sfBusyIndicator.TextColor = Color.ParseColor("#E42E06"); sfBusyIndicator.AnimationType = AnimationTypes.HorizontalPulsingBox; } else if (selectedItem.Equals("MovieTimer")) { sfBusyIndicator.Duration = 600; sfBusyIndicator.TextColor = Color.ParseColor("#2d2d2d"); sfBusyIndicator.SecondaryColor = Color.ParseColor("#9b9b9b"); sfBusyIndicator.AnimationType = AnimationTypes.MovieTimer; } else if (selectedItem.Equals("Print")) { sfBusyIndicator.Duration = 1000; sfBusyIndicator.TextColor = Color.ParseColor("#5E6FF8"); sfBusyIndicator.AnimationType = AnimationTypes.Print; } else if (selectedItem.Equals("Rectangle")) { sfBusyIndicator.Duration = 200; sfBusyIndicator.TextColor = Color.ParseColor("#27AA9E"); sfBusyIndicator.AnimationType = AnimationTypes.Rectangle; } else if (selectedItem.Equals("RollingBall")) { sfBusyIndicator.Duration = 1000; sfBusyIndicator.TextColor = Color.ParseColor("#2d2d2d"); sfBusyIndicator.SecondaryColor = Color.White; sfBusyIndicator.AnimationType = AnimationTypes.RollingBall; } else if (selectedItem.Equals("SingleCircle")) { sfBusyIndicator.Duration = 1000; sfBusyIndicator.TextColor = Color.ParseColor("#AF2541"); sfBusyIndicator.AnimationType = AnimationTypes.SingleCircle; } else if (selectedItem.Equals("SlicedCircle")) { sfBusyIndicator.Duration = 1600; sfBusyIndicator.TextColor = Color.ParseColor("#779772"); sfBusyIndicator.AnimationType = AnimationTypes.SlicedCircle; } else if (selectedItem.Equals("ZoomingTarget")) { sfBusyIndicator.Duration = 600; sfBusyIndicator.TextColor = Color.ParseColor("#ED8F3C"); sfBusyIndicator.AnimationType = AnimationTypes.ZoomingTarget; } else if (selectedItem.Equals("Gear")) { sfBusyIndicator.Duration = 1500; sfBusyIndicator.TextColor = Color.Gray; sfBusyIndicator.AnimationType = AnimationTypes.GearBox; } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Trendlines.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; namespace SampleBrowser { class Trendlines : SamplePage { SfChart chart; SfChart chart2; TextView ForwardForecast; TextView TrendTypeValue; TextView BackwardForecast; TextView PolyomialOrder; SplineSeries splineSeries1; SplineSeries splineSeries2; ChartTrendline linearTrendline; ChartTrendline powerTrendline; List<String> adapter; public override View GetSampleContent(Context context) { GetCurrencyDevationChart(context); chart.Visibility = ViewStates.Visible; var linearlayout = new LinearLayout(context); linearlayout.AddView(chart); GetMeterDevationChart(context); chart2.Visibility = ViewStates.Gone; linearlayout.AddView(chart2); return linearlayout; } private void GetCurrencyDevationChart(Context context) { chart = new SfChart(context); chart.Title.Text = "1 USD to INR form 1977 to 2019"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Top; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.Orientation = ChartOrientation.Vertical; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.TickSize = 0; numericalaxis.Title.Text = "Rupees against Dollars"; numericalaxis.LabelStyle.LabelFormat = "₹##"; chart.SecondaryAxis = numericalaxis; DateTimeAxis primaryAxis = new DateTimeAxis(); primaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Center; primaryAxis.ShowMajorGridLines = false; primaryAxis.Title.Text = "Years"; primaryAxis.ShowMinorGridLines = false; primaryAxis.IntervalType = DateTimeIntervalType.Years; primaryAxis.Interval = 5; chart.PrimaryAxis = primaryAxis; splineSeries1 = new SplineSeries(); splineSeries1.XBindingPath = "Date"; splineSeries1.YBindingPath = "YValue"; splineSeries1.ItemsSource = MainPage.GetTrendlineDataSource1(); splineSeries1.Label = "Rupees"; splineSeries1.LegendIcon = ChartLegendIcon.SeriesType; splineSeries1.DataMarker.ShowMarker = true; splineSeries1.DataMarker.ShowLabel = false; splineSeries1.DataMarker.MarkerHeight = 5; splineSeries1.DataMarker.MarkerWidth = 5; splineSeries1.DataMarker.MarkerStrokeWidth = 2; splineSeries1.DataMarker.MarkerStrokeColor = Color.ParseColor("#00bdae"); splineSeries1.Trendlines = new ChartTrendlineCollection(); linearTrendline = new ChartTrendline() { Type = ChartTrendlineType.Linear, StrokeColor = new Color(201, 23, 97), LegendIcon = ChartLegendIcon.SeriesType, VisibilityOnLegend= Visibility.Visible, Label = "Linear", }; splineSeries1.Trendlines.Add(linearTrendline); chart.Series.Add(splineSeries1); } private void GetMeterDevationChart(Context context) { chart2 = new SfChart(context); chart2.Title.Text = "Distance Measurement"; chart2.Title.TextSize = 15; chart2.SetBackgroundColor(Color.White); chart2.Legend.Visibility = Visibility.Visible; chart2.Legend.DockPosition = ChartDock.Top; chart2.Legend.IconHeight = 14; chart2.Legend.IconWidth = 14; chart2.ColorModel.ColorPalette = ChartColorPalette.Natural; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.TickSize = 0; numericalaxis.Title.Text = "Meters"; chart2.SecondaryAxis = numericalaxis; NumericalAxis primaryAxis = new NumericalAxis(); primaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Center; primaryAxis.ShowMajorGridLines = false; primaryAxis.Title.Text = "Seconds"; primaryAxis.ShowMinorGridLines = false; chart2.PrimaryAxis = primaryAxis; splineSeries2 = new SplineSeries(); splineSeries2.ItemsSource = MainPage.GetTrendlineDataSource2(); splineSeries2.XBindingPath = "XValue"; splineSeries2.YBindingPath = "YValue"; splineSeries2.Label = "Rupees"; splineSeries2.LegendIcon = ChartLegendIcon.SeriesType; splineSeries2.DataMarker.ShowMarker = true; splineSeries2.DataMarker.ShowLabel = false; splineSeries2.DataMarker.MarkerHeight = 5; splineSeries2.DataMarker.MarkerWidth = 5; splineSeries2.DataMarker.MarkerStrokeWidth = 2; splineSeries2.DataMarker.MarkerStrokeColor = Color.ParseColor("#00bdae"); splineSeries2.Trendlines = new ChartTrendlineCollection(); powerTrendline = new ChartTrendline() { Type = ChartTrendlineType.Power, StrokeColor = new Color(201, 23, 97), LegendIcon = ChartLegendIcon.SeriesType, VisibilityOnLegend = Visibility.Visible, Label = "Power", }; splineSeries2.Trendlines.Add(powerTrendline); chart2.Series.Add(splineSeries2); } public override View GetPropertyWindowLayout(Android.Content.Context context) { /** * Property Window * */ int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; LinearLayout propertylayout = new LinearLayout(context); //= new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams( width * 2, 5); layoutParams1.SetMargins(0, 20, 0, 0); TrendTypeValue = new TextView(context); TrendTypeValue.Text = "Trendline Type"; TrendTypeValue.SetPadding(5, 20, 0, 20); ForwardForecast = new TextView(context); ForwardForecast.Text = "Forward Forecast: 0"; ForwardForecast.SetPadding(5, 20, 0, 20); SeekBar FwdForecast = new SeekBar(context); FwdForecast.Max = 5; FwdForecast.Progress = 0; FwdForecast.ProgressChanged += FwdForecast_ProgressChanged; BackwardForecast = new TextView(context); BackwardForecast.Text = "Backward Forecast: 0"; BackwardForecast.SetPadding(5, 20, 0, 20); SeekBar BwdForecast = new SeekBar(context); BwdForecast.Max = 5; BwdForecast.Progress = 0; BwdForecast.ProgressChanged += BwdForecast_ProgressChanged; PolyomialOrder = new TextView(context); PolyomialOrder.Text = "Polynomial Order: 2"; PolyomialOrder.SetPadding(5, 20, 0, 20); SeekBar PolyOrder = new SeekBar(context); PolyOrder.Max = 5; PolyOrder.Progress = 2; PolyOrder.ProgressChanged += PolyOrder_ProgressChanged; var spinner = new Spinner(context, SpinnerMode.Dialog); adapter = new List<String>() { "Linear", "Exponential", "Logarithmic", "Power", "Polynomial" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); spinner.Adapter = dataAdapter; spinner.ItemSelected += Spinner_ItemSelected; propertylayout.AddView(TrendTypeValue); propertylayout.AddView(spinner); propertylayout.AddView(ForwardForecast); propertylayout.AddView(FwdForecast); propertylayout.AddView(BackwardForecast); propertylayout.AddView(BwdForecast); propertylayout.AddView(PolyomialOrder); propertylayout.AddView(PolyOrder); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); propertylayout.AddView(separate, layoutParams1); return propertylayout; } private void PolyOrder_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { var value = (int)e.Progress; if (linearTrendline != null) linearTrendline.PolynomialOrder = value; PolyomialOrder.Text = "Polynomial Order: " + value; } private void BwdForecast_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { var value = (int)e.Progress; if (linearTrendline != null) linearTrendline.BackwardForecast = value; BackwardForecast.Text = "Backward Forecast: " + value; } private void FwdForecast_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { var value = (int)e.Progress; if (linearTrendline != null) linearTrendline.ForwardForecast = value; if (powerTrendline != null) powerTrendline.ForwardForecast = value; ForwardForecast.Text = "Forward Forecast: " + value; } private void Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter[e.Position]; if (selectedItem.Equals("Power")) { chart2.Visibility = ViewStates.Visible; chart.Visibility = ViewStates.Gone; } else { if (selectedItem.Equals("Linear")) { linearTrendline.Type = ChartTrendlineType.Linear; linearTrendline.Label = "Linear"; } else if (selectedItem.Equals("Exponential")) { linearTrendline.Type = ChartTrendlineType.Exponential; linearTrendline.Label = "Exponential"; } else if (selectedItem.Equals("Logarithmic")) { linearTrendline.Label = "Logarithmic"; linearTrendline.Type = ChartTrendlineType.Logarithmic; } else if (selectedItem.Equals("Polynomial")) { linearTrendline.Label = "Polynomial"; linearTrendline.Type = ChartTrendlineType.Polynomial; } if(chart.Visibility == ViewStates.Gone) { chart2.Visibility = ViewStates.Gone; chart.Visibility = ViewStates.Visible; } } } } }<file_sep>/Forms/Cards/Cards/Samples/CardView/CardViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Text; using Xamarin.Forms; namespace SampleBrowser.Cards { public class CardViewModel : INotifyPropertyChanged { internal ObservableCollection<CardViewData> Data = new ObservableCollection<CardViewData>(); private double cornerRadius = 7; public double CornerRadius { get { return cornerRadius; } set { cornerRadius = Math.Round(value); OnPropertyChanged("CornerRadius"); } } private bool isCardAlreadySwiped = false; public bool IsCardAlreadySwiped { get { return isCardAlreadySwiped; } set { isCardAlreadySwiped = value; OnPropertyChanged("IsCardAlreadySwiped"); } } private double indicatorThickness; public double IndicatorThickness { get { return indicatorThickness; } set { indicatorThickness = value; OnPropertyChanged("IndicatorThickness"); } } public event PropertyChangedEventHandler PropertyChanged; private bool enableFadeOutOnSwiping=true; public bool EnableFadeOutOnSwiping { get { return enableFadeOutOnSwiping; } set { enableFadeOutOnSwiping = value; EnableSwipToDismiss = value; OnPropertyChanged("EnableFadeOutOnSwiping"); } } private bool enableSwipToDismiss = true; public bool EnableSwipToDismiss { get { return enableSwipToDismiss; } set { enableSwipToDismiss = value; OnPropertyChanged("EnableSwipToDismiss"); } } public void OnPropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public CardViewModel() { Data.Add(new CardViewData { Name = "<NAME>", Price = "$99", Offer = "35% Offer", ImagePath = "AngleSofa.jpg", }); Data.Add(new CardViewData { Name = "<NAME>", Price = "$80", Offer = "15% Offer", ImagePath = "DiningTable.jpg", }); Data.Add(new CardViewData { Name = "<NAME>", Price = "$99", Offer = "25% Offer", ImagePath = "GraySofa.jpg", }); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/PullToRefresh/SfDataGridInPullToRefresh.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using System.Globalization; using CoreGraphics; using Syncfusion.SfPullToRefresh; using System.Threading.Tasks; namespace SampleBrowser { public class SfDataGridInPullToRefresh : SampleView { #region Fields SfDataGrid SfGrid; SfPullToRefresh pullToRefresh; GridGettingStartedViewModel viewModel; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public SfDataGridInPullToRefresh() { this.pullToRefresh = new SfPullToRefresh(); this.pullToRefresh.RefreshContentThreshold = 45; this.SfGrid = new SfDataGrid (); this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; viewModel = new GridGettingStartedViewModel(); this.SfGrid.ItemsSource = viewModel.OrdersInfo; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.GridStyle.AlternatingRowColor = UIColor.FromRGB (219, 219, 219); this.SfGrid.AllowResizingColumn = true; this.SfGrid.GridStyle = new CustomGridStyle(); this.pullToRefresh.PullableContent = SfGrid; this.pullToRefresh.Refreshing += PullToRefresh_Refreshing; this.AddSubview (this.pullToRefresh); this.OptionView = new Options(pullToRefresh); } private async void PullToRefresh_Refreshing(object sender, RefreshingEventArgs e) { await Task.Delay(4000); viewModel.ItemsSourceRefresh(); e.Refreshed = true; } void GridAutoGenerateColumns (object sender, AutoGeneratingColumnEventArgs e) { if (UserInterfaceIdiomIsPhone) e.Column.MaximumWidth = 150; else e.Column.MaximumWidth = 300; if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.ColumnSizer = ColumnSizer.Auto; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.ColumnSizer = ColumnSizer.Auto; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Index") { e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "<NAME>"; e.Column.ColumnSizer = ColumnSizer.Auto; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "<NAME>"; e.Column.ColumnSizer = ColumnSizer.Auto; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 10; } else if (e.Column.MappingName == "ShippingDate") { e.Column.HeaderText = "Shipping Date"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; e.Column.Format = "d"; } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } } public override void LayoutSubviews () { this.pullToRefresh.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews (); } protected override void Dispose(bool disposing) { base.Dispose(disposing); SfGrid.Dispose(); pullToRefresh.Refreshing -= PullToRefresh_Refreshing; pullToRefresh.Dispose(); } } } <file_sep>/Forms/TreeMap/TreeMap/Samples/DataLabel/DataLabel.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfTreeMap.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfTreeMap { [Preserve(AllMembers = true)] [XamlCompilation(XamlCompilationOptions.Compile)] public partial class DataLabel : SampleView { Label label; Picker picker; public DataLabel() { InitializeComponent(); DrawOptionsPage(); this.PropertyView = GetOptionPage(); } private void DrawOptionsPage() { picker = new Picker(); picker.Items.Add("Trim"); picker.Items.Add("Wrap"); picker.Items.Add("Hide"); picker.HeightRequest = 40; picker.SelectedIndex = 0; picker.SelectedIndexChanged += picker1_SelectedIndexChanged; label = new Label() { Text = "Label OverflowMode", HeightRequest = 20, VerticalTextAlignment = TextAlignment.End, }; if (Device.RuntimePlatform == Device.Android) { picker.BackgroundColor = Color.FromRgb(239, 239, 239); label.FontSize = 20; } } private StackLayout GetOptionPage() { var page = new StackLayout { Spacing = 10, Orientation = StackOrientation.Vertical, Padding = 10, Children = { label, picker } }; return page; } void picker1_SelectedIndexChanged(object sender, EventArgs e) { switch (picker.SelectedIndex) { case 0: { TreeMap.LeafItemSettings.OverflowMode = LabelOverflowMode.Trim; break; } case 1: { TreeMap.LeafItemSettings.OverflowMode = LabelOverflowMode.Wrap; break; } case 2: { TreeMap.LeafItemSettings.OverflowMode = LabelOverflowMode.Hide; break; } } } } public class PopulationConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var label = (double)value / 1000000; string text = ((int)label).ToString() + "M"; return text; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } }<file_sep>/Forms/StepProgressBar/StepProgressBar/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.ProgressBar; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfStepProgressBar { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Themes : SampleView { ShipmentViewModel ShipmentViewModel = new ShipmentViewModel(); public Themes() { InitializeComponent(); stepProgress.StatusChanged += Step_StatusChanged; ShipmentViewModel.PopulateShipmentDetails(); BindableLayout.SetItemsSource(stepProgress, ShipmentViewModel.ShipmentInfoCollection); this.PropertyChanged += Themes_PropertyChanged; } private void Themes_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "BackgroundColor" && stepProgress != null && stepProgress.Children.Count > 0) { for (int i = 0; i < stepProgress.Children.Count; i++) { SetStepViewPrimaryTextColor(stepProgress.Children[i] as StepView); } } } void SetStepViewPrimaryTextColor(StepView view) { if (view.Status == StepStatus.Completed) { view.PrimaryFormattedText.Spans[0].TextColor = stepProgress.CompletedStepStyle.FontColor; view.PrimaryFormattedText.Spans[3].TextColor = stepProgress.CompletedStepStyle.FontColor; view.PrimaryFormattedText.Spans[5].TextColor = stepProgress.CompletedStepStyle.FontColor; } if (view.Status == StepStatus.NotStarted) { view.PrimaryFormattedText.Spans[0].TextColor = Color.FromHex("#6E6E6E"); view.PrimaryFormattedText.Spans[3].TextColor = Color.Transparent; view.PrimaryFormattedText.Spans[5].TextColor = Color.Transparent; } } void Step_StatusChanged(object sender, StatusChangedEventArgs e) { int index = stepProgress.Children.IndexOf(e.Item); SetStepViewPrimaryTextColor(e.Item); if (e.Item == stepProgress.Children[stepProgress.Children.Count - 1] && e.Item.Status == StepStatus.Completed) { TrackButton.IsEnabled = true; } } void Handle_Clicked(object sender, System.EventArgs e) { StepView stepView; switch (TrackButton.Text) { case "Track Status": stepProgress.ProgressAnimationDuration = 1000; stepView = stepProgress.Children[3] as StepView; stepView.Status = StepStatus.Completed; TrackButton.Text = "Reset"; TrackButton.IsEnabled = false; break; default: TrackButton.Text = "Track Status"; stepProgress.ProgressAnimationDuration = 1; stepView = stepProgress.Children[0] as StepView; stepView.Status = StepStatus.NotStarted; break; } } } }<file_sep>/Forms/StepProgressBar/StepProgressBar/Samples/UserRegistration/UserRegistration.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Xamarin.Forms; using Syncfusion.XForms.ProgressBar; using System.Globalization; using System.Diagnostics; using Syncfusion.XForms.ComboBox; using System.Threading; namespace SampleBrowser.SfStepProgressBar { public partial class UserRegistration : SampleView { public List<string> QuestionOne = new List<string>(); public List<string> QuestionTwo = new List<string>(); bool isStatuUpdate = false; string[] profilePage = new string[] { "User.png", "User.png", "UserSelection.png", }; string[] accountSetUpPage = new string[] { "AccountSelection.png", "AccountWhite.png", "AccountWhite.png" }; string[] personalPage = new string[] { "Personal.png", "PersonalSelection.png", "PersonalWhite.png" }; int index = 0; public UserRegistration() { InitializeComponent(); QuestionOne.Add("What was the name of your first pet ?"); QuestionOne.Add("What was the first thing you learned to cook ?"); QuestionTwo.Add("What was the first film saw in the theater ?"); QuestionTwo.Add("What was the last name of the favorite teacher ?"); comboBox1.ComboBoxSource = QuestionOne; comboBox2.ComboBoxSource = QuestionTwo; SetButtonStyles(); AssignStepperIndicatorProperties(); (stepProgressBar.Children[0] as StepView).Status = StepStatus.InProgress; datePicker.Date.ToString(CultureInfo.InvariantCulture.DateTimeFormat); datePicker.DateSelected += DatePicker_DateSelected; datePicker.Unfocused += DatePicker_Unfocused; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; } private void DatePicker_DateSelected(object sender, DateChangedEventArgs e) { DOBEntryField.Text = e.NewDate.Date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture.DateTimeFormat); } private void DatePicker_Unfocused(object sender, FocusEventArgs e) { DOBEntryField.Text = (e.VisualElement as DatePicker).Date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture.DateTimeFormat); } private void SetButtonStyles() { ProfilePageNextButton.BackgroundColor = Color.FromHex("#FF007AFF"); AccountsPageNextButton.BackgroundColor = Color.FromHex("#FF007AFF"); AccountsPagePreviousButton.BackgroundColor = Color.FromHex("#FFFFFFFF"); AccountsPagePreviousButton.TextColor = Color.FromHex("#434343"); AccountsPagePreviousButton.BorderColor = Color.FromHex("EAEAEA"); PersonalPageNextButton.BackgroundColor = Color.FromHex("#FF007AFF"); PersonalPagePreviousButton.BackgroundColor = Color.FromHex("#FFFFFFFF"); PersonalPagePreviousButton.TextColor = Color.FromHex("#434343"); PersonalPagePreviousButton.BorderColor = Color.FromHex("EAEAEA"); NameEntryField.PlaceholderColor = Color.FromHex("#FF949494"); EmailEntryField.PlaceholderColor = Color.FromHex("#FF949494"); PasswordEntryField.PlaceholderColor = Color.FromHex("#FF949494"); ConfirmPasswordField.PlaceholderColor = Color.FromHex("#FF949494"); PhoneNumberEntryField.PlaceholderColor = Color.FromHex("#FF949494"); NameEntryField.FontSize = 14; EmailEntryField.FontSize = 14; PasswordEntryField.FontSize = 14; ConfirmPasswordField.FontSize = 14; PhoneNumberEntryField.FontSize = 14; DOBEntryField.FontSize = 14; } void NextButton_Clicked(object sender, System.EventArgs e) { if (index < 2) { index++; } SetVisibility(); if (isStatuUpdate) { (stepProgressBar.Children[index] as StepView).Status = StepStatus.InProgress; this.UpdateImage(index); isStatuUpdate = false; } } void PreviousButton_Clicked(object sender, System.EventArgs e) { if (index > 0) { index--; } SetVisibility(); if (isStatuUpdate) { (stepProgressBar.Children[index] as StepView).Status = StepStatus.InProgress; this.UpdateImage(index); isStatuUpdate = false; } } private void SetVisibility() { if (index == 0) { AccountSetupPage.IsVisible = true; SecurityQuestionPage.IsVisible = false; ProfilePage.IsVisible = false; isStatuUpdate = true; } else if (index == 1 && ProfilePageNextButton.IsEnabled) { AccountSetupPage.IsVisible = false; ProfilePage.IsVisible = false; SecurityQuestionPage.IsVisible = true; isStatuUpdate = true; } else if (index == 2 && AccountsPageNextButton.IsEnabled) { AccountSetupPage.IsVisible = false; SecurityQuestionPage.IsVisible = false; ProfilePage.IsVisible = true; isStatuUpdate = true; } } void AssignStepperIndicatorProperties() { stepProgressBar.ProgressAnimationDuration = 0; stepProgressBar.NotStartedStepStyle.MarkerSize = 29; stepProgressBar.InProgressStepStyle.MarkerSize = 29; stepProgressBar.CompletedStepStyle.MarkerSize = 29; stepProgressBar.NotStartedStepStyle.MarkerContentSize = 15; stepProgressBar.InProgressStepStyle.MarkerContentSize = 15; stepProgressBar.CompletedStepStyle.MarkerContentSize = 15; stepProgressBar.NotStartedStepStyle.MarkerFillColor = Color.FromHex("#DADADA"); stepProgressBar.NotStartedStepStyle.MarkerStrokeColor = Color.FromHex("#DADADA"); stepProgressBar.InProgressStepStyle.MarkerFillColor = Color.FromHex("#FFFFFF"); stepProgressBar.CompletedStepStyle.MarkerFillColor = Color.FromHex("#007AFF"); stepProgressBar.InProgressStepStyle.FontColor = Color.FromHex("#007AFF"); stepProgressBar.CompletedStepStyle.FontColor = Color.FromHex("#007AFF"); stepProgressBar.StepTapped += Stepprogressbar_StepTapped; } void Stepprogressbar_StepTapped(object sender, StepTappedEventArgs e) { if (e.Index == 1 && !ProfilePageNextButton.IsEnabled) { return; } else if (e.Index == 2 && !AccountsPageNextButton.IsEnabled) { return; } index = e.Index; SetVisibility(); if (isStatuUpdate) { e.Item.Status = StepStatus.InProgress; this.UpdateImage(index); isStatuUpdate = false; } } private void DOBEntryField_Focused(object sender, FocusEventArgs e) { if (Device.RuntimePlatform == Device.UWP) { datePicker.IsVisible = true; datePicker.Focus(); } Device.BeginInvokeOnMainThread(() => { datePicker.Unfocus(); datePicker.Focus(); }); DOBEntryField.Unfocus(); } private void Done(object sender, EventArgs e) { index = 0; (stepProgressBar.Children[index] as StepView).Status = StepStatus.InProgress; this.UpdateImage(index); SetVisibility(); isStatuUpdate = false; male.IsChecked = false; female.IsChecked = false; NameEntryField.Text = null; EmailEntryField.Text = null; PasswordEntryField.Text = null; ConfirmPasswordField.Text = null; question1.Text = null; question2.Text = null; PhoneNumberEntryField.Text = null; DOBEntryField.Text = null; ProfilePageNextButton.IsEnabled = AccountSetupGridValidation(); AccountsPageNextButton.IsEnabled = SecurityQuestionGridValidation(); PersonalPageNextButton.IsEnabled = ProfilePageValidation(); } void UpdateImage(int index) { if (index == 0) { AccountIcon.Color = Color.FromHex("#007aff"); SecurityIcon.Color = Color.FromHex("868686"); PersonalIcon.Color = Color.FromHex("868686"); } else if (index == 1) { AccountIcon.Color = Color.FromHex("#ffffff"); SecurityIcon.Color = Color.FromHex("#007aff"); PersonalIcon.Color = Color.FromHex("868686"); } else if (index == 2) { AccountIcon.Color = Color.FromHex("#ffffff"); SecurityIcon.Color = Color.FromHex("#ffffff"); PersonalIcon.Color = Color.FromHex("007aff"); } } private void EntryField_TextChanged(object sender, TextChangedEventArgs e) { if (AccountSetupPage.IsVisible) { ProfilePageNextButton.IsEnabled = AccountSetupGridValidation(); } else if (SecurityQuestionPage.IsVisible) { AccountsPageNextButton.IsEnabled = SecurityQuestionGridValidation(); } else if(ProfilePage.IsVisible) { PersonalPageNextButton.IsEnabled = ProfilePageValidation(); } } private bool AccountSetupGridValidation() { bool isEnable = false; if (EmailEntryField.Text != null && PasswordEntryField.Text != null && ConfirmPasswordField.Text != null && PasswordEntryField.Text == ConfirmPasswordField.Text) { isEnable = true; } else { isEnable = false; } return isEnable; } private bool SecurityQuestionGridValidation() { bool isEnable = false; if (question1.Text != null && question2.Text != null) { isEnable = true; } else { isEnable = false; } return isEnable; } private bool ProfilePageValidation() { bool isEnable = false; if (NameEntryField.Text != null && PhoneNumberEntryField.Text != null && DOBEntryField.Text != null) { isEnable = true; } else { isEnable = false; } return isEnable; } private void ComboBox1_SelectionChanged(object sender, Syncfusion.XForms.ComboBox.SelectionChangedEventArgs e) { Syncfusion.XForms.ComboBox.SfComboBox comboBox = sender as Syncfusion.XForms.ComboBox.SfComboBox; if (comboBox.SelectedIndex >= 0) { question1.IsEnabled = true; } else { question1.IsEnabled = false; } } private void ComboBox2_SelectionChanged(object sender, Syncfusion.XForms.ComboBox.SelectionChangedEventArgs e) { Syncfusion.XForms.ComboBox.SfComboBox comboBox = sender as Syncfusion.XForms.ComboBox.SfComboBox; if (comboBox.SelectedIndex >= 0) { question2.IsEnabled = true; } else { question2.IsEnabled = false; } } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/Bubble.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Bubble : SampleView { public Bubble () { SFChart chart = new SFChart (); chart.Title.Text = new NSString ("World Countries Details"); SFNumericalAxis primaryAxis = new SFNumericalAxis (); chart.PrimaryAxis = primaryAxis; primaryAxis.Minimum = new NSNumber (60); primaryAxis.Maximum = new NSNumber (100); primaryAxis.Interval = new NSNumber (5); primaryAxis.ShowMinorGridLines = false; primaryAxis.ShowMajorGridLines = false; chart.PrimaryAxis.Title.Text = new NSString ("Literacy Rate"); chart.SecondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis.Title.Text = new NSString ("GDP Growth Rate"); chart.SecondaryAxis.Minimum = new NSNumber (0); chart.SecondaryAxis.Maximum = new NSNumber (10); chart.SecondaryAxis.Interval = new NSNumber(2.5); chart.SecondaryAxis.ShowMinorGridLines = false; chart.SecondaryAxis.ShowMajorGridLines = false; chart.Delegate = new TooltipFormatter(); ChartViewModel dataModel = new ChartViewModel (); SFBubbleSeries series = new SFBubbleSeries(); series.EnableTooltip = true; series.Alpha = 0.6f; series.ItemsSource = dataModel.BubbleData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.Size = "Size"; series.MaximumRadius = 40; series.MinimumRadius = 5; series.ColorModel.Palette = SFChartColorPalette.Natural; series.EnableAnimation = true; chart.Series.Add(series); var tooltip = new SFChartTooltipBehavior(); tooltip.BackgroundColor = UIColor.FromRGBA(64.0f / 255.0f, 64.0f / 255.0f, 65.0f / 255.0f, 1.0f); chart.AddChartBehavior(tooltip); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } class TooltipFormatter : SFChartDelegate { public override void WillShowTooltip(SFChart chart, SFChartTooltip tooltipView) { UIView customView = new UIView(); customView.Frame = new CGRect(0, 0, 140, 70); UILabel label = new UILabel(); label.Frame = new CGRect(45, 0, 180, 18); label.TextColor = UIColor.White; label.Font = UIFont.FromName("Helvetica", 12f); label.Text = (tooltipView.DataPoint as ChartDataModel).Label; UILabel box = new UILabel(); box.Frame = new CGRect(customView.Frame.X, label.Frame.Height, customView.Frame.Width, 1); box.BackgroundColor = UIColor.White; UILabel xLabel = new UILabel(); xLabel.Frame = new CGRect(5, 20, 80, 18); xLabel.TextColor = UIColor.LightGray; xLabel.Font = UIFont.FromName("Helvetica", 12f); xLabel.Text = "Literacy Rate : "; UILabel xValue = new UILabel(); xValue.Frame = new CGRect(87, 20, 35, 18); xValue.TextColor = UIColor.White; xValue.Font = UIFont.FromName("Helvetica", 12f); xValue.Text = (tooltipView.DataPoint as ChartDataModel).XValue + "%"; UILabel yLabel = new UILabel(); yLabel.Frame = new CGRect(5, 35, 180, 18); yLabel.TextColor = UIColor.LightGray; yLabel.Font = UIFont.FromName("Helvetica", 12f); yLabel.Text = "GDP Growth Rate : "; UILabel yValue = new UILabel(); yValue.Frame = new CGRect(112, 35, 35, 18); yValue.TextColor = UIColor.White; yValue.Font = UIFont.FromName("Helvetica", 12f); yValue.Text = tooltipView.Text; UILabel sizeLabel = new UILabel(); sizeLabel.Frame = new CGRect(5, 50, 65, 18); sizeLabel.TextColor = UIColor.LightGray; sizeLabel.Font = UIFont.FromName("Helvetica", 12f); sizeLabel.Text = "Population : "; UILabel sizeValue = new UILabel(); sizeValue.Frame = new CGRect(73, 50, 90, 18); sizeValue.TextColor = UIColor.White; sizeValue.Font = UIFont.FromName("Helvetica", 12f); sizeValue.Text = (tooltipView.DataPoint as ChartDataModel).Size + " Billion"; customView.AddSubview(label); customView.AddSubview(box); customView.AddSubview(xLabel); customView.AddSubview(xValue); customView.AddSubview(yLabel); customView.AddSubview(yValue); customView.AddSubview(sizeLabel); customView.AddSubview(sizeValue); tooltipView.CustomView = customView; } } }<file_sep>/Android/SampleBrowser/Samples/XlsIO/ImportHtmlTablePage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using System; using System.IO; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using System.Reflection; namespace SampleBrowser { public partial class ImportHtmlTablePage : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { int numerHeight = getDimensionPixelSize(con, Resource.Dimension.numeric_txt_ht); int width = con.Resources.DisplayMetrics.WidthPixels - 40; LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample illustrates how to import HTML table to worksheet."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; LinearLayout subLinearLayout = new LinearLayout(con); subLinearLayout.Orientation = Orientation.Horizontal; LinearLayout advancedLinear1; advancedLinear1 = new LinearLayout(con); advancedLinear1.Orientation = Orientation.Horizontal; TextView space4 = new TextView(con); space4.TextSize = 17; space4.TextAlignment = TextAlignment.Center; space4.Text = " "; space4.SetTextColor(Color.ParseColor("#262626")); space4.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear1.AddView(space4); TextView space6 = new TextView(con); space6.TextSize = 17; linear.AddView(space6); Button templateButton = new Button(con); templateButton.Text = "Input Template"; templateButton.Click += OnButtonClicked; linear.AddView(templateButton); Button convertButton = new Button(con); convertButton.Text = "Import"; convertButton.Click += OnConvertButtonClicked; linear.AddView(convertButton); return linear; } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream filestream = null; filestream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.ImportHTMLTable.html"); MemoryStream stream = new MemoryStream(); filestream.CopyTo(stream); stream.Position = 0; SaveAndView(stream, "text/html"); } private void OnConvertButtonClicked(object sender, EventArgs e) { //Instantiate excel engine ExcelEngine excelEngine = new ExcelEngine(); //Excel application IApplication application = excelEngine.Excel; //Get assembly manifest resource Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.ImportHTMLTable.html"); //Create Workbook IWorkbook workbook = application.Workbooks.Create(1); workbook.Version = ExcelVersion.Excel2016; IWorksheet sheet = workbook.Worksheets[0]; sheet.ImportHtmlTable(fileStream, 1, 1); sheet.UsedRange.AutofitColumns(); sheet.UsedRange.AutofitRows(); MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); stream.Position = 0; workbook.Close(); excelEngine.Dispose(); SaveAndView(stream, "application/msexcel"); } void SaveAndView(MemoryStream stream, string contentType) { if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); if (contentType == "text/html") androidSave.Save("ImportHTMLTable.html", contentType, stream, m_context); else androidSave.Save("ImportHTMLTable.xlsx", contentType, stream, m_context); } } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } } }<file_sep>/Forms/Calendar/Calendar/Samples/CalendarLocalization/Views/CalendarLocalization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Syncfusion.SfCalendar.XForms; using Xamarin.Forms; namespace SampleBrowser.SfCalendar { /// <summary> /// Calendar Localization Default /// </summary> public partial class CalendarLocalization : SampleView { /// <summary> /// Initializes a new instance of the <see cref="CalendarLocalization" /> class /// </summary> public CalendarLocalization() { this.InitializeComponent(); } } }<file_sep>/Forms/RadialMenu/RadialMenu/Samples/GettingStarted_RadialMenu/GettingStarted_RadialMenu.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Linq; using System.Collections.Generic; using System.Collections.ObjectModel; using Syncfusion.SfRadialMenu.XForms; using Xamarin.Forms; using SampleBrowser.Core; using System.ComponentModel; using System.Windows.Input; namespace SampleBrowser.SfRadialMenu { public partial class GettingStarted_RadialMenu : SampleView, INotifyPropertyChanged { ObservableCollection<string> list; public GettingStarted_RadialMenu() { InitializeComponent(); this.BindingContext = this; list = new ObservableCollection<string>(); #region Event with Handlers list.CollectionChanged += (sender, e) => { Label lbl = new Label(); lbl.FontSize = 14; lbl.Text = e.NewItems[0].ToString(); eventLogLayout.Children.Insert(0, lbl); }; slider.ValueChanging += (sender, e) => { radial_Menu.Close(); radial_Menu.RimRadius = e.Value; }; rotationSwitch.Toggled += (sender, e) => { radial_Menu.EnableRotation = e.Value; }; dragSwitch.Toggled += (sender, e) => { radial_Menu.IsDragEnabled = e.Value; }; #endregion if (Device.RuntimePlatform == Device.Android) { eventLogsLabel.FontSize = 18; eventLogsLabel.HeightRequest = 40; clearLogsButton.HeightRequest = 35; clearLogsButton.FontSize = 12; logRow.Height = 35; } } public ICommand RadialMenuTapped => new Command(RadialMenuItemTapped); #region Event Handlers void Handle_Clicked(object sender, System.EventArgs e) { eventLogLayout.Children.Clear(); } private void RadialMenuItemTapped(object obj) { var tempItem = (obj as SfRadialMenuItem); if (tempItem.FontIconText == "") list.Add("Spectrum range one is selected"); else if (tempItem.FontIconText == "") list.Add("Spectrum range two is selected"); else if (tempItem.FontIconText == "") list.Add("Spectrum range three is selected"); else if (tempItem.FontIconText == "") list.Add("Spectrum range four is selected"); else if (tempItem.FontIconText == "") list.Add("Notification mode one is selected"); else if (tempItem.FontIconText == "") list.Add("Notification mode two is selected"); else if (tempItem.FontIconText == "") list.Add("Notification mode three is selected"); else if (tempItem.FontIconText == "") list.Add("Slient mode is activated"); else if (tempItem.FontIconText == "") list.Add("Vibrate mode is activated"); else if (tempItem.FontIconText == "") list.Add("Normal mode is activated"); else if (tempItem.FontIconText == "") list.Add("Brightness level is adjusted"); else if (tempItem.FontIconText == "") list.Add("Battery mode one is selected"); else if (tempItem.FontIconText == "") list.Add("Battery mode two is selected"); else if (tempItem.FontIconText == "") list.Add("Battery mode three is selected"); else if (tempItem.FontIconText == "") list.Add("Power saver mode one is selected"); else if (tempItem.FontIconText == "") list.Add("Power saver mode two is selected"); else if (tempItem.FontIconText == "") list.Add("Power saver mode three is selected"); } void Radial_Menu_Opening(object sender, OpeningEventArgs e) { list.Add("RadialMenu is Opening"); } void Radial_Menu_Opened(object sender, OpenedEventArgs e) { list.Add("RadialMenu is Opened"); } void Radial_Menu_Closed(object sender, ClosedEventArgs e) { list.Add("RadialMenu is Closed"); } void Radial_Menu_Closing(object sender, ClosingEventArgs e) { list.Add("RadialMenu is Closing"); } void Radial_Menu_Navigating(object sender, NavigatingEventArgs e) { list.Add("RadialMenu is Navigating"); } void Radial_Menu_Navigated(object sender, NavigatedEventArgs e) { list.Add("RadialMenu is Navigated"); } void Radial_Menu_CenterButtonTapped(object sender, CenterButtonBackTappedEventArgs e) { list.Add("CenterButtonBack is Tapped"); } void Handle_DragBegin(object sender, Syncfusion.SfRadialMenu.XForms.DragBeginEventArgs e) { list.Add("RadialMenu is began to drag" + "\n Start Position :" + " \t X = " + e.Position.X + " \t Y =" + e.Position.Y); } void Handle_DragEnd(object sender, Syncfusion.SfRadialMenu.XForms.DragEndEventArgs e) { if (radial_Menu.CenterButtonPlacement == SfRadialMenuCenterButtonPlacement.Center) { if (e.NewValue.X >= (radial_Menu.Width / 2 - radial_Menu.CenterButtonRadius / 2) || e.NewValue.X <= -(radial_Menu.Width / 2 - radial_Menu.CenterButtonRadius / 2)) { e.Handled = true; } if (e.NewValue.Y >= (radial_Menu.Height / 2 - radial_Menu.CenterButtonRadius / 2) || e.NewValue.Y <= -(radial_Menu.Height / 2 - radial_Menu.CenterButtonRadius / 2)) { e.Handled = true; } } list.Add("RadialMenu is stopped dragging" + "\n Start Position :" + " \t X = " + e.OldValue.X + " \t Y =" + e.OldValue.Y + "\n End Position :" + "\t X = " + e.NewValue.X + "\t Y =" + e.NewValue.Y); } #endregion bool visibility = true; public bool Visible { get { return visibility; } set { visibility = value; RaisePropertyChanged("Visible"); } } #region INotifyPropertyChanged implementation public new event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion public override void OnDisappearing() { if(Device.RuntimePlatform == Device.UWP) { radial_Menu.Dispose(); } base.OnDisappearing(); } double oldHeight, oldWidth; protected override void OnSizeAllocated(double width, double height) { if (height != oldHeight && width != oldWidth) { oldWidth = width; oldHeight = height; if (width < height) { Visible = true; Grid.SetRowSpan(firstRow, 1); radial_Menu.Point = new Point(0, 0); } else { Visible = false; Grid.SetRowSpan(firstRow, 3); radial_Menu.Point = new Point(1, 0); } } base.OnSizeAllocated(width, height); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Zooming/Zooming.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Zooming.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A sampleView that contains the Zooming sample. /// </summary> public partial class Zooming : SampleView { #region Constructor /// <summary> /// Initializes a new instance of the Zooming class. /// </summary> public Zooming() { this.InitializeComponent(); if (Device.RuntimePlatform == Device.UWP) { this.dataGrid.DefaultColumnWidth = 100; } } #endregion /// <summary> /// Raises when slider value changes. /// </summary> /// <param name="sender">Instance of slider.</param> /// <param name="e"><see cref="Xamarin.Forms.ValueChangedEventArgs"/> event argument.</param> private void OnMaximumZoomScale_ValueChanged(object sender, Xamarin.Forms.ValueChangedEventArgs e) { if (this.maximumZoomScale.Value <= this.minimumZoomScale.Value) { this.minimumZoomScale.Value = this.maximumZoomScale.Value - 0.1; } if (this.maximumZoomScale.Value < this.dataGrid.GetZoomScale()) { this.dataGrid.Zoom((float)this.maximumZoomScale.Value); } this.dataGrid.MaximumZoomScale = (float)this.maximumZoomScale.Value; this.maximumZoomScaleValue.Text = "MaximumZoomScale : " + (Math.Truncate(100 * this.maximumZoomScale.Value) / 100).ToString(); } /// <summary> /// Raises when slider value changes. /// </summary> /// <param name="sender">Instance of slider.</param> /// <param name="e"><see cref="Xamarin.Forms.ValueChangedEventArgs"/> event argument.</param> private void OnMinimumZoomScale_ValueChanged(object sender, Xamarin.Forms.ValueChangedEventArgs e) { if (this.minimumZoomScale.Value >= this.maximumZoomScale.Value) { this.maximumZoomScale.Value = this.minimumZoomScale.Value + 0.1; } if (this.minimumZoomScale.Value > this.dataGrid.GetZoomScale()) { this.dataGrid.Zoom((float)this.minimumZoomScale.Value); } this.dataGrid.MinimumZoomScale = (float)this.minimumZoomScale.Value; this.minimumZoomScaleValue.Text = "MinimumZoomScale : " + (Math.Truncate(100 * this.minimumZoomScale.Value) / 100).ToString(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Popup/TicketBookingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; namespace SampleBrowser { public class TicketBookingViewModel { public TicketBookingViewModel() { TicketInfoRepository details = new TicketInfoRepository(); theaterInformation = details.GetDetails(); } #region ItemsSource private ObservableCollection<TicketBookingInfo> theaterInformation; public ObservableCollection<TicketBookingInfo> TheaterInformation { get { return this.theaterInformation; } set { this.theaterInformation = value; } } #endregion } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Selection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Views; using Android.Widget; using System.Collections.Generic; using System.Globalization; using Android.Graphics; namespace SampleBrowser { public class Selection : SamplePage { SfDataGrid sfGrid; SelectionViewModel viewModel; public override Android.Views.View GetSampleContent(Android.Content.Context context) { sfGrid = new SfDataGrid(context); viewModel = new SelectionViewModel(); sfGrid.ItemsSource = (viewModel.ProductDetails); sfGrid.AutoGeneratingColumn += OnAutoGenerateColumn; sfGrid.SelectedIndex = 1; sfGrid.SelectionMode = SelectionMode.Multiple; sfGrid.NavigationMode = NavigationMode.Cell; sfGrid.SelectionController = new CustomSelectionController(sfGrid); sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; sfGrid.GridStyle = new SelectionStyle(); return sfGrid; } public override Android.Views.View GetPropertyWindowLayout(Android.Content.Context context) { View view = new View(context); Spinner spin = new Spinner(context, SpinnerMode.Dialog); List<String> adapter = new List<String>() { "Single", "Single/Deselect", "Multiple", "None" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); spin.Adapter = dataAdapter; TextView txt = new TextView(context); txt.Text = "Set Selection Mode"; txt.TextSize = 15f; txt.SetPadding(10, 10, 10, 10); spin.SetPadding(10, 10, 10, 10); LinearLayout linear = new LinearLayout(context); linear.Orientation = Orientation.Horizontal; linear.AddView(txt); linear.AddView(spin); spin.SetSelection(2); spin.ItemSelected += OnSelectionModeChanged; return linear; } void OnSelectionModeChanged(object sender, AdapterView.ItemSelectedEventArgs e) { if (e.Position == 0) sfGrid.SelectionMode = SelectionMode.Single; if (e.Position == 1) sfGrid.SelectionMode = SelectionMode.SingleDeselect; if (e.Position == 2) sfGrid.SelectionMode = SelectionMode.Multiple; if (e.Position == 3) sfGrid.SelectionMode = SelectionMode.None; } void OnAutoGenerateColumn(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "ProductID") { e.Column.HeaderText = "Product ID"; } else if (e.Column.MappingName == "Product") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "UserRating") { e.Column.HeaderText = "User Rating"; } else if (e.Column.MappingName == "ProductModel") { e.Column.HeaderText = "Product Model"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Price") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo("en-US"); } else if (e.Column.MappingName == "ShippingDays") { e.Column.HeaderText = "Shipping Days"; } else if (e.Column.MappingName == "ProductType") { e.Column.HeaderText = "Product Type"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Availability") { e.Column.TextAlignment = GravityFlags.CenterVertical; } } public override void OnApplyChanges() { base.OnApplyChanges(); } public override void Destroy() { sfGrid.AutoGeneratingColumn -= OnAutoGenerateColumn; sfGrid.Dispose(); viewModel = null; sfGrid = null; } } public class CustomSelectionController : GridSelectionController { public CustomSelectionController(SfDataGrid sfGrid) { this.DataGrid = sfGrid; } protected override void SetSelectionAnimation(VirtualizingCellsControl rowElement) { rowElement.Alpha = 0.5f; rowElement.Animate().Alpha(0.5f).SetDuration(1000).AlphaBy(1f).WithEndAction(new Java.Lang.Runnable(() => { try { rowElement.Alpha = 1f; } catch { } })); } } public class SelectionStyle:DefaultStyle { public SelectionStyle() { } public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Horizontal; } } } <file_sep>/Forms/ComboBox/ComboBox/Samples/GettingStartedSample/GettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfComboBox { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class GettingStarted : SampleView { public GettingStarted () { InitializeComponent (); if (Device.RuntimePlatform == Device.WPF) { this.PropertyView = GettingStartedWPF.PropertyView; } else { this.PropertyView = GettingStartedDefault.PropertyView; } } } }<file_sep>/Forms/Calendar/Calendar/Samples/BlackoutDates/Views/BlackoutDates.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="BlockoutDates.xaml.cs" company="Syncfusion"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfCalendar { using System; using System.Collections.Generic; using SampleBrowser.Core; using Syncfusion.SfCalendar.XForms; using Xamarin.Forms; /// <summary> /// Blackout Dates /// </summary> public partial class BlackoutDates : SampleView { /// <summary> /// Initializes a new instance of the <see cref="BlackoutDates" /> class /// </summary> public BlackoutDates() { this.InitializeComponent(); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DocIO/FormFillingandProtection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class FormFillingAndProtection : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton button; public FormFillingAndProtection() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to fill data and protect the content controls in an existing Word document."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 60); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 60); } this.AddSubview(label); button.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(5, 80, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 80, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.ContentControlTemplate.docx"); //Creates an empty Word document instance. WordDocument document = new WordDocument(); //Opens template document. document.Open(inputStream, FormatType.Word2013); IWTextRange textRange; //Gets table from the template document. IWTable table = document.LastSection.Tables[0]; WTableRow row = table.Rows[1]; #region Inserting content controls #region Calendar content control IWParagraph cellPara = row.Cells[0].Paragraphs[0]; //Accesses the date picker content control. IInlineContentControl inlineControl = (cellPara.ChildEntities[2] as IInlineContentControl); textRange = inlineControl.ParagraphItems[0] as WTextRange; //Sets today's date to display. textRange.Text = DateTime.Now.ToShortDateString(); textRange.CharacterFormat.FontSize = 14; //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; #endregion #region Plain text content controls table = document.LastSection.Tables[1]; row = table.Rows[0]; cellPara = row.Cells[0].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; textRange = inlineControl.ParagraphItems[0] as WTextRange; //Sets text in plain text content control. textRange.Text = "Northwind Analytics"; textRange.CharacterFormat.FontSize = 14; cellPara = row.Cells[1].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; textRange = inlineControl.ParagraphItems[0] as WTextRange; //Sets text in plain text content control. textRange.Text = "Northwind"; textRange.CharacterFormat.FontSize = 14; row = table.Rows[1]; cellPara = row.Cells[0].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; //Sets text in plain text content control. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = "10"; textRange.CharacterFormat.FontSize = 14; cellPara = row.Cells[1].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; //Sets text in plain text content control. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = "<NAME>"; textRange.CharacterFormat.FontSize = 14; #endregion #region CheckBox Content control row = table.Rows[2]; cellPara = row.Cells[0].LastParagraph; //Inserts checkbox content control. inlineControl = cellPara.AppendInlineContentControl(ContentControlType.CheckBox); inlineControl.ContentControlProperties.LockContents = true; //Sets checkbox as checked state. inlineControl.ContentControlProperties.IsChecked = true; textRange = cellPara.AppendText("C#, "); textRange.CharacterFormat.FontSize = 14; //Inserts checkbox content control. inlineControl = cellPara.AppendInlineContentControl(ContentControlType.CheckBox); inlineControl.ContentControlProperties.LockContents = true; //Sets checkbox as checked state. inlineControl.ContentControlProperties.IsChecked = true; textRange = cellPara.AppendText("VB"); textRange.CharacterFormat.FontSize = 14; #endregion #region Drop down list content control cellPara = row.Cells[1].LastParagraph; //Accesses the dropdown list content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); inlineControl.ContentControlProperties.LockContents = true; //Sets default option to display. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = "ASP.NET"; textRange.CharacterFormat.FontSize = 14; inlineControl.ParagraphItems.Add(textRange); //Adds items to the dropdown list. ContentControlListItem item; item = new ContentControlListItem(); item.DisplayText = "ASP.NET MVC"; item.Value = "2"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); item = new ContentControlListItem(); item.DisplayText = "Windows Forms"; item.Value = "3"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); item = new ContentControlListItem(); item.DisplayText = "WPF"; item.Value = "4"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); item = new ContentControlListItem(); item.DisplayText = "Xamarin"; item.Value = "5"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); #endregion #region Calendar content control row = table.Rows[3]; cellPara = row.Cells[0].LastParagraph; //Accesses the date picker content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); inlineControl.ContentControlProperties.LockContents = true; //Sets default date to display. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = DateTime.Now.AddDays(-5).ToShortDateString(); textRange.CharacterFormat.FontSize = 14; cellPara = row.Cells[1].LastParagraph; //Inserts date picker content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); inlineControl.ContentControlProperties.LockContents = true; //Sets default date to display. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = DateTime.Now.AddDays(10).ToShortDateString(); textRange.CharacterFormat.FontSize = 14; #endregion #endregion #region Block content control //Accesses the block content control. BlockContentControl blockContentControl = ((document.ChildEntities[0] as WSection).Body.ChildEntities[2] as BlockContentControl); //Protects the block content control blockContentControl.ContentControlProperties.LockContents = true; #endregion MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("FormFillingAndProtection.docx", "application/msword", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Frame; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Popup/TicketBooking.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Syncfusion.SfDataGrid; using Syncfusion.SfPopupLayout; namespace SampleBrowser { public class TicketBooking : SampleView { #region Fields internal static SfDataGrid datagrid; TicketBookingViewModel viewModel; internal static SfPopupLayout popupLayout; #endregion #region Constructor public TicketBooking() { CreateDataGrid(); CreatePopup(); this.AddSubview(popupLayout); } #endregion private void CreateDataGrid() { datagrid = new SfDataGrid(); viewModel = new TicketBookingViewModel(); datagrid.AutoGenerateColumns = false; datagrid.ColumnSizer = ColumnSizer.Star; datagrid.RowHeight = 117; GridTextColumn movieList = new GridTextColumn(); movieList.HeaderText = "Movies List"; movieList.HeaderTextAlignment = UIKit.UITextAlignment.Center; movieList.UserCellType = typeof(MovieTile); datagrid.Columns.Add(movieList); datagrid.ItemsSource = viewModel.TheaterInformation; } private void CreatePopup() { popupLayout = new SfPopupLayout(); popupLayout.Content = datagrid; } public override void LayoutSubviews() { popupLayout.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } } } <file_sep>/Forms/Button/Button/Samples/CustomizationSample/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Buttons; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Xamarin.Forms; namespace SampleBrowser.SfButton { #region View Model for Getting Started Sample public class ViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// The border color of button. /// </summary> private Color borderColor = Color.Black; /// <summary> /// The background color of button. /// </summary> private Color backgroundColor = Color.FromHex("#af2463"); /// <summary> /// Represents the text color /// </summary> private Color textColor = Color.White; /// <summary> /// The border thickness of button. /// </summary> private double borderThickness = 0; /// <summary> /// The left side corner radius slider. /// </summary> private double leftSideValue = 25; /// <summary> /// The right side corner value /// </summary> private double rightSideValue = 25; /// <summary> /// The corner radius of button. /// </summary> private Thickness cornerRadius = 20; /// <summary> /// The text of button. /// </summary> private string text = "ADD TO CART"; /// <summary> /// The can show background image /// </summary> private bool canShowBackgroundImage = false; /// <summary> /// Represents the font family /// </summary> private string SegoeFontFamily; /// <summary> /// Represents the border width /// </summary> private double borderWidth = 1; /// <summary> /// Represents the visibility of image /// </summary> private bool showImage = true; /// <summary> /// Represents the enable or disable the shadow /// </summary> private bool enableShadow; #endregion #region Property public ObservableCollection<SfSegmentItem> PrimaryColors { get; set; } /// <summary> /// Gets or sets the color of the border of button. /// </summary> /// <value>The color of the border of button.</value> public Color BorderColor { get { return borderColor; } set { borderColor = value; OnPropertyChanged("BorderColor"); } } /// <summary> /// Gets or Sets the text color /// </summary> public Color TextColor { get { return textColor; } set { textColor = value; OnPropertyChanged("TextColor"); } } /// <summary> /// Gets or sets the background color of button. /// </summary> /// <value>The background color of button</value> public Color BackgroundColor { get { return backgroundColor; } set { backgroundColor = value; OnPropertyChanged("BackgroundColor"); } } /// <summary> /// Gets or sets the thickness of border. /// </summary> /// <value>The border thickness.</value> public double BorderThickness { get { return borderThickness; } set { borderThickness = value; OnPropertyChanged("BorderThickness"); } } /// <summary> /// Gets or sets the slider value. /// </summary> /// <value>The slider value.</value> public double LeftSliderValue { get { return leftSideValue; } set { leftSideValue = value; CornerRadius = new Thickness(value, cornerRadius.Top, cornerRadius.Right, value); OnPropertyChanged("LeftSliderValue"); } } /// <summary> /// Gets or Sets the right side corner value /// </summary> public double RightSliderValue { get { return rightSideValue; } set { rightSideValue = value; CornerRadius = new Thickness(cornerRadius.Left, value, value, cornerRadius.Bottom); OnPropertyChanged("RightSliderValue"); } } /// <summary> /// Gets or sets the corner radius. /// </summary> /// <value>The corner radius.</value> public Thickness CornerRadius { get { return cornerRadius; } set { cornerRadius = value; OnPropertyChanged("CornerRadius"); } } /// <summary> /// Gets or sets the border width. /// </summary> public double BorderWidth { get { return borderWidth; } set { borderWidth = value; OnPropertyChanged("BorderWidth"); } } /// <summary> /// Gets or Sets the image visibility /// </summary> public bool ShowImage { get { return showImage; } set { showImage = value; OnPropertyChanged("ShowImage"); } } /// <summary> /// Gets or sets the text. /// </summary> /// <value>The text.</value> public string Text { get { return text; } set { text = value; OnPropertyChanged("Text"); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:button.buttonViewModel"/> is enable stack. /// </summary> /// <value><c>true</c> if is enable stack; otherwise, <c>false</c>.</value> public bool CanShowBackgroundImage { get { return canShowBackgroundImage; } set { canShowBackgroundImage = value; if (value) { BackgroudImage = "buttonbackground.png"; } else { BackgroudImage = string.Empty; } OnPropertyChanged("CanShowBackgroundImage"); OnPropertyChanged("BackgroudImage"); } } /// <summary> /// Source for transparent background /// </summary> public string BackgroudImage { get; set; } /// <summary> /// Gets or sets whether shadow enable or disable /// </summary> public bool EnableShadow { get { return enableShadow; } set { enableShadow = value; OnPropertyChanged("EnableShadow"); } } #endregion #region Property changed method /// <summary> /// Occurs when property changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// The <see cref=" buttonViewModel" properties changed/> /// </summary> /// <param name="property">Changed Property.</param> public void OnPropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="T:button.buttonViewModel"/> class. /// </summary> public ViewModel() { this.SegoeFontFamily = "button_Segoe MDL2 Assets.ttf"; if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB this.SegoeFontFamily = "/Assets/Fonts/button_Segoe MDL2 Assets.ttf.ttf#Segoe MDL2 Assets"; #else if (Core.SampleBrowser.IsIndividualSB) { this.SegoeFontFamily = "/Assets/Fonts/button_Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; } else { this.SegoeFontFamily = $"ms-appx:///SampleBrowser.SfButton.UWP/Assets/Fonts/button_Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; } #endif } else if (Device.RuntimePlatform == Device.iOS) { this.SegoeFontFamily = "Segoe MDL2 Assets"; } this.PrimaryColors = GetSegmentCollection(); } private ObservableCollection<SfSegmentItem> GetSegmentCollection() { ObservableCollection<SfSegmentItem> segmentCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#ffffff"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#c6c6c6"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#538eed"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#af2463"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#000000"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, }; return segmentCollection; } #endregion } #endregion } <file_sep>/Forms/Picker/Picker/Samples/PopupPicker/PopupPicker.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfPicker { public partial class PopupPicker : SampleView, INotifyPropertyChanged { ObservableCollection<object> todaycollection = new ObservableCollection<object>(); public PopupPicker() { InitializeComponent(); startdate.OnColumnLoaded += Startdate_GetColumnWidth; startdate.Closed += Startdate_OnPopUpClosed; enddate.Closed += Enddate_OnPopUpClosed; enddate.OnColumnLoaded += Startdate_GetColumnWidth; startdate.CancelButtonClicked += Startdate_CancelButtonClicked; enddate.CancelButtonClicked += Enddate_CancelButtonClicked; startdatetxt.Focused += Startdatetxt_Focused; enddatetxt.Focused += Enddatetxt_Focused; startdate.Parent = tempGrid; enddate.Parent = tempGrid; if (Device.RuntimePlatform == Device.Android) { startdate.BackgroundColor = Color.White; enddate.BackgroundColor = Color.White; startdatebutton.WidthRequest = 30; enddatebutton.WidthRequest = 30; } if (Device.RuntimePlatform == Device.Android) { submit.BackgroundColor = Color.FromHex("#009688"); submit.TextColor = Color.White; submit.Text = "SUBMIT"; submit.FontFamily = "sans-serif-medium"; innergrid.WidthRequest = 250; submit.WidthRequest = 250; submit.HeightRequest = 36; startdate.HeaderText = "DATE PICKER"; enddate.HeaderText = "DATE PICKER"; startdate.PickerWidth = 270; enddate.PickerWidth = 270; startlabel.Margin = new Thickness(5, 0, 0, 0); endlabel.Margin = new Thickness(5, 0, 0, 0); header.Margin = new Thickness(0, 0, 0, 50); startdate.SelectedItemFontSize = 22; enddate.SelectedItemFontSize = 22; startdate.ColumnHeaderFontSize = 16; enddate.ColumnHeaderFontSize = 16; } if (Device.RuntimePlatform == Device.iOS) { submit.WidthRequest = 250; submit.HeightRequest = 25; startdate.SelectedItemFontSize = 25; enddate.SelectedItemFontSize = 25; startlayout.HeightRequest = 30; endlayout.HeightRequest = 30; startlabel.TextColor = Color.FromRgba(0, 0, 0, 0.5); endlabel.TextColor = Color.FromRgba(0, 0, 0, 0.5); submit.BorderWidth = 1; innergrid.WidthRequest = 250; header.FontFamily = "HelveticaNeue-Thin"; startdatetxt.FontFamily = "HelveticaNeue-Thin"; enddatetxt.FontFamily = "HelveticaNeue-Thin"; startlabel.FontFamily = "HelveticaNeue-Thin"; endlabel.FontFamily = "HelveticaNeue-Thin"; submit.FontFamily = "HelveticaNeue-Thin"; submit.BorderColor = Color.FromHex("#cdcdcd"); submit.FontSize = 14; startdate.SelectedItemFontFamily = "HelveticaNeue-Thin"; startdate.BorderColor = Color.Gray; startdate.UnSelectedItemFontFamily = "HelveticaNeue-Thin"; enddate.SelectedItemFontFamily = "HelveticaNeue-Thin"; enddate.UnSelectedItemFontFamily = "HelveticaNeue-Thin"; submit.FontAttributes = FontAttributes.Bold; header.Margin = new Thickness(0, 0, 0, 50); startdate.HeaderHeight = 40; enddate.HeaderHeight = 40; } this.BindingContext = new ViewModel(); if (DateTime.Now.Day.ToString().Length != 1) { startdatetxt.Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3) + " " + DateTime.Now.Day.ToString() + " " + DateTime.Now.Year.ToString(); enddatetxt.Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3) + " " + DateTime.Now.Day.ToString() + " " + DateTime.Now.Year.ToString(); } else { startdatetxt.Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3) + " 0" + DateTime.Now.Day.ToString() + " " + DateTime.Now.Year.ToString(); enddatetxt.Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3) + " 0" + DateTime.Now.Day.ToString() + " " + DateTime.Now.Year.ToString(); } //Select today dates todaycollection.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0,3)); if (DateTime.Now.Date.Day < 10) todaycollection.Add("0" + DateTime.Now.Date.Day); else todaycollection.Add(DateTime.Now.Date.Day.ToString()); todaycollection.Add(DateTime.Now.Date.Year.ToString()); if (Device.RuntimePlatform == Device.UWP) { if (Device.Idiom != TargetIdiom.Phone) { grid.HorizontalOptions = LayoutOptions.Start; grid.VerticalOptions = LayoutOptions.Start; grid.Margin = new Thickness(20, 20, 0, 0); header.HorizontalOptions = LayoutOptions.Start; } else { innergrid.WidthRequest = 250; } startdate.HeaderText = "PICK A DATE TIME"; enddate.HeaderText = "PICK A DATE TIME"; innergrid.Margin = new Thickness(0,15,0,0); startdate.PickerHeight = 350; startdate.PickerWidth = 300; enddate.PickerHeight = 350; enddate.PickerWidth = 300; startdatetxt.IsEnabled = true; startdatetxt.HeightRequest = 40; startlabel.TextColor = Color.Gray; endlabel.TextColor = Color.Gray; enddatetxt.HeightRequest = 40; enddatetxt.IsEnabled = true; startdatetxt.VerticalOptions = LayoutOptions.Center; enddatetxt.VerticalOptions = LayoutOptions.Center; submit.BackgroundColor = Color.FromHex("#cdcdcd"); submit.TextColor = Color.Black; submit.Margin = new Thickness(0); submit.HorizontalOptions = LayoutOptions.Start; submit.WidthRequest = 205; submit.Margin = new Thickness(0); submit.HeightRequest = 40; submit.BorderWidth = 0; layout1.Margin = new Thickness(0); layout2.Margin = new Thickness(0); startdate.HeaderText = "PICK A DATE TIME"; enddate.HeaderText = "PICK A DATE TIME"; } var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += (s, e) => { if(Device.RuntimePlatform==Device.Android && Device.RuntimePlatform==Device.iOS) startdate.IsOpen = true; }; startdatetxt.GestureRecognizers.Add(tapGestureRecognizer); var tapGestureRecognizer2 = new TapGestureRecognizer(); tapGestureRecognizer2.Tapped += (s, e) => { if (Device.RuntimePlatform == Device.Android && Device.RuntimePlatform == Device.iOS) enddate.IsOpen = true; }; enddatetxt.GestureRecognizers.Add(tapGestureRecognizer2); } private void Enddatetxt_Focused(object sender, FocusEventArgs e) { enddatetxt.Unfocus(); enddate.IsOpen = true; } private void Startdatetxt_Focused(object sender, FocusEventArgs e) { startdatetxt.Unfocus(); startdate.IsOpen = true; } private void Enddate_OnPopUpClosed(object sender, EventArgs e) { if (string.IsNullOrEmpty(enddatetxt.Text)) { (this.BindingContext as ViewModel).EndDate = todaycollection; } else { (this.BindingContext as ViewModel).EndDate = GetCollectionfromstring(enddatetxt.Text); } } private void Startdate_OnPopUpClosed(object sender, EventArgs e) { if(string.IsNullOrEmpty(startdatetxt.Text)) { (this.BindingContext as ViewModel).StartDate = todaycollection; } else { (this.BindingContext as ViewModel).StartDate = GetCollectionfromstring(startdatetxt.Text); } } private void Enddate_CancelButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { (this.BindingContext as ViewModel).EndDate = GetCollectionfromstring(enddatetxt.Text); } private void Startdate_CancelButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { (this.BindingContext as ViewModel).StartDate = GetCollectionfromstring(startdatetxt.Text); } void Startdate_GetColumnWidth(object sender, Syncfusion.SfPicker.XForms.ColumnLoadedEventArgs e) { //if (Device.RuntimePlatform == Device.Android) //{ // if (e.Column == 0) // { // e.ColumnWidth = 300; // } // else if (e.Column == 1) // { // e.ColumnWidth = 200; // } // else // { // e.ColumnWidth = 300; // } //} } #region get Collections and String ObservableCollection<object> GetCollectionfromList(IList dates) { ObservableCollection<object> items = new ObservableCollection<object>(); foreach (var item in dates) { items.Add(item); } return items; } string GetStringfromCollection(ICollection collection) { string dates = string.Empty; foreach (var item in collection) { dates += item + " "; } return dates; } ObservableCollection<object> GetCollectionfromstring(string text) { if (!string.IsNullOrEmpty(text)) { var str = text.Split(' ').Where(s => !string.IsNullOrEmpty(s)); ObservableCollection<object> items = new ObservableCollection<object>(); foreach (var item in str) { items.Add(item); } return items; } return todaycollection; } #endregion private void Button_Click(object sender, EventArgs e) { startdate.IsOpen = true; } private void Button_Click_1(object sender, EventArgs e) { enddate.IsOpen = true; } private void Button_Clicked(object sender, EventArgs e) { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Success", "Your vacation has been updated from "+startdatetxt.Text.ToString()+" to "+enddatetxt.Text.ToString(), "Ok"); startdatetxt.Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3) + " " + DateTime.Now.Day.ToString() + " " + DateTime.Now.Year.ToString(); enddatetxt.Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0, 3) + " " + DateTime.Now.Day.ToString() + " " + DateTime.Now.Year.ToString(); } private void startdate_OkButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { if ((e.NewValue as IList).Count > 0) { startdatetxt.Text = GetStringfromCollection(GetCollectionfromList(e.NewValue as IList)); (this.BindingContext as ViewModel).StartDate = GetCollectionfromList(e.NewValue as IList); } } private void enddate_OkButtonClicked(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { if ((e.NewValue as IList).Count > 0) { enddatetxt.Text = GetStringfromCollection(GetCollectionfromList(e.NewValue as IList)); (this.BindingContext as ViewModel).EndDate = GetCollectionfromList(e.NewValue as IList); } } } public class ViewModel : INotifyPropertyChanged { private ObservableCollection<object> _startdate; public ObservableCollection<object> StartDate { get { return _startdate; } set { _startdate = value; RaisePropertyChanged("StartDate"); } } private ObservableCollection<object> _enddate; public ObservableCollection<object> EndDate { get { return _enddate; } set { _enddate = value; RaisePropertyChanged("EndDate"); } } void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; public ViewModel() { ObservableCollection<object> todaycollection = new ObservableCollection<object>(); //Select today dates todaycollection.Add(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Date.Month).Substring(0,3)); if (DateTime.Now.Date.Day < 10) todaycollection.Add("0" + DateTime.Now.Date.Day); else todaycollection.Add(DateTime.Now.Date.Day.ToString()); todaycollection.Add(DateTime.Now.Date.Year.ToString()); this.StartDate = todaycollection; this.EndDate = todaycollection; } } public class CustomPickerEntry:Entry { } } <file_sep>/Forms/ListView/ListView/Samples/ItemReordering/Model/GroceryListRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ToDoListRepository { #region Constructor public ToDoListRepository() { } #endregion #region Methods internal ObservableCollection<ToDoItem> GetToDoList() { var groceryList = new ObservableCollection<ToDoItem>(); var random = new Random(); for (int i = 0; i < toDoLists.Count(); i++) { var gallery = new ToDoItem() { Name = toDoLists[i], CategoryName = GetCategoryList(i) }; groceryList.Add(gallery); } return groceryList; } private string GetCategoryList(int pos) { string toDoCategory; if (pos < 4) toDoCategory = toDoCategoryLists[0]; else if (pos < 8) toDoCategory = toDoCategoryLists[1]; else if (pos < 13) toDoCategory = toDoCategoryLists[2]; else toDoCategory = toDoCategoryLists[3]; return toDoCategory; } string[] toDoLists = new string[] { "Reserve party venue", "Choose party attire", "Compile guest list", "Choose invitation", "Create wedding website", "Buy wedding ring", "Apply marriage license", "Hire photographer", "Buy wedding dress", "Refine guest list", "Send invitations", "Hire florist", "Shop for decorations", "Hire musicians", "Arrange catering", "Shop for groceries", "Book hotel for guest", "Plan honeymoon", "Book transportation", "Order wedding cake", }; string[] toDoCategoryLists = new string[] { "This Week", "Next Week", "Next Month", "Later" }; #endregion } } <file_sep>/iOS/SampleBrowser/Samples/DocIO/CustomStyle.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class CustomStyle : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton button; public CustomStyle() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to format the Word document contents with user defined styles."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 60); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 60); } this.AddSubview(label); button.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(5,80, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 80, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { WordDocument document = new WordDocument(); IWParagraphStyle style = null; // Adding a new section to the document. WSection section = document.AddSection() as WSection; //Set Margin of the section section.PageSetup.Margins.All = 72; IWParagraph par = document.LastSection.AddParagraph(); WTextRange range = par.AppendText("Using CustomStyles") as WTextRange; range.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; range.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; range.CharacterFormat.FontSize = 18f; document.LastParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; // Create Paragraph styles style = document.AddParagraphStyle("MyStyle_Normal"); style.CharacterFormat.FontName = "Bitstream Vera Serif"; style.CharacterFormat.FontSize = 10f; style.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify; style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(0, 21, 84); style = document.AddParagraphStyle("MyStyle_Low"); style.CharacterFormat.FontName = "Times New Roman"; style.CharacterFormat.FontSize = 16f; style.CharacterFormat.Bold = true; style = document.AddParagraphStyle("MyStyle_Medium"); style.CharacterFormat.FontName = "Monotype Corsiva"; style.CharacterFormat.FontSize = 18f; style.CharacterFormat.Bold = true; style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(51, 66, 125); style = document.AddParagraphStyle("Mystyle_High"); style.CharacterFormat.FontName = "Bitstream Vera Serif"; style.CharacterFormat.FontSize = 20f; style.CharacterFormat.Bold = true; style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(242, 151, 50); IWParagraph paragraph = null; for (int i = 1; i < document.Styles.Count; i++) { //Skip to apply the document default styles and also paragraph style. if (document.Styles[i].Name == "Normal" || document.Styles[i].Name == "Default Paragraph Font" || document.Styles[i].StyleType != StyleType.ParagraphStyle) continue; // Getting styles from Document. style = (IWParagraphStyle)document.Styles[i]; // Adding a new paragraph section.AddParagraph(); paragraph = section.AddParagraph(); // Applying styles to the current paragraph. paragraph.ApplyStyle(style.Name); // Writing Text with the current style and formatting. paragraph.AppendText("Northwind Database with [" + style.Name + "] Style"); // Adding a new paragraph section.AddParagraph(); paragraph = section.AddParagraph(); // Applying another style to the current paragraph. paragraph.ApplyStyle("MyStyle_Normal"); // Writing text with current style. paragraph.AppendText("The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases. Using Northwind, you can become familiar with how a relational database is structured and how the database objects work together to help you enter, store, manipulate, and print your data."); } #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("CustomStyle.docx", "application/msword", stream); } #endregion } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Frame; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Forms/TabView/TabView.Android/CustomEntryRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Android.Content.Res; using Android.Graphics.Drawables; using Android.Text; using SampleBrowser.SfTabView; using SampleBrowser.SfTabView.Droid; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(CustomizedEntry), typeof(CustomEntryRenderer))] namespace SampleBrowser.SfTabView.Droid { public class CustomEntryRenderer : EntryRenderer { public CustomEntryRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { GradientDrawable gd = new GradientDrawable(); gd.SetColor(global::Android.Graphics.Color.Transparent); this.Control.SetBackground(gd); this.Control.SetRawInputType(InputTypes.TextFlagNoSuggestions); Control.SetHintTextColor(ColorStateList.ValueOf(global::Android.Graphics.Color.White)); } } } } <file_sep>/Android/SampleBrowser/Samples/NumericTextBox/NumericTextBox_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Numerictextbox; using Android.Graphics; using Android.Views.InputMethods; using Android.Text; using Android.Text.Style; namespace SampleBrowser { public class NumericTextBox_Mobile { /********************************* **Local Variable Inizialisation** *********************************/ TextView simpleInterestCalculatorLabel, sILabelSpacing, findingSILabel, formulaLabel; TextView formulaLabelSpacing, principalLabel, principalStackSpacing, interestLabel; TextView InterestcalStackSpacing, period, outputLabel, outputStackSpacing; SfNumericTextBox principalAmountNumericTextBox, outputNumberTextBox; SfNumericTextBox interestNumericTextBox, periodValueNumericTextBox; LinearLayout propertylayout, allowNullLayout, allowDefaultDecimalDigitsLayout; ArrayAdapter<String> cultureDataAdapter; Java.Util.Locale localinfo; Spinner cultureSpinner; int numerHeight, width; bool allownull = true, allowDefaultDecimalDigits = true; public View GetSampleContent(Context con) { SamplePageContent(con); FrameLayout mainFrameLayout = new FrameLayout(con); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.FillVertical); mainFrameLayout.LayoutParameters = layoutParams; //PrincipalAmountNumericTextBox principalAmountNumericTextBox = new SfNumericTextBox(con); principalAmountNumericTextBox.FormatString = "C"; principalAmountNumericTextBox.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); principalAmountNumericTextBox.Value = 1000; principalAmountNumericTextBox.AllowNull = true; principalAmountNumericTextBox.Watermark = "Principal Amount"; principalAmountNumericTextBox.MaximumNumberDecimalDigits = 2; var culture = new Java.Util.Locale("en", "US"); principalAmountNumericTextBox.CultureInfo = culture; principalAmountNumericTextBox.ValueChangeMode = ValueChangeMode.OnKeyFocus; //InterestNumericTextBox interestNumericTextBox = new SfNumericTextBox(con); interestNumericTextBox.FormatString = "P"; interestNumericTextBox.Value = 0.1; interestNumericTextBox.PercentDisplayMode = PercentDisplayMode.Compute; interestNumericTextBox.MaximumNumberDecimalDigits = 2; interestNumericTextBox.ValueChangeMode = ValueChangeMode.OnKeyFocus; interestNumericTextBox.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); interestNumericTextBox.Watermark = "Rate of Interest"; interestNumericTextBox.AllowNull = true; interestNumericTextBox.CultureInfo = culture; //PeriodValueNumericTextBox periodValueNumericTextBox = new SfNumericTextBox(con); periodValueNumericTextBox.FormatString = " years"; periodValueNumericTextBox.Value = 20; periodValueNumericTextBox.MaximumNumberDecimalDigits = 0; periodValueNumericTextBox.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); periodValueNumericTextBox.Watermark = "Period (in years)"; periodValueNumericTextBox.ValueChangeMode = ValueChangeMode.OnKeyFocus; periodValueNumericTextBox.CultureInfo = culture; periodValueNumericTextBox.AllowNull = true; //OutputNumberTextBox outputNumberTextBox = new SfNumericTextBox(con); outputNumberTextBox.FormatString = "c"; outputNumberTextBox.MaximumNumberDecimalDigits = 0; outputNumberTextBox.AllowNull = true; outputNumberTextBox.CultureInfo = culture; outputNumberTextBox.Watermark = "Enter Values"; outputNumberTextBox.Clickable = false; outputNumberTextBox.Value = (float)(1000 * 0.1 * 20); outputNumberTextBox.Enabled = false; outputNumberTextBox.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); outputNumberTextBox.ValueChangeMode = ValueChangeMode.OnLostFocus; //Numerictextbox Value Changed Listener principalAmountNumericTextBox.ValueChanged += (object sender, ValueChangedEventArgs e) => { if (e.Value != null && periodValueNumericTextBox.Value != null && interestNumericTextBox.Value != null) outputNumberTextBox.Value = Double.Parse(e.Value.ToString()) * Double.Parse(periodValueNumericTextBox.Value.ToString()) * Double.Parse(interestNumericTextBox.Value.ToString()); }; periodValueNumericTextBox.ValueChanged += (object sender, ValueChangedEventArgs e) => { if (e.Value != null && principalAmountNumericTextBox.Value != null && interestNumericTextBox.Value != null) outputNumberTextBox.Value = Double.Parse(e.Value.ToString()) * Double.Parse(principalAmountNumericTextBox.Value.ToString()) * Double.Parse(interestNumericTextBox.Value.ToString()); }; interestNumericTextBox.ValueChanged += (object sender, ValueChangedEventArgs e) => { if (e.Value != null && principalAmountNumericTextBox.Value != null && periodValueNumericTextBox.Value != null) outputNumberTextBox.Value = Double.Parse(e.Value.ToString()) * Double.Parse(principalAmountNumericTextBox.Value.ToString()) * Double.Parse(periodValueNumericTextBox.Value.ToString()); }; mainFrameLayout.AddView(GetView(con)); ScrollView mainScrollView = new ScrollView(con); mainScrollView.AddView(mainFrameLayout); return mainScrollView; } private LinearLayout GetView(Context con) { //mainLayout LinearLayout mainLayout = new LinearLayout(con); mainLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); mainLayout.SetGravity(GravityFlags.FillVertical); mainLayout.Orientation = Orientation.Vertical; mainLayout.AddView(simpleInterestCalculatorLabel); mainLayout.AddView(sILabelSpacing); mainLayout.AddView(findingSILabel); mainLayout.FocusableInTouchMode = true; mainLayout.AddView(formulaLabel); mainLayout.AddView(formulaLabelSpacing); LinearLayout principalStack = new LinearLayout(con); principalStack.Orientation = Orientation.Horizontal; principalStack.AddView(principalLabel); principalStack.AddView(principalAmountNumericTextBox); mainLayout.AddView(principalStack); mainLayout.AddView(principalStackSpacing); LinearLayout InterestcalStack = new LinearLayout(con); InterestcalStack.Orientation = Orientation.Horizontal; InterestcalStack.AddView(interestLabel); InterestcalStack.AddView(interestNumericTextBox); mainLayout.AddView(InterestcalStack); mainLayout.AddView(InterestcalStackSpacing); LinearLayout periodStack = new LinearLayout(con); periodStack.Orientation = Orientation.Horizontal; periodStack.AddView(period); periodStack.AddView(periodValueNumericTextBox); mainLayout.AddView(periodStack); LinearLayout outputStack = new LinearLayout(con); outputStack.Orientation = Orientation.Horizontal; outputStack.AddView(outputLabel); if (con.Resources.DisplayMetrics.Density > 1.5) { outputStack.SetY(60); } outputStack.AddView(outputNumberTextBox); mainLayout.AddView(outputStack); mainLayout.SetPadding(20, 20, 10, 20); mainLayout.AddView(outputStackSpacing); mainLayout.Touch += (object sender, View.TouchEventArgs e) => { if (outputNumberTextBox.IsFocused || interestNumericTextBox.IsFocused || periodValueNumericTextBox.IsFocused || principalAmountNumericTextBox.IsFocused) { Rect outRect = new Rect(); outputNumberTextBox.GetGlobalVisibleRect(outRect); interestNumericTextBox.GetGlobalVisibleRect(outRect); periodValueNumericTextBox.GetGlobalVisibleRect(outRect); principalAmountNumericTextBox.GetGlobalVisibleRect(outRect); if (!outRect.Contains((int)e.Event.RawX, (int)e.Event.RawY)) { outputNumberTextBox.ClearFocus(); interestNumericTextBox.ClearFocus(); periodValueNumericTextBox.ClearFocus(); principalAmountNumericTextBox.ClearFocus(); } hideSoftKeyboard((Activity)con); } }; return mainLayout; } private void SamplePageContent(Context con) { numerHeight = getDimensionPixelSize(con, Resource.Dimension.numeric_txt_ht); width = con.Resources.DisplayMetrics.WidthPixels - 40; //SimpleInterestCalculatorLabel simpleInterestCalculatorLabel = new TextView(con); simpleInterestCalculatorLabel.Text = "Simple Interest Calculator"; simpleInterestCalculatorLabel.Gravity = GravityFlags.Center; simpleInterestCalculatorLabel.TextSize = 24; //FindingSILabel findingSILabel = new TextView(con); findingSILabel.Text = "The formula for finding simple interest is:"; findingSILabel.TextSize = 18; SpannableStringBuilder formulaBuilder = new SpannableStringBuilder(); //FormulaLabel formulaLabel = new TextView(con); String interest = "Interest"; SpannableString interestSpannable = new SpannableString(interest); interestSpannable.SetSpan(new ForegroundColorSpan(Color.ParseColor("#66BB6A")), 0, interest.Length, 0); formulaBuilder.Append(interestSpannable); formulaBuilder.Append(" = Principal * Rate * Time"); formulaLabel.SetText(formulaBuilder, TextView.BufferType.Spannable); formulaLabel.TextSize = 18; //PrincipalLabel principalLabel = new TextView(con); principalLabel.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); principalLabel.Text = "Principal"; principalLabel.TextSize = 20; //InterestLabel interestLabel = new TextView(con); interestLabel.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); interestLabel.Text = "Interest Rate"; interestLabel.TextSize = 20; //periodLabel period = new TextView(con); period.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); period.Text = "Term"; period.TextSize = 20; //outputLabel outputLabel = new TextView(con); outputLabel.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); outputLabel.Text = "Interest"; outputLabel.TextSize = 20; outputLabel.SetTextColor(Color.ParseColor("#66BB6A")); //SpacingLabel sILabelSpacing = new TextView(con); formulaLabelSpacing = new TextView(con); principalStackSpacing = new TextView(con); InterestcalStackSpacing = new TextView(con); outputStackSpacing = new TextView(con); } /************************ **Apply Changes Method** ************************/ public void OnApplyChanges() { principalAmountNumericTextBox.CultureInfo = localinfo; outputNumberTextBox.CultureInfo = localinfo; principalAmountNumericTextBox.AllowNull = allownull; periodValueNumericTextBox.AllowNull = allownull; interestNumericTextBox.AllowNull = allownull; principalAmountNumericTextBox.AllowDefaultDecimalDigits = allowDefaultDecimalDigits; interestNumericTextBox.AllowDefaultDecimalDigits = allowDefaultDecimalDigits; } public View GetPropertyWindowLayout(Context context) { width = (context.Resources.DisplayMetrics.WidthPixels) / 2; propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; /*********** **Culture** ***********/ LinearLayout.LayoutParams cultureLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); cultureLayoutParams.SetMargins(0, 20, 0, 0); //Culture Text TextView culturetxt = new TextView(context); culturetxt.TextSize = 20; culturetxt.Text = "Culture"; //CultureList List<String> cultureList = new List<String>(); cultureList.Add("United States"); cultureList.Add("United Kingdom"); cultureList.Add("Japan"); cultureList.Add("France"); cultureList.Add("Italy"); cultureDataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, cultureList); cultureDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //CultureSpinner cultureSpinner = new Spinner(context,SpinnerMode.Dialog); cultureSpinner.Adapter = cultureDataAdapter; //CultureSpinner ItemSelected Listener cultureSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = cultureDataAdapter.GetItem(e.Position); if (selectedItem.Equals("United States")) { localinfo = Java.Util.Locale.Us; } if (selectedItem.Equals("United Kingdom")) { localinfo = Java.Util.Locale.Uk; } if (selectedItem.Equals("Japan")) { localinfo = Java.Util.Locale.Japan; } if (selectedItem.Equals("France")) { localinfo = Java.Util.Locale.France; } if (selectedItem.Equals("Italy")) { localinfo = Java.Util.Locale.Italy; } }; propertylayout.AddView(culturetxt); propertylayout.AddView(cultureSpinner); //CultureSeparate SeparatorView cultureSeparate = new SeparatorView(context, width * 2); cultureSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); // propertylayout.AddView(cultureSeparate, cultureLayoutParams); /************* **AllowNull** *************/ TextView allowNullText = new TextView(context); allowNullText.Text = "Allow Null"; allowNullText.Gravity = GravityFlags.Center; allowNullText.TextSize = 20; //AllowNullCheckBox Switch allowNullCheckBox = new Switch(context); allowNullCheckBox.Checked = true; allowNullCheckBox.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { if (!eve.IsChecked) allownull = false; else allownull = true; }; LinearLayout.LayoutParams allowNullCheckBoxLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); allowNullCheckBoxLayoutParams.SetMargins(0, 10, 0, 0); LinearLayout.LayoutParams allowNullTextLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, 70); allowNullTextLayoutParams.SetMargins(0, 10, 0, 0); TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //AllowNullLayout allowNullLayout = new LinearLayout(context); allowNullLayout.AddView(allowNullText); allowNullLayout.AddView(allowNullCheckBox, allowNullCheckBoxLayoutParams); allowNullLayout.Orientation = Orientation.Horizontal; propertylayout.AddView(allowNullLayout); /************* **AllowDefaultDecimalDigits** *************/ TextView allowDefaultDecimalDigitsText = new TextView(context); allowDefaultDecimalDigitsText.Text = "Allow Default Decimal Digits"; allowDefaultDecimalDigitsText.Gravity = GravityFlags.Center; allowDefaultDecimalDigitsText.TextSize = 20; //AllowDefaultDecimalDigits checkbox Switch allowDefaultDecimalDigitsCheckBox = new Switch(context); allowDefaultDecimalDigitsCheckBox.Checked = true; allowDefaultDecimalDigitsCheckBox.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { if (!eve.IsChecked) allowDefaultDecimalDigits = false; else allowDefaultDecimalDigits = true; }; LinearLayout.LayoutParams allowDefaultDecimalDigitsTextCheckBoxLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); allowNullCheckBoxLayoutParams.SetMargins(0, 10, 0, 0); //AllowDefaultDecimalDigits layout allowDefaultDecimalDigitsLayout = new LinearLayout(context); allowDefaultDecimalDigitsLayout.AddView(allowDefaultDecimalDigitsText); allowDefaultDecimalDigitsLayout.AddView(allowDefaultDecimalDigitsCheckBox, allowDefaultDecimalDigitsTextCheckBoxLayoutParams); allowDefaultDecimalDigitsLayout.Orientation = Orientation.Horizontal; propertylayout.AddView(allowDefaultDecimalDigitsLayout); TextView textSpacing1 = new TextView(context); propertylayout.AddView(textSpacing1); //AllowNullSeparate SeparatorView allowNullSeparate = new SeparatorView(context, width * 2); allowNullSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams allowNullLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); allowNullLayoutParams.SetMargins(0, 20, 15, 0); // propertylayout.AddView(allowNullSeparate, allowNullLayoutParams); propertylayout.SetPadding(5, 0, 5, 0); return propertylayout; } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); inputMethodManager.HideSoftInputFromWindow(activity.CurrentFocus.WindowToken, 0); } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } } } <file_sep>/Forms/TabView/TabView/Samples/NestedTab/View/NestedTab.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XForms.TabView; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SampleBrowser.Core; using System.Collections.ObjectModel; using System.Linq; namespace SampleBrowser.SfTabView { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class NestedTab : SampleView { public NestedTab() { InitializeComponent(); this.BindingContext = new ViewModel(); this.simTab.SelectionIndicatorSettings = new SelectionIndicatorSettings() { Position = SelectionIndicatorPosition.Fill, Color = Color.FromHex("#FF00AFF0") }; this.ContactTab1.SelectionIndicatorSettings = this.ContactTab2.SelectionIndicatorSettings = this.CallsTab1.SelectionIndicatorSettings = this.CallTab2.SelectionIndicatorSettings = new SelectionIndicatorSettings() { Position = SelectionIndicatorPosition.Top }; SfTabItem item = new SfTabItem(); //item.Title } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/RadialMenu/TableSourceCollection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Foundation; using UIKit; namespace SampleBrowser { public class TableSourceCollection : UITableViewSource { protected string[] tableItems; protected string cellIdentifier = "TableCell"; //HomeScreen owner; public TableSourceCollection(string[] items) { tableItems = items; //this.owner = owner; } public override nint NumberOfSections(UITableView tableView) { return 1; } public override nint RowsInSection(UITableView tableview, nint section) { return tableItems.Length; } public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) return 16; else return 32; } /// <summary> /// Called by the TableView to get the actual UITableViewCell to render for the particular row /// </summary> public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier); string item = tableItems[indexPath.Row]; //---- if there are no cells to reuse, create a new one if (cell == null) { cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier); } if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) cell.TextLabel.Font = UIFont.FromName("Helvetica", 12f); else cell.TextLabel.Font = UIFont.FromName("Helvetica", 18f); cell.TextLabel.Text = item; return cell; } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/TemplateColumn/FormattedCell.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Syncfusion.Data; using Android.Graphics; using Android.Widget; using System.Reflection; using Android.Content; using System.IO; namespace SampleBrowser { public class GridImageCell:GridCell { private ImageView customerImage; Bitmap bitmap; public GridImageCell (Context context) : base (context) { customerImage = new ImageView (context); this.CanRendererUnload = false; this.AddView (customerImage); } public MemoryStream LoadResource (String name) { MemoryStream aMem = new MemoryStream (); var assm = Assembly.GetExecutingAssembly (); var path = String.Format ("DataGrid.Resources.drawable.{0}", name); var aStream = assm.GetManifestResourceStream (path); aStream.CopyTo (aMem); return aMem; } protected override void UnLoad () { if (this.Parent != null) (this.Parent as VirtualizingCellsControl).RemoveView (this); } protected override void OnLayout (bool changed, int left, int top, int right, int bottom) { customerImage.Layout (0, 5, this.Width, this.Height - 5); } public override void Draw (Canvas canvas) { base.Draw (canvas); bitmap = (Bitmap)DataColumn.RowData.GetType ().GetProperty ("CustomerImage").GetValue (DataColumn.RowData); customerImage.SetImageBitmap (bitmap); } protected override void Dispose (bool disposing) { if (bitmap != null) { this.customerImage.Dispose (); this.customerImage = null; } base.Dispose (disposing); } } public class BoolFormatCell : GridCell { private ToggleButton isOpen; public BoolFormatCell (Context ctxt) : base (ctxt) { isOpen = new ToggleButton (ctxt); isOpen.SetTextColor (Color.Rgb (51, 51, 51)); isOpen.TextOn = "Open"; isOpen.TextOff = "Closed"; isOpen.Click += isOpen_Click; CanRendererUnload = false; this.AddView (isOpen); } void isOpen_Click (object sender, EventArgs e) { bool isChecked = (sender as ToggleButton).Checked; DataColumn.Renderer.DataGrid.View.GetPropertyAccessProvider().SetValue(DataColumn.RowData, DataColumn.GridColumn.MappingName, isChecked); } protected override void UnLoad () { if (this.Parent != null) (this.Parent as VirtualizingCellsControl).RemoveView (this); } protected override void OnLayout (bool changed, int left, int top, int right, int bottom) { isOpen.Layout (35, 20, this.Width - 35, bottom - 20); } public override void Draw (Canvas canvas) { base.Draw (canvas); isOpen.Checked = Convert.ToBoolean (DataColumn.CellValue); } protected override void Dispose (bool disposing) { this.isOpen.Click -= isOpen_Click; this.isOpen.Dispose (); this.isOpen = null; base.Dispose (disposing); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/PieSeries.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Com.Syncfusion.Navigationdrawer; using System.Collections.Generic; namespace SampleBrowser { public class Pie : SamplePage { PieSeries pieSeries; TextView groupToValue; TextView groupMode; List<string> groupModeType; public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "Sales by Sales Person"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Android.Graphics.Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.OverflowMode = ChartLegendOverflowMode.Wrap; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; pieSeries = new PieSeries(); pieSeries.TooltipEnabled = true; pieSeries.GroupTo = 25; pieSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; pieSeries.ItemsSource = MainPage.GetPieData(); pieSeries.XBindingPath = "XValue"; pieSeries.YBindingPath = "YValue"; pieSeries.DataMarker.ShowLabel = true; pieSeries.DataMarker.LabelStyle.LabelFormat = "#.#'%'"; pieSeries.EnableAnimation = true; pieSeries.CircularCoefficient = 0.7; pieSeries.StrokeWidth = 1; pieSeries.StrokeColor = Android.Graphics.Color.White; chart.Series.Add(pieSeries); return chart; } public override View GetPropertyWindowLayout(Android.Content.Context context) { int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; LinearLayout propertylayout = new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams( width * 2, 2); groupToValue = new TextView(context); groupToValue.Text = "GroupTo Value is 25"; groupToValue.SetPadding(5, 20, 0, 20); SeekBar groupTo = new SeekBar(context); groupTo.Progress = 25; groupTo.Max = 40; groupTo.ProgressChanged += GroupTo_ProgressChanged; groupMode = new TextView(context); groupMode.Text = "GroupMode"; Spinner selectLabelMode = new Spinner(context, SpinnerMode.Dialog); groupModeType = new List<string>() { "Value", "Percentage", "Angle" }; ArrayAdapter<string> dataAdapter = new ArrayAdapter<string> (context, Android.Resource.Layout.SimpleSpinnerItem, groupModeType); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += SelectLabelMode_ItemSelected; propertylayout.AddView(groupToValue); propertylayout.AddView(groupTo); propertylayout.AddView(groupMode); propertylayout.AddView(selectLabelMode); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); propertylayout.AddView(separate, layoutParams1); return propertylayout; } void GroupTo_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { groupToValue.Text = "groupToValue is " + ((int)e.Progress).ToString(); pieSeries.GroupTo = (int)e.Progress; } void SelectLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { switch (e.Position) { case 0: pieSeries.GroupMode = PieGroupMode.Value; break; case 1: pieSeries.GroupMode = PieGroupMode.Percentage; break; case 2: pieSeries.GroupMode = PieGroupMode.Angle; break; } } } }<file_sep>/Forms/DocIO/DocIO/Samples/DocIO_BarChart/DocIO_BarChart.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.Core; using System.IO; using System.Reflection; using Syncfusion.DocIO.DLS; using Syncfusion.DocIO; using Syncfusion.OfficeChart; using Xamarin.Forms; namespace SampleBrowser.DocIO { public partial class DocIO_BarChart : SampleView { public DocIO_BarChart() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { //if (!SampleBrowser.DocIO.App.isUWP) //{ // this.Content_1.FontSize = 18.5; //} //else //{ this.Content_1.FontSize = 13.5; //} this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } private void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = typeof(DocIO_BarChart).GetTypeInfo().Assembly; //A new document is created. WordDocument document = new WordDocument(); //Add new section to the Word document IWSection section = document.AddSection(); //Set page margins of the section section.PageSetup.Margins.All = 72; //Add new paragraph to the section IWParagraph paragraph = section.AddParagraph(); //Apply heading style to the title paragraph paragraph.ApplyStyle(BuiltinStyle.Heading1); //Apply center alignment to the paragraph paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; //Append text to the paragraph paragraph.AppendText("Northwind Management Report").CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(46, 116, 181); //Add new paragraph paragraph = section.AddParagraph(); //Set before spacing to the paragraph paragraph.ParagraphFormat.BeforeSpacing = 20; #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif //Load the excel template as stream Stream excelStream = assembly.GetManifestResourceStream(rootPath + "Excel_Template.xlsx"); //Create and Append chart to the paragraph with excel stream as parameter WChart barChart = paragraph.AppendChart(excelStream, 1, "B2:C6", 470, 300); //Set chart data barChart.ChartType = OfficeChartType.Bar_Clustered; barChart.ChartTitle = "Purchase Details"; barChart.ChartTitleArea.FontName = "Calibri (Body)"; barChart.ChartTitleArea.Size = 14; //Set name to chart series barChart.Series[0].Name = "Sum of Purchases"; barChart.Series[1].Name = "Sum of Future Expenses"; //Set Chart Data table barChart.HasDataTable = true; barChart.DataTable.HasBorders = true; barChart.DataTable.HasHorzBorder = true; barChart.DataTable.HasVertBorder = true; barChart.DataTable.ShowSeriesKeys = true; barChart.HasLegend = false; //Setting background color barChart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(208, 206, 206); barChart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(208, 206, 206); //Setting line pattern to the chart area barChart.PrimaryCategoryAxis.Border.LinePattern = OfficeChartLinePattern.None; barChart.PrimaryValueAxis.Border.LinePattern = OfficeChartLinePattern.None; barChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; barChart.PrimaryValueAxis.MajorGridLines.Border.LineColor = Syncfusion.Drawing.Color.FromArgb(175, 171, 171); //Set label for primary catagory axis barChart.PrimaryCategoryAxis.CategoryLabels = barChart.ChartData[2, 1, 6, 1]; #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("BarChart.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("BarChart.docx", "application/msword", stream); #endregion } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/GroupDataTimeConverter.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GroupDataTimeConverter.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using Syncfusion.Data; using Xamarin.Forms; /// <summary> /// Converter for CustomGrouping sample. /// </summary> public class GroupDataTimeConverter : IValueConverter { /// <summary> /// Initializes a new instance of the GroupDataTimeConverter class. /// </summary> public GroupDataTimeConverter() { } /// <param name="value">The value to convert.</param> /// <param name="targetType">The type to which to convert the value.</param> /// <param name="parameter">A parameter to use during the conversion.</param> /// <param name="culture">The culture to use during the conversion.</param> /// <summary>Implement this method to convert <paramref name="value" /> to <paramref name="targetType" /> by using <paramref name="parameter" /> and <paramref name="culture" />.</summary> /// <returns>To be added.</returns> public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) { var saleinfo = value as SalesByDate; if (saleinfo.Total > 1000 && saleinfo.Total < 5000) { return ">1 K and <5 K"; } else if (saleinfo.Total > 5000 && saleinfo.Total < 10000) { return ">5 K and <10 K"; } else if (saleinfo.Total > 10000 && saleinfo.Total < 50000) { return ">10 K and <50 K"; } else if (saleinfo.Total > 20000 && saleinfo.Total < 50000) { return ">20 K and <50 K"; } else if (saleinfo.Total > 50000) { return ">50 K"; } else { return "<1 K"; } } /// <param name="value">The value to convert.</param> /// <param name="targetType">The type to which to convert the value.</param> /// <param name="parameter">A parameter to use during the conversion.</param> /// <param name="culture">The culture to use during the conversion.</param> /// <summary> Implement this method to convert <paramref name="value" /> back from <paramref name="targetType" /> by using <paramref name="parameter" /> and <paramref name="culture" />.</summary> /// <returns> To be added.</returns> public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) { throw new System.NotImplementedException(); } } } <file_sep>/Forms/Border/Border/Samples/GettingStartedSample/GettingStartedSampleViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Buttons; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Xamarin.Forms; namespace SampleBrowser.SfBorder { #region View Model for Getting Started Sample public class GettingStartedSampleViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// The border color of button. /// </summary> private Color borderColor = Color.LightGray; /// <summary> /// The background color of button. /// </summary> private Color backgroundColor = Color.FromHex("#2f7dc0"); /// <summary> /// The left side corner radius slider. /// </summary> private double leftSideValue = 0; /// <summary> /// The right side corner value /// </summary> private double rightSideValue = 25; /// <summary> /// The right side corner value /// </summary> private double bottomrightSideValue = 0; /// <summary> /// The right side corner value /// </summary> private double bottomleftSideValue = 16; /// <summary> /// The corner radius of button. /// </summary> private Thickness cornerRadius = 10; /// <summary> /// Represents the border width /// </summary> private double borderWidth = 1; /// <summary> /// Represents the font family /// </summary> private string SegoeFontFamily; /// <summary> /// Represents the enable or disable the shadow /// </summary> private bool enableShadow = false; /// <summary> /// Represents the border offset /// </summary> private double borderOffset = 0; #endregion #region Property public ObservableCollection<SfSegmentItem> PrimaryColors { get; set; } /// <summary> /// Gets or sets the color of the border of button. /// </summary> /// <value>The color of the border of button.</value> public Color BorderColor { get { return borderColor; } set { borderColor = value; OnPropertyChanged("BorderColor"); } } /// <summary> /// Gets or sets the background color of button. /// </summary> /// <value>The background color of button</value> public Color BackgroundColor { get { return backgroundColor; } set { backgroundColor = value; OnPropertyChanged("BackgroundColor"); } } /// <summary> /// Gets or sets the slider value. /// </summary> /// <value>The slider value.</value> public double LeftSliderValue { get { return leftSideValue; } set { leftSideValue = value; CornerRadius = new Thickness(value, cornerRadius.Top, cornerRadius.Right, cornerRadius.Bottom); OnPropertyChanged("LeftSliderValue"); } } /// <summary> /// Gets or Sets the right side corner value /// </summary> public double RightSliderValue { get { return rightSideValue; } set { rightSideValue = value; CornerRadius = new Thickness(cornerRadius.Left, value, cornerRadius.Right, cornerRadius.Bottom); OnPropertyChanged("RightSliderValue"); } } /// <summary> /// Gets or sets the slider value. /// </summary> /// <value>The slider value.</value> public double BottomLeftSliderValue { get { return bottomleftSideValue; } set { bottomleftSideValue = value; CornerRadius = new Thickness(cornerRadius.Left, cornerRadius.Top, cornerRadius.Right, value); OnPropertyChanged("BottomLeftSliderValue"); } } /// <summary> /// Gets or sets the slider value. /// </summary> /// <value>The slider value.</value> public double BottomRightSliderValue { get { return bottomrightSideValue; } set { bottomrightSideValue = value; CornerRadius = new Thickness(cornerRadius.Left, cornerRadius.Top, value, cornerRadius.Bottom); OnPropertyChanged("BottomRightSliderValue"); } } /// <summary> /// Gets or sets the corner radius. /// </summary> /// <value>The corner radius.</value> public Thickness CornerRadius { get { return cornerRadius; } set { cornerRadius = value; OnPropertyChanged("CornerRadius"); } } /// <summary> /// Gets or sets the border width. /// </summary> public double BorderWidth { get { return borderWidth; } set { borderWidth = value; OnPropertyChanged("BorderWidth"); } } /// <summary> /// Gets or sets whether shadow enable or disable /// </summary> public bool EnableShadow { get { return enableShadow; } set { enableShadow = value; OnPropertyChanged("EnableShadow"); } } /// <summary> /// Gets or sets the border offset. /// </summary> public double BorderOffset { get { return borderOffset; } set { borderOffset = value; OnPropertyChanged("BorderOffset"); } } #endregion #region Property changed method /// <summary> /// Occurs when property changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// The <see cref=" buttonViewModel" properties changed/> /// </summary> /// <param name="property">Changed Property.</param> public void OnPropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="T:button.buttonViewModel"/> class. /// </summary> public GettingStartedSampleViewModel() { this.SegoeFontFamily = "border_Segoe MDL2 Assets.ttf"; if (Device.RuntimePlatform == Device.UWP || (Device.RuntimePlatform == Device.iOS)) { this.SegoeFontFamily = "Segoe MDL2 Assets"; } this.PrimaryColors = GetSegmentCollection(); } private ObservableCollection<SfSegmentItem> GetSegmentCollection() { ObservableCollection<SfSegmentItem> segmentCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#cccccc"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#32318e"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#963376"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#b53f3f"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=Color.FromHex("#f19741"), Text="Square",FontIconFontSize=32, FontIconFontFamily = SegoeFontFamily}, }; return segmentCollection; } #endregion } #endregion } <file_sep>/Android/SampleBrowser/Samples/TreeView/Helper/CustomAdapter/GettingStartedAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Views; using Android.Widget; using Syncfusion.Android.TreeView; namespace SampleBrowser { public class GettingStartedAdapter : TreeViewAdapter { public GettingStartedAdapter() { } protected override void UpdateContentView(View view, TreeViewItemInfoBase itemInfo) { var textView = view as TextView; if (textView != null) { textView.Text = (itemInfo.Node.Content as FoodSpecies).SpeciesName; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/IncrementalLoading.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using System.Globalization; using CoreGraphics; namespace SampleBrowser { public class IncrementalLoading:SampleView { #region Fields SfDataGrid SfGrid; IncrementalLoadingViewModel viewmodel; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public IncrementalLoading() { this.SfGrid = new SfDataGrid (); viewmodel = new IncrementalLoadingViewModel (); this.SfGrid.ItemsSource = viewmodel.GridSource; this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 52; this.SfGrid.GridStyle.AlternatingRowColor = UIColor.FromRGB (219, 219, 219); this.SfGrid.AutoGeneratingColumn += GridAutoGeneratingColumns; this.AddSubview (SfGrid); this.AddSubview(viewmodel.LoaderBorder); } void GridAutoGeneratingColumns (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "OrderID"; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextMargin = 20; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; } else if (e.Column.MappingName == "OrderDate") { e.Column.HeaderText = "Order Date"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; e.Column.Format = "d"; } else if (e.Column.MappingName == "RequiredDate") { e.Column.HeaderText = "Required Date"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; e.Column.Format = "d"; } else if (e.Column.MappingName == "ShippedDate") { e.Column.HeaderText = "Shipped Date"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; e.Column.Format = "d"; } else if (e.Column.MappingName == "ShipVia") { e.Column.HeaderText = "Ship Via"; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); } else if (e.Column.MappingName == "ShipName") { e.Column.HeaderText = "Ship Name"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "ShipAddress") { e.Column.HeaderText = "Ship Address"; e.Column.TextMargin = 10; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextMargin = 20; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "ShipRegion") { e.Column.HeaderText = "Ship Region"; e.Column.TextMargin = 20; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "ShipPostalCode") { e.Column.HeaderText = "Ship Postal Code"; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextMargin = 20; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Order_Details") { e.Column.HeaderText = "Order Details"; e.Column.TextAlignment = UITextAlignment.Left; } else { e.Cancel = true; } } public override void LayoutSubviews () { this.SfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); viewmodel.LoaderBorder.Frame = new CGRect (0, this.Frame.Height- 60, this.Frame.Width, 70); viewmodel.LoaderIndicator.Frame = new CGRect (50, 25, 20, 20); viewmodel.LoaderLable.Frame = new CGRect (80, 0, this.Frame.Width, 70); viewmodel.LoaderLable.TextColor = UIColor.White; base.LayoutSubviews (); } protected override void Dispose(bool disposing) { SfGrid.Dispose(); base.Dispose(disposing); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/ProductRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ProductRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class used to store the item values /// </summary> public class ProductRepository { #region MainGrid DataSource [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] productNames = new string[] { "Bag", "Syrup", "Crab", "Meat", "Cashew", "Chai", "Chang", "Walnuts", "Cajun", "Gumb", "Chocolate", "Cote de", "lax", "Filo", "Geitost", "Flotemy", "Ikura", "Longlife", "Maxilaku", "Mishi", "Ipoh", "Konbu", "Pavlova", "Cabrales" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int[] productID = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Random random = new Random(); #endregion /// <summary> /// Initializes a new instance of the ProductRepository class. /// </summary> public ProductRepository() { } #region GetOrderDetails /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">generates row count</param> /// <returns>returns the added row details</returns> public List<Product> GetProductDetails(int count) { List<Product> productDetails = new List<Product>(); for (int i = 1; i <= count; i++) { int position = this.random.Next(15); var ord = new Product() { SupplierID = i, ProductID = this.productID[position], ProductName = this.productNames[position], Quantity = this.random.Next(1, 20), UnitPrice = this.random.Next(70, 200), UnitsInStock = this.random.Next(3, 12), }; ord.Discount = ord.Quantity + "%"; productDetails.Add(ord); } return productDetails; } #endregion } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/DataPointSelection.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Collections.Generic; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class DataPointSelection : SampleView { SFChart chart; UILabel label; ChartViewModel dataModel; public DataPointSelection() { chart = new SFChart(); chart.Title.Text = new NSString("Product Sale 2016"); SFCategoryAxis primary = new SFCategoryAxis(); primary.LabelPlacement = SFChartLabelPlacement.BetweenTicks; primary.Title.Text = new NSString("Month"); chart.PrimaryAxis = primary; chart.SecondaryAxis = new SFNumericalAxis() { ShowMajorGridLines = false }; chart.SecondaryAxis.Title.Text = new NSString("Sales"); dataModel = new ChartViewModel(); SFColumnSeries series = new SFColumnSeries(); series.ItemsSource = dataModel.SelectionData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableDataPointSelection = true; series.EnableAnimation = true; series.Color = UIColor.FromRGBA(0, 189f / 255f, 174f / 255f, 0.5f); series.SelectedDataPointColor = UIColor.FromRGBA(0, 189f / 255f, 174f / 255f, 1f); chart.Series.Add(series); chart.Delegate = new ChartSelectionDelegate(); chart.AddChartBehavior(new SFChartSelectionBehavior()); label = new UILabel(); label.Text = "Month : Mar, Sales : $ 53"; label.Font = UIFont.FromName("Helvetica", 13f); label.TextAlignment = UITextAlignment.Center; this.AddSubview(chart); this.AddSubview(label); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view == chart) chart.Frame = new CGRect(0, 0, Frame.Width, Frame.Height - 28); else if (view == label) label.Frame = new CGRect(0, Frame.Height - 20, Frame.Width, 20); else view.Frame = Frame; } base.LayoutSubviews(); } public void SetLabelContent(string xValue, string yValue) { if (xValue != null && yValue != null) { label.Text = "Month : " + xValue + ", Sales : $" + yValue; } else { label.Text = "Tap a bar segment to select a data point"; } } } public class ChartSelectionDelegate : SFChartDelegate { public override void DidDataPointSelect(SFChart chart, SFChartSelectionInfo info) { int selectedindex = info.SelectedDataPointIndex; if (selectedindex >= 0) { SFSeries series = info.SelectedSeries; if (series != null) { var dataPoint = (series.ItemsSource as IList<ChartDataModel>); if (dataPoint == null) (chart.Superview as DataPointSelection).SetLabelContent(null, null); else { String x = dataPoint[selectedindex].XValue.ToString(); String y = dataPoint[selectedindex].YValue.ToString(); (chart.Superview as DataPointSelection).SetLabelContent(x, y); } } } else { (chart.Superview as DataPointSelection).SetLabelContent(null, null); } } } }<file_sep>/Forms/Picker/Picker/Samples/Cascading/Itemview.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfPicker { public partial class Itemview : Grid { public Itemview(Country county) { InitializeComponent(); this.BindingContext = county; } } public class Country { public string Name { get; set; } public string Flag { get; set; } } } <file_sep>/Android/SampleBrowser/Samples/DocIO/WordToPDF.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.OfficeChart; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using System.IO; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Webkit; using Android.App; using Android.OS; namespace SampleBrowser { public partial class WordToPDF : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to convert the Word document into PDF."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Input Template"; button1.Click += OnInpTemplateButtonClicked; linear.AddView(button1); Button button2 = new Button(con); button2.Text = "Convert"; button2.Click += OnButtonClicked; linear.AddView(button2); return linear; } void OnInpTemplateButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.DocIO.Templates.WordtoPDF.docx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); fileStream.Dispose(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("WordtoPDF.docx", "application/msword", stream, m_context); } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.DocIO.Templates.WordtoPDF.docx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); // Loads the stream into Word Document. WordDocument wordDocument = new WordDocument(fileStream, Syncfusion.DocIO.FormatType.Automatic); //Instantiation of DocIORenderer for Word to PDF conversion DocIORenderer render = new DocIORenderer(); //Sets Chart rendering Options. render.Settings.ChartRenderingOptions.ImageFormat = Syncfusion.OfficeChart.ExportImageFormat.Jpeg; //Sets ShowInBalloons to render a document comments in converted PDF document. wordDocument.RevisionOptions.CommentDisplayMode = CommentDisplayMode.ShowInBalloons; //Sets the color to be used for Comment Balloon wordDocument.RevisionOptions.CommentColor = RevisionColor.Blue; //Converts Word document into PDF document PdfDocument pdfDocument = render.ConvertToPDF(wordDocument); //Releases all resources used by the Word document and DocIO Renderer objects render.Dispose(); wordDocument.Dispose(); MemoryStream pdfStream = new MemoryStream(); //Save the converted PDF document into MemoryStream. pdfDocument.Save(pdfStream); pdfStream.Position = 0; //Close the PDF document. pdfDocument.Close(true); if (pdfStream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("WordtoPDF.pdf", "application/pdf", pdfStream, m_context); } } } } <file_sep>/Forms/Chart/Chart/Samples/DoughnutChart/DoughnutSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; namespace SampleBrowser.SfChart { public class DoughnutSeriesViewModel : INotifyPropertyChanged { public ObservableCollection<ChartDataModel> DoughnutSeriesData { get; set; } public DoughnutSeriesViewModel() { DoughnutSeriesData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Labour", 10), new ChartDataModel("Legal", 8), new ChartDataModel("Production", 7), new ChartDataModel("License", 5), new ChartDataModel("Facilities", 10), new ChartDataModel("Taxes", 6), new ChartDataModel("Insurance", 18) }; } private int selectedIndex; private string _selectedItemName; private double _selectedItemsPercentage; public string SelectedItemName { get { return _selectedItemName; } set { _selectedItemName = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedItemName")); } } public double SelectedItemsPercentage { get { return _selectedItemsPercentage; } set { _selectedItemsPercentage = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedItemsPercentage")); } } public event PropertyChangedEventHandler PropertyChanged; public int SelectedIndex { get { return selectedIndex; } set { selectedIndex = value; if (selectedIndex == -1) return; SelectedItemName = DoughnutSeriesData[selectedIndex].Name; var sum = DoughnutSeriesData.Sum(item => item.Value); var selectedValue = DoughnutSeriesData[selectedIndex].Value; SelectedItemsPercentage = (selectedValue / sum) * 100; SelectedItemsPercentage = Math.Floor(SelectedItemsPercentage * 100) / 100; } } } }<file_sep>/iOS/SampleBrowser/Samples/DataForm/Helpers/ContactTableSource.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using System.Collections.ObjectModel; namespace SampleBrowser { /// <summary> /// Table source for TableView. /// </summary> public class ContactTableSource : UITableViewSource { internal ObservableCollection<ContactInfo> TableItems; string CellIdentifier = "TableCell"; DataFormController dataFormController; public ContactTableSource(DataFormController controller, ObservableCollection<ContactInfo> items) { TableItems = items; dataFormController = controller; } public override nint RowsInSection(UITableView tableview, nint section) { return TableItems.Count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier); ContactInfo item = TableItems[indexPath.Row]; //---- if there are no cells to reuse, create a new one if (cell == null) { cell = new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier); } cell.TextLabel.Text = item.ContactName; cell.ImageView.Image = item.ContactImage; return cell; } public override bool CanMoveRow(UITableView tableView, NSIndexPath indexPath) { return true; // return false if you don't allow re-ordering } public override bool CanEditRow(UITableView tableView, NSIndexPath indexPath) { return true; // return false if you wish to disable editing for a specific indexPath or for all rows } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { // Show DataForm while selecting a table view cell. dataFormController.refreshLayout = false; dataFormController.UpDateDataFormView(TableItems[indexPath.Row] as ContactInfo); dataFormController.UpdateView(); var navigationController = UIApplication.SharedApplication.KeyWindow.RootViewController as UINavigationController; navigationController.PushViewController(dataFormController, false); } } }<file_sep>/iOS/SampleBrowser/Samples/DataForm/Helpers/DataFormController.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using Syncfusion.iOS.DataForm; using CoreGraphics; namespace SampleBrowser { public class DataFormController : UIViewController { internal bool refreshLayout = false; internal SfDataForm dataForm; private UIImageView image; private UILabel label; UITableView tableView; UIView uIView; private UIBarButtonItem editButton; private UIButton moreFields; UIScrollView scrollView; public DataFormController(SfDataForm dataForm, UITableView tableView) : base() { this.dataForm = dataForm; InitializeViews(); UpdateView(); this.tableView = tableView; } /// <summary> /// Initialize views and add to DataFormController. /// </summary> private void InitializeViews() { scrollView = new UIScrollView(); scrollView.Frame = new CGRect(0, 160, this.View.Frame.Width, this.View.Frame.Height - 160); uIView = new UIView(new CGRect(0, 0, this.View.Frame.Width, 160)); this.View.AddSubview(uIView); this.View.AddSubview(scrollView); uIView.BackgroundColor = UIColor.FromRGB(242.0f / 255.0f, 242.0f / 255.0f, 242.0f / 255.0f); image = new UIImageView(new CGRect(10, 70, 80, 80)); uIView.AddSubview(image); label = new UILabel(new CGRect(100, 70, this.View.Frame.Width - 80, 80)); label.Font.WithSize(12); uIView.AddSubview(label); editButton = new UIBarButtonItem(); editButton.Title = "Edit"; editButton.Clicked += EditButton_Clicked; dataForm.CommitMode = CommitMode.Explicit; dataForm.ValidationMode = ValidationMode.LostFocus; dataForm.AutoGeneratingDataFormItem += DataForm_AutoGeneratingDataFormItem; dataForm.Frame = new CGRect(10, 0, this.View.Frame.Width - 10, this.View.Frame.Height - (160 + 30)); scrollView.AddSubview(dataForm); this.View.BackgroundColor = UIColor.White; moreFields = new UIButton(new CGRect(10, this.scrollView.Frame.Height - 30, dataForm.Frame.Width, 30)); moreFields.SetTitle("More Fields", UIControlState.Normal); moreFields.SetTitleColor(this.View.TintColor, UIControlState.Normal); moreFields.TouchDown += MoreFields_TouchDown; } private void MoreFields_TouchDown(object sender, EventArgs e) { refreshLayout = true; dataForm.RefreshLayout(false); moreFields.RemoveFromSuperview(); dataForm.Frame = new CGRect(10, 0, this.View.Frame.Width - 10, this.View.Frame.Height - 160); } /// <summary> /// DataObject update to set ReadOnly, UIBarButton title update to show edit or done. /// </summary> /// <param name="contactInfo"></param> /// <param name="isAdding"></param> internal void UpDateDataFormView(ContactInfo contactInfo, bool isAdding = false) { dataForm.DataObject = contactInfo; // Setting edit button if (!isAdding) { if (editButton.Title.Equals("Edit")) { dataForm.IsReadOnly = true; editButton.Title = "Edit"; } else { dataForm.IsReadOnly = false; bool isValid = dataForm.Validate(); if (!isValid) return; dataForm.Commit(); editButton.Title = "Done"; } this.NavigationItem.SetRightBarButtonItem(editButton, true); } else { var okButton = new UIBarButtonItem(); okButton.Title = "OK"; dataForm.IsReadOnly = false; refreshLayout = false; this.dataForm.DataObject = contactInfo; okButton.Clicked += OnOK; this.NavigationItem.SetRightBarButtonItem(okButton, true); } } private void EditButton_Clicked(object sender, EventArgs e) { var item = dataForm.DataObject as ContactInfo; if (editButton.Title.Equals("Edit")) { dataForm.IsReadOnly = false; editButton.Title = "Done"; } else { bool isValid = dataForm.Validate(); if (!isValid) return; dataForm.Commit(); dataForm.IsReadOnly = true; editButton.Title = "Edit"; var itemIndex = (tableView.Source as ContactTableSource).TableItems.IndexOf(item); if (itemIndex == -1) return; NSIndexPath[] rowsToReload = new NSIndexPath[] { NSIndexPath.FromRowSection(itemIndex, 0) }; tableView.ReloadRows(rowsToReload, UITableViewRowAnimation.None); } } private void OnOK(object sender, EventArgs e) { // TableView update var tableSource = (this.tableView.Source as ContactTableSource); var item = dataForm.DataObject as ContactInfo; var itemIndex = tableSource.TableItems.IndexOf(item); if (item.ContactImage == null) item.ContactImage = UIImage.FromBundle("ContactName.png"); // DataForm update bool isValid = dataForm.Validate(); if (!isValid) return; dataForm.Commit(); if (itemIndex == -1) { (tableView.Source as ContactTableSource).TableItems.Add(item); tableView.ReloadData(); } this.NavigationItem.SetRightBarButtonItem(null, true); var navigationController = UIApplication.SharedApplication.KeyWindow.RootViewController as UINavigationController; navigationController.PopViewController(false); } /// <summary> /// Updates title bar of DataFormViewController - Contact Image and ConatctName updates. /// </summary> internal void UpdateView() { if (dataForm.DataObject == null) return; scrollView.AddSubview(moreFields); dataForm.Frame = new CGRect(10, 0, this.View.Frame.Width - 10, this.View.Frame.Height - (160 + 30)); var contactInfo = dataForm.DataObject as ContactInfo; if (contactInfo.ContactImage == null) { image.Image = UIImage.FromBundle("ContactName1.png"); var frame = image.Frame; frame.X = (dataForm.Frame.Width / 2) - 40; image.Frame = frame; } else { image.Image = contactInfo.ContactImage; var frame = image.Frame; frame.X = 10; frame.Width = 80; frame.Height = 80; image.Frame = frame; } label.Text = contactInfo.ContactName; } /// <summary> /// Event to cancel the COnatctImage DataFormItem and setting IsReadOnly property. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void DataForm_AutoGeneratingDataFormItem(object sender, AutoGeneratingDataFormItemEventArgs e) { if (e.DataFormItem != null) { if (!refreshLayout) { if (e.DataFormItem.Name.Equals("MiddleName") || e.DataFormItem.Name.Equals("LastName")) e.Cancel = true; } if (e.DataFormItem.Name.Equals("ContactNumber")) (e.DataFormItem as DataFormTextItem).KeyBoardType = UIKeyboardType.NumberPad; else if (e.DataFormItem.Name.Equals("Email")) (e.DataFormItem as DataFormTextItem).KeyBoardType = UIKeyboardType.EmailAddress; } if (e.DataFormGroupItem != null) e.DataFormGroupItem.AllowExpandCollapse = false; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); editButton.Title = "Edit"; } } }<file_sep>/Forms/RadioButton/RadioButton.iOS/FrameRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using CoreGraphics; using Xamarin.Forms; using SampleBrowser.SfRadioButton.iOS; [assembly: ExportRenderer(typeof(Frame), typeof(SampleBrowser.SfRadioButton.iOS.MaterialFrameRenderer))] namespace SampleBrowser.SfRadioButton.iOS { public class MaterialFrameRenderer : Xamarin.Forms.Platform.iOS.FrameRenderer { public override void Draw(CGRect rect) { base.Draw(rect); Layer.ShadowColor = new UIColor(0, 0, 0, 0.16f).CGColor; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/StylesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "StylesViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for Styles sample. /// </summary> public class StylesViewModel : Employee { #region Field [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<OrderInfo> ordersInfo; #endregion /// <summary> /// Initializes a new instance of the StylesViewModel class. /// </summary> public StylesViewModel() { OrderInfoRepository order = new OrderInfoRepository(); this.ordersInfo = order.GetOrderDetails(100); } #region ItemsSource /// <summary> /// Gets or sets the value of OrdersInfo /// </summary> public ObservableCollection<OrderInfo> OrdersInfo { get { return this.ordersInfo; } set { this.ordersInfo = value; } } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/TechnicalIndicator/TechnicalIndicator.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.XForms; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfChart { public partial class TechnicalIndicator : SampleView { Picker animationPicker; StackLayout PropertyWindowLayout; public TechnicalIndicator() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { secondaryAxisLabelStyle.LabelFormat = "'$'0.00"; } else { secondaryAxisLabelStyle.LabelFormat = "'$'##.##"; } PropertyWindowLayout = new StackLayout() { Orientation = StackOrientation.Vertical }; animationPicker = new Picker(); animationPicker.Items.Add("Accumulation Distribution"); animationPicker.Items.Add("Average True"); animationPicker.Items.Add("Exponential Moving Average"); animationPicker.Items.Add("Momentum"); animationPicker.Items.Add("Simple Moving Average"); animationPicker.Items.Add("RSI Indicator"); animationPicker.Items.Add("Triangular Moving Average"); animationPicker.Items.Add("MACD Indicator"); animationPicker.Items.Add("Stochastic"); animationPicker.Items.Add("Bollinger Band"); animationPicker.SelectedIndex = 4; animationPicker.HorizontalOptions = LayoutOptions.FillAndExpand; animationPicker.VerticalOptions = LayoutOptions.Center; SimpleMovingAverageIndicator sma4 = new SimpleMovingAverageIndicator(); NumericalAxis numericalAxis4 = new NumericalAxis(); numericalAxis4.OpposedPosition = true; numericalAxis4.ShowMajorGridLines = false; if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { numericalAxis4.LabelStyle.LabelFormat = "'$'0.00"; } else { numericalAxis4.LabelStyle.LabelFormat = "'$'##.##"; } sma4.YAxis = numericalAxis4; sma4.SeriesName = "Series"; sma4.Period = 14; Chart.TechnicalIndicators.Add(sma4); animationPickerLabel.Text = "Simple Moving Average"; pickerLayout.IsVisible = true; PropertyWindowLayout.IsVisible = true; if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android) { } else { PropertyWindowLayout.Margin = new Thickness(5,2,2,2); } animationPickerTitle.VerticalOptions = LayoutOptions.Start; animationPickerTitle.HorizontalOptions = LayoutOptions.FillAndExpand; animationPicker.HorizontalOptions = LayoutOptions.FillAndExpand; animationPicker.VerticalOptions = LayoutOptions.Center; PropertyWindowLayout.Children.Add(animationPickerTitle); PropertyWindowLayout.Children.Add(animationPicker); this.PropertyView = PropertyWindowLayout; animationPicker.SelectedIndexChanged += labelDisplayMode_SelectedIndexChanged; if (Device.RuntimePlatform != Device.Android && Device.RuntimePlatform != Device.iOS) animationPicker.Margin = new Thickness(5, 5, 10, 0); animationPickerTitle.Margin = new Thickness(3, 5, 10, 0); animationPickerLabel.Margin = new Thickness(10, 5, 10, 5); } void labelDisplayMode_SelectedIndexChanged(object sender, EventArgs e) { animationPickerLabel.Text = animationPicker.Items[animationPicker.SelectedIndex]; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.OpposedPosition = true; numericalAxis.ShowMajorGridLines = false; if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { numericalAxis.LabelStyle.LabelFormat = "'$'0.00"; } else { numericalAxis.LabelStyle.LabelFormat = "'$'##.##"; } switch (animationPicker.SelectedIndex) { case 0: Chart.TechnicalIndicators.RemoveAt(0); AccumulationDistributionIndicator sma = new AccumulationDistributionIndicator(); sma.SeriesName = "Series"; sma.YAxis = numericalAxis; Chart.TechnicalIndicators.Add(sma); break; case 1: Chart.TechnicalIndicators.RemoveAt(0); AverageTrueIndicator sma1 = new AverageTrueIndicator(); sma1.SeriesName = "Series"; sma1.Period = 14; sma1.YAxis = numericalAxis; Chart.TechnicalIndicators.Add(sma1); break; case 2: Chart.TechnicalIndicators.RemoveAt(0); ExponentialMovingAverageIndicator sma2 = new ExponentialMovingAverageIndicator(); sma2.SeriesName = "Series"; sma2.Period = 14; sma2.YAxis = numericalAxis; Chart.TechnicalIndicators.Add(sma2); break; case 3: Chart.TechnicalIndicators.RemoveAt(0); MomentumIndicator sma3 = new MomentumIndicator(); sma3.SeriesName = "Series"; sma3.Period = 14; sma3.YAxis = numericalAxis; Chart.TechnicalIndicators.Add(sma3); break; case 4: if (Chart.TechnicalIndicators.Count > 0) Chart.TechnicalIndicators.RemoveAt(0); SimpleMovingAverageIndicator sma4 = new SimpleMovingAverageIndicator(); sma4.YAxis = numericalAxis; sma4.SeriesName = "Series"; sma4.Period = 14; Chart.TechnicalIndicators.Add(sma4); break; case 5: Chart.TechnicalIndicators.RemoveAt(0); RSIIndicator sma5 = new RSIIndicator(); sma5.SeriesName = "Series"; sma5.Period = 14; sma5.YAxis = numericalAxis; Chart.TechnicalIndicators.Add(sma5); break; case 6: Chart.TechnicalIndicators.RemoveAt(0); TriangularMovingAverageIndicator sma6 = new TriangularMovingAverageIndicator(); sma6.SeriesName = "Series"; sma6.Period = 14; sma6.YAxis = numericalAxis; Chart.TechnicalIndicators.Add(sma6); break; case 7: Chart.TechnicalIndicators.RemoveAt(0); MACDIndicator sma7 = new MACDIndicator(); sma7.ItemsSource = (Chart.BindingContext as TechnicalIndicatorViewModel).TechnicalIndicatorData; sma7.SeriesName = "Series"; sma7.LongPeriod = 10; sma7.ShortPeriod = 2; sma7.Trigger = 14; sma7.YAxis = numericalAxis; Chart.TechnicalIndicators.Add(sma7); break; case 8: Chart.TechnicalIndicators.RemoveAt(0); StochasticIndicator sma8 = new StochasticIndicator(); sma8.SeriesName = "Series"; sma8.Period = 14; sma8.KPeriod = 5; sma8.DPeriod = 6; sma8.YAxis = numericalAxis; Chart.TechnicalIndicators.Add(sma8); break; case 9: Chart.TechnicalIndicators.RemoveAt(0); BollingerBandIndicator sma9 = new BollingerBandIndicator(); sma9.Period = 14; sma9.SeriesName = "Series"; sma9.YAxis = numericalAxis; Chart.TechnicalIndicators.Add(sma9); break; } } } }<file_sep>/Forms/Carousel/Carousel/Samples/Carousel_PullToRefresh/PullToRefresh_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Xamarin.Forms; using Syncfusion.SfCarousel.XForms; using System.Collections.ObjectModel; using System.Threading.Tasks; namespace SampleBrowser.SfCarousel { /// <summary> /// Pull to refresh default. /// </summary> public partial class PullToRefresh_Default : SampleView { CarouselViewModel carouselViewModel; #region PullToRefresh Default view /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.SfCarousel.PullToRefresh_Default"/> class. /// </summary> public PullToRefresh_Default() { InitializeComponent(); carouselViewModel = new CarouselViewModel(); carouselLayout.BindingContext = carouselViewModel; } #endregion #region SB view /// <summary> /// Gets the content. /// </summary> /// <returns>The content.</returns> public View getContent() { return this.Content; } #endregion #region handle event /// <summary> /// Handles the tapped. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void Handle_Tapped(object sender, System.EventArgs e) { // Device.OpenUri(new Uri("https://www.syncfusion.com/downloads")); } #endregion } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/CellTemplateConverter.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CellTemplateConverter.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; [Preserve(AllMembers = true)] /// <summary> /// Converter for the cell template sample in DataGrid /// </summary> public class CellTemplateConverter : IValueConverter { /// <param name="value">The value to convert.</param> /// <param name="targetType">The type to which to convert the value.</param> /// <param name="parameter">A parameter to use during the conversion.</param> /// <param name="culture">The culture to use during the conversion.</param> /// <summary>Implement this method to convert <paramref name="value" /> to <paramref name="targetType" /> by using <paramref name="parameter" /> and <paramref name="culture" />.</summary> /// <returns>To be added.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value; } /// <param name="value">The value to convert.</param> /// <param name="targetType">The type to which to convert the value.</param> /// <param name="parameter">A parameter to use during the conversion.</param> /// <param name="culture">The culture to use during the conversion.</param> /// <summary> Implement this method to convert <paramref name="value" /> back from <paramref name="targetType" /> by using <paramref name="parameter" /> and <paramref name="culture" />.</summary> /// <returns> To be added.</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } } <file_sep>/Android/SampleBrowser/Samples/DocIO/Templates/MarkdownToWord.md # A tour of the C\# language C\# (pronounced "See Sharp") is a modern, object\-oriented, and type\-safe programming language. C\# enables developers to build many types of secure and robust applications that run in .NET. C\# has its roots in the C family of languages and will be immediately familiar to C, C\+\+, Java, and JavaScript programmers. This tour provides an overview of the major components of the language in C\# 11 and earlier. If you want to explore the language through interactive examples, try the [introduction to C#](https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/) tutorials. Several C\# features help create robust and durable applications. [Garbage collection](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/) automatically reclaims memory occupied by unreachable unused objects. [Nullable types](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references) guard against variables that don't refer to allocated objects. [Exception handling](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/exceptions/) provides a structured and extensible approach to error detection and recovery. [Lambda expressions](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions) support functional programming techniques. [Language Integrated Query (LINQ)](https://learn.microsoft.com/en-us/dotnet/csharp/linq/) syntax creates a common pattern for working with data from any source. Language support for [asynchronous operations](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/) provides syntax for building distributed systems. C\# has a [unified type system](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/). All C\# types, including primitive types such as `int` and `double`, inherit from a single root `object` type. All types share a set of common operations. Values of any type can be stored, transported, and operated upon in a consistent manner. Furthermore, C\# supports both user\-defined [reference types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types) and [value types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types). C\# allows dynamic allocation of objects and in\-line storage of lightweight structures. C\# supports generic methods and types, which provide increased type safety and performance. C\# provides iterators, which enable implementers of collection classes to define custom behaviors for client code. # Hello world The "Hello, World" program is traditionally used to introduce a programming language. Here it is in C\#: ``` using System; class Hello { static void Main() { Console.WriteLine("Hello, World"); } } ``` The "Hello, World" program starts with a `using` directive that references the `System` namespace. Namespaces provide a hierarchical means of organizing C\# programs and libraries. A `using` directive that references a given namespace enables unqualified use of the types that are members of that namespace. Because of the `using` directive, the program can use Console.WriteLine as shorthand for System.Console.WriteLine. The Hello `class` declared by the "Hello, World" program has a single member, the method named `Main`. The `Main` method is declared with the static modifier. By convention, a static method named `Main` serves as the entry point of a C\# program. The output of the program is produced by the `WriteLine` method of the `Console` class in the `System` namespace. This class is provided by the standard class libraries, which, by default, are automatically referenced by the compiler. # Types and variables A *type* defines the structure and behavior of any data in C\#. The declaration of a type may include its members, base type, interfaces it implements, and operations permitted for that type. A *variable* is a label that refers to an instance of a specific type. There are two kinds of types in C\#:  1. Value types 1. Reference types. ## Value types C\#'s value types are further divided into *simple types*, *enum types*, *struct types*, *nullable value types*, and *tuple value types*. |Value types|Details| |:---|:---| |[Simple types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types)|[Signed integral](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types), [unsigned integral](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types), [unicode characters](https://learn.microsoft.com/en-us/dotnet/standard/base-types/character-encoding-introduction), [IEEE binary floating-point](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types), [High-precision decimal floating-point](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types), and boolean. | |[Enum types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum)|User\-defined types of the form `enum E {...}`. An `enum` type is a distinct type with named constants. Every `enum` type has an underlying type, which must be one of the eight integral types. The set of values of an `enum` type is the same as the set of values of the underlying type.| |[Struct types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct)|User\-defined types of the form `struct S {...}`| |[Nullable value types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types)|Extensions of all other value types with a `null` value| |[Tuple value types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples)|User\-defined types of the form  `(T1, T2, ...)`| ## Reference types |Reference types|Details| |:---|:---| |[Class types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/class) |Ultimate base class of all other types: object. Unicode strings: string, which represents a sequence of UTF\-16 code units. User\-defined types of the form class C {...}| |[Interface types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/interface) |User\-defined types of the form interface I {...}| |[Array types](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/) |Single\-dimensional, multi\-dimensional, and jagged. For example: int\[], int\[,], and int\[]\[] | |[Delegate types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types) |User\-defined types of the form delegate int D(...) | C\# programs use *type declarations* to create new types. A type declaration specifies the name and the members of the new type. Six of C\#'s categories of types are user\-definable: class types, struct types, interface types, enum types, delegate types, and tuple value types. You can also declare `record` types, either `record struct`, or `record class`. Record types have compiler\-synthesized members. You use records primarily for storing values, with minimal associated behavior. - A `class` type defines a data structure that contains data members (fields) and function members (methods, properties, and others). Class types support single inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes. - A `struct` type is similar to a class type in that it represents a structure with data members and function members. However, unlike classes, structs are value types and don't typically require heap allocation. Struct types don't support user\-specified inheritance, and all struct types implicitly inherit from type `object`. - An `interface` type defines a contract as a named set of public members. A `class` or `struct` that implements an `interface` must provide implementations of the interface's members. An `interface` may inherit from multiple base interfaces, and a `class` or `struct` may implement multiple interfaces. - A `delegate` type represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Delegates are analogous to function types provided by functional languages. They're also similar to the concept of function pointers found in some other languages. Unlike function pointers, delegates are object\-oriented and type\-safe. You can explore more about C\# in this [tutorials](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/classes).<file_sep>/Forms/PdfViewer/PdfViewer/Samples/ViewModel/PdfViewerViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.IO; using System.Reflection; using System.ComponentModel; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.Collections.Generic; using Syncfusion.SfPdfViewer.XForms; namespace SampleBrowser.SfPdfViewer { [Preserve(AllMembers = true)] internal class PdfViewerViewModel : INotifyPropertyChanged { private Stream m_pdfDocumentStream; private string m_currentViewModeIconText = FontMappingHelper.ContinuousPage; private PageViewMode m_currentPageViewMode = PageViewMode.Continuous; private bool m_isToolbarVisible = true; private bool m_isPickerVisible = false; private bool m_moreOptionsToolBarVisible = false; private bool m_isSearchbarVisible = false; private bool m_isBottomToolbarVisible = true; private bool m_isSecondaryAnnotationBarVisible = false; private bool m_isHightlightBarVisible = false; private bool m_isUnderlineBarVisible = false; private bool m_isStrikeThroughBarVisible = false; private bool m_isSquigglyBarVisible = false; private bool m_isRectangleAnnotationBarVisible = false; private bool m_isCircleAnnotationBarVisible = false; private bool m_isLineAnnotationBarVisible = false; private bool m_isArrowAnnotationBarVisible = false; private bool m_isPolygonAnnotationBarVisible = false; private bool m_isCloudAnnotationBarVisible = false; private bool m_isPolylineAnnotationBarVisible = false; private bool m_isEditAnnotationBarVisible = false; private bool m_isEditStampAnnotationBarVisible = false; private bool m_isEditFreeTextAnnotationBarVisible = false; private bool m_isShapeAnnotationBarVisible = false; private bool m_isColorBarVisible = false; private bool m_isMainAnnotationBarVisible = false; private bool m_isInkBarVisible = false; private bool m_isRectangleBarVisible = false; private bool m_isCircleBarVisible = false; private bool m_isLineBarVisible = false; private bool m_isArrowBarVisible = false; private bool m_isPolygonBarVisible = false; private bool m_isCloudBarVisible = false; private bool m_isPolylineBarVisible = false; private bool m_isThicknessBarVisible = false; private bool m_isFontSizeSliderBarVisible = false; private bool m_isOpacityBarVisible = false; private bool m_isInkColorBarVisible = false; private bool m_isShapeColorBarVisible = false; private bool m_isEditTextBarVisible = false; private bool m_isEditInkBarVisible = false; private bool m_isEditRectangleAnnotationBarVisible = false; private bool m_isEditLineAnnotationBarVisible = false; private bool m_isEditCircleAnnotationBarVisible = false; private bool m_isEditTextAnnotationBarVisible = false; private bool m_isEditArrowAnnotationBarVisible = false; private bool m_isEditPolygonAnnotationBarVisible = false; private bool m_isEditCloudAnnotationBarVisible = false; private bool m_isEditPolylineAnnotationBarVisible = false; private bool m_isPopupBarVisible = false; private bool m_isEditPopupAnnotationBarVisible = false; private bool m_isPopupIconSelectorBarVisible = false; private bool m_isAnnotationGridVisible = false; private int m_annotationRowHeight = 50, m_colorRowHeight = 0, m_opacityRowHeight = 0; private int m_annotationGridHeightRequest = 0; private Color m_toggleColor = Color.LightGray; private Color m_highlightColor; private Color m_underlineColor; private Color m_strikeThroughColor; private Color m_squigglyColor; private Color m_deleteButtonColor; private Color m_inkdeleteColor; private Color m_rectangleDeleteColor; private Color m_circleDeleteColor; private Color m_editTextdeleteColor; private Color m_lineDeleteColor; private Color m_arrowDeleteColor; private Color m_polygonDeleteColor; private Color m_cloudDeleteColor; private Color m_polylineDeleteColor; private Color m_inkColor; private Color m_editTextColor; private Color m_rectangleStrokeColor; private Color m_circleStrokeColor; private Color m_lineStrokeColor; private Color m_arrowStrokeColor; private Color m_polygonStrokeColor; private Color m_cloudStrokeColor; private Color m_polylineStrokeColor; private Color m_opacityButtonColor; private bool m_isBookMarkVisible; private bool m_isContextMenuVisible; private Color m_popupDeleteColor; private Color m_popupColor; private PopupIcon m_popupIcon; private PopupIcon m_editPopupIcon; private bool m_isInkEraserBarVisible; public event PropertyChangedEventHandler PropertyChanged; public ICommand ToggleViewModeCommand { get; set; } public ICommand SearchAndToolbarToggleCommand { get; set; } public ICommand AnnotationCommand { get; set; } public ICommand FileOpenCommand { get; set; } public ICommand MoreOptionsCommand { get; set; } public ICommand HighlightCommand { get; set; } public ICommand UnderlineCommand { get; set; } public ICommand StrikeThroughCommand { get; set; } public ICommand SquigglyCommand { get; set; } public ICommand RectangleCommand { get; set; } public ICommand CircleCommand { get; set; } public ICommand LineCommand { get; set; } public ICommand ArrowCommand { get; set; } public ICommand PolygonCommand { get; set; } public ICommand CloudCommand { get; set; } public ICommand PolylineCommand { get; set; } public ICommand ColorButtonClickedCommand { get; set; } public ICommand ColorCommand { get; set; } public ICommand AnnotationBackCommand { get; set; } public ICommand TextMarkupSelectedCommand { get; set; } public ICommand TextMarkupDeselectedCommand { get; set; } public ICommand StampAnnotationSelectedCommand { get; set; } public ICommand StampAnnotationDeselectedCommand { get; set; } public ICommand DeleteCommand { get; set; } public ICommand DocumentLoadedCommand { get; set; } public ICommand TextMarkupCommand { get; set; } public ICommand InkCommand { get; set; } public ICommand EditTextCommand { get; set; } public ICommand ShapeCommand { get; set; } public ICommand TextMarkupBackCommand { get; set; } public ICommand InkBackButtonCommand { get; set; } public ICommand RectangleBackButtonCommand { get; set; } public ICommand CircleBackButtonCommand { get; set; } public ICommand LineBackButtonCommand { get; set; } public ICommand ArrowBackButtonCommand { get; set; } public ICommand PolygonBackButtonCommand { get; set; } public ICommand CloudBackButtonCommand { get; set; } public ICommand PolylineBackButtonCommand { get; set; } public ICommand EditTextBackButtonCommand { get; set; } public ICommand ShapeBackButtonCommand { get; set; } public ICommand InkThicknessCommand { get; set; } public ICommand RectangleThicknessCommand { get; set; } public ICommand CircleThicknessCommand { get; set; } public ICommand LineThicknessCommand { get; set; } public ICommand ArrowThicknessCommand { get; set; } public ICommand PolygonThicknessCommand { get; set; } public ICommand CloudThicknessCommand { get; set; } public ICommand PolylineThicknessCommand { get; set; } public ICommand EditTextFontSizeCommand { get; set; } public ICommand InkOpacityCommand { get; set; } public ICommand InkSelectedCommand { get; set; } public ICommand InkDeselectedCommand { get; set; } public ICommand ShapeSelectedCommand { get; set; } public ICommand ShapeDeselectedCommand { get; set; } public ICommand FreeTextSelectedCommand { get; set; } public ICommand FreeTextDeselectedCommand { get; set; } public ICommand InkDeleteCommand { get; set; } public ICommand ShapeDeleteCommand { get; set; } public ICommand EditTextDeleteCommand { get; set; } public ICommand PopupCommand { get; set; } public ICommand PopupBackButtonCommand { get; set; } public ICommand PopupDeleteCommand { get; set; } public ICommand PopupIconCommand { get; set; } public ICommand SelectPopupIconCommand { get; set; } public ICommand PopupAnnotationSelectedCommand { get; set; } public ICommand PopupAnnotationDeselectedCommand { get; set; } public ICommand OpacityButtonCommand { get; set; } public ICommand TabletBookmarkCommand { get; set; } public ICommand InkEraserCommand { get; set; } public ICommand InkEraserBackButtonCommand { get; set; } public Stream PdfDocumentStream { get { return m_pdfDocumentStream; } set { m_pdfDocumentStream = value; NotifyPropertyChanged("PdfDocumentStream"); } } public bool IsBookMarkVisible { get { return m_isBookMarkVisible; } set { m_isBookMarkVisible = value; NotifyPropertyChanged("IsBookMarkVisible"); } } public bool IsContextMenuVisible { get { return m_isContextMenuVisible; } set { m_isContextMenuVisible = value; NotifyPropertyChanged("IsContextMenuVisible"); } } public int AnnotationGridHeightRequest { get { return m_annotationGridHeightRequest; } set { m_annotationGridHeightRequest = value; NotifyPropertyChanged("AnnotationGridHeightRequest"); } } public Color DeleteButtonColor { get { return m_deleteButtonColor; } set { m_deleteButtonColor = value; NotifyPropertyChanged("DeleteButtonColor"); } } public bool IsAnnotationGridVisible { get { return m_isAnnotationGridVisible; } set { m_isAnnotationGridVisible = value; NotifyPropertyChanged("IsAnnotationGridVisible"); } } public string CurrentViewModeIconText { get { return m_currentViewModeIconText; } set { m_currentViewModeIconText = value; NotifyPropertyChanged("CurrentViewModeIconText"); } } public PageViewMode CurrentPageViewMode { get { return m_currentPageViewMode; } set { m_currentPageViewMode = value; CurrentViewModeIconText = value == PageViewMode.Continuous? FontMappingHelper.ContinuousPage : FontMappingHelper.PageByPage; NotifyPropertyChanged("CurrentPageViewMode"); } } public bool IsEditFreeTextAnnotationBarVisible { get { return m_isEditFreeTextAnnotationBarVisible; } set { m_isEditFreeTextAnnotationBarVisible = value; NotifyPropertyChanged("IsEditFreeTextAnnotationBarVisible"); } } public bool IsEditPopupAnnotationBarVisible { get { return m_isEditPopupAnnotationBarVisible; } set { m_isEditPopupAnnotationBarVisible = value; NotifyPropertyChanged("IsEditPopupAnnotationBarVisible"); } } public Color OpacityButtonColor { get { return m_opacityButtonColor; } set { m_opacityButtonColor = value; NotifyPropertyChanged("OpacityButtonColor"); } } public Color ToggleColor { get { return m_toggleColor; } set { m_toggleColor = value; NotifyPropertyChanged("ToggleColor"); } } public bool IsColorBarVisible { get { return m_isColorBarVisible; } set { m_isColorBarVisible = value; NotifyPropertyChanged("IsColorBarVisible"); } } public bool IsThicknessBarVisible { get { return m_isThicknessBarVisible; } set { m_isThicknessBarVisible = value; NotifyPropertyChanged("IsThicknessBarVisible"); } } public bool IsFontSizeSliderBarVisible { get { return m_isFontSizeSliderBarVisible; } set { m_isFontSizeSliderBarVisible = value; NotifyPropertyChanged("IsFontSizeSliderBarVisible"); } } public bool IsInkColorBarVisible { get { return m_isInkColorBarVisible; } set { m_isInkColorBarVisible = value; NotifyPropertyChanged("IsInkColorBarVisible"); } } public bool IsShapeColorBarVisible { get { return m_isShapeColorBarVisible; } set { m_isShapeColorBarVisible = value; NotifyPropertyChanged("IsShapeColorBarVisible"); } } public bool IsEditTextColorBarVisible { get { return m_isEditTextBarVisible; } set { m_isEditTextBarVisible = value; NotifyPropertyChanged("IsEditTextColorBarVisible"); } } public bool IsPopupBarVisible { get { return m_isPopupBarVisible; } set { m_isPopupBarVisible = value; NotifyPropertyChanged("IsPopupBarVisible"); } } public bool IsPopupIconSelectorBarVisible { get { return m_isPopupIconSelectorBarVisible; } set { m_isPopupIconSelectorBarVisible = value; NotifyPropertyChanged("IsPopupIconSelectorBarVisible"); } } public bool IsOpacityBarVisible { get { return m_isOpacityBarVisible; } set { m_isOpacityBarVisible = value; NotifyPropertyChanged("IsOpacityBarVisible"); } } public bool IsMainAnnotationBarVisible { get { return m_isMainAnnotationBarVisible; } set { m_isMainAnnotationBarVisible = value; NotifyPropertyChanged("IsMainAnnotationBarVisible"); } } public bool IsToolbarVisible { get { return m_isToolbarVisible; } set { if (m_isToolbarVisible == value) return; m_isToolbarVisible = value; NotifyPropertyChanged("IsToolbarVisible"); } } public bool IsEditAnnotationBarVisible { get { return m_isEditAnnotationBarVisible; } set { m_isEditAnnotationBarVisible = value; NotifyPropertyChanged("IsEditAnnotationBarVisible"); } } public bool IsEditStampAnnotationBarVisible { get { return m_isEditStampAnnotationBarVisible; } set { m_isEditStampAnnotationBarVisible = value; NotifyPropertyChanged("IsEditStampAnnotationBarVisible"); } } public bool IsShapeAnnotationBarVisible { get { return m_isShapeAnnotationBarVisible; } set { m_isShapeAnnotationBarVisible = value; NotifyPropertyChanged("IsShapeAnnotationBarVisible"); } } public int AnnotationRowHeight { get { return m_annotationRowHeight; } set { m_annotationRowHeight = value; NotifyPropertyChanged("AnnotationRowHeight"); } } public int OpacityRowHeight { get { return m_opacityRowHeight; } set { m_opacityRowHeight = value; NotifyPropertyChanged("OpacityRowHeight"); } } public int ColorRowHeight { get { return m_colorRowHeight; } set { m_colorRowHeight = value; NotifyPropertyChanged("ColorRowHeight"); } } public bool IsSecondaryAnnotationBarVisible { get { return m_isSecondaryAnnotationBarVisible; } set { if (m_isSecondaryAnnotationBarVisible == value) return; m_isSecondaryAnnotationBarVisible = value; NotifyPropertyChanged("IsSecondaryAnnotationBarVisible"); } } public bool IsHighlightBarVisible { get { return m_isHightlightBarVisible; } set { if (m_isHightlightBarVisible == value) return; m_isHightlightBarVisible = value; NotifyPropertyChanged("IsHighlightBarVisible"); } } public bool IsUnderlineBarVisible { get { return m_isUnderlineBarVisible; } set { if (m_isUnderlineBarVisible == value) return; m_isUnderlineBarVisible = value; NotifyPropertyChanged("IsUnderlineBarVisible"); } } public Color InkDeleteColor { get { return m_inkdeleteColor; } set { m_inkdeleteColor = value; NotifyPropertyChanged("InkDeleteColor"); } } public Color EditTextDeleteColor { get { return m_editTextdeleteColor; } set { m_editTextdeleteColor = value; NotifyPropertyChanged("EditTextDeleteColor"); } } public Color PopupDeleteColor { get { return m_popupDeleteColor; } set { m_popupDeleteColor = value; NotifyPropertyChanged("PopupDeleteColor"); } } public Color RectangleDeleteColor { get { return m_rectangleDeleteColor; } set { m_rectangleDeleteColor = value; NotifyPropertyChanged("RectangleDeleteColor"); } } public Color CircleDeleteColor { get { return m_circleDeleteColor; } set { m_circleDeleteColor = value; NotifyPropertyChanged("CircleDeleteColor"); } } public Color LineDeleteColor { get { return m_lineDeleteColor; } set { m_lineDeleteColor = value; NotifyPropertyChanged("LineDeleteColor"); } } public Color ArrowDeleteColor { get { return m_arrowDeleteColor; } set { m_arrowDeleteColor = value; NotifyPropertyChanged("ArrowDeleteColor"); } } public Color PolygonDeleteColor { get { return m_polygonDeleteColor; } set { m_polygonDeleteColor = value; NotifyPropertyChanged("PolygonDeleteColor"); } } public Color CloudDeleteColor { get { return m_cloudDeleteColor; } set { m_cloudDeleteColor = value; NotifyPropertyChanged("CloudDeleteColor"); } } public Color PolylineDeleteColor { get { return m_polylineDeleteColor; } set { m_polylineDeleteColor = value; NotifyPropertyChanged("PolylineDeleteColor"); } } public bool IsStrikeThroughBarVisible { get { return m_isStrikeThroughBarVisible; } set { if (m_isStrikeThroughBarVisible == value) return; m_isStrikeThroughBarVisible = value; NotifyPropertyChanged("IsStrikeThroughBarVisible"); } } public bool IsSquigglyBarVisible { get { return m_isSquigglyBarVisible; } set { if (m_isSquigglyBarVisible == value) return; m_isSquigglyBarVisible = value; NotifyPropertyChanged("IsSquigglyBarVisible"); } } public bool IsRectangleAnnotationBarVisible { get { return m_isRectangleAnnotationBarVisible; } set { if (m_isRectangleAnnotationBarVisible == value) return; m_isRectangleAnnotationBarVisible = value; NotifyPropertyChanged("IsRectangleAnnotationBarVisible"); } } public bool IsCircleAnnotationBarVisible { get { return m_isCircleAnnotationBarVisible; } set { if (m_isCircleAnnotationBarVisible == value) return; m_isCircleAnnotationBarVisible = value; NotifyPropertyChanged("IsCircleAnnotationBarVisible"); } } public bool IsLineAnnotationBarVisible { get { return m_isLineAnnotationBarVisible; } set { if (m_isLineAnnotationBarVisible == value) return; m_isLineAnnotationBarVisible = value; NotifyPropertyChanged("IsLineAnnotationBarVisible"); } } public bool IsArrowAnnotationBarVisible { get { return m_isArrowAnnotationBarVisible; } set { if (m_isArrowAnnotationBarVisible == value) return; m_isArrowAnnotationBarVisible = value; NotifyPropertyChanged("IsArrowAnnotationBarVisible"); } } public bool IsPolygonAnnotationBarVisible { get { return m_isPolygonAnnotationBarVisible; } set { if (m_isPolygonAnnotationBarVisible == value) { return; } m_isPolygonAnnotationBarVisible = value; NotifyPropertyChanged("IsPolygonAnnotationBarVisible"); } } public bool IsCloudAnnotationBarVisible { get { return m_isCloudAnnotationBarVisible; } set { if (m_isCloudAnnotationBarVisible == value) { return; } m_isCloudAnnotationBarVisible = value; NotifyPropertyChanged("IsCloudAnnotationBarVisible"); } } public bool IsPolylineAnnotationBarVisible { get { return m_isPolylineAnnotationBarVisible; } set { if (m_isPolylineAnnotationBarVisible == value) { return; } m_isPolylineAnnotationBarVisible = value; NotifyPropertyChanged("IsPolylineAnnotationBarVisible"); } } public Color HighlightColor { get { return m_highlightColor; } set { if (m_highlightColor == value) return; m_highlightColor = value; NotifyPropertyChanged("HighlightColor"); } } public Color InkColor { get { return m_inkColor; } set { m_inkColor = value; NotifyPropertyChanged("InkColor"); } } public Color EditTextColor { get { return m_editTextColor; } set { m_editTextColor = value; NotifyPropertyChanged("EditTextColor"); } } public Color PopupColor { get { return m_popupColor; } set { m_popupColor = value; NotifyPropertyChanged("PopupColor"); } } public PopupIcon PopupIcon { get { return m_popupIcon; } set { m_popupIcon = value; NotifyPropertyChanged("PopupIcon"); } } public PopupIcon EditPopupIcon { get { return m_editPopupIcon; } set { m_editPopupIcon = value; NotifyPropertyChanged("EditPopupIcon"); } } public Color RectangleStrokeColor { get { return m_rectangleStrokeColor; } set { m_rectangleStrokeColor = value; NotifyPropertyChanged("RectangleStrokeColor"); } } public Color CircleStrokeColor { get { return m_circleStrokeColor; } set { m_circleStrokeColor = value; NotifyPropertyChanged("CircleStrokeColor"); } } public Color LineStrokeColor { get { return m_lineStrokeColor; } set { m_lineStrokeColor = value; NotifyPropertyChanged("LineStrokeColor"); } } public Color ArrowStrokeColor { get { return m_arrowStrokeColor; } set { m_arrowStrokeColor = value; NotifyPropertyChanged("ArrowStrokeColor"); } } public Color PolygonStrokeColor { get { return m_polygonStrokeColor; } set { m_polygonStrokeColor = value; NotifyPropertyChanged("PolygonStrokeColor"); } } public Color CloudStrokeColor { get { return m_cloudStrokeColor; } set { m_cloudStrokeColor = value; NotifyPropertyChanged("CloudStrokeColor"); } } public Color PolylineStrokeColor { get { return m_polylineStrokeColor; } set { m_polylineStrokeColor = value; NotifyPropertyChanged("PolylineStrokeColor"); } } public Color UnderlineColor { get { return m_underlineColor; } set { if (m_underlineColor == value) return; m_underlineColor = value; NotifyPropertyChanged("UnderlineColor"); } } public Color StrikeThroughColor { get { return m_strikeThroughColor; } set { if (m_strikeThroughColor == value) return; m_strikeThroughColor = value; NotifyPropertyChanged("StrikeThroughColor"); } } public Color SquigglyColor { get { return m_squigglyColor; } set { if (m_squigglyColor == value) return; m_squigglyColor = value; NotifyPropertyChanged("SquigglyColor"); } } public bool IsSearchbarVisible { get { return m_isSearchbarVisible; } set { if (m_isSearchbarVisible == value) return; m_isSearchbarVisible = value; NotifyPropertyChanged("IsSearchbarVisible"); } } public bool IsBottomToolbarVisible { get { return m_isBottomToolbarVisible; } set { if (m_isBottomToolbarVisible == value) return; m_isBottomToolbarVisible = value; NotifyPropertyChanged("IsBottomToolbarVisible"); } } public bool IsEditRectangleAnnotationBarVisible { get { return m_isEditRectangleAnnotationBarVisible; } set { m_isEditRectangleAnnotationBarVisible = value; NotifyPropertyChanged("IsEditRectangleAnnotationBarVisible"); } } public bool IsEditLineAnnotationBarVisible { get { return m_isEditLineAnnotationBarVisible; } set { m_isEditLineAnnotationBarVisible = value; NotifyPropertyChanged("IsEditLineAnnotationBarVisible"); } } public bool IsEditCircleAnnotationBarVisible { get { return m_isEditCircleAnnotationBarVisible; } set { m_isEditCircleAnnotationBarVisible = value; NotifyPropertyChanged("IsEditCircleAnnotationBarVisible"); } } public bool IsEditTextAnnotationBarVisible { get { return m_isEditTextAnnotationBarVisible; } set { m_isEditTextAnnotationBarVisible = value; NotifyPropertyChanged("IsEditTextAnnotationBarVisible"); } } public bool IsEditArrowAnnotationBarVisible { get { return m_isEditArrowAnnotationBarVisible; } set { m_isEditArrowAnnotationBarVisible = value; NotifyPropertyChanged("IsEditArrowAnnotationBarVisible"); } } public bool IsEditCloudAnnotationBarVisible { get { return m_isEditCloudAnnotationBarVisible; } set { m_isEditCloudAnnotationBarVisible = value; NotifyPropertyChanged("IsEditCloudAnnotationBarVisible"); } } public bool IsEditPolygonAnnotationBarVisible { get { return m_isEditPolygonAnnotationBarVisible; } set { m_isEditPolygonAnnotationBarVisible = value; NotifyPropertyChanged("IsEditPolygonAnnotationBarVisible"); } } public bool IsEditPolylineAnnotationBarVisible { get { return m_isEditPolylineAnnotationBarVisible; } set { m_isEditPolylineAnnotationBarVisible = value; NotifyPropertyChanged("IsEditPolylineAnnotationBarVisible"); } } public bool IsEditInkBarVisible { get { return m_isEditInkBarVisible; } set { m_isEditInkBarVisible = value; NotifyPropertyChanged("IsEditInkBarVisible"); } } public bool IsPickerVisible { get { return m_isPickerVisible; } set { m_isPickerVisible = value; NotifyPropertyChanged("IsPickerVisible"); } } public bool IsMoreOptionsToolBarVisible { get { return m_moreOptionsToolBarVisible; } set { m_moreOptionsToolBarVisible = value; NotifyPropertyChanged("IsMoreOptionsToolBarVisible"); } } private string m_searchedText = string.Empty; public string SearchedText { get { return m_searchedText; } set { m_searchedText = value; if (m_searchedText != string.Empty) { IsCancelVisible = true; } else { IsCancelVisible = false; } NotifyPropertyChanged("SearchedText"); } } private bool m_isCancelVisible = false; public bool IsCancelVisible { get { return m_isCancelVisible; } set { if (m_isCancelVisible == value) return; m_isCancelVisible = value; NotifyPropertyChanged("IsCancelVisible"); } } public bool IsInkBarVisible { get { return m_isInkBarVisible; } set { m_isInkBarVisible = value; NotifyPropertyChanged("IsInkBarVisible"); } } public bool IsRectangleBarVisible { get { return m_isRectangleBarVisible; } set { m_isRectangleBarVisible = value; NotifyPropertyChanged("IsRectangleBarVisible"); } } public bool IsCircleBarVisible { get { return m_isCircleBarVisible; } set { m_isCircleBarVisible = value; NotifyPropertyChanged("IsCircleBarVisible"); } } public bool IsLineBarVisible { get { return m_isLineBarVisible; } set { m_isLineBarVisible = value; NotifyPropertyChanged("IsLineBarVisible"); } } public bool IsArrowBarVisible { get { return m_isArrowBarVisible; } set { m_isArrowBarVisible = value; NotifyPropertyChanged("IsArrowBarVisible"); } } public bool IsPolygonBarVisible { get { return m_isPolygonBarVisible; } set { m_isPolygonBarVisible = value; NotifyPropertyChanged("IsPolygonBarVisible"); } } public bool IsCloudBarVisible { get { return m_isCloudBarVisible; } set { m_isCloudBarVisible = value; NotifyPropertyChanged("IsCloudBarVisible"); } } public bool IsPolylineBarVisible { get { return m_isPolylineBarVisible; } set { m_isPolylineBarVisible = value; NotifyPropertyChanged("IsPolylineBarVisible"); } } public bool IsInkEraserBarVisible { get { return m_isInkEraserBarVisible; } set { m_isInkEraserBarVisible = value; NotifyPropertyChanged("IsInkEraserBarVisible"); } } private Document m_selectedItem; public Document SelectedItem { get { return m_selectedItem; } set { if (m_selectedItem == value) { IsPickerVisible = false; return; } m_selectedItem = value; string filePath = string.Empty; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif PdfDocumentStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath+"Assets." + m_selectedItem.FileName + ".pdf"); NotifyPropertyChanged("SelectedItem"); IsPickerVisible = false; } } private IList<Document> m_pdfDocumentCollection; public IList<Document> PdfDocumentCollection { get { if (m_pdfDocumentCollection == null) { m_pdfDocumentCollection = new List<Document> { new Document("F# Succinctly"), new Document("GIS Succinctly"), new Document("HTTP Succinctly"), new Document("JavaScript Succinctly"), new Document("Encrypted Document") }; } return m_pdfDocumentCollection; } set { if (m_pdfDocumentCollection == value) return; m_pdfDocumentCollection = value; NotifyPropertyChanged("PdfDocumentCollection"); } } public PdfViewerViewModel() { string filePath = string.Empty; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif m_pdfDocumentStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath+"Assets.F# Succinctly.pdf"); ToggleViewModeCommand = new Command<object>(OnViewModeToggled, CanExecute); SearchAndToolbarToggleCommand = new Command<object>(OnSearchAndToolbarToggleCommand, CanExecute); FileOpenCommand = new Command<object>(OnFileOpenedCommand, CanExecute); MoreOptionsCommand = new Command<object>(OnMoreOptionsCommand, CanExecute); AnnotationCommand = new Command<object>(OnAnnotationIconClickedCommand, CanExecute); HighlightCommand = new Command<object>(OnHighlightCommand, CanExecute); UnderlineCommand = new Command<object>(OnUnderlineCommand, CanExecute); StrikeThroughCommand = new Command<object>(OnStrikeThroughCommand, CanExecute); SquigglyCommand = new Command<object>(OnSquigglyCommand, CanExecute); RectangleCommand = new Command<object>(OnRectangleCommand, CanExecute); CircleCommand = new Command<object>(OnCircleCommand, CanExecute); LineCommand = new Command<object>(OnLineCommand, CanExecute); ArrowCommand = new Command<object>(OnArrowCommand, CanExecute); PolygonCommand = new Command<object>(OnPolygonCommand, CanExecute); CloudCommand = new Command<object>(OnCloudCommand, CanExecute); PolylineCommand = new Command<object>(OnPolylineCommand, CanExecute); AnnotationBackCommand = new Command<object>(OnAnnotationBackCommand, CanExecute); ColorButtonClickedCommand = new Command<object>(OnColorButtonClickedCommand, CanExecute); ColorCommand = new Command<object>(OnColorCommand, CanExecute); TextMarkupSelectedCommand = new Command<object>(OnTextMarkupSelectedCommand, CanExecute); TextMarkupDeselectedCommand = new Command<object>(OnTextMarkupDeselectedCommand, CanExecute); DeleteCommand = new Command<object>(OnDeleteCommand, CanExecute); DocumentLoadedCommand = new Command<object>(OnDocumentLoadedCommand, CanExecute); TextMarkupCommand = new Command<object>(OnTextMarkupCommand, CanExecute); InkCommand = new Command<object>(OnInkCommand, CanExecute); EditTextCommand = new Command<object>(OnEditTextCommand, CanExecute); ShapeCommand = new Command<object>(OnShapeCommand, CanExecute); InkBackButtonCommand = new Command<object>(OnInkBackButtonCommand, CanExecute); TextMarkupBackCommand = new Command<object>(OnTextMarkupBackCommand, CanExecute); RectangleBackButtonCommand = new Command<object>(OnRectangleBackButtonCommand, CanExecute); CircleBackButtonCommand = new Command<object>(OnCircleBackButtonCommand, CanExecute); LineBackButtonCommand = new Command<object>(OnLineBackButtonCommand, CanExecute); ArrowBackButtonCommand = new Command<object>(OnArrowBackButtonCommand, CanExecute); PolygonBackButtonCommand = new Command<object>(OnPolygonBackButtonCommand, CanExecute); CloudBackButtonCommand = new Command<object>(OnCloudBackButtonCommand, CanExecute); PolylineBackButtonCommand = new Command<object>(OnPolylineBackButtonCommand, CanExecute); EditTextBackButtonCommand = new Command<object>(OnEditTextBackButtonCommand, CanExecute); ShapeBackButtonCommand = new Command<object>(OnShapeBackButtonCommand, CanExecute); InkThicknessCommand = new Command<object>(OnInkThicknessCommand, CanExecute); RectangleThicknessCommand = new Command<object>(OnRectangleThicknessCommand, CanExecute); CircleThicknessCommand = new Command<object>(OnCircleThicknessCommand, CanExecute); LineThicknessCommand = new Command<object>(OnLineThicknessCommand, CanExecute); ArrowThicknessCommand = new Command<object>(OnArrowThicknessCommand, CanExecute); PolygonThicknessCommand = new Command<object>(OnPolygonThicknessCommand, CanExecute); CloudThicknessCommand = new Command<object>(OnCloudThicknessCommand, CanExecute); PolylineThicknessCommand = new Command<object>(OnPolylineThicknessCommand, CanExecute); EditTextFontSizeCommand = new Command<object>(OnEditTextFontSizeCommand, CanExecute); OpacityButtonCommand = new Command<object>(OnOpacityButtonColorCommand, CanExecute); InkOpacityCommand = new Command<object>(OnInkOpacityCommand, CanExecute); InkSelectedCommand = new Command<object>(OnInkSelectedCommand, CanExecute); InkDeselectedCommand = new Command<object>(OnInkDeselectedCommand, CanExecute); ShapeSelectedCommand = new Command<object[]>(OnShapeSelectedCommand, CanExecute); ShapeDeselectedCommand = new Command<object>(OnShapeDeselectedCommand, CanExecute); FreeTextSelectedCommand = new Command<object>(OnFreeTextSelectedCommand, CanExecute); FreeTextDeselectedCommand = new Command<object>(OnFreeTextDeselectedCommand, CanExecute); ShapeDeleteCommand = new Command<object>(OnShapeDeletedCommand, CanExecute); EditTextDeleteCommand = new Command<object>(OnEditTextDeleteCommand, CanExecute); TabletBookmarkCommand = new Command<object>(OnTabletBookmarkCommand, CanExecute); StampAnnotationSelectedCommand = new Command<object>(OnStampSelectedCommand, CanExecute); StampAnnotationDeselectedCommand = new Command<object>(OnStampDeselectedCommand, CanExecute); PopupCommand = new Command<object>(OnPopupCommand, CanExecute); PopupBackButtonCommand = new Command<object>(OnPopupBackButtonCommand, CanExecute); PopupIconCommand = new Command<object>(OnPopupIconCommand, CanExecute); SelectPopupIconCommand = new Command<object>(OnSelectPopupIconCommand, CanExecute); PopupDeleteCommand = new Command<object>(OnPopupDeleteCommand, CanExecute); PopupAnnotationSelectedCommand = new Command(OnPopupAnnotationSelectedCommand, CanExecute); PopupAnnotationDeselectedCommand = new Command(OnPopupAnnotationDeselectedCommand, CanExecute); InkEraserCommand = new Command(OnInkEraserCommand, CanExecute); InkEraserBackButtonCommand = new Command(OnInkEraserBackButtonCommand, CanExecute); } private void OnMoreOptionsCommand(object obj) { IsMoreOptionsToolBarVisible = !IsMoreOptionsToolBarVisible; IsPickerVisible = false; } private void OnViewModeToggled(object parameter) { IsMoreOptionsToolBarVisible = false; CurrentPageViewMode = CurrentPageViewMode == PageViewMode.Continuous ? PageViewMode.PageByPage : PageViewMode.Continuous; } private void OnTabletBookmarkCommand(object parameter) { if (AnnotationGridHeightRequest != 0) OnAnnotationIconClickedCommand(null); } private void OnOpacityButtonColorCommand(object parameter) { if (AnnotationGridHeightRequest == 100) { AnnotationGridHeightRequest = 150; AnnotationRowHeight = 50; ColorRowHeight = 50; OpacityRowHeight = 50; IsOpacityBarVisible = true; } else { AnnotationGridHeightRequest = 100; AnnotationRowHeight = 50; ColorRowHeight = 50; OpacityRowHeight = 1; IsOpacityBarVisible = false; } } private void OnInkDeselectedCommand(object parameter) { if (IsEditInkBarVisible) { AnnotationGridHeightRequest = 0; IsInkBarVisible = false; IsEditInkBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; } } private void OnFreeTextSelectedCommand(object parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsInkBarVisible = false; IsEditInkBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditAnnotationBarVisible = false; IsEditTextAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnFreeTextDeselectedCommand(object parameter) { AnnotationGridHeightRequest = 0; IsInkBarVisible = false; IsEditInkBarVisible = false; IsShapeAnnotationBarVisible = false; IsShapeColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditPolygonAnnotationBarVisible = false; IsEditCloudAnnotationBarVisible = false; IsEditPolylineAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsMainAnnotationBarVisible = false; IsMoreOptionsToolBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnShapeSelectedCommand(object[] parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsInkBarVisible = false; IsEditInkBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsPopupIconSelectorBarVisible = false; IsEditPopupAnnotationBarVisible = false; if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Desktop) { IsMainAnnotationBarVisible = false; } var shapeAnnotation = parameter[0] as Syncfusion.SfPdfViewer.XForms.ShapeAnnotation; var args = (parameter[1] as Syncfusion.SfPdfViewer.XForms.ShapeAnnotationSelectedEventArgs); if (args.AnnotationType == Syncfusion.SfPdfViewer.XForms.AnnotationMode.Rectangle) { IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = true; IsEditPolygonAnnotationBarVisible = false; IsEditCloudAnnotationBarVisible = false; IsEditPolylineAnnotationBarVisible = false; } else if (args.AnnotationType == Syncfusion.SfPdfViewer.XForms.AnnotationMode.Circle) { IsEditCircleAnnotationBarVisible = true; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditPolygonAnnotationBarVisible = false; IsEditCloudAnnotationBarVisible = false; IsEditPolylineAnnotationBarVisible = false; } else if (args.AnnotationType == Syncfusion.SfPdfViewer.XForms.AnnotationMode.Line) { IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = true; IsEditArrowAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditPolygonAnnotationBarVisible = false; IsEditCloudAnnotationBarVisible = false; IsEditPolylineAnnotationBarVisible = false; } else if (args.AnnotationType == Syncfusion.SfPdfViewer.XForms.AnnotationMode.Arrow) { IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = true; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditPolygonAnnotationBarVisible = false; IsEditCloudAnnotationBarVisible = false; IsEditPolylineAnnotationBarVisible = false; } else if (args.AnnotationType == Syncfusion.SfPdfViewer.XForms.AnnotationMode.Polygon) { if (shapeAnnotation.Settings.BorderEffect == BorderEffect.Solid) { IsEditPolygonAnnotationBarVisible = true; IsEditCloudAnnotationBarVisible = false; } else { IsEditCloudAnnotationBarVisible = true; IsEditPolygonAnnotationBarVisible = false; } IsShapeAnnotationBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditPolylineAnnotationBarVisible = false; } else if (args.AnnotationType == Syncfusion.SfPdfViewer.XForms.AnnotationMode.Polyline) { IsEditPolylineAnnotationBarVisible = true; IsShapeAnnotationBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditCloudAnnotationBarVisible = false; IsEditPolygonAnnotationBarVisible = false; } } private void OnShapeDeselectedCommand(object parameter) { AnnotationGridHeightRequest = 0; IsInkBarVisible = false; IsEditInkBarVisible = false; IsShapeAnnotationBarVisible = false; IsShapeColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditPolygonAnnotationBarVisible = false; IsEditCloudAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsMainAnnotationBarVisible = false; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnPopupAnnotationSelectedCommand(object parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsInkBarVisible = false; IsEditInkBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsMoreOptionsToolBarVisible = false; if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Desktop) { IsMainAnnotationBarVisible = false; } IsEditPopupAnnotationBarVisible = true; IsPopupBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnPopupAnnotationDeselectedCommand(object parameter) { AnnotationGridHeightRequest = 0; IsInkBarVisible = false; IsEditInkBarVisible = false; IsShapeAnnotationBarVisible = false; IsShapeColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditPolygonAnnotationBarVisible = false; IsEditCloudAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsMainAnnotationBarVisible = false; IsMoreOptionsToolBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnRectangleDeselectedCommand(object parameter) { if (IsEditRectangleAnnotationBarVisible) { AnnotationGridHeightRequest = 0; IsInkBarVisible = false; IsEditInkBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; } } private void OnCircleDeselectedCommand(object parameter) { if (IsEditCircleAnnotationBarVisible) { AnnotationGridHeightRequest = 0; IsInkBarVisible = false; IsEditInkBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsFontSizeSliderBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsThicknessBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; } } private void OnLineDeselectedCommand(object parameter) { if (IsEditLineAnnotationBarVisible) { AnnotationGridHeightRequest = 0; IsInkBarVisible = false; IsEditInkBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; } } private void OnArrowDeselectedCommand(object parameter) { if (IsEditArrowAnnotationBarVisible) { AnnotationGridHeightRequest = 0; IsInkBarVisible = false; IsEditInkBarVisible = false; IsThicknessBarVisible = false; IsInkColorBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; } } private void OnInkOpacityCommand(object parameter) { if (AnnotationGridHeightRequest == 100) { AnnotationGridHeightRequest = 150; AnnotationRowHeight = 50; ColorRowHeight = 50; OpacityRowHeight = 50; IsOpacityBarVisible = true; } else { AnnotationGridHeightRequest = 100; AnnotationRowHeight = 50; ColorRowHeight = 50; OpacityRowHeight = 1; IsOpacityBarVisible = false; } IsMoreOptionsToolBarVisible = false; } private void OnInkThicknessCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsFontSizeSliderBarVisible = false; IsThicknessBarVisible = true; } else { if (IsInkColorBarVisible) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsInkColorBarVisible = false; IsFontSizeSliderBarVisible = false; IsThicknessBarVisible = true; IsOpacityBarVisible = false; } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsFontSizeSliderBarVisible = false; IsThicknessBarVisible = false; } } } private void OnRectangleThicknessCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsFontSizeSliderBarVisible = false; IsThicknessBarVisible = true; } else { if (IsShapeColorBarVisible) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsInkColorBarVisible = false; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; IsThicknessBarVisible = true; IsOpacityBarVisible = false; } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsFontSizeSliderBarVisible = false; IsThicknessBarVisible = false; IsOpacityBarVisible = false; IsShapeColorBarVisible = false; } } } private void OnCircleThicknessCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; IsFontSizeSliderBarVisible = false; ColorRowHeight = 70; IsThicknessBarVisible = true; } else { if (IsShapeColorBarVisible) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; IsFontSizeSliderBarVisible = false; ColorRowHeight = 70; IsShapeColorBarVisible = false; IsThicknessBarVisible = true; IsOpacityBarVisible = false; } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsFontSizeSliderBarVisible = false; IsThicknessBarVisible = false; IsShapeColorBarVisible = false; } } } private void OnLineThicknessCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; IsFontSizeSliderBarVisible = false; ColorRowHeight = 70; IsThicknessBarVisible = true; } else { if (IsShapeColorBarVisible) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsShapeColorBarVisible = false; IsFontSizeSliderBarVisible = false; IsThicknessBarVisible = true; IsOpacityBarVisible = false; } else { IsFontSizeSliderBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsThicknessBarVisible = false; IsShapeColorBarVisible = false; } } } private void OnArrowThicknessCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; IsFontSizeSliderBarVisible = false; AnnotationRowHeight = 50; ColorRowHeight = 70; IsThicknessBarVisible = true; } else { if (IsShapeColorBarVisible) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; IsThicknessBarVisible = true; IsOpacityBarVisible = false; } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; } } } private void OnPolygonThicknessCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; IsFontSizeSliderBarVisible = false; AnnotationRowHeight = 50; ColorRowHeight = 70; IsThicknessBarVisible = true; } else { if (IsShapeColorBarVisible) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; IsThicknessBarVisible = true; IsOpacityBarVisible = false; } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; } } } private void OnCloudThicknessCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; IsFontSizeSliderBarVisible = false; AnnotationRowHeight = 50; ColorRowHeight = 70; IsThicknessBarVisible = true; } else { if (IsShapeColorBarVisible) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; IsThicknessBarVisible = true; IsOpacityBarVisible = false; } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; } } } private void OnPolylineThicknessCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; IsFontSizeSliderBarVisible = false; AnnotationRowHeight = 50; ColorRowHeight = 70; IsThicknessBarVisible = true; } else { if (IsShapeColorBarVisible) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; IsThicknessBarVisible = true; IsOpacityBarVisible = false; } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; } } } private void OnEditTextFontSizeCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; IsFontSizeSliderBarVisible = true; IsThicknessBarVisible = false; IsOpacityBarVisible = false; } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsFontSizeSliderBarVisible = false; IsThicknessBarVisible = false; IsOpacityBarVisible = false; } } private void OnShapeBackButtonCommand(object parameter) { IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsInkColorBarVisible = false; AnnotationGridHeightRequest = 50; ColorRowHeight = 1; IsRectangleBarVisible = false; IsLineBarVisible = false; IsCircleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsEditAnnotationBarVisible = false; IsShapeAnnotationBarVisible = false; IsMainAnnotationBarVisible = true; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; } private void OnEditTextBackButtonCommand(object parameter) { AnnotationGridHeightRequest = 50; IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsOpacityBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsShapeAnnotationBarVisible = false; IsShapeColorBarVisible = false; IsEditRectangleAnnotationBarVisible = false; ColorRowHeight = 1; IsRectangleBarVisible = false; IsLineBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsEditAnnotationBarVisible = false; IsEditTextAnnotationBarVisible = false; IsMainAnnotationBarVisible = true; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnInkBackButtonCommand(object parameter) { AnnotationGridHeightRequest = 50; IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsOpacityBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsInkColorBarVisible = false; ColorRowHeight = 1; IsFontSizeSliderBarVisible = false; IsRectangleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsLineBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsMainAnnotationBarVisible = true; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; } private void OnRectangleBackButtonCommand(object parameter) { AnnotationGridHeightRequest = 50; IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsInkColorBarVisible = false; IsRectangleBarVisible = false; IsLineBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsEditAnnotationBarVisible = false; ColorRowHeight = 1; IsMainAnnotationBarVisible = false; IsShapeAnnotationBarVisible = true; IsShapeColorBarVisible = false; IsToolbarVisible = true; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnCircleBackButtonCommand(object parameter) { AnnotationGridHeightRequest = 50; IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsInkColorBarVisible = false; IsRectangleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsLineBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsEditAnnotationBarVisible = false; ColorRowHeight = 1; IsMainAnnotationBarVisible = false; IsShapeAnnotationBarVisible = true; IsShapeColorBarVisible = false; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnLineBackButtonCommand(object parameter) { AnnotationGridHeightRequest = 50; IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsInkColorBarVisible = false; IsRectangleBarVisible = false; IsLineBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsEditAnnotationBarVisible = false; IsShapeColorBarVisible = false; ColorRowHeight = 1; IsMainAnnotationBarVisible = false; IsShapeAnnotationBarVisible = true; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnArrowBackButtonCommand(object parameter) { IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsInkColorBarVisible = false; IsRectangleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsLineBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsShapeColorBarVisible = false; IsEditRectangleAnnotationBarVisible = false; AnnotationGridHeightRequest = 50; ColorRowHeight = 1; IsMainAnnotationBarVisible = false; IsShapeAnnotationBarVisible = true; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnPolygonBackButtonCommand(object parameter) { IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsInkColorBarVisible = false; IsRectangleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsLineBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsShapeColorBarVisible = false; IsEditRectangleAnnotationBarVisible = false; AnnotationGridHeightRequest = 50; ColorRowHeight = 1; IsMainAnnotationBarVisible = false; IsShapeAnnotationBarVisible = true; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnCloudBackButtonCommand(object parameter) { IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsInkColorBarVisible = false; IsRectangleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsLineBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsShapeColorBarVisible = false; IsEditRectangleAnnotationBarVisible = false; AnnotationGridHeightRequest = 50; ColorRowHeight = 1; IsMainAnnotationBarVisible = false; IsShapeAnnotationBarVisible = true; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnPolylineBackButtonCommand(object parameter) { IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsInkColorBarVisible = false; IsRectangleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsLineBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsShapeColorBarVisible = false; IsEditRectangleAnnotationBarVisible = false; AnnotationGridHeightRequest = 50; ColorRowHeight = 1; IsMainAnnotationBarVisible = false; IsShapeAnnotationBarVisible = true; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnPopupBackButtonCommand(object parameter) { AnnotationGridHeightRequest = 50; IsInkBarVisible = false; IsColorBarVisible = false; IsThicknessBarVisible = false; IsOpacityBarVisible = false; IsFontSizeSliderBarVisible = false; IsInkColorBarVisible = false; IsShapeAnnotationBarVisible = false; IsShapeColorBarVisible = false; IsEditRectangleAnnotationBarVisible = false; ColorRowHeight = 1; IsRectangleBarVisible = false; IsLineBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsEditAnnotationBarVisible = false; IsEditTextAnnotationBarVisible = false; IsMainAnnotationBarVisible = true; IsToolbarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnTextMarkupBackCommand(object parameter) { IsSecondaryAnnotationBarVisible = false; IsMainAnnotationBarVisible = true; IsMoreOptionsToolBarVisible = false; } private void OnTextMarkupCommand(object parameter) { IsMainAnnotationBarVisible = false; IsSecondaryAnnotationBarVisible = true; IsMoreOptionsToolBarVisible = false; } private void OnInkCommand(object parameter) { IsMainAnnotationBarVisible = false; IsToolbarVisible = false; IsInkBarVisible = true; IsMoreOptionsToolBarVisible = false; } private void OnEditTextCommand(object parameter) { if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Desktop) { IsToolbarVisible = true; } else { IsToolbarVisible = false; } IsMainAnnotationBarVisible = false; IsInkBarVisible = false; IsEditAnnotationBarVisible = false; IsEditTextAnnotationBarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnShapeCommand(object parameter) { if(Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Desktop) { IsMainAnnotationBarVisible = true; IsToolbarVisible = true; } else { IsMainAnnotationBarVisible = false; IsToolbarVisible = false; } IsInkBarVisible = false; IsEditAnnotationBarVisible = false; IsShapeAnnotationBarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnPopupCommand(object parameter) { if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Desktop) { IsToolbarVisible = true; } else { IsToolbarVisible = false; } IsMainAnnotationBarVisible = false; IsInkBarVisible = false; IsEditAnnotationBarVisible = false; IsEditTextAnnotationBarVisible = false; IsPopupBarVisible = true; IsPopupIconSelectorBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnInkEraserCommand(object parameter) { if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Desktop) { IsToolbarVisible = true; } else { IsToolbarVisible = false; if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 120; AnnotationRowHeight = 50; ColorRowHeight = 70; } } IsMainAnnotationBarVisible = false; IsInkEraserBarVisible = true; IsPickerVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnInkEraserBackButtonCommand(object parameter) { AnnotationGridHeightRequest = 50; IsInkEraserBarVisible = false; IsMainAnnotationBarVisible = true; IsPickerVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnDeleteCommand(object parameter) { IsEditAnnotationBarVisible = false; IsEditStampAnnotationBarVisible = false; IsEditInkBarVisible = false; IsInkColorBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; AnnotationGridHeightRequest = 0; IsMoreOptionsToolBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnDocumentLoadedCommand(object parameter) { AnnotationGridHeightRequest = 0; IsSecondaryAnnotationBarVisible = false; IsColorBarVisible = false; IsEditAnnotationBarVisible = false; IsHighlightBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsSquigglyBarVisible = false; IsRectangleAnnotationBarVisible = false; IsShapeAnnotationBarVisible = false; IsCircleAnnotationBarVisible = false; IsLineAnnotationBarVisible = false; IsArrowAnnotationBarVisible = false; IsPolygonAnnotationBarVisible = false; IsCloudAnnotationBarVisible = false; IsPolylineAnnotationBarVisible = false; IsEditAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsInkBarVisible = false; IsInkColorBarVisible = false; IsEditInkBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsOpacityBarVisible = false; IsMainAnnotationBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; IsInkEraserBarVisible = false; } private void OnTextMarkupSelectedCommand(object parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsStrikeThroughBarVisible = false; IsUnderlineBarVisible = false; IsSquigglyBarVisible = false; IsMainAnnotationBarVisible = false; IsEditAnnotationBarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnStampSelectedCommand(object parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsStrikeThroughBarVisible = false; IsUnderlineBarVisible = false; IsSquigglyBarVisible = false; IsMainAnnotationBarVisible = false; IsEditAnnotationBarVisible = false; IsEditStampAnnotationBarVisible = true; IsMoreOptionsToolBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnTextMarkupDeselectedCommand(object parameter) { if (IsEditAnnotationBarVisible) { AnnotationGridHeightRequest = 0; IsEditAnnotationBarVisible = false; } } private void OnStampDeselectedCommand(object parameter) { if (IsEditStampAnnotationBarVisible) { AnnotationGridHeightRequest = 0; IsEditStampAnnotationBarVisible = false; } IsMoreOptionsToolBarVisible = false; } private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private bool CanExecute(object parameter) { return true; } private void OnSearchAndToolbarToggleCommand(object destinationPageParam) { IsToolbarVisible = !IsToolbarVisible; IsSearchbarVisible = !IsSearchbarVisible; IsPickerVisible = false; IsMoreOptionsToolBarVisible = false; IsSecondaryAnnotationBarVisible = false; IsMainAnnotationBarVisible = false; IsColorBarVisible = false; IsHighlightBarVisible = IsUnderlineBarVisible = IsStrikeThroughBarVisible = IsSquigglyBarVisible = false; IsEditAnnotationBarVisible = false; AnnotationGridHeightRequest = 0; SearchedText = string.Empty; IsInkEraserBarVisible = false; } private void OnFileOpenedCommand(object openedFile) { IsPickerVisible = !IsPickerVisible; if(IsBookMarkVisible) IsBookMarkVisible = false; IsMoreOptionsToolBarVisible = false; IsContextMenuVisible = false; } private void OnAnnotationIconClickedCommand(object parameter) { IsSearchbarVisible = false; if (IsAnnotationGridVisible) { IsAnnotationGridVisible = false; } else IsAnnotationGridVisible = true; if (AnnotationGridHeightRequest == 0) { AnnotationGridHeightRequest = 50; IsMainAnnotationBarVisible = true; } else { if (!IsEditAnnotationBarVisible) { AnnotationGridHeightRequest = 0; IsMainAnnotationBarVisible = false; } else { AnnotationGridHeightRequest = 50; IsMainAnnotationBarVisible = true; } } AnnotationRowHeight = 50; ColorRowHeight = 1; IsColorBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsFontSizeSliderBarVisible = false; IsThicknessBarVisible = false; IsShapeColorBarVisible = false; IsHighlightBarVisible = false; IsUnderlineBarVisible = false; IsSquigglyBarVisible = false; IsStrikeThroughBarVisible = false; IsEditAnnotationBarVisible = false; IsSecondaryAnnotationBarVisible = false; IsEditInkBarVisible = false; IsInkBarVisible = false; IsPickerVisible = false; IsMoreOptionsToolBarVisible = false; IsShapeAnnotationBarVisible = false; IsRectangleBarVisible = false; IsCircleBarVisible = false; IsLineBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsPopupIconSelectorBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Desktop) { IsEditTextAnnotationBarVisible = false; } IsArrowBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditPolygonAnnotationBarVisible = false; IsEditCloudAnnotationBarVisible = false; IsEditPolylineAnnotationBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsInkEraserBarVisible = false; } private void OnHighlightCommand(object parameter) { IsSecondaryAnnotationBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsHighlightBarVisible = true; IsSquigglyBarVisible = false; IsEditAnnotationBarVisible = false; IsRectangleBarVisible = false; IsCircleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsLineBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnUnderlineCommand(object parameter) { IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsStrikeThroughBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsUnderlineBarVisible = true; IsSquigglyBarVisible = false; IsEditAnnotationBarVisible = false; IsRectangleBarVisible = false; IsCircleBarVisible = false; IsLineBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnStrikeThroughCommand(object parameter) { IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = true; IsSquigglyBarVisible = false; IsEditAnnotationBarVisible = false; IsRectangleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsCircleBarVisible = false; IsLineBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnSquigglyCommand(object parameter) { IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsSquigglyBarVisible = true; IsEditAnnotationBarVisible = false; IsRectangleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsCircleBarVisible = false; IsLineBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnRectangleCommand(object parameter) { IsRectangleBarVisible = true; IsShapeAnnotationBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsHighlightBarVisible = false; IsSquigglyBarVisible = false; IsEditAnnotationBarVisible = false; IsSecondaryAnnotationBarVisible = false; IsEditInkBarVisible = false; IsInkBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnCircleCommand(object parameter) { IsCircleBarVisible = true; IsShapeAnnotationBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsHighlightBarVisible = false; IsSquigglyBarVisible = false; IsSecondaryAnnotationBarVisible = false; IsEditInkBarVisible = false; IsInkBarVisible = false; IsEditAnnotationBarVisible = false; IsRectangleBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsLineBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnLineCommand(object parameter) { IsLineBarVisible = true; IsShapeAnnotationBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsHighlightBarVisible = false; IsSquigglyBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditAnnotationBarVisible = false; IsSecondaryAnnotationBarVisible = false; IsEditInkBarVisible = false; IsInkBarVisible = false; IsRectangleBarVisible = false; IsCircleBarVisible = false; IsArrowBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnArrowCommand(object parameter) { IsArrowBarVisible = true; IsShapeAnnotationBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsHighlightBarVisible = false; IsSquigglyBarVisible = false; IsEditAnnotationBarVisible = false; IsSecondaryAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditInkBarVisible = false; IsInkBarVisible = false; IsRectangleBarVisible = false; IsCircleBarVisible = false; IsLineBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnPolygonCommand(object parameter) { IsPolygonBarVisible = true; IsArrowBarVisible = false; IsShapeAnnotationBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsHighlightBarVisible = false; IsSquigglyBarVisible = false; IsEditAnnotationBarVisible = false; IsSecondaryAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditInkBarVisible = false; IsInkBarVisible = false; IsRectangleBarVisible = false; IsCircleBarVisible = false; IsLineBarVisible = false; IsCloudBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnCloudCommand(object parameter) { IsCloudBarVisible = true; IsArrowBarVisible = false; IsShapeAnnotationBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsHighlightBarVisible = false; IsSquigglyBarVisible = false; IsEditAnnotationBarVisible = false; IsSecondaryAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditInkBarVisible = false; IsInkBarVisible = false; IsRectangleBarVisible = false; IsCircleBarVisible = false; IsLineBarVisible = false; IsPolygonBarVisible = false; IsPolylineBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnPolylineCommand(object parameter) { IsPolylineBarVisible = true; IsArrowBarVisible = false; IsShapeAnnotationBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsHighlightBarVisible = false; IsSquigglyBarVisible = false; IsEditAnnotationBarVisible = false; IsSecondaryAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditInkBarVisible = false; IsInkBarVisible = false; IsRectangleBarVisible = false; IsCircleBarVisible = false; IsLineBarVisible = false; IsPolygonBarVisible = false; IsCloudBarVisible = false; IsPopupBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnAnnotationBackCommand(object parameter) { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsColorBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsHighlightBarVisible = false; IsUnderlineBarVisible = false; IsStrikeThroughBarVisible = false; IsSquigglyBarVisible = false; IsSecondaryAnnotationBarVisible = true; IsMoreOptionsToolBarVisible = false; } private void OnColorButtonClickedCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 100; AnnotationRowHeight = 50; ColorRowHeight = 50; if (IsHighlightBarVisible || IsUnderlineBarVisible || IsStrikeThroughBarVisible || IsSquigglyBarVisible || IsEditAnnotationBarVisible || IsEditFreeTextAnnotationBarVisible || IsEditTextAnnotationBarVisible) IsColorBarVisible = true; else if (IsInkBarVisible || IsEditInkBarVisible) IsInkColorBarVisible = true; else if (IsRectangleBarVisible || IsCircleBarVisible || IsLineBarVisible || IsArrowBarVisible || IsPolygonBarVisible || IsCloudBarVisible || IsPolylineBarVisible || IsEditArrowAnnotationBarVisible || IsEditCircleAnnotationBarVisible | IsEditRectangleAnnotationBarVisible || IsEditLineAnnotationBarVisible || IsEditPolygonAnnotationBarVisible || IsEditCloudAnnotationBarVisible || IsEditPolylineAnnotationBarVisible || IsPopupBarVisible || IsEditPopupAnnotationBarVisible) { IsShapeColorBarVisible = true; } } else { if (IsThicknessBarVisible || IsFontSizeSliderBarVisible) { IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; AnnotationGridHeightRequest = 100; AnnotationRowHeight = 50; ColorRowHeight = 50; if (IsHighlightBarVisible || IsUnderlineBarVisible || IsStrikeThroughBarVisible || IsSquigglyBarVisible || IsEditAnnotationBarVisible || IsEditFreeTextAnnotationBarVisible || IsEditTextAnnotationBarVisible) IsColorBarVisible = true; else if (IsInkBarVisible || IsEditInkBarVisible) IsInkColorBarVisible = true; else if (IsRectangleBarVisible || IsCircleBarVisible || IsLineBarVisible || IsArrowBarVisible || IsPolygonBarVisible || IsCloudBarVisible || IsPolylineBarVisible || IsEditArrowAnnotationBarVisible || IsEditCircleAnnotationBarVisible | IsEditRectangleAnnotationBarVisible || IsEditLineAnnotationBarVisible || IsEditPolygonAnnotationBarVisible || IsEditCloudAnnotationBarVisible || IsEditPolylineAnnotationBarVisible || IsPopupBarVisible || IsEditPopupAnnotationBarVisible) { IsShapeColorBarVisible = true; } } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; if (IsHighlightBarVisible || IsUnderlineBarVisible || IsStrikeThroughBarVisible || IsSquigglyBarVisible || IsEditAnnotationBarVisible || IsEditFreeTextAnnotationBarVisible || IsEditTextAnnotationBarVisible) IsColorBarVisible = false; else if (IsInkBarVisible || IsEditInkBarVisible) IsInkColorBarVisible = false; else if (IsRectangleBarVisible || IsCircleBarVisible || IsLineBarVisible || IsArrowBarVisible || IsPolygonBarVisible || IsCloudBarVisible || IsPolylineBarVisible || IsEditArrowAnnotationBarVisible || IsEditCircleAnnotationBarVisible | IsEditRectangleAnnotationBarVisible || IsEditLineAnnotationBarVisible || IsEditPolygonAnnotationBarVisible || IsEditCloudAnnotationBarVisible || IsEditPolylineAnnotationBarVisible || IsPopupBarVisible || IsEditPopupAnnotationBarVisible) { IsShapeColorBarVisible = false; } IsOpacityBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; } } } private void OnInkSelectedCommand(object parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsStrikeThroughBarVisible = false; IsUnderlineBarVisible = false; IsSquigglyBarVisible = false; IsMainAnnotationBarVisible = false; IsEditInkBarVisible = true; IsMoreOptionsToolBarVisible = false; IsPopupBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } private void OnRectangleSelectedCommand(object parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsStrikeThroughBarVisible = false; IsUnderlineBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsMainAnnotationBarVisible = false; IsEditInkBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = true; IsMoreOptionsToolBarVisible = false; } private void OnCircleSelectedCommand(object parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsStrikeThroughBarVisible = false; IsUnderlineBarVisible = false; IsMainAnnotationBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsEditInkBarVisible = false; IsEditCircleAnnotationBarVisible = true; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnLineSelectedCommand(object parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsStrikeThroughBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsUnderlineBarVisible = false; IsMainAnnotationBarVisible = false; IsEditInkBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = true; IsEditArrowAnnotationBarVisible = false; IsEditRectangleAnnotationBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnArrowSelectedCommand(object parameter) { ColorRowHeight = 1; IsColorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; IsSecondaryAnnotationBarVisible = false; IsHighlightBarVisible = false; IsStrikeThroughBarVisible = false; IsUnderlineBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; IsMainAnnotationBarVisible = false; IsEditInkBarVisible = false; IsEditCircleAnnotationBarVisible = false; IsEditLineAnnotationBarVisible = false; IsEditArrowAnnotationBarVisible = true; IsEditRectangleAnnotationBarVisible = false; } private void OnShapeDeletedCommand(object parameter) { if (IsEditRectangleAnnotationBarVisible) IsEditRectangleAnnotationBarVisible = false; else if (IsEditCircleAnnotationBarVisible) IsEditCircleAnnotationBarVisible = false; else if (IsEditLineAnnotationBarVisible) IsEditLineAnnotationBarVisible = false; else if (IsEditArrowAnnotationBarVisible) IsEditArrowAnnotationBarVisible = false; else if (IsEditPolygonAnnotationBarVisible) IsEditPolygonAnnotationBarVisible = false; else if (IsEditCloudAnnotationBarVisible) IsEditCloudAnnotationBarVisible = false; else if (IsEditPolylineAnnotationBarVisible) IsEditPolylineAnnotationBarVisible = false; } private void OnEditTextDeleteCommand(object parameter) { if (IsEditRectangleAnnotationBarVisible) { IsShapeColorBarVisible = false; IsColorBarVisible = false; IsEditRectangleAnnotationBarVisible = false; } else if (IsEditCircleAnnotationBarVisible) { IsColorBarVisible = false; IsShapeColorBarVisible = false; IsEditCircleAnnotationBarVisible = false; } else if (IsEditLineAnnotationBarVisible) { IsColorBarVisible = false; IsShapeColorBarVisible = false; IsEditLineAnnotationBarVisible = false; } else if (IsEditArrowAnnotationBarVisible) { IsColorBarVisible = false; IsShapeColorBarVisible = false; IsEditArrowAnnotationBarVisible = false; } else if (IsEditTextAnnotationBarVisible) { IsShapeColorBarVisible = false; IsColorBarVisible = false; IsEditTextAnnotationBarVisible = false; } else if (IsEditFreeTextAnnotationBarVisible) { IsColorBarVisible = false; IsShapeColorBarVisible = false; IsEditFreeTextAnnotationBarVisible = false; } else if (IsEditPolygonAnnotationBarVisible) { IsColorBarVisible = false; IsShapeColorBarVisible = false; IsEditPolygonAnnotationBarVisible = false; } else if (IsEditCloudAnnotationBarVisible) { IsColorBarVisible = false; IsShapeColorBarVisible = false; IsEditCloudAnnotationBarVisible = false; } else if (IsEditPolylineAnnotationBarVisible) { IsColorBarVisible = false; IsShapeColorBarVisible = false; IsEditPolylineAnnotationBarVisible = false; } else if (IsEditPopupAnnotationBarVisible) { IsColorBarVisible = false; IsShapeColorBarVisible = false; IsEditPopupAnnotationBarVisible = false; IsPopupIconSelectorBarVisible = false; } } private void OnPopupIconCommand(object parameter) { switch (parameter.ToString()) { case "Comment": { if (IsPopupBarVisible) PopupIcon = PopupIcon.Comment; else if (IsEditPopupAnnotationBarVisible) EditPopupIcon = PopupIcon.Comment; } break; case "Note": { if (IsPopupBarVisible) PopupIcon = PopupIcon.Note; else if (IsEditPopupAnnotationBarVisible) EditPopupIcon = PopupIcon.Note; } break; case "Help": { if (IsPopupBarVisible) PopupIcon = PopupIcon.Help; else if (IsEditPopupAnnotationBarVisible) EditPopupIcon = PopupIcon.Help; } break; case "Key": { if (IsPopupBarVisible) PopupIcon = PopupIcon.Key; else if (IsEditPopupAnnotationBarVisible) EditPopupIcon = PopupIcon.Key; } break; case "Paragraph": { if (IsPopupBarVisible) PopupIcon = PopupIcon.Paragraph; else if (IsEditPopupAnnotationBarVisible) EditPopupIcon = PopupIcon.Paragraph; } break; case "NewParagraph": { if (IsPopupBarVisible) PopupIcon = PopupIcon.NewParagraph; else if (IsEditPopupAnnotationBarVisible) EditPopupIcon = PopupIcon.NewParagraph; } break; case "Insert": { if (IsPopupBarVisible) PopupIcon = PopupIcon.Insert; else if (IsEditPopupAnnotationBarVisible) EditPopupIcon = PopupIcon.Insert; } break; } IsPopupIconSelectorBarVisible = false; AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsColorBarVisible = false; IsShapeColorBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsMoreOptionsToolBarVisible = false; } private void OnSelectPopupIconCommand(object parameter) { if (AnnotationGridHeightRequest == 50) { AnnotationGridHeightRequest = 100; AnnotationRowHeight = 50; ColorRowHeight = 50; IsPopupIconSelectorBarVisible = true; IsShapeColorBarVisible = false; } else { if (IsThicknessBarVisible || IsFontSizeSliderBarVisible) { IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; AnnotationGridHeightRequest = 100; AnnotationRowHeight = 50; ColorRowHeight = 50; IsPopupIconSelectorBarVisible = true; IsShapeColorBarVisible = false; } else { AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsOpacityBarVisible = false; IsThicknessBarVisible = false; IsFontSizeSliderBarVisible = false; IsShapeColorBarVisible = false; IsPopupIconSelectorBarVisible = false; } } } private void OnPopupDeleteCommand(object parameter) { IsPopupIconSelectorBarVisible = false; IsShapeColorBarVisible = false; } private void OnColorCommand(object parameter) { switch (parameter.ToString()) { case "Cyan": { if (IsHighlightBarVisible) HighlightColor = Color.FromHex("#00FFFF"); if (IsStrikeThroughBarVisible) StrikeThroughColor = Color.FromHex("#00FFFF"); if (IsUnderlineBarVisible) UnderlineColor = Color.FromHex("#00FFFF"); if (IsSquigglyBarVisible) SquigglyColor = Color.FromHex("#00FFFF"); if (IsEditAnnotationBarVisible) DeleteButtonColor = Color.FromHex("00FFFF"); if (IsInkBarVisible) InkColor = Color.FromHex("00FFFF"); if (IsEditInkBarVisible) InkDeleteColor = Color.FromHex("00FFFF"); if (IsEditRectangleAnnotationBarVisible) RectangleDeleteColor = Color.FromHex("00FFFF"); if (IsEditCircleAnnotationBarVisible) CircleDeleteColor = Color.FromHex("00FFFF"); if (IsEditLineAnnotationBarVisible) LineDeleteColor = Color.FromHex("00FFFF"); if (IsEditArrowAnnotationBarVisible) ArrowDeleteColor = Color.FromHex("00FFFF"); if (IsEditPolygonAnnotationBarVisible || IsEditCloudAnnotationBarVisible) PolygonDeleteColor = CloudDeleteColor = Color.FromHex("00FFFF"); if (IsEditPolylineAnnotationBarVisible) PolylineDeleteColor = Color.FromHex("00FFFF"); if (IsEditFreeTextAnnotationBarVisible ) EditTextDeleteColor = Color.FromHex("00FFFF"); if (IsEditTextColorBarVisible || IsEditTextAnnotationBarVisible) EditTextColor = Color.FromHex("00FFFF"); if (IsRectangleBarVisible) RectangleStrokeColor = Color.FromHex("00FFFF"); if (IsCircleBarVisible) CircleStrokeColor = Color.FromHex("00FFFF"); if (IsLineBarVisible) LineStrokeColor = Color.FromHex("00FFFF"); if (IsArrowBarVisible) ArrowStrokeColor = Color.FromHex("00FFFF"); if (IsPolygonBarVisible || IsCloudBarVisible) PolygonStrokeColor = CloudStrokeColor = Color.FromHex("00FFFF"); if (IsPolylineBarVisible) PolylineStrokeColor = Color.FromHex("00FFFF"); if (IsPopupBarVisible) PopupColor = Color.FromHex("00FFFF"); if (IsEditPopupAnnotationBarVisible) PopupDeleteColor = Color.FromHex("00FFFF"); } break; case "Green": { if (IsHighlightBarVisible) HighlightColor = Color.Green; if (IsStrikeThroughBarVisible) StrikeThroughColor = Color.Green; if (IsUnderlineBarVisible) UnderlineColor = Color.Green; if (IsSquigglyBarVisible) SquigglyColor = Color.Green; if (IsEditAnnotationBarVisible) DeleteButtonColor = Color.Green; if (IsInkBarVisible) InkColor = Color.Green; if (IsEditInkBarVisible) InkDeleteColor = Color.Green; if (IsEditRectangleAnnotationBarVisible) RectangleDeleteColor = Color.Green; if (IsEditCircleAnnotationBarVisible) CircleDeleteColor = Color.Green; if (IsEditLineAnnotationBarVisible) LineDeleteColor = Color.Green; if (IsEditArrowAnnotationBarVisible) ArrowDeleteColor = Color.Green; if (IsEditPolygonAnnotationBarVisible || IsEditCloudAnnotationBarVisible) PolygonDeleteColor = CloudDeleteColor = Color.Green; if (IsEditPolylineAnnotationBarVisible) PolylineDeleteColor = Color.Green; if (IsEditFreeTextAnnotationBarVisible ) EditTextDeleteColor = Color.Green; if (IsEditTextColorBarVisible || IsEditTextAnnotationBarVisible) EditTextColor = Color.Green; if (IsRectangleBarVisible) RectangleStrokeColor = Color.Green; if (IsCircleBarVisible) CircleStrokeColor = Color.Green; if (IsLineBarVisible) LineStrokeColor = Color.Green; if (IsArrowBarVisible) ArrowStrokeColor = Color.Green; if (IsPolygonBarVisible || IsCloudBarVisible) PolygonStrokeColor = CloudStrokeColor = Color.Green; if (IsPolylineBarVisible) PolylineStrokeColor = Color.Green; if (IsPopupBarVisible) PopupColor = Color.Green; if (IsEditPopupAnnotationBarVisible) PopupDeleteColor = Color.Green; } break; case "Yellow": { if (IsHighlightBarVisible) HighlightColor = Color.Yellow; if (IsStrikeThroughBarVisible) StrikeThroughColor = Color.Yellow; if (IsUnderlineBarVisible) UnderlineColor = Color.Yellow; if (IsSquigglyBarVisible) SquigglyColor = Color.Yellow; if (IsEditAnnotationBarVisible) DeleteButtonColor = Color.Yellow; if (IsInkBarVisible) InkColor = Color.Yellow; if (IsEditInkBarVisible) InkDeleteColor = Color.Yellow; if (IsEditRectangleAnnotationBarVisible) RectangleDeleteColor = Color.Yellow; if (IsEditCircleAnnotationBarVisible) CircleDeleteColor = Color.Yellow; if (IsEditLineAnnotationBarVisible) LineDeleteColor = Color.Yellow; if (IsEditArrowAnnotationBarVisible) ArrowDeleteColor = Color.Yellow; if (IsEditPolygonAnnotationBarVisible || IsEditCloudAnnotationBarVisible) PolygonDeleteColor = CloudDeleteColor = Color.Yellow; if (IsEditPolylineAnnotationBarVisible) PolylineDeleteColor = Color.Yellow; if (IsEditTextColorBarVisible || IsEditTextAnnotationBarVisible) EditTextColor = Color.Yellow; if ( IsEditFreeTextAnnotationBarVisible ) EditTextDeleteColor = Color.Yellow; if (IsRectangleBarVisible) RectangleStrokeColor = Color.Yellow; if (IsCircleBarVisible) CircleStrokeColor = Color.Yellow; if (IsLineBarVisible) LineStrokeColor = Color.Yellow; if (IsArrowBarVisible) ArrowStrokeColor = Color.Yellow; if (IsPolygonBarVisible || IsCloudBarVisible) PolygonStrokeColor = CloudStrokeColor = Color.Yellow; if (IsPolylineBarVisible) PolylineStrokeColor = Color.Yellow; if (IsPopupBarVisible) PopupColor = Color.Yellow; if (IsEditPopupAnnotationBarVisible) PopupDeleteColor = Color.Yellow; } break; case "Magenta": { if (IsHighlightBarVisible) HighlightColor = Color.FromHex("#FF00FF"); if (IsStrikeThroughBarVisible) StrikeThroughColor = Color.FromHex("#FF00FF"); if (IsUnderlineBarVisible) UnderlineColor = Color.FromHex("#FF00FF"); if (IsSquigglyBarVisible) SquigglyColor = Color.FromHex("#FF00FF"); if (IsEditAnnotationBarVisible) DeleteButtonColor = Color.FromHex("#FF00FF"); if (IsInkBarVisible) InkColor = Color.FromHex("#FF00FF"); if (IsEditInkBarVisible) InkDeleteColor = Color.FromHex("#FF00FF"); if (IsEditRectangleAnnotationBarVisible) RectangleDeleteColor = Color.FromHex("#FF00FF"); if (IsEditCircleAnnotationBarVisible) CircleDeleteColor = Color.FromHex("#FF00FF"); if (IsEditLineAnnotationBarVisible) LineDeleteColor = Color.FromHex("#FF00FF"); if (IsEditFreeTextAnnotationBarVisible ) EditTextDeleteColor = Color.FromHex("#FF00FF"); if (IsEditArrowAnnotationBarVisible) ArrowDeleteColor = Color.FromHex("#FF00FF"); if (IsEditPolygonAnnotationBarVisible || IsEditCloudAnnotationBarVisible) PolygonDeleteColor = CloudDeleteColor = Color.FromHex("FF00FF"); if (IsEditPolylineAnnotationBarVisible) PolylineDeleteColor = Color.FromHex("FF00FF"); if (IsEditTextColorBarVisible || IsEditTextAnnotationBarVisible) EditTextColor = Color.FromHex("FF00FF"); if (IsRectangleBarVisible) RectangleStrokeColor =Color.FromHex("FF00FF"); if (IsCircleBarVisible) CircleStrokeColor =Color.FromHex("FF00FF"); if (IsLineBarVisible) LineStrokeColor =Color.FromHex("FF00FF"); if (IsArrowBarVisible) ArrowStrokeColor =Color.FromHex("FF00FF"); if (IsPolygonBarVisible || IsCloudBarVisible) PolygonStrokeColor = CloudStrokeColor = Color.FromHex("FF00FF"); if (IsPolylineBarVisible) PolylineStrokeColor = Color.FromHex("FF00FF"); if (IsPopupBarVisible) PopupColor = Color.FromHex("FF00FF"); if (IsEditPopupAnnotationBarVisible) PopupDeleteColor = Color.FromHex("FF00FF"); } break; case "Black": { if (IsHighlightBarVisible) HighlightColor = Color.Black; if (IsStrikeThroughBarVisible) StrikeThroughColor = Color.Black; if (IsUnderlineBarVisible) UnderlineColor = Color.Black; if (IsSquigglyBarVisible) SquigglyColor = Color.Black; if (IsEditAnnotationBarVisible) DeleteButtonColor = Color.Black; if (IsInkBarVisible) InkColor = Color.Black; if (IsEditInkBarVisible) InkDeleteColor = Color.Black; if (IsEditRectangleAnnotationBarVisible) RectangleDeleteColor = Color.Black; if (IsEditCircleAnnotationBarVisible) CircleDeleteColor = Color.Black; if (IsEditLineAnnotationBarVisible) LineDeleteColor = Color.Black; if (IsEditFreeTextAnnotationBarVisible) EditTextDeleteColor = Color.Black; if (IsEditArrowAnnotationBarVisible) ArrowDeleteColor = Color.Black; if (IsEditPolygonAnnotationBarVisible || IsEditCloudAnnotationBarVisible) PolygonDeleteColor = CloudDeleteColor = Color.Black; if (IsEditPolylineAnnotationBarVisible) PolylineDeleteColor = Color.Black; if (IsEditTextColorBarVisible || IsEditTextAnnotationBarVisible) EditTextColor = Color.Black; if (IsRectangleBarVisible) RectangleStrokeColor = Color.Black; if (IsCircleBarVisible) CircleStrokeColor = Color.Black; if (IsLineBarVisible) LineStrokeColor = Color.Black; if (IsArrowBarVisible) ArrowStrokeColor = Color.Black; if (IsPolygonBarVisible || IsCloudBarVisible) PolygonStrokeColor = CloudStrokeColor = Color.Black; if (IsPolylineBarVisible) PolylineStrokeColor = Color.Black; if (IsPopupBarVisible) PopupColor = Color.Black; if (IsEditPopupAnnotationBarVisible) PopupDeleteColor = Color.Black; } break; case "White": { if (IsHighlightBarVisible) HighlightColor = Color.White; if (IsStrikeThroughBarVisible) StrikeThroughColor = Color.White; if (IsUnderlineBarVisible) UnderlineColor = Color.White; if (IsSquigglyBarVisible) SquigglyColor = Color.White; if (IsEditAnnotationBarVisible) DeleteButtonColor = Color.White; if (IsInkBarVisible) InkColor = Color.White; if (IsEditInkBarVisible) InkDeleteColor = Color.White; if (IsEditRectangleAnnotationBarVisible) RectangleDeleteColor = Color.White; if (IsEditCircleAnnotationBarVisible) CircleDeleteColor = Color.White; if (IsEditLineAnnotationBarVisible) LineDeleteColor = Color.White; if (IsEditFreeTextAnnotationBarVisible) EditTextDeleteColor = Color.White; if (IsEditArrowAnnotationBarVisible) ArrowDeleteColor = Color.White; if (IsEditPolygonAnnotationBarVisible || IsEditCloudAnnotationBarVisible) PolygonDeleteColor = CloudDeleteColor = Color.White; if (IsEditPolylineAnnotationBarVisible) PolylineDeleteColor = Color.White; if (IsEditTextColorBarVisible || IsEditTextAnnotationBarVisible) EditTextColor = Color.White; if (IsRectangleBarVisible) RectangleStrokeColor = Color.White; if (IsCircleBarVisible) CircleStrokeColor = Color.White; if (IsLineBarVisible) LineStrokeColor = Color.White; if (IsArrowBarVisible) ArrowStrokeColor = Color.White; if (IsPolygonBarVisible || IsCloudBarVisible) PolygonStrokeColor = CloudStrokeColor = Color.White; if (IsPolylineBarVisible) PolylineStrokeColor = Color.White; if (IsPopupBarVisible) PopupColor = Color.White; if (IsEditPopupAnnotationBarVisible) PopupDeleteColor = Color.White; } break; } AnnotationGridHeightRequest = 50; AnnotationRowHeight = 50; ColorRowHeight = 1; IsColorBarVisible = false; IsShapeColorBarVisible = false; IsInkColorBarVisible = false; IsOpacityBarVisible = false; IsMoreOptionsToolBarVisible = false; //IsEditInkBarVisible = false; //IsInkBarVisible = false; //IsRectangleBarVisible = false; //IsCircleBarVisible = false; //IsArrowBarVisible = false; //IsLineBarVisible = false; } } } <file_sep>/Forms/DataSource/DataSource/Samples/DataSourceGrouping/DataSourceGrouping.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Xamarin.Forms; using Syncfusion.DataSource; using Syncfusion.DataSource.Extensions; using SampleBrowser.Core; using Xamarin.Forms.Internals; namespace SampleBrowser.DataSource { [Preserve(AllMembers = true)] public partial class DataSourceGrouping : SampleView { ContatsViewModel viewModel; Syncfusion.DataSource.DataSource sfDataSource; public DataSourceGrouping() { InitializeComponent(); viewModel = new ContatsViewModel(); sfDataSource = new Syncfusion.DataSource.DataSource(); sfDataSource.Source = viewModel.ContactsList; sfDataSource.BeginInit(); sfDataSource.SortDescriptors.Add(new SortDescriptor("ContactName")); sfDataSource.GroupDescriptors.Add(new GroupDescriptor() { PropertyName = "ContactName", KeySelector = (object obj1) => { var item = (obj1 as Contacts); return item.ContactName[0].ToString(); } }); sfDataSource.EndInit(); listView.ItemsSource = sfDataSource.DisplayItems; } private void ListViewTemplate_BindingContextChanged(object sender, EventArgs e) { if (Device.RuntimePlatform == Device.UWP) { var viewCell = sender as ViewCell; if (viewCell.BindingContext is GroupResult) viewCell.View = new Header(); } } private void OnFilterTextChanged(object sender, TextChangedEventArgs e) { if (sfDataSource != null) { this.sfDataSource.Filter = FilterContacts; this.sfDataSource.RefreshFilter(); } } private bool FilterContacts(object obj) { var contacts = obj as Contacts; if (filterText.Text == null || contacts.ContactName.ToLower().Contains(filterText.Text.ToLower()) || contacts.ContactNumber.ToLower().Contains(filterText.Text.ToLower())) return true; else return false; } } } <file_sep>/Forms/XlsIO/XlsIO/Samples/ChartsPage/ChartsPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XlsIO; using Xamarin.Forms; namespace SampleBrowser.XlsIO { /// <summary> /// This class illustrates the creation of Excel document with bar chart. /// </summary> public partial class ChartsPage : SampleView { public ChartsPage() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP)) { this.Content.HorizontalOptions = LayoutOptions.Start; this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } internal void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; // Initializing Workbook string resourcePath = string.Empty; #if COMMONSB resourcePath = "SampleBrowser.Samples.XlsIO.Samples.Template.ChartData.xlsx"; #else resourcePath = "SampleBrowser.XlsIO.Samples.Template.ChartData.xlsx"; #endif Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; // Generate Chart IChartShape chart = sheet.Charts.Add(); chart.DataRange = sheet["A16:E26"]; chart.ChartTitle = sheet["A15"].Text; chart.HasLegend = false; chart.TopRow = 3; chart.LeftColumn = 1; chart.RightColumn = 6; chart.BottomRow = 15; workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Charts.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("Charts.xlsx", "application/msexcel", stream); } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/OHLC.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class OHLC : SampleView { public OHLC () { SFChart chart = new SFChart (); chart.Title.Text = new NSString ("Financial Analysis"); chart.PrimaryAxis = new SFDateTimeAxis (); chart.PrimaryAxis.Title.Text = new NSString ("Date"); chart.PrimaryAxis.LabelRotationAngle = -45; chart.PrimaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Hide; chart.SecondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis.Title.Text = new NSString ("Price in Dollar"); chart.SecondaryAxis.Minimum = new NSNumber (0); chart.SecondaryAxis.Maximum = new NSNumber (250); chart.SecondaryAxis.Interval = new NSNumber (50); chart.Delegate = new ChartDollarDelegate (); ChartViewModel dataModel = new ChartViewModel (); SFOHLCSeries series = new SFOHLCSeries(); series.ItemsSource = dataModel.FinancialData; series.XBindingPath = "XValue"; series.High = "High"; series.Low = "Low"; series.Open = "Open"; series.Close = "Close"; series.EnableTooltip = true; series.EnableAnimation = true; series.ColorModel.Palette = SFChartColorPalette.Natural; chart.Series.Add(series); chart.AddChartBehavior(new SFChartZoomPanBehavior()); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } } <file_sep>/Android/SampleBrowser/Samples/Diagram/OrganizationChart.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using Android.App; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Syncfusion.SfDiagram.Android; using System.IO; using System.Reflection; using Android.Util; namespace SampleBrowser { public partial class OrganizationChart : SamplePage { private bool isTablet; SfDiagram diagram; DataModel dataModel; Dictionary<string, Color> FillColor; Dictionary<string, Color> StrokeColor; private ExpandButton expanded; LinearLayout linearLayout4; float currentDensity = 1; public override View GetSampleContent(Context context) { Display display = ((Activity)context).WindowManager.DefaultDisplay; DisplayMetrics displayMetrics = new DisplayMetrics(); display.GetMetrics(displayMetrics); var wInches = displayMetrics.WidthPixels / (double)displayMetrics.DensityDpi; var hInches = displayMetrics.HeightPixels / (double)displayMetrics.DensityDpi; double screenDiagonal = Math.Sqrt(Math.Pow(wInches, 2) + Math.Pow(hInches, 2)); isTablet = screenDiagonal >= 7.0; //Create SfDiagram. diagram = new SfDiagram(context); diagram.EnableSelection = false; FillColor = new Dictionary<string, Color>(); FillColor.Add("Managing Director", Color.Rgb(239, 75, 93)); FillColor.Add("Project Manager", Color.Rgb(49, 162, 255)); FillColor.Add("Senior Manager", Color.Rgb(49, 162, 255)); FillColor.Add("Project Lead", Color.Rgb(0, 194, 192)); FillColor.Add("Senior S/W Engg", Color.Rgb(0, 194, 192)); FillColor.Add("Software Engg", Color.Rgb(0, 194, 192)); FillColor.Add("Team Lead", Color.Rgb(0, 194, 192)); FillColor.Add("Project Trainee", Color.Rgb(255, 129, 0)); StrokeColor = new Dictionary<string, Color>(); StrokeColor.Add("Managing Director", Color.Rgb(201, 32, 61)); StrokeColor.Add("Project Manager", Color.Rgb(23, 132, 206)); StrokeColor.Add("Senior Manager", Color.Rgb(23, 132, 206)); StrokeColor.Add("Project Lead", Color.Rgb(4, 142, 135)); StrokeColor.Add("Senior S/W Engg", Color.Rgb(4, 142, 135)); StrokeColor.Add("Software Engg", Color.Rgb(4, 142, 135)); StrokeColor.Add("Team Lead", Color.Rgb(4, 142, 135)); StrokeColor.Add("Project Trainee", Color.Rgb(206, 98, 9)); dataModel = new DataModel(); diagram.BackgroundColor = Color.White; diagram.BeginNodeRender += Dia_BeginNodeRender; dataModel.Data(); //To Represent DataSourceSttings Properties DataSourceSettings settings = new DataSourceSettings(); settings.ParentId = "ReportingPerson"; settings.Id = "Name"; settings.DataSource = dataModel.employee; diagram.DataSourceSettings = settings; //(diagram.LayoutManager.Layout as DirectedTreeLayout).IsDraggable //To Represent LayoutManager Properties diagram.LayoutManager = new LayoutManager() { Layout = new DirectedTreeLayout() { Type = LayoutType.Organization, HorizontalSpacing = 70 * MainActivity.Factor, VerticalSpacing = 70 * MainActivity.Factor } }; for (int i = 0; i < diagram.Connectors.Count; i++) { diagram.Connectors[i].TargetDecoratorType = DecoratorType.None; diagram.Connectors[i].Style.StrokeBrush = new SolidBrush(Color.Rgb(127, 132, 133)); } diagram.NodeClicked += Diagram_NodeClicked; diagram.ItemLongPressed += Diagram_ItemLongPressed; diagram.Loaded += Diagram_Loaded; int width = (int)(context.Resources.DisplayMetrics.WidthPixels - context.Resources.DisplayMetrics.Density) / 3; linearLayout4 = new LinearLayout(context); linearLayout4.Orientation = Android.Widget.Orientation.Vertical; linearLayout4.SetMinimumHeight((int)(190 * currentDensity)); linearLayout4.SetMinimumWidth(width); diagram.LayoutNodeDropped += Diagram_OnLayoutNodeDropped; return diagram; } public override void Destroy() { if (diagram != null) diagram.Dispose(); base.Destroy(); } OverviewPanel overview; private void Diagram_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); if (isTablet) { overview = new CustomOverview(diagram.Context); diagram.OverviewPanel = overview; overview.PreventRefresh = true; overview.Layout(0, 0, 400, 400); diagram.AddView(overview); overview.ForceRefresh(); } } internal class CustomOverview : OverviewPanel { internal CustomOverview(Context context) : base(context) { } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); Paint paint = new Paint(); paint.SetStyle(Paint.Style.Stroke); paint.StrokeWidth = 3 * Resources.DisplayMetrics.Density; paint.Color = Color.Orange; SetPadding(10, 10, 10, 10); canvas.DrawRect(new Rect(Left, Top, Right, Bottom), paint); } } public override View GetPropertyWindowLayout(Context context) { LinearLayout gridLinearLayout = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Vertical }; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); layoutParams.TopMargin = (int)(25 * currentDensity); gridLinearLayout.LayoutParameters = layoutParams; gridLinearLayout.SetBackgroundResource(Resource.Drawable.LinearLayout_Border); int width = (int)(context.Resources.DisplayMetrics.WidthPixels - context.Resources.DisplayMetrics.Density); LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Android.Widget.Orientation.Vertical; linearLayout.SetMinimumHeight((int)(190 * currentDensity)); linearLayout.SetMinimumWidth(width); LinearLayout overviewLayout = new LinearLayout(context); overviewLayout.SetPadding(0, (int)(10 * currentDensity), 0, (int)(10 * currentDensity)); overviewLayout.SetMinimumHeight((int)(30 * currentDensity)); TextView overviewLabel = new TextView(context) { Text = "Enable Overview", Gravity = GravityFlags.Start, TextSize = 15 * currentDensity }; overviewLabel.SetMinimumHeight((int)(25 * currentDensity)); overviewLabel.SetWidth((int)(width * 0.4 * currentDensity)); Switch overviewSwitch = new Switch(context); overviewSwitch.Checked = true; overviewSwitch.CheckedChange += OverviewSwitch_CheckedChange; overviewSwitch.Gravity = GravityFlags.Right; overviewSwitch.SetMinimumHeight((int)(25 * currentDensity)); overviewSwitch.SetWidth((int)(width * 0.4 * currentDensity)); overviewLayout.AddView(overviewLabel); overviewLayout.AddView(overviewSwitch); LinearLayout interactionLayout = new LinearLayout(context); interactionLayout.SetPadding(0, (int)(10 * currentDensity), 0, (int)(10 * currentDensity)); interactionLayout.SetMinimumHeight((int)(30 * currentDensity)); TextView interactionLabel = new TextView(context) { Text = "Change Hierarchy", Gravity = GravityFlags.Start, TextSize = 15 * currentDensity }; interactionLabel.SetMinimumHeight((int)(25 * currentDensity)); interactionLabel.SetWidth((int)(width * 0.4 * currentDensity)); Switch interactionSwitch = new Switch(context); interactionSwitch.CheckedChange += LayoutNodeDragSwitch_CheckedChange; interactionSwitch.Gravity = GravityFlags.Right; interactionSwitch.SetMinimumHeight((int)(25 * currentDensity)); interactionSwitch.SetWidth((int)(width * 0.4 * currentDensity)); interactionLayout.AddView(interactionLabel); interactionLayout.AddView(interactionSwitch); if (isTablet) linearLayout.AddView(overviewLayout); linearLayout.AddView(interactionLayout); gridLinearLayout.AddView(linearLayout); return gridLinearLayout; } private void OverviewSwitch_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { overview.Visibility = ViewStates.Visible; } else { overview.Visibility = ViewStates.Invisible; } } private void Diagram_OnLayoutNodeDropped(object sender, LayoutNodeDroppedEventArgs args) { Node draggedNode = args.DraggedItem as Node; Node droppedNode = args.DroppedItem as Node; bool contain = true; if (draggedNode != null && draggedNode != droppedNode) { Node ParentNode = GetParent((droppedNode.Content as DiagramEmployee).ReportingPerson); do { if (ParentNode != draggedNode) { contain = false; } else { contain = true; break; } ParentNode = GetParent((ParentNode.Content as DiagramEmployee).ReportingPerson); } while (ParentNode != null); if (!contain) { List<Connector> connectors = draggedNode.InConnectors as List<Connector>; Connector con; bool hasChild = false; for (int i = 0; i < connectors.Count; i++) { con = connectors[i]; con.SourceNode = droppedNode; hasChild = true; } if (hasChild) { Node PrevParentNode = GetParent((draggedNode.Content as DiagramEmployee).ReportingPerson); if (PrevParentNode != null && PrevParentNode.OutConnectors.Count() == 0) { (PrevParentNode.Content as DiagramEmployee).HasChild = false; DrawTemplate(PrevParentNode); } DiagramEmployee ParentEmployee = (droppedNode.Content as DiagramEmployee); (draggedNode.Content as DiagramEmployee).ReportingPerson = ParentEmployee.Name; ParentEmployee.HasChild = true; DrawTemplate(droppedNode); ExpandAll(draggedNode); } (draggedNode.Content as DiagramEmployee).ReportingPerson = (droppedNode.Content as DiagramEmployee).Name; droppedNode.IsExpanded = true; diagram.LayoutManager.Layout.UpdateLayout(); if (overview != null) overview.ForceRefresh(); } } } private void ExpandAll(Node node) { if ((node.Content as DiagramEmployee).HasChild) { node.IsExpanded = true; DrawTemplate(node); if (node.OutConnectors.Count() > 0) { foreach (var c in node.OutConnectors) { if (c.TargetNode != null) { ExpandAll(c.TargetNode); } } } } } private Node GetParent(string parentId) { foreach (Node node in diagram.Nodes) { if ((node.Content as DiagramEmployee).Name == parentId) { return node; } } return null; } private void LayoutNodeDragSwitch_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { (diagram.LayoutManager.Layout as DirectedTreeLayout).IsDraggable = true; } else { (diagram.LayoutManager.Layout as DirectedTreeLayout).IsDraggable = false; } } private void Diagram_ItemLongPressed(object sender, ItemLongPressedEventArgs args) { if (args.Item is Node) { DisplayInfo(args.Item as Node); diagram.NodeClicked -= Diagram_NodeClicked; } } private void Diagram_NodeClicked(object sender, NodeClickedEventArgs args) { Node node = args.Item; if (node.IsExpanded) { node.IsExpanded = false; if ((node.Content as DiagramEmployee).HasChild) (node.Template.GetChildAt(0) as TextView).Text = "+"; } else { node.IsExpanded = true; if ((node.Content as DiagramEmployee).HasChild) (node.Template.GetChildAt(0) as TextView).Text = "-"; } expanded.Invalidate(); } internal MemoryStream LoadResource(String name) { MemoryStream aMem = new MemoryStream(); var assm = Assembly.GetExecutingAssembly(); var path = String.Format("SampleBrowser.Resources.drawable.{0}", name); var aStream = assm.GetManifestResourceStream(path); aStream.CopyTo(aMem); return aMem; } ViewGroup DrawTemplate(Node node) { if ((node.Content as DiagramEmployee).HasChild) node.Width = 470 * MainActivity.Factor; else node.Width = 370 * MainActivity.Factor; node.Height = 120 * MainActivity.Factor; node.Style.StrokeWidth = 2 * MainActivity.Factor; node.Style.StrokeBrush = new SolidBrush(Color.Black); node.ShapeType = ShapeType.RoundedRectangle; node.CornerRadius = 10 * MainActivity.Factor; //TEMPLATE var template = new Shape(this, diagram.Context, node, dataModel, FillColor, StrokeColor); template.Layout(0, 0, (int)node.Width, (int)node.Height); //EMP IMAGE var img = new ImageView(diagram.Context); var imageId = (node.Content as DiagramEmployee).ImageUrl; if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); img.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } img.SetPadding(0, (int)(10 * MainActivity.Factor), 0, 0); img.Layout((int)(10 * MainActivity.Factor), (int)(10 * MainActivity.Factor), (int)(100 * MainActivity.Factor), (int)(100 * MainActivity.Factor)); //Name of the employee. var name = new TextView(diagram.Context); name.Text = (node.Content as DiagramEmployee).Name; name.SetTextSize(Android.Util.ComplexUnitType.Px, 28 * MainActivity.Factor); name.SetTextColor(Color.White); name.SetPadding(0, (int)(10 * MainActivity.Factor), 0, 0); name.Layout((int)(110 * MainActivity.Factor), (int)(10 * MainActivity.Factor), (int)node.Width, (int)node.Height); //Designation of the employee. var designation = new TextView(diagram.Context); designation.Text = (node.Content as DiagramEmployee).Designation; designation.SetTextSize(Android.Util.ComplexUnitType.Px, 28 * MainActivity.Factor); designation.SetTextColor(Color.White); designation.SetPadding(0, (int)(10 * MainActivity.Factor), 0, 0); designation.Layout((int)(110 * MainActivity.Factor), (int)(50 * MainActivity.Factor), (int)node.Width, (int)node.Height); if ((node.Content as DiagramEmployee).HasChild) { expanded = new ExpandButton(diagram.Context, node, FillColor); template.SetExpanded(expanded); expanded.Text = "-"; expanded.Typeface = Typeface.Create("Times New Roman", TypefaceStyle.Bold); expanded.TextAlignment = TextAlignment.Center; expanded.Gravity = GravityFlags.Center; expanded.SetTextSize(Android.Util.ComplexUnitType.Px, 54 * MainActivity.Factor); expanded.SetTextColor(Color.White); expanded.SetPadding(0, (int)(10 * MainActivity.Factor), 0, 0); expanded.SetColor(template.m_color); expanded.SetStrokeColor(template.m_strokeColor); expanded.Layout((int)(350 * MainActivity.Factor), 0, (int)(node.Width - 10 * MainActivity.Factor), (int)node.Height); template.AddView(expanded); } //Add the view to the template instance. template.AddView(img); template.AddView(name); template.AddView(designation); node.Template = template; return template; } private void DisplayInfo(Node node) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(diagram.Context); var employee = (node.Content as DiagramEmployee); EditText editText = new EditText(diagram.Context); editText.Text = "Name : " + employee.Name + "\n\n" + "Designation : " + employee.Designation + "\n\n" + "ID : " + employee.ID + "\n\n" + "DOJ : " + employee.DOJ; editText.SetBackgroundColor(Color.WhiteSmoke); editText.SetTextColor(Color.Black); editText.Enabled = false; alertBuilder.SetView(editText); alertBuilder.SetCancelable(false); alertBuilder.SetPositiveButton("OK", (senderAlert, args) => { diagram.NodeClicked += Diagram_NodeClicked; }); alertBuilder.Show(); } internal class ExpandButton : TextView { private Node m_node; private Color m_strokeColor; private Paint paint; private Dictionary<string, Color> m_fillColor; internal ExpandButton(Context context, Node node, Dictionary<string, Color> fillColor) : base(context) { m_node = node; SetWillNotDraw(false); SetBackgroundColor(Color.Transparent); m_fillColor = fillColor; } protected override void OnDraw(Canvas canvas) { paint = new Android.Graphics.Paint(); paint.AntiAlias = true; paint.SetStyle(Android.Graphics.Paint.Style.Stroke); paint.Color = m_strokeColor; paint.StrokeWidth = 2 * MainActivity.Factor; canvas.DrawLine(0, 0, 0, m_node.Height, paint); base.OnDraw(canvas); } internal void SetColor(Color color) { SetBackgroundColor(color); } internal void SetStrokeColor(Color strokeColor) { m_strokeColor = strokeColor; } } void Dia_BeginNodeRender(object sender, BeginNodeRenderEventArgs args) { //Set the node size and its properties. var node = (args.Item as Node); DrawTemplate(node); } public override void OnApplyChanges() { //Applies the changes to the layout. (diagram.LayoutManager.Layout as DirectedTreeLayout).UpdateLayout(); } internal class Shape : ViewGroup { internal Color m_color; internal Color m_strokeColor; private ExpandButton m_expanded; private Node m_node; private Dictionary<string, Color> m_fillColor; private OrganizationChart m_chart; internal Shape(OrganizationChart chart, Context context, Node node, DataModel dataModel, Dictionary<string, Color> fillColor, Dictionary<string, Color> strokeColor) : base(context) { m_chart = chart; SetX(0); SetY(0); if (LayoutParameters == null) LayoutParameters = new ViewGroup.LayoutParams((int)node.Width, (int)node.Height); else { LayoutParameters.Height = (int)node.Width; LayoutParameters.Width = (int)node.Height; } m_node = node; SetBackgroundColor(Color.Transparent); m_fillColor = fillColor; SetColor(fillColor[(node.Content as DiagramEmployee).Designation]); SetStrokeColor(strokeColor[(node.Content as DiagramEmployee).Designation]); } protected override void OnDraw(Canvas canvas) { float cornerRadius = 20 * MainActivity.Factor; Paint paint = new Paint(); paint.SetStyle(Paint.Style.Stroke); paint.StrokeWidth = 2 * MainActivity.Factor; paint.Color = m_strokeColor; paint.AntiAlias = true; canvas.DrawRoundRect(Left, Top, Right, Bottom, cornerRadius, cornerRadius, paint); paint = new Paint(); paint.SetStyle(Paint.Style.Fill); paint.AntiAlias = true; paint.Color = m_color; canvas.DrawRoundRect(Left, Top, Right, Bottom, cornerRadius, cornerRadius, paint); base.OnDraw(canvas); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { } internal void SetColor(Color color) { m_color = color; } internal void SetStrokeColor(Color color) { m_strokeColor = color; } internal void SetExpanded(ExpandButton expanded) { m_expanded = expanded; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/AutoRowHeightViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser { public class AutoRowHeightViewModel : INotifyPropertyChanged { public AutoRowHeightViewModel() { ReleaseInfoRepository details = new ReleaseInfoRepository(); releaseInformation = details.GetReleaseDetails(28); } #region ItemsSource private ObservableCollection<ReleaseInfo> releaseInformation; public ObservableCollection<ReleaseInfo> ReleaseInformation { get { return this.releaseInformation; } set { this.releaseInformation = value; } } #endregion #region Property Changed public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion } } <file_sep>/Forms/NumericUpDown/NumericUpDown/Samples/NumericUpDown/NumericUpDown_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfNumericUpDown.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfNumericUpDown { public partial class NumericUpDown_Default : SampleView { void Handle_ValueChanged(object sender, Syncfusion.SfNumericUpDown.XForms.ValueEventArgs e) { if (e.Value.ToString() == "0" || e.Value.ToString() == "0.0") appleAddButton.IsEnabled = false; else appleAddButton.IsEnabled = true; this.AppleCost.Text = "$" + Convert.ToDouble(e.Value) * 0.49; } void Handle_ValueChanged2(object sender, Syncfusion.SfNumericUpDown.XForms.ValueEventArgs e) { if (e.Value.ToString() == "0" || e.Value.ToString() == "0.0") pomegranateAddButton.IsEnabled = false; else pomegranateAddButton.IsEnabled = true; this.PomegranateCost.Text = "$" + Convert.ToDouble(e.Value) * 0.99; } void Handle_ValueChanged3(object sender, Syncfusion.SfNumericUpDown.XForms.ValueEventArgs e) { if (e.Value.ToString() == "0" || e.Value.ToString() == "0.0") orangeAddButton.IsEnabled = false; else orangeAddButton.IsEnabled = true; this.OrangeCost.Text = "$" + Convert.ToDouble(e.Value) * 0.19; } void Handle_ValueChanged4(object sender, Syncfusion.SfNumericUpDown.XForms.ValueEventArgs e) { if (e.Value.ToString() == "0" || e.Value.ToString() == "0.0") bananaAddButton.IsEnabled = false; else bananaAddButton.IsEnabled = true; this.BananaCost.Text = "$" + Convert.ToDouble(e.Value) * 0.09; } int totalCart = 0; void Handle_Clicked(object sender, System.EventArgs e) { totalCart++; TotalCart.Text = "(" + totalCart.ToString() + ")"; } public NumericUpDown_Default() { InitializeComponent(); optionView(); AppleCount.Minimum = PomegranateCount.Minimum = OrangeCount.Minimum = BananaCount.Minimum = 0; AppleCount.Maximum = PomegranateCount.Maximum = OrangeCount.Maximum = BananaCount.Maximum = 25; } public void optionView() { double height = Bounds.Height; double width = Core.SampleBrowser.ScreenWidth; double density = Core.SampleBrowser.Density; minimumValueText.TextChanged += MinimumValueChanged; maximumValueText.TextChanged += MaximumValueChanged; maximumValueText.Unfocused += MaximumValueText_Focused; FontSizeText.TextChanged += FontSizeText_TextChanged; //Auto Reversee autoReverseToggle.Toggled += (object sender, ToggledEventArgs e) => { AppleCount.AutoReverse = PomegranateCount.AutoReverse = OrangeCount.AutoReverse = BananaCount.AutoReverse = e.Value; }; selectallonfocusToggle.Toggled += (object sender, ToggledEventArgs e) => { AppleCount.SelectAllOnFocus = PomegranateCount.SelectAllOnFocus = OrangeCount.SelectAllOnFocus = BananaCount.SelectAllOnFocus = e.Value; }; localePicker.Items.Add("Both"); localePicker.Items.Add("Left"); localePicker.Items.Add("Right"); localePicker.SelectedIndex = 0; localePicker.SelectedIndexChanged += localePickerChanged; if (Device.RuntimePlatform == Device.Android) { fruitHeadingLabel.FontSize = 18; checkoutLabel.FontSize = 16; TotalCart.FontSize = 16; AppleCount.HeightRequest = 45; appleAddButton.HeightRequest = 45; bananaAddButton.HeightRequest = 45; BananaCount.HeightRequest = 45; orangeAddButton.HeightRequest = 45; OrangeCount.HeightRequest = 45; pomegranateAddButton.HeightRequest = 45; PomegranateCount.HeightRequest = 45; appleAddButton.Font = Font.SystemFontOfSize(14); orangeAddButton.Font = Font.SystemFontOfSize(14); bananaAddButton.Font = Font.SystemFontOfSize(14); pomegranateAddButton.Font = Font.SystemFontOfSize(14); } else if (Device.RuntimePlatform == Device.iOS) { fruitHeadingLabel.FontSize = 18; checkoutLabel.FontSize = 18; checkoutLabel.Margin = new Thickness(0, 8, 0, 0); TotalCart.Margin = new Thickness(5, 8, 0, 5); TotalCart.FontSize = 18; AppleCost.FontSize = 15; appleAddButton.FontSize = 14; appleAddButton.WidthRequest = 100; AppleCost.VerticalTextAlignment = TextAlignment.Center; appleAddButton.VerticalOptions = LayoutOptions.Center; AppleCount.HeightRequest = 35; BananaCost.FontSize = 15; bananaAddButton.FontSize = 14; bananaAddButton.WidthRequest = 100; BananaCost.VerticalTextAlignment = TextAlignment.Center; bananaAddButton.VerticalOptions = LayoutOptions.Center; BananaCount.HeightRequest = 35; OrangeCost.FontSize = 15; orangeAddButton.FontSize = 14; orangeAddButton.WidthRequest = 100; OrangeCost.VerticalTextAlignment = TextAlignment.Center; orangeAddButton.VerticalOptions = LayoutOptions.Center; OrangeCount.HeightRequest = 35; PomegranateCost.FontSize = 15; pomegranateAddButton.FontSize = 14; pomegranateAddButton.WidthRequest = 100; PomegranateCost.VerticalTextAlignment = TextAlignment.Center; pomegranateAddButton.VerticalOptions = LayoutOptions.Center; PomegranateCount.HeightRequest = 35; cartInfoStack.Padding = new Thickness(-20, 0, 0, 0); checkoutLabel.HorizontalTextAlignment = TextAlignment.Center; TotalCart.HorizontalTextAlignment = TextAlignment.Center; optionLayout.Padding = new Thickness(0, 0, 10, 0); optionLayout.Spacing = 0; } else if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { sampleLayout.Padding = new Thickness(10, 0, 0, 0); optionLayout.Padding = new Thickness(10, 0, 10, 0); localePicker.HeightRequest = 90; autoReverseToggle.WidthRequest = width / 2; autoReverseToggle.HorizontalOptions = LayoutOptions.End; selectallonfocusToggle.WidthRequest = width / 2; selectallonfocusToggle.HorizontalOptions = LayoutOptions.End; } if (Device.RuntimePlatform == Device.UWP) { minimumValueLabel.TextColor = Color.Gray; maximumValueLabel.TextColor = Color.Gray; autoReverseLabel.TextColor = Color.Gray; selectallonfocuslabel.TextColor = Color.Gray; spinButtonAlignmentLabel.TextColor = Color.Gray; aheader.Height = 25; pheader.Height = 25; bheader.Height = 25; oheader.Height = 25; if (Device.Idiom == TargetIdiom.Desktop) { sampleLayout.HorizontalOptions = LayoutOptions.Center; sampleLayout.WidthRequest = 500; minColumn1.Width = new GridLength(200.0, GridUnitType.Absolute); maxColumn1.Width = new GridLength(200.0, GridUnitType.Absolute); reverseColumn1.Width = new GridLength(200.0, GridUnitType.Absolute); selectallonfocusColumn.Width = new GridLength(200.0, GridUnitType.Absolute); FontSizeColumn.Width = new GridLength(200.0, GridUnitType.Absolute); minimumValueText.HorizontalOptions = LayoutOptions.Start; maximumValueText.HorizontalOptions = LayoutOptions.Start; FontSizeText.HorizontalOptions = LayoutOptions.Start; autoReverseToggle.HorizontalOptions = LayoutOptions.Start; selectallonfocusToggle.HorizontalOptions = LayoutOptions.Start; localePicker.HorizontalOptions = LayoutOptions.Start; localePicker.WidthRequest = 300.0; appleAddButton.FontSize = 12; pomegranateAddButton.FontSize = 12; orangeAddButton.FontSize = 12; bananaAddButton.FontSize = 12; } if (Device.Idiom == TargetIdiom.Phone) { AppleCost.VerticalTextAlignment = TextAlignment.Center; appleAddButton.FontSize = 10; appleAddButton.WidthRequest = 90; pomegranateAddButton.FontSize = 10; pomegranateAddButton.WidthRequest = 90; orangeAddButton.FontSize = 10; orangeAddButton.WidthRequest = 90; bananaAddButton.FontSize = 10; bananaAddButton.WidthRequest = 90; } } } void MinimumValueChanged(object sender, TextChangedEventArgs e) { if (e.NewTextValue.Length > 0) { double minimum; if (double.TryParse(e.NewTextValue, out minimum) && minimum != AppleCount.Minimum) { if (minimum < AppleCount.Maximum) { AppleCount.Minimum = PomegranateCount.Minimum = OrangeCount.Minimum = BananaCount.Minimum = minimum; } else { AppleCount.Minimum = PomegranateCount.Minimum = OrangeCount.Minimum = BananaCount.Minimum = AppleCount.Maximum; minimumValueText.Text = AppleCount.Maximum.ToString(); } } } else { AppleCount.Minimum = PomegranateCount.Minimum = OrangeCount.Minimum = BananaCount.Minimum = 1; } } void MaximumValueChanged(object sender, TextChangedEventArgs e) { if (e.NewTextValue.Length > 0) { double maximum; if (double.TryParse(e.NewTextValue, out maximum) && maximum != AppleCount.Maximum) { AppleCount.Maximum = PomegranateCount.Maximum = OrangeCount.Maximum = BananaCount.Maximum = maximum; } } else { AppleCount.Maximum = PomegranateCount.Maximum = OrangeCount.Maximum = BananaCount.Maximum = 25; } } void FontSizeText_TextChanged(object sender, TextChangedEventArgs e) { if (e.NewTextValue.Length > 0) { double fontsize; if (double.TryParse(e.NewTextValue, out fontsize) && fontsize != AppleCount.FontSize) { AppleCount.FontSize = PomegranateCount.FontSize = OrangeCount.FontSize = BananaCount.FontSize = fontsize; } } else { AppleCount.FontSize = PomegranateCount.FontSize = OrangeCount.FontSize = BananaCount.FontSize = 18; } } void MaximumValueText_Focused(object sender, Xamarin.Forms.FocusEventArgs e) { if(!e.IsFocused) { double maximum; if (double.TryParse(maximumValueText.Text.ToString(), out maximum)) { if (!(maximum > AppleCount.Minimum)) { AppleCount.Maximum = PomegranateCount.Maximum = OrangeCount.Maximum = BananaCount.Maximum = AppleCount.Minimum; maximumValueText.Text = AppleCount.Minimum.ToString(); } } } } void localePickerChanged(object sender, EventArgs e) { switch (localePicker.SelectedIndex) { case 0: { AppleCount.SpinButtonAlignment = PomegranateCount.SpinButtonAlignment = OrangeCount.SpinButtonAlignment = BananaCount.SpinButtonAlignment = SpinButtonAlignment.Both; AppleCount.TextAlignment = PomegranateCount.TextAlignment = OrangeCount.TextAlignment = BananaCount.TextAlignment = TextAlignment.Center; } break; case 1: { AppleCount.SpinButtonAlignment = PomegranateCount.SpinButtonAlignment = OrangeCount.SpinButtonAlignment = BananaCount.SpinButtonAlignment = SpinButtonAlignment.Left; AppleCount.TextAlignment = PomegranateCount.TextAlignment = OrangeCount.TextAlignment = BananaCount.TextAlignment = TextAlignment.End; } break; case 2: { AppleCount.SpinButtonAlignment = PomegranateCount.SpinButtonAlignment = OrangeCount.SpinButtonAlignment = BananaCount.SpinButtonAlignment = SpinButtonAlignment.Right; AppleCount.TextAlignment = PomegranateCount.TextAlignment = OrangeCount.TextAlignment = BananaCount.TextAlignment = TextAlignment.Start; } break; } } public View getContent() { return this.Content; } public View getPropertyView() { return this.PropertyView; } } } <file_sep>/Forms/BusyIndicator/readme.md The `SfBusyIndicator` control makes it easy to let the user know when an application is busy. It is used to indicate busy status during app loading, data processing etc. The following sample is available for busy indicator to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](BusyIndicator/Samples/BusyIndicator)|It demonstrates the available built-in animation types.| <file_sep>/Forms/BadgeView/BadgeView/Samples/Notification/NotificationModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "BadgeModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfBadgeView { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using SampleBrowser.Core; using Xamarin.Forms; /// <summary> /// BadgeView Model Class. /// </summary> [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1027:TabsMustNotBeUsed", Justification = "Reviewed.")] public class NotificationModel { /// <summary> /// Gets or sets the image /// </summary> public string Image { get; set; } /// <summary> /// Gets or sets the Name /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the Time /// </summary> public string Time { get; set; } /// <summary> /// Gets or sets the Count for BadgeView /// </summary> public string Count { get; set; } /// <summary> /// Gets or sets the Message /// </summary> public string Message { get; set; } } }<file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/UICollectionView Helper/CircleView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using CoreGraphics; using Foundation; using UIKit; using CoreAnimation; using CoreText; namespace SampleBrowser { public class CircleView : UIView { private const double radians = Math.PI / 180; public UIColor ViewColor { get; set; } public string text { get; set; } public CircleView() : base() { this.BackgroundColor = UIColor.Clear; this.text = null; } public CircleView(CGRect frame) : base(frame) { this.Frame = frame; this.BackgroundColor = UIColor.Clear; this.text = null; } public override void Draw(CGRect rect) { base.Draw(rect); using (CGContext context = UIGraphics.GetCurrentContext()) { var radius = this.Frame.Width / 2; CGPath path = new CGPath(); path.AddArc(this.Frame.Width / 2, this.Frame.Height / 2, radius - 1, 0, (nfloat)(360 * radians), true); ViewColor.SetColor(); context.AddPath(path); context.DrawPath(CGPathDrawingMode.FillStroke); UIColor.White.SetColor(); CTFont font = new CTFont("Arial", 20); NSAttributedString stringToBeDrawn = new NSAttributedString(text, new CTStringAttributes() { Font = font, ForegroundColorFromContext = true, }); context.TranslateCTM(this.Frame.Width / 2 - stringToBeDrawn.Size.Width / 2, this.Frame.Height / 2 + stringToBeDrawn.Size.Height / 4); context.ScaleCTM(1, -1); CTLine line = new CTLine(stringToBeDrawn); line.Draw(context); font = null; stringToBeDrawn = null; path = null; } } } }<file_sep>/Forms/Kanban/Kanban/Samples/Themes/ThemesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfKanban.XForms; using System.Collections.ObjectModel; using Xamarin.Forms; namespace SampleBrowser.SfKanban { public class ThemesViewModel { public ObservableCollection<KanbanModel> Cards { get; set; } public ThemesViewModel() { Cards = new ObservableCollection<KanbanModel>(); Cards.Add( new KanbanModel() { ID = 1, Title = "iOS - 1", ImageURL = "People_Circle1.png", Category = "Open", Description = "Analyze customer requirements", Tags = new string[] { "Bug", "Customer", "Release Bug" } } ); Cards.Add( new KanbanModel() { ID = 6, Title = "Xamarin - 6", ImageURL = "People_Circle2.png", Category = "Open", Description = "Show the retrived data from the server in grid control", Tags = new string[] { "Bug", "Customer", "Breaking Issue" } } ); Cards.Add( new KanbanModel() { ID = 3, Title = "iOS - 3", ImageURL = "People_Circle3.png", Category = "Open", Description = "Fix the filtering issues reported in safari", Tags = new string[] { "Bug", "Customer", "Breaking Issue" } } ); Cards.Add( new KanbanModel() { ID = 11, Title = "iOS - 11", ImageURL = "People_Circle4.png", Category = "Open", Description = "Add input validation for editing", Tags = new string[] { "Bug", "Customer", "Breaking Issue" } } ); Cards.Add( new KanbanModel() { ID = 15, Title = "Android - 15", Category = "Open", ImageURL = "People_Circle5.png", Description = "Arrange web meeting for cutomer requirement", Tags = new string[] { "Story", "Kanban" } }); Cards.Add( new KanbanModel() { ID = 3, Title = "Android - 3", Category = "Code Review", ImageURL = "People_Circle6.png", Description = "API Improvements", Tags = new string[] { "Bug", "Customer" } }); Cards.Add( new KanbanModel() { ID = 4, Title = "UWP - 4", ImageURL = "People_Circle6.png", Category = "Code Review", Description = "Enhance editing functionality", Tags = new string[] { "Story", "Kanban" } }); Cards.Add( new KanbanModel() { ID = 9, Title = "Xamarin - 9", ImageURL = "People_Circle7.png", Category = "Code Review", Description = "Improve application performance", Tags = new string[] { "Story", "Kanban" } } ); Cards.Add( new KanbanModel() { ID = 13, Title = "UWP - 13", ImageURL = "People_Circle8.png", Category = "In Progress", Description = "Add responsive support to applicaton", Tags = new string[] { "Story", "Kanban" } } ); Cards.Add( new KanbanModel() { ID = 17, Title = "Xamarin - 17", Category = "In Progress", ImageURL = "People_Circle9.png", Description = "Fix the issues reported in IE browser", Tags = new string[] { "Bug", "Customer" } } ); Cards.Add( new KanbanModel() { ID = 21, Title = "Xamarin - 21", Category = "In Progress", ImageURL = "People_Circle10.png", Description = "Improve performance of editing functionality", Tags = new string[] { "Bug", "Customer" } } ); Cards.Add( new KanbanModel() { ID = 19, Title = "iOS - 19", Category = "In Progress", ImageURL = "People_Circle11.png", Description = "Fix the issues reported by the customer", Tags = new string[] { "Bug" } } ); Cards.Add( new KanbanModel() { ID = 8, Title = "Android", Category = "Code Review", ImageURL = "People_Circle12.png", Description = "Check login page validation", Tags = new string[] { "Feature" } } ); Cards.Add( new KanbanModel() { ID = 24, Title = "UWP - 24", ImageURL = "People_Circle13.png", Category = "In Progress", Description = "Test editing functionality", Tags = new string[] { "Feature", "Customer", "Release" } } ); Cards.Add( new KanbanModel() { ID = 20, Title = "iOS - 20", Category = "In Progress", ImageURL = "People_Circle14.png", Description = "Fix the issues reported in data binding", Tags = new string[] { "Feature", "Release", } } ); Cards.Add( new KanbanModel() { ID = 12, Title = "Xamarin - 12", Category = "In Progress", ImageURL = "People_Circle15.png", Description = "Test editing functionality", Tags = new string[] { "Feature", "Release", } } ); Cards.Add( new KanbanModel() { ID = 11, Title = "iOS - 11", Category = "In Progress", ImageURL = "People_Circle16.png", Description = "Check filtering validation", Tags = new string[] { "Feature", "Release", } } ); Cards.Add( new KanbanModel() { ID = 13, Title = "UWP - 13", ImageURL = "People_Circle17.png", Category = "Closed", Description = "Fix cannot open user's default database sql error", Tags = new string[] { "Bug", "Internal", "Release" } }); Cards.Add( new KanbanModel() { ID = 14, Title = "Android - 14", Category = "Closed", ImageURL = "People_Circle18.png", Description = "Arrange web meeting with customer to get login page requirement", Tags = new string[] { "Feature" } } ); Cards.Add( new KanbanModel() { ID = 15, Title = "Xamarin - 15", Category = "Closed", ImageURL = "People_Circle19.png", Description = "Login page validation", Tags = new string[] { "Bug" } } ); Cards.Add( new KanbanModel() { ID = 16, Title = "Xamarin - 16", ImageURL = "People_Circle20.png", Category = "Closed", Description = "Test the application in IE browser", Tags = new string[] { "Bug" } } ); Cards.Add( new KanbanModel() { ID = 20, Title = "UWP - 20", ImageURL = "People_Circle21.png", Category = "Closed", Description = "Analyze stored procedure", Tags = new string[] { "CustomSample", "Customer", "Incident" } } ); Cards.Add( new KanbanModel() { ID = 21, Title = "Android - 21", Category = "Closed", ImageURL = "People_Circle22.png", Description = "Arrange web meeting with customer to get editing requirements", Tags = new string[] { "Story", "Improvement" } } ); } } } <file_sep>/Forms/ListView/ListView/Samples/Grouping/Helper/Behaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DataSource; using Syncfusion.ListView.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] #region GroupingBehavior public class SfListViewGroupingBehavior:Behavior<Syncfusion.ListView.XForms.SfListView> { #region Fields private Syncfusion.ListView.XForms.SfListView ListView; #endregion #region Overrides protected override void OnAttachedTo(Syncfusion.ListView.XForms.SfListView bindable) { ListView = bindable; ListView.DataSource.GroupDescriptors.Add(new GroupDescriptor() { PropertyName = "ContactName", KeySelector = (object obj1) => { var item = (obj1 as ListViewContactsInfo); return item.ContactName[0].ToString(); }, }); base.OnAttachedTo(bindable); } protected override void OnDetachingFrom(Syncfusion.ListView.XForms.SfListView bindable) { ListView = null; base.OnDetachingFrom(bindable); } #endregion } #endregion } <file_sep>/Forms/DataForm/DataForm/App.xaml.cs #region Copyright // <copyright file="App.xaml.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.Linq; using System.Text; using SampleBrowser; using Xamarin.Forms; /// <summary> /// Represents the initialize component of application. /// </summary> public partial class App : Application { /// <summary> /// Initializes a new instance of the <see cref="App"/> class. /// </summary> public App() { this.InitializeComponent(); var page = Core.SampleBrowser.GetMainPage("SfDataForm", "SampleBrowser.SfDataForm"); this.MainPage = page; } /// <summary> /// Handle when your app starts /// </summary> protected override void OnStart() { // Handle when your app starts } /// <summary> /// Handle when your app sleeps /// </summary> protected override void OnSleep() { // Handle when your app sleeps } /// <summary> /// Handle when your app resumes /// </summary> protected override void OnResume() { // Handle when your app resumes } } } <file_sep>/Forms/ComboBox/readme.md The `SfComboBox` control is an editor component that allow users to type a text and choose an option from the list of predefined options. Also, it has editable and non-editable support to make a selection. The following sample is available for combo box to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](ComboBox/Samples/GettingStartedSample)| It demonstrates the basic functionalities like filtering pattern, sensing diacritics in languages, editable options and control customization.| |[Multiple Selection](ComboBox/Samples/ToleratingTypos)| It demonstrates the feature of multi selection in ComboBox. Here, multi selection in token representation has been demonstrated.|<file_sep>/Android/SampleBrowser/Common/Activity/AllControlsSamplePage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content.PM; using Android.Graphics; using Android.Graphics.Drawables; using Android.OS; using Android.Views; using Android.Widget; namespace SampleBrowser { [Activity(Theme = "@style/PropertyApp", MainLauncher = false, ScreenOrientation = ScreenOrientation.Portrait)] public class AllControlsSamplePage : Activity { #region fields private bool isselected = true; #endregion #region properties internal SampleModel SelectedGroup { get; set; } internal SamplePage CurrentSamplePage { get; set; } internal RelativeLayout SettingsButton { get; set; } #endregion #region methods public override void OnBackPressed() { Finish(); base.OnBackPressed(); } public override void Finish() { if (CurrentSamplePage != null) { CurrentSamplePage.Destroy(); CurrentSamplePage = null; } base.Finish(); } public override bool OnOptionsItemSelected(IMenuItem item) { if (item.ItemId == Android.Resource.Id.Home) { Finish(); } return base.OnOptionsItemSelected(item); } protected override void OnCreate(Bundle savedInstanceState) { ActionBar.SetDisplayHomeAsUpEnabled(true); ActionBar.SetDisplayShowCustomEnabled(true); ActionBar.SetIcon(new ColorDrawable(Color.Transparent)); ActionBar.SetDisplayShowTitleEnabled(false); LayoutInflater layoutInflater = LayoutInflater.From(this); View customActionBar = layoutInflater.Inflate(Resource.Layout.CustomActionBar, null); RelativeLayout imageButton = (RelativeLayout)customActionBar.FindViewById(Resource.Id.imageButton); View propertyWindow = layoutInflater.Inflate(Resource.Layout.Propertywindow, null); View mainView = layoutInflater.Inflate(Resource.Layout.layout, null); SettingsButton = imageButton; SetContentView(mainView); var popup = new PopupWindow(propertyWindow, ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); popup.Focusable = true; popup.DismissEvent += (s, e) => isselected = true; imageButton.Click += delegate { popup.ContentView = propertyWindow; if (CurrentSamplePage.PropertyView == null) { CurrentSamplePage.PropertyView = CurrentSamplePage.GetPropertyWindowLayout(this); } var linear = (LinearLayout)propertyWindow.FindViewById(Resource.Id.container); linear.RemoveAllViews(); linear.AddView(CurrentSamplePage.PropertyView); if (isselected) { popup.ShowAsDropDown(imageButton, 0, 280); popup.Focusable = true; popup.Update(); isselected = false; } ImageView iconclose = (ImageView)propertyWindow.FindViewById(Resource.Id.close); Button discard = (Button)propertyWindow.FindViewById(Resource.Id.discard); Button apply = (Button)propertyWindow.FindViewById(Resource.Id.apply); iconclose.Click += delegate { popup.Dismiss(); isselected = true; }; discard.Click += delegate { popup.Dismiss(); isselected = true; }; apply.Click += delegate { CurrentSamplePage.OnApplyChanges(CurrentSamplePage.SampleView); popup.Dismiss(); isselected = true; }; }; ActionBar.CustomView = customActionBar; SelectedGroup = (ControlModel)MainActivity.SelectedIntent.GetSerializableExtra("sample"); var textView = (TextView)FindViewById(Resource.Id.title_text); textView.Text = SelectedGroup.Title; var textParent = (RelativeLayout)FindViewById(Resource.Id.textParent); textParent.Click += (s, e) => Finish(); if ((SelectedGroup as ControlModel).Features.Count > 0) { ActionBar.NavigationMode = ActionBarNavigationMode.Tabs; AddTab("Types", new ChartFragment((SelectedGroup as ControlModel).Samples, this)); AddTab("Features", new ChartFragment((SelectedGroup as ControlModel).Features, this)); } else { ActionBar.NavigationMode = ActionBarNavigationMode.Standard; FrameLayout frameLayout = (FrameLayout)mainView.FindViewById(Resource.Id.fragment_content); var sampleViewActivity = new SampleViewActivity((SelectedGroup as ControlModel).Samples, frameLayout, this, 0); if ((SelectedGroup as ControlModel).Samples.Count > 0) { textView.Text = (SelectedGroup as ControlModel).Samples[0].Title; } sampleViewActivity.BaseTextView = textView; } if (savedInstanceState != null && ActionBar.TabCount > 0) { ActionBar.SelectTab(this.ActionBar.GetTabAt(savedInstanceState.GetInt("tab"))); } base.OnCreate(savedInstanceState); } protected override void OnSaveInstanceState(Bundle outState) { outState.PutInt("tab", this.ActionBar.SelectedNavigationIndex); base.OnSaveInstanceState(outState); } private void AddTab(string tabText, Fragment view) { var tab = ActionBar.NewTab(); tab.SetText(tabText); tab.TabSelected += delegate(object sender, ActionBar.TabEventArgs e) { var fragment = FragmentManager.FindFragmentById(Resource.Id.fragment_content); if (fragment != null) { e.FragmentTransaction.Remove(fragment); } e.FragmentTransaction.Add(Resource.Id.fragment_content, view); }; tab.TabUnselected += delegate(object sender, ActionBar.TabEventArgs e) { e.FragmentTransaction.Remove(view); }; ActionBar.AddTab(tab); } #endregion } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/Exporting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.SfDataGrid; using System.Globalization; using Syncfusion.SfDataGrid.Exporting; using System.Reflection; using System.IO; using Java.IO; using Android.Graphics; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Drawing; using Android.Content.Res; using Android; using Android.Content.PM; using AndroidX.Core.Content; using AndroidX.Core.App; namespace SampleBrowser { public class Exporting : SamplePage { #region Fields SfDataGrid sfGrid; ExportingViewModel viewModel; Button exportPdf; Button exportExcel; ImageView pdfImage; ImageView excelImage; Label spacing; #endregion public override Android.Views.View GetSampleContent(Context context) { sfGrid = new SfDataGrid(context); if (ContextCompat.CheckSelfPermission(context, Manifest.Permission.WriteExternalStorage) != Permission.Granted) { ActivityCompat.RequestPermissions((Android.App.Activity)context, new String[] { Manifest.Permission.WriteExternalStorage }, 1); } sfGrid.SelectionMode = SelectionMode.Single; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; viewModel = new ExportingViewModel(); sfGrid.AutoGeneratingColumn += GridGenerateColumns; sfGrid.ItemsSource = (viewModel.OrdersInfo); pdfImage = new ImageView(context); pdfImage.Touch += ExportToPdf; pdfImage.SetImageResource(Resource.Drawable.pdfexport); pdfImage.SetPadding((int)(10 * Resources.System.DisplayMetrics.Density), 0, 0, 0); exportPdf = new Button(context); exportPdf.Text = "Export PDF"; exportPdf.SetTextSize(Android.Util.ComplexUnitType.Px, 12 * Resources.System.DisplayMetrics.Density); exportPdf.Click += ExportToPdf; exportPdf.SetBackgroundColor(Android.Graphics.Color.Transparent); exportPdf.SetTextColor(Android.Graphics.Color.ParseColor("#666666")); exportPdf.SetPadding(0, 0, (int)(10 * Resources.System.DisplayMetrics.Density), 0); excelImage = new ImageView(context); excelImage.Touch += ExportToExcel; excelImage.SetImageResource(Resource.Drawable.excelexport); excelImage.SetPadding((int)(10 * Resources.System.DisplayMetrics.Density), 0, 0, 0); exportExcel = new Button(context); exportExcel.Text = "Export Excel"; exportExcel.SetTextSize(Android.Util.ComplexUnitType.Px, 12 * Resources.System.DisplayMetrics.Density); exportExcel.Click += ExportToExcel; exportExcel.SetBackgroundColor(Android.Graphics.Color.Transparent); exportExcel.SetTextColor(Android.Graphics.Color.ParseColor("#666666")); exportExcel.SetPadding(0, 0, (int)(10 * Resources.System.DisplayMetrics.Density), 0); spacing = new Label(context); spacing.SetBackgroundColor(Android.Graphics.Color.Transparent); LinearLayout excelOption = new LinearLayout(context); excelOption.SetGravity(GravityFlags.Center); excelOption.Orientation = Android.Widget.Orientation.Horizontal; excelOption.AddView(excelImage, Convert.ToInt32(50 * sfGrid.Resources.DisplayMetrics.Density), Convert.ToInt32(56 * sfGrid.Resources.DisplayMetrics.Density)); excelOption.AddView(exportExcel, Convert.ToInt32(100 * sfGrid.Resources.DisplayMetrics.Density), Convert.ToInt32(56 * sfGrid.Resources.DisplayMetrics.Density)); LinearLayout.LayoutParams excelLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); excelLayoutParams.Gravity = GravityFlags.CenterHorizontal; excelOption.LayoutParameters = excelLayoutParams; excelOption.SetPadding((int)(10 * Resources.System.DisplayMetrics.Density), 0 , (int)(10 * Resources.System.DisplayMetrics.Density), 0 ); excelOption.SetBackgroundResource(Resource.Layout.backgroundborder); LinearLayout pdfOption = new LinearLayout(context ); pdfOption.SetGravity(GravityFlags.Center); pdfOption.Orientation = Android.Widget.Orientation.Horizontal; pdfOption.AddView(pdfImage, Convert.ToInt32(50 * sfGrid.Resources.DisplayMetrics.Density), Convert.ToInt32(56 * sfGrid.Resources.DisplayMetrics.Density)); pdfOption.AddView(exportPdf, Convert.ToInt32(100 * sfGrid.Resources.DisplayMetrics.Density), Convert.ToInt32(56 * sfGrid.Resources.DisplayMetrics.Density)); LinearLayout.LayoutParams pdfLayoutparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); pdfLayoutparams.Gravity = GravityFlags.CenterHorizontal; pdfOption.LayoutParameters = pdfLayoutparams; pdfOption.SetPadding((int)(10 * Resources.System.DisplayMetrics.Density), 0, (int)(10 * Resources.System.DisplayMetrics.Density), 0 ); pdfOption.SetBackgroundResource(Resource.Layout.backgroundborder); LinearLayout option = new LinearLayout(context); option.SetGravity(GravityFlags.Center); option.Orientation = Android.Widget.Orientation.Horizontal; option.AddView(pdfOption, Convert.ToInt32(150 * sfGrid.Resources.DisplayMetrics.Density), Convert.ToInt32(46 * sfGrid.Resources.DisplayMetrics.Density)); option.AddView(spacing, Convert.ToInt32(20 * sfGrid.Resources.DisplayMetrics.Density), Convert.ToInt32(46 * sfGrid.Resources.DisplayMetrics.Density)); option.AddView(excelOption, Convert.ToInt32(150 * sfGrid.Resources.DisplayMetrics.Density), Convert.ToInt32(46 * sfGrid.Resources.DisplayMetrics.Density)); LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layoutparams.Gravity = GravityFlags.Start; option.SetPadding((int)(10 * Resources.System.DisplayMetrics.Density), (int)(10 * Resources.System.DisplayMetrics.Density), 0, (int)(10 * Resources.System.DisplayMetrics.Density)); option.LayoutParameters = layoutparams; LinearLayout mainView = new LinearLayout(context); mainView.Orientation = Android.Widget.Orientation.Vertical; mainView.AddView(option); mainView.AddView(sfGrid); return mainView; } private void ExportToExcel(object sender, EventArgs e) { DataGridExcelExportingController excelExport = new DataGridExcelExportingController(); var excelEngine = excelExport.ExportToExcel(this.sfGrid, new DataGridExcelExportingOption() { ExportRowHeight = false, ExportColumnWidth = false, DefaultColumnWidth = 100, DefaultRowHeight = 60 }); var workbook = excelEngine.Excel.Workbooks[0]; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); Save("DataGrid.xlsx", "application/msexcel", stream , sfGrid.Context); } private void ExportToPdf(object sender, EventArgs e) { DataGridPdfExportingController pdfExport = new DataGridPdfExportingController(); pdfExport.HeaderAndFooterExporting += pdfExport_HeaderAndFooterExporting; MemoryStream stream = new MemoryStream(); var doc = pdfExport.ExportToPdf(this.sfGrid); doc.Save(stream); doc.Close(true); Save("DataGrid.pdf", "application/pdf", stream, sfGrid.Context); } private void pdfExport_HeaderAndFooterExporting(object sender, PdfHeaderFooterEventArgs e) { var width = e.PdfPage.GetClientSize().Width; PdfPageTemplateElement header = new PdfPageTemplateElement(width, 60); var assmbely = Assembly.GetExecutingAssembly(); var imagestream = assmbely.GetManifestResourceStream("SampleBrowser.Resources.drawable.SyncfusionLogo.jpg"); if (imagestream != null) { PdfImage pdfImage = PdfImage.FromStream(imagestream); header.Graphics.DrawImage(pdfImage, new RectangleF(0, 0, width, 50)); e.PdfDocumentTemplate.Top = header; } } public void Save(string fileName, String contentType, MemoryStream stream , Context context) { string exception = string.Empty; string root = null; if (Android.OS.Environment.IsExternalStorageEmulated) { root = Android.OS.Environment.ExternalStorageDirectory.ToString(); } else root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); if (file.Exists()) { file.Delete(); file.CreateNewFile(); } try { FileOutputStream outs = new FileOutputStream(file, false); outs.Write(stream.ToArray()); outs.Flush(); outs.Close(); } catch (Exception e) { exception = e.ToString(); } if (file.Exists() && contentType != "application/html") { Android.Net.Uri path = FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".provider", file); string extension = Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString()); string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); Intent intent = new Intent(Intent.ActionView); intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask); intent.SetDataAndType(path, mimeType); intent.AddFlags(ActivityFlags.GrantReadUriPermission); context.StartActivity(Intent.CreateChooser(intent, "Choose App")); } } void GridGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo("en-US"); e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "Last Name"; e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "ShippingDate") { e.Column.HeaderText = "Shipping Date"; e.Column.Format = "d"; } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextAlignment = GravityFlags.CenterVertical; } } public override void Destroy() { sfGrid.AutoGeneratingColumn -= GridGenerateColumns; sfGrid.Dispose(); sfGrid = null; viewModel = null; } } }<file_sep>/Android/SampleBrowser/Samples/PullToRefresh/SfDataGrid/SfDataGridInPullToRefresh.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Views; using System.Globalization; using Syncfusion.SfPullToRefresh; using System.Threading.Tasks; using Android.Widget; using System.Collections.Generic; using Android.Graphics; using Android.Content; namespace SampleBrowser { public class SfDataGridInPullToRefresh:SamplePage { SfPullToRefresh pullToRefresh; SfDataGrid sfGrid; GettingStartedViewModel viewModel; public override View GetSampleContent (Android.Content.Context context) { pullToRefresh = new SfPullToRefresh(context); pullToRefresh.Refreshing += Pull_Refreshing; sfGrid = new SfDataGrid (context); sfGrid.HeaderRowHeight = 52; pullToRefresh.RefreshContentThreshold = 52; sfGrid.RowHeight = 48; viewModel = new GettingStartedViewModel (); sfGrid.SelectionMode = SelectionMode.Single; viewModel.SetRowstoGenerate (100); sfGrid.AutoGenerateColumns = false; GridGenerateColumns(); sfGrid.ColumnSizer = ColumnSizer.Star; sfGrid.ItemsSource = (viewModel.OrdersInfo); sfGrid.AllowResizingColumn = true; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; pullToRefresh.PullableContent = sfGrid; return pullToRefresh; } void GridGenerateColumns() { sfGrid.Columns.Add(new GridTextColumn() { MappingName = "OrderID", HeaderText = "Order ID" }); sfGrid.Columns.Add(new GridTextColumn() { MappingName = "CustomerID", HeaderText = "Customer ID", TextAlignment = GravityFlags.CenterVertical }); sfGrid.Columns.Add(new GridTextColumn() { MappingName = "Freight", Format = "C", CultureInfo = new CultureInfo("en-US"), TextAlignment = GravityFlags.Center }); sfGrid.Columns.Add(new GridTextColumn() { MappingName = "ShipCity", HeaderText = "Ship City", TextAlignment = GravityFlags.CenterVertical }); } private async void Pull_Refreshing(object sender, RefreshingEventArgs e) { await Task.Delay(3000); if (viewModel != null) viewModel.ItemsSourceRefresh(); e.Refreshed = true; } public override View GetPropertyWindowLayout(Context context) { FrameLayout propertyLayout = new FrameLayout(context); LinearLayout container = new LinearLayout(context); container.Orientation = Orientation.Vertical; container.SetBackgroundColor(Color.White); container.SetPadding(15, 15, 15, 20); TextView transitiontype = new TextView(context); transitiontype.Text = "Tranisition Type"; transitiontype.TextSize = 20; transitiontype.SetPadding(0, 0, 0, 10); transitiontype.SetTextColor(Color.Black); Spinner transitionTypeSpinner = new Spinner(context, SpinnerMode.Dialog); transitionTypeSpinner.SetMinimumHeight(60); transitionTypeSpinner.SetBackgroundColor(Color.Gray); transitionTypeSpinner.DropDownWidth = 600; transitionTypeSpinner.SetPadding(10, 10, 0, 10); transitionTypeSpinner.SetGravity(GravityFlags.CenterHorizontal); container.AddView(transitiontype); container.AddView(transitionTypeSpinner); List<String> list = new List<String>(); list.Add("SlideOnTop"); list.Add("Push"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, list); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); transitionTypeSpinner.Adapter = dataAdapter; transitionTypeSpinner.ItemSelected += transitionTypeSpinner_ItemSelected; if (pullToRefresh.TransitionType == TransitionType.SlideOnTop) transitionTypeSpinner.SetSelection(0); else transitionTypeSpinner.SetSelection(1); propertyLayout.AddView(container); return propertyLayout; } void transitionTypeSpinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; String selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); if (pullToRefresh != null) { if (selectedItem.Equals("SlideOnTop")) { pullToRefresh.TransitionType = TransitionType.SlideOnTop; pullToRefresh.PullingThreshold = 120; } else if (selectedItem.Equals("Push")) { pullToRefresh.TransitionType = TransitionType.Push; pullToRefresh.PullingThreshold = 140; } } } public override void Destroy() { pullToRefresh.Refreshing -= Pull_Refreshing; viewModel = null; pullToRefresh.Dispose(); pullToRefresh = null; } } } <file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/ListViewPullToRefresh/ListViewPullToRefreshViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ListViewPullToRefreshViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using System; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A ViewModel for ListViewPullToRefresh sample. /// </summary> public class ListViewPullToRefreshViewModel { #region Fields [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.internal field does not need documentation")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] internal BlogsInfoRepository Source; #endregion #region Constructor /// <summary> /// Initializes a new instance of the ListViewPullToRefreshViewModel class. /// </summary> public ListViewPullToRefreshViewModel() { this.Source = new BlogsInfoRepository(); this.BlogsInfo = this.Source.GenerateSource(); this.ReadMoreCommand = new Command<object>(this.NavigateToReadMoreContent); this.TwitterCommand = new Command<object>(this.NavigateTwitterLink); this.LinkedInCommand = new Command<object>(this.NavigateLinkedInLink); this.FacebookCommand = new Command<object>(this.NavigateFacebookLink); this.GooglePlusCommand = new Command<object>(this.NavigateGooglePlusLink); } #endregion #region Properties /// <summary> /// Gets or sets the BlogsInfo type of ObservableCollection and notifies user when collection value gets changed. /// </summary> public ObservableCollection<ListViewBlogsInfo> BlogsInfo { get; set; } /// <summary> /// Gets or sets the value of ReadMoreCommand, Defines an System.Windows.Input.ICommand implementation wrapping a generic Action /// </summary> public Command<object> ReadMoreCommand { get; set; } /// <summary> /// Gets or sets the value of TwitterCommand Defines an System.Windows.Input.ICommand implementation wrapping a generic Action /// </summary> public Command<object> TwitterCommand { get; set; } /// <summary> /// Gets or sets the value of LinkedInCommand Defines an System.Windows.Input.ICommand implementation wrapping a generic Action /// </summary> public Command<object> LinkedInCommand { get; set; } /// <summary> /// Gets or sets the value of FacebookCommand, Defines an System.Windows.Input.ICommand implementation wrapping a generic Action /// </summary> public Command<object> FacebookCommand { get; set; } /// <summary> /// Gets or sets the value of GooglePlus with Command Defines an System.Windows.Input.ICommand implementation wrapping a generic Action /// </summary> public Command<object> GooglePlusCommand { get; set; } /// <summary> /// Gets or sets the value of GooglePlus with Interface abstracting platform-specific navigation /// </summary> internal INavigation Navigation { get; set; } #endregion #region Private Methods /// <summary> /// Used to Navigation of Read More Content /// </summary> /// <param name="obj">object type parameter named as object</param> private void NavigateToReadMoreContent(object obj) { ReadMoreContentPage readMoreContentPage = new ReadMoreContentPage(); readMoreContentPage.BindingContext = obj; this.Navigation.PushAsync(readMoreContentPage); } /// <summary> /// Used to Navigate to the twitter link /// </summary> /// <param name="obj">object type parameter named as object</param> private void NavigateTwitterLink(object obj) { string title = (obj as ListViewBlogsInfo).BlogTitle; string firstPart = "https://twitter.com/intent/tweet?status="; string lastPart = "+%7C+Syncfusion+Blog+%3A+http%3A%2F%2Fbit.ly%2FQ2iGwU+%23syncfusionblog&url=http%3A%2F%2Fbit.ly%2FQ2iGwU"; Launcher.OpenAsync(new Uri(firstPart + title.Replace(" ", "+") + lastPart)); } /// <summary> /// Used to Navigate to the Linked in link /// </summary> /// <param name="obj">object type parameter named as object</param> private void NavigateLinkedInLink(object obj) { string title = (obj as ListViewBlogsInfo).BlogTitle; string firstPart = "http://www.linkedin.com/shareArticle?mini=true&url=http%3A%2F%2Fwww.syncfusion.com/blogs/.UARWGQDuyus.linkedin&title="; string lastPart = "+%7C+Syncfusion+Blog+%3A+http%3A%2F%2Fwww.syncfusion.com/blogs/+%23syncfusionblog&ro=false&summary=&source="; Launcher.OpenAsync(new Uri(firstPart + title.Replace(" ", "+") + lastPart)); } /// <summary> /// Used to Navigate to the Facebook link /// </summary> /// <param name="obj">object type parameter named as object</param> private void NavigateFacebookLink(object obj) { string title = (obj as ListViewBlogsInfo).BlogTitle; string firstPart = "https://www.facebook.com/sharer/sharer.php?u=http://www.syncfusion.com/blogs//blogs/post/"; string lastPart = ".aspx"; title = title.ToLower(); title = title.Replace(":", string.Empty); title = title.Replace(" + ", string.Empty); title = title.Replace(" - ", string.Empty); title = title.Replace("&", " and "); title = title.Replace("#", string.Empty); title = title.Replace(",", string.Empty); title = title.Replace("\"", string.Empty); title = title.Replace("?", string.Empty); Launcher.OpenAsync(new Uri(firstPart + title.Replace(" ", "-") + lastPart)); } /// <summary> /// Used to Navigate to the Google plus link /// </summary> /// <param name="obj">object type parameter named as object</param> private void NavigateGooglePlusLink(object obj) { string title = (obj as ListViewBlogsInfo).BlogTitle; string firstPart = "https://plus.google.com/share?url=http%3A%2F%2Fwww.syncfusion.com/blogs/%23.UARa30_n4sY.google_plusone_share&t="; string lastPart = "+%7C+Syncfusion+Blog+%3A+http%3A%2F%2Fwww.syncfusion.com/blogs/+%23syncfusionblog"; Launcher.OpenAsync(new Uri(firstPart + title.Replace(" ", "+") + lastPart)); } #endregion } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Model/BookInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "BookInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// Notifies clients that a property value has changed /// </summary> public class BookInfo : INotifyPropertyChanged { #region private variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int customerID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int bookID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string firstName; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string lastName; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int price; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string bookName; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string country; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private bool isAvailable; #endregion /// <summary> /// Initializes a new instance of the BookInfo class. /// </summary> public BookInfo() { } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the value of CustomerID and notifies user when value gets changed /// </summary> public int CustomerID { get { return this.customerID; } set { this.customerID = value; this.RaisePropertyChanged("CustomerID"); } } /// <summary> /// Gets or sets the value of BookID and notifies user when value gets changed /// </summary> public int BookID { get { return this.bookID; } set { this.bookID = value; this.RaisePropertyChanged("BookID"); } } /// <summary> /// Gets or sets the value of FirstName and notifies user when value gets changed /// </summary> public string FirstName { get { return this.firstName; } set { this.firstName = value; this.RaisePropertyChanged("FirstName"); } } /// <summary> /// Gets or sets the value of LastName and notifies user when value gets changed /// </summary> public string LastName { get { return this.lastName; } set { this.lastName = value; this.RaisePropertyChanged("LastName"); } } /// <summary> /// Gets or sets the value of BookName and notifies user when value gets changed /// </summary> public string BookName { get { return this.bookName; } set { this.bookName = value; this.RaisePropertyChanged("BookName"); } } /// <summary> /// Gets or sets the value of Price and notifies user when value gets changed /// </summary> public int Price { get { return this.price; } set { this.price = value; this.RaisePropertyChanged("Price"); } } /// <summary> /// Gets or sets the value of Country and notifies user when value gets changed /// </summary> public string Country { get { return this.country; } set { this.country = value; this.RaisePropertyChanged("Country"); } } /// <summary> /// Gets or sets a value indicating whether IsAvailable is true or false and notifies user when value gets changed /// </summary> public bool IsAvailable { get { return this.isAvailable; } set { this.isAvailable = value; this.RaisePropertyChanged("IsAvailable"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type of parameter name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Android/SampleBrowser/Samples/XlsIO/FindAndReplace.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public partial class FindAndReplace : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to find the word Berlin and replace it as Rome within the worksheet."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Input Template"; button1.Click += OnButtonClicked; linear.AddView (button1); TextView space3 = new TextView (con); space3.TextSize = 10; linear.AddView (space3); Button button2 = new Button (con); button2.Text = "Replace All"; button2.Click += OnButtonClicked_1; linear.AddView (button2); return linear; } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ReplaceOptions.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly (); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("InputTemplate.xlsx", "application/msexcel", stream, m_context); } } void OnButtonClicked_1(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ReplaceOptions.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly (); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; sheet["A60"].Activate(); #endregion string replaceText = "Berlin"; ExcelFindOptions option = ExcelFindOptions.None; option |= ExcelFindOptions.MatchCase; option |= ExcelFindOptions.MatchEntireCellContent; sheet.Replace (replaceText, "Rome", option); workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("ReplacedFile.xlsx", "application/msexcel", stream, m_context); } } } }<file_sep>/Android/SampleBrowser/Samples/Sunburst/SunburstSelection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.SfSunburstChart.Android; namespace SampleBrowser { [Preserve(AllMembers = true)] public class SunburstSelection : SamplePage { SfSunburstChart chart; List<String> adapter; List<String> adapter1; public ObservableCollection<SunburstModel> Population_Data { get; set; } public override View GetSampleContent(Context context) { this.Population_Data = new ObservableCollection<SunburstModel> { new SunburstModel { State = "Ontario", Continent = "North America", Country = "Canada", Population = 13210600 }, new SunburstModel { State = "New York", Continent = "North America", Country = "United States", Population = 19378102 }, new SunburstModel { State = "Pennsylvania", Continent = "North America", Country = "United States", Population = 12702379 }, new SunburstModel { State = "Ohio", Continent = "North America", Country = "United States", Population = 11536504 }, new SunburstModel { State = "Buenos Aires", Continent = "South America", Country = "Argentina", Population = 15594428 }, new SunburstModel { State = "Minas Gerais", Continent = "South America", Country = "Brazil", Population = 20593366 }, new SunburstModel { State = "Rio de Janeiro", Continent = "South America", Country = "Brazil", Population = 16369178 }, new SunburstModel { State = "Bahia", Continent = "South America", Country = "Brazil", Population = 15044127 }, new SunburstModel { State = "Rio Grande do Sul", Continent = "South America", Country = "Brazil", Population = 11164050 }, new SunburstModel { State = "Parana", Continent = "South America", Country = "Brazil", Population = 10997462 }, new SunburstModel { State = "Chittagong", Continent = "Asia", Country = "Bangladesh", Population = 28079000 }, new SunburstModel { State = "Rajshahi", Continent = "Asia", Country = "Bangladesh", Population = 18329000 }, new SunburstModel { State = "Khulna", Continent = "Asia", Country = "Bangladesh", Population = 15563000 }, new SunburstModel { State = "Liaoning", Continent = "Asia", Country = "China", Population = 43746323 }, new SunburstModel { State = "Shaanxi", Continent = "Asia", Country = "China", Population = 37327378 }, new SunburstModel { State = "Fujian", Continent = "Asia", Country = "China", Population = 36894216 }, new SunburstModel { State = "Shanxi", Continent = "Asia", Country = "China", Population = 35712111 }, new SunburstModel { State = "Kerala", Continent = "Asia", Country = "India", Population = 33387677 }, new SunburstModel { State = "Punjab", Continent = "Asia", Country = "India", Population = 27704236 }, new SunburstModel { State = "Haryana", Continent = "Asia", Country = "India", Population = 25353081 }, new SunburstModel { State = "Delhi", Continent = "Asia", Country = "India", Population = 16753235 }, new SunburstModel { State = "Jammu", Continent = "Asia", Country = "India", Population = 12548926 }, new SunburstModel { State = "West Java", Continent = "Asia", Country = "Indonesia", Population = 43021826 }, new SunburstModel { State = "East Java", Continent = "Asia", Country = "Indonesia", Population = 37476011 }, new SunburstModel { State = "Banten", Continent = "Asia", Country = "Indonesia", Population = 10644030 }, new SunburstModel { State = "Jakarta", Continent = "Asia", Country = "Indonesia", Population = 10187595 }, new SunburstModel { State = "Tianjin", Continent = "Africa", Country = "Ethiopia", Population = 24000200 }, new SunburstModel { State = "Tianjin", Continent = "Africa", Country = "Ethiopia", Population = 15042531 }, new SunburstModel { State = "Rift Valley", Continent = "Africa", Country = "Kenya", Population = 10006805 }, new SunburstModel { State = "Lagos", Continent = "Africa", Country = "Nigeria", Population = 10006805 }, new SunburstModel { State = "Kano", Continent = "Africa", Country = "Nigeria", Population = 10006805 }, new SunburstModel { State = "Gauteng", Continent = "Africa", Country = "South Africa", Population = 12728400 }, new SunburstModel { State = "KwaZulu-Natal", Continent = "Africa", Country = "South Africa", Population = 10456900 }, new SunburstModel { State = "Ile-de- France", Continent = "Europe", Country = "France", Population = 11694000 }, new SunburstModel { State = "North Rhine-Westphalia", Continent = "Europe", Country = "Germany", Population = 17872863 }, new SunburstModel { State = "Bavaria", Continent = "Europe", Country = "Germany", Population = 12510331 }, new SunburstModel { State = "NBaden-Wurttemberg", Continent = "Europe", Country = "Germany", Population = 10747479 }, new SunburstModel { State = "England", Continent = "Europe", Country = "United Kingdom", Population = 51446600 } }; chart = new SfSunburstChart(context); chart.ItemsSource = Population_Data; chart.Radius = 0.95; chart.ValueMemberPath = "Population"; var levels = new SunburstLevelCollection() { new SunburstHierarchicalLevel() { GroupMemberPath = "Continent"}, new SunburstHierarchicalLevel() { GroupMemberPath = "Country"}, new SunburstHierarchicalLevel() { GroupMemberPath = "State"}, }; chart.Levels = levels; chart.Title.IsVisible = true; chart.Title.Margin = new Thickness(10, 5, 5, 5); chart.Title.Text = "Population Data"; chart.Title.TextSize = 20; chart.Legend.IsVisible = true; chart.DataLabel.ShowLabel = true; chart.SelectionSettings.EnableSelection = true; return chart; } public override View GetPropertyWindowLayout(Android.Content.Context context) { TextView selectionMode = new TextView(context); selectionMode.Text = "Selection Mode"; selectionMode.Typeface = Typeface.DefaultBold; selectionMode.SetTextColor(Color.ParseColor("#262626")); selectionMode.TextSize = 20; Spinner spinSelectionMode = new Spinner(context, SpinnerMode.Dialog); adapter = new List<String>() { "Opacity", "Color", "Stroke" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); spinSelectionMode.Adapter = dataAdapter; spinSelectionMode.ItemSelected += SpinMode_ItemSelected; TextView selectionType = new TextView(context); selectionType.Text = "Selection Type"; selectionType.Typeface = Typeface.DefaultBold; selectionType.SetTextColor(Color.ParseColor("#262626")); selectionType.TextSize = 20; Spinner spinSelectionType = new Spinner(context, SpinnerMode.Dialog); adapter1 = new List<String>() { "Child", "Group", "Parent" , "Single"}; ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter1); dataAdapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); spinSelectionType.Adapter = dataAdapter1; spinSelectionType.ItemSelected += spinSelectionType_ItemSelected; LinearLayout optionsPage = new LinearLayout(context); optionsPage.Orientation = Orientation.Vertical; optionsPage.AddView(selectionMode); optionsPage.AddView(spinSelectionMode); optionsPage.AddView(selectionType); optionsPage.AddView(spinSelectionType); optionsPage.SetPadding(10, 10, 10, 10); optionsPage.SetBackgroundColor(Color.White); return optionsPage; } private void spinSelectionType_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter1[e.Position]; if (selectedItem.Equals("Child")) { chart.SelectionSettings.SelectionType = SelectionType.Child; } else if (selectedItem.Equals("Group")) { chart.SelectionSettings.SelectionType = SelectionType.Group; } else if (selectedItem.Equals("Parent")) { chart.SelectionSettings.SelectionType = SelectionType.Parent; } else if (selectedItem.Equals("Single")) { chart.SelectionSettings.SelectionType = SelectionType.Single; } } private void SpinMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter[e.Position]; if (selectedItem.Equals("Opacity")) { chart.SelectionSettings.SelectionDisplayMode = SelectionDisplayMode.HighlightByOpacity; } else if (selectedItem.Equals("Color")) { chart.SelectionSettings.SelectionDisplayMode = SelectionDisplayMode.HighlightByColor; } else if (selectedItem.Equals("Stroke")) { chart.SelectionSettings.SelectionDisplayMode = SelectionDisplayMode.HighlightByStroke; } } } }<file_sep>/iOS/SampleBrowser/Samples/NavigationDrawer/TableSource.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class TableSource : UITableViewSource { public bool customise; string[] TableItems; string[] ContentItems; string item2="test"; UILabel ll,ll1; string CellIdentifier = "TableCell"; public TableSource (string[] items) { TableItems = items; } public TableSource (string[] items,string[] contentitems) { TableItems = items; ContentItems = contentitems; } public override nint RowsInSection (UITableView tableview, nint section) { int i=TableItems.Length; return (nint)i; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { if (!customise) { NavigationDrawer.mainView.setvalue1 ((int)indexPath.Item); NavigationDrawer.sideMenuController.ToggleDrawer (); } } public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { if (customise) return 55; else return 40; } else return 40; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell (CellIdentifier); string item = TableItems[indexPath.Row]; if(ContentItems!=null) item2 = ContentItems[indexPath.Row]; if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, CellIdentifier); } if (customise) { UIView centerview = new UIView (); centerview.Frame = cell.Frame; centerview.BackgroundColor = UIColor.White; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { ll = new UILabel (new CGRect (100, 2, 100, 20)); ll1 = new UILabel (new CGRect (100, 20, 300, 30)); } else { ll = new UILabel (new CGRect (15, 2, 100, 20)); ll1 = new UILabel (new CGRect (15, 20, 300, 20)); } ll.Font= UIFont.FromName ("Helvetica", 15f); ll.Text = item; centerview.Add (ll); ll1.Text = item2; ll1.Lines = 0; ll1.Font= UIFont.FromName ("Helvetica", 13f); centerview.Add (ll1); cell.ContentView.Add (centerview); } else { cell.TextLabel.Text = item; } return cell; } } } <file_sep>/Forms/TreeView/TreeView/Samples/LoadOnDemand/ViewModel/MusicInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.TreeView.Engine; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public class MusicInfoRepository { private ObservableCollection<MusicInfo> menu; public ObservableCollection<MusicInfo> Menu { get { return menu; } set { menu = value; } } public ICommand TreeViewOnDemandCommand { get; set; } public MusicInfoRepository() { this.Menu = this.GetMenuItems(); TreeViewOnDemandCommand = new Command(ExecuteOnDemandLoading, CanExecuteOnDemandLoading); } private bool CanExecuteOnDemandLoading(object arg) { var haschildnodes = ((arg as TreeViewNode).Content as MusicInfo).HasChildNodes; if (haschildnodes) { if ((arg as TreeViewNode).ChildNodes.Count > 0) return false; else return true; } else return false; } private void ExecuteOnDemandLoading(object obj) { var node = obj as TreeViewNode; node.ShowExpanderAnimation = true; MusicInfo musicInfo = node.Content as MusicInfo; Device.BeginInvokeOnMainThread(async () => { await Task.Delay(2000); var items = GetSubMenu(musicInfo.ID); node.PopulateChildNodes(items); if (items.Count() > 0) node.IsExpanded = true; node.ShowExpanderAnimation = false; }); } private ObservableCollection<MusicInfo> GetMenuItems() { ObservableCollection<MusicInfo> menuItems = new ObservableCollection<MusicInfo>(); menuItems.Add(new MusicInfo() { ItemName = "Discover Music", HasChildNodes = true, ID = 1 }); menuItems.Add(new MusicInfo() { ItemName = "Sales and Events", HasChildNodes = true, ID = 2 }); menuItems.Add(new MusicInfo() { ItemName = "Categories", HasChildNodes = true, ID = 3 }); menuItems.Add(new MusicInfo() { ItemName = "MP3 Albums", HasChildNodes = true, ID = 4 }); menuItems.Add(new MusicInfo() { ItemName = "Fiction Book Lists", HasChildNodes = true, ID = 5 }); return menuItems; } public IEnumerable<MusicInfo> GetSubMenu(int iD) { ObservableCollection<MusicInfo> menuItems = new ObservableCollection<MusicInfo>(); if (iD == 1) { menuItems.Add(new MusicInfo() { ItemName = "Hot Singles", HasChildNodes = false, ID = 11 }); menuItems.Add(new MusicInfo() { ItemName = "Rising Artists", HasChildNodes = false, ID = 12 }); menuItems.Add(new MusicInfo() { ItemName = "Live Music", HasChildNodes = false, ID = 13 }); menuItems.Add(new MusicInfo() { ItemName = "More in Music", HasChildNodes = true, ID = 14 }); } else if (iD == 2) { menuItems.Add(new MusicInfo() { ItemName = "100 Albums - $10 Each", HasChildNodes = false, ID = 21 }); menuItems.Add(new MusicInfo() { ItemName = "Hip-Hop and R&B Sale", HasChildNodes = false, ID = 22 }); menuItems.Add(new MusicInfo() { ItemName = "CD Deals", HasChildNodes = false, ID = 23 }); } else if (iD == 3) { menuItems.Add(new MusicInfo() { ItemName = "Songs", HasChildNodes = false, ID = 31 }); menuItems.Add(new MusicInfo() { ItemName = "Bestselling Albums", HasChildNodes = false, ID = 32 }); menuItems.Add(new MusicInfo() { ItemName = "New Releases", HasChildNodes = false, ID = 33 }); menuItems.Add(new MusicInfo() { ItemName = "MP3 Albums", HasChildNodes = false, ID = 34 }); } else if (iD == 4) { menuItems.Add(new MusicInfo() { ItemName = "Rock Music", HasChildNodes = false, ID = 41 }); menuItems.Add(new MusicInfo() { ItemName = "Gospel", HasChildNodes = false, ID = 42 }); menuItems.Add(new MusicInfo() { ItemName = "Latin Music", HasChildNodes = false, ID = 43 }); menuItems.Add(new MusicInfo() { ItemName = "Jazz", HasChildNodes = false, ID = 44 }); } else if (iD == 5) { menuItems.Add(new MusicInfo() { ItemName = "Hunger Games", HasChildNodes = false, ID = 51 }); menuItems.Add(new MusicInfo() { ItemName = "Pride and Prejudice", HasChildNodes = false, ID = 52 }); menuItems.Add(new MusicInfo() { ItemName = "Harry Potter", HasChildNodes = false, ID = 53 }); menuItems.Add(new MusicInfo() { ItemName = "Game Of Thrones", HasChildNodes = false, ID = 54 }); } else if (iD == 14) { menuItems.Add(new MusicInfo() { ItemName = "Music Trade-In", HasChildNodes = false, ID = 141 }); menuItems.Add(new MusicInfo() { ItemName = "Redeem a Gift card", HasChildNodes = false, ID = 142 }); menuItems.Add(new MusicInfo() { ItemName = "Band T-Shirts", HasChildNodes = false, ID = 143 }); } return menuItems; } } } <file_sep>/Forms/Button/Button/Samples/GettingStartedSample/GettingStartedSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.Graphics; using Syncfusion.Buttons.XForms; using Xamarin.Forms; namespace SampleBrowser.SfButton { #region Getting Started Sample Class public partial class GettingStartedSample : SampleView { #region Constructor public GettingStartedSample() { InitializeComponent(); if (Device.RuntimePlatform == Device.WPF) { iconButtonLeft.ImageSource = "button_Heart.png"; iconButtonRight.ImageSource = "button_Heart.png"; SfLinearGradientBrush linearGradientBrush = new SfLinearGradientBrush(); linearGradientBrush.GradientStops = new Syncfusion.XForms.Graphics.GradientStopCollection() { new SfGradientStop(){ Color = Color.FromHex("#2F9BDF"), Offset = 0 }, new SfGradientStop(){ Color = Color.FromHex("#51F1F2"), Offset = 1 } }; gradientButton.FontSize = 14; gradientButton.BackgroundGradient = linearGradientBrush; SetDefaultSize(); } if (Device.RuntimePlatform == Device.UWP) { SetDefaultSize(); } } #endregion private void SetDefaultSize() { iconButton.HeightRequest = iconButton.WidthRequest = circleButton.HeightRequest = circleButton.WidthRequest = iconButtonLeft.HeightRequest = iconButtonRight.HeightRequest = 40; } private void GradientButton_Clicked(object sender, System.EventArgs e) { if (Device.RuntimePlatform == Device.WPF) { SfLinearGradientBrush linearGradientBrush = new SfLinearGradientBrush(); if (gradientButton.IsChecked == true) { linearGradientBrush.GradientStops = new Syncfusion.XForms.Graphics.GradientStopCollection() { new SfGradientStop(){ Color = Color.FromHex("#51F1F2"), Offset = 0 }, new SfGradientStop(){ Color = Color.FromHex("#2F9BDF"), Offset = 1 } }; } else { linearGradientBrush.GradientStops = new Syncfusion.XForms.Graphics.GradientStopCollection() { new SfGradientStop(){ Color = Color.FromHex("#2F9BDF"), Offset = 0 }, new SfGradientStop(){ Color = Color.FromHex("#51F1F2"), Offset = 1 } }; } gradientButton.BackgroundGradient = linearGradientBrush; } } } #endregion }<file_sep>/Forms/Presentation/Presentation/Samples/SlideTransition/SlideTransition.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using SampleBrowser.Core; namespace SampleBrowser.Presentation { public partial class SlideTransition : SampleView { public SlideTransition() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Transition.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Transition.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Create transition for the presentation slides. CreateTransition(presentation); //Save the Presentation to stream MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("SlideTransitionSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("SlideTransitionSample.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } #region Create Slide Transition private void CreateTransition(IPresentation presentation) { //Get the first slide from the presentation ISlide slide1 = presentation.Slides[0]; // Add the 'Wheel' transition effect to the first slide slide1.SlideTransition.TransitionEffect = TransitionEffect.Wheel; // Get the second slide from the presentation ISlide slide2 = presentation.Slides[1]; // Add the 'Checkerboard' transition effect to the second slide slide2.SlideTransition.TransitionEffect = TransitionEffect.Checkerboard; // Add the subtype to the transition effect slide2.SlideTransition.TransitionEffectOption = TransitionEffectOption.Across; // Apply the value to transition mouse on click parameter slide2.SlideTransition.TriggerOnClick = true; // Get the third slide from the presentation ISlide slide3 = presentation.Slides[2]; // Add the 'Orbit' transition effect for slide slide3.SlideTransition.TransitionEffect = TransitionEffect.Orbit; // Add the speed for transition slide3.SlideTransition.Speed = TransitionSpeed.Fast; // Get the fourth slide from the presentation ISlide slide4 = presentation.Slides[3]; // Add the 'Uncover' transition effect to the slide slide4.SlideTransition.TransitionEffect = TransitionEffect.Uncover; // Apply the value to advance on time for slide slide4.SlideTransition.TriggerOnTimeDelay = true; // Assign the advance on time value slide4.SlideTransition.TimeDelay = 5; // Get the fifth slide from the presentation ISlide slide5 = presentation.Slides[4]; // Add the 'PageCurlDouble' transition effect to the slide slide5.SlideTransition.TransitionEffect = TransitionEffect.PageCurlDouble; // Add the duration value for the transition effect slide5.SlideTransition.Duration = 5; } #endregion } } <file_sep>/Android/SampleBrowser/Samples/SfPicker/readme.md The `SfPicker` allows user to pick an item from a list of items that can be customized with custom view. The following sample is available for picker control to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](GettingStarted.cs)| It demonstrates the selection functionality on picker items.| <file_sep>/Android/SampleBrowser/Samples/Presentation/PPTXToImage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Xml; using Syncfusion.PresentationRenderer; using Android.Graphics; namespace SampleBrowser { public partial class PPTXToImage : SamplePage { private Context m_context; RadioGroup radioGroup; RadioButton pngButton; RadioButton jpegButton; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to convert the PowerPoint slide to an image."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; LinearLayout radioLinearLayout = new LinearLayout(con); radioLinearLayout.Orientation = Orientation.Horizontal; TextView imageType = new TextView(con); imageType.Text = "Image Format : "; imageType.TextSize = 19; radioLinearLayout.AddView(imageType); radioGroup = new RadioGroup(con); radioGroup.TextAlignment = TextAlignment.Center; radioGroup.Orientation = Orientation.Horizontal; pngButton = new RadioButton(con); pngButton.Text = "PNG"; radioGroup.AddView(pngButton); jpegButton = new RadioButton(con); jpegButton.Text = "JPEG"; radioGroup.AddView(jpegButton); radioGroup.Check(1); radioLinearLayout.AddView(radioGroup); linear.AddView(radioLinearLayout); pngButton.Checked = true; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button templateButton = new Button(con); templateButton.Text = "Input Template"; templateButton.Click += OnButtonClicked; linear.AddView(templateButton); Button convertButton = new Button(con); convertButton.Text = "Convert"; convertButton.Click += OnConvertButtonClicked; linear.AddView(convertButton); return linear; } private void OnConvertButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Template.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a existing PowerPoint presentation. IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Initialize PresentationRenderer to perform image conversion. presentation.PresentationRenderer = new PresentationRenderer(); //Set file content type string contentType; Syncfusion.Presentation.ExportImageFormat imageFormat; if (pngButton.Checked) { contentType = "image/png"; imageFormat = ExportImageFormat.Png; } else { contentType = "image/jpeg"; imageFormat = ExportImageFormat.Jpeg; } //Convert PowerPoint slide to image stream. Stream stream = presentation.Slides[0].ConvertToImage(imageFormat); //Reset the stream position stream.Position = 0; //Close the PowerPoint Presentation. presentation.Close(); //Save and view the generated file. SaveAndView(stream as MemoryStream, contentType, true); } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Template.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); fileStream.Dispose(); SaveAndView(stream, "application/powerpoint", false); } void SaveAndView(MemoryStream stream, string contentType, bool image) { if (stream != null) { stream.Position = 0; SaveAndroid androidSave = new SaveAndroid(); if (image) androidSave.Save("Image." + contentType.Split('/').ToArray()[1], contentType, stream, m_context); else androidSave.Save("InputTemplate.pptx", contentType, stream, m_context); } } } } <file_sep>/Forms/SunburstChart/SunburstChart/Samples/SunburstViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSunburstChart { [Preserve(AllMembers = true)] public class SunburstViewModel { public SunburstViewModel() { this.DataSource = new ObservableCollection<SunburstModel> { new SunburstModel { Country = "USA", JobDescription = "Sales", JobGroup="Executive", EmployeesCount = 50 }, new SunburstModel { Country = "USA", JobDescription = "Sales", JobGroup = "Analyst", EmployeesCount = 40 }, new SunburstModel { Country = "USA", JobDescription = "Marketing", EmployeesCount = 40 }, new SunburstModel { Country = "USA", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 35 }, new SunburstModel { Country = "USA", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 175 }, new SunburstModel { Country = "USA", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 70 }, new SunburstModel { Country = "USA", JobDescription = "Management", EmployeesCount = 40 }, new SunburstModel { Country = "USA", JobDescription = "Accounts", EmployeesCount = 60 }, new SunburstModel { Country = "India", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 33 }, new SunburstModel { Country = "India", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 125 }, new SunburstModel { Country = "India", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 60 }, new SunburstModel { Country = "India", JobDescription = "HR Executives", EmployeesCount = 70 }, new SunburstModel { Country = "India", JobDescription = "Accounts", EmployeesCount = 45 }, new SunburstModel { Country = "Germany", JobDescription = "Sales", JobGroup = "Executive", EmployeesCount = 30 }, new SunburstModel { Country = "Germany", JobDescription = "Sales", JobGroup = "Analyst", EmployeesCount = 40 }, new SunburstModel { Country = "Germany", JobDescription = "Marketing", EmployeesCount = 50 }, new SunburstModel { Country = "Germany", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 40 }, new SunburstModel { Country = "Germany", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 65 }, new SunburstModel { Country = "Germany", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 27 }, new SunburstModel { Country = "Germany", JobDescription = "Management", EmployeesCount = 33 }, new SunburstModel { Country = "Germany", JobDescription = "Accounts", EmployeesCount = 55 }, new SunburstModel { Country = "UK", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 25 }, new SunburstModel { Country = "UK", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 96 }, new SunburstModel { Country = "UK", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 55 }, new SunburstModel { Country = "UK", JobDescription = "HR Executives", EmployeesCount = 60 }, new SunburstModel { Country = "UK", JobDescription = "Accounts", EmployeesCount = 30 } }; this.Population_Data = new ObservableCollection<SunburstModel> { new SunburstModel { State = "Ontario", Continent = "North America", Country = "Canada", Population = 13210600 }, new SunburstModel { State = "New York", Continent = "North America", Country = "United States", Population = 19378102 }, new SunburstModel { State = "Pennsylvania", Continent = "North America", Country = "United States", Population = 12702379 }, new SunburstModel { State = "Ohio", Continent = "North America", Country = "United States", Population = 11536504 }, new SunburstModel { State = "Buenos Aires", Continent = "South America", Country = "Argentina", Population = 15594428 }, new SunburstModel { State = "Minas Gerais", Continent = "South America", Country = "Brazil", Population = 20593366 }, new SunburstModel { State = "Rio de Janeiro", Continent = "South America", Country = "Brazil", Population = 16369178 }, new SunburstModel { State = "Bahia", Continent = "South America", Country = "Brazil", Population = 15044127 }, new SunburstModel { State = "Rio Grande do Sul", Continent = "South America", Country = "Brazil", Population = 11164050 }, new SunburstModel { State = "Parana", Continent = "South America", Country = "Brazil", Population = 10997462 }, new SunburstModel { State = "Chittagong", Continent = "Asia", Country = "Bangladesh", Population = 28079000 }, new SunburstModel { State = "Rajshahi", Continent = "Asia", Country = "Bangladesh", Population = 18329000 }, new SunburstModel { State = "Khulna", Continent = "Asia", Country = "Bangladesh", Population = 15563000 }, new SunburstModel { State = "Liaoning", Continent = "Asia", Country = "China", Population = 43746323 }, new SunburstModel { State = "Shaanxi", Continent = "Asia", Country = "China", Population = 37327378 }, new SunburstModel { State = "Fujian", Continent = "Asia", Country = "China", Population = 36894216 }, new SunburstModel { State = "Shanxi", Continent = "Asia", Country = "China", Population = 35712111 }, new SunburstModel { State = "Kerala", Continent = "Asia", Country = "India", Population = 33387677 }, new SunburstModel { State = "Punjab", Continent = "Asia", Country = "India", Population = 27704236 }, new SunburstModel { State = "Haryana", Continent = "Asia", Country = "India", Population = 25353081 }, new SunburstModel { State = "Delhi", Continent = "Asia", Country = "India", Population = 16753235 }, new SunburstModel { State = "Jammu", Continent = "Asia", Country = "India", Population = 12548926 }, new SunburstModel { State = "West Java", Continent = "Asia", Country = "Indonesia", Population = 43021826 }, new SunburstModel { State = "East Java", Continent = "Asia", Country = "Indonesia", Population = 37476011 }, new SunburstModel { State = "Banten", Continent = "Asia", Country = "Indonesia", Population = 10644030 }, new SunburstModel { State = "Jakarta", Continent = "Asia", Country = "Indonesia", Population = 10187595 }, new SunburstModel { State = "Tianjin", Continent = "Africa", Country = "Ethiopia", Population = 24000200 }, new SunburstModel { State = "Tianjin", Continent = "Africa", Country = "Ethiopia", Population = 15042531 }, new SunburstModel { State = "Rift Valley", Continent = "Africa", Country = "Kenya", Population = 10006805 }, new SunburstModel { State = "Lagos", Continent = "Africa", Country = "Nigeria", Population = 10006805 }, new SunburstModel { State = "Kano", Continent = "Africa", Country = "Nigeria", Population = 10006805 }, new SunburstModel { State = "Gauteng", Continent = "Africa", Country = "South Africa", Population = 12728400 }, new SunburstModel { State = "KwaZulu-Natal", Continent = "Africa", Country = "South Africa", Population = 10456900 }, new SunburstModel { State = "Ile-de- France", Continent = "Europe", Country = "France", Population = 11694000 }, new SunburstModel { State = "North Rhine-Westphalia", Continent = "Europe", Country = "Germany", Population = 17872863 }, new SunburstModel { State = "Bavaria", Continent = "Europe", Country = "Germany", Population = 12510331 }, new SunburstModel { State = "NBaden-Wurttemberg", Continent = "Europe", Country = "Germany", Population = 10747479 }, new SunburstModel { State = "England", Continent = "Europe", Country = "United Kingdom", Population = 51446600 } }; Data = new ObservableCollection<SunburstModel>(); Data.Add(new SunburstModel() { Quarter = "Q1", Month = "Jan", Sales = 11 }); Data.Add(new SunburstModel() { Quarter = "Q1", Month = "Feb", Sales = 8 }); Data.Add(new SunburstModel() { Quarter = "Q1", Month = "Mar", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q2", Month = "Apr", Sales = 13 }); Data.Add(new SunburstModel() { Quarter = "Q2", Month = "May", Sales = 12 }); Data.Add(new SunburstModel() { Quarter = "Q2", Month = "Jun", Sales = 17 }); Data.Add(new SunburstModel() { Quarter = "Q3", Month = "Jul", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q3", Month = "Aug", Sales = 4 }); Data.Add(new SunburstModel() { Quarter = "Q3", Month = "Sep", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Oct", Sales = 7 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Nov", Sales = 18 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W1", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W2", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W3", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W4", Sales = 5 }); } public ObservableCollection<SunburstModel> DataSource { get; set; } public ObservableCollection<SunburstModel> Data { get; set; } public ObservableCollection<SunburstModel> Population_Data { get; set; } } } <file_sep>/Forms/MaskedEdit/MaskedEdit/Samples/MaskedEdit/MaskedEdit.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfMaskedEdit { public partial class MaskedEdit : SampleView { public MaskedEdit() { InitializeComponent(); if (Device.Idiom == TargetIdiom.Phone || Device.RuntimePlatform == Device.UWP) { MaskedEdit_Default maskedEdit = new MaskedEdit_Default(); this.Content = maskedEdit.getContent(); this.PropertyView = maskedEdit.getPropertyView(); } else if (Device.Idiom == TargetIdiom.Tablet) { MaskedEdit_Tablet maskedEdit = new MaskedEdit_Tablet(); this.Content = maskedEdit.getContent(); this.PropertyView = maskedEdit.getPropertyView(); } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/PDFViewer/FillAndSign.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Reflection; using CoreGraphics; using Syncfusion.SfPdfViewer.iOS; using UIKit; using System.Timers; using System.IO; using System.Diagnostics; using System.Collections.Generic; using Foundation; namespace SampleBrowser { class FillAndSign : SampleView { private SfPdfViewer pdfViewerControl; private UIView parentView; public FillAndSign() { parentView = new UIView(this.Frame); } public override void LayoutSubviews() { base.LayoutSubviews(); parentView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); pdfViewerControl = new SfPdfViewer(); parentView.AddSubview(pdfViewerControl); AddSubview(parentView); var fileStream = typeof(FillAndSign).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDFViewer.Assets.FormFillingDocument.pdf"); pdfViewerControl.LoadDocument(fileStream); pdfViewerControl.DocumentSaveInitiated += PdfViewerControl_DocumentSaveInitiated; } private void PdfViewerControl_DocumentSaveInitiated(object sender, DocumentSaveInitiatedEventArgs args) { Stream stream = args.SaveStream as MemoryStream; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filepath = Path.Combine(path, "savedDocument.pdf"); FileStream outputFillStream = File.Open(filepath, FileMode.Create); stream.Position = 0; stream.CopyTo(outputFillStream); outputFillStream.Close(); UIAlertView alertview = new UIAlertView(); alertview.Frame = new CGRect(20, 100, 200, 200); alertview.Message = filepath; alertview.Title = "The modified document is saved in the below location."; alertview.AddButton("Ok"); alertview.Show(); } } } <file_sep>/Forms/PdfViewer/PdfViewer.Droid/Renderer/AlertViewAndroid.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Xamarin.Forms; [assembly: Dependency(typeof(SampleBrowser.SfPdfViewer.Droid.AlertViewAndroid))] namespace SampleBrowser.SfPdfViewer.Droid { public class AlertViewAndroid : IAlertView { public void Show(string message) { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("", message, "OK"); } } } <file_sep>/iOS/SampleBrowser/Samples/Chart/AutoScrolling.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using CoreAnimation; #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using CoreGraphics; using Foundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.CoreGraphics; using MonoTouch.UIKit; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif using System.Threading.Tasks; namespace SampleBrowser { public class AutoScrolling : SampleView { SFChart chart; UILabel label; NSNumber value; Random random; bool isDispose = false; ChartViewModel dataModel; public AutoScrolling () { chart = new SFChart (); SFNumericalAxis primaryAxis = new SFNumericalAxis (); primaryAxis.AutoScrollingDelta = 10; chart.PrimaryAxis = primaryAxis; SFNumericalAxis secondaryAxis = new SFNumericalAxis (); secondaryAxis.Minimum = NSObject.FromObject(0); secondaryAxis.Maximum = NSObject.FromObject(9); chart.SecondaryAxis = secondaryAxis; dataModel = new ChartViewModel(); SFColumnSeries series = new SFColumnSeries(); series.ColorModel.Palette = SFChartColorPalette.Natural; series.ItemsSource = dataModel.data; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; chart.Series.Add(series); label = new UILabel (); label.Text = "In this demo, a data point is being added for every 500 milliseconds. The Chart is then automatically scrolled to display the fixed range of data points at the end. You can also pan to view previous data points. In this sample the delta value is 10"; label.Font = UIFont.FromName("Helvetica", 12f); label.TextAlignment = UITextAlignment.Center; label.LineBreakMode = UILineBreakMode.WordWrap; label.Lines = 6; label.BackgroundColor = UIColor.FromRGB (249, 249, 249); label.TextColor = UIColor.FromRGB (79, 86, 91); chart.AddChartBehavior (new SFChartZoomPanBehavior()); this.AddSubview (chart); CALayer topLine = new CALayer (); topLine.Frame = new CGRect (0, 0, UIScreen.MainScreen.ApplicationFrame.Width , 0.5); topLine.BackgroundColor = UIColor.FromRGB (178, 178, 178).CGColor; label.Layer.AddSublayer (topLine); this.AddSubview (label); random = new Random (); UpdateData (); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { if (view == chart) chart.Frame = new CGRect (0, 0, Frame.Width, Frame.Height - 72); else if (view == label) label.Frame = new CGRect (0, Frame.Height-74, Frame.Width, 80); } base.LayoutSubviews (); } async void UpdateData() { await Task.Delay(500); if (!isDispose) { AddDataPoint (); UpdateData (); } } private void AddDataPoint() { if (chart != null) { value = new NSNumber(random.Next(0,9)) ; dataModel.data.Add (new ChartDataModel(dataModel.wave1, (double)value)); chart.InsertDataPointAtIndex ((int)dataModel.data.Count - 1, 0); dataModel.wave1++; } } protected override void Dispose (bool disposing) { isDispose = true; base.Dispose (disposing); } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/Styles/Purple.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfDataGrid; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UIKit; namespace SampleBrowser { public class Purple:DataGridStyle { public Purple() { } public override UIColor GetHeaderBackgroundColor() { return UIColor.FromRGB(131, 83, 139); } public override UIColor GetHeaderForegroundColor() { return UIColor.FromRGB(255, 255, 255); } public override UIColor GetAlternatingRowBackgroundColor() { return UIColor.FromRGB(237, 231, 246); } public override UIColor GetSelectionBackgroundColor() { return UIColor.FromRGB(149, 117, 205); } public override UIColor GetSelectionForegroundColor() { return UIColor.FromRGB(255, 255, 255); } public override UIColor GetCaptionSummaryRowBackgroundColor() { return UIColor.FromRGB(224, 224, 224); } public override UIColor GetCaptionSummaryRowForegroundColor() { return UIColor.FromRGB(51, 51, 51); } public override UIColor GetBorderColor() { return UIColor.FromRGB(180, 180, 180); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/LinearGauge/Default.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif using Syncfusion.SfGauge.iOS; namespace SampleBrowser { public class Default : SampleView { SFLinearGauge linearGauge; static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } #region View lifecycle public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; linearGauge.Frame = new CGRect(0, 30, this.Frame.Size.Width, this.Frame.Size.Height - 30); } base.LayoutSubviews(); } public Default() { //LinearGauge this.BackgroundColor = UIColor.White; linearGauge = new SFLinearGauge(); linearGauge.BackgroundColor = UIColor.White; linearGauge.Header = new SFLinearLabel(); SFLinearScale scale = new SFLinearScale(); scale.Minimum = 0; scale.Maximum = 100; scale.Interval = 10; scale.ScaleBarSize = 2; scale.OpposedPosition = true; scale.LabelColor = UIColor.FromRGB(66, 66, 66); scale.LabelFont = UIFont.FromName("Helvetica", 14f); scale.MinorTicksPerInterval = 4; scale.ScaleBarColor = UIColor.FromRGB(158, 158, 158); SFLinearTickSettings major = new SFLinearTickSettings(); major.Thickness = 1.5f; major.Length = 30; major.Color = UIColor.FromRGB(158, 158, 158); scale.MajorTickSettings = major; SFLinearTickSettings minor = new SFLinearTickSettings(); minor.Thickness = 0.9f; minor.Color = UIColor.FromRGB(158, 158, 158); minor.Length = 15; scale.MinorTickSettings = minor; SFSymbolPointer pointer = new SFSymbolPointer(); pointer.SymbolPosition = SymbolPointerPosition.Away; pointer.Thickness = 12; pointer.Value = 10; pointer.Color = UIColor.FromRGB(158, 158, 158); pointer.MarkerShape = MarkerShape.Triangle; scale.Pointers.Add(pointer); linearGauge.Scales.Add(scale); this.AddSubview(linearGauge); } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/CircularGauge/GaugeCustomization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfGauge.iOS; using System.Collections.ObjectModel; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using System.Drawing; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class GaugeCustomization : SampleView { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } SFCircularGauge gauge1; SFCircularGauge gauge2; UISlider slider; UIView option = new UIView(); SFRangePointer pointer1; SFNeedlePointer pointer2; SFRangePointer pointer3; UIPickerView rangePointerColor; UIPickerView needlePointerColor; UIPickerView rangeColor; SFCircularRange range; SFCircularRange range1; public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; gauge1.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height / 2); gauge2.Frame = new CGRect(0, this.Frame.Height / 2 , this.Frame.Width, this.Frame.Height / 2); } base.LayoutSubviews(); } public GaugeCustomization() { gauge1 = new SFCircularGauge(); rangePointerColor = new UIPickerView(); needlePointerColor = new UIPickerView(); rangeColor = new UIPickerView(); SFGaugeHeader header1 = new SFGaugeHeader(); header1.Position = new CGPoint(0.5, 0.06); header1.Text = (Foundation.NSString)"800 GB"; header1.TextColor = UIColor.Black; header1.TextStyle = UIFont.SystemFontOfSize(20); gauge1.Headers.Add(header1); SFCircularScale scale1 = new SFCircularScale(); scale1.StartAngle = 110; scale1.SweepAngle = 250; scale1.StartValue = 0; scale1.EndValue = 1000; scale1.Interval = 500; scale1.ShowLabels = false; scale1.ShowTicks = false; scale1.ShowRim = false; scale1.MinorTicksPerInterval = 0; pointer1 = new SFRangePointer(); pointer1.Value = 800; pointer1.KnobRadius = 0; pointer1.EnableAnimation = false; pointer1.Color = UIColor.FromRGB(255, 221, 0); pointer1.KnobColor = UIColor.FromRGB(255, 221, 0); pointer1.Width = 20; pointer1.Offset = 0.7f; scale1.Pointers.Add(pointer1); pointer2 = new SFNeedlePointer(); pointer2.Value = 800; pointer2.Color = UIColor.FromRGB(66, 66, 66); pointer2.PointerType = SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle; pointer2.LengthFactor = 0.7f; pointer2.Width = 5f; pointer2.KnobRadiusFactor = 0.1f; pointer2.KnobColor = UIColor.FromRGB(66, 66, 66); scale1.Pointers.Add(pointer2); range = new SFCircularRange(); range.StartValue = 0; range.EndValue = 1000; range.Offset = 0.7f; range.Width = 20; range.Color = UIColor.FromRGB(224, 224, 224); scale1.Ranges.Add(range); gauge1.Scales.Add(scale1); gauge2 = new SFCircularGauge(); SFGaugeHeader header2 = new SFGaugeHeader(); header2.Position = new CGPoint(0.5, 0.5); header2.Text = (Foundation.NSString)"800 GB"; header2.TextColor = UIColor.Black; header2.TextStyle = UIFont.SystemFontOfSize(20); SFGaugeHeader header3 = new SFGaugeHeader(); header3.Position = new CGPoint(0.5, 0.6); header3.Text = (Foundation.NSString)"Used"; header3.TextColor = UIColor.Gray; header3.TextStyle = UIFont.SystemFontOfSize(18); gauge2.Headers.Add(header2); gauge2.Headers.Add(header3); SFCircularScale scale2 = new SFCircularScale(); scale2.StartAngle = -180; scale2.SweepAngle = 180; scale2.StartValue = 0; scale2.EndValue = 1000; scale2.Interval = 500; scale2.ShowLabels = false; scale2.ShowTicks = false; scale2.ShowRim = false; scale2.MinorTicksPerInterval = 0; pointer3 = new SFRangePointer(); pointer3.Value = 800; pointer3.EnableAnimation = false; pointer3.Color = UIColor.FromRGB(255, 221, 0); pointer3.Width = 20; pointer3.Offset = 0.8f; scale2.Pointers.Add(pointer3); range1 = new SFCircularRange(); range1.StartValue = 0; range1.EndValue = 1000; range1.Offset = 0.8f; range1.Width = 20; range1.Color = UIColor.FromRGB(224, 224, 224); scale2.Ranges.Add(range1); gauge2.Scales.Add(scale2); this.AddSubview(gauge1); this.AddSubview(gauge2); CreateOptionView(); this.OptionView = option; } private void CreateOptionView() { UILabel text = new UILabel(); text.Text = "Change Pointer Value"; text.TextAlignment = UITextAlignment.Left; text.TextColor = UIColor.Black; text.Frame = new CGRect(10, 10, 320, 20); text.Font = UIFont.FromName("Helvetica", 14f); slider = new UISlider(); slider.Frame = new CGRect(5, 40, 320, 20); slider.MinValue = 0f; slider.MaxValue = 1000f; slider.Value = 60f; slider.ValueChanged += (object sender, EventArgs e) => { pointer1.Value = slider.Value; pointer2.Value = slider.Value; pointer3.Value = slider.Value; }; UILabel text1 = new UILabel(); text1.Text = "RangePointer Color"; text1.TextAlignment = UITextAlignment.Left; text1.TextColor = UIColor.Black; text1.Frame = new CGRect(10, 70, 320, 20); text1.Font = UIFont.FromName("Helvetica", 14f); List<string> position = new List<string> { "Yellow", "Green", "Purple" }; var picker = new OpposedPickerModel(position); rangePointerColor.Model = picker; rangePointerColor.SelectedRowInComponent(0); rangePointerColor.Frame = new CGRect(10, 100, 200, 40); picker.ValueChanged += (sender, e) => { if (picker.SelectedValue == "Yellow") { pointer1.Color = UIColor.Yellow; pointer3.Color = UIColor.Yellow; } else if (picker.SelectedValue == "Green") { pointer1.Color = UIColor.Green; pointer3.Color = UIColor.Green; } else if (picker.SelectedValue == "Purple") { pointer1.Color = UIColor.Purple; pointer3.Color = UIColor.Purple; } }; UILabel text2 = new UILabel(); text2.Text = "NeedlePointer Color"; text2.TextAlignment = UITextAlignment.Left; text2.TextColor = UIColor.Black; text2.Frame = new CGRect(10, 150, 320, 20); text2.Font = UIFont.FromName("Helvetica", 14f); List<string> position1 = new List<string> { "Gray", "Red", "Brown" }; var picker1 = new RangePickerModel(position1); needlePointerColor.Model = picker1; needlePointerColor.Frame = new CGRect(10, 170, 200, 40); picker1.ValueChanged += (sender, e) => { if (picker1.SelectedValue == "Gray") { pointer2.Color = UIColor.Gray; } else if (picker1.SelectedValue == "Red") { pointer2.Color = UIColor.Red; } else if (picker1.SelectedValue == "Brown") { pointer2.Color = UIColor.Brown; } }; UILabel text3 = new UILabel(); text3.Text = "Range Color"; text3.TextAlignment = UITextAlignment.Left; text3.TextColor = UIColor.Black; text3.Frame = new CGRect(10, 220, 320, 20); text3.Font = UIFont.FromName("Helvetica", 14f); List<string> position2 = new List<string> { "Light Gray", "Blue", "Orange" }; var picker2 = new MarkerPickerModel(position2); rangeColor.Model = picker2; rangeColor.SelectedRowInComponent(0); rangeColor.Frame = new CGRect(10, 250, 250, 40); picker2.ValueChanged += (sender, e) => { if (picker2.SelectedValue == "Light Gray") { range.Color = UIColor.LightGray; range1.Color = UIColor.LightGray; } else if (picker2.SelectedValue == "Blue") { range.Color = UIColor.Blue; range1.Color = UIColor.Blue; } else if (picker2.SelectedValue == "Orange") { range.Color = UIColor.Orange; range1.Color = UIColor.Orange; } }; this.option.AddSubview(text); this.option.AddSubview(slider); this.option.AddSubview(text1); this.option.AddSubview(rangePointerColor); this.option.AddSubview(text2); this.option.AddSubview(needlePointerColor); this.option.AddSubview(text3); this.option.AddSubview(rangeColor); } public class OpposedPickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public OpposedPickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; ; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); } } public class RangePickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public RangePickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; ; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); } } public class MarkerPickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public MarkerPickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; ; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); } } protected override void Dispose(bool disposing) { //gauge1.Scales[0].Pointers.Clear(); //gauge1.Scales.Clear(); //gauge1.Dispose(); //gauge2.Scales[0].Pointers.Clear(); //gauge2.Scales.Clear(); //gauge2.Dispose(); base.Dispose(disposing); } } } <file_sep>/iOS/SampleBrowser/ViewController.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; namespace SampleBrowser { public partial class ViewController : UINavigationController { protected ViewController(IntPtr handle) : base(handle) { // Note: this .ctor should not contain any initialization logic. } UIView header; public ViewController() { Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(""); this.SetNavigationBarHidden(true, false); this.View.BackgroundColor = UIColor.White; header = new UIView(); header.BackgroundColor = UIColor.Blue; header.Frame = new CoreGraphics.CGRect(0, 0, this.View.Frame.Size.Width, this.View.Frame.Size.Height / 2.5); this.View.AddSubview(header); } public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); header.Frame = new CoreGraphics.CGRect(0, 0, this.View.Frame.Size.Width, this.View.Frame.Size.Height / 2.5); } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); // Release any cached data, images, etc that aren't in use. } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/TableSummaryRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "TableSummaryRenderer.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; /// <summary> /// Creates TableSummary cells with desired properties /// </summary> public class TableSummaryRenderer : GridTableSummaryCellRenderer { /// <summary> /// Initializes a new instance of the TableSummaryRenderer class. /// </summary> public TableSummaryRenderer() { } /// <summary> /// Override method to get a custom Display View as Label /// </summary> /// <param name="dataColumn">DataColumnBase type of dataColumn parameter</param> /// <param name="view">view is Label type parameter</param> public override void OnInitializeDisplayView(DataColumnBase dataColumn, SfLabel view) { base.OnInitializeDisplayView(dataColumn, view); if (view != null) { view.FontFamily = dataColumn.GridColumn.RecordFont; view.FontAttributes = Xamarin.Forms.FontAttributes.Bold; if (Device.RuntimePlatform == Device.WPF) { view.FontSize = 13; } else { view.FontSize = 16; } } } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/SwipeDelete.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Graphics; using Android.Util; using Android.Widget; using Syncfusion.SfDataGrid; using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; namespace SampleBrowser { public class SwipeDelete : SamplePage { SfDataGrid sfGrid; SwipingViewModel viewModel; SwipeView swipe; LinearLayout linear; public bool IsUndoClicked { get; set; } private int swipedRowindex; private bool isSuspend; public override Android.Views.View GetSampleContent(Android.Content.Context context) { FrameLayout frame = new FrameLayout(context); linear = new LinearLayout(context); linear.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); linear.Orientation = Orientation.Horizontal; TextView swipeViewUndo = new TextView(context); swipeViewUndo.Text = "UNDO"; swipeViewUndo.SetTypeface(swipeViewUndo.Typeface, TypefaceStyle.Bold); swipeViewUndo.Gravity = GravityFlags.Center; swipeViewUndo.SetTextColor(Color.White); swipeViewUndo.SetBackgroundColor(Color.ParseColor("#1AAA87")); swipeViewUndo.Click += swipeViewUndo_Click; TextView swipeViewText = new TextView(context); swipeViewText.SetPadding((int)(25 * context.Resources.DisplayMetrics.Density), 0, 0, 0); swipeViewText.Text = "Deleted"; swipeViewText.Gravity = GravityFlags.CenterVertical | GravityFlags.Left; swipeViewText.SetTextColor(Color.White); swipeViewText.SetBackgroundColor(Color.ParseColor("#1AAA87")); linear.SetBackgroundColor(Color.ParseColor("#1AAA87")); viewModel = new SwipingViewModel(); viewModel.SetRowstoGenerate(100); sfGrid = new SfDataGrid(context); sfGrid.AutoGenerateColumns = false; sfGrid.ItemsSource = (viewModel.OrdersInfo); sfGrid.AllowSwiping = true; sfGrid.ColumnSizer = ColumnSizer.Star; DisplayMetrics metrics = context.Resources.DisplayMetrics; int width = metrics.WidthPixels; sfGrid.MaxSwipeOffset = width; swipe = new SwipeView(context); var undoWidth = (int)(100 * context.Resources.DisplayMetrics.Density); linear.AddView(swipeViewText, (sfGrid.MaxSwipeOffset - undoWidth), (int)sfGrid.RowHeight); linear.AddView(swipeViewUndo, undoWidth, (int)sfGrid.RowHeight); swipe.SetBackgroundColor(Color.ParseColor("#1AAA87")); swipe.AddView(linear); sfGrid.LeftSwipeView = swipe; sfGrid.RightSwipeView = swipe; sfGrid.SwipeEnded += sfGrid_SwipeEnded; sfGrid.SwipeStarted += sfGrid_SwipeStarted; GridTextColumn CustomerID = new GridTextColumn(); CustomerID.MappingName = "CustomerID"; CustomerID.HeaderText = "Customer ID"; GridTextColumn OrderID = new GridTextColumn(); OrderID.MappingName = "OrderID"; OrderID.HeaderText = "Order ID"; GridTextColumn EmployeeID = new GridTextColumn(); EmployeeID.MappingName = "EmployeeID"; EmployeeID.HeaderText = "Employee ID"; GridTextColumn Name = new GridTextColumn(); Name.MappingName = "FirstName"; Name.HeaderText = "Name"; sfGrid.Columns.Add(OrderID); sfGrid.Columns.Add(CustomerID); sfGrid.Columns.Add(EmployeeID); sfGrid.Columns.Add(Name); frame.AddView(sfGrid); return frame; } void swipeViewUndo_Click(object sender, EventArgs e) { var removedData = viewModel.OrdersInfo[swipedRowindex - 1]; var isSelected = sfGrid.SelectedItems.Contains(removedData); viewModel.OrdersInfo.Remove(removedData); viewModel.OrdersInfo.Insert(swipedRowindex - 1, removedData); if (isSelected) sfGrid.SelectedItems.Add(removedData); IsUndoClicked = true; } void sfGrid_SwipeStarted(object sender, SwipeStartedEventArgs e) { if (isSuspend) e.Cancel = true; } private async void sfGrid_SwipeEnded(object sender, SwipeEndedEventArgs e) { isSuspend = true; swipedRowindex = e.RowIndex; if (Math.Abs(e.SwipeOffset) >= sfGrid.MaxSwipeOffset / 2) { await Task.Delay(2000); if (!IsUndoClicked) viewModel.OrdersInfo.RemoveAt(swipedRowindex - 1); else { var removedData = viewModel.OrdersInfo[swipedRowindex - 1]; var isSelected = sfGrid.SelectedItems.Contains(removedData); viewModel.OrdersInfo.Remove(removedData); viewModel.OrdersInfo.Insert(swipedRowindex - 1, removedData); if (isSelected) sfGrid.SelectedItems.Add(removedData); IsUndoClicked = false; } isSuspend = false; } else isSuspend = false; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/MultipleAxis.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class MultipleAxes : SampleView { public MultipleAxes () { SFChart chart = new SFChart (); SFCategoryAxis primaryAxis = new SFCategoryAxis (); primaryAxis.LabelPlacement = SFChartLabelPlacement.BetweenTicks; primaryAxis.Title.Text = new NSString("Years"); chart.PrimaryAxis = primaryAxis; chart.SecondaryAxis = new SFNumericalAxis (){ ShowMajorGridLines = false }; chart.SecondaryAxis.Title.Text = new NSString ("Revenue (in millions)"); NSNumberFormatter formatter = new NSNumberFormatter (); formatter.PositiveFormat = "$"; chart.SecondaryAxis.LabelStyle.LabelFormatter = formatter; chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.ItemMargin = new UIEdgeInsets (0, 0, 50, 20); MultipleAxisDataSource dataModel = new MultipleAxisDataSource (); chart.DataSource = dataModel as SFChartDataSource; this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } } public class MultipleAxisDataSource : SFChartDataSource { NSMutableArray DataPoints; NSMutableArray DataPoints1; public MultipleAxisDataSource () { DataPoints = new NSMutableArray (); DataPoints1 = new NSMutableArray (); AddDataPointsForChart("2010", 20,6); AddDataPointsForChart("2011", 21,15); AddDataPointsForChart("2012", 22.5,35); AddDataPointsForChart("2013", 26,65); AddDataPointsForChart("2014", 27,75); } void AddDataPointsForChart (String XValue, Double YValue, Double YValue1) { DataPoints.Add (new SFChartDataPoint (NSObject.FromObject (XValue), NSObject.FromObject(YValue))); DataPoints1.Add (new SFChartDataPoint (NSObject.FromObject (XValue), NSObject.FromObject(YValue1))); } public override nint NumberOfSeriesInChart (SFChart chart) { return 2; } public override SFSeries GetSeries (SFChart chart, nint index) { if (index == 0) { SFColumnSeries series = new SFColumnSeries (); series.EnableTooltip = true; series.Label = new NSString("Revenue"); series.EnableAnimation = true; return series; } else { SFLineSeries series = new SFLineSeries (); series.EnableTooltip = true; series.LineWidth = 5; series.Label = new NSString("Customers"); series.YAxis = new SFNumericalAxis (){ OpposedPosition = true, Minimum = NSObject.FromObject(0), Maximum = NSObject.FromObject(80), Interval = NSObject.FromObject(5), ShowMajorGridLines = false }; series.DataMarker.ShowLabel = true; series.YAxis.Title.Text = new NSString ("Number of Customers"); series.EnableAnimation = true; return series; } } public override SFChartDataPoint GetDataPoint (SFChart chart, nint index, nint seriesIndex) { if (seriesIndex == 0) return DataPoints.GetItem<SFChartDataPoint> ((nuint)index); else return DataPoints1.GetItem<SFChartDataPoint> ((nuint)index); } public override nint GetNumberOfDataPoints (SFChart chart, nint index) { if(index == 0) return (int)DataPoints.Count; else return (int)DataPoints1.Count; } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Model/BankInfo.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; using Android.Graphics; namespace SampleBrowser { public class BankInfo:INotifyPropertyChanged { public BankInfo () { } #region private variables private int branchNo; private int customerID; private string customerName; private int savings; private int currentbalance; private int balanceScale; private bool isOpen; private Bitmap customerImage; #endregion #region Public Properties public int CustomerID { get { return customerID; } set { this.customerID = value; RaisePropertyChanged ("CustomerID"); } } public int BranchNo { get { return branchNo; } set { this.branchNo = value; RaisePropertyChanged ("BranchNo"); } } public string CustomerName { get { return this.customerName; } set { this.customerName = value; RaisePropertyChanged ("CustomerName"); } } public int Savings { get { return savings; } set { this.savings = value; RaisePropertyChanged ("Savings"); } } public int Current { get { return currentbalance; } set { this.currentbalance = value; RaisePropertyChanged ("CurrentBalance"); } } public int BalanceScale { get { return this.balanceScale; } set { this.balanceScale = value; RaisePropertyChanged ("BalanceScale"); } } public bool IsOpen { get { return this.isOpen; } set { this.isOpen = value; RaisePropertyChanged ("IsOpen"); } } public Bitmap CustomerImage { get { return this.customerImage; } set { this.customerImage = value; RaisePropertyChanged ("CustomerImage"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged (String name) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (name)); } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/AutoScrolling/AutoScrolling.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class AutoScrolling : SampleView { AutoScrollingViewModel viewModel; public AutoScrolling() { InitializeComponent(); viewModel = Chart.BindingContext as AutoScrollingViewModel; viewModel.LoadData(); if (Device.RuntimePlatform == Device.macOS || Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { duplicateAxis.IsVisible = true; if (Device.RuntimePlatform == Device.WPF) { label.FontSize = 15; } } } public override void OnAppearing() { viewModel.IsDisappear = false; Device.StartTimer(new TimeSpan(0, 0, 0, 0, 500), viewModel.UpdateData); base.OnAppearing(); } public override void OnDisappearing() { viewModel.IsDisappear = true; base.OnDisappearing(); } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if ((Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS)) { if (height > 0 && width > 0) { if (height > width) { layout.Padding = new Thickness(10); stack.Padding = new Thickness(5); duplicateAxis.IsVisible = false; } else { stack.Padding = new Thickness(5); layout.Padding = new Thickness(10); duplicateAxis.IsVisible = true; } } } } } } <file_sep>/Forms/Chart/Chart/Samples/MultipleAxes/MultipleAxesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class MultipleAxesViewModel { public ObservableCollection<ChartDataModel> ColumnData { get; set; } public ObservableCollection<ChartDataModel> LineData { get; set; } public MultipleAxesViewModel() { ColumnData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 35 ), new ChartDataModel("Mon", 40 ), new ChartDataModel("Tue", 80 ), new ChartDataModel("Wed", 70 ), new ChartDataModel("Thu", 65 ), new ChartDataModel("Fri", 55 ), new ChartDataModel("Sat", 50 ) }; LineData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 30 ), new ChartDataModel("Mon", 28 ), new ChartDataModel("Tue", 29 ), new ChartDataModel("Wed", 30 ), new ChartDataModel("Thu", 33 ), new ChartDataModel("Fri", 32 ), new ChartDataModel("Sat", 34 ) }; } } }<file_sep>/Forms/Chart/Chart/Samples/DateTimeAxis/DateTimeAxis.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using Xamarin.Forms; using Syncfusion.SfChart.XForms; namespace SampleBrowser.SfChart { public partial class DateTimeAxis : SampleView { int month = int.MaxValue; public DateTimeAxis() { InitializeComponent(); Chart.Scroll += (sender, e) => { month = int.MaxValue; }; Chart.ZoomEnd += (sender, e) => { month = int.MaxValue; }; Chart.ZoomDelta += (sender, e) => { month = int.MaxValue; }; Chart.ZoomStart += (sender, e) => { month = int.MaxValue; }; Chart.PrimaryAxis.LabelCreated += Primary_LabelCreated; if (Device.RuntimePlatform == Device.WPF) { Chart.ChartPadding = new Thickness(0, 0, 0, 10); } } private void Primary_LabelCreated(object sender, ChartAxisLabelEventArgs e) { DateTime baseDate = new DateTime(1899, 12, 30); var date = baseDate.AddDays(e.Position); if (date.Month != month) { ChartAxisLabelStyle labelStyle = new ChartAxisLabelStyle(); labelStyle.LabelFormat = "MMM-dd"; labelStyle.FontSize = 9; labelStyle.FontAttributes = FontAttributes.Bold; e.LabelStyle = labelStyle; month = date.Month; } else { ChartAxisLabelStyle labelStyle = new ChartAxisLabelStyle(); labelStyle.LabelFormat = "dd"; e.LabelStyle = labelStyle; if (Device.RuntimePlatform == Device.WPF) { labelStyle.FontSize = 12; } } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); month = int.MaxValue; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/GroupingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; namespace SampleBrowser { public class GroupingViewModel : NotificationObject { public GroupingViewModel() { ProductInfoRespository products = new ProductInfoRespository(); ProductDetails = products.GetProductDetails(100); } private List<ProductInfo> productDetails; /// <summary> /// Gets or sets the product details. /// </summary> /// <value>The product details.</value> public List<ProductInfo> ProductDetails { get { return productDetails; } set { productDetails = value; RaisePropertyChanged("ProductDetails"); } } } } <file_sep>/Forms/Presentation/Presentation/Samples/OLEObject/OLEObject.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using SampleBrowser.Core; namespace SampleBrowser.Presentation { public partial class OLEObject : SampleView { public OLEObject() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.btnExtractOle.HorizontalOptions = LayoutOptions.Start; this.btnExtractOle.VerticalOptions = LayoutOptions.Center; this.btnExtractOle.BackgroundColor = Color.Gray; this.btnInsertOle.HorizontalOptions = LayoutOptions.Start; this.btnInsertOle.VerticalOptions = LayoutOptions.Center; this.btnInsertOle.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.btnExtractOle.VerticalOptions = LayoutOptions.Center; this.btnInsertOle.VerticalOptions = LayoutOptions.Center; } } void OnInsertOleButtonClicked(object sender, EventArgs e) { Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; //New Instance of PowerPoint is Created.[Equivalent to launching MS PowerPoint with no slides]. IPresentation presentation = Syncfusion.Presentation.Presentation.Create(); ISlide slide = presentation.Slides.Add(SlideLayoutType.TitleOnly); IShape titleShape = slide.Shapes[0] as IShape; titleShape.Left = 0.65 * 72; titleShape.Top = 0.24 * 72; titleShape.Width = 11.5 * 72; titleShape.Height = 1.45 * 72; titleShape.TextBody.AddParagraph("Ole Object"); titleShape.TextBody.Paragraphs[0].Font.Bold = true; titleShape.TextBody.Paragraphs[0].HorizontalAlignment = HorizontalAlignmentType.Left; IShape heading = slide.Shapes.AddTextBox(100, 100, 100, 100); heading.Left = 0.84 * 72; heading.Top = 1.65 * 72; heading.Width = 2.23 * 72; heading.Height = 0.51 * 72; heading.TextBody.AddParagraph("MS Word Object"); heading.TextBody.Paragraphs[0].Font.Italic = true; heading.TextBody.Paragraphs[0].Font.Bold = true; heading.TextBody.Paragraphs[0].Font.FontSize = 18; string mswordPath = ""; #if COMMONSB mswordPath = "SampleBrowser.Samples.Presentation.Samples.Templates.OleTemplate.docx"; #else mswordPath = "SampleBrowser.Presentation.Samples.Templates.OleTemplate.docx"; #endif //Get the word file as stream Stream wordStream = assembly.GetManifestResourceStream(mswordPath); string imagePath = ""; #if COMMONSB imagePath = "SampleBrowser.Samples.Presentation.Samples.Templates.OlePicture.png"; #else imagePath = "SampleBrowser.Presentation.Samples.Templates.OlePicture.png"; #endif //Image to be displayed, This can be any image Stream imageStream = assembly.GetManifestResourceStream(imagePath); IOleObject oleObject = slide.Shapes.AddOleObject(imageStream, "Word.Document.12", wordStream); //Set size and position of the ole object oleObject.Left = 4.53 * 72; oleObject.Top = 0.79 * 72; oleObject.Width = 4.26 * 72; oleObject.Height = 5.92 * 72; //Set DisplayAsIcon as true, to open the embedded document in separate (default) application. oleObject.DisplayAsIcon = true; MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InsertOLEObject.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("InsertOLEObject.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } void OnExtractOleButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.EmbeddedOleObject.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.EmbeddedOleObject.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Gets the first slide of the Presentation ISlide slide = presentation.Slides[0]; //Gets the Ole Object of the slide IOleObject oleObject = slide.Shapes[2] as IOleObject; //Gets the file data of embedded Ole Object. byte[] array = oleObject.ObjectData; //Gets the file Name of OLE Object string outputFile = oleObject.FileName; //Save the Presentation to stream MemoryStream stream = new MemoryStream(array); presentation.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save(outputFile, "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save(outputFile, "application/msword", stream); } } } <file_sep>/Forms/Sparkline/Sparkline/Samples/Sparkline/SparklineModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSparkline { [Preserve(AllMembers = true)] public class SparklineModel { public double Performance { get; set; } public double YearPerformance { get; set; } } } <file_sep>/Forms/ListView/ListView/Samples/AutoFitContent/Model/BookInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewBookInfo : INotifyPropertyChanged { #region Fields private string bookName; private string bookDesc; private string bookAuthor; private string _authorImage; #endregion #region Constructor public ListViewBookInfo() { } #endregion #region Properties public string BookName { get { return bookName; } set { bookName = value; OnPropertyChanged("BookName"); } } public string BookDescription { get { return bookDesc; } set { bookDesc = value; OnPropertyChanged("BookDescription"); } } public string BookAuthor { get { return bookAuthor; } set { bookAuthor = value; OnPropertyChanged("BookAuthor"); } } public string AuthorImage { get { return _authorImage; } set { _authorImage = value; OnPropertyChanged("AuthorImage"); } } #endregion #region Interface Member public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Forms/Diagram/Diagram/Samples/MindMap/AddNote.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfDiagram { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddNote : ContentPage { MindMap MindMap; public AddNote(MindMap mindMap) { InitializeComponent(); MindMap = mindMap; if (mindMap.SelectedNode.Content == null) { NotesLabel.Text = "Add Note"; } else { NotesLabel.Text = "Edit Note"; } crossImage.Margin = tickImage.Margin = new Thickness(0, 0, 10, 0); if (Device.RuntimePlatform == Device.iOS) { ParentGrid.Margin = new Thickness(0, 20, 0, 0); if (Device.Idiom == TargetIdiom.Tablet) { crossIconCol.Width = 50; tickIconCol.Width = 50; } } } private void AddNodeNote(object sender, EventArgs e) { if (MindMap.SelectedNode != null) { MindMap.SelectedNode.Content = note.Text; } Navigation.PopAsync(); } private void CancelNote(object sender, EventArgs e) { Navigation.PopAsync(); } protected override void OnAppearing() { note.Focus(); if (MindMap.SelectedNode != null) { if (MindMap.SelectedNode.Content != null) { note.Text = MindMap.SelectedNode.Content.ToString(); } } base.OnAppearing(); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Rotator/Rotator_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Foundation; using Syncfusion.SfRotator.iOS; using System.Collections.Generic; using CoreGraphics; namespace SampleBrowser { public class Rotator_Mobile : SampleView { SFRotator rotator; NSMutableArray array; UIView main_view; UIScrollView sub_View; UISwitch autoPlaySwitch; UIPickerView navigationModePicker,navigationDirectionPicker,tabStripPicker; UILabel navigationModeLabel,navigationDirectionLabel,tabStripLabel,autoPlayLabel; UIButton navigationModeButton,navigationDirectionButton,tabStripButton; UIButton doneButton; private string selectedType; private readonly IList<string> navigationModeList = new List<string>{ "Dots", "Thumbnail" }; private readonly IList<string> navigationDirectionList = new List<string>{ "Horizontal", "Vertical" }; private readonly IList<string> tabStripPositionList = new List<string>{ "Left", "Top", "Right", "Bottom" }; public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; main_view.Frame = new CGRect(0,0,Frame.Width,Frame.Height); rotator.Frame = new CGRect (0,main_view.Frame.Y,main_view.Frame.Size.Width, Frame.Height / 2+30); sub_View.Frame = new CGRect (0,main_view.Frame.Height/2+35,main_view.Frame.Size.Width, Frame.Height / 2-35); navigationModeLabel.Frame = new CGRect (10, 4, main_view.Frame.Size.Width,25 ); navigationDirectionLabel.Frame = new CGRect (10,67, main_view.Frame.Size.Width, 25); tabStripLabel.Frame = new CGRect (10, 130, main_view.Frame.Size.Width, 25); navigationModePicker.Frame = new CGRect (0, this.Frame.Size.Height-(this.Frame.Size.Height/3), this.Frame.Size.Width, this.Frame.Size.Height/3); navigationDirectionPicker.Frame = new CGRect (0, this.Frame.Size.Height-(this.Frame.Size.Height/3), this.Frame.Size.Width , this.Frame.Size.Height/3); tabStripPicker.Frame = new CGRect (0, this.Frame.Size.Height-(this.Frame.Size.Height/3), this.Frame.Size.Width , this.Frame.Size.Height/3); doneButton.Frame = new CGRect (0, this.Frame.Size.Height-(this.Frame.Size.Height/3)-30, this.Frame.Size.Width, 30); navigationModeButton.Frame = new CGRect (10, 35, main_view.Frame.Size.Width-20,30 ); navigationDirectionButton.Frame = new CGRect (10,95, main_view.Frame.Size.Width-20,30 ); tabStripButton.Frame = new CGRect (10, 158, main_view.Frame.Size.Width-20,30 ); autoPlayLabel.Frame=new CGRect(10, 205, this.Frame.Size.Width-20, 20); autoPlaySwitch.Frame=new CGRect(250,200, this.Frame.Size.Width-20, 20); sub_View.ContentSize = new CGSize (main_view.Frame.Width,main_view.Frame.Height/2+20); } base.LayoutSubviews (); } public Rotator_Mobile () { array = new NSMutableArray (); getRotatorItem (); //Control Initialization rotator = new SFRotator (); rotator.DataSource = array; rotator.EnableLooping=true; rotator.NavigationStripMode=SFRotatorNavigationStripMode.Dots; rotator.SelectedIndex=0; rotator.NavigationDelay = 2; getPropertiesInitialization (); this.AddSubview (main_view); this.BackgroundColor = UIColor.White; main_view.BringSubviewToFront (navigationModePicker); main_view.BringSubviewToFront (navigationDirectionPicker); main_view.BringSubviewToFront (tabStripPicker); main_view.BringSubviewToFront (doneButton); } void getRotatorItem() { SFRotatorItem item1 = new SFRotatorItem (); UIView view1 = new UIView(); UIImageView image1 =new UIImageView(); image1.Frame = view1.Frame; image1.Image = UIImage.FromFile ("movie1.png"); item1.View = view1; view1.AddSubview(image1); SFRotatorItem item2 = new SFRotatorItem (); UIView view2 = new UIView(); UIImageView image2 =new UIImageView(); image2.Frame = view2.Frame; image2.Image = UIImage.FromFile ("movie2.png"); item2.View = view2; view2.AddSubview(image2); SFRotatorItem item3 = new SFRotatorItem (); UIView view3 = new UIView(); UIImageView image3 =new UIImageView(); image3.Frame = view3.Frame; image3.Image = UIImage.FromFile ("movie3.png"); item3.View = view3; view3.AddSubview(image3); SFRotatorItem item4 = new SFRotatorItem (); UIView view4 = new UIView(); UIImageView image4 =new UIImageView(); image4.Frame = view4.Frame; image4.Image = UIImage.FromFile ("movie4.png"); item4.View = view4; view4.AddSubview(image4); SFRotatorItem item5 = new SFRotatorItem (); UIView view5 = new UIView(); UIImageView image5 =new UIImageView(); image5.Frame = view5.Frame; image5.Image = UIImage.FromFile ("movie5.png"); item5.View = view5; view5.AddSubview(image5); SFRotatorItem item6 = new SFRotatorItem (); UIView view6 = new UIView(); UIImageView image6 =new UIImageView(); image6.Frame = view6.Frame; image6.Image = UIImage.FromFile ("movie6.png"); item6.View = view6; view6.AddSubview(image6); SFRotatorItem item7 = new SFRotatorItem (); UIView view7 = new UIView(); UIImageView image7 =new UIImageView(); image7.Frame = view7.Frame; image7.Image = UIImage.FromFile ("movie7.png"); item7.View = view7; view7.AddSubview(image7); image1.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image2.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image3.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image4.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image5.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image6.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; image7.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; array.Add (item1); array.Add (item2); array.Add (item3); array.Add (item4); array.Add (item5); } void getPropertiesInitialization() { navigationModePicker = new UIPickerView (); navigationDirectionPicker = new UIPickerView (); tabStripPicker = new UIPickerView (); PickerModel navigationModeModel = new PickerModel (navigationModeList); navigationModePicker.Model = navigationModeModel; PickerModel navigationDirectionModel = new PickerModel (navigationDirectionList); navigationDirectionPicker.Model = navigationDirectionModel; PickerModel tabStripModel = new PickerModel (tabStripPositionList); tabStripPicker.Model = tabStripModel; //navigationModeLabel navigationModeLabel = new UILabel(); navigationModeLabel.Text = "NavigationStrip Mode"; navigationModeLabel.TextColor = UIColor.Black; navigationModeLabel.TextAlignment = UITextAlignment.Left; navigationDirectionLabel = new UILabel(); navigationDirectionLabel.Text = "Navigation Direction"; navigationDirectionLabel.TextColor = UIColor.Black; navigationDirectionLabel.TextAlignment = UITextAlignment.Left; tabStripLabel = new UILabel(); tabStripLabel.Text = "NavigationStrip Position"; tabStripLabel.TextColor = UIColor.Black; tabStripLabel.TextAlignment = UITextAlignment.Left; //navigationModeButton navigationModeButton = new UIButton(); navigationModeButton.SetTitle("Dots",UIControlState.Normal); navigationModeButton.SetTitleColor(UIColor.Black,UIControlState.Normal); navigationModeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; navigationModeButton.Layer.CornerRadius = 8; navigationModeButton.Layer.BorderWidth = 2; navigationModeButton.Layer.BorderColor =UIColor.FromRGB(246,246,246).CGColor; //navigationDirectionButton navigationDirectionButton = new UIButton(); navigationDirectionButton.SetTitle("Horizontal",UIControlState.Normal); navigationDirectionButton.SetTitleColor(UIColor.Black,UIControlState.Normal); navigationDirectionButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; navigationDirectionButton.Layer.CornerRadius = 8; navigationDirectionButton.Layer.BorderWidth = 2; navigationDirectionButton.Layer.BorderColor =UIColor.FromRGB(246,246,246).CGColor; //tabStripButton tabStripButton = new UIButton(); tabStripButton.SetTitle("Bottom",UIControlState.Normal); tabStripButton.SetTitleColor(UIColor.Black,UIControlState.Normal); tabStripButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; tabStripButton.Layer.CornerRadius = 8; tabStripButton.Layer.BorderWidth = 2; tabStripButton.TouchUpInside += ShowtabStripPicker; tabStripButton.Layer.BorderColor =UIColor.FromRGB(246,246,246).CGColor; doneButton = new UIButton (); doneButton.SetTitle("Done\t",UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black,UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(246,246,246); navigationModeModel.PickerChanged += navigationModeSelectedIndexChanged; navigationDirectionModel.PickerChanged += navigationDirectionSelectedIndexChanged; tabStripModel.PickerChanged += tabStripSelectedIndexChanged; navigationModePicker.ShowSelectionIndicator = true; navigationModePicker.Hidden = true; navigationModePicker.BackgroundColor = UIColor.Gray; navigationDirectionPicker.BackgroundColor = UIColor.Gray; navigationDirectionPicker.ShowSelectionIndicator = true; navigationDirectionPicker.Hidden = true; tabStripPicker.BackgroundColor = UIColor.Gray; tabStripPicker.ShowSelectionIndicator = true; tabStripPicker.Hidden = true; //autoPlayLabel autoPlayLabel = new UILabel(); autoPlayLabel.TextColor = UIColor.Black; autoPlayLabel.BackgroundColor= UIColor.Clear; autoPlayLabel.Text=@"Enable AutoPlay"; autoPlayLabel.TextAlignment= UITextAlignment.Left; autoPlayLabel.Font=UIFont.FromName("Helvetica", 16f); //allowSwitch autoPlaySwitch = new UISwitch(); autoPlaySwitch.ValueChanged += autoPlayToggleChanged; autoPlaySwitch.On=false; //adding to mainview main_view = new UIView (); main_view.AddSubview (rotator); main_view.AddSubview (doneButton); main_view.AddSubview (navigationDirectionPicker); main_view.AddSubview (navigationModePicker); main_view.AddSubview (tabStripPicker); sub_View = new UIScrollView (); sub_View.AddSubview (navigationModeLabel); sub_View.AddSubview (navigationModeButton); sub_View.AddSubview (navigationDirectionLabel); sub_View.AddSubview (navigationDirectionButton); sub_View.AddSubview (tabStripLabel); sub_View.AddSubview (tabStripButton); sub_View.AddSubview (autoPlayLabel); sub_View.AddSubview (autoPlaySwitch); main_view.AddSubview (sub_View); } void ShowtabStripPicker (object sender, EventArgs e) { sub_View.UserInteractionEnabled = false; doneButton.Hidden = false; navigationModePicker.Hidden = true; navigationDirectionPicker.Hidden = true; tabStripPicker.Hidden = false; navigationModeButton.Hidden = true; navigationModeLabel.Hidden = true; tabStripLabel.Hidden = true; tabStripButton.Hidden = true; navigationDirectionButton.Hidden = true; navigationDirectionLabel.Hidden = true; autoPlayLabel.Hidden = true; autoPlaySwitch.Hidden = true; } void HidePicker (object sender, EventArgs e) { sub_View.UserInteractionEnabled = true; doneButton.Hidden = true; navigationDirectionPicker.Hidden = true; navigationModePicker.Hidden = true; tabStripPicker.Hidden = true; navigationModeButton.Hidden = false; navigationModeLabel.Hidden = false; tabStripLabel.Hidden = false; tabStripButton.Hidden = false; navigationDirectionButton.Hidden = false; navigationDirectionLabel.Hidden = false; autoPlayLabel.Hidden = false; autoPlaySwitch.Hidden = false; } private void navigationModeSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; navigationModeButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Dots") rotator.NavigationStripMode = SFRotatorNavigationStripMode.Dots; else rotator.NavigationStripMode = SFRotatorNavigationStripMode.Thumbnail; } private void navigationDirectionSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; navigationDirectionButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Horizontal") rotator.NavigationDirection = SFRotatorNavigationDirection.Horizontal; else rotator.NavigationDirection = SFRotatorNavigationDirection.Vertical; } private void tabStripSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; tabStripButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Left") rotator.NavigationStripPosition = SFRotatorNavigationStripPosition.Left; else if (selectedType == "Top") rotator.NavigationStripPosition =SFRotatorNavigationStripPosition.Top; else if (selectedType == "Right") rotator.NavigationStripPosition =SFRotatorNavigationStripPosition.Right; else rotator.NavigationStripPosition =SFRotatorNavigationStripPosition.Bottom; } private void autoPlayToggleChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { rotator.EnableAutoPlay = true; } else { rotator.EnableAutoPlay = false; } } } } <file_sep>/Forms/Chart/Chart/Samples/SplineChart/SplineSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class SplineSeriesViewModel { public ObservableCollection<ChartDataModel> SplineData1 { get; set; } public ObservableCollection<ChartDataModel> SplineData2 { get; set; } public ObservableCollection<ChartDataModel> SplineData3 { get; set; } public SplineSeriesViewModel() { SplineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 15), new ChartDataModel("Mon", 22), new ChartDataModel("Tue", 32), new ChartDataModel("Wed", 31), new ChartDataModel("Thu", 29), new ChartDataModel("Fri", 26), new ChartDataModel("Sat", 18), }; SplineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 10), new ChartDataModel("Mon", 18), new ChartDataModel("Tue", 28), new ChartDataModel("Wed", 28), new ChartDataModel("Thu", 26), new ChartDataModel("Fri", 20), new ChartDataModel("Sat", 15), }; SplineData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 2), new ChartDataModel("Mon", 12), new ChartDataModel("Tue", 22), new ChartDataModel("Wed", 23), new ChartDataModel("Thu", 19), new ChartDataModel("Fri", 13), new ChartDataModel("Sat", 8), }; } } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/GettingStarted/GettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GettingStarted.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using Core; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; [Preserve(AllMembers = true)] [XamlCompilation(XamlCompilationOptions.Compile)] /// <summary> /// A sampleView that contains the Dialogs sample. /// </summary> public partial class GettingStarted : SampleView { /// <summary> /// Initializes a new instance of the <see cref="GettingStarted" /> class /// </summary> public GettingStarted() { this.InitializeComponent(); } /// <summary> /// You can override this method while View was disappear from window /// </summary> public override void OnDisappearing() { base.OnDisappearing(); if (this.alertDialog != null) { this.alertDialog.Dispose(); this.alertDialog = null; } if (this.alertWithTitleDialogue != null) { this.alertWithTitleDialogue.Dispose(); this.alertWithTitleDialogue = null; } if (this.simpleDialog != null) { this.simpleDialog.Dispose(); this.simpleDialog = null; } if (this.confirmationDialog != null) { this.confirmationDialog.Dispose(); this.confirmationDialog = null; } if (this.modelWindow != null) { this.modelWindow.Dispose(); this.modelWindow = null; } if (this.relativeDialog != null) { this.relativeDialog.Dispose(); this.relativeDialog = null; } if (this.fullScreenDialog != null) { this.fullScreenDialog.Dispose(); this.fullScreenDialog = null; } } } }<file_sep>/Android/SampleBrowser/Samples/XlsIO/ImportCollectionObjectsPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.Xml; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using SampleBrowser; using Android.App; using Syncfusion.SfDataGrid; using System.ComponentModel; namespace SampleBrowser { public partial class ImportCollectionObjectsPage : SamplePage { private Context m_context; SfDataGrid sfGrid; Button btnExport; CLRObjectViewModel viewmodel; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample allows you to import/export data from/to CLR Objects."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); m_context = con; Button btnInput = new Button(con); btnInput.Text = "Input Template"; btnInput.Click += ButtonInputClicked; linear.AddView(btnInput); Button btnImport = new Button(con); btnImport.Text = "Import From Excel"; btnImport.Click += ButtonImportClicked; linear.AddView(btnImport); btnExport = new Button(con); btnExport.Text = "Export To Excel"; btnExport.Click += ButtonExportClicked; btnExport.Enabled = false; linear.AddView(btnExport); sfGrid = new SfDataGrid(con); viewmodel = new CLRObjectViewModel(); sfGrid.AutoGenerateColumns = false; sfGrid.RowHeight = 50; sfGrid.AllowEditing = true; sfGrid.EditTapAction = TapAction.OnTap; sfGrid.ColumnSizer = ColumnSizer.Star; sfGrid.SelectionMode = SelectionMode.None; sfGrid.HeaderRowHeight = 40; sfGrid.ItemsSource = viewmodel.CustomersInfo; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; GridTextColumn brand = new GridTextColumn(); brand.MappingName = "BrandName"; brand.HeaderText = "Brand"; //salesPerson.ItemsSource = viewmodel.CustomersInfo; brand.HeaderTextAlignment = GravityFlags.Center; GridTextColumn vehicleType = new GridTextColumn(); vehicleType.MappingName = "VehicleType.VehicleName"; vehicleType.HeaderText = "Vehicle Type"; // salesJanJune.ItemsSource = viewmodel.CustomersInfo; vehicleType.HeaderTextAlignment = GravityFlags.Center; GridTextColumn model = new GridTextColumn(); model.MappingName = "VehicleType.Model.ModelName"; model.HeaderText = "Model"; //salesJulyDec.ItemsSource = viewmodel.CustomersInfo; model.HeaderTextAlignment = GravityFlags.Center; sfGrid.Columns.Add(brand); sfGrid.Columns.Add(vehicleType); sfGrid.Columns.Add(model); linear.AddView(sfGrid); return linear; } void ButtonInputClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; string resourcePath = ""; resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExportData.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); IWorksheet sheet = workbook.Worksheets[0]; workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("Input Template.xlsx", "application/msexcel", stream, m_context); } } void ButtonImportClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; string resourcePath = ""; resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExportData.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); IWorksheet sheet = workbook.Worksheets[0]; workbook.Version = ExcelVersion.Excel2013; Dictionary<string, string> mappingProperties = new Dictionary<string, string>(); mappingProperties.Add("Brand", "BrandName"); mappingProperties.Add("Vehicle Type", "VehicleType.VehicleName"); mappingProperties.Add("Model", "VehicleType.Model.ModelName"); List<Brand> CLRObjects = sheet.ExportData<Brand>(4, 1, 141, 3, mappingProperties); sfGrid.ItemsSource = CLRObjects; btnExport.Enabled = true; } void ButtonExportClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook //A new workbook is created.[Equivalent to creating a new workbook in MS Excel] //The new workbook will have 1 worksheets IWorkbook workbook = application.Workbooks.Create(1); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; sheet.ImportData((List<Brand>)sfGrid.ItemsSource, 4, 1, true); #region Define Styles IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle"); IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle"); pageHeader.Font.FontName = "Calibri"; pageHeader.Font.Size = 16; pageHeader.Font.Bold = true; pageHeader.Color = Syncfusion.Drawing.Color.FromArgb(0, 146, 208, 80); pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Font.Bold = true; tableHeader.Font.FontName = "Calibri"; tableHeader.Color = Syncfusion.Drawing.Color.FromArgb(0, 146, 208, 80); #endregion #region Apply Styles // Apply style for header sheet["A1:C2"].Merge(); sheet["A1"].Text = "Automobile Brands in the US"; sheet["A1"].CellStyle = pageHeader; sheet["A4:C4"].CellStyle = tableHeader; sheet["A1:C1"].CellStyle.Font.Bold = true; sheet.UsedRange.AutofitColumns(); #endregion #endregion #region Saving workbook and disposing objects workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("CLRObjects.xlsx", "application/msexcel", stream, m_context); } #endregion } } public class CLRObjectViewModel : INotifyPropertyChanged { private bool isDataGridExported; public bool IsDataGridExported { get { return isDataGridExported; } set { isDataGridExported = value; RaisePropertyChanged("IsDataGridExported"); } } public CLRObjectViewModel() { CustomersInfo = new List<Brand>(); foreach (int i in Enumerable.Range(1, 20)) { CustomersInfo.Add(new Brand()); } } #region ItemsSource private List<Brand> customersInfo; public List<Brand> CustomersInfo { get { return customersInfo; } set { this.customersInfo = value; RaisePropertyChanged("CustomersInfo"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } /// <summary> /// Class used to store the customer details /// </summary> public class CustomerObject : INotifyPropertyChanged { public CustomerObject() { } #region private variables private string _salesPerson; private int _salesJanJune; private int _salesJulyDec; private string _change; #endregion #region Public Properties public string SalesPerson { get { return _salesPerson; } set { this._salesPerson = value; RaisePropertyChanged("SalesPerson"); } } public int SalesJanJune { get { return _salesJanJune; } set { this._salesJanJune = value; RaisePropertyChanged("SalesJanJune"); } } public int SalesJulyDec { get { return _salesJulyDec; } set { this._salesJulyDec = value; RaisePropertyChanged("SalesJulyDec"); } } public string Change { get { return _change; } set { this._change = value; RaisePropertyChanged("Change"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String Name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(Name)); } #endregion } public class Brand { private string m_brandName; [DisplayNameAttribute("Brand")] public string BrandName { get { return m_brandName; } set { m_brandName = value; RaisePropertyChanged("BrandName"); } } private VehicleType m_vehicleType; public VehicleType VehicleType { get { return m_vehicleType; } set { m_vehicleType = value; RaisePropertyChanged("VehicleType"); } } public Brand(string brandName) { m_brandName = brandName; } public Brand() { } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String Name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(Name)); } #endregion } public class VehicleType { private string m_vehicleName; [DisplayNameAttribute("Vehicle Type")] public string VehicleName { get { return m_vehicleName; } set { m_vehicleName = value; RaisePropertyChanged("VehicleName"); } } private ModelObject m_model; public ModelObject Model { get { return m_model; } set { m_model = value; RaisePropertyChanged("Model"); } } public VehicleType(string vehicle) { m_vehicleName = vehicle; } public VehicleType() { } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String Name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(Name)); } #endregion } public class ModelObject { private string m_modelName; [DisplayNameAttribute("Model")] public string ModelName { get { return m_modelName; } set { m_modelName = value; RaisePropertyChanged("ModelName"); } } public ModelObject(string name) { m_modelName = name; } public ModelObject() { } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String Name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(Name)); } #endregion } } <file_sep>/Forms/Switch/Switch/Samples/VisualType/VisualType.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.XForms.Buttons; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfSwitch { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class VisualType : SampleView { public VisualType() { InitializeComponent(); if (Device.RuntimePlatform == Device.Android) { scrollView.InputTransparent = true; } if (Device.RuntimePlatform == Device.iOS) { mainStack.WidthRequest = 500; } } bool setState = false; private void SfSwitch_StateChanged(object sender, SwitchStateChangedEventArgs e) { this.OnStateLabel.Text = GetLabel(this.OnStateSwitch.IsOn); setStates(true, this.OnStateSwitch.IsOn); } private void SfSwitch_StateChanged_1(object sender, SwitchStateChangedEventArgs e) { this.IndeterminateStateLabel.Text = GetLabel(this.IndeterminateStateSwitch.IsOn); setStates(null, this.IndeterminateStateSwitch.IsOn); } private void SfSwitch_StateChanged_2(object sender, SwitchStateChangedEventArgs e) { this.OffStateLabel.Text = GetLabel(this.OffStateSwitch.IsOn); setStates(false, this.OffStateSwitch.IsOn); } private string GetLabel(bool? value) { if (value == true) return "On"; else if (value == false) return "Off"; else return "Indeterminate"; } private async void setStates(bool? value, bool? state) { if (setState) return; setState = true; if (value == true) { if (state == true) { this.IndeterminateStateSwitch.IsOn = null; this.OffStateSwitch.IsOn = false; } else if (state == false) { this.IndeterminateStateSwitch.IsOn = null; this.OffStateSwitch.IsOn = true; } else { this.IndeterminateStateSwitch.IsOn = false; this.OffStateSwitch.IsOn = true; } } else if (value == false) { if (state == true) { this.IndeterminateStateSwitch.IsOn = null; this.OnStateSwitch.IsOn = false; } else if (state == false) { this.IndeterminateStateSwitch.IsOn = null; this.OnStateSwitch.IsOn = true; } else { this.IndeterminateStateSwitch.IsOn = false; this.OnStateSwitch.IsOn = true; } } else { if (state == true) { this.OnStateSwitch.IsOn = null; this.OffStateSwitch.IsOn = false; } else if (state == false) { this.OnStateSwitch.IsOn = true; this.OffStateSwitch.IsOn = null; } else { this.OnStateSwitch.IsOn = true; this.OffStateSwitch.IsOn = false; } } await Task.Delay(100); setState = false; } private void SfSwitch_StateChanged_3(object sender, SwitchStateChangedEventArgs e) { if (this.ModeSwitch.IsOn == true) this.ModeLabel.Text = "Night mode"; else this.ModeLabel.Text = "Day mode"; } bool isOn = true; private async void SfSwitch_StateChanging(object sender, SwitchStateChangingEventArgs e) { this.busySwitch1.IsBusy = true; await Task.Delay(2000); this.busySwitch1.IsOn = isOn; this.busySwitch1.IsBusy = false; isOn = !isOn; } private async void SfSwitch_StateChanging_1(object sender, SwitchStateChangingEventArgs e) { this.busySwitch2.IsBusy = true; await Task.Delay(2000); this.busySwitch2.IsOn = false; this.busySwitch2.IsBusy = false; } } }<file_sep>/iOS/SampleBrowser/Samples/DocIO/BookmarkNavigation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class BookmarkNavigation : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton button; UIButton viewButton; public BookmarkNavigation() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; viewButton = new UIButton(UIButtonType.System); viewButton.TouchUpInside += OnConvertClicked1; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to insert, retrieve, replace and delete the contents of a specified bookmark using BookmarkNavigator functionality of DocIO."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 90); } this.AddSubview(label); button.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 80, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 135, frameRect.Size.Width, 10); } this.AddSubview(button); viewButton.SetTitle("View Template", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { viewButton.Frame = new CGRect(0, 70, frameRect.Location.X + frameRect.Size.Width, 10); } else { viewButton.Frame = new CGRect(frameRect.Location.X, 105, frameRect.Size.Width, 10); } this.AddSubview(viewButton); } void OnConvertClicked1(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Bookmark_Template.docx"); MemoryStream stream = new MemoryStream(); inputStream.CopyTo(stream); inputStream.Dispose(); string fileName = null; string ContentType = null; fileName = "Bookmark_Template.docx"; ContentType = "application/msword"; //Reset the stream position stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save(fileName, ContentType, stream as MemoryStream); } } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Creating a new document. WordDocument document = new WordDocument(); //Adds section with one empty paragraph to the Word document document.EnsureMinimal(); //sets the page margins document.LastSection.PageSetup.Margins.All = 72f; //Appends bookmark to the paragraph document.LastParagraph.AppendBookmarkStart("NorthwindDatabase"); document.LastParagraph.AppendText("Northwind database with relational data"); document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase"); // Open an existing template document with single section. WordDocument nwdInformation = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Bookmark_Template.docx"); // Open an existing template document. nwdInformation.Open(inputStream, FormatType.Doc); inputStream.Dispose(); // Open an existing template document with multiple section. WordDocument templateDocument = new WordDocument(); inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.BkmkDocumentPart_Template.docx"); // Open an existing template document. templateDocument.Open(inputStream, FormatType.Doc); inputStream.Dispose(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the template document. BookmarksNavigator bk = new BookmarksNavigator(templateDocument); // Move to the NorthWind bookmark in template document bk.MoveToBookmark("NorthWind"); //Gets the bookmark content as WordDocumentPart WordDocumentPart documentPart = bk.GetContent(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the Northwind information document. bk = new BookmarksNavigator(nwdInformation); // Move to the information bookmark bk.MoveToBookmark("Information"); // Get the content of information bookmark. TextBodyPart bodyPart = bk.GetBookmarkContent(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the destination document. bk = new BookmarksNavigator(document); // Move to the NorthWind database in the destination document bk.MoveToBookmark("NorthwindDatabase"); //Replace the bookmark content using word document parts bk.ReplaceContent(documentPart); // Move to the Northwind_Information in the destination document bk.MoveToBookmark("Northwind_Information"); // Replacing content of Northwind_Information bookmark. bk.ReplaceBookmarkContent(bodyPart); #region Bookmark selection for table // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the Northwind information document. bk = new BookmarksNavigator(nwdInformation); bk.MoveToBookmark("SuppliersTable"); //Sets the column index where the bookmark starts within the table bk.CurrentBookmark.FirstColumn = 1; //Sets the column index where the bookmark ends within the table bk.CurrentBookmark.LastColumn = 5; // Get the content of suppliers table bookmark. bodyPart = bk.GetBookmarkContent(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the destination document. bk = new BookmarksNavigator(document); bk.MoveToBookmark("Table"); bk.ReplaceBookmarkContent(bodyPart); #endregion // Move to the text bookmark bk.MoveToBookmark("Text"); //Deletes the bookmark content bk.DeleteBookmarkContent(true); // Inserting text inside the bookmark. This will preserve the source formatting bk.InsertText("Northwind Database contains the following table:"); #region tableinsertion WTable tbl = new WTable(document); tbl.TableFormat.Borders.BorderType = BorderStyle.None; tbl.TableFormat.IsAutoResized = true; tbl.ResetCells(8, 2); IWParagraph paragraph; tbl.Rows[0].IsHeader = true; paragraph = tbl[0, 0].AddParagraph(); paragraph.AppendText("Suppliers"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[0, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[1, 0].AddParagraph(); paragraph.AppendText("Customers"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[1, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[2, 0].AddParagraph(); paragraph.AppendText("Employees"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[2, 1].AddParagraph(); paragraph.AppendText("3"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[3, 0].AddParagraph(); paragraph.AppendText("Products"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[3, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[4, 0].AddParagraph(); paragraph.AppendText("Inventory"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[4, 1].AddParagraph(); paragraph.AppendText("2"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[5, 0].AddParagraph(); paragraph.AppendText("Shippers"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[5, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[6, 0].AddParagraph(); paragraph.AppendText("PO Transactions"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[6, 1].AddParagraph(); paragraph.AppendText("3"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[7, 0].AddParagraph(); paragraph.AppendText("Sales Transactions"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[7, 1].AddParagraph(); paragraph.AppendText("7"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; bk.InsertTable(tbl); #endregion bk.MoveToBookmark("Image"); bk.DeleteBookmarkContent(true); // Inserting image to the bookmark. IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture; inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Northwind.png"); pic.LoadImage(inputStream); inputStream.Dispose(); pic.WidthScale = 50f; // It reduce the image size because it don't fit pic.HeightScale = 75f; // in document page. #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("Bookmark Navigation.docx", "application/msword", stream); } #endregion } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Android/SampleBrowser/Samples/NumericTextBox/NumericTextBox_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Numerictextbox; using Android.Graphics; using Android.Views.InputMethods; using Android.Text; using Android.Text.Style; namespace SampleBrowser { public class NumericTextBox_Tab : SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ SfNumericTextBox principalAmountNumericTextBox, outputNumberTextBox, interestNumericTextBox, periodValueNumericTextBox; LinearLayout propertylayout, mainLayout; ArrayAdapter<String> cultureDataAdapter; Spinner cultureSpinner; Java.Util.Locale localinfo; Button propertyButton; FrameLayout propertyFrameLayout, buttomButtonLayout; bool allownull = true, allowDefaultDecimalDigits= true; int culturePosition = 0, numerHeight, width; bool allowNullPosition = true, allowDefaultDecimalDigitsPosition = true; double actionBarHeight, navigationBarHeight, totalHeight; Context context, con; FrameLayout frame, mainFrameLayout; public override View GetSampleContent(Context con1) { context = con = con1; InitialMethod(); HeaderLabel(); // principalAmountNumericTextBox LinearLayout principalStack = new LinearLayout(con); TextView principalLabel = new TextView(con); principalLabel.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); principalLabel.Text = "Principal"; principalLabel.TextSize = 20; principalAmountNumericTextBox = new SfNumericTextBox(con); principalAmountNumericTextBox.FormatString = "C"; principalAmountNumericTextBox.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); principalAmountNumericTextBox.Value = 1000; principalAmountNumericTextBox.AllowNull = true; principalAmountNumericTextBox.Watermark = "Principal Amount"; principalAmountNumericTextBox.MaximumNumberDecimalDigits = 2; principalAmountNumericTextBox.FocusChange += PrincipalAmountNumericTextBox_FocusChange; var culture = new Java.Util.Locale("en", "US"); principalAmountNumericTextBox.CultureInfo = culture; principalAmountNumericTextBox.ValueChangeMode = ValueChangeMode.OnKeyFocus; principalStack.Orientation = Orientation.Horizontal; principalStack.AddView(principalLabel); principalStack.AddView(principalAmountNumericTextBox); mainLayout.AddView(principalStack); TextView principalStackSpacing = new TextView(con); mainLayout.AddView(principalStackSpacing); //interestNumericTextBox LinearLayout InterestcalStack = new LinearLayout(con); TextView interestLabel = new TextView(con); interestLabel.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); interestLabel.Text = "Interest Rate"; interestLabel.TextSize = 20; interestNumericTextBox = new SfNumericTextBox(con); interestNumericTextBox.FormatString = "P"; interestNumericTextBox.Value = 0.1; interestNumericTextBox.PercentDisplayMode = PercentDisplayMode.Compute; interestNumericTextBox.MaximumNumberDecimalDigits = 2; interestNumericTextBox.ValueChangeMode = ValueChangeMode.OnKeyFocus; interestNumericTextBox.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); interestNumericTextBox.Watermark = "Rate of Interest"; interestNumericTextBox.AllowNull = true; interestNumericTextBox.CultureInfo = culture; interestNumericTextBox.FocusChange += InterestNumericTextBox_FocusChange; InterestcalStack.Orientation = Orientation.Horizontal; InterestcalStack.AddView(interestLabel); InterestcalStack.AddView(interestNumericTextBox); mainLayout.AddView(InterestcalStack); TextView InterestcalStackSpacing = new TextView(con); mainLayout.AddView(InterestcalStackSpacing); //periodValueNumericTextBox LinearLayout periodStack = new LinearLayout(con); TextView period = new TextView(con); period.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); period.Text = "Term"; period.TextSize = 20; periodValueNumericTextBox = new SfNumericTextBox(con); periodValueNumericTextBox.FormatString = " years"; periodValueNumericTextBox.Value = 20; periodValueNumericTextBox.MaximumNumberDecimalDigits = 0; periodValueNumericTextBox.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); periodValueNumericTextBox.Watermark = "Period (in years)"; periodValueNumericTextBox.ValueChangeMode = ValueChangeMode.OnKeyFocus; periodValueNumericTextBox.CultureInfo = culture; periodValueNumericTextBox.AllowNull = true; periodValueNumericTextBox.FocusChange += PeriodValueNumericTextBox_FocusChange; periodStack.Orientation = Orientation.Horizontal; periodStack.AddView(period); periodStack.AddView(periodValueNumericTextBox); mainLayout.AddView(periodStack); //outputNumberTextBox LinearLayout outputStack = new LinearLayout(con); TextView outputLabel = new TextView(con); outputLabel.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); outputLabel.Text = "Interest"; outputLabel.TextSize = 20; outputLabel.SetTextColor(Color.ParseColor("#66BB6A")); outputNumberTextBox = new SfNumericTextBox(con); outputNumberTextBox.FormatString = "c"; outputNumberTextBox.MaximumNumberDecimalDigits = 0; outputNumberTextBox.AllowNull = true; outputNumberTextBox.CultureInfo = culture; outputNumberTextBox.Watermark = "Enter Values"; outputNumberTextBox.Clickable = false; outputNumberTextBox.Value = (float)(1000 * 0.1 * 20); outputNumberTextBox.Enabled = false; outputNumberTextBox.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); outputNumberTextBox.ValueChangeMode = ValueChangeMode.OnLostFocus; outputStack.Orientation = Orientation.Horizontal; outputStack.AddView(outputLabel); if (con.Resources.DisplayMetrics.Density > 1.5) { outputStack.SetY(60); } outputStack.AddView(outputNumberTextBox); mainLayout.AddView(outputStack); TextView outputStackSpacing = new TextView(con); mainLayout.AddView(outputStackSpacing); ValueChangeListener(); return frame; } private void InitialMethod() { frame = new FrameLayout(con); totalHeight = con.Resources.DisplayMetrics.HeightPixels; TypedValue tv = new TypedValue(); if (con.Theme.ResolveAttribute(Android.Resource.Attribute.ActionBarSize, tv, true)) { actionBarHeight = TypedValue.ComplexToDimensionPixelSize(tv.Data, con.Resources.DisplayMetrics); } navigationBarHeight = getNavigationBarHeight(con); totalHeight = totalHeight - navigationBarHeight - actionBarHeight; numerHeight = getDimensionPixelSize(con, Resource.Dimension.numeric_txt_ht); width = con.Resources.DisplayMetrics.WidthPixels - 40; mainFrameLayout = new FrameLayout(con); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.FillVertical); mainFrameLayout.LayoutParameters = layoutParams; //mainLayout mainLayout = new LinearLayout(con); mainLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.6), GravityFlags.Top | GravityFlags.CenterHorizontal); mainLayout.SetGravity(GravityFlags.FillVertical); mainLayout.SetPadding(10, 10, 10, 10); mainLayout.SetBackgroundColor(Color.White); mainLayout.Orientation = Orientation.Vertical; } private void HeaderLabel() { //simpleInterestCalculatorLabel TextView simpleInterestCalculatorLabel = new TextView(con); simpleInterestCalculatorLabel.Text = "Simple Interest Calculator"; simpleInterestCalculatorLabel.Gravity = GravityFlags.Center; simpleInterestCalculatorLabel.TextSize = 24; mainLayout.AddView(simpleInterestCalculatorLabel); TextView sILabelSpacing = new TextView(con); mainLayout.AddView(sILabelSpacing); //findingSILabel TextView findingSILabel = new TextView(con); findingSILabel.Text = "The formula for finding simple interest is:"; findingSILabel.TextSize = 16; //mainLayout.AddView(findingSILabel); mainLayout.FocusableInTouchMode = true; SpannableStringBuilder formulaBuilder = new SpannableStringBuilder(); //formulaLabel TextView formulaLabel = new TextView(con); String interest = ""; SpannableString interestSpannable = new SpannableString(interest); interestSpannable.SetSpan(new ForegroundColorSpan(Color.ParseColor("#66BB6A")), 0, interest.Length, 0); formulaBuilder.Append(interestSpannable); formulaBuilder.Append(" Principal * Rate * Time"); formulaLabel.SetText(formulaBuilder, TextView.BufferType.Spannable); formulaLabel.TextSize = 16; //formulaLayout LinearLayout formulaLayout = new LinearLayout(con); formulaLayout.Orientation = Android.Widget.Orientation.Horizontal; formulaLayout.AddView(findingSILabel); formulaLayout.AddView(formulaLabel); mainLayout.AddView(formulaLayout); TextView formulaLabelSpacing = new TextView(con); mainLayout.AddView(formulaLabelSpacing); } private void ValueChangeListener() { //numerictextbox Value Changed Listener principalAmountNumericTextBox.ValueChanged += (object sender, ValueChangedEventArgs e) => { if (e.Value != null && periodValueNumericTextBox.Value != null && interestNumericTextBox.Value != null) outputNumberTextBox.Value = Double.Parse(e.Value.ToString()) * Double.Parse(periodValueNumericTextBox.Value.ToString()) * Double.Parse(interestNumericTextBox.Value.ToString()); }; periodValueNumericTextBox.ValueChanged += (object sender, ValueChangedEventArgs e) => { if (e.Value != null && principalAmountNumericTextBox.Value != null && interestNumericTextBox.Value != null) outputNumberTextBox.Value = Double.Parse(e.Value.ToString()) * Double.Parse(principalAmountNumericTextBox.Value.ToString()) * Double.Parse(interestNumericTextBox.Value.ToString()); }; interestNumericTextBox.ValueChanged += (object sender, ValueChangedEventArgs e) => { if (e.Value != null && principalAmountNumericTextBox.Value != null && periodValueNumericTextBox.Value != null) outputNumberTextBox.Value = Double.Parse(e.Value.ToString()) * Double.Parse(principalAmountNumericTextBox.Value.ToString()) * Double.Parse(periodValueNumericTextBox.Value.ToString()); }; mainLayout.Touch += (object sender, View.TouchEventArgs e) => { if (outputNumberTextBox.IsFocused || interestNumericTextBox.IsFocused || periodValueNumericTextBox.IsFocused || principalAmountNumericTextBox.IsFocused) { Rect outRect = new Rect(); outputNumberTextBox.GetGlobalVisibleRect(outRect); interestNumericTextBox.GetGlobalVisibleRect(outRect); periodValueNumericTextBox.GetGlobalVisibleRect(outRect); principalAmountNumericTextBox.GetGlobalVisibleRect(outRect); if (!outRect.Contains((int)e.Event.RawX, (int)e.Event.RawY)) { outputNumberTextBox.ClearFocus(); interestNumericTextBox.ClearFocus(); periodValueNumericTextBox.ClearFocus(); principalAmountNumericTextBox.ClearFocus(); } hideSoftKeyboard((Activity)con); } }; //frame frame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); frame.SetBackgroundColor(Color.White); //scrollView1 ScrollView scrollView1 = new ScrollView(con); scrollView1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.6), GravityFlags.Top | GravityFlags.CenterHorizontal); scrollView1.AddView(mainLayout); frame.AddView(scrollView1); //buttomButtonLayout buttomButtonLayout = new FrameLayout(con); buttomButtonLayout.SetBackgroundColor(Color.Transparent); buttomButtonLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1), GravityFlags.Bottom | GravityFlags.CenterHorizontal); //propertyButton propertyButton = new Button(con); propertyButton.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Bottom | GravityFlags.CenterHorizontal); propertyButton.Text = "OPTIONS"; propertyButton.Gravity = GravityFlags.Start; propertyFrameLayout = new FrameLayout(con); propertyFrameLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.36), GravityFlags.CenterHorizontal); propertyFrameLayout.AddView(GetPropertyLayout(con)); propertyButton.Click += (object sender, EventArgs e) => { buttomButtonLayout.RemoveAllViews(); propertyFrameLayout.RemoveAllViews(); outputNumberTextBox.ClearFocus(); interestNumericTextBox.ClearFocus(); periodValueNumericTextBox.ClearFocus(); principalAmountNumericTextBox.ClearFocus(); propertyFrameLayout.AddView(GetPropertyLayout(con)); }; //scrollView ScrollView scrollView = new ScrollView(con); scrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.36), GravityFlags.Bottom | GravityFlags.CenterHorizontal); scrollView.AddView(propertyFrameLayout); //frame frame.AddView(scrollView); frame.AddView(buttomButtonLayout); frame.FocusableInTouchMode = true; } private void PeriodValueNumericTextBox_FocusChange(object sender, View.FocusChangeEventArgs e) { if (e.HasFocus) { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); } } private void InterestNumericTextBox_FocusChange(object sender, View.FocusChangeEventArgs e) { if (e.HasFocus) { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); } } private void PrincipalAmountNumericTextBox_FocusChange(object sender, View.FocusChangeEventArgs e) { if (e.HasFocus) { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); } } //Apply Changes Method public void ApplyChanges() { principalAmountNumericTextBox.CultureInfo = localinfo; outputNumberTextBox.CultureInfo = localinfo; principalAmountNumericTextBox.AllowNull = allownull; periodValueNumericTextBox.AllowNull = allownull; interestNumericTextBox.AllowNull = allownull; principalAmountNumericTextBox.AllowDefaultDecimalDigits = allowDefaultDecimalDigits; interestNumericTextBox.AllowDefaultDecimalDigits = allowDefaultDecimalDigits; } int totalWidth; public View GetPropertyLayout(Context context) { //Property Window width = (context.Resources.DisplayMetrics.WidthPixels) / 2; totalWidth = (context.Resources.DisplayMetrics.WidthPixels); OptionLayout(); CultureLayout(); AllowDefaultDecimalDigitsLayout(); AllowNullLayout(); return propertylayout; } FrameLayout topProperty; LinearLayout proprtyOptionsLayout; private void OptionLayout() { propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; //propertyLabel TextView propertyLabel = new TextView(context); propertyLabel.SetTextColor(Color.ParseColor("#282828")); propertyLabel.Gravity = GravityFlags.CenterVertical; propertyLabel.TextSize = 18; propertyLabel.SetPadding(0, 10, 0, 10); propertyLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.Left | GravityFlags.CenterHorizontal); propertyLabel.Text = " " + "OPTIONS"; //closeLabel TextView closeLabel = new TextView(context); closeLabel.SetBackgroundColor(Color.Transparent); closeLabel.Gravity = GravityFlags.CenterVertical; closeLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLabel.SetBackgroundResource(Resource.Drawable.sfclosebutton); //closeLayout FrameLayout closeLayout = new FrameLayout(context); closeLayout.SetBackgroundColor(Color.Transparent); closeLayout.SetPadding(0, 10, 0, 10); closeLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLayout.AddView(closeLabel); //topProperty topProperty = new FrameLayout(context); topProperty.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); topProperty.SetBackgroundColor(Color.Rgb(230, 230, 230)); topProperty.AddView(propertyLabel); topProperty.AddView(closeLayout); topProperty.Touch += (object sendar, View.TouchEventArgs e) => { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); }; proprtyOptionsLayout = new LinearLayout(context); proprtyOptionsLayout.Orientation = Android.Widget.Orientation.Vertical; //spaceText TextView spaceText1 = new TextView(context); spaceText1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.08), GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText1); } private void CultureLayout() { //culture TextView culturetxt = new TextView(context); culturetxt.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); culturetxt.TextSize = 15; culturetxt.Text = "Culture"; cultureSpinner = new Spinner(context,SpinnerMode.Dialog); cultureSpinner.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); List<String> cultureList = new List<String>(); cultureList.Add("United States"); cultureList.Add("United Kingdom"); cultureList.Add("Japan"); cultureList.Add("France"); cultureList.Add("Italy"); cultureDataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, cultureList); cultureDataAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem); cultureSpinner.Adapter = cultureDataAdapter; cultureSpinner.SetSelection(culturePosition); cultureSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = cultureDataAdapter.GetItem(e.Position); culturePosition = e.Position; if (selectedItem.Equals("United States")) { localinfo = Java.Util.Locale.Us; } if (selectedItem.Equals("United Kingdom")) { localinfo = Java.Util.Locale.Uk; } if (selectedItem.Equals("Japan")) { localinfo = Java.Util.Locale.Japan; } if (selectedItem.Equals("France")) { localinfo = Java.Util.Locale.France; } if (selectedItem.Equals("Italy")) { localinfo = Java.Util.Locale.Italy; } ApplyChanges(); }; LinearLayout cultureLayout = new LinearLayout(context); cultureLayout.Orientation = Android.Widget.Orientation.Horizontal; cultureLayout.AddView(culturetxt); cultureLayout.AddView(cultureSpinner); proprtyOptionsLayout.AddView(cultureLayout); //spaceText TextView spaceText2 = new TextView(context); spaceText2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.05), GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText2); } private void AllowNullLayout() { //AllowNull TextView allowNullText = new TextView(context); allowNullText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); allowNullText.Text = "Allow Null"; allowNullText.TextSize = 15; Switch allowNullCheckBox = new Switch(context); allowNullCheckBox.Gravity = GravityFlags.Left; // allowNullCheckBox.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); allowNullCheckBox.Checked = allowNullPosition; allowNullCheckBox.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { if (!eve.IsChecked) allownull = false; else allownull = true; allowNullPosition = allownull; ApplyChanges(); }; //spaceText TextView spaceText7 = new TextView(context); spaceText7.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); LinearLayout allowNullLayout = new LinearLayout(context); allowNullLayout.Orientation = Android.Widget.Orientation.Horizontal; allowNullLayout.AddView(allowNullText); allowNullLayout.AddView(allowNullCheckBox); allowNullLayout.AddView(spaceText7); proprtyOptionsLayout.AddView(allowNullLayout); //spaceText TextView spaceText3 = new TextView(context); spaceText3.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.08), GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText3); TextView spaceLabel = new TextView(context); spaceLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent); LinearLayout layout1 = new LinearLayout(context); layout1.Orientation = Android.Widget.Orientation.Horizontal; layout1.AddView(spaceLabel); layout1.AddView(proprtyOptionsLayout); propertylayout.AddView(topProperty); propertylayout.AddView(layout1); propertylayout.SetBackgroundColor(Color.Rgb(240, 240, 240)); propertylayout.SetPadding(10, 0, 10, 10); //ScrollView scroll = new ScrollView(context); //scroll.AddView(propertylayout); } private void AllowDefaultDecimalDigitsLayout() { //AllowDefaultDecimalDigits TextView allowDefaultDecimalDigitsText = new TextView(context); allowDefaultDecimalDigitsText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); allowDefaultDecimalDigitsText.Text = "Allow Default Decimal Digits"; allowDefaultDecimalDigitsText.TextSize = 15; Switch allowDefaultDecimalDigitsCheckBox = new Switch(context); allowDefaultDecimalDigitsCheckBox.Gravity = GravityFlags.Left; allowDefaultDecimalDigitsCheckBox.Checked = allowDefaultDecimalDigitsPosition; allowDefaultDecimalDigitsCheckBox.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { if (!eve.IsChecked) allowDefaultDecimalDigits = false; else allowDefaultDecimalDigits = true; allowDefaultDecimalDigitsPosition = allowDefaultDecimalDigits; ApplyChanges(); }; //spaceText TextView spaceText = new TextView(context); spaceText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); LinearLayout allowDefaultDecimalDigitsLayout = new LinearLayout(context); allowDefaultDecimalDigitsLayout.Orientation = Android.Widget.Orientation.Horizontal; allowDefaultDecimalDigitsLayout.AddView(allowDefaultDecimalDigitsText); allowDefaultDecimalDigitsLayout.AddView(allowDefaultDecimalDigitsCheckBox); allowDefaultDecimalDigitsLayout.AddView(spaceText); proprtyOptionsLayout.AddView(allowDefaultDecimalDigitsLayout); //spaceText TextView spaceText2 = new TextView(context); spaceText2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.05), GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText2); } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); inputMethodManager.HideSoftInputFromWindow(activity.CurrentFocus.WindowToken, 0); } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } private int getStatusBarHeight(Android.Content.Context con) { int barHeight = 0; int resourceId = con.Resources.GetIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { barHeight = con.Resources.GetDimensionPixelSize(resourceId); } return barHeight; } private int getNavigationBarHeight(Android.Content.Context con) { int navBarHeight = 0; int resourceId = con.Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navBarHeight = con.Resources.GetDimensionPixelSize(resourceId); } return navBarHeight; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Sorting/SortingBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SortingBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Sorting samples /// </summary> public class SortingBehaviors : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Switch switch1; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Switch switch2; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Switch switch3; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Switch switch4; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of para named as bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.dataGrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.switch1 = bindAble.FindByName<Switch>("switch1"); this.switch2 = bindAble.FindByName<Switch>("switch2"); this.switch3 = bindAble.FindByName<Switch>("switch3"); this.switch4 = bindAble.FindByName<Switch>("switch4"); this.switch1.Toggled += this.Switch1_Toggled; this.switch2.Toggled += this.Switch2_Toggled; this.switch3.Toggled += this.Switch3_Toggled; this.switch4.Toggled += this.Switch4_Toggled; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">SampleView type of bindAble parameter</param> protected override void OnDetachingFrom(SampleView bindAble) { this.switch1.Toggled -= this.Switch1_Toggled; this.switch2.Toggled -= this.Switch2_Toggled; this.switch3.Toggled -= this.Switch3_Toggled; this.switch4.Toggled -= this.Switch4_Toggled; this.dataGrid = null; this.switch1 = null; this.switch2 = null; this.switch3 = null; this.switch4 = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Triggers while Switch was enabled /// </summary> /// <param name="sender">Switch1_Toggled event sender</param> /// <param name="e">Switch1_Toggled event args e</param> private void Switch1_Toggled(object sender, ToggledEventArgs e) { if (e.Value) { this.dataGrid.AllowSorting = true; } else { this.dataGrid.AllowSorting = false; } } /// <summary> /// Triggers while Switch was enabled /// </summary> /// <param name="sender">Switch2_Toggled event sender</param> /// <param name="e">Switch2_Toggled event args e</param> private void Switch2_Toggled(object sender, ToggledEventArgs e) { if (e.Value) { this.dataGrid.AllowTriStateSorting = true; } else { this.dataGrid.AllowTriStateSorting = false; } } /// <summary> /// Triggers while Switch was enabled /// </summary> /// <param name="sender">Switch3_Toggled event sender</param> /// <param name="e">Switch3_Toggled event args e</param> private void Switch3_Toggled(object sender, ToggledEventArgs e) { if (e.Value) { this.dataGrid.AllowMultiSorting = true; } else { this.dataGrid.AllowMultiSorting = false; } } /// <summary> /// Triggers while Switch was enabled /// </summary> /// <param name="sender">Switch4_Toggled event sender</param> /// <param name="e">Switch4_Toggled event args e</param> private void Switch4_Toggled(object sender, ToggledEventArgs e) { if (e.Value) { this.dataGrid.Columns["ProductName"].AllowSorting = true; } else { this.dataGrid.Columns["ProductName"].AllowSorting = false; } } } } <file_sep>/Forms/ComboBox/ComboBox/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using SampleBrowser.Core; using Syncfusion.XForms.ComboBox; using Xamarin.Forms; namespace SampleBrowser.SfComboBox { public partial class Themes : SampleView { public Themes() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { layoutRoot.HorizontalOptions = LayoutOptions.Center; layoutRoot.WidthRequest = 250; } List<String> employeeList = new List<String>(); employeeList.Add("Frank"); employeeList.Add("James"); employeeList.Add("Steve"); employeeList.Add("Lucas"); employeeList.Add("Mark"); employeeList.Add("Michael"); comboBox.ComboBoxSource = employeeList; } } } <file_sep>/Forms/PDF/PDF/Samples/ImageInsertion/ImageInsertion.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Parsing; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using System.Reflection; using SampleBrowser.Core; using Syncfusion.Pdf.Graphics; namespace SampleBrowser.PDF { public partial class ImageInsertion : SampleView { public ImageInsertion() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { // Create a new instance of PdfDocument class. PdfDocument document = new PdfDocument(); // Add a new page to the newly created document. PdfPage page = document.Pages.Add(); PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold); PdfGraphics g = page.Graphics; g.DrawString("JPEG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 40)); //Load JPEG image to stream. #if COMMONSB Stream jpgImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Xamarin_JPEG.jpg"); #else Stream jpgImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Xamarin_JPEG.jpg"); #endif //Load the JPEG image PdfImage jpgImage = new PdfBitmap(jpgImageStream); //Draw the JPEG image g.DrawImage(jpgImage,new Syncfusion.Drawing.RectangleF(0,70,515,215)); g.DrawString("PNG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 355)); //Load PNG image to stream. #if COMMONSB Stream pngImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Xamarin_PNG.png"); #else Stream pngImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Xamarin_PNG.png"); #endif //Load the PNG image PdfImage pngImage = new PdfBitmap(pngImageStream); //Draw the PNG image g.DrawImage(pngImage,new Syncfusion.Drawing.RectangleF(0,365,199,300)); MemoryStream stream = new MemoryStream(); //Save the PDF document document.Save(stream); stream.Position = 0; //Close the PDF document document.Close(true); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("ImageInsertion.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("ImageInsertion.pdf", "application/pdf", stream); } } } <file_sep>/Forms/Maps/Maps/Samples/BubbleVisualization/BubbleVisualizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] public class BubbleVisualizationViewModel { public BubbleVisualizationViewModel() { Countries = new ObservableCollection<BubbleVisualizationModel>(); Countries.Add(new BubbleVisualizationModel("China", 1393730000, 18.2)); Countries.Add(new BubbleVisualizationModel("India", 1336180000, 17.5)); Countries.Add(new BubbleVisualizationModel("United States", 327726000, 4.29)); Countries.Add(new BubbleVisualizationModel("Indonesia", 265015300, 3.47)); Countries.Add(new BubbleVisualizationModel("Pakistan", 209503000, 2.78)); Countries.Add(new BubbleVisualizationModel("Brazil", 201795000, 2.74)); Countries.Add(new BubbleVisualizationModel("Nigeria", 197306006, 2.53)); Countries.Add(new BubbleVisualizationModel("Bangladesh", 165086000, 2.16)); Countries.Add(new BubbleVisualizationModel("Russia", 146877088, 1.92)); Countries.Add(new BubbleVisualizationModel("Japan", 126490000, 1.66)); Countries.Add(new BubbleVisualizationModel("Mexico", 124737789, 1.63)); Countries.Add(new BubbleVisualizationModel("Ethiopia", 107534882, 1.41)); Countries.Add(new BubbleVisualizationModel("Philippines", 106375000, 1.39)); Countries.Add(new BubbleVisualizationModel("Egypt", 97459100, 1.27)); Countries.Add(new BubbleVisualizationModel("Vietnam", 94660000, 1.24)); Countries.Add(new BubbleVisualizationModel("Germany", 82740900, 1.08)); Countries.Add(new BubbleVisualizationModel("Iran", 81737800, 1.07)); Countries.Add(new BubbleVisualizationModel("Turkey", 80810525, 1.06)); Countries.Add(new BubbleVisualizationModel("Thailand", 69183173, 0.91)); Countries.Add(new BubbleVisualizationModel("France", 67297000, 0.88)); Countries.Add(new BubbleVisualizationModel("United Kingdom", 66040229, 0.86)); Countries.Add(new BubbleVisualizationModel("Italy", 60436469, 0.79)); Countries.Add(new BubbleVisualizationModel("South Africa", 57725600, 0.76)); Countries.Add(new BubbleVisualizationModel("Colombia", 49918600, 0.65)); Countries.Add(new BubbleVisualizationModel("Spain", 46659302, 0.61)); Countries.Add(new BubbleVisualizationModel("Argentina", 44494502, 0.58)); Countries.Add(new BubbleVisualizationModel("Poland", 38433600, 0.5)); Countries.Add(new BubbleVisualizationModel("Canada", 37206700, 0.48)); Countries.Add(new BubbleVisualizationModel("Saudi Arabia", 33413660, 0.44)); Countries.Add(new BubbleVisualizationModel("Malaysia", 32647000, 0.42)); Countries.Add(new BubbleVisualizationModel("Nepal", 29218867, 0.38)); Countries.Add(new BubbleVisualizationModel("Australia", 25015400, 0.32)); Countries.Add(new BubbleVisualizationModel("Kazakhstan", 18253300, 0.24)); Countries.Add(new BubbleVisualizationModel("Cambodia", 16069921, 0.21)); Countries.Add(new BubbleVisualizationModel("Belgium", 11414214, 0.15)); Countries.Add(new BubbleVisualizationModel("Greece", 10768193, 0.14)); Countries.Add(new BubbleVisualizationModel("Sweden", 10171524, 0.13)); Countries.Add(new BubbleVisualizationModel("Somalia", 15181925, 0.12)); Countries.Add(new BubbleVisualizationModel("Austria", 8830487, 0.12)); Countries.Add(new BubbleVisualizationModel("Bulgaria", 7050034, 0.092)); } public ObservableCollection<BubbleVisualizationModel> Countries { get; set; } } } <file_sep>/Forms/DataForm/DataForm/Samples/ContactForm/Helpers/SfDataFormBehavior.cs #region Copyright // <copyright file="SfDataFormBehavior.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.DataForm; using Xamarin.Forms; /// <summary> /// User defined behaviour to respond arbitrary conditions and events of DataForm. /// </summary> public class SfDataFormBehavior : Behavior<ContentPage> { /// <summary> /// DataForm control to edit the data fields of any data object /// </summary> private Syncfusion.XForms.DataForm.SfDataForm dataForm; /// <summary> /// Represents the view model of the <see cref="ContactListViewModel" /> class. /// </summary> private ContactListViewModel viewModel; /// <summary> /// Represents the contact label button. /// </summary> private Button contactLabel; /// <summary> /// Represents the edit and done button. /// </summary> private Button editAndDoneButton; /// <summary> /// Attaches to the superclass and then calls the OnAttachedTo method on this object. /// </summary> /// <param name="bindable">The bindable object to which the behavior was attached.</param> protected override void OnAttachedTo(ContentPage bindable) { this.dataForm = bindable.FindByName<Syncfusion.XForms.DataForm.SfDataForm>("dataForm"); this.dataForm.LayoutManager = new DataFormLayoutManagerExt(this.dataForm); this.contactLabel = bindable.FindByName<Button>("contactLabel"); this.editAndDoneButton = bindable.FindByName<Button>("editButton"); this.dataForm.RegisterEditor("SaveTo", "Segment"); this.dataForm.RegisterEditor("EmailType", "DropDown"); this.dataForm.RegisterEditor("ContactType", "DropDown"); this.dataForm.RegisterEditor("AddressTypes", "DropDown"); this.dataForm.BindingContextChanged += this.OnBindingContextChanged; this.viewModel = bindable.BindingContext as ContactListViewModel; this.dataForm.AutoGeneratingDataFormItem += this.OnAutoGeneratingDataFormItem; this.dataForm.Validating += this.OnValidating; base.OnAttachedTo(bindable); } /// <summary> /// Calls the OnDetachingFrom method and then detaches from the superclass. /// </summary> /// <param name="bindable">The bindable object from which the behavior was detached.</param> protected override void OnDetachingFrom(ContentPage bindable) { base.OnDetachingFrom(bindable); this.contactLabel.Text = "EditContact"; this.dataForm.AutoGeneratingDataFormItem -= this.OnAutoGeneratingDataFormItem; this.dataForm.BindingContextChanged -= this.OnBindingContextChanged; this.dataForm.Validating -= this.OnValidating; } /// <summary> /// Occurs when Binding context of the data form is changed. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Event arguments of binding context changed event.</param> private void OnBindingContextChanged(object sender, EventArgs e) { this.viewModel = this.dataForm.BindingContext as ContactListViewModel; this.viewModel.RefreshLayout = false; this.viewModel.IsVisible = true; if (this.viewModel.IsNewContact) { this.dataForm.IsReadOnly = false; this.contactLabel.Text = "Add Contact"; this.viewModel.IsNewContact = false; this.editAndDoneButton.Text = "Done"; } } /// <summary> /// Validates the value in the data form fields. /// </summary> /// <param name="sender">Sender object.</param> /// <param name="e">Event arguments of OnValidating event.</param> private void OnValidating(object sender, ValidatingEventArgs e) { if (e.PropertyName.Equals("ContactNumber")) { if (e.Value != null && e.Value.ToString().Length > 10) { e.ErrorMessage = "Phone number should not exceed 10 digits."; e.IsValid = false; } } } /// <summary> /// Raised to set read only property and cancel the some properties. /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">Contains arguments of auto generating data form event</param> private void OnAutoGeneratingDataFormItem(object sender, AutoGeneratingDataFormItemEventArgs e) { if (e.DataFormItem != null) { if (!this.viewModel.RefreshLayout) { if (e.DataFormItem.Name.Equals("MiddleName") || e.DataFormItem.Name.Equals("LastName") || e.DataFormItem.Name.Equals("Notes")) { e.Cancel = true; } } if (e.DataFormItem.Name.Equals("ContactNumber")) { var dataFormMaskedItem = e.DataFormItem as DataFormMaskedEditTextItem; dataFormMaskedItem.KeyBoard = Keyboard.Telephone; dataFormMaskedItem.CutCopyMaskFormat = Syncfusion.XForms.MaskedEdit.MaskFormat.ExcludePromptAndLiterals; dataFormMaskedItem.SkipLiterals = true; dataFormMaskedItem.ValueMaskFormat = Syncfusion.XForms.MaskedEdit.MaskFormat.ExcludePromptAndLiterals; e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { LeadingView = new Label() { VerticalTextAlignment = Device.RuntimePlatform == Device.iOS ? TextAlignment.Center : TextAlignment.Start, FontSize = Device.RuntimePlatform == Device.iOS ? 18 : 24, Text = "F", FontFamily = Device.RuntimePlatform == Device.iOS ? "ContactsIcons" : Device.RuntimePlatform == Device.Android ? "ContactsIcons.ttf#ContactsIcons" : "Assets/Fonts/ContactsIcons.ttf#ContactsIcons" }, ReserveSpaceForAssistiveLabels = true }; } else if (e.DataFormItem.Name.Equals("Email")) { (e.DataFormItem as DataFormTextItem).KeyBoard = Keyboard.Email; e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { LeadingView = new Label() { FontSize = Device.RuntimePlatform == Device.iOS ? 18 : 24, Text = "G", FontFamily = Device.RuntimePlatform == Device.iOS ? "ContactsIcons" : Device.RuntimePlatform == Device.Android ? "ContactsIcons.ttf#ContactsIcons" : "Assets/Fonts/ContactsIcons.ttf#ContactsIcons" } }; } else if (e.DataFormItem.Name.Equals("ContactName")) { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { LeadingView = new Label() { VerticalTextAlignment = Device.RuntimePlatform == Device.iOS ? TextAlignment.Center : TextAlignment.Start, FontSize = Device.RuntimePlatform == Device.iOS ? 18 : 24, Text = "A", FontFamily = Device.RuntimePlatform == Device.iOS ? "ContactsIcons":Device.RuntimePlatform == Device.Android ? "ContactsIcons.ttf#ContactsIcons" : "Assets/Fonts/ContactsIcons.ttf#ContactsIcons" } }; } else if (e.DataFormItem.Name.Equals("MiddleName")) { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { LeadingView = new Label() { VerticalTextAlignment = Device.RuntimePlatform == Device.iOS ? TextAlignment.Center : TextAlignment.Start, FontSize = Device.RuntimePlatform == Device.iOS ? 18 : 24, Text = "A", FontFamily = Device.RuntimePlatform == Device.iOS ? "ContactsIcons":Device.RuntimePlatform == Device.Android ? "ContactsIcons.ttf#ContactsIcons" : "Assets/Fonts/ContactsIcons.ttf#ContactsIcons" } }; } else if (e.DataFormItem.Name.Equals("LastName")) { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { LeadingView = new Label() { VerticalTextAlignment = Device.RuntimePlatform == Device.iOS ? TextAlignment.Center : TextAlignment.Start, FontSize = Device.RuntimePlatform == Device.iOS ? 18 : 24, Text = "A", FontFamily = Device.RuntimePlatform == Device.iOS ? "ContactsIcons" : Device.RuntimePlatform == Device.Android ? "ContactsIcons.ttf#ContactsIcons" : "Assets/Fonts/ContactsIcons.ttf#ContactsIcons" } }; } else if (e.DataFormItem.Name.Equals("ContactImage")) { e.Cancel = true; } else if (e.DataFormItem.Name.Equals("BirthDate")) { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { LeadingView = new Label() { FontSize = Device.RuntimePlatform == Device.iOS ? 18 : 24, Text = "H", FontFamily = Device.RuntimePlatform == Device.iOS ? "ContactsIcons" : Device.RuntimePlatform == Device.Android ? "ContactsIcons.ttf#ContactsIcons" : "Assets/Fonts/ContactsIcons.ttf#ContactsIcons" } }; } else if (e.DataFormItem.Name.Equals("GroupName")) { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { LeadingView = new Label() { FontSize = Device.RuntimePlatform == Device.iOS ? 18 : 24, Text = "B", FontFamily = Device.RuntimePlatform == Device.iOS ? "ContactsIcons" : Device.RuntimePlatform == Device.Android ? "ContactsIcons.ttf#ContactsIcons" : "Assets/Fonts/ContactsIcons.ttf#ContactsIcons" } }; } else if (e.DataFormItem.Name.Equals("Address")) { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { LeadingView = new Label() { VerticalTextAlignment = Device.RuntimePlatform == Device.iOS ? TextAlignment.Center : TextAlignment.Start, FontSize = Device.RuntimePlatform == Device.iOS ? 18 : 24, Text = "I", FontFamily = Device.RuntimePlatform == Device.iOS ? "ContactsIcons" : Device.RuntimePlatform == Device.Android ? "ContactsIcons.ttf#ContactsIcons" : "Assets/Fonts/ContactsIcons.ttf#ContactsIcons" } }; } else if (e.DataFormItem.Name.Equals("Notes")) { e.DataFormItem.TextInputLayoutSettings = new TextInputLayoutSettings() { LeadingView = new Label() { VerticalTextAlignment = Device.RuntimePlatform == Device.iOS ? TextAlignment.Center : TextAlignment.Start, FontSize = Device.RuntimePlatform == Device.iOS ? 18 : 24, Text = "C", FontFamily = Device.RuntimePlatform == Device.iOS ? "ContactsIcons" : Device.RuntimePlatform == Device.Android ? "ContactsIcons.ttf#ContactsIcons" : "Assets/Fonts/ContactsIcons.ttf#ContactsIcons" } }; } else if (e.DataFormItem.Name.Equals("ContactType")) { e.DataFormItem.LayoutOptions = LayoutType.Default; } else if (e.DataFormItem.Name.Equals("EmailType")) { e.DataFormItem.LayoutOptions = LayoutType.Default; } else if (e.DataFormItem.Name.Equals("AddressTypes")) { e.DataFormItem.LayoutOptions = LayoutType.Default; } else if (e.DataFormItem.Name.Equals("SaveTo")) { e.DataFormItem.LayoutOptions = LayoutType.Default; } this.ChangeItemOrder(e.DataFormItem); } if (e.DataFormGroupItem != null) { e.DataFormGroupItem.AllowExpandCollapse = false; } } private void ChangeItemOrder(DataFormItem dataFormItem) { if(dataFormItem.Name == "ContactNumber") { dataFormItem.Order = App.Current.MainPage.FlowDirection != FlowDirection.RightToLeft ? 4 : 5; } if (dataFormItem.Name == "ContactType") { dataFormItem.Order = App.Current.MainPage.FlowDirection != FlowDirection.RightToLeft ? 5 : 4; } if (dataFormItem.Name == "Email") { dataFormItem.Order = App.Current.MainPage.FlowDirection != FlowDirection.RightToLeft ? 6 : 7; } if (dataFormItem.Name == "EmailType") { dataFormItem.Order = App.Current.MainPage.FlowDirection != FlowDirection.RightToLeft ? 7 : 6; } if (dataFormItem.Name == "Address") { dataFormItem.Order = App.Current.MainPage.FlowDirection != FlowDirection.RightToLeft ? 8 : 9; } if (dataFormItem.Name == "AddressTypes") { dataFormItem.Order = App.Current.MainPage.FlowDirection != FlowDirection.RightToLeft ? 9 : 8; } } } }<file_sep>/iOS/SampleBrowser/Controllers/SampleViewController.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Foundation; using CoreGraphics; namespace SampleBrowser { public class SampleViewController : UIViewController { bool codeVisible, codeVisited; bool optionVisible; bool showOptions; public NSIndexPath indexPath; SampleView sample; UIView fadeOutView; UIBarButtonItem codeViewButton; UIBarButtonItem optionButton; UICollectionView collectionView; UICollectionViewFlowLayout layout; UILabel overlayTags; bool isKeyboardVisible = true, isOptionVisible = false; bool isOptionsKeyboard = false; // iOS 10 issue fix for resetting last button color public UIButton deselectedButton; public UIButton deselectedButtonX; public UIView optionView { get; set; } public string ControlName { get; set;} public string sampleNameToLoad { get; set; } public NSArray SamplesCollection; NSObject obs1; NSObject obs2; public SampleViewController(NSIndexPath indexPath) { //Fix to restrict setting automatic inset for scrollview and tableview this.AutomaticallyAdjustsScrollViewInsets = false; this.indexPath = indexPath; SamplesCollection = new NSArray(); } public override void ViewDidLoad() { base.ViewDidLoad(); this.View.BackgroundColor = UIColor.White; this.NavigationItem.SetRightBarButtonItem(codeViewButton, true); this.NavigationController.InteractivePopGestureRecognizer.Enabled = false; optionVisible = false; codeVisible = false; showOptions = false; overlayTags = new UILabel(); overlayTags.Layer.CornerRadius = 20f; overlayTags.TextColor = UIColor.White; overlayTags.TextAlignment = UITextAlignment.Center; overlayTags.ClipsToBounds = true; overlayTags.Alpha = 0.0f; overlayTags.Font = UIFont.SystemFontOfSize(14); overlayTags.BackgroundColor = UIColor.FromRGB(101.0f / 255.0f, 101.0f / 255.0f, 101.0f / 255.0f); overlayTags.Layer.ZPosition = 1000; this.View.AddSubview(overlayTags); fadeOutView = new UIView(this.View.Bounds); fadeOutView.BackgroundColor = UIColor.FromRGBA(0.537f, 0.537f, 0.537f, 0.3f); UITapGestureRecognizer singleFingerTap = new UITapGestureRecognizer(); singleFingerTap.AddTarget(() => HandleSingleTap(singleFingerTap)); fadeOutView.AddGestureRecognizer(singleFingerTap); codeViewButton = new UIBarButtonItem(); codeViewButton.Image = UIImage.FromBundle("Controls/Tags/Viewcode"); codeViewButton.Style = UIBarButtonItemStyle.Plain; codeViewButton.Target = this; codeViewButton.Clicked += ViewCode; optionButton = new UIBarButtonItem(); optionButton.Image = UIImage.FromBundle("Controls/Tags/Option"); optionButton.Style = UIBarButtonItemStyle.Plain; optionButton.Target = this; optionButton.Clicked += OpenOptionView; this.LoadCollectionView(); this.LoadSample(); } private void LoadCollectionView() { layout = new UICollectionViewFlowLayout(); layout.ScrollDirection = UICollectionViewScrollDirection.Horizontal; collectionView = new UICollectionView(CGRect.Empty, layout); collectionView.DataSource = new TextCollectionDataSource(this); collectionView.Delegate = new TextCollectionDelegate(this); collectionView.BackgroundColor = Utility.BackgroundColor; UINib nib = UINib.FromName("TextCell", null); collectionView.RegisterNibForCell(nib, "textReuseCell"); this.View.AddSubview(collectionView); } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); if (!Utility.IsIPad) { obs1 = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, delegate (NSNotification n) { if (isKeyboardVisible && isOptionVisible) { var kbdRect = UIKeyboard.FrameEndFromNotification(n); var duration = UIKeyboard.AnimationDurationFromNotification(n); var frame = optionView.Frame; frame.Y = 66; frame.Height = this.View.Frame.Height - kbdRect.Height; UIView.BeginAnimations("ResizeForKeyboard"); UIView.SetAnimationDuration(duration); optionView.Frame = frame; UIView.CommitAnimations(); isKeyboardVisible = false; isOptionsKeyboard = true; } }); obs2 = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, delegate (NSNotification n) { if (isOptionsKeyboard && isOptionVisible) { var duration = UIKeyboard.AnimationDurationFromNotification(n); UIView.BeginAnimations("ResizeForKeyboard"); UIView.SetAnimationDuration(duration); optionView.Frame = new CGRect(0, this.View.Bounds.Height - this.View.Bounds.Height / 1.5, this.View.Bounds.Width, this.View.Bounds.Height / 1.5); UIView.CommitAnimations(); isKeyboardVisible = true; isOptionsKeyboard = false; } }); } if (indexPath != null) { var cell = collectionView.CellForItem(indexPath); if (cell != null) { deselectedButton = (UIButton)cell.ViewWithTag(500); deselectedButtonX = (UIButton)cell.ViewWithTag(510); } collectionView.SelectItem(indexPath, true, UICollectionViewScrollPosition.CenteredHorizontally); } if(!codeVisited) UIView.Animate(0.5, 0, UIViewAnimationOptions.CurveLinear, () => { overlayTags.Alpha = 1.0f; }, () => { UIView.Animate(3.0, () => { overlayTags.Alpha = 0.0f; }); } ); } public void LoadSample() { overlayTags.Alpha = 0.0f; overlayTags.Hidden = false; codeVisited = false; if (sample != null && sample.IsDescendantOfView(this.View)) { if (sample.OptionView != null) { sample.OptionView.RemoveFromSuperview(); sample.OptionView.Dispose(); sample.OptionView = null; } foreach (UIView view in sample.Subviews) { view.RemoveFromSuperview(); view.Dispose(); } sample.RemoveFromSuperview(); sample.Dispose(); } Control control = SamplesCollection.GetItem<Control>((nuint)indexPath.Row); ControlName = control.ControlName; sampleNameToLoad = control.Name; if (control.Tag == "NEW") { overlayTags.Text = " New Sample"; } else if (control.Tag == "UPDATED") { overlayTags.Text = " Updated Sample"; } else { overlayTags.Hidden = true; } NSString dispName = control.DisplayName; this.Title = string.IsNullOrEmpty(dispName) ? dispName : sampleNameToLoad; sampleNameToLoad = sampleNameToLoad.Replace(" ", string.Empty); string classname = "SampleBrowser." + sampleNameToLoad; if (sampleNameToLoad == "100% Stacked Area") { classname = "SampleBrowser.StackingArea100"; } else if (sampleNameToLoad == "100% Stacked Column") { classname = "SampleBrowser.StackingColumn100"; } else if (sampleNameToLoad == "100% Stacked Bar") { classname = "SampleBrowser.StackingBar100"; } if (classname == "SampleBrowser.CustomizationKanban") this.NavigationController.NavigationBar.BarTintColor = UIColor.FromRGB(211.0f / 255.0f, 51.0f / 255.0f, 54.0f / 255.0f); else this.NavigationController.NavigationBar.BarTintColor = Utility.ThemeColor; Type sampleClass = Type.GetType(classname); if (sampleClass != null) { sample = Activator.CreateInstance(sampleClass) as SampleView; sample.RemoveFromSuperview(); this.View.AddSubview(sample); this.NavigationItem.RightBarButtonItems = null; this.View.AddSubview(sample); this.View.AddSubview(fadeOutView); fadeOutView.Hidden = true; if (sample.OptionView != null) { if (!Utility.IsIPad) { optionView = new UIView(); optionView.Frame = new CGRect(0, this.View.Bounds.Height, this.View.Bounds.Width, this.View.Bounds.Height / 1.5); UIMarginLabel title = new UIMarginLabel(); title.Text = "PROPERTIES"; title.Insets = new UIEdgeInsets(0, 20, 0, 0); title.Frame = new CGRect(0, 0, this.View.Frame.Size.Width, 50); title.BackgroundColor = UIColor.Clear; optionView.AddSubview(title); UIButton close = new UIButton(); close.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); close.BackgroundColor = UIColor.FromRGBA(1, 1, 1, 0.95f); close.SetTitle("X", UIControlState.Normal); close.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; close.VerticalAlignment = UIControlContentVerticalAlignment.Center; close.TouchUpInside += (object sender, EventArgs e) => { this.View.EndEditing(true); HideOptionView(); }; close.Frame = new CGRect(this.View.Frame.Width - 45, 0, 45, 45); optionView.AddSubview(close); UITapGestureRecognizer singleFingerTap = new UITapGestureRecognizer(); singleFingerTap.AddTarget(() => HandleSingleTap(singleFingerTap)); close.AddGestureRecognizer(singleFingerTap); sample.OptionView.Frame = new CGRect(0, 40, optionView.Frame.Width, optionView.Frame.Height - 30); optionView.AddSubview(sample.OptionView); optionView.BackgroundColor = UIColor.FromRGBA(1, 1, 1, 0.95f); if (control.ControlName != "DataGrid" && control.ControlName != "DataSource") { UITapGestureRecognizer tap = new UITapGestureRecognizer(); tap.AddTarget(() => HideKeyboard(tap)); optionView.AddGestureRecognizer(tap); } this.View.AddSubview(optionView); } else optionView = sample.OptionView; this.NavigationItem.SetRightBarButtonItems(new UIBarButtonItem[] { optionButton, codeViewButton }, true); } else { this.NavigationItem.SetRightBarButtonItem(codeViewButton, true); } } UIView.Animate(0.5, 0, UIViewAnimationOptions.CurveLinear, () => { overlayTags.Alpha = 1.0f; }, () => { UIView.Animate(3.0, () => { overlayTags.Alpha = 0.0f; }); } ); } void HideKeyboard(UITapGestureRecognizer gesture) { this.View.EndEditing(true); } public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); float collectionViewHeight = 50; if (SamplesCollection.Count == 0 || SamplesCollection.Count == 1) collectionViewHeight = 0; sample.Frame = new CGRect(this.View.Frame.X, this.View.Frame.Y + 66, this.View.Frame.Width, this.View.Frame.Height - 66 - collectionViewHeight); collectionView.Frame = new CGRect(0, this.View.Frame.Size.Height - collectionViewHeight, this.View.Frame.Width, collectionViewHeight); overlayTags.Frame = new CGRect(sample.Frame.Width/2 - 75, this.View.Frame.Height - 100 , 150, 35); } void ViewCode(object sender, EventArgs ea) { codeVisited = true; codeVisible = true; CodeViewController viewController = new CodeViewController(); viewController.ControlName = ControlName; viewController.SampleName = sampleNameToLoad; this.NavigationItem.BackBarButtonItem = new UIBarButtonItem("Back", UIBarButtonItemStyle.Plain, null); this.NavigationController.PushViewController(viewController, true); } void OpenOptionView(object sender, EventArgs ea) { optionVisible = true; if (!Utility.IsIPad) { if (!showOptions) this.ShowOptionView(); else this.HideOptionView(); showOptions = !showOptions; } else { //iPad view, present PopOver OptionViewController optionController = new OptionViewController(); optionController.OptionView = optionView; UIPopoverController popover = new UIPopoverController(optionController); popover.SetPopoverContentSize(new CGSize(320.0, 400.0), true); UIBarButtonItem barbtn = sender as UIBarButtonItem; UIView view = barbtn.ValueForKey(new NSString("view")) as UIView; CGRect frame = new CGRect(this.View.Frame.Width - view.Frame.Width, view.Frame.Y + 23, view.Frame.Width, view.Frame.Height); popover.PresentFromRect(frame, this.View, UIPopoverArrowDirection.Up, true); } } void ShowOptionView() { this.View.EndEditing(true); isOptionVisible = true; isKeyboardVisible = true; fadeOutView.Hidden = false; UIView.Animate(0.3, () => { optionView.Frame = new CGRect(0, this.View.Bounds.Height - this.View.Bounds.Height / 1.5, this.View.Bounds.Width, this.View.Bounds.Height / 1.5); }); } void HideOptionView() { UIView.Animate(0.4, () => { optionView.Frame = new CGRect(0, this.View.Bounds.Height, this.View.Bounds.Width, this.View.Bounds.Height / 1.5); },()=>sample.OnOptionsViewClosed()); fadeOutView.Hidden = true; isOptionVisible = false; this.View.EndEditing(true); } void HandleSingleTap(UITapGestureRecognizer gesture) { showOptions = false; HideOptionView(); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); this.NavigationController.SetNavigationBarHidden(false, false); if (sampleNameToLoad == "CustomizationKanban") this.NavigationController.NavigationBar.BarTintColor = UIColor.FromRGB(211.0f / 255.0f, 51.0f / 255.0f, 54.0f / 255.0f); else this.NavigationController.NavigationBar.BarTintColor = Utility.ThemeColor; optionVisible = false; codeVisible = false; overlayTags.Alpha = 0f; } public override void ViewDidDisappear(bool animated) { base.ViewWillDisappear(animated); if (!Utility.IsIPad) { NSNotificationCenter.DefaultCenter.RemoveObserver(obs1); NSNotificationCenter.DefaultCenter.RemoveObserver(obs2); } if (this.IsMovingFromParentViewController) { //moving back if (!(optionVisible || codeVisible )) { if (sample != null) { if (sample.OptionView != null) { sample.OptionView.RemoveFromSuperview(); sample.OptionView.Dispose(); sample.OptionView = null; } Utility.DisposeEx(sample); sample.RemoveFromSuperview(); sample.Dispose(); sample = null; } if (optionView != null) { //optionView.RemoveFromSuperview(); optionView.Dispose(); optionView = null; } if (collectionView != null) { collectionView.Dispose(); collectionView = null; } Utility.DisposeEx(this.View); this.Dispose(); } } } } public class TextCollectionDataSource : UICollectionViewDataSource { SampleViewController controller; public TextCollectionDataSource(SampleViewController controller) { this.controller = controller; } public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) { UICollectionViewCell cell = (UICollectionViewCell)collectionView.DequeueReusableCell("textReuseCell", indexPath); cell.BackgroundColor = UIColor.Clear; UIButton label = (UIButton)cell.ViewWithTag(500); UIButton labelX = (UIButton)cell.ViewWithTag(510); labelX.TouchUpInside += (sender, e) => { if (controller.indexPath != indexPath) { HighlightCell(label, labelX, collectionView, indexPath); } }; label.TouchUpInside += (sender, e) => { if (controller.indexPath != indexPath) { HighlightCell(label, labelX, collectionView, indexPath); } }; label.SetTitle(string.Empty, UIControlState.Normal); labelX.SetTitle(string.Empty, UIControlState.Normal); Control item = controller.SamplesCollection.GetItem<Control>((nuint)indexPath.Row); NSString sampleName = item.Name; NSString dispName = item.DisplayName; dispName = string.IsNullOrEmpty(dispName) ? sampleName : dispName; UIImageView tag = (UIImageView)cell.ViewWithTag(502); if (item.Tag == "NEW") { label.SetTitle(dispName, UIControlState.Normal); tag.Image = UIImage.FromBundle("Controls/Tags/x_new.png"); } else if (item.Tag == "UPDATED") { label.SetTitle(dispName, UIControlState.Normal); tag.Image = UIImage.FromBundle("Controls/Tags/x_update.png"); } else { labelX.SetTitle(dispName, UIControlState.Normal); tag.Image = null; } label.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f),UIControlState.Normal); labelX.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); label.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Highlighted); labelX.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Highlighted); if (indexPath.Row == (int)controller.indexPath.Row) { label.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); labelX.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); } return cell; } public override nint GetItemsCount(UICollectionView collectionView, nint section) { return (nint)controller.SamplesCollection.Count; } public void HighlightCell(UIButton label, UIButton labelX, UICollectionView collectionView, NSIndexPath indexPath) { if (controller.indexPath != indexPath) { foreach (UICollectionViewCell collectionViewCell in collectionView.VisibleCells) { UIButton label1 = (UIButton)collectionViewCell.ViewWithTag(510); UIButton label2 = (UIButton)collectionViewCell.ViewWithTag(510); label1.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); label2.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); } if (controller.deselectedButton != null) { controller.deselectedButton.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); controller.deselectedButtonX.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); } collectionView.SelectItem(indexPath, true, UICollectionViewScrollPosition.CenteredHorizontally); controller.indexPath = indexPath; controller.deselectedButton = label; controller.deselectedButtonX = labelX; Control control = controller.SamplesCollection.GetItem<Control>((nuint)indexPath.Row); if (control.ControlName.Equals("DataGrid")) { label.Alpha = 0.5f; labelX.Alpha = 0.5f; NSTimer.CreateScheduledTimer(new TimeSpan(0, 0, 0, 0, 2), (t) => { label.Alpha = 1f; labelX.Alpha = 1f; controller.LoadSample(); }); }
 else
 controller.LoadSample(); label.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); labelX.SetTitleColor(Utility.ThemeColor, UIControlState.Normal); } } } public class TextCollectionDelegate : UICollectionViewDelegateFlowLayout { SampleViewController controller; public TextCollectionDelegate(SampleViewController controller) { this.controller = controller; } public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath) { if (controller.indexPath != indexPath) { var cell = collectionView.CellForItem(indexPath); cell.Alpha = 0.5f; if (cell != null) { UIButton labelX = (UIButton)cell.ViewWithTag(510); labelX.SendActionForControlEvents(UIControlEvent.TouchUpInside); } } } public override void ItemDeselected(UICollectionView collectionView, NSIndexPath indexPath) { var cell = collectionView.CellForItem(indexPath); if (cell != null) { UIButton label = (UIButton)cell.ViewWithTag(500); UIButton labelX = (UIButton)cell.ViewWithTag(510); label.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); labelX.SetTitleColor(UIColor.FromRGB(45.0f / 255.0f, 45.0f / 255.0f, 45.0f / 255.0f), UIControlState.Normal); } } public override CGSize GetSizeForItem(UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath) { Control control = controller.SamplesCollection.GetItem<Control>((nuint)indexPath.Row); NSString sampleName = control.Name; NSString dispName = control.DisplayName; NSString name = string.IsNullOrEmpty(dispName) ? sampleName : dispName; UIStringAttributes attribs = new UIStringAttributes { Font = UIFont.SystemFontOfSize(15) }; CGSize size = name.GetSizeUsingAttributes(attribs); if (string.IsNullOrEmpty(control.Tag)) return new CGSize(size.Width + 20, 50); else return new CGSize(size.Width + 40, 50); } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/DataPointSelection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Android.Graphics; using System.Collections.ObjectModel; using System.Collections.Generic; using System; using Com.Syncfusion.Navigationdrawer; namespace SampleBrowser { public class DataPointSelection : SamplePage { private TextView label; private TextView productLabel1; private TextView productLabel2; double sumOfTotalSeries1 = 0; double sumOfTotalSeries2 = 0; IList<DataPoint> datapoint; IList<DataPoint> datapoint1; List<String> selectionMode; ColumnSeries columnSeries; ColumnSeries columnSeries1; SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Product Sale 2016"; chart.SetBackgroundColor(Color.White); var primaryAxis = new CategoryAxis { LabelPlacement = LabelPlacement.BetweenTicks }; primaryAxis.Title.Text = "Month"; chart.PrimaryAxis = primaryAxis; var secondaryAxis = new NumericalAxis(); primaryAxis.ShowMajorGridLines = false; secondaryAxis.Title.Text = "Sales"; secondaryAxis.LabelStyle.LabelFormat = "$##.##"; chart.SecondaryAxis = secondaryAxis; columnSeries = new ColumnSeries { ItemsSource = MainPage.GetSelectionData(), XBindingPath = "XValue", YBindingPath = "YValue", Color = Color.ParseColor("#00BDAE"), SelectedDataPointColor = Color.ParseColor("#007168"), DataPointSelectionEnabled = true, EnableAnimation = true, Label = "Product A" }; chart.Series.Add(columnSeries); columnSeries1 = new ColumnSeries { ItemsSource = MainPage.GetSelectionData1(), XBindingPath = "XValue", YBindingPath = "YValue", Color = Color.ParseColor("#7F84E8"), SelectedDataPointColor = Color.ParseColor("#4A4FB2"), DataPointSelectionEnabled = true, EnableAnimation = true, Label = "Product B" }; chart.Series.Add(columnSeries1); datapoint = columnSeries.ItemsSource as IList<DataPoint>; datapoint1 = columnSeries1.ItemsSource as IList<DataPoint>; foreach (var data in datapoint) { sumOfTotalSeries1 += data.YValue; } foreach (var data in datapoint1) { sumOfTotalSeries2 += data.YValue; } chart.Behaviors.Add(new ChartSelectionBehavior()); chart.SelectionChanged += chart_SelectionChanged; label = new TextView(context){ TextSize = 15 }; label.Text = "Tap on a bar segment to select a data point."; label.SetPadding(5, 5, 5, 5); productLabel1 = new TextView(context) { TextSize = 15, Visibility = ViewStates.Gone, }; productLabel1.SetTextColor(Color.ParseColor("#007168")); productLabel1.SetPadding(5, 5, 5, 5); productLabel2 = new TextView(context) { TextSize = 15, Visibility = ViewStates.Gone, }; productLabel2.SetTextColor(Color.ParseColor("#4A4FB2")); productLabel2.SetPadding(5, 5, 5, 5); var layout = new LinearLayout(context){ Orientation = Android.Widget.Orientation.Vertical }; var layoutLabel = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Horizontal, LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent) }; layoutLabel.SetHorizontalGravity(GravityFlags.CenterHorizontal); layoutLabel.AddView(label); layoutLabel.AddView(productLabel1); layoutLabel.AddView(productLabel2); layout.AddView(layoutLabel); layout.AddView(chart); return layout; } private void chart_SelectionChanged(object sender, SfChart.SelectionChangedEventArgs e) { var chart = sender as SfChart; var series = e.P1.SelectedSeries; if (series == null) return; if (chart.EnableSeriesSelection) { productLabel1.Visibility = ViewStates.Gone; productLabel2.Visibility = ViewStates.Gone; label.Visibility = ViewStates.Visible; if (columnSeries.IsSelected) { label.Text = series.Label + " | Total Sales : $" + sumOfTotalSeries1; return; } else if (columnSeries1.IsSelected) { label.Text = series.Label + " | Total Sales : $" + sumOfTotalSeries2; return; } label.Text = "Tap on a bar segment to select a series"; } else { productLabel1.Visibility = ViewStates.Visible; productLabel2.Visibility = ViewStates.Visible; label.Visibility = ViewStates.Gone; var selectedindex = e.P1.SelectedDataPointIndex; var seriesIndex = chart.Series.IndexOf(e.P1.SelectedSeries); if (selectedindex < 0) { if (seriesIndex == 0) productLabel1.Text = "Tap on a bar segment"; else productLabel2.Text = "Tap on a bar segment"; return; } else { if (seriesIndex == 0) { var x = datapoint[selectedindex].XValue; var y = datapoint[selectedindex].YValue; productLabel1.Text = "Month : " + x + ", Sales : $" + y; } else if (seriesIndex == 1) { var x = datapoint1[selectedindex].XValue; var y = datapoint1[selectedindex].YValue; productLabel2.Text = "Month : " + x + ", Sales : $" + y; } } } } public override View GetPropertyWindowLayout(Context context) { int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; LinearLayout propertylayout = new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams( width * 2, 5); layoutParams1.SetMargins(0, 20, 0, 0); TextView selection = new TextView(context); selection.TextSize = 20; selection.Text = "Selection"; selection.SetPadding(5, 20, 0, 20); Spinner selectLabelMode = new Spinner(context, SpinnerMode.Dialog); selectionMode = new List<String>() { "Data Point Selection", "Series Selection" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, selectionMode); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += SelectLabelMode_ItemSelected; SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); propertylayout.AddView(selection); propertylayout.AddView(selectLabelMode); propertylayout.AddView(separate, layoutParams1); return propertylayout; } private void SelectLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = selectionMode[e.Position]; if (selectedItem.Equals("Data Point Selection")) { chart.EnableSeriesSelection = false; } else if (selectedItem.Equals("Series Selection")) { chart.EnableSeriesSelection = true; } } public override void OnApplyChanges() { base.OnApplyChanges(); } } }<file_sep>/Android/SampleBrowser/Samples/DataSource/Model/BookDetails.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Graphics; using System; using System.ComponentModel; namespace SampleBrowser { public class BookDetails : INotifyPropertyChanged { public BookDetails() { } #region private variables private int bookID; private string customerName; private int price; private string bookName; private Bitmap customerImage; #endregion #region Public Properties public int BookID { get { return bookID; } set { this.bookID = value; RaisePropertyChanged("BookID"); } } public Bitmap CustomerImage { get { return this.customerImage; } set { this.customerImage = value; RaisePropertyChanged("CustomerImage"); } } public string CustomerName { get { return this.customerName; } set { this.customerName = value; RaisePropertyChanged("FirstName"); } } public string BookName { get { return bookName; } set { this.bookName = value; RaisePropertyChanged("BookName"); } } public int Price { get { return price; } set { this.price = value; RaisePropertyChanged("Price"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Forms/PdfViewer/PdfViewer/Samples/Model/DocumentData.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser.SfPdfViewer { public static class DocumentData { public static IList<Document> DocumentList { get; private set; } static DocumentData() { DocumentList = new List<Document>(); DocumentList.Add(new Document("F# Succinctly")); DocumentList.Add(new Document("GIS Succinctly")); DocumentList.Add(new Document("HTTP Succinctly")); DocumentList.Add(new Document("JavaScript Succinctly")); } } } <file_sep>/Android/SampleBrowser/Samples/Sunburst/DrillDown.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Syncfusion.SfSunburstChart.Android; namespace SampleBrowser { [Preserve(AllMembers = true)] public class DrillDown : SamplePage { SfSunburstChart chart; public ObservableCollection<SunburstModel> DataSource { get; set; } public override View GetSampleContent(Context context) { this.DataSource = new ObservableCollection<SunburstModel> { new SunburstModel { Country = "USA", JobDescription = "Sales", JobGroup="Executive", EmployeesCount = 50 }, new SunburstModel { Country = "USA", JobDescription = "Sales", JobGroup = "Analyst", EmployeesCount = 40 }, new SunburstModel { Country = "USA", JobDescription = "Marketing", EmployeesCount = 40 }, new SunburstModel { Country = "USA", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 35 }, new SunburstModel { Country = "USA", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 175 }, new SunburstModel { Country = "USA", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 70 }, new SunburstModel { Country = "USA", JobDescription = "Management", EmployeesCount = 40 }, new SunburstModel { Country = "USA", JobDescription = "Accounts", EmployeesCount = 60 }, new SunburstModel { Country = "India", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 33 }, new SunburstModel { Country = "India", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 125 }, new SunburstModel { Country = "India", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 60 }, new SunburstModel { Country = "India", JobDescription = "HR Executives", EmployeesCount = 70 }, new SunburstModel { Country = "India", JobDescription = "Accounts", EmployeesCount = 45 }, new SunburstModel { Country = "Germany", JobDescription = "Sales", JobGroup = "Executive", EmployeesCount = 30 }, new SunburstModel { Country = "Germany", JobDescription = "Sales", JobGroup = "Analyst", EmployeesCount = 40 }, new SunburstModel { Country = "Germany", JobDescription = "Marketing", EmployeesCount = 50 }, new SunburstModel { Country = "Germany", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 40 }, new SunburstModel { Country = "Germany", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 65 }, new SunburstModel { Country = "Germany", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 27 }, new SunburstModel { Country = "Germany", JobDescription = "Management", EmployeesCount = 33 }, new SunburstModel { Country = "Germany", JobDescription = "Accounts", EmployeesCount = 55 }, new SunburstModel { Country = "UK", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 25 }, new SunburstModel { Country = "UK", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 96 }, new SunburstModel { Country = "UK", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 55 }, new SunburstModel { Country = "UK", JobDescription = "HR Executives", EmployeesCount = 60 }, new SunburstModel { Country = "UK", JobDescription = "Accounts", EmployeesCount = 30 } }; chart = new SfSunburstChart(context); chart.ItemsSource = DataSource; chart.Radius = 0.95; chart.ValueMemberPath = "EmployeesCount"; var levels = new SunburstLevelCollection() { new SunburstHierarchicalLevel() { GroupMemberPath = "Country"}, new SunburstHierarchicalLevel() { GroupMemberPath = "JobDescription"}, new SunburstHierarchicalLevel() { GroupMemberPath = "JobGroup"}, new SunburstHierarchicalLevel() { GroupMemberPath = "JobRole"} }; chart.Levels = levels; chart.Title.IsVisible = true; chart.Title.Margin = new Thickness(10, 40 * context.Resources.DisplayMetrics.Density, 5, 5); chart.Title.Text = "Employees Count"; chart.Title.TextSize = 20; chart.Legend.IsVisible = true; chart.DataLabel.ShowLabel = true; chart.DrilldownSettings.Enable = true; var label = new TextView(context); label.SetPadding(5, 5, 5, 5); label.Text = "Double tap on the segment to perform drill down."; label.TextSize = 16; label.SetTextColor(Color.Red); label.SetX(0); label.SetY(0); chart.AddView(label); return chart; } } }<file_sep>/iOS/SampleBrowser/Samples/DataGrid/Model/EmployeeInformationRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.Collections.Generic; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class EmployeeInformationRepository { public EmployeeInformationRepository () { } #region private variables private ObservableCollection<DateTime> BirthDates; private ObservableCollection<DateTime> HireDates; private Random random = new Random (); #endregion #region GetOrderDetails public ObservableCollection<EmployeeInformation> GetEmployeeDetails (int count) { setCity (); this.BirthDates = GetDateBetween (1980, 1992, count); this.HireDates = GetDateBetween (2005, 2014, count); ObservableCollection<EmployeeInformation> employeeDetails = new ObservableCollection<EmployeeInformation> (); for (int i = 0; i < count; i++) { var country = Countries [random.Next (1)]; var city = Cities [country]; var emp = new EmployeeInformation () { EmployeeID = i + 1, FirstName = FirstNames [i % FirstNames.Length], LastName = LastNames [i % LastNames.Length], Designation = Titles [random.Next (5)], DateOfBirth = BirthDates [i], DateOfJoining = HireDates [i], Address = Addresses [random.Next (6)], Country = Countries [random.Next (2)], City = city [random.Next (city.Length - 1)], Telephone = HomePhones [random.Next (8)], Qualification = Notes [i % Notes.Length], }; employeeDetails.Add (emp); } return employeeDetails; } #endregion #region MainGrid DataSource private ObservableCollection<DateTime> GetDateBetween (int startYear, int endYear, int count) { ObservableCollection<DateTime> date = new ObservableCollection<DateTime> (); Random d = new Random (1); Random m = new Random (2); Random y = new Random (startYear); for (int i = 0; i < count; i++) { int year = y.Next (startYear, endYear); int month = m.Next (3, 13); int day = d.Next (1, 31); date.Add (new DateTime (year, month, day)); } return date; } string[] Titles = new string[] { "Sales Representative", "Vice President, Sales", "Sales Representative", "Sales Manager", "Inside Sales Coordinator", "Business Manager", "Mail Clerk", "Receptionist", "Marketing Director", "Marketing Associate", "Advertising Specialist" }; string[] FirstNames = new string[] { "Nancy", "Andrew", "Janet", "Margaret", "Steven", "Michael", "Robert", "Laura", "Anne", "Albert", "Caroline", "Xavier", }; string[] LastNames = new string[] { "Davolio", "Fuller", "Leverling", "Peacock", "Buchanan", "Suyama", "King", "Callahan", "Dodsworth", "Hellstern", "Patterson", "Martin", }; string[] HomePhones = new string[] { "(206) 555-9857", "(206) 555-9482", "(206) 555-3412", "(206) 555-8122", "(71) 555-4848", "(71) 555-7773", "(71) 555-5598", "(206) 555-1189", "(71) 555-4444", "(206) 555-4869", "(206) 555-3857", "(206) 555-3487", "88 83 83 16", "88 62 43 53", "88 01 01 68", }; string[] Addresses = new string[] { "507 - 20th Ave. E. Apt. 2A", "908 W. Capital Way", "722 Moss Bay Blvd.", "4110 Old Redmond Rd.", "14 <NAME>", "Coventry House Miner Rd.", "Edgeham Hollow Winchester Way", "4726 - 11th Ave. N.E.", "7 Houndstooth Rd.", "13920 S.E. 40th Street", "30301 - 166th Ave. N.E.", "16 Maple Lane", "2 impasse du Soleil", "9 place de la Liberté", "7 rue Nationale" }; string[] Notes = new string[] { "Education includes a BA in Psychology from The Colorado State University in 1970.", "Andrew received his BTS commercial in 1964 and an MBA in International Marketing from the University of Dallas in 1971.", "Janet has a BS degree in Chemistry from The Boston College (1984). She has also completed a certification in Food Retailing Management.", "Margaret holds a BA in English literature from Concordia College (1958) and an MA from the American Institute of Culinary Arts (1966).", "<NAME> graduated from St. Andrews University, Scotland, with a BSC degree in 1976.", "Michael is a graduate of Sussex University (MA, economics, 1983) and the University of California at Los Angeles (MBA, marketing, 1986).", "<NAME> served in Peace Corps and traveled extensively before completing his English degree at the University of Michigan in 1992, the year he joined in the company.", "Laura received a BA in psychology from the University of Washington. She has also completed a course in business French.", "Anne has a BA degree in English from St. Lawrence College. She is fluent in French and German languages.", "<NAME> is a graduate of Harvard University, where he earned a Bachelor of Science degree in 1981.", "<NAME> is a graduate from The Tahoma High School and she also has an AA degree from the Bellevue Community College in Bellevue.", "<NAME> is a graduate of the University of Chicago. Mr. Martin is completely fluent in German, French and English and understands Polish." }; string[] Countries = new string[] { "USA", "UK", "France", }; Dictionary<string, string[]> Cities = new Dictionary<string, string[]> (); private void setCity () { string[] france = new string[] { "Haguenau", "Schiltigheim", "Strasbourg" }; string[] uk = new string[] { "Colchester", "Hedge End", "London" }; string[] usa = new string[] { "Seattle", "Tacoma", "Kirkland", "Redmond", "Bellevue", "Kent", "Auburn", }; Cities.Add ("France", france); Cities.Add ("UK", uk); Cities.Add ("USA", usa); } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/Maps/OSM.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfBusyIndicator.iOS; using System; using System.Net; using System.Threading.Tasks; using Syncfusion.SfMaps.iOS; using Foundation; using CoreGraphics; using UIKit; using Syncfusion.SfCarousel.iOS; using System.Collections.Generic; namespace SampleBrowser { public class OSM : SampleView { bool TapGesture_ShouldReceiveTouch(UIGestureRecognizer recognizer, UITouch touch) { if (touch.TapCount == 1) { UIApplication.SharedApplication.OpenUrl(new NSUrl("https://www.openstreetmap.org/copyright")); } return true; } internal SfBusyIndicator busyindicator; UIView view; UIView mainGrid; UIView childGrid; double previousWidth; double previousHeight; CGSize label1Size; CGSize label2Size; UILabel label1; UILabel label2; bool isDisposed; SFMap maps; UILabel label; bool isConnected; SfCarousel carousel; List<string> imageList; List<string> headerList; List<string> descriptionList; NSMutableArray<SfCarouselItem> carouselItems; ImageryLayer layer; public override void LayoutSubviews() { view.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); if (childGrid != null) childGrid.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); if (mainGrid != null) mainGrid.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); if (maps != null) maps.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); if (label1 != null && label2 != null) { label1.Frame = new CGRect(Frame.Size.Width - (label1Size.Width + label2Size.Width) - 4, Frame.Size.Height - label2Size.Height - 4, label1Size.Width + 4, label1Size.Height + 4); label2.Frame = new CGRect(Frame.Size.Width - label2Size.Width - 2, Frame.Size.Height - label2Size.Height - 4, label2Size.Width + 4, label2Size.Height + 4); } if (carousel != null) { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { carousel.ItemHeight = Frame.Size.Height * 0.2f; } else { carousel.ItemHeight = Frame.Size.Height * 0.150f; } carousel.Frame = new CGRect(0, Frame.Size.Height - carousel.ItemHeight - label2Size.Height, Frame.Size.Width, carousel.ItemHeight); carousel.ItemWidth = Frame.Size.Width * 0.75f; carousel.SelectedItemOffset = (carousel.ItemWidth / 2) - 30; AddCarouselItems(); } if (childGrid != null && childGrid.Subviews.Length > 0 && previousWidth == view.Frame.Size.Width && previousHeight == view.Frame.Size.Height) return; double row = 0; double column = 0; if (view.Frame.Size.Height > 0) { row = view.Frame.Size.Height / 512; if (Math.Ceiling(row) <= 0) row = 1; else row = Math.Ceiling(row); previousHeight = view.Frame.Size.Height; } if (view.Frame.Size.Width > 0) { column = view.Frame.Size.Width / 512; if (Math.Ceiling(column) <= 0) column = 1; else column = Math.Ceiling(column); previousWidth = view.Frame.Size.Width; } for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { UIImageView image = new UIImageView(); image.Image = UIImage.FromBundle("grid.png"); var xPos = i * 512; var yPos = j * 512; image.Frame = new CGRect(xPos, yPos, 512, 512); childGrid.AddSubview(image); SetNeedsDisplay(); } } childGrid.ClipsToBounds = true; SetNeedsDisplay(); } private void AddCarouselItems() { AddCarouselContent(); for (int i = 0; i <= 6; i++) { var width = carousel.ItemWidth * 0.6; SfCarouselItem items = new SfCarouselItem(); items.BackgroundColor = UIColor.White; UIStackView stackView = new UIStackView(); stackView.BackgroundColor = UIColor.White; stackView.Axis = UILayoutConstraintAxis.Horizontal; stackView.Frame = new CGRect(0, 0, carousel.ItemWidth, carousel.ItemHeight); stackView.Layer.CornerRadius = 10; stackView.Layer.BorderColor = UIColor.LightGray.CGColor; stackView.Layer.BorderWidth = 0.5f; UIStackView stackView1 = new UIStackView(); stackView1.Axis = UILayoutConstraintAxis.Vertical; stackView1.Frame = new CGRect(0, 0, width, carousel.ItemHeight); UILabel label1 = new UILabel(); label1.Text = headerList[i]; label1.Font = UIFont.SystemFontOfSize(14, UIFontWeight.Bold); label1.Frame = new CGRect(10, 5, width, carousel.ItemHeight * 0.25); stackView1.Add(label1); UILabel label = new UILabel(); label.Text = descriptionList[i]; label.Font = UIFont.SystemFontOfSize(10, UIFontWeight.Regular); label.Lines = 4; label.ContentMode = UIViewContentMode.TopLeft; label.LineBreakMode = UILineBreakMode.WordWrap | UILineBreakMode.TailTruncation; label.Frame = new CGRect(10, carousel.ItemHeight * 0.25, stackView1.Frame.Width - 10, carousel.ItemHeight * 0.75); stackView1.Add(label); UIImageView uiImageView = new UIImageView(); uiImageView.Image = UIImage.FromBundle(imageList[i]); uiImageView.Frame = new CGRect(width + 8, 10, carousel.ItemWidth * 0.4 - 16, carousel.ItemHeight - 20); uiImageView.Layer.CornerRadius = 7; uiImageView.Layer.BorderColor = UIColor.LightGray.CGColor; uiImageView.ClipsToBounds = true; stackView.Add(stackView1); stackView.Add(uiImageView); items.View = stackView; carouselItems.Add(items); } carousel.DataSource = carouselItems; } private void AddCarouselContent() { imageList = new List<string>(); imageList.Add("Mexico.jpg"); imageList.Add("Peru.jpg"); imageList.Add("Christ.jpg"); imageList.Add("Colosseum.jpg"); imageList.Add("Petra.jpg"); imageList.Add("TajMahal.jpg"); imageList.Add("China_wall.jpg"); headerList = new List<string>(); headerList.Add("<NAME>, Mexico"); headerList.Add("<NAME>"); headerList.Add("Chirst the Redeemer, Brazil"); headerList.Add("Colosseum, Rome"); headerList.Add("Petra, Jordan"); headerList.Add("<NAME>, India"); headerList.Add("Great wall of China, China"); descriptionList = new List<string>(); descriptionList.Add("Mayan ruins on Mexico's Yucatan Peninsula. It was one of the largest Maya cities, thriving from around A.D. 600 to 1200."); descriptionList.Add("An inca citadel built in the mid-1400s. It was not widely known until the early 20th century."); descriptionList.Add("An enormous statue of Jesus Christ with open arms. A symbol of Christianity across the world, the statue has also become a cultural icon of both Rio de Janeiro and Brazil."); descriptionList.Add("Built between A.D. 70 and 80. It is one of the most popular touristattractions in Europe."); descriptionList.Add("It is a historic and archaeological city in southern Jordan. Petra lies around Jabal Al-Madbah in a basin surrounded by mountains which form the eastern flank of the Arabah valley that runs from the Dead Sea to the Gulf of Aqaba."); descriptionList.Add("It is an ivory-white marble mausoleum on the southern bank of the river Yamuna in the Indian city of Agra."); descriptionList.Add("The Great Wall of China is a series of fortifications that were built across the historical northern borders of ancient Chinese states and Imperial China as protection against various nomadic groups from the Eurasian Steppe."); carouselItems = new NSMutableArray<SfCarouselItem>(); } public OSM() { view = new UIView(); view.Frame = new CGRect(0, 0, 300, 400); AddMainView(); busyindicator = new SfBusyIndicator(); busyindicator.ViewBoxWidth = 75; busyindicator.ViewBoxHeight = 75; busyindicator.Foreground = UIColor.FromRGB(0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; IsConnectedToNetwork(); } protected override void Dispose(bool disposing) { isDisposed = true; base.Dispose(disposing); } async void IsConnectedToNetwork() { isConnected = await IsConnected(); if (isDisposed) return; if (isConnected) { view.AddSubview(busyindicator); NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(0.3), delegate { if (isDisposed) return; maps.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); view.AddSubview(mainGrid); }); } else { label = new UILabel(); label.TextAlignment = UITextAlignment.Center; label.Text = "Since this application requires network connection, " + "Please check your network connection"; label.Font = UIFont.SystemFontOfSize(14); label.Frame = new CGRect(0, 0, 300, 300); label.TextColor = UIColor.Black; label.LineBreakMode = UILineBreakMode.WordWrap; label.Lines = 2; view.AddSubview(label); } AddSubview(view); } async Task<bool> IsConnected() { var webRequest = (HttpWebRequest)WebRequest.Create("https://www.openstreetmap.org"); webRequest.Method = "HEAD"; try { using (var httpResponse = await webRequest.GetResponseAsync() as HttpWebResponse) { if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.OK) return true; return false; } } catch (WebException) { return false; } } void AddMainView() { if (childGrid == null) childGrid = new UIView(); mainGrid = new UIView(); mainGrid.BackgroundColor = UIColor.FromRGB(243, 239, 233); mainGrid.AddSubview(childGrid); maps = new SFMap(); maps.ZoomLevel = 4; maps.MinimumZoom = 4; maps.MaximumZoom = 10; layer = new ImageryLayer(); layer.GeoCoordinates = new CGPoint(27.1751, 78.0421); PopulationMarker marker1 = new PopulationMarker(); marker1.Latitude = 20.6843f; marker1.Longitude = -88.5678f; layer.Markers.Add(marker1); PopulationMarker marker2 = new PopulationMarker(); marker2.Latitude = -13.1631f; marker2.Longitude = -72.5450f; layer.Markers.Add(marker2); PopulationMarker marker3 = new PopulationMarker(); marker3.Latitude = -22.9519f; marker3.Longitude = -43.2106f; layer.Markers.Add(marker3); PopulationMarker marker4 = new PopulationMarker(); marker4.Latitude = 41.8902; marker4.Longitude = 12.4922; layer.Markers.Add(marker4); PopulationMarker marker5 = new PopulationMarker(); marker5.Latitude = 30.3285; marker5.Longitude = 35.4444; layer.Markers.Add(marker5); PopulationMarker marker6 = new PopulationMarker(); marker6.Latitude = 27.1751; marker6.Longitude = 78.0421; layer.Markers.Add(marker6); PopulationMarker marker7 = new PopulationMarker(); marker7.Latitude = 40.4319; marker7.Longitude = 116.5704; layer.Markers.Add(marker7); maps.Layers.Add(layer); maps.Delegate = new OSMDelegate(this); mainGrid.AddSubview(maps); carousel = new SfCarousel(); carousel.RotationAngle = 0; carousel.SelectedIndex = 5; carousel.SelectionChanged += Carousel_SelectionChanged; mainGrid.AddSubview(carousel); label1 = new UILabel(); label1.TextColor = UIColor.Black; label1.LayoutMargins = new UIEdgeInsets(2, 2, 3, 2); label1.Font = UIFont.FromName("Helvetica", 12); var text = new NSString("©"); var stringAtribute = new NSDictionary(UIStringAttributeKey.Font, label1.Font, UIStringAttributeKey.ForegroundColor, UIColor.Black); UIStringAttributes strAtr = new UIStringAttributes(stringAtribute); label1.Text = text; label1Size = text.GetSizeUsingAttributes(strAtr); label1.BackgroundColor = UIColor.White; mainGrid.AddSubview(label1); label2 = new UILabel(); label2.TextColor = UIColor.FromRGB(0, 212, 255); label2.LayoutMargins = new UIEdgeInsets(1, 2, 3, 2); label2.Font = UIFont.FromName("Helvetica", 12); var text1 = new NSString("OpenStreetMap contributors."); var stringAtribute1 = new NSDictionary(UIStringAttributeKey.Font, label2.Font, UIStringAttributeKey.ForegroundColor, UIColor.FromRGB(0, 212, 255)); UIStringAttributes strAtr1 = new UIStringAttributes(stringAtribute); label2.Text = text1; label2Size = text1.GetSizeUsingAttributes(strAtr1); label2.BackgroundColor = UIColor.White; label2.UserInteractionEnabled = true; UITapGestureRecognizer tapGesture = new UITapGestureRecognizer(); tapGesture.ShouldReceiveTouch += TapGesture_ShouldReceiveTouch; label2.AddGestureRecognizer(tapGesture); mainGrid.AddSubview(label2); } private void Carousel_SelectionChanged(object sender, SelectionChangedEventArgs e) { int index = (int)(sender as SfCarousel).SelectedIndex; if (index == 0) { layer.GeoCoordinates = new CGPoint(20.6843, -88.5678); } else if (index == 1) { layer.GeoCoordinates = new CGPoint(-13.1631, -72.5450); } else if (index == 2) { layer.GeoCoordinates = new CGPoint(-22.9519, -43.2106); } else if (index == 3) { layer.GeoCoordinates = new CGPoint(41.8902, 12.4922); } else if (index == 4) { layer.GeoCoordinates = new CGPoint(30.3285, 35.4444); } else if (index == 5) { layer.GeoCoordinates = new CGPoint(27.1751, 78.0421); } else if (index == 6) { layer.GeoCoordinates = new CGPoint(40.4319, 116.5704); } } } public class OSMDelegate : SFMapsDelegate { OSM sample; public OSMDelegate(OSM osm) { sample = osm; } public override void DidLoad(SFMap map) { if (sample.busyindicator != null) { sample.busyindicator.RemoveFromSuperview(); sample.busyindicator = null; } } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/CustomersRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CustomersRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class Used to Store the Item values /// </summary> public class CustomersRepository { #region Fields [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Random random = new Random(); #endregion #region MainGrid DataSource [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] genders = new string[] { "Male", "Female", "Female", "Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male", "Male", "Female", "Female", "Female", "Male", "Male", "Male", "Female", "Female", "Female", "Male", "Male", "Male", "Male" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] firstNames = new string[] { "Kyle", "Gina", "Irene", "Katie", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Brenda", "Danielle", "Fiona", "Howard", "Jack", "Larry", "Holly", "Jennifer", "Liz", "Pete", "Steve", "Vince", "Zeke" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] lastNames = new string[] { "Adams", "Crowley", "Ellis", "Gable", "Irvine", "Keefe", "Mendoza", "Owens", "Rooney", "Waddell", "Thomas", "Betts", "Doran", "Holmes", "Landry", "Newberry", "Perez", "Spencer", "Vargas", "Grimes", "Edwards", "Stark", "Cruise", "Fitz", "Chief", "Blanc", "Perry", "Stone", "Williams", "Lane", "Jobs" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] customerID = new string[] { "Alfki", "Frans", "Merep", "Folko", "Simob", "Warth", "Vaffe", "Furib", "Seves", "Linod", "Riscu", "Picco", "Blonp", "Welli", "Folig" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] country = new string[] { "Argentina", "Austria", "Belgium", "Brazil", "Canada", "Denmark", "Finland", "France", "Germany", "Ireland", "Italy", "Mexico", "Norway", "Poland", "Portugal", "Spain", "Sweden", "UK", "USA", }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Dictionary<string, string[]> city = new Dictionary<string, string[]>(); #endregion /// <summary> /// Initializes a new instance of the CustomersRepository class. /// </summary> public CustomersRepository() { } #region GetOrderDetails /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">generates row count</param> /// <returns>returns the added record rows</returns> public ObservableCollection<CustomerDetails> GetCutomerDetails(int count) { this.SetCity(); ObservableCollection<CustomerDetails> orderDetails = new ObservableCollection<CustomerDetails>(); for (int i = 10001; i <= count + 10000; i++) { var country = this.country[this.random.Next(5)]; var citycoll = this.city[country]; var ord = new CustomerDetails() { CustomerID = this.customerID[this.random.Next(15)], FirstName = this.firstNames[this.random.Next(15)], LastName = this.lastNames[this.random.Next(15)], Gender = this.genders[this.random.Next(5)], Country = this.country[this.random.Next(5)], City = citycoll[this.random.Next(citycoll.Length - 1)], }; orderDetails.Add(ord); } return orderDetails; } /// <summary> /// Used to stored a String type collection value /// </summary> private void SetCity() { string[] argentina = new string[] { "Rosario" }; string[] austria = new string[] { "Graz", "Salzburg" }; string[] belgium = new string[] { "Bruxelles", "Charleroi" }; string[] brazil = new string[] { "Campinas", "Resende", "Manaus", "Recife" }; string[] canada = new string[] { "Montréal", "Tsawassen", "Vancouver" }; string[] denmark = new string[] { "Århus", "København" }; string[] finland = new string[] { "Helsinki", "Oulu" }; string[] france = new string[] { "Lille", "Lyon", "Marseille", "Nantes", "Paris", "Reims", "Strasbourg", "Toulouse", "Versailles" }; string[] germany = new string[] { "Aachen", "Berlin", "Cunewalde", "Frankfurt", "Köln", "Leipzig", "Mannheim", "München", "Münster", "Stuttgart" }; string[] ireland = new string[] { "Cork" }; string[] italy = new string[] { "Bergamo", "Reggio", "Torino" }; string[] mexico = new string[] { "México D.F." }; string[] norway = new string[] { "Stavern" }; string[] poland = new string[] { "Warszawa" }; string[] portugal = new string[] { "Lisboa" }; string[] spain = new string[] { "Barcelona", "Madrid", "Sevilla" }; string[] sweden = new string[] { "Bräcke", "Luleå" }; string[] switzerland = new string[] { "Bern", "Genève" }; string[] uk = new string[] { "Colchester", "Hedge End", "London" }; string[] usa = new string[] { "Albuquerque", "Anchorage", "Boise", "Butte", "Elgin", "Eugene", "Kirkland", "Lander", "Portland", "Seattle", "Walla" }; string[] venezuela = new string[] { "Barquisimeto", "Caracas", "<NAME>", "San Cristóbal" }; this.city.Add("Argentina", argentina); this.city.Add("Austria", austria); this.city.Add("Belgium", belgium); this.city.Add("Brazil", brazil); this.city.Add("Canada", canada); this.city.Add("Denmark", denmark); this.city.Add("Finland", finland); this.city.Add("France", france); this.city.Add("Germany", germany); this.city.Add("Ireland", ireland); this.city.Add("Italy", italy); this.city.Add("Mexico", mexico); this.city.Add("Norway", norway); this.city.Add("Poland", poland); this.city.Add("Portugal", portugal); this.city.Add("Spain", spain); this.city.Add("Sweden", sweden); this.city.Add("Switzerland", switzerland); this.city.Add("UK", uk); this.city.Add("USA", usa); this.city.Add("Venezuela", venezuela); } #endregion } }<file_sep>/Forms/DocIO/DocIO/Samples/WordToPDF/WordToPDF.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using SampleBrowser.Core; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.DocIO; using Syncfusion.DocIORenderer; using Syncfusion.Pdf; using Syncfusion.OfficeChart; namespace SampleBrowser.DocIO { public partial class WordToPDF : SampleView { public WordToPDF() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInpTemplate.HorizontalOptions = LayoutOptions.Start; this.btnInpTemplate.VerticalOptions = LayoutOptions.Center; this.btnInpTemplate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnInpTemplate.VerticalOptions = LayoutOptions.Center; } } void OnInputButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else resourcePath = "SampleBrowser.DocIO.Samples.Templates."; #endif Assembly assembly = typeof(WordToPDF).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath + "WordtoPDF.docx"); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); stream.Position = 0; fileStream.Dispose(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("WordtoPDF.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("WordtoPDF.docx", "application/msword", stream); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = typeof(WordToPDF).GetTypeInfo().Assembly; // Creating a new document. WordDocument document = new WordDocument(); #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif Stream inputStream = assembly.GetManifestResourceStream(rootPath + "WordtoPDF.docx"); // Loads the stream into Word Document. WordDocument wordDocument = new WordDocument(inputStream, Syncfusion.DocIO.FormatType.Automatic); //Sets ShowInBalloons to render a document comments in converted PDF document. wordDocument.RevisionOptions.CommentDisplayMode = CommentDisplayMode.ShowInBalloons; //Sets the color to be used for Comment Balloon wordDocument.RevisionOptions.CommentColor = RevisionColor.Blue; //Instantiation of DocIORenderer for Word to PDF conversion DocIORenderer render = new DocIORenderer(); //Sets Chart rendering Options. render.Settings.ChartRenderingOptions.ImageFormat = Syncfusion.OfficeChart.ExportImageFormat.Jpeg; //Converts Word document into PDF document PdfDocument pdfDocument = render.ConvertToPDF(wordDocument); //Releases all resources used by the Word document and DocIO Renderer objects render.Dispose(); wordDocument.Dispose(); //Saves the PDF file MemoryStream outputStream = new MemoryStream(); pdfDocument.Save(outputStream); //Closes the instance of PDF document object pdfDocument.Close(); if (Device.RuntimePlatform == Device.UWP) DependencyService.Get<ISaveWindowsPhone>() .Save("WordtoPDF.pdf", "application/pdf", outputStream); else DependencyService.Get<ISave>().Save("WordtoPDF.pdf", "application/pdf", outputStream); } } } <file_sep>/Forms/PDF/PDF/Samples/Stamping/Stamping.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.Drawing; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Parsing; using System.Reflection; using Xamarin.Forms; using System.IO; using SampleBrowser.Core; namespace SampleBrowser.PDF { public partial class Stamping : SampleView { public Stamping() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { //Load PDF document to stream. #if COMMONSB Stream docStream = typeof(Stamping).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Product Catalog.pdf"); #else Stream docStream = typeof(Stamping).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Product Catalog.pdf"); #endif //Load the PDF document into the loaded document object. PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream); //Create font object. PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular); //Stamp or watermark on all the pages. foreach (PdfPageBase lPage in ldoc.Pages) { PdfGraphics g = lPage.Graphics; PdfGraphicsState state = g.Save(); g.TranslateTransform(ldoc.Pages[0].Size.Width / 2, ldoc.Pages[0].Size.Height / 2); g.SetTransparency(0.25f); SizeF waterMarkSize = font.MeasureString("Sample"); g.RotateTransform(-40); g.DrawString("Sample", font, PdfPens.Red, PdfBrushes.Red, new PointF(-waterMarkSize.Width / 2, -waterMarkSize.Height / 2)); g.Restore(state); } MemoryStream stream = new MemoryStream(); //Save the PDF document ldoc.Save(stream); //Close the document ldoc.Close(true); //Open in default system viewer. if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Stamping.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("Stamping.pdf", "application/pdf", stream); } } } <file_sep>/Android/SampleBrowser/Samples/RangeSlider/Slider.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Com.Syncfusion.Sfrangeslider; using System; using System.Threading.Tasks; using Android.Widget; using Android.Views; namespace SampleBrowser { //[con(Label = "Slider")] public class Slider : SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ TextView opacityLabel; SfRangeSlider range; ImageView mountImg; int height; public override View GetSampleContent (Context con) { SamplePageContent(con); /*************** **RangeSlider** ***************/ range = new SfRangeSlider(con); range.Minimum = 0;range.Maximum = 100; range.Value = 100; range.ShowRange = false; range.SnapsTo = SnapsTo.None; range.Orientation = Com.Syncfusion.Sfrangeslider.Orientation.Horizontal; range.TickPlacement = TickPlacement.BottomRight; range.ShowValueLabel = true; range.TickFrequency = 20; range.ValuePlacement = ValuePlacement.BottomRight; range.LayoutParameters = (new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, GettingStarted_Mobile.getDimensionPixelSize(con,Resource.Dimension.range_ht))); range.ValueChanged += ValueChanged ; range.SetY(-30); //Frame Layout FrameLayout frame = new FrameLayout(con); frame.SetBackgroundColor (Color.White); frame.LayoutParameters = ( new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent,GravityFlags.Center)); frame.AddView(GetView(con)); return frame; } private LinearLayout GetView(Context con) { /*************** **LinearLayout** ***************/ LinearLayout linearLayout = new LinearLayout(con); linearLayout.SetGravity(Android.Views.GravityFlags.CenterHorizontal); linearLayout.Orientation = Android.Widget.Orientation.Vertical; linearLayout.SetBackgroundColor(Color.White); linearLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); linearLayout.SetPadding(20, 20, 20, 20); linearLayout.AddView(mountImg); linearLayout.AddView(opacityLabel); linearLayout.AddView(range); return linearLayout; } private void SamplePageContent(Context con) { height = con.Resources.DisplayMetrics.HeightPixels / 2; //MountImg mountImg = new ImageView(con); mountImg.SetImageResource(Resource.Drawable.mount1); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(height + (height / 10)), GravityFlags.Center); mountImg.SetPadding(12, 0, 10, 0); mountImg.LayoutParameters = (layoutParams); //Opacity Label opacityLabel = new TextView(con); opacityLabel.Text = " Opacity"; opacityLabel.TextSize = 20; opacityLabel.Gravity = GravityFlags.Left; } public void ValueChanged(object sender, ValueChangedEventArgs e) { float alpha = (float)(e.Value / 100); mountImg.Alpha = alpha; } } }<file_sep>/Forms/Maps/Maps/Samples/Drilldown/Drilldown.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfMaps.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] public partial class Drilldown : SampleView { public Drilldown() { InitializeComponent(); var tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += (s, e) => { Map.BaseMapIndex = 0; stackLayout.IsVisible = false; header.IsVisible = true; }; label.GestureRecognizers.Add(tapGestureRecognizer); } private void Layer_ShapeSelectionChanged(object sender, ShapeSelectedEventArgs args) { DrilldownModel data = args.Data as DrilldownModel; if (data != null) { continentLabel.Text = data.Continent; stackLayout.IsVisible = true; header.IsVisible = false; if (data.Continent == "South America") { Map.BaseMapIndex = 1; layer.ShapeSettings.SelectedShapeColor = Color.FromHex("#9C3367"); } else if (data.Continent == "North America") { Map.BaseMapIndex = 2; layer.ShapeSettings.SelectedShapeColor = Color.FromHex("#C13664"); } else if (data.Continent == "Europe") { Map.BaseMapIndex = 3; layer.ShapeSettings.SelectedShapeColor = Color.FromHex("#622D6C"); } else if (data.Continent == "Africa") { Map.BaseMapIndex = 4; layer.ShapeSettings.SelectedShapeColor = Color.FromHex("#80306A"); } else if (data.Continent == "Australia") { Map.BaseMapIndex = 5; layer.ShapeSettings.SelectedShapeColor = Color.FromHex("#2A2870"); } else if (data.Continent == "Asia") { Map.BaseMapIndex = 6; layer.ShapeSettings.SelectedShapeColor = Color.FromHex("#462A6D"); } } } } }<file_sep>/Forms/SegmentedControl/SegmentedControl/Samples/SegmentViewGettingStarted/View/SegmentViewGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Globalization; using SampleBrowser.Core; using Syncfusion.XForms.Buttons; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SegmentedEventArgs = Syncfusion.XForms.Buttons.SelectionChangedEventArgs; namespace SampleBrowser.SegmentedControl { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SegmentViewGettingStarted : SampleView { private readonly GettingStartedViewModel _viewModel = new GettingStartedViewModel(); public SegmentViewGettingStarted() { InitializeComponent(); this.BindingContext = _viewModel; if (Device.Idiom == TargetIdiom.Tablet) { descriptiontext.FontSize = 16; descriptiondetail.FontSize = 16; sizetext.FontSize = 16; colortext.FontSize = 16; detail.FontSize = 16; preview.FontSize = 150; } if (Device.Idiom == TargetIdiom.Desktop) { MainGrid.VerticalOptions = LayoutOptions.Center; MainGrid.HorizontalOptions = LayoutOptions.Center; MainGrid.WidthRequest = 500; MainGrid.RowDefinitions[0].Height = 100; MainGrid.RowDefinitions[1].Height = 150; MainGrid.RowDefinitions[2].Height = 20; MainGrid.RowDefinitions[3].Height = 100; MainGrid.RowDefinitions[4].Height = 100; MainGrid.RowDefinitions[5].Height = 50; clothType.HorizontalOptions = LayoutOptions.Center; PrimaryColorSegment.HorizontalOptions = LayoutOptions.Center; clothType.SegmentWidth = 120; SegmentedView1.HorizontalOptions = LayoutOptions.Center; SegmentedView1.WidthRequest = 350; SegmentedView1.Margin = new Thickness(10, 20, 0, 0); MainScrollView.HorizontalOptions = LayoutOptions.Center; } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.Idiom != TargetIdiom.Desktop) { if (width > height) { MainGrid.HeightRequest = width; } else { MainGrid.HeightRequest = height; } } } /// <summary> /// Raised when change the color from segmented control. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Handle_SelectionChanged(object sender, SegmentedEventArgs e) { this.PrimaryColorSegment.SelectionTextColor = _viewModel.PrimaryColors[e.Index].FontIconFontColor; this.preview.TextColor = _viewModel.PrimaryColors[e.Index].FontIconFontColor; } /// <summary> /// Raised when select the cloth type segmented control. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ClothType_OnSelectionChanged(object sender, SegmentedEventArgs e) { var index = e.Index; if (index == 0) { _viewModel.FontIconText = "A"; } else if (index == 1) { _viewModel.FontIconText = "B"; } else { _viewModel.FontIconText = "C"; } } } /// <summary> /// To get the platformm specfic path for font icon. /// </summary> public class SegmentedConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (Device.RuntimePlatform == "Android") { if (parameter != null && parameter is string) return "Segmented.ttf#" + parameter.ToString(); else return "Segmented.ttf"; } else if (Device.RuntimePlatform == "iOS") { return "Segmented"; } else { #if COMMONSB return "/Assets/Fonts/Segmented.ttf#Segmented"; #else if (Core.SampleBrowser.IsIndividualSB) { if (Device.RuntimePlatform == "UWP") return "/Assets/Fonts/Segmented.ttf#Segmented"; else return "pack://application:,,,/SampleBrowser.SfSegmentedControl.WPF;component/Assets/Fonts/#Segmented"; } else { return $"ms-appx:///SampleBrowser.SfSegmentedControl.UWP/Assets/Fonts/Segmented.ttf#Segmented"; // "SampleBrowser.SfTabView.UWP\\Assets/Fonts/NestedTab.ttf#NestedTab"; } #endif } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/iOS/SampleBrowser/Samples/PDF/ZugFerd_XML/ZugFerdInvoice.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml; namespace Syncfusion.ZugFerd { /// <summary> /// zugFerd Invoice /// </summary> public class ZugFerdInvoice { public string InvoiceNumber { get; set; } public DateTime InvoiceDate { get; set; } public CurrencyCodes Currency { get; set; } public InvoiceType Type { get; set; } public UserDetails Buyer { get; set; } public UserDetails Seller { get; set; } public ZugFerdProfile Profile { get; set; } public float TotalAmount { get; set; } List<Product> products = new List<Product>(); string rsm = "urn:ferd:CrossIndustryDocument:invoice:1p0"; string xsi = "http://www.w3.org/2001/XMLSchema-instance"; string udt = "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15"; string ram = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12"; public void AddProduct(Product product) { products.Add(product); } public void AddProduct(string productID, string productName, float price, float quantity, float totalPrice) { Product product = new Product() { ProductID = productID, productName = productName, Price = price, Quantity = quantity, Total = totalPrice }; products.Add(product); } public ZugFerdInvoice(string invoiceNumber, DateTime invoiceDate, CurrencyCodes currency) { InvoiceNumber = invoiceNumber; InvoiceDate = invoiceDate; Currency = currency; } public Stream Save(Stream stream) { XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); XmlElement CrossIndustryDocument = doc.CreateElement("rsm", "CrossIndustryDocument", rsm); CrossIndustryDocument.SetAttribute("xmlns:xsi", xsi); CrossIndustryDocument.SetAttribute("xmlns:rsm", rsm); CrossIndustryDocument.SetAttribute("xmlns:udt", udt); CrossIndustryDocument.SetAttribute("xmlns:ram", ram); XmlElement specifiedExchangedDocument = doc.CreateElement("rsm", "SpecifiedExchangedDocumentContext", rsm); XmlElement TestIndicator = doc.CreateElement("ram", "TestIndicator", ram); XmlElement Indicator = doc.CreateElement("udt", "Indicator", udt); Indicator.InnerText = "true"; TestIndicator.AppendChild(Indicator); specifiedExchangedDocument.AppendChild(TestIndicator); XmlElement guidelineSpecifiedDocument = doc.CreateElement("ram", "GuidelineSpecifiedDocumentContextParameter", ram); XmlElement id = doc.CreateElement("ram", "ID", ram); id.InnerText = "urn:ferd:CrossIndustryDocument:invoice:1p0:" + Profile.ToString(); guidelineSpecifiedDocument.AppendChild(id); specifiedExchangedDocument.AppendChild(guidelineSpecifiedDocument); CrossIndustryDocument.AppendChild(specifiedExchangedDocument); XmlElement headerExchangeDocument = WriteHeaderExchangeDocument(doc); XmlElement SpecifiedSupplyChainTradeTransaction = doc.CreateElement("rsm", "SpecifiedSupplyChainTradeTransaction", rsm); XmlElement ApplicableSupplyChainTradeAgreement = doc.CreateElement("ram", "ApplicableSupplyChainTradeAgreement", ram); XmlElement SellerTradeParty = WriteUserDetails(doc, "SellerTradeParty", Seller); XmlElement BuyerTradeParty = WriteUserDetails(doc, "BuyerTradeParty", Buyer); ApplicableSupplyChainTradeAgreement.AppendChild(SellerTradeParty); ApplicableSupplyChainTradeAgreement.AppendChild(BuyerTradeParty); SpecifiedSupplyChainTradeTransaction.AppendChild(ApplicableSupplyChainTradeAgreement); XmlElement ApplicableSupplyChainTradeSettlement = doc.CreateElement("ram", "ApplicableSupplyChainTradeSettlement", ram); XmlElement InvoiceCurrencyCode = doc.CreateElement("ram", "InvoiceCurrencyCode", ram); InvoiceCurrencyCode.InnerText = Currency.ToString("g"); ApplicableSupplyChainTradeSettlement.AppendChild(InvoiceCurrencyCode); XmlElement SpecifiedTradeSettlementMonetarySummation = doc.CreateElement("ram", "SpecifiedTradeSettlementMonetarySummation", ram); XmlElement GrandTotalAmount = doc.CreateElement("ram", "GrandTotalAmount", ram); GrandTotalAmount.InnerText = TotalAmount.ToString(); SpecifiedTradeSettlementMonetarySummation.AppendChild(GrandTotalAmount); ApplicableSupplyChainTradeSettlement.AppendChild(SpecifiedTradeSettlementMonetarySummation); SpecifiedSupplyChainTradeTransaction.AppendChild(ApplicableSupplyChainTradeSettlement); XmlElement LineItem = AddTradeLineItems(doc); SpecifiedSupplyChainTradeTransaction.AppendChild(LineItem); CrossIndustryDocument.AppendChild(headerExchangeDocument); CrossIndustryDocument.AppendChild(SpecifiedSupplyChainTradeTransaction); doc.AppendChild(CrossIndustryDocument); doc.Save(stream); stream.Position = 0; return stream; } private XmlElement AddTradeLineItems(XmlDocument doc) { XmlElement IncludedSupplyChainTradeLineItem = null; foreach (Product product in this.products) { IncludedSupplyChainTradeLineItem = doc.CreateElement("ram", "IncludedSupplyChainTradeLineItem", ram); if (Profile != ZugFerdProfile.Basic) { XmlElement SpecifiedSupplyChainTradeAgreement = doc.CreateElement("ram", "SpecifiedSupplyChainTradeAgreement", ram); XmlElement GrossPriceProductTradePrice = doc.CreateElement("ram", "GrossPriceProductTradePrice", ram); XmlElement BasisQuantity = doc.CreateElement("ram", "BasisQuantity", ram); BasisQuantity.InnerText = product.Quantity.ToString(); BasisQuantity.SetAttribute("unitCode", "KGM"); GrossPriceProductTradePrice.AppendChild(BasisQuantity); SpecifiedSupplyChainTradeAgreement.AppendChild(GrossPriceProductTradePrice); IncludedSupplyChainTradeLineItem.AppendChild(SpecifiedSupplyChainTradeAgreement); } XmlElement SpecifiedSupplyChainTradeDelivery = doc.CreateElement("ram", "SpecifiedSupplyChainTradeDelivery", ram); XmlElement BilledQuantity = doc.CreateElement("ram", "BilledQuantity", ram); BilledQuantity.InnerText = product.Quantity.ToString(); BilledQuantity.SetAttribute("unitCode", "KGM"); SpecifiedSupplyChainTradeDelivery.AppendChild(BilledQuantity); IncludedSupplyChainTradeLineItem.AppendChild(SpecifiedSupplyChainTradeDelivery); XmlElement SpecifiedSupplyChainTradeSettlement = doc.CreateElement("ram", "SpecifiedSupplyChainTradeSettlement", ram); XmlElement SpecifiedTradeSettlementMonetarySummation = doc.CreateElement("ram", "SpecifiedTradeSettlementMonetarySummation", ram); XmlElement LineTotalAmount = doc.CreateElement("ram", "LineTotalAmount", ram); LineTotalAmount.InnerText = FormatValue(TotalAmount); LineTotalAmount.SetAttribute("currencyID", this.Currency.ToString("g")); SpecifiedTradeSettlementMonetarySummation.AppendChild(LineTotalAmount); SpecifiedSupplyChainTradeSettlement.AppendChild(SpecifiedTradeSettlementMonetarySummation); IncludedSupplyChainTradeLineItem.AppendChild(SpecifiedSupplyChainTradeSettlement); XmlElement SpecifiedTradeProduct = doc.CreateElement("ram", "SpecifiedTradeProduct", ram); XmlElement productElement = WriteOptionalElement(doc, "Name", product.productName); SpecifiedTradeProduct.AppendChild(productElement); IncludedSupplyChainTradeLineItem.AppendChild(SpecifiedTradeProduct); } return IncludedSupplyChainTradeLineItem; } private XmlElement WriteOptionalElement(XmlDocument doc, string tagName, string value) { XmlElement element = null; if (!String.IsNullOrEmpty(value)) { element = doc.CreateElement("ram", tagName, ram); element.InnerText = value; } return element; } private void WriteOptionalAmount(XmlWriter writer, string tagName, float value, int numDecimals = 2) { if (value !=float.MinValue) { writer.WriteStartElement(tagName); writer.WriteAttributeString("currencyID", Currency.ToString("g")); writer.WriteValue(FormatValue(value, numDecimals)); writer.WriteEndElement(); } } private XmlElement WriteUserDetails(XmlDocument doc, string customerTag, UserDetails user) { XmlElement customerTagElement = null; if (user != null) { customerTagElement = doc.CreateElement("ram", customerTag, ram); if (!String.IsNullOrEmpty(user.ID)) { XmlElement ID = doc.CreateElement("ram", "ID", ram); ID.InnerText = user.ID; customerTagElement.AppendChild(ID); } if (!String.IsNullOrEmpty(user.Name)) { XmlElement Name = doc.CreateElement("ram", "Name", ram); Name.InnerText = user.Name; customerTagElement.AppendChild(Name); } XmlElement PostalTradeAddress = doc.CreateElement("ram", "PostalTradeAddress", ram); XmlElement PostcodeCode = doc.CreateElement("ram", "PostcodeCode", ram); PostcodeCode.InnerText = user.Postcode; PostalTradeAddress.AppendChild(PostcodeCode); XmlElement LineOne = doc.CreateElement("ram", "LineOne", ram); LineOne.InnerText = string.IsNullOrEmpty(user.ContactName) ? user.Street : user.ContactName; PostalTradeAddress.AppendChild(LineOne); if (!string.IsNullOrEmpty(user.ContactName)) { XmlElement LineTwo = doc.CreateElement("ram", "LineTwo", ram); LineTwo.InnerText = user.Street; PostalTradeAddress.AppendChild(LineTwo); } XmlElement CityName = doc.CreateElement("ram", "CityName", ram); CityName.InnerText = user.City; PostalTradeAddress.AppendChild(CityName); XmlElement CountryID = doc.CreateElement("ram", "CountryID", ram); CountryID.InnerText = user.Country.ToString("g"); PostalTradeAddress.AppendChild(CountryID); customerTagElement.AppendChild(PostalTradeAddress); } return customerTagElement; } private XmlElement WriteHeaderExchangeDocument(XmlDocument doc) { #region HeaderExchangedDocument XmlElement headerExchangedDocument= doc.CreateElement("rsm", "HeaderExchangedDocument", rsm); XmlElement ID = doc.CreateElement("ram", "ID", ram); ID.InnerText = InvoiceNumber; headerExchangedDocument.AppendChild(ID); XmlElement Name = doc.CreateElement("ram", "Name", ram); Name.InnerText = GetInvoiceTypeName(Type); headerExchangedDocument.AppendChild(Name); XmlElement TypeCode = doc.CreateElement("ram", "TypeCode", ram); TypeCode.InnerText = GetInvoiceTypeCode(Type).ToString(); headerExchangedDocument.AppendChild(TypeCode); XmlElement issueDateTime = doc.CreateElement("ram", "IssueDateTime", ram); XmlElement dateTimeString = doc.CreateElement("udt", "DateTimeString", udt); dateTimeString.SetAttribute("format", "102"); dateTimeString.InnerText = ConvertDateFormat(InvoiceDate, "102"); issueDateTime.AppendChild(dateTimeString); headerExchangedDocument.AppendChild(issueDateTime); #endregion return headerExchangedDocument; } private string ConvertDateFormat(DateTime date, String format = "102") { if (format.Equals("102")) { return date.ToString("yyyymmdd"); } else { return date.ToString("yyyy-MM-ddTHH:mm:ss"); } } private string GetInvoiceTypeName(InvoiceType type) { switch (type) { case InvoiceType.Invoice: return "RECHNUNG"; case InvoiceType.Correction: return "KORREKTURRECHNUNG"; case InvoiceType.CreditNote: return "GUTSCHRIFT"; case InvoiceType.DebitNote: return ""; case InvoiceType.SelfBilledInvoice: return ""; default: return ""; } } private int GetInvoiceTypeCode(InvoiceType type) { if ((int)type > 1000) { type -= 1000; } return (int)type; } private string FormatValue(float value, int numDecimals = 2) { string formatString = "0."; for (int i = 0; i < numDecimals; i++) { formatString += "0"; } return value.ToString(formatString).Replace(",", "."); } } }<file_sep>/Forms/ListView/ListView.Android/GridExtRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Views = Android.Views; using Xamarin.Forms; using SampleBrowser.SfListView; using SampleBrowser.SfListView.Droid; using Xamarin.Forms.Platform.Android; [assembly: ExportRenderer(typeof(GridExt), typeof(GridExtRenderer))] namespace SampleBrowser.SfListView.Droid { #pragma warning disable CS0618 // Type or member is obsolete class GridExtRenderer : VisualElementRenderer<GridExt> { public override bool OnTouchEvent(Views.MotionEvent e) { Parent.RequestDisallowInterceptTouchEvent(true); return base.OnTouchEvent(e); } } #pragma warning restore CS0618 // Type or member is obsolete } <file_sep>/Forms/AutoComplete/AutoComplete/Samples/MusicSearch/MusicViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public class MusicViewModel : INotifyPropertyChanged { private MusicInfo selectedItem; public MusicInfo SelectedItem { get { return selectedItem; } set { selectedItem = value; if (MusicIcon == "I") MusicIcon = "T"; else MusicIcon = "I"; OnPropertyChange("SelectedItem"); } } private string musicIcon = "I"; public string MusicIcon { get { return musicIcon; } set { musicIcon = value; OnPropertyChange("MusicIcon"); } } private int move = 40; public int Move { get { return move; } set { move = value; OnPropertyChange("Move"); } } private string playing = "0:00"; public string Playing { get { return playing; } set { playing = value; OnPropertyChange("Playing"); } } private bool isFocused = false; public bool IsFocused { get { return isFocused; } set { OnPropertyChange("IsFocused"); } } public string watermark = "Search here"; public string Watermark { get { return watermark; } set { watermark = value; OnPropertyChange("Watermark"); } } public string customText = string.Empty; public string CustomText { get { return customText; } set { customText = value; OnPropertyChange("CustomText"); } } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; #endregion string hintText = "d'une"; double hintCount = 0; ObservableCollection<ContactsInfo> SelectedObject = new ObservableCollection<ContactsInfo>(); public bool ShowHint() { if (hintCount < hintText.Length) { CustomText += hintText[(int)hintCount++]; return true; } else { return false; } } public void OnPropertyChange(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public ObservableCollection<MusicInfo> DataCollection { get; set; } public MusicViewModel() { DataCollection = new ObservableCollection<MusicInfo>(); DataCollection = new MusicInfoRepository().GetMusicInfo(); } } public class NullToBoolConveter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return false; } return true; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/AutoRowHeight.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Views; using Android.Content.Res; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public class AutoRowHeight:SamplePage { SfDataGrid sfGrid; AutoRowHeightViewModel viewModel; public override Android.Views.View GetSampleContent (Android.Content.Context context) { sfGrid = new SfDataGrid (context); sfGrid.ColumnSizer = ColumnSizer.None; sfGrid.SelectionMode = SelectionMode.Single; sfGrid.QueryRowHeight += HandleQueryRowHeightEventHandler; viewModel = new AutoRowHeightViewModel (); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = (viewModel.ReleaseInformation); sfGrid.VerticalOverScrollMode= VerticalOverScrollMode.None; sfGrid.Alpha = 0.87f ; if (MainActivity.IsTablet) { GridTextColumn sno = new GridTextColumn(); sno.MappingName = "SNo"; sno.HeaderText = "S.No"; sno.ColumnSizer = ColumnSizer.Auto; sno.HeaderTextAlignment = GravityFlags.Center; sno.TextAlignment = GravityFlags.Center; this.sfGrid.Columns.Insert(0, sno); this.sfGrid.ColumnSizer = ColumnSizer.Star; } return sfGrid; } void HandleQueryRowHeightEventHandler (object sender, QueryRowHeightEventArgs e) { if (e.RowIndex > 0) { double height = SfDataGridHelpers.GetRowHeight(sfGrid, e.RowIndex); e.Height = height + (16 * Resources.System.DisplayMetrics.Density); e.Handled = true; } } void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "SNo") e.Cancel = true; if (e.Column.MappingName == "ReleaseVersion") { e.Column.LineBreakMode = LineBreakMode.WordWrap; e.Column.HeaderText = "Release Version"; e.Column.TextAlignment = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; e.Column.HeaderTextMargin = new Thickness(8); e.Column.TextMargin = new Thickness(8); e.Column.HeaderCellTextSize = 13; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont= Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "Platform") { e.Column.HeaderText = "Platform"; e.Column.LineBreakMode = LineBreakMode.WordWrap; e.Column.TextAlignment = GravityFlags.Left | GravityFlags.CenterVertical; e.Column.HeaderTextMargin = new Thickness(8); e.Column.TextMargin= new Thickness(8); e.Column.HeaderCellTextSize = 13; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "Features") { e.Column.HeaderText = "Feature"; e.Column.TextAlignment = GravityFlags.Left | GravityFlags.CenterVertical; e.Column.LineBreakMode = LineBreakMode.WordWrap; e.Column.HeaderTextMargin = new Thickness(8); e.Column.TextMargin = new Thickness(8); e.Column.HeaderCellTextSize = 13; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "Description") { e.Column.HeaderText = "Description"; e.Column.TextAlignment = GravityFlags.Left | GravityFlags.CenterVertical; e.Column.LineBreakMode = LineBreakMode.WordWrap; e.Column.HeaderTextMargin = new Thickness(8); e.Column.TextMargin = new Thickness(8); e.Column.HeaderCellTextSize = 13; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } } public override void Destroy () { this.sfGrid.QueryRowHeight -= HandleQueryRowHeightEventHandler; sfGrid.Dispose (); sfGrid = null; viewModel = null; } } } <file_sep>/Android/SampleBrowser/Samples/CheckBox/CheckBox_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Widget; using Android.OS; using Syncfusion.Android.Buttons; using Android.Graphics; using Android.Views; using Android.Content; using Android.Util; using System; namespace SampleBrowser { public class CheckBox_Mobile { private bool skip = false; SfCheckBox selectAllBox, grilledBox, tikkaBox, beefBox, sausaga; Button button; AlertDialog.Builder resultsDialog; public CheckBox_Mobile() { } public View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.Orientation = Orientation.Vertical; LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent, (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 3, con.Resources.DisplayMetrics)); int margin; if (IsTabletDevice(con)) margin = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 15, con.Resources.DisplayMetrics); else margin = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 9.5f, con.Resources.DisplayMetrics); linearLayoutParams.SetMargins(margin, margin, margin, margin); ImageView imageView = new ImageView(con); imageView.SetScaleType(ImageView.ScaleType.FitStart); imageView.SetAdjustViewBounds(true); imageView.SetImageResource(Resource.Drawable.Pizzaimage); linear.AddView(imageView); int padding = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 7, con.Resources.DisplayMetrics); LinearLayout frameParent = new LinearLayout(con); frameParent.SetBackgroundColor(Color.White); frameParent.Orientation = Orientation.Vertical; frameParent.LayoutParameters = linearLayoutParams; LinearLayout frame = new LinearLayout(con); frame.Orientation = Orientation.Vertical; int currentapiVersion = (int)Build.VERSION.SdkInt; if (currentapiVersion > 21) frame.Background = con.Resources.GetDrawable(Resource.Drawable.shadow, con.Theme); TextView headLabel = new TextView(con); headLabel.SetPadding(padding, headLabel.PaddingTop, headLabel.PaddingRight, headLabel.PaddingBottom); headLabel.TextSize = 18; headLabel.SetTextColor(Color.ParseColor("#FF007DE6")); headLabel.Text = "Add Extra Toppings"; frame.AddView(headLabel); #region Items Layout selectAllBox = new SfCheckBox(con); selectAllBox.Text = "Select All"; selectAllBox.TextSize = 15; selectAllBox.SetTextColor(Color.ParseColor("#FF000000")); selectAllBox.StateChanged += SelectAll1_StateChanged; selectAllBox.LayoutParameters = linearLayoutParams; frame.AddView(selectAllBox); grilledBox = new SfCheckBox(con); grilledBox.Text = "Grilled Chicken"; grilledBox.TextSize = 15; grilledBox.SetTextColor(Color.ParseColor("#FF000000")); grilledBox.StateChanged += NonvegToppingsChanged; grilledBox.LayoutParameters = linearLayoutParams; frame.AddView(grilledBox); tikkaBox = new SfCheckBox(con); tikkaBox.Text = "Chicken Tikka"; tikkaBox.TextSize = 15; tikkaBox.SetTextColor(Color.ParseColor("#FF000000")); tikkaBox.StateChanged += NonvegToppingsChanged; tikkaBox.LayoutParameters = linearLayoutParams; frame.AddView(tikkaBox); sausaga = new SfCheckBox(con); sausaga.Text = "Chicken Sausage"; sausaga.TextSize = 15; sausaga.SetTextColor(Color.ParseColor("#FF000000")); sausaga.StateChanged += NonvegToppingsChanged; sausaga.LayoutParameters = linearLayoutParams; frame.AddView(sausaga); beefBox = new SfCheckBox(con); beefBox.Text = "Beef"; beefBox.TextSize = 15; beefBox.SetTextColor(Color.ParseColor("#FF000000")); beefBox.StateChanged += NonvegToppingsChanged; beefBox.LayoutParameters = linearLayoutParams; frame.AddView(beefBox); frameParent.AddView(frame); linear.AddView(frameParent); #endregion button = new Button(con); button.SetWidth(ActionBar.LayoutParams.MatchParent); button.SetHeight(43); button.TextSize = 21; button.Text = "Order Now"; button.SetBackgroundColor(Color.ParseColor("#FF007DE6")); button.SetTextColor(Color.ParseColor("#73FFFFFF")); button.Click += SearchButton_Click; button.Enabled = false; linear.AddView(button); resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); return linear; } public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = Java.Lang.Math.Sqrt(Math.Pow(screenWidth, 2) + Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } private void NonVegBox_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { grilledBox.Visibility = tikkaBox.Visibility = sausaga.Visibility = beefBox.Visibility = ViewStates.Visible; } else { grilledBox.Visibility = tikkaBox.Visibility = sausaga.Visibility = beefBox.Visibility = ViewStates.Gone; } if (!e.IsChecked) { selectAllBox.Checked = false; grilledBox.Checked = tikkaBox.Checked = sausaga.Checked = beefBox.Checked = false; } } private void SearchButton_Click(object sender, EventArgs e) { bool? temp = ValidateNonVegToopings(); if (!temp.HasValue || (temp.HasValue && temp.Value)) { resultsDialog.SetMessage("Your order has been placed successfully !"); selectAllBox.Checked = false; } resultsDialog.Create().Show(); } private bool? ValidateNonVegToopings() { if (grilledBox.Checked.Value && tikkaBox.Checked.Value && sausaga.Checked.Value && beefBox.Checked.Value) return true; else if (!grilledBox.Checked.Value && !tikkaBox.Checked.Value && !sausaga.Checked.Value && !beefBox.Checked.Value) return false; else return null; } private void NonvegToppingsChanged(object sender, Syncfusion.Android.Buttons.StateChangedEventArgs eventArgs) { if (!skip) { skip = true; selectAllBox.Checked = ValidateNonVegToopings(); if (!selectAllBox.Checked.HasValue || (selectAllBox.Checked.HasValue && selectAllBox.Checked.Value)) { button.Enabled = true; button.SetTextColor(Color.ParseColor("#FFFFFF")); } else { button.Enabled = false; button.SetTextColor(Color.ParseColor("#73FFFFFF")); } skip = false; } } private void SelectAll1_StateChanged(object sender, Syncfusion.Android.Buttons.StateChangedEventArgs eventArgs) { if (!skip) { skip = true; grilledBox.Checked = tikkaBox.Checked = sausaga.Checked = beefBox.Checked = eventArgs.IsChecked.Value; button.Enabled = eventArgs.IsChecked.Value; if (button.Enabled) { button.SetTextColor(Color.ParseColor("#FFFFFF")); } else { button.SetTextColor(Color.ParseColor("#73FFFFFF")); } skip = false; } } } }<file_sep>/Forms/NumericTextBox/NumericTextBox/Samples/NumericTextBox/NumericTextBox_Tablet.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfNumericTextBox.XForms; using Syncfusion.XForms.Editors; using Xamarin.Forms; namespace SampleBrowser.SfNumericTextBox { public partial class NumericTextBox_Tablet : SampleView { StackLayout view; Button closeButton; Switch allowNullToggle; Picker localePicker; int precision = 0; bool tooltip = true; Label allowNullLabel; double width; public NumericTextBox_Tablet() { InitializeComponent(); width = Core.SampleBrowser.ScreenWidth; clearButtonPicker.SelectedIndex = precision; getPropertiesWindow(); DevicesChanges(); } public void getPropertiesWindow() { view = new StackLayout(); view.HeightRequest = Property_Windows.HeightRequest; view.BackgroundColor = Color.FromRgb(250, 250, 250); if (Device.RuntimePlatform == Device.iOS) { Property_Windows.HeightRequest = 250; } StackLayout propertyLayout = new StackLayout(); propertyLayout.Orientation = StackOrientation.Horizontal; propertyLayout.BackgroundColor = Color.FromRgb(230, 230, 230); propertyLayout.Padding = new Thickness(10, 0, 0, 0); TapGestureRecognizer tab = new TapGestureRecognizer(); tab.Tapped += tab_Tapped; propertyLayout.GestureRecognizers.Add(tab); Label propertyLabel = new Label(); propertyLabel.Text = "OPTIONS"; propertyLabel.WidthRequest = 150; propertyLabel.VerticalOptions = LayoutOptions.Center; propertyLabel.HorizontalOptions = LayoutOptions.Start; propertyLabel.FontFamily = "Helvetica"; propertyLabel.FontSize = 20; closeButton = new Button(); if (Device.RuntimePlatform == Device.iOS) { closeButton.Text = "X"; closeButton.TextColor = Color.FromRgb(51, 153, 255); } else if (Device.RuntimePlatform == Device.Android) { closeButton.ImageSource = "cancelsearch.png"; }else{ closeButton.ImageSource = "sfclosebutton.png"; } closeButton.Clicked += Close_Button; closeButton.HorizontalOptions = LayoutOptions.EndAndExpand; propertyLayout.Children.Add(propertyLabel); propertyLayout.Children.Add(closeButton); temp.BackgroundColor = Color.FromRgb(230, 230, 230); closeButton.BackgroundColor = Color.FromRgb(230, 230, 230); Property_Button.BackgroundColor = Color.FromRgb(230, 230, 230); StackLayout emptyLayout = new StackLayout(); emptyLayout.Orientation = StackOrientation.Vertical; emptyLayout.BackgroundColor = Color.FromRgb(250, 250, 250); if (Device.RuntimePlatform == Device.iOS) { emptyLayout.Padding = new Thickness(60, 20, 40, 40); } else { emptyLayout.Padding = new Thickness(30, 20, 40, 40); } StackLayout cultureLayout = new StackLayout(); cultureLayout.Orientation = StackOrientation.Horizontal; cultureLayout.Padding = new Thickness(100, 20, 0, 20); Label cultureLabel = new Label(); cultureLabel.Text = "Culture"; cultureLabel.WidthRequest = 150; cultureLabel.VerticalOptions = LayoutOptions.Center; cultureLabel.HorizontalOptions = LayoutOptions.End; cultureLabel.FontFamily = "Helvetica"; cultureLabel.FontSize = 16; localePicker = new Picker(); localePicker.VerticalOptions = LayoutOptions.Center; localePicker.HorizontalOptions = LayoutOptions.Start; localePicker.Items.Add("United States"); localePicker.Items.Add("United Kingdom"); localePicker.Items.Add("Japan"); localePicker.Items.Add("France"); localePicker.Items.Add("Italy"); localePicker.SelectedIndex = precision; localePicker.SelectedIndexChanged += localePicker_Changed; cultureLayout.Children.Add(cultureLabel); cultureLayout.Children.Add(localePicker); StackLayout allowNullLayout = new StackLayout(); allowNullLayout.Orientation = StackOrientation.Horizontal; allowNullLayout.Padding = new Thickness(100, 20, 0, 20); allowNullLabel = new Label(); allowNullLabel.Text = "Allow Null"; allowNullLabel.WidthRequest = 150; allowNullLabel.VerticalOptions = LayoutOptions.Center; allowNullLabel.HorizontalOptions = LayoutOptions.End; allowNullLabel.FontFamily = "Helvetica"; allowNullLabel.FontSize = 16; allowNullToggle = new Switch(); allowNullToggle.Toggled += toggleStateChanged; allowNullToggle.IsToggled = tooltip; allowNullToggle.HorizontalOptions = LayoutOptions.Start; allowNullToggle.VerticalOptions = LayoutOptions.Center; allowNullLayout.Children.Add(allowNullLabel); allowNullLayout.Children.Add(allowNullToggle); emptyLayout.Children.Add(cultureLayout); emptyLayout.Children.Add(allowNullLayout); view.Children.Add(propertyLayout); view.Children.Add(emptyLayout); Property_Windows.Children.Remove(temp); //Property_Windows.Children.Insert(0, view); } void tab_Tapped(object sender, EventArgs e) { closeAction(); } void tap_Gestue_Prob_Tapped(object sender, EventArgs e) { getPropertiesWindow(); } public void closeAction() { view.BackgroundColor = Color.White; Property_Windows.Children.Add(temp); Property_Windows.Children.Remove(view); } public void Property_Button_Clicked(object c, EventArgs e) { getPropertiesWindow(); } public void localePicker_Changed(object c, EventArgs e) { switch (localePicker.SelectedIndex) { case 0: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); precision = 0; } break; case 1: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("en-GB"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("en-GB"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("en-GB"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("en-GB"); precision = 1; } break; case 2: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("ja-JP"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("ja-JP"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("ja-JP"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("ja-JP"); precision = 2; } break; case 3: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("fr-FR"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("fr-FR"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("fr-FR"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("fr-FR"); precision = 3; } break; case 4: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("it-IT"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("it-IT"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("it-IT"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("it-IT"); precision = 4; } break; } } public void toggleStateChanged(object c, ToggledEventArgs e) { if (e.Value) { principalNumericTextBox.AllowNull = e.Value; interestRateNumericTextBox.AllowNull = e.Value; termNumericTextBox.AllowNull = e.Value; interestNumericTextBox.AllowNull = e.Value; tooltip = e.Value; } else { principalNumericTextBox.AllowNull = e.Value; interestRateNumericTextBox.AllowNull = e.Value; termNumericTextBox.AllowNull = e.Value; interestNumericTextBox.AllowNull = e.Value; tooltip = e.Value; } } void DevicesChanges() { TapGestureRecognizer tap_Gestue_Prob = new TapGestureRecognizer(); tap_Gestue_Prob.Tapped += tap_Gestue_Prob_Tapped; temp.GestureRecognizers.Add(tap_Gestue_Prob); if (Device.Idiom == TargetIdiom.Tablet) { width /= 2; } Property_Button.Clicked += Property_Button_Clicked; principalNumericTextBox.ValueChanged += (object sender, ValueEventArgs e) => { if (e.Value == null) interestNumericTextBox.Value = 0.0; else interestNumericTextBox.Value = Convert.ToDouble(interestRateNumericTextBox.Value.ToString()) * Convert.ToDouble(e.Value.ToString()) * Convert.ToDouble(termNumericTextBox.Value.ToString()); }; principalNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); interestRateNumericTextBox.ValueChanged += (object sender, ValueEventArgs e) => { if (e.Value == null) interestNumericTextBox.Value = 0.0; else interestNumericTextBox.Value = Convert.ToDouble(principalNumericTextBox.Value.ToString()) * Convert.ToDouble(e.Value.ToString()) * Convert.ToDouble(termNumericTextBox.Value.ToString()); }; interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); termNumericTextBox.ValueChanged += (object sender, ValueEventArgs e) => { if (e.Value == null) interestNumericTextBox.Value = 0.0; else interestNumericTextBox.Value = Convert.ToDouble(principalNumericTextBox.Value.ToString()) * Convert.ToDouble(interestRateNumericTextBox.Value.ToString()) * Convert.ToDouble(e.Value.ToString()); }; termNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); if (Device.RuntimePlatform == Device.iOS) { principalNumericTextBox.WidthRequest = width / 2; interestRateNumericTextBox.WidthRequest = width / 2; termNumericTextBox.WidthRequest = width / 2; interestNumericTextBox.WidthRequest = width / 2; } else if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { principalNumericTextBox.WidthRequest = width / 2; interestRateNumericTextBox.WidthRequest = width / 2; termNumericTextBox.WidthRequest = width / 2; interestNumericTextBox.WidthRequest = width / 2; principalNumericTextBox.HeightRequest = 75; interestRateNumericTextBox.HeightRequest = 75; termNumericTextBox.HeightRequest = 75; interestNumericTextBox.HeightRequest = 75; interestRateNumericTextBox.FormatString = "0 %"; termNumericTextBox.FormatString = "0 years"; } else { principalNumericTextBox.WidthRequest = width / 3; interestRateNumericTextBox.WidthRequest = width / 3; termNumericTextBox.WidthRequest = width / 3; interestNumericTextBox.WidthRequest = width / 3; } if (Device.RuntimePlatform == Device.UWP) { simpleInterestCalculatorLabel.TextColor = Color.Gray; findingSimpleInterestLabel.TextColor = Color.Gray; principalLabel.TextColor = Color.Gray; interestRateLabel.TextColor = Color.Gray; termLabel.TextColor = Color.Gray; interestLabel.TextColor = Color.Gray; interestRateNumericTextBox.FormatString = "0 %"; termNumericTextBox.FormatString = "0 years"; if (Device.Idiom != TargetIdiom.Tablet) { interestNumericTextBox.IsEnabled = true; } } } public void Close_Button(object c, EventArgs e) { closeAction(); } public View getContent() { return this.Content; } private void OnClearButtonPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (clearButtonPicker.SelectedIndex) { case 0: { principalNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; interestRateNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; termNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; interestNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; } break; case 1: { principalNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.Never; interestRateNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.Never; termNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.Never; interestNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.Never; } break; } } } } <file_sep>/Forms/Kanban/Kanban/Samples/KanbanCustomizationSample/KanbanCutomizationSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.Generic; using Syncfusion.SfKanban.XForms; using Xamarin.Forms; using SampleBrowser.Core; using Xamarin.Forms.Internals; namespace SampleBrowser.SfKanban { [Preserve(AllMembers = true)] public partial class KanbanCustomizationSample : SampleView { KanbanCustomViewModel model; public KanbanCustomizationSample() { model = new KanbanCustomViewModel(); InitializeComponent(); kanban.BindingContext = model; column1.Categories = new List<object>() { "Menu" }; column2.Categories = new List<object>() { "Dining", "Delivery" }; column3.Categories = new List<object>() { "Ready to Serve" }; column4.Categories = new List<object>() { "Door Delivery" }; KanbanErrorBarSettings errorBar = new KanbanErrorBarSettings(); errorBar.Height = 2; errorBar.Color = Color.FromRgb(179.0f / 255.0f, 71.0f / 255.0f, 36.0f / 255.0f); errorBar.MaxValidationColor = Color.FromRgb(211.0f / 255.0f, 51.0f / 255.0f, 54.0f / 255.0f); errorBar.MinValidationColor = Color.FromRgb(67.0f / 255.0f, 188.0f / 255.0f, 131.0f / 255.0f); column1.ErrorbarSettings = column2.ErrorbarSettings = column3.ErrorbarSettings = column4.ErrorbarSettings = errorBar; column1.AllowDrop = false; column3.AllowDrag = column4.AllowDrag = false; KanbanPlaceholderStyle style = new KanbanPlaceholderStyle(); style.SelectedBackgroundColor = Color.FromRgb(250.0f / 255.0f, 199.0f / 255.0f, 173.0f / 255.0f); kanban.PlaceholderStyle = style; List<KanbanWorkflow> flows = new List<KanbanWorkflow>(); flows.Add(new KanbanWorkflow("Menu", new List<object>() { "Dining", "Delivery" })); flows.Add(new KanbanWorkflow("Dining", new List<object>() { "Ready to Serve" })); flows.Add(new KanbanWorkflow("Delivery", new List<object>() { "Door Delivery" })); flows.Add(new KanbanWorkflow("Ready to Serve", new List<object>() { })); flows.Add(new KanbanWorkflow("Door Delivery", new List<object>() { })); kanban.Workflows = flows; } void Handle_DragEnd(object sender, KanbanDragEndEventArgs e) { if (e.TargetColumn != null && e.SourceColumn.Title.ToString() == "Menu" && e.TargetColumn.Title.ToString() == "Order") { e.Cancel = true; model.LastOrderID += 1; model.Cards.Add(CloneModel((e.Data as CustomKanbanModel), e.TargetCategory)); } else if (e.TargetColumn != null && e.TargetCategory != null) { (e.Data as CustomKanbanModel).Category = e.TargetCategory; } } void Handle_DragStart(object sender, KanbanDragStartEventArgs e) { if ((e.Data as CustomKanbanModel).Category.ToString() == "Menu") e.KeepItem = true; } void Handle_DragOver(object sender, KanbanDragOverEventArgs e) { if (e.TargetColumn.Title.ToString() == "Menu") e.Cancel = true; } CustomKanbanModel CloneModel(CustomKanbanModel datamodel, object category) { CustomKanbanModel newModel = new CustomKanbanModel(); newModel.ImageURL = datamodel.ImageURL; newModel.Category = category; newModel.ColorKey = datamodel.ColorKey; newModel.Description = datamodel.Description; newModel.ID = datamodel.ID; newModel.Tags = datamodel.Tags; newModel.Title = datamodel.Title; newModel.OrderID = "Order ID - #" + model.LastOrderID.ToString(); return newModel; } } public class KanbanTemplateSelector : DataTemplateSelector { private readonly DataTemplate menuTemplate; private readonly DataTemplate orderTemplate; private readonly DataTemplate readyToServeTemplate; private readonly DataTemplate deliveryTemplate; public KanbanTemplateSelector() { menuTemplate = new DataTemplate(typeof(MenuTemplate)); orderTemplate = new DataTemplate(typeof(OrderTemplate)); readyToServeTemplate = new DataTemplate(typeof(ReadyToServeTemplate)); deliveryTemplate = new DataTemplate(typeof(DeliveryTemplate)); } protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { var data = item as CustomKanbanModel; if (data == null) return null; string category = data.Category?.ToString(); if (category == null) return null; return category.Equals("Menu") ? menuTemplate : category.Equals("Dining") || category.Equals("Delivery") ? orderTemplate : category.Equals("Ready to Serve") ? readyToServeTemplate : deliveryTemplate; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/FormsView.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "FormsView.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfDataGrid.XForms; using Syncfusion.XForms.Buttons; using Xamarin.Forms; /// <summary> /// A layout which positions child elements in a single line which can be oriented vertically or horizontally. /// </summary> public class FormsView : StackLayout { #region Fields [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private OrderInfo swipedRowData; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid grid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private bool isSuspend; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private bool isLoaded; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private bool visibility = true; #endregion #region Constructor /// <summary> /// Initializes a new instance of the FormsView class. /// </summary> /// <param name="grid">Which indicates DataGrid Instance</param> public FormsView(Syncfusion.SfDataGrid.XForms.SfDataGrid grid) { this.isSuspend = true; this.grid = grid; if (Device.RuntimePlatform != Device.UWP) { this.Visibility = false; } else { this.IsVisible = false; } this.Columns = grid.Columns; this.Spacing = 10; this.BackgroundColor = Color.FromRgb(43, 43, 43); this.Orientation = StackOrientation.Vertical; this.Padding = new Thickness(10); this.FormContentView = new StackLayout() { Orientation = StackOrientation.Horizontal, Spacing = 20 }; if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.macOS) { this.BackgroundColor = Color.Black; this.Footer = new StackLayout() { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.CenterAndExpand, Spacing = 5 }; if (Device.RuntimePlatform == Device.UWP) { this.SaveButton = new SfButton { WidthRequest = 150, FontSize = 16, HeightRequest = 80, Text = "SAVE", HorizontalOptions = LayoutOptions.CenterAndExpand, BackgroundColor = Color.FromHex("#333333"), TextColor = Color.White }; this.CancelButton = new SfButton { WidthRequest = 150, FontSize = 16, HeightRequest = 80, Text = "CANCEL", HorizontalOptions = LayoutOptions.CenterAndExpand, BackgroundColor = Color.FromHex("#333333"), TextColor = Color.White }; } else { this.Save = new Button { WidthRequest = 150, FontSize = 16, Text = "SAVE", HorizontalOptions = LayoutOptions.CenterAndExpand, BackgroundColor = Color.FromHex("#333333"), TextColor = Color.White }; this.Cancel = new Button { WidthRequest = 150, FontSize = 16, Text = "CANCEL", HorizontalOptions = LayoutOptions.CenterAndExpand, BackgroundColor = Color.FromHex("#333333"), TextColor = Color.White }; } } else { this.Footer = new StackLayout() { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.EndAndExpand }; this.Save = new Button { FontSize = 18, Text = "SAVE", HorizontalOptions = LayoutOptions.End, BackgroundColor = Color.Transparent, TextColor = Color.FromHex("#EC407A") }; this.Cancel = new Button { FontSize = 18, Text = "CANCEL", HorizontalOptions = LayoutOptions.End, BackgroundColor = Color.Transparent, TextColor = Color.FromHex("#EC407A") }; } if (Device.RuntimePlatform == Device.UWP) { this.SaveButton.Clicked += this.Save_Clicked; this.CancelButton.Clicked += this.Cancel_Clicked; this.Footer.Children.Add(new ContentView() { Content = this.SaveButton }); this.Footer.Children.Add(new ContentView() { Content = this.CancelButton }); } else { this.Save.Clicked += this.Save_Clicked; this.Cancel.Clicked += this.Cancel_Clicked; this.Footer.Children.Add(new ContentView() { Content = this.Save }); this.Footer.Children.Add(new ContentView() { Content = this.Cancel }); } this.Title = new Label { Text = "Edit Details", Margin = new Thickness(15, 15, 0, 0), FontSize = 20, HeightRequest = 30, TextColor = Color.White }; this.HeaderView = new StackLayout() { Orientation = StackOrientation.Vertical, Spacing = 5, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand }; this.EditorView = new StackLayout() { Orientation = StackOrientation.Vertical, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Spacing = 5 }; this.EditorView.BindingContextChanged += this.EditView_BindingContextChanged; this.isSuspend = false; } #endregion #region Property /// <summary> /// Gets or sets the value of Columns /// </summary> public Columns Columns { get; set; } /// <summary> /// Gets or sets the value of HeaderView /// </summary> public StackLayout HeaderView { get; set; } /// <summary> /// Gets or sets the value of EditorView /// </summary> public StackLayout EditorView { get; set; } /// <summary> /// Gets or sets the value of Title /// </summary> public Label Title { get; set; } /// <summary> /// Gets or sets the value of Footer /// </summary> public StackLayout Footer { get; set; } /// <summary> /// Gets or sets a value indicating whether Visibility has true or false value and notifies user when value has changed /// </summary> public bool Visibility { get { return this.visibility; } set { this.visibility = value; this.OnPropertyChanged("Visibility"); } } /// <summary> /// Gets or sets the value of Save /// </summary> private SfButton SaveButton { get; set; } /// <summary> /// Gets or sets the value of Cancel /// </summary> private SfButton CancelButton { get; set; } /// <summary> /// Gets or sets the value of Save /// </summary> private Button Save { get; set; } /// <summary> /// Gets or sets the value of Cancel /// </summary> private Button Cancel { get; set; } /// <summary> /// Gets or sets the value of FormContentView /// </summary> private StackLayout FormContentView { get; set; } #endregion #region Protected Methods /// <summary> /// Method to decide whether to call <see cref="Xamarin.Forms.VisualElement.InvalidateMeasure()"/> when adding a child. /// </summary> /// <param name="child">A child of the <see cref="SfDataGrid"/>.</param> /// <returns>A boolean value do decide whether to invalidate when adding a child.</returns> protected override bool ShouldInvalidateOnChildAdded(View child) { return false; } /// <summary> /// Method to decide whether to call <see cref="Xamarin.Forms.VisualElement.InvalidateMeasure()"/> when removing a child. /// </summary> /// <param name="child">A child of the <see cref="SfDataGrid"/>.</param> /// <returns>A boolean value do decide whether to invalidate when removing a child.</returns> protected override bool ShouldInvalidateOnChildRemoved(View child) { return false; } /// <summary> /// This method is called when the size of the element is set during a layout cycle. This method is called directly /// before the <see cref="Xamarin.Forms.VisualElement.SizeChanged"/> event is emitted. /// </summary> /// <param name="width">The new width of the element.</param> /// <param name="height">The new height of the element.</param> protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (this.isSuspend || this.isLoaded) { return; } foreach (var column in Columns) { var labelContentView = new ContentView(); var editorContentView = new ContentView(); var colonContentView = new ContentView(); var label = new Label() { BackgroundColor = Color.Transparent, WidthRequest = (this.Parent as VisualElement).Width / 3, HeightRequest = 50, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, FontSize = 15, TextColor = Color.Gray, HorizontalTextAlignment = TextAlignment.End, VerticalTextAlignment = TextAlignment.Center, Text = column.HeaderText, BindingContext = this.BindingContext }; var editor = new GridCustomEntry() { BackgroundColor = Color.Transparent, TextColor = Color.White, WidthRequest = (this.Parent as VisualElement).Width / 3, HeightRequest = 50, HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, BindingContext = this.BindingContext }; editor.SetBinding(Entry.TextProperty, new Binding(column.MappingName, BindingMode.TwoWay)); if (column.MappingName == "Name") { label.Text = "<NAME>"; } if (Device.RuntimePlatform == Device.macOS) { editor.BackgroundColor = Color.Black; label.HorizontalOptions = LayoutOptions.StartAndExpand; } labelContentView.Content = label; editorContentView.Content = editor; this.HeaderView.Children.Add(labelContentView); this.EditorView.Children.Add(editorContentView); } var scrollView = new ScrollView(); scrollView.Orientation = ScrollOrientation.Vertical; scrollView.Content = this.FormContentView; this.FormContentView.Children.Add(this.HeaderView); this.FormContentView.Children.Add(this.EditorView); this.Children.Add(this.Title); this.Children.Add(scrollView); this.Children.Add(this.Footer); this.isLoaded = true; } #endregion #region Private Methods /// <summary> /// Triggers while Cancel button was clicked /// </summary> /// <param name="sender">Cancel_Clicked event sender</param> /// <param name="e">Cancel_Clicked event args e</param> private void Cancel_Clicked(object sender, EventArgs e) { var editedrow = this.EditorView.BindingContext as OrderInfo; editedrow.CustomerID = this.swipedRowData.CustomerID; editedrow.EmployeeID = this.swipedRowData.EmployeeID; editedrow.OrderID = this.swipedRowData.OrderID; editedrow.ShipCountry = this.swipedRowData.ShipCountry; editedrow.FirstName = this.swipedRowData.FirstName; if (Device.RuntimePlatform != Device.UWP) { this.Visibility = false; } else { this.IsVisible = false; } this.grid.Opacity = 1.0; this.grid.IsEnabled = true; } /// <summary> /// Triggers while save button was clicked /// </summary> /// <param name="sender">Save_Clicked event sender</param> /// <param name="e">Save_Clicked event args e</param> private void Save_Clicked(object sender, EventArgs e) { if (Device.RuntimePlatform != Device.UWP) { this.Visibility = false; } else { this.IsVisible = false; } this.grid.Opacity = 1.0; this.grid.IsEnabled = true; } /// <summary> /// Triggers while EditView binding context was changed /// </summary> /// <param name="sender">EditView_BindingContextChanged event sender</param> /// <param name="e">EditView_BindingContextChanged event args e</param> private void EditView_BindingContextChanged(object sender, EventArgs e) { var orderInfo = this.EditorView.BindingContext as OrderInfo; if (orderInfo != null) { this.swipedRowData = new OrderInfo() { ShipCountry = orderInfo.ShipCountry, EmployeeID = orderInfo.EmployeeID, OrderID = orderInfo.OrderID, CustomerID = orderInfo.CustomerID, FirstName = orderInfo.FirstName }; foreach (ContentView child in this.EditorView.Children) { child.Content.BindingContext = this.EditorView.BindingContext; } } } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/Rating/readme.md The `SfRating` control provides the number of stars that represents a rating value, with this user can rate an application by clicking on the star. The following sample is available for rating control to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](Rating.cs)| It demonstrates the accuracy level of filling the rating star, modifying the rating count and positioning the tooltips.| <file_sep>/Forms/ListView/ListView.Android/Helper/SfImageRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Xamarin.Forms; using Syncfusion.ListView.XForms; using Syncfusion.ListView.XForms.Android; using Xamarin.Forms.Platform.Android; using System.IO; using System.Reflection; using Android.Graphics; using System.ComponentModel; using System.Threading.Tasks; using Java.Lang; using SampleBrowser.SfListView.Droid.Helper; using SampleBrowser.SfListView; [assembly: ExportRenderer(typeof(SampleBrowser.SfListView.SfImage), typeof(SfImageRenderer))] namespace SampleBrowser.SfListView.Droid.Helper { /// <summary> /// Represents a renderer of <see cref="Syncfusion.ListView.XForms.SfImage"/> /// </summary> [Preserve(AllMembers = true)] internal class SfImageRenderer : ViewRenderer<SfImage, ImageView> { #region Fields /// <summary> /// Used to process the function in the <see cref="Runnable"/> thread in which bitmap image is set to <see cref="ImageView"/>. /// </summary> private Handler mainHandler; #endregion #region Properties /// <summary> /// Gets or sets the <see cref="ImageView"/>. /// </summary> private ImageView NativeImage { get; set; } #endregion #region Constructor #pragma warning disable CS0618 // Type or member is obsolete /// <summary> /// Initializes a new instance of the <see cref="SfImageRenderer"/> class. /// </summary> public SfImageRenderer() { AutoPackage = false; mainHandler = new Handler(Looper.MainLooper); } #pragma warning restore CS0618 // Type or member is obsolete #endregion #region Override Methods /// <summary> /// Method to define the equivalent native image view for <see cref="SfImage"/>. /// </summary> /// <param name="e">Represents the element changed event arguments for <see cref="SfImage"/>.</param> protected override void OnElementChanged(ElementChangedEventArgs<SfImage> e) { if (e.NewElement != null) { NativeImage = new ImageView(Context); #pragma warning disable CS0618 // Type or member is obsolete NativeImage.DrawingCacheEnabled = true; #pragma warning restore CS0618 // Type or member is obsolete this.SetNativeControl(NativeImage); SetImageSourceToNativeView(); UpdateAspect(); } } /// <summary> /// Updates the <see cref="SfImageRenderer"/> when <see cref="SfImage"/> properties are changed. /// </summary> /// <param name="sender">Respresents the <see cref="SfImage"/>.</param> /// <param name="e">Represents the property changed event arguments.</param> protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Source") { SetImageSourceToNativeView(); } else if (e.PropertyName == "Aspect") { UpdateAspect(); } else base.OnElementPropertyChanged(sender, e); } #endregion #region Private Methods /// <summary> /// Updates the <see cref="NativeImage"/>'s scale type based on the <see cref="Image.Aspect"/> property. /// </summary> private void UpdateAspect() { if (Element == null || NativeImage == null) return; ImageView.ScaleType type = this.GetScaleType(Element.Aspect); NativeImage.SetScaleType(type); } /// <summary> /// Decodes the <see cref="Bitmap"/> image from <see cref="ImageSource"/>. /// </summary> /// <returns>Returns the <see cref="Bitmap"/>.</returns> private async Task<Bitmap> GetBitMapImageFromSource() { if (this.Element.Source == null) return null; var imageHandler = this.GetHandler(Element.Source); if (imageHandler != null) { var bitmapimage = await imageHandler.LoadImageAsync(Element.Source, NativeImage.Context); imageHandler = null; return bitmapimage; } imageHandler = null; return null; } /// <summary> /// Loads the <see cref="SfImage.Source"/> to <see cref="ImageView"/>. /// </summary> private async void SetImageSourceToNativeView() { var bitmapimage = await GetBitMapImageFromSource(); Runnable myRunnable = new Runnable(() => { if (this.Control != null && this.Control.Handle != IntPtr.Zero) { this.Control.SetImageBitmap(bitmapimage); ((IVisualElementController)Element).NativeSizeChanged(); bitmapimage = null; } }); if (mainHandler != null) mainHandler.Post(myRunnable); } /// <summary> /// Helper method to initialize the respective <see cref="IImageSourceHandler"/> to native <see cref="ImageView"/> using <see cref="SfImage.Source"/> property. /// </summary> /// <param name="source">Represents the <see cref="ImageSource"/>.</param> /// <returns>Returns the <see cref="IImageSourceHandler"/> based on <see cref="ImageSource"/>.</returns> private IImageSourceHandler GetHandler(ImageSource source) { IImageSourceHandler sourcehandler = null; if (source is UriImageSource) { sourcehandler = new ImageLoaderSourceHandler(); } else if (source is FileImageSource) { sourcehandler = new FileImageSourceHandler(); } else if (source is StreamImageSource) { sourcehandler = new StreamImagesourceHandler(); } return sourcehandler; } /// <summary> /// Helper method to get the <see cref="NativeImage"/>'s scale type from the <see cref="Image.Aspect"/> property. /// </summary> /// <param name="aspect">Represents the <see cref="Aspect"/> property of <see cref="Image"/>.</param> /// <returns>Returns the <see cref="ImageView.ScaleType"/> value.</returns> public ImageView.ScaleType GetScaleType(Aspect aspect) { switch (aspect) { case Aspect.Fill: return ImageView.ScaleType.FitXy; case Aspect.AspectFill: return ImageView.ScaleType.CenterCrop; default: case Aspect.AspectFit: return ImageView.ScaleType.FitCenter; } } #endregion #region Dispose Methods /// <summary> /// Dispose the instances, if parameter is true. /// </summary> /// <param name="disposing">Represents the boolean value for disposing objects</param> protected override void Dispose(bool disposing) { if (disposing) { NativeImage = null; mainHandler = null; GC.SuppressFinalize(this); } base.Dispose(disposing); } #endregion } }<file_sep>/Forms/ImageEditor/ImageEditor/Samples/Serialization/SerializationContentPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Threading.Tasks; using Syncfusion.ListView.XForms; using Syncfusion.SfImageEditor.XForms; using Xamarin.Forms; namespace SampleBrowser.SfImageEditor { public partial class SerializationContentPage : ContentPage { SerializationModel SelectedItem; SerializationViewModel mainModel; string itemName = ""; Assembly assembly = typeof(ImageSerializeModel).GetTypeInfo().Assembly; void ImageEditor_ImageSaving(object sender, Syncfusion.SfImageEditor.XForms.ImageSavingEventArgs args) { SerializationModel newItem = new SerializationModel(); if (SelectedItem.ImageName == "CreateNew") { var serializationModel = new SerializationModel() { SelectionImage = new FontImageSource() { Glyph = "\ue718", FontFamily = Device.RuntimePlatform == Device.iOS ? "Sync FontIcons" : Device.RuntimePlatform == Device.Android ? "Sync FontIcons.ttf#" : "Sync FontIcons.ttf#Sync FontIcons", Color = Color.LightGray }, ImageName = itemName != "" ? itemName : ValidateName(), HorizontalOption = LayoutOptions.FillAndExpand, VerticalOption = LayoutOptions.FillAndExpand, Visibility = "true", Height = 50, BackGround = Color.FromHex("#D3D3D3"), CreateNewvisibility = "false", SelectedImageVisibility = "false", SelectedItemThickness = new Thickness(0, 0, 0, 0), Strm = imageEditor.SaveEdits() }; mainModel.ModelList.Add(serializationModel); SelectedItem = serializationModel; } else { SelectedItem.Strm = imageEditor.SaveEdits(); } } void ImageEditor_ImageSaved(object sender, Syncfusion.SfImageEditor.XForms.ImageSavedEventArgs args) { if (Device.RuntimePlatform != "iOS") { SelectedItem.Location = args.Location; } else { SelectedItem.SetLocation(args.Location); } } public SerializationContentPage(SerializationModel selectedItem, Syncfusion.ListView.XForms.SfListView listView, SerializationViewModel model) { InitializeComponent(); mainModel = model; SelectedItem = selectedItem; imageEditor.SetToolbarItemVisibility("save,effects", false); HeaderToolbarItem item1 = new HeaderToolbarItem(); item1.Text = "Save Edits"; item1.Name = "CustomSave"; imageEditor.ImageSaving += ImageEditor_ImageSaving; imageEditor.ImageSaved += ImageEditor_ImageSaved; imageEditor.ToolbarSettings.ToolbarItems.Add(item1); imageEditor.ToolbarSettings.ToolbarItemSelected += (sender, e) => { if (e.ToolbarItem is HeaderToolbarItem) { var text = e.ToolbarItem.Name; if (text == "CustomSave") { if (SelectedItem.ImageName == "CreateNew") { popup.IsVisible = true; grid.IsVisible = true; } else imageEditor.Save(); } } }; if (Device.RuntimePlatform == Device.UWP && SelectedItem.ImageName == "CreateNew") { #if COMMONSB imageEditor.Source = ImageSource.FromResource("SampleBrowser.Icons.Editor_Plain.png", assembly); #else imageEditor.Source = ImageSource.FromResource("SampleBrowser.SfImageEditor.Icons.Editor_Plain.png", assembly); #endif } LoadStream(); } async void LoadStream() { await DelayActionAsync(1500, Action); } void Ok_Clicked(object sender, System.EventArgs e) { itemName = entry.Text; imageEditor.Save(); popup.IsVisible = false; grid.IsVisible = false; entry.Text = ""; } void Cancel_Clicked(object sender, System.EventArgs e) { popup.IsVisible = false; grid.IsVisible = false; entry.Text = ""; } public async Task DelayActionAsync(int delay, Action action) { await Task.Delay(delay); action(); } void Action() { if (SelectedItem.Strm != null) { imageEditor.LoadEdits(SelectedItem.Strm); } else if (SelectedItem.Imagestream != null) { var assembly = typeof(App).GetTypeInfo().Assembly; Stream stream = new MemoryStream(); imageEditor.LoadEdits(assembly.GetManifestResourceStream(SelectedItem.Imagestream)); } } void AddNewTemplate() { } string ValidateName() { String Name = "NewItem"; int j = 1; for (int i = 0; i < mainModel.ModelList.Count; i++) { if (mainModel.ModelList[i].ImageName == Name) { Name = "NewItem " + j; j++; } } return Name; } protected override void OnAppearing() { base.OnAppearing(); } protected override void OnDisappearing() { base.OnDisappearing(); } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/Model/Employee.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class NotificationObject : INotifyPropertyChanged { #region INotifyPropertyChanged Implementation public void RaisePropertyChanged (string propName) { if (this.PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (propName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion } public class BaseEmployee : NotificationObject { #region Private variable private int employeeID; #endregion #region Public property public int EmployeeID { get { return this.employeeID; } set { this.employeeID = value; this.RaisePropertyChanged ("EmployeeID"); } } #endregion } public class Employee : BaseEmployee { #region Private variables private string name; private int contactID; private string title; private DateTime birthDate; private string gender; private double sickLeaveHours; private decimal salary; #endregion #region Public Property public int ContactID { get { return this.contactID; } set { this.contactID = value; this.RaisePropertyChanged ("ContactID"); } } public string Name { get { return this.name; } set { this.name = value; this.RaisePropertyChanged ("Name"); } } public decimal Salary { get { return this.salary; } set { this.salary = value; this.RaisePropertyChanged ("Salary"); } } public string Title { get { return this.title; } set { this.title = value; this.RaisePropertyChanged ("Title"); } } public DateTime BirthDate { get { return this.birthDate; } set { this.birthDate = value; this.RaisePropertyChanged ("BirthDate"); } } public string Gender { get { return this.gender; } set { this.gender = value; this.RaisePropertyChanged ("Gender"); } } public double SickLeaveHours { get { return this.sickLeaveHours; } set { this.sickLeaveHours = value; this.RaisePropertyChanged ("SickLeaveHours"); } } #endregion } } <file_sep>/Android/SampleBrowser/Samples/CircularGauge/GradientRange.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfCircularGauge; using System.Collections.ObjectModel; using Android.Graphics; using Com.Syncfusion.Gauges.SfCircularGauge.Enums; using Android.Renderscripts; namespace SampleBrowser { public class GradientRange : SamplePage { public override View GetSampleContent (Context con) { SfCircularGauge sfCircularGauge = new SfCircularGauge(con); ObservableCollection<Header> headers = new ObservableCollection<Header>(); Header header = new Header(); header.Text = "0"; header.TextSize = 20; header.TextColor = Color.ParseColor("#F03E3E"); header.Position = new PointF((float)0.28, (float)0.86); headers.Add(header); Header header1 = new Header(); header1.Text = "100"; header1.TextSize = 20; header1.TextColor = Color.ParseColor("#30B32D"); header1.Position = new PointF((float)0.75, (float)0.86); headers.Add(header1); Header header2 = new Header(); header2.Text = "55%"; header2.TextSize = 20; header2.TextColor = Color.ParseColor("#F03E3E"); header2.Position = new PointF((float)0.5, (float)0.5); headers.Add(header2); sfCircularGauge.Headers = headers; ObservableCollection<CircularScale> circularScales = new ObservableCollection<CircularScale>(); CircularScale scale = new CircularScale(); scale.StartValue = 0; scale.EndValue = 100; scale.Interval = 10; scale.ShowRim = false; scale.ShowTicks = false; scale.ShowLabels = false; ObservableCollection<CircularRange> ranges = new ObservableCollection<CircularRange>(); CircularRange circularRange = new CircularRange(); circularRange.Offset = 0.8; circularRange.StartValue = 0; circularRange.EndValue = 100; circularRange.Width = 25; ObservableCollection<GaugeGradientStop> gradients = new ObservableCollection<GaugeGradientStop>(); GaugeGradientStop gaugeGradientStop = new GaugeGradientStop(); gaugeGradientStop.Value = 0; gaugeGradientStop.Color = Color.ParseColor("#F03E3E"); gradients.Add(gaugeGradientStop); GaugeGradientStop gaugeGradientStop1 = new GaugeGradientStop(); gaugeGradientStop1.Value = 35; gaugeGradientStop1.Color = Color.ParseColor("#FFDD00"); gradients.Add(gaugeGradientStop1); GaugeGradientStop gaugeGradientStop2 = new GaugeGradientStop(); gaugeGradientStop2.Value = 75; gaugeGradientStop2.Color = Color.ParseColor("#FFDD00"); gradients.Add(gaugeGradientStop2); GaugeGradientStop gaugeGradientStop3 = new GaugeGradientStop(); gaugeGradientStop3.Value = 100; gaugeGradientStop3.Color = Color.ParseColor("#30B32D"); gradients.Add(gaugeGradientStop3); circularRange.GradientStops = gradients; ranges.Add(circularRange); scale.CircularRanges = ranges; ObservableCollection<CircularPointer> pointers = new ObservableCollection<CircularPointer>(); MarkerPointer markerPointer = new MarkerPointer(); markerPointer.MarkerShape = Com.Syncfusion.Gauges.SfCircularGauge.Enums.MarkerShape.InvertedTriangle; markerPointer.Offset = 0.8; markerPointer.MarkerHeight = 15; markerPointer.MarkerWidth = 15; markerPointer.Value = 55; markerPointer.Color = Color.Red; pointers.Add(markerPointer); scale.CircularPointers = pointers; circularScales.Add(scale); sfCircularGauge.CircularScales = circularScales; sfCircularGauge.SetBackgroundColor(Color.White); LinearLayout linearLayout = new LinearLayout(con); linearLayout.AddView(sfCircularGauge); linearLayout.SetPadding(30, 30, 30, 30); linearLayout.SetBackgroundColor(Color.White); return linearLayout; } } } <file_sep>/iOS/SampleBrowser/Samples/Maps/BubbleVisualization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfBusyIndicator.iOS; using System; using Syncfusion.SfMaps.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using CoreGraphics; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGPoint= System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class BubbleVisualization : SampleView { bool TapGesture_ShouldReceiveTouch(UIGestureRecognizer recognizer, UITouch touch) { if (touch.TapCount == 1) { UIApplication.SharedApplication.OpenUrl(new NSUrl("https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population")); } return true; } internal SfBusyIndicator busyindicator; UIView view; UILabel label; UILabel label2; CGSize label2Size; bool isDisposed; public override void LayoutSubviews () { view.Frame = new CGRect(Frame.Location.X,0,Frame.Size.Width,Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X,0,Frame.Size.Width,Frame.Size.Height); label.Frame = new CGRect(0f, 0f, Frame.Size.Width, 40); label2.Frame = new CGRect(Frame.Size.Width - 50, Frame.Size.Height - 20, Frame.Size.Width, 20); SetNeedsDisplay (); } protected override void Dispose(bool disposing) { isDisposed = true; base.Dispose(disposing); } public BubbleVisualization () { SFMap maps = new SFMap (); view = new UIView (); view.Frame=new CGRect(0,0,300,400); busyindicator = new SfBusyIndicator(); busyindicator.ViewBoxWidth=75; busyindicator.ViewBoxHeight=75; busyindicator.Foreground= UIColor.FromRGB (0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType=SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; view.AddSubview (busyindicator); label = new UILabel (); label.TextAlignment = UITextAlignment.Center; label.Text = "Top 40 Population Countries With Bubbles"; label.Font = UIFont.SystemFontOfSize (18); label.Frame=new CGRect(0,0,400,40); label.TextColor = UIColor.Black; view.AddSubview (label); NSTimer.CreateScheduledTimer (TimeSpan.FromSeconds (0.3), delegate { if (isDisposed) return; maps.Frame = new CGRect(Frame.Location.X,60,Frame.Size.Width-6,Frame.Size.Height-60); view.AddSubview (maps); }); SFShapeFileLayer layer = new SFShapeFileLayer (); layer.Uri = (NSString)NSBundle.MainBundle.PathForResource("world1", "shp"); layer.ShapeIDPath = (NSString)"Country"; layer.ShapeIDTableField = (NSString)"NAME"; layer.ShowMapItems = true; layer.DataSource = GetDataSource(); SFShapeSetting shapeSettings = new SFShapeSetting (); shapeSettings.Fill = UIColor.LightGray; layer.ShapeSettings = shapeSettings; SFBubbleMarkerSetting marker = new SFBubbleMarkerSetting(); marker.ValuePath = (NSString)"Percent"; marker.ColorValuePath = (NSString)"Percent"; BubbleCustomTooltipSetting tooltipSetting = new BubbleCustomTooltipSetting(); tooltipSetting.ShowTooltip = true; marker.TooltipSettings = tooltipSetting; ObservableCollection<SFMapColorMapping> colorMappings = new ObservableCollection<SFMapColorMapping>(); SFRangeColorMapping rangeColorMapping1 = new SFRangeColorMapping(); rangeColorMapping1.To = 20; rangeColorMapping1.From = 4; rangeColorMapping1.LegendLabel = (NSString)"Above 4%"; rangeColorMapping1.Color = UIColor.FromRGB(46, 118, 159); colorMappings.Add(rangeColorMapping1); SFRangeColorMapping rangeColorMapping2 = new SFRangeColorMapping(); rangeColorMapping2.To = 4; rangeColorMapping2.From = 2; rangeColorMapping2.LegendLabel = (NSString)"4% - 2%"; rangeColorMapping2.Color = UIColor.FromRGB(216, 68, 68); colorMappings.Add(rangeColorMapping2); SFRangeColorMapping rangeColorMapping3 = new SFRangeColorMapping(); rangeColorMapping3.To = 2; rangeColorMapping3.From = 1; rangeColorMapping3.LegendLabel = (NSString)"2% - 1%"; rangeColorMapping3.Color = UIColor.FromRGB(129, 111, 40); colorMappings.Add(rangeColorMapping3); SFRangeColorMapping rangeColorMapping4 = new SFRangeColorMapping(); rangeColorMapping4.To = 1; rangeColorMapping4.From = 0; rangeColorMapping4.LegendLabel = (NSString)"Below 1%"; rangeColorMapping4.Color = UIColor.FromRGB(127, 56, 160); colorMappings.Add(rangeColorMapping4); marker.ColorMappings = colorMappings; layer.BubbleMarkerSetting = marker; SFMapLegendSettings mapLegendSettings = new SFMapLegendSettings(); mapLegendSettings.ShowLegend = true; mapLegendSettings.LegendType = LegendType.Bubbles; layer.LegendSettings = mapLegendSettings; maps.Layers.Add (layer); label2 = new UILabel(); label2.TextAlignment = UITextAlignment.Center; var text1 = new NSString("en.wikipedia.org"); label2.Text = text1; label2.Font = UIFont.SystemFontOfSize(12); var stringAtribute = new NSDictionary(UIStringAttributeKey.Font, label2.Font, UIStringAttributeKey.ForegroundColor, UIColor.FromRGB(0, 191, 255)); UIStringAttributes strAtr1 = new UIStringAttributes(stringAtribute); label2Size = text1.GetSizeUsingAttributes(strAtr1); label2.TextColor = UIColor.FromRGB(0, 191, 255); label2.Frame = new CGRect(Frame.Size.Width, Frame.Size.Height - 20, 100, 20); label2.UserInteractionEnabled = true; UITapGestureRecognizer tapGesture = new UITapGestureRecognizer(); tapGesture.ShouldReceiveTouch += TapGesture_ShouldReceiveTouch; label2.AddGestureRecognizer(tapGesture); view.AddSubview(label2); AddSubview (view); maps.Delegate = new MapsBubbleDelegate (this); } NSMutableArray GetDataSource() { NSMutableArray array = new NSMutableArray (); array.Add(getDictionary("China", 1393730000, 18.2)); array.Add(getDictionary("India", 1336180000, 17.5)); array.Add(getDictionary("United States", 327726000, 4.29)); array.Add(getDictionary("Indonesia", 265015300, 3.47)); array.Add(getDictionary("Pakistan", 209503000, 2.78)); array.Add(getDictionary("Brazil", 201795000, 2.74)); array.Add(getDictionary("Nigeria", 197306006, 2.53)); array.Add(getDictionary("Bangladesh", 165086000, 2.16)); array.Add(getDictionary("Russia", 146877088, 1.92)); array.Add(getDictionary("Japan", 126490000, 1.66)); array.Add(getDictionary("Mexico", 124737789, 1.63)); array.Add(getDictionary("Ethiopia", 107534882, 1.41)); array.Add(getDictionary("Philippines", 106375000, 1.39)); array.Add(getDictionary("Egypt", 97459100, 1.27)); array.Add(getDictionary("Vietnam", 94660000, 1.24)); array.Add(getDictionary("Germany", 82740900, 1.08)); array.Add(getDictionary("Iran", 81737800, 1.07)); array.Add(getDictionary("Turkey", 80810525, 1.06)); array.Add(getDictionary("Thailand", 69183173, 0.91)); array.Add(getDictionary("France", 67297000, 0.88)); array.Add(getDictionary("United Kingdom", 66040229, 0.86)); array.Add(getDictionary("Italy", 60436469, 0.79)); array.Add(getDictionary("South Africa", 57725600, 0.76)); array.Add(getDictionary("Colombia", 49918600, 0.65)); array.Add(getDictionary("Spain", 46659302, 0.61)); array.Add(getDictionary("Argentina", 44494502, 0.58)); array.Add(getDictionary("Poland", 38433600, 0.5)); array.Add(getDictionary("Canada", 37206700, 0.48)); array.Add(getDictionary("Saudi Arabia", 33413660, 0.44)); array.Add(getDictionary("Malaysia", 32647000, 0.42)); array.Add(getDictionary("Nepal", 29218867, 0.38)); array.Add(getDictionary("Australia", 25015400, 0.32)); array.Add(getDictionary("Kazakhstan", 18253300, 0.24)); array.Add(getDictionary("Cambodia", 16069921, 0.21)); array.Add(getDictionary("Belgium", 11414214, 0.15)); array.Add(getDictionary("Greece", 10768193, 0.14)); array.Add(getDictionary("Sweden", 10171524, 0.13)); array.Add(getDictionary("Somalia", 15181925, 0.12)); array.Add(getDictionary("Austria", 8830487, 0.12)); array.Add(getDictionary("Bulgaria", 7050034, 0.092)); return array; } NSDictionary getDictionary(string name,double population,double percent) { NSString name1= (NSString)name; object[] objects= new object[3]; object[] keys=new object[3]; keys.SetValue ("Country", 0); keys.SetValue ("Population", 1); keys.SetValue ("Percent", 2); objects.SetValue (name1, 0); objects.SetValue (population, 1); objects.SetValue (percent, 2); return NSDictionary.FromObjectsAndKeys (objects, keys); } } public class MapsBubbleDelegate:SFMapsDelegate { public MapsBubbleDelegate(BubbleVisualization bubble) { sample= bubble; } BubbleVisualization sample; public override void DidLoad (SFMap map) { if (sample.busyindicator != null) { sample.busyindicator.RemoveFromSuperview (); sample.busyindicator = null; } } } public class BubbleCustomTooltipSetting : TooltipSetting { public BubbleCustomTooltipSetting() { } public override UIView GetView(object shapeData) { NSDictionary dic = (NSDictionary)shapeData; UIView view = new UIView(); NSString topText = (NSString)(dic["Country"]); NSString bottomText = (NSString)(dic["Percent"].ToString() + "%"); UILabel topLabel = new UILabel(); topLabel.Text = topText; topLabel.Font = UIFont.SystemFontOfSize(12); topLabel.TextColor = UIColor.White; topLabel.TextAlignment = UITextAlignment.Center; UILabel bottomLabel = new UILabel(); bottomLabel.Text = bottomText; bottomLabel.Font = UIFont.SystemFontOfSize(12); bottomLabel.TextColor = UIColor.White; bottomLabel.TextAlignment = UITextAlignment.Center; view.AddSubview(topLabel); view.AddSubview(bottomLabel); CGSize expectedLabelSize1 = topText.GetSizeUsingAttributes(new UIStringAttributes() { Font = topLabel.Font }); CGSize expectedLabelSize2 = bottomText.GetSizeUsingAttributes(new UIStringAttributes() { Font = bottomLabel.Font }); view.Frame = new CGRect(0.0f, 0.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width), 35.0f); topLabel.Frame = new CGRect(0.0f, 0.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width), 15.0f); bottomLabel.Frame = new CGRect(0.0f, 20.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width), 15.0f); return view; } } } <file_sep>/Android/SampleBrowser/Samples/ProgressBar/Linear.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser { using System.Threading.Tasks; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Syncfusion.Android.ProgressBar; public class Linear : SamplePage { private Context context; private LinearLayout.LayoutParams layoutParams; public override View GetSampleContent(Context ctx) { this.context = ctx; this.layoutParams = new LinearLayout.LayoutParams( this.context.Resources.DisplayMetrics.WidthPixels - 120, this.context.Resources.DisplayMetrics.HeightPixels / 18); LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.SetPadding(60, 20, 0, 0); linearLayout.AddView(this.GetLinearDeterminate()); linearLayout.AddView(this.GetLinearIndeterminate()); linearLayout.AddView(this.GetLinearCornerRadius()); linearLayout.AddView(this.GetLinearPadding()); linearLayout.AddView(this.GetLinearRangeColors()); linearLayout.AddView(this.GetLinearRangeColorsWithGradient()); linearLayout.AddView(this.GetLinearBuffer()); linearLayout.AddView(this.GetLinearSegment()); linearLayout.AddView(this.GetLinearSegmentedCornerRadius()); ScrollView scrollView = new ScrollView(this.context); scrollView.AddView(linearLayout); return scrollView; } private View GetTextView(string content) { TextView textView = new TextView(this.context) { Text = content }; textView.TextSize = 15; return textView; } private View GetLinearDeterminate() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(this.GetTextView("Determinate")); linearLayout.AddView(new SfLinearProgressBar(this.context) { Progress = 75, LayoutParameters = this.layoutParams }); return linearLayout; } private View GetLinearSegment() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(this.GetTextView("Segment")); linearLayout.AddView(new SfLinearProgressBar(this.context) { Progress = 75, SegmentCount = 4, LayoutParameters = this.layoutParams }); return linearLayout; } private View GetLinearRangeColors() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(this.GetTextView("Range colors")); RangeColorCollection rangeColorCollection = new RangeColorCollection { new RangeColor { Color = Color.ParseColor("#36BBE1"), Start = 0, End = 25 }, new RangeColor { Color = Color.ParseColor("#9AEDE1"), Start = 25, End = 50 }, new RangeColor { Color = Color.ParseColor("#FFDC28"), Start = 50, End = 75 }, new RangeColor { Color = Color.ParseColor("#E15E0D"), Start = 75, End = 100 } }; SfLinearProgressBar progressBar = new SfLinearProgressBar(this.context) { AnimationDuration = 10000, Progress = 100, LayoutParameters = this.layoutParams, RangeColors = rangeColorCollection }; linearLayout.AddView(progressBar); progressBar.ValueChanged += this.ProgressBar_ValueChanged; return linearLayout; } private View GetLinearRangeColorsWithGradient() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(this.GetTextView("Gradient")); RangeColorCollection rangeColorCollection = new RangeColorCollection { new RangeColor { IsGradient = true, Color = Color.ParseColor("#E9ECF7"), Start = 0, End = 20 }, new RangeColor { IsGradient = true, Color = Color.ParseColor("#A0D9EF"), Start = 20, End = 40 }, new RangeColor { IsGradient = true, Color = Color.ParseColor("#62C1E5"), Start = 40, End = 60 }, new RangeColor { IsGradient = true, Color = Color.ParseColor("#20A7DB"), Start = 60, End = 80 }, new RangeColor { IsGradient = true, Color = Color.ParseColor("#1C96C5"), Start = 80, End = 100 } }; SfLinearProgressBar progressBar = new SfLinearProgressBar(this.context) { AnimationDuration = 10000, Progress = 100, LayoutParameters = this.layoutParams, RangeColors = rangeColorCollection }; progressBar.ValueChanged += this.ProgressBar_ValueChanged; linearLayout.AddView(progressBar); return linearLayout; } private View GetLinearCornerRadius() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(this.GetTextView("Corner radius")); SfLinearProgressBar progressBar = new SfLinearProgressBar(this.context) { AnimationDuration = 10000, Progress = 100, CornerRadius = 10, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged; linearLayout.AddView(progressBar); return linearLayout; } private View GetLinearBuffer() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(this.GetTextView("Buffer")); SfLinearProgressBar progressBar = new SfLinearProgressBar(this.context) { AnimationDuration = 20000, SecondaryAnimationDuration = 10000, Progress = 100, SecondaryProgress = 100, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged1; linearLayout.AddView(progressBar); return linearLayout; } private View GetLinearPadding() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(this.GetTextView("Padding")); SfLinearProgressBar progressBar = new SfLinearProgressBar(this.context) { AnimationDuration = 10000, Progress = 100, CornerRadius = 10, IndicatorPadding = new Thickness(2), LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged; linearLayout.AddView(progressBar); return linearLayout; } private View GetLinearSegmentedCornerRadius() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(this.GetTextView("Segment with corner radius")); SfLinearProgressBar progressBar = new SfLinearProgressBar(this.context) { AnimationDuration = 10000, SegmentCount = 4, Progress = 100, CornerRadius = 10, GapWidth = 7, LayoutParameters = this.layoutParams }; progressBar.ValueChanged += this.ProgressBar_ValueChanged; linearLayout.AddView(progressBar); return linearLayout; } private View GetLinearIndeterminate() { LinearLayout linearLayout = new LinearLayout(this.context) { Orientation = Orientation.Vertical }; linearLayout.AddView(this.GetTextView("Indeterminate")); linearLayout.AddView(new SfLinearProgressBar(this.context) { IsIndeterminate = true, LayoutParameters = this.layoutParams }); return linearLayout; } private async void ProgressBar_ValueChanged1(object sender, ProgressValueEventArgs e) { SfLinearProgressBar progressbar = sender as SfLinearProgressBar; if (e.Progress.Equals(100)) { progressbar.AnimationDuration = 0; progressbar.Progress = 0; progressbar.SecondaryAnimationDuration = 0; progressbar.SecondaryProgress = 0; } if (e.Progress.Equals(0)) { progressbar.AnimationDuration = 20000; await Task.Delay(100); progressbar.Progress = 100; progressbar.SecondaryAnimationDuration = 10000; await Task.Delay(100); progressbar.SecondaryProgress = 100; } } private async void ProgressBar_ValueChanged(object sender, ProgressValueEventArgs e) { SfLinearProgressBar progressbar = sender as SfLinearProgressBar; if (e.Progress.Equals(100)) { progressbar.AnimationDuration = 0; progressbar.Progress = 0; } if (e.Progress.Equals(0)) { progressbar.AnimationDuration = 10000; await Task.Delay(100); progressbar.Progress = 100; } } } }<file_sep>/Android/SampleBrowser/Samples/PDF/Booklet.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.IO; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf; using System.Reflection; namespace SampleBrowser { public partial class Booklet : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to create a booklet from an existing PDF document."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate PDF"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { Stream docStream = typeof(Booklet).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.JavaScript Succinctly.pdf"); PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream); float width = 1224; float height = 792; PdfDocument document = PdfBookletCreator.CreateBooklet(ldoc, new Syncfusion.Drawing.SizeF(width, height), true); MemoryStream stream = new MemoryStream(); document.Save(stream); document.Close(true); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("Booklet.pdf", "application/pdf", stream, m_context); } } } }<file_sep>/Android/SampleBrowser/Samples/PDF/OpenTypeFont.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Android.Views; using Android.Widget; using System.IO; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf; using Syncfusion.Drawing; using System.Reflection; namespace SampleBrowser { public partial class OpenTypeFont : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to draw a text with OpenType font in a PDF document."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate PDF"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { //Create a new PDF document PdfDocument document = new PdfDocument(); //Add a page PdfPage page = document.Pages.Add(); //Create font Stream fontStream = typeof(OpenTypeFont).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.NotoSerif-Black.otf"); PdfFont font = new PdfTrueTypeFont(fontStream, 14); //Text to draw string text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; //Create a brush PdfBrush brush = new PdfSolidBrush(new PdfColor(0, 0, 0)); PdfPen pen = new PdfPen(new PdfColor(0, 0, 0)); SizeF clipBounds = page.Graphics.ClientSize; RectangleF rect = new RectangleF(0, 0, clipBounds.Width, clipBounds.Height); //Draw text. page.Graphics.DrawString(text, font, brush, rect); MemoryStream stream = new MemoryStream(); //Save the PDF dcoument. document.Save(stream); //Close the PDF document. document.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("OpenTypeFont.pdf", "application/pdf", stream, m_context); } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/CheckBox/CheckBox.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; namespace SampleBrowser { public class CheckBox : SampleView { CheckBox_Mobile phoneView; public CheckBox() { phoneView = new CheckBox_Mobile(); this.AddSubview(phoneView); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } } } }<file_sep>/Forms/XlsIO/XlsIO/Samples/ExcelToPDFPage/ExcelToPDFPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using System.Reflection; using SampleBrowser.Core; using Syncfusion.XlsIO; using Syncfusion.Pdf; using Syncfusion.XlsIORenderer; using Xamarin.Forms; using LayoutOptions = Xamarin.Forms.LayoutOptions; namespace SampleBrowser.XlsIO { /// <summary> /// This class is the conversion of a Excel document to PDF. /// </summary> public partial class ExcelToPDFPage : SampleView { public ExcelToPDFPage() { InitializeComponent(); this.picker.Items.Add("NoScaling"); this.picker.Items.Add("FitAllRowsOnOnePage"); this.picker.Items.Add("FitAllColumnsOnOnePage"); this.picker.Items.Add("FitSheetOnOnePage"); this.picker.SelectedIndex = 0; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInput.HorizontalOptions = LayoutOptions.Start; this.btnInput.VerticalOptions = LayoutOptions.Center; this.btnInput.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } internal void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; Stream stream = null; if (this.checkfontName.IsChecked.Value || this.checkfontStream.IsChecked.Value) { application.SubstituteFont += new Syncfusion.XlsIO.Implementation.SubstituteFontEventHandler(SubstituteFont); stream = GetFileStream("InvoiceTemplate.xlsx"); } else stream = GetFileStream("ExcelToPDF.xlsx"); IWorkbook workbook = application.Workbooks.Open(stream); XlsIORenderer renderer = new XlsIORenderer(); XlsIORendererSettings settings = new XlsIORendererSettings(); settings.IsConvertBlankPage = false; //Set the Layout Options for the output Pdf page. if (this.picker.SelectedIndex == 0) { settings.LayoutOptions = Syncfusion.XlsIORenderer.LayoutOptions.NoScaling; } else if (this.picker.SelectedIndex == 1) { settings.LayoutOptions = Syncfusion.XlsIORenderer.LayoutOptions.FitAllRowsOnOnePage; } else if (this.picker.SelectedIndex == 2) { settings.LayoutOptions = Syncfusion.XlsIORenderer.LayoutOptions.FitAllColumnsOnOnePage; } else if (this.picker.SelectedIndex == 3) { settings.LayoutOptions = Syncfusion.XlsIORenderer.LayoutOptions.FitSheetOnOnePage; } settings.EnableFormFields = true; PdfDocument pdfDocument = renderer.ConvertToPDF(workbook, settings); MemoryStream memoryStream = new MemoryStream(); pdfDocument.Save(memoryStream); pdfDocument.Close(true); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("ExcelToPDF.pdf", "application/pdf", memoryStream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("ExcelToPDF.pdf", "application/pdf", memoryStream); } } internal Stream GetFileStream(string fileName) { Stream stream = null; #if COMMONSB stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template."+ fileName); #else stream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template." + fileName); #endif return stream; } internal void OnInputButtonClicked(object sender, EventArgs e) { //Load Input Template to memory stream. Stream file; if (this.checkfontName.IsChecked.Value || this.checkfontStream.IsChecked.Value) { file = GetFileStream("InvoiceTemplate.xlsx"); } else file = GetFileStream("ExcelToPDF.xlsx"); file.Position = 0; MemoryStream stream = new MemoryStream(); file.CopyTo(stream); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.xlsx", "application/msexcel", stream); } } private void SubstituteFont(object sender, Syncfusion.XlsIO.Implementation.SubstituteFontEventArgs args) { if (checkfontName.IsChecked.Value && (args.OriginalFontName == "Bahnschrift Pro SemiBold" || args.OriginalFontName == "Georgia Pro Semibold")) { args.AlternateFontName = "Calibri"; } if (checkfontStream.IsChecked.Value) { if (args.OriginalFontName == "Georgia Pro Semibold") { Stream file = GetFileStream("georgiab.ttf"); MemoryStream memoryStream = new MemoryStream(); file.CopyTo(memoryStream); file.Close(); args.AlternateFontStream = memoryStream; } else if (args.OriginalFontName == "Bahnschrift Pro SemiBold") { Stream file = GetFileStream("bahnschrift.ttf"); MemoryStream memoryStream = new MemoryStream(); file.CopyTo(memoryStream); file.Close(); args.AlternateFontStream = memoryStream; } } } } }<file_sep>/Forms/DocIO/DocIO/Samples/FormFillingAndProtection/FormFillingAndProtection.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using System.Reflection; using SampleBrowser.Core; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Xamarin.Forms; namespace SampleBrowser.DocIO { /// <summary> /// A sample view that can be used on FormFillingAndProtection. /// </summary> public partial class FormFillingAndProtection : SampleView { /// <summary> /// Constructor for FormFillingAndProtection. /// </summary> public FormFillingAndProtection() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { //if (!SampleBrowser.DocIO.App.isUWP) //{ // this.Content_1.FontSize = 18.5; //} //else //{ this.Content_1.FontSize = 13.5; // } this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } /// <summary> /// Button click event for FormFillingAndProtection. /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Event args</param> private void OnButtonClicked(object sender, EventArgs e) { #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif // Load Template document stream. Stream inputStream = typeof(FormFillingAndProtection).GetTypeInfo().Assembly.GetManifestResourceStream(rootPath + "ContentControlTemplate.docx"); // Creates an empty Word document instance. WordDocument document = new WordDocument(); // Opens template document. document.Open(inputStream, FormatType.Docx); IWTextRange textRange; //Gets table from the template document. IWTable table = document.LastSection.Tables[0]; WTableRow row = table.Rows[1]; #region Inserting content controls #region Calendar content control IWParagraph cellPara = row.Cells[0].Paragraphs[0]; //Accesses the date picker content control. IInlineContentControl inlineControl = (cellPara.ChildEntities[2] as IInlineContentControl); textRange = inlineControl.ParagraphItems[0] as WTextRange; //Sets today's date to display. textRange.Text = DateTime.Now.ToString("d"); textRange.CharacterFormat.FontSize = 14; //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; #endregion #region Plain text content controls table = document.LastSection.Tables[1]; row = table.Rows[0]; cellPara = row.Cells[0].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; textRange = inlineControl.ParagraphItems[0] as WTextRange; //Sets text in plain text content control. textRange.Text = "Northwind Analytics"; textRange.CharacterFormat.FontSize = 14; cellPara = row.Cells[1].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; textRange = inlineControl.ParagraphItems[0] as WTextRange; //Sets text in plain text content control. textRange.Text = "Northwind"; textRange.CharacterFormat.FontSize = 14; row = table.Rows[1]; cellPara = row.Cells[0].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; //Sets text in plain text content control. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = "10"; textRange.CharacterFormat.FontSize = 14; cellPara = row.Cells[1].LastParagraph; //Accesses the plain text content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); //Protects the content control. inlineControl.ContentControlProperties.LockContents = true; //Sets text in plain text content control. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = "<NAME>"; textRange.CharacterFormat.FontSize = 14; #endregion #region CheckBox Content control row = table.Rows[2]; cellPara = row.Cells[0].LastParagraph; //Inserts checkbox content control. inlineControl = cellPara.AppendInlineContentControl(ContentControlType.CheckBox); inlineControl.ContentControlProperties.LockContents = true; //Sets checkbox as checked state. inlineControl.ContentControlProperties.IsChecked = true; textRange = cellPara.AppendText("C#, "); textRange.CharacterFormat.FontSize = 14; //Inserts checkbox content control. inlineControl = cellPara.AppendInlineContentControl(ContentControlType.CheckBox); inlineControl.ContentControlProperties.LockContents = true; //Sets checkbox as checked state. inlineControl.ContentControlProperties.IsChecked = true; textRange = cellPara.AppendText("VB"); textRange.CharacterFormat.FontSize = 14; #endregion #region Drop down list content control cellPara = row.Cells[1].LastParagraph; //Accesses the dropdown list content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); inlineControl.ContentControlProperties.LockContents = true; //Sets default option to display. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = "ASP.NET"; textRange.CharacterFormat.FontSize = 14; inlineControl.ParagraphItems.Add(textRange); //Adds items to the dropdown list. ContentControlListItem item; item = new ContentControlListItem(); item.DisplayText = "ASP.NET MVC"; item.Value = "2"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); item = new ContentControlListItem(); item.DisplayText = "Windows Forms"; item.Value = "3"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); item = new ContentControlListItem(); item.DisplayText = "WPF"; item.Value = "4"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); item = new ContentControlListItem(); item.DisplayText = "Xamarin"; item.Value = "5"; inlineControl.ContentControlProperties.ContentControlListItems.Add(item); #endregion #region Calendar content control row = table.Rows[3]; cellPara = row.Cells[0].LastParagraph; //Accesses the date picker content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); inlineControl.ContentControlProperties.LockContents = true; //Sets default date to display. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = DateTime.Now.AddDays(-5).ToString("d"); textRange.CharacterFormat.FontSize = 14; cellPara = row.Cells[1].LastParagraph; //Inserts date picker content control. inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl); inlineControl.ContentControlProperties.LockContents = true; //Sets default date to display. textRange = inlineControl.ParagraphItems[0] as WTextRange; textRange.Text = DateTime.Now.AddDays(10).ToString("d"); textRange.CharacterFormat.FontSize = 14; #endregion #endregion #region Block content control //Accesses the block content control. BlockContentControl blockContentControl = ((document.ChildEntities[0] as WSection).Body.ChildEntities[2] as BlockContentControl); //Protects the block content control blockContentControl.ContentControlProperties.LockContents = true; #endregion MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Docx); document.Close(); if (Device.RuntimePlatform == Device.UWP) DependencyService.Get<ISaveWindowsPhone>() .Save("FormFillingAndProtection.docx", "application/msword", stream); else DependencyService.Get<ISave>().Save("FormFillingAndProtection.docx", "application/msword", stream); } } } <file_sep>/Forms/Cards/Cards/Samples/CardView/CardViewTemplate.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Cards; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.Cards { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CardViewTemplate : SfCardView { private bool isPotrait = true; private double width, height; private Grid grid; private int childIndex; private bool isAnimationCompleted; public CardViewTemplate () { InitializeComponent (); if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.UWP) { cardView.BorderWidth = 0.5; cardView.BorderColor = Color.DarkGray; } if (Device.RuntimePlatform == Device.UWP) { cardView.HorizontalOptions = LayoutOptions.Center; cardView.WidthRequest = 400; } } private void OnCardViewDismissed(object sender, Syncfusion.XForms.Cards.DismissedEventArgs e) { double viewHeight = cardView.Height; if (Device.RuntimePlatform == Device.UWP) { if (isAnimationCompleted) return; viewHeight = height - 1; } (cardView.Parent.BindingContext as CardViewModel).IsCardAlreadySwiped = true; grid = cardView.Parent as Grid; childIndex = grid.Children.IndexOf(cardView); var animation = new Animation(a => grid.RowDefinitions[childIndex].Height = a, viewHeight, 0); animation.Commit(this, "CardViewAnimation", 16, 200, Easing.Linear, (a, c) => Animate(), () => false); } private void Animate() { if (Device.RuntimePlatform == Device.UWP) { isAnimationCompleted = true; grid.RowDefinitions[childIndex].Height = 0; } else if (Device.RuntimePlatform == Device.Android) { grid.RowDefinitions[childIndex].Height = cardView.Height; } else { cardView.HeightRequest = 0; } } private void OnCardViewSizeChanged(object sender, EventArgs e) { if (!(sender as CardViewTemplate).IsDismissed) height = (sender as CardViewTemplate).Height; } protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint) { if (isPotrait && widthConstraint != double.PositiveInfinity) { width = widthConstraint; isPotrait = false; } return base.OnMeasure(width, heightConstraint); } } public class FontConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (Device.RuntimePlatform == Device.Android) { return "Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; } else if (Device.RuntimePlatform == Device.iOS) { return "Segoe MDL2 Assets"; } else { #if COMMONSB return "/Assets/Fonts/Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; #else if (Core.SampleBrowser.IsIndividualSB) { return "/Assets/Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; } else { return $"ms-appx:///SampleBrowser.Cards.UWP/Assets/Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; } #endif } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }<file_sep>/Android/SampleBrowser/Samples/DocIO/MailMerge.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public partial class MailMerge : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to create a letter format document by filling the data using Mail merge functionality of DocIO."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Creating a new document. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Letter Formatting.docx"); //Open Template document document.Open(inputStream, FormatType.Word2013); inputStream.Dispose(); List<Customer> source = new List<Customer>(); source.Add(new Customer("ALFKI", "<NAME>", "<NAME>", "Sales Representative", "Obere Str. 57", "Berlin", "12209", "Germany", "030-0074321", "030-0076545")); //source.Add(new Customer("ANATR", "<NAME>", "<NAME>", "Owner", "Avda. de la Constitución 2222", "<NAME>.", "05021", "Mexico", "(5) 555-4729", "(5) 555-3745")); document.MailMerge.Execute(source); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("LetterFormatting.docx", "application/msword", stream, m_context); } } } public class Customer { #region fields string m_customerID; string m_companyName; string m_contactName; string m_contactTitle; string m_address; string m_city; string m_postalCode; string m_country; string m_phone; string m_fax; #endregion #region properties public string CustomerID { get { return m_customerID; } set { m_customerID = value; } } public string CompanyName { get { return m_companyName; } set { m_companyName = value; } } public string ContactName { get { return m_contactName; } set { m_contactName = value; } } public string ContactTitle { get { return m_contactTitle; } set { m_contactTitle = value; } } public string Address { get { return m_address; } set { m_address = value; } } public string City { get { return m_city; } set { m_city = value; } } public string PostalCode { get { return m_postalCode; } set { m_postalCode = value; } } public string Country { get { return m_country; } set { m_country = value; } } public string Phone { get { return m_phone; } set { m_phone = value; } } public string Fax { get { return m_fax; } set { m_fax = value; } } #endregion #region constructor public Customer() { } public Customer(string customerID, string companyName, string contactName, string contactTitle, string address, string city, string postalCode, string country, string phone, string fax) { m_customerID = customerID; m_companyName = companyName; m_contactName = contactName; m_contactTitle = contactTitle; m_address = address; m_city = city; m_postalCode = postalCode; m_country = country; m_phone = phone; m_fax = fax; } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Presentation/Images.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { public partial class ImagesPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to add an image in PowerPoint presentation."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Presentation"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Images.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); #region Slide1 ISlide slide1 = presentation.Slides[0]; IShape shape1 = (IShape)slide1.Shapes[0]; shape1.Left = 1.27 * 72; shape1.Top = 0.56 * 72; shape1.Width = 9.55 * 72; shape1.Height = 5.4 * 72; ITextBody textFrame = shape1.TextBody; IParagraphs paragraphs = textFrame.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Left; ITextParts textParts = paragraph.TextParts; textParts.Add(); ITextPart textPart = textParts[0]; textPart.Text = "Essential Presentation "; textPart.Font.CapsType = TextCapsType.All; textPart.Font.FontName = "Calibri Light (Headings)"; textPart.Font.FontSize = 80; textPart.Font.Color = ColorObject.Black; #endregion #region Slide2 ISlide slide2 = presentation.Slides.Add(SlideLayoutType.ContentWithCaption); slide2.Background.Fill.FillType = FillType.Solid; slide2.Background.Fill.SolidFill.Color = ColorObject.White; //Adds shape in slide shape1 = (IShape)slide2.Shapes[0]; shape1.Left = 0.47 * 72; shape1.Top = 1.15 * 72; shape1.Width = 3.5 * 72; shape1.Height = 4.91 * 72; ITextBody textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe IParagraphs paragraphs1 = textFrame1.Paragraphs; IParagraph paragraph1 = paragraphs1.Add(); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Left; ITextPart textpart1 = paragraph1.AddTextPart(); textpart1.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph2 = paragraphs1.Add(); paragraph2.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph2.AddTextPart(); textpart1.Text = "Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph3 = paragraphs1.Add(); paragraph3.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph3.AddTextPart(); textpart1.Text = "Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph4 = paragraphs1.Add(); paragraph4.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph4.AddTextPart(); textpart1.Text = "Lorem tortor neque, purus taciti quis id. Elementum integer orci accumsan minim phasellus vel."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); slide2.Shapes.RemoveAt(1); slide2.Shapes.RemoveAt(1); //Adds picture in the shape resourcePath = "SampleBrowser.Samples.Presentation.Templates.tablet.jpg"; assembly = Assembly.GetExecutingAssembly(); fileStream = assembly.GetManifestResourceStream(resourcePath); slide2.Shapes.AddPicture(fileStream, 5.18 * 72, 1.15 * 72, 7.3 * 72, 5.31 * 72); fileStream.Close(); #endregion MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("Images.pptx", "application/powerpoint", stream, m_context); } } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Selection/SelectionBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SelectionBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Selection samples /// </summary> public class SelectionBehaviors : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt selectionPicker; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt selectionUnitPicker; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SelectionViewModel viewModel; /// <summary> /// Triggers while selected Index was changed, used to set a SelectionMode /// </summary> /// <param name="sender">OnSelectionChanged event sender</param> /// <param name="e">EventArgs e</param> public void OnSelectionChanged(object sender, EventArgs e) { if (this.selectionPicker.SelectedIndex == 0) { this.dataGrid.SelectionMode = Syncfusion.SfDataGrid.XForms.SelectionMode.None; } else if (this.selectionPicker.SelectedIndex == 1) { this.dataGrid.SelectionMode = Syncfusion.SfDataGrid.XForms.SelectionMode.Single; } else if (this.selectionPicker.SelectedIndex == 2) { this.dataGrid.SelectionMode = Syncfusion.SfDataGrid.XForms.SelectionMode.SingleDeselect; } else if (this.selectionPicker.SelectedIndex == 3) { this.dataGrid.SelectionMode = Syncfusion.SfDataGrid.XForms.SelectionMode.Multiple; } } /// <summary> /// Triggers while selected Index was changed, used to set a SelectionMode /// </summary> /// <param name="sender">OnSelectionChanged event sender</param> /// <param name="e">EventArgs e</param> public void OnSelectionUnitChanged(object sender, EventArgs e) { if (this.selectionUnitPicker.SelectedIndex == 0) { this.dataGrid.SelectionUnit = SelectionUnit.Row; this.dataGrid.ShowRowHeader = false; } else if (this.selectionUnitPicker.SelectedIndex == 1) { this.dataGrid.SelectionUnit = SelectionUnit.Cell; this.dataGrid.ShowRowHeader = false; } else if (this.selectionUnitPicker.SelectedIndex == 2) { this.dataGrid.SelectionUnit = SelectionUnit.Any; this.dataGrid.ShowRowHeader = true; } } /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.viewModel = new SelectionViewModel(); bindAble.BindingContext = this.viewModel; this.selectionPicker = bindAble.FindByName<PickerExt>("SelectionPicker"); this.selectionPicker.Items.Add("None"); this.selectionPicker.Items.Add("Single"); this.selectionPicker.Items.Add("Single Deselect"); this.selectionPicker.Items.Add("Multiple"); this.selectionUnitPicker = bindAble.FindByName<PickerExt>("SelectionUnitPicker"); this.selectionUnitPicker.Items.Add("Row"); this.selectionUnitPicker.Items.Add("Cell"); this.selectionUnitPicker.Items.Add("Any"); this.dataGrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.dataGrid.ItemsSource = this.viewModel.OrdersInfo; this.dataGrid.AllowKeyboardNavigation = true; this.dataGrid.GridStyle = new SelectionControllerStyle(); this.selectionUnitPicker.SelectedIndexChanged += this.OnSelectionUnitChanged; this.selectionPicker.SelectedIndexChanged += this.OnSelectionChanged; this.dataGrid.SelectedItems.Add(this.viewModel.OrdersInfo[1]); this.dataGrid.SelectedItems.Add(this.viewModel.OrdersInfo[3]); this.dataGrid.SelectedItems.Add(this.viewModel.OrdersInfo[7]); base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">A sampleView type of bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.selectionPicker.SelectedIndexChanged -= this.OnSelectionChanged; this.selectionUnitPicker.SelectedIndexChanged -= this.OnSelectionUnitChanged; this.dataGrid = null; this.selectionPicker = null; base.OnDetachingFrom(bindAble); } } } <file_sep>/Forms/PDF/PDF/Samples/TiffToPDF/TiffToPDF.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Pdf; using System; using System.IO; using Xamarin.Forms; using System.Reflection; using SampleBrowser.Core; using Syncfusion.Pdf.Graphics; namespace SampleBrowser.PDF { public partial class TiffToPDF : SampleView { public TiffToPDF() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { //Load Tiff image to stream. #if COMMONSB Stream imageFileStream = typeof(TiffToPDF).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.image.tiff"); #else Stream imageFileStream = typeof(TiffToPDF).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.image.tiff"); #endif //Create a new PDF document PdfDocument document = new PdfDocument(); //Set margin to the page document.PageSettings.Margins.All = 0; //Load Multiframe Tiff image PdfTiffImage tiffImage = new PdfTiffImage(imageFileStream); //Get the frame count int frameCount = tiffImage.FrameCount; //Access each frame and draw into the page for (int i = 0; i < frameCount; i++) { //Add new page for each frames PdfPage page = document.Pages.Add(); //Get page graphics PdfGraphics graphics = page.Graphics; //Set active frame. tiffImage.ActiveFrame = i; //Draw Tiff image into page graphics.DrawImage(tiffImage, 0, 0, page.GetClientSize().Width, page.GetClientSize().Height); } //Save PDF document MemoryStream stream = new MemoryStream(); document.Save(stream); //Close the PDF document document.Close(true); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("TiffToPDF.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("TiffToPDF.pdf", "application/pdf", stream); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Calendar/CalendarBlackoutDates.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfCalendar.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class CalendarBlackoutDates:SampleView { SFCalendar calendar1; public static UITableView appView; UIView calendarView = new UIView (); public CalendarBlackoutDates () { //Calendar calendar1 = new SFCalendar (); calendar1.ViewMode = SFCalendarViewMode.SFCalendarViewModeMonth; calendar1.HeaderHeight = 40; this.AddSubview (calendar1); //Setting BlackOutDates NSDate today = new NSDate (); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components ( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second calendar1.BlackoutDates = new NSMutableArray (); for (int i = 0; i < 5; i++) { NSDate startDate = calendar.DateFromComponents (components); components.Day += 1; calendar1.BlackoutDates.Add (startDate); } appView = new UITableView (); appView.RegisterClassForCellReuse (typeof(UITableViewCell), "Cell"); if((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { calendarView.AddSubview (calendar1); this.AddSubview (calendarView); } this.AddSubview (appView); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { if (view is SFCalendar) { view.Frame = new CGRect (this.Frame.X, -2, Frame.Size.Width, (Frame.Size.Height)); } calendarView.Frame = new CGRect (0, 0,this.Frame.Size.Width, this.Frame.Size.Height); calendar1.Frame = new CGRect (0, 0, this.Frame.Size.Width, this.Frame.Size.Height); } base.LayoutSubviews (); } public class CalendarPickerModel : UIPickerViewModel { private readonly IList<string> values; public event EventHandler<CalendarPickerChangedEventArgs> PickerChanged; public CalendarPickerModel(IList<string> values) { this.values = values; } #if __UNIFIED__ public override nint GetComponentCount (UIPickerView picker) { return 1; } public override nint GetRowsInComponent (UIPickerView picker, nint component) { return values.Count; } public override string GetTitle (UIPickerView picker, nint row, nint component) { return values[(int)row]; } public override nfloat GetRowHeight (UIPickerView picker, nint component) { return 30f; } public override void Selected (UIPickerView picker, nint row, nint component) { if (this.PickerChanged != null) { this.PickerChanged(this, new CalendarPickerChangedEventArgs{SelectedValue = values[(int)row]}); } } #else #endif } public class CalendarPickerChangedEventArgs : EventArgs { public string SelectedValue {get; set;} } } } <file_sep>/Forms/Calendar/Calendar/Samples/CalendarGettingStarted/Behaviors/GettingStartedBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using SampleBrowser.Core; using Syncfusion.SfCalendar.XForms; using Xamarin.Forms; using SelectionMode = Syncfusion.SfCalendar.XForms.SelectionMode; namespace SampleBrowser.SfCalendar { internal class GettingStartedBehavior : Behavior<SampleView> { private Syncfusion.SfCalendar.XForms.SfCalendar calendar; private Grid grid; private double calendarHeight = 400; private double calendarWidth = 400; private int padding = 50; protected override void OnAttachedTo(SampleView bindable) { base.OnAttachedTo(bindable); this.calendar = bindable.Content.FindByName<Syncfusion.SfCalendar.XForms.SfCalendar>("calendar"); this.grid = bindable.Content.FindByName<Grid>("grid"); if (Device.RuntimePlatform == "UWP") { this.grid.HorizontalOptions = LayoutOptions.Center; this.grid.VerticalOptions = LayoutOptions.Center; this.grid.HeightRequest = this.calendarHeight; this.grid.WidthRequest = this.calendarWidth; bindable.SizeChanged += this.Bindable_SizeChanged; } this.calendar.SelectionMode = SelectionMode.MultiSelection; var random = new Random(); var dates = new System.Collections.Generic.List<DateTime>(); var currentDate = DateTime.Now; for (int i = 0; i < 6; i++) { dates.Add(new DateTime(currentDate.Year, currentDate.Month, random.Next(1, 27))); } this.calendar.SelectedDates = dates; this.calendar.MinDate = DateTime.Now.AddMonths(-5); this.calendar.MaxDate = DateTime.Now.AddMonths(5); MonthViewSettings monthSettings = new MonthViewSettings(); monthSettings.HeaderBackgroundColor = Color.White; monthSettings.TodayBorderColor = Color.Transparent; if (Device.Idiom == TargetIdiom.Tablet) { if (Device.RuntimePlatform == "Android") { monthSettings.SelectionRadius = 30; } else { monthSettings.SelectionRadius = 15; } } this.calendar.MonthViewSettings = monthSettings; if (Device.RuntimePlatform == "UWP") { this.calendar.ShowNavigationButtons = true; } if (Device.RuntimePlatform == "Android" || (Device.RuntimePlatform == "UWP" && Device.Idiom == TargetIdiom.Desktop)) { this.calendar.HeaderHeight = 50; } else if (Device.RuntimePlatform == "iOS") { this.calendar.HeaderHeight = 40; } var selectionModePicker = bindable.Content.FindByName<Picker>("selectionModePicker"); selectionModePicker.SelectedIndex = 1; selectionModePicker.SelectedIndexChanged += SelectionModePicker_SelectedIndexChanged; var viewModePicker = bindable.Content.FindByName<Picker>("viewModePicker"); viewModePicker.SelectedIndex = 0; viewModePicker.SelectedIndexChanged += ViewModePicker_SelectedIndexChanged; var selectionShape = bindable.Content.FindByName<StackLayout>("selectionShape"); if (Device.RuntimePlatform != "UWP") { selectionShape.IsVisible = false; } else { this.calendar.MonthViewSettings.SelectionShape = SelectionShape.Circle; } var selectionShapePicker = bindable.Content.FindByName<Picker>("selectionShapePicker"); selectionShapePicker.SelectedIndex = 0; selectionShapePicker.SelectedIndexChanged += SelectionShapePicker_SelectedIndexChanged; var minDatePicker = bindable.Content.FindByName<DatePicker>("minDatePicker"); minDatePicker.Date = this.calendar.MinDate; minDatePicker.DateSelected += MinDatePicker_DateSelected; var maxDatePicker = bindable.Content.FindByName<DatePicker>("maxDatePicker"); maxDatePicker.Date = this.calendar.MaxDate; maxDatePicker.DateSelected += MaxDatePicker_DateSelected; var navigationDirectionPicker = bindable.Content.FindByName<Picker>("navigationDirectionPicker"); navigationDirectionPicker.SelectedIndex = 0; navigationDirectionPicker.SelectedIndexChanged += NavigationDirectionPicker_SelectedIndexChanged; var horizontalLinePicker = bindable.Content.FindByName<Picker>("horizontalLinePicker"); horizontalLinePicker.SelectedIndex = 3; horizontalLinePicker.SelectedIndexChanged += HorizontalLinePicker_SelectedIndexChanged; if (Device.RuntimePlatform != "Android" && Device.RuntimePlatform != "iOS") { var horizontalLineLabel = bindable.Content.FindByName<Label>("horizontalLineLabel"); horizontalLineLabel.IsVisible = false; horizontalLinePicker.IsVisible = false; } var yearViewPicker = bindable.Content.FindByName<Picker>("yearViewPicker"); yearViewPicker.SelectedIndex = 0; yearViewPicker.SelectedIndexChanged += YearViewPicker_SelectedIndexChanged; } private void Bindable_SizeChanged(object sender, EventArgs e) { var sampleView = sender as SampleView; if (sampleView.Height < this.calendarHeight + padding) { this.grid.HeightRequest = sampleView.Height - padding; } if (sampleView.Width < this.calendarWidth + padding) { this.grid.WidthRequest = sampleView.Width - padding; } } private void SelectionShapePicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: { this.calendar.MonthViewSettings.SelectionShape = SelectionShape.Circle; break; } case 1: { this.calendar.MonthViewSettings.SelectionShape = SelectionShape.Fill; break; } } } private void ViewModePicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: { calendar.ViewMode = ViewMode.MonthView; break; } case 1: { calendar.ViewMode = ViewMode.YearView; break; } case 2: { calendar.ViewMode = ViewMode.Decade; break; } case 3: { calendar.ViewMode = ViewMode.Century; break; } } } private void SelectionModePicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: { this.calendar.SelectionMode = SelectionMode.SingleSelection; if (Device.RuntimePlatform == "Android" || Device.RuntimePlatform == "iOS") { this.calendar.Refresh(); } else if (Device.RuntimePlatform == "UWP") { this.calendar.ShowNavigationButtons = false; } } break; case 1: { this.calendar.SelectionMode = SelectionMode.MultiSelection; if (Device.RuntimePlatform == "Android" || Device.RuntimePlatform == "iOS") { this.calendar.Refresh(); } else if (Device.RuntimePlatform == "UWP") { this.calendar.ShowNavigationButtons = false; } } break; case 2: { this.calendar.SelectionMode = SelectionMode.RangeSelection; if (Device.RuntimePlatform == "Android" || Device.RuntimePlatform == "iOS") { this.calendar.Refresh(); } else if (Device.RuntimePlatform == "UWP") { this.calendar.ShowNavigationButtons = true; } } break; case 3: { this.calendar.SelectionMode = SelectionMode.MultiRangeSelection; if (Device.RuntimePlatform == "Android" || Device.RuntimePlatform == "iOS") { this.calendar.Refresh(); } else if (Device.RuntimePlatform == "UWP") { this.calendar.ShowNavigationButtons = true; } } break; } } private void MinDatePicker_DateSelected(object sender, DateChangedEventArgs e) { this.calendar.MinDate = e.NewDate; } private void MaxDatePicker_DateSelected(object sender, DateChangedEventArgs e) { this.calendar.MaxDate = e.NewDate; } private void NavigationDirectionPicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: { this.calendar.NavigationDirection = NavigationDirection.Horizontal; } break; case 1: { this.calendar.NavigationDirection = NavigationDirection.Vertical; } break; } } private void HorizontalLinePicker_SelectedIndexChanged(object sender, EventArgs e) { MonthViewSettings monthViewSettings = new MonthViewSettings(); switch ((sender as Picker).SelectedIndex) { case 0: { if (Device.RuntimePlatform == "UWP") { monthViewSettings.CellGridOptions = CellGridOptions.HorizontalLines; } else { this.calendar.MonthViewSettings.CellGridOptions = CellGridOptions.HorizontalLines; } } break; case 1: { if (Device.RuntimePlatform == "UWP") { monthViewSettings.CellGridOptions = CellGridOptions.VerticalLines; } else { this.calendar.MonthViewSettings.CellGridOptions = CellGridOptions.VerticalLines; } } break; case 2: { if (Device.RuntimePlatform == "UWP") { monthViewSettings.CellGridOptions = CellGridOptions.Both; } else { this.calendar.MonthViewSettings.CellGridOptions = CellGridOptions.Both; } } break; case 3: { if (Device.RuntimePlatform == "UWP") { monthViewSettings.CellGridOptions = CellGridOptions.None; } else { this.calendar.MonthViewSettings.CellGridOptions = CellGridOptions.None; } } if (Device.RuntimePlatform == "UWP") { this.calendar.MonthViewSettings = monthViewSettings; } break; } } private void YearViewPicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: { calendar.ShowYearView = true; } break; case 1: { calendar.ShowYearView = false; } break; } } protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); if (Device.RuntimePlatform == "UWP") { bindable.SizeChanged -= this.Bindable_SizeChanged; } this.grid = null; this.calendar = null; } } } <file_sep>/iOS/SampleBrowser/Samples/PDF/HtmlTextElement.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class HtmlTextElement : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label1; UIButton button; public HtmlTextElement() { label1 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label1.Frame = frameRect; label1.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label1.Text = "This sample demonstrates drawing HTML text element in the PDF document."; label1.Font = UIFont.SystemFontOfSize(15); label1.Lines = 0; label1.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label1.Font = UIFont.SystemFontOfSize(18); label1.Frame = new CGRect(0, 12, frameRect.Location.X + frameRect.Size.Width, 50); } else { label1.Frame = new CGRect(frameRect.Location.X, 12, frameRect.Size.Width, 50); } this.AddSubview(label1); button.SetTitle("Generate PDF", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 70, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 70, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { PdfDocument doc = new PdfDocument(); //Add a page PdfPage page = doc.Pages.Add(); PdfSolidBrush brush = new PdfSolidBrush(Syncfusion.Drawing.Color.Black); PdfPen pen = new PdfPen(Syncfusion.Drawing.Color.Black, 1f); //Create font PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 11.5f); PdfFont heading = new PdfStandardFont(PdfFontFamily.TimesRoman, 12, PdfFontStyle.Bold); font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f); page.Graphics.DrawString("Create, Read, and Edit PDF Files from C#, VB.NET", heading, PdfBrushes.Black, new RectangleF(0, 0, page.GetClientSize().Width, 20), new PdfStringFormat(PdfTextAlignment.Center)); string longText = "The <b> Syncfusion Essential PDF </b> is a feature-rich and high-performance .NET PDF library that allows you to add robust PDF functionalities to any .NET application." + "It allows you to create, read, and edit PDF documents programmatically without Adobe dependencies. This library also offers functionality to <font color='#0000F8'> merge, split, stamp, form-fill, compress, and secure PDF files.</font>" + "<br/><br/><font color='#FF3440'><b>1. Secure your PDF with advanced encryption, digital signatures, and redaction.</b></font>" + "<br/><br/><font color='#FF9E4D'><b>2. Extract text and images from your PDF files.</b></font>" + "<br/><br/><font color='#4F6200'><b>3. Top features: forms, tables, barcodes; stamp, split, and merge PDFs.</b></font>"; //Rendering HtmlText PdfHTMLTextElement richTextElement = new PdfHTMLTextElement(longText, font, brush); // Formatting Layout PdfLayoutFormat format = new PdfLayoutFormat(); format.Layout = PdfLayoutType.OnePage; //Drawing htmlString richTextElement.Draw(page, new RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height), format); MemoryStream stream = new MemoryStream(); //Save the PDF dcoument. doc.Save(stream); //Close the PDF document. doc.Close(); stream.Position = 0; if (stream != null) { SaveiOS iosSave = new SaveiOS(); iosSave.Save("HtmlTextElement.pdf", "application/pdf", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Forms/Chart/Chart/Samples/StackedArea100Chart/StackedArea100SeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class StackedArea100SeriesViewModel { public ObservableCollection<ChartDataModel> StackedArea100Data1 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data2 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data3 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data4 { get; set; } public StackedArea100SeriesViewModel() { StackedArea100Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.61), new ChartDataModel("2001", 0.81), new ChartDataModel("2002", 0.91), new ChartDataModel("2003", 1), new ChartDataModel("2004", 1.19), new ChartDataModel("2005", 1.47), new ChartDataModel("2006", 1.74), new ChartDataModel("2007", 1.98), new ChartDataModel("2008", 1.99), new ChartDataModel("2009", 1.70), new ChartDataModel("2010", 1.48), new ChartDataModel("2011", 1.38), new ChartDataModel("2012", 1.66), new ChartDataModel("2013", 1.66), new ChartDataModel("2014", 1.67), }; StackedArea100Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.03), new ChartDataModel("2001", 0.05), new ChartDataModel("2002", 0.06), new ChartDataModel("2003", 0.09), new ChartDataModel("2004", 0.14), new ChartDataModel("2005", 0.20), new ChartDataModel("2006", 0.29), new ChartDataModel("2007", 0.46), new ChartDataModel("2008", 0.64), new ChartDataModel("2009", 0.75), new ChartDataModel("2010", 1.06), new ChartDataModel("2011", 1.25), new ChartDataModel("2012", 1.55), new ChartDataModel("2013", 1.55), new ChartDataModel("2014", 1.65), }; StackedArea100Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.48), new ChartDataModel("2001", 0.53), new ChartDataModel("2002", 0.57), new ChartDataModel("2003", 0.61), new ChartDataModel("2004", 0.63), new ChartDataModel("2005", 0.64), new ChartDataModel("2006", 0.66), new ChartDataModel("2007", 0.76), new ChartDataModel("2008", 0.77), new ChartDataModel("2009", 0.55), new ChartDataModel("2010", 0.54), new ChartDataModel("2011", 0.57), new ChartDataModel("2012", 0.61), new ChartDataModel("2013", 0.67), new ChartDataModel("2014", 0.67), }; StackedArea100Data4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.23), new ChartDataModel("2001", 0.17), new ChartDataModel("2002", 0.17), new ChartDataModel("2003", 0.20), new ChartDataModel("2004", 0.23), new ChartDataModel("2005", 0.36), new ChartDataModel("2006", 0.43), new ChartDataModel("2007", 0.52), new ChartDataModel("2008", 0.72), new ChartDataModel("2009", 1.29), new ChartDataModel("2010", 1.38), new ChartDataModel("2011", 1.82), new ChartDataModel("2012", 2.16), new ChartDataModel("2013", 2.51), new ChartDataModel("2014", 2.61), }; } } }<file_sep>/iOS/SampleBrowser/Samples/DataGrid/DragAndDrop.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Syncfusion.SfDataGrid; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using UIKit; namespace SampleBrowser { public class DragAndDrop : SampleView { #region Fields SfDataGrid sfGrid; DragAndDropViewModel viewModel; #endregion #region Static Methods static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } #endregion #region Constructor public DragAndDrop() { sfGrid = new SfDataGrid(); this.sfGrid.SelectionMode = SelectionMode.Single; viewModel = new DragAndDropViewModel(); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = viewModel.OrdersInfo; sfGrid.AllowDraggingRow = true; sfGrid.RowDragDropTemplate = new RowDragDropTemplate(); sfGrid.AllowDraggingColumn = true; sfGrid.QueryRowDragging += QueryRowDragging; sfGrid.ColumnSizer = ColumnSizer.Star; this.AddSubview(sfGrid); } #endregion #region Override Methods public override void LayoutSubviews() { this.sfGrid.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { if (disposing) { if (sfGrid != null) { sfGrid.QueryRowDragging -= QueryRowDragging; sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; sfGrid.Dispose(); sfGrid = null; } viewModel = null; } base.Dispose(disposing); } #endregion #region CallBacks void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "<NAME>"; e.Column.TextMargin = 5; e.Column.TextAlignment = UITextAlignment.Left; } else e.Cancel = true; e.Column.RecordFont = UIFont.FromName("HelveticaNeue", 12); } private void QueryRowDragging(object sender, QueryRowDraggingEventArgs e) { if (e.Reason == QueryRowDraggingReason.DragStarted) { (sfGrid.RowDragDropTemplate as RowDragDropTemplate).UpdateRow(e.RowData); } } #endregion } public class RowDragDropTemplate : UIView { #region Field UILabel label1; UILabel label2; UILabel label3; UILabel label4; #endregion #region Constructor public RowDragDropTemplate() { label1 = new UILabel() { TextAlignment = UITextAlignment.Center, TextColor = UIColor.Black, LineBreakMode = UILineBreakMode.TailTruncation, Font = UIFont.FromName("HelveticaNeue", 12) }; label2 = new UILabel() { TextAlignment = UITextAlignment.Center, TextColor = UIColor.Black, LineBreakMode = UILineBreakMode.TailTruncation, Font = UIFont.FromName("HelveticaNeue", 12) }; label3 = new UILabel() { TextAlignment = UITextAlignment.Center, TextColor = UIColor.Black, LineBreakMode = UILineBreakMode.TailTruncation, Font = UIFont.FromName("HelveticaNeue", 12) }; label4 = new UILabel() { TextAlignment = UITextAlignment.Center, TextColor = UIColor.Black, LineBreakMode = UILineBreakMode.TailTruncation, Font = UIFont.FromName("HelveticaNeue", 12) }; this.AddSubview(label1); this.AddSubview(label2); this.AddSubview(label3); this.AddSubview(label4); this.Layer.MasksToBounds = true; this.Layer.AllowsEdgeAntialiasing = true; this.Layer.BorderWidth = 0.25f; this.Layer.BorderColor = UIColor.Black.CGColor; } #endregion #region Method public void UpdateRow(object rowData) { var orderInfo = rowData as OrderInfo; label1.Text = orderInfo.OrderID; label2.Text = orderInfo.EmployeeID; label3.Text = orderInfo.CustomerID; label4.Text = orderInfo.FirstName; } public override void LayoutSubviews() { base.LayoutSubviews(); label1.Frame = new CGRect(0, 0, this.Frame.Width / 4, this.Frame.Height); label2.Frame = new CGRect(this.Frame.Width / 4, 0, this.Frame.Width / 4, this.Frame.Height); label3.Frame = new CGRect((this.Frame.Width / 4) * 2, 0, this.Frame.Width / 4, this.Frame.Height); label4.Frame = new CGRect((this.Frame.Width / 4) * 3, 0, this.Frame.Width / 4, this.Frame.Height); } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/Chart/Trackball.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using CoreAnimation; #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Trackball : SampleView { UILabel label; SFChart chart; public Trackball() { chart = new SFChart(); chart.ColorModel.Palette = SFChartColorPalette.Natural; SFDateTimeAxis primaryAxis = new SFDateTimeAxis(); primaryAxis.AxisLineOffset = 7; primaryAxis.PlotOffset = 7; primaryAxis.ShowMajorGridLines = false; primaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; primaryAxis.Interval = new NSNumber(1); primaryAxis.IntervalType = SFChartDateTimeIntervalType.Years; NSCalendar calendar = new NSCalendar(NSCalendarType.Gregorian); primaryAxis.Minimum = calendar.DateFromComponents(new NSDateComponents() {Year = 1999, Month = 12, Day = 31 }); chart.PrimaryAxis = primaryAxis; SFNumericalAxis secondaryAxis = new SFNumericalAxis(); secondaryAxis.MajorTickStyle.LineSize = 0; secondaryAxis.AxisLineStyle.LineWidth = 0; secondaryAxis.Minimum = new NSNumber(10); secondaryAxis.Maximum = new NSNumber(80); secondaryAxis.Interval = new NSNumber(10); secondaryAxis.Title.Text = new NSString("Revenue"); secondaryAxis.AxisLineStyle.LineWidth = 0; secondaryAxis.MajorTickStyle.LineWidth = 0; NSNumberFormatter formatter = new NSNumberFormatter(); formatter.PositiveSuffix = "M"; secondaryAxis.LabelStyle.LabelFormatter = formatter; chart.SecondaryAxis = secondaryAxis; ChartViewModel dataModel = new ChartViewModel(); SFLineSeries series1 = new SFLineSeries(); series1.ItemsSource = dataModel.LineSeries1; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.Label = "John"; series1.DataMarker.ShowMarker = true; series1.DataMarker.MarkerColor = UIColor.White; series1.DataMarker.MarkerBorderColor = UIColor.FromRGBA(0.0f / 255.0f, 189.0f / 255.0f, 174.0f / 255.0f, 1.0f); series1.DataMarker.MarkerBorderWidth = 2; series1.DataMarker.MarkerWidth = 5f; series1.DataMarker.MarkerHeight = 5f; series1.LineWidth = 3; chart.Series.Add(series1); SFLineSeries series2 = new SFLineSeries(); series2.ItemsSource = dataModel.LineSeries2; series2.XBindingPath = "XValue"; series2.YBindingPath = "YValue"; series2.Label = "Andrew"; series2.DataMarker.ShowMarker = true; series2.DataMarker.MarkerColor = UIColor.White; series2.DataMarker.MarkerBorderColor = UIColor.FromRGBA(64.0f / 255.0f, 64.0f / 255.0f, 65.0f / 255.0f, 1.0f); series2.DataMarker.MarkerBorderWidth = 2; series2.DataMarker.MarkerWidth = 5f; series2.DataMarker.MarkerHeight = 5f; series2.LineWidth = 3; chart.Series.Add(series2); SFLineSeries series3 = new SFLineSeries(); series3.ItemsSource = dataModel.LineSeries3; series3.XBindingPath = "XValue"; series3.YBindingPath = "YValue"; series3.Label = "Thomas"; series3.EnableTooltip = true; series3.DataMarker.ShowMarker = true; series3.DataMarker.MarkerHeight = 5f; series3.DataMarker.MarkerWidth = 5f; series3.DataMarker.MarkerBorderColor = UIColor.FromRGBA(53.0f / 255.0f, 124.0f / 255.0f, 210.0f / 255.0f, 1.0f); series3.DataMarker.MarkerBorderWidth = 2; series3.DataMarker.MarkerColor = UIColor.White; series3.LineWidth = 3; chart.Series.Add(series3); label = new UILabel(); label.Text = "Press and hold to enable trackball"; label.Font = UIFont.FromName("Helvetica", 12f); label.TextAlignment = UITextAlignment.Center; label.LineBreakMode = UILineBreakMode.WordWrap; label.Lines = 2; label.BackgroundColor = UIColor.FromRGB(249, 249, 249); label.TextColor = UIColor.FromRGB(79, 86, 91); CALayer topLine = new CALayer(); topLine.Frame = new CGRect(0, 0, UIScreen.MainScreen.ApplicationFrame.Width, 0.5); topLine.BackgroundColor = UIColor.FromRGB(178, 178, 178).CGColor; label.Layer.AddSublayer(topLine); chart.Legend.Visible = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; chart.AddChartBehavior(new SFChartTrackballBehavior()); this.AddSubview(chart); this.AddSubview(label); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view == chart) chart.Frame = new CGRect(0, 0, Frame.Width, Frame.Height - 48); else if (view == label) label.Frame = new CGRect(0, Frame.Height - 10, Frame.Width, 20); else view.Frame = Bounds; } base.LayoutSubviews(); } } public class CustomTrackballBehavior : SFChartTrackballBehavior { public override UIView ViewForTrackballLabel(SFChartPointInfo pointInfo) { pointInfo.MarkerStyle.BorderColor = pointInfo.Series.Color; UIView customView = new UIView(); customView.Frame = new CGRect(0, 0, 48, 30); UILabel xLabel = new UILabel(); xLabel.Frame = new CGRect(7, 0, 50, 15); xLabel.TextColor = UIColor.White; xLabel.Font = UIFont.FromName("HelveticaNeue-BoldItalic", 13f); xLabel.Text = (pointInfo.Data as ChartDataModel).YValue.ToString() + "%"; UILabel yLabel = new UILabel(); yLabel.Frame = new CGRect(7, 15, 50, 15); yLabel.TextColor = UIColor.White; yLabel.Font = UIFont.FromName("Helvetica", 8f); yLabel.Text = "Efficiency"; customView.AddSubview(xLabel); customView.AddSubview(yLabel); return customView; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Calculate/Helper/FunctionsLibraryView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreAnimation; using CoreGraphics; using Foundation; using Syncfusion.Calculate; using System; using System.Collections.Generic; using System.Text; using UIKit; namespace SampleBrowser { public class FunctionsLibraryView : UIScrollView { #region Fields UIPickerView functionsPicker; UILabel titleLabel; UILabel descripLabel; UILabel functionLabel; UILabel formulaLabel; UILabel calculatedLabel; UILabel label00; UILabel labelA0; UILabel labelB0; UILabel labelC0; UILabel label01; UILabel label02; UILabel label03; UILabel label04; UILabel label05; UITextField textA1; UITextField textB1; UITextField textC1; UITextField textA2; UITextField textB2; UITextField textC2; UITextField textA3; UITextField textB3; UITextField textC3; UITextField textA4; UITextField textB4; UITextField textC4; UITextField textA5; UITextField textB5; UITextField textC5; UITextField formulaText = new UITextField(); UILabel calculatedText; CALayer layer; UIButton calculateButton; UITextField pickerTextView; CalcData calcData; NSObject showNotification; NSObject hideNotification; #endregion #region Property internal CalcEngine Engine { get; set; } #endregion #region Constructor public FunctionsLibraryView() { InitializeEngine(); Initilizeview(); RegisterForKeyboardNotifications(); } #endregion #region Methods private void Initilizeview() { #region Header titleLabel = new UILabel(); titleLabel.Text = "Functions Library"; titleLabel.Font = UIFont.FromName("Helvetica-Bold", 25f); titleLabel.TextAlignment = UITextAlignment.Center; descripLabel = new UILabel(); descripLabel.Text = "This sample demonstrates the calculation using various Excel-like functions."; descripLabel.Lines = 0; descripLabel.LineBreakMode = UILineBreakMode.WordWrap; descripLabel.Font = UIFont.FromName("Helvetica", 12f); #endregion #region Functions functionLabel = new UILabel(); functionLabel.Text = "Select a function"; functionLabel.Font = UIFont.FromName("Helvetica", 14f); pickerTextView = new UITextField(); pickerTextView.Text = "ABS"; pickerTextView.Font = UIFont.FromName("Helvetica", 14f); FunctionsLibraryViewModel model = new FunctionsLibraryViewModel(formulaText, pickerTextView, this); functionsPicker = new UIPickerView(); functionsPicker.Model = model; pickerTextView.InputView = functionsPicker; #endregion #region GridView label00 = CreateLabel(""); labelA0 = CreateLabel("A"); labelB0 = CreateLabel("B"); labelC0 = CreateLabel("C"); label01 = CreateLabel("1"); label02 = CreateLabel("2"); label03 = CreateLabel("3"); label04 = CreateLabel("4"); label05 = CreateLabel("5"); textA1 = CreateTextField("32"); textB1 = CreateTextField("50"); textC1 = CreateTextField("10"); textA2 = CreateTextField("12"); textB2 = CreateTextField("24"); textC2 = CreateTextField("90"); textA3 = CreateTextField("88"); textB3 = CreateTextField("-22"); textC3 = CreateTextField("37"); textA4 = CreateTextField("73"); textB4 = CreateTextField("91"); textC4 = CreateTextField("21"); textA5 = CreateTextField("63"); textB5 = CreateTextField("29"); textC5 = CreateTextField("44"); #endregion #region Formula formulaLabel = new UILabel(); formulaLabel.Text = "Formula"; formulaLabel.Font = UIFont.FromName("Helvetica", 14f); formulaText.BorderStyle = UITextBorderStyle.Line; formulaText.Text = "=ABS(B3)"; formulaText.Font = UIFont.FromName("Helvetica", 14f); formulaText.ResignFirstResponder(); #endregion #region Compute calculateButton = new UIButton(); calculateButton.SetTitle("Compute", UIControlState.Normal); calculateButton.Layer.BorderWidth = 1; calculateButton.Layer.CornerRadius = 4; calculateButton.SetTitleColor(UIColor.Black, UIControlState.Highlighted); calculateButton.BackgroundColor = UIColor.LightGray; calculateButton.TouchUpInside += CalculateButton_TouchUpInside; #endregion #region Result calculatedLabel = new UILabel(); calculatedLabel.Text = "Computed Value"; calculatedLabel.Font = UIFont.FromName("Helvetica", 14f); layer = new CALayer() { BorderWidth = 1, BorderColor = UIColor.Black.CGColor }; calculatedText = new UILabel(); calculatedText.Font = UIFont.FromName("Helvetica", 14f); calculatedText.Layer.AddSublayer(layer); #endregion AddSubview(titleLabel); AddSubview(descripLabel); AddSubview(functionLabel); AddSubview(pickerTextView); AddSubview(label00); AddSubview(labelA0); AddSubview(labelB0); AddSubview(labelC0); AddSubview(label01); AddSubview(textA1); AddSubview(textB1); AddSubview(textC1); AddSubview(label02); AddSubview(textA2); AddSubview(textB2); AddSubview(textC2); AddSubview(label03); AddSubview(textA3); AddSubview(textB3); AddSubview(textC3); AddSubview(label04); AddSubview(textA4); AddSubview(textB4); AddSubview(textC4); AddSubview(label05); AddSubview(textA5); AddSubview(textB5); AddSubview(textC5); AddSubview(formulaLabel); AddSubview(formulaText); AddSubview(calculateButton); AddSubview(calculatedLabel); AddSubview(calculatedText); } public override void LayoutSubviews() { base.LayoutSubviews(); var width = Frame.Width - 20; this.ContentSize = new CGSize(this.Frame.Width, 560); titleLabel.Frame = new CGRect(5, 15, width, 25); descripLabel.Frame = new CGRect(5, 45, width, 30); functionLabel.Frame = new CGRect(5, 70, width / 2, 40); pickerTextView.Frame = new CGRect((width / 2) + 5, 76, width / 2, 30); var startCellWidth = width * 0.1; var cellWidth = (width - startCellWidth) / 3; var xpos = 5; label00.Frame = new CGRect(xpos, 115, startCellWidth, 30); label01.Frame = new CGRect(xpos, 145, startCellWidth, 30); label02.Frame = new CGRect(xpos, 175, startCellWidth, 30); label03.Frame = new CGRect(xpos, 205, startCellWidth, 30); label04.Frame = new CGRect(xpos, 235, startCellWidth, 30); label05.Frame = new CGRect(xpos, 265, startCellWidth, 30); xpos += (int)startCellWidth; labelA0.Frame = new CGRect(xpos, 115, cellWidth, 30); textA1.Frame = new CGRect(xpos, 145, cellWidth, 30); textA2.Frame = new CGRect(xpos, 175, cellWidth, 30); textA3.Frame = new CGRect(xpos, 205, cellWidth, 30); textA4.Frame = new CGRect(xpos, 235, cellWidth, 30); textA5.Frame = new CGRect(xpos, 265, cellWidth, 30); xpos += (int)cellWidth; labelB0.Frame = new CGRect(xpos, 115, cellWidth, 30); textB1.Frame = new CGRect(xpos, 145, cellWidth, 30); textB2.Frame = new CGRect(xpos, 175, cellWidth, 30); textB3.Frame = new CGRect(xpos, 205, cellWidth, 30); textB4.Frame = new CGRect(xpos, 235, cellWidth, 30); textB5.Frame = new CGRect(xpos, 265, cellWidth, 30); xpos += (int)cellWidth; labelC0.Frame = new CGRect(xpos, 115, cellWidth, 30); textC1.Frame = new CGRect(xpos, 145, cellWidth, 30); textC2.Frame = new CGRect(xpos, 175, cellWidth, 30); textC3.Frame = new CGRect(xpos, 205, cellWidth, 30); textC4.Frame = new CGRect(xpos, 235, cellWidth, 30); textC5.Frame = new CGRect(xpos, 265, cellWidth, 30); formulaLabel.Frame = new CGRect(5, 305, width / 2, 30); formulaText.Frame = new CGRect((width / 2) + 5, 305, width / 2, 30); calculateButton.Frame = new CGRect(5, 350, width, 30); calculatedLabel.Frame = new CGRect(5, 390, width / 2, 30); calculatedText.Frame = new CGRect((width / 2) + 5, 390, width / 2, 30); layer.Frame = new CGRect(calculatedText.Bounds.Left, calculatedText.Bounds.Bottom - 5, calculatedText.Bounds.Right, 1); } private void InitializeEngine() { calcData = new CalcData(); Engine = new CalcEngine(calcData); Engine.UseNoAmpersandQuotes = true; Engine.RegisterGridAsSheet("CalcData", calcData, 0); } private UILabel CreateLabel(string text) { return new UILabel() { Text = text, TextAlignment = UITextAlignment.Center, Font = UIFont.FromName("Helvetica", 14f) }; } private UITextField CreateTextField(string text) { return new UITextField() { Text = text, TextAlignment = UITextAlignment.Center, KeyboardType = UIKeyboardType.PhonePad, Font = UIFont.FromName("Helvetica", 14f) }; } private void CalculateButton_TouchUpInside(object sender, EventArgs e) { this.EndEditing(true); calcData.SetValueRowCol(textA1.Text, 1, 1); calcData.SetValueRowCol(textA2.Text, 2, 1); calcData.SetValueRowCol(textA3.Text, 3, 1); calcData.SetValueRowCol(textA4.Text, 4, 1); calcData.SetValueRowCol(textA5.Text, 5, 1); calcData.SetValueRowCol(textB1.Text, 1, 2); calcData.SetValueRowCol(textB2.Text, 2, 2); calcData.SetValueRowCol(textB3.Text, 3, 2); calcData.SetValueRowCol(textB4.Text, 4, 2); calcData.SetValueRowCol(textB5.Text, 5, 2); calcData.SetValueRowCol(textC1.Text, 1, 3); calcData.SetValueRowCol(textC2.Text, 2, 3); calcData.SetValueRowCol(textC3.Text, 3, 3); calcData.SetValueRowCol(textC4.Text, 4, 3); calcData.SetValueRowCol(textC5.Text, 5, 3); calculatedText.Text = Engine.ParseAndComputeFormula(formulaText.Text); } public override void TouchesBegan(NSSet touches, UIEvent evt) { this.EndEditing(true); } protected virtual void RegisterForKeyboardNotifications() { hideNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, OnKeyboardNotification); showNotification = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, OnKeyboardNotification); } private void OnKeyboardNotification(NSNotification notification) { var visible = notification.Name == UIKeyboard.WillShowNotification; var keyboardFrame = visible ? UIKeyboard.FrameEndFromNotification(notification) : UIKeyboard.FrameBeginFromNotification(notification); if (visible) this.SetContentOffset(new CGPoint(this.Frame.Left, (this.Frame.Height - keyboardFrame.Height) / 2), false); else this.SetContentOffset(new CGPoint(this.Frame.Left, this.Frame.Top), false); } protected override void Dispose(bool disposing) { calcData = null; if (Engine != null) { Engine.Dispose(); Engine = null; } NSNotificationCenter.DefaultCenter.RemoveObserver(showNotification); NSNotificationCenter.DefaultCenter.RemoveObserver(hideNotification); base.Dispose(disposing); } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/Chart/Area.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; #endif namespace SampleBrowser { public class Area : SampleView { public Area () { SFChart chart = new SFChart (); chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.Title.Text = new NSString ("Average Sales Comparison"); chart.Title.TextAlignment = UITextAlignment.Center; SFNumericalAxis primaryAxis = new SFNumericalAxis(); primaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; primaryAxis.Minimum = new NSNumber(2000); primaryAxis.Maximum = new NSNumber(2005); primaryAxis.Interval = new NSNumber(1); primaryAxis.ShowMajorGridLines = false; chart.PrimaryAxis = primaryAxis; SFNumericalAxis secondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis = secondaryAxis; secondaryAxis.Minimum = new NSNumber (2); secondaryAxis.Maximum = new NSNumber (5); secondaryAxis.Interval = new NSNumber (1); secondaryAxis.Title.Text = new NSString("Revenue in Millions"); secondaryAxis.AxisLineStyle.LineWidth = 0; secondaryAxis.MajorTickStyle.LineSize = 0; chart.Delegate = new AxisLabelFormatter(); ChartViewModel dataModel = new ChartViewModel(); SFAreaSeries series1 = new SFAreaSeries(); series1.ItemsSource = dataModel.AreaData1; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.EnableTooltip = true; series1.Alpha = 0.5f; series1.Label = "Product A"; series1.EnableAnimation = true; series1.LegendIcon = SFChartLegendIcon.SeriesType; chart.Series.Add(series1); SFAreaSeries series2 = new SFAreaSeries(); series2.ItemsSource = dataModel.AreaData2; series2.XBindingPath = "XValue"; series2.YBindingPath = "YValue"; series2.EnableTooltip = true; series2.Alpha = 0.5f; series2.Label = "Product B"; series2.EnableAnimation = true; series2.LegendIcon = SFChartLegendIcon.SeriesType; chart.Series.Add(series2); chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } class AxisLabelFormatter : SFChartDelegate { public override NSString GetFormattedAxisLabel(SFChart chart, NSString label, NSObject value, SFAxis axis) { if (axis == chart.SecondaryAxis) { String formattedLabel = label + "M"; label = new NSString(formattedLabel); return label; } return label; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/ExportingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace SampleBrowser { public class ExportingViewModel { #region Constructor public ExportingViewModel() { OrderDetailsRepository order = new OrderDetailsRepository(); OrdersInfo = order.GetOrderDetails(100); } #endregion #region ItemsSource private ObservableCollection<OrderInfo> _ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return _ordersInfo; } set { this._ordersInfo = value; } } #endregion } } <file_sep>/Forms/DataForm/DataForm/Samples/GettingStarted/Model/RecipientInfo.cs #region Copyright // <copyright file="RecipientInfo.cs" company="Syncfusion"> // Copyright (c) Syncfusion Inc. 2001 - 2017. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Re-distribution in any form is strictly // prohibited. Any infringement will be prosecuted under applicable laws. // </copyright> #endregion namespace SampleBrowser.SfDataForm { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Syncfusion.XForms.DataForm; using Xamarin.Forms.Internals; using System.ComponentModel.DataAnnotations; /// <summary> /// Describes the possible account type. /// </summary> [Preserve(AllMembers = true)] public enum AccountType { /// <summary> /// Represents savings account type. /// </summary> Savings, /// <summary> /// Represents current account type. /// </summary> Current, /// <summary> /// Represents overdraft account type. /// </summary> Overdraft, /// <summary> /// Represents cashcredit account type. /// </summary> CashCredit, /// <summary> /// Represents loan account type. /// </summary> LoanAccount, /// <summary> /// Represents NRE account type. /// </summary> NRE, /// <summary> /// Represents cardpayment type. /// </summary> CardPayment } /// <summary> /// Represents the recipient information of the data form getting started sample. /// </summary> [Preserve(AllMembers = true)] public class RecipientInfo : INotifyPropertyChanged, INotifyDataErrorInfo { #region Fields /// <summary> /// Represents the account number of the recipient information. /// </summary> private string accountNumber; /// <summary> /// Represents the second account number of the recipient information. /// </summary> private string accountNumber1; /// <summary> /// Represents the email id of the recipient information. /// </summary> private string email; /// <summary> /// Represents the amount of the recipient information. /// </summary> private double? amount = null; /// <summary> /// Represents the name of the recipient information. /// </summary> private string name; /// <summary> /// Represents the swift of the recipient information. /// </summary> private string swift; /// <summary> /// Represents the terms and conditions of the recipient information. /// </summary> private bool agree; /// <summary> /// Represents the password of the recipient information. /// </summary> private string password; /// <summary> /// Represents the account type of the recipient information. /// </summary> private AccountType accountType; /// <summary> /// Represents the immutable email regular expression. /// </summary> private Regex emailRegex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"); /// <summary> /// Represents a collection of keys and values. /// </summary> private Dictionary<string, List<string>> propErrors = new Dictionary<string, List<string>>(); /// <summary> /// Represents a immutable regular expression. /// </summary> private Regex swiftRegex = new Regex("^[A-Z]{6}[A-Z0-9]{2}([A-Z0-9]{3})?$"); #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="RecipientInfo"/> class. /// </summary> public RecipientInfo() { } /// <summary> /// Represents the method that will handle when a property is changed on a component. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Represents the method that will handle when a Errors are changed. /// </summary> public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; #endregion #region Public Properties /// <summary> /// Gets a value indicating whether recipient information contains errors. /// </summary> ////[Display(AutoGenerateField = false)] public bool HasErrors { get { var propErrorsCount = this.propErrors.Values.FirstOrDefault(r => r.Count > 0); if (propErrorsCount != null) { return true; } else { return false; } } } /// <summary> /// Gets or sets the account number field. /// </summary> [Display(ShortName = "Account number")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter account number.")] public string AccountNumber { get { return this.accountNumber; } set { if (value != this.AccountNumber) { this.accountNumber = value; this.RaisePropertyChanged("AccountNumber"); this.RaiseErrorChanged("AccountNumber"); } } } /// <summary> /// Gets or sets the first account number field. /// </summary> [Display(ShortName = "Re-enter account number")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please re-enter account number.")] public string AccountNumber1 { get { return this.accountNumber1; } set { if (value != this.AccountNumber1) { this.accountNumber1 = value; this.RaisePropertyChanged("AccountNumber1"); this.RaiseErrorChanged("AccountNumber1"); } } } /// <summary> /// Gets or sets the SWIFT field. /// </summary> [Display(Order = 0, ShortName = "SWIFT code", Prompt = "Enter 8 or 11 upper case letters")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the SWIFT code.")] [DisplayOptions(ValidMessage = "Name length is enough")] public string SWIFT { get { return this.swift; } set { this.swift = value; this.RaisePropertyChanged("SWIFT"); this.RaiseErrorChanged("SWIFT"); } } /// <summary> /// Gets or sets the name field. /// </summary> [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the name.")] public string Name { get { return this.name; } set { this.name = value; this.RaisePropertyChanged("Name"); this.RaiseErrorChanged("Name"); } } /// <summary> /// Gets or sets the email field. /// </summary> [Display(ShortName = "Email")] [EmailAddress(ErrorMessage = "Please enter a valid e-mail id.")] public string Email { get { return this.email; } set { this.email = value; this.RaisePropertyChanged("Email"); this.RaiseErrorChanged("Email"); } } /// <summary> /// Gets or sets the ammount field. /// </summary> [Display(ShortName = "Amount")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the amount.")] public double? Amount { get { return this.amount; } set { this.amount = value; this.RaisePropertyChanged("Amount"); this.RaiseErrorChanged("Amount"); } } /// <summary> /// Gets or sets the password field. /// </summary> [Display(ShortName = "Transaction password", Prompt = "Enter password")] [Required(AllowEmptyStrings = false, ErrorMessage = "Please enter the password.")] [DataType(DataType.Password)] public string Password { get { return this.password; } set { this.password = value; this.RaisePropertyChanged("Password"); this.RaiseErrorChanged("Password"); } } /// <summary> /// Gets or sets the account type field. /// </summary> [Display(ShortName = "Account type")] public AccountType AccountType { get { return this.accountType; } set { this.accountType = value; this.RaisePropertyChanged("AccountType"); this.RaiseErrorChanged("AccountType"); } } /// <summary> /// Gets or sets a value indicating whether terms and conditions of the recipient information is agreed. /// </summary> [DisplayOptions(ShowLabel = false)] public bool Agree { get { return this.agree; } set { this.agree = value; this.RaisePropertyChanged("Agree"); this.RaiseErrorChanged("Agree"); } } #endregion /// <summary> /// Gets the errors by validating the properties of the recipient informatio. /// </summary> /// <param name="propertyName">Property name of the recipient information.</param> /// <returns>Returns the errors if property name is not null.</returns> public IEnumerable GetErrors(string propertyName) { if (propertyName == null) { return null; } List<string> errors = new List<string>(); if (propertyName == "AccountNumber") { if (!string.IsNullOrEmpty(this.AccountNumber)) { this.propErrors.Remove("AccountNumber"); var accountNumberLength = this.AccountNumber.ToString().Length; if (accountNumberLength > 10 || accountNumberLength < 5) { if (!this.propErrors.TryGetValue(propertyName, out errors)) { errors = new List<string>(); errors.Add("Length should be between 5 and 10."); this.propErrors.Add("AccountNumber", errors); } } else if (this.propErrors.TryGetValue(propertyName, out errors)) { errors.Clear(); this.propErrors.Remove(propertyName); } } else if (this.propErrors.TryGetValue(propertyName, out errors)) { errors.Clear(); this.propErrors.Remove(propertyName); } } else if (propertyName == "AccountNumber1") { if (!string.IsNullOrEmpty(this.AccountNumber1)) { var accountNumberLength = this.AccountNumber1.ToString().Length; var error = string.Empty; if (this.AccountNumber1 != this.AccountNumber) { error = "Account numbers don't match."; } else if (accountNumberLength > 10 || accountNumberLength < 5) { error = "Length should be between 5 and 10."; } else if (this.propErrors.TryGetValue(propertyName, out errors)) { errors.Clear(); this.propErrors.Remove(propertyName); } if (!this.propErrors.TryGetValue(propertyName, out errors) && !string.IsNullOrEmpty(error)) { errors = new List<string>(); errors.Add(error); this.propErrors.Add("AccountNumber1", errors); } } else if (this.propErrors.TryGetValue(propertyName, out errors)) { errors.Clear(); this.propErrors.Remove(propertyName); } } else if (propertyName == "Amount") { if (this.Amount <= 0) { if (!this.propErrors.TryGetValue(propertyName, out errors)) { errors = new List<string>(); errors.Add("Amount should be greater than 0."); this.propErrors.Add("Amount", errors); } } else if (this.propErrors.TryGetValue(propertyName, out errors)) { errors.Clear(); this.propErrors.Remove(propertyName); } } else if (propertyName == "SWIFT") { if (string.IsNullOrEmpty(this.SWIFT)) { return string.Empty; } if (!this.swiftRegex.IsMatch(this.SWIFT)) { if (!this.propErrors.TryGetValue(propertyName, out errors)) { errors = new List<string>(); errors.Add("SWIFT code should be 8 or 11 upper case letters."); this.propErrors.Add("SWIFT", errors); } } else if (this.propErrors.TryGetValue(propertyName, out errors)) { errors.Clear(); this.propErrors.Remove(propertyName); } } else if (propertyName == "Password") { if (string.IsNullOrEmpty(this.Password)) { return string.Empty; } var error = string.Empty; if (this.Password != "<PASSWORD>") { error = "Password is incorrect."; } if (!this.propErrors.TryGetValue(propertyName, out errors) && !string.IsNullOrEmpty(error)) { errors = new List<string>(); errors.Add(error); this.propErrors.Add("Password", errors); } else if (this.propErrors.TryGetValue(propertyName, out errors)) { errors.Clear(); this.propErrors.Remove(propertyName); } } else if (propertyName == "Agree") { var error = string.Empty; if (this.Agree != true) { error = "Please check the checkbox to agree to the Terms & Conditions."; } if (!this.propErrors.TryGetValue(propertyName, out errors)) { errors = new List<string>(); errors.Add(error); this.propErrors.Add("Agree", errors); } else if (this.propErrors.TryGetValue(propertyName, out errors)) { errors.Clear(); this.propErrors.Remove(propertyName); } } if (this.propErrors.TryGetValue(propertyName, out errors)) { return errors; } return null; } /// <summary> /// Occurs when propery value is changed. /// </summary> /// <param name="propName">Property name</param> private void RaisePropertyChanged(string propName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } /// <summary> /// Occurs when error value is changed. /// </summary> /// <param name="propName">Property name</param> private void RaiseErrorChanged(string propName) { if (this.ErrorsChanged != null) { this.ErrorsChanged(this, new DataErrorsChangedEventArgs(propName)); } } } }<file_sep>/iOS/SampleBrowser/Samples/RangeSlider/readme.md The `SfRangeSlider` control provides way to select the range of value within the specified minimum and maximum limits. The range can be selected by moving the Thumb control along a track. The following samples are available for range slider to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](RangeSliderGettingStarted.cs)| It demonstrates the way to set start and end value of range, tick placement and label placement.| |[SliderView](Slider.cs)|It shows the way of handling `ValueChanged` event. Based on the value, opacity of images was changed. | |[Equalizer](Orientation.cs)|In that sample, we have three range sliders in vertical orientation looks like equalizer and custom labels were used to plot the values.| <file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/UICollectionView Helper/InboxRepositiory.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using UIKit; namespace SampleBrowser { public class InboxRepositiory { private Random random; public ObservableCollection<Mail> InboxItems { get; set; } public InboxRepositiory() { random = new Random(); InboxItems = new ObservableCollection<Mail>(); GenerateItems(50); } private void GenerateItems(int count) { for(int i =0; i< count;i++) { int randomNumber = random.Next(0, 9); Mail mail = new Mail(); mail.Sender = sender[random.Next(0,24)]; mail.Subject = subject[randomNumber]; mail.Details = details[randomNumber]; mail.BackgroundColor = colors[randomNumber]; InboxItems.Add(mail); } } public void RefreshItemSource() { int count = random.Next(1, 6); for (int i = 0; i < count; i++) { int randomNumber = random.Next(0, 9); Mail mail = new Mail(); mail.Sender = sender[random.Next(0, 24)]; mail.Subject = subject[randomNumber]; mail.Details = details[randomNumber]; mail.BackgroundColor = colors[randomNumber]; InboxItems.Insert(i, mail); } } string[] sender = new string[] { "Adams", "Crowley", "Ellis", "Gable", "Irvine", "Keefe", "Mendoza", "Owens", "Rooney", "Fitzgerald", "Holmes", "Jefferson", "Landry", "Perez", "Spencer", "Vargas", "Grimes", "Edwards", "Stark", "Cruise", "Fitz", "Chief", "Blanc", "Perry", "Stone", "Williams" }; string[] subject = new string[]{ "Transaction alert on your card", "Job openings", "New Release", "Festive Offers", "Distance Education", "Internship offer", "Delivery Status Notification", "Online Exam Intimation", "Account Statement", "Successfully Registered" }; string[] details = new string[]{ "Dear Customer, Thank you for using your card at Shopping Bazaar on 8th November 2017. Your card balance is $9999.", "Excellent jobs for freshers. Candidates who can join immediately needed. The qualification required, interview timings and the venue details are provided in the attachment.", "We are happy to inform you that Syncfusion has successfully rolled out the 2017 Volume 4 release. Customers can update to the new version and make use of the new features.", "Hurry up..! Mega offers for festival. Special offers are available for you. Discount of 10% to 35% is available based on the products. Many new arrivals. ", "You are receiving this mail as you have registered in our website. This is to notify you the opportunities that are available for you to study your preferable course in your favorite institutions. Please find the details of the courses and the institutions in the attachment.", "Internship for students available. Interested students, click the below link and register in it. Please find the qualification and other details of the internship in the attachment.", "Dear Customer, This is to inform you that, the product you ordered is shipped and it will be delivered to you in the given address on 12th December 2017. Expecting your patience until then.", "Dear Student, Your exam dates are finalized. The time table of the exams are published in our site. Get more details of it from the attachment. The venue details will be confirmed and informed in the next intimation.", "Dear Customer, your account statement summary for the month January - February is updated. Please find the details of your account statement in the attachment.", "You have successfully registered in our website. You will get notifications emails for all our updates. To keep your account active, login to your account regularly." }; private UIColor[] colors = new UIColor[] { UIColor.FromRGB(0,191,255), UIColor.FromRGB(255, 0, 191), UIColor.FromRGB(255, 26, 26), UIColor.FromRGB(255, 165, 0), UIColor.FromRGB(135, 206, 250), UIColor.FromRGB(241, 137, 48), UIColor.FromRGB(132, 92, 214), UIColor.FromRGB(247, 61, 40), UIColor.FromRGB(0, 154, 0), UIColor.FromRGB(255, 165, 0), }; } }<file_sep>/Forms/TreeView/TreeView/Samples/AutoFitContent/Model/Conversation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { interface IChatMessageInfo { string Message { get; set; } string Name { get; set; } DateTime Date { get; set; } string ReplyMessage { get; set; } bool IsInEditMode { get; set; } } [Preserve(AllMembers = true)] public class Conversation : IChatMessageInfo, INotifyPropertyChanged { private string message; private string replyMessage; private string profileIcon; private DateTime date; private string name; private ObservableCollection<Reply> replies = new ObservableCollection<Reply>(); private Color textColor= Color.FromHex("#757575"); private bool isInEditMode; private bool isNeedExpand = false; public string Message { get { return message; } set { message = value; RaisedOnPropertyChanged("Message"); } } public string ReplyMessage { get { return replyMessage; } set { replyMessage = value; RaisedOnPropertyChanged("ReplyMessage"); } } public bool IsInEditMode { get { return isInEditMode; } set { isInEditMode = value; RaisedOnPropertyChanged("IsInEditMode"); } } public bool IsNeedExpand { get { return isNeedExpand; } set { isNeedExpand = value; RaisedOnPropertyChanged("IsNeedExpand"); } } public string ProfileIcon { get { return profileIcon; } set { profileIcon = value; RaisedOnPropertyChanged("ProfileIcon"); } } public DateTime Date { get { return date; } set { date = value; RaisedOnPropertyChanged("Date"); } } public string Name { get { return name; } set { name = value; RaisedOnPropertyChanged("Name"); } } public ObservableCollection<Reply> Replies { get { return replies; } set { replies = value; if (replies.Count > 0 && !IsNeedExpand) IsNeedExpand = true; RaisedOnPropertyChanged("Replies"); } } public Color TextColor { get { return textColor; } set { textColor = value; RaisedOnPropertyChanged("TextColor"); } } public Conversation() { } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } [Preserve(AllMembers = true)] public class Reply : IChatMessageInfo, INotifyPropertyChanged { private string message = null; private string replyMessage; private Assembly assembly; private string profileIcon; private DateTime date; private string name; private Color textColor = Color.FromHex("#757575"); private bool isInEditMode; public string Message { get { return message; } set { message = value; RaisedOnPropertyChanged("Message"); } } public string ProfileIcon { get { return profileIcon; } set { profileIcon = value; RaisedOnPropertyChanged("ProfileIcon"); } } public string ReplyMessage { get { return replyMessage; } set { replyMessage = value; RaisedOnPropertyChanged("ReplyMessage"); } } public bool IsInEditMode { get { return isInEditMode; } set { isInEditMode = value; RaisedOnPropertyChanged("IsInEditMode"); } } public DateTime Date { get { return date; } set { date = value; RaisedOnPropertyChanged("Date"); } } public string Name { get { return name; } set { name = value; RaisedOnPropertyChanged("Name"); } } public Color TextColor { get { return textColor; } set { textColor = value; RaisedOnPropertyChanged("TextColor"); } } public Reply() { assembly = typeof(AutoFitContent).GetTypeInfo().Assembly; } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } } <file_sep>/Forms/TreeView/TreeView/Samples/AutoFitContent/ViewModel/ChatInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.TreeView.Engine; using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.Threading.Tasks; using XFSfTreeView = Syncfusion.XForms.TreeView.SfTreeView; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public class ChatInfo : INotifyPropertyChanged { private Assembly assembly; private string conversationMessage = ""; private ObservableCollection<Conversation> conversations; private string sendIcon; private string replyIcon; public ObservableCollection<Conversation> Conversations { get { return conversations; } set { conversations = value; RaisedOnPropertyChanged("Conversations"); } } public string ReplyIcon { get { return replyIcon; } set { replyIcon = value; RaisedOnPropertyChanged("ReplyIcon"); } } public string SendIcon { get { return sendIcon; } set { sendIcon = value; RaisedOnPropertyChanged("SendIcon"); } } public string ConversationMessage { get { return conversationMessage; } set { conversationMessage = value; RaisedOnPropertyChanged("ConversationMessage"); } } public string UserIcon { get; set; } public ICommand NewConversationCommand { get; private set; } public ICommand NewReplyCommand { get; private set; } public ICommand ReplyEditCommand { get; private set; } public ICommand ExpandActionCommand { get; private set; } public event EventHandler<ChatEventArgs> ConversationAdded; protected virtual void OnConversationAdded(ChatEventArgs e) { EventHandler<ChatEventArgs> handler = ConversationAdded; handler?.Invoke(this, e); } public event EventHandler<ReplyEditEventArgs> ReplyTapped; protected virtual void OnReplyTapped(ReplyEditEventArgs e) { EventHandler<ReplyEditEventArgs> handler = ReplyTapped; handler?.Invoke(this, e); } public event EventHandler<ChatEventArgs> ReplyAdded; protected virtual void OnReplyAdded(ChatEventArgs e) { EventHandler<ChatEventArgs> handler = ReplyAdded; handler?.Invoke(this, e); } public ChatInfo() { Initialize(); } private void Initialize() { assembly = typeof(AutoFitContent).GetTypeInfo().Assembly; this.Conversations = this.GenerateConversations(); SendIcon = "\ue745"; UserIcon = "User.png"; ReplyIcon = "\ue710"; NewConversationCommand = new Command(OnConversationAdding); ReplyEditCommand = new Command(OnInitializeReply); ExpandActionCommand = new Command(OnExpandAction); NewReplyCommand = new Command(OnReplyConversation); } private void OnReplyConversation(object sender) { var treeViewNode = sender as TreeViewNode; var content = (IChatMessageInfo)treeViewNode.Content; Conversation conversation = null; if (content is Conversation) conversation = (Conversation)content; else if (content is Reply) conversation = (Conversation)treeViewNode.ParentNode.Content; if (conversation != null && !string.IsNullOrWhiteSpace(content.ReplyMessage)) { var replies = conversation.Replies; replies.Insert(replies.Count, new Reply { Message = content.ReplyMessage, Date = DateTime.Now, Name = "Me", ProfileIcon = "User.png", TextColor = Color.FromHex("#f23518") }); conversation.Replies = replies; content.IsInEditMode = false; if (content is Conversation) conversation.IsNeedExpand = true; OnReplyAdded(new ChatEventArgs() { ChatMessageItem = content, Conversation = conversation }); } content.ReplyMessage = null; } private void OnExpandAction(object sender) { var node = sender as TreeViewNode; node.IsExpanded = !node.IsExpanded; } private void ResetEditMode() { foreach (Conversation conversation in this.Conversations) { if (conversation.IsInEditMode) { conversation.IsInEditMode = false; conversation.ReplyMessage = null; } foreach (Reply reply in conversation.Replies) { if (reply.IsInEditMode) { reply.IsInEditMode = false; reply.ReplyMessage = null; break; } } } } private void OnInitializeReply(object sender) { var content = (sender as TreeViewNode).Content; this.ResetEditMode(); if (content is Conversation) { var conversation = (Conversation)content; conversation.IsInEditMode = true; conversation.IsNeedExpand = false; } else if (content is Reply) { Reply reply = (Reply)content; reply.IsInEditMode = true; } OnReplyTapped(new ReplyEditEventArgs() { Content = content }); } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion private void OnConversationAdding() { ChatInfo instance = this; if (!string.IsNullOrWhiteSpace(instance.ConversationMessage)) { Conversation conversation = new Conversation { Message = instance.ConversationMessage, Date = DateTime.Now, Name = "Me", ProfileIcon = "User.png", TextColor = Color.FromHex("#f23518") }; instance.Conversations.Add(conversation); OnConversationAdded(new ChatEventArgs() { Conversation = conversation }); } instance.ConversationMessage = null; } internal ObservableCollection<Conversation> GenerateConversations() { // Conversations var conversation1 = new Conversation() { Name = "Thomas", Message = "Hi Guys, good morning! I’m delighted to share with you the news that our team is going to develop a new mobile application.", Date = DateTime.Now.AddHours(-4), ProfileIcon = "People_Circle8.png", IsNeedExpand = true }; conversation1.Replies.Add(new Reply() { Name = "Catherine", Message = "What kind of application?", Date = DateTime.Now.AddHours(-3).AddMinutes(-30), ProfileIcon = "People_Circle6.png" }); conversation1.Replies.Add(new Reply() { Name = "Thomas", Message = "An emergency broadcast app. The app will help users broadcast emergency messages to friends and family from mobile devices with location information during emergencies.", Date = DateTime.Now.AddHours(-3).AddMinutes(-10), ProfileIcon = "People_Circle8.png" }); conversation1.Replies.Add(new Reply() { Name = "Nancy", Message = "Could it broadcast data all the time? It would be better to provide options to broadcast to select people based on time or profile.", Date = DateTime.Now.AddHours(-2).AddMinutes(-30), ProfileIcon = "People_Circle9.png" }); conversation1.Replies.Add(new Reply() { Name = "Catherine", Message = "That’s a great idea. Let’s consider that in our requirements.", Date = DateTime.Now.AddHours(-2).AddMinutes(-20), ProfileIcon = "People_Circle6.png" }); var conversation2 = new Conversation() { Name = "Andrew", Message = "Are we going to develop it as a native or hybrid app?", Date = DateTime.Now.AddHours(-1).AddMinutes(-50), ProfileIcon = "People_Circle5.png", IsNeedExpand = true }; conversation2.Replies.Add(new Reply() { Name = "Thomas", Message = "We’ll develop it in Xamarin, which provides native experience and performance.", Date = DateTime.Now.AddHours(-1).AddMinutes(-30), ProfileIcon = "People_Circle8.png" }); conversation2.Replies.Add(new Reply() { Name = "Catherine", Message = "I haven’t heard of Xamarin. Can someone share details about it?", Date = DateTime.Now.AddMinutes(-59), ProfileIcon = "People_Circle6.png" }); conversation2.Replies.Add(new Reply() { Name = "Andrew", Message = "Xamarin is a library that enables you to build native UIs for iOS, Android, and Windows Phone from a single, shared C# code base.", Date = DateTime.Now.AddMinutes(-45), ProfileIcon = "People_Circle5.png" }); var conversation3 = new Conversation() { Name = "Nancy", Message = "Will this app be supported in wearable technology too?", Date = DateTime.Now.AddMinutes(-35), ProfileIcon = "People_Circle9.png", IsNeedExpand = true }; conversation3.Replies.Add(new Reply() { Name = "Thomas", Message = "No. We are going to develop it for the phone version first. Support for wearable watches can be considered in the next version.", Date = DateTime.Now.AddMinutes(-25), ProfileIcon = "People_Circle8.png" }); conversation3.Replies.Add(new Reply() { Name = "Andrew", Message = "Are we going to recruit a new team? If not, will we migrate our existing engineers from the current product?", Date = DateTime.Now.AddMinutes(-20), ProfileIcon = "People_Circle5.png" }); conversation3.Replies.Add(new Reply() { Name = "Nancy", Message = "This is going to be great!", Date = DateTime.Now.AddMinutes(-13), ProfileIcon = "People_Circle9.png" }); var conversationList = new ObservableCollection<Conversation>(); conversationList.Add(conversation1); conversationList.Add(conversation2); conversationList.Add(conversation3); return conversationList; } } public class ReplyEditEventArgs : EventArgs { public object Content { get; set; } } public class ChatEventArgs : EventArgs { public object ChatMessageItem { get; set; } public Conversation Conversation { get; set; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Spline.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Spline : SampleView { public Spline () { SFChart chart = new SFChart (); chart.Title.Text = new NSString ("Climate Graph"); chart.ColorModel.Palette = SFChartColorPalette.Natural; SFCategoryAxis primaryAxis = new SFCategoryAxis (); chart.PrimaryAxis = primaryAxis; primaryAxis.LabelPlacement = SFChartLabelPlacement.BetweenTicks; primaryAxis.Title.Text = new NSString ("Month"); chart.SecondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis.Title.Text = new NSString ("Temperature (celsius)"); ChartViewModel dataModel = new ChartViewModel(); SFSplineSeries series1 = new SFSplineSeries(); series1.ItemsSource = dataModel.SplineData1; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.EnableTooltip = true; series1.DataMarker.ShowMarker = true; series1.DataMarker.MarkerHeight = 5; series1.DataMarker.MarkerWidth = 5; series1.Label = "London"; series1.EnableAnimation = true; chart.Series.Add(series1); SFSplineSeries series2 = new SFSplineSeries(); series2.ItemsSource = dataModel.SplineData2; series2.XBindingPath = "XValue"; series2.YBindingPath = "YValue"; series2.EnableTooltip = true; series2.DataMarker.MarkerHeight = 5; series2.DataMarker.MarkerWidth = 5; series2.DataMarker.ShowMarker = true; series2.Label = "France"; series2.EnableAnimation = true; chart.Series.Add(series2); chart.Legend.Visible = true; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; chart.AddChartBehavior(new SFChartZoomPanBehavior()); this.AddSubview(chart); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews (); } } }<file_sep>/Forms/ListView/ListView/Samples/Paging/ViewModel/PagingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class PagingViewModel : INotifyPropertyChanged { private PagingProductRepository pagingProductRepository; public ObservableCollection<PagingProduct> pagingProducts { get; set; } public PagingViewModel() { pagingProductRepository = new PagingProductRepository(); pagingProducts = new ObservableCollection<PagingProduct>(); GenerateSource(); } private void GenerateSource() { var index = 0; for (int i = 0; i < pagingProductRepository.Names.Count(); i++) { if (index == 21) index = 0; var p = new PagingProduct() { Name = pagingProductRepository.Names[i], Weight = pagingProductRepository.Weights[i], Price = pagingProductRepository.Prices[i], ReviewValue = pagingProductRepository.ReviewValue[i], Ratings = pagingProductRepository.Ratings[i], Offer = pagingProductRepository.Offer[i], Image = pagingProductRepository.Names1[i % 22] + ".jpg" }; index++; pagingProducts.Add(p); } } private void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; } } <file_sep>/Forms/RadialMenu/RadialMenu/Samples/Customization_RadialMenu/Customization_RadialMenu.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Xamarin.Forms; using System.Globalization; namespace SampleBrowser.SfRadialMenu { public partial class Customization_RadialMenu : SampleView { Rotator_ViewModel rotator_ViewModel; public Customization_RadialMenu() { InitializeComponent(); //teamUSARadialMenu.Point = new Point(0, 0); rotator_ViewModel = new Rotator_ViewModel(); sfRotator.BindingContext = rotator_ViewModel; Device.StartTimer(new TimeSpan(0, 0, 0, 0, 500), TimerElapsed); if(Device.RuntimePlatform == Device.iOS) { rowHeight.Height = 240; } } #region Event Handler void Handle_ItemTapped(object sender, Syncfusion.SfRadialMenu.XForms.ItemTappedEventArgs e) { Syncfusion.SfRadialMenu.XForms.SfRadialMenuItem item1 = sender as Syncfusion.SfRadialMenu.XForms.SfRadialMenuItem; rotator_ViewModel.RotatorCollection[sfRotator.SelectedIndex].TeamColor = item1.BackgroundColor; teamUSARadialMenu.Close(); } #endregion private bool TimerElapsed() { Device.BeginInvokeOnMainThread(() => { teamUSARadialMenu.Show(); }); return false; } public override void OnDisappearing() { if (Device.RuntimePlatform == Device.UWP) { teamUSARadialMenu.Dispose(); } base.OnDisappearing(); } } public class CustomizationFontConversion : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (Device.RuntimePlatform == Device.Android) { if (parameter != null && parameter is string) return "radialmenu_RadialMenu.ttf#" + parameter.ToString(); else return "radialmenu_RadialMenu.ttf"; } else if (Device.RuntimePlatform == Device.iOS) { return "RadialMenu"; } else { #if COMMONSB return "radialmenu_RadialMenu.ttf#RadialMenu"; #else if (Core.SampleBrowser.IsIndividualSB) { return "radialmenu_RadialMenu.ttf#RadialMenu"; } else { return "SampleBrowser.SfRadialMenu.UWP\\radialmenu_RadialMenu.ttf#RadialMenu"; } #endif } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Forms/Maps/Maps.iOS/NetConnection_iOS.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Net; using System.Threading.Tasks; using SampleBrowser.SfMaps.iOS; [assembly: Xamarin.Forms.Dependency(typeof(NetConnection_iOS))] namespace SampleBrowser.SfMaps.iOS { public class NetConnection_iOS : OSMINetwork { public bool IsConnected { get; set; } public async Task CheckNetworkConnection() { var webRequest = (HttpWebRequest)WebRequest.Create("https://www.openstreetmap.org"); webRequest.Method = "HEAD"; try { using (var httpResponse = await webRequest.GetResponseAsync() as HttpWebResponse) { if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.OK) IsConnected = true; else IsConnected = false; } } catch (WebException) { IsConnected = false; } } } }<file_sep>/Forms/Backdrop/Backdrop/Behaviors/SelectionBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Backdrop; using Syncfusion.XForms.Buttons; using System; using System.Collections.Generic; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfBackdrop { [Preserve(AllMembers = true)] public class SelectionBehavior : Behavior<Syncfusion.XForms.Buttons.SfSegmentedControl> { public static readonly BindableProperty CommandProperty = BindableProperty.Create("Command", typeof(ICommand), typeof(SelectionBehavior), null); public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create("CommandParameter", typeof(object), typeof(SelectionBehavior), null); public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } } public object CommandParameter { get { return (object)GetValue(CommandParameterProperty); } set { SetValue(CommandParameterProperty, value); } } public Syncfusion.XForms.Buttons.SfSegmentedControl AssociatedObject { get; private set; } protected override void OnAttachedTo(Syncfusion.XForms.Buttons.SfSegmentedControl bindable) { base.OnAttachedTo(bindable); AssociatedObject = bindable; bindable.BindingContextChanged += OnBindingContextChanged; bindable.SelectionChanged += SelectionChanged; } protected override void OnDetachingFrom(Syncfusion.XForms.Buttons.SfSegmentedControl bindable) { base.OnDetachingFrom(bindable); bindable.BindingContextChanged -= OnBindingContextChanged; bindable.SelectionChanged -= SelectionChanged; AssociatedObject = null; } protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); BindingContext = AssociatedObject.BindingContext; } private void SelectionChanged(object sender, Syncfusion.XForms.Buttons.SelectionChangedEventArgs e) { if (Command == null) { return; } var paramerter = new List<object> { e, CommandParameter }; if (Command.CanExecute(paramerter)) { Command.Execute(paramerter); } } private void OnBindingContextChanged(object sender, EventArgs e) { OnBindingContextChanged(); } } } <file_sep>/Android/SampleBrowser/Samples/AutoComplete/readme.md The `SfAutoComplete` control filters and provides suggestion to choose from a list based on the typed text. Suggestions are provided as text appended to the original text or displayed in a drop-down list. The following samples are available for AutoComplete to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](AutoComplete.cs)|It demonstrates the basic functionalities of autocomplete, the filtering pattern, customizing dropdown height and providing delay to display the dropdown list| |[Multiple Selection](TokensSample/TokensSamplePage.cs)|It demonstrates the feature of multi selection in AutoComplete. Here, multi selection in token representation has been demonstrated.| |[Tolerating Typos](ToleratingTyposSample/ToleratingTyposSamplePage.cs)| It shows the custom filtering ability to get suggestions even if the typed text has typographical errors.| |[Diacritics Sense](DiacriticSample/DiacriticSamplePage.cs)|It demonstrates the ability to sense diacritics in languages and providing filtered list.|<file_sep>/Forms/ComboBox/ComboBox/Samples/Converters.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfComboBox { public class TextToProperConveter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value.ToString().Replace("-WF", ""); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class TextToValueConveter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value.ToString().Contains("-WF")) { return "Wireframe Icon"; } return "Flat Icon"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class NormalizationTextToProperConveter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value.ToString().Replace("-WF", ""); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class NormalizationTextToValueConveter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value.ToString().Contains("-WF")) { return "Wireframe Icon"; } return "Flat Icon"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class NormalizationNullToBoolConveter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return false; } return true; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/PDFViewer/CustomToolbar.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Reflection; using CoreGraphics; using Syncfusion.Pdf.Interactive; using Syncfusion.Pdf.Parsing; using Syncfusion.SfPdfViewer.iOS; using Syncfusion.SfRangeSlider.iOS; using UIKit; namespace SampleBrowser { public class CustomToolbar : SampleView { internal SfPdfViewer pdfViewerControl; internal const float DefaultToolbarHeight = 50f; internal UIView parentView; internal UIView toolbar; private UIView topBorder = new UIView(); private UITextField pageNumberField = new UITextField(); private UILabel totalPageLabel = new UILabel(); private UIButton undoButton = new UIButton(); private UIButton redoButton = new UIButton(); private UISearchBar searchBar = new UISearchBar(); private UIButton searchButton = new UIButton(); private UIButton backButton = new UIButton(); private UIButton searchNextButton = new UIButton(); private UIButton searchPreviousButton = new UIButton(); private UIButton fileButton = new UIButton(); internal CGRect toolBarFrame = new CGRect(); internal CGRect bottomToolbarFrame = new CGRect(); internal CGRect annotationFrame = new CGRect(); internal CGRect separateAnnotationFrame = new CGRect(); internal CGRect colorFrame = new CGRect(); private bool isLoaded = false; internal UIView toolBar = new UIView(); internal UIView searchToolBar = new UIView(); private ActivityIndicator activityDialog; private DropDownMenu dropDownMenu; private UIAlertView popUpAlertView; private Stream fileStream; internal UIView bottomToolBar = new UIView(); private UIButton annotationButton = new UIButton(); internal UIView textAnnotationToolbar = new UIView(); internal UIButton highlightAnnotationButton = new UIButton(); internal UIButton underlineAnnotationButton = new UIButton(); internal UIButton strikeOutAnnotationButton = new UIButton(); internal UIView highlightToolbar = new UIView(); internal UIView underlineToolbar = new UIView(); internal UIView strikeOutToolbar = new UIView(); internal UIButton toolbarBackbutton = new UIButton(); internal UIButton colorButton = new UIButton(); internal UIView colorToolbar = new UIView(); internal UIView thicknessToolbar = new UIView(); internal UIButton deleteButton = new UIButton(); private UIButton saveButton = new UIButton(); internal UIButton highlightEnable = new UIButton(); internal UIButton underlineEnable = new UIButton(); internal UIButton strikeEnable = new UIButton(); internal UIButton redButton = new UIButton(); internal UIButton blueButton = new UIButton(); internal UIButton yellowButton = new UIButton(); internal UIButton blackButton = new UIButton(); internal UIButton greenButton = new UIButton(); internal UIButton grayButton = new UIButton(); internal UIButton whiteButton = new UIButton(); private UIAlertView pagePopupView = new UIAlertView(); internal UIView annotationToolbar = new UIView(); internal UIButton textMarkupAnnotationButton = new UIButton(); internal UIButton inkAnnotationButton = new UIButton(); internal UIButton editTextAnnotationButton = new UIButton(); internal UIButton shapeAnnotationButton = new UIButton(); internal UIView inkAnnotationToolbar = new UIView(); internal UIView editTextAnnotationToolbar = new UIView(); internal UIView inkAnnotationSessionToolbar = new UIView(); internal UIButton inkButton = new UIButton(); internal UIButton inkThicknessButton = new UIButton(); internal UIButton inkColorButton = new UIButton(); internal UIButton inkUndoButton = new UIButton(); internal UIButton inkRedoButton = new UIButton(); internal UIButton inkConfirmButton = new UIButton(); internal UIButton textToolbarBackButton = new UIButton(); internal UIButton bookmarkButton = new UIButton(); internal bool isOpacityNeeded = false; internal bool isOpacitySelected = false; internal bool isThicknessTouched = false; internal bool isColorToolbarAdded = false; internal bool isOpacityToolbarAdded = false; internal bool colorToolbarCreated = false; internal UIButton opacitybutton = new UIButton(); internal UISlider thicknessBar = new UISlider(); internal UISlider opacitySlider = new UISlider(); internal CGRect thicknessFrame = new CGRect(); internal CGRect opacityFrame = new CGRect(); internal UIView opacityPanel = new UIView(); internal UILabel sliderValue = new UILabel(); internal UILabel opacitySliderValue = new UILabel(); internal bool isAnnotationToolbarVisible; internal IAnnotation annotation; internal AlertViewDelegate alertViewDelegate; internal UIFont highFont; internal UIFont fontSizeFont; internal UIFont bookmarkFont; internal bool IsSelected; internal UIButton inkdeleteButton = new UIButton(); internal bool isColorSelected; internal TextMarkupAnnotationHelper helper; internal EditTextAnnotationHelper edittextHelper; internal InkAnnotationHelper inkHelper; internal AnnotationHelper annotHelper; internal ShapeAnnotationHelper shapeHelper; internal UIButton BoldBtn1 = new UIButton(); internal UIButton BoldBtn2 = new UIButton(); internal UIButton BoldBtn3 = new UIButton(); internal UIButton BoldBtn4 = new UIButton(); internal UIButton BoldBtn5 = new UIButton(); internal UIButton BoldColorBtn1 = new UIButton(); internal UIButton BoldColorBtn2 = new UIButton(); internal UIButton BoldColorBtn3 = new UIButton(); internal UIButton BoldColorBtn4 = new UIButton(); internal UIButton BoldColorBtn5 = new UIButton(); internal bool iseditEnable = false; internal UIButton edittextThicknessButton = new UIButton(); internal UIButton edittextColorButton = new UIButton(); internal UIButton edittextDeleteButton = new UIButton(); internal UIView FontSizePanel = new UIView(); internal SfRangeSlider rangeSlider; internal UIButton rectangleAnnotationButton = new UIButton(); internal UIButton circleAnnotationButton = new UIButton(); internal UIButton lineAnnotationButton = new UIButton(); internal UIButton arrowAnnotationButton = new UIButton(); internal UIView shapeAnnotationToolbar = new UIView(); internal UIView lineToolbar = new UIView(); internal UIView rectangleToolbar = new UIView(); internal UIView circleToolbar = new UIView(); internal UIView arrowToolbar = new UIView(); internal UIButton lineEnable = new UIButton(); internal UIButton arrowEnable = new UIButton(); internal UIButton circleEnable = new UIButton(); internal UIButton rectangleEnable = new UIButton(); internal UIButton shapeThicknessButton = new UIButton(); internal UIButton shapeDeleteButton = new UIButton(); internal UIButton shapeColorButton = new UIButton(); internal UIToolbar annottoolbar = new UIToolbar(); internal UIView separator = new UIView(); internal AnnotationMode shapeView; internal UIButton signatureButton = new UIButton(); internal UIFont signatureFont; //PdfLoadedDocument instance from which the bookmarks will be obtained internal PdfLoadedDocument loadedDocument; internal Stream initialStream; internal BookmarkToolbar bookmarkToolbar; internal List<CustomBookmark> listViewItemsSource = new List<CustomBookmark>(); internal bool isBookmarkPaneVisible; public CustomToolbar() { parentView = new UIView(this.Frame); initialStream = typeof(CustomToolbar).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDFViewer.Assets.F# Succinctly.pdf"); loadedDocument = new PdfLoadedDocument(initialStream); PopulateInitialBookmarkList(); var tap = new UITapGestureRecognizer(OnSingleTap); tap.CancelsTouchesInView = false; //for iOS5 highFont = UIFont.FromName("Final_PDFViewer_IOS_FontUpdate", 30); fontSizeFont = UIFont.FromName("Font size Font", 30); signatureFont = UIFont.FromName("Signature_PDFViewer_FONT", 30); //Font that defines the icons for the bookmark toolbar buttons bookmarkFont = UIFont.FromName("PdfViewer_FONT", 30); this.AddGestureRecognizer(tap); helper = new TextMarkupAnnotationHelper(this); inkHelper = new InkAnnotationHelper(this); annotHelper = new AnnotationHelper(this); rangeSlider = new SfRangeSlider(); edittextHelper = new EditTextAnnotationHelper(this); shapeHelper = new ShapeAnnotationHelper(this); opacitybutton.TouchUpInside += inkHelper.Opacitybutton_TouchUpInside; pdfViewerControl = new SfPdfViewer(); pdfViewerControl.Toolbar.Enabled = false; pdfViewerControl.PageChanged += ViewerControl_PageChanged; pdfViewerControl.TextMarkupSelected += helper.PdfViewerControl_TextMarkupSelected; pdfViewerControl.TextMarkupDeselected += helper.PdfViewerControl_TextMarkupDeselected; pdfViewerControl.CanUndoModified += PdfViewerControl_CanUndoModified; pdfViewerControl.CanRedoModified += PdfViewerControl_CanRedoModified; pdfViewerControl.CanUndoInkModified += inkHelper.PdfViewerControl_CanUndoInkModified; pdfViewerControl.CanRedoInkModified += inkHelper.PdfViewerControl_CanRedoInkModified; pdfViewerControl.InkSelected += inkHelper.PdfViewerControl_InkSelected; pdfViewerControl.InkDeselected += inkHelper.PdfViewerControl_InkDeselected; pdfViewerControl.FreeTextAnnotationAdded += edittextHelper.PdfViewerControl_FreeTextAnnotationAdded; pdfViewerControl.FreeTextAnnotationDeselected += edittextHelper.PdfViewerControl_FreeTextAnnotationDeselected; pdfViewerControl.FreeTextAnnotationSelected += edittextHelper.PdfViewerControl_FreeTextAnnotationSelected; pdfViewerControl.FreeTextPopupDisappeared += edittextHelper.PdfViewerControl_FreeTextPopupDisappearing; pdfViewerControl.ShapeAnnotationSelected += shapeHelper.PdfViewerControl_ShapeAnnotationSelected; pdfViewerControl.ShapeAnnotationDeselected += shapeHelper.PdfViewerControl_ShapeAnnotationDeselected; BoldBtn1.TouchUpInside += inkHelper.BoldColorBtn1_TouchUpInside; BoldColorBtn1.TouchUpInside += inkHelper.BoldColorBtn1_TouchUpInside; BoldBtn2.TouchUpInside += inkHelper.BoldColorBtn2_TouchUpInside; BoldColorBtn2.TouchUpInside += inkHelper.BoldColorBtn2_TouchUpInside; BoldBtn3.TouchUpInside += inkHelper.BoldColorBtn3_TouchUpInside; BoldColorBtn3.TouchUpInside += inkHelper.BoldColorBtn3_TouchUpInside; BoldColorBtn4.TouchUpInside += inkHelper.BoldColorBtn4_TouchUpInside; BoldBtn4.TouchUpInside += inkHelper.BoldColorBtn4_TouchUpInside; BoldColorBtn5.TouchUpInside += inkHelper.BoldColorBtn5_TouchUpInside; BoldBtn5.TouchUpInside += inkHelper.BoldColorBtn5_TouchUpInside; inkColorButton.TouchUpInside += helper.ColorButton_TouchUpInside; colorButton.TouchUpInside += helper.ColorButton_TouchUpInside; inkAnnotationButton.TouchUpInside += inkHelper.InkAnnotationButton_TouchUpInside; inkThicknessButton.TouchUpInside += inkHelper.InkThicknessButton_TouchUpInside; shapeThicknessButton.TouchUpInside += inkHelper.InkThicknessButton_TouchUpInside; edittextThicknessButton.TouchUpInside += edittextHelper.EditTextThicknessButton_TouchUpInside; edittextColorButton.TouchUpInside += helper.ColorButton_TouchUpInside; shapeColorButton.TouchUpInside += helper.ColorButton_TouchUpInside; pageNumberField.Text = "1"; CreateTopToolbar(); bottomToolBar = CreateBottomToolbar(); toolbar = toolBar; parentView.AddSubview(pdfViewerControl); AddSubview(parentView); AddSubview(toolbar); AddSubview(bottomToolBar); topBorder.BackgroundColor = UIColor.FromRGBA(red: 0.86f, green: 0.86f, blue: 0.86f, alpha: 1.0f); AddSubview(topBorder); activityDialog = new ActivityIndicator(); activityDialog.Frame = new CGRect(UIScreen.MainScreen.Bounds.Width / 2 - 125, UIScreen.MainScreen.Bounds.Height / 2 - 50, 250, 100); popUpAlertView = new UIAlertView(); dropDownMenu = CreateDropDownMenu(); dropDownMenu.DropDownMenuItemChanged += (e, a) => { fileStream = typeof(CustomToolbar).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDFViewer.Assets." + a.DisplayText + ".pdf"); loadedDocument = new PdfLoadedDocument(fileStream); PopulateInitialBookmarkList(); pdfViewerControl.LoadDocument(fileStream); isBookmarkPaneVisible = false; if (bookmarkToolbar != null && bookmarkToolbar.Superview != null) bookmarkToolbar.RemoveFromSuperview(); ResetToolBar(); annotHelper.RemoveAllToolbars(false); dropDownMenu.Close(); }; } //Populates the bookmark toolbar with the bookmarks when a PDF is loaded private void PopulateInitialBookmarkList() { listViewItemsSource.Clear(); PdfBookmarkBase bookmarkBase = loadedDocument.Bookmarks; for (int i = 0; i < bookmarkBase.Count; i++) listViewItemsSource.Add(new CustomBookmark(bookmarkBase[i], false)); if(bookmarkToolbar != null) bookmarkToolbar.bookmarkListView.ReloadData(); } public override void LayoutSubviews() { base.LayoutSubviews(); if (!isBookmarkPaneVisible || UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { //Set the frames to SfPdfViewer and bookmark toolbar based on whether the bookmark toolbar is visible if (!isBookmarkPaneVisible) { parentView.Frame = new CGRect(0, DefaultToolbarHeight, this.Frame.Width, this.Frame.Height - (DefaultToolbarHeight)); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && bookmarkToolbar != null) bookmarkToolbar.Frame = new CGRect(this.Frame.Width, this.Frame.Y, 0, 0); } else { parentView.Frame = new CGRect(0, DefaultToolbarHeight, 3 * this.Frame.Width / 5, this.Frame.Height - DefaultToolbarHeight); if (bookmarkToolbar != null) bookmarkToolbar.Frame = new CGRect(3 * this.Frame.Width / 5, DefaultToolbarHeight, this.Frame.Width - (3 * this.Frame.Width / 5), this.Frame.Height - 2*DefaultToolbarHeight); } if (!isLoaded) { pdfViewerControl.LoadDocument(initialStream); totalPageLabel.Text = "/ " + pdfViewerControl.PageCount.ToString(); totalPageLabel.SetNeedsDisplay(); isLoaded = true; } pdfViewerControl.Frame = new CGRect(0, 0, parentView.Frame.Width, parentView.Frame.Height - DefaultToolbarHeight + 2); toolBarFrame.Width = this.Frame.Width; toolbar.Frame = toolBarFrame; bookmarkButton.Frame = new CGRect(this.Frame.Width - 105, 7, 35, 35); searchButton.Frame = new CGRect(this.Frame.Width - 60, 7, 35, 35); undoButton.Frame = new CGRect((this.Frame.Width / 2) - 25, 7, 35, 35); redoButton.Frame = new CGRect((this.Frame.Width / 2) + 10, 7, 35, 35); bottomToolbarFrame.X = -2; bottomToolbarFrame.Width = this.Frame.Width + 3; bottomToolbarFrame.Y = parentView.Frame.Height + 2; bottomToolBar.Frame = bottomToolbarFrame; topBorder.Frame = new CGRect(toolBarFrame.X, toolBarFrame.Bottom - 1, toolBarFrame.Width, 1); annotationButton.Frame = new CGRect(this.Frame.Width - 60, 7, 35, 35); colorFrame.Width = bottomToolbarFrame.Width; annotationFrame.Width = bottomToolbarFrame.Width; colorFrame.Height = bottomToolbarFrame.Height; colorFrame.Y = parentView.Frame.Height - (DefaultToolbarHeight + colorFrame.Height - 4); colorToolbar.Frame = colorFrame; annotationFrame.Height = bottomToolbarFrame.Height; annotationFrame.Y = parentView.Frame.Height - annotationFrame.Height + 4; textAnnotationToolbar.Frame = annotationFrame; if (!IsSelected) colorButton.Frame = new CGRect(this.Frame.Width - 120, 7, 35, 35); else colorButton.Frame = new CGRect(this.Frame.Width - 55, 7, 35, 35); separateAnnotationFrame.Width = bottomToolbarFrame.Width; separateAnnotationFrame.Height = bottomToolbarFrame.Height; separateAnnotationFrame.Y = parentView.Frame.Height - separateAnnotationFrame.Height + 4; annotationToolbar.Frame = separateAnnotationFrame; highlightToolbar.Frame = separateAnnotationFrame; underlineToolbar.Frame = separateAnnotationFrame; strikeOutToolbar.Frame = separateAnnotationFrame; deleteButton.Frame = new CGRect(this.Frame.Width - 100, 7, 35, 35); toolbarBackbutton.Frame = new CGRect(15, 7, 35, 35); inkAnnotationSessionToolbar.Frame = toolBarFrame; shapeAnnotationToolbar.Frame = separateAnnotationFrame; editTextAnnotationToolbar.Frame = separateAnnotationFrame; lineToolbar.Frame = separateAnnotationFrame; rectangleToolbar.Frame = separateAnnotationFrame; circleToolbar.Frame = separateAnnotationFrame; arrowToolbar.Frame = separateAnnotationFrame; annotationToolbar.AutoresizingMask = UIViewAutoresizing.FlexibleWidth; } //For mobile set the frame to bookmark toolbar so that it occupies the entire view else if(UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) bookmarkToolbar.Frame = new CGRect(this.Frame.X, 0, this.Frame.Width, this.Frame.Height); } void PdfViewerControl_CanUndoModified(object sender, CanUndoModifiedEventArgs args) { if (args.CanUndo) { undoButton.SetTitle("\ue70a", UIControlState.Normal); undoButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); } else { undoButton.SetTitle("\ue70a", UIControlState.Normal); undoButton.SetTitleColor(UIColor.LightGray, UIControlState.Normal); } } void PdfViewerControl_CanRedoModified(object sender, CanRedoModifiedEventArgs args) { if (args.CanRedo) { redoButton.SetTitle("\ue716", UIControlState.Normal); redoButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); } else { redoButton.SetTitle("\ue716", UIControlState.Normal); redoButton.SetTitleColor(UIColor.LightGray, UIControlState.Normal); } } public void OnSingleTap(UITapGestureRecognizer gesture) { this.EndEditing(true); pageNumberField.Text = pdfViewerControl.PageNumber.ToString(); } private void ResetToolBar() { pageNumberField.Text = pdfViewerControl.PageNumber.ToString(); totalPageLabel.Text = "/ " + pdfViewerControl.PageCount.ToString(); totalPageLabel.Frame = new CGRect(totalPageLabel.Frame.X, totalPageLabel.Frame.Y, totalPageLabel.IntrinsicContentSize.Width, totalPageLabel.Frame.Height); } private void PageNumberField_EditingDidBegin(object sender, EventArgs e) { pageNumberField.ResignFirstResponder(); alertViewDelegate = new AlertViewDelegate(pdfViewerControl); pagePopupView.Frame = new CGRect(40, parentView.Frame.Height / 4, 400, 150); pagePopupView.BackgroundColor = UIColor.White; pagePopupView.Layer.BorderWidth = 1; pagePopupView.Layer.BorderColor = new CGColor(0.2f, 0.2f); pagePopupView.Layer.CornerRadius = 10; pagePopupView.Title = "Go To Page"; pagePopupView.Message = "Enter Page Number (1 - " + pdfViewerControl.PageCount.ToString() + ")"; pagePopupView.AddButton("Cancel"); pagePopupView.AddButton("OK"); pagePopupView.Delegate = alertViewDelegate; pagePopupView.AlertViewStyle = UIAlertViewStyle.PlainTextInput; pagePopupView.GetTextField(0).KeyboardType = UIKeyboardType.NumberPad; pagePopupView.CancelButtonIndex = 0; pagePopupView.GetTextField(0).BecomeFirstResponder(); pageNumberField.Text = pdfViewerControl.PageNumber.ToString(); pagePopupView.Show(); } private void ViewerControl_PageChanged(object sender, PageChangedEventArgs args) { pageNumberField.Text = args.NewPageNumber.ToString(); } protected virtual UIView CreateTopToolbar() { toolBarFrame = this.Frame; toolBarFrame.Height = DefaultToolbarHeight; toolBarFrame.Y = 0; toolBar.Frame = toolBarFrame; toolBar.BackgroundColor = UIColor.FromRGB(249, 249, 249); toolBar.AutoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) fileButton.Frame = new CGRect(10, 7, 35, 35); else fileButton.Frame = new CGRect(5, 7, 35, 35); fileButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; fileButton.TouchUpInside += (e, a) => { if (dropDownMenu.IsOpened) dropDownMenu.Close(); else dropDownMenu.Open(); }; fileButton.Font = highFont; fileButton.SetTitle("\ue71d", UIControlState.Normal); fileButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); toolBar.Add(fileButton); saveButton.Frame = new CGRect(55, 7, 35, 35); saveButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; saveButton.TouchUpInside += annotHelper.SaveButton_TouchUpInside; saveButton.Font = highFont; saveButton.SetTitle("\ue718", UIControlState.Normal); saveButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); toolBar.Add(saveButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) undoButton.Frame = new CGRect(parentView.Frame.Width / 2 - 25, 7, 35, 35); else undoButton.Frame = new CGRect(130, 7, 35, 35); undoButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; undoButton.TouchUpInside += UndoButton_TouchUpInside; ; undoButton.Font = highFont; undoButton.SetTitle("\ue70a", UIControlState.Normal); undoButton.SetTitleColor(UIColor.LightGray, UIControlState.Normal); toolBar.Add(undoButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) redoButton.Frame = new CGRect(parentView.Frame.Width / 2 + 10, 7, 35, 35); else redoButton.Frame = new CGRect(175, 7, 35, 35); redoButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; redoButton.TouchUpInside += RedoButton_TouchUpInside; ; redoButton.Font = highFont; redoButton.SetTitle("\ue716", UIControlState.Normal); redoButton.SetTitleColor(UIColor.LightGray, UIControlState.Normal); toolBar.Add(redoButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) bookmarkButton.Frame = new CGRect(parentView.Frame.Width - 50, 7, 35, 35); else bookmarkButton.Frame = new CGRect(parentView.Frame.Width - 55, 7, 35, 35); bookmarkButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; bookmarkButton.TouchUpInside += BookmarkButton_TouchUpInside; bookmarkButton.Font = bookmarkFont; bookmarkButton.SetTitle("\ue701", UIControlState.Normal); bookmarkButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); toolBar.Add(bookmarkButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) searchButton.Frame = new CGRect(parentView.Frame.Width - 50, 7, 35, 35); else searchButton.Frame = new CGRect(parentView.Frame.Width - 10, 7, 35, 35); searchButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; searchButton.TouchUpInside += SearchButtonClicked; searchButton.Font = highFont; searchButton.SetTitle("\ue719", UIControlState.Normal); searchButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); toolBar.Add(searchButton); return toolBar; } //Handles the click event of the bookmark button on the top toolbar private void BookmarkButton_TouchUpInside(object sender, EventArgs e) { if(bookmarkToolbar == null) bookmarkToolbar = new BookmarkToolbar(this); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { if (bookmarkToolbar.Superview == null) AddSubview(bookmarkToolbar); else bookmarkToolbar.RemoveFromSuperview(); isBookmarkPaneVisible = !isBookmarkPaneVisible; annotHelper.RemoveAllToolbars(false); pdfViewerControl.AnnotationMode = AnnotationMode.None; isAnnotationToolbarVisible = false; } else { if (bookmarkToolbar.Superview == null) AddSubview(bookmarkToolbar); isBookmarkPaneVisible = true; } } private UIView CreateBottomToolbar() { bottomToolbarFrame = this.Frame; bottomToolbarFrame.Height = DefaultToolbarHeight; bottomToolbarFrame.Y = 0; bottomToolBar.Frame = bottomToolbarFrame; bottomToolBar.BackgroundColor = UIColor.FromRGB(249, 249, 249); bottomToolBar.AutoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) pageNumberField.Frame = new CGRect(45, 7, 45, 35); else pageNumberField.Frame = new CGRect(45, 7, 45, 35); pageNumberField.EditingDidBegin += PageNumberField_EditingDidBegin; pageNumberField.BorderStyle = UITextBorderStyle.RoundedRect; pageNumberField.TextColor = UIColor.FromRGB(0, 118, 255); pageNumberField.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; pageNumberField.TextAlignment = UITextAlignment.Center; bottomToolBar.Add(pageNumberField); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) totalPageLabel.Frame = new CGRect(90, 7, 40, 35); else totalPageLabel.Frame = new CGRect(90, 7, 40, 35); totalPageLabel.TextColor = UIColor.FromRGB(0, 118, 255); bottomToolBar.Add(totalPageLabel); annotationButton.Frame = new CGRect(parentView.Frame.Width - 50, 7, 35, 35); annotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; annotationButton.TouchUpInside += annotHelper.AnnotationButton_TouchUpInside; annotationButton.Font = highFont; annotationButton.SetTitle("\ue706", UIControlState.Normal); annotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); bottomToolBar.Add(annotationButton); bottomToolBar.Layer.BorderWidth = 1; bottomToolBar.Layer.BorderColor = new CGColor(0.2f, 0.2f); return bottomToolBar; } internal UIView UpdateToolbarBorder(UIView updateToolbar, CGRect toolbarFrame) { updateToolbar.Layer.BorderWidth = 1; updateToolbar.Layer.BorderColor = new CGColor(0.2f, 0.2f); updateToolbar.Frame = new CGRect(toolbarFrame.X - 1, toolbarFrame.Y - 1, textAnnotationToolbar.Frame.Width + 2, textAnnotationToolbar.Frame.Height + 2); return updateToolbar; } protected virtual UIView CreateSearchTopToolbar() { annotHelper.RemoveAllToolbars(false); toolBarFrame = Frame; toolBarFrame.Height = DefaultToolbarHeight; toolBarFrame.Y = 0; searchToolBar.Frame = toolBarFrame; searchToolBar.BackgroundColor = UIColor.FromRGB(249, 249, 249); searchToolBar.AutoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) backButton.Frame = new CGRect(20, 2, 50, 50); else backButton.Frame = new CGRect(2, 5, 40, 40); backButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; backButton.TouchUpInside += BackButtonClicked; backButton.Font = highFont; backButton.SetTitle("\ue71b", UIControlState.Normal); backButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); searchToolBar.Add(backButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) searchBar.Frame = new CGRect(95, 5, 550, 40); else searchBar.Frame = new CGRect(40, 5, 210, 40); searchBar.Placeholder = "Enter text to search"; searchBar.TextChanged += SearchBar_TextChanged; searchBar.SearchButtonClicked += SearchBar_SearchButtonClicked; searchToolBar.Add(searchBar); return searchToolBar; } internal void ToolbarBackbutton_TouchUpInside(object sender, EventArgs e) { if (pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { pdfViewerControl.EndInkSession(false); } pdfViewerControl.AnnotationMode = AnnotationMode.None; annotHelper.RemoveAllToolbars(false); Add(annotationToolbar); isColorSelected = false; FontSizePanel.RemoveFromSuperview(); rangeSlider.RemoveFromSuperview(); } private void SearchBar_TextChanged(object sender, UISearchBarTextChangedEventArgs e) { if ((sender as UISearchBar).Text == string.Empty) { pdfViewerControl.CancelSearch(); } } private void SearchCancelClicked(object sender, EventArgs e) { pdfViewerControl.CancelSearch(); searchBar.Text = String.Empty; } public void UpdateToolBarValues() { pageNumberField.Text = pdfViewerControl.PageNumber.ToString(); } private void SearchBar_SearchButtonClicked(object sender, EventArgs e) { dropDownMenu.Close(); searchBar.ResignFirstResponder(); pdfViewerControl.SearchText(searchBar.Text); } void RedoButton_TouchUpInside(object sender, EventArgs e) { pdfViewerControl.PerformRedo(); annotHelper.RemoveAllToolbars(false); } void UndoButton_TouchUpInside(object sender, EventArgs e) { pdfViewerControl.PerformUndo(); annotHelper.RemoveAllToolbars(false); } void SearchClicked(object sender, EventArgs ea) { pdfViewerControl.SearchText(searchBar.Text); } void SearchButtonClicked(object sender, EventArgs ea) { annotHelper.RemoveAllToolbars(false); toolbar.RemoveFromSuperview(); backButton.Enabled = true; CreateSearchTopToolbar(); toolbar = searchToolBar; searchBar.BecomeFirstResponder(); AddSubview(toolbar); isBookmarkPaneVisible = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && bookmarkToolbar != null && bookmarkToolbar.Superview != null) bookmarkToolbar.RemoveFromSuperview(); dropDownMenu.Close(); } void BackButtonClicked(object sender, EventArgs ea) { pdfViewerControl.CancelSearch(); searchBar.Text = String.Empty; UpdateToolBarValues(); searchToolBar.RemoveFromSuperview(); toolBar.RemoveFromSuperview(); toolbar = toolBar; toolBarFrame.Height = DefaultToolbarHeight; AddSubview(toolbar); } #region DropDown private List<DropDownMenuItem> GetResource() { var list = new List<DropDownMenuItem>(); list.Add(new DropDownMenuItem() { DisplayText = "F# Succinctly", IsSelected = true }); list.Add(new DropDownMenuItem() { DisplayText = "GIS Succinctly", }); list.Add(new DropDownMenuItem() { DisplayText = "HTTP Succinctly", }); list.Add(new DropDownMenuItem() { DisplayText = "JavaScript Succinctly", }); return list; } private DropDownMenu CreateDropDownMenu() { var dropDownMenu = new DropDownMenu(this, GetResource().ToArray()) { BackgroundColor = UIColor.Clear, TextColor = UIColor.Black, Opacity = 1, BorderWidth = 1, Frame = new CGRect(0, DefaultToolbarHeight + 20, 250, 200) }; return dropDownMenu; } #endregion } }<file_sep>/Forms/PdfViewer/PdfViewer/Samples/Helper/EditBookmarkPopup.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfPdfViewer.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfPdfViewer { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class EditBookmarkPopup : Grid { private PDFViewerCustomToolbar_Desktop desktopToolbar; private PDFViewerCustomToolbar_Phone phoneToolbar; private PDFViewerCustomToolbar_Tablet tabletToolbar; public bool IsRenamePopupOpened { get; set; } public bool IsRenameEntryFocused { get; set; } internal Entry EditEntry { get { return textEntry; } } internal EditBookmarkPopup(PDFViewerCustomToolbar_Desktop desktopToolbar) { InitializeComponent(); BackgroundColor = Color.FromRgba(0, 0, 0, 0.3); CancelBtn.Text = "CANCEL"; OKBtn.Text = "OK"; this.desktopToolbar = desktopToolbar; } internal EditBookmarkPopup(PDFViewerCustomToolbar_Phone phoneToolbar) { InitializeComponent(); BackgroundColor = Color.FromRgba(0, 0, 0, 0.3); CancelBtn.Text = "CANCEL"; OKBtn.Text = "OK"; this.phoneToolbar = phoneToolbar; } internal EditBookmarkPopup(PDFViewerCustomToolbar_Tablet tabletToolbar) { InitializeComponent(); BackgroundColor = Color.FromRgba(0, 0, 0, 0.3); CancelBtn.Text = "CANCEL"; OKBtn.Text = "OK"; this.tabletToolbar = tabletToolbar; } private void textEntry_TextChanged(object sender, TextChangedEventArgs e) { if (e.OldTextValue != null || e.OldTextValue != String.Empty) { if (e.NewTextValue != String.Empty || e.OldTextValue == String.Empty) { OKBtn.IsEnabled = true; } else { OKBtn.IsEnabled = false; } } else { OKBtn.IsEnabled = false; } } private void CancelBtn_Clicked(object sender, EventArgs e) { this.IsVisible = false; IsRenamePopupOpened = false; textEntry.Text = string.Empty; } private async void OKBtn_Clicked(object sender, EventArgs e) { this.IsVisible = false; if (Device.Idiom == TargetIdiom.Desktop) { desktopToolbar.bookMarkPane.messageLabel.Text = desktopToolbar.pdfViewer.CustomBookmarks[desktopToolbar.bookMarkPane.selectedCustomBookmarkIndex].Name + "-Edited"; if(textEntry.Text!= desktopToolbar.pdfViewer.CustomBookmarks[desktopToolbar.bookMarkPane.selectedCustomBookmarkIndex].Name) { desktopToolbar.pdfViewer.CustomBookmarks[desktopToolbar.bookMarkPane.selectedCustomBookmarkIndex].Name = textEntry.Text; desktopToolbar.PositionToastMessage(); desktopToolbar.bookMarkPane.toastMessageFrame.IsVisible = true; await desktopToolbar.bookMarkPane.toastMessageFrame.FadeTo(1, 1000); await desktopToolbar.bookMarkPane.toastMessageFrame.FadeTo(0, 1000); } else { desktopToolbar.bookMarkPane.toastMessageFrame.IsVisible = false; } } else if (Device.Idiom == TargetIdiom.Phone) { phoneToolbar.bookmarkToolbar.messageLabel.Text = phoneToolbar.pdfViewer.CustomBookmarks[phoneToolbar.bookmarkToolbar.selectedCustomBookmarkIndex].Name + "-Edited"; if(textEntry.Text!= phoneToolbar.pdfViewer.CustomBookmarks[phoneToolbar.bookmarkToolbar.selectedCustomBookmarkIndex].Name) { phoneToolbar.pdfViewer.CustomBookmarks[phoneToolbar.bookmarkToolbar.selectedCustomBookmarkIndex].Name = textEntry.Text; phoneToolbar.bookmarkToolbar.toastMessageFrame.IsVisible = true; await phoneToolbar.bookmarkToolbar.toastMessageFrame.FadeTo(1, 1000); await phoneToolbar.bookmarkToolbar.toastMessageFrame.FadeTo(0, 1000); } else { phoneToolbar.bookmarkToolbar.toastMessageFrame.IsVisible = false; } } else { tabletToolbar.bookmarkToolbar.messageLabel.Text = tabletToolbar.pdfViewer.CustomBookmarks[tabletToolbar.bookmarkToolbar.selectedCustomBookmarkIndex].Name + "-Edited"; if(textEntry.Text!= tabletToolbar.pdfViewer.CustomBookmarks[tabletToolbar.bookmarkToolbar.selectedCustomBookmarkIndex].Name) { tabletToolbar.pdfViewer.CustomBookmarks[tabletToolbar.bookmarkToolbar.selectedCustomBookmarkIndex].Name = textEntry.Text; tabletToolbar.PositionToastMessage(); tabletToolbar.bookmarkToolbar.toastMessageFrame.IsVisible = true; await tabletToolbar.bookmarkToolbar.toastMessageFrame.FadeTo(1, 1000); await tabletToolbar.bookmarkToolbar.toastMessageFrame.FadeTo(0, 1000); } else { tabletToolbar.bookmarkToolbar.toastMessageFrame.IsVisible = false ; } } IsRenamePopupOpened = false; textEntry.Text = string.Empty; } private void textEntry_Focused(object sender, FocusEventArgs e) { IsRenamePopupOpened = true; IsRenameEntryFocused = true; EditEntry.CursorPosition = 0; EditEntry.SelectionLength = EditEntry.Text.Length; } private void textEntry_Unfocused(object sender, FocusEventArgs e) { IsRenameEntryFocused = false; } } internal class EditBookmarkPopupEffect : RoutingEffect { internal EditBookmarkPopupEffect() : base("SampleBrowser.SfPdfViewer.EditBookmarkPopupEffect") { } } }<file_sep>/Android/SampleBrowser/Samples/Kanban/KanbanGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Syncfusion.SfKanban.Android; using System.Collections.Generic; using Android.Graphics; using Android.Graphics.Drawables; namespace SampleBrowser { public class KanbanGettingStarted : SamplePage { KanbanColumn column1; KanbanColumn column2; KanbanColumn column3; KanbanColumn column4; public override View GetSampleContent(Context context) { var kanban = new SfKanban(context); column1 = new KanbanColumn(context) { Categories = new List<object>() { "Open", "Postponed", "Validated" } }; column1.Title = "To Do"; column1.MinimumLimit = 5; column1.MaximumLimit = 20; kanban.Columns.Add(column1); column2 = new KanbanColumn(context) { Categories = new List<object>() { "In Progress" } }; column2.Title = "In Progress"; column2.MinimumLimit = 5; column2.MaximumLimit = 10; kanban.Columns.Add(column2); column3 = new KanbanColumn(context) { Categories = new List<object>() { "Code Review" } }; column3.Title = "Code Review"; column3.MinimumLimit = 10; column3.MaximumLimit = 15; kanban.Columns.Add(column3); column4 = new KanbanColumn(context) { Categories = new List<object>() { "Closed", "Closed-No Code Changes", "Resolved" } }; column4.Title = "Done"; column4.MinimumLimit = 10; column4.MaximumLimit = 15; kanban.Columns.Add(column4); kanban.ItemsSource = new KanbanData().Data; List<KanbanColorMapping> colormodels = new List<KanbanColorMapping>(); colormodels.Add(new KanbanColorMapping("Green", Color.Green)); colormodels.Add(new KanbanColorMapping("Red", Color.Red)); colormodels.Add(new KanbanColorMapping("Orange", Color.Orange)); colormodels.Add(new KanbanColorMapping("Brown", Color.Brown)); kanban.IndicatorColorPalette = colormodels; List<KanbanWorkflow> keyfield = new List<KanbanWorkflow>(); keyfield.Add(new KanbanWorkflow("Open", new List<object> { "In Progress" })); keyfield.Add(new KanbanWorkflow("In Progress", new List<object> { "Postponed", "Validated", "Code Review", "Closed-No Code Changes" })); keyfield.Add(new KanbanWorkflow("Code Review", new List<object> { "Closed", "Resolved" })); keyfield.Add(new KanbanWorkflow("Closed", new List<object> { "Open" })); keyfield.Add(new KanbanWorkflow("Postponed", new List<object> { "In Progress" })); keyfield.Add(new KanbanWorkflow("Validated", new List<object> { "In Progress" })); keyfield.Add(new KanbanWorkflow("Closed-No Code Changes", new List<object> { })); keyfield.Add(new KanbanWorkflow("Resolved", new List<object> { })); kanban.Workflows = keyfield; return kanban; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/DataBinding/DataBindingBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DataBindingBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Syncfusion.SfDataGrid.XForms.DataPager; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Paging samples /// </summary> public class DataBindingBehavior : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid datagrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt selectionPicker; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DataBindingViewModel getGettingStartedViewModel; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.datagrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.getGettingStartedViewModel = new DataBindingViewModel(); this.selectionPicker = bindAble.FindByName<PickerExt>("SelectionPicker"); this.selectionPicker.Items.Add("Observable Collection"); this.selectionPicker.Items.Add("DataTable"); this.selectionPicker.SelectedIndexChanged += this.SelectionPicker_SelectedIndexChanged; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">A sampleView type of bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { this.datagrid = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Triggers while selected Index was changed, used to set a Collection /// </summary> /// <param name="sender">OnSelectionChanged event sender</param> /// <param name="e">EventArgs e</param> private void SelectionPicker_SelectedIndexChanged(object sender, EventArgs e) { if (this.selectionPicker.SelectedIndex == 0) { this.datagrid.Columns.Clear(); this.datagrid.ItemsSource = this.getGettingStartedViewModel.OrdersInfo; GridTextColumn orderIdColumn = new GridTextColumn(); orderIdColumn.MappingName = "OrderID"; orderIdColumn.HeaderText = "Order ID"; orderIdColumn.LineBreakMode = LineBreakMode.TailTruncation; orderIdColumn.HeaderFontAttribute = FontAttributes.Bold; orderIdColumn.TextAlignment = TextAlignment.End; orderIdColumn.HeaderTextAlignment = TextAlignment.Start; orderIdColumn.HeaderCellTextSize = 13; orderIdColumn.CellTextSize = 13; orderIdColumn.Padding = new Thickness(5, 0, 5, 0); GridTextColumn customerIdColumn = new GridTextColumn(); customerIdColumn.MappingName = "EmployeeID"; customerIdColumn.HeaderText = "Customer ID"; customerIdColumn.HeaderFontAttribute = FontAttributes.Bold; customerIdColumn.LineBreakMode = LineBreakMode.TailTruncation; customerIdColumn.TextAlignment = TextAlignment.End; customerIdColumn.HeaderTextAlignment = TextAlignment.Start; customerIdColumn.HeaderCellTextSize = 13; customerIdColumn.CellTextSize = 13; customerIdColumn.Padding = new Thickness(5, 0, 5, 0); GridTextColumn customerColumn = new GridTextColumn(); customerColumn.MappingName = "CustomerID"; customerColumn.HeaderText = "Name"; customerColumn.HeaderFontAttribute = FontAttributes.Bold; customerColumn.LineBreakMode = LineBreakMode.TailTruncation; customerColumn.TextAlignment = TextAlignment.Start; customerColumn.HeaderTextAlignment = TextAlignment.Start; customerColumn.HeaderCellTextSize = 13; customerColumn.CellTextSize = 13; customerColumn.Padding = new Thickness(5, 0, 0, 0); GridTextColumn cityColumn = new GridTextColumn(); cityColumn.MappingName = "ShipCity"; cityColumn.HeaderText = "City"; cityColumn.HeaderFontAttribute = FontAttributes.Bold; cityColumn.LineBreakMode = LineBreakMode.TailTruncation; cityColumn.TextAlignment = TextAlignment.Start; cityColumn.HeaderTextAlignment = TextAlignment.Start; cityColumn.HeaderCellTextSize = 13; cityColumn.CellTextSize = 13; cityColumn.Padding = new Thickness(5, 0, 0, 0); this.datagrid.Columns.Add(orderIdColumn); this.datagrid.Columns.Add(customerIdColumn); this.datagrid.Columns.Add(customerColumn); this.datagrid.Columns.Add(cityColumn); } else if (this.selectionPicker.SelectedIndex == 1) { this.datagrid.Columns.Clear(); this.datagrid.ItemsSource = this.GetDataTable(); GridTextColumn customerId = new GridTextColumn(); customerId.MappingName = "CustomerID"; customerId.HeaderText = "Customer ID"; customerId.HeaderFontAttribute = FontAttributes.Bold; customerId.LineBreakMode = LineBreakMode.WordWrap; customerId.TextAlignment = TextAlignment.Start; customerId.HeaderTextAlignment = TextAlignment.Start; customerId.HeaderCellTextSize = 13; customerId.CellTextSize = 13; customerId.Padding = new Thickness(5, 0, 5, 0); GridTextColumn companyName = new GridTextColumn(); companyName.MappingName = "Company"; companyName.HeaderText = "Company"; companyName.HeaderFontAttribute = FontAttributes.Bold; companyName.LineBreakMode = LineBreakMode.WordWrap; companyName.TextAlignment = TextAlignment.Start; companyName.HeaderTextAlignment = TextAlignment.Start; companyName.HeaderCellTextSize = 13; companyName.CellTextSize = 13; companyName.Padding = new Thickness(5, 0, 5, 0); GridTextColumn contactName = new GridTextColumn(); contactName.MappingName = "ContactName"; contactName.HeaderText = "Contact Name"; contactName.HeaderFontAttribute = FontAttributes.Bold; contactName.LineBreakMode = LineBreakMode.WordWrap; contactName.TextAlignment = TextAlignment.Start; contactName.HeaderTextAlignment = TextAlignment.Start; contactName.HeaderCellTextSize = 13; contactName.CellTextSize = 13; contactName.Padding = new Thickness(5, 0, 0, 0); GridTextColumn city = new GridTextColumn(); city.MappingName = "City"; city.HeaderText = "City"; city.HeaderFontAttribute = FontAttributes.Bold; city.LineBreakMode = LineBreakMode.WordWrap; city.TextAlignment = TextAlignment.Start; city.HeaderTextAlignment = TextAlignment.Start; city.HeaderCellTextSize = 13; city.CellTextSize = 13; city.Padding = new Thickness(5, 0, 0, 0); this.datagrid.Columns.Add(customerId); this.datagrid.Columns.Add(companyName); this.datagrid.Columns.Add(contactName); this.datagrid.Columns.Add(city); } } /// <summary> /// Create the DataTable /// </summary> /// <returns>Data Table</returns> private DataTable GetDataTable() { DataTable employeeCollection = new DataTable(); employeeCollection.Columns.Add("CustomerID", typeof(string)); employeeCollection.Columns.Add("Company", typeof(string)); employeeCollection.Columns.Add("ContactName", typeof(string)); employeeCollection.Columns.Add("City", typeof(string)); employeeCollection.Rows.Add("ALFKI", "<NAME>", "<NAME>", "Berlin"); employeeCollection.Rows.Add("ANATR", "<NAME>", "<NAME>", "Mexico D.F."); employeeCollection.Rows.Add("ANTON", "<NAME>", "<NAME>", "Mexico D.F."); employeeCollection.Rows.Add("AROUT", "Around the Horn", "<NAME>", "London"); employeeCollection.Rows.Add("BERGS", "<NAME>", "<NAME>", "Lulea"); employeeCollection.Rows.Add("BLAUS", "<NAME>", "<NAME>", "Mannheim"); employeeCollection.Rows.Add("BLONP", "<NAME>", "<NAME>", "Strasbourg"); employeeCollection.Rows.Add("BOLID", "Bolids Comidas Preparadas", "<NAME>", "Madrid"); employeeCollection.Rows.Add("BONP", "<NAME>", "<NAME>", "Marseille"); employeeCollection.Rows.Add("BOTTM", "Bottom-Dollar Markets", "<NAME>", "Tsawassen"); employeeCollection.Rows.Add("BSBEV", "B's Beverages", "<NAME>", "London"); employeeCollection.Rows.Add("CACTU", "Cactus Comidas para llevar", "<NAME>", "Bu<NAME>"); employeeCollection.Rows.Add("CENTC", "Centro Comercial Moctezuma", "<NAME>", "Mexico D.F."); employeeCollection.Rows.Add("CHOPS", "Ch<NAME>", "<NAME>", "Bern"); employeeCollection.Rows.Add("COMMI", "<NAME>", "<NAME>", "<NAME>"); employeeCollection.Rows.Add("CONSH", "Consolidated Holdings", "<NAME>", "London"); employeeCollection.Rows.Add("DRACD", "<NAME>", "<NAME>", "Aachen"); employeeCollection.Rows.Add("DUMON", "<NAME>", "<NAME>", "Nantes"); employeeCollection.Rows.Add("EASTC", "Eastern Connection", "<NAME>", "London"); employeeCollection.Rows.Add("ERNSH", "<NAME>", "<NAME>", "Graz"); return employeeCollection; } } } <file_sep>/Forms/Calendar/README.md ## SfCalendar Calendar is a user interface component that displays Gregorian calendar. This component allows the user to select a date. It also provides a gesture-friendly UI to perform operations such as navigations, events, and more. | Sample | Description | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| | GettingStarted | Showcases the single and multiple selections support to restrict navigation beyond the specified minimum and maximum dates and month view lines appearance customization. | | InlineEvents | Showcases the inline events in inline view mode and agenda view mode in a specific date of the month. | | BlockoutDates | Showcases the specific date blackout capability of calendar. | | Globalization | Showcases localization and globalization. |<file_sep>/Forms/DataGrid/DataGrid/Samples/Model/Product.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Product.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties and notifies clients that a property value has changed. /// </summary> public class Product : INotifyPropertyChanged { #region private variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int supplierID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int productID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string productName; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int quantity; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int unitPrice; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int unitsInStock; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string discount; #endregion /// <summary> /// Initializes a new instance of the Product class. /// </summary> public Product() { } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the value of SupplierID and notifies user when value gets changed /// </summary> public int SupplierID { get { return this.supplierID; } set { this.supplierID = value; this.RaisePropertyChanged("SupplierID"); } } /// <summary> /// Gets or sets the value of ProductID and notifies user when value gets changed /// </summary> public int ProductID { get { return this.productID; } set { this.productID = value; this.RaisePropertyChanged("ProductID"); } } /// <summary> /// Gets or sets the value of ProductName and notifies user when value gets changed /// </summary> public string ProductName { get { return this.productName; } set { this.productName = value; this.RaisePropertyChanged("ProductName"); } } /// <summary> /// Gets or sets the value of Quantity and notifies user when value gets changed /// </summary> public int Quantity { get { return this.quantity; } set { this.quantity = value; this.RaisePropertyChanged("Quantity"); } } /// <summary> /// Gets or sets the value of UnitPrice and notifies user when value gets changed /// </summary> public int UnitPrice { get { return this.unitPrice; } set { this.unitPrice = value; this.RaisePropertyChanged("UnitPrice"); } } /// <summary> /// Gets or sets the value of UnitsInStock and notifies user when value gets changed /// </summary> public int UnitsInStock { get { return this.unitsInStock; } set { this.unitsInStock = value; this.RaisePropertyChanged("UnitsInStock"); } } /// <summary> /// Gets or sets the value of Discount and notifies user when value gets changed /// </summary> public string Discount { get { return this.discount; } set { this.discount = value; this.RaisePropertyChanged("Discount"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">String type of parameter name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/iOS/SampleBrowser/Resources/Samples/PDFViewer/Helpers/AnnotationHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Reflection; using CoreGraphics; using Syncfusion.SfPdfViewer.iOS; using UIKit; namespace SampleBrowser { public class AnnotationHelper { CustomToolbar m_parent; InkAnnotationHelper m_inkannot; internal const float DefaultToolbarHeight = 50f; private CustomToolbar Parent { get { return m_parent; } set { m_parent = value; } } public AnnotationHelper(CustomToolbar customtoolbar) { Parent = customtoolbar; } internal void AnnotationButton_TouchUpInside(object sender, EventArgs e) { Parent.isColorSelected = false; Parent.isThicknessTouched = false; Parent.isOpacityNeeded = false; if(Parent.pdfViewerControl.AnnotationMode== AnnotationMode.Ink) { Parent.pdfViewerControl.EndInkSession(false); } if (Parent.annotation != null) { Parent.inkThicknessButton.Frame = new CGRect(Parent.parentView.Frame.Width - 55, 7, 35, 35); Parent.inkAnnotationToolbar.Add(Parent.inkThicknessButton); Parent.inkColorButton.Frame = new CGRect(Parent.parentView.Frame.Width - 100, 7, 35, 35); Parent.inkAnnotationToolbar.Add(Parent.inkColorButton); Parent.inkdeleteButton.RemoveFromSuperview(); Parent.annotation = null; } if (!Parent.isAnnotationToolbarVisible) { Parent.thicknessToolbar.RemoveFromSuperview(); Parent.toolBar.RemoveFromSuperview(); Parent.toolbar = Parent.toolBar; Parent.toolBarFrame.Height = DefaultToolbarHeight; Parent.AddSubview(Parent.toolbar); Parent.searchToolBar.RemoveFromSuperview(); Parent.annotationFrame = Parent.Frame; Parent.annotationFrame.Height = DefaultToolbarHeight; Parent.annotationFrame.Y = Parent.parentView.Frame.Height - Parent.annotationFrame.Height + 4; Parent.annotationToolbar.Frame = Parent.annotationFrame; Parent.annotationToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); Parent.textMarkupAnnotationButton.Frame = new CGRect(Parent.annotationToolbar.Frame.Width / 2 - 85, 7, 35, 35); Parent.textMarkupAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.textMarkupAnnotationButton.TouchUpInside += Parent.helper.TextMarkupAnnotationButton_TouchUpInside; Parent.textMarkupAnnotationButton.Font = Parent.highFont; Parent.textMarkupAnnotationButton.SetTitle("\ue70e", UIControlState.Normal); Parent.textMarkupAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); Parent.annotationToolbar.Add(Parent.textMarkupAnnotationButton); Parent.inkAnnotationButton.Frame = new CGRect(Parent.annotationToolbar.Frame.Width / 2 + 85, 7, 35, 35); Parent.inkAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; Parent.inkAnnotationButton.Font = Parent.highFont; Parent.inkAnnotationButton.SetTitle("\ue704", UIControlState.Normal); Parent.inkAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); Parent.annotationToolbar.Add(Parent.inkAnnotationButton); Parent.annotationToolbar = Parent.UpdateToolbarBorder(Parent.annotationToolbar, Parent.annotationFrame); Parent.Add(Parent.annotationToolbar); Parent.isAnnotationToolbarVisible = true; Parent.highlightToolbar.RemoveFromSuperview(); Parent.strikeOutToolbar.RemoveFromSuperview(); Parent.underlineToolbar.RemoveFromSuperview(); Parent.colorToolbar.RemoveFromSuperview(); } else { RemoveAllToolbars(false); Parent.pdfViewerControl.AnnotationMode = AnnotationMode.None; Parent.isAnnotationToolbarVisible = false; } } internal void RemoveAllToolbars(bool isBackButton) { Parent.textAnnotationToolbar.RemoveFromSuperview(); if (!isBackButton) { Parent.colorToolbar.RemoveFromSuperview(); Parent.highlightToolbar.RemoveFromSuperview(); Parent.strikeOutToolbar.RemoveFromSuperview(); Parent.underlineToolbar.RemoveFromSuperview(); Parent.opacityPanel.RemoveFromSuperview(); Parent.inkAnnotationSessionToolbar.RemoveFromSuperview(); Parent.textAnnotationToolbar.RemoveFromSuperview(); Parent.inkAnnotationToolbar.RemoveFromSuperview(); Parent.annotationToolbar.RemoveFromSuperview(); Parent.thicknessToolbar.RemoveFromSuperview(); } Parent.isAnnotationToolbarVisible = false; Parent.isColorSelected = false; Parent.isThicknessTouched = false; Parent.isOpacityNeeded = false; } internal void SaveButton_TouchUpInside(object sender, EventArgs e) { Stream stream = new MemoryStream(); stream = Parent.pdfViewerControl.SaveDocument(); string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filepath = Path.Combine(path, "savedDocument.pdf"); FileStream outputFillStream = File.Open(filepath, FileMode.Create); stream.Position = 0; stream.CopyTo(outputFillStream); outputFillStream.Close(); UIAlertView alertview = new UIAlertView(); alertview.Frame = new CGRect(20, 100, 200, 200); alertview.Message = filepath; alertview.Title = "The modified document is saved in the below location."; alertview.AddButton("Ok"); alertview.Show(); RemoveAllToolbars(false); } } }<file_sep>/Forms/ListView/ListView/Samples/PullToRefresh/Model/BlogsInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewBlogsInfo : INotifyPropertyChanged { #region Fields private string blogTitle; private string blogCategory; private string blogAuthor; private string readMoreContent; #endregion #region Constructor public ListViewBlogsInfo() { } #endregion #region Properties public string BlogTitle { get { return blogTitle; } set { blogTitle = value; OnPropertyChanged("BlogTitle"); } } public string BlogCategory { get { return blogCategory; } set { blogCategory = value; OnPropertyChanged("BlogCategory"); } } public string BlogAuthor { get { return blogAuthor; } set { blogAuthor = value; OnPropertyChanged("BlogAuthor"); } } public string ReadMoreContent { get { return readMoreContent; } set { readMoreContent = value; OnPropertyChanged("ReadMoreContent"); } } #endregion #region Interface Member public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Forms/DataGrid/DataGrid.Android/MainActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "MainActivity.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid.Droid { using Android.App; using Android.Content.PM; using Android.OS; using SampleBrowser.Core.Droid; [Activity(Label = "SampleBrowser.SfDataGrid", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] /// <summary> /// The MainActivity of the Application /// </summary> public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { /// <summary> /// Called when the activity is starting /// </summary> /// <param name="bundle">On Create method parameter as bundle type bundle</param> protected override void OnCreate(Bundle bundle) { Xamarin.Forms.Platform.Android.FormsAppCompatActivity.TabLayoutResource = Resource.Layout.Tabbar; Xamarin.Forms.Platform.Android.FormsAppCompatActivity.ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); //// Pass the activity and Resources to core android project SampleBrowser.Core.Droid.CoreSampleBrowser.Init(this.Resources, this); this.LoadApplication(new App()); } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/BoxAndWhisker.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Graphics; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; namespace SampleBrowser { public class BoxAndWhisker : SamplePage { SfChart chart; BoxAndWhiskerSeries boxPlotSeries; TextView boxPlotMode; TextView showMedian; TextView symbol; List<string> boxPlotModeType; List<string> symbolType; Switch medianSwitch; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Employee Age Group in Various Department"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); CategoryAxis categoryAxis = new CategoryAxis(); categoryAxis.LabelPlacement = LabelPlacement.BetweenTicks; categoryAxis.ShowMajorGridLines = false; categoryAxis.Title.Text = "Department"; chart.PrimaryAxis = categoryAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Title.Text = "Age"; numericalAxis.Maximum = 60; numericalAxis.Minimum = 20; numericalAxis.Interval = 5; numericalAxis.ShowMinorGridLines = false; numericalAxis.LineStyle.StrokeWidth = 0; numericalAxis.MajorTickStyle.TickSize = 0; chart.SecondaryAxis = numericalAxis; boxPlotSeries = new BoxAndWhiskerSeries(); boxPlotSeries.ItemsSource = MainPage.BoxAndWhiskerData(); boxPlotSeries.XBindingPath = "Department"; boxPlotSeries.YBindingPath = "EmployeeAges"; boxPlotSeries.Width = 0.5; boxPlotSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; boxPlotSeries.TooltipEnabled = true; boxPlotSeries.EnableAnimation = true; boxPlotSeries.ShowMedian = true; chart.Series.Add(boxPlotSeries); return chart; } public override View GetPropertyWindowLayout(Context context) { int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; LinearLayout propertylayout = new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams( width * 2, 5); layoutParams1.SetMargins(0, 20, 0, 0); boxPlotMode = new TextView(context); boxPlotMode.Text = "Box Plot Mode"; boxPlotMode.SetPadding(5, 20, 0, 20); showMedian = new TextView(context); showMedian.Text = "Show Median"; showMedian.SetPadding(5, 20, 0, 20); symbol = new TextView(context); symbol.Text = "Symbol Type"; symbol.SetPadding(5, 20, 0, 20); Spinner selectBoxPlotModeType = new Spinner(context, SpinnerMode.Dialog); boxPlotModeType = new List<string>() { "Exclusive", "Inclusive", "Normal" }; Spinner selectSymbolType = new Spinner(context, SpinnerMode.Dialog); symbolType = new List<string>() { "Ellipse", "Diamond", "Cross", "Hexagon", "InvertedTriangle", "Pentagon", "Plus", "Rectangle", "Triangle" }; ArrayAdapter<string> dataAdapter = new ArrayAdapter<string> (context, Android.Resource.Layout.SimpleSpinnerItem, boxPlotModeType); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectBoxPlotModeType.Adapter = dataAdapter; selectBoxPlotModeType.ItemSelected += SelectBoxPlotModeType_ItemSelected; ArrayAdapter<string> dataAdapter1 = new ArrayAdapter<string> (context, Android.Resource.Layout.SimpleSpinnerItem, symbolType); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectSymbolType.Adapter = dataAdapter1; selectSymbolType.ItemSelected += SelectSymbolType_ItemSelected; medianSwitch = new Switch(context); medianSwitch.Checked = true; medianSwitch.CheckedChange += MedianSwitch_CheckedChange; propertylayout.AddView(boxPlotMode); propertylayout.AddView(selectBoxPlotModeType); propertylayout.AddView(symbol); propertylayout.AddView(selectSymbolType); propertylayout.AddView(showMedian); propertylayout.AddView(medianSwitch); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); propertylayout.AddView(separate, layoutParams1); return propertylayout; } private void MedianSwitch_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { boxPlotSeries.ShowMedian = e.IsChecked; } private void SelectSymbolType_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { switch (e.Position) { case 0: boxPlotSeries.SymbolType = ChartSymbolType.Ellipse; break; case 1: boxPlotSeries.SymbolType = ChartSymbolType.Diamond; break; case 2: boxPlotSeries.SymbolType = ChartSymbolType.Cross; break; case 3: boxPlotSeries.SymbolType = ChartSymbolType.Hexagon; break; case 4: boxPlotSeries.SymbolType = ChartSymbolType.InvertedTriangle; break; case 5: boxPlotSeries.SymbolType = ChartSymbolType.Pentagon; break; case 6: boxPlotSeries.SymbolType = ChartSymbolType.Plus; break; case 7: boxPlotSeries.SymbolType = ChartSymbolType.Rectangle; break; case 8: boxPlotSeries.SymbolType = ChartSymbolType.Triangle; break; } } private void SelectBoxPlotModeType_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { switch (e.Position) { case 0: boxPlotSeries.BoxPlotMode = BoxPlotMode.Exclusive; break; case 1: boxPlotSeries.BoxPlotMode = BoxPlotMode.Inclusive; break; case 2: boxPlotSeries.BoxPlotMode = BoxPlotMode.Normal; break; } } } }<file_sep>/iOS/SampleBrowser/Samples/TreeView/Model/FileManager.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using System.ComponentModel; using UIKit; namespace SampleBrowser { public class FileManager : INotifyPropertyChanged { private string fileName; private UIImage imageIcon; private ObservableCollection<FileManager> subFolder; public ObservableCollection<FileManager> SubFolder { get { return subFolder; } set { subFolder = value; RaisedOnPropertyChanged("SubFolder"); } } public string FileName { get { return fileName; } set { fileName = value; RaisedOnPropertyChanged("FileName"); } } public UIImage ImageIcon { get { return imageIcon; } set { imageIcon = value; RaisedOnPropertyChanged("ImageIcon"); } } public FileManager() { } public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } } }<file_sep>/Forms/PDF/PDF/Samples/MailAttachment/MailAttachment.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Drawing; using Syncfusion.Pdf; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using System.Reflection; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Parsing; using SampleBrowser.Core; namespace SampleBrowser.PDF { public partial class MailAttachment : SampleView { public MailAttachment() { InitializeComponent(); AddDetails(); this.newsLetter.IsToggled = true; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnTemplate.HorizontalOptions = LayoutOptions.Start; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; this.btnTemplate.VerticalOptions = LayoutOptions.Center; this.btnTemplate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnTemplate.VerticalOptions = LayoutOptions.Center; } } public void OnButtonClicked(object sender, EventArgs e) { #if COMMONSB Stream docStream = typeof(MailAttachment).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.FormFillingDocument.pdf"); #else Stream docStream = typeof(MailAttachment).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.FormFillingDocument.pdf"); #endif MemoryStream stream = new MemoryStream(); //Load the existing PDF document using (PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream)) { //Get the PDF form PdfLoadedForm lForm = ldoc.Form; if (name.Text != null) { //Load the textbox field PdfLoadedTextBoxField nameText = lForm.Fields["name"] as PdfLoadedTextBoxField; //Fill the text box nameText.Text = this.name.Text; } //Get the Radio button field PdfLoadedRadioButtonListField genderRadio = lForm.Fields["gender"] as PdfLoadedRadioButtonListField; switch(gender.Items[gender.SelectedIndex]) { case "Male": genderRadio.SelectedIndex = 0; break; case "Female": genderRadio.SelectedIndex = 2; break; case "Unspecified": genderRadio.SelectedIndex = 1; break; } //Load the textbox field PdfLoadedTextBoxField dobText = lForm.Fields["dob"] as PdfLoadedTextBoxField; //Fill the text box dobText.Text = this.dob.Date.ToString("dd MMMM yyyy"); if (this.emailID.Text != null) { //Load the textbox field PdfLoadedTextBoxField emailText = lForm.Fields["email"] as PdfLoadedTextBoxField; //Fill the text box emailText.Text = this.emailID.Text; } //Load the combobox field PdfLoadedComboBoxField countryCombo = lForm.Fields["state"] as PdfLoadedComboBoxField; //Set the selected value countryCombo.SelectedValue =this.country.Items[country.SelectedIndex]; //Get the Checkbox field PdfLoadedCheckBoxField newsCheck = lForm.Fields["newsletter"] as PdfLoadedCheckBoxField; newsCheck.Checked = this.newsLetter.IsToggled; //Flatten the form fields ldoc.Form.Flatten = true; //Save the PDF document ldoc.Save(stream); } stream.Position = 0; //Open in default system viewer. if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<IMailService>().ComposeMail("MailAttachment.pdf", null, "Workshop Registration", "Syncfusion", stream); else Xamarin.Forms.DependencyService.Get<IMailService>().ComposeMail("MailAttachment.pdf", null, "Workshop Registration", "Syncfusion", stream); } public void OnTemplateButtonClicked(object sender, EventArgs e) { #if COMMONSB Stream docStream = typeof(MailAttachment).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.FormFillingDocument.pdf"); #else Stream docStream = typeof(MailAttachment).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.FormFillingDocument.pdf"); #endif MemoryStream stream = new MemoryStream(); //Load the template document using (PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream)) { //Save the document loadedDocument.Save(stream); } if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("MailAttachmentTemplate.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("MailAttachmentTemplate.pdf", "application/pdf", stream); } #region Helper method private void AddDetails() { this.gender.Items.Add("Male"); this.gender.Items.Add("Female"); this.gender.Items.Add("Unspecified"); this.gender.SelectedIndex = 0; string[] countryList = new string[] { "Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming" }; for (int i = 0; i < countryList.Length; i++) country.Items.Add(countryList[i]); this.country.SelectedIndex = 0; } #endregion } } <file_sep>/Forms/DataGrid/DataGrid.iOS/AppDelegate.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "AppDelegate.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed.")] namespace SampleBrowser.SfDataGrid.iOS { using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] /// <summary> /// The UIApplicationDelegate for the application. This class is responsible for launching the User Interface of the application, as well as listening (and optionally responding) to application events from iOS. /// </summary> public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { /// <summary> /// This method is invoked when the application has loaded and is ready to run. In this method you should instantiate the window, load the UI into it and then make the window visible. You have 17 seconds to return from this method, or iOS will terminate your application. /// </summary> /// <param name="app">UIApplication type of app parameter</param> /// <param name="options">NSDictionary type of options parameter</param> /// <returns>returns base.FinishedLaunching</returns> public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); Syncfusion.SfDataGrid.XForms.iOS.SfDataGridRenderer.Init(); Syncfusion.ListView.XForms.iOS.SfListViewRenderer.Init(); Syncfusion.SfPullToRefresh.XForms.iOS.SfPullToRefreshRenderer.Init(); Syncfusion.XForms.iOS.PopupLayout.SfPopupLayoutRenderer.Init(); Syncfusion.SfSparkline.XForms.iOS.SfSparklineRenderer.Init(); Syncfusion.XForms.iOS.MaskedEdit.SfMaskedEditRenderer.Init(); SampleBrowser.Core.iOS.CoreSampleBrowser.Init(UIScreen.MainScreen.Bounds, app.StatusBarFrame.Size.Height); this.LoadApplication(new App()); return base.FinishedLaunching(app, options); } } } <file_sep>/iOS/SampleBrowser/Samples/CircularGauge/PointerDragging.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Foundation; using Syncfusion.SfGauge.iOS; using UIKit; namespace SampleBrowser { public class PointerDragging : SampleView { UISlider slider; UIView option = new UIView(); SFCircularGauge gauge; SFMarkerPointer markerPointer1; SFMarkerPointer markerPointer2; SFGaugeHeader header; SFCircularRange range; float firstMarkerValue = 2; float secondMarkerValue = 10; static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } if (Utility.IsIPad) { gauge.Frame = new CGRect(50, 50, (float)this.Frame.Width - 100, (float)this.Frame.Height - 100); } else { gauge.Frame = new CGRect(10, 10, (float)this.Frame.Width - 20, (float)this.Frame.Height - 20); } var minSize = Math.Min(gauge.Bounds.Width, gauge.Bounds.Height); var radius = (float)minSize / 2; var scale = gauge.Scales[0]; if (scale != null) { float pointerSize = radius * Math.Abs(scale.ScaleStartOffset - scale.ScaleEndOffSet); foreach (SFMarkerPointer pointer in scale.Pointers) { pointer.MarkerHeight = pointerSize; pointer.MarkerWidth = pointerSize; } } base.LayoutSubviews(); } public PointerDragging() { gauge = new SFCircularGauge(); header = new SFGaugeHeader(); header.Position = new CGPoint(0.5, 0.5); header.TextStyle = UIFont.FromName("Helvetica", 25f); header.TextColor = UIColor.FromRGB(255, 69, 0); header.Text = (NSString)("08" + " h" + " 00" + " min"); gauge.Headers.Add(header); SFCircularScale scale = new SFCircularScale(); scale.StartValue = 0; scale.EndValue = 12; scale.StartAngle = 180; scale.SweepAngle = 540; scale.Interval = 1; scale.LabelOffset = 0.67f; scale.ShowFirstLabel = false; scale.ScaleStartOffset = 0.9f; scale.ScaleEndOffSet = 0.8f; scale.MinorTicksPerInterval = 4; SFTickSettings majorTickSetting = new SFTickSettings(); majorTickSetting.StartOffset = 0.8f; majorTickSetting.EndOffset = 0.72f; majorTickSetting.Width = 2; majorTickSetting.Color = UIColor.DarkGray; SFTickSettings minorTickSetting = new SFTickSettings(); minorTickSetting.StartOffset = 0.8f; minorTickSetting.EndOffset = 0.75f; scale.MajorTickSettings = majorTickSetting; scale.MinorTickSettings = minorTickSetting; markerPointer1 = new SFMarkerPointer(); markerPointer1.EnableAnimation = false; markerPointer1.EnableDragging = true; markerPointer1.Offset = 0.9f; markerPointer1.Value = firstMarkerValue; markerPointer1.MarkerShape = MarkerShape.Circle; markerPointer1.Color = UIColor.FromRGB(247, 206, 114); markerPointer1.ValueChanging += MarkerPointer1_ValueChanging; markerPointer2 = new SFMarkerPointer(); markerPointer2.EnableAnimation = false; markerPointer2.EnableDragging = true; markerPointer2.Offset = 0.9f; markerPointer2.Value = secondMarkerValue; markerPointer2.MarkerShape = MarkerShape.Circle; markerPointer2.Color = UIColor.FromRGB(247, 206, 114); markerPointer2.ValueChanging += MarkerPointer2_ValueChanging; ; scale.Pointers.Add(markerPointer1); scale.Pointers.Add(markerPointer2); markerPointer2.StepFrequency = markerPointer1.StepFrequency = 0.2; range = new SFCircularRange(); range.StartValue = markerPointer1.Value; range.EndValue = markerPointer2.Value; range.InnerEndOffset = 0.8f; range.InnerStartOffset = 0.8f; range.OuterEndOffset = 0.9f; range.OuterStartOffset = 0.9f; range.Color = UIColor.FromRGB(229, 121, 130); gauge.PointerPositionChange += Gauge_PointerPositionChange; scale.Ranges.Add(range); gauge.Scales.Add(scale); this.AddSubview(gauge); CreateOptionView(); this.OptionView = option; } private void Gauge_PointerPositionChange(object sender, GaugeEventArgs e) { var index = e.PointerPosition.PointerIndex; double value; if (index == 0) { firstMarkerValue = (float)e.PointerPosition.PointerValue; value = Math.Abs(firstMarkerValue - secondMarkerValue); } else { secondMarkerValue = (float)e.PointerPosition.PointerValue; value = Math.Abs(secondMarkerValue - markerPointer1.Value); } range.StartValue = firstMarkerValue; range.EndValue = secondMarkerValue; CalculateTimeDifference(value); } private void MarkerPointer2_ValueChanging(object sender, SFCircularPointer.PointerValueChangingEventArgs e) { if ((e.NewValue) <= firstMarkerValue || Math.Abs(e.NewValue - secondMarkerValue) > 1) e.Cancel = true; } private void MarkerPointer1_ValueChanging(object sender, SFCircularPointer.PointerValueChangingEventArgs e) { if ((e.NewValue) >= secondMarkerValue || Math.Abs(e.NewValue - firstMarkerValue) > 1) e.Cancel = true; } private void CreateOptionView() { UILabel stepFrequencyText = new UILabel(); stepFrequencyText.Frame = new CGRect(10, 25, 150, 40); stepFrequencyText.Text = "Step Frequency : "; stepFrequencyText.Font = UIFont.BoldSystemFontOfSize(16); stepFrequencyText.TextColor = UIColor.FromRGB(0, 0, 0); UILabel stepFrequencyValue = new UILabel(); stepFrequencyValue.Frame = new CGRect(170, 25, 100, 40); stepFrequencyValue.Text = "0.2"; stepFrequencyValue.Font = UIFont.BoldSystemFontOfSize(16); stepFrequencyValue.TextColor = UIColor.FromRGB(0, 0, 0); slider = new UISlider(); slider.Frame = new CGRect(10, 80, 250, 60); slider.MinValue = 0f; slider.MaxValue = 1f; slider.Value = 0.2f; slider.ValueChanged += (object sender, EventArgs e) => { slider.Value = (float) (Math.Round(slider.Value / 0.2f) * 0.2f); markerPointer1.StepFrequency = markerPointer2.StepFrequency = slider.Value; stepFrequencyValue.Text = slider.Value.ToString(); }; this.option.AddSubview(stepFrequencyText); this.option.AddSubview(stepFrequencyValue); this.option.AddSubview(slider); } private void CalculateTimeDifference(double value) { int hour = Convert.ToInt32(Math.Floor(value)); float digit = hour / 10f; bool isHourSingleDigit = digit >= 1 ? false : true; var min = Math.Floor((value - hour) * 60); digit = (float)min / 10f; bool isMinuteSingleDigit = digit >= 1 ? false : true; string hourValue = isHourSingleDigit ? "0" + hour.ToString() : hour.ToString(); string minutesValue = isMinuteSingleDigit ? "0" + min.ToString() : min.ToString(); header.Text = (NSString)(hourValue + " h " + minutesValue + " min"); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Presentation/SlidesPresentation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.Presentation; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using System.Xml; using System.Linq; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class SlidesPresentation : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; public SlidesPresentation() { label1 = new UILabel(); label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to create a slide with predefined layouts, like Microsoft PowerPoint."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width , 50); } else { label.Frame = new CGRect (frameRect.Location.X, 5, frameRect.Size.Width , 70); } this.AddSubview (label); button.SetTitle("Generate Presentation",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect (0, 65, frameRect.Location.X + frameRect.Size.Width , 10); } else { button.Frame = new CGRect (frameRect.Location.X, 70, frameRect.Size.Width , 10); } this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Slides.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Presentation.Open(fileStream); #region Slide1 ISlide slide1 = presentation.Slides[0]; IShape shape1 = slide1.Shapes[0] as IShape; shape1.Left = 108; shape1.Top = 139.68; shape1.Width = 743.04; shape1.Height = 144; ITextBody textFrame1 = shape1.TextBody; IParagraphs paragraphs1 = textFrame1.Paragraphs; IParagraph paragraph1 = paragraphs1.Add(); paragraphs1[0].IndentLevelNumber = 0; AddParagraphData(paragraph1, "ESSENTIAL PRESENTATION", "Calibri", 48,true); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center; slide1.Shapes.RemoveAt(1); #endregion #region Slide2 ISlide slide2 = presentation.Slides.Add(SlideLayoutType.SectionHeader); shape1 = slide2.Shapes[0] as IShape; shape1.Left = 55; shape1.Top = 23; shape1.Width = 573; shape1.Height = 71; textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe paragraphs1 = textFrame1.Paragraphs; paragraph1 = paragraphs1.Add(); AddParagraphData(paragraph1, "Slide with simple text", "Calibri", 40, false); paragraphs1[0].HorizontalAlignment = HorizontalAlignmentType.Left; IShape shape2 = slide2.Shapes[1] as IShape; shape2.Left = 87; shape2.Top = 119; shape2.Width = 725; shape2.Height = 355; ITextBody textFrame2 = shape2.TextBody; //Instance to hold paragraphs in textframe IParagraphs paragraphs2 = textFrame2.Paragraphs; //Add paragrpah text IParagraph paragraph_1 = paragraphs2.Add(); AddParagraphData(paragraph_1, "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.", "Calibri", 15, false); IParagraph paragraph_2 = paragraphs2.Add(); AddParagraphData(paragraph_2, "In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group.", "Calibri", 15, false); #endregion #region Slide3 slide2 = presentation.Slides.Add(SlideLayoutType.TwoContent); shape1 = slide2.Shapes[0] as IShape; shape1.Left = 26; shape1.Top = 37; shape1.Width = 815; shape1.Height = 76; //Adds textframe in shape textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe paragraphs1 = textFrame1.Paragraphs; paragraphs1.Add(); paragraph1 = paragraphs1[0]; AddParagraphData(paragraph1, "Slide with Image", "Calibri", 44, false); //Adds shape in slide shape2 = slide2.Shapes[1] as IShape; shape2.Left = 578; shape2.Top = 141; shape2.Width = 316; shape2.Height = 326; textFrame2 = shape2.TextBody; //Instance to hold paragraphs in textframe paragraphs2 = textFrame2.Paragraphs; IParagraph paragraph2 = paragraphs2.Add(); AddParagraphData(paragraph2, "The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases.", "Calibri", 16, false); IParagraph paragraph3 = paragraphs2.Add(); AddParagraphData(paragraph3, "Using Northwind, you can become familiar with how a relational database is structured and how the database objects work together to help you enter, store, manipulate, and print your data.", "Calibri", 16, false); IParagraph paragraph4 = paragraphs2.Add(); // AddParagraphData(paragraph4, ref textpart1, "While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.", "Calibri", 16); IShape shape3 = (IShape)slide2.Shapes[2]; slide2.Shapes.RemoveAt(2); //Adds picture in the shape resourcePath = "SampleBrowser.Samples.Presentation.Templates.tablet.jpg"; assembly = Assembly.GetExecutingAssembly(); fileStream = assembly.GetManifestResourceStream(resourcePath); IPicture picture1 = slide2.Shapes.AddPicture(fileStream, 58, 141, 477, 318); fileStream.Close(); #endregion #region Slide4 ISlide slide4 = presentation.Slides.Add(SlideLayoutType.TwoContent); shape1 = slide4.Shapes[0] as IShape; shape1.Left = 37; shape1.Top = 24; shape1.Width = 815; shape1.Height = 76; textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe paragraphs1 = textFrame1.Paragraphs; paragraphs1.Add(); paragraph1 = paragraphs1[0]; AddParagraphData(paragraph1, "Slide with Table", "Calibri", 44, false); shape2 = slide4.Shapes[1] as IShape; slide4.Shapes.Remove(shape2); ITable table = (ITable)slide4.Shapes.AddTable(6, 6, 58, 154, 823, 273); table.Rows[0].Height = 61.2; table.Rows[1].Height = 30; table.Rows[2].Height = 61; table.Rows[3].Height = 61; table.Rows[4].Height = 61; table.Rows[5].Height = 61; table.HasBandedRows = true; table.HasHeaderRow = true; table.HasBandedColumns = false; table.BuiltInStyle = BuiltInTableStyle.MediumStyle2Accent1; ICell cell1 = table.Rows[0].Cells[0]; textFrame2 = cell1.TextBody; paragraph2 = textFrame2.Paragraphs.Add(); paragraph2.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart2 = paragraph2.AddTextPart(); textPart2.Text = "ID"; ICell cell2 = table.Rows[0].Cells[1]; ITextBody textFrame3 = cell2.TextBody; paragraph3 = textFrame3.Paragraphs.Add(); paragraph3.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart3 = paragraph3.AddTextPart(); textPart3.Text = "Company Name"; ICell cell3 = table.Rows[0].Cells[2]; ITextBody textFrame4 = cell3.TextBody; paragraph4 = textFrame4.Paragraphs.Add(); paragraph4.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart4 = paragraph4.AddTextPart(); textPart4.Text = "Contact Name"; ICell cell4 = table.Rows[0].Cells[3]; ITextBody textFrame5 = cell4.TextBody; IParagraph paragraph5 = textFrame5.Paragraphs.Add(); paragraph5.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart5 = paragraph5.AddTextPart(); textPart5.Text = "Address"; ICell cell5 = table.Rows[0].Cells[4]; ITextBody textFrame6 = cell5.TextBody; IParagraph paragraph6 = textFrame6.Paragraphs.Add(); paragraph6.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart6 = paragraph6.AddTextPart(); textPart6.Text = "City"; ICell cell6 = table.Rows[0].Cells[5]; ITextBody textFrame7 = cell6.TextBody; IParagraph paragraph7 = textFrame7.Paragraphs.Add(); paragraph7.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart7 = paragraph7.AddTextPart(); textPart7.Text = "Country"; //Add data in table AddTableData(cell1, table, textFrame1, paragraph1); slide4.Shapes.RemoveAt(1); #endregion MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("SlidesPresentation.pptx", "application/mspowerpoint", stream); } } void AddTableData(ICell cell1, ITable table, ITextBody textFrame1, IParagraph paragraph1) { Dictionary<string, Dictionary<string, string>> products = LoadXMLData(); int count = 0; for (int i = 1; i <= 5; i++) { for (int j = 0; j <= 5; j++) { cell1 = table.Rows[i].Cells[j]; textFrame1 = cell1.TextBody; paragraph1 = textFrame1.Paragraphs.Add(); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textpart1 = paragraph1.AddTextPart(); textpart1.Text = products.Values.ToList()[0].Values.ToList()[count]; count++; } } } void AddParagraphData(IParagraph paragraph, string text, string fontname, int fontsize,bool isBolt) { ITextPart textpart = paragraph.AddTextPart(); paragraph.HorizontalAlignment = HorizontalAlignmentType.Left; textpart.Text = text; textpart.Font.FontName = fontname; textpart.Font.FontSize = fontsize; textpart.Font.Color = ColorObject.Black; textpart.Font.Bold = isBolt; } private Dictionary<string, Dictionary<string, string>> LoadXMLData() { Dictionary<string, Dictionary<string, string>> Products = new Dictionary<string, Dictionary<string, string>>(); Assembly assembly = Assembly.GetExecutingAssembly(); Stream productXMLStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.Presentation.Templates.SlideTableData.xml"); XmlReader reader = XmlReader.Create(productXMLStream); string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; string cell; while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Products": Dictionary<string, string> Cell_Value = new Dictionary<string, string>(); while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Product": while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.Name) { case "Cell": while (reader.Read()) { cell = reader.Name; if (reader.IsStartElement()) { cell = reader.Name; while (reader.Read()) { if (reader.IsStartElement()) { if (reader.Name == "Value") { reader.Read(); reader.MoveToContent(); Cell_Value.Add(cell, reader.Value); } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == cell) { break; } } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Cell") { break; } } break; case "ProductName": reader.Read(); reader.MoveToContent(); productName = reader.Value; break; } } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Product") { break; } } break; } Products.Add(productName, Cell_Value); Cell_Value = new Dictionary<string, string>(); } else if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "Products") break; } break; } } } return Products; } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/iOS/SampleBrowser/Samples/Maps/DataLabels.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Syncfusion.SfBusyIndicator.iOS; #endregion using System; using Syncfusion.SfMaps.iOS; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Drawing; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGPoint= System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class DataLabels : SampleView { internal SfBusyIndicator busyindicator; UIPickerView smartLabelMode; UIPickerView intersectActionMode; UIView option = new UIView(); UIView view; SFShapeFileLayer layer; bool isDisposed; public override void LayoutSubviews() { view.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); ; SetNeedsDisplay(); } protected override void Dispose(bool disposing) { isDisposed = true; base.Dispose(disposing); } public DataLabels() { smartLabelMode = new UIPickerView(); intersectActionMode = new UIPickerView(); SFMap maps = new SFMap(); view = new UIView(); view.Frame = new CGRect(0, 0, 300, 400); busyindicator = new SfBusyIndicator(); busyindicator.ViewBoxWidth = 75; busyindicator.ViewBoxHeight = 75; busyindicator.Foreground = UIColor.FromRGB(0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; view.AddSubview(busyindicator); NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(0.3), delegate { if (isDisposed) return; maps.Frame = new CGRect(Frame.Location.X, 60, Frame.Size.Width - 6, Frame.Size.Height - 60); view.AddSubview(maps); }); layer = new SFShapeFileLayer(); layer.Uri = (NSString)NSBundle.MainBundle.PathForResource("usa_state", "shp"); layer.ShapeIDPath = (NSString)"Name"; layer.ShapeIDTableField = (NSString)"STATE_NAME"; layer.ShowMapItems = true; layer.DataSource = GetDataSource(); SFShapeSetting shapeSettings = new SFShapeSetting(); shapeSettings.ColorValuePath = (NSString)"Type"; shapeSettings.ValuePath = (NSString)"Name"; shapeSettings.Fill = UIColor.FromRGB(169, 217, 247); SetColorMapping(shapeSettings); layer.ShapeSettings = shapeSettings; layer.TooltipSettings.ShowTooltip = true; layer.TooltipSettings.ValuePath = (NSString)"Name"; SFDataLabelSetting dataLabelSetting = new SFDataLabelSetting(); dataLabelSetting.SmartLabelMode = IntersectAction.Trim; dataLabelSetting.IntersectionAction = IntersectAction.None; layer.DataLabelSettings = dataLabelSetting; maps.Layers.Add(layer); AddSubview(view); CreateOptionView(); this.OptionView = option; maps.Delegate = new MapsDataLabelsDelegate(this); } private void CreateOptionView() { UILabel text1 = new UILabel(); text1.Text = "SmartLabelMode"; text1.TextAlignment = UITextAlignment.Left; text1.TextColor = UIColor.Black; text1.Frame = new CGRect(10, 10, 320, 40); text1.Font = UIFont.FromName("Helvetica", 14f); List<string> position1 = new List<string> { "Trim", "None", "Hide" }; var picker1 = new SmartLabelPickerModel(position1); smartLabelMode.Model = picker1; smartLabelMode.SelectedRowInComponent(0); smartLabelMode.Frame = new CGRect(10, 50, 200, 40); picker1.ValueChanged += (sender, e) => { if (picker1.SelectedValue == "None") layer.DataLabelSettings.SmartLabelMode = IntersectAction.None; else if (picker1.SelectedValue == "Trim") layer.DataLabelSettings.SmartLabelMode = IntersectAction.Trim; else if (picker1.SelectedValue == "Hide") layer.DataLabelSettings.SmartLabelMode = IntersectAction.Hide; }; UILabel text2 = new UILabel(); text2.Text = "Intersection Action"; text2.TextAlignment = UITextAlignment.Left; text2.TextColor = UIColor.Black; text2.Frame = new CGRect(10, 90, 320, 40); text2.Font = UIFont.FromName("Helvetica", 14f); List<string> position2 = new List<string> { "None", "Trim", "Hide" }; var picker2 = new IntersectActionPickerModel(position2); intersectActionMode.Model = picker2; intersectActionMode.SelectedRowInComponent(0); intersectActionMode.Frame = new CGRect(10, 140, 200, 40); picker2.ValueChanged += (sender, e) => { if (picker2.SelectedValue == "None") layer.DataLabelSettings.IntersectionAction = IntersectAction.None; else if (picker2.SelectedValue == "Trim") layer.DataLabelSettings.IntersectionAction = IntersectAction.Trim; else if (picker2.SelectedValue == "Hide") layer.DataLabelSettings.IntersectionAction = IntersectAction.Hide; }; this.option.AddSubview(text1); this.option.AddSubview(smartLabelMode); this.option.AddSubview(text2); this.option.AddSubview(intersectActionMode); } void SetColorMapping(SFShapeSetting setting) { ObservableCollection<SFMapColorMapping> colorMappings = new ObservableCollection<SFMapColorMapping>(); SFEqualColorMapping colorMapping1 = new SFEqualColorMapping(); colorMapping1.Value = (NSString)"Rice"; colorMapping1.Color = UIColor.FromRGB(181, 228, 133); colorMappings.Add(colorMapping1); SFEqualColorMapping colorMapping2 = new SFEqualColorMapping(); colorMapping2.Value = (NSString)"Vegetables"; colorMapping2.Color = UIColor.FromRGB(236, 155, 121); colorMappings.Add(colorMapping2); SFEqualColorMapping colorMapping3 = new SFEqualColorMapping(); colorMapping3.Value = (NSString)"Wheat"; colorMapping3.Color = UIColor.FromRGB(145, 120, 227); colorMappings.Add(colorMapping3); SFEqualColorMapping colorMapping4 = new SFEqualColorMapping(); colorMapping4.Value = (NSString)"Grains"; colorMapping4.Color = UIColor.FromRGB(228, 193, 108); colorMappings.Add(colorMapping4); SFEqualColorMapping colorMapping5 = new SFEqualColorMapping(); colorMapping5.Value = (NSString)"Oats"; colorMapping5.Color = UIColor.FromRGB(223, 129, 156); colorMappings.Add(colorMapping5); setting.ColorMappings = colorMappings; } NSMutableArray GetDataSource() { NSMutableArray array = new NSMutableArray(); array.Add(getDictionary("Alabama", "Vegetables", 42)); array.Add(getDictionary("Alabama", "Vegetables", 42)); array.Add(getDictionary("Alaska", "Vegetables", 0)); array.Add(getDictionary("Arizona", "Rice", 36)); array.Add(getDictionary("Arkansas", "Vegetables", 46)); array.Add(getDictionary("California", "Rice", 24)); array.Add(getDictionary("Colorado", "Rice", 31)); array.Add(getDictionary("Connecticut", "Grains", 18)); array.Add(getDictionary("Delaware", "Grains", 28)); array.Add(getDictionary("District of Columbia", "Grains", 27)); array.Add(getDictionary("Florida", "Rice", 48)); array.Add(getDictionary("Georgia", "Oats", 44)); array.Add(getDictionary("Hawaii", "Grains", 49)); array.Add(getDictionary("Idaho", "Grains", 8)); array.Add(getDictionary("Illinois", "Vegetables", 26)); array.Add(getDictionary("Indiana", "Grains", 21)); array.Add(getDictionary("Iowa", "Vegetables", 13)); array.Add(getDictionary("Kansas", "Rice", 33)); array.Add(getDictionary("Kentucky", "Grains", 32)); array.Add(getDictionary("Louisiana", "Oats", 47)); array.Add(getDictionary("Maine", "Oats", 3)); array.Add(getDictionary("Maryland", "Grains", 30)); array.Add(getDictionary("Massachusetts", "Grains", 14)); array.Add(getDictionary("Michigan", "Grains", 50)); array.Add(getDictionary("Minnesota", "Wheat", 10)); array.Add(getDictionary("Mississippi", "Vegetables", 43)); array.Add(getDictionary("Missouri", "Oats", 35)); array.Add(getDictionary("Montana", "Grains", 2)); array.Add(getDictionary("Nebraska", "Rice", 15)); array.Add(getDictionary("Nevada", "Wheat", 22)); array.Add(getDictionary("New Hampshire", "Grains", 12)); array.Add(getDictionary("New Jersey", "Vegetables", 20)); array.Add(getDictionary("New Mexico", "Oats", 41)); array.Add(getDictionary("New York", "Vegetables", 16)); array.Add(getDictionary("North Carolina", "Rice", 38)); array.Add(getDictionary("North Dakota", "Grains", 4)); array.Add(getDictionary("Ohio", "Vegetables", 25)); array.Add(getDictionary("Oklahoma", "Rice", 37)); array.Add(getDictionary("Oregon", "Wheat", 11)); array.Add(getDictionary("Pennsylvania", "Oats", 17)); array.Add(getDictionary("Rhode Island", "Grains", 19)); array.Add(getDictionary("South Carolina", "Rice", 45)); array.Add(getDictionary("South Dakota", "Grains", 5)); array.Add(getDictionary("Tennessee", "Vegetables", 39)); array.Add(getDictionary("Texas", "Vegetables", 40)); array.Add(getDictionary("Utah", "Rice", 23)); array.Add(getDictionary("Vermont", "Grains", 9)); array.Add(getDictionary("Virginia", "Rice", 34)); array.Add(getDictionary("Washington", "Vegetables", 1)); array.Add(getDictionary("West Virginia", "Grains", 29)); array.Add(getDictionary("Wisconsin", "Oats", 7)); array.Add(getDictionary("Wyoming", "Wheat", 6)); return array; } NSDictionary getDictionary(string name, string type, int index) { NSString name1 = (NSString)name; object[] objects = new object[3]; object[] keys = new object[3]; keys.SetValue("Name", 0); keys.SetValue("index", 1); keys.SetValue("Type", 2); objects.SetValue(name1, 0); objects.SetValue(index, 1); objects.SetValue(type, 2); return NSDictionary.FromObjectsAndKeys(objects, keys); } } public class SmartLabelPickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public SmartLabelPickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); } } public class IntersectActionPickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public IntersectActionPickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); } } public class MapsDataLabelsDelegate : SFMapsDelegate { public MapsDataLabelsDelegate(DataLabels dataLabels) { sample = dataLabels; } DataLabels sample; public override void DidLoad(SFMap map) { if (sample.busyindicator != null) { sample.busyindicator.RemoveFromSuperview(); sample.busyindicator = null; } } } } <file_sep>/Android/SampleBrowser/Samples/DataSource/Helper/TemplateView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Graphics.Drawables; using Com.Syncfusion.Rating; using Android.Util; using Android.Graphics.Drawables.Shapes; namespace SampleBrowser { public class GettingStartedTemplate : GridLayout { #region Field private ImageView imageView; private TextView label1; private TextView label2; private TextView label3; private TextView label4; private GridLayout detailsLayout; #endregion public GettingStartedTemplate(Context context) : base(context) { this.ColumnCount = 2; this.RowCount = 1; var paddingValue = (int)(15 * Resources.DisplayMetrics.Density); this.SetPadding(paddingValue, paddingValue, paddingValue / 2, paddingValue); imageView = new ImageView(context); imageView.SetMaxHeight((int)(100 * this.Resources.DisplayMetrics.Density)); imageView.SetMaxWidth((int)(80 * this.Resources.DisplayMetrics.Density)); label1 = new TextView(context); label2 = new TextView(context); label3 = new TextView(context); label4 = new TextView(context); detailsLayout = new GridLayout(context); detailsLayout.RowCount = 4; detailsLayout.ColumnCount = 1; detailsLayout.AddView(label1); detailsLayout.AddView(label2); detailsLayout.AddView(label3); detailsLayout.AddView(label4); this.AddView(imageView, (int)(80 * this.Resources.DisplayMetrics.Density), (int)(100 * this.Resources.DisplayMetrics.Density)); this.AddView(detailsLayout, ViewGroup.LayoutParams.MatchParent, (int)(100 * this.Resources.DisplayMetrics.Density)); } public void UpdateValue(object obj) { var bookDetails = obj as BookDetails; imageView.SetImageBitmap(bookDetails.CustomerImage); label1.Text = "Name : " + bookDetails.CustomerName; label2.Text = "Book ID : " + bookDetails.BookID.ToString(); label3.Text = "Book name : " + bookDetails.BookName; label4.Text = "Price : " + "$" + bookDetails.Price.ToString(); } private void UpdateHeight() { var imageWidth = (int)(this.Resources.DisplayMetrics.WidthPixels * 0.35); detailsLayout.SetPadding((int)(this.Resources.DisplayMetrics.WidthPixels * 0.15), 0, 0, 0); var labelWidth = this.Resources.DisplayMetrics.WidthPixels - (imageWidth / 2); var labelHeight = ((int)(100 * this.Resources.DisplayMetrics.Density)) / 4; label1.SetMinimumHeight(labelHeight); label1.SetMinimumWidth(labelWidth); label2.SetMinimumHeight(labelHeight); label2.SetMinimumWidth(labelWidth); label3.SetMinimumHeight(labelHeight); label3.SetMinimumWidth(labelWidth); label4.SetMinimumHeight(labelHeight); label4.SetMinimumWidth(labelWidth); label1.Measure(labelWidth, labelHeight); label2.Measure(labelWidth, labelHeight); label3.Measure(labelWidth, labelHeight); label4.Measure(labelWidth, labelHeight); } protected override void OnSizeChanged(int w, int h, int oldw, int oldh) { UpdateHeight(); base.OnSizeChanged(w, h, oldw, oldh); } } public class ConctactTemplate : GridLayout { private CircleView label1; private TextView label2; private TextView label3; private GridLayout detailsLayout; public ConctactTemplate(Context context) : base(context) { this.SetPadding(25, 25, 25, 25); this.ColumnCount = 2; this.RowCount = 1; label1 = new CircleView(context); label1.SetTypeface(Typeface.DefaultBold, TypefaceStyle.Bold); label1.TextSize = 25; label1.Gravity = GravityFlags.Center; label1.SetTextColor(Color.White); label2 = new TextView(context); label3 = new TextView(context); label2.Gravity = GravityFlags.Start; label3.Gravity = GravityFlags.Start; label2.SetTextColor(Color.Black); label2.TextSize = 18; label3.TextSize = 14; label3.SetTextColor(Color.LightGray); detailsLayout = new GridLayout(context); detailsLayout.RowCount = 4; detailsLayout.ColumnCount = 1; detailsLayout.AddView(label2); detailsLayout.AddView(label3); detailsLayout.SetPadding((int)(20 * this.Resources.DisplayMetrics.Density), (int)(5 * this.Resources.DisplayMetrics.Density), 0, 0); this.AddView(label1, (int)(50 * this.Resources.DisplayMetrics.Density), (int)(50 * this.Resources.DisplayMetrics.Density)); this.AddView(detailsLayout); } public void UpdateValue(object obj) { var contact = obj as Contacts; label1.Text = contact.ContactName[0].ToString(); label2.Text = contact.ContactName; label3.Text = contact.ContactNumber; label1.CircleColor = contact.ContactColor; } } public class CircleView : TextView { private Paint paint; private Paint textPaint; public Color CircleColor { get; set; } public CircleView(Context context) : base(context) { CircleColor = Color.White; paint = new Paint(PaintFlags.AntiAlias); paint.SetStyle(Android.Graphics.Paint.Style.FillAndStroke); textPaint = new Paint(PaintFlags.AntiAlias); textPaint.SetStyle(Android.Graphics.Paint.Style.Stroke); textPaint.TextSize = 20; } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure(widthMeasureSpec, heightMeasureSpec); } protected override void OnDraw(Canvas canvas) { paint.Color = CircleColor; var x = this.Width / 2; canvas.DrawCircle(x, x, x, paint); base.OnDraw(canvas); } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/StackedDoughnut.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Java.Lang; using System.Collections.ObjectModel; namespace SampleBrowser { public class StackedDoughnut : SamplePage { void Chart_LegendItemCreated(object sender, ChartLegendItemCreatedEventArgs e) { MultipleCircleModel datamodel = e.LegendItem.DataPoint as MultipleCircleModel; LinearLayout outerLayout = new LinearLayout(chart.Context); outerLayout.Orientation = Orientation.Horizontal; outerLayout.SetBackgroundColor(Color.Transparent); LinearLayout innerLayout = new LinearLayout(chart.Context); innerLayout.Orientation = Orientation.Vertical; innerLayout.SetPadding(3, 30, 3, 0); innerLayout.SetBackgroundColor(Color.Transparent); TextView loanName = new TextView(chart.Context); TextView loanPercent = new TextView(chart.Context); ImageView centerView = new ImageView(chart.Context); centerView.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams((int)(40 * density), (int)(40 * density))); centerView.SetImageResource(datamodel.ImageResId); loanPercent.Text = (e.LegendItem.DataPoint as MultipleCircleModel).YValue + "%"; loanPercent.TextAlignment = Android.Views.TextAlignment.Center; loanPercent.Gravity = GravityFlags.Center; loanPercent.SetTextColor(e.LegendItem.IconColor); loanPercent.TextSize = 15; loanName.Text = (e.LegendItem.DataPoint as MultipleCircleModel).XValue; loanName.TextAlignment = Android.Views.TextAlignment.Center; loanName.Gravity = GravityFlags.Center; loanName.SetTextColor(Color.Black); innerLayout.AddView(loanPercent); innerLayout.AddView(loanName); SfChart sfChart = new SfChart(chart.Context); sfChart.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams((int)(65 * density), (int)(65 * density))); sfChart.SetBackgroundColor(Color.White); DoughnutSeries series = new DoughnutSeries(); series.Color = e.LegendItem.IconColor; series.ItemsSource = new ObservableCollection<MultipleCircleModel>() { datamodel }; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.StartAngle = -90; series.EndAngle = 270; series.MaximumValue = 100; series.Spacing = 0.4; series.DoughnutCoefficient = 0.6; series.CircularCoefficient = 0.9; series.CapStyle = DoughnutCapStyle.BothCurve; series.IsStackedDoughnut = true; series.CenterView = centerView; sfChart.Series.Add(series); outerLayout.AddView(sfChart); outerLayout.AddView(innerLayout); e.LegendItem.View = outerLayout; } List<Color> colors; SfChart chart; float density; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Percentage of Loan Closure"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.OverflowMode = ChartLegendOverflowMode.Wrap; chart.LegendItemCreated += Chart_LegendItemCreated; density = context.Resources.DisplayMetrics.Density; colors = new List<Color>(); colors.Add(Color.ParseColor("#47ba9f")); colors.Add(Color.ParseColor("#e58870")); colors.Add(Color.ParseColor("#9686c9")); colors.Add(Color.ParseColor("#e56590")); ImageView image = new ImageView(chart.Context); image.LayoutParameters = new ViewGroup.LayoutParams(new LinearLayout.LayoutParams((int)(100 * density), (int)(100 * density))); image.SetImageResource(Resource.Drawable.Person); DoughnutSeries doughnutSeries = new DoughnutSeries(); doughnutSeries.ColorModel.ColorPalette = ChartColorPalette.Custom; doughnutSeries.ColorModel.CustomColors = colors; doughnutSeries.ItemsSource = MainPage.GetStackedDoughnutData(); doughnutSeries.XBindingPath = "XValue"; doughnutSeries.YBindingPath = "YValue"; doughnutSeries.StartAngle = -90; doughnutSeries.EndAngle = 270; doughnutSeries.MaximumValue = 100; doughnutSeries.Spacing = 0.4; doughnutSeries.DoughnutCoefficient = 0.6; doughnutSeries.CircularCoefficient = 0.9; doughnutSeries.IsStackedDoughnut = true; doughnutSeries.CapStyle = DoughnutCapStyle.BothCurve; doughnutSeries.CenterView = image; chart.Series.Add(doughnutSeries); return chart; } } public class MultipleCircleModel { public string XValue { get; set; } public double YValue { get; set; } public int ImageResId { get; set; } public MultipleCircleModel(string xValue, double yValue, int image) { XValue = xValue; YValue = yValue; ImageResId = image; } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/ContextMenu.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Syncfusion.iOS.PopupLayout; using Syncfusion.SfDataGrid; using System.Linq; using System.Collections; using UIKit; using System.ComponentModel; namespace SampleBrowser { public class ContextMenu : SampleView { #region Private Field //Source Initializing private SfDataGrid sfGrid; private SfPopupLayout sfPopup; private ContextMenuViewModel contextMenuItem; private String currentColumn; //Button and Image Initializing private UIView buttonColumn; private UIView imageColumn; //Buttons and Image Arrray private string[] contextMenuButtonNames; private string[] contextMenuImageNames; #endregion #region Constructor public ContextMenu() { //Button and Images Name's Contained in array this.contextMenuButtonNames = new string[] { "Sort Ascending", "Sort Descending", "Clear Sorting", "seperator", "Group this Column", "Clear Grouping" }; this.contextMenuImageNames = new string[] { "Images/Sort_Ascending_Icons.png", "Images/Sort_descending_Icons.png", "Images/Clear_sorting_Icon.png", "seperator", "Images/Grouping_Icon.png", "Images/Clear_grouping_icon.png" }; this.sfGrid = new SfDataGrid(); this.sfGrid.AutoGenerateColumns = true; this.contextMenuItem = new ContextMenuViewModel(); this.sfGrid.ItemsSource = this.contextMenuItem.Products; this.sfPopup = new SfPopupLayout(); this.sfPopup.Content = this.sfGrid; //Event Handling this.sfGrid.GridLongPressed += SfGrid_GridLongPressed; //Popup Initializing InitializingPopContent(); //ContextMenu Initializing InitializingContextMenuLayout(); //Adding the poppup view as rootView this.Add(this.sfPopup); } #endregion #region Methods public override void LayoutSubviews() { this.sfPopup.Frame = new CoreGraphics.CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } private void InitializingPopContent() { this.sfPopup.PopupView.AnimationMode = AnimationMode.Fade; this.sfPopup.PopupView.AnimationDuration = 300; this.sfPopup.PopupView.ShowHeader = false; this.sfPopup.PopupView.ShowFooter = false; this.sfPopup.PopupView.ShowCloseButton = false; this.sfPopup.PopupView.Frame = new CoreGraphics.CGRect(0, 0, 200, 200); } private void InitializingContextMenuLayout() { //contextMenu UIView contextMenu = new UIView(); contextMenu.BackgroundColor = UIColor.White; contextMenu.Frame = new CGRect(0, 0, 200, 200); //contextMenuView with horizontal alignment to hold the imageColum & buttonColumn UIStackView contextMenuView = new UIStackView { Axis = UILayoutConstraintAxis.Horizontal }; contextMenuView.Frame = new CGRect(0, 0, 200, 200); //initializing & Framing this.imageColumn = new UIView(); this.imageColumn.Frame = new CGRect(10, 0, 50, 200); this.buttonColumn = new UIView(); this.buttonColumn.Frame = new CGRect(imageColumn.Frame.Width, 0, 150, 200); //Method to creating Image's and Button CreateImages(contextMenuImageNames); CreateButtons(contextMenuButtonNames); contextMenuView.AddSubview(this.imageColumn); contextMenuView.AddSubview(this.buttonColumn); contextMenu.AddSubview(contextMenuView); this.sfPopup.PopupView.ContentView = contextMenu; } void SfGrid_GridLongPressed(object sender, GridLongPressedEventArgs e) { this.currentColumn = this.sfGrid.Columns[e.RowColumnIndex.ColumnIndex].MappingName; this.sfPopup.ShowAtTouchPoint(); } private void CreateImages(string[] imageNames) { var initialEntry = false; for (int i = 0; i < imageNames.Length; i++) { if (imageNames[i].Equals("seperator")) { UIView seperatorView = new UIView(); seperatorView.BackgroundColor = UIKit.UIColor.White; seperatorView.Frame = new CGRect(0, imageColumn.Subviews[i - 1].Frame.Bottom + 5, 30, 2); seperatorView.Alpha = .1f; this.imageColumn.AddSubview(seperatorView); } else { UIImageView imageView = new UIImageView(); imageView.Image = new UIImage(imageNames[i]); imageView.Frame = !initialEntry ? new CGRect(0, 10, 25, 25) : new CGRect(0, imageColumn.Subviews[i - 1].Frame.Bottom + 10, 25, 25); if (imageNames[i].Equals("Images/Clear_sorting_Icon.png") || imageNames[i].Equals("Images/Clear_grouping_icon.png")) { imageView.Alpha = .3f; } //Adding the every image into the contextMenuOptionImage this.imageColumn.AddSubview(imageView); initialEntry = true; } } } private void CreateButtons(string[] buttonNames) { var initialEntry = false; for (int i = 0; i < buttonNames.Length; i++) { if (buttonNames[i].Equals("seperator")) { UIView seperatorView = new UIView(); seperatorView.BackgroundColor = UIColor.Gray; seperatorView.Frame = new CGRect(-42, buttonColumn.Subviews[i - 1].Frame.Bottom + 1, 180, 1); seperatorView.Alpha = .3f; this.buttonColumn.AddSubview(seperatorView); } else { UIButton buttonView = UIButton.FromType(UIButtonType.System); buttonView.SetTitle(buttonNames[i], UIControlState.Normal); buttonView.SetTitleColor(UIColor.Black, UIControlState.Normal); buttonView.Frame = !initialEntry ? new CGRect(0, 10, this.buttonColumn.Frame.Width, this.buttonColumn.Frame.Height / 6) : new CGRect(0, buttonColumn.Subviews[i - 1].Frame.Bottom + 2, this.buttonColumn.Frame.Width, this.buttonColumn.Frame.Height / 6); if (buttonNames[i].Equals("Clear Sorting") || buttonNames[i].Equals("Clear Grouping")) { buttonView.Alpha = .3f; } buttonView.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; //Event Trigger buttonView.TouchUpInside += ButtonTouch; //Adding the every button into the contextMenuButton this.buttonColumn.AddSubview(buttonView); initialEntry = true; } } } private void ButtonTouch(object sender, EventArgs e) { var buttonName = (sender as UIButton).TitleLabel.Text; switch (buttonName) { case "Sort Ascending": case "Sort Descending": case "Clear Sorting": this.sfGrid.SortColumnDescriptions.Clear(); if (!(buttonName == "Clear Sorting")) { // Sorting is applied this.sfGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = this.currentColumn, SortDirection = (buttonName == "Sort Ascending") ? ListSortDirection.Ascending : ListSortDirection.Descending }); } ApplyAlphaToSorting(buttonName); break; case "Group this Column": case "Clear Grouping": { if (sfGrid.GroupColumnDescriptions.Count == 0) { // Grouping is applied sfGrid.GroupColumnDescriptions.Add(new GroupColumnDescription() { ColumnName = this.currentColumn }); } else { // Clears the Grouping this.sfGrid.GroupColumnDescriptions.Clear(); if (this.sfGrid.SortColumnDescriptions.Count > 0) { this.sfGrid.SortColumnDescriptions.Clear(); ApplyAlphaToSorting("Clear Sorting"); } } ApplyAlphaToGrouping(); break; } } this.sfPopup.IsOpen = false; } private void ApplyAlphaToSorting(string buttonName) { this.imageColumn.Subviews[0].Alpha = buttonName == "Sort Ascending" ? .4f : 1f; this.buttonColumn.Subviews[0].Alpha = buttonName == "Sort Ascending" ? .4f : 1f; this.imageColumn.Subviews[1].Alpha = buttonName == "Sort Descending" ? .4f : 1f; this.buttonColumn.Subviews[1].Alpha = buttonName == "Sort Descending" ? .4f : 1f; this.imageColumn.Subviews[2].Alpha = this.sfGrid.SortColumnDescriptions.Count > 0 ? 1f : .4f; this.buttonColumn.Subviews[2].Alpha = this.sfGrid.SortColumnDescriptions.Count > 0 ? 1f : .4f; } private void ApplyAlphaToGrouping() { (this.buttonColumn.Subviews[4] as UIButton).Enabled = this.sfGrid.GroupColumnDescriptions.Count > 0 ? false : true; this.buttonColumn.Subviews[4].Alpha = this.sfGrid.GroupColumnDescriptions.Count > 0 ? .4f : 1; this.imageColumn.Subviews[4].Alpha = this.sfGrid.GroupColumnDescriptions.Count > 0 ? .4f : 1; this.imageColumn.Subviews[5].Alpha = this.sfGrid.GroupColumnDescriptions.Count > 0 ? 1f : .4f; this.buttonColumn.Subviews[5].Alpha = this.sfGrid.GroupColumnDescriptions.Count > 0 ? 1f : .4f; } #endregion } } <file_sep>/Forms/TabView/TabView.UWP/CustomFrameRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.SfTabView; using SampleBrowser.SfTabView.UWP; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; [assembly: ExportRenderer(typeof(CustomFrame), typeof(CustomFrameRenderer))] namespace SampleBrowser.SfTabView.UWP { public class CustomFrameRenderer : FrameRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Frame> e) { base.OnElementChanged(e); if (e.NewElement != null) { (this.Control as Border).Background = FormColorToNativeColor((e.NewElement as CustomFrame).BackgroundColor); if ((e.NewElement as CustomFrame).CornerRadius != -1) (this.Control as Border).CornerRadius = new Windows.UI.Xaml.CornerRadius((e.NewElement as CustomFrame).CornerRadius); } } internal Windows.UI.Xaml.Media.SolidColorBrush FormColorToNativeColor(Color color) { return new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Color.FromArgb((byte)(color.A * 255), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255))); } } } <file_sep>/Forms/Diagram/Diagram/Samples/DrawingTool/DrawingTool.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfDiagram.XForms; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfDiagram { public partial class DrawingTool : SampleView { public DrawingTool() { InitializeComponent(); if (Device.RuntimePlatform == Device.Android) Xamarin.Forms.DependencyService.Get<IText>().GenerateFactor(); diagram.IsReadOnly = true; Node n1 = DrawNode(145, 110, 100, 55, ShapeType.Rectangle, "Node1"); if (Device.RuntimePlatform == Device.UWP) { n1.ShapeType = ShapeType.Rectangle; } n1.Style.Brush = new SolidBrush(Color.FromRgb(49, 162, 255)); n1.Style.StrokeBrush = new SolidBrush(Color.FromRgb(23, 132, 206)); PortCollection node1ports = new PortCollection(); Port port1 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 0, ShapeType = ShapeType.Circle,IsVisible=true }; Port port2 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle ,IsVisible = true}; Port port3 = new Port() { Width = 10, Height = 10, NodeOffsetX = 1, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle ,IsVisible = true}; Port port4 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 1, ShapeType = ShapeType.Circle ,IsVisible = true}; node1ports.Add(port1); node1ports.Add(port2); node1ports.Add(port3); node1ports.Add(port4); n1.Ports = node1ports; Node n2 = DrawNode(30, 260, 100, 55, ShapeType.Rectangle, "Node2"); if (Device.RuntimePlatform == Device.UWP) { n2.ShapeType = ShapeType.Rectangle; } n2.Style.Brush = new SolidBrush(Color.FromRgb(239, 75, 93)); n2.Style.StrokeBrush = new SolidBrush(Color.FromRgb(201, 32, 61)); PortCollection node2ports = new PortCollection(); Port port5 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 0, ShapeType = ShapeType.Circle, IsVisible = true }; Port port6 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port7 = new Port() { Width = 10, Height = 10, NodeOffsetX = 1, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port8 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 1, ShapeType = ShapeType.Circle, IsVisible = true }; node2ports.Add(port5); node2ports.Add(port6); node2ports.Add(port7); node2ports.Add(port8); n2.Ports = node2ports; Node n3 = DrawNode(260, 260, 100, 55, ShapeType.Rectangle, "Node3"); if (Device.RuntimePlatform == Device.UWP) { n3.ShapeType = ShapeType.Rectangle; } n3.Style.Brush = new SolidBrush(Color.FromRgb(0, 194, 192)); n3.Style.StrokeBrush = new SolidBrush(Color.FromRgb(14, 142, 135)); PortCollection node3ports = new PortCollection(); Port port9 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 0, ShapeType = ShapeType.Circle, IsVisible = true }; Port port10 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port11 = new Port() { Width = 10, Height = 10, NodeOffsetX = 1, NodeOffsetY = 0.5, ShapeType = ShapeType.Circle, IsVisible = true }; Port port12 = new Port() { Width = 10, Height = 10, NodeOffsetX = 0.5, NodeOffsetY = 1, ShapeType = ShapeType.Circle, IsVisible = true }; node3ports.Add(port9); node3ports.Add(port10); node3ports.Add(port11); node3ports.Add(port12); n3.Ports = node3ports; Connector con1 = new Connector() { SourcePort = port4, TargetPort = port5 ,SegmentType=SegmentType.StraightSegment,TargetDecoratorType=DecoratorType.None}; Connector con2 = new Connector() { SourcePort = port4, TargetPort = port9 ,SegmentType = SegmentType.StraightSegment,TargetDecoratorType = DecoratorType.None}; Connector con3 = new Connector() { SourcePort = port7, TargetPort = port10 ,SegmentType = SegmentType.StraightSegment,TargetDecoratorType = DecoratorType.None}; diagram.AddNode(n1); diagram.AddNode(n2); diagram.AddNode(n3); diagram.AddConnector(con1); diagram.AddConnector(con2); diagram.AddConnector(con3); } //Creates the Node with Specified input private Node DrawNode(float x, float y, float w, float h, ShapeType shape, string annotation) { var node = new Node(); node.Style.StrokeWidth = 1; if (Device.RuntimePlatform == Device.Android) { node.OffsetX = x * DiagramUtility.factor; node.OffsetY = y * DiagramUtility.factor; node.Width = w * DiagramUtility.factor; node.Height = h * DiagramUtility.factor; } else { node.OffsetX = x; node.OffsetY = y; node.Width = w; node.Height = h; } node.ShapeType = shape; if (Device.RuntimePlatform == Device.Android) { node.Annotations.Add(new Annotation() { Content = annotation, TextBrush = new SolidBrush(Color.White), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, FontSize = 13 * DiagramUtility.factor }); } else { node.Annotations.Add(new Annotation() { Content = annotation, TextBrush = new SolidBrush(Color.FromRgb(255, 255, 255)), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, FontSize = 13 * DiagramUtility.factor }); } return node; } void None_Clicked(object sender, System.EventArgs e) { diagram.IsReadOnly = true; diagram.DrawingMode = DrawingMode.None; ColorChange(Color.DodgerBlue, Color.White, Color.White); } void Connector_Clicked(object sender, System.EventArgs e) { diagram.IsReadOnly = false; diagram.ClearSelection(); diagram.DrawingMode = DrawingMode.Connector; ColorChange(Color.White, Color.DodgerBlue, Color.White); } void Textnode_Clicked(object sender, System.EventArgs e) { diagram.IsReadOnly = false; diagram.ClearSelection(); diagram.DrawingMode = DrawingMode.TextNode; ColorChange(Color.White, Color.White, Color.DodgerBlue); } void ColorChange(Color none, Color connectortool, Color textnode) { if (none == Color.DodgerBlue) { None.ImageSource = "PointerW"; Connector.ImageSource = "ConnectorTool1"; Textnode.ImageSource = "TextNodeNormal"; } else if(connectortool==Color.DodgerBlue) { Connector.ImageSource = "ConnectorToolW"; None.ImageSource = "Pointer1"; Textnode.ImageSource = "TextNodeNormal"; } else if(textnode == Color.DodgerBlue) { Textnode.ImageSource = "TextNodeW"; Connector.ImageSource = "ConnectorTool1"; None.ImageSource = "Pointer1"; } None.BackgroundColor = none; Connector.BackgroundColor = connectortool; Textnode.BackgroundColor = textnode; } } } <file_sep>/iOS/SampleBrowser/Controllers/CodeViewController.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Foundation; using CoreGraphics; #endregion using System; using UIKit; namespace SampleBrowser { public class CodeViewController : UIViewController { #region fields private UILabel viewer; private bool menuVisible; private UIView fadeOutView; private UIScrollView scrollview; private UIBarButtonItem menuButton; #endregion #region ctor public CodeViewController() { SampleName = string.Empty; ControlName = string.Empty; } #endregion #region properties public NSArray SampleDictionaryArray { get; set; } public string SampleName { get; set; } public string ControlName { get; set; } public UIView MenuView { get; set; } public UITableView MenuTable { get; set; } #endregion #region methods public override void ViewDidLoad() { base.ViewDidLoad(); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); this.NavigationController.NavigationBar.BarTintColor = Utility.ThemeColor; this.View.BackgroundColor = UIColor.White; menuButton = new UIBarButtonItem { Image = UIImage.FromBundle("Images/Changefile"), Style = UIBarButtonItemStyle.Plain, Target = this }; menuButton.Clicked += OpenMenu; fadeOutView = new UIView(this.View.Bounds) { BackgroundColor = UIColor.FromRGBA(0.537f, 0.537f, 0.537f, 0.3f) }; UITapGestureRecognizer singleFingerTap = new UITapGestureRecognizer(); singleFingerTap.AddTarget(() => HandleSingleTap(singleFingerTap)); fadeOutView.AddGestureRecognizer(singleFingerTap); string controlListPathString = NSBundle.MainBundle.BundlePath + "/plist/SourceList.plist"; NSDictionary controlDict = new NSDictionary(); controlDict = NSDictionary.FromFile(controlListPathString); NSString controlDictKey = new NSString(ControlName); string sample = GetFileName(SampleName); NSDictionary controlDictArray = controlDict.ValueForKey(controlDictKey) as NSDictionary; if (controlDictArray != null) { NSString sampleDictKey = new NSString(sample); SampleDictionaryArray = controlDictArray.ValueForKey(sampleDictKey) as NSArray; if (SampleDictionaryArray != null) { sample = (string)SampleDictionaryArray.GetItem<NSString>(0); this.NavigationItem.SetRightBarButtonItem(menuButton, true); menuVisible = false; nfloat height = this.View.Bounds.Height - 64; nfloat left = this.View.Bounds.Width - 260; MenuView = new UIView(new CGRect(left, 64, 260, height)); MenuTable = new UITableView(new CGRect(0, 0, 260, height)); MenuTable.Layer.BorderWidth = 0.5f; MenuTable.Layer.BorderColor = UIColor.FromRGBA(0.537f, 0.537f, 0.537f, 0.5f).CGColor; MenuTable.BackgroundColor = UIColor.White; MenuTable.Source = new SampleDataSource(this); NSIndexPath indexPath = NSIndexPath.FromRowSection(0, 0); MenuTable.SelectRow(indexPath, false, UITableViewScrollPosition.Top); MenuView.AddSubview(MenuTable); } } viewer = new UILabel { Font = UIFont.SystemFontOfSize(12.0f), Lines = 0, LineBreakMode = UILineBreakMode.WordWrap }; viewer.SizeToFit(); scrollview = new UIScrollView(); scrollview.AddSubview(viewer); this.View.AddSubview(scrollview); this.LoadSample((string)sample); } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); if (viewer != null) { viewer.RemoveFromSuperview(); viewer.Dispose(); viewer = null; } if (scrollview != null) { scrollview.RemoveFromSuperview(); scrollview.Dispose(); scrollview = null; } Utility.DisposeEx(this.View); this.Dispose(); } public void LoadSample(string sample) { this.Title = sample + ".cs"; menuVisible = false; string sampleListPathString = NSBundle.MainBundle.BundlePath + "/Samples/" + this.ControlName + "/" + sample + ".cs"; NSData data = NSData.FromFile(sampleListPathString); string text = NSString.FromData(data, NSStringEncoding.UTF8); viewer.Text = text; viewer.Lines = 10000; viewer.SizeToFit(); viewer.Frame = new CGRect(5, 5, viewer.Frame.Width + 5, viewer.Frame.Height + 5); CGSize maxSize = new CGSize(viewer.Frame.Size.Width, float.MaxValue); CGSize labelSize = viewer.SizeThatFits(maxSize); scrollview.Frame = new CGRect(0, 0, this.View.Frame.Size.Width, this.View.Frame.Size.Height); scrollview.ContentSize = labelSize; scrollview.ContentOffset = new CGPoint(0, 0); } public void HideMenu() { MenuView.Frame = new CGRect(this.View.Bounds.Width - 260, 64, 260, this.View.Bounds.Height - 64 - 49); fadeOutView.RemoveFromSuperview(); UIView.AnimateNotify( 0.3, () => MenuView.Frame = new CGRect( this.View.Bounds.Width, 64, 260, this.View.Bounds.Height - 64 - 49), (bool finished) => { if (finished) { MenuView.RemoveFromSuperview(); } }); } private void ShowMenu() { MenuView.Frame = new CGRect(this.View.Bounds.Width, 64, 260, this.View.Bounds.Height - 64 - 49); UIView.Animate(0.3, () => MenuView.Frame = new CGRect(this.View.Bounds.Width - 260, 64, 260, this.View.Bounds.Height - 64 - 49)); } private void OpenMenu(object sender, EventArgs ea) { if (menuVisible) { menuVisible = false; HideMenu(); } else { menuVisible = true; this.View.AddSubview(fadeOutView); this.View.AddSubview(MenuView); ShowMenu(); } } private static string GetFileName(string selectedSample) { string name = selectedSample; if (name == "Stacked Area") { name = "StackingArea"; } else if (name == "AutoComplete") { name = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad ? "AutoComplete_Tablet" : "AutoComplete"; } else if (name == "BusyIndicator") { name = "BusyIndicator_Mobile"; } else if (name == "CalendarViews") { name = "CalendarViews_Mobile"; } else if (name == "CalendarLocalization") { name = "CalendarLocalization_Mobile"; } else if (name == "CalendarConfiguration") { name = "CalendarConfiguration_Mobile"; } else if (name == "Carousel") { name = "Carousel_Mobile"; } else if (name == "NumericTextBox") { name = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad ? "NumericTextBox_Tablet" : "NumericTextBox_Mobile"; } else if (name == "NumericUpDown") { name = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad ? "NumericUpDown_Tablet" : "NumericUpDown_Tablet"; } else if (name == "RangeSlider") { name = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad ? "RangeSlider_Tablet" : "RangeSlider_Mobile"; } else if (name == "Rating") { name = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad ? "Rating_Tablet" : "Rating_Mobile"; } else if (name == "SegmentedControl") { name = "SegementViewGettingStarted"; } else if (name == "Rotator") { name = "Rotator_Mobile"; } else if (name == "RangeSliderGettingStarted") { name = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad ? "RangeSliderGettingStarted_Tablet" : "RangeSliderGettingStarted_Mobile"; } else if (name == "MaskedEdit") { name = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad ? "MaskedEdit_Tablet" : "MaskedEdit_Mobile"; } else if (name == "CheckBox") { name = "CheckBox_Mobile"; } else if (name == "RadioButton") { name = "RadioButton_Mobile"; } else if (name == "PdfViewerDemo") { name = "GettingStartedPDFViewer"; } else if (name == "Stacked Column") { name = "StackingColumn"; } else if (name == "Stacked Bar") { name = "StackingBar"; } else if (name == "100% Stacked Area") { name = "StackingArea100"; } else if (name == "100% Stacked Column") { name = "StackingColumn100"; } else if (name == "100% Stacked Bar") { name = "StackingBar100"; } else if (name == "Data Point Selection") { name = "ChartSelection"; } else if (name == "Zooming and Panning") { name = "ChartZooming"; } else if (name == "Live Update") { name = "LiveUpate"; } else if (name == "Category Axis") { name = "Category"; } else if (name == "Numerical Axis") { name = "Numerical"; } else if (name == "Logarithmic Axis") { name = "Logarithmic"; } else if (name == "Multiple Axes") { name = "MultipleAxis"; } else if (name == "Strip Lines") { name = "StripLine"; } else if (name == "DateTime Axis") { name = "Date"; } if (name != "Vertical Chart") { name = name.Replace(" ", string.Empty); } return name; } private void HandleSingleTap(UITapGestureRecognizer gesture) { if (menuVisible) { menuVisible = false; HideMenu(); } } #endregion } internal class SampleDataSource : UITableViewSource { #region fields private CodeViewController controller; #endregion #region ctor public SampleDataSource(CodeViewController sampleControl) { this.controller = sampleControl; } #endregion #region methods public override nint RowsInSection(UITableView tableview, nint section) { return (nint)this.controller.SampleDictionaryArray.Count; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { nuint row = (nuint)indexPath.Row; string sample = this.controller.SampleDictionaryArray.GetItem<NSString>(row); this.controller.HideMenu(); this.controller.LoadSample(sample); } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell(AllControlsViewCell.Key) as AllControlsViewCell; if (cell == null) { cell = new AllControlsViewCell(); } nuint row = (nuint)indexPath.Row; string sample = this.controller.SampleDictionaryArray.GetItem<NSString>(row); string[] tokens = sample.Split('/'); if (tokens.Length > 1) { sample = tokens[tokens.Length - 1]; } cell.TextLabel.Text = sample + ".cs"; cell.DetailTextLabel.Font = UIFont.FromName("Helvetica", 10f); cell.DetailTextLabel.TextColor = UIColor.White; cell.TextLabel.HighlightedTextColor = Utility.ThemeColor; UIView selectionColor = new UIView(); selectionColor.Frame = cell.Frame; selectionColor.BackgroundColor = UIColor.FromRGB(249, 249, 249); cell.SelectedBackgroundView = selectionColor; return cell; } #endregion } }<file_sep>/Forms/Rating/readme.md The `SfRating` control provides the number of stars that represents a rating value, with this user can rate an application by clicking on the star. The following sample is available for rating control to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](Rating/Samples/Rating)| It demonstrates the accuracy level of filling the rating star, modifying the rating count and positioning the tooltips.| |[Customization](Rating/Samples/Rating_Customization)|It show cases the custom views as rating items instead of star by passing selected and unselected item views.|<file_sep>/iOS/SampleBrowser/Samples/DataGrid/Selection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using CoreGraphics; using System.Collections.Generic; using System.Globalization; namespace SampleBrowser { public class Selection:SampleView { #region Fields SfDataGrid SfGrid; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public Selection() { this.SfGrid = new SfDataGrid (); this.SfGrid.ItemsSource = new SelectionViewModel ().ProductDetails; this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.SelectedIndex = 1; this.SfGrid.SelectionMode = SelectionMode.Multiple; this.SfGrid.NavigationMode = NavigationMode.Cell; this.AddSubview(SfGrid); } void GridAutoGenerateColumns (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "ProductID") { e.Column.HeaderText = "Product ID"; } else if (e.Column.MappingName == "Product") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 10; } else if (e.Column.MappingName == "UserRating") { e.Column.HeaderText = "User Rating"; } else if (e.Column.MappingName == "ProductModel") { e.Column.HeaderText = "Product Model"; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Price") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); } else if (e.Column.MappingName == "ShippingDays") { e.Column.HeaderText = "Shipping Days"; } else if (e.Column.MappingName == "ProductType") { e.Column.HeaderText = "Product Type"; e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "Availability") { e.Column.TextMargin = new Thickness(30, 6, 5, 6); } } public override void LayoutSubviews () { if (Utility.IsIPad) { if ((UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.LandscapeLeft) || (UIDevice.CurrentDevice.Orientation == UIDeviceOrientation.LandscapeRight)) this.SfGrid.ColumnSizer = ColumnSizer.Star; else this.SfGrid.ColumnSizer = ColumnSizer.None; } this.SfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews (); } protected override void Dispose(bool disposing) { if (disposing) { if (SfGrid != null) { SfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; SfGrid.Dispose(); SfGrid = null; } } base.Dispose(disposing); } } } <file_sep>/Forms/DocIO/DocIO/Samples/DocIO_PieChart/DocIO_PieChart.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.Core; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.OfficeChart; using Xamarin.Forms; using System.Xml.Linq; using System.Globalization; namespace SampleBrowser.DocIO { public partial class DocIO_PieChart : SampleView { public DocIO_PieChart() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { //if (!SampleBrowser.DocIO.App.isUWP) // { // this.Content_1.FontSize = 18.5; // } // else // { this.Content_1.FontSize = 13.5; //} this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } private void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = typeof(DocIO_PieChart).GetTypeInfo().Assembly; //A new document is created. WordDocument document = new WordDocument(); //Add new section to the Word document IWSection section = document.AddSection(); //Set page margins of the section section.PageSetup.Margins.All = 72; //Add new paragraph to the section IWParagraph paragraph = section.AddParagraph(); //Apply heading style to the title paragraph paragraph.ApplyStyle(BuiltinStyle.Heading1); //Apply center alignment to the paragraph paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; //Append text to the paragraph paragraph.AppendText("Northwind Management Report").CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(46, 116, 181); //Add new paragraph paragraph = section.AddParagraph(); //Get chart data from xml file List<ProductDetail> Products = LoadXMLData(); //Create and Append chart to the paragraph WChart pieChart = document.LastParagraph.AppendChart(446, 270); //Set chart data pieChart.ChartType = OfficeChartType.Pie; pieChart.ChartTitle = "Best Selling Products"; pieChart.ChartTitleArea.FontName = "Calibri (Body)"; pieChart.ChartTitleArea.Size = 14; for (int i = 0; i < Products.Count; i++) { ProductDetail product = Products[i]; pieChart.ChartData.SetValue(i + 2, 1, product.ProductName); pieChart.ChartData.SetValue(i + 2, 2, product.Sum); } //Create a new chart series with the name “Sales” IOfficeChartSerie pieSeries = pieChart.Series.Add("Sales"); pieSeries.Values = pieChart.ChartData[2, 2, 11, 2]; //Setting data label pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true; pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside; //Setting background color pieChart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); pieChart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242); pieChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; pieChart.PrimaryCategoryAxis.CategoryLabels = pieChart.ChartData[2, 1, 11, 1]; MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>() .Save("PieChart.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("PieChart.docx", "application/msword", stream); } private List<ProductDetail> LoadXMLData() { XDocument productXml; List<ProductDetail> Products = new List<ProductDetail>(); ProductDetail productDetails; Assembly assembly = typeof(DocIO_PieChart).GetTypeInfo().Assembly; #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif Stream productXMLStream = assembly.GetManifestResourceStream(rootPath + "Products.xml"); productXml = XDocument.Load(productXMLStream); IEnumerable<XElement> pc = from p in productXml.Descendants("Product") select p; string serailNo = string.Empty; string productName = string.Empty; string sum = string.Empty; foreach (XElement dt in pc) { foreach (XElement el in dt.Descendants()) { var xElement = dt.Element(el.Name); if (xElement != null) { string value = xElement.Value; string elementName = el.Name.ToString(); switch (elementName) { case "SNO": serailNo = value; break; case "ProductName": productName = value; break; case "Sum": sum = value; break; } } } productDetails = new ProductDetail(int.Parse(serailNo), productName, decimal.Parse(sum, CultureInfo.InvariantCulture)); Products.Add(productDetails); } return Products; } } public class ProductDetail { #region fields private int m_serialNo; private string m_productName; private decimal m_sum; #endregion #region properties public int SNO { get { return m_serialNo; } set { m_serialNo = value; } } public string ProductName { get { return m_productName; } set { m_productName = value; } } public decimal Sum { get { return m_sum; } set { m_sum = value; } } #endregion #region Constructor public ProductDetail(int serialNumber, string productName, decimal sum) { SNO = serialNumber; ProductName = productName; Sum = Math.Round(sum, 3); } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/README.md The data grid control for Xamarin.iOS is a high-performance grid component that helps display and manipulate large amounts of data in a tabular format. Its rich feature set includes functionalities like data-binding, sorting, grouping, editing, filtering, swiping, dragging, resizing, loading more items, pull-to-refresh, and exporting to Excel and PDF file formats. The following samples are available for data grid to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [Getting Started](GridGettingStarted.cs) | This sample showcases a simple DataGrid with ObservableCollection as the data source. | | [Sorting](Sorting.cs) | This sample showcases the sorting capabilities of data in DataGrid that allows you to sort against one or more columns and also provides tri-state sorting functionality. | | [Filtering](Filtering.cs) | This sample showcases the filtering capabilities of data in DataGrid. | | [Frozen View](FrozenView.cs) | This sample showcases the freeze panes capability of DataGrid which provides support to freeze rows at the top and columns at the left of the view. | | [Grouping](Grouping.cs) | This sample showcases the grouping capabilities of data in DataGrid that allows you to group by one or more columns with option to expand/collapse the groups. | | [Selection](Selection.cs) | This sample showcases the selection capability of DataGrid which provides selection mode options like single, multiple, single-deselect and none. | | [Editing](Editing.cs) | This sample showcases the editing capabilities of DataGrid which provides support to edit GridTextColumn, GridNumericColumn, GridPickerColumn and GridDateTimeColumn. | | [Formatting](Formatting.cs) | This sample showcases the columns capability of SfDataGrid which provides support for text, image and loading custom views to the cells in the columns. | | [Drag And Drop](DragAndDrop.cs) | This sample showcases the column and row drag and drop capabilities of DataGrid which provide user flexibility when interacting with the grid rows and grid columns. | | [Unbound Column](UnboundColumn.cs) | This sample showcases the unbound column capability of DataGrid. Unbound columns are extra columns that do not belong to the data source. | | [Styles](Styles.cs) | This sample showcases the styling capabilities of DataGrid. Styling allows you to change the visual appearance of the DataGrid and its inner elements. | | [Auto Row Height](AutoRowHeight.cs) | This sample showcases the auto row height feature of DataGrid which renders grid rows based on its content to improve the readability and occurs on-demand basis. | | [Load More](LoadMore.cs) | This sample showcases the load more capability of DataGrid that allows you to load a subset of data to the bound data source using built-in UI. | | [Pull To Refresh](PullToRefresh.cs) | This sample showcases the pull-to-refresh capability of DataGrid which allows you to refresh the data source upon pull-to-refresh action. | | [Paging](Paging.cs) | This sample showcases the paging capabilities of DataGrid using our DataPager control which allows you to load the data from the data source in an efficient way. | | [Swiping](Swiping.cs) | This sample showcases the swiping capabilities of DataGrid which allow you to load swipe views and associate them with custom actions. | | [Rendering Dynamic Data](RenderingDynamicData.cs) | This sample illustrates the real time updates capabilibilies of the DataGrid by frequent updates that occur in random cells across the grid by keeping processor usage to a minimum. | | [Exporting](Exporting.cs) | This sample showcases the excel and pdf exporting capabilities of DataGrid. DataGrid also provides you various customization options for exporting. |<file_sep>/Android/SampleBrowser/Samples/Sunburst/SunburstChart.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using System; using Syncfusion.SfSunburstChart.Android; using System.Collections.Generic; using System.Collections.ObjectModel; using Android.Runtime; namespace SampleBrowser { [Preserve(AllMembers = true)] public class SunburstChart :SamplePage { SfSunburstChart chart; public override View GetSampleContent(Context context) { var Data = new ObservableCollection<SunburstModel>(); Data.Add(new SunburstModel() { Quarter = "Q1", Month = "Jan", Sales = 11 }); Data.Add(new SunburstModel() { Quarter = "Q1", Month = "Feb", Sales = 8 }); Data.Add(new SunburstModel() { Quarter = "Q1", Month = "Mar", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q2", Month = "Apr", Sales = 13 }); Data.Add(new SunburstModel() { Quarter = "Q2", Month = "May", Sales = 12 }); Data.Add(new SunburstModel() { Quarter = "Q2", Month = "Jun", Sales = 17 }); Data.Add(new SunburstModel() { Quarter = "Q3", Month = "Jul", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q3", Month = "Aug", Sales = 4 }); Data.Add(new SunburstModel() { Quarter = "Q3", Month = "Sep", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Oct", Sales = 7 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Nov", Sales = 18 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W1", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W2", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W3", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W4", Sales = 5 }); chart = new SfSunburstChart(context); chart.ItemsSource = Data; chart.Radius = 0.95; chart.ValueMemberPath = "Sales"; var levels = new SunburstLevelCollection() { new SunburstHierarchicalLevel() { GroupMemberPath = "Quarter"}, new SunburstHierarchicalLevel() { GroupMemberPath = "Month"}, new SunburstHierarchicalLevel() { GroupMemberPath = "Week"} }; chart.Levels = levels; chart.EnableAnimation = true; chart.Title.IsVisible = true; chart.Title.Margin = new Thickness(10, 5, 5, 5); chart.Title.Text = "Sales Performance"; chart.Title.TextSize = 20; chart.Legend.IsVisible = true; chart.DataLabel.ShowLabel = true; chart.TooltipSettings = new CustomTooltip(context); chart.TooltipSettings.ShowTooltip = true; return chart; } } public class CustomTooltip : SunburstTooltipSettings { Context context; public CustomTooltip(Context con) { context = con; } public override View GetView(SunburstSegment segment) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; TextView textView = new TextView(context); textView.SetTextColor(Color.White); textView.Text = "Category : " + segment.Category; TextView textView1 = new TextView(context); textView1.SetTextColor(Color.White); textView1.Text = "Value : " + segment.Value; linearLayout.AddView(textView); linearLayout.AddView(textView1); return linearLayout; } } [Preserve(AllMembers = true)] public class SunburstModel { public string Category { get; set; } public string Country { get; set; } public string JobDescription { get; set; } public string JobGroup { get; set; } public string JobRole { get; set; } public double EmployeesCount { get; set; } public string Quarter { get; set; } public string Month { get; set; } public string Week { get; set; } public double Sales { get; set; } public string Continent { get; set; } public string State { get; set; } public double Population { get; set; } } }<file_sep>/iOS/SampleBrowser/Samples/PopupLayout/README.md The pop-up control layout lets you display an alert message with options to customize and load any desired view inside the control. The following samples are available for pop-up to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | | [OnBoard Helps](Onboard%20Helps/PopupGettingStarted.cs) | This sample show case the usage of popup layout as on-board help views with different customized animations. | | [Popup Customizations](Popup%20Customizations/PopupCustomizations.cs)| This sample showcases the various layouts of the popup layout with built-in animatation that comes in handy in a sleek ticket booking app. | | [Popup Menu](Details%20View/DetailsView.cs)| This sample showcases the usage of popup layout in the contact list for displaying available options relatively below the tapped user data. |<file_sep>/iOS/SampleBrowser/Samples/Schedule/AgendaView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class AgendaView : SampleView { private static SFSchedule schedule; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public AgendaView() { schedule = new SFSchedule(); schedule.ScheduleView = SFScheduleView.SFScheduleViewMonth; MonthViewSettings monthSettings = new MonthViewSettings(); monthSettings.ShowAppointmentsInline = false; monthSettings.ShowAgendaView = true; schedule.MonthViewSettings = monthSettings; schedule.ItemsSource = CreateAppointments(); this.AddSubview(schedule); } protected override void Dispose(bool disposing) { if (disposing) { if (schedule != null) { schedule.Dispose(); schedule = null; } } base.Dispose(disposing); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } private ObservableCollection<ScheduleAppointment> CreateAppointments() { NSDate today = new NSDate(); SetColors(); SetSubjects(); ObservableCollection<ScheduleAppointment> appCollection = new ObservableCollection<ScheduleAppointment>(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; var startDay = components.Day; var nextMonth = components.Month; var prevMonth = components.Month; if (nextMonth == 12) { nextMonth = 1; } else { nextMonth = nextMonth + 1; } if (prevMonth == 1) { prevMonth = 12; } else { prevMonth = prevMonth - 1; } Random randomNumber = new Random(); var count = 0; for (int i = 0; i < 30; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); if (i < 10 && i >= 0) { appointment.StartTime = startDate; appointment.EndTime = endDate; } else if (i < 20 && i >= 10) { components.Month = nextMonth; endDateComponents.Month = nextMonth; appointment.StartTime = startDate; appointment.EndTime = endDate; } else if (i < 30 && i >= 20) { components.Month = prevMonth; endDateComponents.Month = prevMonth; appointment.StartTime = startDate; appointment.EndTime = endDate; } components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)subjectCollection[count]; appointment.AppointmentBackground = colorCollection[count]; if (i == 10 || i == 20) { components.Day = startDay; endDateComponents.Day = startDay; } count++; if (count == 10) { count = 0; } appCollection.Add(appointment); } return appCollection; } private List<String> subjectCollection; private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); } // adding colors collection private List<UIColor> colorCollection; private void SetColors() { colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0xF0, 0x96, 0x09)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Trackball.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using CoreAnimation; #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Trackball : SampleView { UILabel label; SFChart chart; public Trackball() { SFChart chart = new SFChart(); chart.ColorModel.Palette = SFChartColorPalette.Natural; SFCategoryAxis primaryAxis = new SFCategoryAxis(); primaryAxis.AxisLineOffset = 2; primaryAxis.PlotOffset = 5; primaryAxis.ShowMajorGridLines = false; chart.PrimaryAxis = primaryAxis; SFNumericalAxis secondaryAxis = new SFNumericalAxis(); secondaryAxis.MajorTickStyle.LineSize = 0; secondaryAxis.AxisLineStyle.LineWidth = 0; secondaryAxis.Minimum = new NSNumber(25); secondaryAxis.Maximum = new NSNumber(50); chart.SecondaryAxis = secondaryAxis; ChartViewModel dataModel = new ChartViewModel(); SFLineSeries series1 = new SFLineSeries(); series1.ItemsSource = dataModel.LineSeries1; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; series1.Label = "Germany"; series1.LineWidth = 3; chart.Series.Add(series1); SFLineSeries series2 = new SFLineSeries(); series2.ItemsSource = dataModel.LineSeries2; series2.XBindingPath = "XValue"; series2.YBindingPath = "YValue"; series2.Label = "England"; series2.LineWidth = 3; chart.Series.Add(series2); SFLineSeries series3 = new SFLineSeries(); series3.ItemsSource = dataModel.LineSeries3; series3.XBindingPath = "XValue"; series3.YBindingPath = "YValue"; series3.Label = "France"; series3.LineWidth = 3; chart.Series.Add(series3); label = new UILabel(); label.Text = "Press and hold to enable trackball"; label.Font = UIFont.FromName("Helvetica", 12f); label.TextAlignment = UITextAlignment.Center; label.LineBreakMode = UILineBreakMode.WordWrap; label.Lines = 2; label.BackgroundColor = UIColor.FromRGB(249, 249, 249); label.TextColor = UIColor.FromRGB(79, 86, 91); CALayer topLine = new CALayer(); topLine.Frame = new CGRect(0, 0, UIScreen.MainScreen.ApplicationFrame.Width, 0.5); topLine.BackgroundColor = UIColor.FromRGB(178, 178, 178).CGColor; label.Layer.AddSublayer(topLine); chart.Legend.Visible = true; chart.Legend.IconWidth = 14; chart.Legend.IconHeight = 14; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = SFChartLegendPosition.Bottom; chart.AddChartBehavior(new SFChartTrackballBehavior()); this.AddSubview(chart); this.AddSubview(label); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view == chart) chart.Frame = new CGRect(0, 0, Frame.Width, Frame.Height - 48); else if (view == label) label.Frame = new CGRect(0, Frame.Height - 10, Frame.Width, 20); else view.Frame = Bounds; } base.LayoutSubviews(); } } public class CustomTrackballBehavior : SFChartTrackballBehavior { public override UIView ViewForTrackballLabel(SFChartPointInfo pointInfo) { pointInfo.MarkerStyle.BorderColor = pointInfo.Series.Color; UIView customView = new UIView(); customView.Frame = new CGRect(0, 0, 48, 30); UILabel xLabel = new UILabel(); xLabel.Frame = new CGRect(7, 0, 50, 15); xLabel.TextColor = UIColor.White; xLabel.Font = UIFont.FromName("HelveticaNeue-BoldItalic", 13f); xLabel.Text = (pointInfo.Data as ChartDataModel).YValue.ToString() + "%"; UILabel yLabel = new UILabel(); yLabel.Frame = new CGRect(7, 15, 50, 15); yLabel.TextColor = UIColor.White; yLabel.Font = UIFont.FromName("Helvetica", 8f); yLabel.Text = "Efficiency"; customView.AddSubview(xLabel); customView.AddSubview(yLabel); return customView; } } } <file_sep>/Forms/ListView/ListView/Samples/DataTemplateSelector/View/IncomingTextTemplate.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SampleBrowser; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public partial class IncomingTextTemplate : ViewCell { #region IncomingMessageTemplate public IncomingTextTemplate() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP) this.gridLayout.ColumnSpacing = -23 ; else this.frame.BackgroundColor = Color.FromRgb(192, 238, 252); } #endregion } }<file_sep>/Android/SampleBrowser/Samples/TreeMap/DataLabel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Com.Syncfusion.Treemap; using Org.Json; using Range = Com.Syncfusion.Treemap.Range; namespace SampleBrowser { class DataLabel : SamplePage { public DataLabel() { } List<String> adapter; SfTreeMap tree; public override View GetSampleContent(Context context) { tree = new SfTreeMap(context); tree.WeightValuePath = "Population"; tree.ColorValuePath = "Population"; tree.HighlightOnSelection = false; float density = context.Resources.DisplayMetrics.Density; //LeafItemSetting tree.LeafItemSettings = new LeafItemSetting() { ShowLabels = true, Gap = 1, LabelPath = "Region", StrokeWidth = 2 }; tree.LeafItemSettings.LabelStyle = new Style() { TextSize = 18 }; TreeMapTooltipSetting tooltip = new TreeMapTooltipSetting(context); tree.TooltipSettings = tooltip; List<Range> ranges = new List<Range>(); ranges.Add(new Range() { LegendLabel = "200M - 1.3B", From = 200000000, To = 10000000000, Color = Color.ParseColor("#4B134F") }); ranges.Add(new Range() { LegendLabel = "100M - 200M", From = 100000000, To = 200000000, Color = Color.ParseColor("#8C304D") }); ranges.Add(new Range() { LegendLabel = "20M - 100M", From = 20000000, To = 100000000, Color = Color.ParseColor("#C84B4B") }); tree.LeafItemColorMapping = new RangeColorMapping() { Ranges = ranges }; tree.ShowTooltip = true; //LegendSetting Size legendSize = new Size(300, 100); Size iconSize = new Size(14, 14); tree.LegendSettings = new LegendSetting() { LabelStyle = new Style() { TextSize = 14, TextColor = Android.Graphics.Color.Black }, IconSize = iconSize, ShowLegend = true, LegendSize = legendSize }; tree.DataSource = GetDataSource(); return tree; } public override View GetPropertyWindowLayout(Android.Content.Context context) { TextView label = new TextView(context); label.Text = "DataLabelOverflowMode"; label.Typeface = Typeface.DefaultBold; label.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); label.TextSize = 20; Spinner labelMode = new Spinner(context, SpinnerMode.Dialog); adapter = new List<String>() { "Trim", "Wrap", "Hide" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); labelMode.Adapter = dataAdapter; labelMode.ItemSelected += LabelMode_ItemSelected; LinearLayout optionsPage = new LinearLayout(context); optionsPage.Orientation = Orientation.Vertical; optionsPage.AddView(label); optionsPage.AddView(labelMode); optionsPage.SetPadding(10, 10, 10, 10); optionsPage.SetBackgroundColor(Android.Graphics.Color.White); return optionsPage; } private void LabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter[e.Position]; if (selectedItem.Equals("Trim")) { tree.LeafItemSettings.OverflowMode = LabelOverflowMode.Trim; } else if (selectedItem.Equals("Wrap")) { tree.LeafItemSettings.OverflowMode = LabelOverflowMode.Wrap; } else if (selectedItem.Equals("Hide")) { tree.LeafItemSettings.OverflowMode = LabelOverflowMode.Hide; } } JSONArray GetDataSource() { JSONArray array = new JSONArray(); array.Put(getJsonObject("China", 1388232693)); array.Put(getJsonObject("India", 1342512706)); array.Put(getJsonObject("United States of America", 326474013)); array.Put(getJsonObject("Indonesia", 263510146)); array.Put(getJsonObject("Brazil", 211243220)); array.Put(getJsonObject("Pakistan", 196744376)); array.Put(getJsonObject("Nigeria", 191835936)); array.Put(getJsonObject("Bangladesh", 164827718)); array.Put(getJsonObject("Russian Federation", 143375006)); array.Put(getJsonObject("Mexico", 130222815)); array.Put(getJsonObject("Japan", 126045211)); array.Put(getJsonObject("Ethiopia", 104344901)); array.Put(getJsonObject("Philippines", 103796832)); array.Put(getJsonObject("Viet Nam", 95414640)); array.Put(getJsonObject("Egypt", 95215102)); array.Put(getJsonObject("D.R. Congo", 82242685)); array.Put(getJsonObject("Iran", 80945718)); array.Put(getJsonObject("Germany", 80636124)); array.Put(getJsonObject("Turkey", 80417526)); array.Put(getJsonObject("Thailand", 68297547)); array.Put(getJsonObject("United Kingdom", 65511098)); array.Put(getJsonObject("France", 64938716)); array.Put(getJsonObject("Italy", 59797978)); array.Put(getJsonObject("Tanzania", 56877529)); array.Put(getJsonObject("South Africa", 55436360)); array.Put(getJsonObject("Myanmar", 54836483)); array.Put(getJsonObject("Republic of Korea", 50704971)); array.Put(getJsonObject("Colombia", 49067981)); array.Put(getJsonObject("Kenya", 48466928)); array.Put(getJsonObject("Spain", 46070146)); array.Put(getJsonObject("Ukraine", 44405055)); array.Put(getJsonObject("Argentina", 44272125)); array.Put(getJsonObject("Sudan", 42166323)); array.Put(getJsonObject("Uganda", 41652938)); array.Put(getJsonObject("Algeria", 41063753)); array.Put(getJsonObject("Iraq", 38654287)); array.Put(getJsonObject("Poland", 38563573)); array.Put(getJsonObject("Canada", 36626083)); array.Put(getJsonObject("Morocco", 35241418)); array.Put(getJsonObject("Afghanistan", 34169169)); array.Put(getJsonObject("Saudi Arabia", 32742664)); array.Put(getJsonObject("Peru", 32166473)); array.Put(getJsonObject("Venezuela", 31925705)); array.Put(getJsonObject("Malaysia", 31164177)); array.Put(getJsonObject("Uzbekistan", 30690914)); array.Put(getJsonObject("Mozambique", 29537914)); array.Put(getJsonObject("Nepal", 29187037)); array.Put(getJsonObject("Ghana", 28656723)); array.Put(getJsonObject("Yemen", 28119546)); array.Put(getJsonObject("Angola", 26655513)); array.Put(getJsonObject("Madagascar", 25612972)); array.Put(getJsonObject("Dem Peoples Republic of Korea", 25405296)); array.Put(getJsonObject("Australia", 24641662)); array.Put(getJsonObject("Cameroon", 24513689)); array.Put(getJsonObject("Côte dIvoire", 23815886)); array.Put(getJsonObject("Taiwan", 23405309)); array.Put(getJsonObject("Niger", 21563607)); return array; } JSONObject getJsonObject(String region, double population) { JSONObject obj = new JSONObject(); obj.Put("Region", region); obj.Put("Population", population); return obj; } } public class TreeMapTooltipSetting : TooltipSetting { Context context; public TreeMapTooltipSetting(Context con) { context = con; } public override View GetView(object data, Context context) { LinearLayout layout = new LinearLayout(context); LinearLayout.LayoutParams linearlayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layout.Orientation = Orientation.Vertical; layout.LayoutParameters = linearlayoutParams; layout.SetGravity(GravityFlags.CenterHorizontal); TextView topLabel = new TextView(context); topLabel.Text = ((JSONObject)data).GetString("Region"); topLabel.TextSize = 12; topLabel.SetTextColor(Color.ParseColor("#FFFFFF")); topLabel.Gravity = GravityFlags.CenterHorizontal; TextView SplitLine = new TextView(context); SplitLine.Text = "-------"; SplitLine.SetTextColor(Color.Gray); SplitLine.Gravity = GravityFlags.CenterHorizontal; TextView bottoLabel = new TextView(context); var population = ((JSONObject)data).GetDouble("Population") / 1000000; bottoLabel.Text = ((int)population).ToString() + "M"; bottoLabel.TextSize = 12; bottoLabel.SetTextColor(Color.ParseColor("#FFFFFF")); bottoLabel.Gravity = GravityFlags.CenterHorizontal; layout.AddView(topLabel); layout.AddView(SplitLine); layout.AddView(bottoLabel); return layout; } } }<file_sep>/Forms/PdfViewer/PdfViewer/Samples/Helper/CustomViewCell.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfPdfViewer { [Preserve(AllMembers = true)] public class CustomViewCell : ViewCell { public static readonly BindableProperty SelectedBackgroundColorProperty = BindableProperty.Create("SelectedBackgroundColor", typeof(Color), typeof(CustomViewCell), Color.Default); public Color SelectedBackgroundColor { get { return (Color)GetValue(SelectedBackgroundColorProperty); } set { SetValue(SelectedBackgroundColorProperty, value); } } } } <file_sep>/Android/SampleBrowser/Samples/PullToRefresh/PullToRefresh.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Text.Style; using System; using Android.Graphics; using Org.Json; using Android.Widget; using Android.Views; using Android.Content; using Syncfusion.SfPullToRefresh; using System.Collections.Generic; using Java.Text; using Java.Util; using Android.Text; using Android.OS; using System.Threading.Tasks; namespace SampleBrowser { public class PullToRefreshDemo: SamplePage { SfPullToRefresh pull; LinearLayout linearLayout,linearLayoutChild, selectedLayout; List<WeatherData> dataSource; Handler handler; TextView textView,textView1,degreetext; ImageView imageView3; WeatherData selectedData; View view ; Java.Lang.Runnable run; public PullToRefreshDemo() { } public override View GetSampleContent (Context context) { handler = new Handler (); LayoutInflater layoutInflater = LayoutInflater.From(context); view = layoutInflater.Inflate(Resource.Layout.pulltorefresh, null); Calendar cal = Calendar.GetInstance(Java.Util.TimeZone.Default); SimpleDateFormat dateformat = new SimpleDateFormat("EEEE, MMMM dd "); String strDate = dateformat.Format(cal.Time); linearLayout = (LinearLayout) view; linearLayout.SetBackgroundColor(Color.ParseColor("#039be5")); linearLayoutChild = (LinearLayout) view.FindViewById(Resource.Id.pullscroller); dataSource= GetData(); TextView textView3= (TextView) view.FindViewById(Resource.Id.text); String s= ""+dataSource[0].Temperature+ (char) 0x00B0 + "/12"; SpannableString ss1= new SpannableString(s); ss1.SetSpan(new RelativeSizeSpan(2f), 0, 4, SpanTypes.ExclusiveExclusive); textView3.SetText(ss1,TextView.BufferType.Normal); ImageView imageView= (ImageView) view.FindViewById(Resource.Id.imageview); imageView.SetImageResource(dataSource[0].Type); TextView textView6= (TextView) view.FindViewById(Resource.Id.text1); textView6.Text=strDate; for (int i = 0; i <dataSource.Count; i++) { LinearLayout lay = (LinearLayout)layoutInflater.Inflate(Resource.Layout.pulltorefreshtemplate, null); textView= (TextView) lay.FindViewById(Resource.Id.text3); textView.Text=dataSource[i].Day; textView1= (TextView) lay.FindViewById(Resource.Id.text4); textView1.Text="" + (int) dataSource[i].Temperature+(char) 0x00B0 ; imageView= (ImageView) lay.FindViewById(Resource.Id.imageview1); imageView.SetImageResource(dataSource[i].Type); if(i==0) { textView.SetTextColor(Color.ParseColor("#fbb03b")); textView1.SetTextColor(Color.ParseColor("#fbb03b")); imageView.SetImageResource(dataSource[i].SelectedType); selectedData = dataSource[i]; selectedLayout = lay; } setOnClick(lay, i); linearLayoutChild.AddView(lay); } pull = new SfPullToRefresh (context); pull.RefreshContentThreshold = 0; pull.PullableContent=linearLayout; pull.Refreshing += (sender, e) => { if(selectedLayout!=null){ run = new Java.Lang.Runnable(() => { Java.Util.Random rnd = new Java.Util.Random(); int i = rnd.NextInt(6 - 0 + 1) + 0; imageView3 = (ImageView) linearLayout.FindViewById(Resource.Id.imageview); imageView3.SetImageResource(dataSource[i].Type); degreetext = (TextView) linearLayout.FindViewById(Resource.Id.text); String s1= "" + dataSource[i].Temperature + (char) 0x00B0 + "/12"; SpannableString ss3 = new SpannableString(s1); ss3.SetSpan(new RelativeSizeSpan(2f),0,4,SpanTypes.ExclusiveExclusive); degreetext.SetText(ss3,TextView.BufferType.Normal); e.Refreshed = true; }); handler.PostDelayed(run, 3000); } }; return pull; } private void setOnClick( LinearLayout lay, int i){ lay.Click += (object sender, EventArgs e) => { if (selectedLayout != null) { TextView oldTextView1 = (TextView)selectedLayout.FindViewById (Resource.Id.text3); TextView oldTextView2 = (TextView)selectedLayout.FindViewById (Resource.Id.text4); ImageView newImageView = (ImageView)selectedLayout.FindViewById (Resource.Id.imageview1); oldTextView1.SetTextColor (Color.ParseColor ("#ffffff")); oldTextView2.SetTextColor (Color.ParseColor ("#ffffff")); newImageView.SetImageResource (selectedData.Type); } TextView newTextView1 = (TextView)lay.FindViewById (Resource.Id.text3); TextView newTextView12 = (TextView)lay.FindViewById (Resource.Id.text4); ImageView newimageView = (ImageView)lay.FindViewById (Resource.Id.imageview1); WeatherData data = dataSource[i]; newTextView1.SetTextColor (Color.ParseColor ("#fbb03b")); newTextView12.SetTextColor (Color.ParseColor ("#fbb03b")); newimageView.SetImageResource (data.SelectedType); ImageView imageView = (ImageView)linearLayout.FindViewById (Resource.Id.imageview); imageView.SetImageResource (data.Type); TextView degreeText = (TextView)linearLayout.FindViewById (Resource.Id.text); String s2 = "" + data.Temperature + (char) 0x00B0 + "/12"; SpannableString ss2= new SpannableString(s2); ss2.SetSpan(new RelativeSizeSpan(2f),0,4,SpanTypes.ExclusiveExclusive); degreeText.SetText(ss2,TextView.BufferType.Normal); TextView dayText = (TextView)linearLayout.FindViewById (Resource.Id.text1); dayText.Text=dataSource[i].Date; selectedData = data; selectedLayout = lay; }; } List<WeatherData> GetData() { List<WeatherData> list = new List<WeatherData>(); SimpleDateFormat dateformat = new SimpleDateFormat("EEEE, MMMM dd "); SimpleDateFormat dateformat1=new SimpleDateFormat("EEEE"); Calendar cal = Calendar.GetInstance(Java.Util.TimeZone.Default); String strDate = dateformat.Format(cal.Time); String strDay = dateformat1.Format(cal.Time); Calendar cal1 = Calendar.GetInstance(Java.Util.TimeZone.Default); cal1.Add(CalendarField.Date,+1); String strDate1 = dateformat.Format(cal1.Time); String strDay1 = dateformat1.Format(cal1.Time); Calendar cal2 = Calendar.GetInstance(Java.Util.TimeZone.Default); cal2.Add(CalendarField.Date,+2); String strDate2 = dateformat.Format(cal2.Time); String strDay2 = dateformat1.Format(cal2.Time); Calendar cal3 = Calendar.GetInstance(Java.Util.TimeZone.Default); cal3.Add(CalendarField.Date,+3); String strDate3 = dateformat.Format(cal3.Time); String strDay3 = dateformat1.Format(cal3.Time); Calendar cal4 = Calendar.GetInstance(Java.Util.TimeZone.Default); cal4.Add(CalendarField.Date,+4); String strDate4 = dateformat.Format(cal4.Time); String strDay4 = dateformat1.Format(cal4.Time); Calendar cal5 = Calendar.GetInstance(Java.Util.TimeZone.Default); cal5.Add(CalendarField.Date,+5); String strDate5 = dateformat.Format(cal5.Time); String strDay5 = dateformat1.Format(cal5.Time); Calendar cal6 = Calendar.GetInstance(Java.Util.TimeZone.Default); cal6.Add(CalendarField.Date,+6); String strDate6 = dateformat.Format(cal6.Time); String strDay6 = dateformat1.Format(cal6.Time); list.Add(new WeatherData(strDay,strDate,21,Resource.Drawable.humid,Resource.Drawable.humidselected )); list.Add(new WeatherData(strDay1,strDate1,24, Resource.Drawable.cloudy,Resource.Drawable.cloudyselected )); list.Add(new WeatherData(strDay2,strDate2,26,Resource.Drawable.humid,Resource.Drawable.humidselected )); list.Add(new WeatherData(strDay3,strDate3,23,Resource.Drawable.rainy,Resource.Drawable.rainyselected )); list.Add(new WeatherData(strDay4,strDate4,32,Resource.Drawable.warm,Resource.Drawable.warmselected )); list.Add(new WeatherData(strDay5,strDate5,12,Resource.Drawable.windy,Resource.Drawable.windyselected )); list.Add(new WeatherData(strDay6,strDate6,30, Resource.Drawable.cloudy,Resource.Drawable.cloudyselected)); return list; } public override View GetPropertyWindowLayout(Context context) { FrameLayout propertyLayout = new FrameLayout(context); LinearLayout layout = new LinearLayout(context); layout.Orientation = Orientation.Vertical; layout.SetBackgroundColor(Color.White); layout.SetPadding(15, 15, 15, 20); TextView transitiontype = new TextView(context); transitiontype.Text="Tranisition Type"; transitiontype.TextSize = 20; transitiontype.SetPadding(0, 0, 0, 10); transitiontype.SetTextColor(Color.Black); Spinner sType_spinner = new Spinner(context,SpinnerMode.Dialog); sType_spinner.SetMinimumHeight(60); sType_spinner.SetBackgroundColor(Color.Gray); sType_spinner.DropDownWidth = 600; sType_spinner.SetPadding(10, 10, 0, 10); sType_spinner.SetGravity(GravityFlags.CenterHorizontal); layout.AddView(transitiontype); layout.AddView(sType_spinner); List<String> list = new List<String>(); list.Add("SlideOnTop"); list.Add("Push"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, list); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); sType_spinner.Adapter = dataAdapter; sType_spinner.ItemSelected += sType_spinner_ItemSelected; if (pull.TransitionType == TransitionType.SlideOnTop) sType_spinner.SetSelection(0); else sType_spinner.SetSelection(1); propertyLayout.AddView(layout); return propertyLayout; } void sType_spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; String selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); if (pull != null) { if (selectedItem.Equals("SlideOnTop")) { pull.TransitionType = TransitionType.SlideOnTop; pull.RefreshContentThreshold = 0; } else if (selectedItem.Equals("Push")) { pull.TransitionType = TransitionType.Push; pull.RefreshContentThreshold = 25; } } } public override void Destroy() { handler.RemoveCallbacks(run); pull.Dispose(); pull = null; } } public class WeatherData { public WeatherData(String day,String date,int temperature,int type,int selectedType) { Day = day; Date = date; Temperature = temperature; SelectedType=selectedType; Type=type; id=type; } public String Day; public int SelectedType; public String Date; public int Temperature; public int Type; public int id; } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Scatter.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; #endif namespace SampleBrowser { public class Scatter : SampleView { public Scatter() { SFChart chart = new SFChart(); chart.ColorModel.Palette = SFChartColorPalette.Natural; chart.Title.Text = new NSString("World Countries Details"); SFNumericalAxis primary = new SFNumericalAxis(); primary.ShowMajorGridLines = false; chart.PrimaryAxis = primary; chart.PrimaryAxis.Title.Text = new NSString("Literacy Rate"); SFNumericalAxis secondary = new SFNumericalAxis(); secondary.Title.Text = new NSString("GDP Growth Rate"); secondary.ShowMajorGridLines = false; secondary.Minimum = new NSNumber(-500); secondary.Maximum = new NSNumber(700); chart.SecondaryAxis = secondary; ChartViewModel dataModel = new ChartViewModel(); SFScatterSeries series = new SFScatterSeries(); series.ItemsSource = dataModel.ScatterData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.ScatterHeight = 5; series.ScatterWidth = 5; series.Alpha = 0.7f; series.EnableAnimation = true; chart.Series.Add(series); chart.AddChartBehavior(new SFChartZoomPanBehavior()); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } }<file_sep>/Forms/Diagram/Diagram/Samples/MindMap/MindMap.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using System.Linq; using Syncfusion.SfDiagram.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfDiagram { [Preserve(AllMembers = true)] public partial class MindMap : SampleView { Node RootNode; UserHandleCollection DefaultHandles; internal Node SelectedNode; Frame Notifier; Entry textinput; UserHandlePosition CurrentHandle; Random rnd = new Random(); List<Color> FColor; List<Color> SColor; int index; private DataTemplate m_collapseTemplate; private DataTemplate m_expandTemplate; List<NodeStyle> nodeStyleCollection; LineStyle lineStyle; object objShape1 = ShapeType.RoundedRectangle; object objShape2 = ShapeType.RoundedRectangle; object objShape3 = ShapeType.RoundedRectangle; object objShape4 = ShapeType.RoundedRectangle; object objShape5 = ShapeType.RoundedRectangle; SegmentType segment = SegmentType.CurveSegment; int themeIndex = 0; String simpleCurveTree = "default"; SfGraphics gra; List<Point> point; DecoratorType Dectype = DecoratorType.None; Color connColor = Color.Gray; ApplyColorFrom connLineColorFrom = ApplyColorFrom.TargetBorder; ApplyColorFrom connDecColorFrom = ApplyColorFrom.TargetBorder; private bool m_isDiagramLoaded = true; public MindMap() { if (nodeStyleCollection == null) nodeStyleCollection = new List<NodeStyle>(); if (gra == null) { gra = new SfGraphics(); } if (point == null) { point = new List<Point>(); } if (SColor == null) { SColor = new List<Color>(); } if (FColor == null) { FColor = new List<Color>(); } InitializeComponent(); diagram.ContextMenuSettings.Visibility = false; if (Device.RuntimePlatform == Device.Android) Xamarin.Forms.DependencyService.Get<IText>().GenerateFactor(); style.Items.Add("Default"); style.Items.Add("Rainbow"); style.Items.Add("Rosetta"); style.Items.Add("Autumn"); style.Items.Add("Woody"); style.Items.Add("Ashes"); style.Items.Add("Navy"); style.SelectedIndex = 0; style.SelectedIndexChanged += style_SelectedIndexChanged; if (Device.RuntimePlatform == Device.UWP) { var label = new Label(); label.Text = "Sample Not Supported !"; label.HorizontalTextAlignment = TextAlignment.Center; label.VerticalTextAlignment = TextAlignment.Center; label.FontSize = 15; parent.Children.Add(label); diagram.IsReadOnly = true; } else { int width = 150; int height = 75; if (Device.RuntimePlatform == Device.Android) { width = (int)(125 * DiagramUtility.factor); height = (int)(60 * DiagramUtility.factor); } var node = AddNode(300, 400, width, height, "Goals"); RootNode = node; diagram.AddNode(node); SColor.Add(Color.FromHex("#d1afdf")); SColor.Add(Color.FromHex("#90C8C2")); SColor.Add(Color.FromHex("#8BC1B7")); SColor.Add(Color.FromHex("#E2C180")); SColor.Add(Color.FromHex("#BBBFD6")); SColor.Add(Color.FromHex("#ACCBAA")); FColor.Add(Color.FromHex("#e9d4f1")); FColor.Add(Color.FromHex("#d4efed")); FColor.Add(Color.FromHex("#c4f2e8")); FColor.Add(Color.FromHex("#f7e0b3")); FColor.Add(Color.FromHex("#DEE2FF")); FColor.Add(Color.FromHex("#E5FEE4")); var ch1node = AddNode(100, 100, width, height, "Financial"); index = rnd.Next(5); diagram.AddNode(ch1node); var ch1childnode = AddNode(100, 100, width, height, "Investment"); diagram.AddNode(ch1childnode); var ch2node = AddNode(100, 600, width, height, "Social"); index = rnd.Next(5); diagram.AddNode(ch2node); var ch2childnode1 = AddNode(100, 100, width, height, "Friends"); diagram.AddNode(ch2childnode1); var ch2childnode2 = AddNode(100, 100, width, height, "Family"); diagram.AddNode(ch2childnode2); var ch3node = AddNode(500, 100, width, height, "Personal"); index = rnd.Next(5); diagram.AddNode(ch3node); var ch3childnode1 = AddNode(500, 100, width, height, "Sports"); diagram.AddNode(ch3childnode1); var ch3childnode2 = AddNode(500, 100, width, height, "Food"); diagram.AddNode(ch3childnode2); var ch4node = AddNode(500, 600, width, height, "Work"); index = rnd.Next(5); diagram.AddNode(ch4node); var ch4childnode1 = AddNode(500, 100, width, height, "Project"); diagram.AddNode(ch4childnode1); var ch4childnode2 = AddNode(500, 100, width, height, "Career"); diagram.AddNode(ch4childnode2); diagram.AddConnector(AddConnector(node, ch1node)); diagram.AddConnector(AddConnector(node, ch2node)); diagram.AddConnector(AddConnector(node, ch3node)); diagram.AddConnector(AddConnector(node, ch4node)); diagram.AddConnector(AddConnector(ch1node, ch1childnode)); diagram.AddConnector(AddConnector(ch2node, ch2childnode1)); diagram.AddConnector(AddConnector(ch2node, ch2childnode2)); diagram.AddConnector(AddConnector(ch3node, ch3childnode1)); diagram.AddConnector(AddConnector(ch3node, ch3childnode2)); diagram.AddConnector(AddConnector(ch4node, ch4childnode1)); diagram.AddConnector(AddConnector(ch4node, ch4childnode2)); diagram.UserHandleClicked += Diagram_UserHandleClicked; AddHandles(); diagram.NodeClicked += Diagram_NodeClicked; diagram.DiagramClicked += Diagram_DiagramClicked; diagram.Loaded += Diagram_Loaded; SelectedNode = node; diagram.TextChanged += Diagram_TextChanged; diagram.ConnectorClicked += Diagram_ConnectorClicked; } } private void DefaultLayout(object sender, EventArgs e) { simpleCurveTree = "default"; objShape1 = ShapeType.RoundedRectangle; objShape2 = ShapeType.RoundedRectangle; objShape3 = ShapeType.RoundedRectangle; objShape4 = ShapeType.RoundedRectangle; objShape5 = ShapeType.RoundedRectangle; segment = SegmentType.CurveSegment; fontVerticalAlignment = VerticalAlignment.Center; Dectype = DecoratorType.None; connColor = Color.Black; connLineColorFrom = ApplyColorFrom.TargetBorder; connDecColorFrom = ApplyColorFrom.TargetBorder; UpdateTheme(themeIndex); } void ManualLayout_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e) { if (ManualLayoutSwitch.IsToggled) { (diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm = true; } else { (diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm = false; } } private void SimpletreeCurvedLayout(object sender, EventArgs e) { simpleCurveTree = "simpleCurveTree"; objShape1 = ShapeType.RoundedRectangle; objShape2 = ShapeType.RoundedRectangle; objShape3 = ShapeType.RoundedRectangle; objShape4 = ShapeType.RoundedRectangle; objShape5 = ShapeType.RoundedRectangle; segment = SegmentType.CurveSegment; fontVerticalAlignment = VerticalAlignment.Center; Dectype = DecoratorType.None; connColor = Color.FromHex("#949494"); connLineColorFrom = ApplyColorFrom.Custom; connDecColorFrom = ApplyColorFrom.Custom; UpdateTheme(themeIndex); } private void OrthogonalLayout(object sender, EventArgs e) { simpleCurveTree = "orthotree"; objShape1 = ShapeType.Rectangle; objShape2 = ShapeType.Rectangle; objShape3 = ShapeType.Rectangle; objShape4 = ShapeType.Rectangle; objShape5 = ShapeType.Rectangle; segment = SegmentType.OrthoSegment; fontVerticalAlignment = VerticalAlignment.Center; Dectype = DecoratorType.None; connColor = Color.Black; connLineColorFrom = ApplyColorFrom.TargetBorder; connDecColorFrom = ApplyColorFrom.TargetBorder; UpdateTheme(themeIndex); } VerticalAlignment fontVerticalAlignment = VerticalAlignment.Center; private void ContinuousTreeDefaultLayout(object sender, EventArgs e) { simpleCurveTree = "contCurveTree"; SfGraphicsPath path = new SfGraphicsPath(); if (Device.RuntimePlatform == Device.Android) { path.MoveTo(0, 0); path.MoveTo(0, 50); path.LineTo(100, 50); path.MoveTo(100, 100); gra.DrawPath(path); Pen pe = new Pen(); pe.StrokeBrush = new SolidBrush(Color.Gray); pe.StrokeWidth = 5; point.Add(new Point(0, 50)); point.Add(new Point(100, 50)); gra.DrawLines(pe, point); } else { Pen pe = new Pen(); pe.StrokeBrush = new SolidBrush(Color.Gray); pe.StrokeWidth = 3; point.Add(new Point(0, 37)); point.Add(new Point(150, 37)); gra.DrawLines(pe, point); } objShape1 = ShapeType.Ellipse; objShape2 = gra; objShape3 = gra; objShape4 = gra; objShape5 = gra; segment = SegmentType.CurveSegment; fontVerticalAlignment = VerticalAlignment.Top; Dectype = DecoratorType.None; connColor = Color.Black; connLineColorFrom = ApplyColorFrom.TargetBorder; connDecColorFrom = ApplyColorFrom.TargetBorder; UpdateTheme(themeIndex); } private void style_SelectedIndexChanged(object sender, EventArgs e) { UpdateTheme(style.SelectedIndex); themeIndex = style.SelectedIndex; } private void UpdateTheme(int themeIndex) { if (themeIndex == 0) { bool m_repeatmode = true; nodeStyleCollection.Clear(); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#d7ebf6")), Color.FromHex("#d7ebf6"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#ffebc4")), Color.FromHex("#ffebc4"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#ffcdcd")), Color.FromHex("#ffcdcd"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#e7eeb8")), Color.FromHex("#e7eeb8"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#d7ebf6")), Color.FromHex("#d7ebf6"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "orthotree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#d7ebf6")), Color.FromHex("#b4d6e8"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#ffebc4")), Color.FromHex("#f2dcb1"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#ffcdcd")), Color.FromHex("#ecb6b6"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#e7eeb8")), Color.FromHex("#d6dda6"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#d7ebf6")), Color.FromHex("#b4d6e8"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { m_repeatmode = false; nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#d7ebf6")), Color.FromHex("#b4d6e8"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { m_repeatmode = false; nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#d7ebf6")), Color.FromHex("#d7ebf6"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#949494")), Color.FromHex("#949494"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#949494")), Color.FromHex("#949494"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#949494")), Color.FromHex("#949494"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#949494")), Color.FromHex("#949494"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connLineColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Branch, m_repeatmode)); } if (themeIndex == 1) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#eea4af")), Color.FromHex("#ce2340"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#c6ebb4")), Color.FromHex("#7cea56"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#a7c7ed")), Color.FromHex("#2f75d3"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#eac4a1")), Color.FromHex("#ce7023"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#ede3a2")), Color.FromHex("#d6bb29"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connLineColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 2) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#f0a8e1")), Color.FromHex("#da2eb8"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#eec3eb")), Color.FromHex("#ae8fa7"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#f0e8f0")), Color.FromHex("#ae8fa7"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#9a88b7")), Color.FromHex("#716587"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#efa6c8")), Color.FromHex("#ae7893"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connLineColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 3) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#f3d8d6")), Color.FromHex("#e3a39f"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#e9afa4")), Color.FromHex("#cd3e24"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#e6c6a7")), Color.FromHex("#c5752d"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#e9d5b3")), Color.FromHex("#cc9d44"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#ebc3a2")), Color.FromHex("#cf7225"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connLineColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 4) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#dabeb7")), Color.FromHex("#a66757"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#c4b2a3")), Color.FromHex("#714621"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#cec3cd")), Color.FromHex("#897386"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#d2c2b9")), Color.FromHex("#977460"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#d1c4c0")), Color.FromHex("#92736e"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connLineColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 5) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#c5cacd")), Color.FromHex("#747f86"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#d3d2d6")), Color.FromHex("#96979f"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#e7e8e7")), Color.FromHex("#c2bac1"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#b3b9bb")), Color.FromHex("#475859"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#c9cfce")), Color.FromHex("#7f8d8a"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connLineColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } if (themeIndex == 6) { nodeStyleCollection.Clear(); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#a1c6de")), Color.FromHex("#2174b1"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#a8c6ee")), Color.FromHex("#2f76da"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#a4baef")), Color.FromHex("#285cda"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#babaf3")), Color.FromHex("#585be4"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.FromHex("#b9dadf")), Color.FromHex("#57a5b3"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Gray), Color.Gray, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.XForms.TextStyle((int)(14 * DiagramUtility.factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, fontVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 3, connLineColorFrom, Dectype, connDecColorFrom, connDecColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Level, true)); } } private Connector AddConnector(Node node, Node ch1node) { var c1 = new Connector(); c1.SourceNode = node; c1.TargetNode = ch1node; c1.SegmentType = SegmentType.CurveSegment; return c1; } Node AddNode(int x, int y, int w, int h, string text) { var node = new Node(x, y, w, h); node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 2; if (Device.RuntimePlatform == Device.Android) node.Annotations.Add(new Annotation() { Content = text, FontSize = 17 * DiagramUtility.factor, TextBrush = new SolidBrush(Color.Black) }); else if (Device.RuntimePlatform == Device.iOS) node.Annotations.Add(new Annotation() { Content = text, FontSize = 15, TextBrush = new SolidBrush(Color.Black) }); return node; } private void AddAnnotation(string headertext) { StackLayout root; root = new StackLayout(); Label title = new Label(); title.Margin = new Thickness(0, 2, 0, 0); title.Text = headertext; title.TextColor = Color.Black; title.FontSize = 15; title.FontAttributes = FontAttributes.Bold; title.VerticalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Start }; title.HorizontalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Start }; root.Children.Add(title); textinput = new Entry(); textinput.Margin = new Thickness(0, 25, 0, 0); textinput.WidthRequest = 300; textinput.HeightRequest = 50; textinput.Focused += Textinput_Focused; textinput.Focus(); textinput.Placeholder = "Text"; textinput.VerticalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Center }; textinput.HorizontalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Center }; Button ok = new Button(); ok.BackgroundColor = Color.Transparent; ok.Text = "OK"; ok.TextColor = Color.FromHex("#e63375"); ok.Margin = new Thickness(0, 0, 0, 0); ok.VerticalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Center }; ok.HorizontalOptions = new LayoutOptions() { Alignment = LayoutAlignment.End }; ok.Clicked += Ok_Clicked; root.Children.Add(textinput); Button cancel = new Button(); cancel.Text = " CANCEL"; cancel.TextColor = Color.FromHex("#e63375"); cancel.BackgroundColor = Color.Transparent; cancel.Margin = new Thickness(0, 0, 0, 0); cancel.VerticalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Center }; cancel.HorizontalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Center }; cancel.Clicked += Cancel_Clicked; Grid buttonGrid = new Grid(); buttonGrid.Children.Add(cancel); buttonGrid.Children.Add(ok); root.Children.Add(buttonGrid); Notifier = new Frame(); Notifier.WidthRequest = 300; Notifier.HeightRequest = 150; Notifier.Content = root; Notifier.VerticalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Center }; Notifier.HorizontalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Center }; Notifier.CornerRadius = 5; Notifier.BackgroundColor = Color.White; Notifier.BorderColor = Color.Black; diagram.PageSettings.PageBackGround = Color.DarkGray; diagram.Opacity = 0.2; parent.Children.Add(Notifier); } private void Cancel_Clicked(object sender, EventArgs e) { diagram.Opacity = 1; diagram.PageSettings.PageBackGround = Color.White; parent.Children.Remove(Notifier); } private void AddHandles() { var plusTemplate = GetTemplate("plus.png"); var deleteTemplate = GetTemplate("delete.png"); m_expandTemplate = GetTemplate("mindmapcollpase.png"); m_collapseTemplate = GetTemplate("mindmapexpand.png"); var moreTemplate = GetTemplate("more.png"); DefaultHandles = new UserHandleCollection(); DefaultHandles.Add(new UserHandle("Left", UserHandlePosition.Left, plusTemplate)); DefaultHandles.Add(new UserHandle("Right", UserHandlePosition.Right, plusTemplate)); DefaultHandles.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, m_expandTemplate)); DefaultHandles.Add(new UserHandle("Delete", UserHandlePosition.Bottom, deleteTemplate) { Visible = false }); DefaultHandles.Add(new UserHandle("info", UserHandlePosition.TopRight, moreTemplate)); diagram.UserHandles = DefaultHandles; } private DataTemplate GetTemplate(string imageId) { return new DataTemplate(() => { var root = new StackLayout() { Orientation = StackOrientation.Horizontal, BackgroundColor = Color.Transparent }; Image image = new Image(); image.WidthRequest = 25; image.HeightRequest = 25; image.Source = imageId; root.Children.Add(image); return root; }); } private void Diagram_TextChanged(object sender, Syncfusion.SfDiagram.XForms.TextChangedEventArgs args) { args.Item.TextBrush = new SolidBrush(Color.Black); if (Device.RuntimePlatform == Device.Android) args.Item.FontSize = 17 * DiagramUtility.factor; else args.Item.FontSize = 15; } private void Diagram_Loaded(object sender) { if (m_isDiagramLoaded) { diagram.EnableDrag = false; diagram.ShowSelectorHandle(false, SelectorPosition.SourcePoint); diagram.ShowSelectorHandle(false, SelectorPosition.TargetPoint); diagram.ShowSelectorHandle(false, SelectorPosition.Rotator); diagram.ShowSelectorHandle(false, SelectorPosition.TopLeft); diagram.ShowSelectorHandle(false, SelectorPosition.TopRight); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleLeft); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleRight); diagram.ShowSelectorHandle(false, SelectorPosition.BottomCenter); diagram.ShowSelectorHandle(false, SelectorPosition.BottomLeft); diagram.ShowSelectorHandle(false, SelectorPosition.BottomRight); diagram.ShowSelectorHandle(false, SelectorPosition.TopCenter); diagram.LayoutManager = new LayoutManager() { Layout = new MindMapLayout() { MindMapOrientation = Orientation.Horizontal, HorizontalSpacing = 70, } }; if (Device.RuntimePlatform == Device.Android) { (diagram.LayoutManager.Layout as MindMapLayout).HorizontalSpacing = 70 * DiagramUtility.factor; } if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) { diagram.LayoutManager.Layout.UpdateLayout(); } diagram.Select(RootNode); diagram.BringToView(RootNode); UpdateTheme(0); m_isDiagramLoaded = false; } } private void Diagram_DiagramClicked(object sender, DiagramClickedEventArgs args) { diagram.Opacity = 1; diagram.PageSettings.PageBackGround = Color.White; if (Notifier != null && parent.Children.Contains(Notifier)) { textinput.Unfocus(); parent.Children.Remove(Notifier); } SelectedNode = null; } private void Diagram_UserHandleClicked(object sender, UserHandleClickedEventArgs args) { if (Notifier != null && parent.Children.Contains(Notifier)) { parent.Children.Remove(Notifier); diagram.Opacity = 1; diagram.PageSettings.PageBackGround = Color.White; } else { if (args.Item.Name == "Delete") { diagram.RemoveNode(SelectedNode, true); if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayout(); } else if (args.Item.Name == "ExpColl") { diagram.ClearSelection(); if (SelectedNode.IsExpanded) { SelectedNode.IsExpanded = false; args.Item.Content = m_collapseTemplate; } else { SelectedNode.IsExpanded = true; args.Item.Content = m_expandTemplate; } if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayout(); UpdateHandle(); diagram.Select(SelectedNode); } else if (args.Item.Name == "info") { ShowInfo(); } else { if (args.Item.Name == "Left") { CurrentHandle = UserHandlePosition.Left; AddAnnotation("Add Topic"); } else if (args.Item.Name == "Right") { CurrentHandle = UserHandlePosition.Right; AddAnnotation("Add Topic"); } } } } async void ShowInfo() { var nav = new AddNote(this); NavigationPage.SetHasBackButton(nav, false); NavigationPage.SetHasNavigationBar(nav, false); await Navigation.PushAsync(nav); } private void Textinput_Focused(object sender, FocusEventArgs e) { Notifier.VerticalOptions = new LayoutOptions() { Alignment = LayoutAlignment.Start }; Notifier.Margin = new Thickness(0, 50, 0, 0); if (Device.RuntimePlatform == Device.iOS) Notifier.Margin = new Thickness(0, 200, 0, 0); } private void Ok_Clicked(object sender, EventArgs e) { diagram.Opacity = 1; diagram.PageSettings.PageBackGround = Color.White; parent.Children.Remove(Notifier); if (textinput.Text == null) { textinput.Text = ""; } var node = new Node(); if (CurrentHandle == UserHandlePosition.Left) { node.OffsetX = SelectedNode.OffsetX - SelectedNode.Width - 100; node.OffsetY = SelectedNode.OffsetY; } else if (CurrentHandle == UserHandlePosition.Right) { node.OffsetX = SelectedNode.OffsetX + SelectedNode.Width + 100; node.OffsetY = SelectedNode.OffsetY; } node.Width = SelectedNode.Width; node.Height = SelectedNode.Height; node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 2; if (SelectedNode == RootNode) { index = rnd.Next(5); node.Style.Brush = new SolidBrush(FColor[index]); node.Style.StrokeBrush = new SolidBrush(SColor[index]); } else { node.Style = SelectedNode.Style; } if (Device.RuntimePlatform == Device.Android) node.Annotations.Add(new Annotation() { Content = textinput.Text, FontSize = 17 * DiagramUtility.factor, TextBrush = new SolidBrush(Color.Black) }); else if (Device.RuntimePlatform == Device.iOS) node.Annotations.Add(new Annotation() { Content = textinput.Text, FontSize = 15, TextBrush = new SolidBrush(Color.Black) }); diagram.AddNode(node); var c1 = new Connector(); c1.SourceNode = SelectedNode; c1.TargetNode = node; c1.Style.StrokeBrush = node.Style.StrokeBrush; c1.Style.StrokeWidth = 3; c1.TargetDecoratorStyle.Fill = (node.Style.StrokeBrush as SolidBrush).FillColor; c1.TargetDecoratorStyle.Stroke = (node.Style.StrokeBrush as SolidBrush).FillColor; c1.SegmentType = SegmentType.CurveSegment; c1.Style.StrokeStyle = StrokeStyle.Dashed; diagram.AddConnector(c1); if (CurrentHandle == UserHandlePosition.Left) { if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateLeftOrTop(); } else if (CurrentHandle == UserHandlePosition.Right) { if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateRightOrBottom(); } SelectedNode = node; UpdateHandle(); diagram.UserHandles[2].Visible = false; diagram.Select(node); SelectedNode = node; diagram.BringToView(node); } private void Diagram_NodeClicked(object sender, NodeClickedEventArgs args) { SelectedNode = args.Item; diagram.Opacity = 1; diagram.PageSettings.PageBackGround = Color.White; if (Notifier != null && parent.Children.Contains(Notifier)) { parent.Children.Remove(Notifier); } else { UpdateHandle(); } } private String GetNodeDirection(Node node) { string side = null; if (node != RootNode && node.OffsetX > RootNode.OffsetX) { side = "Right"; } else if (node != RootNode && node.OffsetX < RootNode.OffsetX) { side = "Left"; } else if (node == RootNode) { side = "Center"; } return side; } private void UpdateHandle() { var side = GetNodeDirection(SelectedNode); if (side == "Right") { //Left add diagram.UserHandles[0].Visible = false; //Right add diagram.UserHandles[1].Visible = true; //ExpColl if (SelectedNode.IsExpanded) { diagram.UserHandles[2].Content = m_collapseTemplate; } else { diagram.UserHandles[2].Content = m_expandTemplate; } diagram.UserHandles[2].Visible = true; //Delete diagram.UserHandles[3].Visible = true; //Info diagram.UserHandles[4].Visible = true; if (!SelectedNode.IsExpanded) { diagram.UserHandles[1].Visible = false; } } else if (side == "Left") { //Left add diagram.UserHandles[0].Visible = true; //Right add diagram.UserHandles[1].Visible = false; //ExpColl if (SelectedNode.IsExpanded) { diagram.UserHandles[2].Content = m_expandTemplate; } else { diagram.UserHandles[2].Content = m_collapseTemplate; } diagram.UserHandles[2].Visible = true; //Delete diagram.UserHandles[3].Visible = true; //Info diagram.UserHandles[4].Visible = true; if (!SelectedNode.IsExpanded) { diagram.UserHandles[0].Visible = false; } } else if (side == "Center") { //Left add diagram.UserHandles[0].Visible = true; //Right add diagram.UserHandles[1].Visible = true; //ExpColl diagram.UserHandles[2].Visible = true; //Delete diagram.UserHandles[3].Visible = false; //Info diagram.UserHandles[4].Visible = true; if (!SelectedNode.IsExpanded) { diagram.UserHandles[0].Visible = false; diagram.UserHandles[1].Visible = false; } } if (SelectedNode.Children.Any()) { diagram.UserHandles[2].Visible = true; } else { diagram.UserHandles[2].Visible = false; } } void Diagram_ConnectorClicked(object sender, ConnectorClickedEventArgs args) { diagram.ClearSelection(); if (Notifier != null && parent.Children.Contains(Notifier)) { parent.Children.Remove(Notifier); } } public override void OnDisappearing() { if (nodeStyleCollection != null) { nodeStyleCollection = null; } if (gra != null) { gra = null; } if (point != null) { point = null; } if (SColor != null) { SColor = null; } if (FColor != null) { FColor = null; } GC.Collect(); base.OnDisappearing(); } } }<file_sep>/Android/SampleBrowser/Samples/TreeView/Helper/CustomViews/TemplateSelectorView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using System; using Syncfusion.Android.TreeView; using Android.Util; using Android.Runtime; namespace SampleBrowser { public class TemplateView : LinearLayout { #region Fields private ContentLabel label1; private ContentLabel label2; private int expanderWidth; #endregion #region Constructor public TemplateView(Context context, TreeViewItemInfoBase itemInfo) : base(context) { this.Orientation = Orientation.Horizontal; label1 = new ContentLabel(context); label1.Gravity = GravityFlags.CenterVertical; label1.SetPadding(0, 0, 0, 0); label2 = new ContentLabel(context); label2.Gravity = GravityFlags.Center; expanderWidth = (int)(itemInfo as TreeViewItemInfo).TreeView.ExpanderWidth; this.AddView(label1); this.AddView(label2); } #endregion #region Methods protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure(widthMeasureSpec, heightMeasureSpec); var density = Resources.DisplayMetrics.Density; var measuredwidth = (int)(40 * density); var measuredheight = (int)(40 * density); var labelPadding = (int)(10 * density); var labelwidth = Math.Abs(widthMeasureSpec - measuredwidth); this.label1.SetMinimumHeight(measuredheight); this.label1.SetMinimumWidth(labelwidth); this.label2.SetMinimumHeight(measuredheight - (labelPadding * 2)); this.label2.SetMinimumWidth(measuredwidth - labelPadding); this.label2.Measure(measuredwidth - labelPadding, measuredheight - (labelPadding * 2)); this.label1.Measure(labelwidth, measuredheight); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { var density = Resources.DisplayMetrics.Density; var measuredwidth = (int)(40 * density); var padding = (int)(10 * density); var measuredheight = (int)(40 * density); var expanderwidth = (int)(expanderWidth * density); this.label1.Layout(0, 0, this.Width - (measuredwidth + expanderwidth), measuredheight); this.label2.Layout(this.Width - (measuredwidth + expanderwidth), padding, this.Width- (expanderwidth + padding), measuredheight - padding); } #endregion } }<file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/ListViewPullToRefresh/Model/ListViewBlogsInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ListViewBlogsInfo.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains Properties and Notifies that a property value has changed /// </summary> public class ListViewBlogsInfo : INotifyPropertyChanged { #region Fields [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string blogTitle; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string blogCategory; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string blogAuthor; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ImageSource categoryIcon; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ImageSource autherIcon; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ImageSource blogFacebookIcon; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ImageSource blogTwitterIcon; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ImageSource blogGooglePlusIcon; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ImageSource blogLinkedInIcon; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string readMoreContent; #endregion #region Constructor #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Properties /// <summary> /// Gets or sets the BlogTitle and notifies user when collection value gets changed. /// </summary> public string BlogTitle { get { return this.blogTitle; } set { this.blogTitle = value; this.OnPropertyChanged("BlogTitle"); } } /// <summary> /// Gets or sets the BlogCategory and notifies user when collection value gets changed. /// </summary> public string BlogCategory { get { return this.blogCategory; } set { this.blogCategory = value; this.OnPropertyChanged("BlogCategory"); } } /// <summary> /// Gets or sets the BlogAuthor and notifies user when collection value gets changed. /// </summary> public string BlogAuthor { get { return this.blogAuthor; } set { this.blogAuthor = value; this.OnPropertyChanged("BlogAuthor"); } } /// <summary> /// Gets or sets the BlogAuthorIcon and notifies user when collection value gets changed. /// </summary> public ImageSource BlogAuthorIcon { get { return this.autherIcon; } set { this.autherIcon = value; this.OnPropertyChanged("BlogAuthorIcon"); } } /// <summary> /// Gets or sets the BlogCategoryIcon and notifies user when collection value gets changed. /// </summary> public ImageSource BlogCategoryIcon { get { return this.categoryIcon; } set { this.categoryIcon = value; this.OnPropertyChanged("BlogCategoryIcon"); } } /// <summary> /// Gets or sets the BlogFacebookIcon and notifies user when collection value gets changed. /// </summary> public ImageSource BlogFacebookIcon { get { return this.blogFacebookIcon; } set { this.blogFacebookIcon = value; this.OnPropertyChanged("BlogFacebookIcon"); } } /// <summary> /// Gets or sets the BlogTwitterIcon and notifies user when collection value gets changed. /// </summary> public ImageSource BlogTwitterIcon { get { return this.blogTwitterIcon; } set { this.blogTwitterIcon = value; this.OnPropertyChanged("BlogTwitterIcon"); } } /// <summary> /// Gets or sets the BlogGooglePlusIcon and notifies user when collection value gets changed. /// </summary> public ImageSource BlogGooglePlusIcon { get { return this.blogGooglePlusIcon; } set { this.blogGooglePlusIcon = value; this.OnPropertyChanged("BlogGooglePlusIcon"); } } /// <summary> /// Gets or sets the BlogLinkedInIcon and notifies user when collection value gets changed. /// </summary> public ImageSource BlogLinkedInIcon { get { return this.blogLinkedInIcon; } set { this.blogLinkedInIcon = value; this.OnPropertyChanged("BlogLinkedInIcon"); } } /// <summary> /// Gets or sets the ReadMoreContent and notifies user when collection value gets changed. /// </summary> public string ReadMoreContent { get { return this.readMoreContent; } set { this.readMoreContent = value; this.OnPropertyChanged("ReadMoreContent"); } } #endregion #region Interface Member /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name represents property name</param> public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Styles/Red.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Red.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using Syncfusion.SfDataGrid; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Derived from DataGridStyle to add the custom styles /// </summary> public class Red : DataGridStyle { /// <summary> /// Initializes a new instance of the Red class. /// </summary> public Red() { } //// public override Color GetHeaderBorderColor() //// { //// return Color.Red; //// } /// <summary> /// Overrides this method to write a custom style for header back ground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetHeaderBackgroundColor() { return Color.FromRgb(190, 93, 93); } /// <summary> /// Overrides this method to write a custom style for header foreground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetHeaderForegroundColor() { return Color.FromRgb(255, 255, 255); } /// <summary> /// Overrides this method to write a custom style for selection background color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetSelectionBackgroundColor() { return Color.FromRgb(229, 115, 115); } /// <summary> /// Overrides this method to write a custom style for selection foreground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetSelectionForegroundColor() { return Color.FromRgb(255, 255, 255); } /// <summary> /// Overrides this method to write a custom style for caption summary row background color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetCaptionSummaryRowBackgroundColor() { return Color.FromRgb(224, 224, 224); } /// <summary> /// Overrides this method to write a custom style for caption summary row foreground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetCaptionSummaryRowForegroundColor() { return Color.FromRgb(51, 51, 51); } /// <summary> /// Overrides this method to write a custom style for border color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetBorderColor() { return Color.FromRgb(180, 180, 180); } /// <summary> /// Overrides this method to write a custom style for alternate row background color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetAlternatingRowBackgroundColor() { return Color.FromRgb(255, 235, 237); } /// <summary> /// Overrides this method to write a custom style for alternate record foreground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetRecordForegroundColor() { return Color.FromRgb(0, 0, 0); } /// <summary> /// Overrides this method to write a Grid line visibility /// </summary> /// <returns>Returns GridLinesVisibility Horizontal</returns> public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Horizontal; } } }<file_sep>/Android/SampleBrowser/Samples/Calendar/README.md ## SfCalendar Calendar is a user interface component that displays Gregorian calendar. This component allows the user to select a date. It also provides a gesture-friendly UI to perform operations such as navigations, events, and more. | Sample | Description | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| | GettingStarted | Showcases different view modes support: month and year views. | | Blackout Dates | Showcases the specific date blackout capability of calendar. | | Inline Events | Showcases the inline events in inline view mode and agenda view mode in a specific date of the month. | | Localization | Showcases localization and globalization. | | Customization | Showcases the month cell customization using custom view with restriction support to navigate beyond the specified minimum and maximum dates. | <file_sep>/Forms/XlsIO/XlsIO/ISave.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.IO; using System.Threading.Tasks; namespace SampleBrowser.XlsIO { public interface ISave { void Save(string filename, string contentType, MemoryStream stream); } public interface ISaveWindowsPhone { Task Save(string filename, string contentType, MemoryStream stream); } public interface IAndroidVersionDependencyService { int GetAndroidVersion(); } } <file_sep>/Android/SampleBrowser/Samples/CircularGauge/MultipleScale.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfCircularGauge; using System.Collections.ObjectModel; using Android.Graphics; using Com.Syncfusion.Gauges.SfCircularGauge.Enums; using Android.Renderscripts; namespace SampleBrowser { public class MultipleScale : SamplePage { double value; double value1; double value2; double value3; CircularScale scale; CircularScale circularScale2; public override View GetSampleContent (Context con) { SfCircularGauge sfCircularGauge = new SfCircularGauge(con); ObservableCollection<CircularScale> circularScales = new ObservableCollection<CircularScale>(); scale = new CircularScale(); scale.StartValue = 0; scale.EndValue = 240; scale.Interval = 20; scale.StartAngle = 135; scale.SweepAngle = 270; scale.RimColor = Color.ParseColor("#C62E0A"); scale.LabelColor = Color.ParseColor("#C62E0A"); scale.LabelOffset = 0.88; scale.ScaleStartOffset = 0.7; scale.ScaleEndOffset = 0.69; scale.MinorTicksPerInterval = 1; scale.MajorTickSettings.StartOffset = 0.7; scale.MajorTickSettings.EndOffset = 0.77; scale.MajorTickSettings.Width = 2; scale.MajorTickSettings.Color = Color.ParseColor("#C62E0A"); scale.MinorTickSettings.StartOffset = 0.7; scale.MinorTickSettings.EndOffset = 0.75; scale.MinorTickSettings.Width = 2; scale.MinorTickSettings.Color = Color.ParseColor("#C62E0A"); ObservableCollection<CircularPointer> pointers = new ObservableCollection<CircularPointer>(); MarkerPointer markerPointer = new MarkerPointer(); markerPointer.Value = 120; markerPointer.Color = Color.ParseColor("#C62E0A"); markerPointer.Offset = 0.69; markerPointer.MarkerShape = Com.Syncfusion.Gauges.SfCircularGauge.Enums.MarkerShape.InvertedTriangle; markerPointer.EnableAnimation = false; pointers.Add(markerPointer); scale.CircularPointers = pointers; circularScales.Add(scale); circularScale2 = new CircularScale(); circularScale2.StartAngle = 135; circularScale2.SweepAngle = 270; circularScale2.StartValue = 0; circularScale2.EndValue = 160; circularScale2.Interval = 40; circularScale2.MinorTicksPerInterval = 1; circularScale2.RimColor = Color.ParseColor("#333333"); circularScale2.LabelOffset = 0.45; circularScale2.LabelColor = Color.ParseColor("#333333"); circularScale2.ScaleStartOffset = 0.65; circularScale2.ScaleEndOffset = 0.64; circularScale2.MajorTickSettings.StartOffset = 0.64; circularScale2.MajorTickSettings.EndOffset = 0.57; circularScale2.MajorTickSettings.Width = 2; circularScale2.MajorTickSettings.Color = Color.ParseColor("#333333"); circularScale2.MinorTickSettings.StartOffset = 0.64; circularScale2.MinorTickSettings.EndOffset = 0.59; circularScale2.MinorTickSettings.Width = 2; circularScale2.MinorTickSettings.Color = Color.ParseColor("#333333"); ObservableCollection<CircularPointer> circularPointers = new ObservableCollection<CircularPointer>(); MarkerPointer markerPointer1 = new MarkerPointer(); markerPointer1.Value = 80; markerPointer1.Color = Color.ParseColor("#333333"); markerPointer1.Offset = 0.65; markerPointer1.MarkerShape = Com.Syncfusion.Gauges.SfCircularGauge.Enums.MarkerShape.Triangle; markerPointer1.EnableAnimation = false; circularPointers.Add(markerPointer1); circularScale2.CircularPointers = circularPointers; circularScales.Add(circularScale2); sfCircularGauge.CircularScales = circularScales; sfCircularGauge.SetBackgroundColor(Color.White); LinearLayout linearLayout = new LinearLayout(con); linearLayout.AddView(sfCircularGauge); linearLayout.SetPadding(30, 30, 30, 30); linearLayout.SetBackgroundColor(Color.White); return linearLayout; } public override View GetPropertyWindowLayout(Android.Content.Context context) { TextView startAngle = new TextView(context); startAngle.Text = "Change StartAngle"; startAngle.Typeface = Typeface.DefaultBold; startAngle.SetTextColor(Color.ParseColor("#262626")); startAngle.TextSize = 20; TextView sweepAngle = new TextView(context); sweepAngle.Text = "Change SweepAngle"; sweepAngle.Typeface = Typeface.DefaultBold; sweepAngle.SetTextColor(Color.ParseColor("#262626")); sweepAngle.TextSize = 20; TextView startAngle1 = new TextView(context); startAngle1.Text = "Change StartAngle"; startAngle1.Typeface = Typeface.DefaultBold; startAngle1.SetTextColor(Color.ParseColor("#262626")); startAngle1.TextSize = 20; TextView sweepAngle1 = new TextView(context); sweepAngle1.Text = "Change SweepAngle"; sweepAngle1.Typeface = Typeface.DefaultBold; sweepAngle1.SetTextColor(Color.ParseColor("#262626")); sweepAngle1.TextSize = 20; SeekBar pointerSeek = new SeekBar(context); pointerSeek.Max = 350; pointerSeek.Progress = 135; pointerSeek.ProgressChanged += pointerSeek_ProgressChanged; SeekBar pointerSeek1 = new SeekBar(context); pointerSeek1.Max = 350; pointerSeek1.Progress = 270; pointerSeek1.ProgressChanged += pointerSeek_ProgressChanged1; SeekBar pointerSeek2 = new SeekBar(context); pointerSeek2.Max = 350; pointerSeek2.Progress = 135; pointerSeek2.ProgressChanged += pointerSeek_ProgressChanged2; SeekBar pointerSeek3 = new SeekBar(context); pointerSeek3.Max = 350; pointerSeek3.Progress = 270; pointerSeek3.ProgressChanged += pointerSeek_ProgressChanged3; LinearLayout optionsPage = new LinearLayout(context); optionsPage.Orientation = Orientation.Vertical; optionsPage.AddView(startAngle); optionsPage.AddView(pointerSeek); optionsPage.AddView(sweepAngle); optionsPage.AddView(pointerSeek1); optionsPage.AddView(startAngle1); optionsPage.AddView(pointerSeek2); optionsPage.AddView(sweepAngle1); optionsPage.AddView(pointerSeek3); optionsPage.SetPadding(10, 10, 10, 10); optionsPage.SetBackgroundColor(Color.White); return optionsPage; } void pointerSeek_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { value = e.Progress; scale.StartAngle = value; } void pointerSeek_ProgressChanged1(object sender, SeekBar.ProgressChangedEventArgs e) { value1 = e.Progress; scale.SweepAngle = value1; } void pointerSeek_ProgressChanged2(object sender, SeekBar.ProgressChangedEventArgs e) { value2 = e.Progress; circularScale2.StartAngle = value2; } void pointerSeek_ProgressChanged3(object sender, SeekBar.ProgressChangedEventArgs e) { value3 = e.Progress; circularScale2.SweepAngle = value3; } //public override void OnApplyChanges() //{ // base.OnApplyChanges(); // scale.StartAngle = value; // scale.SweepAngle = value1; // circularScale2.StartAngle = value2; // circularScale2.SweepAngle = value3; //} } } <file_sep>/Forms/PdfViewer/PdfViewer/Samples/Annotations/Annotations.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfPdfViewer.XForms; using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.IO; namespace SampleBrowser.SfPdfViewer { [Preserve(AllMembers = true)] public partial class Annotations : SampleView { string currentDocument = "Annotations"; public Annotations() { InitializeComponent(); pdfViewerControl.DocumentSaveInitiated += PdfViewerControl_DocumentSaved; (BindingContext as GettingStartedViewModel).DocumentName = currentDocument; } private void PdfViewerControl_DocumentSaved(object sender, DocumentSaveInitiatedEventArgs args) { string filePath = DependencyService.Get<ISave>().Save(args.SaveStream as MemoryStream); string message = "The PDF has been saved to " + filePath; DependencyService.Get<IAlertView>().Show(message); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataForm/Model/ContactInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using System.Collections.ObjectModel; namespace SampleBrowser { class ContactsInfoRepository { #region Fields private Random random = new Random(); #endregion #region Constructor public ContactsInfoRepository() { } #endregion #region Get Contacts Details public ObservableCollection<ContactInfo> GetContactDetails(int count) { ObservableCollection<ContactInfo> customerDetails = new ObservableCollection<ContactInfo>(); for (int i = 0; i < 9; i++) { var details = new ContactInfo() { ContactType = ContactInfo.ContactsType.Business, ContactNumber = random.Next(100000, 400000).ToString(), ContactName = CustomerNames[i], ContactImage = UIImage.FromBundle("Contact" + (i % 10) + ".png"), }; customerDetails.Add(details); } return customerDetails; } #endregion #region Contacts Information string[] contactType = new string[] { "HOME", "WORK", "MOBILE", "OTHER", "BUSINESS" }; string[] CustomerNames = new string[] { "Liz", "Ralph", "Oscar", "Torrey", "Gina", "Irene", "Katie", "Fiona", "Kyle", "Michael", "William", "Bill", }; #endregion } }<file_sep>/Forms/NavigationDrawer/NavigationDrawer/Samples/NavigationDrawer_Main/Archive_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using SampleBrowser.Core; using Syncfusion.SfNavigationDrawer.XForms; using Xamarin.Forms; namespace SampleBrowser.SfNavigationDrawer { public partial class Archive_Default : ContentView { public Archive_Default(ObservableCollection<Message> items, string title) { InitializeComponent(); headerGradiant.WidthRequest = Core.SampleBrowser.ScreenWidth; headerLabel.Text = title; listView.ItemsSource = items; btn.BackgroundColor = Color.FromHex("#00a0e1"); btn.HeightRequest = 40; btn.WidthRequest = 40; btn.Text = "H"; btn.FontSize = 16; if (Device.RuntimePlatform == Device.iOS && Device.Idiom == TargetIdiom.Tablet) { headingGrid.Padding = new Thickness(10, 10, 0, 10); } if (Device.RuntimePlatform == Device.Android) { if(Device.Idiom == TargetIdiom.Tablet) btn.WidthRequest = 60; btn.FontFamily = "navigation.ttf#navigation"; recentButton.Text = "\uE823"; headerLabel.WidthRequest = ((Core.SampleBrowser.ScreenWidth * Core.SampleBrowser.Density) - (Core.SampleBrowser.Density * btn.WidthRequest)); recentButton.WidthRequest = 60; recentButton.FontFamily = "segoe-mdl2-assets.ttf#segoe-mdl2-assets"; } else if (Device.RuntimePlatform == Device.UWP) { btn.FontSize = 21; btn.Text = "\xE700"; btn.FontFamily = "Segoe MDL2 Assets"; btn.HeightRequest = 50; btn.WidthRequest = 50; recentButton.FontFamily = "SB Icons.ttf#SB Icons"; recentButton.Text = "\uE726"; recentButton.WidthRequest = 50; recentButton.HeightRequest = 50; } else { btn.FontFamily = "SB Icons"; btn.Text = "\uE731"; btn.WidthRequest = 50; btn.HeightRequest = 50; recentButton.FontFamily = "SB Icons"; recentButton.Text = "\uE726"; recentButton.WidthRequest = 50; recentButton.HeightRequest = 50; } btn.TextColor = Color.White; } void Handle_ItemTapped(object sender, Xamarin.Forms.ItemTappedEventArgs e) { (sender as ListView).SelectedItem = null; } void Btn_Clicked(object sender, EventArgs e) { if((sender as Button) == btn) DependencyService.Get<IToggleDrawer>().ToggleDrawer(); else if((sender as Button) == recentButton) DependencyService.Get<IToggleSecondaryDrawer>().ToggleSecondaryDrawer(); } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (Device.RuntimePlatform == Device.iOS) { recentButton.HeightRequest = 48; recentButton.WidthRequest = 48; } } } } <file_sep>/Forms/PDF/PDF/Samples/ZugFerd/ZugFerdInvoice.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml; using System.Xml.Linq; namespace Syncfusion.ZugFerd { /// <summary> /// zugFerd Invoice /// </summary> public class ZugFerdInvoice { public string InvoiceNumber { get; set; } public DateTime InvoiceDate { get; set; } public CurrencyCodes Currency { get; set; } public InvoiceType Type { get; set; } public UserDetails Buyer { get; set; } public UserDetails Seller { get; set; } public ZugFerdProfile Profile { get; set; } public float TotalAmount { get; set; } List<Product> products = new List<Product>(); XNamespace rsm = "urn:ferd:CrossIndustryDocument:invoice:1p0"; XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance"; XNamespace udt = "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15"; XNamespace ram = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12"; public void AddProduct(Product product) { products.Add(product); } public void AddProduct(string productID, string productName,float price, float quantity, float totalPrice) { Product product = new Product() { ProductID = productID, productName = productName, Price = price, Quantity = quantity, Total = totalPrice }; products.Add(product); } public ZugFerdInvoice(string invoiceNumber, DateTime invoiceDate, CurrencyCodes currency) { InvoiceNumber= invoiceNumber; InvoiceDate = invoiceDate; Currency = currency; } public Stream Save(Stream stream) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.Encoding = Encoding.UTF8; XDocument doc = new XDocument(); XElement root = new XElement(rsm + "CrossIndustryDocument", new XAttribute(XNamespace.Xmlns + "xsi", xsi)); root.SetAttributeValue(XNamespace.Xmlns + "rsm", rsm); root.SetAttributeValue(XNamespace.Xmlns + "ram", ram); root.SetAttributeValue(XNamespace.Xmlns + "udt", udt); #region SpecifiedExchangedDocumentContext XElement SpecifiedExchangedDocumentContext = new XElement(rsm + "SpecifiedExchangedDocumentContext"); XElement testIndicator = new XElement(ram + "TestIndicator"); XElement udtIndicator = new XElement(udt + "Indicator"); udtIndicator.Value = "true"; testIndicator.Add(udtIndicator); SpecifiedExchangedDocumentContext.Add(testIndicator); XElement guidelineSpecifiedDocumentContextParameter = new XElement(ram + "GuidelineSpecifiedDocumentContextParameter"); XElement id = new XElement(ram + "ID"); id.Value = "urn:ferd:CrossIndustryDocument:invoice:1p0:" + Profile.ToString(); guidelineSpecifiedDocumentContextParameter.Add(id); SpecifiedExchangedDocumentContext.Add(guidelineSpecifiedDocumentContextParameter); root.Add(SpecifiedExchangedDocumentContext); #endregion #region HeaderExchangedDocument XElement headerExchangedDocument = new XElement(rsm + "HeaderExchangedDocument"); id = new XElement(ram + "ID"); id.Value = InvoiceNumber; headerExchangedDocument.Add(id); XElement name = new XElement(ram + "Name"); name.Value = GetInvoiceTypeName(Type); headerExchangedDocument.Add(name); XElement typeCode = new XElement(ram + "TypeCode"); typeCode.Value = GetInvoiceTypeCode(Type).ToString(); headerExchangedDocument.Add(typeCode); XElement issueDateTime = new XElement(ram + "IssueDateTime"); XElement dateTimeString = new XElement(udt + "DateTimeString", new XAttribute("format", "102")); dateTimeString.Value = ConvertDateFormat(InvoiceDate, "102"); issueDateTime.Add(dateTimeString); headerExchangedDocument.Add(issueDateTime); root.Add(headerExchangedDocument); #endregion #region SpecifiedSupplyChainTradeTransaction XElement specifiedSupplyChainTradeTransaction = new XElement(rsm + "SpecifiedSupplyChainTradeTransaction"); XElement applicableSupplyChainTradeAgreement = new XElement(ram + "ApplicableSupplyChainTradeAgreement"); XElement sellerParty = WriteUserDetails("SellerTradeParty", Seller); applicableSupplyChainTradeAgreement.Add(sellerParty); XElement buyerParty =WriteUserDetails("BuyerTradeParty", Buyer); applicableSupplyChainTradeAgreement.Add(buyerParty); specifiedSupplyChainTradeTransaction.Add(applicableSupplyChainTradeAgreement); XElement ApplicableSupplyChainTradeSettlement = new XElement(ram+"ApplicableSupplyChainTradeSettlement"); XElement InvoiceCurrencyCode = new XElement(ram+ "InvoiceCurrencyCode"); InvoiceCurrencyCode.Value = Currency.ToString("g"); ApplicableSupplyChainTradeSettlement.Add(InvoiceCurrencyCode); XElement SpecifiedTradeSettlementMonetarySummation = new XElement(ram+"SpecifiedTradeSettlementMonetarySummation"); XElement GrandTotalAmount = new XElement(ram+"GrandTotalAmount"); GrandTotalAmount.Value = TotalAmount.ToString(); GrandTotalAmount.SetAttributeValue("currencyID",Currency.ToString("g")); SpecifiedTradeSettlementMonetarySummation.Add(GrandTotalAmount); ApplicableSupplyChainTradeSettlement.Add(SpecifiedTradeSettlementMonetarySummation); specifiedSupplyChainTradeTransaction.Add(ApplicableSupplyChainTradeSettlement); foreach (Product product in this.products) { XElement LineItem = AddTradeLineItems(product); specifiedSupplyChainTradeTransaction.Add(LineItem); } root.Add(specifiedSupplyChainTradeTransaction); #endregion doc.Add(root); XmlWriter writer = XmlWriter.Create(stream, settings); doc.WriteTo(writer); writer.Flush(); stream.Position = 0; return stream; } private XElement AddTradeLineItems(Product product) { XElement tradeLineItem = null; if (products.Count == 0) throw new Exception("prodcut empty"); tradeLineItem = new XElement(ram + "IncludedSupplyChainTradeLineItem"); if (Profile != ZugFerdProfile.Basic) { XElement tradeAgreement = new XElement(ram + "SpecifiedSupplyChainTradeAgreement"); XElement tradePrice = new XElement(ram + "GrossPriceProductTradePrice"); XElement basisQuantity = new XElement(ram + "BasisQuantity"); basisQuantity.Value = product.Quantity.ToString(); tradePrice.Add(basisQuantity); tradeAgreement.Add(tradePrice); tradeLineItem.Add(tradeAgreement); } XElement SpecifiedSupplyChainTradeDelivery = new XElement(ram + "SpecifiedSupplyChainTradeDelivery"); XElement BilledQuantity = new XElement(ram + "BilledQuantity"); BilledQuantity.Value = product.Quantity.ToString(); BilledQuantity.SetAttributeValue("unitCode", "KGM"); SpecifiedSupplyChainTradeDelivery.Add(BilledQuantity); tradeLineItem.Add(SpecifiedSupplyChainTradeDelivery); XElement tradSettlement = new XElement(ram + "SpecifiedSupplyChainTradeSettlement"); XElement monetarySummation = new XElement(ram + "SpecifiedTradeSettlementMonetarySummation"); XElement LineTotalAmount = new XElement(ram + "LineTotalAmount"); LineTotalAmount.Value = FormatValue(TotalAmount); LineTotalAmount.SetAttributeValue("currencyID", this.Currency.ToString("g")); monetarySummation.Add(LineTotalAmount); tradSettlement.Add(monetarySummation); tradeLineItem.Add(tradSettlement); XElement SpecifiedTradeProduct = new XElement(ram + "SpecifiedTradeProduct"); XElement productName = new XElement(ram + "Name"); productName.Value = product.productName; SpecifiedTradeProduct.Add(productName); tradeLineItem.Add(SpecifiedTradeProduct); return tradeLineItem; } private void WriteAttribute(XmlWriter writer, string tagName, string attributeName, string attributeValue, string nodeValue) { writer.WriteStartElement(tagName); writer.WriteAttributeString(attributeName, attributeValue); writer.WriteValue(nodeValue); writer.WriteEndElement(); } private void WriteOptionalElement(XmlWriter writer, string tagName, string value) { if (!String.IsNullOrEmpty(value)) { writer.WriteElementString(tagName, value); } } private void WriteOptionalAmount(XmlWriter writer, string tagName, float value, int numDecimals = 2) { if (value !=float.MinValue) { writer.WriteStartElement(tagName); writer.WriteAttributeString("currencyID", Currency.ToString("g")); writer.WriteValue(FormatValue(value, numDecimals)); writer.WriteEndElement(); } } private XElement WriteUserDetails( string customerTag, UserDetails user) { XElement sellerTradeParty = null; if (user != null) { sellerTradeParty = new XElement(ram + customerTag); XElement id = new XElement(ram + "ID"); sellerTradeParty.Add(id); id.Value = user.ID; XElement name = new XElement(ram + "Name"); name.Value = user.Name; sellerTradeParty.Add(name); XElement postalTradeAddress = new XElement(ram + "PostalTradeAddress"); XElement postcodeCode = new XElement(ram + "PostcodeCode"); postcodeCode.Value = user.Postcode; postalTradeAddress.Add(postcodeCode); XElement lineOne = new XElement(ram + "LineOne"); lineOne.Value = string.IsNullOrEmpty(user.ContactName) ? user.Street : user.ContactName; postalTradeAddress.Add(lineOne); XElement lineTwo = new XElement(ram + "LineTwo"); lineTwo.Value = user.Street; postalTradeAddress.Add(lineTwo); XElement cityName = new XElement(ram + "CityName"); cityName.Value = user.City; postalTradeAddress.Add(cityName); XElement countryID = new XElement(ram + "CountryID"); countryID.Value = user.Country.ToString("g"); postalTradeAddress.Add(countryID); sellerTradeParty.Add(postalTradeAddress); } return sellerTradeParty; } private string ConvertDateFormat(DateTime date, String format = "102") { if (format.Equals("102")) { return date.ToString("yyyymmdd"); } else { return date.ToString("yyyy-MM-ddTHH:mm:ss"); } } private string GetInvoiceTypeName(InvoiceType type) { switch (type) { case InvoiceType.Invoice: return "RECHNUNG"; case InvoiceType.Correction: return "KORREKTURRECHNUNG"; case InvoiceType.CreditNote: return "GUTSCHRIFT"; case InvoiceType.DebitNote: return ""; case InvoiceType.SelfBilledInvoice: return ""; default: return ""; } } private int GetInvoiceTypeCode(InvoiceType type) { if ((int)type > 1000) { type -= 1000; } return (int)type; } private string FormatValue(float value, int numDecimals = 2) { string formatString = "0."; for (int i = 0; i < numDecimals; i++) { formatString += "0"; } return value.ToString(formatString).Replace(",", "."); } } }<file_sep>/Forms/ListView/ListView/Samples/Swiping/Helper/Converter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Syncfusion.ListView.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class SwipingBoolToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return "\ue75e"; else return "\ue758"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class SwipeStartConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is Syncfusion.ListView.XForms.SwipeStartedEventArgs) { var eventArg = value as Syncfusion.ListView.XForms.SwipeStartedEventArgs; return eventArg; } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class SwipeEndConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is Syncfusion.ListView.XForms.SwipeEndedEventArgs) { var eventArg = value as Syncfusion.ListView.XForms.SwipeEndedEventArgs; return eventArg; } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class ImageColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return Color.FromHex("#ffcc00"); else return Color.FromHex("#8c8c8c"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/RenderingDynamicDataViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "RenderingDynamicDataViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for RenderingDynamicData sample. /// </summary> public class RenderingDynamicDataViewModel : INotifyPropertyChanged { #region Members [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<StockData> data; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Random r = new Random(123345345); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int noOfUpdates = 500; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private List<string> stockSymbols = new List<string>(); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] accounts = new string[] { "American Funds", "College Savings", "Day Trading", "Mountain Range", "Fidelity Funds", "Mortages", "Housing Loans" }; #region Constructor /// <summary> /// Initializes a new instance of the RenderingDynamicDataViewModel class. /// </summary> public RenderingDynamicDataViewModel() { this.data = new ObservableCollection<StockData>(); this.AddRows(200); this.ResetRefreshFrequency(2500); } #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion /// <summary> /// Gets the stocks. /// </summary> /// <value>The stocks.</value> public ObservableCollection<StockData> Stocks { get { return this.data; } } /// <summary> /// Gets or sets the value of SelectedItem notifies user when value gets changed /// </summary> public object SelectedItem { get { return this.noOfUpdates; } set { this.noOfUpdates = 2; this.RaisePropertyChanged("SelectedItem"); } } /// <summary> /// Gets the value of ComboCollection /// </summary> public List<int> ComboCollection { get { return new List<int> { 500, 5000, 50000, 500000 }; } } #region Timer and updating code /// <summary> /// Starts the timer. /// </summary> public void StartTimer() { Device.StartTimer( TimeSpan.FromMilliseconds(200), () => { Timer_Tick(); return true; }); } /// <summary> /// Used to reset the refresh frequency /// </summary> /// <param name="changesPerTick">integer type parameter changesPerTick</param> public void ResetRefreshFrequency(int changesPerTick) { this.noOfUpdates = changesPerTick; this.StartTimer(); } /// <summary> /// Handles the Tick event of the timer control. /// </summary> private void Timer_Tick() { int startTime = DateTime.Now.Millisecond; this.noOfUpdates = 100; this.ChangeRows(this.noOfUpdates); } /// <summary> /// Adds the rows. /// </summary> /// <param name="count">The given count.</param> private void AddRows(int count) { for (int i = 0; i < count; ++i) { var newRec = new StockData(); newRec.Symbol = this.ChangeSymbol(); newRec.Account = this.ChangeAccount(i); newRec.Open = Math.Round(this.r.NextDouble() * 30, 2); newRec.LastTrade = Math.Round(1 + (this.r.NextDouble() * 50)); double d = this.r.NextDouble(); if (d < .5) { newRec.StockChange = Math.Round(d, 2); } else { newRec.StockChange = Math.Round(d, 2) * -1; } newRec.PreviousClose = Math.Round(this.r.NextDouble() * 30, 2); newRec.Volume = this.r.Next(); this.data.Add(newRec); } } /// <summary> /// Changes the symbol. /// </summary> /// <returns>returns builder value</returns> private string ChangeSymbol() { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; do { builder = new StringBuilder(); for (int i = 0; i < 4; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor((26 * random.NextDouble()) + 65))); builder.Append(ch); } } while (this.stockSymbols.Contains(builder.ToString())); this.stockSymbols.Add(builder.ToString()); return builder.ToString(); } /// <summary> /// Changes the account. /// </summary> /// <param name="index">The index.</param> /// <returns>returns the get calculated value</returns> private string ChangeAccount(int index) { return this.accounts[index % this.accounts.Length]; } /// <summary> /// Changes the rows. /// </summary> /// <param name="count">The count.</param> private void ChangeRows(int count) { if (this.data.Count < count) { count = this.data.Count; } for (int i = 0; i < count; ++i) { int recNo = this.r.Next(this.data.Count); StockData recRow = this.data[recNo]; this.data[recNo].LastTrade = Math.Round(1 + (this.r.NextDouble() * 50)); double d = this.r.NextDouble(); if (d < .5) { this.data[recNo].StockChange = Math.Round(d, 2); } else { this.data[recNo].StockChange = Math.Round(d, 2) * -1; } this.data[recNo].Open = Math.Round(this.r.NextDouble() * 50, 2); this.data[recNo].PreviousClose = Math.Round(this.r.NextDouble() * 30, 2); this.data[recNo].Volume = this.r.Next(); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type of name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/StripLines/StripLinesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class StripLinesViewModel { public ObservableCollection<ChartDataModel> StripLineData { get; set; } public StripLinesViewModel() { StripLineData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 26), new ChartDataModel("Mon", 24), new ChartDataModel("Tue", 31), new ChartDataModel("Wed", 28), new ChartDataModel("Thu", 30), new ChartDataModel("Fri", 26), new ChartDataModel("Sat", 30) }; } } }<file_sep>/Android/SampleBrowser/Samples/SegmentedView/SegmentViewGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Util; using System; using System.Collections.Generic; using Android.Content; using Android.Views; using Android.Widget; using Android.Content.Res; using Android.Graphics; using Syncfusion.Android.Buttons; namespace SampleBrowser { public class SegmentViewGettingStarted : SamplePage { SfSegmentedControl segmentedView, colorSegmentView, sizeSegmentView; SelectionIndicatorSettings segmentedIndicatorSettings, colorIndicatorSettings, sizeIndicatorSettings; SegementViewViewModel ViewModel; TextView ClothView; private string fontIconText = String.Empty; LinearLayout mainLayout; public SegmentViewGettingStarted() { } public override View GetSampleContent(Context con) { mainLayout = new LinearLayout(con); mainLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); mainLayout.Orientation = Android.Widget.Orientation.Vertical; segmentedIndicatorSettings = new SelectionIndicatorSettings(); colorIndicatorSettings = new SelectionIndicatorSettings(); sizeIndicatorSettings = new SelectionIndicatorSettings(); segmentedView = new SfSegmentedControl(con); colorSegmentView = new SfSegmentedControl(con); sizeSegmentView = new SfSegmentedControl(con); ViewModel = new SegementViewViewModel(con); LinearLayout segementLayout = new LinearLayout(con); segementLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 120); segementLayout.Orientation = Android.Widget.Orientation.Vertical; segementLayout.SetPadding(20, 0, 20, 0); segmentedView.ItemsSource = ViewModel.ClothTypeCollection; segmentedView.SegmentHeight = 100; segmentedView.CornerRadius = 50; segmentedView.SegmentHeight = 35; segmentedView.VisibleSegmentsCount = 3; segmentedView.SelectedIndex = 0; segmentedView.BorderColor = Color.Rgb(63, 63, 63); segmentedView.SelectionTextColor = Color.Rgb(2, 160, 174); segmentedView.FontColor = Color.DarkGray; segmentedView.SelectionIndicatorSettings = new SelectionIndicatorSettings { Color = Color.Transparent }; segmentedView.SelectionChanged += SegmentedView_SelectionChanged; segementLayout.AddView(segmentedView); Typeface tf = Typeface.CreateFromAsset(con.Assets, "Segmented.ttf"); ClothView = new TextView(con); ClothView.Text = "A"; ClothView.TextSize = 115; ClothView.TextAlignment = TextAlignment.Center; ClothView.Gravity = GravityFlags.Center; ClothView.Typeface = tf; ClothView.SetTextColor(Color.ParseColor("#32318E")); ///PriceSegment LinearLayout priceLAyout = new LinearLayout(con); priceLAyout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 150); priceLAyout.Orientation = Android.Widget.Orientation.Vertical; TextView clothText = new TextView(con); clothText.Text = "Best trendy outfits for men."; clothText.TextSize = 12; clothText.SetTextColor(Color.ParseColor("#3F3F3F")); clothText.TextAlignment = TextAlignment.TextStart; clothText.Gravity = GravityFlags.Start; TextView priceText = new TextView(con); priceText.Text = "$300"; priceText.Typeface = Typeface.DefaultBold; priceText.SetTextColor(Color.ParseColor("#3F3F3F")); priceText.TextAlignment = TextAlignment.TextStart; priceText.Gravity = GravityFlags.Start; priceText.TextSize = 12; priceLAyout.SetPadding(20, 0, 0, 0); priceLAyout.AddView(clothText); priceLAyout.AddView(priceText); ///ColorSegment LinearLayout colorSegementLayout = new LinearLayout(con); colorSegementLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 210); colorSegementLayout.Orientation = Android.Widget.Orientation.Vertical; colorSegementLayout.SetPadding(20, 0, 20, 0); TextView colorText = new TextView(con); colorText.Text = "Color"; colorText.Typeface = Typeface.DefaultBold; colorText.TextSize = 12; colorText.TextAlignment = TextAlignment.TextStart; colorText.Gravity = GravityFlags.Start; TextView colorspaceText = new TextView(con); colorspaceText.SetHeight(10); colorSegmentView.ItemsSource = ViewModel.PrimaryColors; colorSegmentView.CornerRadius = 50; colorSegmentView.SegmentHeight = 50; colorSegmentView.SegmentWidth = 70; colorSegmentView.SetBackgroundColor(Color.Transparent); colorSegmentView.BorderColor = Color.ParseColor("#EEEEEE"); colorSegmentView.FontIconFontColor = Color.Black; colorSegmentView.SelectedIndex = 0; colorSegmentView.FontSize = 12; colorSegmentView.VisibleSegmentsCount = 7; colorSegmentView.SegmentCornerRadius = 15; colorSegmentView.SelectionTextColor = Color.ParseColor("#32318E"); colorSegmentView.DisplayMode = SegmentDisplayMode.Image; colorIndicatorSettings.Color = Color.ParseColor("#EEEEEE"); colorIndicatorSettings.Position = SelectionIndicatorPosition.Fill; colorSegmentView.SelectionIndicatorSettings = colorIndicatorSettings; colorSegmentView.SelectionChanged += ColorSegmentView_SelectionChanged; colorSegmentView.SetGravity(GravityFlags.Center); colorSegementLayout.AddView(colorText); colorSegementLayout.AddView(colorspaceText); colorSegementLayout.AddView(colorSegmentView); ///SizeSegment LinearLayout sizeSegementLayout = new LinearLayout(con); sizeSegementLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 240); sizeSegementLayout.Orientation = Android.Widget.Orientation.Vertical; sizeSegementLayout.SetPadding(20, 0, 20, 0); TextView sizeText = new TextView(con); sizeText.Text = "Size"; sizeText.Typeface = Typeface.DefaultBold; sizeText.TextSize = 12; sizeText.TextAlignment = TextAlignment.TextStart; sizeText.Gravity = GravityFlags.Start; TextView sizespaceText = new TextView(con); sizespaceText.SetHeight(10); sizeSegmentView.ItemsSource = ViewModel.SizeCollection; sizeSegmentView.SegmentHeight = 100; sizeSegmentView.CornerRadius = 50; sizeSegmentView.BorderColor = Color.ParseColor("#2C7BBC"); sizeSegmentView.SelectionTextColor = Color.White; sizeSegmentView.DisplayMode = SegmentDisplayMode.Text; sizeSegmentView.VisibleSegmentsCount = 5; sizeSegmentView.SegmentHeight = 40; sizeSegmentView.FontSize = 16; sizeSegmentView.SegmentWidth = 40; sizeSegmentView.FontColor = Color.Black; sizeIndicatorSettings.Color = Color.ParseColor("#2C7BBC"); sizeSegmentView.FontIconFontColor = Color.Black; //sizeIndicatorSettings.CornerRadius = 20; sizeIndicatorSettings.Position = SelectionIndicatorPosition.Fill; sizeSegmentView.SelectionIndicatorSettings = sizeIndicatorSettings; sizeSegementLayout.AddView(sizeText); sizeSegementLayout.AddView(sizespaceText); sizeSegementLayout.AddView(sizeSegmentView); ///DesCription LinearLayout desCriptionLayout = new LinearLayout(con); desCriptionLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 250); desCriptionLayout.Orientation = Android.Widget.Orientation.Vertical; desCriptionLayout.SetPadding(20, 0, 0, 0); TextView descriptionText = new TextView(con); descriptionText.Text = "Description"; descriptionText.Typeface = Typeface.DefaultBold; descriptionText.TextSize = 12; descriptionText.TextAlignment = TextAlignment.TextStart; descriptionText.Gravity = GravityFlags.Start; TextView spaceText = new TextView(con); spaceText.SetHeight(5); TextView detailDescription = new TextView(con); detailDescription.Text = "95 % Polyester, 5 % Spandex, imported, machine wash, casual wear.This outfit keeps you cool and comfortable in quick - dry fabric that wicks away moisture."; detailDescription.TextSize = 12; detailDescription.TextAlignment = TextAlignment.TextStart; detailDescription.Gravity = GravityFlags.Start; desCriptionLayout.AddView(descriptionText); desCriptionLayout.AddView(spaceText); desCriptionLayout.AddView(detailDescription); TextView space = new TextView(con); if (IsTabletDevice(con) == true) { mainLayout.SetPadding(50, 0, 50, 0); descriptionText.TextSize = 16; detailDescription.TextSize = 16; sizeText.TextSize = 16; clothText.TextSize = 16; colorText.TextSize = 16; priceText.TextSize = 16; } if (con.Resources.DisplayMetrics.Density > 3) { segementLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 120*2); priceLAyout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 150 * 2); colorSegementLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 210 *2); sizeSegementLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 240 * 2); desCriptionLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 250 *2); } mainLayout.AddView(space); mainLayout.AddView(segementLayout); mainLayout.AddView(ClothView); mainLayout.AddView(priceLAyout); mainLayout.AddView(colorSegementLayout); mainLayout.AddView(sizeSegementLayout); mainLayout.AddView(desCriptionLayout); return mainLayout; } public static bool IsTabletDevice(Android.Content.Context context) { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = Math.Sqrt(Math.Pow(screenWidth, 2) + Math.Pow(screenHeight, 2)); return size >= 6; } void SegmentedView_SelectionChanged(object sender, SelectionChangedEventArgs e) { var index = e.Index; if (index == 0) { fontIconText = "A"; } else if (index == 1) { fontIconText = "B"; } else { fontIconText = "C"; } this.ClothView.Text = fontIconText; } void ColorSegmentView_SelectionChanged(object sender, SelectionChangedEventArgs e) { this.colorSegmentView.SelectionTextColor = ViewModel.PrimaryColors[e.Index].FontIconFontColor; this.ClothView.SetTextColor(ViewModel.PrimaryColors[e.Index].FontIconFontColor); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataForm/Model/ContactInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using Syncfusion.iOS.DataForm; namespace SampleBrowser { public class ContactInfo : INotifyPropertyChanged { #region Fields private string contactName; private string middelName; private string lastname; private string contactNo; private UIImage image; private ContactsType contactType; private ContactsType emailType; private string email; private AddressType addressType; private string address; private DateTime birthDate; private string groupName; private Save saveTo; #endregion #region Constructor public ContactInfo() { } #endregion #region Public Properties [DisplayOptions(ImageSource = "LabelContactName.png", ColumnSpan = 2)] [Display(Prompt = "First Name", GroupName = "Name")] public string ContactName { get { return this.contactName; } set { this.contactName = value; RaisePropertyChanged("ContactName"); } } [DisplayOptions(ShowLabel = false)] [Display(Prompt = "Middle Name", GroupName = "Name")] public string MiddleName { get { return this.middelName; } set { this.middelName = value; RaisePropertyChanged("MiddleName"); } } [DisplayOptions(ShowLabel = false)] [Display(Prompt = "Last Name", GroupName = "Name")] public string LastName { get { return this.lastname; } set { this.lastname = value; RaisePropertyChanged("LastName"); } } [DisplayOptions(ImageSource = "Phone.png")] [Display(Prompt = "Phone")] [StringLength(10, ErrorMessage = "Phone number should not exceed 10 digits.")] public string ContactNumber { get { return contactNo; } set { this.contactNo = value; RaisePropertyChanged("ContactNumber"); } } [DisplayOptions(ShowLabel = false)] public ContactsType ContactType { get { return contactType; } set { this.contactType = value; RaisePropertyChanged("ContactType"); } } [Display(AutoGenerateField = false)] public UIImage ContactImage { get { return this.image; } set { this.image = value; this.RaisePropertyChanged("ContactImage"); } } [DisplayOptions(ImageSource = "Email.png")] [Display(Prompt = "Email")] public string Email { get { return email; } set { email = value; this.RaisePropertyChanged("Email"); } } [DisplayOptions(ShowLabel = false)] public ContactsType EmailType { get { return emailType; } set { emailType = value; this.RaisePropertyChanged("EmailType"); } } [DisplayOptions(ImageSource = "Address.png")] [Display(Prompt = "Address")] public string Address { get { return address; } set { address = value; this.RaisePropertyChanged("Address"); } } [DisplayOptions(ShowLabel = false)] public AddressType AddressTypes { get { return addressType; } set { addressType = value; this.RaisePropertyChanged("AddressType"); } } [DisplayOptions(ImageSource = "BirthDate.png", ColumnSpan = 2)] [Display(Prompt = "Birth Date")] public DateTime BirthDate { get { return birthDate; } set { birthDate = value; this.RaisePropertyChanged("BirthDate"); } } [DisplayOptions(ImageSource = "Group.png", ColumnSpan = 2)] [Display(Prompt = "Group")] public string GroupName { get { return groupName; } set { groupName = value; this.RaisePropertyChanged("GroupName"); } } [DisplayOptions(ColumnSpan = 2)] [Display(Prompt = "Save To", ShortName = "Save To")] public Save SaveTo { get { return saveTo; } set { saveTo = value; this.RaisePropertyChanged("SaveTo"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion public enum ContactsType { Home, Work, Mobile, Other, Business }; public enum AddressType { Home, Office }; public enum Save { Sim, Phone } } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/OnBoardHelps/DragAndDropBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DragAndDropBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using Xamarin.Forms; /// <summary> /// Drag and drop Behavior class performs drag and drop animation. /// </summary> public class DragAndDropBehavior : Behavior<Image> { /// <summary> /// Holds the hand symbol of the drag and drop layout. /// </summary> private Image handSymbol; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="image">Image which is attached.</param> protected override void OnAttachedTo(Image image) { base.OnAttachedTo(image); this.handSymbol = image; this.AnimateDragAndDropIllustration(); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="image">Image which is attached.</param> protected override void OnDetachingFrom(Image image) { base.OnDetachingFrom(image); this.handSymbol = null; } /// <summary> /// used to animate drag and drop image illustration. /// </summary> private async void AnimateDragAndDropIllustration() { this.handSymbol.AnchorY = 10; //// Rotate View to 10 degree await this.handSymbol.RotateTo(10, 500); ////transalte View to based on x, y point await this.handSymbol.TranslateTo(25, 25, 500); ////Reset rotaion,x,y position this.handSymbol.Rotation = 0; await this.handSymbol.TranslateTo(0, 0, 0); this.AnimateDragAndDropIllustration(); } } } <file_sep>/Forms/XlsIO/XlsIO/Samples/ImportCollectionObjectsPage/ImportCollectionObjectsPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using System.Xml.Linq; using COLOR = Syncfusion.Drawing; using SampleBrowser.Core; using Syncfusion.SfDataGrid; using Syncfusion.SfDataGrid.XForms; using Syncfusion.XlsIO; using Xamarin.Forms; namespace SampleBrowser.XlsIO { /// <summary> /// This class allows you to import/export data from/to Collection Objects. /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public partial class ImportCollectionObjectsPage : SampleView { private ExportingViewModel exportViewModel; public ImportCollectionObjectsPage(ExportingViewModel viewModel) { exportViewModel = viewModel; } public ImportCollectionObjectsPage() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && (Device.RuntimePlatform == Device.UWP)) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInput.BackgroundColor = Color.Gray; this.btnImport.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; } this.Content_1.VerticalOptions = LayoutOptions.Center; } if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.iOS) { this.dataGrid.DefaultColumnWidth = 120; } else { this.dataGrid.DefaultColumnWidth = 160; } } internal void OnInputClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; // Initializing Workbook Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = null; #if COMMONSB fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ExportData.xlsx"); #else fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ExportData.xlsx"); #endif IWorkbook workbook = application.Workbooks.Open(fileStream); workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.xlsx", "application/msexcel", stream); } } internal void OnImportClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; // Initializing Workbook Assembly assembly = typeof(App).GetTypeInfo().Assembly; Stream fileStream = null; #if COMMONSB fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ExportData.xlsx"); #else fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ExportData.xlsx"); #endif IWorkbook workbook = application.Workbooks.Open(fileStream); workbook.Version = ExcelVersion.Excel2013; IWorksheet sheet = workbook.Worksheets[0]; Dictionary<string, string> mappingProperties = new Dictionary<string, string>(); mappingProperties.Add("Brand", "BrandName"); mappingProperties.Add("Vehicle Type", "VehicleType.VehicleName"); mappingProperties.Add("Model", "VehicleType.Model.ModelName"); List<Brand> clrObjects = sheet.ExportData<Brand>(4, 1, 141, 3, mappingProperties); dataGrid.ItemsSource = clrObjects; this.btnGenerate.IsEnabled = true; workbook.Close(); excelEngine.Dispose(); } internal void OnExportClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; //Initializing Workbook //A new workbook is created.[Equivalent to creating a new workbook in MS Excel] //The new workbook will have 1 worksheets IWorkbook workbook = application.Workbooks.Create(1); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; sheet.ImportData((List<Brand>)dataGrid.ItemsSource, 4, 1, true); #region Define Styles IStyle pageHeader = workbook.Styles.Add("PageHeaderStyle"); IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle"); pageHeader.Font.FontName = "Calibri"; pageHeader.Font.Size = 16; pageHeader.Font.Bold = true; pageHeader.Color = Syncfusion.Drawing.Color.FromArgb(0, 146, 208, 80); pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter; pageHeader.VerticalAlignment = ExcelVAlign.VAlignCenter; tableHeader.Font.Bold = true; tableHeader.Font.FontName = "Calibri"; tableHeader.Color = Syncfusion.Drawing.Color.FromArgb(0, 146, 208, 80); #endregion #region Apply Styles // Apply style for header sheet["A1:C2"].Merge(); sheet["A1"].Text = "Automobile Brands in the US"; sheet["A1"].CellStyle = pageHeader; sheet["A4:C4"].CellStyle = tableHeader; sheet["A1:C1"].CellStyle.Font.Bold = true; sheet.UsedRange.AutofitColumns(); #endregion // Saving workbook and disposing objects workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (Device.RuntimePlatform == Device.UWP) { Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("CollectionObjects.xlsx", "application/msexcel", stream); } else { Xamarin.Forms.DependencyService.Get<ISave>().Save("CollectionObjects.xlsx", "application/msexcel", stream); } } } /// <summary> /// Provides the implementation for ExportToDataGrid View Model /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public class ExportingViewModel : INotifyPropertyChanged { private bool isDataGridExported; public bool IsDataGridExported { get { return isDataGridExported; } set { isDataGridExported = value; RaisePropertyChanged("IsDataGridExported"); } } public ExportingViewModel() { CustomersInfo = new List<Brand>(); foreach (int i in Enumerable.Range(1, 20)) { CustomersInfo.Add(new Brand()); } } #region ItemsSource private List<Brand> customersInfo; public List<Brand> CustomersInfo { get { return customersInfo; } set { this.customersInfo = value; RaisePropertyChanged("CustomersInfo"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string name) { if (PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } /// <summary> /// Class used to store the customer details /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] public class CustomerObject : INotifyPropertyChanged { public CustomerObject() { } #region private variables private string salesPerson; private int salesJanJune; private int salesJulyDec; private int change; #endregion #region Public Properties public string SalesPerson { get { return salesPerson; } set { this.salesPerson = value; RaisePropertyChanged("SalesPerson"); } } public int SalesJanJune { get { return salesJanJune; } set { this.salesJanJune = value; RaisePropertyChanged("SalesJanJune"); } } public int SalesJulyDec { get { return salesJulyDec; } set { this.salesJulyDec = value; RaisePropertyChanged("SalesJulyDec"); } } public int Change { get { return change; } set { this.change = value; RaisePropertyChanged("Change"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string name) { if (PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } public class Brand { private int m_Id; [Bindable(false)] public int ID { get { return m_Id; } set { m_Id = value; } } private string m_brandName; [DisplayNameAttribute("Brand")] public string BrandName { get { return m_brandName; } set { m_brandName = value; } } private VehicleType m_vehicleType; public VehicleType VehicleType { get { return m_vehicleType; } set { m_vehicleType = value; } } public Brand(string brandName) { m_brandName = brandName; } public Brand() { } } public class VehicleType { private string m_vehicleName; [DisplayNameAttribute("Vehicle Type")] public string VehicleName { get { return m_vehicleName; } set { m_vehicleName = value; } } private Model m_model; public Model Model { get { return m_model; } set { m_model = value; } } public VehicleType(string vehicle) { m_vehicleName = vehicle; } public VehicleType() { } } public class Model { private string m_modelName; [DisplayNameAttribute("Model")] public string ModelName { get { return m_modelName; } set { m_modelName = value; } } public Model(string name) { m_modelName = name; } public Model() { } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/UnboundColumn.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Syncfusion.SfDataGrid; using Syncfusion.SfDataGrid.Renderers; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using UIKit; namespace SampleBrowser { class UnboundColumn: SampleView { #region Fields SfDataGrid SfGrid; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public UnboundColumn () { this.SfGrid = new SfDataGrid (); this.SfGrid.ColumnSizer = ColumnSizer.Auto; this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.AutoGenerateColumns = false; this.SfGrid.ItemsSource = new UnboundViewModel ().Products; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.GridStyle = new Blue(); this.SfGrid.AllowResizingColumn = true; this.SfGrid.GridStyle = new CustomGridStyle(); SfGrid.CellRenderers.Remove("Unbound"); SfGrid.CellRenderers.Add("Unbound", new UnboundColumnRenderer()); SfGrid.CellRenderers.Remove("TextView"); SfGrid.CellRenderers.Add("TextView", new TextRenderer()); GridTextColumn ProductName = new GridTextColumn(); ProductName.HeaderText = "Product Name"; ProductName.LineBreakMode = UILineBreakMode.WordWrap; ProductName.TextAlignment = UITextAlignment.Left; ProductName.HeaderTextAlignment = UITextAlignment.Center; //ProductName.HeaderCellTextSize = 12; ProductName.MappingName = "ProductName"; SfGrid.Columns.Add(ProductName); GridTextColumn UnitPrice = new GridTextColumn(); UnitPrice.HeaderText = "Price"; UnitPrice.Format = "C"; UnitPrice.HeaderTextAlignment = UITextAlignment.Center; //UnitPrice.HeaderCellTextSize = 12; UnitPrice.TextAlignment = UITextAlignment.Center; UnitPrice.MappingName = "UnitPrice"; SfGrid.Columns.Add(UnitPrice); GridTextColumn Quantity = new GridTextColumn(); Quantity.HeaderText = "Quantity"; Quantity.HeaderTextAlignment = UITextAlignment.Center; //Quantity.HeaderCellTextSize = 12; Quantity.MappingName = "Quantity"; Quantity.TextAlignment = UITextAlignment.Center; SfGrid.Columns.Add(Quantity); GridTextColumn Discount = new GridTextColumn(); Discount.TextAlignment = UITextAlignment.Center; Discount.HeaderText = "Discount"; Discount.HeaderTextAlignment = UITextAlignment.Center; Discount.HeaderCellTextSize = UIFont.SystemFontOfSize(12); Discount.TextAlignment = UITextAlignment.Center; Discount.MappingName = "Discount"; SfGrid.Columns.Add(Discount); GridUnboundColumn Total = new GridUnboundColumn(); Total.TextAlignment = UITextAlignment.Center; Total.Expression = "(Quantity * UnitPrice) - ((Quantity * UnitPrice)/100 * Quantity)"; Total.Format = "C"; Total.HeaderText = "Total"; Total.TextAlignment = UITextAlignment.Center; Total.MappingName = "Total"; SfGrid.Columns.Add(Total); foreach (GridColumn column in SfGrid.Columns) { if (UserInterfaceIdiomIsPhone) SfGrid.ColumnSizer = ColumnSizer.None; else SfGrid.ColumnSizer = ColumnSizer.Star; } this.AddSubview (SfGrid); } public override void LayoutSubviews() { this.SfGrid.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { SfGrid.Dispose(); base.Dispose(disposing); } } public class UnboundColumnRenderer : GridUnboundCellTextBoxRenderer { public UnboundColumnRenderer() { } public override void OnInitializeDisplayView(DataColumnBase dataColumn, UILabel view) { base.OnInitializeDisplayView(dataColumn, view); var gridcell = dataColumn.GetType().GetRuntimeProperties().FirstOrDefault(x => x.Name.Equals("Element")).GetValue(dataColumn); (gridcell as UIView).BackgroundColor = UIColor.FromRGB(225, 245, 254); } } public class TextRenderer: GridCellTextViewRenderer { public TextRenderer() { } public override void OnInitializeDisplayView(DataColumnBase dataColumn, UILabel view) { base.OnInitializeDisplayView(dataColumn, view); var gridcell = dataColumn.GetType().GetRuntimeProperties().FirstOrDefault(x => x.Name.Equals("Element")).GetValue(dataColumn); (gridcell as UIView).BackgroundColor = UIColor.White; } } } <file_sep>/Forms/Schedule/Schedule/Samples/ViewCustomization/HelperClass/MonthCellDataTemplateSelector.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Month Cell Data Template Selector class /// </summary> public class MonthCellDataTemplateSelector : DataTemplateSelector { /// <summary> /// Initializes a new instance of the <see cref="MonthCellDataTemplateSelector" /> class. /// </summary> public MonthCellDataTemplateSelector() { this.MonthAppointmentTemplate = new DataTemplate(typeof(MonthAppointmentTemplate)); this.MonthCellDatesTemplate = new DataTemplate(typeof(MonthCellDatesTemplate)); } /// <summary> /// Gets or sets Month Appointment Template /// </summary> public DataTemplate MonthAppointmentTemplate { get; set; } /// <summary> /// Gets or sets Month Cell Dates Template /// </summary> public DataTemplate MonthCellDatesTemplate { get; set; } /// <summary> /// Template selection method /// </summary> /// <param name="item">return the object</param> /// <param name="container">return the bindable object</param> /// <returns>return the template</returns> protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { var sfSchedule = container as Syncfusion.SfSchedule.XForms.SfSchedule; if (sfSchedule == null) { return null; } if (sfSchedule != null) { var appointments = (IList)(item as MonthCellItem).Appointments; foreach (var appointment in appointments) { CustomizationViewModel.ScheduleAppointment = appointment as ScheduleAppointment; return this.MonthAppointmentTemplate; } CustomizationViewModel.MonthCellItem = item as MonthCellItem; return this.MonthCellDatesTemplate; } else { return null; } } } }<file_sep>/Forms/NumericTextBox/NumericTextBox.Android/CustomNumericBoxRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser.SfNumericTextBox; using SampleBrowser.SfNumericTextBox.Droid; using Syncfusion.SfNumericTextBox.XForms.Droid; using Xamarin.Forms; [assembly: ExportRenderer(typeof(NumericTextBoxRenderer), typeof(CustomNumericBoxRenderer))] namespace SampleBrowser.SfNumericTextBox.Droid { public class CustomNumericBoxRenderer : SfNumericTextBoxRenderer { public CustomNumericBoxRenderer() { } protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Syncfusion.SfNumericTextBox.XForms.SfNumericTextBox> e) { base.OnElementChanged(e); if (e.NewElement != null) { Control.SetBackgroundResource(0); } } } } <file_sep>/Forms/PdfViewer/PdfViewer.Droid/SaveAndroid.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Content.Res; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Xamarin.Forms; [assembly:Dependency(typeof(SampleBrowser.SfPdfViewer.Droid.SaveAndroid))] [assembly:Dependency(typeof(SampleBrowser.SfPdfViewer.Droid.DeviceInfo))] [assembly: Dependency(typeof(SampleBrowser.SfPdfViewer.Droid.BrowserURI))] namespace SampleBrowser.SfPdfViewer.Droid { public class SaveAndroid : ISave { public string Save(MemoryStream stream) { string root = null; string fileName = "SavedDocument.pdf"; if (Android.OS.Environment.IsExternalStorageEmulated) { #pragma warning disable CS0618 // Type or member is obsolete root = Android.OS.Environment.ExternalStorageDirectory.ToString(); #pragma warning restore CS0618 // Type or member is obsolete } Java.IO.File myDir = new Java.IO.File(root + "/Syncfusion"); myDir.Mkdir(); Java.IO.File file = new Java.IO.File(myDir, fileName); string filePath = file.Path; if (file.Exists()) file.Delete(); Java.IO.FileOutputStream outs = new Java.IO.FileOutputStream(file); outs.Write(stream.ToArray()); var ab = file.Path; outs.Flush(); outs.Close(); return filePath; } } public class BrowserURI : IDeviceOpenURI { public void OpenURI(string selectedText) { String escapedQuery = Java.Net.URLEncoder.Encode(selectedText, "UTF-8"); var uri = Android.Net.Uri.Parse($"https://www.google.com/search?q={escapedQuery}"); var intent = new Intent(Intent.ActionView, uri); intent.AddFlags(ActivityFlags.NewTask); intent.AddFlags(ActivityFlags.MultipleTask); Android.App.Application.Context.StartActivity(intent); } } public class DeviceInfo : IDeviceInfo { public ScreenSize GetScreenSize() { if ((Resources.System.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeNormal) return ScreenSize.Normal; else if ((Resources.System.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeLarge) return ScreenSize.Large; else if ((Resources.System.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeSmall) return ScreenSize.Small; else if ((Resources.System.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeXlarge) return ScreenSize.Small; return ScreenSize.Normal; } } }<file_sep>/Forms/PopupLayout/PopupLayout/Samples/ViewModel/SwipingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SwipingViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A ViewModel for Swiping sample. /// </summary> public class SwipingViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// Holds the instance of the repository. /// </summary> private OrderInfoRepository order; /// <summary> /// backing field for OrdersInfo collection. /// </summary> private ObservableCollection<OrderInfo> ordersInfo; /// <summary> /// backing field for the DeleteCommand. /// </summary> private Command<OrderInfo> deleteCommand; #endregion #region Constructor /// <summary> /// Initializes a new instance of the SwipingViewModel class. /// </summary> public SwipingViewModel() { this.SetRowstoGenerate(100); this.DeleteCommand = new Command<OrderInfo>(this.DeleteRowData); } #endregion #region Events /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Properties /// <summary> /// Gets or sets the Command that is executed when Delete is clicked. /// </summary> public Command<OrderInfo> DeleteCommand { get { return this.deleteCommand; } set { this.deleteCommand = value; this.RaisePropertyChanged("DeleteCommand"); } } #region ItemsSource /// <summary> /// Gets or sets the OrdersInfo and notifies when user value gets changed. /// </summary> public ObservableCollection<OrderInfo> OrdersInfo { get => this.ordersInfo; set { this.ordersInfo = value; this.RaisePropertyChanged("OrdersInfo"); } } #endregion #endregion #region ItemSource Generator /// <summary> /// Generates Rows with given count /// </summary> /// <param name="count">integer type of parameter named as count</param> public void SetRowstoGenerate(int count) { this.order = new OrderInfoRepository(); this.ordersInfo = this.order.GetOrderDetails(count); } #endregion #region Private Methods /// <summary> /// Deletes the row data. /// </summary> /// <param name="bindingObject">The binding object.</param> private void DeleteRowData(OrderInfo bindingObject) { this.OrdersInfo.Remove(bindingObject); } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Android/SampleBrowser/Samples/DataSource/DataSourceGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.DataSource; using System.Reflection; using Android.Graphics; using Syncfusion.Data; namespace SampleBrowser { public class DataSourceGettingStarted : SamplePage, IDisposable { private DataSource dataSource; private DataSourceGettingStartedViewModel viewModel; private SearchView filterText; private Spinner conditionDropdown; private Spinner columnDropdown; private ArrayAdapter condtionAdapter; private GridLayout gridlayout; private TextView conditionTextView; private TextView columnTextView; private TextView groupTextView; private ListView listView; public override Android.Views.View GetSampleContent(Android.Content.Context context) { LinearLayout linear = new LinearLayout(context); linear.Orientation = Orientation.Vertical; dataSource = new DataSource(); viewModel = new DataSourceGettingStartedViewModel(context); viewModel.SetRowstoGenerate(100); listView = new ListView(context); dataSource.Source = viewModel.BookInfo; dataSource.LiveDataUpdateMode = Syncfusion.DataSource.LiveDataUpdateMode.AllowDataShaping; dataSource.SortDescriptors.Add(new SortDescriptor() { Direction = Syncfusion.DataSource.ListSortDirection.Descending, PropertyName = "BookID", }); listView.Adapter = new CustomAdapter(dataSource, context); filterText = new SearchView(context); filterText.SetIconifiedByDefault(false); filterText.SetPadding(0, 0, 0, (int)(10 * context.Resources.DisplayMetrics.Density)); this.filterText.KeyPress += FilterText_KeyPress; filterText.SetQueryHint("Enter the text to filter"); filterText.QueryTextChange += OnFilterTextChanged; viewModel.Filtertextchanged = OnFilterChanged; linear.AddView(new LinearLayout(context) { Focusable = true, FocusableInTouchMode = true }, 0, 0); linear.AddView(filterText); linear.AddView(listView); return linear; } private void FilterText_KeyPress(object sender, View.KeyEventArgs e) { listView.RemoveAllViews(); } public override View GetPropertyWindowLayout(Android.Content.Context context) { gridlayout = new GridLayout(context); gridlayout.SetPadding(20, 20, 20, 20); gridlayout.RowCount = 2; gridlayout.ColumnCount = 2; conditionTextView = new TextView(context); conditionTextView.Text = "Select the condition to filter"; columnTextView = new TextView(context); columnTextView.Text = "Select the column to filter"; groupTextView = new TextView(context); groupTextView.Text = "Group by"; columnDropdown = new Spinner(context, SpinnerMode.Dialog); var columnAdapter = new ArrayAdapter(context, Android.Resource.Layout.SimpleSpinnerItem); var properties = typeof(BookDetails).GetProperties(); columnAdapter.Add("All Columns"); foreach (var propertyInfo in properties) { if (propertyInfo.Name != "CustomerImage") { columnAdapter.Add(propertyInfo.Name); } } columnAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); columnDropdown.Adapter = columnAdapter; conditionDropdown = new Spinner(context, SpinnerMode.Dialog); condtionAdapter = new ArrayAdapter(context, Android.Resource.Layout.SimpleSpinnerItem); condtionAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); conditionDropdown.Adapter = condtionAdapter; columnDropdown.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(OnColumnSelected); conditionDropdown.ItemSelected += OnConditionSelected; gridlayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent); gridlayout.AddView(columnTextView, LinearLayout.LayoutParams.WrapContent, (int)(30 * context.Resources.DisplayMetrics.Density)); gridlayout.AddView(columnDropdown); gridlayout.AddView(conditionTextView, LinearLayout.LayoutParams.WrapContent, (int)(30 * context.Resources.DisplayMetrics.Density)); gridlayout.AddView(conditionDropdown); return gridlayout; } private void OnColumnSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner newSpinner = (Spinner)sender; viewModel.SelectedColumn = newSpinner.GetItemAtPosition(e.Position).ToString(); if (viewModel.SelectedColumn == "All Columns") { conditionDropdown.Visibility = ViewStates.Gone; conditionTextView.Visibility = ViewStates.Gone; } else { conditionDropdown.Visibility = ViewStates.Visible; conditionTextView.Visibility = ViewStates.Visible; var prop = typeof(BookDetails).GetProperty(viewModel.SelectedColumn); if (prop.Name == viewModel.SelectedColumn) { if (prop.PropertyType == typeof(string)) { condtionAdapter.Clear(); condtionAdapter.Add("Equals"); condtionAdapter.Add("Contains"); if (this.viewModel.SelectedCondition == "Equals") { this.viewModel.SelectedCondition = "Equals"; } else { this.viewModel.SelectedCondition = "Contains"; } } else { condtionAdapter.Clear(); condtionAdapter.Add("Equals"); condtionAdapter.Add("NotEquals"); if (this.viewModel.SelectedCondition == "Equals") { this.viewModel.SelectedCondition = "Equals"; } else { this.viewModel.SelectedCondition = "NotEquals"; } } } } if (string.IsNullOrEmpty(filterText.Query)) { this.OnFilterChanged(); } } private void OnFilterChanged() { if (dataSource != null) { this.dataSource.Filter = viewModel.FilerRecords; this.dataSource.RefreshFilter(); } } private void OnFilterTextChanged(object sender, SearchView.QueryTextChangeEventArgs e) { viewModel.FilterText = (sender as SearchView).Query.ToString(); } private void OnConditionSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner newSpinner = (Spinner)sender; viewModel.SelectedCondition = newSpinner.GetItemAtPosition(e.Position).ToString(); if (string.IsNullOrEmpty(filterText.Query)) { this.OnFilterChanged(); } } public override void Destroy() { dataSource.Dispose(); conditionDropdown = null; columnDropdown = null; filterText = null; columnTextView = null; conditionTextView = null; dataSource = null; viewModel = null; condtionAdapter = null; gridlayout.RemoveAllViews(); gridlayout = null; } public void Dispose() { if (dataSource != null) { dataSource.Dispose(); dataSource = null; } if (conditionDropdown != null) { conditionDropdown.Dispose(); conditionDropdown = null; } if (columnDropdown != null) { columnDropdown.Dispose(); columnDropdown = null; } if (filterText != null) { filterText.Dispose(); filterText = null; } if (columnTextView != null) { columnTextView.Dispose(); columnTextView = null; } if (conditionTextView != null) { conditionTextView.Dispose(); conditionTextView = null; } if (condtionAdapter != null) { condtionAdapter.Dispose(); condtionAdapter = null; } if (gridlayout != null) { gridlayout.Dispose(); gridlayout = null; } if (columnDropdown != null) { columnDropdown.Dispose(); columnDropdown = null; } if (groupTextView != null) { groupTextView.Dispose(); groupTextView = null; } if (listView != null) { listView.Dispose(); listView = null; } if (filterText != null) { filterText.Dispose(); filterText = null; } } } }<file_sep>/Forms/ListView/ListView.UWP/DataTemplateRenderer/OutgoingCustomContentViewRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.SfListView.UWP; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Xamarin.Forms.Platform.UWP; using Xamarin.Forms; [assembly: ExportRenderer(typeof(SampleBrowser.SfListView.OutgoingCustomContentView), typeof(OutgoingCustomContentViewRenderer))] namespace SampleBrowser.SfListView.UWP { #region OutgoingCustomContentViewRenderer public class OutgoingCustomContentViewRenderer : VisualElementRenderer<OutgoingCustomContentView, Border> { Border border; protected override void OnElementChanged(ElementChangedEventArgs<OutgoingCustomContentView> e) { base.OnElementChanged(e); if (e.NewElement != null) { border = new Border(); border.BorderThickness = new Windows.UI.Xaml.Thickness(2); border.Background = new Windows.UI.Xaml.Media.SolidColorBrush(Windows.UI.Color.FromArgb(255, 229, 245, 251)); border.CornerRadius = new Windows.UI.Xaml.CornerRadius(8); border.Margin = new Windows.UI.Xaml.Thickness(-2); this.SetNativeControl(border); Canvas.SetZIndex(border, -1); } } } #endregion } <file_sep>/iOS/SampleBrowser/Resources/Samples/TabView/TemplateView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using UIKit; namespace SampleBrowser { internal class TemplateView : UIView { UIImageView imageView; UILabel imageLabel; UILabel ratingLabel; UILabel ratingTextLabel; UILabel priceLabel; UILabel offerLabel; UILabel descriptionLabel; UIView ratingView; public TemplateView() { this.BackgroundColor = UIColor.White; imageView = new UIImageView(); imageView.BackgroundColor = UIColor.Red; imageLabel = new UILabel(); imageLabel.LineBreakMode = UILineBreakMode.WordWrap; imageLabel.Lines = 2; imageLabel.Font = UIFont.SystemFontOfSize(17); ratingView = new UIView(); ratingView.Layer.CornerRadius = 9; ratingView.ClipsToBounds = true; ratingView.BackgroundColor = UIColor.FromRGB(77, 146, 223); ratingLabel = new UILabel(); ratingLabel.TextColor = UIColor.White; ratingLabel.Text = "\uE735"; ratingLabel.TextAlignment = UITextAlignment.Center; ratingLabel.Font = UIFont.FromName("Segoe MDL2 Assets", 10); ratingTextLabel = new UILabel(); ratingTextLabel.TextColor = UIColor.White; ratingTextLabel.TextAlignment = UITextAlignment.Center; ratingTextLabel.Font = UIFont.SystemFontOfSize(10); ratingView.Add(ratingLabel); ratingView.Add(ratingTextLabel); descriptionLabel = new UILabel(); descriptionLabel.LineBreakMode = UILineBreakMode.WordWrap; descriptionLabel.Lines = 10; descriptionLabel.TextColor = UIColor.FromRGB(134, 134, 134); descriptionLabel.Font = UIFont.SystemFontOfSize((nfloat)8.5); priceLabel = new UILabel(); priceLabel.TextColor = UIColor.FromRGB(128, 207, 53); ; priceLabel.LineBreakMode = UILineBreakMode.WordWrap; priceLabel.Font = UIFont.SystemFontOfSize((nfloat)13); offerLabel = new UILabel(); offerLabel.TextColor = UIColor.FromRGB(128, 207, 53); offerLabel.LineBreakMode = UILineBreakMode.WordWrap; offerLabel.Font = UIFont.SystemFontOfSize((nfloat)13); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { imageLabel.Font = UIFont.SystemFontOfSize(22); priceLabel.Font = UIFont.SystemFontOfSize(18); offerLabel.Font = UIFont.SystemFontOfSize(18); descriptionLabel.Font = UIFont.SystemFontOfSize(14); descriptionLabel.LineBreakMode = UILineBreakMode.WordWrap; descriptionLabel.Lines = 3; } Add(imageView); Add(imageLabel); Add(ratingView); Add(priceLabel); Add(offerLabel); Add(descriptionLabel); } public override void LayoutSubviews() { if(this.Frame.Width > 0 && this.Frame.Height > 0) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { imageView.Frame = new CGRect(10, 10, 150, 140); imageLabel.Frame = new CGRect(168, 0, 550, 50); ratingView.Frame = new CGRect(375, 49, 35, 20); priceLabel.Frame = new CGRect(168, 49, 275, 20); offerLabel.Frame = new CGRect(270, 49, 275, 20); descriptionLabel.Frame = new CGRect(168, 69, 570, 85); ratingLabel.Frame = new CGRect(0, 0, 15, ratingView.Frame.Height); ratingTextLabel.Frame = new CGRect(8, 0, 30, ratingView.Frame.Height); } else { imageView.Frame = new CGRect(10, 10, 150, 140); imageLabel.Frame = new CGRect(168, 0, 90, 50); ratingView.Frame = new CGRect(this.Frame.Width / 2 + 110, 5, 35, 20); priceLabel.Frame = new CGRect(168, 49, 53, 20); offerLabel.Frame = new CGRect(235, 49, 80, 20); descriptionLabel.Frame = new CGRect(168, 69, 125, 85); ratingLabel.Frame = new CGRect(0, 0, 15, ratingView.Frame.Height); ratingTextLabel.Frame = new CGRect(8, 0, 30, ratingView.Frame.Height); } } base.LayoutSubviews(); } internal void UpdateContent(string image, string title, string price, string offer, string rating,string description) { imageView.Image = UIImage.FromBundle(image); imageLabel.Text = title; priceLabel.Text = price; offerLabel.Text = offer+" Offer"; ratingTextLabel.Text = rating; descriptionLabel.Text = description; } } } <file_sep>/Android/SampleBrowser/Samples/DocIO/MarkdownToWord.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.Compression; using Syncfusion.OfficeChart; using Syncfusion.DocIORenderer; using Syncfusion.Office; using Syncfusion.Pdf; using System.IO; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Webkit; using Android.App; using Android.OS; namespace SampleBrowser { public partial class MarkdownToWord : SamplePage { private Context m_context; RadioGroup radioGroup; RadioButton docxButton; RadioButton pdfButton; RadioButton htmlButton; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to convert the Markdown file to Word document using .NET Word (DocIO) library."; text1.SetPadding(5, 10, 10, 5); linear.AddView(text1); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; LinearLayout radioLinearLayout = new LinearLayout(con); radioLinearLayout.Orientation = Orientation.Horizontal; TextView imageType = new TextView(con); imageType.Text = "Save As : "; imageType.TextSize = 19; radioLinearLayout.AddView(imageType); radioGroup = new RadioGroup(con); radioGroup.TextAlignment = TextAlignment.Center; radioGroup.Orientation = Orientation.Horizontal; docxButton = new RadioButton(con); docxButton.Text = "DOCX"; radioGroup.AddView(docxButton); htmlButton = new RadioButton(con); htmlButton.Text = "HTML"; radioGroup.AddView(htmlButton); pdfButton = new RadioButton(con); pdfButton.Text = "PDF"; radioGroup.AddView(pdfButton); radioGroup.Check(1); radioLinearLayout.AddView(radioGroup); linear.AddView(radioLinearLayout); docxButton.Checked = true; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Document"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.DocIO.Templates.MarkdownToWord.md"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); // Loads the stream into Word Document. WordDocument document = new WordDocument(fileStream, Syncfusion.DocIO.FormatType.Markdown); MemoryStream stream = new MemoryStream(); //Set file content type string contentType = null; string fileName = null; //Save the document as .html if (htmlButton.Checked) { fileName = "MarkdownToWord.html"; contentType = "application/html"; document.Save(stream, FormatType.Html); } //Save the document as .Pdf else if(pdfButton.Checked) { fileName = "MarkdownToWord.pdf"; contentType = "application/pdf"; //Convert the word document to PDF. DocIORenderer renderer = new DocIORenderer(); PdfDocument pdfDoc = renderer.ConvertToPDF(document); pdfDoc.Save(stream); pdfDoc.Close(); } //Save the document as .docx else { fileName = "MarkdownToWord.docx"; contentType = "application/msword"; document.Save(stream, FormatType.Docx); } document.Dispose(); if (contentType == "application/html" && stream != null) { //Set the stream to start position to read the content as string stream.Position = 0; StreamReader reader = new StreamReader (stream); string htmlString = reader.ReadToEnd (); Intent i = new Intent (m_context, typeof(WebViewActivity)); i.PutExtra ("HtmlString", htmlString); m_context.StartActivity (i); } else if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save(fileName, contentType, stream, m_context); } } } } <file_sep>/Android/SampleBrowser/Samples/RangeSlider/Equalizer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using droid = Android.Widget.Orientation; using Com.Syncfusion.Sfrangeslider; using Android.Graphics; using Android.Content; namespace SampleBrowser { //[con(Label = "Orientation")] public class Equalizer : SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ SfRangeSlider slider1,slider2,slider3; TextView adjLabel, hertzLabel, hertzLabel1, hertzLabel2, decibelLabel; TextView decibelLabel1, decibelLabel2, adjLabel7, adjLabel8, adjLabel9, adjLabel10; int height, width; LinearLayout mainLayout, layout1, layout2, layout3; FrameLayout.LayoutParams sliderLayout; public override View GetSampleContent (Context con) { height = con.Resources.DisplayMetrics.HeightPixels/2; width = con.Resources.DisplayMetrics.WidthPixels/3; SamplePageContent(con); sliderLayout = new FrameLayout.LayoutParams(width, height + (height / 4)); /**************** **RangeSlider1** ****************/ slider1 = new SfRangeSlider(con); slider1.Minimum=-12; slider1.Maximum=12; slider1.TickFrequency=12; slider1.TrackSelectionColor=Color.Gray; slider1.Orientation=Com.Syncfusion.Sfrangeslider.Orientation.Vertical; slider1.TickPlacement=TickPlacement.None; slider1.ValuePlacement=ValuePlacement.TopLeft; slider1.ShowValueLabel=true; slider1.SnapsTo=SnapsTo.None; slider1.Value=6; slider1.ValueChanged += (object sender, ValueChangedEventArgs e) => { String decibelString=(string)(Math.Round(e.Value)+".0db"); decibelLabel.Text=decibelString; }; /**************** **RangeSlider2** ****************/ slider2 = new SfRangeSlider(con); slider2.Minimum=-12; slider2.Maximum=12; slider2.TickFrequency=12; slider2.TrackSelectionColor=Color.Gray; slider2.Orientation=Com.Syncfusion.Sfrangeslider.Orientation.Vertical; slider2.TickPlacement=TickPlacement.None; slider2.ValuePlacement=ValuePlacement.TopLeft; slider2.ShowValueLabel=true; slider2.SnapsTo=SnapsTo.None; slider2.Value=-3; slider2.LayoutParameters=sliderLayout; slider2.ValueChanged+= (object sender, ValueChangedEventArgs e) => { decibelLabel1.Text=Convert.ToString(Math.Round(e.Value)+".0db"); }; /**************** **RangeSlider3** ****************/ slider3 = new SfRangeSlider(con); slider3.Minimum=-12; slider3.Maximum=12; slider3.TickFrequency=12; slider3.TrackSelectionColor=Color.Gray; slider3.Orientation=Com.Syncfusion.Sfrangeslider.Orientation.Vertical; slider3.TickPlacement=TickPlacement.None; slider3.ValuePlacement=ValuePlacement.TopLeft; slider3.ShowValueLabel=true; slider3.SnapsTo=SnapsTo.None; slider3.Value=12; slider3.LayoutParameters=sliderLayout; slider3.ValueChanged+= (object sender, ValueChangedEventArgs e) => { decibelLabel2.Text=Convert.ToString(Math.Round(e.Value)+".0db"); }; LinearLayout mainView = GetView(con); return mainView; } private LinearLayout GetView(Context con) { //mainLayout mainLayout = new LinearLayout(con); mainLayout.SetBackgroundColor(Color.White); mainLayout.SetGravity(GravityFlags.Center); //parentLayout LinearLayout parentLayout = new LinearLayout(con); parentLayout.Orientation = droid.Vertical; parentLayout.SetBackgroundColor(Color.White); parentLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); parentLayout.AddView(adjLabel10); parentLayout.AddView(mainLayout); parentLayout.SetGravity(GravityFlags.Center); //layout1 layout1 = new LinearLayout(con); layout1.Orientation = droid.Vertical; layout1.SetGravity(GravityFlags.Center); layout1.AddView(hertzLabel); layout1.AddView(decibelLabel); layout1.AddView(adjLabel); layout1.AddView(slider1, sliderLayout); //layout2 layout2 = new LinearLayout(con); layout2.Orientation = droid.Vertical; layout2.SetGravity(GravityFlags.Center); layout2.AddView(hertzLabel1); layout2.AddView(decibelLabel1); layout2.AddView(adjLabel7); layout2.AddView(slider2, sliderLayout); //layout3 layout3 = new LinearLayout(con); layout3.Orientation = droid.Vertical; layout3.SetGravity(GravityFlags.Center); layout3.AddView(hertzLabel2); layout3.AddView(decibelLabel2); layout3.AddView(adjLabel8); layout3.AddView(slider3, sliderLayout); mainLayout.AddView(layout1); mainLayout.AddView(layout2); mainLayout.AddView(layout3); return parentLayout; } private void SamplePageContent(Context con) { /************* **Adj Label** *************/ adjLabel = new TextView(con); adjLabel7 = new TextView(con); adjLabel8 = new TextView(con); adjLabel9 = new TextView(con); adjLabel9.Text = ""; adjLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); adjLabel9.TextSize = 20; adjLabel9.Gravity = GravityFlags.Center; adjLabel9.SetTextColor(Color.Argb(255, 182, 182, 182)); adjLabel10 = new TextView(con); //hertzLabel hertzLabel = new TextView(con); hertzLabel.Text = "60HZ"; hertzLabel.TextSize = 20; hertzLabel.SetTextColor(Color.Black); hertzLabel.Gravity = GravityFlags.Center; hertzLabel.Typeface = Typeface.Create("Helvetica", TypefaceStyle.Normal); //decibelLabel decibelLabel = new TextView(con); decibelLabel.TextSize = 14; decibelLabel.SetTextColor(Color.Argb(255, 50, 180, 228)); decibelLabel.Text = "6.0db"; decibelLabel.Typeface = Typeface.Create("Helvetica", TypefaceStyle.Normal); decibelLabel.Gravity = GravityFlags.Center; //hertzLabel1 hertzLabel1 = new TextView(con); hertzLabel1.Text = "170HZ"; hertzLabel1.TextSize = 20; hertzLabel1.SetTextColor(Color.Black); hertzLabel1.Gravity = GravityFlags.Center; hertzLabel1.Typeface = Typeface.Create("Helvetica", TypefaceStyle.Normal); //decibelLabel1 decibelLabel1 = new TextView(con); decibelLabel1.TextSize = 14; decibelLabel1.SetTextColor(Color.Argb(255, 50, 180, 228)); decibelLabel1.Text = "-3.0db"; decibelLabel1.Typeface = Typeface.Create("Helvetica", TypefaceStyle.Normal); decibelLabel1.Gravity = GravityFlags.Center; //hertzLabel2 hertzLabel2 = new TextView(con); hertzLabel2.Text = "310HZ"; hertzLabel2.TextSize = 20; hertzLabel2.SetTextColor(Color.Black); hertzLabel2.Gravity = GravityFlags.Center; hertzLabel2.Typeface = Typeface.Create("Helvetica", TypefaceStyle.Normal); //decibelLabel2 decibelLabel2 = new TextView(con); decibelLabel2.TextSize = 14; decibelLabel2.SetTextColor(Color.Argb(255, 50, 180, 228)); decibelLabel2.Text = "12.0db"; decibelLabel2.Typeface = Typeface.Create("Helvetica", TypefaceStyle.Normal); decibelLabel2.Gravity = GravityFlags.Center; } } } <file_sep>/Forms/ListView/ListView/Samples/Paging/Model/PagingProductRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class PagingProductRepository { internal string[] Names = new string[] { "Fuji Apple","Honey Banana","Hawaiian Papaya","Lime","Pomegranate", "Mandarin Orange","Watermelon","Apricot","Black Grapes","Redrose Cherry", "Avacado","Organic Dragon","Asian Guava","Kesar Mango","Organic Lemon", "Bluberry","Jackfruit","Fuzzy Kiwi","Peaches","Pineapple","Strawberry","Rasberry", "Gala Apple","Saba Banana","Red Papaya","Key Lime","Pomegranate", "Blood Orange","Watermelon","Apium Apricot","Fresh Grapes","Bing Cherry", "Avacado","Dragon","Guava","Fresh Mango","Lemon", "Bluberry","Jackfruit","Fuzzy Kiwi","Gala Peaches","Fresh Pineapple","Red Strawberry","Rasberry", "Apple","Banana","Marsh Papaya","Key Lime","Fresh Pomegranate", "Manddarin Orange","Fresh Watermelon","Dried Apricot","Black Grapes","Redrose Cherry", "Asian Avacado","Dragon","Guava","Langra Mango","Organic Lemon", "Fresh Bluberry","Jackfruit","Hardy Kiwi","Gala Peaches","Fresh Pineapple","Red Strawberry","Rasberry", "Gala Apple","Saba Banana","Red Papaya","Key Limes", }; internal string[] Ratings = new string[] { "1500 Reviews", "1000 Reviews", "1200 Reviews", "1400 Reviews", "1600 Reviews", "1700 Reviews", "1800 Reviews", "1900 Reviews", "2500 Reviews", "1500 Reviews", "1800 Reviews", "1700 Reviews", "1460 Reviews", "1760 Reviews", "1660 Reviews", "1230 Reviews", "1850 Reviews", "1120 Reviews", "1980 Reviews", "1540 Reviews", "1980 Reviews", "1340 Reviews", "1340 Reviews", "1870 Reviews", "1360 Reviews", "1870 Reviews", "1230 Reviews", "1650 Reviews", "1860 Reviews", "1750 Reviews", "1570 Reviews", "1650 Reviews", "1660 Reviews", "1650 Reviews", "1270 Reviews", "1700 Reviews", "1540 Reviews", "1860 Reviews", "1480 Reviews", "1680 Reviews", "1240 Reviews", "1860 Reviews", "1240 Reviews", "1860 Reviews", "1200 Reviews", "1400 Reviews", "1600 Reviews", "1700 Reviews", "1800 Reviews", "1900 Reviews", "2500 Reviews", "2150 Reviews", "1380 Reviews", "1700 Reviews", "1460 Reviews", "1760 Reviews", "1660 Reviews", "1230 Reviews", "1850 Reviews", "1120 Reviews", "1980 Reviews", "1540 Reviews", "1980 Reviews", "1340 Reviews", "1340 Reviews", "1870 Reviews", "1360 Reviews", "1870 Reviews", "1230 Reviews", "1650 Reviews", "1240 Reviews", }; internal double[] ReviewValue = new double[] { 4.5,3.1,2.2,4.3,3.4,2.5,3.6,4.7,4.8,3.9,2.5,4.2,3.1,4.2,2.3,4.4,3.5,4.6,2.7,4.8, 3.9,4.6,2.5,2.1,3.2,4.3,4.4,3.5,4.6,2.7,4.8,4.9,2.3,3.4,4.1,2.2,4.3,3.4,4.5,4.6, 2.7,3.8,4.9,3.4,4.7,2.5,4.6,4.9,2.2,4.3,3.4,2.5,3.6,4.7,4.8,3.9,2.5,4.2,3.1,4.2, 2.3,4.4,3.5,4.6,2.7,4.8,3.9,4.6,2.5,2.1,3.2,4.3,4.4,3.5,4.8 }; internal string[] Names1 = new string[] { "Apple","Banana","Papaya","Lime","Pomegranate","Orange","Watermelon","Apricot", "Grapes","Cherry","Avacado","Dragon","Guava","Mango","Lemon","Blueberry", "Jackfruit","Kiwi","Peach","Pineapple","Strawberry","Raspberry" }; internal string[] Weights = new string[] { "1 lb","1 lb","1 lb","1 lb","1 lb","2 lb","2 lb","2 lb","1 lb", "2 lb","1.5 lb","2 lb","1 lb","1 lb","1 lb","1 lb","1 lb","2 lb", "1 lb","1 lb","1.5 lb","1 lb","1.5 lb","2 lb","1 lb","1.5 lb","1 lb", "1.5 lb","2 lb","2 lb","1 lb","1 lb","1 lb","2 lb","1 lb","1 lb", "1 lb","1 lb","1 lb","1 lb","1.5 lb","2 lb","1 lb","2 lb","1 lb", "2 lb","1 lb","1.5 lb","2 lb","2 lb","1 lb","2 lb","1 lb","2 lb", "1 lb","1 lb","1 lb","1 lb","1 lb","2 lb","1.5 lb","1 lb","1 lb", "1 lb","1 lb","2 lb","2 lb","1 lb","1 lb","1 lb","2 lb" }; internal double[] Prices = new double[] { 2.47,1.40,5.48,2.28,1.45,5.00,3.98,3.50,6.50,7.48,6.29,2.46,1.47,2.10,4.40,5.00, 8.27,7.33,9.99,2.00,3.97,3.79,1.17,6.40,1.78,2.18,3.78,2.12,3.98,9.95,6.50,6.18, 1.05,2.76,3.47,7.10,6.40,8.25,7.17,8.33,1.55,6.00,1.55,1.15,5.48,2.18,1.40,4.95, 3.88,1.39,6.40,7.38,6.19,2.36,1.57,2.20,4.30,5.10,8.37,7.23,9.89,2.10,3.87,3.29, 1.07,6.10,2.08,1.78,4.28,2.10,1.15 }; internal string[] Offer = new string[] { "10 % Off","25 % Off","50 % Off","30 % Off","60 % Off","35 % Off","40 % Off", "70 % Off","25 % Off","90 % Off","20 % Off","45 % Off","50 % Off","20 % Off", "15 % Off","10 % Off","20 % Off","45 % Off", "10 % Off", "20 % Off", "15 % Off", "40 % Off", "20 % Off", "15 % Off", "50 % Off", "20 % Off", "15 % Off", "80 % Off", "20 % Off", "45 % Off", "30 % Off", "80 % Off", "35 % Off", "10 % Off", "30 % Off", "75 % Off", "50 % Off", "20 % Off", "55 % Off", "40 % Off", "20 % Off", "85 % Off", "10 % Off", "20 % Off", "50 % Off", "30 % Off", "60 % Off", "35 % Off", "40 % Off", "70 % Off", "25 % Off", "90 % Off", "20 % Off", "45 % Off", "50 % Off", "20 % Off", "15 % Off", "10 % Off", "20 % Off", "45 % Off", "10 % Off", "20 % Off", "15 % Off", "40 % Off", "20 % Off", "15 % Off", "50 % Off", "20 % Off", "15 % Off", "80 % Off", "30 % Off" }; } }<file_sep>/Forms/Chat/Chat/Samples/FlightBooking/BotService.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Microsoft.Bot.Schema; using Newtonsoft.Json; using Syncfusion.XForms.Chat; using System; using System.Collections.ObjectModel; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; namespace SampleBrowser.SfChat { /// <summary> /// A Class used to communicate with Azure bot service. /// </summary> public class BotService { /// <summary> /// Http client. /// </summary> private HttpClient httpClient; /// <summary> /// Conversation details. /// </summary> private Conversation conversation; /// <summary> /// Direct line address to establish connection. /// </summary> private string BotBaseAddress = "https://directline.botframework.com/v3/directline/conversations/"; /// <summary> /// Direct line key to establish connection to syncfusion bot. /// </summary> private string directLineKey = "Key = \"<KEY>"; /// <summary> /// water mark used to get newly added message or actvity. /// </summary> private string watermark = string.Empty; /// <summary> /// Initializes a new instance of <see cref="BotService"/> class. /// </summary> /// <param name="viewModel">view model as paramter.</param> public BotService(FlightBookingViewModel viewModel) { this.ViewModel = viewModel; InitializeHttpConnection(); } /// <summary> /// Gets or set the flight booking view model. /// </summary> internal FlightBookingViewModel ViewModel { get; set; } /// <summary> /// Checks internet connection state. /// </summary> /// <returns>true if internet connection is established else false.</returns> internal bool CheckInternetConnection() { Connectivity.ConnectivityChanged += OnConnectivityChanged; if (Connectivity.NetworkAccess == NetworkAccess.Internet) { this.ViewModel.IsConnectionNotEstablished = false; return true; } else { this.ViewModel.ShowBusyIndicator = false; this.ViewModel.IsConnectionNotEstablished = true; return false; } } /// <summary> /// Raised when internet connection is changed. /// </summary> /// <param name="sender">object as sender</param> /// <param name="e">ConnectivityChangedEventArgs as e</param> internal async void OnConnectivityChanged(object sender, ConnectivityChangedEventArgs e) { if (e.NetworkAccess == NetworkAccess.Internet) { this.ViewModel.IsConnectionNotEstablished = false; if (this.conversation == null || (this.conversation != null && string.IsNullOrEmpty(this.conversation.ConversationId))) { this.ViewModel.ShowBusyIndicator = true; SetupConversation(); } else { await this.ReadMessageFromBot(); this.ViewModel.ShowBusyIndicator = false; } } else { this.ViewModel.ShowBusyIndicator = false; this.ViewModel.IsConnectionNotEstablished = true; } } /// <summary> /// Activity is created and message is send to bot. /// </summary> /// <param name="text">text from current user.</param> internal void SendMessageToBot(string text) { Activity activity = new Activity() { From = new ChannelAccount() { Id = this.ViewModel.CurrentUser.Name }, Text = text, Type = "message" }; PostActvityToBot(activity); } /// <summary> /// Reading bot response message. /// </summary> /// <returns></returns> internal async Task ReadMessageFromBot() { try { string conversationUrl = this.BotBaseAddress + this.conversation.ConversationId + "/activities?watermark=" + this.watermark; using (HttpResponseMessage messagesReceived = await this.httpClient.GetAsync(conversationUrl, HttpCompletionOption.ResponseContentRead)) { string messagesReceivedData = await messagesReceived.Content.ReadAsStringAsync(); ActivitySet messagesRoot = JsonConvert.DeserializeObject<ActivitySet>(messagesReceivedData); if (messagesRoot != null) { this.watermark = messagesRoot.Watermark; Device.BeginInvokeOnMainThread(() => { foreach (Activity activity in messagesRoot.Activities) { if (activity.From.Id == "CardMessageBot" && activity.Type == "message") { this.ProcessBotReplyAndAddMessage(activity); } } }); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception while reading Bot activity. exception message - {0}", ex.Message); } this.ViewModel.ShowTypingIndicator = false; this.ViewModel.ShowBusyIndicator = false; } /// <summary> /// Initialize the Http client and initiate conversation if internet connection is available. /// </summary> private void InitializeHttpConnection() { this.httpClient = new HttpClient(); this.httpClient.BaseAddress = new Uri(this.BotBaseAddress); this.httpClient.DefaultRequestHeaders.Accept.Clear(); this.httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.directLineKey); this.httpClient.Timeout = Timeout.InfiniteTimeSpan; if (CheckInternetConnection()) { SetupConversation(); } } /// <summary> /// Starts conversation to azure bot. /// </summary> private async void SetupConversation() { HttpContent contentPost = new StringContent(JsonConvert.SerializeObject(new Conversation()), Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await this.httpClient.PostAsync("/v3/directline/conversations", contentPost); if (response.IsSuccessStatusCode) { string conversationInfo = await response.Content.ReadAsStringAsync(); this.conversation = JsonConvert.DeserializeObject<Conversation>(conversationInfo); await Task.Delay(2000); Activity activity = new Activity(); activity.From = new ChannelAccount() { Id = ViewModel.CurrentUser.Name, Name = ViewModel.CurrentUser.Name, }; activity.Type = "add"; activity.Action = "add"; this.PostActvityToBot(activity); } } catch { } } /// <summary> /// current user message is passed to Bot. /// </summary> /// <param name="activity"></param> private async void PostActvityToBot(Activity activity) { StringContent contentPost = new StringContent(JsonConvert.SerializeObject(activity), Encoding.UTF8, "application/json"); string conversationUrl = this.BotBaseAddress + this.conversation.ConversationId + "/activities"; try { await this.httpClient.PostAsync(conversationUrl, contentPost); await this.ReadMessageFromBot(); } catch { } } /// <summary> /// Used to identify what type of message should be added in message collection. /// </summary> /// <param name="activity">bot reply message is received as activity.</param> private void ProcessBotReplyAndAddMessage(Activity activity) { if (!string.IsNullOrEmpty(activity.Text)) { if (activity.Text == "What else can I do for you?") { return; } if (activity.Text == "When are you planning to travel?" || activity.Text == "Oops ! This doesn’t seem to be a valid date. Please select a valid date.") { this.AddCalendarMessage(activity.Text); } else if (activity.Text == "Which city are you headed?") { this.AddCardMessage(activity); } else { this.AddTextMessage(activity); } } } /// <summary> /// Text message is created and added to the message collection. /// </summary> /// <param name="text">new message text.</param> /// <param name="suggestedActions">suggestion value for message</param> private void AddTextMessage(Activity activity) { TextMessage message = new TextMessage(); message.Text = activity.Text; message.Author = this.ViewModel.Bot; message.DateTime = DateTime.Now; if (activity.SuggestedActions != null && activity.SuggestedActions.Actions.Count > 0) { ChatSuggestions suggestions = new ChatSuggestions(); var suggestionItems = new ObservableCollection<ISuggestion>(); foreach (CardAction action in activity.SuggestedActions.Actions) { var suggestion = new Suggestion(); suggestion.Text = action.Title; suggestionItems.Add(suggestion); } suggestions.Items = suggestionItems; message.Suggestions = suggestions; } ViewModel.Messages?.Add(message); } /// <summary> /// Calendar message is created and added to the message collection. /// </summary> /// <param name="text">text for calendar message.</param> private void AddCalendarMessage(string text) { DatePickerMessage message = new DatePickerMessage(); message.Text = text; message.DateTime = DateTime.Now; message.Author = this.ViewModel.Bot; message.SelectedDate = DateTime.Now; ViewModel.Messages?.Add(message); } /// <summary> /// Card message is created and added to the message collection. /// </summary> /// <param name="activity">Activity that contains card attachments.</param> private void AddCardMessage(Activity activity) { CardMessage cardMessage = new CardMessage(); cardMessage.Text = activity.Text; cardMessage.Author = this.ViewModel.Bot; ObservableCollection<Card> cards = new ObservableCollection<Card>(); System.Collections.Generic.IList<Microsoft.Bot.Schema.Attachment> attachments = activity.Attachments as System.Collections.Generic.IList<Microsoft.Bot.Schema.Attachment>; HeroCard heroCard = new HeroCard(); foreach (Attachment attachment in attachments) { var type = attachment.ContentType; if (type == "application/vnd.microsoft.card.hero") { var temp = JsonConvert.SerializeObject(attachment.Content); heroCard = JsonConvert.DeserializeObject<HeroCard>(temp); } WebClient Client = new WebClient(); var byteArray = Client.DownloadData(heroCard.Images[0].Url.ToString()); Card card = new Card() { Title = heroCard.Title.ToString(), Description = heroCard.Text.ToString(), Image = ImageSource.FromStream(() => new MemoryStream(byteArray)) }; card.Buttons.Add(new CardButton() { Value = heroCard.Buttons[0].Value.ToString(), Title = heroCard.Buttons[0].Title }); cards.Add(card); } cardMessage.Cards = cards; this.ViewModel.Messages?.Add(cardMessage); } } } <file_sep>/Forms/Chart/Chart/Samples/GradientChart/GradientChartViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class GradientChartViewModel { public ObservableCollection<OxygenRate> OxygenHighDate { get; set; } public GradientChartViewModel() { DateTime date = new DateTime(2017, 5, 1); OxygenHighDate = new ObservableCollection<OxygenRate>(); OxygenHighDate.Add(new OxygenRate { High = 29, Low= 80, Date= date}); OxygenHighDate.Add(new OxygenRate { High = 33,Low = 80, Date = date.AddDays(6) }); OxygenHighDate.Add(new OxygenRate { High = 24,Low = 80, Date = date.AddDays(15) }); OxygenHighDate.Add(new OxygenRate { High = 28,Low = 80, Date = date.AddDays(23) }); OxygenHighDate.Add(new OxygenRate { High = 26,Low = 80, Date = date.AddDays(30) }); OxygenHighDate.Add(new OxygenRate { High = 38,Low = 80, Date = date.AddDays(39) }); OxygenHighDate.Add(new OxygenRate { High = 32,Low = 80, Date = date.AddDays(50) }); } } public class OxygenRate { public double High { get; set; } public double Low { get; set; } public DateTime Date { get; set; } } } <file_sep>/Forms/Calendar/Calendar/Samples/BlackoutDates/Behaviors/BlackoutDatesBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using SampleBrowser.Core; using Syncfusion.SfCalendar.XForms; using Xamarin.Forms; namespace SampleBrowser.SfCalendar { internal class BlackoutDatesBehavior : Behavior<SampleView> { private Syncfusion.SfCalendar.XForms.SfCalendar calendar; private Grid grid; private int calendarHeight = 400; private int calendarWidth = 400; private int padding = 50; protected override void OnAttachedTo(SampleView bindable) { base.OnAttachedTo(bindable); this.calendar = bindable.Content.FindByName<Syncfusion.SfCalendar.XForms.SfCalendar>("calendar"); this.grid = bindable.Content.FindByName<Grid>("grid"); if (Device.RuntimePlatform == "UWP") { this.grid.HorizontalOptions = LayoutOptions.Center; this.grid.VerticalOptions = LayoutOptions.Center; this.grid.HeightRequest = this.calendarHeight; this.grid.WidthRequest = this.calendarWidth; bindable.SizeChanged += this.Bindable_SizeChanged; } MonthViewSettings monthSettings = new MonthViewSettings { HeaderBackgroundColor = Color.White, TodayBorderColor = Color.FromHex("#2196F3"), TodayTextColor = Color.FromHex("#2196F3"), BlackoutColor = Color.Red }; this.calendar.MonthViewSettings = monthSettings; if (Device.Idiom == TargetIdiom.Tablet) { if (Device.RuntimePlatform == "Android") { this.calendar.MonthViewSettings.SelectionRadius = 30; } else { this.calendar.MonthViewSettings.SelectionRadius = 20; } } if (Device.RuntimePlatform == "Android" || (Device.RuntimePlatform == "UWP" && Device.Idiom == TargetIdiom.Desktop)) { this.calendar.HeaderHeight = 50; } else if (Device.RuntimePlatform == "iOS") { this.calendar.HeaderHeight = 40; } this.calendar.OnMonthCellLoaded += Calendar_OnMonthCellLoaded; } private void Calendar_OnMonthCellLoaded(object sender, MonthCellLoadedEventArgs e) { var blackoutDates = new ObservableCollection<DateTime>(); if (e.Date.DayOfWeek == DayOfWeek.Sunday || e.Date.DayOfWeek == DayOfWeek.Saturday) { if (this.calendar.BlackoutDates != null) { blackoutDates = (ObservableCollection<DateTime>)this.calendar.BlackoutDates; } blackoutDates.Add(e.Date); this.calendar.BlackoutDates = blackoutDates; } } private void Bindable_SizeChanged(object sender, EventArgs e) { var sampleView = sender as SampleView; if (sampleView.Height < this.calendarHeight + padding) { this.grid.HeightRequest = sampleView.Height - padding; } if (sampleView.Width < this.calendarWidth + padding) { this.grid.WidthRequest = sampleView.Width - padding; } } protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); if (Device.RuntimePlatform == "UWP") { bindable.SizeChanged -= this.Bindable_SizeChanged; } this.grid = null; this.calendar = null; } } } <file_sep>/iOS/SampleBrowser/Samples/XlsIO/Filters.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XlsIO; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class Filters : SampleView { public Filters () { this.filterList.Add((NSString)"Custom Filter"); this.filterList.Add((NSString)"Text Filter"); this.filterList.Add((NSString)"DateTime Filter"); this.filterList.Add((NSString)"Dynamic Filter"); this.filterList.Add((NSString)"Color Filter"); this.filterList.Add((NSString)"Icon Filter"); this.filterList.Add((NSString)"Advanced Filter"); this.filterActionList.Add((NSString)"Filter In Place"); this.filterActionList.Add((NSString)"Filter Copy"); selectedFilterType = "Custom Filter"; selectedFilterActionType = "Filter In Place"; this.colorFilterTypeList.Add((NSString)"Font Color"); this.colorFilterTypeList.Add((NSString)"Cell Color"); this.colorsList.Add((NSString)"Red"); this.colorsList.Add((NSString)"Blue"); this.colorsList.Add((NSString)"Green"); this.colorsList.Add((NSString)"Yellow"); this.colorsList.Add((NSString)"Empty"); this.iconSetList.Add((NSString)"ThreeSymbols"); this.iconSetList.Add((NSString)"FourRating"); this.iconSetList.Add((NSString)"FiveArrows"); this.iconIdList1.Add((NSString)"RedCrossSymbol"); this.iconIdList1.Add((NSString)"YellowExclamationSymbol"); this.iconIdList1.Add((NSString)"GreenCheckSymbol"); this.iconIdList1.Add((NSString)"NoIcon"); this.iconIdList2.Add((NSString)"SignalWithOneFillBar"); this.iconIdList2.Add((NSString)"SignalWithTwoFillBars"); this.iconIdList2.Add((NSString)"SignalWithThreeFillBars"); this.iconIdList2.Add((NSString)"SignalWithFourFillBars"); this.iconIdList2.Add((NSString)"NoIcon"); this.iconIdList3.Add((NSString)"RedDownArrow"); this.iconIdList3.Add((NSString)"YellowDownInclinedArrow"); this.iconIdList3.Add((NSString)"YellowSideArrow"); this.iconIdList3.Add((NSString)"YellowUpInclinedArrow"); this.iconIdList3.Add((NSString)"GreenUpArrow"); this.iconIdList3.Add((NSString)"NoIcon"); } CGRect frameRect = new CGRect (); float frameMargin = 8.0f; private readonly IList<string> filterList = new List<string>(); private readonly IList<string> filterActionList = new List<string>(); private readonly IList<string> colorFilterTypeList = new List<string>(); private readonly IList<string> colorsList = new List<string>(); private readonly IList<string> iconSetList = new List<string>(); private readonly IList<string> iconIdList1 = new List<string>(); private readonly IList<string> iconIdList2 = new List<string>(); private readonly IList<string> iconIdList3 = new List<string>(); UILabel filterLabel; UIButton filterDoneButton; UIButton filterButton; UIPickerView filterPicker; UILabel filterActionLabel; UIButton filterActionDoneButton; UIButton filterActionButton; UIButton colorFilterTypeButton; UIButton colorsListButton; UIButton colorFilterTypeDoneButton; UIButton colorsListDoneButton; UIButton iconSetListButton; UIButton iconSetListDoneButton; UIButton iconIdListButton; UIButton iconIdListDoneButton; UIPickerView filterActionPicker; UIPickerView colorFilterType; UIPickerView colorsListPicker; UIPickerView iconSetPicker; UIPickerView iconIdPicker; UIPickerView iconIdPicker2; UIPickerView iconIdPicker3; string selectedFilterType; string selectedFilterActionType; string selectedColorFilterType = "Font Color"; string selectedColor = "Red"; string selectedIconSet = "ThreeSymbols"; string selectedIconId = "RedCrossSymbol"; UILabel uniqueRecordsLabel; UILabel colorFilterTypeLabel; UILabel colorsLabel; UILabel iconSetLabel; UILabel iconIdLabel; UISwitch uniqueRecordsSwitch; UIButton button; bool isLoaded = false; void LoadAllowedTextsLabel() { #region Description Label UILabel label = new UILabel (); label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to filter data within a range of Excel worksheet."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width ,35); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width ,50); } this.AddSubview (label); #endregion #region Filter Region filterLabel = new UILabel(); filterDoneButton = new UIButton(); filterButton = new UIButton(); filterPicker = new UIPickerView(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { filterLabel.Font = UIFont.SystemFontOfSize(18); filterLabel.Frame = new CGRect(10, 45, frameRect.Location.X + frameRect.Size.Width-20, 50); filterButton.Frame = new CGRect(10, 95, frameRect.Location.X + frameRect.Size.Width - 20, 40); } else { filterLabel.Frame = new CGRect(10, 50, frameRect.Location.X + frameRect.Size.Width-20, 50); filterButton.Frame = new CGRect(10, 100, frameRect.Location.X + frameRect.Size.Width - 20, 40); } //filter Label filterLabel.TextColor = UIColor.Black; filterLabel.BackgroundColor = UIColor.Clear; filterLabel.Text = @"Filter Type"; filterLabel.TextAlignment = UITextAlignment.Left; filterLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(filterLabel); //filter button filterButton.SetTitle("Custom Filter", UIControlState.Normal); filterButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; filterButton.BackgroundColor = UIColor.Clear; filterButton.SetTitleColor(UIColor.Black, UIControlState.Normal); filterButton.Hidden = false; filterButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; filterButton.Layer.BorderWidth = 4; filterButton.Layer.CornerRadius = 8; filterButton.Font = UIFont.FromName("Helvetica", 16f); filterButton.TouchUpInside += ShowFilterPicker; this.AddSubview(filterButton); //filterpicker PickerModel filterPickermodel = new PickerModel(this.filterList); filterPickermodel.PickerChanged += (sender, e) => { this.selectedFilterType = e.SelectedValue; filterButton.SetTitle(selectedFilterType, UIControlState.Normal); }; filterPicker = new UIPickerView(); filterPicker.ShowSelectionIndicator = true; filterPicker.Hidden = true; filterPicker.Model = filterPickermodel; filterPicker.BackgroundColor = UIColor.White; //filterDoneButtonn filterDoneButton = new UIButton(); filterDoneButton.SetTitle("Done\t", UIControlState.Normal); filterDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; filterDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); filterDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); filterDoneButton.Hidden = true; filterDoneButton.TouchUpInside += HideFilterPicker; filterPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 20, this.Frame.Size.Width, this.Frame.Size.Height / 3); filterDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 20, this.Frame.Size.Width, 40); this.AddSubview(filterPicker); this.AddSubview(filterDoneButton); #endregion #region Filter Action Region filterActionLabel = new UILabel(); colorFilterTypeLabel = new UILabel(); colorsLabel = new UILabel(); iconSetLabel = new UILabel(); iconIdLabel = new UILabel(); filterActionDoneButton = new UIButton(); filterActionButton = new UIButton(); colorFilterTypeButton = new UIButton(); colorsListButton = new UIButton(); iconSetListButton = new UIButton(); iconSetListDoneButton = new UIButton(); iconIdListButton = new UIButton(); iconIdListDoneButton = new UIButton(); filterActionPicker = new UIPickerView(); colorFilterType = new UIPickerView(); colorsListPicker = new UIPickerView(); iconSetPicker = new UIPickerView(); iconIdPicker = new UIPickerView(); iconIdPicker2 = new UIPickerView(); iconIdPicker3 = new UIPickerView(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { filterActionLabel.Font = UIFont.SystemFontOfSize(18); filterActionLabel.Frame = new CGRect(10, 140, frameRect.Location.X + frameRect.Size.Width - 20, 50); filterActionButton.Frame = new CGRect(10, 190, frameRect.Location.X + frameRect.Size.Width - 20, 40); colorFilterTypeLabel.Font = UIFont.SystemFontOfSize(18); colorFilterTypeLabel.Frame = new CGRect(10, 140, frameRect.Location.X + frameRect.Size.Width - 20, 50); colorsLabel.Font = UIFont.SystemFontOfSize(18); colorFilterTypeButton.Frame = new CGRect(10, 190, frameRect.Location.X + frameRect.Size.Width - 20, 40); colorsLabel.Frame = new CGRect(10, 240, frameRect.Location.X + frameRect.Size.Width - 20, 50); colorsListButton.Frame = new CGRect(10, 290, frameRect.Location.X + frameRect.Size.Width - 20, 40); iconSetLabel.Font = UIFont.SystemFontOfSize(18); iconSetLabel.Frame = new CGRect(10, 140, frameRect.Location.X + frameRect.Size.Width - 20, 50); iconIdLabel.Font = UIFont.SystemFontOfSize(18); iconSetListButton.Frame = new CGRect(10, 190, frameRect.Location.X + frameRect.Size.Width - 20, 40); iconIdLabel.Frame = new CGRect(10, 240, frameRect.Location.X + frameRect.Size.Width - 20, 50); iconIdListButton.Frame = new CGRect(10, 290, frameRect.Location.X + frameRect.Size.Width - 20, 40); } else { filterActionLabel.Frame = new CGRect(10, 145, frameRect.Location.X + frameRect.Size.Width - 20, 50); filterActionButton.Frame = new CGRect(10, 195, frameRect.Location.X + frameRect.Size.Width - 20, 40); colorFilterTypeLabel.Frame = new CGRect(10, 145, frameRect.Location.X + frameRect.Size.Width - 20, 50); colorFilterTypeButton.Frame = new CGRect(10, 195, frameRect.Location.X + frameRect.Size.Width - 20, 40); colorsLabel.Frame = new CGRect(10, 245, frameRect.Location.X + frameRect.Size.Width - 20, 50); colorsListButton.Frame = new CGRect(10, 295, frameRect.Location.X + frameRect.Size.Width - 20, 40); iconSetLabel.Frame = new CGRect(10, 145, frameRect.Location.X + frameRect.Size.Width - 20, 50); iconSetListButton.Frame = new CGRect(10, 195, frameRect.Location.X + frameRect.Size.Width - 20, 40); iconIdLabel.Frame = new CGRect(10, 245, frameRect.Location.X + frameRect.Size.Width - 20, 50); iconIdListButton.Frame = new CGRect(10, 295, frameRect.Location.X + frameRect.Size.Width - 20, 40); } //filterActionLabel filterActionLabel.TextColor = UIColor.Black; filterActionLabel.BackgroundColor = UIColor.Clear; filterActionLabel.Text = @"Filter Action"; filterActionLabel.TextAlignment = UITextAlignment.Left; filterActionLabel.Font = UIFont.FromName("Helvetica", 16f); //filterActionButton filterActionButton.SetTitle("Filter In Place", UIControlState.Normal); filterActionButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; filterActionButton.BackgroundColor = UIColor.Clear; filterActionButton.SetTitleColor(UIColor.Black, UIControlState.Normal); filterActionButton.Hidden = false; filterActionButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; filterActionButton.Layer.BorderWidth = 4; filterActionButton.Layer.CornerRadius = 8; filterActionButton.Font = UIFont.FromName("Helvetica", 16f); filterActionButton.TouchUpInside += ShowFilterActionPicker; //filterActionPickermodel PickerModel filterActionPickermodel = new PickerModel(this.filterActionList); filterActionPickermodel.PickerChanged += (sender, e) => { this.selectedFilterActionType = e.SelectedValue; filterActionButton.SetTitle(selectedFilterActionType, UIControlState.Normal); }; filterActionPicker = new UIPickerView(); filterActionPicker.ShowSelectionIndicator = true; filterActionPicker.Hidden = true; filterActionPicker.Model = filterActionPickermodel; filterActionPicker.BackgroundColor = UIColor.White; //filterActionDoneButton filterActionDoneButton = new UIButton(); filterActionDoneButton.SetTitle("Done\t", UIControlState.Normal); filterActionDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; filterActionDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); filterActionDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); filterActionDoneButton.Hidden = true; filterActionDoneButton.TouchUpInside += HideFilterActionPicker; filterActionPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); filterActionDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 30,this.Frame.Size.Width, 40); this.AddSubview(filterActionPicker); this.AddSubview(filterActionDoneButton); //unique records label uniqueRecordsLabel = new UILabel(); uniqueRecordsLabel.TextColor = UIColor.Black; uniqueRecordsLabel.BackgroundColor = UIColor.Clear; uniqueRecordsLabel.Text = @"Unique Records"; uniqueRecordsLabel.TextAlignment = UITextAlignment.Left; uniqueRecordsLabel.Font = UIFont.FromName("Helvetica", 16f); uniqueRecordsLabel.Frame = new CGRect(10, 240, this.Frame.Size.Width - 20, 40); //unique records switch uniqueRecordsSwitch = new UISwitch(); uniqueRecordsSwitch.On = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) uniqueRecordsSwitch.Frame=new CGRect(330,240, this.Frame.Size.Width - 220, 40); else uniqueRecordsSwitch.Frame=new CGRect(250,240, this.Frame.Size.Width - 20, 40); //Color Filter Type label colorFilterTypeLabel.TextColor = UIColor.Black; colorFilterTypeLabel.BackgroundColor = UIColor.Clear; colorFilterTypeLabel.Text = @"Color Filter Type"; colorFilterTypeLabel.TextAlignment = UITextAlignment.Left; colorFilterTypeLabel.Font = UIFont.FromName("Helvetica", 16f); colorFilterTypeButton.SetTitle("Font Color", UIControlState.Normal); colorFilterTypeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; colorFilterTypeButton.BackgroundColor = UIColor.Clear; colorFilterTypeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); colorFilterTypeButton.Hidden = false; colorFilterTypeButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; colorFilterTypeButton.Layer.BorderWidth = 4; colorFilterTypeButton.Layer.CornerRadius = 8; colorFilterTypeButton.Font = UIFont.FromName("Helvetica", 16f); colorFilterTypeButton.TouchUpInside += ShowColorFilterTypePicker; colorFilterTypeDoneButton = new UIButton(); colorFilterTypeDoneButton.SetTitle("Done\t", UIControlState.Normal); colorFilterTypeDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; colorFilterTypeDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); colorFilterTypeDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); colorFilterTypeDoneButton.Hidden = true; colorFilterTypeDoneButton.TouchUpInside += HideColorFilterTypePicker; //Color Filter Type picker model PickerModel colorFilterPickerModel = new PickerModel(colorFilterTypeList); colorFilterPickerModel.PickerChanged += (sender, e) => { this.selectedColorFilterType = e.SelectedValue; colorFilterTypeButton.SetTitle(selectedColorFilterType, UIControlState.Normal); }; //colorFilterType.Hidden = true; colorFilterType.ShowSelectionIndicator = true; colorFilterType.Hidden = true; colorFilterType.Model = colorFilterPickerModel; colorFilterType.BackgroundColor = UIColor.White; colorFilterType.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); colorFilterTypeDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 30,this.Frame.Size.Width, 40); this.AddSubview(colorFilterType); this.AddSubview(colorFilterTypeDoneButton); colorsLabel.TextColor = UIColor.Black; colorsLabel.BackgroundColor = UIColor.Clear; colorsLabel.Text = @"Color"; colorsLabel.TextAlignment = UITextAlignment.Left; colorsLabel.Font = UIFont.FromName("Helvetica", 16f); colorsListButton.SetTitle("Red", UIControlState.Normal); colorsListButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; colorsListButton.BackgroundColor = UIColor.Clear; colorsListButton.SetTitleColor(UIColor.Black, UIControlState.Normal); colorsListButton.Hidden = false; colorsListButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; colorsListButton.Layer.BorderWidth = 4; colorsListButton.Layer.CornerRadius = 8; colorsListButton.Font = UIFont.FromName("Helvetica", 16f); colorsListButton.TouchUpInside += ShowColorsListPicker; colorsListDoneButton = new UIButton(); colorsListDoneButton.SetTitle("Done\t", UIControlState.Normal); colorsListDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; colorsListDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); colorsListDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); colorsListDoneButton.Hidden = true; colorsListDoneButton.TouchUpInside += HideColorsListPicker; //Colors List picker model PickerModel colorsListPickerModel = new PickerModel(colorsList); colorsListPickerModel.PickerChanged += (sender, e) => { this.selectedColor = e.SelectedValue; colorsListButton.SetTitle(selectedColor, UIControlState.Normal); }; colorsListPicker.ShowSelectionIndicator = true; colorsListPicker.Hidden = true; colorsListPicker.Model = colorsListPickerModel; colorsListPicker.BackgroundColor = UIColor.White; colorsListPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); colorsListDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 30, this.Frame.Size.Width, 40); this.AddSubview(colorsListPicker); this.AddSubview(colorsListDoneButton); //IconSet label iconSetLabel.TextColor = UIColor.Black; iconSetLabel.BackgroundColor = UIColor.Clear; iconSetLabel.Text = @"IconSet Type"; iconSetLabel.TextAlignment = UITextAlignment.Left; iconSetLabel.Font = UIFont.FromName("Helvetica", 16f); iconSetListButton.SetTitle("ThreeSymbols", UIControlState.Normal); iconSetListButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; iconSetListButton.BackgroundColor = UIColor.Clear; iconSetListButton.SetTitleColor(UIColor.Black, UIControlState.Normal); iconSetListButton.Hidden = false; iconSetListButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; iconSetListButton.Layer.BorderWidth = 4; iconSetListButton.Layer.CornerRadius = 8; iconSetListButton.Font = UIFont.FromName("Helvetica", 16f); iconSetListButton.TouchUpInside += ShowIconSetPicker; iconSetListDoneButton = new UIButton(); iconSetListDoneButton.SetTitle("Done\t", UIControlState.Normal); iconSetListDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; iconSetListDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); iconSetListDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); iconSetListDoneButton.Hidden = true; iconSetListDoneButton.TouchUpInside += HideIconSetPicker; //Color Filter Type picker model PickerModel iconFilterPickerModel = new PickerModel(iconSetList); iconFilterPickerModel.PickerChanged += (sender, e) => { this.selectedIconSet = e.SelectedValue; iconSetListButton.SetTitle(selectedIconSet, UIControlState.Normal); if(this.selectedIconSet == "ThreeSymbols") { this.selectedIconId = "RedCrossSymbol"; iconIdListButton.SetTitle(selectedIconId, UIControlState.Normal); } else if(this.selectedIconSet == "FourRating") { this.selectedIconId = "SignalWithOneFillBar"; iconIdListButton.SetTitle(selectedIconId, UIControlState.Normal); } else { this.selectedIconId = "RedDownArrow"; iconIdListButton.SetTitle(selectedIconId, UIControlState.Normal); } }; //colorFilterType.Hidden = true; iconSetPicker.ShowSelectionIndicator = true; iconSetPicker.Hidden = true; iconSetPicker.Model = iconFilterPickerModel; iconSetPicker.BackgroundColor = UIColor.White; iconSetPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); iconSetListDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 30, this.Frame.Size.Width, 40); this.AddSubview(iconSetPicker); this.AddSubview(iconSetListDoneButton); iconIdLabel.TextColor = UIColor.Black; iconIdLabel.BackgroundColor = UIColor.Clear; iconIdLabel.Text = @"Icon ID"; iconIdLabel.TextAlignment = UITextAlignment.Left; iconIdLabel.Font = UIFont.FromName("Helvetica", 16f); iconIdListButton.SetTitle("RedCrossSymbol", UIControlState.Normal); iconIdListButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; iconIdListButton.BackgroundColor = UIColor.Clear; iconIdListButton.SetTitleColor(UIColor.Black, UIControlState.Normal); iconIdListButton.Hidden = false; iconIdListButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; iconIdListButton.Layer.BorderWidth = 4; iconIdListButton.Layer.CornerRadius = 8; iconIdListButton.Font = UIFont.FromName("Helvetica", 16f); iconIdListButton.TouchUpInside += ShowIconIdPicker; iconIdListDoneButton = new UIButton(); iconIdListDoneButton.SetTitle("Done\t", UIControlState.Normal); iconIdListDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; iconIdListDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); iconIdListDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); iconIdListDoneButton.Hidden = true; iconIdListDoneButton.TouchUpInside += HideIconIdPicker; //Colors List picker model PickerModel iconIdPickerModel = new PickerModel(iconIdList1); iconIdPickerModel.PickerChanged += (sender, e) => { this.selectedIconId = e.SelectedValue; iconIdListButton.SetTitle(selectedIconId, UIControlState.Normal); }; PickerModel iconIdPickerModel2 = new PickerModel(iconIdList2); iconIdPickerModel2.PickerChanged += (sender, e) => { this.selectedIconId = e.SelectedValue; iconIdListButton.SetTitle(selectedIconId, UIControlState.Normal); }; PickerModel iconIdPickerModel3 = new PickerModel(iconIdList3); iconIdPickerModel3.PickerChanged += (sender, e) => { this.selectedIconId = e.SelectedValue; iconIdListButton.SetTitle(selectedIconId, UIControlState.Normal); }; iconIdPicker.ShowSelectionIndicator = true; iconIdPicker.Hidden = true; iconIdPicker.Model = iconIdPickerModel; iconIdPicker.BackgroundColor = UIColor.White; iconIdPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); iconIdPicker2.ShowSelectionIndicator = true; iconIdPicker2.Hidden = true; iconIdPicker2.Model = iconIdPickerModel2; iconIdPicker2.BackgroundColor = UIColor.White; iconIdPicker2.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); iconIdPicker3.ShowSelectionIndicator = true; iconIdPicker3.Hidden = true; iconIdPicker3.Model = iconIdPickerModel3; iconIdPicker3.BackgroundColor = UIColor.White; iconIdPicker3.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); iconIdListDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 30, this.Frame.Size.Width, 40); this.AddSubview(iconIdPicker); this.AddSubview(iconIdPicker2); this.AddSubview(iconIdPicker3); this.AddSubview(iconIdListDoneButton); #endregion this.AddSubview(filterActionLabel); this.AddSubview(filterActionButton); this.AddSubview(uniqueRecordsLabel); this.AddSubview(uniqueRecordsSwitch); this.AddSubview(colorFilterTypeLabel); this.AddSubview(colorFilterTypeButton); this.AddSubview(colorsLabel); this.AddSubview(colorsListButton); this.AddSubview(iconSetLabel); this.AddSubview(iconSetListButton); this.AddSubview(iconIdLabel); this.AddSubview(iconIdListButton); filterActionLabel.Hidden = true; filterActionButton.Hidden = true; uniqueRecordsLabel.Hidden = true; uniqueRecordsSwitch.Hidden = true; colorFilterTypeLabel.Hidden = true; colorFilterTypeButton.Hidden = true; colorsLabel.Hidden = true; colorsListButton.Hidden = true; iconSetLabel.Hidden = true; iconSetListButton.Hidden = true; iconIdLabel.Hidden = true; iconIdListButton.Hidden = true; //button button = new UIButton (UIButtonType.System); button.SetTitle("Generate Excel", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 150, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(0, 155, frameRect.Location.X + frameRect.Size.Width, 10); } button.TouchUpInside += OnButtonClicked; this.AddSubview (button); isLoaded = true; } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook string resourcePath = null; int index = filterList.IndexOf(selectedFilterType); if(index == 6) resourcePath = "SampleBrowser.Samples.XlsIO.Template.AdvancedFilterData.xlsx"; else if (index == 5) resourcePath = "SampleBrowser.Samples.XlsIO.Template.IconFilterData.xlsx"; else if(index == 4) resourcePath = "SampleBrowser.Samples.XlsIO.Template.FilterData_Color.xlsx"; else resourcePath = "SampleBrowser.Samples.XlsIO.Template.FilterData.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly (); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); IWorksheet sheet = workbook.Worksheets[0]; #endregion if(index !=6) sheet.AutoFilters.FilterRange = sheet.Range[1, 1, 49, 3]; switch (index) { case 0: IAutoFilter filter1 = sheet.AutoFilters[0]; filter1.IsAnd = false; filter1.FirstCondition.ConditionOperator = ExcelFilterCondition.Equal; filter1.FirstCondition.DataType = ExcelFilterDataType.String; filter1.FirstCondition.String = "Owner"; filter1.SecondCondition.ConditionOperator = ExcelFilterCondition.Equal; filter1.SecondCondition.DataType = ExcelFilterDataType.String; filter1.SecondCondition.String = "Sales Representative"; break; case 1: IAutoFilter filter2 = sheet.AutoFilters[0]; filter2.AddTextFilter(new string[] { "Owner", "Sales Representative", "Sales Associate" }); break; case 2: IAutoFilter filter3 = sheet.AutoFilters[1]; filter3.AddDateFilter(new DateTime(2004, 9, 1, 1, 0, 0, 0), DateTimeGroupingType.month); filter3.AddDateFilter(new DateTime(2011, 1, 1, 1, 0, 0, 0), DateTimeGroupingType.year); break; case 3: IAutoFilter filter4 = sheet.AutoFilters[1]; filter4.AddDynamicFilter(DynamicFilterType.Quarter1); break; case 4: #region sheet.AutoFilters.FilterRange = sheet["A1:C49"]; Syncfusion.Drawing.Color color = Syncfusion.Drawing.Color.Empty; switch(selectedColor.ToLower()) { case "red": color = Syncfusion.Drawing.Color.Red; break; case "blue": color = Syncfusion.Drawing.Color.Blue; break; case "green": color = Syncfusion.Drawing.Color.Green; break; case "yellow": color = Syncfusion.Drawing.Color.Yellow; break; case "empty": //Do nothing. break; } if(selectedColorFilterType.ToLower().Equals("font color")) { IAutoFilter filter = sheet.AutoFilters[2]; filter.AddColorFilter(color, ExcelColorFilterType.FontColor); } else { IAutoFilter filter = sheet.AutoFilters[0]; filter.AddColorFilter(color, ExcelColorFilterType.CellColor); } #endregion break; case 5: #region IconFilter sheet.AutoFilters.FilterRange = sheet["A4:D44"]; ExcelIconSetType iconSet = ExcelIconSetType.FiveArrows; int filterIndex = 0; int iconId = 0; switch(iconSetList.IndexOf(selectedIconSet)) { case 0: filterIndex = 3; iconSet = ExcelIconSetType.ThreeSymbols; switch(iconIdList1.IndexOf(selectedIconId)) { case 0: iconId = 0; break; case 1: iconId = 1; break; case 2: iconId = 2; break; case 3: iconSet = (ExcelIconSetType)(-1); break; } break; case 1: filterIndex = 1; iconSet = ExcelIconSetType.FourRating; switch (iconIdList1.IndexOf(selectedIconId)) { case 0: iconId = 0; break; case 1: iconId = 1; break; case 2: iconId = 2; break; case 3: iconId = 3; break; case 4: iconSet = (ExcelIconSetType)(-1); break; } break; case 2: filterIndex = 2; iconSet = ExcelIconSetType.FiveArrows; switch (iconIdList1.IndexOf(selectedIconId)) { case 0: iconId = 0; break; case 1: iconId = 1; break; case 2: iconId = 2; break; case 3: iconId = 3; break; case 4: iconId = 4; break; case 5: iconSet = (ExcelIconSetType)(-1); break; } break; } IAutoFilter filter5 = sheet.AutoFilters[filterIndex]; filter5.AddIconFilter(iconSet, iconId); #endregion break; case 6: #region AdvancedFilter IRange filterRange = sheet.Range["A8:G51"]; IRange criteriaRange = sheet.Range["A2:B5"]; if (selectedFilterActionType == "Filter In Place") { sheet.AdvancedFilter(ExcelFilterAction.FilterInPlace, filterRange, criteriaRange, null, uniqueRecordsSwitch.On); } else { IRange range = sheet.Range["I7:O7"]; range.Merge(); range.Text = "FilterCopy"; range.CellStyle.Font.RGBColor = Syncfusion.Drawing.Color.FromArgb(0, 112, 192); range.HorizontalAlignment = ExcelHAlign.HAlignCenter; range.CellStyle.Font.Bold = true; IRange copyRange = sheet.Range["I8"]; sheet.AdvancedFilter(ExcelFilterAction.FilterCopy, filterRange, criteriaRange, copyRange, uniqueRecordsSwitch.On); } #endregion break; } workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("Filters.xlsx", "application/msexcel", stream); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); if(!isLoaded) LoadAllowedTextsLabel (); base.LayoutSubviews(); } void ShowFilterPicker(object sender, EventArgs e) { filterDoneButton.Hidden = false; filterPicker.Hidden = false; button.Hidden = true; filterActionLabel.Hidden = true; filterActionButton.Hidden = true; uniqueRecordsLabel.Hidden = true; uniqueRecordsSwitch.Hidden = true; colorFilterTypeLabel.Hidden = true; colorFilterTypeButton.Hidden = true; colorsLabel.Hidden = true; colorsListButton.Hidden = true; iconSetLabel.Hidden = true; iconSetListButton.Hidden = true; iconIdLabel.Hidden = true; iconIdListButton.Hidden = true; this.BecomeFirstResponder(); } void HideFilterPicker(object sender, EventArgs e) { filterDoneButton.Hidden = true; filterPicker.Hidden = true; button.Hidden = false; this.BecomeFirstResponder(); if (selectedFilterType == "Advanced Filter") { filterActionLabel.Hidden = false; filterActionButton.Hidden = false; uniqueRecordsLabel.Hidden = false; uniqueRecordsSwitch.Hidden = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 290, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(0, 295, frameRect.Location.X + frameRect.Size.Width, 10); } colorFilterTypeLabel.Hidden = true; colorsLabel.Hidden = true; colorsListButton.Hidden = true; } else if(selectedFilterType == "Color Filter") { colorFilterTypeLabel.Hidden = false; colorFilterTypeButton.Hidden = false; colorsLabel.Hidden = false; colorsListButton.Hidden = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 345, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(0, 350, frameRect.Location.X + frameRect.Size.Width, 10); } } else if (selectedFilterType == "Icon Filter") { iconSetLabel.Hidden = false; iconSetListButton.Hidden = false; iconIdLabel.Hidden = false; iconIdListButton.Hidden = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 345, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(0, 350, frameRect.Location.X + frameRect.Size.Width, 10); } } else { filterActionLabel.Hidden = true; filterActionButton.Hidden = true; uniqueRecordsLabel.Hidden = true; uniqueRecordsSwitch.Hidden = true; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 150, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(0, 155, frameRect.Location.X + frameRect.Size.Width, 10); } colorFilterTypeLabel.Hidden = true; colorFilterTypeButton.Hidden = true; colorsLabel.Hidden = true; colorsListButton.Hidden = true; iconSetLabel.Hidden = true; iconSetListButton.Hidden = true; iconIdLabel.Hidden = true; iconIdListButton.Hidden = true; } } void ShowFilterActionPicker(object sender, EventArgs e) { filterActionLabel.Hidden = true; filterActionButton.Hidden = true; filterActionDoneButton.Hidden = false; filterActionPicker.Hidden = false; uniqueRecordsLabel.Hidden = true; uniqueRecordsSwitch.Hidden = true; button.Hidden = true; filterButton.Hidden = true; colorFilterTypeButton.Hidden = true; this.BecomeFirstResponder(); } void HideFilterActionPicker(object sender, EventArgs e) { filterActionLabel.Hidden = false; filterActionButton.Hidden = false; filterActionDoneButton.Hidden = true; filterActionPicker.Hidden = true; uniqueRecordsLabel.Hidden = false; uniqueRecordsSwitch.Hidden = false; button.Hidden = false; filterButton.Hidden = false; colorFilterTypeButton.Hidden = true; this.BecomeFirstResponder(); } void ShowColorFilterTypePicker(object sender, EventArgs e) { filterButton.Hidden = true; colorFilterTypeLabel.Hidden = true; button.Hidden = true; colorFilterTypeButton.Hidden = true; colorFilterType.Hidden = false; colorFilterTypeDoneButton.Hidden = false; colorsLabel.Hidden = true; colorsListButton.Hidden = true; this.BecomeFirstResponder(); } void HideColorFilterTypePicker(object sender, EventArgs e) { filterButton.Hidden = false; colorFilterTypeLabel.Hidden = false; button.Hidden = false; colorFilterTypeButton.Hidden = false; colorFilterType.Hidden = true; colorFilterTypeDoneButton.Hidden = true; colorsLabel.Hidden = false; colorsListButton.Hidden = false; this.BecomeFirstResponder(); } void ShowColorsListPicker(object sender, EventArgs e) { colorFilterTypeLabel.Hidden = true; button.Hidden = true; colorFilterTypeButton.Hidden = true; colorFilterType.Hidden = true; colorFilterTypeDoneButton.Hidden = true; colorsListButton.Hidden = true; colorsListDoneButton.Hidden = false; colorsListPicker.Hidden = false; colorsLabel.Hidden = true; filterButton.Hidden = true; this.BecomeFirstResponder(); } void HideColorsListPicker(object sender, EventArgs e) { colorFilterTypeLabel.Hidden = false; button.Hidden = false; colorFilterTypeButton.Hidden = false; colorFilterType.Hidden = true; colorFilterTypeDoneButton.Hidden = true; colorsListButton.Hidden = false; colorsListDoneButton.Hidden = true; colorsListPicker.Hidden = true; colorsLabel.Hidden = false; filterButton.Hidden = false; this.BecomeFirstResponder(); } void ShowIconSetPicker(object sender, EventArgs e) { button.Hidden = true; filterButton.Hidden = true; iconSetLabel.Hidden = true; iconSetListButton.Hidden = true; iconIdLabel.Hidden = true; iconIdListButton.Hidden = true; iconSetPicker.Hidden = false; iconSetListDoneButton.Hidden = false; this.BecomeFirstResponder(); } void HideIconSetPicker(object sender, EventArgs e) { button.Hidden = false; filterButton.Hidden = false; iconSetPicker.Hidden = true; iconSetLabel.Hidden = false; iconSetListButton.Hidden = false; iconIdLabel.Hidden = false; iconIdListButton.Hidden = false; iconSetListDoneButton.Hidden = true; this.BecomeFirstResponder(); } void ShowIconIdPicker(object sender, EventArgs e) { button.Hidden = true; filterButton.Hidden = true; iconSetLabel.Hidden = true; iconSetListButton.Hidden = true; iconIdLabel.Hidden = true; iconIdListButton.Hidden = true; iconIdListDoneButton.Hidden = false; this.BecomeFirstResponder(); if (selectedIconSet == "ThreeSymbols") { iconIdPicker.Hidden = false; iconIdPicker2.Hidden = true; iconIdPicker3.Hidden = true; } else if (selectedIconSet == "FourRating") { iconIdPicker.Hidden = true; iconIdPicker2.Hidden = false; iconIdPicker3.Hidden = true; } else { iconIdPicker.Hidden = true; iconIdPicker2.Hidden = true; iconIdPicker3.Hidden = false; } } void HideIconIdPicker(object sender, EventArgs e) { button.Hidden = false; filterButton.Hidden = false; iconIdPicker.Hidden = true; iconIdPicker2.Hidden = true; iconIdPicker3.Hidden = true; iconSetLabel.Hidden = false; iconSetListButton.Hidden = false; iconIdLabel.Hidden = false; iconIdListButton.Hidden = false; iconIdListDoneButton.Hidden = true; this.BecomeFirstResponder(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/Histogram.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Drawing; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Histogram : SampleView { public Histogram() { SFChart chart = new SFChart(); chart.Title.Text = new NSString("Examination Result"); chart.ColorModel.Palette = SFChartColorPalette.Natural; SFNumericalAxis primary = new SFNumericalAxis(); primary.Title.Text = new NSString("Score of Final Examination"); primary.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; primary.ShowMajorGridLines = false; chart.PrimaryAxis = primary; chart.SecondaryAxis = new SFNumericalAxis(); chart.SecondaryAxis.Title.Text = new NSString("Number of Students"); chart.SecondaryAxis.ShowMajorGridLines = true; chart.SecondaryAxis.Visible = true; chart.SecondaryAxis.AxisLineStyle.LineWidth = 0; chart.SecondaryAxis.MajorTickStyle.LineWidth = new NSNumber(0); ChartViewModel dataModel = new ChartViewModel(); SFHistogramSeries series1 = new SFHistogramSeries(); series1.ItemsSource = dataModel.HistogramData; series1.XBindingPath = "YValue"; series1.YBindingPath = "XValue"; series1.EnableTooltip = true; series1.Interval = 20; series1.StrokeColor = UIColor.White; series1.StrokeWidth = 1; series1.EnableAnimation = true; series1.LegendIcon = SFChartLegendIcon.SeriesType; series1.DataMarker.ShowLabel = true; series1.DataMarker.LabelStyle.LabelPosition = SFChartDataMarkerLabelPosition.Inner; series1.DataMarker.LabelStyle.BackgroundColor = UIColor.Clear; series1.DataMarker.LabelStyle.Color = UIColor.White; chart.Series.Add(series1); chart.Delegate = new HistogramTooltipFormatter(); var tooltip = new SFChartTooltipBehavior(); tooltip.BackgroundColor = UIColor.FromRGBA(64.0f / 255.0f, 64.0f / 255.0f, 65.0f / 255.0f, 1.0f); chart.AddChartBehavior(tooltip); this.AddSubview(chart); this.OptionView = new UIView(); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } class HistogramTooltipFormatter : SFChartDelegate { int interval = 20; public override void WillShowTooltip(SFChart chart, SFChartTooltip tooltipView) { UIView customView = new UIView(); customView.Frame = new CGRect(0, 0, 65, 45); UILabel label = new UILabel(); label.Frame = new CGRect(20, 0, 180, 18); label.TextColor = UIColor.White; label.Font = UIFont.FromName("Helvetica", 12f); label.Text = "Score"; UILabel box = new UILabel(); box.Frame = new CGRect(customView.Frame.X, label.Frame.Height + 2, customView.Frame.Width, 1); box.BackgroundColor = UIColor.White; var data = tooltipView.DataPoint as List<object>; int x = 0; int index = (int)(data[0] as ChartDataModel).YValue / interval; x = interval * index; UILabel xLabel = new UILabel(); xLabel.Frame = new CGRect(5, 25, 80, 18); xLabel.TextColor = UIColor.LightGray; xLabel.Font = UIFont.FromName("Helvetica", 12f); xLabel.Text = x + "-" + (x + interval) + " : "; UILabel xValue = new UILabel(); xValue.Frame = index == 4 ? new CGRect(52, 25, 35, 18) : new CGRect(45, 25, 35, 18); xValue.TextColor = UIColor.White; xValue.Font = UIFont.FromName("Helvetica", 12f); xValue.Text = data.Count.ToString(); customView.AddSubview(label); customView.AddSubview(box); customView.AddSubview(xLabel); customView.AddSubview(xValue); tooltipView.CustomView = customView; } } }<file_sep>/iOS/SampleBrowser/Samples/Sunburst/SunburstSelection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSunburstChart.iOS; using CoreGraphics; using UIKit; using System.Collections.ObjectModel; using System.Drawing; namespace SampleBrowser { public class SunburstSelection : SampleView { SfSunburstChart chart; UIPickerView selectionModePicker; UIPickerView selectionTypePicker; UIView option; public ObservableCollection<SunburstModel> Population_Data { get; set; } public SunburstSelection() { selectionModePicker = new UIPickerView(); selectionTypePicker = new UIPickerView(); option = new UIView(); this.Population_Data = new ObservableCollection<SunburstModel> { new SunburstModel { State = "Ontario", Continent = "North America", Country = "Canada", Population = 13210600 }, new SunburstModel { State = "New York", Continent = "North America", Country = "United States", Population = 19378102 }, new SunburstModel { State = "Pennsylvania", Continent = "North America", Country = "United States", Population = 12702379 }, new SunburstModel { State = "Ohio", Continent = "North America", Country = "United States", Population = 11536504 }, new SunburstModel { State = "Buenos Aires", Continent = "South America", Country = "Argentina", Population = 15594428 }, new SunburstModel { State = "Minas Gerais", Continent = "South America", Country = "Brazil", Population = 20593366 }, new SunburstModel { State = "Rio de Janeiro", Continent = "South America", Country = "Brazil", Population = 16369178 }, new SunburstModel { State = "Bahia", Continent = "South America", Country = "Brazil", Population = 15044127 }, new SunburstModel { State = "Rio Grande do Sul", Continent = "South America", Country = "Brazil", Population = 11164050 }, new SunburstModel { State = "Parana", Continent = "South America", Country = "Brazil", Population = 10997462 }, new SunburstModel { State = "Chittagong", Continent = "Asia", Country = "Bangladesh", Population = 28079000 }, new SunburstModel { State = "Rajshahi", Continent = "Asia", Country = "Bangladesh", Population = 18329000 }, new SunburstModel { State = "Khulna", Continent = "Asia", Country = "Bangladesh", Population = 15563000 }, new SunburstModel { State = "Liaoning", Continent = "Asia", Country = "China", Population = 43746323 }, new SunburstModel { State = "Shaanxi", Continent = "Asia", Country = "China", Population = 37327378 }, new SunburstModel { State = "Fujian", Continent = "Asia", Country = "China", Population = 36894216 }, new SunburstModel { State = "Shanxi", Continent = "Asia", Country = "China", Population = 35712111 }, new SunburstModel { State = "Kerala", Continent = "Asia", Country = "India", Population = 33387677 }, new SunburstModel { State = "Punjab", Continent = "Asia", Country = "India", Population = 27704236 }, new SunburstModel { State = "Haryana", Continent = "Asia", Country = "India", Population = 25353081 }, new SunburstModel { State = "Delhi", Continent = "Asia", Country = "India", Population = 16753235 }, new SunburstModel { State = "Jammu", Continent = "Asia", Country = "India", Population = 12548926 }, new SunburstModel { State = "West Java", Continent = "Asia", Country = "Indonesia", Population = 43021826 }, new SunburstModel { State = "East Java", Continent = "Asia", Country = "Indonesia", Population = 37476011 }, new SunburstModel { State = "Banten", Continent = "Asia", Country = "Indonesia", Population = 10644030 }, new SunburstModel { State = "Jakarta", Continent = "Asia", Country = "Indonesia", Population = 10187595 }, new SunburstModel { State = "Tianjin", Continent = "Africa", Country = "Ethiopia", Population = 24000200 }, new SunburstModel { State = "Tianjin", Continent = "Africa", Country = "Ethiopia", Population = 15042531 }, new SunburstModel { State = "Rift Valley", Continent = "Africa", Country = "Kenya", Population = 10006805 }, new SunburstModel { State = "Lagos", Continent = "Africa", Country = "Nigeria", Population = 10006805 }, new SunburstModel { State = "Kano", Continent = "Africa", Country = "Nigeria", Population = 10006805 }, new SunburstModel { State = "Gauteng", Continent = "Africa", Country = "South Africa", Population = 12728400 }, new SunburstModel { State = "KwaZulu-Natal", Continent = "Africa", Country = "South Africa", Population = 10456900 }, new SunburstModel { State = "Ile-de- France", Continent = "Europe", Country = "France", Population = 11694000 }, new SunburstModel { State = "North Rhine-Westphalia", Continent = "Europe", Country = "Germany", Population = 17872863 }, new SunburstModel { State = "Bavaria", Continent = "Europe", Country = "Germany", Population = 12510331 }, new SunburstModel { State = "NBaden-Wurttemberg", Continent = "Europe", Country = "Germany", Population = 10747479 }, new SunburstModel { State = "England", Continent = "Europe", Country = "United Kingdom", Population = 51446600 } }; chart = new SfSunburstChart(); chart.ItemsSource = Population_Data; chart.Radius = 0.95; chart.ValueMemberPath = "Population"; var levels = new SunburstLevelCollection() { new SunburstHierarchicalLevel() { GroupMemberPath = "Continent"}, new SunburstHierarchicalLevel() { GroupMemberPath = "Country"}, new SunburstHierarchicalLevel() { GroupMemberPath = "State"} }; chart.Levels = levels; chart.Title.IsVisible = true; chart.Title.Text = "Population Data"; chart.Title.Font= UIFont.SystemFontOfSize(20); chart.Title.Margin = new UIEdgeInsets(10, 5, 5, 5); chart.Legend.IsVisible = true; chart.Legend.LabelStyle.Font= UIFont.SystemFontOfSize(16); chart.Legend.IconHeight = 12; chart.Legend.IconWidth = 12; chart.SelectionSettings.EnableSelection = true; chart.DataLabel.ShowLabel = true; this.AddSubview(chart); CreateOptionView(); this.OptionView = option; } public override void LayoutSubviews() { base.LayoutSubviews(); chart.Frame = new CGRect(Frame.Location.X, 0, this.Frame.Width, this.Frame.Height); } private void CreateOptionView() { UILabel selectionMode = new UILabel(); selectionMode.Text = "Selection Mode"; selectionMode.TextAlignment = UITextAlignment.Left; selectionMode.TextColor = UIColor.Black; selectionMode.Frame = new CGRect(10, 20, 120, 20); selectionMode.Font = UIFont.FromName("Helvetica", 14f); UILabel selectionType = new UILabel(); selectionType.Text = "Selection Type"; selectionType.TextAlignment = UITextAlignment.Left; selectionType.TextColor = UIColor.Black; selectionType.Frame = new CGRect(10, 80, 120, 20); selectionType.Font = UIFont.FromName("Helvetica", 14f); List<string> position1 = new List<string> { "Opacity", "Color", "Stroke" }; var picker1 = new SelectionPickerModel(position1); selectionModePicker.Model = picker1; selectionModePicker.SelectedRowInComponent(0); selectionModePicker.Frame = new CGRect(140, 10, 150, 40); picker1.ValueChanged += (sender, e) => { if (picker1.SelectedValue == "Opacity") { chart.SelectionSettings.SelectionDisplayMode = SelectionDisplayMode.HighlightByOpacity; } else if (picker1.SelectedValue == "Color") { chart.SelectionSettings.SelectionDisplayMode = SelectionDisplayMode.HighlightByColor; } else if (picker1.SelectedValue == "Stroke") { chart.SelectionSettings.SelectionDisplayMode = SelectionDisplayMode.HighlightByStroke; } }; List<string> position2 = new List<string> { "Child", "Group", "Parent" , "Single"}; var picker2 = new SelectionPickerModel(position2); selectionTypePicker.Model = picker2; selectionTypePicker.SelectedRowInComponent(0); selectionTypePicker.Frame = new CGRect(140, 70, 150, 40); picker2.ValueChanged += (sender, e) => { if (picker2.SelectedValue == "Child") { chart.SelectionSettings.SelectionType = SelectionType.Child; } else if (picker2.SelectedValue == "Group") { chart.SelectionSettings.SelectionType = SelectionType.Group; } else if (picker2.SelectedValue == "Parent") { chart.SelectionSettings.SelectionType = SelectionType.Parent; } else if (picker2.SelectedValue == "Single") { chart.SelectionSettings.SelectionType = SelectionType.Single; } }; this.option.AddSubview(selectionMode); this.option.AddSubview(selectionType); this.option.AddSubview(selectionModePicker); this.option.AddSubview(selectionTypePicker); } } public class SelectionPickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public SelectionPickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; ; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); } } }<file_sep>/iOS/SampleBrowser/Samples/Sunburst/DrillDown.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSunburstChart.iOS; using CoreGraphics; using UIKit; using System.Collections.ObjectModel; namespace SampleBrowser { public class DrillDown : SampleView { SfSunburstChart chart; UILabel label; public ObservableCollection<SunburstModel> DataSource { get; set; } public DrillDown() { this.DataSource = new ObservableCollection<SunburstModel> { new SunburstModel { Country = "USA", JobDescription = "Sales", JobGroup="Executive", EmployeesCount = 50 }, new SunburstModel { Country = "USA", JobDescription = "Sales", JobGroup = "Analyst", EmployeesCount = 40 }, new SunburstModel { Country = "USA", JobDescription = "Marketing", EmployeesCount = 40 }, new SunburstModel { Country = "USA", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 35 }, new SunburstModel { Country = "USA", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 175 }, new SunburstModel { Country = "USA", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 70 }, new SunburstModel { Country = "USA", JobDescription = "Management", EmployeesCount = 40 }, new SunburstModel { Country = "USA", JobDescription = "Accounts", EmployeesCount = 60 }, new SunburstModel { Country = "India", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 33 }, new SunburstModel { Country = "India", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 125 }, new SunburstModel { Country = "India", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 60 }, new SunburstModel { Country = "India", JobDescription = "HR Executives", EmployeesCount = 70 }, new SunburstModel { Country = "India", JobDescription = "Accounts", EmployeesCount = 45 }, new SunburstModel { Country = "Germany", JobDescription = "Sales", JobGroup = "Executive", EmployeesCount = 30 }, new SunburstModel { Country = "Germany", JobDescription = "Sales", JobGroup = "Analyst", EmployeesCount = 40 }, new SunburstModel { Country = "Germany", JobDescription = "Marketing", EmployeesCount = 50 }, new SunburstModel { Country = "Germany", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 40 }, new SunburstModel { Country = "Germany", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 65 }, new SunburstModel { Country = "Germany", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 27 }, new SunburstModel { Country = "Germany", JobDescription = "Management", EmployeesCount = 33 }, new SunburstModel { Country = "Germany", JobDescription = "Accounts", EmployeesCount = 55 }, new SunburstModel { Country = "UK", JobDescription = "Technical", JobGroup = "Testers", EmployeesCount = 25 }, new SunburstModel { Country = "UK", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Windows", EmployeesCount = 96 }, new SunburstModel { Country = "UK", JobDescription = "Technical", JobGroup = "Developers", JobRole = "Web", EmployeesCount = 55 }, new SunburstModel { Country = "UK", JobDescription = "HR Executives", EmployeesCount = 60 }, new SunburstModel { Country = "UK", JobDescription = "Accounts", EmployeesCount = 30 } }; chart = new SfSunburstChart(); chart.ItemsSource = DataSource; chart.Radius = 0.95; chart.ValueMemberPath = "EmployeesCount"; var levels = new SunburstLevelCollection() { new SunburstHierarchicalLevel() { GroupMemberPath = "Country"}, new SunburstHierarchicalLevel() { GroupMemberPath = "JobDescription"}, new SunburstHierarchicalLevel() { GroupMemberPath = "JobGroup"}, new SunburstHierarchicalLevel() { GroupMemberPath = "JobRole"} }; chart.Levels = levels; chart.Title.IsVisible = true; chart.Title.Text = "Employee Count"; chart.Title.Font= UIFont.SystemFontOfSize(20); chart.Title.Margin = new UIEdgeInsets(10, 5, 5, 5); chart.Legend.IsVisible = true; chart.Legend.LegendPosition = SunburstDockPosition.Top; chart.Legend.LabelStyle.Font= UIFont.SystemFontOfSize(16); chart.Legend.IconHeight = 12; chart.Legend.IconWidth = 12; chart.DrilldownSettings.Enable = true; chart.DataLabel.ShowLabel = true; label = new UILabel(); label.Text = "Double tap on the segment to perform drill down."; label.TextColor = UIColor.Black; label.TextAlignment = UITextAlignment.Center; label.Font= UIFont.FromName("Helvetica", 12f); this.AddSubview(chart); this.AddSubview(label); } public override void LayoutSubviews() { base.LayoutSubviews(); chart.Frame = new CGRect(Frame.Location.X, 0, this.Frame.Width, this.Frame.Height); label.Frame = new CGRect(0, Frame.Height - 20, Frame.Width, 20); } } }<file_sep>/Forms/Schedule/Schedule/Samples/AppointmentEditor/ViewModels/EditorLayoutViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser.SfSchedule { /// <summary> /// Editor Layout View Model class /// </summary> internal class EditorLayoutViewModel { /// <summary> /// method for appointment modified /// </summary> /// <param name="e">Schedule Appointment Modified Event Args</param> public virtual void OnAppointmentModified(ScheduleAppointmentModifiedEventArgs e) { EventHandler<ScheduleAppointmentModifiedEventArgs> handler = this.AppointmentModified; if (handler != null) { handler(this, e); } } /// <summary> /// Event handler /// </summary> public event EventHandler<ScheduleAppointmentModifiedEventArgs> AppointmentModified; } /// <summary> /// schedule appointment modified event args /// </summary> public class ScheduleAppointmentModifiedEventArgs : EventArgs { /// <summary> /// Gets or sets appointment /// </summary> public Meeting Appointment { get; set; } /// <summary> /// Gets or sets is modified value /// </summary> public bool IsModified { get; set; } } } <file_sep>/Forms/PdfViewer/PdfViewer.iOS/SaveiOS.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; using Foundation; using UIKit; using System.IO; [assembly: Dependency(typeof(SampleBrowser.SfPdfViewer.iOS.SaveiOS))] [assembly: Dependency(typeof(SampleBrowser.SfPdfViewer.iOS.BrowserURI))] namespace SampleBrowser.SfPdfViewer.iOS { public class SaveiOS : ISave { public string Save(MemoryStream fileStream) { string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filepath = Path.Combine(path, "SavedDocument.pdf"); FileStream outputFileStream = File.Open(filepath, FileMode.Create); fileStream.Position = 0; fileStream.CopyTo(outputFileStream); outputFileStream.Close(); return filepath; } } public class BrowserURI : IDeviceOpenURI { public void OpenURI(string selectedText) { Foundation.NSUrl url = new Foundation.NSUrl($"https://www.google.com/search?q={selectedText}"); UIApplication.SharedApplication.OpenUrl(url); } } }<file_sep>/Forms/SegmentedControl/readme.md The `SfSegmentedControl` lets users choose from a linear set of two or more segments, each functioning as a button. The following sample is available for segmented control to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](SegementedControl/Samples/SegmentViewGettingStarted)|It demonstrates the following functionalities of segmented control like displaying the segments with text, font icons and handling the selection on segmented items.| |[Customization](SegementedControl/Samples/SegmentCustomization)| It demonstrates the available customization options in segmented view.| |[Switches and Tokens](SegementedControl/Samples/Tokens)| It shows segmented controls like switches and tokens by customization support.| |[Custom Views](SegementedControl/Samples/SegmentCustomView)| It show cases the support for setting custom views in segmented items.| <file_sep>/Android/SampleBrowser/Samples/DataSource/DataSourceGrouping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syncfusion.DataSource; using Android.Widget; using Android.Views; using Android.Graphics; namespace SampleBrowser { public class DataSourceGrouping : SamplePage, IDisposable { #region Fields private DataSource dataSource; private ContatsViewModel viewModel; private ListView listView; private SearchView filterText; #endregion #region Override public override Android.Views.View GetSampleContent(Android.Content.Context context) { LinearLayout linear = new LinearLayout(context) { Orientation = Orientation.Vertical }; listView = new ListView(context); viewModel = new ContatsViewModel(); dataSource = new DataSource(); dataSource.Source = viewModel.ContactsList; dataSource.LiveDataUpdateMode = LiveDataUpdateMode.AllowDataShaping; listView.Adapter = new ContactsAdapter(dataSource, context); dataSource.SortDescriptors.Add(new SortDescriptor("ContactName")); dataSource.GroupDescriptors.Add(new GroupDescriptor() { PropertyName = "ContactName", KeySelector = (object obj1) => { var item = obj1 as Contacts; return item.ContactName[0].ToString(); } }); filterText = new SearchView(context); filterText.SetIconifiedByDefault(false); filterText.SetPadding(0, 0, 0, (int)(10 * context.Resources.DisplayMetrics.Density)); filterText.SetQueryHint("Search contact"); filterText.QueryTextChange += OnFilterTextChanged; linear.AddView(new LinearLayout(context) { Focusable = true, FocusableInTouchMode = true }, 0, 0); linear.AddView(filterText); linear.AddView(listView); return linear; } private void OnFilterTextChanged(object sender, SearchView.QueryTextChangeEventArgs e) { if (dataSource != null) { this.dataSource.Filter = FilterContacts; this.dataSource.RefreshFilter(); } } private bool FilterContacts(object obj) { var contacts = obj as Contacts; if (contacts.ContactName.ToLower().Contains(filterText.Query.ToLower()) || contacts.ContactNumber.ToLower().Contains(filterText.Query.ToLower())) { return true; } else { return false; } } #endregion public void Dispose() { if (dataSource != null) { dataSource.Dispose(); dataSource = null; } if (listView != null) { listView.Dispose(); listView = null; } if (filterText != null) { filterText.Dispose(); filterText = null; } } } }<file_sep>/Android/SampleBrowser/Samples/Maps/DataLabels.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Com.Syncfusion.Maps; using Org.Json; using System.Collections.Generic; using Android.Graphics; using Android.Widget; using Android.OS; using Com.Syncfusion.Sfbusyindicator; using Com.Syncfusion.Sfbusyindicator.Enums; using Android.Views; namespace SampleBrowser { public class DataLabels : SamplePage { SfMaps maps; Handler handler; List<String> adapter; List<String> smartLabelAdapter; ShapeFileLayer layer; public override Android.Views.View GetSampleContent(Android.Content.Context context) { handler = new Handler(); LinearLayout layout = new LinearLayout(context); layout.Orientation = Orientation.Vertical; maps = new SfMaps(context); layer = new ShapeFileLayer(); layer.Uri = "usa_state.shp"; layer.ShowItems = true; layer.EnableSelection = false; layer.ShapeIdTableField = "STATE_NAME"; layer.ShapeIdPath = "Name"; layer.ShapeSettings.ShapeFill = Color.ParseColor("#A9D9F7"); layer.ShapeSettings.ShapeValuePath = "Name"; layer.ShapeSettings.ShapeColorValuePath = "Type"; layer.DataSource = GetDataSource(); SetColorMapping(layer.ShapeSettings); layer.DataLabelSettings.IntersectionAction = IntersectAction.None; layer.DataLabelSettings.SmartLabelMode = IntersectAction.Trim; layer.TooltipSettings.ShowTooltip = true; layer.TooltipSettings.ValuePath = "Name"; maps.Layers.Add(layer); SfBusyIndicator sfBusyIndicator = new SfBusyIndicator(context); sfBusyIndicator.IsBusy = true; sfBusyIndicator.AnimationType = AnimationTypes.SlicedCircle; sfBusyIndicator.ViewBoxWidth = 50; sfBusyIndicator.ViewBoxHeight = 50; sfBusyIndicator.TextColor = Color.ParseColor("#779772"); layout.AddView(sfBusyIndicator); Java.Lang.Runnable run = new Java.Lang.Runnable(() => { layout.RemoveView(sfBusyIndicator); layout.AddView(maps); }); handler.PostDelayed(run, 100); return layout; } JSONArray GetDataSource() { JSONArray array = new JSONArray(); array.Put(getJsonObject("Alabama", "Vegetables", 9)); array.Put(getJsonObject("Alaska", "Vegetables", 3)); array.Put(getJsonObject("Arizona", "Rice", 11)); array.Put(getJsonObject("Arkansas", "Vegetables", 6)); array.Put(getJsonObject("California", "Rice", 55)); array.Put(getJsonObject("Colorado", "Rice", 9)); array.Put(getJsonObject("Connecticut", "Grains", 7)); array.Put(getJsonObject("Delaware", "Grains", 3)); array.Put(getJsonObject("District of Columbia", "Grains", 3)); array.Put(getJsonObject("Florida", "Rice", 29)); array.Put(getJsonObject("Georgia", "Rice", 16)); array.Put(getJsonObject("Hawaii", "Grains", 4)); array.Put(getJsonObject("Idaho", "Grains", 4)); array.Put(getJsonObject("Illinois", "Vegetables", 20)); array.Put(getJsonObject("Indiana", "Grains", 11)); array.Put(getJsonObject("Iowa", "Vegetables", 6)); array.Put(getJsonObject("Kansas", "Rice", 6)); array.Put(getJsonObject("Kentucky", "Grains", 8)); array.Put(getJsonObject("Louisiana", "Rice", 8)); array.Put(getJsonObject("Maine", "Grains", 4)); array.Put(getJsonObject("Maryland", "Grains", 10)); array.Put(getJsonObject("Massachusetts", "Grains", 11)); array.Put(getJsonObject("Michigan", "Grains", 16)); array.Put(getJsonObject("Minnesota", "Wheat", 10)); array.Put(getJsonObject("Mississippi", "Vegetables", 6)); array.Put(getJsonObject("Missouri", "Vegetables", 10)); array.Put(getJsonObject("Montana", "Grains", 3)); array.Put(getJsonObject("Nebraska", "Rice", 5)); array.Put(getJsonObject("Nevada", "Wheat", 6)); array.Put(getJsonObject("New Hampshire", "Grains", 4)); array.Put(getJsonObject("New Jersey", "Vegetables", 14)); array.Put(getJsonObject("New Mexico", "Rice", 5)); array.Put(getJsonObject("New York", "Vegetables", 29)); array.Put(getJsonObject("North Carolina", "Rice", 15)); array.Put(getJsonObject("North Dakota", "Grains", 3)); array.Put(getJsonObject("Ohio", "Vegetables", 18)); array.Put(getJsonObject("Oklahoma", "Rice", 7)); array.Put(getJsonObject("Oregon", "Wheat", 7)); array.Put(getJsonObject("Pennsylvania", "Vegetables", 20)); array.Put(getJsonObject("Rhode Island", "Grains", 4)); array.Put(getJsonObject("South Carolina", "Rice", 9)); array.Put(getJsonObject("South Dakota", "Grains", 3)); array.Put(getJsonObject("Tennessee", "Vegetables", 11)); array.Put(getJsonObject("Texas", "Vegetables", 38)); array.Put(getJsonObject("Utah", "Rice", 6)); array.Put(getJsonObject("Vermont", "Grains", 3)); array.Put(getJsonObject("Virginia", "Rice", 13)); array.Put(getJsonObject("Washington", "Vegetables", 12)); array.Put(getJsonObject("West Virginia", "Grains", 5)); array.Put(getJsonObject("Wisconsin", "Grains", 10)); array.Put(getJsonObject("Wyoming", "Wheat", 3)); return array; } JSONObject getJsonObject(String name, String type, double count) { JSONObject obj = new JSONObject(); obj.Put("Name", name); obj.Put("Type", type); return obj; } void SetColorMapping(ShapeSetting setting) { List<ColorMapping> colorMappings = new List<ColorMapping>(); EqualColorMapping colorMapping2 = new EqualColorMapping(); colorMapping2.Value = "Rice"; colorMapping2.Color = Color.ParseColor("#b5e485"); colorMappings.Add(colorMapping2); EqualColorMapping colorMapping3 = new EqualColorMapping(); colorMapping3.Value = "Wheat"; colorMapping3.Color = Color.ParseColor("#9178e3"); colorMappings.Add(colorMapping3); EqualColorMapping colorMapping4 = new EqualColorMapping(); colorMapping4.Value = "Grains"; colorMapping4.Color = Color.ParseColor("#e4c16c"); colorMappings.Add(colorMapping4); EqualColorMapping colorMapping1 = new EqualColorMapping(); colorMapping1.Value = "Vegetables"; colorMapping1.Color = Color.ParseColor("#ec9b79"); colorMappings.Add(colorMapping1); EqualColorMapping colorMapping5 = new EqualColorMapping(); colorMapping5.Value = "Oats"; colorMapping5.Color = Color.ParseColor("#df819c"); colorMappings.Add(colorMapping5); setting.ColorMapping = colorMappings; } public override View GetPropertyWindowLayout(Android.Content.Context context) { TextView smartLabel = new TextView(context); smartLabel.Text = "SmartLabel"; smartLabel.Typeface = Typeface.DefaultBold; smartLabel.SetTextColor(Color.ParseColor("#262626")); smartLabel.TextSize = 20; Spinner smartLabelMode = new Spinner(context, SpinnerMode.Dialog); smartLabelAdapter = new List<String>() { "Trim", "None", "Hide" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, smartLabelAdapter); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); smartLabelMode.Adapter = dataAdapter; smartLabelMode.ItemSelected += SmartLabelMode_ItemSelected; TextView intersection = new TextView(context); intersection.Text = "IntersectAction"; intersection.Typeface = Typeface.DefaultBold; intersection.SetTextColor(Color.ParseColor("#262626")); intersection.TextSize = 20; Spinner intersectionAction = new Spinner(context, SpinnerMode.Dialog); adapter = new List<String>() { "None", "Trim", "Hide" }; ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); intersectionAction.Adapter = dataAdapter1; intersectionAction.ItemSelected += IntersectionAction_ItemSelected; LinearLayout optionsPage = new LinearLayout(context); optionsPage.Orientation = Orientation.Vertical; optionsPage.AddView(smartLabel); optionsPage.AddView(smartLabelMode); optionsPage.AddView(intersection); optionsPage.AddView(intersectionAction); optionsPage.SetPadding(10, 10, 10, 10); optionsPage.SetBackgroundColor(Color.White); return optionsPage; } private void SmartLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = smartLabelAdapter[e.Position]; if (selectedItem.Equals("Trim")) { layer.DataLabelSettings.SmartLabelMode = IntersectAction.Trim; } else if (selectedItem.Equals("None")) { layer.DataLabelSettings.SmartLabelMode = IntersectAction.None; } else if (selectedItem.Equals("Hide")) { layer.DataLabelSettings.SmartLabelMode = IntersectAction.Hide; } } private void IntersectionAction_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter[e.Position]; if (selectedItem.Equals("None")) { layer.DataLabelSettings.IntersectionAction = IntersectAction.None; } else if (selectedItem.Equals("Trim")) { layer.DataLabelSettings.IntersectionAction = IntersectAction.Trim; } else if (selectedItem.Equals("Hide")) { layer.DataLabelSettings.IntersectionAction = IntersectAction.Hide; } } } } <file_sep>/Android/SampleBrowser/Samples/DocIO/WebViewActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Webkit; namespace SampleBrowser { [Activity (Label = "WebView")] public class WebViewActivity : Activity { private WebView m_webView; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); SetContentView (Resource.Layout.HtmlViewer); m_webView = FindViewById<WebView> (Resource.Id.webview); m_webView.Settings.JavaScriptEnabled = true; string htmlString = Intent.GetStringExtra ("HtmlString"); m_webView.LoadDataWithBaseURL (null, htmlString, "text/html", "utf-8", null); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataSource/DataSourceGrouping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Syncfusion.DataSource; using System; using System.Collections.Generic; using System.Text; using UIKit; namespace SampleBrowser { public class DataSourceGrouping : SampleView { #region Fields UITableView tableView; ContatsViewModel viewModel; DataSource sfDataSource; UISearchBar searchbar; #endregion #region Static Methods static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } #endregion #region Constructor public DataSourceGrouping() { tableView = new UITableView(); tableView.AllowsSelection = false; tableView.SeparatorColor = UIColor.Clear; tableView.RowHeight = 70; tableView.EstimatedRowHeight = 70; viewModel = new ContatsViewModel(); sfDataSource = new DataSource(); sfDataSource.Source = viewModel.ContactsList; sfDataSource.LiveDataUpdateMode = LiveDataUpdateMode.AllowDataShaping; sfDataSource.DisplayItems.CollectionChanged += DisplayItems_CollectionChanged; sfDataSource.SortDescriptors.Add(new SortDescriptor("ContactName")); sfDataSource.GroupDescriptors.Add(new GroupDescriptor() { PropertyName = "ContactName", KeySelector = (object obj1) => { var item = (obj1 as Contacts); return item.ContactName[0].ToString(); } }); searchbar = new UISearchBar(); searchbar.OnEditingStarted += HandleOnEditingStarted; searchbar.TextChanged += HandleTextChanged; searchbar.CancelButtonClicked += HandleCancelButtonClicked; searchbar.EnablesReturnKeyAutomatically = false; searchbar.Placeholder = "Search Contact"; tableView.Source = new TableViewSource(sfDataSource); this.AddSubview(searchbar); this.AddSubview (tableView); } #endregion #region Private Methods private void DisplayItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { tableView.ReloadData(); } void HandleCancelButtonClicked(object sender, EventArgs e) { searchbar.ResignFirstResponder(); searchbar.SetShowsCancelButton(false, true); } void HandleTextChanged(object sender, UISearchBarTextChangedEventArgs e) { if (sfDataSource != null) { this.sfDataSource.Filter = FilterContacts; this.sfDataSource.RefreshFilter(); } } void HandleOnEditingStarted(object sender, EventArgs e) { searchbar.SetShowsCancelButton(true, true); } private bool FilterContacts(object obj) { var contacts = obj as Contacts; if (searchbar.Text == null || contacts.ContactName.ToLower().Contains(searchbar.Text.ToLower()) || contacts.ContactNumber.ToLower().Contains(searchbar.Text.ToLower())) return true; else return false; } #endregion #region Override Methods public override void LayoutSubviews () { searchbar.Frame = (new CGRect(0, 0, this.Frame.Width, 40)); if (UIDevice.CurrentDevice.CheckSystemVersion(7, 1)) { searchbar.SizeToFit(); this.tableView.Frame = new CGRect(0, searchbar.Bounds.Height, this.Frame.Width, this.Frame.Height - 44); } else { searchbar.SizeToFit(); this.tableView.Frame = new CGRect(0, searchbar.Bounds.Height, this.Frame.Width, this.Frame.Height - 44); } base.LayoutSubviews(); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Funnel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class Funnel : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Website Visitors"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; FunnelSeries funnelSeries = new FunnelSeries(); funnelSeries.ItemsSource = MainPage.GetFunnelData(); funnelSeries.XBindingPath = "XValue"; funnelSeries.YBindingPath = "YValue"; funnelSeries.DataMarker.ShowLabel = true; funnelSeries.DataMarker.LabelStyle.LabelFormat = "#.#'%'"; funnelSeries.DataMarker.LabelStyle.BackgroundColor = Color.Transparent; funnelSeries.DataMarker.LabelStyle.TextColor = Color.White; funnelSeries.StrokeWidth = 1; funnelSeries.StrokeColor = Color.White; funnelSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; chart.Series.Add(funnelSeries); return chart; } } }<file_sep>/Forms/CircularGauge/CircularGauge/Samples/CustomizationSample/CustomizationSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Xamarin.Forms.Internals; namespace SampleBrowser.SfCircularGauge { [Preserve(AllMembers = true)] public partial class CustomizationSample : SampleView { public CustomizationSample() { InitializeComponent(); header1.Text = Math.Round(viewModel.PointerValue, 2) + " GB"; header2.Text = Math.Round(viewModel.PointerValue, 2) + " GB"; pointer_slider.BindingContext = viewModel; pointer_slider.ValueChanged += Pointer_slider_ValueChanged; rangePointerColorPicker.SelectedIndex = 0; rangePointerColorPicker.SelectedIndexChanged += RangePointerColorPicker_SelectedIndexChanged; needlePointerColorPicker.SelectedIndex = 0; needlePointerColorPicker.SelectedIndexChanged += NeedlePointerColorPicker_SelectedIndexChanged; rangeColorPicker.SelectedIndex = 0; rangeColorPicker.SelectedIndexChanged += RangeColorPicker_SelectedIndexChanged; } private void Pointer_slider_ValueChanged(object sender, EventArgs e) { header1.Text = Math.Round(viewModel.PointerValue, 2) + " GB"; header2.Text = Math.Round(viewModel.PointerValue, 2) + " GB"; } private void RangePointerColorPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (rangePointerColorPicker.SelectedIndex) { case 0: viewModel.RangePointerColor = Color.FromHex("#FFDD00"); break; case 1: viewModel.RangePointerColor = Color.FromHex("#00bdae"); break; case 2: viewModel.RangePointerColor = Color.FromHex("#FF2680"); break; } } private void NeedlePointerColorPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (needlePointerColorPicker.SelectedIndex) { case 0: viewModel.NeedlePointerColor = Color.FromHex("#424242"); break; case 1: viewModel.NeedlePointerColor = Color.FromHex("#6f6fe2"); break; case 2: viewModel.NeedlePointerColor = Color.FromHex("#9e480e"); break; } } private void RangeColorPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (rangeColorPicker.SelectedIndex) { case 0: viewModel.RangeColor = Color.FromHex("#E0E0E0"); break; case 1: viewModel.RangeColor = Color.FromHex("#7bb4eb"); break; case 2: viewModel.RangeColor = Color.FromHex("#ea7e57"); break; } } } } <file_sep>/iOS/SampleBrowser/Samples/NumericTextBox/NumericTextBox_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfNumericTextBox.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class NumericTextBox_Tablet : SampleView { UIPickerView culturePicker; UILabel titleLabel, descriptionLabel, formulaLabel, principalLabel, interestRateLabel, termLabel, interestLabel, cultureLabel, allowNullLabel, propertiesLabel, allowDefaultDecimal; UISwitch allowSwitch, allowDecimalSwitch; UIButton cultureDoneButton, cultureButton; UIView subView = new UIView(); UIView contentView, controlView; UIButton showPropertyButton, closeButton; private string cultureSelectedType; SfNumericTextBox principalNumericTextBox; SfNumericTextBox interestRateNumericTextBox; SfNumericTextBox periodNumericTextBox; SfNumericTextBox outputNumericTextBox; private readonly IList<string> cultureList = new List<string>(); public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; subView.Frame = new CGRect(0, this.Frame.Size.Height - this.Frame.Size.Height / 3 + 75, this.Frame.Size.Width, this.Frame.Height / 3 - 75); controlView.Frame = new CGRect(150, 40, this.Frame.Size.Width - 200, this.Frame.Size.Height - 40); contentView.Frame = new CGRect(0, 40, subView.Frame.Size.Width, subView.Frame.Size.Height - 30); principalNumericTextBox.Frame = new CGRect(15, 170, controlView.Frame.Width - 320, 40); interestRateNumericTextBox.Frame = new CGRect(15, 250, controlView.Frame.Width - 320, 40); periodNumericTextBox.Frame = new CGRect(15, 330, controlView.Frame.Width - 320, 40); outputNumericTextBox.Frame = new CGRect(15, 410, controlView.Frame.Width - 320, 40); titleLabel.Frame = new CGRect(15, 10, controlView.Frame.Size.Width - 20, 50); descriptionLabel.Frame = new CGRect(15, 70, controlView.Frame.Size.Width - 20, 30); formulaLabel.Frame = new CGRect(15, 100, controlView.Frame.Size.Width - 20, 30); principalLabel.Frame = new CGRect(15, 140, controlView.Frame.Size.Width - 20, 30); interestRateLabel.Frame = new CGRect(15, 220, controlView.Frame.Size.Width - 20, 30); termLabel.Frame = new CGRect(15, 300, controlView.Frame.Size.Width - 20, 30); interestLabel.Frame = new CGRect(15, 380, controlView.Frame.Size.Width - 20, 30); cultureLabel.Frame = new CGRect(110, 40, contentView.Frame.Size.Width - 220, 40); cultureButton.Frame = new CGRect(350, 40, contentView.Frame.Size.Width - 520, 40); allowNullLabel.Frame = new CGRect(110, 100, contentView.Frame.Size.Width - 220, 40); allowSwitch.Frame = new CGRect(350, 100, contentView.Frame.Size.Width - 220, 40); allowDefaultDecimal.Frame = new CGRect(110, 140, contentView.Frame.Size.Width - 220, 40); allowDecimalSwitch.Frame = new CGRect(350, 140, contentView.Frame.Size.Width - 220, 40); culturePicker.Frame = new CGRect(100, 20, contentView.Frame.Size.Width - 200, 150); cultureDoneButton.Frame = new CGRect(100, 0, contentView.Frame.Size.Width - 200, 40); showPropertyButton.Frame = new CGRect(0, this.Frame.Size.Height - 25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect(this.Frame.Size.Width - 30, 5, 20, 30); propertiesLabel.Frame = new CGRect(10, 5, this.Frame.Width, 30); } base.LayoutSubviews(); } static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public NumericTextBox_Tablet() { controlView = new UIView(); //principalNumericTextBox principalNumericTextBox = new SfNumericTextBox(); principalNumericTextBox.Watermark = "Enter Principal"; principalNumericTextBox.AllowNull = true; principalNumericTextBox.MaximumNumberDecimalDigits = 2; principalNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; principalNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnKeyFocus; principalNumericTextBox.FormatString = "c"; principalNumericTextBox.Value = 1000; principalNumericTextBox.Layer.CornerRadius = 8; principalNumericTextBox.ClipsToBounds = true; principalNumericTextBox.Layer.BorderWidth = (nfloat)1.2; principalNumericTextBox.Layer.BorderColor = UIColor.Black.CGColor; principalNumericTextBox.CultureInfo = new NSLocale("en_US"); principalNumericTextBox.AllowDefaultDecimalDigits = true; controlView.AddSubview(principalNumericTextBox); //interestRateNumericTextBox interestRateNumericTextBox = new SfNumericTextBox(); interestRateNumericTextBox.Watermark = "Enter RI"; interestRateNumericTextBox.AllowNull = true; interestRateNumericTextBox.Layer.CornerRadius = 8; interestRateNumericTextBox.ClipsToBounds = true; interestRateNumericTextBox.Layer.BorderWidth = (nfloat)1.2; interestRateNumericTextBox.MaximumNumberDecimalDigits = 1; interestRateNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; interestRateNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnKeyFocus; interestRateNumericTextBox.ClearButtonMode = UITextFieldViewMode.WhileEditing; interestRateNumericTextBox.FormatString = @"p"; interestRateNumericTextBox.Value = 0.2f; interestRateNumericTextBox.CultureInfo = new NSLocale("en_US"); interestRateNumericTextBox.AllowDefaultDecimalDigits = true; controlView.AddSubview(interestRateNumericTextBox); //periodNumericTextBox periodNumericTextBox = new SfNumericTextBox(); periodNumericTextBox.Watermark = @"Enter Years"; periodNumericTextBox.AllowNull = true; periodNumericTextBox.MaximumNumberDecimalDigits = 0; periodNumericTextBox.Layer.CornerRadius = 8; periodNumericTextBox.ClipsToBounds = true; periodNumericTextBox.Layer.BorderWidth = (nfloat)1.2; periodNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; periodNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnKeyFocus; periodNumericTextBox.FormatString = @"years"; periodNumericTextBox.Value = 20; periodNumericTextBox.CultureInfo = new NSLocale("en_US"); controlView.AddSubview(periodNumericTextBox); //outputNumericTextBox outputNumericTextBox = new SfNumericTextBox(); outputNumericTextBox.Watermark = @"Enter a number"; outputNumericTextBox.AllowNull = true; outputNumericTextBox.MaximumNumberDecimalDigits = 0; outputNumericTextBox.Layer.CornerRadius = 8; outputNumericTextBox.ClipsToBounds = true; outputNumericTextBox.Layer.BorderWidth = (nfloat)1.2; outputNumericTextBox.PercentDisplayMode = SFNumericTextBoxPercentDisplayMode.Compute; outputNumericTextBox.ValueChangeMode = SFNumericTextBoxValueChangeMode.OnLostFocus; outputNumericTextBox.FormatString = @"c"; outputNumericTextBox.Value = 2000; outputNumericTextBox.Enabled = false; outputNumericTextBox.TextColor = UIColor.Gray; outputNumericTextBox.CultureInfo = new NSLocale("en_US"); controlView.AddSubview(outputNumericTextBox); this.AddSubview(controlView); principalNumericTextBox.ValueChanged += Box_ValueChanged; periodNumericTextBox.ValueChanged += Box_ValueChanged; interestRateNumericTextBox.ValueChanged += Box_ValueChanged; this.mainPageDesign(); this.loadOptionView(); } void Box_ValueChanged(object sender, ValueEventArgs e) { outputNumericTextBox.Value = Convert.ToDecimal(principalNumericTextBox.Value) * Convert.ToDecimal(interestRateNumericTextBox.Value) * Convert.ToDecimal(periodNumericTextBox.Value); } public void mainPageDesign() { //titleLabell titleLabel = new UILabel(); titleLabel.TextColor = UIColor.Black; titleLabel.BackgroundColor = UIColor.Clear; titleLabel.Text = @"Simple Interest Calculator"; titleLabel.TextAlignment = UITextAlignment.Left; titleLabel.Font = UIFont.FromName("Helvetica-Bold", 22f); controlView.AddSubview(titleLabel); //descriptionLabell descriptionLabel = new UILabel(); descriptionLabel.TextColor = UIColor.Black; descriptionLabel.BackgroundColor = UIColor.Clear; descriptionLabel.Text = @"The formula for finding simple interest "; descriptionLabel.TextAlignment = UITextAlignment.Left; descriptionLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(descriptionLabel); //formulaLabell formulaLabel = new UILabel(); formulaLabel.TextColor = UIColor.Black; formulaLabel.BackgroundColor = UIColor.Clear; formulaLabel.Text = @"Amount = Principal * Rate * Time"; formulaLabel.TextAlignment = UITextAlignment.Left; formulaLabel.Font = UIFont.ItalicSystemFontOfSize(16f); controlView.AddSubview(formulaLabel); //principalLabell principalLabel = new UILabel(); principalLabel.TextColor = UIColor.Black; principalLabel.BackgroundColor = UIColor.Clear; principalLabel.Text = @"Principal"; principalLabel.Font = UIFont.FromName("Helvetica", 16f); principalLabel.TextAlignment = UITextAlignment.Left; controlView.AddSubview(principalLabel); //interestRateLabell interestRateLabel = new UILabel(); interestRateLabel.TextColor = UIColor.Black; interestRateLabel.BackgroundColor = UIColor.Clear; interestRateLabel.Font = UIFont.FromName("Helvetica", 16f); interestRateLabel.Text = @"Interest Rate"; interestRateLabel.TextAlignment = UITextAlignment.Left; controlView.AddSubview(interestRateLabel); //termLabell termLabel = new UILabel(); termLabel.TextColor = UIColor.Black; termLabel.BackgroundColor = UIColor.Clear; termLabel.Text = @"Term (in years)"; termLabel.TextAlignment = UITextAlignment.Left; termLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(termLabel); //interestLabell interestLabel = new UILabel(); interestLabel.TextColor = UIColor.Black; interestLabel.BackgroundColor = UIColor.Clear; interestLabel.Text = @"Amount"; interestLabel.TextAlignment = UITextAlignment.Left; interestLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(interestLabel); } public void loadOptionView() { contentView = new UIView(); //allowNullLabel allowNullLabel = new UILabel(); allowNullLabel.TextColor = UIColor.Black; allowNullLabel.BackgroundColor = UIColor.Clear; allowNullLabel.Text = @"Allow Null"; allowNullLabel.TextAlignment = UITextAlignment.Left; allowNullLabel.Font = UIFont.FromName("Helvetica", 14f); contentView.AddSubview(allowNullLabel); //allowSwitch allowSwitch = new UISwitch(); allowSwitch.OnTintColor = UIColor.FromRGB(50, 150, 221); allowSwitch.ValueChanged += allowNullToggleChanged; allowSwitch.On = true; contentView.AddSubview(allowSwitch); //cultureLabel cultureLabel = new UILabel(); cultureLabel.TextColor = UIColor.Black; cultureLabel.BackgroundColor = UIColor.Clear; cultureLabel.Text = @"Culture"; cultureLabel.TextAlignment = UITextAlignment.Left; cultureLabel.Font = UIFont.FromName("Helvetica", 14f); contentView.AddSubview(cultureLabel); //adding locale to culture listt this.cultureList.Add((NSString)"United States"); this.cultureList.Add((NSString)"United Kingdom"); this.cultureList.Add((NSString)"Japan"); this.cultureList.Add((NSString)"France"); this.cultureList.Add((NSString)"Italy"); //cultureButton cultureButton = new UIButton(); cultureButton.SetTitle("United States", UIControlState.Normal); cultureButton.Font = UIFont.FromName("Helvetica", 14f); cultureButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; cultureButton.BackgroundColor = UIColor.Clear; cultureButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureButton.Hidden = false; cultureButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; cultureButton.Layer.BorderWidth = 4; cultureButton.Layer.CornerRadius = 8; cultureButton.TouchUpInside += (object sender, EventArgs e) => { cultureDoneButton.Hidden = false; culturePicker.Hidden = false; allowNullLabel.Hidden = true; allowSwitch.Hidden = true; }; contentView.AddSubview(cultureButton); //culturePickerModel PickerModel culturePickermodel = new PickerModel(this.cultureList); culturePickermodel.PickerChanged += (sender, e) => { this.cultureSelectedType = e.SelectedValue; cultureButton.SetTitle(cultureSelectedType, UIControlState.Normal); if (cultureSelectedType == "United States") { principalNumericTextBox.CultureInfo = new NSLocale("en_US"); interestRateNumericTextBox.CultureInfo = new NSLocale("en_US"); periodNumericTextBox.CultureInfo = new NSLocale("en_US"); outputNumericTextBox.CultureInfo = new NSLocale("en_US"); } else if (cultureSelectedType == "United Kingdom") { principalNumericTextBox.CultureInfo = new NSLocale("en_UK"); interestRateNumericTextBox.CultureInfo = new NSLocale("en_UK"); periodNumericTextBox.CultureInfo = new NSLocale("en_UK"); outputNumericTextBox.CultureInfo = new NSLocale("en_UK"); } else if (cultureSelectedType == "Japan") { principalNumericTextBox.CultureInfo = new NSLocale("ja_JP"); interestRateNumericTextBox.CultureInfo = new NSLocale("ja_JP"); periodNumericTextBox.CultureInfo = new NSLocale("ja_JP"); outputNumericTextBox.CultureInfo = new NSLocale("ja_JP"); } else if (cultureSelectedType == "France") { principalNumericTextBox.CultureInfo = new NSLocale("fr_FR"); interestRateNumericTextBox.CultureInfo = new NSLocale("fr_FR"); periodNumericTextBox.CultureInfo = new NSLocale("fr_FR"); outputNumericTextBox.CultureInfo = new NSLocale("fr_FR"); } else if (cultureSelectedType == "Italy") { principalNumericTextBox.CultureInfo = new NSLocale("it_IT"); interestRateNumericTextBox.CultureInfo = new NSLocale("it_IT"); periodNumericTextBox.CultureInfo = new NSLocale("it_IT"); outputNumericTextBox.CultureInfo = new NSLocale("it_IT"); } }; //culturePicker culturePicker = new UIPickerView(); culturePicker.ShowSelectionIndicator = true; culturePicker.Hidden = true; culturePicker.Model = culturePickermodel; culturePicker.BackgroundColor = UIColor.Gray; contentView.AddSubview(culturePicker); //cultureDoneButton cultureDoneButton = new UIButton(); cultureDoneButton.SetTitle("Done\t", UIControlState.Normal); cultureDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; cultureDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); cultureDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureDoneButton.Hidden = true; cultureDoneButton.Font = UIFont.FromName("Helvetica", 14f); cultureDoneButton.TouchUpInside += HideCulturePicker; contentView.AddSubview(cultureDoneButton); //allowDefaultDecimal allowDefaultDecimal = new UILabel(); allowDefaultDecimal.TextColor = UIColor.Black; allowDefaultDecimal.BackgroundColor = UIColor.Clear; allowDefaultDecimal.Text = @"Allow Default Decimal Digits"; allowDefaultDecimal.TextAlignment = UITextAlignment.Left; allowDefaultDecimal.Font = UIFont.FromName("Helvetica", 16f); contentView.AddSubview(allowDefaultDecimal); //allowDecimalSwitchh allowDecimalSwitch = new UISwitch(); allowDecimalSwitch.ValueChanged += AllowDecimalSwitch_ValueChanged; allowDecimalSwitch.On = false; contentView.AddSubview(allowDecimalSwitch); //propertiesLabel propertiesLabel = new UILabel(); propertiesLabel.Text = "OPTIONS"; //showPropertyButton showPropertyButton = new UIButton(); showPropertyButton.Hidden = true; showPropertyButton.SetTitle(" OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = false; showPropertyButton.Hidden = true; }; this.AddSubview(showPropertyButton); //closeButton closeButton = new UIButton(); closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; }; //subVieww subView.AddSubview(closeButton); subView.AddSubview(propertiesLabel); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); contentView.BackgroundColor = UIColor.FromRGB(240, 240, 240); subView.AddSubview(contentView); this.AddSubview(subView); //AddingGesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer(() => { subView.Hidden = true; showPropertyButton.Hidden = false; } ); propertiesLabel.UserInteractionEnabled = true; propertiesLabel.AddGestureRecognizer(tapgesture); } private void AllowDecimalSwitch_ValueChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { principalNumericTextBox.AllowDefaultDecimalDigits = true; interestRateNumericTextBox.AllowDefaultDecimalDigits = true; } else { principalNumericTextBox.AllowDefaultDecimalDigits = false; interestRateNumericTextBox.AllowDefaultDecimalDigits = false; } } void ShowCulturePicker(object sender, EventArgs e) { cultureDoneButton.Hidden = false; culturePicker.Hidden = false; allowNullLabel.Hidden = true; allowSwitch.Hidden = true; cultureLabel.Hidden = true; this.BecomeFirstResponder(); } void HideCulturePicker(object sender, EventArgs e) { cultureDoneButton.Hidden = true; culturePicker.Hidden = true; allowNullLabel.Hidden = false; allowSwitch.Hidden = false; cultureLabel.Hidden = false; this.BecomeFirstResponder(); } private void allowNullToggleChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { principalNumericTextBox.AllowNull = true; interestRateNumericTextBox.AllowNull = true; periodNumericTextBox.AllowNull = true; outputNumericTextBox.AllowNull = true; } else { principalNumericTextBox.AllowNull = false; interestRateNumericTextBox.AllowNull = false; periodNumericTextBox.AllowNull = false; outputNumericTextBox.AllowNull = false; } } public override void TouchesBegan(NSSet touches, UIEvent evt) { this.EndEditing(true); } } } <file_sep>/Android/SampleBrowser/Samples/DigitalGauge/DigitalGauge_Tab.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any indigitalGaugeLayoutingement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfDigitalGauge; using System.Reflection.Emit; using Java.Text; using Java.Lang; using Android.Graphics; using Java.Util; namespace SampleBrowser { public class DigitalGauge_Tab : SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ SfDigitalGauge segmentSevenGauge; SfDigitalGauge segmentFourteenGauge; SfDigitalGauge segmentSixteenGauge; SfDigitalGauge segmentMatrixGauge; TextView segmentSevenText, segmentFourteenText, segmentSixteenText, segmentMatrixText, segmentSeven, segmentFourteen, segmentSixteen, segmentMatrix; Context con; int totalHeight; LinearLayout segmentSixteenLayout, segmentMatrixLayout, segmentFourteenLayout; LinearLayout sevenTextLayout, fourteenTextLayout, sixteenTextLayout, matrixTextLayout; LinearLayout segmentSevenLayout; string currentDateandTime; LinearLayout mainDigitalGaugeLayout; TextView spaceText1; ScrollView mainGaugeScrollView; public override View GetSampleContent (Context con1) { con = con1; totalHeight = con.Resources.DisplayMetrics.HeightPixels; SevenSegmentLayout(); FourteenSegmentLayout(); SixteenSegmentLayout(); SegmentMatrixLayout(); SegmentTextLayout(); GaugeViewLayout(); return mainGaugeScrollView; } private void SevenSegmentLayout() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH mm ss"); currentDateandTime = simpleDateFormat.Format(new Java.Util.Date()); segmentSevenGauge = new SfDigitalGauge(con); segmentFourteenGauge = new SfDigitalGauge(con); segmentSixteenGauge = new SfDigitalGauge(con); segmentMatrixGauge = new SfDigitalGauge(con); //SevenSegmentLayout segmentSevenLayout = new LinearLayout(con); segmentSevenLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1)); segmentSevenLayout.SetGravity(GravityFlags.Center); segmentSevenLayout.AddView(segmentSevenGauge); segmentSevenGauge.CharacterStroke = Color.Rgb(20, 108, 237); segmentSevenGauge.CharacterHeight = 25; segmentSevenGauge.CharactersSpacing = 2; segmentSevenGauge.CharacterWidth = 12; segmentSevenGauge.SegmentStrokeWidth = 2; segmentSevenGauge.CharacterType = CharacterTypes.SegmentSeven; segmentSevenGauge.Value = currentDateandTime.ToString(); segmentSevenGauge.DimmedSegmentColor = Color.Rgb(20, 108, 237); segmentSevenGauge.DimmedSegmentAlpha = 30; float segmentSevenHeight = TypedValue.ApplyDimension(ComplexUnitType.Pt, (float)segmentSevenGauge.CharacterHeight, con.Resources.DisplayMetrics); float segmentSevenWidth = TypedValue.ApplyDimension(ComplexUnitType.Pt, (float)(8 * segmentSevenGauge.CharacterWidth + 8 * segmentSevenGauge.CharactersSpacing), con.Resources.DisplayMetrics); segmentSevenGauge.LayoutParameters = (new LinearLayout.LayoutParams((int)segmentSevenWidth, (int)segmentSevenHeight)); segmentSevenGauge.SetBackgroundColor(Color.Rgb(240, 240, 240)); segmentFourteenGauge.SetBackgroundColor(Color.Rgb(240, 240, 240)); segmentSixteenGauge.SetBackgroundColor(Color.Rgb(240, 240, 240)); segmentMatrixGauge.SetBackgroundColor(Color.Rgb(240, 240, 240)); } private void FourteenSegmentLayout() { //segmentFourteenLayout segmentFourteenLayout = new LinearLayout(con); segmentFourteenLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1)); segmentFourteenLayout.SetGravity(GravityFlags.Center); segmentFourteenLayout.AddView(segmentFourteenGauge); segmentFourteenGauge.DimmedSegmentAlpha = 30; segmentFourteenGauge.DimmedSegmentColor = Color.Rgb(2, 186, 94); segmentFourteenGauge.CharacterStroke = Color.Rgb(2, 186, 94); segmentFourteenGauge.CharacterHeight = 25; segmentFourteenGauge.CharactersSpacing = 2; segmentFourteenGauge.CharacterWidth = 12; segmentFourteenGauge.SegmentStrokeWidth = 2; segmentFourteenGauge.CharacterType = CharacterTypes.SegmentFourteen; segmentFourteenGauge.Value = currentDateandTime; float segmentFourteenHeight = TypedValue.ApplyDimension(ComplexUnitType.Pt, (float)segmentFourteenGauge.CharacterHeight, con.Resources.DisplayMetrics); float segmentFourteenWidth = TypedValue.ApplyDimension(ComplexUnitType.Pt, (float)(8 * segmentFourteenGauge.CharacterWidth + 8 * segmentFourteenGauge.CharactersSpacing), con.Resources.DisplayMetrics); segmentFourteenGauge.LayoutParameters = (new LinearLayout.LayoutParams((int)segmentFourteenWidth, (int)segmentFourteenHeight)); } private void SixteenSegmentLayout() { //segmentSixteenLayout segmentSixteenLayout = new LinearLayout(con); segmentSixteenLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1)); segmentSixteenLayout.SetGravity(GravityFlags.Center); segmentSixteenLayout.AddView(segmentSixteenGauge); segmentSixteenGauge.DimmedSegmentAlpha = 30; segmentSixteenGauge.DimmedSegmentColor = Color.Rgb(219, 153, 7); segmentSixteenGauge.CharacterStroke = Color.Rgb(219, 153, 7); segmentSixteenGauge.CharacterHeight = 25; segmentSixteenGauge.CharactersSpacing = 2; segmentSixteenGauge.CharacterWidth = 12; segmentSixteenGauge.SegmentStrokeWidth = 2; segmentSixteenGauge.CharacterType = CharacterTypes.SegmentSixteen; segmentSixteenGauge.Value = currentDateandTime; float segmentSixteenHeight = TypedValue.ApplyDimension(ComplexUnitType.Pt, (float)segmentSixteenGauge.CharacterHeight, con.Resources.DisplayMetrics); float segmentSixteenWidth = TypedValue.ApplyDimension(ComplexUnitType.Pt, (float)(8 * segmentSixteenGauge.CharacterWidth + 8 * segmentSixteenGauge.CharactersSpacing), con.Resources.DisplayMetrics); segmentSixteenGauge.LayoutParameters = (new LinearLayout.LayoutParams((int)segmentSixteenWidth, (int)segmentSixteenHeight)); } private void SegmentMatrixLayout() { //segmentMatrixLayout segmentMatrixLayout = new LinearLayout(con); segmentMatrixLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1)); segmentMatrixLayout.SetGravity(GravityFlags.Center); segmentMatrixLayout.AddView(segmentMatrixGauge); segmentMatrixGauge.DimmedSegmentAlpha = 30; segmentMatrixGauge.DimmedSegmentColor = Color.Rgb(249, 66, 53); segmentMatrixGauge.CharacterStroke = Color.Rgb(249, 66, 53); segmentMatrixGauge.CharacterHeight = 25; segmentMatrixGauge.CharactersSpacing = 5; segmentMatrixGauge.CharacterWidth = 9; segmentMatrixGauge.SegmentStrokeWidth = 2; segmentMatrixGauge.CharacterType = CharacterTypes.EightCrossEightDotMatrix; segmentMatrixGauge.Value = currentDateandTime; float segmentMatrixHeight = TypedValue.ApplyDimension(ComplexUnitType.Pt, (float)segmentMatrixGauge.CharacterHeight, con.Resources.DisplayMetrics); float segmentMatrixWidth = TypedValue.ApplyDimension(ComplexUnitType.Pt, (float)(8 * segmentMatrixGauge.CharacterWidth + 8 * segmentMatrixGauge.CharactersSpacing), con.Resources.DisplayMetrics); segmentMatrixGauge.LayoutParameters = (new LinearLayout.LayoutParams((int)segmentMatrixWidth, (int)segmentMatrixHeight)); } private void SegmentTextLayout() { //TextView segmentSevenText = new TextView(con); segmentFourteenText = new TextView(con); segmentSixteenText = new TextView(con); segmentMatrixText = new TextView(con); segmentSeven = new TextView(con); segmentFourteen = new TextView(con); segmentSixteen = new TextView(con); segmentMatrix = new TextView(con); //TextLayout sevenTextLayout = new LinearLayout(con); sevenTextLayout.SetGravity(GravityFlags.Center); sevenTextLayout.AddView(segmentSevenText); fourteenTextLayout = new LinearLayout(con); fourteenTextLayout.SetGravity(GravityFlags.Center); fourteenTextLayout.AddView(segmentFourteenText); sixteenTextLayout = new LinearLayout(con); sixteenTextLayout.SetGravity(GravityFlags.Center); sixteenTextLayout.AddView(segmentSixteenText); matrixTextLayout = new LinearLayout(con); matrixTextLayout.SetGravity(GravityFlags.Center); matrixTextLayout.AddView(segmentMatrixText); //definition segmentSevenText.Text = "7 Segment"; segmentSevenText.SetTextColor(Color.Rgb(34, 34, 34)); segmentSevenText.TextSize = 25; segmentFourteenText.Text = "14 Segment"; segmentFourteenText.SetTextColor(Color.Rgb(34, 34, 34)); segmentFourteenText.TextSize = 25; segmentSixteenText.Text = "16 Segment"; segmentSixteenText.SetTextColor(Color.Rgb(34, 34, 34)); segmentSixteenText.TextSize = 25; segmentMatrixText.Text = "8 X 8 DotMatrix"; segmentMatrixText.SetTextColor(Color.Rgb(34, 34, 34)); segmentMatrixText.TextSize = 25; segmentSeven.TextSize = TypedValue.ApplyDimension(ComplexUnitType.Pt, 8, con.Resources.DisplayMetrics); segmentFourteen.TextSize = TypedValue.ApplyDimension(ComplexUnitType.Pt, 8, con.Resources.DisplayMetrics); segmentSixteen.TextSize = TypedValue.ApplyDimension(ComplexUnitType.Pt, 8, con.Resources.DisplayMetrics); segmentMatrix.TextSize = TypedValue.ApplyDimension(ComplexUnitType.Pt, 8, con.Resources.DisplayMetrics); //spaceText spaceText1 = new TextView(con); spaceText1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 100, GravityFlags.Center); } private void GaugeViewLayout() { //gaugeScrollView ScrollView gaugeScrollView = new ScrollView(con); gaugeScrollView.HorizontalScrollBarEnabled = true; LinearLayout digitalGaugeLayout = new LinearLayout(con); digitalGaugeLayout.Orientation = Orientation.Vertical; digitalGaugeLayout.AddView(spaceText1); digitalGaugeLayout.AddView(sevenTextLayout); digitalGaugeLayout.AddView(segmentSevenLayout); digitalGaugeLayout.AddView(segmentFourteen); digitalGaugeLayout.AddView(fourteenTextLayout); digitalGaugeLayout.AddView(segmentFourteenLayout); digitalGaugeLayout.AddView(segmentSixteen); digitalGaugeLayout.AddView(sixteenTextLayout); digitalGaugeLayout.AddView(segmentSixteenLayout); digitalGaugeLayout.AddView(segmentMatrix); digitalGaugeLayout.AddView(matrixTextLayout); digitalGaugeLayout.AddView(segmentMatrixLayout); digitalGaugeLayout.SetGravity(GravityFlags.Center); //mainGaugeScrollView mainGaugeScrollView = new ScrollView(con); mainDigitalGaugeLayout = new LinearLayout(con); mainDigitalGaugeLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); //mainDigitalGaugeLayout mainDigitalGaugeLayout.AddView(digitalGaugeLayout); mainDigitalGaugeLayout.SetBackgroundColor(Color.White); mainDigitalGaugeLayout.SetGravity(GravityFlags.Center); gaugeScrollView.SetForegroundGravity(GravityFlags.Center); gaugeScrollView.SetPadding(2, 2, 2, 2); gaugeScrollView.SetBackgroundColor(Color.Rgb(248, 248, 248)); mainGaugeScrollView.AddView(mainDigitalGaugeLayout); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Styles/Green.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; namespace SampleBrowser { public class Green : DataGridStyle { public Green () { } public override UIColor GetHeaderBackgroundColor () { return UIColor.FromRGB (92, 138, 94); } public override UIColor GetHeaderForegroundColor() { return UIColor.FromRGB(255, 255, 255); } public override UIColor GetAlternatingRowBackgroundColor () { return UIColor.FromRGB (232, 248, 233); } public override UIColor GetSelectionBackgroundColor () { return UIColor.FromRGB (129, 199, 132); } public override UIColor GetSelectionForegroundColor () { return UIColor.FromRGB (255, 255, 255); } public override UIColor GetCaptionSummaryRowBackgroundColor () { return UIColor.FromRGB (224, 224, 224); } public override UIColor GetCaptionSummaryRowForegroundColor () { return UIColor.FromRGB (51, 51, 51); } public override UIColor GetBorderColor () { return UIColor.FromRGB (180, 180, 180); } // public override int GetHeaderSortIndicatorDown () // { // return Resource.Drawable.SortingDown; // } // // public override int GetHeaderSortIndicatorUp () // { // return Resource.Drawable.SortingUp; // } } } <file_sep>/Android/SampleBrowser/Samples/RangeNavigator/CustomRangeNavigator.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Rangenavigator; using Android.Util; using Android.Graphics; namespace SampleBrowser { public class CustomRangeNavigator : SfDateTimeRangeNavigator { public CustomRangeNavigator(Context context) : base(context) { } public CustomRangeNavigator(Context context, IAttributeSet attrs) : base(context, attrs) { } public CustomRangeNavigator(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { } protected override void DrawLeftThumb(Android.Graphics.Canvas p0, float x1, float y1, float x2, float y2) { float density = Context.Resources.DisplayMetrics.Density; Paint paint = new Paint(); paint.AntiAlias = true; RectF rounderRectF = new RectF(x2 - (16.5f * density), y2 - (3.33f * density), x2 + (1.66f * density), y2 + (16.5f * density)); paint.Color = (Color.ParseColor("#5f6872")); p0.DrawRoundRect(rounderRectF, 7, 7, paint); Path path = new Path(); path.MoveTo(x2, y2 - (16.66f * density)); path.LineTo(x2, y2); path.LineTo(x2 - (16.66f * density), y2 - (2 * density)); path.Close(); p0.DrawPath(path, paint); paint.StrokeWidth = (3.33f * density); p0.DrawLine(x1, y1, x2, y2, paint); SetLeftThumbBounds(new RectF(x2 - 25, y1 - 25, x2 + 25, y2 + 25)); } protected override void DrawRightThumb(Android.Graphics.Canvas p0, float x1, float y1, float x2, float y2) { float density = Context.Resources.DisplayMetrics.Density; Paint paint = new Paint(); paint.AntiAlias = true; RectF rounderRectF = new RectF(x2 - (1.66f * density), y2 - (3.33f * density), x2 + (16.66f * density), y2 + (16.66f * density)); paint.Color = (Color.ParseColor("#5f6872")); p0.DrawRoundRect(rounderRectF, 7, 7, paint); Path path = new Path(); path.MoveTo(x2, y2 - (16.66f * density)); path.LineTo(x2, y2); path.LineTo(x2 + (16.66f * density), y2 - (2 * density)); path.Close(); p0.DrawPath(path, paint); paint.StrokeWidth = (3.33f * density); p0.DrawLine(x1, y1, x2, y2, paint); SetRightThumbBounds(new RectF(x2 - 25, y1 - 25, x2 + 25, y2 + 25)); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/RangeNavigator/GettingStartedRangeNavigator.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class GettingStartedRangeNavigator : SampleView { SFChart chart; SFDateTimeRangeNavigator rangeNavigator; SFDateTimeAxis primaryAxis; SFNumericalAxis secondaryAxis; ChartViewModel dataModel = new ChartViewModel(); public GettingStartedRangeNavigator () { chart = new SFChart (); primaryAxis = new SFDateTimeAxis (); primaryAxis.Minimum = DateTimeToNSDate( new DateTime (2015, 5, 15, 0, 0, 0)); primaryAxis.Maximum = DateTimeToNSDate( new DateTime (2015, 8, 15, 0, 0, 0)); chart.PrimaryAxis = primaryAxis; secondaryAxis = new SFNumericalAxis (); chart.SecondaryAxis = secondaryAxis; SFSplineAreaSeries series = new SFSplineAreaSeries(); series.Alpha = 0.6f; series.BorderColor = UIColor.FromRGBA(255.0f / 255.0f, 191.0f / 255.0f, 0.0f / 255.0f, 1.0f); series.ItemsSource = dataModel.DateTimeRangeData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; chart.Series.Add(series); this.AddSubview (chart); rangeNavigator = new SFDateTimeRangeNavigator (); rangeNavigator.Delegate = new RangeNavigatorDelegate(primaryAxis); SFSplineAreaSeries series1 = new SFSplineAreaSeries(); series1.Alpha = 0.6f; series1.BorderColor = UIColor.FromRGBA(255.0f / 255.0f, 191.0f / 255.0f, 0.0f / 255.0f, 1.0f); series1.ItemsSource = dataModel.DateTimeRangeData; series1.XBindingPath = "XValue"; series1.YBindingPath = "YValue"; chart.Series.Add(series1); ((SFChart)rangeNavigator.Content).Series.Add(series1); DateTime minDate = new DateTime (2015, 1, 1, 0, 0, 0); DateTime maxDate = new DateTime (2015, 12, 1, 0, 0, 0); DateTime startDate = new DateTime (2015, 5, 15, 0, 0, 0); DateTime endDate = new DateTime (2015, 8, 15, 0, 0, 0); rangeNavigator.Minimum = DateTimeToNSDate (minDate); rangeNavigator.Maximum = DateTimeToNSDate (maxDate); rangeNavigator.ViewRangeStart = DateTimeToNSDate (startDate); rangeNavigator.ViewRangeEnd = DateTimeToNSDate (endDate); this.AddSubview (rangeNavigator); //this.control = this; } public override void LayoutSubviews () { foreach (var view in this.Subviews) { if (view == rangeNavigator) view.Frame = new CGRect (0, Frame.Size.Height - 100, Frame.Width, 100); else if (view == chart) view.Frame = new CGRect (0, 0, Frame.Size.Width, Frame.Size.Height - 100); else view.Frame = Frame; } base.LayoutSubviews (); } public void UpdateChart(NSDate startDate, NSDate endDate) { primaryAxis.Minimum = startDate; primaryAxis.Maximum = endDate; } public NSDate DateTimeToNSDate(DateTime date) { DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime( new DateTime(2001, 1, 1, 0, 0, 0) ); return NSDate.FromTimeIntervalSinceReferenceDate((date - reference).TotalSeconds); } } } public class RangeNavigatorDelegate: SFRangeNavigatorDelegate { SFDateTimeAxis primaryAxis; public RangeNavigatorDelegate(SFDateTimeAxis _primaryAxis) { primaryAxis = _primaryAxis; } public override void RangeChanged (SFDateTimeRangeNavigator rangeNavigator, NSDate startDate, NSDate endDate) { primaryAxis.Minimum = startDate; primaryAxis.Maximum = endDate; } }<file_sep>/Forms/XlsIO/XlsIO.Droid/SplashScreenActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // <copyright file="SplashScreenActivity.cs" company=" Syncfusion Inc."> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> #endregion namespace SampleBrowser.XlsIO.Droid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; /// <summary> /// A splash screen may display start up progress to the user or to indicate branding. /// </summary> [Activity(Theme = "@style/Theme.Splash", MainLauncher = true, NoHistory = true, Icon = "@drawable/AppIcon")] public class SplashScreenActivity : SampleBrowser.Core.Android.SplashScreenActivity { /// <summary> /// Override the value of <see cref="Type"/> class. /// </summary> /// <returns>Return the value of <see cref="MainActivity"/> class.</returns> protected override Type GetMainActivityType() { return typeof(MainActivity); } } } <file_sep>/Forms/SignaturePad/SignaturePad/Samples/SignaturePadGettingStarted/View/SignaturePadGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SampleBrowser.Core; using System.Collections.ObjectModel; using System.Linq; using System.IO; using Syncfusion.XForms.Border; using Avatar = Syncfusion.XForms.AvatarView; using System.Globalization; using System.ComponentModel; using System.Runtime.CompilerServices; namespace SampleBrowser.SfSignaturePad { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SignaturePadGettingStarted : SampleView { ViewModel view = new ViewModel(); public SignaturePadGettingStarted() { InitializeComponent(); this.BindingContext = view; } /// <summary> /// override method for size allocated /// </summary> /// <param name="width">The width of the page</param> /// <param name="height">The height of the page</param> protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if (width > height) { optionsGrid.Height = 100; } else { optionsGrid.Height = 250; } } Image image1 = new Image(); private void Save_Clicked(object sender, EventArgs e) { signaturepad.Save(); if (signaturepad.ImageSource != null) { Navigation.PushAsync(new SignatureImagePage(signaturepad.ImageSource)); } } private void Clear_Clicked(object sender, EventArgs e) { signaturepad.Clear(); } } public class ViewModel : INotifyPropertyChanged { private Color pencolor; public Color PenColor { get { return pencolor; } set { pencolor = value; OnPropertyChanged(); } } protected void OnPropertyChanged([CallerMemberName] string name = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } private ObservableCollection<Avatar.SfAvatarView> colorItemCollection = new ObservableCollection<Avatar.SfAvatarView>(); public ObservableCollection<Avatar.SfAvatarView> ColorItemCollection { get { return colorItemCollection; } set { colorItemCollection = value; } } private void PopulateColorCollection() { ColorItemCollection.Clear(); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#030303"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#F60618"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#0C15F1"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#34AB0A"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#FBAD0A"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#D50BF4"))); ColorItemCollection[0].BorderWidth = 2; ColorItemCollection[0].BorderColor = Color.FromHex("9E9E9E"); PenColor = ColorItemCollection[0].BackgroundColor; } private Avatar.SfAvatarView GetColorPickerItem(Color backgroundColor) { Avatar.SfAvatarView colorAvatar = new Avatar.SfAvatarView(); colorAvatar.BackgroundColor = backgroundColor; colorAvatar.BorderWidth = 1; colorAvatar.BorderColor = Color.White; colorAvatar.InitialsColor = Color.Transparent; colorAvatar.AvatarShape = Avatar.AvatarShape.Circle; colorAvatar.AvatarSize = Avatar.AvatarSize.Medium; colorAvatar.VerticalOptions = LayoutOptions.Center; colorAvatar.HorizontalOptions = LayoutOptions.Center; TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += ColorTapGestureRecognizer_Tapped; colorAvatar.GestureRecognizers.Add(tapGestureRecognizer); return colorAvatar; } Avatar.SfAvatarView tappedAvatarView = new Avatar.SfAvatarView(); public event PropertyChangedEventHandler PropertyChanged; private void ColorTapGestureRecognizer_Tapped(object sender, EventArgs e) { foreach(var items in ColorItemCollection) { items.BorderWidth = 1; items.BorderColor = Color.White; } tappedAvatarView = (sender as Avatar.SfAvatarView); tappedAvatarView.BorderWidth = 2; tappedAvatarView.BorderColor = Color.FromHex("9E9E9E"); PenColor = tappedAvatarView.BackgroundColor; } public ViewModel() { PopulateColorCollection(); } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/CustomLayout.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CustomLayout.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; /// <summary> /// A layout that arranges views in rows and columns /// </summary> public class CustomLayout : Grid { /// <summary> /// Updates the bounds of the element during the layout cycle. /// </summary> /// <param name="x">A value representing the x coordinate of the child region bounding box.</param> /// <param name="y">A value representing the y coordinate of the child region bounding box.</param> /// <param name="width">A value representing the width of the child region bounding box.</param> /// <param name="height">A value representing the height of the child region bounding box.</param> protected override void LayoutChildren(double x, double y, double width, double height) { this.Children[0].Layout(new Rectangle(0, 0, this.Width, this.Height)); } /// <summary> /// Method to decide whether to call <see cref="Xamarin.Forms.VisualElement.InvalidateMeasure()"/> when adding a child. /// </summary> /// <param name="child">A child of the <see cref="SfDataGrid"/>.</param> /// <returns>A boolean value do decide whether to invalidate when adding a child.</returns> protected override bool ShouldInvalidateOnChildAdded(View child) { return false; } /// <summary> /// Method to decide whether to call <see cref="Xamarin.Forms.VisualElement.InvalidateMeasure()"/> when removing a child. /// </summary> /// <param name="child">A child of the <see cref="SfDataGrid"/>.</param> /// <returns>A boolean value do decide whether to invalidate when removing a child.</returns> protected override bool ShouldInvalidateOnChildRemoved(View child) { return false; } } } <file_sep>/iOS/SampleBrowser/Samples/Presentation/ConnectorsPresentation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Presentation; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class ConnectorsPresentation : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; public ConnectorsPresentation() { label1 = new UILabel(); label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to insert the connectors in a PowerPoint slide."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width , 50); } else { label.Frame = new CGRect (frameRect.Location.X, 5, frameRect.Size.Width , 70); } this.AddSubview (label); button.SetTitle("Generate Presentation",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect (0, 65, frameRect.Location.X + frameRect.Size.Width , 10); } else { button.Frame = new CGRect (frameRect.Location.X, 70, frameRect.Size.Width , 10); } this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { //Create an instance for PowerPoint IPresentation presentation = Presentation.Create(); //Add a blank slide to Presentation ISlide slide = presentation.Slides.Add(SlideLayoutType.Blank); //Add header shape IShape headerTextBox = slide.Shapes.AddTextBox(58.44, 53.85, 221.93, 81.20); //Add a paragraph into the text box IParagraph paragraph = headerTextBox.TextBody.AddParagraph("Flow chart with "); //Add a textPart ITextPart textPart = paragraph.AddTextPart("Connector"); //Change the color of the font textPart.Font.Color = ColorObject.FromArgb(44, 115, 230); //Make the textpart bold textPart.Font.Bold = true; //Set the font size of the paragraph paragraph.Font.FontSize = 28; //Add start shape to slide IShape startShape = slide.Shapes.AddShape(AutoShapeType.FlowChartTerminator, 420.45, 36.35, 133.93, 50.39); //Add a paragraph into the start shape text body AddParagraph(startShape, "Start", ColorObject.FromArgb(255, 149, 34)); //Add alarm shape to slide IShape alarmShape = slide.Shapes.AddShape(AutoShapeType.FlowChartProcess, 420.45, 126.72, 133.93, 50.39); //Add a paragraph into the alarm shape text body AddParagraph(alarmShape, "Alarm Rings", ColorObject.FromArgb(255, 149, 34)); //Add condition shape to slide IShape conditionShape = slide.Shapes.AddShape(AutoShapeType.FlowChartDecision, 420.45, 222.42, 133.93, 97.77); //Add a paragraph into the condition shape text body AddParagraph(conditionShape, "Ready to Get Up ?", ColorObject.FromArgb(44, 115, 213)); //Add wake up shape to slide IShape wakeUpShape = slide.Shapes.AddShape(AutoShapeType.FlowChartProcess, 420.45, 361.52, 133.93, 50.39); //Add a paragraph into the wake up shape text body AddParagraph(wakeUpShape, "Wake Up", ColorObject.FromArgb(44, 115, 213)); //Add end shape to slide IShape endShape = slide.Shapes.AddShape(AutoShapeType.FlowChartTerminator, 420.45, 453.27, 133.93, 50.39); //Add a paragraph into the end shape text body AddParagraph(endShape, "End", ColorObject.FromArgb(44, 115, 213)); //Add snooze shape to slide IShape snoozeShape = slide.Shapes.AddShape(AutoShapeType.FlowChartProcess, 624.85, 245.79, 159.76, 50.02); //Add a paragraph into the snooze shape text body AddParagraph(snoozeShape, "Hit Snooze button", ColorObject.FromArgb(255, 149, 34)); //Add relay shape to slide IShape relayShape = slide.Shapes.AddShape(AutoShapeType.FlowChartDelay, 624.85, 127.12, 159.76, 49.59); //Add a paragraph into the relay shape text body AddParagraph(relayShape, "Relay", ColorObject.FromArgb(255, 149, 34)); //Connect the start shape with alarm shape using connector IConnector connector1 = slide.Shapes.AddConnector(ConnectorType.Straight, startShape, 2, alarmShape, 0); //Set the arrow style for the connector connector1.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the alarm shape with condition shape using connector IConnector connector2 = slide.Shapes.AddConnector(ConnectorType.Straight, alarmShape, 2, conditionShape, 0); //Set the arrow style for the connector connector2.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the condition shape with snooze shape using connector IConnector connector3 = slide.Shapes.AddConnector(ConnectorType.Straight, conditionShape, 3, snoozeShape, 1); //Set the arrow style for the connector connector3.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the snooze shape with relay shape using connector IConnector connector4 = slide.Shapes.AddConnector(ConnectorType.Straight, snoozeShape, 0, relayShape, 2); //Set the arrow style for the connector connector4.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the relay shape with alarm shape using connector IConnector connector5 = slide.Shapes.AddConnector(ConnectorType.Straight, relayShape, 1, alarmShape, 3); //Set the arrow style for the connector connector5.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the condition shape with wake up shape using connector IConnector connector6 = slide.Shapes.AddConnector(ConnectorType.Straight, conditionShape, 2, wakeUpShape, 0); //Set the arrow style for the connector connector6.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Connect the wake up shape with end shape using connector IConnector connector7 = slide.Shapes.AddConnector(ConnectorType.Straight, wakeUpShape, 2, endShape, 0); //Set the arrow style for the connector connector7.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow; //Add No textbox to slide IShape noTextBox = slide.Shapes.AddTextBox(564.02, 245.43, 51.32, 26.22); //Add a paragraph into the text box noTextBox.TextBody.AddParagraph("No"); //Add Yes textbox to slide IShape yesTextBox = slide.Shapes.AddTextBox(487.21, 327.99, 50.09, 26.23); //Add a paragraph into the text box yesTextBox.TextBody.AddParagraph("Yes"); MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("ConnectorsPresentation.pptx", "application/mspowerpoint", stream); } } /// <summary> /// Add a paragraph into the specified shape with specified text /// </summary> /// <param name="shape">Represent the shape</param> /// <param name="text">Represent the text to be added</param> /// <param name="fillColor">Represent the color to fill the shape</param> private void AddParagraph(IShape shape, string text, IColor fillColor) { //set the fill type as solid shape.Fill.FillType = FillType.Solid; //Set the color of the solid fill shape.Fill.SolidFill.Color = fillColor; //set the fill type of line format as solid shape.LineFormat.Fill.FillType = FillType.Solid; //set the fill color of line format if (fillColor.R == 255) shape.LineFormat.Fill.SolidFill.Color = ColorObject.FromArgb(190, 100, 39); else shape.LineFormat.Fill.SolidFill.Color = ColorObject.FromArgb(54, 91, 157); //Add a paragraph into the specified shape with specified text IParagraph paragraph = shape.TextBody.AddParagraph(text); //Set the vertical alignment as center shape.TextBody.VerticalAlignment = VerticalAlignmentType.Middle; //Set horizontal alignment as center paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; //Set font color as white paragraph.Font.Color = ColorObject.White; //Change the font size paragraph.Font.FontSize = 16; } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/Forms/Chart/Chart.macOS/ViewController.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using AppKit; using Foundation; namespace SampleBrowser.SfChart.macOS { public partial class ViewController : NSViewController { public ViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); // Do any additional setup after loading the view. } public override NSObject RepresentedObject { get { return base.RepresentedObject; } set { base.RepresentedObject = value; // Update the view, if already loaded. } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/Configuration/ScheduleConfigurationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Foundation; using Syncfusion.SfSchedule.iOS; using UIKit; namespace SampleBrowser { internal class ScheduleConfigurationViewModel { internal ObservableCollection<ScheduleAppointment> CreateAppointments() { NSDate today = new NSDate(); setColors(); setSubjects(); ObservableCollection<ScheduleAppointment> appCollection = new ObservableCollection<ScheduleAppointment>(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment appointment = new ScheduleAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)subjectCollection[i]; appointment.AppointmentBackground = colorCollection[i]; appCollection.Add(appointment); } return appCollection; } private List<String> subjectCollection; private void setSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); } // adding colors collection private List<UIColor> colorCollection; private void setColors() { colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0xF0, 0x96, 0x09)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); } } }<file_sep>/Forms/Presentation/Presentation/Samples/PPTXToImage/PPTXToImage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using SampleBrowser.Core; using Syncfusion.PresentationRenderer; namespace SampleBrowser.Presentation { public partial class PPTXToImage : SampleView { public PPTXToImage() { InitializeComponent(); this.pngButton.IsChecked = true; if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.btnGenerate.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.btnInput.HorizontalOptions = Xamarin.Forms.LayoutOptions.Start; this.Content_1.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnInput.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnInput.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { { this.Content_1.FontSize = 13.5; } this.Content_1.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnGenerate.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; this.btnInput.VerticalOptions = Xamarin.Forms.LayoutOptions.Center; } } internal void OnInputButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Template.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Template.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); MemoryStream stream = new MemoryStream(); fileStream.CopyTo(stream); stream.Position = 0; fileStream.Dispose(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("InputTemplate.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("InputTemplate.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Template.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Template.pptx"; #endif Assembly assembly = typeof(GettingStarted).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); //Initialize PresentationRenderer to perform image conversion. presentation.PresentationRenderer = new PresentationRenderer(); string fileName = null; string contentType = null; Syncfusion.Presentation.ExportImageFormat imageFormat; if (this.jpegButton.IsChecked != null && (bool)this.jpegButton.IsChecked) { imageFormat = ExportImageFormat.Jpeg; fileName = "Image.jpeg"; contentType = "image/jpeg"; } else { imageFormat = ExportImageFormat.Png; fileName = "Image.png"; contentType = "image/png"; } //Convert PowerPoint slide to image stream. Stream stream = presentation.Slides[0].ConvertToImage(imageFormat); //Close the PowerPoint Presentation. presentation.Close(); //Reset the stream position. stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save(fileName, contentType, stream as MemoryStream); else Xamarin.Forms.DependencyService.Get<ISave>().Save(fileName, contentType, stream as MemoryStream); } } } <file_sep>/Android/SampleBrowser/Samples/RadialMenu/readme.md The `SfRadialMenu` displays a hierarchical menu in a circular layout, which is optimized for touch enabled devices. Typically, it is used as a context menu, and it can expose more menu items in the same space than traditional menus. The following samples are available for radial menu to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](RadialMenuGettingStarted.cs)| t demonstrates the arrangement of sub menu items and its event like `Opened`,`Opening`,`Closed` and `Closing`.| |[Customization](RadialMenuCustomization.cs)| It shows the way of customizing radial menu items with icon fonts. The color of rotator items are changed to exhibit the Tapped event in radial menu items.| |[Contextual Menu](RadialShare.cs)| It provides the way to create a sample like contextual menu using radial menu.| <file_sep>/iOS/SampleBrowser/Resources/Samples/TreeView/Helper/CustomView/TemplateSelectorView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using UIKit; using CoreGraphics; namespace SampleBrowser { public class TemplateSelectorView : UIView { #region Fields UILabel label1; UILabel label2; #endregion #region Constructor public TemplateSelectorView() { label1 = new UILabel(); label2 = new UILabel(); this.AddSubview(label1); this.AddSubview(label2); } #endregion #region Override Methods public override void LayoutSubviews() { this.label1.Frame = new CGRect(0, 0, this.Frame.Width-100, 40); this.label2.Frame = new CGRect(this.Frame.Width-50, 10, 20,20); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion } }<file_sep>/Forms/AutoComplete/AutoComplete/Samples/ToleratingTypos/ToleratingTypos.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Reflection; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public partial class ToleratingTypos : SampleView, INotifyPropertyChanged { public ObservableCollection<string> Source { get; set; } public ObservableCollection<ListModel> ListSource { get; set; } public ObservableCollection<SearchData> DummySource { get; set; } private ObservableCollection<string> stringDummySource { get; set; } public object selectedItem; public object SelectedItem { get { return selectedItem; } set { selectedItem = value; if (selectedItem == null || selectedItem.ToString() == "") Results(0); else Results(100000); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem")); } } } private IEnumerable<object> filteredCollection; public IEnumerable<object> FilteredCollection { get { return filteredCollection; } set { if (filteredCollection != value) { filteredCollection = value; filteredCollection = getOrder(DummySource); DummySource = new ObservableCollection<SearchData>(); stringDummySource.Clear(); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("FilteredCollection")); } } } } public ObservableCollection<string> getOrder(ObservableCollection<SearchData> sourceOrder) { ObservableCollection<string> orderedSource = new ObservableCollection<string>(); for (int i = 0; i < 10; i++) { int count=0; for (int c = 0; c < sourceOrder.Count; c++) { count++; if (sourceOrder[c] != null && sourceOrder[c].Distance == i) { orderedSource.Add(sourceOrder[c].Item); } } } return orderedSource; } private string text; public string Text { get { return text; } set { text = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Text")); } } } public ToleratingTypos() { InitializeComponent(); Source = new StringData().GetStringCollection(); ListSource = new StringData().GetListCollection(); this.autoComplete.Filter = AutoCompleteSearch; DummySource = new ObservableCollection<SearchData>(); stringDummySource = new ObservableCollection<string>(); this.BindingContext = this; if (Device.RuntimePlatform == Device.UWP) { sampleLayout.WidthRequest = 500; sampleLayout.HorizontalOptions = LayoutOptions.Center; } } ToleratingTyposHelper helper = new ToleratingTyposHelper(); public bool AutoCompleteSearch(object value1, object value2) { var string1 = value1.ToString().ToLower(); var string2 = value2.ToString().ToLower(); if (string1.Length > 0 && string2.Length > 0) if (string1[0] != string2[0]) return false; var originalString1 = string.Empty; var originalString2 = string.Empty; if (string1.Length < string2.Length) { originalString2 = string2.Remove(string1.Length); originalString1 = string1; } if (string2.Length < string1.Length) { return false; } if (string2.Length == string1.Length) { originalString1 = string1; originalString2 = string2; } bool IsMatchSoundex = helper.ProcessOnSoundexAlgorithmn(originalString1) == helper.ProcessOnSoundexAlgorithmn(originalString2); int Distance = helper.GetDamerauLevenshteinDistance(originalString1, originalString2); if (IsMatchSoundex || Distance <= 4) { var searchData = new SearchData() { Item = value2.ToString(), Distance = Distance }; if (!stringDummySource.Contains(value2.ToString())) { DummySource.Add(searchData); stringDummySource.Add(value2.ToString()); } return true; } else return false; } Random random = new Random(); public new event PropertyChangedEventHandler PropertyChanged; public void Results(int value) { foreach (var item in ListSource) { item.Count = random.Next(value).ToString(); } } } public class SearchData { public string Item { get; set; } public int Distance { get; set; } } public class StringData { public ObservableCollection<string> GetStringCollection() { var assembly = typeof(StringData).GetTypeInfo().Assembly; Stream stream = null; #if COMMONSB stream = assembly.GetManifestResourceStream("SampleBrowser.Samples.AutoComplete.strings.txt"); #else stream = assembly.GetManifestResourceStream("SampleBrowser.SfAutoComplete.strings.txt"); #endif ObservableCollection<string> stringCollection = new ObservableCollection<string>(); string text = ""; using (var reader = new System.IO.StreamReader(stream)) { while ((text = reader.ReadLine()) != null) { stringCollection.Add(text); } } return stringCollection; } public ObservableCollection<ListModel> GetListCollection() { ObservableCollection<ListModel> listCollection = new ObservableCollection<ListModel>(); listCollection.Add(new ListModel() { Text = "General", Image = "AllApps.png" }); listCollection.Add(new ListModel() { Text = "Maps", Image = "Maps_Violet.png" }); listCollection.Add(new ListModel() { Text = "Images", Image = "Picture.png" }); listCollection.Add(new ListModel() { Text = "News", Image = "Newspaper.png" }); listCollection.Add(new ListModel() { Text = "Video", Image = "Media.png" }); listCollection.Add(new ListModel() { Text = "Music", Image = "Music.png" }); listCollection.Add(new ListModel() { Text = "Books", Image = "Book_Icon.png" }); listCollection.Add(new ListModel() { Text = "Flight", Image = "Aeroplane.png" }); listCollection.Add(new ListModel() { Text = "Quick Search", Image = "Spaceship.png" }); return listCollection; } } public class ListModel : INotifyPropertyChanged { public string Text { get; set; } public string Image { get; set; } public string count = "0"; public string Count { get { return "About " + count + " results"; } set { count = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Count")); } } } public event PropertyChangedEventHandler PropertyChanged; } }<file_sep>/Android/SampleBrowser/Samples/Carousel/Carousel_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Carousel; using Java.Util; using Android.Graphics; using Android.Views.InputMethods; namespace SampleBrowser { public class Carousel_Tab :SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ EditText offSet, scaleOffset, RotateAngle; LinearLayout proprtyOptionsLayout; Spinner tickSpinner; ArrayAdapter<String> dataAdapter; SfCarousel carousel; Context context1; int width; public override View GetSampleContent(Context context) { context1 = context; //carousel carousel = new SfCarousel(context1); List<SfCarouselItem> tempCollection = new List<SfCarouselItem>(); for (int i = 1; i <= 7; i++) { SfCarouselItem carouselItem = new SfCarouselItem(context1); carouselItem.ImageName = "images" + i; tempCollection.Add(carouselItem); } carousel.DataSource = tempCollection; carousel.SelectedIndex = 3; carousel.ScaleOffset = 0.8f; if (context1.Resources.DisplayMetrics.Density > 1.5) { carousel.ItemHeight = Convert.ToInt32(240 * context1.Resources.DisplayMetrics.Density); carousel.ItemWidth = Convert.ToInt32(170 * context1.Resources.DisplayMetrics.Density); } carousel.LayoutParameters = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); return carousel; } public override View GetPropertyWindowLayout(Context context) { context1 = context; width = (context1.Resources.DisplayMetrics.WidthPixels) / 2; proprtyOptionsLayout = new LinearLayout(context1); proprtyOptionsLayout.Orientation = Orientation.Vertical; OffsetLayout(); ScaleOffsetLayout(); RotationAngleLayout(); VisualModeLayout(); return proprtyOptionsLayout; } private void OffsetLayout() { //OffsetLabel TextView offsetLabel = new TextView(context1); offsetLabel.SetPadding(0, 0, 0, 10); offsetLabel.Text = "Offset"; offsetLabel.TextSize = 20; offsetLabel.Gravity = GravityFlags.CenterVertical; //offSetText offSet = new EditText(context1); offSet.Text = "60"; offSet.InputType = Android.Text.InputTypes.ClassNumber; offSet.TextSize = 20; offSet.SetTextColor(Color.Black); //Offset Text Changed Listener offSet.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (offSet.Text.Length > 0) { int i = Convert.ToInt32(e.Text.ToString()); if (i >= 40 && i <= 100) carousel.Offset = i; else carousel.Offset = 60; } }; //offSetLayout LinearLayout offSetLayout = new LinearLayout(context1); offSetLayout.SetPadding(20, 20, 0, 40); offSetLayout.Orientation = Android.Widget.Orientation.Vertical; offSetLayout.AddView(offsetLabel); offSetLayout.AddView(offSet); proprtyOptionsLayout.AddView(offSetLayout); } private void ScaleOffsetLayout() { //ScaleLabel TextView scaleLabel = new TextView(context1); scaleLabel.SetPadding(0, 0, 0, 10); scaleLabel.Text = "Scale Offset"; scaleLabel.TextSize = 20; scaleLabel.Gravity = GravityFlags.CenterVertical; //scaleOffsetText scaleOffset = new EditText(context1); scaleOffset.InputType = Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.NumberFlagSigned | Android.Text.InputTypes.ClassNumber; scaleOffset.TextSize = 20; scaleOffset.Text = "0.8"; scaleOffset.SetTextColor(Color.Black); //Scale Offset Text Changed Listener scaleOffset.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (scaleOffset.Text.Length > 0) { float i = (float)Convert.ToDouble(e.Text.ToString()); if (i >= 0.5 && i <= 1) { carousel.ScaleOffset = i; } else carousel.ScaleOffset = 0.8f; } }; //scaleLayout LinearLayout scaleLayout = new LinearLayout(context1); scaleLayout.SetPadding(20, 20, 0, 40); scaleLayout.Orientation = Android.Widget.Orientation.Vertical; scaleLayout.AddView(scaleLabel); scaleLayout.AddView(scaleOffset); proprtyOptionsLayout.AddView(scaleLayout); } private void RotationAngleLayout() { //Rotator Lable TextView rotateLabel = new TextView(context1); rotateLabel.SetPadding(0, 0, 0, 10); rotateLabel.Text = "Rotation Angle"; rotateLabel.TextSize = 20; rotateLabel.Gravity = GravityFlags.CenterVertical; //Rotation Angle RotateAngle = new EditText(context1); RotateAngle.InputType = Android.Text.InputTypes.ClassNumber; RotateAngle.TextSize = 20; RotateAngle.Text = "45"; RotateAngle.SetTextColor(Color.Black); //Rotation Angle Text Changed Listener RotateAngle.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (RotateAngle.Text.Length > 0) { int i = Convert.ToInt32(e.Text.ToString()); if (i >= 0 && i <= 360) carousel.RotationAngle = i; else carousel.RotationAngle = 45; } }; //rotateLayout LinearLayout rotateLayout = new LinearLayout(context1); rotateLayout.SetPadding(20, 20, 0, 40); rotateLayout.Orientation = Android.Widget.Orientation.Vertical; rotateLayout.AddView(rotateLabel); rotateLayout.AddView(RotateAngle); proprtyOptionsLayout.AddView(rotateLayout); } private void VisualModeLayout() { //placementLabel TextView placementLabel = new TextView(context1); placementLabel.SetPadding(0,0,0,10); placementLabel.Text = "View Mode"; placementLabel.TextSize = 20; //tickSpinner tickSpinner = new Spinner(context1,SpinnerMode.Dialog); tickSpinner.SetPadding(0, 0, 0, 0); //positionList List<String> positionList = new List<String>(); positionList.Add("Default"); positionList.Add("Linear"); dataAdapter = new ArrayAdapter<String>(context1, Android.Resource.Layout.SimpleSpinnerItem, positionList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); tickSpinner.Adapter = dataAdapter; //tickSpinner ItemSelected Listener tickSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Default")) { if (context1.Resources.DisplayMetrics.Density > 1.5) { carousel.ItemHeight = Convert.ToInt32(250 * context1.Resources.DisplayMetrics.Density); carousel.ItemWidth = Convert.ToInt32(180 * context1.Resources.DisplayMetrics.Density); } carousel.ViewMode = ViewMode.Default; } else if (selectedItem.Equals("Linear")) { if (context1.Resources.DisplayMetrics.Density > 1.5) { carousel.ItemHeight = Convert.ToInt32(250 * context1.Resources.DisplayMetrics.Density); carousel.ItemWidth = Convert.ToInt32(250 * context1.Resources.DisplayMetrics.Density); } carousel.ViewMode = ViewMode.Linear; } }; LinearLayout linearLayout = new LinearLayout(context1); linearLayout.SetPadding(20,40,0,40); linearLayout.Orientation = Android.Widget.Orientation.Vertical; linearLayout.AddView(placementLabel); linearLayout.AddView(tickSpinner); proprtyOptionsLayout.AddView(linearLayout); } public override void OnApplyChanges() { base.OnApplyChanges(); } } } <file_sep>/Forms/DataGrid/DataGrid.macOS/AppDelegate.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "AppDelegate.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid.MacOS { using System.Diagnostics.CodeAnalysis; using AppKit; using CoreGraphics; using Foundation; using Syncfusion.SfDataGrid.XForms.MacOS; using Xamarin.Forms.Platform.MacOS; [Register("AppDelegate")] /// <summary> /// The UIApplicationDelegate for the application. This class is responsible for launching the User Interface of the application, as well as listening (and optionally responding) to application events from iOS. /// </summary> public class AppDelegate : FormsApplicationDelegate { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private NSWindow nswindow; /// <summary> /// Initializes a new instance of the AppDelegate class. /// </summary> public AppDelegate() { var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled; var rect = new CGRect(0, 1000, 200, 200); this.nswindow = new NSWindow(rect, style, NSBackingStore.Buffered, false); var screenFrame = this.nswindow.Screen.Frame; this.nswindow.SetFrame(new CGRect(0, 0, screenFrame.Width, screenFrame.Height), true, true); this.nswindow.TitleVisibility = NSWindowTitleVisibility.Hidden; } /// <summary> /// Gets the value of FilterText /// </summary> public override NSWindow MainWindow { get { return this.nswindow; } } /// <summary> /// Sent by the default notification center after the application has been launched and initialized but before it has received its first event. /// </summary> /// <param name="notification">The value for this key is an NSNumber containing a Boolean value. The value is false if the app was launched to open or print a file, to perform a Service action, if the app had saved state that will be restored, or if the app launch was in some other sense not a default launch. Otherwise its value will be true.</param> public override void DidFinishLaunching(NSNotification notification) { Xamarin.Forms.Forms.Init(); SampleBrowser.Core.MacOS.SampleBrowserMac.Init(); this.LoadApplication(new App()); Syncfusion.ListView.XForms.MacOS.SfListViewRenderer.Init(); SfDataGridRenderer.Init(); base.DidFinishLaunching(notification); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Histogram.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Com.Syncfusion.Navigationdrawer; namespace SampleBrowser { public class Histogram : SamplePage { public override View GetSampleContent(Context context) { SfChart chart = new SfChart(context); chart.Title.Text = "Examination Result"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.ColorModel.ColorPalette = ChartColorPalette.Natural; NumericalAxis categoryaxis = new NumericalAxis(); categoryaxis.Title.Text = "Score of Final Examination"; categoryaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; categoryaxis.ShowMajorGridLines = false; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Title.Text = "Number of Students"; numericalaxis.ShowMajorGridLines = true; numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.TickSize = 0; chart.SecondaryAxis = numericalaxis; HistogramSeries histogramSeries = new HistogramSeries(); histogramSeries.ItemsSource = MainPage.GetHistogramData(); histogramSeries.XBindingPath = "YValue"; histogramSeries.YBindingPath = "XValue"; histogramSeries.Interval = 20; histogramSeries.TooltipEnabled = true; histogramSeries.EnableAnimation = true; histogramSeries.StrokeColor = Color.White; histogramSeries.StrokeWidth = 1; histogramSeries.DataMarker.ShowLabel = true; histogramSeries.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Inner; histogramSeries.DataMarker.LabelStyle.BackgroundColor = Color.Transparent; histogramSeries.DataMarker.LabelStyle.TextColor = Color.White; chart.Series.Add(histogramSeries); return chart; } } } <file_sep>/Forms/PdfViewer/PdfViewer/Samples/Helper/StampAnnotationView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfPdfViewer { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class StampAnnotationView : ContentView { TapGestureRecognizer recognizer; Syncfusion.SfPdfViewer.XForms.SfPdfViewer pdfViewer; public StampAnnotationView(Syncfusion.SfPdfViewer.XForms.SfPdfViewer pdfViewer) { InitializeComponent(); this.pdfViewer = pdfViewer; Grid.SetRow(this, 0); if (Device.Idiom != TargetIdiom.Desktop) Grid.SetRowSpan(this, 3); else Grid.SetRowSpan(this, 2); recognizer = new TapGestureRecognizer() { NumberOfTapsRequired = 1 }; recognizer.Tapped += (s, e) => { CreateAndAddCustomStamp(s as Image); }; approved.GestureRecognizers.Add(recognizer); notapproved.GestureRecognizers.Add(recognizer); draft.GestureRecognizers.Add(recognizer); confidential.GestureRecognizers.Add(recognizer); expired.GestureRecognizers.Add(recognizer); } private void CreateAndAddCustomStamp(Image tappedImage) { Image customImage = new Image(); customImage.HeightRequest = 90; customImage.WidthRequest = 300; if (tappedImage == approved) customImage.Source = "Approved.png"; else if (tappedImage == notapproved) customImage.Source = "NotApproved.png"; else if (tappedImage == draft) customImage.Source = "Draft.png"; else if (tappedImage == expired) customImage.Source = "Expired.png"; else if (tappedImage == confidential) customImage.Source = "Confidential.png"; pdfViewer.AddStamp(customImage, pdfViewer.PageNumber, new Point(250, 400)); (Parent as Grid).Children.Remove(this); } private void BackButton_Clicked(object sender, EventArgs e) { (Parent as Grid).Children.Remove(this); } private void Button_Clicked(object sender, EventArgs e) { (Parent as Grid).Children.Remove(this); } } public class CustomStampEffect : RoutingEffect { public CustomStampEffect() : base("SampleBrowser.SfPdfViewer.CustomStampEffect") { } } }<file_sep>/iOS/SampleBrowser/Samples/RadioButton/RadioButton_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Syncfusion.iOS.Buttons; using CoreGraphics; using CoreAnimation; namespace SampleBrowser { public class RadioButton_Mobile : SampleView { UIView View; UIStackView mainStackView = new UIStackView(); UILabel hedinglbl = new UILabel(); UILabel payamountlabl = new UILabel(); UILabel amntLabl = new UILabel(); UILabel selcetPaylbl = new UILabel(); SfRadioGroup sfr = new SfRadioGroup(); UIButton button = new UIButton(); CALayer layer = new CALayer(); CALayer innerLayer = new CALayer(); UIAlertView alertView = new UIAlertView(); SfRadioButton netBanking = new SfRadioButton(); SfRadioButton debitCard = new SfRadioButton(); SfRadioButton creditCard = new SfRadioButton(); UIFontDescriptor descriptor = null; UIFontDescriptorSymbolicTraits traits = (UIFontDescriptorSymbolicTraits)0; public RadioButton_Mobile() { View = new UIView(); //Main statck layer.BorderWidth = 1.5f; layer.CornerRadius = 10; layer.BorderColor = UIColor.FromRGB(205, 205, 205).CGColor; Layer.AddSublayer(layer); //inner layer innerLayer.BorderWidth = 1.5f; innerLayer.CornerRadius = 10; innerLayer.BorderColor = UIColor.FromRGB(205, 205, 205).CGColor; mainStackView.Layer.AddSublayer(innerLayer); descriptor = new UIFontDescriptor().CreateWithFamily(amntLabl.Font.FamilyName); traits = traits | UIFontDescriptorSymbolicTraits.Bold; descriptor = descriptor.CreateWithTraits(traits); //heading hedinglbl.Text = "Complete your Payment"; hedinglbl.TextColor = UIColor.FromRGB(85, 85, 85); hedinglbl.Font = UIFont.FromDescriptor(descriptor, 20); mainStackView.AddSubview(hedinglbl); //payable payamountlabl.Text = "Total payable amount"; payamountlabl.TextColor = UIColor.Black; mainStackView.AddSubview(payamountlabl); //amount amntLabl.Text = "$120"; amntLabl.TextColor = UIColor.FromRGB(0, 125, 230); amntLabl.Font = UIFont.FromDescriptor(descriptor, 18); mainStackView.AddSubview(amntLabl); //amount selcetPaylbl.Text = "Select your payment mode"; mainStackView.AddSubview(selcetPaylbl); //RadioGroup sfr.Axis = UILayoutConstraintAxis.Vertical; sfr.Spacing = 20; netBanking.SetTitle("Net banking", UIControlState.Normal); netBanking.StateChanged += paymentMode_StateChanged; sfr.AddArrangedSubview(netBanking); debitCard.SetTitle("Debit card", UIControlState.Normal); debitCard.StateChanged += paymentMode_StateChanged; sfr.AddArrangedSubview(debitCard); creditCard.SetTitle("Credit card", UIControlState.Normal); creditCard.StateChanged += paymentMode_StateChanged; sfr.AddArrangedSubview(creditCard); mainStackView.AddSubview(sfr); View.AddSubview(mainStackView); button.SetTitle("Pay Now", UIControlState.Normal); button.SetTitleColor(UIColor.LightGray, UIControlState.Disabled); button.SetTitleColor(UIColor.White, UIControlState.Normal); button.TouchDown += Button_Clicked; button.BackgroundColor = UIColor.FromRGB(0, 125, 230); button.Enabled = false; alertView.Message = "Payment Successfull !"; alertView.AddButton("OK"); View.AddSubview(button); AddSubview(View); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = new CGRect(Frame.Location.X, 0.0f, Frame.Size.Width, Frame.Size.Height); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { mainStackView.Frame = new CGRect(45, 110, Frame.Size.Width - 110, 550); layer.Frame = new CGRect(45, 90, Frame.Size.Width - 110, 550); hedinglbl.Frame = new CGRect(150, 20, 400, 45); payamountlabl.Frame = new CGRect(20, 100, 350, 35); amntLabl.Frame = new CGRect(580, 100, 350, 35); innerLayer.Frame = new CGRect(17, 170, 625, 2); selcetPaylbl.Frame = new CGRect(20, 205, 400, 35); sfr.Frame = new CGRect(20, 275, 200, 200); sfr.Spacing = 40; button.Frame = new CGRect(0, Frame.Size.Height - 40, Frame.Size.Width, 40); hedinglbl.Font = UIFont.FromDescriptor(descriptor, 30); payamountlabl.Font = UIFont.FromName(payamountlabl.Font.FamilyName, 22); amntLabl.Font = UIFont.FromDescriptor(descriptor, 22); selcetPaylbl.Font = UIFont.FromName(selcetPaylbl.Font.FamilyName, 22); netBanking.Font = UIFont.FromName(netBanking.Font.FamilyName, 20); debitCard.Font = UIFont.FromName(netBanking.Font.FamilyName, 20); creditCard.Font = UIFont.FromName(netBanking.Font.FamilyName, 20); button.Font = UIFont.FromName(netBanking.Font.FamilyName, 25); } else { mainStackView.Frame = new CGRect(20, 35, Frame.Size.Width - 40, 400); layer.Frame = new CGRect(20, 35, Frame.Size.Width - 40, 400); hedinglbl.Frame = new CGRect(20, 20, 260, 30); payamountlabl.Frame = new CGRect(10, 75, 200, 35); amntLabl.Frame = new CGRect(220, 75, 200, 35); innerLayer.Frame = new CGRect(8, 140, 263, 1); selcetPaylbl.Frame = new CGRect(10, 165, 250, 35); sfr.Frame = new CGRect(10, 220, 200, 150); button.Frame = new CGRect(0, 465, Frame.Size.Width, 38); } } base.LayoutSubviews(); } private void Button_Clicked(object sender, EventArgs e) { alertView.Show(); debitCard.IsChecked = false; creditCard.IsChecked = false; netBanking.IsChecked = false; button.Enabled = false; } private void paymentMode_StateChanged(object sender, StateChangedEventArgs eventArgs) { button.Enabled = true; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Popup/PopupGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using System.Globalization; using CoreGraphics; using Syncfusion.iOS.PopupLayout; using System.Linq; using System.Reflection; using Foundation; using System.Threading; using System.Timers; using CoreAnimation; using System.Threading.Tasks; namespace SampleBrowser { public class PopupGettingStarted : SampleView { #region Fields SfDataGrid SfGrid; int clickCount = 0; UIView mainView; SfPopupLayout sfPopUp; UIView backgroundView; UIImageView imageView; UIImageView img; UITapGestureRecognizer tapGesture; SwipingViewModel viewModel; DetailView detailView; UIButton nextButton; UILabel col1; UILabel col2; UILabel col3; UILabel col4; UITextField orderIDText; UITextField customerIDText; UITextField employeeIDText; UITextField nameText; private int swipedRowindex; private bool IsUndoClicked { get; set; } #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public PopupGettingStarted() { mainView = new UIView(); CreatePopup(); this.CreateDataGrid(); this.nextButton = new UIButton(); nextButton.SetTitle("Next", UIControlState.Normal); nextButton.SetTitleColor(UIColor.White, UIControlState.Normal); nextButton.VerticalAlignment = UIControlContentVerticalAlignment.Center; nextButton.BackgroundColor = UIColor.Clear; nextButton.TouchDown += NextButton_TouchDown; sfPopUp.Content = mainView; mainView.AddSubview(SfGrid); this.AddSubview(sfPopUp); this.AddSubview(nextButton); tapGesture = new UITapGestureRecognizer() { NumberOfTapsRequired = 1 }; tapGesture.AddTarget(() => { BackgroundViewPressed(tapGesture); }); } public override void LayoutSubviews() { base.LayoutSubviews(); this.SfGrid.Frame = new CGRect(mainView.Frame.Left, mainView.Frame.Top, mainView.Frame.Width, mainView.Frame.Height ); this.sfPopUp.Frame = new CGRect(0, 0, this.Frame.Width , this.Frame.Height); this.nextButton.Frame = new CGRect(this.Frame.Width - 100, this.Frame.Height- 60, 100, 30); detailView.Frame = new CGRect(10, this.SfGrid.Frame.Top + 100, SfGrid.Frame.Width - 20, 200); col1.Frame = new CGRect(detailView.Frame.Right * 0.15, detailView.Frame.Top + 20, detailView.Frame.Right / 2, 20); col2.Frame = new CGRect(detailView.Frame.Right * 0.15, col1.Frame.Bottom + 10, detailView.Frame.Right / 2, 20); col3.Frame = new CGRect(detailView.Frame.Right * 0.15, col2.Frame.Bottom + 10, detailView.Frame.Right / 2, 20); col4.Frame = new CGRect(detailView.Frame.Right * 0.15, col3.Frame.Bottom + 10, detailView.Frame.Right / 2, 20); orderIDText.Frame = new CGRect(col1.Frame.Right, detailView.Frame.Top + 20, detailView.Frame.Right, 20); customerIDText.Frame = new CGRect(col2.Frame.Right, orderIDText.Frame.Bottom + 10, detailView.Frame.Right, 20); employeeIDText.Frame = new CGRect(col3.Frame.Right, customerIDText.Frame.Bottom + 10, detailView.Frame.Right, 20); nameText.Frame = new CGRect(col4.Frame.Right, employeeIDText.Frame.Bottom + 10, detailView.Frame.Right, 20); var navigationBar = (((mainView.Superview as UIView).Window.RootViewController)as UINavigationController).NavigationBar; } void NextButton_TouchDown(object sender, EventArgs e) { clickCount++; sfPopUp.IsOpen = false; if (imageView == null) { imageView = new UIImageView(); } if (clickCount == 1) { imageView = null; imageView = new UIImageView(); UIView hostingView = new UIView(); imageView.Image = UIImage.FromFile("Images/Popup_ResizingIllustration.png"); sfPopUp.PopupView.Frame = new CGRect(1, this.Frame.Y, this.Frame.Width, 130); hostingView.Frame = new CGRect(0, 0, 160, 130); imageView.Frame = new CGRect(this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(0, 2)).X, 0, 130, 130); imageView.Center = new CGPoint(this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(0, 2)).X, this.Frame.Y); hostingView.AddSubview(imageView); sfPopUp.PopupView.ContentView = hostingView; sfPopUp.IsOpen = true; } else if (clickCount == 2) { imageView = null; imageView = new UIImageView(); imageView.Image = UIImage.FromFile("Images/Popup_EditIllustration.png"); sfPopUp.PopupView.ContentView = imageView; var point = this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(4, 2)); sfPopUp.PopupView.Frame = new CGRect(point.X, point.Y, 150, 150); sfPopUp.IsOpen = true; } else if (clickCount == 3) { imageView = null; UIView hostingView = new UIView(); imageView = new UIImageView(); imageView.StopAnimating(); imageView.Image = UIImage.FromFile("Images/Popup_SwipeIllustration.png"); var point = this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(4, 0)); sfPopUp.PopupView.Frame = new CGRect(point.X, point.Y - 10, 300, 150); hostingView.Frame = new CGRect(0, sfPopUp.PopupView.Frame.Top, 300, 150); imageView.Frame = new CGRect(point.X, 0, 200, 150); hostingView.AddSubview(imageView); sfPopUp.PopupView.ContentView = hostingView; sfPopUp.IsOpen = true; } else if (clickCount == 4) { UIView view = new UIView(); imageView = null; imageView = new UIImageView(); imageView.Image = UIImage.FromFile("Images/Popup_DragAndDropIllustration.png"); imageView.Frame = new CGRect(0, 0, 200, 100); var point = this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(4, 0)); view.AddSubview(imageView); img = new UIImageView(); img.Image = UIImage.FromFile("Images/Popup_HandSymbol.png"); img.Frame = new CGRect(10, 0, 20, 20); view.AddSubview(img); sfPopUp.PopupView.ContentView = view; sfPopUp.PopupView.Frame = new CGRect(point.X + 10, point.Y + 5, 200, 100); nextButton.SetTitle("Ok,Got It", UIControlState.Normal); sfPopUp.IsOpen = true; } else if (clickCount > 4) { backgroundView.RemoveFromSuperview(); nextButton.RemoveFromSuperview(); } } private void CreateDataGrid() { col1 = new UILabel(); col1.Text = "Order ID"; col2 = new UILabel(); col2.Text = "Customer ID"; col3 = new UILabel(); col3.Text = "Employee ID"; col4 = new UILabel(); col4.Text = "Name"; orderIDText = new UITextField(); orderIDText.AllowsEditingTextAttributes = true; orderIDText.ShouldReturn += (textField) => { orderIDText.ResignFirstResponder(); return true; }; customerIDText = new UITextField(); customerIDText.ShouldReturn += (textField) => { customerIDText.ResignFirstResponder(); return true; }; employeeIDText = new UITextField(); employeeIDText.ShouldReturn += (textField) => { employeeIDText.ResignFirstResponder(); return true; }; nameText = new UITextField(); nameText.ShouldReturn += (textField) => { nameText.ResignFirstResponder(); return true; }; orderIDText.Hidden = true; customerIDText.Hidden = true; employeeIDText.Hidden = true; nameText.Hidden = true; col1.Hidden = true; col2.Hidden = true; col3.Hidden = true; col4.Hidden = true; this.detailView = new DetailView(); this.detailView.Hidden = true; this.SfGrid = new SfDataGrid(); this.SfGrid.GridLoaded += SfGrid_GridLoaded; this.SfGrid.AllowDraggingRow = true; this.SfGrid.AllowEditing = true; this.SfGrid.AllowResizingColumn = true; this.viewModel = new SwipingViewModel(); this.SfGrid.ItemsSource = viewModel.OrdersInfo; this.SfGrid.AutoGenerateColumns = false; this.SfGrid.GridStyle = new CustomStyles(); this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.ColumnSizer = ColumnSizer.Star; UIButton leftSwipeViewText = new UIButton(); leftSwipeViewText.SetTitle("Delete", UIControlState.Normal); leftSwipeViewText.SetTitleColor(UIColor.White, UIControlState.Normal); leftSwipeViewText.VerticalAlignment = UIControlContentVerticalAlignment.Center; leftSwipeViewText.BackgroundColor = UIColor.FromRGB(220, 89, 95); leftSwipeViewText.TouchDown += LeftSwipeViewButton_TouchDown; leftSwipeViewText.Frame = new CGRect(56, 0, 60, 45); UIButton leftSwipeViewButton = new UIButton(); leftSwipeViewButton.SetImage(UIImage.FromFile("Images/Popup_Delete.png"), UIControlState.Normal); leftSwipeViewButton.BackgroundColor = UIColor.FromRGB(220, 89, 95); leftSwipeViewButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; leftSwipeViewButton.TouchDown += LeftSwipeViewButton_TouchDown; leftSwipeViewButton.Frame = new CGRect(16, 10, 24, 24); CustomSwipeView leftSwipeView = new CustomSwipeView(); leftSwipeView.AddSubview(leftSwipeViewButton); leftSwipeView.AddSubview(leftSwipeViewText); leftSwipeView.Frame = new CGRect(0, 0, 120, 44); leftSwipeView.BackgroundColor = UIColor.FromRGB(220, 89, 95); this.SfGrid.AllowSwiping = true; this.SfGrid.LeftSwipeView = leftSwipeView; this.SfGrid.SwipeEnded += SfGrid_SwipeEnded; this.SfGrid.SwipeStarted += SfGrid_SwipeStarted; GridTextColumn CustomerID = new GridTextColumn(); CustomerID.MappingName = "CustomerID"; CustomerID.HeaderText = "Customer ID"; GridTextColumn OrderID = new GridTextColumn(); OrderID.MappingName = "OrderID"; OrderID.HeaderText = "Order ID"; GridTextColumn EmployeeID = new GridTextColumn(); EmployeeID.MappingName = "EmployeeID"; EmployeeID.HeaderText = "Employee ID"; GridTextColumn Name = new GridTextColumn(); Name.MappingName = "FirstName"; Name.HeaderText = "Name"; this.SfGrid.Columns.Add(OrderID); this.SfGrid.Columns.Add(CustomerID); this.SfGrid.Columns.Add(EmployeeID); this.SfGrid.Columns.Add(Name); } void LeftSwipeViewButton_TouchDown (object sender, EventArgs e) { viewModel.OrdersInfo.RemoveAt(swipedRowindex - 1); } void SfGrid_SwipeStarted(object sender, SwipeStartedEventArgs e) { SfGrid.MaxSwipeOffset = 120; } private void initializeTextFields() { if (swipedRowindex > 0) { var swipedRowData = this.viewModel.OrdersInfo[this.swipedRowindex - 1]; orderIDText.Text = swipedRowData.OrderID; this.customerIDText.Text = swipedRowData.CustomerID; this.employeeIDText.Text = swipedRowData.EmployeeID; this.nameText.Text = swipedRowData.FirstName; } } private void SfGrid_SwipeEnded(object sender, SwipeEndedEventArgs e) { swipedRowindex = e.RowIndex; initializeTextFields(); } private void SfGrid_GridLoaded(object sender, GridLoadedEventArgs e) { sfPopUp.PopupView.Frame = new CGRect(this.Frame.Width - 25, this.Frame.Y, 150, 100); sfPopUp.Show(); } private void CreatePopup() { sfPopUp = new SfPopupLayout(); sfPopUp.StaysOpen = true; sfPopUp.PopupView.AnimationMode = AnimationMode.None; sfPopUp.PopupView.PopupStyle.BorderThickness = 0; sfPopUp.PopupView.PopupStyle.BorderColor = UIColor.Clear; sfPopUp.PopupView.ShowFooter = false; sfPopUp.PopupView.ShowHeader = false; sfPopUp.Opened += SfPopUp_PopupOpened; sfPopUp.Closed += SfPopUp_PopupClosed; sfPopUp.BackgroundColor = UIColor.Clear; imageView = new UIImageView(); imageView.Image = UIImage.FromFile("Images/Popup_InfoNotification.png"); sfPopUp.PopupView.ContentView = imageView; } private void SfPopUp_PopupClosed(object sender, EventArgs e) { //if (clickCount == 5) //backgroundView.RemoveFromSuperview(); } private void SfPopUp_PopupOpened(object sender, EventArgs e) { AddBackgroundView(); if (clickCount == 0) { Action moveUpDown = () => { var ypos = this.Frame.Y + 20; imageView.Center = new CGPoint(imageView.Center.X, ypos); }; UIView.Animate(1, 0, UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.Autoreverse | UIViewAnimationOptions.Repeat, moveUpDown, () => { }); } else if (clickCount == 1) { Action moveLeftRight = () => { var xpos = imageView.Center.X + 60; var ypos = sfPopUp.PopupView.Center.Y; imageView.Center = new CGPoint(xpos, imageView.Center.Y); }; UIView.Animate(2, 0, UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Repeat, moveLeftRight, () => { }); } else if (clickCount == 2) { imageView.Alpha = 0.0f; Action setOpacity = () => { imageView.Alpha = 1.0f; }; UIView.Animate(0.25, 0, UIViewAnimationOptions.CurveEaseInOut , setOpacity ,async () => { imageView.Alpha = 0.0f; await Task.Delay(200); imageView.Alpha = 1.0f; await Task.Delay(1000); LoopAnimate(); }); } else if (clickCount == 3) { Action moveLeftRight = () => { var xpos = sfPopUp.PopupView.Center.X + 60; var ypos = imageView.Center.Y; imageView.Center = new CGPoint(xpos, ypos); }; UIView.Animate(2, 0, UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.Repeat, moveLeftRight, () => { }); } else if (clickCount == 4) { CGPoint fromPt = new CGPoint(img.Center.X + 10, img.Center.Y + 10); img.Layer.Position = new CGPoint(img.Center.X + 70, img.Center.Y + 70); CGPath path = new CGPath(); path.AddLines(new CGPoint[] { fromPt, new CGPoint(30, 20),new CGPoint(40, 25), new CGPoint(50, 30), new CGPoint(60, 40),new CGPoint(70, 50),new CGPoint(80, 60), new CGPoint(80,70) }); CAKeyFrameAnimation animPosition = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath("position"); animPosition.Path = path; animPosition.RepeatCount = int.MaxValue; animPosition.Duration = 1.25; img.Layer.AddAnimation(animPosition, "position"); } } private async void LoopAnimate() { if (clickCount > 2) return; else { imageView.Alpha = 0.0f; Action setOpacity = () => { imageView.Alpha = 1.0f; }; UIView.Animate(0.25, 0, UIViewAnimationOptions.CurveEaseInOut, setOpacity, async () => { imageView.Alpha = 0.0f; await Task.Delay(200); imageView.Alpha = 1.0f; await Task.Delay(1000); LoopAnimate(); }); } } private void AddBackgroundView() { if (mainView.Subviews.FirstOrDefault(x => x.Tag == 100) == null) { backgroundView = new UIView(); backgroundView.Tag = 100; backgroundView.BackgroundColor = UIColor.Black; backgroundView.Alpha = 0.82f; backgroundView.AddGestureRecognizer(tapGesture); this.mainView.AddSubview(backgroundView); backgroundView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); } } private void BackgroundViewPressed(UITapGestureRecognizer tapGesture) { clickCount++; sfPopUp.IsOpen = false; if (imageView == null) { imageView = new UIImageView(); } if (clickCount == 1) { imageView = null; imageView = new UIImageView(); UIView hostingView = new UIView(); imageView.Image = UIImage.FromFile("Images/Popup_ResizingIllustration.png"); sfPopUp.PopupView.Frame = new CGRect(1, this.Frame.Y, this.Frame.Width, 130); hostingView.Frame = new CGRect(0, 0, 160, 130); imageView.Frame = new CGRect(this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(0, 2)).X, 0, 130, 130); imageView.Center = new CGPoint(this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(0, 2)).X, this.Frame.Y); hostingView.AddSubview(imageView); sfPopUp.PopupView.ContentView = hostingView; sfPopUp.IsOpen = true; } else if (clickCount == 2) { imageView = null; imageView = new UIImageView(); imageView.Image = UIImage.FromFile("Images/Popup_EditIllustration.png"); sfPopUp.PopupView.ContentView = imageView; var point = this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(4, 2)); sfPopUp.PopupView.Frame = new CGRect(point.X, point.Y, 150, 150); sfPopUp.IsOpen = true; } else if (clickCount == 3) { imageView = null; UIView hostingView = new UIView(); imageView = new UIImageView(); imageView.StopAnimating(); imageView.Image = UIImage.FromFile("Images/Popup_SwipeIllustration.png"); var point = this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(4, 0)); sfPopUp.PopupView.Frame = new CGRect(point.X, point.Y - 10, 300, 150); hostingView.Frame = new CGRect(0, sfPopUp.PopupView.Frame.Top, 300, 150); imageView.Frame = new CGRect(point.X, 0, 200, 150); hostingView.AddSubview(imageView); sfPopUp.PopupView.ContentView = hostingView; sfPopUp.IsOpen = true; } else if (clickCount == 4) { UIView view = new UIView(); imageView = null; imageView = new UIImageView(); imageView.Image = UIImage.FromFile("Images/Popup_DragAndDropIllustration.png"); imageView.Frame = new CGRect(0, 0, 200, 100); var point = this.SfGrid.RowColumnIndexToPoint(new Syncfusion.GridCommon.ScrollAxis.RowColumnIndex(4, 0)); view.AddSubview(imageView); img = new UIImageView(); img.Image = UIImage.FromFile("Images/Popup_HandSymbol.png"); img.Frame = new CGRect(10, 0, 20, 20); view.AddSubview(img); sfPopUp.PopupView.ContentView = view; sfPopUp.PopupView.Frame = new CGRect(point.X + 10, point.Y + 5, 200, 100); nextButton.SetTitle("Ok,Got It", UIControlState.Normal); sfPopUp.IsOpen = true; } else if (clickCount > 4) { backgroundView.RemoveFromSuperview(); nextButton.RemoveFromSuperview(); } } protected override void Dispose(bool disposing) { //sfPopUp.DismissPopup(true); if (backgroundView != null) { mainView.WillRemoveSubview(backgroundView); mainView.SendSubviewToBack(backgroundView); sfPopUp.RemoveFromSuperview(); backgroundView.BackgroundColor = UIColor.Brown; backgroundView.UserInteractionEnabled = false; backgroundView.Frame = new CGRect(0, 0, 0, 0); backgroundView.RemoveFromSuperview(); nextButton.RemoveFromSuperview(); backgroundView = null; } base.Dispose(disposing); if (SfGrid != null) SfGrid.Dispose(); if (sfPopUp != null) sfPopUp.Dispose(); mainView = null; } } } <file_sep>/iOS/SampleBrowser/Samples/PDF/Encryption.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf; using Syncfusion.Pdf.Barcode; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Security; using MessageUI; using System.Collections.Generic; using Syncfusion.Pdf.Interactive; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class Encryption : SampleView { public Encryption() { this.algorithmlist.Add((NSString)"AES"); this.algorithmlist.Add((NSString)"RC4"); this.AESkeylist.Add((NSString)"128 Bit"); this.AESkeylist.Add((NSString)"256 Bit"); this.AESkeylist.Add((NSString)"256Revision6"); RC4keylist.Add((NSString)"40 Bit"); RC4keylist.Add((NSString)"128 Bit"); this.options.Add("Encrypt all contents"); this.options.Add("Encrypt all contents except metadata"); this.options.Add("Encrypt only attachments"); algorithmfilterType = "AES"; keysizefilterType = "128 Bit"; optionType = "Encrypt all contents"; } CGRect frameRect = new CGRect (); float frameMargin = 8.0f; private readonly IList<string> algorithmlist = new List<string>(); private readonly IList<string> AESkeylist = new List<string>(); private readonly IList<string> RC4keylist = new List<string>(); private readonly IList<string> options = new List<string>(); UILabel filterLabel; UILabel userPasswordLabel; UILabel ownerPasswordLabel; UIButton filterDoneButton; UIButton filterButton; UIPickerView filterPicker; UILabel filterActionLabel; UIButton filterActionDoneButton; UIButton filterActionButton; UIPickerView filterActionPicker; UILabel filterActionLabel1; UIButton filterActionDoneButton1; UIButton filterActionButton1; UIPickerView filterActionPicker1; string algorithmfilterType; string keysizefilterType; string optionType; bool isLoaded = false; UIButton button; UILabel optionLabel; UIButton optionDoneButton; UIButton optionButton; UIPickerView optionPicker; void LoadAllowedTextsLabel() { #region Description Label UILabel label = new UILabel (); label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to create secure PDF document."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width ,35); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width ,50); } this.AddSubview (label); #endregion #region Filter Region filterLabel = new UILabel(); userPasswordLabel = new UILabel(); ownerPasswordLabel = new UILabel(); filterDoneButton = new UIButton(); filterButton = new UIButton(); filterPicker = new UIPickerView(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { filterLabel.Font = UIFont.SystemFontOfSize(18); userPasswordLabel.Font = UIFont.SystemFontOfSize(15); ownerPasswordLabel.Font = UIFont.SystemFontOfSize(15); userPasswordLabel.Frame = new CGRect(10, 320, frameRect.Location.X + frameRect.Size.Width - 20, 30); ownerPasswordLabel.Frame = new CGRect(10, 350, frameRect.Location.X + frameRect.Size.Width - 20, 30); filterLabel.Frame = new CGRect(10, 45, frameRect.Location.X + frameRect.Size.Width - 20, 50); filterButton.Frame = new CGRect(10, 95, frameRect.Location.X + frameRect.Size.Width - 20, 40); } else { userPasswordLabel.Frame = new CGRect(10, 325, frameRect.Location.X + frameRect.Size.Width - 20, 30); ownerPasswordLabel.Frame = new CGRect(10, 355, frameRect.Location.X + frameRect.Size.Width - 20, 30); filterLabel.Frame = new CGRect(10, 50, frameRect.Location.X + frameRect.Size.Width - 20, 50); filterButton.Frame = new CGRect(10, 100, frameRect.Location.X + frameRect.Size.Width - 20, 40); } //filter Label filterLabel.TextColor = UIColor.Black; filterLabel.BackgroundColor = UIColor.Clear; filterLabel.Text = @"Encryption Algorithms"; filterLabel.TextAlignment = UITextAlignment.Left; filterLabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(filterLabel); //user password label //userPasswordLabel.TextColor = UIColor.Black; userPasswordLabel.BackgroundColor = UIColor.Clear; userPasswordLabel.Text = @"User Password: <PASSWORD>"; userPasswordLabel.TextAlignment = UITextAlignment.Left; userPasswordLabel.Font = UIFont.FromName("Helvetica", 15f); //owner password label //ownerPasswordLabel.TextColor = UIColor.Black; ownerPasswordLabel.BackgroundColor = UIColor.Clear; ownerPasswordLabel.Text = @"Owner Password: <PASSWORD>"; ownerPasswordLabel.TextAlignment = UITextAlignment.Left; ownerPasswordLabel.Font = UIFont.FromName("Helvetica", 15f); //filter button filterButton.SetTitle("AES", UIControlState.Normal); filterButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; filterButton.BackgroundColor = UIColor.Clear; filterButton.SetTitleColor(UIColor.Black, UIControlState.Normal); filterButton.Hidden = false; filterButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; filterButton.Layer.BorderWidth = 4; filterButton.Layer.CornerRadius = 8; filterButton.Font = UIFont.FromName("Helvetica", 16f); filterButton.TouchUpInside += ShowFilterPicker; this.AddSubview(filterButton); //filterpicker PickerModel filterPickermodel = new PickerModel(this.algorithmlist); filterPickermodel.PickerChanged += (sender, e) => { this.algorithmfilterType = e.SelectedValue; filterButton.SetTitle(algorithmfilterType, UIControlState.Normal); }; filterPicker = new UIPickerView(); filterPicker.ShowSelectionIndicator = true; filterPicker.Hidden = true; filterPicker.Model = filterPickermodel; filterPicker.BackgroundColor = UIColor.White; //filterDoneButtonn filterDoneButton = new UIButton(); filterDoneButton.SetTitle("Done\t", UIControlState.Normal); filterDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; filterDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); filterDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); filterDoneButton.Hidden = true; filterDoneButton.TouchUpInside += HideFilterPicker; filterPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 20, this.Frame.Size.Width, this.Frame.Size.Height / 3); filterDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 20, this.Frame.Size.Width, 40); this.AddSubview(filterPicker); this.AddSubview(filterDoneButton); #endregion #region Filter Action Region filterActionLabel = new UILabel(); filterActionDoneButton = new UIButton(); filterActionButton = new UIButton(); filterActionPicker = new UIPickerView(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { filterActionLabel.Font = UIFont.SystemFontOfSize(18); filterActionLabel.Frame = new CGRect(10, 140, frameRect.Location.X + frameRect.Size.Width - 20, 50); filterActionButton.Frame = new CGRect(10, 190, frameRect.Location.X + frameRect.Size.Width - 20, 40); } else { filterActionLabel.Frame = new CGRect(10, 145, frameRect.Location.X + frameRect.Size.Width - 20, 50); filterActionButton.Frame = new CGRect(10, 195, frameRect.Location.X + frameRect.Size.Width - 20, 40); } //filterActionLabel filterActionLabel.TextColor = UIColor.Black; filterActionLabel.BackgroundColor = UIColor.Clear; filterActionLabel.Text = @"Encryption KeySize"; filterActionLabel.TextAlignment = UITextAlignment.Left; filterActionLabel.Font = UIFont.FromName("Helvetica", 16f); //filterActionButton filterActionButton.SetTitle("128 Bit", UIControlState.Normal); filterActionButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; filterActionButton.BackgroundColor = UIColor.Clear; filterActionButton.SetTitleColor(UIColor.Black, UIControlState.Normal); filterActionButton.Hidden = false; filterActionButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; filterActionButton.Layer.BorderWidth = 4; filterActionButton.Layer.CornerRadius = 8; filterActionButton.Font = UIFont.FromName("Helvetica", 16f); filterActionButton.TouchUpInside += ShowFilterActionPicker; //filterActionPickermodel PickerModel filterActionPickermodel = new PickerModel(this.AESkeylist); filterActionPickermodel.PickerChanged += (sender, e) => { this.keysizefilterType = e.SelectedValue; filterActionButton.SetTitle(keysizefilterType, UIControlState.Normal); }; filterActionPicker = new UIPickerView(); filterActionPicker.ShowSelectionIndicator = true; filterActionPicker.Hidden = true; filterActionPicker.Model = filterActionPickermodel; filterActionPicker.BackgroundColor = UIColor.White; //filterActionDoneButton filterActionDoneButton = new UIButton(); filterActionDoneButton.SetTitle("Done\t", UIControlState.Normal); filterActionDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; filterActionDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); filterActionDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); filterActionDoneButton.Hidden = true; filterActionDoneButton.TouchUpInside += HideFilterActionPicker; filterActionPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); filterActionDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 30,this.Frame.Size.Width, 40); this.AddSubview(filterActionPicker); this.AddSubview(filterActionDoneButton); optionLabel = new UILabel(); optionDoneButton = new UIButton(); optionButton = new UIButton(); optionPicker = new UIPickerView(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { optionLabel.Font = UIFont.SystemFontOfSize(18); optionLabel.Frame = new CGRect(10, 235, frameRect.Location.X + frameRect.Size.Width - 20, 50); optionButton.Frame = new CGRect(10, 285, frameRect.Location.X + frameRect.Size.Width - 20, 40); } else { optionLabel.Frame = new CGRect(10, 240, frameRect.Location.X + frameRect.Size.Width - 20, 50); optionButton.Frame = new CGRect(10, 280, frameRect.Location.X + frameRect.Size.Width - 20, 40); } //optionLabel optionLabel.TextColor = UIColor.Black; optionLabel.BackgroundColor = UIColor.Clear; optionLabel.Text = @"Encryption Options"; optionLabel.TextAlignment = UITextAlignment.Left; optionLabel.Font = UIFont.FromName("Helvetica", 16f); //optionButton optionButton.SetTitle("Encrypt all contents", UIControlState.Normal); optionButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; optionButton.BackgroundColor = UIColor.Clear; optionButton.SetTitleColor(UIColor.Black, UIControlState.Normal); optionButton.Hidden = false; optionButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; optionButton.Layer.BorderWidth = 4; optionButton.Layer.CornerRadius = 8; optionButton.Font = UIFont.FromName("Helvetica", 16f); optionButton.TouchUpInside += ShowOptionPicker; //optionPickermodel PickerModel optionPickermodel = new PickerModel(this.options); optionPickermodel.PickerChanged += (sender, e) => { this.optionType = e.SelectedValue; optionButton.SetTitle(this.optionType, UIControlState.Normal); }; optionPicker = new UIPickerView(); optionPicker.ShowSelectionIndicator = true; optionPicker.Hidden = true; optionPicker.Model = optionPickermodel; optionPicker.BackgroundColor = UIColor.White; //optionDoneButton optionDoneButton = new UIButton(); optionDoneButton.SetTitle("Done\t", UIControlState.Normal); optionDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; optionDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); optionDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); optionDoneButton.Hidden = true; optionDoneButton.TouchUpInside += HideOptionPicker; optionPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); optionDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 30, this.Frame.Size.Width, 40); this.AddSubview(optionPicker); this.AddSubview(optionDoneButton); #endregion #region filterActionLabel1 = new UILabel(); filterActionDoneButton1 = new UIButton(); filterActionButton1 = new UIButton(); filterActionPicker1 = new UIPickerView(); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { filterActionButton1.Frame = new CGRect(10, 190, frameRect.Location.X + frameRect.Size.Width - 20, 40); } else { filterActionButton1.Frame = new CGRect(10, 195, frameRect.Location.X + frameRect.Size.Width - 20, 40); } //filterActionButton filterActionButton1.SetTitle("40 Bit", UIControlState.Normal); filterActionButton1.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; filterActionButton1.BackgroundColor = UIColor.Clear; filterActionButton1.SetTitleColor(UIColor.Black, UIControlState.Normal); filterActionButton1.Hidden = true; filterActionButton1.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; filterActionButton1.Layer.BorderWidth = 4; filterActionButton1.Layer.CornerRadius = 8; filterActionButton1.Font = UIFont.FromName("Helvetica", 16f); filterActionButton1.TouchUpInside += ShowFilterActionPicker; //filterActionPickermodel PickerModel filterActionPickermodel1 = new PickerModel(this.RC4keylist); filterActionPickermodel1.PickerChanged += (sender, e) => { this.keysizefilterType = e.SelectedValue; filterActionButton1.SetTitle(keysizefilterType, UIControlState.Normal); }; filterActionPicker1 = new UIPickerView(); filterActionPicker1.ShowSelectionIndicator = true; filterActionPicker1.Hidden = true; filterActionPicker1.Model = filterActionPickermodel1; filterActionPicker1.BackgroundColor = UIColor.White; //filterActionDoneButton filterActionDoneButton1 = new UIButton(); filterActionDoneButton1.SetTitle("Done\t", UIControlState.Normal); filterActionDoneButton1.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; filterActionDoneButton1.BackgroundColor = UIColor.FromRGB(240, 240, 240); filterActionDoneButton1.SetTitleColor(UIColor.Black, UIControlState.Normal); filterActionDoneButton1.Hidden = true; filterActionDoneButton1.TouchUpInside += HideFilterActionPicker; filterActionPicker1.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 30, this.Frame.Size.Width, this.Frame.Size.Height / 3); filterActionDoneButton1.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 30, this.Frame.Size.Width, 40); this.AddSubview(filterActionPicker1); this.AddSubview(filterActionDoneButton1); this.AddSubview(filterActionButton1); #endregion this.AddSubview(filterActionLabel); this.AddSubview(filterActionButton); this.AddSubview(optionLabel); this.AddSubview(optionButton); this.AddSubview(userPasswordLabel); this.AddSubview(ownerPasswordLabel); //button button = new UIButton (UIButtonType.System); button.SetTitle("Generate PDF", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 390, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(0, 395, frameRect.Location.X + frameRect.Size.Width, 10); } button.TouchUpInside += OnButtonClicked; this.AddSubview (button); isLoaded = true; } void OnButtonClicked(object sender, EventArgs e) { //Create new PDF document. PdfDocument document = new PdfDocument(); //Add page to the PDF document. PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; //Create font object. PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Bold); PdfBrush brush = PdfBrushes.Black; //Document security PdfSecurity security = document.Security; int algorithmindex = algorithmlist.IndexOf(algorithmfilterType); int keyindex; if(algorithmindex==0) { keyindex= AESkeylist.IndexOf(keysizefilterType); security.Algorithm = PdfEncryptionAlgorithm.AES; if(keyindex == 0) { security.KeySize = PdfEncryptionKeySize.Key128Bit; } else if(keyindex == 1) { security.KeySize = PdfEncryptionKeySize.Key256Bit; } else if(keyindex == 2) { security.KeySize = PdfEncryptionKeySize.Key256BitRevision6; } } else { keyindex=RC4keylist.IndexOf(keysizefilterType); if(keyindex == 0) { security.KeySize = PdfEncryptionKeySize.Key40Bit; } else if(keyindex == 1) { security.KeySize = PdfEncryptionKeySize.Key128Bit; } } int optionIndex = options.IndexOf(optionType); if (optionIndex == 0) { security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents; } else if (optionIndex == 1) { security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata; } else if (optionIndex == 2) { //Read the file Stream file = typeof(DigitalSignatureValidation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Products.xml"); //Creates an attachment PdfAttachment attachment = new PdfAttachment("Products.xml", file); attachment.ModificationDate = DateTime.Now; attachment.Description = "About Syncfusion"; attachment.MimeType = "application/txt"; //Adds the attachment to the document document.Attachments.Add(attachment); security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments; } security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint; security.UserPassword = "<PASSWORD>"; security.OwnerPassword = "<PASSWORD>"; string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" + "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm); if(algorithmindex==1) { if(keyindex == 2) { text += String.Format("\n\nRevision: {0}", "Revision 6"); } else if (keyindex == 1 ) { text += String.Format("\n\nRevision: {0}", "Revision 5"); } } // Draw String. graphics.DrawString("Document is Encrypted with following settings", font, brush, Syncfusion.Drawing.PointF.Empty); font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Bold); graphics.DrawString(text, font, brush, new Syncfusion.Drawing.PointF(0, 40)); MemoryStream stream = new MemoryStream(); //Save the PDF document. document.Save(stream); document.Close(); if (stream != null) { stream.Position = 0; SaveiOS iosSave = new SaveiOS(); iosSave.Save("Secure.pdf", "application/pdf", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); if(!isLoaded) LoadAllowedTextsLabel(); base.LayoutSubviews(); } void ShowFilterPicker(object sender, EventArgs e) { filterDoneButton.Hidden = false; filterPicker.Hidden = false; button.Hidden = true; filterActionLabel.Hidden = true; userPasswordLabel.Hidden = true; ownerPasswordLabel.Hidden = true; filterActionButton.Hidden = true; filterActionButton1.Hidden = true; optionButton.Hidden = true; optionLabel.Hidden = true; this.BecomeFirstResponder(); } void HideFilterPicker(object sender, EventArgs e) { int index = algorithmlist.IndexOf(algorithmfilterType); filterDoneButton.Hidden = true; filterPicker.Hidden = true; button.Hidden = false; this.BecomeFirstResponder(); filterActionLabel.Hidden = false; userPasswordLabel.Hidden = false; ownerPasswordLabel.Hidden = false; if (index == 1) { filterActionButton.Hidden = true; filterActionButton1.Hidden = false; } else { filterActionButton.Hidden = false; filterActionButton1.Hidden = true; } this.optionType = "Encrypt all contents"; optionButton.SetTitle(this.optionType, UIControlState.Normal); if (algorithmfilterType == "RC4") { this.keysizefilterType = "40 Bit"; this.optionLabel.Hidden = true; this.optionButton.Hidden = true; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.userPasswordLabel.Frame = new CGRect(10, 235, frameRect.Location.X + frameRect.Size.Width - 20, 50); this.ownerPasswordLabel.Frame = new CGRect(10, 255, frameRect.Location.X + frameRect.Size.Width - 20, 50); button.Frame = new CGRect(0, 300, frameRect.Location.X + frameRect.Size.Width, 10); } else { this.userPasswordLabel.Frame = new CGRect(10, 240, frameRect.Location.X + frameRect.Size.Width - 20, 50); this.ownerPasswordLabel.Frame = new CGRect(10, 260, frameRect.Location.X + frameRect.Size.Width - 20, 50); button.Frame = new CGRect(0, 305, frameRect.Location.X + frameRect.Size.Width, 10); } } else { this.keysizefilterType = "128 Bit"; this.optionLabel.Hidden = false; this.optionButton.Hidden = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.userPasswordLabel.Frame = new CGRect(10, 325, frameRect.Location.X + frameRect.Size.Width - 20, 30); this.ownerPasswordLabel.Frame = new CGRect(10, 355, frameRect.Location.X + frameRect.Size.Width - 20, 30); button.Frame = new CGRect(0, 390, frameRect.Location.X + frameRect.Size.Width, 10); } else { this.userPasswordLabel.Frame = new CGRect(10, 330, frameRect.Location.X + frameRect.Size.Width - 20, 30); this.ownerPasswordLabel.Frame = new CGRect(10, 360, frameRect.Location.X + frameRect.Size.Width - 20, 30); button.Frame = new CGRect(0, 395, frameRect.Location.X + frameRect.Size.Width, 10); } } } void ShowFilterActionPicker(object sender, EventArgs e) { int index = algorithmlist.IndexOf(algorithmfilterType); filterActionLabel.Hidden = true; userPasswordLabel.Hidden = true; ownerPasswordLabel.Hidden = true; filterActionButton.Hidden = true; if (index == 1) { filterActionButton.Hidden = true; filterActionButton1.Hidden = true; filterActionDoneButton.Hidden = true; filterActionPicker.Hidden = true; filterActionDoneButton1.Hidden = false; filterActionPicker1.Hidden = false; } else { filterActionButton.Hidden = true; filterActionButton1.Hidden = true; filterActionDoneButton.Hidden = false; filterActionPicker.Hidden = false; filterActionDoneButton1.Hidden = true; filterActionPicker1.Hidden = true; } optionButton.Hidden = true; optionLabel.Hidden = true; button.Hidden = true; filterButton.Hidden = true; this.BecomeFirstResponder(); } void ShowOptionPicker(object sender, EventArgs e) { optionDoneButton.Hidden = false; optionPicker.Hidden = false; button.Hidden = true; filterActionLabel.Hidden = true; userPasswordLabel.Hidden = true; ownerPasswordLabel.Hidden = true; filterActionButton.Hidden = true; filterActionButton1.Hidden = true; filterLabel.Hidden = true; filterButton.Hidden = true; optionButton.Hidden = true; optionLabel.Hidden = true; this.BecomeFirstResponder(); } void HideFilterActionPicker(object sender, EventArgs e) { int index = algorithmlist.IndexOf(algorithmfilterType); filterActionLabel.Hidden = false; userPasswordLabel.Hidden = false; ownerPasswordLabel.Hidden = false; filterActionDoneButton.Hidden = true; filterActionPicker.Hidden = true; filterActionDoneButton1.Hidden = true; filterActionPicker1.Hidden = true; if (index == 1) { filterActionButton.Hidden = true; filterActionButton1.Hidden = false; } else { filterActionButton.Hidden = false; filterActionButton1.Hidden = true; } button.Hidden = false; filterButton.Hidden = false; if (algorithmfilterType == "RC4") { this.optionLabel.Hidden = true; this.optionButton.Hidden = true; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.userPasswordLabel.Frame = new CGRect(10, 235, frameRect.Location.X + frameRect.Size.Width - 20, 50); this.ownerPasswordLabel.Frame = new CGRect(10, 255, frameRect.Location.X + frameRect.Size.Width - 20, 50); button.Frame = new CGRect(0, 300, frameRect.Location.X + frameRect.Size.Width, 10); } else { this.userPasswordLabel.Frame = new CGRect(10, 240, frameRect.Location.X + frameRect.Size.Width - 20, 50); this.ownerPasswordLabel.Frame = new CGRect(10, 260, frameRect.Location.X + frameRect.Size.Width - 20, 50); button.Frame = new CGRect(0, 305, frameRect.Location.X + frameRect.Size.Width, 10); } } else { this.optionLabel.Hidden = false; this.optionButton.Hidden = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.userPasswordLabel.Frame = new CGRect(10, 325, frameRect.Location.X + frameRect.Size.Width - 20, 30); this.ownerPasswordLabel.Frame = new CGRect(10, 355, frameRect.Location.X + frameRect.Size.Width - 20, 30); button.Frame = new CGRect(0, 390, frameRect.Location.X + frameRect.Size.Width, 10); } else { this.userPasswordLabel.Frame = new CGRect(10, 330, frameRect.Location.X + frameRect.Size.Width - 20, 30); this.ownerPasswordLabel.Frame = new CGRect(10, 360, frameRect.Location.X + frameRect.Size.Width - 20, 30); button.Frame = new CGRect(0, 395, frameRect.Location.X + frameRect.Size.Width, 10); } } this.BecomeFirstResponder(); } void HideOptionPicker(object sender, EventArgs e) { optionDoneButton.Hidden = true; optionPicker.Hidden = true; button.Hidden = false; filterActionLabel.Hidden = false; userPasswordLabel.Hidden = false; filterActionButton.Hidden = false; filterActionButton1.Hidden = true; filterLabel.Hidden = false; filterButton.Hidden = false; optionButton.Hidden = false; optionLabel.Hidden = false; if (this.optionType == "Encrypt only attachments") { this.ownerPasswordLabel.Hidden = true; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 360, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(0, 365, frameRect.Location.X + frameRect.Size.Width, 10); } } else { this.ownerPasswordLabel.Hidden = false; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.ownerPasswordLabel.Frame = new CGRect(10, 355, frameRect.Location.X + frameRect.Size.Width - 20, 30); button.Frame = new CGRect(0, 390, frameRect.Location.X + frameRect.Size.Width, 10); } else { this.ownerPasswordLabel.Frame = new CGRect(10, 360, frameRect.Location.X + frameRect.Size.Width - 20, 30); button.Frame = new CGRect(0, 395, frameRect.Location.X + frameRect.Size.Width, 10); } } this.BecomeFirstResponder(); } } } <file_sep>/Forms/Chart/Chart/Samples/LineChart/LineSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class LineSeriesViewModel { public ObservableCollection<ChartDataModel> LineData1 { get; set; } public ObservableCollection<ChartDataModel> LineData2 { get; set; } public LineSeriesViewModel() { LineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2005", 21), new ChartDataModel("2006", 24), new ChartDataModel("2007", 36), new ChartDataModel("2008", 38), new ChartDataModel("2009", 54), new ChartDataModel("2010", 57), new ChartDataModel("2011", 70) }; LineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2005", 28), new ChartDataModel("2006", 44), new ChartDataModel("2007", 48), new ChartDataModel("2008", 50), new ChartDataModel("2009", 66), new ChartDataModel("2010", 78), new ChartDataModel("2011", 84) }; } } }<file_sep>/Forms/NavigationDrawer/NavigationDrawer/Samples/NavigationDrawer_Main/MenuCollection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.ObjectModel; using System.ComponentModel; using Xamarin.Forms; namespace SampleBrowser.SfNavigationDrawer { public class MenuCollectionModel : INotifyPropertyChanged { public ObservableCollection<Message> MessageContent { get; set; } private string menuItem; public MenuCollectionModel() { } public string MenuItem { get { return menuItem; } set { menuItem = value; } } public string Icon { get; set; } private Color fontColor = Color.FromHex("#8e8e92"); public Color FontColor { get { return fontColor; } set { fontColor = value; OnPropertyChanged("FontColor"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } public class Message { public string Sender { get; set; } public String Subject { get; set; } public String Content { get; set; } public String Date { get; set; } public Color SubjectColor { get; set; } public FontAttributes FontAttribute { get; set; } public String ContactType { get; set; } public String ContactImage { get; set; } } public class MenuCollectionViewModel { string[] MonthArray = new string[] { "Jan", "Jan", "Mar", "Apr", "May", "May", "May", "June", "July", "Sep", "Sep" }; Random random = new Random(); public MenuCollectionModel getItem(string item, string icon) { int randomValue = 0; MenuCollectionModel mCollection = new MenuCollectionModel(); mCollection.MessageContent = new ObservableCollection<Message>(); for (int i = 0; i < 10; i++) { if (item == "Follow up") { if (i % 4 != 0) continue; } if (item == "Sent mail") { if (i % 4 != 0) continue; } if (item == "Trash ") { if (i % 3 == 0) continue; } randomValue = random.Next(0, 9); Message message = new Message(); message.Sender = sender[i]; message.Date = MonthArray[i] + " " + (i + 7).ToString(); if (item != "Inbox") { randomValue = random.Next(0, 29); message.Subject = subject[randomValue]; message.Content = textContent[randomValue]; } else{ randomValue = i; message.Subject = subject[randomValue]; message.Content = textContent[randomValue]; } if(item == "Inbox" && i<7) { message.SubjectColor = Color.FromHex("#006bcd"); message.FontAttribute = FontAttributes.Bold; message.ContactImage ="People_Circle" + (i+1).ToString() + ".png"; message.ContactType = contactType[i]; } else { message.SubjectColor = Color.FromHex("#545659"); message.FontAttribute = FontAttributes.None; } mCollection.MessageContent.Add(message); } mCollection.MenuItem = item; mCollection.Icon = icon; return mCollection; } string[] contactType = new string[] { "Green.jpg", "Gray.jpg", "Yellow.jpg", "Red.jpg", "Orange_Shape.jpg", "Gray.jpg", "Green.jpg", "Green.jpg", }; ObservableCollection<string> sender = new ObservableCollection<string>(); ObservableCollection<string> subject = new ObservableCollection<string>(); ObservableCollection<string> textContent = new ObservableCollection<string>(); ObservableCollection<MenuCollectionModel> menuCollection; public MenuCollectionViewModel() { menuCollection = new ObservableCollection<MenuCollectionModel>(); sender.Add("Adriana"); sender.Add("Daleyza"); sender.Add("Kyle"); sender.Add("Victoriya"); sender.Add("Steve"); sender.Add("Briley"); sender.Add("Maci"); sender.Add("Zariah"); sender.Add("Mckenna"); sender.Add("Miranda"); subject.Add("Goto Meeting"); subject.Add("FW: Status Update"); subject.Add("Greetings! Congrats"); subject.Add("Report Monitor"); subject.Add("News Letter"); subject.Add("Conference about Latest Technology"); subject.Add("RE: Status Update"); subject.Add("Success! Report Automation"); subject.Add("Monthly Reports Documents"); subject.Add("Meeting Confirmation"); subject.Add("Goto Meeting"); subject.Add("FW: Status Update"); subject.Add("Greetings! Congrats"); subject.Add("Report Monitor"); subject.Add("News Letter"); subject.Add("Conference about Latest Technology"); subject.Add("RE: Status Update"); subject.Add("Success! Report Automation"); subject.Add("Monthly Reports Documents"); subject.Add("Meeting Confirmation"); subject.Add("Goto Meeting"); subject.Add("FW: Status Update"); subject.Add("Greetings! Congrats"); subject.Add("Report Monitor"); subject.Add("News Letter"); subject.Add("Conference about Latest Technology"); subject.Add("RE: Status Update"); subject.Add("Success! Report Automation"); subject.Add("Monthly Reports Documents"); subject.Add("Meeting Confirmation"); textContent.Add("Join meeting to discuss about daily status, workflow, pending work and improve process"); textContent.Add("Hi, Please find the today's status"); textContent.Add("Hi, Congrats you have won the raffle"); textContent.Add("Do not reply, Please find the attachment. Attachment have the full details of monitor report with timing"); textContent.Add("Hi, Please find the attached news letter"); textContent.Add("Hi, We are scheduled a meeting"); textContent.Add("Thanks for the status report"); textContent.Add("Do not reply, Automation result will update soon"); textContent.Add("Hi, All documents are reviewed"); textContent.Add("Thanks for scheduling the meeting"); textContent.Add("Join meeting to discuss about daily status, workflow, pending work and improve process"); textContent.Add("Hi, Please find the today's status"); textContent.Add("Hi, Congrats you have won the raffle"); textContent.Add("Do not reply, Please find the attachment. Attachment have the full details of monitor report with timing"); textContent.Add("Hi, Please find the attached news letter"); textContent.Add("Hi,We are scheduled a conference meeting"); textContent.Add("Thanks for the status report"); textContent.Add("Do not reply, Automation result will update soon"); textContent.Add("Hi, All documents are reviewed"); textContent.Add("Thanks for scheduling the meeting"); textContent.Add("Join meeting to discuss about daily status, workflow, pending work and improve process"); textContent.Add("Hi, Please find the today's status"); textContent.Add("Hi, Congrats you have won the raffle"); textContent.Add("Do not reply, Please find the attachment. Attachment have the full details of monitor report with timing"); textContent.Add("Hi, Please find the attached news letter"); textContent.Add("Hi,We are scheduled a conference meeting"); textContent.Add("Thanks for the status report"); textContent.Add("Do not reply, Automation result will update soon"); textContent.Add("Hi, All documents are reviewed"); textContent.Add("Thanks for scheduling the meeting"); if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android) { menuCollection.Add(getItem("Inbox", "I")); menuCollection.Add(getItem("Starred", "R")); menuCollection.Add(getItem("Sent mail", "G")); menuCollection.Add(getItem("Drafts", "D")); menuCollection.Add(getItem("All mail", "A")); menuCollection.Add(getItem("Trash", "T")); menuCollection.Add(getItem("Spam", "S")); menuCollection.Add(getItem("Follow up", "F")); } if (Device.RuntimePlatform == Device.UWP || (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone)) { this.menuCollection.Add(getItem("Inbox", "\xEDB3")); this.menuCollection.Add(getItem("Starred", "\xE208")); this.menuCollection.Add(getItem("Sent mail", "\xE120")); this.menuCollection.Add(getItem("Drafts", "\xE70B")); this.menuCollection.Add(getItem("All mail", "\xE715")); this.menuCollection.Add(getItem("Trash", "\xE107")); this.menuCollection.Add(getItem("Spam", "\xE10A")); this.menuCollection.Add(getItem("Follow up", "\xE290")); } } public ObservableCollection<MenuCollectionModel> MenuCollection { get { return menuCollection; } set { menuCollection = value; } } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/Filtering.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Syncfusion.SfDataGrid; using System.Globalization; using CoreGraphics; using System.Collections.Generic; namespace SampleBrowser { public class Filtering : SampleView { #region Fields SfDataGrid SfGrid; UISearchBar searchbar; OptionsView option; private FilterViewModel viewmodel; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public Filtering() { viewmodel = new FilterViewModel(); this.SfGrid = new SfDataGrid(); this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; this.SfGrid.ItemsSource = viewmodel.BookInfo; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; if (Utility.IsIPad) this.SfGrid.ColumnSizer = ColumnSizer.Star; this.SfGrid.GridStyle.AlternatingRowColor = UIColor.FromRGB(219, 219, 219); searchbar = new UISearchBar(); searchbar.OnEditingStarted += HandleOnEditingStarted; searchbar.TextChanged += HandleTextChanged; searchbar.CancelButtonClicked += HandleCancelButtonClicked; searchbar.SearchButtonClicked += HandleSearchButtonClicked; if (UIDevice.CurrentDevice.CheckSystemVersion(7, 1)) searchbar.EnablesReturnKeyAutomatically = false; searchbar.Placeholder = "Search in All Columns"; viewmodel.filtertextchanged = OnFilterChanged; option = new OptionsView(viewmodel, searchbar, this); this.OptionView = option; this.AddSubview(searchbar); this.AddSubview(SfGrid); } internal void PopUpDissmissed() { this.OptionView.RemoveFromSuperview(); } void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "Last Name"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "BookID") { e.Column.HeaderText = "Book ID"; e.Column.TextAlignment = UITextAlignment.Center; } else if (e.Column.MappingName == "BookName") { e.Column.HeaderText = "Book Name"; e.Column.TextMargin = 15; e.Column.TextAlignment = UITextAlignment.Left; } else if (e.Column.MappingName == "Price") { e.Column.TextAlignment = UITextAlignment.Center; e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo("en-US"); } else if (e.Column.MappingName == "Country") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } } internal void OnFilterChanged() { if (this.SfGrid.View != null) { SfGrid.View.Filter = viewmodel.FilerRecords; SfGrid.View.RefreshFilter(); } } //XAMARINIOS-3537 Keyboard is not getting close when click on rows private void HandleSearchButtonClicked(object sender, EventArgs e) { searchbar.EndEditing(true); } void HandleCancelButtonClicked(object sender, EventArgs e) { searchbar.ResignFirstResponder(); searchbar.SetShowsCancelButton(false, true); searchbar.ResignFirstResponder(); searchbar.EndEditing(true); } void HandleTextChanged(object sender, UISearchBarTextChangedEventArgs e) { viewmodel.FilterText = e.SearchText; } void HandleOnEditingStarted(object sender, EventArgs e) { searchbar.SetShowsCancelButton(true, true); } public override void LayoutSubviews() { searchbar.Frame = (new CGRect(0, 0, this.Frame.Width, 40)); if (UIDevice.CurrentDevice.CheckSystemVersion(7, 1)) { searchbar.SizeToFit(); this.SfGrid.Frame = new CGRect(0, searchbar.Bounds.Height, this.Frame.Width, this.Frame.Height - 40); } else { searchbar.SizeToFit(); this.SfGrid.Frame = new CGRect(0, searchbar.Bounds.Height, this.Frame.Width, this.Frame.Height - 40); } base.LayoutSubviews(); } protected override void Dispose(bool disposing) { if(disposing) { if(searchbar !=null) { searchbar.OnEditingStarted -= HandleOnEditingStarted; searchbar.TextChanged -= HandleTextChanged; searchbar.CancelButtonClicked -= HandleCancelButtonClicked; searchbar.SearchButtonClicked -= HandleSearchButtonClicked; } if(SfGrid !=null) { SfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; SfGrid.Dispose(); } searchbar = null; option = null; viewmodel = null; SfGrid = null; } base.Dispose(disposing); } public override void OnOptionsViewClosed() { base.OnOptionsViewClosed(); option.CommitValues(); } } public partial class OptionsView : UIView { private FilterViewModel filtermodel; private UITableView table; private UISearchBar bar; private UITableView filterconditiontable; List<string> items; Filtering ParentView; static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public OptionsView () { items = new List<string> (); table = new UITableView (); filterconditiontable = new UITableView (); table.SectionIndexTrackingBackgroundColor = UIColor.FromRGB (0, 121, 255); filterconditiontable.AllowsSelection = true; this.AddSubview (filterconditiontable); this.AddSubview (table); } public OptionsView (FilterViewModel model, UISearchBar bar , Filtering parentView) : this () { this.ParentView = parentView; this.filtermodel = model; var columnnames = filtermodel.BookInfo.GetType ().GetGenericArguments () [0].GetProperties (); this.bar = bar; foreach (var propety in columnnames) { items.Add (propety.Name); } table.Source = new OptionsTableSource (items); filterconditiontable.Source = new FilterOptionsTableSource (new List<string> () { "Contains", "Equals", "Not Equals" }); this.AddSubview (filterconditiontable); this.AddSubview (table); } public override void RemoveFromSuperview() { base.RemoveFromSuperview(); CommitValues(); } internal void CommitValues() { filtermodel.SelectedColumn = (table.Source as OptionsTableSource).selectedItem; filtermodel.SelectedCondition = (filterconditiontable.Source as FilterOptionsTableSource).selecteditem; if (filtermodel.SelectedColumn != null && filtermodel.SelectedCondition != null) { this.bar.Placeholder = "Search " + filtermodel.SelectedColumn + " with " + filtermodel.SelectedCondition; if (this.bar.Text != "") this.ParentView.OnFilterChanged(); } else if ((filtermodel.SelectedColumn != null && filtermodel.SelectedCondition == null) || (filtermodel.SelectedColumn == null && filtermodel.SelectedCondition != null)) { #pragma warning disable CS0618 // Type or member is obsolete var alert = new UIAlertView("Error", "Should Select Both ColumnName and Condition Type", null, "Cancel", null); #pragma warning restore CS0618 // Type or member is obsolete alert.Frame = new CGRect(50, this.Frame.GetMidX(), 60, this.Frame.GetMidY()); alert.Show(); } } public override void LayoutSubviews () { table.Frame = (new CGRect (0, 0, this.Frame.Width, (this.Frame.Height / 2)+13)); filterconditiontable.Frame=(new CGRect (0, table.Bounds.Bottom + 2, this.Frame.Width, this.Frame.Height)); base.LayoutSubviews (); } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Styles.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using Android.Graphics; using Android.Views; using System.Globalization; using Android.Widget; using System.Collections.Generic; namespace SampleBrowser { public class Styles:SamplePage { SfDataGrid sfGrid; StylesViewModel viewModel; DataGridStyle defaultStyle; Dark darkStyle; Red redStyle; Green greenStyle; Blue blueStyle; Purple purpleStyle; public override Android.Views.View GetSampleContent (Android.Content.Context context) { sfGrid = new SfDataGrid (context); viewModel = new StylesViewModel (); sfGrid.ItemsSource = (viewModel.OrdersInfo); sfGrid.AutoGeneratingColumn += GridGenerateColumns; sfGrid.SelectionMode = SelectionMode.Single; sfGrid.GridViewCreated += SfGrid_GridViewCreated; sfGrid.QueryRowHeight += SfGrid_QueryRowHeight; sfGrid.VerticalOverScrollMode = VerticalOverScrollMode.None; sfGrid.Alpha = 1.0f; defaultStyle = new DataGridStyle (); darkStyle = new Dark (); blueStyle = new Blue (); redStyle = new Red (); greenStyle = new Green (); purpleStyle = new Purple(); return sfGrid; } public override View GetPropertyWindowLayout (Android.Content.Context context) { LinearLayout linear = new LinearLayout (context); linear.Orientation = Orientation.Horizontal; TextView txt = new TextView (context); txt.Text = "Select Theme"; txt.SetPadding (10, 10, 10, 10); txt.TextSize = 15f; Spinner themeDropDown = new Spinner (context, SpinnerMode.Dialog); List<String> adapter = new List<String> (){"Default","Dark","Blue","Red","Green", "Purple" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, adapter); themeDropDown.Adapter = dataAdapter; themeDropDown.SetPadding (10, 10, 10, 10); themeDropDown.SetSelection(5); themeDropDown.ItemSelected += OnGridThemeChanged; themeDropDown.SetMinimumHeight (70); linear.AddView (txt); linear.AddView (themeDropDown); return linear; } void OnGridThemeChanged (object sender, AdapterView.ItemSelectedEventArgs e) { if (e.Position == 0) sfGrid.GridStyle = defaultStyle; if (e.Position == 1) sfGrid.GridStyle = darkStyle; if (e.Position == 2) sfGrid.GridStyle = blueStyle; if (e.Position == 3) sfGrid.GridStyle = redStyle; if (e.Position == 4) sfGrid.GridStyle = greenStyle; if (e.Position == 5) sfGrid.GridStyle = purpleStyle; } void SfGrid_GridViewCreated (object sender, GridViewCreatedEventArgs e) { this.sfGrid.SelectedItem = viewModel.OrdersInfo[3]; this.sfGrid.GridStyle = purpleStyle; } void SfGrid_QueryRowHeight (object sender, QueryRowHeightEventArgs e) { if (SfDataGridHelpers.IsCaptionSummaryRow (this.sfGrid, e.RowIndex)) { e.Height = 30 * sfGrid.Resources.DisplayMetrics.Density; e.Handled = true; } } void GridGenerateColumns (object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "OrderID") { e.Column.HeaderText = "Order ID"; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.TextAlignment = GravityFlags.CenterVertical; } else if (e.Column.MappingName == "Freight") { e.Column.Format = "C"; e.Column.CultureInfo = new CultureInfo ("en-US"); e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.TextAlignment = GravityFlags.Center; } else if (e.Column.MappingName == "ShipCity") { e.Column.HeaderText = "Ship City"; e.Column.TextAlignment = GravityFlags.CenterVertical; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "ShipCountry") { e.Column.HeaderText = "Ship Country"; e.Column.TextAlignment = GravityFlags.CenterVertical; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = GravityFlags.Center; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "<NAME>"; e.Column.TextAlignment = GravityFlags.CenterVertical; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "<NAME>"; e.Column.TextAlignment = GravityFlags.CenterVertical; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = GravityFlags.CenterVertical; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "ShippingDate") { e.Column.HeaderText = "Shipping Date"; e.Column.Format = "d"; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextAlignment = GravityFlags.CenterVertical; e.Column.HeaderCellTextSize = 12; e.Column.CellTextSize = 13; e.Column.HeaderFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); e.Column.RecordFont = Typeface.Create("Roboto-Regular", TypefaceStyle.Normal); } } public override void Destroy () { sfGrid.AutoGeneratingColumn -= GridGenerateColumns; sfGrid.Dispose (); sfGrid = null; viewModel = null; defaultStyle = null; darkStyle = null; blueStyle = null; redStyle = null; greenStyle = null; purpleStyle = null; } } } <file_sep>/Forms/PDF/PDF/Samples/PDFToPDFAConformance/PDFToPDFAConformance.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Pdf; using System; using System.IO; using Xamarin.Forms; using System.Reflection; using SampleBrowser.Core; using Syncfusion.Pdf.Parsing; using SkiaSharp; using Syncfusion.Pdf.Graphics; namespace SampleBrowser.PDF { public partial class PDFToPDFAConformance : SampleView { public PDFToPDFAConformance() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } private void ButtonView_Click(object sender, EventArgs e) { #if COMMONSB Stream documentStream = typeof(PDFToPDFAConformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.InvoiceTemplate.pdf"); #else Stream documentStream = typeof(PDFToPDFAConformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.InvoiceTemplate.pdf"); #endif MemoryStream stream = new MemoryStream(); documentStream.CopyTo(stream); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("ConformanceTemplate.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("ConformanceTemplate.pdf", "application/pdf", stream); } void OnButtonClicked(object sender, EventArgs e) { #if COMMONSB Stream documentStream = typeof(PDFToPDFAConformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.InvoiceTemplate.pdf"); #else Stream documentStream = typeof(PDFToPDFAConformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.InvoiceTemplate.pdf"); #endif //Load the PDF document from stream. PdfLoadedDocument document = new PdfLoadedDocument(documentStream); //Sample level font event handling document.SubstituteFont += LoadedDocument_SubstituteFont; //convert a document to PDF/A standard document. document.ConvertToPDFA(PdfConformanceLevel.Pdf_A1B); MemoryStream stream = new MemoryStream(); //Saves the PDF to the memory stream. document.Save(stream); //Close the PDF document document.Close(true); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("PDFToPDFAConformance.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("PDFToPDFAConformance.pdf", "application/pdf", stream); } static void LoadedDocument_SubstituteFont(object sender, PdfFontEventArgs args) { //get the font name string fontName = args.FontName.Split(',')[0]; //get the font style PdfFontStyle fontStyle = args.FontStyle; SKFontStyle sKFontStyle = SKFontStyle.Normal; if (fontStyle != PdfFontStyle.Regular) { if (fontStyle == PdfFontStyle.Bold) { sKFontStyle = SKFontStyle.Bold; } else if (fontStyle == PdfFontStyle.Italic) { sKFontStyle = SKFontStyle.Italic; } else if (fontStyle == (PdfFontStyle.Italic | PdfFontStyle.Bold)) { sKFontStyle = SKFontStyle.BoldItalic; } } SKTypeface typeface = SKTypeface.FromFamilyName(fontName, sKFontStyle); SKStreamAsset typeFaceStream = typeface.OpenStream(); MemoryStream memoryStream = null; if (typeFaceStream != null && typeFaceStream.Length > 0) { //Create the fontData from the type face stream. byte[] fontData = new byte[typeFaceStream.Length]; typeFaceStream.Read(fontData, typeFaceStream.Length); typeFaceStream.Dispose(); //Create the new memory stream from the font data. memoryStream = new MemoryStream(fontData); } //set the font stream to the event args. args.FontStream = memoryStream; } } } <file_sep>/Forms/ImageEditor/ImageEditor/Samples/ProfileEditor/ProfileEditPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.IO; using Syncfusion.SfImageEditor.XForms; using Xamarin.Forms; namespace SampleBrowser.SfImageEditor { public partial class ProfileEditPage : ContentPage { ProfileEditorViewModel ViewModel; public ProfileEditPage(ProfileEditorViewModel viewModel) { InitializeComponent(); ViewModel = viewModel; if (viewModel.ByteArray == null) { imageEditor.Source = viewModel.ProfilePicture; } else { imageEditor.Source = ImageSource.FromStream(() => new MemoryStream(ViewModel.ByteArray)); } imageEditor.SetToolbarItemVisibility("Text, Shape, Brightness, Effects, Bradley Hand, Path, 3:1, 3:2, 4:3, 5:4, 16:9, Undo, Redo, Transform", false); imageEditor.ToolbarSettings.ToolbarItems.Add(new FooterToolbarItem() { Text = "Crop" }); imageEditor.ImageLoaded += ImageEditor_ImageLoaded; imageEditor.ImageSaving += ImageEditor_ImageSaving; imageEditor.ToolbarSettings.ToolbarItemSelected += ToolbarSettings_ToolbarItemSelected; } private void ImageEditor_ImageLoaded(object sender, ImageLoadedEventArgs args) { imageEditor.ToggleCropping(true, 3); } private void ToolbarSettings_ToolbarItemSelected(object sender, ToolbarItemSelectedEventArgs e) { if (e.ToolbarItem.Text == "Crop") { imageEditor.ToggleCropping(true, 3); e.Cancel = true; } } private void ImageEditor_ImageSaving(object sender, ImageSavingEventArgs args) { ViewModel.ByteArray = GetImageStreamAsBytes(args.Stream); args.Cancel = true; Navigation.PopAsync(); } private byte[] GetImageStreamAsBytes(Stream input) { var buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } } } <file_sep>/iOS/SampleBrowser/Samples/DocIO/HelloWorld.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class HelloWorld : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton button; public HelloWorld() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to create simple Word document with text, images and tables."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 60); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 60); } this.AddSubview(label); button.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 80, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 80, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Creating a new document. // Creating a new document. WordDocument document = new WordDocument(); //Adding a new section to the document. WSection section = document.AddSection() as WSection; //Set Margin of the section section.PageSetup.Margins.All = 72; //Set page size of the section section.PageSetup.PageSize = new Syncfusion.Drawing.SizeF(612, 792); //Create Paragraph styles WParagraphStyle style = document.AddParagraphStyle("Normal") as WParagraphStyle; style.CharacterFormat.FontName = "Calibri"; style.CharacterFormat.FontSize = 11f; style.ParagraphFormat.BeforeSpacing = 0; style.ParagraphFormat.AfterSpacing = 8; style.ParagraphFormat.LineSpacing = 13.8f; style = document.AddParagraphStyle("Heading 1") as WParagraphStyle; style.ApplyBaseStyle("Normal"); style.CharacterFormat.FontName = "Calibri Light"; style.CharacterFormat.FontSize = 16f; style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(46, 116, 181); style.ParagraphFormat.BeforeSpacing = 12; style.ParagraphFormat.AfterSpacing = 0; style.ParagraphFormat.Keep = true; style.ParagraphFormat.KeepFollow = true; style.ParagraphFormat.OutlineLevel = OutlineLevel.Level1; IWParagraph paragraph = section.HeadersFooters.Header.AddParagraph(); Stream imageStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.AdventureCycle.jpg"); WPicture picture = paragraph.AppendPicture(imageStream) as WPicture; picture.TextWrappingStyle = TextWrappingStyle.InFrontOfText; picture.VerticalOrigin = VerticalOrigin.Margin; picture.VerticalPosition = -24; picture.HorizontalOrigin = HorizontalOrigin.Column; picture.HorizontalPosition = 263.5f; picture.WidthScale = 20; picture.HeightScale = 15; paragraph.ApplyStyle("Normal"); paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; WTextRange textRange = paragraph.AppendText("Adventure Works Cycles") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Calibri"; textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Red; //Appends paragraph. paragraph = section.AddParagraph(); paragraph.ApplyStyle("Heading 1"); paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; textRange = paragraph.AppendText("Adventure Works Cycles") as WTextRange; textRange.CharacterFormat.FontSize = 18f; textRange.CharacterFormat.FontName = "Calibri"; //Appends paragraph. paragraph = section.AddParagraph(); paragraph.ParagraphFormat.FirstLineIndent = 36; paragraph.BreakCharacterFormat.FontSize = 12f; textRange = paragraph.AppendText("Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional sales teams are located throughout their market base.") as WTextRange; textRange.CharacterFormat.FontSize = 12f; paragraph = section.AddParagraph(); paragraph.ParagraphFormat.FirstLineIndent = 36; paragraph.BreakCharacterFormat.FontSize = 12f; textRange = paragraph.AppendText("In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group.") as WTextRange; textRange.CharacterFormat.FontSize = 12f; paragraph = section.AddParagraph(); paragraph.ApplyStyle("Heading 1"); paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left; textRange = paragraph.AppendText("Product Overview") as WTextRange; textRange.CharacterFormat.FontSize = 16f; textRange.CharacterFormat.FontName = "Calibri"; //Appends table. IWTable table = section.AddTable(); table.ResetCells(3, 2); table.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None; table.TableFormat.IsAutoResized = true; //Appends paragraph. paragraph = table[0, 0].AddParagraph(); paragraph.ParagraphFormat.AfterSpacing = 0; paragraph.BreakCharacterFormat.FontSize = 12f; imageStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Mountain-200.jpg"); //Appends picture to the paragraph. picture = paragraph.AppendPicture(imageStream) as WPicture; picture.TextWrappingStyle = TextWrappingStyle.TopAndBottom; picture.VerticalOrigin = VerticalOrigin.Paragraph; picture.VerticalPosition = 0; picture.HorizontalOrigin = HorizontalOrigin.Column; picture.HorizontalPosition = -5.15f; picture.WidthScale = 79; picture.HeightScale = 79; //Appends paragraph. paragraph = table[0, 1].AddParagraph(); paragraph.ApplyStyle("Heading 1"); paragraph.ParagraphFormat.AfterSpacing = 0; paragraph.ParagraphFormat.LineSpacing = 12f; paragraph.AppendText("Mountain-200"); //Appends paragraph. paragraph = table[0, 1].AddParagraph(); paragraph.ParagraphFormat.AfterSpacing = 0; paragraph.ParagraphFormat.LineSpacing = 12f; paragraph.BreakCharacterFormat.FontSize = 12f; paragraph.BreakCharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Product No: BK-M68B-38\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Size: 38\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Weight: 25\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Price: $2,294.99\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; //Appends paragraph. paragraph = table[0, 1].AddParagraph(); paragraph.ParagraphFormat.AfterSpacing = 0; paragraph.ParagraphFormat.LineSpacing = 12f; paragraph.BreakCharacterFormat.FontSize = 12f; //Appends paragraph. paragraph = table[1, 0].AddParagraph(); paragraph.ApplyStyle("Heading 1"); paragraph.ParagraphFormat.AfterSpacing = 0; paragraph.ParagraphFormat.LineSpacing = 12f; paragraph.AppendText("Mountain-300 "); //Appends paragraph. paragraph = table[1, 0].AddParagraph(); paragraph.ParagraphFormat.AfterSpacing = 0; paragraph.ParagraphFormat.LineSpacing = 12f; paragraph.BreakCharacterFormat.FontSize = 12f; paragraph.BreakCharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Product No: BK-M47B-38\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Size: 35\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Weight: 22\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Price: $1,079.99\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; //Appends paragraph. paragraph = table[1, 0].AddParagraph(); paragraph.ParagraphFormat.AfterSpacing = 0; paragraph.ParagraphFormat.LineSpacing = 12f; paragraph.BreakCharacterFormat.FontSize = 12f; //Appends paragraph. paragraph = table[1, 1].AddParagraph(); paragraph.ApplyStyle("Heading 1"); paragraph.ParagraphFormat.LineSpacing = 12f; imageStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Mountain-300.jpg"); //Appends picture to the paragraph. picture = paragraph.AppendPicture(imageStream) as WPicture; picture.TextWrappingStyle = TextWrappingStyle.TopAndBottom; picture.VerticalOrigin = VerticalOrigin.Paragraph; picture.VerticalPosition = 8.2f; picture.HorizontalOrigin = HorizontalOrigin.Column; picture.HorizontalPosition = -14.95f; picture.WidthScale = 75; picture.HeightScale = 75; //Appends paragraph. paragraph = table[2, 0].AddParagraph(); paragraph.ApplyStyle("Heading 1"); paragraph.ParagraphFormat.LineSpacing = 12f; imageStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Road-550-W.jpg"); //Appends picture to the paragraph. picture = paragraph.AppendPicture(imageStream) as WPicture; picture.TextWrappingStyle = TextWrappingStyle.TopAndBottom; picture.VerticalOrigin = VerticalOrigin.Paragraph; picture.VerticalPosition = 0; picture.HorizontalOrigin = HorizontalOrigin.Column; picture.HorizontalPosition = -4.9f; picture.WidthScale = 92; picture.HeightScale = 92; //Appends paragraph. paragraph = table[2, 1].AddParagraph(); paragraph.ApplyStyle("Heading 1"); paragraph.ParagraphFormat.AfterSpacing = 0; paragraph.ParagraphFormat.LineSpacing = 12f; paragraph.AppendText("Road-150 "); //Appends paragraph. paragraph = table[2, 1].AddParagraph(); paragraph.ParagraphFormat.AfterSpacing = 0; paragraph.ParagraphFormat.LineSpacing = 12f; paragraph.BreakCharacterFormat.FontSize = 12f; paragraph.BreakCharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Product No: BK-R93R-44\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Size: 44\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Weight: 14\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; textRange = paragraph.AppendText("Price: $3,578.27\r") as WTextRange; textRange.CharacterFormat.FontSize = 12f; textRange.CharacterFormat.FontName = "Times New Roman"; //Appends paragraph. paragraph = table[2, 1].AddParagraph(); paragraph.ApplyStyle("Heading 1"); paragraph.ParagraphFormat.LineSpacing = 12f; //Appends paragraph. section.AddParagraph(); MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("GettingStarted.docx", "application/msword", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Frame; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/iOS/SampleBrowser/Controllers/OptionViewController.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using UIKit; namespace SampleBrowser { public class OptionViewController : UIViewController { #region ctor public OptionViewController() { } #endregion #region properties public UIView OptionView { get; set; } #endregion public override void ViewDidLoad() { base.ViewDidLoad(); this.Title = "Options"; this.View.BackgroundColor = UIColor.White; OptionView.Frame = new CGRect(0, 0, 320, 400); this.View.AddSubview(OptionView); } } } <file_sep>/Forms/Expander/Expander/Samples/ExpandableListView/Model/Contact.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.Expander; using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfExpander { [Preserve(AllMembers = true)] public class Contact : INotifyPropertyChanged { #region Fields private string contactName; private string callTime; private string contactImage; private bool isExpanded; public AnimationEasing animation; #endregion #region Properties public AnimationEasing Animation { get { return animation; } set { animation = value; this.RaisedOnPropertyChanged("Animation"); } } public bool IsExpanded { get { return isExpanded; } set { isExpanded = value; this.RaisedOnPropertyChanged("IsExpanded"); } } public string ContactName { get { return contactName; } set { if (contactName != value) { contactName = value; this.RaisedOnPropertyChanged("ContactName"); } } } public string CallTime { get { return callTime; } set { if (callTime != value) { callTime = value; this.RaisedOnPropertyChanged("CallTime"); } } } public string ContactImage { get { return this.contactImage; } set { this.contactImage = value; this.RaisedOnPropertyChanged("ContactImage"); } } #endregion #region Constructor public Contact() { } public Contact(string Name) { contactName = Name; } #endregion #region Interface Member public event PropertyChangedEventHandler PropertyChanged; public void RaisedOnPropertyChanged(string _PropertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName)); } } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/BusyIndicator/BusyIndicator_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfBusyIndicator.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class BusyIndicator_Tablet: SampleView { private readonly IList<string> animationTypes = new List<string> (); private string selectedType; UIPickerView animationPicker = new UIPickerView (); UIButton animationTextButton = new UIButton (); UILabel animationTypeLabel = new UILabel (); UIButton doneButton = new UIButton (); UIButton showPropertyButton=new UIButton(); UIButton closeButton=new UIButton(); UIView subView = new UIView (); UIView contentView = new UIView (); UIView mainView=new UIView(); UILabel propertiesLabel = new UILabel (); SFBusyIndicator busyIndicator; public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Frame; mainView.Frame = new CGRect(100, 40, this.Frame.Size.Width - 200, (this.Frame.Size.Height / 2) - 50); subView.Frame = new CGRect(0, this.Frame.Size.Height - this.Frame.Size.Height / 3 + 50, this.Frame.Size.Width, this.Frame.Height / 2); contentView.Frame = new CGRect(0, 40, subView.Frame.Size.Width, subView.Frame.Size.Height - 50); busyIndicator.Frame = new CGRect(0, 120, this.Frame.Size.Width, 200); animationTypeLabel.Frame = new CGRect(110, 60, contentView.Frame.Size.Width - 220, 40); animationTextButton.Frame = new CGRect(110, 100, contentView.Frame.Size.Width - 220, 40); animationPicker.Frame = new CGRect(100, 0, contentView.Frame.Size.Width - 200, 200); doneButton.Frame = new CGRect(100, 0, contentView.Frame.Size.Width - 200, 40); showPropertyButton.Frame = new CGRect(0, this.Frame.Size.Height - 25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect(this.Frame.Size.Width - 30, 5, 20, 30); propertiesLabel.Frame = new CGRect(10, 5, this.Frame.Size.Width, 30); } base.LayoutSubviews(); } public BusyIndicator_Tablet() { //busyIndicator busyIndicator = new SFBusyIndicator(); busyIndicator.Foreground = UIColor.FromRGB (36,63,217); busyIndicator.ViewBoxWidth = 100; busyIndicator.ViewBoxHeight = 100; busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeBall; mainView.AddSubview (busyIndicator); this.AddSubview (mainView); this.loadOptionView(); } public void loadOptionView() { // adding animation types to array this.animationTypes.Add((NSString)"Ball"); this.animationTypes.Add((NSString)"Battery"); this.animationTypes.Add((NSString)"DoubleCircle"); this.animationTypes.Add((NSString)"ECG"); this.animationTypes.Add((NSString)"Globe"); this.animationTypes.Add((NSString)"HorizontalPulsingBox"); this.animationTypes.Add((NSString)"MovieTimer"); this.animationTypes.Add((NSString)"Print"); this.animationTypes.Add((NSString)"Rectangle"); this.animationTypes.Add((NSString)"RollingBall"); this.animationTypes.Add((NSString)"SingleCircle"); this.animationTypes.Add((NSString)"SlicedCircle"); this.animationTypes.Add((NSString)"ZoomingTarget"); this.animationTypes.Add((NSString)"Gear"); this.animationTypes.Add((NSString)"Box"); //animationTypeLabel animationTypeLabel.Text = "Animation Types"; animationTypeLabel.TextColor = UIColor.Black; animationTypeLabel.Font = UIFont.FromName("Helvetica", 14f); contentView.AddSubview(animationTypeLabel); //animationTextButton animationTextButton.SetTitle("Ball", UIControlState.Normal); animationTextButton.Font = UIFont.FromName("Helvetica", 14f); animationTextButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; animationTextButton.BackgroundColor = UIColor.Clear; animationTextButton.SetTitleColor(UIColor.Black, UIControlState.Normal); animationTextButton.Hidden = false; animationTextButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; animationTextButton.Layer.BorderWidth = 4; animationTextButton.Layer.CornerRadius = 8; animationTextButton.TouchUpInside += ShowPicker; contentView.AddSubview(animationTextButton); //pickerModel PickerModel model = new PickerModel(this.animationTypes); model.PickerChanged += (sender, e) => { this.selectedType = e.SelectedValue; animationTextButton.SetTitle(selectedType, UIControlState.Normal); if (selectedType == "Ball") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 120; busyIndicator.ViewBoxHeight = 120; busyIndicator.Foreground = UIColor.FromRGB(36, 63, 217); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeBall; } else if (selectedType == "Battery") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 120; busyIndicator.ViewBoxHeight = 120; busyIndicator.Foreground = UIColor.FromRGB(167, 0, 21); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeBattery; } else if (selectedType == "DoubleCircle") { busyIndicator.Duration = 0.6f; busyIndicator.ViewBoxWidth = 120; busyIndicator.ViewBoxHeight = 120; busyIndicator.Foreground = UIColor.FromRGB(149, 140, 123); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeDoubleCircle; } else if (selectedType == "ECG") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 120; busyIndicator.ViewBoxHeight = 120; busyIndicator.Foreground = UIColor.FromRGB(218, 144, 26); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeECG; } else if (selectedType == "Globe") { busyIndicator.Duration = 0.5f; busyIndicator.ViewBoxWidth = 150; busyIndicator.ViewBoxHeight = 150; busyIndicator.Foreground = UIColor.FromRGB(158, 168, 238); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeGlobe; } else if (selectedType == "HorizontalPulsingBox") { busyIndicator.Duration = 0.2f; busyIndicator.ViewBoxWidth = 150; busyIndicator.ViewBoxHeight = 150; busyIndicator.Foreground = UIColor.FromRGB(228, 46, 6); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeHorizontalPulsingBox; } else if (selectedType == "MovieTimer") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 150; busyIndicator.ViewBoxHeight = 150; busyIndicator.Foreground = UIColor.FromRGB(45, 45, 45); busyIndicator.SecondaryColor = UIColor.FromRGB(155, 155, 155); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeMovieTimer; } else if (selectedType == "Print") { busyIndicator.Duration = 0.5f; busyIndicator.ViewBoxWidth = 120; busyIndicator.ViewBoxHeight = 120; busyIndicator.Foreground = UIColor.FromRGB(94, 111, 248); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypePrint; } else if (selectedType == "Rectangle") { busyIndicator.Duration = 0.1f; busyIndicator.ViewBoxWidth = 150; busyIndicator.ViewBoxHeight = 150; busyIndicator.Foreground = UIColor.FromRGB(39, 170, 158); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeRectangle; } else if (selectedType == "RollingBall") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 120; busyIndicator.ViewBoxHeight = 120; busyIndicator.Foreground = UIColor.FromRGB(45, 45, 45); busyIndicator.SecondaryColor = UIColor.White; busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeRollingBall; } else if (selectedType == "SingleCircle") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 120; busyIndicator.ViewBoxHeight = 120; busyIndicator.Foreground = UIColor.FromRGB(175, 37, 65); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSingleCircle; } else if (selectedType == "SlicedCircle") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 120; busyIndicator.ViewBoxHeight = 120; busyIndicator.Foreground = UIColor.FromRGB(119, 151, 114); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; } else if (selectedType == "ZoomingTarget") { busyIndicator.Duration = 1; busyIndicator.ViewBoxWidth = 120; busyIndicator.ViewBoxHeight = 120; busyIndicator.Foreground = UIColor.FromRGB(237, 143, 60); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeZoomingTarget; } else if (selectedType == "Gear") { busyIndicator.Duration = 1.5f; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.Gray; busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeGear; } else if (selectedType == "Box") { busyIndicator.Duration = 0.1f; busyIndicator.ViewBoxWidth = 70; busyIndicator.ViewBoxHeight = 70; busyIndicator.Foreground = UIColor.FromRGB(36, 63, 217); busyIndicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeBox; } }; //animationPicker animationPicker.ShowSelectionIndicator = true; animationPicker.Hidden = true; animationPicker.Model = model; animationPicker.BackgroundColor = UIColor.Gray; contentView.AddSubview(animationPicker); //doneButton doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.Hidden = true; doneButton.Font = UIFont.FromName("Helvetica", 14f); doneButton.TouchUpInside += HidePicker; contentView.AddSubview(doneButton); contentView.BackgroundColor = UIColor.FromRGB(240, 240, 240); //subView propertiesLabel.Text = "OPTIONS"; subView.AddSubview(closeButton); subView.AddSubview(contentView); subView.AddSubview(propertiesLabel); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); this.AddSubview(subView); //showPropertyButton showPropertyButton.Hidden = true; showPropertyButton.SetTitle("OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = false; showPropertyButton.Hidden = true; }; this.AddSubview(showPropertyButton); //closeButton closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; }; //AddingGesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer(() => { subView.Hidden = true; showPropertyButton.Hidden = false; } ); propertiesLabel.UserInteractionEnabled = true; propertiesLabel.AddGestureRecognizer(tapgesture); // Perform any additional setup after loading the view, typically from a nib. } void ShowPicker (object sender, EventArgs e) { doneButton.Hidden = false; animationPicker.Hidden = false; animationTextButton.Hidden = true; animationTypeLabel.Hidden = true; this.BecomeFirstResponder (); } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; animationPicker.Hidden = true; animationTextButton.Hidden = false; animationTypeLabel.Hidden = false; this.BecomeFirstResponder (); } } }<file_sep>/Android/SampleBrowser/Samples/XlsIO/ExcelToPDFPage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using Syncfusion.XlsIORenderer; using System; using System.IO; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using System.Reflection; using Syncfusion.Pdf; namespace SampleBrowser { public partial class ExcelToPDFPage : SamplePage { private Context m_context; Spinner spinner; CheckBox checkfontName; CheckBox checkfontStream; public override View GetSampleContent (Context con) { int numerHeight = getDimensionPixelSize(con, Resource.Dimension.numeric_txt_ht); int width = con.Resources.DisplayMetrics.WidthPixels - 40; LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample illustrates the conversion of a simple Excel document to PDF."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; LinearLayout subLinearLayout = new LinearLayout(con); subLinearLayout.Orientation = Orientation.Horizontal; TextView pageSetup = new TextView(con); pageSetup.Text = "Page Setup Options : "; pageSetup.TextAlignment = TextAlignment.Center; pageSetup.TextSize = 17; pageSetup.SetTextColor(Color.ParseColor("#262626")); pageSetup.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); subLinearLayout.AddView(pageSetup); string[] list = { "NoScaling", "FitAllRowsOnOnePage", "FitAllColumnsOnOnePage", "FitSheetOnOnePage"}; ArrayAdapter<String> array = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleSpinnerItem, list); spinner = new Spinner(con); spinner.Adapter = array; spinner.SetSelection(0); subLinearLayout.AddView(spinner); linear.AddView(subLinearLayout); TextView space3 = new TextView(con); space3.TextSize = 10; linear.AddView(space3); TextView susbstitute = new TextView(con); susbstitute.Text = "Substitute Fonts : "; susbstitute.TextAlignment = TextAlignment.ViewStart; susbstitute.TextSize = 17; susbstitute.SetTextColor(Color.ParseColor("#262626")); linear.AddView(susbstitute); TextView space5 = new TextView(con); space5.TextSize = 17; linear.AddView(space5); checkfontName = new CheckBox(con); checkfontName.Text = "Font Name"; linear.AddView(checkfontName); TextView susbstituteFontName = new TextView(con); susbstituteFontName.Text = "Missing fonts in the device will be substituted to Calibri."; susbstituteFontName.TextAlignment = TextAlignment.ViewStart; susbstituteFontName.TextSize = 10; susbstituteFontName.SetTextColor(Color.ParseColor("#262626")); linear.AddView(susbstituteFontName); TextView space6 = new TextView(con); space6.TextSize = 17; linear.AddView(space6); checkfontStream = new CheckBox(con); checkfontStream.Text = "Font Stream"; linear.AddView(checkfontStream); TextView susbstituteFontStream = new TextView(con); susbstituteFontStream.Text = "Missing fonts in the device will be substituted from embedded resource."; susbstituteFontStream.TextAlignment = TextAlignment.ViewStart; susbstituteFontStream.TextSize = 10; susbstituteFontStream.SetTextColor(Color.ParseColor("#262626")); linear.AddView(susbstituteFontStream); TextView space4 = new TextView(con); space4.TextSize = 17; linear.AddView(space4); Button templateButton = new Button(con); templateButton.Text = "Input Template"; templateButton.Click += OnButtonClicked; linear.AddView(templateButton); Button convertButton = new Button (con); convertButton.Text = "Convert To PDF"; convertButton.Click += OnConvertButtonClicked; linear.AddView (convertButton); return linear; } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream filestream = null; if (this.checkfontName.Checked || this.checkfontStream.Checked) filestream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.InvoiceTemplate.xlsx"); else filestream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.ExcelToPDF.xlsx"); MemoryStream stream = new MemoryStream(); filestream.CopyTo(stream); SaveAndView(stream, "application/msexcel"); } private void OnConvertButtonClicked(object sender, EventArgs e) { //Instantiate excel engine ExcelEngine excelEngine = new ExcelEngine(); //Excel application IApplication application = excelEngine.Excel; //Get assembly manifest resource Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream; if (this.checkfontName.Checked || this.checkfontStream.Checked) { application.SubstituteFont += new Syncfusion.XlsIO.Implementation.SubstituteFontEventHandler(SubstituteFont); fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.InvoiceTemplate.xlsx"); } else fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.ExcelToPDF.xlsx"); //Open Workbook IWorkbook workbook = application.Workbooks.Open(fileStream); XlsIORenderer renderer = new XlsIORenderer(); XlsIORendererSettings settings = new XlsIORendererSettings(); settings.IsConvertBlankPage = false; int index = spinner.SelectedItemPosition; if (index == 0) settings.LayoutOptions = LayoutOptions.NoScaling; else if (index == 1) settings.LayoutOptions = LayoutOptions.FitAllRowsOnOnePage; else if (index == 2) settings.LayoutOptions = LayoutOptions.FitAllColumnsOnOnePage; else settings.LayoutOptions = LayoutOptions.FitSheetOnOnePage; settings.EnableFormFields = true; PdfDocument pdfDocument = renderer.ConvertToPDF(workbook, settings); MemoryStream memoryStream = new MemoryStream(); pdfDocument.Save(memoryStream); pdfDocument.Close(true); workbook.Close(); excelEngine.Dispose(); //Save and view the generated file. SaveAndView(memoryStream, "application/pdf"); } void SaveAndView(MemoryStream stream, string contentType) { if (stream != null) { stream.Position = 0; SaveAndroid androidSave = new SaveAndroid(); if (contentType == "application/pdf") androidSave.Save("ExcelToPDF.pdf", contentType, stream, m_context); else androidSave.Save("Input Template.xlsx", contentType, stream, m_context); } } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } private void SubstituteFont(object sender, Syncfusion.XlsIO.Implementation.SubstituteFontEventArgs args) { Assembly assembly = Assembly.GetExecutingAssembly(); if (checkfontName.Checked && (args.OriginalFontName == "Bahnschrift Pro SemiBold" || args.OriginalFontName == "Georgia Pro Semibold")) { args.AlternateFontName = "Calibri"; } if (checkfontStream.Checked) { if (args.OriginalFontName == "Georgia Pro Semibold") { Stream file = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.georgiab.ttf"); MemoryStream memoryStream = new MemoryStream(); file.CopyTo(memoryStream); file.Close(); args.AlternateFontStream = memoryStream; } else if (args.OriginalFontName == "Bahnschrift Pro SemiBold") { Stream file = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.bahnschrift.ttf"); MemoryStream memoryStream = new MemoryStream(); file.CopyTo(memoryStream); file.Close(); args.AlternateFontStream = memoryStream; } } } } } <file_sep>/Android/SampleBrowser/Samples/RadialMenu/RadialMenuCustomization.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Syncfusion.SfRadialMenu.Android; namespace SampleBrowser { public class RadialMenuCustomization : SamplePage { LinearLayout mainLayout; double width, height; int buttonCount; float density; DoodleDraw dd; SfRadialMenu radialMenu; public override View GetSampleContent(Context context) { mainLayout = new LinearLayout(context); mainLayout.Orientation = Orientation.Vertical; mainLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); LinearLayout colorPalatte1 = new LinearLayout(context); height = context.Resources.DisplayMetrics.HeightPixels; width = context.Resources.DisplayMetrics.WidthPixels; density = context.Resources.DisplayMetrics.Density; dd = new DoodleDraw(context); TextView pickColor = new TextView(context); pickColor.Text = "Pick Color"; pickColor.TextSize = 20; pickColor.Left = (int)(5 * density); pickColor.SetTextColor(Color.Black); //mainLayout.AddView(pickColor); buttonCount = (int)(width / (35 * density)); for (int i = 0; i < buttonCount; i++) { RoundButton btn = new RoundButton(context, (30 * density), (30 * density), GetRandomColor(), dd); btn.LayoutParameters = new ViewGroup.LayoutParams((int)(30 * density), (int)(30 * density)); colorPalatte1.AddView(new TextView(context), new ViewGroup.LayoutParams((int)(5 * density), ViewGroup.LayoutParams.MatchParent)); colorPalatte1.AddView(btn); } colorPalatte1.SetBackgroundColor(Color.LightGray); colorPalatte1.SetPadding((int)(10 * density), (int)(10 * density), (int)(10 * density), (int)(10 * density)); colorPalatte1.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); mainLayout.AddView(colorPalatte1); dd.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); FrameLayout frame = new FrameLayout(context); frame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(0.80 * height)); frame.AddView(dd); mainLayout.AddView(frame); Typeface typeface = Typeface.CreateFromAsset(context.Assets, "Android.ttf"); Button touchDraw = new Button(context); touchDraw.Text = "Touch to draw"; touchDraw.SetTextColor(Color.Blue); touchDraw.SetBackgroundColor(Color.Transparent); touchDraw.TextSize = TypedValue.ApplyDimension(ComplexUnitType.Pt, 3, context.Resources.DisplayMetrics); frame.AddView(touchDraw, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.Center)); radialMenu = new SfRadialMenu(context); radialMenu.RimColor = Color.Transparent; FrameLayout penLayout = new FrameLayout(context); penLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView penImage = new ImageView(context); penImage.LayoutParameters = penLayout.LayoutParameters; penImage.SetImageResource(Resource.Drawable.green); penImage.SetScaleType(ImageView.ScaleType.FitXy); TextView penText = new TextView(context); penText.LayoutParameters = penLayout.LayoutParameters; penText.Text = "L"; penText.Typeface = typeface; penText.TextSize = 20; penText.TextAlignment = TextAlignment.Center; penText.Gravity = GravityFlags.Center; penText.SetTextColor(Color.White); penLayout.AddView(penImage); penLayout.AddView(penText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem pen = new SfRadialMenuItem(context) { View = penLayout, ItemWidth = 70, ItemHeight = 70 }; pen.ItemTapped += Pen_ItemTapped; radialMenu.Items.Add(pen); FrameLayout brushLayout = new FrameLayout(context); brushLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView brushImage = new ImageView(context); brushImage.LayoutParameters = brushLayout.LayoutParameters; brushImage.SetImageResource(Resource.Drawable.green); brushImage.SetScaleType(ImageView.ScaleType.FitXy); TextView brushText = new TextView(context); brushText.LayoutParameters = brushLayout.LayoutParameters; brushText.Text = "A"; brushText.Typeface = typeface; brushText.TextSize = 20; brushText.TextAlignment = TextAlignment.Center; brushText.Gravity = GravityFlags.Center; brushText.SetTextColor(Color.White); brushLayout.AddView(brushImage); brushLayout.AddView(brushText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem brush = new SfRadialMenuItem(context) { View = brushLayout, ItemWidth = 70, ItemHeight = 70 }; brush.SetBackgroundColor(Color.Transparent); brush.ItemTapped += Brush_ItemTapped; ; radialMenu.Items.Add(brush); FrameLayout eraserLayout = new FrameLayout(context); eraserLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView eraserImage = new ImageView(context); eraserImage.LayoutParameters = eraserLayout.LayoutParameters; eraserImage.SetImageResource(Resource.Drawable.green); eraserImage.SetScaleType(ImageView.ScaleType.FitXy); TextView eraserText = new TextView(context); eraserText.LayoutParameters = eraserLayout.LayoutParameters; eraserText.Text = "R"; eraserText.Typeface = typeface; eraserText.TextSize = 20; eraserText.TextAlignment = TextAlignment.Center; eraserText.Gravity = GravityFlags.Center; eraserText.SetTextColor(Color.White); eraserLayout.AddView(eraserImage); eraserLayout.AddView(eraserText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem eraser = new SfRadialMenuItem(context) { View = eraserLayout, ItemWidth = 70, ItemHeight = 70 }; eraser.ItemTapped += Eraser_ItemTapped; eraser.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(eraser); FrameLayout clearLayout = new FrameLayout(context); clearLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView clearImage = new ImageView(context); clearImage.LayoutParameters = clearLayout.LayoutParameters; clearImage.SetImageResource(Resource.Drawable.green); clearImage.SetScaleType(ImageView.ScaleType.FitXy); TextView clearText = new TextView(context); clearText.LayoutParameters = clearLayout.LayoutParameters; clearText.Text = "Q"; clearText.Typeface = typeface; clearText.TextSize = 20; clearText.TextAlignment = TextAlignment.Center; clearText.Gravity = GravityFlags.Center; clearText.SetTextColor(Color.White); clearLayout.AddView(clearImage); clearLayout.AddView(clearText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem clear = new SfRadialMenuItem(context) { View = clearLayout, ItemWidth = 70, ItemHeight = 70 }; clear.ItemTapped += Clear_ItemTapped; clear.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(clear); FrameLayout thickLayout = new FrameLayout(context); thickLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView thickImage = new ImageView(context); thickImage.LayoutParameters = thickLayout.LayoutParameters; thickImage.SetImageResource(Resource.Drawable.green); thickImage.SetScaleType(ImageView.ScaleType.FitXy); TextView thickText = new TextView(context); thickText.LayoutParameters = thickLayout.LayoutParameters; thickText.Text = "G"; thickText.Typeface = typeface; thickText.TextSize = 20; brushText.TextAlignment = TextAlignment.Center; thickText.Gravity = GravityFlags.Center; thickText.SetTextColor(Color.White); thickLayout.AddView(thickImage); thickLayout.AddView(thickText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem thickBrush = new SfRadialMenuItem(context) { View = thickLayout, ItemWidth = 70, ItemHeight = 70 }; thickBrush.ItemTapped += ThickBrush_ItemTapped; thickBrush.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(thickBrush); FrameLayout paintBoxLayout = new FrameLayout(context); paintBoxLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView paintBoxImage = new ImageView(context); paintBoxImage.LayoutParameters = paintBoxLayout.LayoutParameters; paintBoxImage.SetImageResource(Resource.Drawable.green); paintBoxImage.SetScaleType(ImageView.ScaleType.FitXy); TextView paintBoxText = new TextView(context); paintBoxText.LayoutParameters = paintBoxLayout.LayoutParameters; paintBoxText.Text = "V"; paintBoxText.Typeface = typeface; paintBoxText.TextSize = 20; paintBoxText.TextAlignment = TextAlignment.Center; paintBoxText.Gravity = GravityFlags.Center; paintBoxText.SetTextColor(Color.White); paintBoxLayout.AddView(paintBoxImage); paintBoxLayout.AddView(paintBoxText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem paintBox = new SfRadialMenuItem(context) { View = paintBoxLayout, ItemWidth = 70, ItemHeight = 70 }; paintBox.ItemTapped += PaintBox_ItemTapped; paintBox.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(paintBox); FrameLayout menuLayout = new FrameLayout(context); menuLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView menuImage = new ImageView(context); menuImage.LayoutParameters = menuLayout.LayoutParameters; menuImage.SetImageResource(Resource.Drawable.blue); menuImage.SetScaleType(ImageView.ScaleType.FitXy); TextView menuText = new TextView(context); menuText.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); menuText.Text = "U"; menuText.Typeface = typeface; menuText.TextSize = 40; menuText.TextAlignment = TextAlignment.Center; menuText.Gravity = GravityFlags.Center; menuText.SetTextColor(Color.White); menuLayout.AddView(menuImage); menuLayout.AddView(menuText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); radialMenu.CenterButtonView = menuLayout; radialMenu.IsDragEnabled = false; radialMenu.OuterRimColor = Color.Transparent; radialMenu.CenterButtonRadius = 30; radialMenu.RimRadius = 100; radialMenu.SelectionColor = Color.Transparent; radialMenu.CenterButtonBackground = Color.Transparent; frame.AddView(radialMenu, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.Center)); radialMenu.Point = new Point(0,(int)(context.Resources.DisplayMetrics.HeightPixels / context.Resources.DisplayMetrics.Density / 3.5)); touchDraw.Click += (sender, e) => { touchDraw.Visibility = ViewStates.Gone; }; return mainLayout; } private int getNavigationBarHeight(Android.Content.Context con) { int navBarHeight = 0; int resourceId = con.Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navBarHeight = con.Resources.GetDimensionPixelSize(resourceId); } return navBarHeight; } View GetIconView(Context con, Typeface typeface, string v1, int v2) { FrameLayout frame = new FrameLayout(con); ImageView backImage = new ImageView(con); backImage.SetScaleType(ImageView.ScaleType.FitXy); frame.LayoutParameters = new FrameLayout.LayoutParams(v2, v2); backImage.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); frame.AddView(backImage); TextView menuIcon = new TextView(con); menuIcon.Text = v1; menuIcon.TextSize = 10 * density; menuIcon.Typeface = typeface; frame.AddView(menuIcon); return frame; } static Random rand = new Random(); public static Color GetRandomColor() { Color color = Color.Rgb(rand.Next(255), rand.Next(255), rand.Next(255)); return color; } public void OnClick(View v) { if (v != null) { dd.drawColor = (v as RoundButton).fillColor; dd.Invalidate(); } } void Pen_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { dd.strokeWidth = 2; dd.isPaintTapped = false; radialMenu.Close(); //dd.Invalidate(); } void Brush_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { dd.style = Paint.Style.Stroke; dd.strokeWidth = 12; dd.isPaintTapped = false; radialMenu.Close(); //dd.Invalidate(); } void ThickBrush_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { dd.style = Paint.Style.Stroke; dd.strokeWidth = 80; dd.isPaintTapped = false; radialMenu.Close(); } void Eraser_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { dd.style = Paint.Style.Stroke; dd.strokeWidth = 30; dd.drawColor = Color.White; dd.isPaintTapped = false; radialMenu.Close(); } void PaintBox_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { dd.isPaintTapped = true; radialMenu.Close(); } void Clear_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { dd.isPaintTapped = false; dd.mCanvas.DrawColor(Color.White, PorterDuff.Mode.Clear); dd.mPath.Reset(); dd.Invalidate(); radialMenu.Close(); } } } <file_sep>/Android/SampleBrowser/Samples/TreeView/ViewModel/MailFolderViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using System.ComponentModel; namespace SampleBrowser { public class MailFolderViewModel { public ObservableCollection<MailFolder> Folders { get; set; } public MailFolderViewModel() { GenerateItems(); } private void GenerateItems() { var fav = new MailFolder() { FolderName = "Favorites" }; var myFolder = new MailFolder() { FolderName = "My Folder" }; var inbox = new MailFolder() { FolderName = "Inbox", MailsCount = 20 }; var drafts = new MailFolder() { FolderName = "Drafts", MailsCount = 5 }; var deleted = new MailFolder() { FolderName = "Deleted Items" }; var sent = new MailFolder() { FolderName = "Sent Items" }; var sales = new MailFolder() { FolderName = "Sales Report", MailsCount = 4 }; var marketing = new MailFolder() { FolderName = "Marketing Reports", MailsCount = 6 }; var outbox = new MailFolder() { FolderName = "Outbox" }; var calender = new MailFolder() { FolderName = "Calender" }; var birthday = new MailFolder() { FolderName = "Birthdays" }; var holiday = new MailFolder() { FolderName = "Holidays" }; var groups = new MailFolder() { FolderName = "Groups" }; var developmentTeam = new MailFolder() { FolderName = "Development Team", MailsCount = 11 }; var salesTeam = new MailFolder() { FolderName = "Sales Team", MailsCount = 5 }; var testingTeam = new MailFolder() { FolderName = "Testing Team", MailsCount = 33 }; fav.SubFolder = new ObservableCollection<MailFolder> { new MailFolder() { FolderName = "Sales Report", MailsCount = 4 }, new MailFolder() { FolderName = "Sent Items" }, new MailFolder() { FolderName = "Marketing Reports", MailsCount = 6 } }; myFolder.SubFolder = new ObservableCollection<MailFolder> { inbox, drafts, deleted, sent, sales, marketing, outbox }; calender.SubFolder = new ObservableCollection<MailFolder> { birthday, holiday }; groups.SubFolder = new ObservableCollection<MailFolder> { developmentTeam, salesTeam, testingTeam }; this.Folders = new ObservableCollection<MailFolder>(); Folders.Add(fav); Folders.Add(myFolder); Folders.Add(calender); Folders.Add(groups); } } }<file_sep>/Android/SampleBrowser/Common/Activity/SampleViewActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.App; using Android.Graphics; using Android.Views; using Android.Widget; using AndroidX.RecyclerView.Widget; namespace SampleBrowser { public class SampleViewActivity { #region fields private Activity activity; private FrameLayout sampleView; private List<SampleModel> samples; private SampleModel selectedSample; private RecyclerViewAdapter adapter; #endregion #region ctor public SampleViewActivity(List<SampleModel> sampleCollection, FrameLayout mainView, Activity act, int index) { activity = act; samples = sampleCollection; if (samples.Count > 0) { selectedSample = samples[index]; } View view = LayoutInflater.From(mainView.Context).Inflate(Resource.Layout.SamplePageLayout, null); mainView.AddView(view); OnViewCreated(view); } #endregion #region properties internal TextView BaseTextView { get; set; } #endregion #region methods public void OnViewCreated(View view) { sampleView = (FrameLayout)view.FindViewById(Resource.Id.SampleView); var layoutManager = new LinearLayoutManager(activity, LinearLayoutManager.Horizontal, false); var recyclerView = view.FindViewById<RecyclerView>(Resource.Id.horizontal_RecyclerView); recyclerView.SetBackgroundResource(Resource.Layout.listviewborder); recyclerView.SetLayoutManager(layoutManager); if (samples.Count == 1) { recyclerView.Visibility = ViewStates.Gone; } else { adapter = new RecyclerViewAdapter(samples); adapter.ItemClick += Adapter_ItemClick; recyclerView.SetAdapter(adapter); } Refresh(selectedSample); } private void Adapter_ItemClick(object sender, ListViewSelectionChangedEventArgs e) { TextView selectedItem = e.SelectedItem, prevSelectedItem = e.PreviousSelectedItem; if (selectedItem.Text != prevSelectedItem?.Text) { selectedSample = samples[e.SelectedIndex]; Refresh(selectedSample); selectedItem.SetTextColor(Color.ParseColor("#0277F5")); prevSelectedItem?.SetTextColor(Color.Black); } } private void Refresh(SampleModel selectedSample) { SamplePage samplePage; if (BaseTextView != null) { BaseTextView.Text = selectedSample.Title; } bool isClassExists = Type.GetType("SampleBrowser." + selectedSample.Name) != null; if (isClassExists) { var handle = Activator.CreateInstance(null, "SampleBrowser." + selectedSample.Name); samplePage = (SamplePage)handle.Unwrap(); sampleView.RemoveAllViews(); sampleView.AddView(samplePage.GetSampleContent(activity)); var allControlsSamplePage = activity as AllControlsSamplePage; if (allControlsSamplePage != null) { if (allControlsSamplePage.CurrentSamplePage != null) { allControlsSamplePage.CurrentSamplePage.Destroy(); } allControlsSamplePage.CurrentSamplePage = samplePage; allControlsSamplePage.SettingsButton.Visibility = samplePage.GetPropertyWindowLayout(activity) != null ? ViewStates.Visible : ViewStates.Invisible; } } } #endregion } }<file_sep>/Forms/GradientView/GradientView/Samples/GradientGettingStarted/GettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "GettingStartedViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfGradientView { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; using Syncfusion.XForms.Buttons; using Syncfusion.XForms.Graphics; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] public class GettingStartedViewModel : INotifyPropertyChanged { /// <summary> /// Gets or sets the background brush for gradient view. /// </summary> private SfGradientBrush backgroundGradient; /// <summary> /// Gets or sets the background brush for gradient view. /// </summary> public SfGradientBrush BackgroundGradient { get { return backgroundGradient; } set { backgroundGradient = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("BackgroundGradient")); } } } /// <summary> /// Gets or sets the string to toggle between linear and radial gradient. /// </summary> public ObservableCollection<string> ToggleItems { get; set; } /// <summary> /// Gets or sets the linear gradient brushes. /// </summary> public ObservableCollection<SfLinearGradientBrush> LinearGradientBrushes { get; set; } /// <summary> /// Gets or sets the radial gradient brushes. /// </summary> public ObservableCollection<SfRadialGradientBrush> RadialGradientBrushes { get; set; } public GettingStartedViewModel() { LinearGradientBrushes = new ObservableCollection<SfLinearGradientBrush>(); LinearGradientBrushes.Add(AddLinearGradient("#2DDD78", "#FFAB2B", 0, 1)); LinearGradientBrushes.Add(AddLinearGradient("#08D1B6", "#E419FC", 0, 1)); LinearGradientBrushes.Add(AddLinearGradient("#DD582D", "#FFAB2B", 0, 1)); LinearGradientBrushes.Add(AddLinearGradient("#FC72CF", "#1B73FF", 0, 1)); LinearGradientBrushes.Add(AddLinearGradient("#401AE8", "#CF21B4", 0, 1)); LinearGradientBrushes.Add(AddLinearGradient("#2131C6", "#00D8B3", 0, 1)); RadialGradientBrushes = new ObservableCollection<SfRadialGradientBrush>(); RadialGradientBrushes.Add(AddRadialGradient("#2DDD78", "#FFAB2B", 0, 1)); RadialGradientBrushes.Add(AddRadialGradient("#08D1B6", "#E419FC", 0, 1)); RadialGradientBrushes.Add(AddRadialGradient("#DD582D", "#FFAB2B", 0, 1)); RadialGradientBrushes.Add(AddRadialGradient("#FC72CF", "#1B73FF", 0, 1)); RadialGradientBrushes.Add(AddRadialGradient("#401AE8", "#CF21B4", 0, 1)); RadialGradientBrushes.Add(AddRadialGradient("#2131C6", "#00D8B3", 0, 1)); BackgroundGradient = LinearGradientBrushes[0]; ToggleItems = new ObservableCollection<string>(); ToggleItems.Add("LINEAR"); ToggleItems.Add("RADIAL"); } public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Add the radial gradient brushes. /// </summary> /// <param name="color1">color1</param> /// <param name="color2">color2</param> /// <param name="offset1">offset1</param> /// <param name="offset2">offset2</param> /// <returns>radial gradient</returns> private SfRadialGradientBrush AddRadialGradient(string color1, string color2, double offset1, double offset2) { SfRadialGradientBrush gradient1 = new SfRadialGradientBrush(); gradient1.Center = new Point(0.5, 0.5); gradient1.Radius = 0.7; gradient1.GradientStops.Add(new SfGradientStop() { Color = Color.FromHex(color1), Offset = offset1 }); gradient1.GradientStops.Add(new SfGradientStop() { Color = Color.FromHex(color2), Offset = offset2 }); return gradient1; } /// <summary> /// Add the linear gradient brushes. /// </summary> /// <param name="color1">color1</param> /// <param name="color2">color2</param> /// <param name="offset1">offset1</param> /// <param name="offset2">offset2</param> /// <returns>linear gradient</returns> private SfLinearGradientBrush AddLinearGradient(string color1, string color2, int offset1, int offset2) { SfLinearGradientBrush gradient1 = new SfLinearGradientBrush(); gradient1.StartPoint = new Point(0.5, 0); gradient1.EndPoint = new Point(0.5, 1); gradient1.GradientStops.Add(new SfGradientStop() { Color = Color.FromHex(color1), Offset = offset1 }); gradient1.GradientStops.Add(new SfGradientStop() { Color = Color.FromHex(color2), Offset = offset2 }); return gradient1; } } } <file_sep>/Forms/AvatarView/AvatarView/Samples/GettingStartedSample/AvatarGettingStartedSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.ObjectModel; using Xamarin.Forms; using Syncfusion.Core.XForms; using Avatar = Syncfusion.XForms.AvatarView; using Syncfusion.XForms.AvatarView; using Syncfusion.XForms.Graphics; namespace SampleBrowser.SfAvatarView { #region Getting Started Sample Class public partial class AvatarGettingStartedSample : SampleView { private bool useDefinedAvatar = false; public bool UseDefinedAvatar { get { return useDefinedAvatar; } set { useDefinedAvatar = value; if (value) { UseCustomAvatar = false; UseInitialAvatar = true; ContentType = ContentType.AvatarCharacter; } else if (!UseCustomAvatar) { ContentType = ContentType.Initials; UseInitialAvatar = true; } this.OnPropertyChanged(); } } private SfGradientBrush gradientBrush; public SfGradientBrush GradientBrush { get { return gradientBrush; } set { gradientBrush = value; this.OnPropertyChanged(); } } private bool useCustomAvatar = false; public bool UseCustomAvatar { get { return useCustomAvatar; } set { useCustomAvatar = value; if (value) { UseDefinedAvatar = false; UseInitialAvatar = false; ContentType = ContentType.Custom; } else if (!UseDefinedAvatar) { ContentType = ContentType.Initials; UseInitialAvatar = true; } this.OnPropertyChanged(); } } private ContentType contentType; public ContentType ContentType { get { return contentType; } set { contentType = value; this.OnPropertyChanged(); } } private AvatarCharacter definedAvatarItem; public AvatarCharacter DefinedAvatarItem { get { return definedAvatarItem; } set { definedAvatarItem = value; this.OnPropertyChanged(); } } private bool editionIsVisible = true; public bool EditionIsVisible { get { return editionIsVisible; } set { editionIsVisible = value; this.OnPropertyChanged(); } } private bool useInitialAvatar = true; public bool UseInitialAvatar { get { return useInitialAvatar; } set { useInitialAvatar = value; if (value) ColorPickerOpacity = 1; else ColorPickerOpacity = 0.3; this.OnPropertyChanged(); } } private bool useGradients; public bool UseGradients { get { return useGradients; } set { useGradients = value; SetGradients(); SetColorToAvatar(); this.OnPropertyChanged(); } } private String firstName = "Ellana"; public String FirstName { get { return firstName; } set { firstName = value; UserName = FirstName + " " + LastName; this.OnPropertyChanged(); } } private String lastName; public String LastName { get { return lastName; } set { lastName = value; UserName = FirstName + " " + LastName; this.OnPropertyChanged(); } } private String userName; public String UserName { get { return userName; } set { userName = value; TitleText = value; this.OnPropertyChanged(); } } private String titleText; public String TitleText { get { if (UserName == String.Empty || UserName == " ") return String.Empty; return "Hi " + titleText; } set { titleText = value; this.OnPropertyChanged(); } } private Color profileColor; public Color ProfileColor { get { return profileColor; } set { profileColor = value; this.OnPropertyChanged(); } } private Color textColor; public Color TextColor { get { return textColor; } set { textColor = value; this.OnPropertyChanged(); } } private double colorPickerOpacity = 1; public double ColorPickerOpacity { get { return colorPickerOpacity; } set { colorPickerOpacity = value; this.OnPropertyChanged(); } } private ObservableCollection<ColorBackgroundAvatar> colorItemCollection = new ObservableCollection<ColorBackgroundAvatar>(); public ObservableCollection<ColorBackgroundAvatar> ColorItemCollection { get { return colorItemCollection; } set { colorItemCollection = value; this.OnPropertyChanged(); } } private ObservableCollection<Avatar.SfAvatarView> definedAvatarCollection = new ObservableCollection<Avatar.SfAvatarView>(); public ObservableCollection<Avatar.SfAvatarView> DefinedAvatarCollection { get { return definedAvatarCollection; } set { definedAvatarCollection = value; this.OnPropertyChanged(); } } public AvatarGettingStartedSample() { InitializeComponent(); this.cmdButton.Clicked += CmdButton_Clicked; this.StatusIndicatorSwitch.Toggled += StatusIndicatorSwitch_Toggled; this.BindingContext = this; PopulateCollection(); tappedAvatar = ColorItemCollection[0]; DefinedAvatarCollection[0].BorderWidth = 1; DefinedAvatarCollection[0].BorderColor = Color.FromHex("#9E9E9E"); UseGradients = true; if(Device.Idiom == TargetIdiom.Tablet ) { gradientcollection.Margin = 70; definedcollection.Margin = 70; } } private void StatusIndicatorSwitch_Toggled(object sender, ToggledEventArgs e) { if (this.StatusIndicatorSwitch.IsToggled) { this.StatusBadge.BadgeSettings.BadgeIcon = Syncfusion.XForms.BadgeView.BadgeIcon.Available; } else { this.StatusBadge.BadgeSettings.BadgeIcon = Syncfusion.XForms.BadgeView.BadgeIcon.None; } } private void PopulateCollection() { for(int i = 1; i<=10;i++) { DefinedAvatarCollection.Add(GetDefinedAvatarItem("Avatar" + i)); } PopulateColorCollection(); } private void PopulateColorCollection() { ColorItemCollection.Clear(); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#976F0C"),Color.FromHex("#58B7C6"), Color.FromHex("#7FB3E8"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#740A1C"),Color.FromHex("#95479B"), Color.FromHex("#FF8F8F"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#5C2E91"),Color.FromHex("#3C7F91"), Color.FromHex("#71B280"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#004E8C"),Color.FromHex("#525CE5"), Color.FromHex("#9437C3"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#B73EAA"),Color.FromHex("#80C6CF"), Color.FromHex("#87DFAC"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#90DDFE"),Color.FromHex("#E7A8FA"), Color.FromHex("#F3DED6"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#9FCC69"),Color.FromHex("#FFDBC7"), Color.FromHex("#FC9F9F"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#FCCE65"),Color.FromHex("#A6F0FF"), Color.FromHex("#BCC1FF"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#FE9B90"),Color.FromHex("#BCC2F4"), Color.FromHex("#E8BEF7"))); ColorItemCollection.Add(GetColorPickerItem(Color.FromHex("#9AA8F5"),Color.FromHex("#96E6A1"), Color.FromHex("#DCFA97"))); } private Avatar.SfAvatarView GetDefinedAvatarItem(String avatar) { Avatar.SfAvatarView defaultAvatar = new Avatar.SfAvatarView(); defaultAvatar.AvatarShape = AvatarShape.Circle; defaultAvatar.AvatarSize = AvatarSize.Medium; defaultAvatar.VerticalOptions = LayoutOptions.Center; defaultAvatar.HorizontalOptions = LayoutOptions.Center; defaultAvatar.BorderWidth = 5; defaultAvatar.BorderColor = Color.White; defaultAvatar.ContentType = ContentType.AvatarCharacter; defaultAvatar.AvatarCharacter = (AvatarCharacter)Enum.Parse(typeof(AvatarCharacter), avatar, true); TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += TapGestureRecognizer_Tapped; defaultAvatar.GestureRecognizers.Add(tapGestureRecognizer); return defaultAvatar; } private ColorBackgroundAvatar GetColorPickerItem(Color backgroundColor, Color startcolor, Color stopcolor) { ColorBackgroundAvatar colorAvatar = new ColorBackgroundAvatar(); colorAvatar.BackgroundColor = backgroundColor; colorAvatar.BorderColor = Color.FromHex("#9E9E9E"); colorAvatar.InitialsColor = Color.Transparent; colorAvatar.AvatarShape = AvatarShape.Circle; colorAvatar.AvatarSize = AvatarSize.Medium; colorAvatar.VerticalOptions = LayoutOptions.Center; colorAvatar.HorizontalOptions = LayoutOptions.Center; TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += ColorTapGestureRecognizer_Tapped; colorAvatar.GestureRecognizers.Add(tapGestureRecognizer); colorAvatar.StartColor = startcolor; colorAvatar.StopColor = stopcolor; return colorAvatar; } private void SetGradients() { foreach (var item in ColorItemCollection) { if (this.UseGradients) if (ColorItemCollection.IndexOf(item) < 5) item.BackgroundGradient = GetGradients(item.StartColor,item.StopColor); else item.BackgroundGradient = GetGradients(item.StartColor, item.StopColor); else item.BackgroundGradient = null; } } private SfLinearGradientBrush GetGradients(Color startColor, Color endColor) { SfLinearGradientBrush linearGradientBrush = new SfLinearGradientBrush(); linearGradientBrush.GradientStops = new Syncfusion.XForms.Graphics.GradientStopCollection() { new SfGradientStop(){Color = startColor, Offset=0.0}, new SfGradientStop(){Color = endColor, Offset=1.0}, }; return linearGradientBrush; } Avatar.SfAvatarView tappedAvatarView; ColorBackgroundAvatar tappedAvatar; private void TapGestureRecognizer_Tapped(object sender, EventArgs e) { tappedAvatarView = (sender as Avatar.SfAvatarView); if (tappedAvatarView.ContentType == ContentType.AvatarCharacter) { SetDefaultAvatar(); } else { SetColorToAvatar(); } } private void ColorTapGestureRecognizer_Tapped(object sender, EventArgs e) { tappedAvatar = (sender as ColorBackgroundAvatar); if (tappedAvatar.ContentType == ContentType.AvatarCharacter) { SetDefaultAvatar(); } else { SetColorToAvatar(); } } private void SetDefaultAvatar() { foreach (var item in DefinedAvatarCollection) { item.BorderWidth = 5; item.BorderColor = Color.White; } tappedAvatarView.BorderWidth = 1; tappedAvatarView.BorderColor = Color.FromHex("#9E9E9E"); DefinedAvatarItem = tappedAvatarView.AvatarCharacter; } private void SetColorToAvatar() { if (tappedAvatar == null) return; foreach (var item in ColorItemCollection) { item.InitialsColor = Color.Transparent; } if (ColorItemCollection.IndexOf(tappedAvatar) < 5) tappedAvatar.InitialsColor = Color.White; else tappedAvatar.InitialsColor = Color.Black; ProfileColor = tappedAvatar.BackgroundColor; TextColor = tappedAvatar.InitialsColor; if (UseGradients) { GradientBrush = tappedAvatar.BackgroundGradient; } else { GradientBrush = null; } } private void CmdButton_Clicked(object sender, EventArgs e) { if ((sender as Button).Text == "Edit Profile") { (sender as Button).Text = "Done"; EditionIsVisible = true; } else { (sender as Button).Text = "Edit Profile"; EditionIsVisible = false; } } public class ColorBackgroundAvatar : Avatar.SfAvatarView { private Color startColor; public Color StartColor { get { return startColor; } set { startColor = value; this.OnPropertyChanged(); } } private Color stopcolor; public Color StopColor { get { return stopcolor; } set { stopcolor = value; this.OnPropertyChanged(); } } } } #endregion }<file_sep>/Forms/Chart/Chart/Samples/FunnelChart/FunnelSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class FunnelSeriesViewModel { public ObservableCollection<ChartDataModel> FunnelData { get; set; } public FunnelSeriesViewModel() { FunnelData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Renewed", 18.2), new ChartDataModel("Subscribe", 27.3), new ChartDataModel("Support", 55.9), new ChartDataModel("Downloaded", 76.8), new ChartDataModel("Visited", 100) }; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/EmployeeInformation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; namespace SampleBrowser { public class EmployeeInformation : INotifyPropertyChanged { public EmployeeInformation () { } #region Private Variables private int employeeID; private string firstName; private string lastName; private string designation; private DateTime birthDate; private DateTime hireDate; private string address; private string city; private string country; private string telePhone; private string qualification; #endregion #region Public Properties public int EmployeeID { get { return this.employeeID; } set { this.employeeID = value; this.RaisePropertyChanged ("EmployeeID"); } } public string Designation { get { return this.designation; } set { this.designation = value; this.RaisePropertyChanged ("Designation"); } } public string Qualification { get { return this.qualification; } set { this.qualification = value; this.RaisePropertyChanged ("Qualification"); } } public string FirstName { get { return this.firstName; } set { this.firstName = value; this.RaisePropertyChanged ("FirstName"); } } public string LastName { get { return this.lastName; } set { this.lastName = value; this.RaisePropertyChanged ("LastName"); } } public DateTime DateOfBirth { get { return this.birthDate; } set { this.birthDate = value; this.RaisePropertyChanged ("DateOfBirth"); } } public DateTime DateOfJoining { get { return this.hireDate; } set { this.hireDate = value; this.RaisePropertyChanged ("DateOfJoining"); } } public string Address { get { return this.address; } set { this.address = value; this.RaisePropertyChanged ("Address"); } } public string City { get { return this.city; } set { this.city = value; this.RaisePropertyChanged ("City"); } } public string Country { get { return this.country; } set { this.country = value; this.RaisePropertyChanged ("Country"); } } public string Telephone { get { return this.telePhone; } set { this.telePhone = value; this.RaisePropertyChanged ("Telephone"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged (String name) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (name)); } #endregion } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/EmployeeInformation.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "EmployeeInformation.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws.// </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties and notifies clients that a property value has changed. /// </summary> public class EmployeeInformation : INotifyPropertyChanged { #region Private Variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int employeeID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string firstName; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string lastName; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string designation; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DateTime birthDate; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DateTime hireDateTime; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string address; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string city; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string country; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string telePhone; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string qualification; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string hireDate; #endregion /// <summary> /// Initializes a new instance of the EmployeeInformation class. /// </summary> public EmployeeInformation() { } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the value of EmployeeID and notifies user when value gets changed /// </summary> public int EmployeeID { get { return this.employeeID; } set { this.employeeID = value; this.RaisePropertyChanged("EmployeeID"); } } /// <summary> /// Gets or sets the value of Designation and notifies user when value gets changed /// </summary> public string Designation { get { return this.designation; } set { this.designation = value; this.RaisePropertyChanged("Designation"); } } /// <summary> /// Gets or sets the value of Qualification and notifies user when value gets changed /// </summary> public string Qualification { get { return this.qualification; } set { this.qualification = value; this.RaisePropertyChanged("Qualification"); } } /// <summary> /// Gets or sets the value of FirstName and notifies user when value gets changed /// </summary> public string FirstName { get { return this.firstName; } set { this.firstName = value; this.RaisePropertyChanged("FirstName"); } } /// <summary> /// Gets or sets the value of LastName and notifies user when value gets changed /// </summary> public string LastName { get { return this.lastName; } set { this.lastName = value; this.RaisePropertyChanged("LastName"); } } /// <summary> /// Gets or sets the value of DateOfBirth and notifies user when value gets changed /// </summary> public DateTime DateOfBirth { get { return this.birthDate; } set { this.birthDate = value; this.RaisePropertyChanged("DateOfBirth"); } } /// <summary> /// Gets or sets the value of DateOfJoining and notifies user when value gets changed /// </summary> public DateTime DateOfJoining { get { return this.hireDateTime; } set { this.hireDateTime = value; this.RaisePropertyChanged("DateOfJoining"); } } /// <summary> /// Gets or sets the value of Address and notifies user when value gets changed /// </summary> public string Address { get { return this.address; } set { this.address = value; this.RaisePropertyChanged("Address"); } } /// <summary> /// Gets or sets the value of City and notifies user when value gets changed /// </summary> public string City { get { return this.city; } set { this.city = value; this.RaisePropertyChanged("City"); } } /// <summary> /// Gets or sets the value of Country and notifies user when value gets changed /// </summary> public string Country { get { return this.country; } set { this.country = value; this.RaisePropertyChanged("Country"); } } /// <summary> /// Gets or sets the value of Telephone and notifies user when value gets changed /// </summary> public string Telephone { get { return this.telePhone; } set { this.telePhone = value; this.RaisePropertyChanged("Telephone"); } } /// <summary> /// Gets or sets the value of HireDate and notifies user when value gets changed /// </summary> public string HireDate { get { return this.hireDate; } set { this.hireDate = value; this.RaisePropertyChanged("Telephone"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Forms/ProgressBar/ProgressBar/Samples/Linear/LinearBuffer.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfProgressBar { using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.XForms.ProgressBar; using Xamarin.Forms; public partial class LinearBuffer : SampleView { public LinearBuffer() { InitializeComponent(); this.SecondaryProgressProgressBar.AnimationDuration = 2000; this.SecondaryProgressProgressBar.SecondaryAnimationDuration = 1000; } public void Dispose() { SecondaryProgressProgressBar?.Dispose(true); } public override void OnDisappearing() { this.Dispose(); } private async void SecondaryProgressProgressBar_ValueChanged(object sender, ProgressValueEventArgs e) { if (e.Progress.Equals(100)) { this.SecondaryProgressProgressBar.SecondaryAnimationDuration = 0; await Task.Delay(100); this.SecondaryProgressProgressBar.SecondaryProgress = 0; this.SecondaryProgressProgressBar.SetProgress(0, 0, Easing.Linear); } if (e.Progress.Equals(0)) { this.SecondaryProgressProgressBar.SecondaryAnimationDuration = 1000; await Task.Delay(100); this.SecondaryProgressProgressBar.SecondaryProgress = 100; this.SecondaryProgressProgressBar.Progress = 100; } } } }<file_sep>/Forms/Chart/Chart/Samples/MultipleCircle/MultipleCircleViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class MultipleCircleViewModel { public ObservableCollection<MultipleCircleModel> DoughnutSeriesData { get; set; } public MultipleCircleViewModel() { DoughnutSeriesData = new ObservableCollection<MultipleCircleModel> { new MultipleCircleModel("Vehicle", 62.7,"ToyCar.png"), new MultipleCircleModel("Education",29.5,"Chart_Book.png"), new MultipleCircleModel("Home", 85.2, "HouseIcon.png"), new MultipleCircleModel("Personal", 45.6,"Savings.png") }; } } public class MultipleCircleModel { public string XValue { get; set; } public double YValue { get; set; } public string Image { get; set; } public MultipleCircleModel(string xValue, double yValue, string image) { XValue = xValue; YValue = yValue; Image = image; } } }<file_sep>/Forms/ListView/ListView/Samples/Swiping/Model/ListViewInboxInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewInboxInfo : INotifyPropertyChanged { #region Fields private string title; private string subject; private string desc; private string date; private bool isFavorite = true; #endregion #region Constructor public ListViewInboxInfo() { } #endregion #region Properties public string Title { get { return title; } set { title = value; OnPropertyChanged("Title"); } } public string Subject { get { return subject; } set { subject = value; OnPropertyChanged("Subject"); } } public string Description { get { return desc; } set { desc = value; OnPropertyChanged("Description"); } } public string Date { get { return date; } set { date = value; OnPropertyChanged("Date"); } } public bool IsFavorite { get { return isFavorite; } set { isFavorite = value; OnPropertyChanged("IsFavorite"); } } #endregion #region Interface Member public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/Diagram/Organization Chart.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.Collections.Generic; using System.ComponentModel; using CoreGraphics; using Syncfusion.SfDiagram.iOS; using UIKit; using Foundation; using System.Linq; namespace SampleBrowser { public partial class OrganizationalChart : SampleView { SfDiagram diagram; DataModel datamodel; Dictionary<string, UIColor> FillColor; Dictionary<string, CGColor> StrokeColor; UIPickerView selectionPicker1; private UILabel overviewLabel; private UISwitch overviewSwitch; private UILabel dragLabel; private UISwitch dragSwitch; OverviewPanel overviewPanel; public OrganizationalChart() { selectionPicker1 = new UIPickerView(); this.OptionView = new UIView(); string deviceType = UIDevice.CurrentDevice.Model; overviewLabel = new UILabel(); overviewLabel.Text = "Enable Overview"; overviewLabel.TextColor = UIColor.Black; overviewLabel.TextAlignment = UITextAlignment.Left; overviewLabel.BackgroundColor = UIColor.Clear; overviewLabel.Frame = new CGRect(this.Frame.X + 10, 70, 150, 30); overviewSwitch = new UISwitch(); overviewSwitch.On = true; overviewSwitch.Frame = new CGRect(this.Frame.X + 250, 70, 50, 30); overviewSwitch.TouchUpInside += OverviewSwitch_TouchUpInside; overviewSwitch.BackgroundColor = UIColor.Clear; dragLabel = new UILabel(); dragLabel.Text = "Change Hierarchy"; dragLabel.TextColor = UIColor.Black; dragLabel.TextAlignment = UITextAlignment.Left; dragLabel.BackgroundColor = UIColor.Clear; dragLabel.Frame = new CGRect(this.Frame.X + 10, 10, 150, 30); dragSwitch = new UISwitch(); dragSwitch.On = false; dragSwitch.Frame = new CGRect(this.Frame.X + 250, 10, 50, 30); dragSwitch.TouchUpInside += dragSwitch_TouchUpInside; dragSwitch.BackgroundColor = UIColor.Clear; diagram = new SfDiagram(); //Dictionary collection FillColor = new Dictionary<string, UIColor>(); FillColor.Add("Managing Director", UIColor.FromRGB(239, 75, 93)); FillColor.Add("Project Manager", UIColor.FromRGB(49, 162, 255)); FillColor.Add("Senior Manager", UIColor.FromRGB(49, 162, 255)); FillColor.Add("Project Lead", UIColor.FromRGB(0, 194, 192)); FillColor.Add("Senior S/W Engg", UIColor.FromRGB(0, 194, 192)); FillColor.Add("Software Engg", UIColor.FromRGB(0, 194, 192)); FillColor.Add("Team Lead", UIColor.FromRGB(0, 194, 192)); FillColor.Add("Project Trainee", UIColor.FromRGB(255, 129, 0)); StrokeColor = new Dictionary<string, CGColor>(); StrokeColor.Add("Managing Director", UIColor.FromRGB(201, 32, 61).CGColor); StrokeColor.Add("Project Manager", UIColor.FromRGB(23, 132, 206).CGColor); StrokeColor.Add("Senior Manager", UIColor.FromRGB(23, 132, 206).CGColor); StrokeColor.Add("Project Lead", UIColor.FromRGB(4, 142, 135).CGColor); StrokeColor.Add("Senior S/W Engg", UIColor.FromRGB(4, 142, 135).CGColor); StrokeColor.Add("Software Engg", UIColor.FromRGB(4, 142, 135).CGColor); StrokeColor.Add("Team Lead", UIColor.FromRGB(4, 142, 135).CGColor); StrokeColor.Add("Project Trainee", UIColor.FromRGB(206, 98, 9).CGColor); diagram.BeginNodeRender += Dia_BeginNodeRender; diagram.ItemLongPressed += Dia_ItemLongPressed; diagram.LayoutNodeDropped += Diagram_OnLayoutNodeDropped; diagram.BackgroundColor = UIColor.White; diagram.EnableSelectors = false; diagram.NodeClicked += Dia_NodeClicked; diagram.Loaded += Dia_Loaded; //Initialize Method datamodel = new DataModel(); datamodel.Data(); //To Represent DataSourceSttings Properties DataSourceSettings settings = new DataSourceSettings(); settings.ParentId = "ReportingPerson"; settings.Id = "Name"; settings.DataSource = datamodel.employee; diagram.DataSourceSettings = settings; //To Represent LayoutManager Properties diagram.LayoutManager = new LayoutManager() { Layout = new DirectedTreeLayout() { Type = LayoutType.Organization, HorizontalSpacing = 35, } }; for (int i = 0; i < diagram.Connectors.Count; i++) { diagram.Connectors[i].TargetDecoratorType = DecoratorType.None; diagram.Connectors[i].Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(127, 132, 133)); diagram.Connectors[i].Style.StrokeWidth = 1; } this.AddSubview(diagram); diagram.Width = (float)this.Frame.Width; diagram.Height = (float)this.Frame.Height; OptionView.AddSubview(dragLabel); OptionView.AddSubview(dragSwitch); if (deviceType == "iPad") { OptionView.AddSubview(overviewLabel); OptionView.AddSubview(overviewSwitch); overviewPanel = new OverviewPanel(); overviewPanel.Layer.BorderColor = UIColor.Orange.CGColor; overviewPanel.Layer.BorderWidth = 2; overviewPanel.Frame = new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width / 2, UIScreen.MainScreen.Bounds.Height / 4); diagram.AddSubview(overviewPanel); diagram.OverviewPanel = overviewPanel; } } private void Diagram_OnLayoutNodeDropped(object sender, LayoutNodeDroppedEventArgs args) { Node draggedNode = args.DraggedItem as Node; Node droppedNode = args.DroppedItem as Node; bool contain = true; if (draggedNode != null && draggedNode != droppedNode) { Node ParentNode = GetParent((droppedNode.Content as DiagramEmployee).ReportingPerson); do { if (ParentNode != draggedNode) { contain = false; } else { contain = true; break; } ParentNode = GetParent((ParentNode.Content as DiagramEmployee).ReportingPerson); } while (ParentNode != null); if (!contain) { Connector con;bool hasChild = false; foreach (Connector connector in draggedNode.InConnectors) { con = connector; con.SourceNode = droppedNode; hasChild = true; } if (hasChild) { Node PrevParentNode = GetParent((draggedNode.Content as DiagramEmployee).ReportingPerson); bool noChild = true; foreach(Connector c in PrevParentNode.OutConnectors) { noChild = false; } if (PrevParentNode != null && noChild) { (PrevParentNode.Content as DiagramEmployee).HasChild = false; DrawTemplate(PrevParentNode); } DiagramEmployee ParentEmployee = (droppedNode.Content as DiagramEmployee); (draggedNode.Content as DiagramEmployee).ReportingPerson = ParentEmployee.Name; ParentEmployee.HasChild = true; ExpandAll(draggedNode); UpdateTemplate(draggedNode); UpdateTemplate(droppedNode); } droppedNode.IsExpanded = true; diagram.LayoutManager.Layout.UpdateLayout(); if (overviewPanel != null) overviewPanel.ForceRefresh(); } } } private void UpdateTemplate(Node node) { var template = new UIView(); template.Frame = new CGRect(0, 0, node.Width, node.Height); template.BackgroundColor = FillColor[(node.Content as DiagramEmployee).Designation]; template.Layer.BorderColor = StrokeColor[((node.Content as DiagramEmployee).Designation)]; template.Layer.CornerRadius = 4; template.Layer.BorderWidth = 1; //EMP IMAGE var img = new UIImageView(); img.Frame = new CGRect(5, 8, 35, 35); img.Image = UIImage.FromBundle((node.Content as DiagramEmployee).ImageUrl); //EMP NAME var name = new UILabel() { Text = (node.Content as DiagramEmployee).Name, Font = UIFont.FromName(".SF UI Text", 12), TextColor = UIColor.FromRGB(255, 255, 255), Frame = new CGRect(45, -10, node.Width, node.Height) }; name.Layer.ShouldRasterize = true; name.Layer.RasterizationScale = UIScreen.MainScreen.Scale; //EMP DESIGNATION var designation = new UILabel() { Text = (node.Content as DiagramEmployee).Designation, Font = UIFont.FromName(".SF UI Text", 12), TextColor = UIColor.FromRGB(255, 255, 255), Frame = new CGRect(45, 8, node.Width, node.Height) }; designation.Layer.ShouldRasterize = true; designation.Layer.RasterizationScale = UIScreen.MainScreen.Scale; if ((node.Content as DiagramEmployee).HasChild) { var temp = 35; if (node.Width == 190) { temp = 0; } else temp = 35; template.Frame = new CGRect(0, 0, node.Width + temp, node.Height); var indication = new UILabel(); indication.Frame = new CGRect(template.Frame.Width - 35, template.Frame.Height / 2 - 22.5, 40, 40); indication.Font = UIFont.FromName(".SF UI Text", 35); indication.TextAlignment = UITextAlignment.Center; indication.TextColor = UIColor.White; indication.Text = "-"; template.AddSubview(indication); var indicationLine = new UIView(); indicationLine.Frame = new CGRect(template.Frame.Width - 35, 0, 1, template.Frame.Height); indicationLine.BackgroundColor = new UIColor(template.Layer.BorderColor); template.AddSubview(indicationLine); indication.Layer.ShouldRasterize = true; indication.Layer.RasterizationScale = UIScreen.MainScreen.Scale; } template.AddSubview(img); template.AddSubview(name); template.AddSubview(designation); node.Template = template; } private void ExpandAll(Node node) { if ((node.Content as DiagramEmployee).HasChild) { node.IsExpanded = true; UpdateTemplate(node); if (node.OutConnectors.Any()) { foreach (var c in node.OutConnectors) { if (c.TargetNode != null) { ExpandAll(c.TargetNode); } } } } } private Node GetParent(string parentId) { foreach (Node node in diagram.Nodes) { if ((node.Content as DiagramEmployee).Name == parentId) { return node; } } return null; } void dragSwitch_TouchUpInside(object sender, EventArgs e) { if ((sender as UISwitch).On) { (diagram.LayoutManager.Layout as DirectedTreeLayout).IsDraggable = true; } else { (diagram.LayoutManager.Layout as DirectedTreeLayout).IsDraggable = false; } } void OverviewSwitch_TouchUpInside(object sender, EventArgs e) { if ((sender as UISwitch).On) { overviewPanel.Hidden = false; } else { overviewPanel.Hidden = true; } } void Dia_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); } void Dia_BeginNodeRender(object sender, BeginNodeRenderEventArgs args) { var node = (args.Item as Node); node.Width = 155; node.Height = 50; DrawTemplate(node); } void DrawTemplate(Node node) { var template = new UIView(); template.Frame = new CGRect(0, 0, node.Width, node.Height); template.BackgroundColor = FillColor[(node.Content as DiagramEmployee).Designation]; template.Layer.BorderColor = StrokeColor[((node.Content as DiagramEmployee).Designation)]; template.Layer.CornerRadius = 4; template.Layer.BorderWidth = 1; //EMP IMAGE var img = new UIImageView(); img.Frame = new CGRect(5, 8, 35, 35); img.Image = UIImage.FromBundle((node.Content as DiagramEmployee).ImageUrl); //EMP NAME var name = new UILabel() { Text = (node.Content as DiagramEmployee).Name, Font = UIFont.FromName(".SF UI Text", 12), TextColor = UIColor.FromRGB(255, 255, 255), Frame = new CGRect(45, -10, node.Width, node.Height) }; name.Layer.ShouldRasterize = true; name.Layer.RasterizationScale = UIScreen.MainScreen.Scale; //EMP DESIGNATION var designation = new UILabel() { Text = (node.Content as DiagramEmployee).Designation, Font = UIFont.FromName(".SF UI Text", 12), TextColor = UIColor.FromRGB(255, 255, 255), Frame = new CGRect(45, 8, node.Width, node.Height) }; designation.Layer.ShouldRasterize = true; designation.Layer.RasterizationScale = UIScreen.MainScreen.Scale; if ((node.Content as DiagramEmployee).HasChild) { template.Frame = new CGRect(0, 0, node.Width + 35, node.Height); var indication = new UILabel(); indication.Frame = new CGRect(node.Width - 2, node.Height / 2 - 22.5, 40, 40); indication.Font = UIFont.FromName(".SF UI Text", 35); indication.TextAlignment = UITextAlignment.Center; indication.TextColor = UIColor.White; indication.Text = "-"; template.AddSubview(indication); var indicationLine = new UIView(); indicationLine.Frame = new CGRect(node.Width - 5, 0, 1, node.Height); indicationLine.BackgroundColor = new UIColor(template.Layer.BorderColor); template.AddSubview(indicationLine); indication.Layer.ShouldRasterize = true; indication.Layer.RasterizationScale = UIScreen.MainScreen.Scale; } template.AddSubview(img); template.AddSubview(name); template.AddSubview(designation); node.Template = template; } void Dia_ItemLongPressed(object sender, ItemLongPressedEventArgs args) { if (!((diagram.LayoutManager.Layout as DirectedTreeLayout).IsDraggable)) { var node = args.Item as Node; var info = new UIAlertView(); info.AddButton("OK"); info.Message = "Name : " + (node.Content as DiagramEmployee).Name + "\n" + "Designation : " + (node.Content as DiagramEmployee).Designation + "\n" + "ID : " + (node.Content as DiagramEmployee).ID + "\n" + "DOJ : " + (node.Content as DiagramEmployee).DOJ + "\n" + "Reporting Person : " + (node.Content as DiagramEmployee).ReportingPerson; info.Show(); } } void Dia_NodeClicked(object sender, NodeClickedEventArgs args) { if (args.Item.IsExpanded) { if ((args.Item.Content as DiagramEmployee).HasChild) { ((args.Item.Template as UIView).Subviews[0] as UILabel).Font = UIFont.SystemFontOfSize(30); ((args.Item.Template as UIView).Subviews[0] as UILabel).Text = "+"; } args.Item.IsExpanded = false; } else { if ((args.Item.Content as DiagramEmployee).HasChild) { ((args.Item.Template as UIView).Subviews[0] as UILabel).Font = UIFont.SystemFontOfSize(35); ((args.Item.Template as UIView).Subviews[0] as UILabel).Text = "-"; } args.Item.IsExpanded = true; } } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Helpers/RowTemplate.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "RowTemplate.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; /// <summary> /// A layout that arranges views in rows and columns /// </summary> public class RowTemplate : Grid { #region Constructor /// <summary> /// Initializes a new instance of the RowTemplate class. /// </summary> public RowTemplate() { this.BackgroundColor = Color.White; this.Children.Add(this.CreateLabel("OrderID")); this.Children.Add(new BoxView() { Color = Color.Gray, WidthRequest = 1 }); this.Children.Add(this.CreateLabel("EmployeeID")); this.Children.Add(new BoxView() { Color = Color.Gray, WidthRequest = 1 }); this.Children.Add(this.CreateLabel("CustomerID")); this.Children.Add(new BoxView() { Color = Color.Gray, WidthRequest = 1 }); this.Children.Add(this.CreateLabel("FirstName")); this.Children.Add(new BoxView() { Color = Color.Gray, WidthRequest = 1 }); this.Children.Add(this.CreateLabel("LastName")); } #endregion #region Override Method /// <summary> /// Updates the bounds of the element during the layout cycle. /// </summary> /// <param name="x">A value representing the x coordinate of the child region bounding box.</param> /// <param name="y">A value representing the y coordinate of the child region bounding box.</param> /// <param name="width">A value representing the width of the child region bounding box.</param> /// <param name="height">A value representing the height of the child region bounding box.</param> protected override void LayoutChildren(double x, double y, double width, double height) { foreach (var child in this.Children) { if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { if (child is ContentView) { child.Layout(new Rectangle(x, y, (width / ((Children.Count + 1) / 2)) - 0.5, height)); } else { child.Layout(new Rectangle(x, y, 0.5, height)); } } else { if (child is ContentView) { child.Layout(new Rectangle(x, y, (width / ((Children.Count + 1) / 2)) - 1, height)); } else { child.Layout(new Rectangle(x, y, 1, height)); } } x += child.Width; } } #endregion #region Private Method /// <summary> /// Used to create Label with desired properties /// </summary> /// <param name="property">string type text</param> /// <returns>returns a created label</returns> private ContentView CreateLabel(string property) { var label = new Label(); label.TextColor = Color.Black; label.LineBreakMode = LineBreakMode.NoWrap; label.FontSize = 12; label.HorizontalTextAlignment = TextAlignment.Center; label.VerticalTextAlignment = TextAlignment.Center; label.VerticalOptions = LayoutOptions.Center; label.SetBinding(Label.TextProperty, property); return new ContentView() { Content = label }; } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/DataPointSelection/DataPointSelectionViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class DataPointSelectionViewModel { public ObservableCollection<ChartDataModel> SelectionData { get; set; } public ObservableCollection<ChartDataModel> SelectionData1 { get; set; } public DataPointSelectionViewModel() { SelectionData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 60), new ChartDataModel("Feb", 80), new ChartDataModel("Mar", 70), new ChartDataModel("Apr", 90) }; SelectionData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 50), new ChartDataModel("Feb", 70), new ChartDataModel("Mar", 80), new ChartDataModel("Apr", 70) }; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/AutoComplete/ToleratingTypos_Main.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using SampleBrowser; using UIKit; namespace SampleBrowser { public class ToleratingTypos_Main:SampleView { ToleratingTypos phoneView; ToleratingTypos_Tablet tableyviewOfAuto; public ToleratingTypos_Main() { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { tableyviewOfAuto = new ToleratingTypos_Tablet(); this.AddSubview(tableyviewOfAuto); } else { phoneView = new ToleratingTypos(); this.AddSubview(phoneView); } } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Kanban/GettingStartedKanban.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using Syncfusion.SfKanban.iOS; using System.Collections.Generic ; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class GettingStartedKanban : SampleView { SfKanban kanban; public GettingStartedKanban () { KanbanColumn column1; KanbanColumn column2; KanbanColumn column3; KanbanColumn column4; kanban = new SfKanban (); column1 = new KanbanColumn() { Categories = new List<object>() { "Open", "Postponed", "Validated" } }; column1.Title = "To Do"; column1.MinimumLimit = 5; column1.MaximumLimit = 15; kanban.Columns.Add(column1); column2 = new KanbanColumn() { Categories = new List<object>() { "In Progress" } }; column2.Title = "In Progress"; column2.MinimumLimit = 3; column2.MaximumLimit = 8; kanban.Columns.Add(column2); column3 = new KanbanColumn() { Categories = new List<object>() { "Code Review" } }; column3.Title = "Code Review"; column3.MinimumLimit = 5; column3.MaximumLimit = 10; kanban.Columns.Add(column3); column4 = new KanbanColumn() { Categories = new List<object>() { "Closed", "Closed-No Code Changes", "Resolved" } }; column4.Title = "Done"; column4.MinimumLimit = 8; column4.MaximumLimit = 12; kanban.Columns.Add(column4); kanban.ItemsSource = new KanbanDataSource().Data; List<KanbanColorMapping> colormodels = new List<KanbanColorMapping>(); colormodels.Add(new KanbanColorMapping("Purple", UIColor.Purple)); colormodels.Add(new KanbanColorMapping("Red", UIColor.Red)); colormodels.Add(new KanbanColorMapping("Orange", UIColor.Orange)); colormodels.Add(new KanbanColorMapping("Brown", UIColor.Brown)); kanban.IndicatorColorPalette = colormodels; List<KanbanWorkflow> keyfield = new List<KanbanWorkflow>(); keyfield.Add(new KanbanWorkflow("Open", new List<object> { "In Progress" })); keyfield.Add(new KanbanWorkflow("In Progress", new List<object> { "Postponed", "Validated", "Code Review", "Closed-No Code Changes" })); keyfield.Add(new KanbanWorkflow("Code Review", new List<object> { "Closed", "Resolved" })); keyfield.Add(new KanbanWorkflow("Closed", new List<object> { "Open" })); keyfield.Add(new KanbanWorkflow("Postponed", new List<object> { "In Progress" })); keyfield.Add(new KanbanWorkflow("Validated", new List<object> { "In Progress" })); keyfield.Add(new KanbanWorkflow("Closed-No Code Changes", new List<object> { })); keyfield.Add(new KanbanWorkflow("Resolved", new List<object> { })); kanban.Workflows = keyfield; this.AddSubview (kanban); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { if(view == kanban) view.Frame = Bounds; } base.LayoutSubviews (); } protected override void Dispose(bool disposing) { base.Dispose(disposing); kanban.Dispose(); } } public class KanbanDataSource { public ObservableCollection<KanbanModel> Data { get; set; } public KanbanDataSource() { Data = ItemsSourceCards(); } ObservableCollection<KanbanModel> ItemsSourceCards() { ObservableCollection<KanbanModel> cards = new ObservableCollection<KanbanModel>(); cards.Add( new KanbanModel() { ID = 1, Title = "iOS - 1", ImageURL = "Image8.png", Category = "Open", Description = "Analyze customer requirements", ColorKey = "Red", Tags = new string[] { "Bug", "Customer", "Release Bug" } } ); cards.Add( new KanbanModel() { ID = 6, Title = "Xamarin - 6", ImageURL = "Image9.png", Category = "Open", Description = "Show the retrived data from the server in grid control", ColorKey = "Red", Tags = new string[] { "Bug", "Customer", "Breaking Issue" } } ); cards.Add( new KanbanModel() { ID = 3, Title = "iOS - 3", ImageURL = "Image10.png", Category = "Open", Description = "Fix the filtering issues reported in safari", ColorKey = "Red", Tags = new string[] { "Bug", "Customer", "Breaking Issue" } } ); cards.Add( new KanbanModel() { ID = 11, Title = "iOS - 11", ImageURL = "Image11.png", Category = "Open", Description = "Add input validation for editing", ColorKey = "Red", Tags = new string[] { "Bug", "Customer", "Breaking Issue" } } ); cards.Add( new KanbanModel() { ID = 15, Title = "Android - 15", Category = "Open", ImageURL = "Image12.png", Description = "Arrange web meeting for cutomer requirement", ColorKey = "Red", Tags = new string[] { "Story", "Kanban" } }); cards.Add( new KanbanModel() { ID = 3, Title = "Android - 3", Category = "Code Review", ImageURL = "Image13.png", Description = "API Improvements", ColorKey = "Purple", Tags = new string[] { "Bug", "Customer" } }); cards.Add( new KanbanModel() { ID = 4, Title = "UWP - 4", ImageURL = "Image14.png", Category = "Code Review", Description = "Enhance editing functionality", ColorKey = "Brown", Tags = new string[] { "Story", "Kanban" } }); cards.Add( new KanbanModel() { ID = 9, Title = "Xamarin - 9", ImageURL = "Image15.png", Category = "Code Review", Description = "Improve application performance", ColorKey = "Orange", Tags = new string[] { "Story", "Kanban" } } ); cards.Add( new KanbanModel() { ID = 13, Title = "UWP - 13", ImageURL = "Image16.png", Category = "In Progress", Description = "Add responsive support to applicaton", ColorKey = "Brown", Tags = new string[] { "Story", "Kanban" } } ); cards.Add( new KanbanModel() { ID = 17, Title = "Xamarin - 17", Category = "In Progress", ImageURL = "Image17.png", Description = "Fix the issues reported in IE browser", ColorKey = "Brown", Tags = new string[] { "Bug", "Customer" } } ); cards.Add( new KanbanModel() { ID = 21, Title = "Xamarin - 21", Category = "In Progress", ImageURL = "Image18.png", Description = "Improve performance of editing functionality", ColorKey = "Purple", Tags = new string[] { "Bug", "Customer" } } ); cards.Add( new KanbanModel() { ID = 19, Title = "iOS - 19", Category = "In Progress", ImageURL = "Image19.png", Description = "Fix the issues reported by the customer", ColorKey = "Purple", Tags = new string[] { "Bug" } } ); cards.Add( new KanbanModel() { ID = 8, Title = "Android", Category = "Code Review", ImageURL = "Image20.png", Description = "Check login page validation", ColorKey = "Brown", Tags = new string[] { "Feature" } } ); cards.Add( new KanbanModel() { ID = 24, Title = "UWP - 24", ImageURL = "Image21.png", Category = "In Progress", Description = "Editing functionality", ColorKey = "Orange", Tags = new string[] { "Feature", "Customer", "Release" } } ); cards.Add( new KanbanModel() { ID = 20, Title = "iOS - 20", Category = "In Progress", ImageURL = "Image22.png", Description = "Fix the issues reported in data binding", ColorKey = "Red", Tags = new string[] { "Feature", "Release", } } ); cards.Add( new KanbanModel() { ID = 12, Title = "Xamarin - 12", Category = "In Progress", ImageURL = "Image23.png", Description = "Editing functionality", ColorKey = "Red", Tags = new string[] { "Feature", "Release", } } ); cards.Add( new KanbanModel() { ID = 11, Title = "iOS - 11", Category = "In Progress", ImageURL = "Image24.png", Description = "Check filtering validation", ColorKey = "Red", Tags = new string[] { "Feature", "Release", } } ); cards.Add( new KanbanModel() { ID = 13, Title = "UWP - 13", ImageURL = "Image25.png", Category = "Closed", Description = "Fix cannot open user's default database sql error", ColorKey = "Purple", Tags = new string[] { "Bug", "Internal", "Release" } }); cards.Add( new KanbanModel() { ID = 14, Title = "Android - 14", Category = "Closed", ImageURL = "Image26.png", Description = "Arrange web meeting with customer to get login page requirement", ColorKey = "Red", Tags = new string[] { "Feature" } } ); cards.Add( new KanbanModel() { ID = 15, Title = "Xamarin - 15", Category = "Closed", ImageURL = "Image27.png", Description = "Login page validation", ColorKey = "Red", Tags = new string[] { "Bug" } } ); cards.Add( new KanbanModel() { ID = 16, Title = "Xamarin - 16", ImageURL = "Image28.png", Category = "Closed", Description = "Improve application performance", ColorKey = "Purple", Tags = new string[] { "Bug" } } ); cards.Add( new KanbanModel() { ID = 20, Title = "UWP - 20", ImageURL = "Image29.png", Category = "Closed", Description = "Analyze stored procedure", ColorKey = "Brown", Tags = new string[] { "CustomSample", "Customer", "Incident" } } ); cards.Add( new KanbanModel() { ID = 21, Title = "Android - 21", Category = "Closed", ImageURL = "Image30.png", Description = "Arrange web meeting with customer to get editing requirements", ColorKey = "Orange", Tags = new string[] { "Story", "Improvement" } } ); return cards; } } } <file_sep>/Forms/AutoComplete/AutoComplete/Samples/MultiSelect/MultiSelectViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public class MultiSelectViewModel : INotifyPropertyChanged { #region Property public ObservableCollection<ContactsInfo> ContactData { get; set; } private int toHeight = 40; public int ToHeight { get { return toHeight; } set { toHeight = value; RaisePropertyChanged("ToHeight"); } } private int ccHeight = 40; public int CcHeight { get { return ccHeight; } set { ccHeight = value; RaisePropertyChanged("CcHeight"); } } private int bccHeight = 40; public int BccHeight { get { return bccHeight; } set { bccHeight = value; RaisePropertyChanged("BccHeight"); } } private bool isToFocused = false; public bool IsToFocused { get { return isToFocused; } set { isToFocused = value; ToHeight = GetHeight(value); IsFocused = true; RaisePropertyChanged("IsToFocused"); } } private bool isCcFocused = false; public bool IsCcFocused { get { return isCcFocused; } set { isCcFocused = value; CcHeight = GetHeight(value); IsFocused = true; RaisePropertyChanged("IsCcFocused"); } } private bool isBccFocused = false; public bool IsBccFocused { get { return isBccFocused; } set { isBccFocused = value; IsFocused = true; BccHeight = GetHeight(value); RaisePropertyChanged("IsBccFocused"); } } private object selectedItem; public object SelectedItem { get { return selectedItem; } set { selectedItem = value; RaisePropertyChanged("SelectedItem"); } } private bool isFocused = false; public bool IsFocused { get { return isFocused; } set { RaisePropertyChanged("IsFocused"); } } public string watermark = ""; public string Watermark { get { return watermark; } set { watermark = value; RaisePropertyChanged("Watermark"); } } public string customText = string.Empty; public string CustomText { get { return customText; } set { customText = value; RaisePropertyChanged("CustomText"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion string hintText = "ryan"; double hintCount = 0; ObservableCollection<ContactsInfo> SelectedObject = new ObservableCollection<ContactsInfo>(); public bool ShowHint() { if (hintCount < hintText.Length) { CustomText += hintText[(int)hintCount++]; foreach (var info in ContactData) { if (info.ContactName.ToLower() == CustomText) { SelectedObject.Add(info); } } if (CustomText == "kyle") { SelectedItem = ContactData[0]; IsCcFocused = true; return false; } return true; } else { return false; } } public MultiSelectViewModel() { ContactData = new ContactsInfoRepository().GetContactDetails(); } public int GetHeight(bool value) { if (value) return 90; return 40; } } public class ImageSourceToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Android/SampleBrowser/Samples/Presentation/GettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using System.IO; using System.Reflection; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Presentation = Syncfusion.Presentation; namespace SampleBrowser { public partial class GettingStartedPresentation : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates how to create a PowerPoint presentation by adding text with simple text-formattings."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate Presentation"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.HelloWorld.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); #region Slide1 ISlide slide1 = presentation.Slides[0]; IShape titleShape = slide1.Shapes[0] as IShape; titleShape.Left = 0.33 * 72; titleShape.Top = 0.58 * 72; titleShape.Width = 12.5 * 72; titleShape.Height = 1.75 * 72; ITextBody textFrame1 = (slide1.Shapes[0] as IShape).TextBody; IParagraphs paragraphs1 = textFrame1.Paragraphs; IParagraph paragraph = paragraphs1.Add(); paragraph.HorizontalAlignment = HorizontalAlignmentType.Center; ITextPart textPart1 = paragraph.AddTextPart(); textPart1.Text = "Essential Presentation"; textPart1.Font.CapsType = TextCapsType.All; textPart1.Font.FontName = "Arial"; textPart1.Font.Bold = true; textPart1.Font.FontSize = 40; IShape subtitle = slide1.Shapes[1] as IShape; subtitle.Left = 0.5 * 72; subtitle.Top = 3 * 72; subtitle.Width = 11.8 * 72; subtitle.Height = 1.7 * 72; ITextBody textFrame2 = (slide1.Shapes[1] as IShape).TextBody; textFrame2.VerticalAlignment = VerticalAlignmentType.Top; IParagraphs paragraphs2 = textFrame2.Paragraphs; IParagraph para = paragraphs2.Add(); para.HorizontalAlignment = HorizontalAlignmentType.Left; ITextPart textPart2 = para.AddTextPart(); textPart2.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus.Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet."; textPart2.Font.FontName = "Arial"; textPart2.Font.FontSize = 21; para = paragraphs2.Add(); para.HorizontalAlignment = HorizontalAlignmentType.Left; textPart2 = para.AddTextPart(); textPart2.Text = "Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet. Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula."; textPart2.Font.FontName = "Arial"; textPart2.Font.FontSize = 21; //Add hyperlink to the paragraph ITextPart textPart3 = para.AddTextPart(); textPart3.Text = "click here"; textPart3.Font.FontName = "Arial"; textPart3.SetHyperlink("https://msdn.microsoft.com/en-in/library/mt299001.aspx"); #endregion MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("GettingStarted.pptx", "application/powerpoint", stream, m_context); } } } } <file_sep>/Forms/TreeMap/TreeMap/Samples/Hierarchical/HierarchicalViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeMap { [Preserve(AllMembers = true)] public class CountrySalesCollection : ObservableCollection<CountrySale> { public CountrySalesCollection() { this.Add(new CountrySale() { Name = "United States", Sales = 98456, Expense = 87000 }); this.Add(new CountrySale() { Name = "Canada", Sales = 43523, Expense = 40000 }); this.Add(new CountrySale() { Name = "Mexico", Sales = 45634, Expense = 46000 }); this[0].RegionalSales.Add(new RegionSale() { Country = "United States", Name = "New York", Sales = 2353, Expense = 2000 }); this[0].RegionalSales.Add(new RegionSale() { Country = "United States", Name = "Los Angeles", Sales = 3453, Expense = 3000 }); this[0].RegionalSales.Add(new RegionSale() { Country = "United States", Name = "San Francisco", Sales = 8456, Expense = 8000 }); this[0].RegionalSales.Add(new RegionSale() { Country = "United States", Name = "Chicago", Sales = 6785, Expense = 7000 }); this[0].RegionalSales.Add(new RegionSale() { Country = "United States", Name = "Miami", Sales = 7045, Expense = 6000 }); this[1].RegionalSales.Add(new RegionSale() { Country = "Canada", Name = "Toronto", Sales = 7045, Expense = 7000 }); this[1].RegionalSales.Add(new RegionSale() { Country = "Canada", Name = "Vancouver", Sales = 4352, Expense = 4000 }); this[1].RegionalSales.Add(new RegionSale() { Country = "Canada", Name = "Winnipeg", Sales = 7843, Expense = 7500 }); this[2].RegionalSales.Add(new RegionSale() { Country = "Mexico", Name = "Mexico City", Sales = 7843, Expense = 6500 }); this[2].RegionalSales.Add(new RegionSale() { Country = "Mexico", Name = "Cancun", Sales = 6683, Expense = 6000 }); this[2].RegionalSales.Add(new RegionSale() { Country = "Mexico", Name = "Acapulco", Sales = 2454, Expense = 2000 }); } } } <file_sep>/Forms/XlsIO/XlsIO/Samples/Extensions.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Xml.Linq; using System.Linq; using Syncfusion.XlsIO; namespace SampleBrowser.XlsIO { public static class TypeExtension { public static PropertyInfo[] GetProperties(this Type type) { IEnumerator<PropertyInfo> propertyEnum = type.GetTypeInfo().DeclaredProperties.GetEnumerator(); IList<PropertyInfo> listProperties = new List<PropertyInfo>(); while (propertyEnum.MoveNext()) { listProperties.Add(propertyEnum.Current); } return listProperties.ToArray<PropertyInfo>(); } public static PropertyInfo GetProperty(this Type type, string name) { IEnumerator<PropertyInfo> propertyEnum = type.GetTypeInfo().DeclaredProperties.GetEnumerator(); while (propertyEnum.MoveNext()) { if (propertyEnum.Current.Name == name) { return propertyEnum.Current; } } return null; } } public class XlsIOExtensions { /// <summary> /// Import XML file into Excel file. /// </summary> /// <param name="fileStream">XML file stream</param> /// <param name="sheet">Worksheet to import</param> /// <param name="row">Row to which import begin</param> /// <param name="col">Column to which import begin</param> /// <param name="header">Imports header if true</param> public void ImportXML(Stream fileStream, IWorksheet sheet, int row, int col, bool header) { StreamReader reader = new StreamReader(fileStream); IEnumerable<Customers> customers = GetData<Customers>(reader.ReadToEnd()); PropertyInfo[] propertyInfo = null; bool headerXML = true; int newCol = col; foreach (object obj in customers) { if (obj != null) { propertyInfo = obj.GetType().GetProperties(); if (header && headerXML) { foreach (var cell in propertyInfo) { sheet[row, newCol].Text = cell.Name; newCol++; } row++; headerXML = false; } newCol = col; foreach (var cell in propertyInfo) { Type currentRecordType = obj.GetType(); PropertyInfo property = currentRecordType.GetProperty(cell.Name); sheet[row, newCol].Value2 = property.GetValue(obj, null); newCol++; } headerXML = false; row++; } } } internal static IEnumerable<T> GetData<T>(string xml) where T : Customers, new() { return XElement.Parse(xml) .Elements("Customers") .Select(c => new T { CustomerID = (string)c.Element("CustomerID"), CompanyName = (string)c.Element("CompanyName"), ContactName = (string)c.Element("ContactName"), ContactTitle = (string)c.Element("ContactTitle"), Address = (string)c.Element("Address"), City = (string)c.Element("City"), PostalCode = (string)c.Element("PostalCode"), Country = (string)c.Element("Country"), Phone = (string)c.Element("Phone"), Fax = (string)c.Element("Fax") }); } } public class Customers { public string CustomerID { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string Address { get; set; } public string City { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string Phone { get; set; } public string Fax { get; set; } } public class BusinessObject { public string SalesPerson { get; set; } public int SalesJanJune { get; set; } public int SalesJulyDec { get; set; } public int Change { get; set; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/CustomGrouping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using CoreGraphics; using Foundation; using UIKit; using Syncfusion.Data; using Syncfusion.SfDataGrid; namespace SampleBrowser { public class CustomGrouping : SampleView { #region Fields SfDataGrid sfGrid; SalesInfoViewModel viewModel; #endregion #region Static Methods static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } #endregion #region Constructor public CustomGrouping () { sfGrid = new SfDataGrid (); this.sfGrid.SelectionMode = SelectionMode.Single; viewModel = new SalesInfoViewModel (); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = viewModel.DailySalesDetails; sfGrid.AllowSorting = true; this.sfGrid.HeaderRowHeight = 45; this.sfGrid.RowHeight = 45; this.sfGrid.AllowGroupExpandCollapse = true; sfGrid.SortComparers.Add (new SortComparer() { Comparer = new CustomSortComparer (), PropertyName = "Total" }); sfGrid.GroupColumnDescriptions.Add(new GroupColumnDescription() { ColumnName = "Total", Converter = new GroupDataTimeConverter() }); //TableSummary codes GridTableSummaryRow summaryRow = new GridTableSummaryRow(); summaryRow.Title = "Total items:{Total} items"; summaryRow.ShowSummaryInRow = true; summaryRow.Position = Position.Bottom; GridSummaryColumn summaryColumn = new GridSummaryColumn(); summaryColumn.Name = "Total"; summaryColumn.MappingName = "Name"; summaryColumn.Format = "{Count}"; summaryColumn.SummaryType = Syncfusion.Data.SummaryType.CountAggregate; summaryRow.SummaryColumns.Add(summaryColumn); sfGrid.TableSummaryRows.Add(summaryRow); this.AddSubview (sfGrid); } #endregion #region Override Methods public override void LayoutSubviews () { this.sfGrid.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews (); } protected override void Dispose(bool disposing) { sfGrid.Dispose(); base.Dispose(disposing); } #endregion #region CallBacks private void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "Name") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "QS1") { e.Column.HeaderText = "Sales in Quarter1"; } else if (e.Column.MappingName == "QS2") { e.Column.HeaderText = "Sales in Quarter2"; } else if (e.Column.MappingName == "QS3") { e.Column.HeaderText = "Sales in Quarter3"; } else if (e.Column.MappingName == "QS4") { e.Column.HeaderText = "Sales in Quarter4"; } else if (e.Column.MappingName == "Total") { e.Column.HeaderText = "Total Sales in Year"; } } #endregion } }<file_sep>/iOS/SampleBrowser/Samples/DataSource/Model/Contacts.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using UIKit; namespace SampleBrowser { public class Contacts { private string contactName; private string contactNumber; private UIColor color; public Contacts(string name, string number) { contactName = name; contactNumber = number; } public string ContactName { get { return contactName; } set { contactName = value; } } public string ContactNumber { get { return contactNumber; } set { contactNumber = value; } } public UIColor ContactColor { get { return color; } set { color = value; } } } }<file_sep>/iOS/SampleBrowser/Samples/Calendar/CalendarViews.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfCalendar.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class CalendarViews : SampleView { private CalendarViews_Mobile phoneView; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public CalendarViews() { phoneView = new CalendarViews_Mobile(); this.AddSubview(phoneView); this.OptionView = phoneView.Option; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DocIO/WordToHTML.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using ObjCRuntime; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class WordToHTML : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; bool isGenerateButtonClicked = false; UILabel label; UIButton button; public WordToHTML() { label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to convert a Word document into HTML file."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 40); } else { label.Frame = new CGRect(frameRect.Location.X, 5, frameRect.Size.Width, 40); } this.AddSubview(label); button.SetTitle("Generate", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(5, 60, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 60, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); // Creating a new document. WordDocument document = new WordDocument(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.WordtoHTML.doc"); //Open the Word document to convert document.Open(inputStream, FormatType.Doc); //Export the Word document to HTML file MemoryStream stream = new MemoryStream(); HTMLExport htmlExport = new HTMLExport(); htmlExport.SaveAsXhtml(document, stream); document.Close(); stream.Position = 0; StreamReader reader = new StreamReader(stream); string htmlString = reader.ReadToEnd(); isGenerateButtonClicked = true; UIWebView webView = new UIWebView(this.Bounds); webView.Frame = new CGRect(0, 0, this.Bounds.Width, this.Bounds.Height); this.AddSubview(webView); webView.LoadHtmlString(htmlString, NSBundle.MainBundle.BundleUrl); webView.ScalesPageToFit = false; } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Frame; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); if (!isGenerateButtonClicked) LoadAllowedTextsLabel(); base.LayoutSubviews(); } } class WebViewController : UIViewController { UIWebView webView; private string m_htmlString = string.Empty; public WebViewController(string htmlString) { m_htmlString = htmlString; } public override void ViewDidLoad() { base.ViewDidLoad(); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); this.View.BackgroundColor = UIColor.White; webView = new UIWebView(this.View.Bounds); webView.Frame = new CGRect(0, 0, this.View.Bounds.Width, this.View.Bounds.Height); this.View.AddSubview(webView); webView.LoadHtmlString(m_htmlString, NSBundle.MainBundle.BundleUrl); webView.ScalesPageToFit = false; } public override void ViewDidDisappear(bool animated) { if (webView != null) { webView.RemoveFromSuperview(); webView.Dispose(); webView = null; } base.ViewWillDisappear(animated); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/PDF/GettingStartedPDF.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf; using Syncfusion.Pdf.Barcode; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Interactive; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class GettingStartedPDF : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; PdfDocument doc; PdfPage page; Syncfusion.Drawing.Color gray = Syncfusion.Drawing.Color.FromArgb(255, 77, 77, 77); Syncfusion.Drawing.Color black = Syncfusion.Drawing.Color.FromArgb(255, 0, 0, 0); Syncfusion.Drawing.Color white = Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255); Syncfusion.Drawing.Color violet = Syncfusion.Drawing.Color.FromArgb(255, 151, 108, 174); UILabel label1; UIButton button ; public GettingStartedPDF() { label1 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label1.Frame = frameRect; label1.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label1.Text = "This sample demonstrates how to create a simple PDF document with text and images."; label1.Font = UIFont.SystemFontOfSize(15); label1.Lines = 0; label1.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label1.Font = UIFont.SystemFontOfSize(18); label1.Frame = new CGRect(0, 12, frameRect.Location.X + frameRect.Size.Width, 50); } else { label1.Frame = new CGRect(frameRect.Location.X, 12, frameRect.Size.Width, 50); } this.AddSubview(label1); button.SetTitle("Generate PDF", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 70, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 70, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { doc = new PdfDocument(); doc.PageSettings.Margins.All = 0; page = doc.Pages.Add(); PdfGraphics g = page.Graphics; PdfFont headerFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 35); PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16); g.DrawRectangle(new PdfSolidBrush(gray), new RectangleF(0, 0, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height)); g.DrawRectangle(new PdfSolidBrush(black), new RectangleF(0, 0, page.Graphics.ClientSize.Width, 130)); g.DrawRectangle(new PdfSolidBrush(white), new RectangleF(0, 400, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height - 450)); g.DrawString("Syncfusion", headerFont, new PdfSolidBrush(violet), new PointF(10, 20)); g.DrawRectangle(new PdfSolidBrush(violet), new RectangleF(10, 63, 155, 35)); g.DrawString("File Formats", subHeadingFont, new PdfSolidBrush(black), new PointF(45, 70)); PdfLayoutResult result = HeaderPoints("Optimized for usage in a server environment where spread and low memory usage in critical.", 15); result = HeaderPoints("Proven, reliable platform thousands of users over the past 10 years.", result.Bounds.Bottom + 15); result = HeaderPoints("Microsoft Excel, Word, Presentation, PDF and PDF Viewer.", result.Bounds.Bottom + 15); result = HeaderPoints("Why start from scratch? Rely on our dependable solution frameworks.", result.Bounds.Bottom + 15); result = BodyContent("Deployment-ready framework tailored to your needs.", result.Bounds.Bottom + 45); result = BodyContent("Enable your applications to read and write file formats documents easily.", result.Bounds.Bottom + 25); result = BodyContent("Solutions available for web, desktop, and mobile applications.", result.Bounds.Bottom + 25); result = BodyContent("Backed by our end-to-end product maintenance infrastructure.", result.Bounds.Bottom + 25); result = BodyContent("The quickest path from concept to delivery.", result.Bounds.Bottom + 25); PdfPen redPen = new PdfPen(PdfBrushes.Red, 2); g.DrawLine(redPen, new PointF(40, result.Bounds.Bottom + 92), new PointF(40, result.Bounds.Bottom + 145)); float headerBulletsXposition = 40; PdfTextElement txtElement = new PdfTextElement("The Experts"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 90, 450, 200)); PdfPen violetPen = new PdfPen(PdfBrushes.Violet, 2); g.DrawLine(violetPen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 92), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 145)); txtElement = new PdfTextElement("Accurate Estimates"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 90, 450, 200)); txtElement = new PdfTextElement("A substantial number of .NET reporting applications use our frameworks."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200)); txtElement = new PdfTextElement("Given our expertise, you can expect estimates to be accurate."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200)); PdfPen greenPen = new PdfPen(PdfBrushes.Green, 2); g.DrawLine(greenPen, new PointF(40, result.Bounds.Bottom + 32), new PointF(40, result.Bounds.Bottom + 85)); txtElement = new PdfTextElement("No-Hassle Licensing"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 30, 450, 200)); PdfPen bluePen = new PdfPen(PdfBrushes.Blue, 2); g.DrawLine(bluePen, new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 32), new PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 85)); txtElement = new PdfTextElement("About Syncfusion"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 30, 450, 200)); txtElement = new PdfTextElement("No royalties, run time, or server deployment fees means no surprises."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200)); txtElement = new PdfTextElement("Syncfusion is the enterprise technology partner of choice for software development, delivering a board range of web, mobile, and desktop controls."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200)); Stream imgStream = typeof(GettingStartedPDF).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Xamarin_bannerEdit.jpg"); g.DrawImage(PdfImage.FromStream(imgStream), 180, 630, 280, 150); g.DrawString("All trademarks mentioned belong to their owners.", new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic), PdfBrushes.White, new PointF(10, g.ClientSize.Height - 30)); PdfTextWebLink linkAnnot = new PdfTextWebLink(); linkAnnot.Url = "http://www.syncfusion.com"; linkAnnot.Text = "www.syncfusion.com"; linkAnnot.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic); linkAnnot.Brush = PdfBrushes.White; linkAnnot.DrawTextWebLink(page, new PointF(g.ClientSize.Width - 100, g.ClientSize.Height - 30)); MemoryStream stream = new MemoryStream(); doc.Save(stream); doc.Close(true); if (stream != null) { SaveiOS iosSave = new SaveiOS(); iosSave.Save("GettingStarted.pdf", "application/pdf", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } private PdfLayoutResult BodyContent(string text, float yPosition) { float headerBulletsXposition = 35; PdfTextElement txtElement = new PdfTextElement("3"); txtElement.Font = new PdfStandardFont(PdfFontFamily.ZapfDingbats, 16); txtElement.Brush = new PdfSolidBrush(violet); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; txtElement.Draw(page, new RectangleF(headerBulletsXposition, yPosition, 320, 100)); txtElement = new PdfTextElement(text); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 17); txtElement.Brush = new PdfSolidBrush(white); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; PdfLayoutResult result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 25, yPosition, 450, 130)); return result; } private PdfLayoutResult HeaderPoints(string text, float yPosition) { float headerBulletsXposition = 220; PdfTextElement txtElement = new PdfTextElement("l"); txtElement.Font = new PdfStandardFont(PdfFontFamily.ZapfDingbats, 10); txtElement.Brush = new PdfSolidBrush(violet); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; txtElement.Draw(page, new RectangleF(headerBulletsXposition, yPosition, 300, 100)); txtElement = new PdfTextElement(text); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11); txtElement.Brush = new PdfSolidBrush(white); txtElement.StringFormat = new PdfStringFormat(); txtElement.StringFormat.WordWrap = PdfWordWrapType.Word; txtElement.StringFormat.LineLimit = true; PdfLayoutResult result = txtElement.Draw(page, new RectangleF(headerBulletsXposition + 20, yPosition, 320, 100)); return result; } } } <file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/ListViewPullToRefresh/ListViewPullToRefresh.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ListViewPullToRefresh.xaml.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using Core; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A sampleView that contains the ListViewPullToRefresh sample. /// </summary> public partial class ListViewPullToRefresh : SampleView { /// <summary> /// Initializes a new instance of the <see cref="ListViewPullToRefresh" /> class. /// </summary> public ListViewPullToRefresh() { this.InitializeComponent(); } } }<file_sep>/Forms/TabView/TabView/Samples/TabViewGettingStarted/View/ProductView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Globalization; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfTabView { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ProductView : ViewCell { public ProductView() { InitializeComponent(); } } public class CustomFrame: Frame { } public class ProductViewFontConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (Device.RuntimePlatform == "Android") { return "Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; } else if (Device.RuntimePlatform == "iOS") { return "Segoe MDL2 Assets"; } else { #if COMMONSB return "/Assets/Fonts/Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; #else if (Core.SampleBrowser.IsIndividualSB) { return "/Assets/Fonts/Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; } else { return $"ms-appx:///SampleBrowser.SfTabView.UWP/Assets/Fonts/Segoe MDL2 Assets.ttf#Segoe MDL2 Assets"; // "SampleBrowser.SfTabView.UWP\\Assets/Fonts/NestedTab.ttf#NestedTab"; } #endif } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/SegmentedControl/SegementViewGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.iOS.Buttons; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class SegementViewGettingStarted : SampleView { SfSegmentedControl segmentedView,colorSegmentedView,sizeSegmentedView; UILabel clothTypeLabel, clothNameLabel, clothPriceLabel, colorLabel, sizeLabel, descriptionLabel, descriptionText, fontIconText; internal ObservableCollection<SfSegmentItem> SizeCollection; internal ObservableCollection<string> SettingCollection = new ObservableCollection<string>(); internal ObservableCollection<SfSegmentItem> EntertainCollection = new ObservableCollection<SfSegmentItem>(); internal ObservableCollection<string> ClothTypeCollection = new ObservableCollection<string>(); internal ObservableCollection<string> SwitchCollection; internal ObservableCollection<SfSegmentItem> PrimaryColors = new ObservableCollection<SfSegmentItem>(); public SegementViewGettingStarted() { segmentedView = new SfSegmentedControl(); colorSegmentedView = new SfSegmentedControl(); sizeSegmentedView = new SfSegmentedControl(); fontIconText = new UILabel(); AddCollection(); //SegmentedView segmentedView.ItemsSource = ClothTypeCollection; segmentedView.FontColor = UIColor.Black; segmentedView.Font = UIFont.SystemFontOfSize(12); segmentedView.CornerRadius = 20; segmentedView.SegmentHeight = 40; segmentedView.SegmentWidth = 20; segmentedView.BackgroundColor = UIColor.Clear; segmentedView.VisibleSegmentsCount = 3; segmentedView.SelectedIndex = 0; segmentedView.BorderThickness = 1; segmentedView.BorderColor = UIColor.FromRGB(63, 63, 63); segmentedView.SelectionTextColor = UIColor.FromRGB(2, 160, 174); segmentedView.SelectionChanged += SegmentedView_SelectionChanged; segmentedView.SelectionIndicatorSettings = new SelectionIndicatorSettings() { Color = UIColor.Clear, CornerRadius = 20 }; clothTypeLabel = new UILabel(); clothTypeLabel.Text = "A"; clothTypeLabel.TextAlignment = UITextAlignment.Center; clothTypeLabel.Font = UIFont.FromName("Segmented", 115); clothTypeLabel.TextColor = UIColor.FromRGB(0, 141, 127); clothNameLabel = new UILabel(); clothNameLabel.Text = "Best trendy outfits for men."; clothNameLabel.Font = UIFont.SystemFontOfSize(12); clothNameLabel.TextColor = UIColor.FromRGB(63, 63, 63); clothNameLabel.TextAlignment = UITextAlignment.Left; clothPriceLabel = new UILabel(); clothPriceLabel.Text="$300"; clothPriceLabel.Font=UIFont.FromName("Helvetica-Bold", 10f); colorLabel = new UILabel(); colorLabel.Text = "Color"; colorLabel.Font = UIFont.FromName("Helvetica-Bold", 10f); //ColorSegmentedView colorSegmentedView.ItemsSource = PrimaryColors; colorSegmentedView.CornerRadius = 3; colorSegmentedView.SegmentHeight = 50; colorSegmentedView.SegmentWidth = 20; colorSegmentedView.BorderThickness = 1; colorSegmentedView.BackgroundColor = UIColor.Clear; colorSegmentedView.BorderColor = UIColor.FromRGB(238, 238, 238); colorSegmentedView.SelectedIndex = 6; colorSegmentedView.Font = UIFont.SystemFontOfSize(8); colorSegmentedView.FontIconFontColor = UIColor.Black; colorSegmentedView.SelectionTextColor = UIColor.FromRGB(0, 141, 127); colorSegmentedView.VisibleSegmentsCount = 7; colorSegmentedView.SegmentCornerRadius = 15; colorSegmentedView.DisplayMode = SegmentDisplayMode.Image; colorSegmentedView.SelectionIndicatorSettings = new SelectionIndicatorSettings() { Color = UIColor.FromRGB(238, 238, 238), Position = SelectionIndicatorPosition.Fill }; colorSegmentedView.SelectionChanged += ColorSegmentedView_SelectionChanged; //SizeSegment sizeLabel = new UILabel(); sizeLabel.Text = "Size"; sizeLabel.Font = UIFont.FromName("Helvetica-Bold", 10f); sizeSegmentedView.ItemsSource = SizeCollection; sizeSegmentedView.CornerRadius = 25; sizeSegmentedView.BorderColor = UIColor.Black; sizeSegmentedView.SelectionTextColor =UIColor.White; sizeSegmentedView.DisplayMode = SegmentDisplayMode.Image; sizeSegmentedView.Font = UIFont.SystemFontOfSize(16); sizeSegmentedView.FontIconFontColor = UIColor.Black; sizeSegmentedView.VisibleSegmentsCount = 5; sizeSegmentedView.SegmentHeight = 50; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { sizeSegmentedView.BorderThickness = 3; } else { sizeSegmentedView.BorderThickness = 1; } sizeSegmentedView.SegmentWidth = 20; sizeSegmentedView.SelectionIndicatorSettings = new SelectionIndicatorSettings() { Color = UIColor.FromRGB(44, 123, 188), Position = SelectionIndicatorPosition.Fill }; //Description Segement descriptionLabel = new UILabel(); descriptionLabel.Text = "Description"; descriptionLabel.Font = UIFont.FromName("Helvetica-Bold", 10f); descriptionText = new UILabel(); descriptionText.Text = "95% Polyester, 5% Spandex, imported, machine wash, casual wear. This outfit keeps you cool and comfortable in quick-dry fabric that wicks away moisture."; descriptionText.Font = UIFont.SystemFontOfSize(10); descriptionText.Lines = 5; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { clothTypeLabel.Font = UIFont.FromName("Segmented", 250); clothNameLabel.Font = UIFont.SystemFontOfSize(20); clothPriceLabel.Font = UIFont.FromName("Helvetica-Bold", 20f); colorLabel.Font = UIFont.FromName("Helvetica-Bold", 20f); sizeLabel.Font = UIFont.FromName("Helvetica-Bold", 20f); descriptionLabel.Font = UIFont.FromName("Helvetica-Bold", 20f); descriptionText.Font = UIFont.SystemFontOfSize(18); } //Add Views this.AddSubview(segmentedView); this.AddSubview(clothTypeLabel); this.AddSubview(clothNameLabel); this.AddSubview(clothPriceLabel); this.AddSubview(colorLabel); this.AddSubview(colorSegmentedView); this.AddSubview(sizeLabel); this.AddSubview(sizeSegmentedView); this.AddSubview(descriptionLabel); this.AddSubview(descriptionText); } private void AddCollection() { ClothTypeCollection.Add("Formals"); ClothTypeCollection.Add("Casuals"); ClothTypeCollection.Add("Trendy"); UIFont fontFamily = UIFont.FromName("Segmented", 10f); UIFont colorfontFamily = UIFont.FromName("Segoe MDL2 Assets", 32f); SwitchCollection = new ObservableCollection<string>() { "", "" }; SizeCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){Text = "A", IconFont="XS"}, new SfSegmentItem(){Text = "A", IconFont="S"}, new SfSegmentItem(){Text = "A", IconFont="M"}, new SfSegmentItem(){Text = "A", IconFont="L"}, new SfSegmentItem(){Text = "A", IconFont="XL"}, }; SettingCollection = new ObservableCollection<string> { "Off", "Manual", "Auto" }; EntertainCollection = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "A", FontIconFontColor=UIColor.FromRGB(35,58,126), FontIconFont = fontFamily}, new SfSegmentItem(){IconFont = "A", FontIconFontColor=UIColor.FromRGB(126,129,136), FontIconFont = fontFamily}, new SfSegmentItem(){IconFont = "A", FontIconFontColor=UIColor.FromRGB(41,38,57), FontIconFont = fontFamily}, new SfSegmentItem(){IconFont = "A", FontIconFontColor=UIColor.FromRGB(17,117,109), FontIconFont = fontFamily}, new SfSegmentItem(){IconFont = "A", FontIconFontColor=UIColor.FromRGB(110,0,34), FontIconFont = fontFamily}, }; PrimaryColors = new ObservableCollection<SfSegmentItem> { new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=UIColor.FromRGB(50,49,142), Text="Square",Font=UIFont.SystemFontOfSize(32), FontIconFont = colorfontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=UIColor.FromRGB(47,125,192), Text="Square",Font=UIFont.SystemFontOfSize(32), FontIconFont = colorfontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=UIColor.FromRGB(149,51,118), Text="Square",Font=UIFont.SystemFontOfSize(32), FontIconFont = colorfontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=UIColor.FromRGB(179,63,63), Text="Square",Font=UIFont.SystemFontOfSize(32), FontIconFont = colorfontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=UIColor.FromRGB(241,151,63), Text="Square",Font=UIFont.SystemFontOfSize(32), FontIconFont = colorfontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=UIColor.FromRGB(201,214,86), Text="Square",Font=UIFont.SystemFontOfSize(32), FontIconFont = colorfontFamily}, new SfSegmentItem(){IconFont = "\uE91F", FontIconFontColor=UIColor.FromRGB(0,141,127), Text="Square",Font=UIFont.SystemFontOfSize(32), FontIconFont = colorfontFamily}, }; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { segmentedView.Frame = new CGRect(100, 40, view.Frame.Width -230, 40); clothTypeLabel.Frame = new CGRect(230, 130, 300, 250); clothNameLabel.Frame = new CGRect(10, 380, view.Frame.Width, 30); clothPriceLabel.Frame = new CGRect(10, 420, view.Frame.Width, 30); colorLabel.Frame = new CGRect(10, 460, view.Frame.Width, 30); colorSegmentedView.Frame = new CGRect(100, 500, view.Frame.Width-200, 50); sizeLabel.Frame = new CGRect(10, 570, view.Frame.Width, 30); sizeSegmentedView.Frame = new CGRect(100, 600, view.Frame.Width -230, 50); descriptionLabel.Frame = new CGRect(10, 680, view.Frame.Width, 30); descriptionText.Frame = new CGRect(10, 720, view.Frame.Width, 120); } else { segmentedView.Frame = new CGRect(10, 30, view.Frame.Width-20, 40); clothTypeLabel.Frame = new CGRect(100, 80, 120, 100); clothNameLabel.Frame = new CGRect(5, 200, view.Frame.Width, 10); clothPriceLabel.Frame = new CGRect(5, 215, view.Frame.Width, 15); colorLabel.Frame = new CGRect(5, 240, view.Frame.Width, 10); colorSegmentedView.Frame = new CGRect(5, 260, view.Frame.Width-12, 50); sizeLabel.Frame = new CGRect(5, 320, view.Frame.Width, 10); sizeSegmentedView.Frame = new CGRect(10, 340, view.Frame.Width -20, 50); descriptionLabel.Frame = new CGRect(10, 410, view.Frame.Width, 10); descriptionText.Frame = new CGRect(10, 420, view.Frame.Width, 55); } } base.LayoutSubviews(); } void SegmentedView_SelectionChanged(object sender, SelectionChangedEventArgs e) { var index = e.Index; if (index == 0) { fontIconText.Text = "A"; } else if (index == 1) { fontIconText.Text = "B"; } else { fontIconText.Text = "C"; } this.clothTypeLabel.Text = fontIconText.Text; } void ColorSegmentedView_SelectionChanged(object sender, SelectionChangedEventArgs e) { this.colorSegmentedView.SelectionTextColor = PrimaryColors[e.Index].FontIconFontColor; this.clothTypeLabel.TextColor = PrimaryColors[e.Index].FontIconFontColor; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Styles/Dark.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "Dark.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using Syncfusion.SfDataGrid; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Derived from DataGridStyle to add the custom styles /// </summary> public class Dark : DataGridStyle { /// <summary> /// Initializes a new instance of the Dark class. /// </summary> public Dark() { } /// <summary> /// Overrides this method to write a custom style for header back ground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetHeaderBackgroundColor() { return Color.FromRgb(33, 33, 33); } /// <summary> /// Overrides this method to write a custom style for header foreground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetHeaderForegroundColor() { return Color.FromRgb(255, 255, 255); } /// <summary> /// Overrides this method to write a custom style for record background color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetRecordBackgroundColor() { return Color.FromRgb(0, 0, 0); } /// <summary> /// Overrides this method to write a custom style for record foreground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetRecordForegroundColor() { return Color.FromRgb(255, 255, 255); } /// <summary> /// Overrides this method to write a custom style for selection background color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetSelectionBackgroundColor() { return Color.FromRgb(85, 85, 85); } /// <summary> /// Overrides this method to write a custom style for selection foreground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetSelectionForegroundColor() { return Color.FromRgb(255, 255, 255); } /// <summary> /// Overrides this method to write a custom style for caption summary row background color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetCaptionSummaryRowBackgroundColor() { return Color.FromRgb(02, 02, 02); } /// <summary> /// Overrides this method to write a custom style for caption summary row background color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetCaptionSummaryRowForegroundColor() { return Color.FromRgb(255, 255, 255); } /// <summary> /// Overrides this method to write a custom style for border color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetBorderColor() { return Color.FromRgb(81, 83, 82); } /// <summary> /// Overrides this method to write a alternate row back ground color /// </summary> /// <returns>Returns From R g b Color</returns> public override Color GetAlternatingRowBackgroundColor() { return Color.FromRgb(46, 46, 46); } /// <summary> /// Overrides this method to write a Grid line visibility /// </summary> /// <returns>Returns GridLinesVisibility Horizontal</returns> public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Horizontal; } } }<file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/PullToRefreshDemo Helper/CustomScroll.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using UIKit; namespace SampleBrowser { public class CustomScroll: UIScrollView { public CustomScroll() { } public CustomScroll(CGRect frame) : base(frame) { Frame = frame; } public override void SetContentOffset(CoreGraphics.CGPoint contentOffset, bool animated) { if (contentOffset.Y == -64) { contentOffset.Y = 0; } base.SetContentOffset(contentOffset, animated); } } } <file_sep>/Forms/ListView/ListView/Samples/SortingFiltering/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Syncfusion.ListView.XForms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class SortingFilteringViewModel : INotifyPropertyChanged { #region Fields private ListViewSortOptions sortingOptions; #endregion #region Constructor public SortingFilteringViewModel() { AddItemDetails(); } #endregion #region Properties public ObservableCollection<TaskInfo> Items { get; set; } /// <summary> /// Gets or sets the value whether indicates the sorting options, ascending or descending or none. /// </summary> public ListViewSortOptions SortingOptions { get { return sortingOptions; } set { sortingOptions = value; OnPropertyChanged("SortingOptions"); } } #endregion #region Methods private void AddItemDetails() { Items = new ObservableCollection<TaskInfo>(); var random = new Random(); for (int i = 0; i < Features.Count(); i++) { var details = new TaskInfo() { Title = Features[i], Description = Description[i], Tag = Tags[random.Next(0, 4)], }; Items.Add(details); } } string[] Tags = new string[] { "Feature Implementation", "Bug Fixing", "Testing", "Design", "Post Processing" }; string[] Features = new string[] { "Drag and drop", "Swiping", "Pull To Refresh", "Selection in row header", "Multiple selection color", "Animating the selected row", "Long press event", "Double click event", "Header Template", "Orientation for ListView", "Multi-line text", "Item Border", "Item Style", "Scroll to a row/column index", "Group expand", "Enabling / disabling the bouncing behavior", "Group collapse", "Auto row height", }; string[] Description = new string[] { "Rearrange the columns by dragging and dropping them", "Enables the users to swipe", "Pull To Refresh action refreshes the grid", "Apply selection using row header", "Apply different selection colors for different rows", "Add an animation upon selecting a row", "Users can listen to LongPresses in the listview", "Users can listen to double taps in the listview", "Load custom views as templates in header cells", "Orientation are vertical, horizontal", "Displays multi-line text for the record", "Enable item border", "Set the items style", "Scroll to a particular row and/or column index", "Expand groups in runtime", "Enable/disable the bouncing of the grid when over-scrolled", "Collapse groups in runtime", "Automatically adjusts the height of item to fit the content", }; #endregion #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } public enum ListViewSortOptions { None, Ascending, Descending } } <file_sep>/Forms/ParallaxView/ParallaxView/Samples/ParallaxView/ParallaxView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Reflection; using SampleBrowser.Core; using Syncfusion.ListView.XForms; using Syncfusion.XForms.ParallaxView; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfParallaxView { [Preserve(AllMembers = true)] public partial class ParallaxView : SampleView { public ParallaxView() { InitializeComponent(); Assembly assembly = typeof(ParallaxView).GetTypeInfo().Assembly; image.Source = ImageSource.FromFile("ParallaxWallpaper.png"); listview.ItemsSource = viewModel.GetItemSource(); parallaxview.Source = listview; speed_slider.BindingContext = viewModel; speed_value.BindingContext = speed_slider; } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Area.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class Area : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Average Sales Comparison"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.Visibility = Visibility.Visible; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.ToggleSeriesVisibility = true; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; NumericalAxis categoryaxis = new NumericalAxis(); categoryaxis.Minimum = 2000; categoryaxis.Maximum = 2005; categoryaxis.Interval = 1; categoryaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; categoryaxis.Title.Text = "Year"; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Minimum = 2; numericalaxis.Maximum = 5; numericalaxis.Interval = 1; numericalaxis.Title.Text = "Revenue in Millions"; numericalaxis.LabelStyle.LabelFormat = "#'M '"; chart.SecondaryAxis = numericalaxis; var areaSeries1 = new AreaSeries { Label = "Product A", Alpha = 0.5f, EnableAnimation= true, ItemsSource = MainPage.GetAreaData1(), XBindingPath = "XValue", YBindingPath = "YValue", LegendIcon = ChartLegendIcon.SeriesType }; var areaSeries2 = new AreaSeries { Label = "Product B", Alpha = 0.5f, EnableAnimation = true, ItemsSource = MainPage.GetAreaData2(), XBindingPath = "XValue", YBindingPath = "YValue", LegendIcon = ChartLegendIcon.SeriesType }; chart.Series.Add(areaSeries1); chart.Series.Add(areaSeries2); areaSeries1.TooltipEnabled = true; areaSeries2.TooltipEnabled = true; areaSeries1.EnableAnimation = true; areaSeries2.EnableAnimation = true; return chart; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/OrderInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; using UIKit; using Foundation; namespace SampleBrowser { public class OrderInfo : INotifyPropertyChanged { public OrderInfo () { } #region private variables private string _orderID; private string _employeeID; private string _customerID; private string _firstname; private string _lastname; private string _gender; private string _shipCity; private string _shipCountry; private string _freight; private DateTime _shippingDate; private bool _isClosed; #endregion #region Public Properties [Preserve] public string OrderID { get { return _orderID; } set { this._orderID = value; RaisePropertyChanged ("OrderID"); } } [Preserve] public string EmployeeID { get { return _employeeID; } set { this._employeeID = value; RaisePropertyChanged ("EmployeeID"); } } [Preserve] public string CustomerID { get { return _customerID; } set { this._customerID = value; RaisePropertyChanged ("CustomerID"); } } [Preserve] public string FirstName { get { return _firstname; } set { this._firstname = value; RaisePropertyChanged ("FirstName"); } } [Preserve] public string LastName { get { return _lastname; } set { this._lastname = value; RaisePropertyChanged ("LastName"); } } [Preserve] public string Gender { get { return _gender; } set { this._gender = value; RaisePropertyChanged ("Gender"); } } [Preserve] public string ShipCity { get { return _shipCity; } set { this._shipCity = value; RaisePropertyChanged ("ShipCity"); } } [Preserve] public string ShipCountry { get { return _shipCountry; } set { this._shipCountry = value; RaisePropertyChanged ("ShipCountry"); } } [Preserve] public string Freight { get { return _freight; } set { this._freight = value; RaisePropertyChanged ("Freight"); } } [Preserve] public bool IsClosed { get { return _isClosed; } set { this._isClosed = value; RaisePropertyChanged ("IsClosed"); } } [Preserve] public DateTime ShippingDate { get { return _shippingDate; } set { this._shippingDate = value; RaisePropertyChanged ("ShippingDate"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged (String Name) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (Name)); } #endregion } } <file_sep>/Forms/Schedule/Schedule/Samples/TimelineView/Behaviors/TimelineViewBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using System; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { internal class TimelineViewBehavior : Behavior<SampleView> { /// <summary> /// schedule initialize /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule schedule; /// <summary> /// view picker /// </summary> private Picker viewPicker; /// <summary> /// Resource view mode picker /// </summary> //private Picker viewModePicker; /// <summary> /// Resource view switch. /// </summary> private Switch showResourceView; /// <summary> /// TimelineView settings /// </summary> private TimelineViewSettings timelineViewSettings; /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(SampleView bindable) { if (bindable == null) { return; } base.OnAttachedTo(bindable); this.schedule = bindable.Content.FindByName<Syncfusion.SfSchedule.XForms.SfSchedule>("Schedule"); if(Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { this.schedule.TimeIntervalHeight = -1; } else if (Device.RuntimePlatform == "iOS") { this.schedule.TimeIntervalHeight = 80; } this.timelineViewSettings = new TimelineViewSettings(); this.timelineViewSettings.DaysCount = 7; this.SetDateFormat(); this.schedule.ScheduleView = ScheduleView.TimelineView; this.schedule.ResourceViewMode = ResourceViewMode.Absolute; this.schedule.ShowResourceView = true; if (Device.Idiom == TargetIdiom.Phone) { this.schedule.ResourceViewHeight = Device.RuntimePlatform == Device.iOS ? 75 : 100; } this.schedule.TimeInterval = 720; this.schedule.ViewHeaderStyle.DateFontSize = this.schedule.HeaderStyle.FontSize; this.schedule.TimelineViewSettings = this.timelineViewSettings; if (Device.RuntimePlatform == Device.Android) { this.schedule.ViewHeaderHeight = 70; } else if (Device.RuntimePlatform == Device.iOS) { this.schedule.ViewHeaderHeight = 30; } this.viewPicker = bindable.FindByName<Picker>("viewPicker"); if (this.viewPicker == null) { return; } this.viewPicker.SelectedIndex = 1; this.viewPicker.SelectedIndexChanged += this.ViewPicker_SelectedIndexChanged; //this.viewModePicker = bindable.FindByName<Picker>("viewModePicker"); //if (this.viewModePicker == null) //{ // return; //} //this.viewModePicker.SelectedIndex = 1; //this.viewModePicker.SelectedIndexChanged += OnViewModePickerSelectedIndexChanged; this.showResourceView = bindable.FindByName<Switch>("showResourceView"); if (this.showResourceView == null) { return; } this.showResourceView.Toggled += OnShowResourceViewToggled; } /// <summary> /// Method to show resource view /// </summary> /// <param name="sender">Return the object</param> /// <param name="e">Event args</param> private void OnShowResourceViewToggled(object sender, ToggledEventArgs e) { if ((sender as Switch).IsToggled) { this.schedule.ShowResourceView = true; } else { this.schedule.ShowResourceView = false; } } /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); if (this.viewPicker != null) { this.viewPicker.SelectedIndexChanged -= this.ViewPicker_SelectedIndexChanged; this.viewPicker = null; } //if (this.viewModePicker != null) //{ // this.viewModePicker.SelectedIndexChanged -= OnViewModePickerSelectedIndexChanged; // this.viewModePicker = null; //} if (this.showResourceView != null) { this.showResourceView.Toggled -= OnShowResourceViewToggled; this.showResourceView = null; } if (this.schedule != null) { this.schedule = null; } } /// <summary> /// Method for schedule view selection /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void ViewPicker_SelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: this.timelineViewSettings.NonWorkingsDays = new System.Collections.ObjectModel.ObservableCollection<DayOfWeek>(); this.timelineViewSettings.DaysCount = 1; this.schedule.TimeInterval = 60; break; case 1: this.timelineViewSettings.NonWorkingsDays = new System.Collections.ObjectModel.ObservableCollection<DayOfWeek>(); this.timelineViewSettings.DaysCount = 7; this.schedule.TimeInterval = 720; break; case 2: this.timelineViewSettings.NonWorkingsDays = new System.Collections.ObjectModel.ObservableCollection<DayOfWeek>() { DayOfWeek.Sunday, DayOfWeek.Saturday }; this.timelineViewSettings.DaysCount = 5; this.schedule.TimeInterval = 720; break; } this.SetDateFormat(); } /// <summary> /// Method for schedule resource view mode selection. /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void OnViewModePickerSelectedIndexChanged(object sender, EventArgs e) { switch ((sender as Picker).SelectedIndex) { case 0: this.schedule.ResourceViewMode = ResourceViewMode.Selection; if (Device.Idiom == TargetIdiom.Phone) { this.schedule.ResourceViewHeight = Device.RuntimePlatform == Device.iOS ? 100 : 150; } break; case 1: this.schedule.ResourceViewMode = ResourceViewMode.Absolute; if (Device.Idiom == TargetIdiom.Phone) { this.schedule.ResourceViewHeight = Device.RuntimePlatform == Device.iOS ? 75 : 100; } break; } } /// <summary> /// Sets the date format for timeline view. /// </summary> private void SetDateFormat() { string dateFormat; if (this.timelineViewSettings.DaysCount == 1) { dateFormat = Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS ? "dd EEEE" : "%d dddd"; } else { dateFormat = Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS ? "dd EEE" : "%d ddd"; } timelineViewSettings.LabelSettings.DateFormat = dateFormat; } } }<file_sep>/iOS/SampleBrowser/Samples/Calendar/CalendarInlineEvents.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfCalendar.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class CalendarInlineEvents : SampleView { private SFCalendar calendar; private UIView calendarView = new UIView(); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public CalendarInlineEvents() { //Calendar calendar = new SFCalendar(); calendar.Appointments = GetEnglishAppointments(); calendar.EnableInLine = true; calendar.ViewMode = SFCalendarViewMode.SFCalendarViewModeMonth; calendar.HeaderHeight = 40; this.AddSubview(calendar); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { calendarView.AddSubview(calendar); this.AddSubview(calendarView); } } private NSMutableArray GetEnglishAppointments() { NSDate today = new NSDate(); SetColors(); SetEnglishCollectionSubjects(); NSMutableArray appCollection = new NSMutableArray(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; Random randomNumber = new Random(); for (int i = 0; i < 10; i++) { components.Hour = randomNumber.Next(10, 16); endDateComponents.Hour = components.Hour + randomNumber.Next(1, 3); NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); SFAppointment appointment = new SFAppointment(); appointment.StartTime = startDate; appointment.EndTime = endDate; components.Day = components.Day + 1; endDateComponents.Day = endDateComponents.Day + 1; appointment.Subject = (NSString)englishCollection[i]; appointment.AppointmentBackground = colorCollection[i]; appCollection.Add(appointment); } return appCollection; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { if (view is SFCalendar) { view.Frame = new CGRect(this.Frame.X, -2, Frame.Size.Width, Frame.Size.Height); } calendarView.Frame = new CGRect(0, 0, this.Frame.Size.Width, this.Frame.Size.Height); calendar.Frame = new CGRect(0, 0, this.Frame.Size.Width, this.Frame.Size.Height); } base.LayoutSubviews(); } private List<string> englishCollection; private void SetEnglishCollectionSubjects() { englishCollection = new List<string>(); englishCollection.Add("GoToMeeting"); englishCollection.Add("Business Meeting"); englishCollection.Add("Conference"); englishCollection.Add("Project Status Discussion"); englishCollection.Add("Auditing"); englishCollection.Add("Client Meeting"); englishCollection.Add("Generate Report"); englishCollection.Add("Target Meeting"); englishCollection.Add("General Meeting"); englishCollection.Add("Pay House Rent"); englishCollection.Add("Car Service"); englishCollection.Add("Medical Check Up"); englishCollection.Add("Wedding Anniversary"); englishCollection.Add("Sam's Birthday"); englishCollection.Add("Jenny's Birthday"); englishCollection.Add("Master Checkup"); englishCollection.Add("Hospital"); englishCollection.Add("Phone Bill Payment"); englishCollection.Add("Project Plan"); englishCollection.Add("Auditing"); englishCollection.Add("Client Meeting"); englishCollection.Add("Generate Report"); englishCollection.Add("Target Meeting"); englishCollection.Add("General Meeting"); englishCollection.Add("Play Golf"); englishCollection.Add("Car Service"); englishCollection.Add("Medical Check Up"); englishCollection.Add("Mary's Birthday"); englishCollection.Add("John's Birthday"); englishCollection.Add("Micheal's Birthday"); } // adding colors collection private List<UIColor> colorCollection; private void SetColors() { colorCollection = new List<UIColor>(); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0xF0, 0x96, 0x09)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x1B, 0xA1, 0xE2)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0xA2, 0xC1, 0x39)); colorCollection.Add(UIColor.FromRGB(0xD8, 0x00, 0x73)); colorCollection.Add(UIColor.FromRGB(0x33, 0x99, 0x33)); colorCollection.Add(UIColor.FromRGB(0xE6, 0x71, 0xB8)); colorCollection.Add(UIColor.FromRGB(0x00, 0xAB, 0xA9)); } public class SchedulePickerModel : UIPickerViewModel { private readonly IList<string> values; public event EventHandler<SchedulePickerChangedEventArgs> PickerChanged; public SchedulePickerModel(IList<string> values) { this.values = values; } #if __UNIFIED__ public override nint GetComponentCount(UIPickerView picker) { return 1; } public override nint GetRowsInComponent(UIPickerView picker, nint component) { return values.Count; } public override string GetTitle(UIPickerView picker, nint row, nint component) { return values[(int)row]; } public override nfloat GetRowHeight(UIPickerView picker, nint component) { return 30f; } public override void Selected(UIPickerView picker, nint row, nint component) { if (this.PickerChanged != null) { this.PickerChanged(this, new SchedulePickerChangedEventArgs { SelectedValue = values[(int)row] }); } } #else public override int GetComponentCount (UIPickerView picker) { return 1; } public override int GetRowsInComponent (UIPickerView picker, int component) { return values.Count; } public override string GetTitle (UIPickerView picker, int row, int component) { return values[(int)row]; } public override nfloat GetRowHeight (UIPickerView picker, int component) { return 30f; } public override void Selected (UIPickerView picker, int row, int component) { if (this.PickerChanged != null) { this.PickerChanged(this, new SchedulePickerChangedEventArgs{SelectedValue = values[(int)row]}); } } #endif } public class SchedulePickerChangedEventArgs : EventArgs { public string SelectedValue { get; set; } } } }<file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/UICollectionViewInPullToRefresh.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; using Syncfusion.SfPullToRefresh; using System.Threading.Tasks; using CoreGraphics; namespace SampleBrowser { public class UICollectionViewInPullToRefresh : SampleView { SfPullToRefresh pullToRefresh; UICollectionView collectionView; CollectionViewSource collectionViewSource; UICollectionViewFlowLayout collectionViewFlowLayout; public UICollectionViewInPullToRefresh() { this.pullToRefresh = new SfPullToRefresh(); this.pullToRefresh.Refreshing += PullToRefresh_Refreshing; this.pullToRefresh.TransitionType = TransitionType.Push; this.collectionViewFlowLayout = new UICollectionViewFlowLayout() { MinimumLineSpacing = 0.5f, ScrollDirection = UICollectionViewScrollDirection.Vertical, }; this.collectionView = new UICollectionView(CGRect.Empty, collectionViewFlowLayout); this.collectionView.ShowsHorizontalScrollIndicator = false; this.collectionViewSource = new CollectionViewSource(); this.collectionView.DataSource = this.collectionViewSource; this.collectionView.RegisterClassForCell(typeof(CollectionViewCell), CollectionViewCell.CellID); this.pullToRefresh.PullableContent = this.collectionView; this.pullToRefresh.PullableContent.BackgroundColor = UIColor.LightGray; this.AddSubview(this.pullToRefresh); this.OptionView = new Options(pullToRefresh); } private async void PullToRefresh_Refreshing(object sender, RefreshingEventArgs e) { await Task.Delay(3000); this.collectionViewSource.repository.RefreshItemSource(); this.collectionView.ReloadData(); e.Refreshed = true; } public override void LayoutSubviews() { base.LayoutSubviews(); this.pullToRefresh.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); this.collectionViewFlowLayout.ItemSize = new CGSize(this.Frame.Width, 70); } protected override void Dispose(bool disposing) { if (disposing) { if (pullToRefresh != null) { this.pullToRefresh.Refreshing -= PullToRefresh_Refreshing; this.pullToRefresh.Dispose(); } } base.Dispose(disposing); } } }<file_sep>/Android/SampleBrowser/Samples/BusyIndicator/BusyIndicator_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.Content; using Android.Views; using Android.Widget; using Com.Syncfusion.Sfbusyindicator; using Android.Graphics; using Com.Syncfusion.Sfbusyindicator.Enums; namespace SampleBrowser { public class BusyIndicator_Mobile { /********************************* **Local Variable Inizialisation** *********************************/ TextView animationTypeText, spaceAdderText1, spaceAdderText2; SfBusyIndicator sfBusyIndicator; Spinner animationSpinner; public View GetSampleContent(Context con) { SamplePageContent(con); /****************** **BusyIndicator** ******************/ sfBusyIndicator = new SfBusyIndicator(con); sfBusyIndicator.IsBusy = true; sfBusyIndicator.TextColor = Color.Rgb(62, 101, 254); sfBusyIndicator.AnimationType = AnimationTypes.DoubleCircle; sfBusyIndicator.ViewBoxWidth = 133; sfBusyIndicator.ViewBoxHeight = 133; sfBusyIndicator.TextSize = 60; sfBusyIndicator.Title = ""; sfBusyIndicator.SetBackgroundColor(Color.Rgb(255, 255, 255)); //main view LinearLayout mainView = GetView(con); return mainView; } private LinearLayout GetView(Context con) { //linearLayout LinearLayout linearLayout = new LinearLayout(con); linearLayout.SetPadding(20, 20, 20, 30); linearLayout.SetBackgroundColor(Color.Rgb(236, 235, 242)); linearLayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); linearLayout.Orientation = Orientation.Vertical; linearLayout.AddView(animationTypeText); linearLayout.AddView(spaceAdderText2); linearLayout.AddView(animationSpinner); linearLayout.AddView(spaceAdderText1); linearLayout.AddView(sfBusyIndicator); return linearLayout; } private void SamplePageContent(Context con) { //Animation Spinner animationSpinner = new Spinner(con,SpinnerMode.Dialog); animationSpinner.SetMinimumHeight(60); animationSpinner.DropDownWidth = 500; animationSpinner.SetBackgroundColor(Color.Gray); //Animation List List<String> animationList = new List<String>(); animationList.Add("Ball"); animationList.Add("Battery"); animationList.Add("DoubleCircle"); animationList.Add("ECG"); animationList.Add("Globe"); animationList.Add("HorizontalPulsingBox"); animationList.Add("MovieTimer"); animationList.Add("Print"); animationList.Add("Rectangle"); animationList.Add("RollingBall"); animationList.Add("SingleCircle"); animationList.Add("SlicedCircle"); animationList.Add("ZoomingTarget"); animationList.Add("Gear"); //Data Adapter ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (con, Android.Resource.Layout.SimpleSpinnerItem, animationList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); animationSpinner.Adapter = dataAdapter; animationSpinner.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs>(animationSpinner_ItemSelected); //Animation Text animationTypeText = new TextView(con); animationTypeText.TextSize = 20; animationTypeText.Text = "Animation Types"; //Space Adder Text1 spaceAdderText1 = new TextView(con); spaceAdderText1.TextSize = 10; animationTypeText.SetTextColor(Color.Black); //Space Adder Text2 spaceAdderText2 = new TextView(con); spaceAdderText2.TextSize = 10; spaceAdderText2.SetTextColor(Color.Black); } /***************************************** **Animation Spinner ItemSelected Method** *****************************************/ private void animationSpinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner animationSpinner = (Spinner)sender; String selectedItem = animationSpinner.GetItemAtPosition(e.Position).ToString(); if (selectedItem.Equals("Ball")) { sfBusyIndicator.ViewBoxWidth = 130; sfBusyIndicator.ViewBoxHeight = 130; sfBusyIndicator.Duration = 1000; sfBusyIndicator.TextColor = Color.ParseColor("#243FD9"); sfBusyIndicator.AnimationType = AnimationTypes.Ball; } else if (selectedItem.Equals("Battery")) { sfBusyIndicator.ViewBoxWidth = 80; sfBusyIndicator.ViewBoxHeight = 80; sfBusyIndicator.Duration = 300; sfBusyIndicator.TextColor = Color.ParseColor("#A70015"); sfBusyIndicator.AnimationType = AnimationTypes.Battery; } else if (selectedItem.Equals("DoubleCircle")) { sfBusyIndicator.ViewBoxWidth = 80; sfBusyIndicator.ViewBoxHeight = 80; sfBusyIndicator.Duration = 1800; sfBusyIndicator.TextColor = Color.ParseColor("#958C7B"); sfBusyIndicator.AnimationType = AnimationTypes.DoubleCircle; } else if (selectedItem.Equals("ECG")) { sfBusyIndicator.ViewBoxWidth = 80; sfBusyIndicator.ViewBoxHeight = 80; sfBusyIndicator.Duration = 1500; sfBusyIndicator.TextColor = Color.ParseColor("#DA901A"); sfBusyIndicator.AnimationType = AnimationTypes.Ecg; } else if (selectedItem.Equals("Globe")) { sfBusyIndicator.ViewBoxWidth = 80; sfBusyIndicator.ViewBoxHeight = 80; sfBusyIndicator.Duration = 800; sfBusyIndicator.TextColor = Color.ParseColor("#9EA8EE"); sfBusyIndicator.AnimationType = AnimationTypes.Globe; } else if (selectedItem.Equals("HorizontalPulsingBox")) { sfBusyIndicator.ViewBoxWidth = 100; sfBusyIndicator.ViewBoxHeight = 100; sfBusyIndicator.Duration = 500; sfBusyIndicator.TextColor = Color.ParseColor("#E42E06"); sfBusyIndicator.AnimationType = AnimationTypes.HorizontalPulsingBox; } else if (selectedItem.Equals("MovieTimer")) { sfBusyIndicator.ViewBoxWidth = 80; sfBusyIndicator.ViewBoxHeight = 80; sfBusyIndicator.Duration = 800; sfBusyIndicator.TextColor = Color.ParseColor("#2d2d2d"); sfBusyIndicator.SecondaryColor = Color.ParseColor("#9b9b9b"); sfBusyIndicator.AnimationType = AnimationTypes.MovieTimer; } else if (selectedItem.Equals("Print")) { sfBusyIndicator.ViewBoxWidth = 80; sfBusyIndicator.ViewBoxHeight = 80; sfBusyIndicator.Duration = 1000; sfBusyIndicator.TextColor = Color.ParseColor("#5E6FF8"); sfBusyIndicator.AnimationType = AnimationTypes.Print; } else if (selectedItem.Equals("Rectangle")) { sfBusyIndicator.ViewBoxWidth = 100; sfBusyIndicator.ViewBoxHeight = 100; sfBusyIndicator.Duration = 500; sfBusyIndicator.TextColor = Color.ParseColor("#27AA9E"); sfBusyIndicator.AnimationType = AnimationTypes.Rectangle; } else if (selectedItem.Equals("RollingBall")) { sfBusyIndicator.ViewBoxWidth = 80; sfBusyIndicator.ViewBoxHeight = 80; sfBusyIndicator.Duration = 1000; sfBusyIndicator.TextColor = Color.ParseColor("#2d2d2d"); sfBusyIndicator.SecondaryColor = Color.White; sfBusyIndicator.AnimationType = AnimationTypes.RollingBall; } else if (selectedItem.Equals("SingleCircle")) { sfBusyIndicator.ViewBoxWidth = 70; sfBusyIndicator.ViewBoxHeight = 70; sfBusyIndicator.Duration = 2000; sfBusyIndicator.TextColor = Color.ParseColor("#AF2541"); sfBusyIndicator.AnimationType = AnimationTypes.SingleCircle; } else if (selectedItem.Equals("SlicedCircle")) { sfBusyIndicator.ViewBoxWidth = 60; sfBusyIndicator.ViewBoxHeight = 60; sfBusyIndicator.Duration = 3000; sfBusyIndicator.TextColor = Color.ParseColor("#779772"); sfBusyIndicator.AnimationType = AnimationTypes.SlicedCircle; } else if (selectedItem.Equals("ZoomingTarget")) { sfBusyIndicator.ViewBoxWidth = 80; sfBusyIndicator.ViewBoxHeight = 80; sfBusyIndicator.Duration = 600; sfBusyIndicator.TextColor = Color.ParseColor("#ED8F3C"); sfBusyIndicator.AnimationType = AnimationTypes.ZoomingTarget; } else if (selectedItem.Equals("Gear")) { sfBusyIndicator.ViewBoxWidth = 80; sfBusyIndicator.ViewBoxHeight = 80; sfBusyIndicator.Duration = 1500; sfBusyIndicator.TextColor = Color.Gray; sfBusyIndicator.AnimationType = AnimationTypes.GearBox; } } } } <file_sep>/Android/SampleBrowser/Samples/Kanban/KanbanData.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Collections.ObjectModel; using Syncfusion.SfKanban.Android; using Android.Graphics; using Android.Graphics.Drawables; namespace SampleBrowser { public class CustomKanbanModel : KanbanModel { public string Name { get; set; } } class KanbanData { public ObservableCollection<CustomKanbanModel> Data { get; set; } public KanbanData() { Data = ItemsSourceCards(); } ObservableCollection<CustomKanbanModel> ItemsSourceCards() { ObservableCollection<CustomKanbanModel> cards = new ObservableCollection<CustomKanbanModel>(); cards.Add( new CustomKanbanModel() { ID = 1, Title = "iOS - 1", ImageURL = "user.png", Category = "Open", Description = "Analyze customer requirements", ColorKey = "Red", Tags = new string[] { "Bug", "Customer", "Release Bug" } } ); cards.Add( new CustomKanbanModel() { ID = 6, Title = "Xamarin - 6", ImageURL = "user1.png", Category = "Open", Description = "Show the retrived data from the server in grid control", ColorKey = "Red", Tags = new string[] { "Bug", "Customer", "Breaking Issue" } } ); cards.Add( new CustomKanbanModel() { ID = 3, Title = "iOS - 3", ImageURL = "user2.png", Category = "Open", Description = "Fix the filtering issues reported in safari", ColorKey = "Red", Tags = new string[] { "Bug", "Customer", "Breaking Issue" } } ); cards.Add( new CustomKanbanModel() { ID = 11, Title = "iOS - 11", ImageURL = "user3.png", Category = "Open", Description = "Add input validation for editing", ColorKey = "Red", Tags = new string[] { "Bug", "Customer", "Breaking Issue" } } ); cards.Add( new CustomKanbanModel() { ID = 15, Title = "Android - 15", Category = "Open", ImageURL = "user4.png", Description = "Arrange web meeting for cutomer requirement", ColorKey = "Red", Tags = new string[] { "Story", "Kanban" } }); cards.Add( new CustomKanbanModel() { ID = 3, Title = "Android - 3", Category = "Code Review", ImageURL = "user5.png", Description = "API Improvements", ColorKey = "Purple", Tags = new string[] { "Bug", "Customer" } }); cards.Add( new CustomKanbanModel() { ID = 4, Title = "UWP - 4", ImageURL = "user.png", Category = "Code Review", Description = "Enhance editing functionality", ColorKey = "Brown", Tags = new string[] { "Story", "Kanban" } }); cards.Add( new CustomKanbanModel() { ID = 9, Title = "Xamarin - 9", ImageURL = "user1.png", Category = "Code Review", Description = "Improve application performance", ColorKey = "Orange", Tags = new string[] { "Story", "Kanban" } } ); cards.Add( new CustomKanbanModel() { ID = 13, Title = "UWP - 13", ImageURL = "user3.png", Category = "In Progress", Description = "Add responsive support to applicaton", ColorKey = "Brown", Tags = new string[] { "Story", "Kanban" } } ); cards.Add( new CustomKanbanModel() { ID = 17, Title = "Xamarin - 17", Category = "In Progress", ImageURL = "user5.png", Description = "Fix the issues reported in IE browser", ColorKey = "Brown", Tags = new string[] { "Bug", "Customer" } } ); cards.Add( new CustomKanbanModel() { ID = 21, Title = "Xamarin - 21", Category = "In Progress", ImageURL = "user2.png", Description = "Improve performance of editing functionality", ColorKey = "Purple", Tags = new string[] { "Bug", "Customer" } } ); cards.Add( new CustomKanbanModel() { ID = 19, Title = "iOS - 19", Category = "In Progress", ImageURL = "user4.png", Description = "Fix the issues reported by the customer", ColorKey = "Purple", Tags = new string[] { "Bug" } } ); cards.Add( new CustomKanbanModel() { ID = 8, Title = "Android", Category = "Code Review", ImageURL = "user.png", Description = "Check login page validation", ColorKey = "Brown", Tags = new string[] { "Feature" } } ); cards.Add( new CustomKanbanModel() { ID = 24, Title = "UWP - 24", ImageURL = "user1.png", Category = "In Progress", Description = "Test editing functionality", ColorKey = "Orange", Tags = new string[] { "Feature", "Customer", "Release" } } ); cards.Add( new CustomKanbanModel() { ID = 20, Title = "iOS - 20", Category = "In Progress", ImageURL = "user4.png", Description = "Fix the issues reported in data binding", ColorKey = "Red", Tags = new string[] { "Feature", "Release", } } ); cards.Add( new CustomKanbanModel() { ID = 12, Title = "Xamarin - 12", Category = "In Progress", ImageURL = "user5.png", Description = "Test editing functionality", ColorKey = "Red", Tags = new string[] { "Feature", "Release", } } ); cards.Add( new CustomKanbanModel() { ID = 11, Title = "iOS - 11", Category = "In Progress", ImageURL = "user1.png", Description = "Check filtering validation", ColorKey = "Red", Tags = new string[] { "Feature", "Release", } } ); cards.Add( new CustomKanbanModel() { ID = 13, Title = "UWP - 13", ImageURL = "user.png", Category = "Closed", Description = "Fix cannot open user's default database sql error", ColorKey = "Purple", Tags = new string[] { "Bug", "Internal", "Release" } }); cards.Add( new CustomKanbanModel() { ID = 14, Title = "Android - 14", Category = "Closed", ImageURL = "user3.png", Description = "Arrange web meeting with customer to get login page requirement", ColorKey = "Red", Tags = new string[] { "Feature" } } ); cards.Add( new CustomKanbanModel() { ID = 15, Title = "Xamarin - 15", Category = "Closed", ImageURL = "user5.png", Description = "Login page validation", ColorKey = "Red", Tags = new string[] { "Bug" } } ); cards.Add( new CustomKanbanModel() { ID = 16, Title = "Xamarin - 16", ImageURL = "user.png", Category = "Closed", Description = "Test the application in IE browser", ColorKey = "Purple", Tags = new string[] { "Bug" } } ); cards.Add( new CustomKanbanModel() { ID = 20, Title = "UWP - 20", ImageURL = "user5.png", Category = "Closed", Description = "Analyze stored procedure", ColorKey = "Brown", Tags = new string[] { "CustomSample", "Customer", "Incident" } } ); cards.Add( new CustomKanbanModel() { ID = 21, Title = "Android - 21", Category = "Closed", ImageURL = "user4.png", Description = "Arrange web meeting with customer to get editing requirements", ColorKey = "Orange", Tags = new string[] { "Story", "Improvement" } } ); cards.Add( new CustomKanbanModel() { ID = 1, Title = "Margherita", ImageURL = "margherita.png", Category = "Menu", Description = "The classic. Fresh tomatoes, garlic, olive oil, and basil. For pizza purists and minimalists only", Tags = new string[] { "Cheese" } } ); cards.Add( new CustomKanbanModel() { ID = 2, Title = "Double Cheese Margherita", ImageURL = "doublecheesemargherita.png", Category = "Menu", Description = "The minimalist classic with a double helping of cheese", Tags = new string[] { "Cheese" } } ); cards.Add( new CustomKanbanModel() { ID = 3, Title = "Bucolic Pie", ImageURL = "bucolicpie.png", Category = "Menu", Description = "The pizza you daydream about to escape city life. Onions, peppers, and tomatoes.", Tags = new string[] { "Onions", "Capsicum" } } ); cards.Add( new CustomKanbanModel() { ID = 4, Title = "Bumper Crop", ImageURL = "bumpercrop.png", Category = "Menu", Description = "Can't get enough veggies? Eat this. Carrots, mushrooms, potatoes, and way more.", Tags = new string[] { "Tomato", "Mushroom" } } ); cards.Add( new CustomKanbanModel() { ID = 5, Title = "Spice of Life", ImageURL = "spiceoflife.png", Category = "Menu", Description = "Thrill-seeking, heat-seeking pizza people only. It's hot. Trust us", Tags = new string[] { "Corn", "Gherkins" } } ); cards.Add( new CustomKanbanModel() { ID = 6, Title = "Very Nicoise", ImageURL = "verynicoise.png", Category = "Menu", Description = "Anchovies, Dijon vinaigrette, shallots, red peppers, and potatoes.", Tags = new string[] { "Red pepper", "Capsicum" } } ); cards.Add( new CustomKanbanModel() { ID = 8, Title = "Salad Daze", ImageURL = "saladdaze.png", Category = "Menu", Description = "Pretty much salad on a pizza. Broccoli, olives, cherry tomatoes, red onion.", Tags = new string[] { "Capsicum", "Mushroom" } } ); cards.Add( new CustomKanbanModel() { ID = 9, Title = "Margherita", ImageURL = "margherita.png", Category = "Delivery", Description = "The classic. Fresh tomatoes, garlic, olive oil, and basil. For pizza purists and minimalists only", Tags = new string[] { "Cheese" } } ); cards.Add( new CustomKanbanModel() { ID = 10, Title = "Double Cheese Margherita", ImageURL = "doublecheesemargherita.png", Category = "Ready", Description = "The minimalist classic with a double helping of cheese", Tags = new string[] { "Cheese" } } ); cards.Add( new CustomKanbanModel() { ID = 11, Title = "Bucolic Pie", ImageURL = "bucolicpie.png", Category = "Dining", Description = "The pizza you daydream about to escape city life. Onions, peppers, and tomatoes.", Tags = new string[] { "Onions", "Capsicum" } } ); cards.Add( new CustomKanbanModel() { ID = 12, Title = "Bumper Crop", ImageURL = "bumpercrop.png", Category = "Ready", Description = "Can't get enough veggies? Eat this. Carrots, mushrooms, potatoes, and way more.", Tags = new string[] { "Tomato", "Mushroom" } } ); cards.Add( new CustomKanbanModel() { ID = 13, Title = "Spice of Life", ImageURL = "spiceoflife.png", Category = "Ready", Description = "Thrill-seeking, heat-seeking pizza people only. It's hot. Trust us", Tags = new string[] { "Corn", "Gherkins" } } ); cards.Add( new CustomKanbanModel() { ID = 14, Title = "Very Nicoise", ImageURL = "verynicoise.png", Category = "Dining", Description = "Anchovies, Dijon vinaigrette, shallots, red peppers, and potatoes.", Tags = new string[] { "Red pepper", "Capsicum" } } ); cards.Add( new CustomKanbanModel() { ID = 16, Title = "Salad Daze", ImageURL = "saladdaze.png", Category = "Delivery", Description = "Pretty much salad on a pizza. Broccoli, olives, cherry tomatoes, red onion.", Tags = new string[] { "Capsicum", "Mushroom" } } ); cards.Add( new CustomKanbanModel() { ID = 17, Title = "<NAME>", ImageURL = "bumpercrop.png", Category = "Door Delivery", Description = "Can't get enough veggies? Eat this. Carrots, mushrooms, potatoes, and way more.", Tags = new string[] { "Tomato", "Mushroom" } } ); cards.Add( new CustomKanbanModel() { ID = 18, Title = "Spice of Life", ImageURL = "spiceoflife.png", Category = "Door Delivery", Description = "Thrill-seeking, heat-seeking pizza people only. It's hot. Trust us", Tags = new string[] { "Corn", "Gherkins" } } ); return cards; } } }<file_sep>/iOS/SampleBrowser/.github/PULL_REQUEST_TEMPLATE/bugTemplate.md **Bug description** * Clearly and concisely describe the problem or feature (this cannot be empty). **Root cause** * Briefly describe the root cause and analysis of the problem. * If there is an internal discussion on the forum, provide the link. **Reason for not identifying earlier** * Explain how it was missed in our earlier testing and development. This will help prevent similar mistakes in the future. ***Guidelines/documents are not followed*** * Common guidelines / Core team guideline * Specification document * Requirement document ***Guidelines/documents are not given*** * Common guidelines / Core team guideline * Specification document * Requirement document ***Reason:*** Mention any one or more reasons from the above points. ***Action taken:*** What action did you take to avoid this in future? ***Related areas:*** Is there any other related areas also to be addressed? **Solution description** * Describe your code changes in detail for reviewers. **Areas affected and ensured** * List the areas affected by your code changes. **Additional checklist** [ ] Doesn’t have memory leak. [ ] Have you ensured the changes in Android API 19 and iOS 9? [ ] Ensured in iOS, Android, UWP and macOS (if supported). <file_sep>/Forms/ListView/ListView/Samples/DataTemplateSelector/Model/MessageInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class MessageInfo : INotifyPropertyChanged { #region Fields private string text; private string profileImage; private String dateTime; private string username; #endregion #region Properties public string Text { get { return text; } set { text = value; OnPropertyChanged("Text"); } } public string ProfileImage { get { return profileImage; } set { profileImage = value; OnPropertyChanged("ProfileImage"); } } public String DateTime { get { return dateTime; } set { dateTime = value; OnPropertyChanged("DateTime"); } } public string Username { get { return username; } set { username = value; OnPropertyChanged("Username"); } } public TemplateType TemplateType { get; set; } #endregion #region Constructor public MessageInfo() { } #endregion #region Interface Member public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string Property = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(Property)); } } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Calendar/CalendarConfiguration_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfCalendar.iOS; using Syncfusion.SfRangeSlider.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class CalendarConfiguration_Tablet :SampleView { SFCalendar calendar; private string selectedType; UILabel label_calendarView; UIButton button_calendarView = new UIButton (); UIButton doneButton=new UIButton(); UIButton showPropertyButton = new UIButton (); UIButton closeButton = new UIButton (); UILabel propertiesLabel = new UILabel (); UIView subView = new UIView (); UIView pickerSubView = new UIView (); UIView contentView = new UIView (); UIView calendarView = new UIView (); UIPickerView selectionPicker=new UIPickerView(); public CalendarConfiguration_Tablet() { //Calendar calendar = new SFCalendar (); calendar.ViewMode = SFCalendarViewMode.SFCalendarViewModeMonth; calendar.Delegate = new CalendarDelegate(); calendar.HeaderHeight = 40; NSMutableArray<NSString> customLabel = new NSMutableArray<NSString>(); customLabel.Add((NSString)"SUN"); customLabel.Add((NSString)"MON"); customLabel.Add((NSString)"TUE"); customLabel.Add((NSString)"WED"); customLabel.Add((NSString)"THU"); customLabel.Add((NSString)"FRI"); customLabel.Add((NSString)"SAT"); calendar.CustomDayLabels = customLabel; //MonthViewSettings SFMonthViewSettings monthSettings = new SFMonthViewSettings (); monthSettings.HeaderFontAttribute = UIFont.SystemFontOfSize(24f); monthSettings.WeekDayFontAttribute = UIFont.FromName("Menlo-Italic", 16f); monthSettings.FontAttribute = UIFont.FromName("Menlo-Regular", 16f); monthSettings.HeaderTextColor = UIColor.White; monthSettings.HeaderBackgroundColor = UIColor.FromRGB (61,61,61); monthSettings.DayLabelTextColor = UIColor.White; monthSettings.DayLabelBackgroundColor = UIColor.FromRGB (61,61,61); monthSettings.DateSelectionColor = UIColor.FromRGB (61,61,61); calendar.MonthViewSettings = monthSettings; this.AddSubview (calendar); this.loadOptionView(); } public void loadOptionView() { PickerModel model = new PickerModel(_calendarViewsCollection); //label label_calendarView = new UILabel(); label_calendarView.Text = "Selection Mode "; label_calendarView.TextColor = UIColor.Black; label_calendarView.Font = UIFont.FromName("Helvetica", 14f); label_calendarView.TextAlignment = UITextAlignment.Left; //button button_calendarView = new UIButton(); button_calendarView.SetTitle("Single Selection", UIControlState.Normal); button_calendarView.SetTitleColor(UIColor.Black, UIControlState.Normal); button_calendarView.Font = UIFont.FromName("Helvetica", 14f); button_calendarView.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_calendarView.Layer.CornerRadius = 8; button_calendarView.Layer.BorderWidth = 2; button_calendarView.TouchUpInside += ShowPicker1; button_calendarView.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //doneButton doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.Font = UIFont.FromName("Helvetica", 14f); doneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); //selectionPicker model.PickerChanged += SelectedIndexChanged1; selectionPicker.Model = model; selectionPicker.ShowSelectionIndicator = true; selectionPicker.Hidden = true; selectionPicker.BackgroundColor = UIColor.Gray; contentView.AddSubview(label_calendarView); contentView.AddSubview(button_calendarView); pickerSubView.AddSubview(selectionPicker); pickerSubView.BackgroundColor = UIColor.Gray; pickerSubView.Hidden = true; contentView.AddSubview(pickerSubView); contentView.AddSubview(doneButton); contentView.BackgroundColor = UIColor.FromRGB(240, 240, 240); subView.AddSubview(contentView); subView.AddSubview(closeButton); subView.AddSubview(propertiesLabel); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); this.AddSubview(subView); //showPropertyButton propertiesLabel.Text = " OPTIONS"; showPropertyButton.Hidden = true; showPropertyButton.SetTitle("OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; }; this.AddSubview(showPropertyButton); //CloseButton closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; }; //AddingGesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer(() => { subView.Hidden = true; showPropertyButton.Hidden = false; } ); propertiesLabel.UserInteractionEnabled = true; propertiesLabel.AddGestureRecognizer(tapgesture); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = new CGRect(Frame.X, -2, Frame.Width, Frame.Height); subView.Frame = new CGRect (0, 4 * this.Frame.Size.Height / 5-25, this.Frame.Size.Width, 2 * this.Frame.Size.Height / 5); contentView.Frame=new CGRect(0,40,subView.Frame.Size.Width,subView.Frame.Size.Height-50); calendarView.Frame = new CGRect (0, 0,this.Frame.Size.Width, this.Frame.Size.Height-30); calendar.Frame = new CGRect (0, 0, this.Frame.Size.Width, this.Frame.Size.Height-30); label_calendarView.Frame = new CGRect ( 110, 70, this.Frame.Size.Width - 220, 30); button_calendarView.Frame = new CGRect (350, 70, contentView.Frame.Size.Width-520, 30); selectionPicker.Frame = new CGRect (105, 0, pickerSubView.Frame.Size.Width-200 , 150); pickerSubView.Frame = new CGRect (100, 0, contentView.Frame.Size.Width - 200, 150); doneButton.Frame = new CGRect(100, 0, contentView.Frame.Size.Width-200, 30); showPropertyButton.Frame = new CGRect (0, this.Frame.Size.Height-25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect (this.Frame.Size.Width - 30, 5, 20, 30); propertiesLabel.Frame = new CGRect (10, 5, this.Frame.Width, 30); } base.LayoutSubviews (); } private readonly IList<string> _calendarViewsCollection = new List<string> { "Single Selection", "Multi Selection" }; void ShowPicker1 (object sender, EventArgs e) { doneButton.Hidden = false; selectionPicker.Hidden = false; button_calendarView.Hidden = true; pickerSubView.Hidden = false; } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; selectionPicker.Hidden = true; button_calendarView.Hidden = false; pickerSubView.Hidden = true; } private void SelectedIndexChanged1(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; if (selectedType == "Single Selection") { calendar.SelectionMode = SFCalenderSelectionMode.SFCalenderSelectionModeSingle; } else if (selectedType == "Multi Selection") { calendar.SelectionMode = SFCalenderSelectionMode.SFCalenderSelectionModeMultiple; }else if (selectedType == "Range Selection") { calendar.SelectionMode = SFCalenderSelectionMode.SFCalenderSelectionModeRange; } button_calendarView.SetTitle(selectedType.ToString(),UIControlState.Normal); } public class CalendarDelegate:SFCalendarDelegate { public override SFMonthCell DidDrawMonthCell (SFCalendar calendar, SFMonthCell monthCell) { NSDate now = monthCell.Date; NSDateFormatter dateFormatter = new NSDateFormatter(); dateFormatter.DateFormat = "EEEE"; NSDateFormatter dateFormatter2 = new NSDateFormatter(); dateFormatter2.DateFormat = "d"; NSString day = (NSString)dateFormatter2.ToString(now); NSString dayname = (NSString)dateFormatter.ToString(now); if (dayname.ToString().Equals("Saturday") || dayname.ToString().Equals("Sunday")) { monthCell.TextColor = UIColor.FromRGB(9, 144, 233); } if (day.ToString().Equals("15") || day.ToString().Equals("24")) { UIImageView view = new UIImageView(); view.Image = UIImage.FromBundle("Shop-Closed.png"); monthCell.View = view; } return monthCell; } } } } <file_sep>/Forms/TreeView/TreeView/Samples/AutoFitContent/Helper/ItemTemplateSelector.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.Core; using Xamarin.Forms.Internals; using Syncfusion.TreeView.Engine; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] #region MessageTemplateSelector public class ItemTemplateSelector : Xamarin.Forms.DataTemplateSelector { #region Properties public DataTemplate ConversationTemplate { get; set; } public DataTemplate ReplyTemplate { get; set; } #endregion #region Constructor public ItemTemplateSelector() { } #endregion #region OnSelectTemplate protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { var node = item as TreeViewNode; var level = node.Level; if (level == 0) return ConversationTemplate; return ReplyTemplate; } #endregion } #endregion } <file_sep>/Forms/ListView/ListView.macOS/AppDelegate.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using AppKit; using Foundation; using Syncfusion.ListView.XForms.MacOS; using Xamarin.Forms; using CoreGraphics; using Xamarin.Forms.Platform.MacOS; using SampleBrowser.Core.MacOS; namespace SampleBrowser.SfListView.MacOS { [Register("AppDelegate")] public class AppDelegate : FormsApplicationDelegate { NSWindow nswindow; public AppDelegate() { var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | NSWindowStyle.Titled; var rect = new CGRect(0, 1000, 200, 200); nswindow = new NSWindow(rect, style, NSBackingStore.Buffered, false); var screenFrame = nswindow.Screen.Frame; nswindow.SetFrame(new CGRect(0, 0, screenFrame.Width, screenFrame.Height), true, true); nswindow.TitleVisibility = NSWindowTitleVisibility.Hidden; } public override NSWindow MainWindow { get { return nswindow; } } public override void DidFinishLaunching(NSNotification notification) { Forms.Init(); LoadApplication(new App()); SfListViewRenderer.Init(); SampleBrowserMac.Init(); base.DidFinishLaunching(notification); } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/StackingArea.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.OS; using Android.Graphics; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Android.Views; namespace SampleBrowser { public class StackingArea : SamplePage { private SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Trend in Sales of Ethical Produce"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis primaryAxis = new CategoryAxis(); primaryAxis.Interval = 2; primaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; primaryAxis.ShowMajorGridLines = false; chart.PrimaryAxis = primaryAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Minimum = 0; numericalAxis.Maximum = 7; numericalAxis.Interval = 1; numericalAxis.Title.Text = "Spends"; numericalAxis.LineStyle.StrokeWidth = 0; numericalAxis.MajorTickStyle.TickSize = 0; numericalAxis.LabelStyle.LabelFormat = "##.##B "; chart.SecondaryAxis = numericalAxis; StackingAreaSeries stackingAreaSeries = new StackingAreaSeries(); stackingAreaSeries.EnableAnimation = true; stackingAreaSeries.ItemsSource = MainPage.GetStackedAreaData1(); stackingAreaSeries.XBindingPath = "XValue"; stackingAreaSeries.YBindingPath = "YValue"; stackingAreaSeries.Label = "Organic"; stackingAreaSeries.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingAreaSeries); StackingAreaSeries stackingAreaSeries1 = new StackingAreaSeries(); stackingAreaSeries1.EnableAnimation = true; stackingAreaSeries1.ItemsSource = MainPage.GetStackedAreaData2(); stackingAreaSeries1.XBindingPath = "XValue"; stackingAreaSeries1.YBindingPath = "YValue"; stackingAreaSeries1.Label = "Fair-trade"; stackingAreaSeries1.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingAreaSeries1); StackingAreaSeries stackingAreaSeries2 = new StackingAreaSeries(); stackingAreaSeries2.EnableAnimation = true; stackingAreaSeries2.ItemsSource = MainPage.GetStackedAreaData3(); stackingAreaSeries2.XBindingPath = "XValue"; stackingAreaSeries2.YBindingPath = "YValue"; stackingAreaSeries2.Label = "Veg Alternatives"; stackingAreaSeries2.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingAreaSeries2); StackingAreaSeries stackingAreaSeries3 = new StackingAreaSeries(); stackingAreaSeries3.EnableAnimation = true; stackingAreaSeries3.ItemsSource = MainPage.GetStackedAreaData4(); stackingAreaSeries3.XBindingPath = "XValue"; stackingAreaSeries3.YBindingPath = "YValue"; stackingAreaSeries3.Label = "Others"; stackingAreaSeries3.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingAreaSeries3); stackingAreaSeries.TooltipEnabled = true; stackingAreaSeries1.TooltipEnabled = true; stackingAreaSeries2.TooltipEnabled = true; stackingAreaSeries3.TooltipEnabled = true; stackingAreaSeries.EnableAnimation = true; stackingAreaSeries1.EnableAnimation = true; stackingAreaSeries2.EnableAnimation = true; stackingAreaSeries3.EnableAnimation = true; return chart; } } }<file_sep>/iOS/SampleBrowser/Samples/CircularGauge/CircularGaugeAnnotation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System;
using Syncfusion.SfGauge.iOS;
using System.Collections.ObjectModel;
using System.Threading.Tasks; #if __UNIFIED__
using Foundation;
using UIKit;
using CoreGraphics;
using System.Drawing; #else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using CGSize = System.Drawing.SizeF;
using nfloat = System.Single;
using System.Drawing;
 #endif
namespace SampleBrowser
{ public class CircularGaugeAnnotation : SampleView { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public SFCircularGauge Gauge { get; set; } public SFCircularGauge Annotation1 { get; set; } public SFCircularGauge Annotation2 { get; set; } public UILabel LabelAnnotation1 { get; set; } public UILabel LabelAnnotation2 { get; set; } public UILabel LabelAnnotation3 { get; set; } bool isDispose = false; public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } if (Utility.IsIPad) { Gauge.Frame = new CGRect(50, 50, (float)this.Frame.Width - 100, (float)this.Frame.Height - 100); } else { Gauge.Frame = new CGRect(10, 10, (float)this.Frame.Width - 20, (float)this.Frame.Height - 20); } base.LayoutSubviews(); } public CircularGaugeAnnotation() { Gauge = new SFCircularGauge(); SFCircularScale scale = new SFCircularScale(); scale.StartValue = 0; scale.EndValue = 12; scale.Interval = 1; scale.Interval = 1; scale.MinorTicksPerInterval = 4; scale.RimColor = UIColor.FromRGB(237, 238, 239); scale.LabelColor = UIColor.Gray; scale.LabelOffset = 0.8f; scale.ScaleEndOffSet = 0.925f; scale.StartAngle = -180; scale.SweepAngle = 180; scale.LabelFont = UIFont.SystemFontOfSize(14); scale.ShowFirstLabel = false; scale.MinorTickSettings = new SFTickSettings { Color = UIColor.Black, StartOffset = 1, EndOffset = .95f, Width = 1 }; scale.MajorTickSettings = new SFTickSettings { Color = UIColor.Black, StartOffset = 1, EndOffset = .9f, Width = 3 }; scale.Ranges = new ObservableCollection<SFCircularRange> { new SFCircularRange {StartValue = 0, EndValue = 3, Color= UIColor.Gray, InnerStartOffset = 0.925f, OuterStartOffset = 1, InnerEndOffset = 0.925f, OuterEndOffset = 1} }; scale.Pointers = new ObservableCollection<SFCircularPointer> { new SFNeedlePointer { EnableAnimation = false, KnobRadius = 6, LengthFactor = .75f, KnobColor = UIColor.White, Color = UIColor.Black, Width = 3.5f, KnobStrokeColor = UIColor.Black, KnobStrokeWidth = 5 , TailLengthFactor = 0.25f, TailColor = UIColor.Black}, new SFNeedlePointer { EnableAnimation = false, KnobRadius = 6, LengthFactor = .4f, KnobColor = UIColor.White, Color = UIColor.Black, Width = 5, PointerType= SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle }, new SFNeedlePointer { EnableAnimation = false, KnobRadius = 6, LengthFactor = .65f, KnobColor = UIColor.White, Color =UIColor.Black, Width = 5, PointerType= SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle}, }; SFGaugeAnnotation anno = new SFGaugeAnnotation(); LabelAnnotation1 = new UILabel { Text = "", Font = UIFont.FromName("Helvetica", 12f), TextColor = UIColor.Black }; LabelAnnotation1.Frame = new CGRect(0, 0, 50, 50); anno.View = LabelAnnotation1; anno.Angle = 00; anno.Offset = 0.5f; SFGaugeAnnotation anno1 = new SFGaugeAnnotation(); LabelAnnotation2 = new UILabel { Text = "", Font = UIFont.FromName("Helvetica", 12f), TextColor = UIColor.Black }; LabelAnnotation2.Frame = new CGRect(0, 0, 50, 50); anno1.View = LabelAnnotation2; anno1.Angle = 300; anno1.Offset = 0.6f; Annotation1 = new SFCircularGauge() { Scales = new ObservableCollection<SFCircularScale> { new SFCircularScale() { StartAngle = -180, SweepAngle = 180, ShowLabels = false, StartValue = 0, EndValue = 60, Interval = 5, RimColor = UIColor.FromRGB(237, 238, 239), Ranges = new ObservableCollection<SFCircularRange> { new SFCircularRange() {StartValue = 0, EndValue = 30, Color = UIColor.Gray, InnerStartOffset = 0.925f, OuterStartOffset = 1, InnerEndOffset = 0.925f, OuterEndOffset = 1} , }, MajorTickSettings = new SFTickSettings { Color = UIColor.Black, StartOffset = 1, EndOffset = .85f, Width = 2f }, MinorTickSettings = new SFTickSettings { Color = UIColor.Black, StartOffset = 1, EndOffset = .90f, Width = 0.5f }, Pointers = new ObservableCollection<SFCircularPointer> { new SFNeedlePointer { PointerType = SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle, KnobRadius = 4, Width = 3, EnableAnimation = false, KnobColor = UIColor.Black, Color = UIColor.Black } } } } }; Annotation1.Annotations.Add(anno1); Annotation1.Frame = new CGRect(0, 0, 70, 70); SFGaugeAnnotation anno2 = new SFGaugeAnnotation(); anno2.View = Annotation1; anno2.Angle = 90; anno2.Offset = 0.5f; SFGaugeAnnotation anno3 = new SFGaugeAnnotation(); LabelAnnotation3 = new UILabel { Text = "", Font = UIFont.FromName("Helvetica", 12f), TextColor = UIColor.Black }; LabelAnnotation3.Frame = new CGRect(10, 10, 50, 50); anno3.View = LabelAnnotation3; anno3.Angle = 300; anno3.Offset = 0.55f; Annotation2 = new SFCircularGauge { Scales = new ObservableCollection<SFCircularScale> { new SFCircularScale() { StartAngle = -180, SweepAngle = 180, StartValue = 0, EndValue = 60, Interval = 5, ShowLabels = false, RimColor = UIColor.FromRGB(237, 238, 239), Ranges = new ObservableCollection<SFCircularRange> { new SFCircularRange() {StartValue = 0, EndValue = 30, Color = UIColor.Gray, InnerStartOffset = 0.925f, OuterStartOffset = 1, InnerEndOffset = 0.925f, OuterEndOffset = 1} , }, MajorTickSettings = new SFTickSettings { Color = UIColor.Black, StartOffset = 1, EndOffset = .85f, Width = 2 }, MinorTickSettings = new SFTickSettings { Color = UIColor.Black, StartOffset = 1, EndOffset = .90f, Width = 0.5f }, Pointers = new ObservableCollection<SFCircularPointer> { new SFNeedlePointer { PointerType = SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle, KnobRadius = 4, Width = 3, EnableAnimation = false, KnobColor = UIColor.Black, Color = UIColor.Black } } } } }; Annotation2.Annotations.Add(anno3); Annotation2.Frame = new CGRect(0, 0, 70, 70); SFGaugeAnnotation anno4 = new SFGaugeAnnotation(); anno4.View = Annotation2; anno4.Angle = 180; anno4.Offset = 0.5f; Gauge.Scales.Add(scale); Gauge.Annotations.Add(anno); Gauge.Annotations.Add(anno2); Gauge.Annotations.Add(anno4); DynamicUpdate(); this.AddSubview(Gauge); } private async void DynamicUpdate() { while (!isDispose) { var dataTime = DateTime.Now; var hour = (double)dataTime.Hour; hour = hour > 12 ? hour % 12 : hour; var min = (double)dataTime.Minute; var sec = (double)dataTime.Second; if (Gauge.Scales.Count > 0) { Gauge.Scales[0].Pointers[0].Value = (nfloat)sec / 5; Gauge.Scales[0].Pointers[1].Value = (nfloat)(hour + min / 60); Gauge.Scales[0].Pointers[2].Value = (nfloat)(min / 5 + (sec / 60 * .2)); Annotation1.Scales[0].Pointers[0].Value = (nfloat)sec; Annotation2.Scales[0].Pointers[0].Value = (nfloat)(min + sec / 60); var meridiem = dataTime.Hour > 12 ? "PM" : "AM"; LabelAnnotation1.Text = hour.ToString() + " : " + min.ToString() + " " + meridiem; LabelAnnotation2.Text = sec.ToString() + " S"; LabelAnnotation3.Text = min.ToString() + " M"; await Task.Delay(1000); } } } protected override void Dispose(bool disposing) { isDispose = disposing; base.Dispose(disposing); } }
}

<file_sep>/Forms/ListView/ListView/Samples/PullToRefresh/Helper/Behaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DataSource; using Syncfusion.ListView.XForms; using Syncfusion.SfPullToRefresh.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.Core; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] #region PullToRefreshBehavior public class SfListViewPullToRefreshBehavior : Behavior<SampleView> { #region Fields private ListViewPullToRefreshViewModel pulltoRefreshViewModel; private Syncfusion.ListView.XForms.SfListView ListView; private Syncfusion.SfPullToRefresh.XForms.SfPullToRefresh pullToRefresh = null; private PickerExt picker; #endregion #region Overrides protected override void OnAttachedTo(SampleView bindable) { ListView = bindable.FindByName<Syncfusion.ListView.XForms.SfListView>("listView"); picker = bindable.FindByName<PickerExt>("transitionTypePicker"); picker.SelectedIndexChanged += Picker_SelectedIndexChanged; pullToRefresh = bindable.FindByName<Syncfusion.SfPullToRefresh.XForms.SfPullToRefresh>("pullToRefresh"); pullToRefresh.Refreshing += PullToRefresh_Refreshing; pulltoRefreshViewModel = new ListViewPullToRefreshViewModel(); pulltoRefreshViewModel.Navigation = bindable.Navigation; ListView.BindingContext = pulltoRefreshViewModel; ListView.ItemsSource = pulltoRefreshViewModel.BlogsInfo; picker.Items.Add("SlideOnTop"); picker.Items.Add("Push"); picker.SelectedIndex = 1; base.OnAttachedTo(bindable); } private void Picker_SelectedIndexChanged(object sender, EventArgs e) { if (picker.SelectedIndex == 0) { pullToRefresh.RefreshContentThreshold = 0; pullToRefresh.TransitionMode = TransitionType.SlideOnTop; } else { pullToRefresh.RefreshContentThreshold = 50; pullToRefresh.TransitionMode = TransitionType.Push; } } #endregion #region Private Methods private async void PullToRefresh_Refreshing(object sender, EventArgs args) { pullToRefresh.IsRefreshing = true; await Task.Delay(2000); var blogsTitleCount = pulltoRefreshViewModel.BlogsTitle.Count() - 1; if ((pulltoRefreshViewModel.BlogsInfo.Count - 1) == blogsTitleCount) { pullToRefresh.IsRefreshing = false; return; } var blogsCategoryCount = pulltoRefreshViewModel.BlogsCategory.Count() - 1; var blogsAuthorCount = pulltoRefreshViewModel.BlogsAuthers.Count() - 1; var blogsReadMoreCount = pulltoRefreshViewModel.BlogsReadMoreInfo.Count() - 1; for (int i = 0; i < 3; i++) { var blogsCount = pulltoRefreshViewModel.BlogsInfo.Count; var item = new ListViewBlogsInfo() { BlogTitle = pulltoRefreshViewModel.BlogsTitle[blogsTitleCount - blogsCount], BlogAuthor = pulltoRefreshViewModel.BlogsAuthers[blogsAuthorCount - blogsCount], BlogCategory = pulltoRefreshViewModel.BlogsCategory[blogsCategoryCount - blogsCount], ReadMoreContent = pulltoRefreshViewModel.BlogsReadMoreInfo[blogsReadMoreCount - blogsCount], }; pulltoRefreshViewModel.BlogsInfo.Insert(0, item); } pullToRefresh.IsRefreshing = false; } #endregion } #endregion } <file_sep>/Android/SampleBrowser/Samples/PDF/HtmlTextElement.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.Content; using Android.Views; using Android.Widget; using Syncfusion.Pdf; using System.IO; using Syncfusion.Pdf.Graphics; using Syncfusion.Drawing; namespace SampleBrowser { public partial class HtmlTextElement : SamplePage { private Context m_context; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample demonstrates drawing HTML text element in the PDF document."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Generate PDF"; button1.Click += OnButtonClicked; linear.AddView(button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { PdfDocument doc = new PdfDocument(); //Add a page PdfPage page = doc.Pages.Add(); PdfSolidBrush brush = new PdfSolidBrush(Syncfusion.Drawing.Color.Black); PdfPen pen = new PdfPen(Syncfusion.Drawing.Color.Black, 1f); //Create font PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 11.5f); PdfFont heading = new PdfStandardFont(PdfFontFamily.TimesRoman, 12, PdfFontStyle.Bold); font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f); page.Graphics.DrawString("Create, Read, and Edit PDF Files from C#, VB.NET", heading, PdfBrushes.Black, new RectangleF(0, 0, page.GetClientSize().Width, 20), new PdfStringFormat(PdfTextAlignment.Center)); string longText = "The <b> Syncfusion Essential PDF </b> is a feature-rich and high-performance .NET PDF library that allows you to add robust PDF functionalities to any .NET application." + "It allows you to create, read, and edit PDF documents programmatically without Adobe dependencies. This library also offers functionality to <font color='#0000F8'> merge, split, stamp, form-fill, compress, and secure PDF files.</font>" + "<br/><br/><font color='#FF3440'><b>1. Secure your PDF with advanced encryption, digital signatures, and redaction.</b></font>" + "<br/><br/><font color='#FF9E4D'><b>2. Extract text and images from your PDF files.</b></font>" + "<br/><br/><font color='#4F6200'><b>3. Top features: forms, tables, barcodes; stamp, split, and merge PDFs.</b></font>"; //Rendering HtmlText PdfHTMLTextElement richTextElement = new PdfHTMLTextElement(longText, font, brush); // Formatting Layout PdfLayoutFormat format = new PdfLayoutFormat(); format.Layout = PdfLayoutType.OnePage; //Drawing htmlString richTextElement.Draw(page, new RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height), format); MemoryStream stream = new MemoryStream(); //Save the PDF dcoument. doc.Save(stream); //Close the PDF document. doc.Close(); stream.Position = 0; if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("HtmlTextElement.pdf", "application/pdf", stream, m_context); } } } }<file_sep>/iOS/SampleBrowser/Samples/DataGrid/ViewModel/DragAndDropViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; namespace SampleBrowser { public class DragAndDropViewModel : INotifyPropertyChanged { public DragAndDropViewModel() { SetRowstoGenerate(100); } #region ItemsSource private OrderDetailsRepository order; private ObservableCollection<OrderInfo> ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; RaisePropertyChanged("OrdersInfo"); } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { order = new OrderDetailsRepository(); ordersInfo = order.GetOrderDetails(count); } #endregion private Random random = new Random(); internal void ItemsSourceRefresh() { var count = random.Next(1, 6); for (int i = 11000; i < 11000 + count; i++) { int val = i + random.Next(100, 150); this.OrdersInfo.Insert(0, order.RefreshItemsource(val)); } } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Forms/LinearGauge/LinearGauge/Samples/Annotation/Annotation.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfLinearGauge { [Preserve(AllMembers = true)] public partial class Annotation : SampleView { public Annotation() { InitializeComponent(); for (int i = 0; i < 7; i++) { if (i >2 && i <6) { gauge.Annotations[i].ViewMargin = new Point(0, 80); } else if(i==6) gauge.Annotations[i].ViewMargin = new Point(0, -80); else { gauge.Annotations[i].ViewMargin = new Point(0, 30); } } } } }<file_sep>/Forms/ListView/ListView/Samples/Grouping/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Syncfusion.ListView.XForms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewGroupingViewModel { #region Fields private ObservableCollection<ListViewContactsInfo> contactsInfo; #endregion #region Constructor public ListViewGroupingViewModel() { GenerateSource(100); } #endregion #region Properties public ObservableCollection<ListViewContactsInfo> ContactsInfo { get { return contactsInfo; } set { this.contactsInfo = value; } } #endregion #region ItemSource public void GenerateSource(int count) { ListViewContactsInfoRepository contactRepository = new ListViewContactsInfoRepository(); contactsInfo = contactRepository.GetContactDetails(count); } #endregion } } <file_sep>/Forms/PdfViewer/PdfViewer/Samples/Helper/BookmarkHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.Pdf.Interactive; using Syncfusion.Pdf.Parsing; using Syncfusion.XForms.TabView; using Syncfusion.XForms.TextInputLayout; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfPdfViewer { internal class BookmarkToolbar : Grid { internal AbsoluteLayout absoluteLayoutContainer = new AbsoluteLayout(); internal ListView bookmarkView; internal ListView customBookmarkView; List<PdfBookmark> navigationQueue = new List<PdfBookmark>(); IList<ContentBookmark> listViewItemsSource; Syncfusion.SfPdfViewer.XForms.SfPdfViewer pdfViewer; Grid parentGrid; internal bool isBookmarkPaneVisible = false; internal PdfLoadedDocument bookmarkLoadedDocument; Syncfusion.XForms.TabView.SfTabView tabView = new Syncfusion.XForms.TabView.SfTabView(); private Grid tabviewHeader_Content; private Grid tabviewHeader_Bookmark; internal Frame toastMessageFrame; Frame contextOptionsFrame; internal Label messageLabel; internal SfFontButton AddBookmarkButton; StackLayout contextOptions; StackLayout RenameTextButton; StackLayout DeleteTextButton; SfFontButton RenameIcon; SfFontButton DeleteIcon; Label RenameText; Label DeleteText; internal int selectedCustomBookmarkIndex; private double CustomBookmarkView_ScrollY; PDFViewerCustomToolbar_Phone PDFViewerCustomToolbar_Phone; PDFViewerCustomToolbar_Tablet PDFViewerCustomToolbar_Tablet; Grid tapDetectorGrid; internal Grid NobookmarksLabel { get; set; } internal Grid CustomNobookmarksLabel { get; set; } internal Grid customBookmarkContainer; internal BookmarkToolbar(PDFViewerCustomToolbar_Phone sampleView) { parentGrid = sampleView.parentGrid; pdfViewer = sampleView.pdfViewer; listViewItemsSource = sampleView.listViewItemsSource; PDFViewerCustomToolbar_Phone = sampleView; CreateBookmarkToolbar(); } internal BookmarkToolbar(PDFViewerCustomToolbar_Tablet sampleView) { parentGrid = sampleView.parentGrid; pdfViewer = sampleView.pdfViewer; listViewItemsSource = sampleView.listViewItemsSource; PDFViewerCustomToolbar_Tablet=sampleView; CreateBookmarkToolbar(); } private void CreateBookmarkToolbar() { RowSpacing = 0; ColumnSpacing = 0; BackgroundColor = Color.White; if (Device.Idiom == TargetIdiom.Tablet) { ColumnDefinitions.Add(new ColumnDefinition() { Width = 1 }); ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); } RowDefinitions.Add(new RowDefinition() { Height = 60 }); RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); Grid title = new Grid() { ColumnSpacing = 0, RowSpacing = 0, BackgroundColor = Color.FromHex("#EDEDED") }; title.ColumnDefinitions.Add(new ColumnDefinition() { Width = 40 }); title.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); title.ColumnDefinitions.Add(new ColumnDefinition() { Width = 40 }); title.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); title.RowDefinitions.Add(new RowDefinition() { Height = 1 }); Label bookmarkTitleText = new Label(); bookmarkTitleText.HorizontalOptions = LayoutOptions.Start; bookmarkTitleText.VerticalOptions = LayoutOptions.Center; bookmarkTitleText.Text = "Bookmarks"; bookmarkTitleText.FontSize = 16; bookmarkTitleText.TextColor = Color.FromHex("#000000"); bookmarkTitleText.FontFamily = "Roboto"; bookmarkTitleText.FontAttributes = FontAttributes.Bold; Grid.SetColumn(bookmarkTitleText, 1); Grid.SetRow(bookmarkTitleText, 0); title.Children.Add(bookmarkTitleText); if (Device.Idiom != TargetIdiom.Tablet) { SfFontButton backButton = new SfFontButton() { Text = FontMappingHelper.BookmarkBackward, TextColor = Color.FromHex("8A000000"), BackgroundColor = Color.Transparent, VerticalOptions = LayoutOptions.Center }; backButton.FontFamily = FontMappingHelper.BookmarkFont; backButton.FontSize = 24; backButton.Clicked += BookmarkPaneBackButton_Clicked; backButton.HorizontalOptions = LayoutOptions.CenterAndExpand; backButton.VerticalOptions = LayoutOptions.CenterAndExpand; backButton.VerticalOptions = LayoutOptions.Center; Grid.SetColumn(backButton, 0); Grid.SetRow(backButton, 0); title.Children.Add(backButton); } else { SfFontButton bookmarkCloseButton = new SfFontButton() { Text = FontMappingHelper.Close, TextColor = Color.FromHex("8A000000"), BackgroundColor = Color.Transparent, VerticalOptions = LayoutOptions.Center }; bookmarkCloseButton.FontFamily = FontMappingHelper.FontFamily; bookmarkCloseButton.FontSize = 24; bookmarkCloseButton.Clicked += BookmarkCloseButton_Clicked; bookmarkCloseButton.HorizontalOptions = LayoutOptions.CenterAndExpand; bookmarkCloseButton.VerticalOptions = LayoutOptions.CenterAndExpand; bookmarkCloseButton.VerticalOptions = LayoutOptions.Center; Grid.SetColumn(bookmarkCloseButton, 2); Grid.SetRow(bookmarkCloseButton, 0); title.Children.Add(bookmarkCloseButton); } Frame titleBottomBorder = new Frame() { BackgroundColor = Color.FromHex("#000000"), Opacity = 0.12 }; Grid.SetRow(titleBottomBorder, 1); Grid.SetColumn(titleBottomBorder, 0); Grid.SetColumnSpan(titleBottomBorder, 2); title.Children.Add(titleBottomBorder); if (Device.Idiom == TargetIdiom.Tablet) Grid.SetColumn(title, 1); Grid.SetRow(title, 0); Children.Add(title); NobookmarksLabel = new Grid(); Label label = new Label() { Text = "No Bookmarks", FontSize = 20, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }; NobookmarksLabel.Children.Add(label); CustomNobookmarksLabel = new Grid(); Label customLabel = new Label() { Text = "No Bookmarks", FontSize = 20, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }; CustomNobookmarksLabel.Children.Add(customLabel); if (Device.Idiom == TargetIdiom.Tablet) Grid.SetColumn(absoluteLayoutContainer, 1); Grid.SetRow(absoluteLayoutContainer, 1); Children.Add(absoluteLayoutContainer); bookmarkView = new ListView(ListViewCachingStrategy.RecycleElement); bookmarkView.ItemTapped += BookmarkView_ItemTapped; bookmarkView.SeparatorVisibility = SeparatorVisibility.None; bookmarkView.ItemsSource = listViewItemsSource; bookmarkView.RowHeight = 60; bookmarkView.ItemTemplate = new DataTemplate(() => { ViewCell viewCell = new ViewCell(); Grid view = new Grid() { ColumnSpacing = 0, RowSpacing = 0, BackgroundColor = Color.White }; view.ColumnDefinitions.Add(new ColumnDefinition() { Width = 40 }); view.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); view.ColumnDefinitions.Add(new ColumnDefinition() { Width = 40 }); view.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); view.RowDefinitions.Add(new RowDefinition() { Height = 1 }); Label bookmarkTitle = new Label(); bookmarkTitle.HorizontalOptions = LayoutOptions.Start; bookmarkTitle.LineBreakMode = LineBreakMode.TailTruncation; bookmarkTitle.VerticalOptions = LayoutOptions.Center; //Bind the Text property of the bookmark title label to the Title property of custom bookmark bookmarkTitle.SetBinding(Label.TextProperty, "Title"); bookmarkTitle.TextColor = Color.FromHex("#000000"); bookmarkTitle.Opacity = 0.87; bookmarkTitle.FontFamily = "Roboto"; bookmarkTitle.FontSize = 16; Grid.SetColumn(bookmarkTitle, 1); Grid.SetRow(bookmarkTitle, 0); view.Children.Add(bookmarkTitle); SfFontButton backToParentButton = new SfFontButton() { Text = FontMappingHelper.BookmarkBackward, TextColor = Color.FromHex("8A000000"), BackgroundColor = Color.Transparent }; backToParentButton.FontFamily = FontMappingHelper.BookmarkFont; backToParentButton.FontSize = 24; backToParentButton.Clicked += BackToParentButton_Clicked; backToParentButton.HorizontalOptions = LayoutOptions.CenterAndExpand; backToParentButton.VerticalOptions = LayoutOptions.CenterAndExpand; Grid.SetRow(backToParentButton, 0); Grid.SetColumn(backToParentButton, 0); view.Children.Add(backToParentButton); //Bind the IsVisible property of the backtoparent button to the IsBackToParentButtonVisible property of CustomBookmark backToParentButton.SetBinding(IsVisibleProperty, "IsBackToParentButtonVisible"); SfFontButton expandButton = new SfFontButton() { Text = FontMappingHelper.BookmarkForward, TextColor = Color.FromHex("8A000000"), BackgroundColor = Color.Transparent }; expandButton.SetBinding(SfFontButton.CommandParameterProperty, "."); expandButton.FontFamily = FontMappingHelper.BookmarkFont; expandButton.FontSize = 24; expandButton.Clicked += BookmarkExpand_Clicked; expandButton.HorizontalOptions = LayoutOptions.CenterAndExpand; expandButton.VerticalOptions = LayoutOptions.CenterAndExpand; Grid.SetRow(expandButton, 0); Grid.SetColumn(expandButton, 2); view.Children.Add(expandButton); //Bind the IsVisible property of the expand button to the IsExpandButtonVisible property of CustomBookmark expandButton.SetBinding(IsVisibleProperty, "IsExpandButtonVisible"); Frame bottomBorder = new Frame() { BackgroundColor = Color.FromHex("#000000"), Opacity = 0.12, Margin = 0 }; Grid.SetRow(bottomBorder, 1); Grid.SetColumn(bottomBorder, 0); Grid.SetColumnSpan(bottomBorder, 3); view.Children.Add(bottomBorder); viewCell.View = view; return viewCell; }); customBookmarkView = new ListView(ListViewCachingStrategy.RecycleElement); customBookmarkView.SeparatorVisibility = SeparatorVisibility.None; customBookmarkView.ItemsSource = pdfViewer.CustomBookmarks; customBookmarkView.RowHeight = 60; customBookmarkView.Scrolled += CustomBookmarkView_Scrolled; customBookmarkView.ItemTapped += CustomBookmarkView_ItemTapped; ; customBookmarkView.ItemTemplate = new DataTemplate(() => { ViewCell viewCell = new ViewCell(); Grid viewChild = new Grid() { ColumnSpacing=0,RowSpacing=0, BackgroundColor = Color.White }; viewChild.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) }); viewChild.ColumnDefinitions.Add(new ColumnDefinition() { Width = 32 }); viewChild.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) }); viewChild.RowDefinitions.Add(new RowDefinition() { Height = 1 }); Label bookmarkLabel = new Label() { TextColor = Color.FromHex("#000000") }; bookmarkLabel.Margin = new Thickness(12, 8, 0, 9); bookmarkLabel.LineBreakMode = LineBreakMode.TailTruncation; bookmarkLabel.VerticalOptions = LayoutOptions.Center; bookmarkLabel.SetBinding(Label.TextProperty, "Name"); bookmarkLabel.FontFamily = "SegoeUI"; bookmarkLabel.FontSize = 16; Grid.SetColumn(bookmarkLabel, 0); Grid.SetRow(bookmarkLabel,0); SfFontButton popUpMenuButton = new SfFontButton() { TextColor = Color.FromHex("8A000000") ,HorizontalOptions=LayoutOptions.Center,VerticalOptions=LayoutOptions.Center }; popUpMenuButton.FontSize = 24; popUpMenuButton.FontFamily = FontMappingHelper.MoreOptionsFont; popUpMenuButton.BackgroundColor = Color.Transparent; popUpMenuButton.Text = FontMappingHelper.Moreoptions; popUpMenuButton.Clicked += PopUpMenuButton_Clicked; ; popUpMenuButton.Margin = new Thickness(0, 10, 12, 10); Grid.SetColumn(popUpMenuButton, 1); Grid.SetRow(popUpMenuButton, 0); Frame bottomBorder = new Frame() { BackgroundColor = Color.FromHex("#000000"), Opacity = 0.12, Margin = 0 }; Grid.SetRow(bottomBorder, 1); Grid.SetColumn(bottomBorder, 0); Grid.SetColumnSpan(bottomBorder, 2); viewChild.Children.Add(bookmarkLabel); viewChild.Children.Add(popUpMenuButton); viewChild.Children.Add(bottomBorder); viewCell.View = viewChild; return viewCell; }); tabviewHeader_Content = new Grid(); SfFontButton Bookmark_DefaultHeader = new SfFontButton() {ButtonName= "defaultHeader", BackgroundColor =Color.Transparent }; Bookmark_DefaultHeader.WidthRequest = 40; Bookmark_DefaultHeader.FontFamily = FontMappingHelper.CustomBookmarkFont; Bookmark_DefaultHeader.Text = FontMappingHelper.Bookmark_Default; Bookmark_DefaultHeader.TextColor = Color.FromHex("#007CEE"); Bookmark_DefaultHeader.FontSize = 25; Bookmark_DefaultHeader.Clicked += Bookmark_DefaultHeader_Clicked; Bookmark_DefaultHeader.HorizontalOptions = LayoutOptions.Center; Bookmark_DefaultHeader.VerticalOptions = LayoutOptions.Center; tabviewHeader_Content.Children.Add(Bookmark_DefaultHeader); tabviewHeader_Bookmark = new Grid(); SfFontButton Bookmark_CustomHeader = new SfFontButton() {ButtonName= "customHeader", BackgroundColor = Color.Transparent ,TextColor=Color.FromHex("#000000")}; Bookmark_CustomHeader.WidthRequest = 40; Bookmark_CustomHeader.FontFamily = FontMappingHelper.CustomBookmarkFont; Bookmark_CustomHeader.Text = FontMappingHelper.Bookmark_Custom; Bookmark_CustomHeader.FontSize = 20; Bookmark_CustomHeader.HorizontalOptions = LayoutOptions.Center; Bookmark_CustomHeader.VerticalOptions = LayoutOptions.Center; Bookmark_CustomHeader.Clicked += Bookmark_CustomHeader_Clicked; tabviewHeader_Bookmark.Children.Add(Bookmark_CustomHeader); TapGestureRecognizer tapGestureToHideContextMenu = new TapGestureRecognizer(); tapGestureToHideContextMenu.Tapped += TapGestureToHideContextMenu_Tapped; customBookmarkContainer = new Grid(); customBookmarkContainer.Children.Add(customBookmarkView); pdfViewer.CustomBookmarks.CollectionChanged += CustomBookmarks_CollectionChanged; if (Device.RuntimePlatform == Device.Android) { tapDetectorGrid = new Grid(); double topMargin = customBookmarkView.RowHeight * pdfViewer.CustomBookmarks.Count; tapDetectorGrid.Margin = new Thickness(0, topMargin, 0, 0); tapDetectorGrid.GestureRecognizers.Add(tapGestureToHideContextMenu); customBookmarkContainer.Children.Add(tapDetectorGrid); } else { customBookmarkContainer.GestureRecognizers.Add(tapGestureToHideContextMenu); } var tabItems = new TabItemCollection { new SfTabItem() { HorizontalOptions = LayoutOptions.CenterAndExpand, VerticalOptions = LayoutOptions.CenterAndExpand, Content = bookmarkView, HeaderContent=tabviewHeader_Content }, new SfTabItem() { HorizontalOptions = LayoutOptions.CenterAndExpand, VerticalOptions = LayoutOptions.CenterAndExpand, Content = customBookmarkContainer, HeaderContent=tabviewHeader_Bookmark }, }; tabView.TabHeight = 32; if (Device.Idiom == TargetIdiom.Tablet) { tabView.TabWidth = ((Application.Current.MainPage.Width * 0.4)/ 2 ) - 1; } else { tabView.TabWidth = Application.Current.MainPage.Width/2; } tabView.Items = tabItems; tabView.SelectionChanged += TabView_SelectionChanged; AbsoluteLayout.SetLayoutFlags(tabView, AbsoluteLayoutFlags.All); AbsoluteLayout.SetLayoutBounds(tabView, new Rectangle(0, 0, 1, 1)); absoluteLayoutContainer.Children.Add(tabView); toastMessageFrame = new Frame() { IsVisible = false, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.End, CornerRadius = 4, HeightRequest = 32, BackgroundColor = Color.FromHex("#353535"), Padding = 0, Margin = new Thickness(0, 0, 0, 13) , HasShadow=false}; messageLabel = new Label() { BackgroundColor = Color.Transparent, HeightRequest = 20, Margin = new Thickness(13, 7, 13, 7), TextColor = Color.FromHex("#FFFFFF"), FontSize = 14, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center, VerticalTextAlignment = TextAlignment.Center }; toastMessageFrame.Content = messageLabel; AbsoluteLayout.SetLayoutFlags(toastMessageFrame, AbsoluteLayoutFlags.PositionProportional); AbsoluteLayout.SetLayoutBounds(toastMessageFrame, new Rectangle(0.5, 1, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)); absoluteLayoutContainer.Children.Add(toastMessageFrame); AddBookmarkButton = new SfFontButton() { TextColor = Color.White, FontSize = 24 }; VisualStateGroupList visualStateGroupList = new VisualStateGroupList(); VisualStateGroup commonStateGroup = new VisualStateGroup(); VisualState EnabledState = new VisualState() { Name = "Normal" }; EnabledState.Setters.Add(new Setter { Property = Button.BackgroundColorProperty, Value = Color.FromHex("#007CEE") }); VisualState DisabledState = new VisualState() { Name = "Disabled" }; DisabledState.Setters.Add(new Setter { Property = Button.BackgroundColorProperty, Value = Color.FromHex("#7BB9F2") }); DisabledState.Setters.Add(new Setter { Property=Button.TextColorProperty, Value = Color.FromHex("#FFFFFF")}); AddBookmarkButton.FontFamily = FontMappingHelper.CustomBookmarkFont; AddBookmarkButton.Text = FontMappingHelper.Bookmark_Add; AddBookmarkButton.CornerRadius = 34; AddBookmarkButton.HeightRequest = 68; AddBookmarkButton.WidthRequest = 68; AddBookmarkButton.Margin = new Thickness(0, 0, 26, 26); AddBookmarkButton.Clicked += AddBookmarkButton_Clicked; AbsoluteLayout.SetLayoutFlags(AddBookmarkButton, AbsoluteLayoutFlags.PositionProportional); AbsoluteLayout.SetLayoutBounds(AddBookmarkButton, new Rect(1, 1, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)); commonStateGroup.States.Add(EnabledState); commonStateGroup.States.Add(DisabledState); visualStateGroupList.Add(commonStateGroup); VisualStateManager.SetVisualStateGroups(AddBookmarkButton, visualStateGroupList); absoluteLayoutContainer.Children.Add(AddBookmarkButton); contextOptionsFrame = new Frame() { HasShadow = false, IsVisible = false, Padding = 1, CornerRadius = 4, HeightRequest = 88, WidthRequest = 149, BackgroundColor = Color.FromHex("#D5D5D5") ,Margin= new Thickness(0,0,22,0) }; contextOptionsFrame.SetBinding(Frame.IsVisibleProperty, "IsContextMenuVisible"); Frame contextOptionsInnerFrame = new Frame() { Padding = new Thickness(0, 3, 0, 3), HasShadow = false, CornerRadius = 4, WidthRequest = 147, HeightRequest = 86, BackgroundColor = Color.FromHex("#F6F6F6") }; contextOptions = new StackLayout() {Spacing=0, Orientation = StackOrientation.Vertical, BackgroundColor = Color.FromHex("#F6F6F6") , Margin=new Thickness(0,4,0,4)}; contextOptions.HeightRequest = 80; contextOptions.WidthRequest = 147; AbsoluteLayout.SetLayoutFlags(contextOptionsFrame, AbsoluteLayoutFlags.PositionProportional); AbsoluteLayout.SetLayoutBounds(contextOptionsFrame, new Rect(1, 0, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize)); RenameTextButton = new StackLayout() { HeightRequest = 40, WidthRequest = 99, Orientation = StackOrientation.Horizontal, BackgroundColor = Color.Transparent, Padding = 0 }; DeleteTextButton = new StackLayout() { HeightRequest = 40, WidthRequest = 99, Orientation = StackOrientation.Horizontal, BackgroundColor = Color.Transparent, Padding = 0 }; RenameIcon = new SfFontButton() { ButtonName="renameBookmarkButton", WidthRequest=40 , HeightRequest=40, Text = FontMappingHelper.RenameBookmark, TextColor = Color.FromHex("#000000"), BackgroundColor = Color.Transparent, FontSize = 16, Margin =0 , HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }; RenameIcon.FontFamily = FontMappingHelper.CustomBookmarkFont; RenameIcon.Clicked += RenameIcon_Clicked; DeleteIcon = new SfFontButton() {ButtonName="deleteBookmarkButton", WidthRequest=40,HeightRequest=40, Text = FontMappingHelper.DeleteBookmark, TextColor = Color.FromHex("#000000"), BackgroundColor = Color.Transparent, FontSize = 16, Margin =0, HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }; DeleteIcon.FontFamily = FontMappingHelper.CustomBookmarkFont; DeleteIcon.Clicked += DeleteIcon_Clicked; RenameText = new Label() { Text = "Rename", TextColor = Color.FromHex("#000000"), BackgroundColor = Color.Transparent, FontSize = 12, WidthRequest = 59, HeightRequest = 40, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Start, VerticalTextAlignment = TextAlignment.Center }; DeleteText = new Label() { Text = "Delete", TextColor = Color.FromHex("#000000"), BackgroundColor = Color.Transparent, FontSize = 12, WidthRequest = 59, HeightRequest = 40, HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Start, VerticalTextAlignment = TextAlignment.Center }; var renameTapGestureRecognizer = new TapGestureRecognizer(); var deleteTapGestureRecognizer = new TapGestureRecognizer(); RenameTextButton.GestureRecognizers.Add(renameTapGestureRecognizer); DeleteTextButton.GestureRecognizers.Add(deleteTapGestureRecognizer); Command renameOptionsCommand = new Command<object>(OnRenameOptions, CanExecute); Command deleteOptionsCommand = new Command<object>(OnDeleteOptions, CanExecute); renameTapGestureRecognizer.Command = renameOptionsCommand; deleteTapGestureRecognizer.Command = deleteOptionsCommand; RenameTextButton.Children.Add(RenameIcon); RenameTextButton.Children.Add(RenameText); DeleteTextButton.Children.Add(DeleteIcon); DeleteTextButton.Children.Add(DeleteText); contextOptions.Children.Add(RenameTextButton); contextOptions.Children.Add(DeleteTextButton); contextOptionsInnerFrame.Content = contextOptions; contextOptionsFrame.Content = contextOptionsInnerFrame; contextOptionsFrame.IsVisible = false; absoluteLayoutContainer.Children.Add(contextOptionsFrame); //Add the border between bookmark toolbar and pdfviewer only if the device is tablet if (Device.Idiom == TargetIdiom.Tablet) { Frame leftBorder = new Frame() { BackgroundColor = Color.FromHex("#000000"), Opacity = 0.12, Margin = 0 }; Grid.SetRow(leftBorder, 0); Grid.SetColumn(leftBorder, 0); Grid.SetRowSpan(leftBorder, 2); Children.Add(leftBorder); } } internal void UpdateBookmarkContent() { if (absoluteLayoutContainer.Parent == null) { Children.Add(absoluteLayoutContainer); } if (bookmarkLoadedDocument !=null && bookmarkLoadedDocument.Bookmarks != null && bookmarkLoadedDocument.Bookmarks.Count == 0) { tabView.Items[0].Content = NobookmarksLabel; } else if (bookmarkLoadedDocument != null && bookmarkLoadedDocument.Bookmarks.Count > 0) { tabView.Items[0].Content = bookmarkView; } } internal void UpdateCustomBookmarkView() { if (absoluteLayoutContainer.Parent == null) { Children.Add(absoluteLayoutContainer); } if (pdfViewer.CustomBookmarks.Count == 0) { tabView.Items[1].Content = CustomNobookmarksLabel; AddBookmarkButton.IsEnabled = true; } else if (pdfViewer.CustomBookmarks.Count != 0) { tabView.Items[1].Content = customBookmarkContainer; } } private void Bookmark_CustomHeader_Clicked(object sender, EventArgs e) { tabView.SelectedIndex = 1; } private void Bookmark_DefaultHeader_Clicked(object sender, EventArgs e) { tabView.SelectedIndex = 0; } private bool CanExecute(object parameter) { return true; } private void CustomBookmarks_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (Device.RuntimePlatform == Device.Android) { double topMargin = customBookmarkView.RowHeight * pdfViewer.CustomBookmarks.Count; tapDetectorGrid.Margin = new Thickness(0, topMargin, 0, 0); } UpdateCustomBookmarkView(); } private void TapGestureToHideContextMenu_Tapped(object sender, EventArgs e) { contextOptionsFrame.IsVisible = false; (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; } private void OnRenameOptions(object obj) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; if (Device.Idiom == TargetIdiom.Phone) { Grid.SetRow(PDFViewerCustomToolbar_Phone.editBookmarkPopup, 0); Grid.SetColumn(PDFViewerCustomToolbar_Phone.editBookmarkPopup, 0); Grid.SetRowSpan(PDFViewerCustomToolbar_Phone.editBookmarkPopup, 2); Children.Add(PDFViewerCustomToolbar_Phone.editBookmarkPopup); PDFViewerCustomToolbar_Phone.editBookmarkPopup.EditEntry.Text = pdfViewer.CustomBookmarks[selectedCustomBookmarkIndex].Name; PDFViewerCustomToolbar_Phone.editBookmarkPopup.EditEntry.Focus(); PDFViewerCustomToolbar_Phone.editBookmarkPopup.EditEntry.CursorPosition = 0; PDFViewerCustomToolbar_Phone.editBookmarkPopup.EditEntry.SelectionLength= PDFViewerCustomToolbar_Phone.editBookmarkPopup.EditEntry.Text.Length; PDFViewerCustomToolbar_Phone.editBookmarkPopup.IsVisible = true; } else { PDFViewerCustomToolbar_Tablet.ToggleBookmarkPopup(); PDFViewerCustomToolbar_Tablet.editBookmarkPopup.EditEntry.Text = pdfViewer.CustomBookmarks[selectedCustomBookmarkIndex].Name; PDFViewerCustomToolbar_Tablet.editBookmarkPopup.EditEntry.Focus(); PDFViewerCustomToolbar_Tablet.editBookmarkPopup.EditEntry.CursorPosition = 0; PDFViewerCustomToolbar_Tablet.editBookmarkPopup.EditEntry.SelectionLength= PDFViewerCustomToolbar_Tablet.editBookmarkPopup.EditEntry.Text.Length; PDFViewerCustomToolbar_Tablet.editBookmarkPopup.IsVisible = true; } contextOptionsFrame.IsVisible = false; } private async void OnDeleteOptions(object obj) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; this.messageLabel.Text = pdfViewer.CustomBookmarks[selectedCustomBookmarkIndex].Name + "- Deleted"; if (pdfViewer.PageNumber == pdfViewer.CustomBookmarks[selectedCustomBookmarkIndex].PageNumber) { AddBookmarkButton.IsEnabled = true; } pdfViewer.CustomBookmarks.RemoveAt(selectedCustomBookmarkIndex); if (pdfViewer.CustomBookmarks.Count == 0) { AddBookmarkButton.IsEnabled = true; UpdateCustomBookmarkView(); } if (Device.Idiom == TargetIdiom.Tablet) { PDFViewerCustomToolbar_Tablet.PositionToastMessage(); } toastMessageFrame.IsVisible = true; contextOptionsFrame.IsVisible = false; await toastMessageFrame.FadeTo(1, 1000); await toastMessageFrame.FadeTo(0, 1000); } private void CustomBookmarkView_Scrolled(object sender, ScrolledEventArgs e) { CustomBookmarkView_ScrollY = e.ScrollY; (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; } private void DeleteIcon_Clicked(object sender, EventArgs e) { OnDeleteOptions(sender); } private void RenameIcon_Clicked(object sender, EventArgs e) { OnRenameOptions(sender); } private async void AddBookmarkButton_Clicked(object sender, EventArgs e) { pdfViewer.CustomBookmarks.Add(new Syncfusion.SfPdfViewer.XForms.CustomBookmark("Page "+ pdfViewer.PageNumber ,pdfViewer.PageNumber)); tabView.SelectedIndex = 1; AddBookmarkButton.IsEnabled = false; toastMessageFrame.IsVisible = true; if (Device.Idiom == TargetIdiom.Tablet) { PDFViewerCustomToolbar_Tablet.PositionToastMessage(); } (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; this.messageLabel.Text = pdfViewer.CustomBookmarks.Last().Name + "- Added"; await toastMessageFrame.FadeTo(1, 1000); await toastMessageFrame.FadeTo(0, 1000); } private void TabView_SelectionChanged(object sender, Syncfusion.XForms.TabView.SelectionChangedEventArgs e) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; foreach (var item in tabView.Items) { if (e.Index == tabView.Items.IndexOf(item)) ((item.HeaderContent as Grid).Children[0] as Button).TextColor = Color.FromHex("#007CEE"); else ((item.HeaderContent as Grid).Children[0] as Button).TextColor = Color.Black; ; } } private void PopUpMenuButton_Clicked(object sender, EventArgs e) { contextOptionsFrame.IsVisible = true; this.selectedCustomBookmarkIndex = pdfViewer.CustomBookmarks.IndexOf((Syncfusion.SfPdfViewer.XForms.CustomBookmark)(sender as Button).BindingContext); var YOffset = (selectedCustomBookmarkIndex * 60) + (60 * 0.5) - this.CustomBookmarkView_ScrollY + tabView.TabHeight; if (YOffset > absoluteLayoutContainer.Height - contextOptionsFrame.Height - 20) { YOffset = absoluteLayoutContainer.Height - contextOptionsFrame.Height - 20; } contextOptionsFrame.TranslationY = YOffset; if ((BindingContext as PdfViewerViewModel).IsContextMenuVisible) (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; else (BindingContext as PdfViewerViewModel).IsContextMenuVisible = true; } private void CustomBookmarkView_ItemTapped(object sender, ItemTappedEventArgs e) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; pdfViewer.GoToBookmark(e.Item as Syncfusion.SfPdfViewer.XForms.CustomBookmark); if (Device.Idiom == TargetIdiom.Phone) { parentGrid.Children.Remove(this); isBookmarkPaneVisible = false; } (sender as ListView).SelectedItem = null; } //Handles the click event of the close button on bookmark toolbar in tablet private void BookmarkCloseButton_Clicked(object sender, EventArgs e) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; this.WidthRequest = 0; isBookmarkPaneVisible = false; } private void BookmarkView_ItemTapped(object sender, ItemTappedEventArgs e) { //Obtain the bookmark from the listview item and navigate to its destination pdfViewer.GoToBookmark((e.Item as ContentBookmark).Bookmark); //If the device is phone remove bookmark toolbar once the bookmark is navigated to if (Device.Idiom == TargetIdiom.Phone) { parentGrid.Children.Remove(this); isBookmarkPaneVisible = false; } } //Handles the click event of the backtoparent button on each bookmark in the list private void BackToParentButton_Clicked(object sender, EventArgs e) { listViewItemsSource.Clear(); if (navigationQueue.Count < 2) { for (int i = 0; i < bookmarkLoadedDocument.Bookmarks.Count; i++) listViewItemsSource.Add(new ContentBookmark(bookmarkLoadedDocument.Bookmarks[i], false)); if(navigationQueue.Count != 0) navigationQueue.RemoveAt(navigationQueue.Count - 1); } else { //Obtain the bookmark that was added to the navigationQueue when the expand button was clicked before PdfBookmark parentBookmark = navigationQueue[navigationQueue.Count - 2]; navigationQueue.RemoveAt(navigationQueue.Count - 2); UpdateBookmarkList(parentBookmark); } } //Populate the bookmark toolbar with the bookmarks when a new PDF is loaded internal void PopulateInitialBookmarkList() { listViewItemsSource.Clear(); PdfBookmarkBase bookmarkBase = bookmarkLoadedDocument.Bookmarks; for (int i = 0; i < bookmarkBase.Count; i++) listViewItemsSource.Add(new ContentBookmark(bookmarkBase[i], false)); } //Update the listview with new bookmarks when the backtoparent or expand button is clicked internal void UpdateBookmarkList(PdfBookmark bookmark) { listViewItemsSource.Clear(); listViewItemsSource.Add(new ContentBookmark(bookmark, true)); for (int i = 0; i < bookmark.Count; i++) listViewItemsSource.Add(new ContentBookmark(bookmark[i], false)); } //Handles the click event of the expand button of a bookmark. The expand button is visible only for bookmark with children private void BookmarkExpand_Clicked(object sender, EventArgs e) { PdfBookmark bookmark = ((sender as SfFontButton).CommandParameter as ContentBookmark).Bookmark; navigationQueue.Add(bookmark); UpdateBookmarkList(bookmark); } //Handles the click event of the back button on the bookmark toolbar in phone private void BookmarkPaneBackButton_Clicked(object sender, EventArgs e) { (BindingContext as PdfViewerViewModel).IsContextMenuVisible = false; contextOptionsFrame.IsVisible = false; //XAMARIN-44384 if (Device.Idiom == TargetIdiom.Phone) { if (PDFViewerCustomToolbar_Phone?.editBookmarkPopup != null) { Children?.Remove(PDFViewerCustomToolbar_Phone.editBookmarkPopup); } } parentGrid.Children.Remove(this); isBookmarkPaneVisible = false; } } //Class that holds the bookmark data. internal class ContentBookmark : INotifyPropertyChanged { private string desktopExpandButtonIcon = "\ue702"; public event PropertyChangedEventHandler PropertyChanged; public PdfBookmark Bookmark { get; set; } internal ContentBookmark(PdfBookmark bookmark, bool isBackToParentButtonVisible) { Bookmark = bookmark; IsBackToParentButtonVisible = isBackToParentButtonVisible; } internal ContentBookmark(PdfBookmark bookmark) { Bookmark = bookmark; } //Title of the bookmark public string Title { get { return Bookmark.Title; } } public string DesktopExpandButtonIcon { get { return desktopExpandButtonIcon; } set { desktopExpandButtonIcon = value; PropertyChanged(this, new PropertyChangedEventArgs("DesktopExpandButtonIcon")); } } //Returns a value that indicates whether the expand button should be visible public bool IsExpandButtonVisible { get { return Bookmark.Count != 0 && !IsBackToParentButtonVisible; } } //Gets or sets a value that indicates whether the backtoparent button should be visible public bool IsBackToParentButtonVisible { get; set; } } } <file_sep>/Android/SampleBrowser/Samples/PopupLayout/DetailsView/DetailsView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.ComponentModel; using Java.Lang; using Android.Graphics; using System.Collections.ObjectModel; using Syncfusion.Android.PopupLayout; using System.IO; using System.Reflection; using Android.Graphics.Drawables; using Android.Content.Res; namespace SampleBrowser { [Activity(Label = "DetailsView")] public class DetailsView : SamplePage { LinearLayout linearLayout; ListView listView; SfPopupLayout initialPopup; SfPopupLayout detailsPopup; ContatsViewModel viewModel; float density; Context context; TextView Label1; public override View GetSampleContent(Context context) { this.context = context; density = context.Resources.DisplayMetrics.Density; viewModel = new ContatsViewModel(); linearLayout = new LinearLayout(context); linearLayout.ViewAttachedToWindow += SampleLoaded; linearLayout.ViewDetachedFromWindow += SampleExited; linearLayout.Orientation = Android.Widget.Orientation.Vertical; listView = new ListView(context); listView.SetPadding((int)(16 * density), (int)(10 * density), (int)(16 * density), 0); listView.DividerHeight = 16; listView.Divider.Alpha = 0; listView.SetBackgroundColor(Color.ParseColor("#F4F4F4")); listView.ItemClick += ListView_ItemClick; listView.Adapter = new CustomPopupAdapter(viewModel, context); Label1 = new TextView(context); Label1.Gravity = GravityFlags.CenterVertical; Label1.Alpha = 221; Label1.SetTextColor(Color.Gray); Label1.SetBackgroundColor(Color.ParseColor("#F4F4F4")); Label1.TextSize = 20; Label1.Text = "Today"; Label1.SetTypeface(Typeface.Default, TypefaceStyle.Bold); Label1.SetPadding((int)(16 * density),0,0,0); linearLayout.AddView(Label1, LinearLayout.LayoutParams.MatchParent, (int)(50 * density)); linearLayout.AddView(listView); return linearLayout; } public override void Destroy() { base.Destroy(); linearLayout.ViewAttachedToWindow -= SampleLoaded; linearLayout.ViewDetachedFromWindow -= SampleExited; listView.ItemClick -= ListView_ItemClick; } private void SampleExited(object sender, View.ViewDetachedFromWindowEventArgs e) { initialPopup.Dispose(); initialPopup = null; if (detailsPopup != null) { detailsPopup.Dispose(); detailsPopup = null; } } private void SampleLoaded(object sender, View.ViewAttachedToWindowEventArgs e) { DisplayInitialPopup(); } private void DisplayInitialPopup() { initialPopup = new SfPopupLayout(context); initialPopup.PopupView.AppearanceMode = AppearanceMode.OneButton; initialPopup.PopupView.ShowFooter = true; initialPopup.PopupView.ShowCloseButton = false; initialPopup.PopupView.HeaderTitle = "Notification !"; initialPopup.PopupView.AcceptButtonText = "OK"; initialPopup.PopupView.PopupStyle.HeaderTextSize = 16; initialPopup.StaysOpen = true; TextView messageView = new TextView(context); messageView.Text = "Click on the contact tile to view the options"; messageView.SetTextColor(Color.Black); messageView.SetBackgroundColor(Color.White); messageView.TextSize = 14; initialPopup.PopupView.ContentView = messageView; initialPopup.PopupView.ContentView.SetPadding((int)(10 * density), (int)(10 * density), (int)(10 * density), (int)(10 * density)); initialPopup.PopupView.PopupStyle.CornerRadius = 3; initialPopup.PopupView.HeightRequest = 180; initialPopup.Show(); } private void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { CreateDetailsPopup(e.View); if ((50 * density) + e.View.Bottom + (130 * density) >= listView.Bottom) detailsPopup.ShowRelativeToView(e.View, RelativePosition.AlignTop, 0, 0); else detailsPopup.ShowRelativeToView(e.View, RelativePosition.AlignBottom, 0, 0); } private void CreateDetailsPopup(View view) { detailsPopup = new SfPopupLayout(context); detailsPopup.PopupView.WidthRequest = (int)(view.Width / Resources.System.DisplayMetrics.Density); detailsPopup.PopupView.HeightRequest = 130; detailsPopup.PopupView.ShowHeader = false; detailsPopup.PopupView.PopupStyle.BorderColor = Color.White; detailsPopup.PopupView.PopupStyle.BorderThickness = 5; detailsPopup.PopupView.ShowFooter = false; detailsPopup.StaysOpen = false; detailsPopup.PopupView.PopupStyle.CornerRadius = 5; detailsPopup.PopupView.AnimationMode = AnimationMode.None; detailsPopup.PopupView.ContentView = GetCustomPopupView(this.context, view); } private View GetCustomPopupView(Context context, View view) { LinearLayout mainLinearLayout; LinearLayout linearLayout1; LinearLayout linearLayout2; LinearLayout linearLayout3; ImageView imageView1; ImageView imageView2; ImageView imageView3; TextView label1; TextView label2; TextView label3; imageView1 = new ImageView(context); imageView1.Alpha = 137; imageView1.SetImageResource(Resource.Drawable.Popup_SendMessage); label1 = new TextView(context); label1.Click += Label1_Click; label1.Alpha = 0.87f; label1.Gravity = GravityFlags.Top; label1.SetTextColor(Color.Black); label1.TextSize = 16; label1.Text = "Send a message"; linearLayout1 = new LinearLayout(context); linearLayout1.Orientation = Android.Widget.Orientation.Horizontal; linearLayout1.AddView(imageView1, (int)(60 * density), (int)(20 * density)); linearLayout1.AddView(label1, LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); imageView2 = new ImageView(context); imageView2.Alpha = 0.6f; imageView2.SetImageResource(Resource.Drawable.Popup_BlockContact); label2 = new TextView(context); label2.Alpha = 137; label2.Click += Label2_Click; label2.Gravity = GravityFlags.Top; label2.SetTextColor(Color.Black); label2.TextSize = 16; label2.Alpha = 0.87f; label2.Text = "Block/report spam"; linearLayout2 = new LinearLayout(context); linearLayout2.Orientation = Android.Widget.Orientation.Horizontal; linearLayout2.AddView(imageView2, (int)(60 * density), (int)(20 * density)); linearLayout2.AddView(label2, LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); imageView3 = new ImageView(context); imageView3.Alpha = 0.6f; imageView3.SetImageResource(Resource.Drawable.Popup_ContactInfo); label3 = new TextView(context); label2.Alpha = 0.87f; label3.Gravity = GravityFlags.Top; label3.SetTextColor(Color.Black); label3.TextSize = 16; label3.Click += Label3_Click; label3.Text = "Call details"; linearLayout3 = new LinearLayout(context); linearLayout3.Orientation = Android.Widget.Orientation.Horizontal; linearLayout3.AddView(imageView3, (int)(60 * density), (int)(20 * density)); linearLayout3.AddView(label3, LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); mainLinearLayout = new LinearLayout(context); mainLinearLayout.SetPadding((int)(10 * density), (int)(10 * density), (int)(10 * density), (int)(10 * density)); mainLinearLayout.Orientation = Android.Widget.Orientation.Vertical; mainLinearLayout.SetBackgroundColor(Color.ParseColor("#FFFFFF")); mainLinearLayout.AddView(linearLayout1, LinearLayout.LayoutParams.MatchParent, (int)(40 * density)); mainLinearLayout.AddView(linearLayout2, LinearLayout.LayoutParams.MatchParent, (int)(40 * density)); mainLinearLayout.AddView(linearLayout3, LinearLayout.LayoutParams.MatchParent, (int)(40 * density)); return mainLinearLayout; } private void Label2_Click(object sender, EventArgs e) { Toast toast = Toast.MakeText(context, "Contact Blocked", ToastLength.Short); toast.Show(); Handler handler = new Handler(); handler.PostDelayed(new Runnable(toast.Cancel), 500); handler = null; toast = null; } private void Label1_Click(object sender, EventArgs e) { Toast toast = Toast.MakeText(context, "Message Sent", ToastLength.Short); toast.Show(); Handler handler = new Handler(); handler.PostDelayed(new Runnable(toast.Cancel), 500); handler = null; toast = null; } private void Label3_Click(object sender, EventArgs e) { Toast toast = Toast.MakeText(context, "No outgoing call history", ToastLength.Short); toast.Show(); Handler handler = new Handler(); handler.PostDelayed(new Runnable(toast.Cancel), 500); handler = null; toast = null; } } public class CustomPopupAdapter : BaseAdapter { ContatsViewModel viewModel; Context context; public CustomPopupAdapter(ContatsViewModel viewmodel, Context contxt) : base() { this.viewModel = viewmodel; this.context = contxt; } public override int Count { get { return viewModel.ContactsList.Count; } } public override Java.Lang.Object GetItem(int position) { return position; } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { if (convertView != null) return convertView; else { var view = new CustomView(this.context); view.SetValue(viewModel.ContactsList[position]); return view; } } } public class CustomView : GridLayout { ImageView image1; ImageView image2; TextView Label1; TextView Label2; GridLayout DetailsLayout; internal static TextView currentLabel; public CustomView(Context context) : base(context) { this.SetPadding(25, 25, 25, 25); this.SetBackgroundColor(Color.ParseColor("#FFFFFF")); this.ColumnCount = 3; this.RowCount = 1; image1 = new ImageView(context); image1.SetPadding(0, 10, 0, 10); image2 = new ImageView(context); image2.SetPadding(0, (int)(15 * Resources.DisplayMetrics.Density), 0, (int)(15 * Resources.DisplayMetrics.Density)); Label1 = new TextView(context); Label1.Gravity = GravityFlags.Start; Label1.Alpha = 221; Label1.SetTextColor(Color.Black); Label1.TextSize = 20; Label2 = new TextView(context); Label2.Gravity = GravityFlags.Start; Label2.Alpha = 137; Label2.TextSize = 16; Label2.SetTextColor(Color.Gray); DetailsLayout = new GridLayout(context); DetailsLayout.RowCount = 4; DetailsLayout.ColumnCount = 1; DetailsLayout.AddView(Label1); DetailsLayout.AddView(Label2); DetailsLayout.SetPadding((int)(20 * this.Resources.DisplayMetrics.Density), (int)(5 * this.Resources.DisplayMetrics.Density), 0, 0); if(MainActivity.IsTablet) this.AddView(image1, (int)(70 * this.Resources.DisplayMetrics.Density), (int)(70 * this.Resources.DisplayMetrics.Density)); else this.AddView(image1, (int)(50 * this.Resources.DisplayMetrics.Density), (int)(50 * this.Resources.DisplayMetrics.Density)); this.AddView(DetailsLayout, Resources.DisplayMetrics.WidthPixels - (int)(120 * Resources.DisplayMetrics.Density) - 70, ViewGroup.LayoutParams.MatchParent); this.AddView(image2, (int)(50 * this.Resources.DisplayMetrics.Density), (int)(50 * this.Resources.DisplayMetrics.Density)); } internal void SetValue(object obj) { List<int> list = new List<int>(); Random r = new Random(); list.Add(Resource.Drawable.PopupImage1); list.Add(Resource.Drawable.PopupImage2); list.Add(Resource.Drawable.PopupImage3); list.Add(Resource.Drawable.PopupImage4); list.Add(Resource.Drawable.PopupImage5); list.Add(Resource.Drawable.PopupImage6); list.Add(Resource.Drawable.PopupImage7); list.Add(Resource.Drawable.PopupImage8); list.Add(Resource.Drawable.PopupImage9); list.Add(Resource.Drawable.PopupImage10); var contacts = obj as Contacts; Label1.Text = contacts.ContactName; currentLabel = Label1; Label2.Text = contacts.ContactNumber.ToString(); image1.SetImageResource(list[r.Next(10)]); image2.SetImageResource(Resource.Drawable.Popup_CallerImage); image2.Alpha = 0.54f; } } }<file_sep>/iOS/SampleBrowser/Samples/PDF/Booklet.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.IO; using Syncfusion.Drawing; using System.Reflection; using Syncfusion.Pdf; using Syncfusion.Pdf.Barcode; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Parsing; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class Booklet : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label1; UIButton button ; public Booklet() { label1 = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label1.Frame = frameRect; label1.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label1.Text = "This sample demonstrates how to create a booklet from an existing PDF document."; label1.Font = UIFont.SystemFontOfSize(15); label1.Lines = 0; label1.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label1.Font = UIFont.SystemFontOfSize(18); label1.Frame = new CGRect(0, 12, frameRect.Location.X + frameRect.Size.Width, 50); } else { label1.Frame = new CGRect(frameRect.Location.X, 12, frameRect.Size.Width, 50); } this.AddSubview(label1); button.SetTitle("Generate PDF", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 70, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(frameRect.Location.X, 70, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { Stream docStream = typeof(Booklet).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.JavaScript Succinctly.pdf"); PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream); float width = 1224; float height = 792; PdfDocument document = PdfBookletCreator.CreateBooklet(ldoc, new Syncfusion.Drawing.SizeF(width, height), true); MemoryStream stream = new MemoryStream(); document.Save(stream); document.Close(true); if (stream != null) { SaveiOS iosSave = new SaveiOS(); iosSave.Save("Booklet.pdf", "application/pdf", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Helpers/Command.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; namespace SampleBrowser { public class Command : ICommand { private Action execute; private bool canExecute = true; public event EventHandler CanExecuteChanged; public Command(Action action) { execute = action; } public bool CanExecute(object parameter) { return canExecute; } public void Execute(object parameter) { changeCanExecute(true); execute.Invoke(); } private void changeCanExecute(bool canExecute) { this.canExecute = canExecute; if (CanExecuteChanged != null) CanExecuteChanged(this, new EventArgs()); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/SemiPie.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Android.Graphics; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class SemiPie : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Title.Text = "Products Growth - 2015"; chart.Title.TextSize = 15; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.ToggleSeriesVisibility = true; var datas = new List<DataPoint>(); datas.Add(new DataPoint("Product A", 14)); datas.Add(new DataPoint("Product B", 54)); datas.Add(new DataPoint("Product C", 23)); datas.Add(new DataPoint("Product D", 53)); var pieSeries = new PieSeries { ItemsSource = datas, XBindingPath = "XValue", YBindingPath = "YValue", StartAngle = 180, EndAngle = 360, }; pieSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; pieSeries.DataMarker.ShowLabel = true; pieSeries.DataMarker.LabelContent = LabelContent.Percentage; pieSeries.DataMarkerPosition = CircularSeriesDataMarkerPosition.Outside; pieSeries.EnableAnimation = true; chart.Series.Add(pieSeries); return chart; } } }<file_sep>/Forms/AutoComplete/AutoComplete/Samples/CustomSearchPage/CustomSearchPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Syncfusion.ListView.XForms; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public partial class CustomSearchPage : SampleView { public CustomSearchPage() { InitializeComponent(); this.BindingContext = new CustomViewModel(); this.autoComplete.Filter = (this.BindingContext as CustomViewModel).CustomSearchLogic; if (Device.RuntimePlatform == Device.UWP) { FirstColumn.Padding = new Thickness(0, 0, 0, 0); sampleLayout.WidthRequest = 500; sampleLayout.HorizontalOptions = LayoutOptions.Center; sampleLayoutScrollView.HorizontalOptions = LayoutOptions.Center; } if (Device.Idiom == TargetIdiom.Tablet) { GridLayout gridLayout = new GridLayout(); gridLayout.SpanCount = 8; listView.LayoutManager = gridLayout; listView.WidthRequest = 600; } } } }<file_sep>/iOS/SampleBrowser/Samples/ImageEditor/ProfileEditor.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Threading.Tasks; using CoreAnimation; using CoreGraphics; using Foundation; using Syncfusion.SfImageEditor.iOS; using UIKit; namespace SampleBrowser { public class ProfileEditor : SampleView { UIView mainView; UINavigationController navigationController; UIImageView imageView; public override void LayoutSubviews() { base.LayoutSubviews(); mainView = new UIView(); mainView.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); UIStackView profileView = new UIStackView(); var height = mainView.Frame.Height * 0.45; profileView.Frame = new CoreGraphics.CGRect(0, 0, mainView.Frame.Width, height); profileView.Axis = UILayoutConstraintAxis.Vertical; CAGradientLayer gradientLayer = new CAGradientLayer(); gradientLayer.Frame = profileView.Frame; gradientLayer.Colors = new CGColor[] { UIColor.FromRGB(115, 218,240).CGColor, UIColor.FromRGB(0, 113, 138).CGColor }; gradientLayer.StartPoint = new CGPoint(0, 0); gradientLayer.EndPoint = new CGPoint(0, 1); profileView.Layer.AddSublayer(gradientLayer); var height1 = profileView.Frame.Height * 0.25; var height2 = profileView.Frame.Height * 0.5; var height3 = profileView.Frame.Height * 0.25; UILabel label = new UILabel(new CGRect(20, 0, profileView.Frame.Width, height1)); label.BackgroundColor = UIColor.Clear; label.Font = UIFont.SystemFontOfSize(25); label.TextColor = UIColor.Black; label.TextAlignment = UITextAlignment.Left; label.Text = "Profile"; profileView.Add(label); imageView = new UIImageView(); imageView.ContentMode = UIViewContentMode.ScaleAspectFit; imageView.Frame = new CoreGraphics.CGRect(0, label.Frame.Bottom, profileView.Frame.Width, height2); imageView.Image = UIImage.FromBundle("Images/ImageEditor/Profile.png"); profileView.Add(imageView); UIButton button = new UIButton(); button.SetTitle("Edit Image", UIControlState.Normal); var size = imageView.SizeThatFits(CGSize.Empty); button.Frame = new CoreGraphics.CGRect(profileView.Frame.Width / 2 - size.Width / 4, imageView.Frame.Bottom + 20, size.Width / 2, height3 / 2); button.VerticalAlignment = UIControlContentVerticalAlignment.Center; button.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button.BackgroundColor = UIColor.Clear; button.Font = UIFont.SystemFontOfSize(20); button.Layer.CornerRadius = 20; button.Layer.BorderColor = UIColor.White.CGColor; button.Layer.BorderWidth = 2; button.SetTitleColor(UIColor.White, UIControlState.Normal); button.TouchDown += (sender, e) => { navigationController.PushViewController(new ProfileViewController(imageView.Image, navigationController, imageView), false); }; profileView.Add(button); mainView.AddSubview(profileView); UIView detailsView = new UIView(); detailsView.Frame = new CGRect(0, profileView.Frame.Bottom, mainView.Frame.Width, mainView.Frame.Height * 0.55); previousTop = 0; for (int i = 0; i < 4; i++) { UIView itemView = CreateView(detailsView, i); detailsView.Add(itemView); } mainView.AddSubview(detailsView); AddSubview(mainView); } double previousTop; private UIView CreateView(UIView detailsView, int index) { var itemHeight = detailsView.Frame.Height / 5; var iconsWidth = detailsView.Frame.Width * 0.2; var detailsWidth = detailsView.Frame.Width * 0.8; var padding = 5; previousTop = index * itemHeight; UIView nameView = new UIView(); nameView.Frame = new CGRect(0, previousTop, mainView.Frame.Width, itemHeight); UIImageView icon = new UIImageView(); icon.BackgroundColor = UIColor.Clear; icon.ContentMode = UIViewContentMode.ScaleAspectFit; icon.Frame = new CGRect(0, itemHeight /4, iconsWidth, itemHeight / 2); UILabel name = new UILabel(); name.Font = UIFont.SystemFontOfSize(20); name.TextColor = UIColor.Gray; name.TextAlignment = UITextAlignment.Left; name.Frame = new CGRect(icon.Frame.Right + padding, 10, detailsWidth, itemHeight / 3); UILabel profileName = new UILabel(); profileName.Font = UIFont.SystemFontOfSize(24); profileName.TextColor = UIColor.Black; profileName.TextAlignment = UITextAlignment.Left; profileName.Frame = new CGRect(icon.Frame.Right + padding, name.Frame.Bottom, detailsWidth, itemHeight / 2); UIView border = new UIView(); border.Layer.BorderWidth = 1; border.Layer.BorderColor = UIColor.Gray.CGColor; border.Frame = new CGRect(icon.Frame.Right + padding, profileName.Frame.Bottom, detailsWidth, 1); if (index == 0) { icon.Image = UIImage.FromBundle("Images/ImageEditor/LabelContactName.png"); name.Text = "Name"; profileName.Text = "<NAME>"; } else if (index == 1) { icon.Image = UIImage.FromBundle("Images/ImageEditor/Email.png"); name.Text = "Email"; profileName.Text = "<EMAIL>ody<EMAIL>"; } else if (index == 2) { icon.Image = UIImage.FromBundle("Images/ImageEditor/Phone.png"); name.Text = "Phone"; profileName.Text = "+1-123-456-7890"; } else if (index == 3) { icon.Image = UIImage.FromBundle("Images/ImageEditor/Address.png"); name.Text = "Address"; profileName.Text = "Avenue 8th street, NW SY"; } nameView.Add(icon); nameView.Add(name); nameView.Add(profileName); nameView.Add(border); return nameView; } public override void MovedToSuperview() { base.MovedToSuperview(); var window = UIApplication.SharedApplication.KeyWindow; navigationController = window.RootViewController as UINavigationController; } } public class ProfileViewController : UIViewController { SfImageEditor editor; UIImage editorImage; UINavigationController controller; UIImageView profilePicture; public ProfileViewController(UIImage image, UINavigationController navigationController, UIImageView imageView) { editorImage = image; controller = navigationController; profilePicture = imageView; } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); editor = new SfImageEditor(new CGRect(View.Frame.Location.X, 60, View.Frame.Size.Width, View.Frame.Size.Height - 60)); editor.ImageLoaded += Editor_ImageLoaded; editor.Image = editorImage; this.View.AddSubview(editor); editor.ToolBarSettings.ToolbarItems.Add(new FooterToolbarItem() { Text = "Crop" }); editor.SetToolbarItemVisibility("Text, Shape, Brightness, Effects, Bradley Hand, Path, 3:1, 3:2, 4:3, 5:4, 16:9, Undo, Redo, Transform", false); editor.ImageSaving += Editor_ImageSaving; editor.ToolBarSettings.ToolbarItemSelected += ToolBarSettings_ToolbarItemSelected; } private void Editor_ImageSaving(object sender, ImageSavingEventArgs e) { e.Cancel = true; var imageData = NSData.FromStream(e.Stream); profilePicture.Image = UIImage.LoadFromData(imageData); controller.PopViewController(false); } private void Editor_ImageSaved(object sender, ImageSavedEventArgs e) { controller.PopViewController(false); } private void ToolBarSettings_ToolbarItemSelected(object sender, ToolbarItemSelectedEventArgs e) { if (e.ToolbarItem.Text == "Crop") { editor.ToggleCropping(true, 3); e.Cancel = true; } } private async void Editor_ImageLoaded(object sender, ImageLoadedEventArgs e) { await Task.Delay(25); editor.ToggleCropping(true, 3); } } } <file_sep>/iOS/SampleBrowser/Samples/DocIO/TrackChanges.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.Pdf; using Syncfusion.DocIORenderer; using Syncfusion.OfficeChart; using Syncfusion.Drawing; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using Syncfusion.iOS.Buttons; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using ObjCRuntime; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class TrackChanges : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UIButton imageType; UIButton generateButton; UIButton viewButton; //RadioButton SfRadioGroup radioGroup = new SfRadioGroup(); SfRadioButton acceptAll = new SfRadioButton(); SfRadioButton rejectAll = new SfRadioButton(); public TrackChanges() { label = new UILabel(); imageType = new UIButton(); viewButton = new UIButton(UIButtonType.System); viewButton.TouchUpInside += OnConvertClicked1; generateButton = new UIButton(UIButtonType.System); generateButton.TouchUpInside += OnConvertClicked2; } void LoadAllowedTextsLabel() { #region Description Label label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to accept or reject the tracked changes in the Word document using Essential DocIO."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 35); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 70); } this.AddSubview(label); #endregion #region ImageFormat Label imageType.Frame = new CGRect(10, 100, frameRect.Location.X + frameRect.Size.Width - 20, 40); #endregion #region Radio Buttons for track changes radioGroup.Axis = UILayoutConstraintAxis.Horizontal; acceptAll.SetTitle("Accepts all", UIControlState.Normal); radioGroup.AddArrangedSubview(acceptAll); rejectAll.SetTitle("Rejects all", UIControlState.Normal); radioGroup.AddArrangedSubview(rejectAll); acceptAll.IsChecked = true; radioGroup.Distribution = UIStackViewDistribution.FillProportionally; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { radioGroup.Frame = new CGRect(5, 60, frameRect.Width, 40); } else { radioGroup.Frame = new CGRect(5, 80, frameRect.Width, 40); } this.AddSubview(radioGroup); #endregion #region Convert Button viewButton.SetTitle("View Template", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { viewButton.Frame = new CGRect(0, 115, frameRect.Location.X + frameRect.Size.Width, 10); } else { viewButton.Frame = new CGRect(0, 135, frameRect.Location.X + frameRect.Size.Width, 10); } this.AddSubview(viewButton); generateButton.SetTitle("Generate Word", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { generateButton.Frame = new CGRect(0, 145, frameRect.Location.X + frameRect.Size.Width, 10); } else { generateButton.Frame = new CGRect(0, 165, frameRect.Location.X + frameRect.Size.Width, 10); } this.AddSubview(generateButton); #endregion } void OnConvertClicked1(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.TrackChangesTemplate.docx"); MemoryStream stream = new MemoryStream(); inputStream.CopyTo(stream); inputStream.Dispose(); string fileName = null; string ContentType = null; fileName = "TrackChangesTemplate.docx"; ContentType = "application/msword"; //Reset the stream position stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save(fileName, ContentType, stream as MemoryStream); } } void OnConvertClicked2(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); WordDocument document = new WordDocument(); // Open an existing template document. Stream inputStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.TrackChangesTemplate.docx"); document.Open(inputStream, FormatType.Docx); inputStream.Dispose(); if (rejectAll != null && (bool)rejectAll.IsChecked) document.Revisions.RejectAll(); else document.Revisions.AcceptAll(); string fileName = null; string ContentType = null; MemoryStream ms = new MemoryStream(); fileName = "Track Changes.docx"; ContentType = "application/msword"; document.Save(ms, FormatType.Docx); //Reset the stream position ms.Position = 0; //Close the document instance. document.Close(); if (ms != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save(fileName, ContentType, ms as MemoryStream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/ViewModel/SelectionViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SelectionViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Syncfusion.Data; using Syncfusion.Data.Extensions; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// A ViewModel for Selection sample. /// </summary> public class SelectionViewModel : Employee { #region Field [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private ObservableCollection<OrderInfo> ordersInfo; #endregion /// <summary> /// Initializes a new instance of the SelectionViewModel class. /// </summary> public SelectionViewModel() { this.SetRowstoGenerate(200); } #region ItemsSource /// <summary> /// Gets or sets the Value of OrdersInfo and notifies user when value gets changed /// </summary> public ObservableCollection<OrderInfo> OrdersInfo { get { return this.ordersInfo; } set { this.ordersInfo = value; } } #endregion #region ItemSource Generator /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">generates row count</param> public void SetRowstoGenerate(int count) { OrderInfoRepository order = new OrderInfoRepository(); this.ordersInfo = order.GetOrderDetails(100); } #endregion } } <file_sep>/Forms/TextInputLayout/TextInputLayout/Samples/PaymentView/PaymentView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SampleBrowser.Core; using Syncfusion.XForms.MaskedEdit; using Syncfusion.XForms.Buttons; using Border = Syncfusion.XForms.Border.SfBorder; using System.Collections.ObjectModel; namespace SampleBrowser.SfTextInputLayout { /// <summary> /// Payment view. /// </summary> public partial class PaymentView : SampleView { private ObservableCollection<View> viewCollection = new ObservableCollection<View>(); /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.SfTextInputLayout.PaymentView"/> class. /// </summary> public PaymentView() { InitializeComponent(); amount.Culture = new System.Globalization.CultureInfo("es-US"); // picker.SelectedIndex = 1; if (Device.RuntimePlatform == Device.UWP) { grid.IsVisible = false; } if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { var colors = paymentViewModel.Colors; foreach (Color color in colors) { Grid grid = new Grid(); Border border = new Border { Margin = new Thickness(2), HorizontalOptions = LayoutOptions.Center, CornerRadius = 25, BorderWidth = 0, Content = new BoxView { Color = color } }; grid.Children.Add(border); viewCollection.Add(grid); } colorsView.ItemsSource = viewCollection; } PrimaryColorChanged(colorsView.SelectedIndex); } private void CornerRadiusChanged(object sender, Xamarin.Forms.ValueChangedEventArgs e) { nameLayout.OutlineCornerRadius = e.NewValue; cornerRadiusValue.Text = "Corner radius : " + Math.Round(e.NewValue).ToString(); } private void Color_SelectionChanged(object sender, Syncfusion.XForms.Buttons.SelectionChangedEventArgs e) { if (colorsView.SelectedIndex >= 0) { PrimaryColorChanged(colorsView.SelectedIndex); } } private void PrimaryColorChanged(int index) { switch (index) { case 1: paymentViewModel.BackgroundColor = Color.FromHex("#EAF1FC"); paymentViewModel.FocusedColor = Color.FromHex("#0074C4"); break; case 2: paymentViewModel.BackgroundColor = Color.FromHex("#f4edf2"); paymentViewModel.FocusedColor = Color.FromHex("#5C1349"); break; default: paymentViewModel.BackgroundColor = Color.FromUint(0x0A000000); paymentViewModel.FocusedColor = Color.FromHex("#0074C4"); break; } } private void Picker_SelectedIndexChanged(object sender, EventArgs e) { var picker = sender as Picker; if (Device.RuntimePlatform == Device.Android) { if (picker.SelectedIndex == 0) { expiredMonth.HeightRequest = 60; expiredYear.HeightRequest = 60; } else { expiredMonth.HeightRequest = 52; expiredYear.HeightRequest = 52; } } if (Device.RuntimePlatform == Device.UWP) { if (picker.SelectedIndex == 0) { expiredMonth.HeightRequest = 60; expiredYear.HeightRequest = 60; } else if (picker.SelectedIndex == 1) { expiredMonth.HeightRequest = 45; expiredYear.HeightRequest = 45; } else if (picker.SelectedIndex == 2) { expiredMonth.HeightRequest = 50; expiredYear.HeightRequest = 50; } } } } }<file_sep>/Forms/Cards/Cards/Samples/CardView/CardViewData.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; namespace SampleBrowser.Cards { public class CardViewData : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string imagePath; public string ImagePath { get { return imagePath; } set { imagePath = value; OnPropertyChanged(); } } private string name; public string Name { get { return name; } set { name = value; OnPropertyChanged(); } } private string price; public string Price { get { return price; } set { price = value; OnPropertyChanged(); } } private string offer; public string Offer { get { return offer; } set { offer = value; OnPropertyChanged(); } } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/iOS/SampleBrowser/Samples/PDF/readme.md PDF is a .NET class library used to create, read, and write PDF. This library is used in Windows Forms, WPF, Silverlight, ASP.NET and ASP.NET MVC, WinRT, Windows Phone, Windows store universal, and Xamarin applications without the dependency of Adobe Acrobat. PDF creates files from version 1.5 and later, and supports PDF version 1.4 and later. This is viewed by using Adobe Reader 7.x or later versions. The following samples are available for PDF to demonstrate the functionalities of each feature: | Sample | Description | | ------ | ----------- | | [Getting Started PDF](GettingStartedPDF.cs) | Demonstrates how to create a simple PDF document with text and images. | | [Stamping](Stamping.cs) | Demonstrates how to stamp or watermark an existing PDF document. | | [Table Features](TableFeatures.cs) | Demonstrates how to create borderless tables in a PDF document. | | [Booklet](Booklet.cs) | Demonstrates how to create a booklet from an existing PDF document. | | [Barcode](Barcode.cs) | Demonstrates how to create various barcode in a PDF document. | | [Digital Signature](DigitalSiganture.cs) | Demonstrates how to digitally sign PDF document using a .pfx certificate. | | [Image Insertion](mageInsertion.cs) | Demonstrates how to insert images in a PDF document. | | [Encryption](Encryption.cs) | Demonstrates how to create a secure PDF document. | | [RTL Text](RTLSupport.cs) | Demonstrates drawing right-to-left language text in the PDF document. | | [Conformance](Conformance.cs) | Demonstrates how to create a PDF/A-1b standard document. | | [ZUGFeRD Invoice](ZugFerd.cs) | Demonstrates how to create a ZUGFeRD PDF document. | | [OpenType Font](OpenTypeFont.cs) | Demonstrates how to draw a text with OpenType font in a PDF document. |<file_sep>/Android/SampleBrowser/Samples/Chart/Series/StackingColumn100.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class StackingColumn100 : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "Gross Domestic Product Growth"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis PrimaryAxis = new CategoryAxis(); PrimaryAxis.ShowMajorGridLines = false; PrimaryAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; PrimaryAxis.LabelPlacement = LabelPlacement.BetweenTicks; chart.PrimaryAxis = PrimaryAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Title.Text = "GDP (%) Per Annum"; numericalAxis.Minimum = 0; numericalAxis.Maximum = 100; numericalAxis.Interval = 10; numericalAxis.LineStyle.StrokeWidth = 0; numericalAxis.MajorTickStyle.TickSize = 0; numericalAxis.LabelStyle.LabelFormat = "#'%' "; chart.SecondaryAxis = numericalAxis; StackingColumn100Series stackingColumn100Series1 = new StackingColumn100Series(); stackingColumn100Series1.EnableAnimation = true; stackingColumn100Series1.Label = "UK"; stackingColumn100Series1.ItemsSource = MainPage.GetStackedColumn100Data1(); stackingColumn100Series1.XBindingPath = "XValue"; stackingColumn100Series1.YBindingPath = "YValue"; stackingColumn100Series1.LegendIcon = ChartLegendIcon.SeriesType; StackingColumn100Series stackingColumn100Series2 = new StackingColumn100Series(); stackingColumn100Series2.EnableAnimation = true; stackingColumn100Series2.Label = "Germany"; stackingColumn100Series2.ItemsSource = MainPage.GetStackedColumn100Data2(); stackingColumn100Series2.XBindingPath = "XValue"; stackingColumn100Series2.YBindingPath = "YValue"; stackingColumn100Series2.LegendIcon = ChartLegendIcon.SeriesType; StackingColumn100Series stackingColumn100Series3 = new StackingColumn100Series(); stackingColumn100Series3.EnableAnimation = true; stackingColumn100Series3.Label = "France"; stackingColumn100Series3.ItemsSource = MainPage.GetStackedColumn100Data3(); stackingColumn100Series3.XBindingPath = "XValue"; stackingColumn100Series3.YBindingPath = "YValue"; stackingColumn100Series3.LegendIcon = ChartLegendIcon.SeriesType; StackingColumn100Series stackingColumn100Series4 = new StackingColumn100Series(); stackingColumn100Series4.EnableAnimation = true; stackingColumn100Series4.Label = "Italy"; stackingColumn100Series4.ItemsSource = MainPage.GetStackedColumn100Data4(); stackingColumn100Series4.XBindingPath = "XValue"; stackingColumn100Series4.YBindingPath = "YValue"; stackingColumn100Series4.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingColumn100Series1); chart.Series.Add(stackingColumn100Series2); chart.Series.Add(stackingColumn100Series3); chart.Series.Add(stackingColumn100Series4); stackingColumn100Series1.TooltipEnabled = true; stackingColumn100Series2.TooltipEnabled = true; stackingColumn100Series3.TooltipEnabled = true; stackingColumn100Series4.TooltipEnabled = true; stackingColumn100Series1.EnableAnimation = true; stackingColumn100Series2.EnableAnimation = true; stackingColumn100Series3.EnableAnimation = true; stackingColumn100Series4.EnableAnimation = true; return chart; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/EditingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Data.Extensions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; namespace SampleBrowser { public class EditingViewModel : INotifyPropertyChanged { #region Constructor public EditingViewModel() { DealerRepository dealerrep = new DealerRepository(); dealerInformation = dealerrep.GetDealerDetails(100); this.CustomerNames = dealerrep.Customers.ToObservableCollection(); } #endregion #region ItemsSource private ObservableCollection<DealerInfo> dealerInformation; public ObservableCollection<DealerInfo> DealerInformation { get { return this.dealerInformation; } set { this.dealerInformation = value; } } public ObservableCollection<string> CustomerNames { get; set; } #endregion #region Property Changed public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion } }<file_sep>/Android/SampleBrowser/Samples/PopupLayout/Popup Customizations/Adapter/TheaterAdapter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Syncfusion.Android.PopupLayout; using Android.Content.Res; using Android.Graphics; using Android.Util; using System.Windows.Input; using Android.Graphics.Drawables; namespace SampleBrowser { public class TheaterAdapter : BaseAdapter<TableItem> { private List<TableItem> items; private Activity context; public static ImageView info; private SfPopupLayout termsAndConditionsPopup; private SfPopupLayout infoPopup; private FrameLayout mainView; internal static int counter = 0; private TextView timing1; private TextView timing2; private ImageView infoImage; private Button cancelButton; private Button okButton; private Button proceed; private double density; TextView seatCountLabel; public TheaterAdapter(Activity context, List<TableItem> items, FrameLayout view) : base() { this.context = context; this.items = items; this.mainView = view; this.density = Resources.System.DisplayMetrics.Density; } public override long GetItemId(int position) { return position; } public override TableItem this[int position] { get { return items[position]; } } public override int Count { get { return items.Count; } } public override View GetView(int position, View convertView, ViewGroup parent) { (parent as ListView).ViewDetachedFromWindow += TheaterAdapter_ViewDetachedFromWindow; var item = items[position]; View view = convertView; view = context.LayoutInflater.Inflate(Resource.Layout.CustomListView, null); return CreateTheaterTile(view as LinearLayout, item); } private void TheaterAdapter_ViewDetachedFromWindow(object sender, View.ViewDetachedFromWindowEventArgs e) { timing1.Click -= Timing1_Click; timing2.Click -= Timing2_Click; infoImage.Click -= Info_Click; } private LinearLayout CreateTheaterTile(LinearLayout view, TableItem item) { LinearLayout theaterInfo = new LinearLayout(context); theaterInfo.Orientation = Android.Widget.Orientation.Vertical; TextView theaterName = new TextView(context); theaterName.Text = item.Heading; theaterName.SetTextColor(Color.ParseColor("#000000")); theaterName.SetTextSize(ComplexUnitType.Dip, 16); theaterName.SetPadding((int)(12 * density), 0, 0, (int)(8 * density)); TextView areaName = new TextView(context); areaName.Text = item.SubHeading; areaName.SetTextColor(Color.ParseColor("#000000")); areaName.SetTextSize(ComplexUnitType.Dip, 12); areaName.SetPadding((int)(12 * density), 0, 0, (int)(10 * density)); LinearLayout timingLayout = new LinearLayout(context); timingLayout.Orientation = Android.Widget.Orientation.Horizontal; timing1 = new TextView(context); timing1.Text = item.Timing1; timing1.Click += Timing1_Click; timing1.SetX((int)(12 * density)); timing1.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; timing1.SetTextColor(Color.ParseColor("#007CEE")); timing1.SetTextSize(ComplexUnitType.Dip, 14); timing1.SetBackgroundResource(Resource.Layout.BorderLayout1); timing2 = new TextView(context); timing2.Text = item.Timing2; timing2.SetTextColor(Color.ParseColor("#007CEE")); timing2.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; timing2.SetX((int)(22 * density)); if (MainActivity.IsTablet) timing2.SetPadding(0, 2, 0, 0); else timing2.SetPadding(0, 20, 0, 0); timing2.SetTextSize(ComplexUnitType.Dip, 14); timing2.Click += Timing2_Click; timing2.SetBackgroundResource(Resource.Layout.BorderLayout1); timingLayout.AddView(timing1, (int)(80 * density), ViewGroup.LayoutParams.MatchParent); timingLayout.AddView(timing2, (int)(80 * density), ViewGroup.LayoutParams.MatchParent); theaterInfo.AddView(theaterName); theaterInfo.AddView(areaName); if (MainActivity.IsTablet) theaterInfo.AddView(timingLayout, ViewGroup.LayoutParams.MatchParent, (int)(25 * density)); else theaterInfo.AddView(timingLayout, ViewGroup.LayoutParams.MatchParent, (int)(32 * density)); infoImage = new ImageView(context); infoImage.SetImageResource(item.ImageResourceId); infoImage.Click += Info_Click; infoImage.Alpha = 0.5f; infoImage.SetY((int)(38 * density)); view.AddView(theaterInfo,(int)(Resources.System.DisplayMetrics.WidthPixels - (48 * density)), (int)(100 * density)); view.AddView(infoImage, (int)(24* density), (int)(24 * density)); if (item.Timing1 != null) { timing1.Text = item.Timing1; } else { timing1.Visibility = ViewStates.Invisible; timing1.Gravity = GravityFlags.CenterHorizontal; } if (item.Timing2 != null) { timing2.Text = item.Timing2; timing2.Gravity = GravityFlags.CenterHorizontal; } else { timing2.Visibility = ViewStates.Invisible; } return view; } private void Timing2_Click(object sender, EventArgs e) { CreateTermsAndConditionsPopup(); termsAndConditionsPopup.Show(); } private void Timing1_Click(object sender, EventArgs e) { CreateTermsAndConditionsPopup(); termsAndConditionsPopup.Show(); } private void CreateTermsAndConditionsPopup() { termsAndConditionsPopup = new SfPopupLayout(this.context); termsAndConditionsPopup.PopupView.SetBackgroundColor(Color.White); termsAndConditionsPopup.StaysOpen = true; termsAndConditionsPopup.PopupView.HeaderTitle = "Terms & Conditions"; termsAndConditionsPopup.PopupView.PopupStyle.HeaderTextGravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; termsAndConditionsPopup.PopupView.PopupStyle.HeaderBackgroundColor = Color.White; termsAndConditionsPopup.PopupView.PopupStyle.HeaderTextColor = Color.Black; termsAndConditionsPopup.PopupView.PopupStyle.BorderColor = Color.LightGray; termsAndConditionsPopup.PopupView.PopupStyle.BorderThickness = 1; termsAndConditionsPopup.PopupView.ShowFooter = true; termsAndConditionsPopup.PopupView.ShowCloseButton = false; termsAndConditionsPopup.PopupView.AppearanceMode = AppearanceMode.TwoButton; TextView messageView = new TextView(this.context) { Text = "1. Children below the age of 18 cannot be admitted for movies certified A.\n2. Please carry proof of age for movies certified A.\n3. Drinking and alcohol is strictly prohibited inside the premises \n4. Please purchase tickets for children above age of 3."}; termsAndConditionsPopup.PopupView.ContentView = messageView; termsAndConditionsPopup.PopupView.AppearanceMode = AppearanceMode.TwoButton; LinearLayout footer = new LinearLayout(context); footer.Orientation = Android.Widget.Orientation.Horizontal; cancelButton = new Button(context); cancelButton.Text = "Decline"; cancelButton.Click += CancelButton_Click; cancelButton.SetBackgroundColor(Color.White); cancelButton.Gravity = GravityFlags.Center; cancelButton.SetTextSize(ComplexUnitType.Dip, 14); cancelButton.SetTextColor(Color.ParseColor("#007CEE")); okButton = new Button(context); okButton.Text = "Accept"; okButton.Click += AcceptTerms_Click; okButton.SetTextSize(ComplexUnitType.Dip,14); okButton.SetBackgroundColor(Color.White); okButton.Gravity = GravityFlags.Center; okButton.SetTextColor(Color.ParseColor("#007CEE")); if (MainActivity.IsTablet) { messageView.TextSize = 19; messageView.SetTextColor(Color.Gray); messageView.SetBackgroundColor(Color.White); messageView.SetPadding((int)(10 * density), (int)(30 * density), (int)(10 * density), (int)(30 * density)); termsAndConditionsPopup.PopupView.WidthRequest = 450; termsAndConditionsPopup.PopupView.HeightRequest = 320; footer.SetMinimumWidth(450); footer.AddView(cancelButton, (int)(225 * density) , ViewGroup.LayoutParams.MatchParent); footer.AddView(new View(context) { Background = new ColorDrawable(Color.LightGray) }, (int)(1 * density), ViewGroup.LayoutParams.MatchParent); footer.AddView(okButton, (int)(225 * density), ViewGroup.LayoutParams.MatchParent); } else { messageView.TextSize = 14; messageView.SetTextColor(Color.Gray); messageView.SetBackgroundColor(Color.White); messageView.SetPadding((int)(10 * density), (int)(10 * density), (int)(10 * density), (int)(10 * density)); termsAndConditionsPopup.PopupView.WidthRequest = 300; termsAndConditionsPopup.PopupView.HeightRequest = 270; footer.SetMinimumWidth(300); footer.AddView(cancelButton, (int)(150 * density), ViewGroup.LayoutParams.MatchParent); footer.AddView(new View(context) {Background = new ColorDrawable(Color.LightGray) }, (int)(1 * density), ViewGroup.LayoutParams.MatchParent); footer.AddView(okButton, (int)(150 * density), ViewGroup.LayoutParams.MatchParent); } termsAndConditionsPopup.PopupView.FooterView = footer; termsAndConditionsPopup.PopupView.FooterHeight = 50; termsAndConditionsPopup.PopupView.ShowHeader = true; } private void CancelButton_Click(object sender, EventArgs e) { termsAndConditionsPopup.Dismiss(); } private void AcceptTerms_Click(object sender, EventArgs e) { termsAndConditionsPopup.StaysOpen = false; termsAndConditionsPopup.PopupView.ShowCloseButton = true; if (((termsAndConditionsPopup.PopupView.FooterView as LinearLayout).GetChildAt(0) as Button).Text == "Proceed") { Toast.MakeText(context, "Tickets booked successfully", ToastLength.Long).Show(); termsAndConditionsPopup.Dismiss(); } else { termsAndConditionsPopup.PopupView.HeaderTitle = "How many seats ?"; termsAndConditionsPopup.PopupView.ContentView = CreateSeatSelectionPage(); } } private LinearLayout CreateSeatSelectionPage() { LinearLayout seatSelectionMainLayout = new LinearLayout(context); seatSelectionMainLayout.Orientation = Android.Widget.Orientation.Vertical; seatSelectionMainLayout.SetBackgroundColor(Color.White); LinearLayout numberOfSeatsLayout = new LinearLayout(context); numberOfSeatsLayout.Orientation = Android.Widget.Orientation.Horizontal; if (MainActivity.IsTablet) { numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("1"), (int)((450 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("2", 1), (int)((450 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("3"), (int)((450 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("4"), (int)((450 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("5"), (int)((450 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("6"), (int)((450 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("7"), (int)((450 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("8"), (int)((450 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); } else { numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("1"), (int)((300 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("2", 1), (int)((300 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("3"), (int)((300 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("4"), (int)((300 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("5"), (int)((300 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("6"), (int)((300 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("7"), (int)((300 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); numberOfSeatsLayout.AddView(CreateSeatSelectionLayout("8"), (int)((300 * Resources.System.DisplayMetrics.Density) / 8), (int)(42 * Resources.System.DisplayMetrics.Density)); } TextView title2 = new TextView(context); title2.Text = "Select your seat class"; if(!MainActivity.IsTablet) title2.SetY(10); title2.SetTextColor(Color.Black); title2.SetTextSize(ComplexUnitType.Dip, 14); LinearLayout seatClassLayout = new LinearLayout(context); seatClassLayout.Orientation = Android.Widget.Orientation.Vertical; if (MainActivity.IsTablet) { seatClassLayout.SetPadding((int)(22 * density), 0, 0, 0); } else { seatClassLayout.SetPadding((int)(22 * density), (int)(15 * density), 0, 0); } seatClassLayout.AddView(CreateSeatClassLayoutTile("Silver"), (int)(300 * density), (int)(40 * density)); seatClassLayout.AddView(CreateSeatClassLayoutTile("Premier"), (int)(300 * density), (int)(40 * density)); if (MainActivity.IsTablet) { numberOfSeatsLayout.SetPadding(0, (int)(15 * density), 0, 0); title2.SetPadding((int)(10 * density), 0, 0, 0); seatSelectionMainLayout.AddView(numberOfSeatsLayout, ViewGroup.LayoutParams.MatchParent, (int)(84 * Resources.System.DisplayMetrics.Density)); seatSelectionMainLayout.AddView(title2, ViewGroup.LayoutParams.MatchParent, (int)(45 * density)); seatSelectionMainLayout.AddView(seatClassLayout, ViewGroup.LayoutParams.MatchParent, (int)(120 * density)); termsAndConditionsPopup.PopupView.FooterHeight = 60; } else { numberOfSeatsLayout.SetPadding(0, (int)(10 * density), 0, 0); title2.SetPadding((int)(10 * density), (int)(15 * density), 0, 0); seatSelectionMainLayout.AddView(numberOfSeatsLayout, ViewGroup.LayoutParams.MatchParent, (int)(52 * Resources.System.DisplayMetrics.Density)); seatSelectionMainLayout.AddView(title2, ViewGroup.LayoutParams.MatchParent, (int)(45 * density)); seatSelectionMainLayout.AddView(seatClassLayout, ViewGroup.LayoutParams.MatchParent, (int)(95 * density)); termsAndConditionsPopup.PopupView.FooterHeight = 40; } termsAndConditionsPopup.PopupView.HeaderTitle = "Select your seats"; termsAndConditionsPopup.PopupView.PopupStyle.HeaderTextColor = Color.Black; termsAndConditionsPopup.PopupView.PopupStyle.HeaderBackgroundColor = Color.White;// ParseColor("#007CEE"); termsAndConditionsPopup.PopupView.PopupStyle.BorderThickness = 1; termsAndConditionsPopup.PopupView.ShowFooter = true; termsAndConditionsPopup.PopupView.ShowHeader = true; if (MainActivity.IsTablet) termsAndConditionsPopup.PopupView.HeightRequest = 350; else termsAndConditionsPopup.PopupView.HeightRequest = 300; termsAndConditionsPopup.PopupView.AppearanceMode = AppearanceMode.TwoButton; (termsAndConditionsPopup.PopupView.FooterView as LinearLayout).RemoveAllViews(); proceed = new Button(context); proceed.Text = "Proceed"; proceed.SetTextSize(ComplexUnitType.Dip,14); proceed.SetTextColor(Color.White); proceed.SetBackgroundColor(Color.ParseColor("#007CEE")); proceed.SetMinimumWidth((int)(300 * density)); (termsAndConditionsPopup.PopupView.FooterView as LinearLayout).AddView(proceed, ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); proceed.Click += AcceptTerms_Click; termsAndConditionsPopup.PopupView.PopupStyle.FooterBackgroundColor = Color.White; return seatSelectionMainLayout; } private TextView CreateSeatSelectionLayout(string count, object selected = null) { seatCountLabel = new TextView(context); if (selected == null) { seatCountLabel.SetBackgroundColor(Android.Graphics.Color.White); seatCountLabel.SetTextColor(Color.Black); } else { seatCountLabel.SetBackgroundColor(Color.ParseColor("#007CEE")); seatCountLabel.SetTextColor(Color.White); } seatCountLabel.Text = count; seatCountLabel.SetTypeface(Android.Graphics.Typeface.Default, TypefaceStyle.Bold); seatCountLabel.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; seatCountLabel.Click += SeatCountLabel_Click; return seatCountLabel; } private void SeatCountLabel_Click(object sender, EventArgs e) { for (int i = 0; i < ((sender as TextView).Parent as LinearLayout).ChildCount; i++) { // Remove selection color to other date views (((sender as TextView).Parent as LinearLayout).GetChildAt(i) as TextView).SetBackgroundColor(Color.White); (((sender as TextView).Parent as LinearLayout).GetChildAt(i) as TextView).SetTextColor(Color.Black); } (sender as TextView).SetBackgroundColor(Color.ParseColor("#007CEE")); (sender as TextView).SetTextColor(Color.White); } private LinearLayout CreateSeatClassLayoutTile(string text) { LinearLayout linear = new LinearLayout(context); linear.Orientation = Android.Widget.Orientation.Horizontal; TextView clas = new TextView(context); clas.Text = text; clas.SetTextColor(Color.Gray); clas.SetTextSize(ComplexUnitType.Dip, 14); TextView cost = new TextView(context); if (text == "Silver") cost.Text = "$19.69"; else cost.Text = "$23.65"; cost.SetTextColor(Color.Black); cost.SetTextSize(ComplexUnitType.Dip, 14); TextView availability = new TextView(context); if (text == "Silver") { availability.Text = "Available"; availability.SetTextColor(Color.ParseColor("#00BD81")); } else { availability.Text = "Unavailable"; availability.SetTextColor(Color.Red); } availability.SetTextSize(ComplexUnitType.Dip, 14); linear.AddView(clas, (int)((300 / 3) * density), (int)(30 * density)); linear.AddView(cost, (int)((300 / 3) * density), (int)(30 * density)); linear.AddView(availability, (int)((300 / 3) * density), (int)(30 * density)); return linear; } private void Info_Click(object sender, EventArgs e) { CreateInfoLayout(sender); } private void CreateInfoLayout(object sender) { var header = (((sender as ImageView).Parent as LinearLayout).GetChildAt(0) as LinearLayout).GetChildAt(0) as TextView; LinearLayout bodyView = new LinearLayout(context); bodyView.Orientation = Android.Widget.Orientation.Vertical; bodyView.SetBackgroundColor(Color.White); TextView body = new TextView(context); body.Text = ((((sender as ImageView).Parent as LinearLayout).GetChildAt(0) as LinearLayout).GetChildAt(1) as TextView).Text + "421 E DRACHMAN TUCSON AZ 85705 - 7598 USA"; body.SetTextSize(ComplexUnitType.Dip, 14); body.SetPadding((int)(12 * density), (int)(10 * density), 0, 0); body.SetTextColor(Color.ParseColor("#007CEE")); TextView facilities = new TextView(context); facilities.Text = "Available Facilities"; facilities.Gravity = GravityFlags.CenterHorizontal; facilities.SetTextColor(Color.Black); facilities.SetTextSize(ComplexUnitType.Dip, 14); LinearLayout facilitiesLayout = new LinearLayout(context); facilitiesLayout.Orientation = Android.Widget.Orientation.Vertical; facilitiesLayout.SetPadding(0, (int)(10 * density), 0, 0); LinearLayout iconLayout = new LinearLayout(context); iconLayout.Orientation = Android.Widget.Orientation.Horizontal; iconLayout.SetHorizontalGravity(GravityFlags.CenterHorizontal); LinearLayout iconDescLayout = new LinearLayout(context); iconDescLayout.Orientation = Android.Widget.Orientation.Horizontal; iconDescLayout.SetHorizontalGravity(GravityFlags.CenterHorizontal); ImageView mticket = new ImageView(context); mticket.SetImageResource(Resource.Drawable.Popup_MTicket); ImageView parking = new ImageView(context); parking.SetImageResource(Resource.Drawable.Popup_Parking); ImageView foodCourt = new ImageView(context); foodCourt.SetImageResource(Resource.Drawable.Popup_FoodCourt); iconLayout.AddView(mticket, (int)(100 * density), (int)(30 * density)); iconLayout.AddView(parking, (int)(100 * density), (int)(30 * density)); iconLayout.AddView(foodCourt, (int)(100 * density), (int)(30 * density)); TextView mtick = new TextView(context); mtick.Text = "M-Ticket"; mtick.SetTextSize(ComplexUnitType.Dip, 10); mtick.SetTextColor(Color.Black); mtick.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; TextView park = new TextView(context); park.Text = "Parking"; park.SetTextSize(ComplexUnitType.Dip, 10); park.SetTextColor(Color.Black); park.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; TextView food = new TextView(context); food.Text = "Food Court"; food.SetTextSize(ComplexUnitType.Dip, 10); food.SetTextColor(Color.Black); food.Gravity = GravityFlags.CenterHorizontal | GravityFlags.CenterVertical; iconDescLayout.AddView(mtick, (int)(100 * density), (int)(30 * density)); iconDescLayout.AddView(park, (int)(100 * density), (int)(30 * density)); iconDescLayout.AddView(food, (int)(100 * density), (int)(30 * density)); facilitiesLayout.AddView(iconLayout); facilitiesLayout.AddView(iconDescLayout); bodyView.AddView(body, ViewGroup.LayoutParams.MatchParent, (int)(50 * density)); bodyView.AddView(facilities, ViewGroup.LayoutParams.MatchParent, (int)(30 * density)); bodyView.AddView(facilitiesLayout, ViewGroup.LayoutParams.MatchParent, (int)(70 * density)); DisplayInfoPopup(bodyView, header.Text); } private void DisplayInfoPopup(View bodyView,string headerText) { bodyView.SetPadding(10, 0, 10, 0); infoPopup = new SfPopupLayout(context); infoPopup.PopupView.HeaderTitle = headerText; infoPopup.PopupView.PopupStyle.HeaderTextColor = Color.Black; infoPopup.PopupView.PopupStyle.HeaderTextSize = 18; infoPopup.PopupView.AppearanceMode = AppearanceMode.OneButton; infoPopup.PopupView.PopupStyle.HeaderBackgroundColor = Color.White; infoPopup.PopupView.ShowHeader = true; infoPopup.PopupView.ShowCloseButton = true; infoPopup.StaysOpen = false; infoPopup.PopupView.ShowFooter = false; if (MainActivity.IsTablet) infoPopup.PopupView.WidthRequest = 450; else infoPopup.PopupView.WidthRequest = 300; infoPopup.PopupView.HeightRequest = 250; infoPopup.PopupView.ContentView = bodyView; infoPopup.PopupView.PopupStyle.BorderThickness = 1; infoPopup.IsOpen = true; } } }<file_sep>/Forms/RichTextEditor/RichTextEditor/Samples/MailPage/MailPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using SampleBrowser.SfRichTextEditor.Samples; using Syncfusion.XForms.RichTextEditor; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfRichTextEditor { public partial class MailPage : SampleView { public MailPage() { InitializeComponent(); #if COMMONSB RichTextEditorResourceManager.Manager = new ResourceManager("SampleBrowser.Samples.RichTextEditor.Resources.Syncfusion.SfRichTextEditor.XForms", Application.Current.GetType().Assembly); #else RichTextEditorResourceManager.Manager = new ResourceManager("SampleBrowser.SfRichTextEditor.Resources.Syncfusion.SfRichTextEditor.XForms", Application.Current.GetType().Assembly); #endif if (Device.RuntimePlatform != Device.UWP) { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } else { CultureInfo.CurrentUICulture = new CultureInfo("en-US"); } if (Device.RuntimePlatform == Device.iOS) { EntryFieldTo.Margin = EntryFieldSubject.Margin = new Thickness(16, 16, 16, 16); } RTE.Text = "<p>Hi,<br><br>The rich text editor component is WYSIWYG (\"what you see is what you get\") editor that provides the best user experience to create and update the content.Users can format their content using standard toolbar commands.<p>This Sample illustrates formatting related to <b>Bold</b>, <i>Italic</i>,<u> Underline</u>, <span style=\"background-color: rgb(255,255,0);\" > Highlight </span><span style=\"background-color: rgb(250,0,0); \">Colors </span>and <span style=\"color: rgb(255, 0, 0); text - decoration: inherit; \">Font </span><span style=\"color: blue; text - decoration: inherit; \"></span><span style=\"color: rgb(0,0,200); text - decoration: inherit; \">Colors </span>in Xamarin RTE control.<br></p>"; } } public class ViewModel : INotifyPropertyChanged { Stream boogalooFontStream, handleeFontStream, kaushanFontStream, pinyonFontStream, robotoFontStream; public ICommand FontCommand { get; set; } public ICommand ImageCommand { get; set; } public ViewModel() { var assembly = Assembly.GetAssembly(Application.Current.GetType()); #if COMMONSB boogalooFontStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.RichTextEditor.Fonts.Boogaloo.ttf"); handleeFontStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.RichTextEditor.Fonts.Handlee.ttf"); kaushanFontStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.RichTextEditor.Fonts.Kaushan Script.ttf"); pinyonFontStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.RichTextEditor.Fonts.Pinyon Script.ttf"); robotoFontStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.RichTextEditor.Fonts.Roboto-Regular.ttf"); #else boogalooFontStream = assembly.GetManifestResourceStream("SampleBrowser.SfRichTextEditor.Fonts.Boogaloo.ttf"); handleeFontStream = assembly.GetManifestResourceStream("SampleBrowser.SfRichTextEditor.Fonts.Handlee.ttf"); kaushanFontStream = assembly.GetManifestResourceStream("SampleBrowser.SfRichTextEditor.Fonts.Kaushan Script.ttf"); pinyonFontStream = assembly.GetManifestResourceStream("SampleBrowser.SfRichTextEditor.Fonts.Pinyon Script.ttf"); robotoFontStream = assembly.GetManifestResourceStream("SampleBrowser.SfRichTextEditor.Fonts.Roboto-Regular.ttf"); #endif ImageCommand = new Command<object>(LoadImage); FontCommand = new Command<object>(LoadFonts); } void LoadFonts(object obj) { FontButtonClickedEventArgs fontEventArgs = (obj as FontButtonClickedEventArgs); if (!fontEventArgs.FontStreamCollection.ContainsKey("Boogaloo")) fontEventArgs.FontStreamCollection.Add("Boogaloo", boogalooFontStream); if (!fontEventArgs.FontStreamCollection.ContainsKey("Handlee")) fontEventArgs.FontStreamCollection.Add("Handlee", handleeFontStream); if (!fontEventArgs.FontStreamCollection.ContainsKey("Kaushan Script")) fontEventArgs.FontStreamCollection.Add("Kaushan Script", kaushanFontStream); if (!fontEventArgs.FontStreamCollection.ContainsKey("Pinyon Script")) fontEventArgs.FontStreamCollection.Add("Pinyon Script", pinyonFontStream); } void LoadImage(object obj) { ImageInsertedEventArgs imageInsertedEventArgs = (obj as ImageInsertedEventArgs); this.GetImage(imageInsertedEventArgs); } async void GetImage(ImageInsertedEventArgs imageInsertedEventArgs) { using (Stream imageStream = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync()) { if (imageStream != null) { Syncfusion.XForms.RichTextEditor.ImageSource imageSource = new Syncfusion.XForms.RichTextEditor.ImageSource(); imageSource.ImageStream = imageStream; imageInsertedEventArgs.ImageSourceCollection.Add(imageSource); } } } public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChange([CallerMemberName] string propertyname = null) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyname)); } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/LoadMoreViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; namespace SampleBrowser { public class LoadMoreViewModel : INotifyPropertyChanged { #region Fields private OrderDetailsRepository order; private ObservableCollection<OrderInfo> ordersInfo; #endregion #region Constructor public LoadMoreViewModel() { SetRowstoGenerate(30); } #endregion #region ItemsSource public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; RaisePropertyChanged("OrdersInfo"); } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { order = new OrderDetailsRepository(); ordersInfo = order.GetOrderDetails(count); } #endregion #region LoadMore Generator internal void LoadMoreItems() { for (int i = 0; i < 20; i++) this.OrdersInfo.Add(order.GenerateOrder(OrdersInfo.Count + 1)); } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Android/SampleBrowser/Samples/CircularGauge/DirectionCompass.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfCircularGauge; using System.Collections.ObjectModel; using Android.Graphics; using Com.Syncfusion.Gauges.SfCircularGauge.Enums; using Android.Renderscripts; namespace SampleBrowser { public class DirectionCompass : SamplePage { List<String> adapter; NeedlePointer pointer; public override View GetSampleContent (Context con) { SfCircularGauge sfCircularGauge = new SfCircularGauge(con); ObservableCollection<CircularScale> circularScales = new ObservableCollection<CircularScale>(); CircularScale scale = new CircularScale(); scale.StartAngle = 270; scale.StartValue = 0; scale.EndValue = 16; scale.Interval = 2; scale.LabelOffset = 0.75; scale.SweepAngle = 360; scale.MinorTicksPerInterval = 1; scale.ShowLastLabel = false; scale.ScaleStartOffset = 0.99; scale.ScaleEndOffset = 0.9; scale.LabelCreated += Scale_LabelCreated; scale.RimColor = Color.ParseColor("#E0E0E0"); scale.LabelColor = Color.ParseColor("#4B4B4B"); scale.MajorTickSettings.StartOffset = 0.9; scale.MajorTickSettings.EndOffset = 0.83; scale.MajorTickSettings.Width = 2; scale.MajorTickSettings.Color = Color.ParseColor("#9E9E9E"); scale.MinorTickSettings.StartOffset = 0.9; scale.MinorTickSettings.EndOffset = 0.85; scale.MinorTickSettings.Width = 2; scale.MinorTickSettings.Color = Color.ParseColor("#9E9E9E"); ObservableCollection<CircularPointer> pointers = new ObservableCollection<CircularPointer>(); pointer = new NeedlePointer(); pointer.Value = 14; pointer.Color = Color.ParseColor("#f03e3e"); pointer.Type = Com.Syncfusion.Gauges.SfCircularGauge.Enums.NeedleType.Triangle; pointer.LengthFactor = 0.65; pointer.Width = 20; pointer.KnobRadiusFactor = 0; pointer.KnobColor = Color.White; pointer.KnobStrokeWidth = 3; pointer.KnobStrokeColor = Color.White; pointer.EnableAnimation = false; pointers.Add(pointer); NeedlePointer needlePointer = new NeedlePointer(); needlePointer.Value = 6; needlePointer.Type = Com.Syncfusion.Gauges.SfCircularGauge.Enums.NeedleType.Triangle; needlePointer.LengthFactor = 0.65; needlePointer.Width = 20; needlePointer.Color = Color.ParseColor("#9E9E9E"); needlePointer.KnobRadiusFactor = 0.11; needlePointer.KnobColor = Color.White; needlePointer.KnobStrokeWidth = 3; needlePointer.KnobStrokeColor = Color.White; needlePointer.EnableAnimation = false; pointers.Add(needlePointer); scale.CircularPointers = pointers; circularScales.Add(scale); sfCircularGauge.CircularScales = circularScales; sfCircularGauge.SetBackgroundColor(Color.White); LinearLayout linearLayout = new LinearLayout(con); linearLayout.AddView(sfCircularGauge); linearLayout.SetPadding(30, 30, 30, 30); linearLayout.SetBackgroundColor(Color.White); return linearLayout; } private void Scale_LabelCreated(object sender, LabelCreatedEventArgs e) { switch ((string)e.LabelContent) { case "0": e.LabelContent = "N"; break; case "2": e.LabelContent = "NE"; break; case "4": e.LabelContent = "E"; break; case "6": e.LabelContent = "SE"; break; case "8": e.LabelContent = "S"; break; case "10": e.LabelContent = "SW"; break; case "12": e.LabelContent = "W"; break; case "14": e.LabelContent = "NW"; break; } } public override View GetPropertyWindowLayout(Android.Content.Context context) { TextView pointervalue1 = new TextView(context); pointervalue1.Text = "RangePointer Color"; pointervalue1.Typeface = Typeface.DefaultBold; pointervalue1.SetTextColor(Color.ParseColor("#262626")); pointervalue1.TextSize = 20; Spinner selectLabelMode = new Spinner(context, SpinnerMode.Dialog); adapter = new List<String>() { "Red", "Blue", "Orange" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += SelectLabelMode_ItemSelected; LinearLayout optionsPage = new LinearLayout(context); optionsPage.Orientation = Orientation.Vertical; optionsPage.AddView(pointervalue1); optionsPage.AddView(selectLabelMode); optionsPage.SetPadding(10, 10, 10, 10); optionsPage.SetBackgroundColor(Color.White); return optionsPage; } private void SelectLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter[e.Position]; if (selectedItem.Equals("Red")) { pointer.Color = Color.Red; } else if (selectedItem.Equals("Blue")) { pointer.Color = Color.Blue; } else if (selectedItem.Equals("Orange")) { pointer.Color = Color.Orange; } } } } <file_sep>/Forms/ListView/ListView/Samples/Grouping/Model/ListViewContactsInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] class ListViewContactsInfoRepository { #region Fields private Random random = new Random(); #endregion #region Constructor public ListViewContactsInfoRepository() { } #endregion #region Get Contacts Details public ObservableCollection<ListViewContactsInfo> GetContactDetails(int count) { ObservableCollection<ListViewContactsInfo> customerDetails = new ObservableCollection<ListViewContactsInfo>(); int girlsCount = 0, boysCount = 0; for (int i = 0; i < count; i++) { var details = new ListViewContactsInfo() { ContactType = contactType[random.Next(0, 5)], ContactNumber = random.Next(100, 400).ToString() + "-" + random.Next(500, 800).ToString() + "-" + random.Next(1000, 2000).ToString(), ContactImage = "People_Circle" + (i % 19) + ".png", }; if (imagePosition.Contains(i % 19)) details.ContactName = CustomerNames_Boys[boysCount++ % 32]; else details.ContactName = CustomerNames_Girls[girlsCount++ % 93]; customerDetails.Add(details); } return customerDetails; } #endregion #region Contacts Information int[] imagePosition = new int[] { 5, 8, 12, 14, 18 }; string[] contactType = new string[] { "HOME", "WORK", "MOBILE", "OTHER", "BUSINESS" }; string[] CustomerNames_Girls = new string[] { "Kyle", "Gina", "Brenda", "Danielle", "Fiona", "Lila", "Jennifer", "Liz", "Pete", "Katie", "Vince", "Fiona", "Liam ", "Georgia", "Elijah ", "Alivia", "Evan ", "Ariel", "Vanessa", "Gabriel", "Angelina", "Eli ", "Remi", "Levi", "Alina", "Layla", "Ella", "Mia", "Emily", "Clara", "Lily", "Melanie", "Rose", "Brianna", "Bailey", "Juliana", "Valerie", "Hailey", "Daisy", "Sara", "Victoria", "Grace", "Layla", "Josephine", "Jade", "Evelyn", "Mila", "Camila", "Chloe", "Zoey", "Nora", "Ava", "Natalia", "Eden", "Cecilia", "Finley", "Trinity", "Sienna", "Rachel", "Sawyer", "Amy", "Ember", "Rebecca", "Gemma", "Catalina", "Tessa", "Juliet", "Zara", "Malia", "Samara", "Hayden", "Ruth", "Kamila", "Freya", "Kali", "Leiza", "Myla", "Daleyza", "Maggie", "Zuri", "Millie", "Lilliana", "Kaia", "Nina", "Paislee", "Raelyn", "Talia", "Cassidy", "Rylie", "Laura", "Gracelynn", "Heidi", "Kenzie", }; string[] CustomerNames_Boys = new string[] { "Irene", "Watson", "Ralph", "Torrey", "William", "Bill", "Howard", "Daniel", "Frank", "Jack", "Oscar", "Larry", "Holly", "Steve", "Zeke", "Aiden", "Jackson", "Mason", "Jacob ", "Jayden ", "Ethan ", "Noah ", "Lucas ", "Brayden", "Logan ", "Caleb ", "Caden ", "Benjamin", "Xaviour", "Ryan ", "Connor ", "Michael", }; #endregion } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Model/StockData.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "StockData.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties and notifies clients that a property value has changed. /// </summary> public class StockData : INotifyPropertyChanged { #region Private Members [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string symbol; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string account; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double lastTrade; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double stockChange; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double previousClose; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double open; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private long volume; #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public properties /// <summary> /// Gets or sets the stock change. /// </summary> /// <value>The stock change.</value> public double StockChange { get { return this.stockChange; } set { this.stockChange = value; this.RaisePropertyChanged("StockChange"); } } /// <summary> /// Gets or sets the open. /// </summary> /// <value>The open.</value> public double Open { get { return this.open; } set { this.open = value; this.RaisePropertyChanged("Open"); } } /// <summary> /// Gets or sets the last trade. /// </summary> /// <value>The last trade.</value> public double LastTrade { get { return this.lastTrade; } set { this.lastTrade = value; this.RaisePropertyChanged("LastTrade"); } } /// <summary> /// Gets or sets the previous close. /// </summary> /// <value>The previous close.</value> public double PreviousClose { get { return this.previousClose; } set { this.previousClose = value; this.RaisePropertyChanged("PreviousClose"); } } /// <summary> /// Gets or sets the symbol. /// </summary> /// <value>The symbol.</value> public string Symbol { get { return this.symbol; } set { this.symbol = value; this.RaisePropertyChanged("Symbol"); } } /// <summary> /// Gets or sets the account. /// </summary> /// <value>The account.</value> public string Account { get { return this.account; } set { this.account = value; this.RaisePropertyChanged("Account"); } } /// <summary> /// Gets or sets the volume. /// </summary> /// <value>The volume.</value> public long Volume { get { return this.volume; } set { this.volume = value; this.RaisePropertyChanged("Volume"); } } #endregion #region Public Methods /// <summary> /// Initializes the on. /// </summary> /// <param name="other">The other.</param> public void InitializeOn(StockData other) { this.Symbol = other.Symbol; this.LastTrade = other.LastTrade; this.StockChange = other.StockChange; this.PreviousClose = other.PreviousClose; this.Open = other.Open; this.Volume = other.Volume; } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="propertyName">string type of parameter propertyName</param> public void RaisePropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } }<file_sep>/Forms/RangeNavigator/RangeNavigator.Android/SplashScreenActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser.SfRangeNavigator.Droid { [Activity(Theme = "@style/Theme.Splash", MainLauncher = true, NoHistory = true, Icon = "@drawable/AppIcon")] public class SplashScreenActivity : SampleBrowser.Core.Android.SplashScreenActivity { protected override Type GetMainActivityType() { return typeof(MainActivity); } } } <file_sep>/Forms/TreeMap/TreeMap/Samples/DataLabel/DataLabelViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeMap { [Preserve(AllMembers = true)] public class LabelPopulationViewModel { public LabelPopulationViewModel() { LabelPopulationDetails = new ObservableCollection<LabelPopulationDetail>(); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "China", Population = 1388232693 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "India", Population = 1342512706 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "United States of America", Population = 326474013 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Indonesia", Population = 263510146 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Brazil", Population = 211243220 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Pakistan", Population = 196744376 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Nigeria", Population = 191835936 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Bangladesh", Population = 164827718 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Russian Federation", Population = 143375006 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Mexico", Population = 130222815 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Japan", Population = 126045211 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Ethiopia", Population = 104344901 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Philippines", Population = 103796832 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Viet Nam", Population = 95414640 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Egypt", Population = 95215102 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "D.R. Congo", Population = 82242685 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Iran", Population = 80945718 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Germany", Population = 80636124 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Turkey", Population = 80417526 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Thailand", Population = 68297547 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "United Kingdom", Population = 65511098 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "France", Population = 64938716 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Italy", Population = 59797978 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Tanzania", Population = 56877529 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "South Africa", Population = 55436360 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Myanmar", Population = 54836483 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Republic of Korea", Population = 50704971 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Colombia", Population = 49067981 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Kenya", Population = 48466928 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Spain", Population = 46070146 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Ukraine", Population = 44405055 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Argentina", Population = 44272125 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Sudan", Population = 42166323 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Uganda", Population = 41652938 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Algeria", Population = 41063753 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Iraq", Population = 38654287 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Poland", Population = 38563573 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Canada", Population = 36626083 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Morocco", Population = 35241418 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Afghanistan", Population = 34169169 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Saudi Arabia", Population = 32742664 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Peru", Population = 32166473 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Venezuela", Population = 31925705 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Malaysia", Population = 31164177 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Uzbekistan", Population = 30690914 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Mozambique", Population = 29537914 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Nepal", Population = 29187037 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Ghana", Population = 28656723 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Yemen", Population = 28119546 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Angola", Population = 26655513 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Madagascar", Population = 25612972 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Dem Peoples Republic of Korea", Population = 25405296 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Australia", Population = 24641662 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Cameroon", Population = 24513689 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Côte dIvoire", Population = 23815886 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Taiwan", Population = 23405309 }); LabelPopulationDetails.Add(new LabelPopulationDetail() { Country = "Niger", Population = 21563607 }); } public ObservableCollection<LabelPopulationDetail> LabelPopulationDetails { get; set; } } } <file_sep>/Forms/StepProgressBar/StepProgressBar/Samples/ShipmentTracking/ShipmentTracking.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.ProgressBar; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using Xamarin.Forms; namespace SampleBrowser.SfStepProgressBar { public partial class ShipmentTracking : SampleView { ShipmentViewModel ShipmentViewModel = new ShipmentViewModel(); public ShipmentTracking() { InitializeComponent(); stepProgress.StatusChanged += Step_StatusChanged; ShipmentViewModel.PopulateShipmentDetails(); BindableLayout.SetItemsSource(stepProgress, ShipmentViewModel.ShipmentInfoCollection); } void Step_StatusChanged(object sender, StatusChangedEventArgs e) { int index = stepProgress.Children.IndexOf(e.Item); if (e.Item == stepProgress.Children[stepProgress.Children.Count - 1] && e.Item.Status == StepStatus.Completed) { TrackButton.IsEnabled = true; } } void Handle_Clicked(object sender, System.EventArgs e) { StepView stepView; switch (TrackButton.Text) { case "Track Status": stepProgress.ProgressAnimationDuration = 1000; stepView = stepProgress.Children[3] as StepView; stepView.Status = StepStatus.Completed; TrackButton.Text = "Reset"; TrackButton.IsEnabled = false; break; default: TrackButton.Text = "Track Status"; stepProgress.ProgressAnimationDuration = 1; stepView = stepProgress.Children[0] as StepView; stepView.Status = StepStatus.NotStarted; break; } } } /// <summary> /// Shipment View Model Class /// </summary> public class ShipmentViewModel { private ObservableCollection<Shipment> shipmentInfoCollection = new ObservableCollection<Shipment>(); /// <summary> /// Gets or sets ShipmentInfoCollection /// </summary> public ObservableCollection<Shipment> ShipmentInfoCollection { get { return shipmentInfoCollection; } set { shipmentInfoCollection = value; } } /// <summary> /// Populate shipment details /// </summary> public void PopulateShipmentDetails() { ShipmentInfoCollection.Add(CreateShipmentInfo("Ordered and Approved", "Your Order has been placed.", "Sat, 27th Oct")); ShipmentInfoCollection.Add(CreateShipmentInfo("Packed", "Your item has been picked up by courier partner.", "Mon, 29th Oct")); ShipmentInfoCollection.Add(CreateShipmentInfo("Shipped", "", "")); ShipmentInfoCollection.Add(CreateShipmentInfo("Delivered", "", "")); } /// <summary> /// Create shipment information /// </summary> /// <param name="title">title text</param> /// <param name="titleStatus">status title text</param> /// <param name="date">date text</param> /// <returns>returns shipment</returns> public Shipment CreateShipmentInfo(string title, string titleStatus, string date) { Shipment shipment = new Shipment() { Title = title, TitleStatus = titleStatus, Date = date }; return shipment; } } /// <summary> /// Shipment class /// </summary> public class Shipment : INotifyPropertyChanged { /// <summary> /// title field /// </summary> private string title; /// <summary> /// status title field /// </summary> private string titleStatus; /// <summary> /// date field /// </summary> private string date; /// <summary> /// Gets or sets the Title /// </summary> public string Title { get { return title; } set { if (title != value) { title = value; RaisePropertyChange(); } } } /// <summary> /// Gets or sets the TitleStatus /// </summary> public string TitleStatus { get { return titleStatus; } set { if (titleStatus != value) { titleStatus = value; RaisePropertyChange(); } } } /// <summary> /// Gets or sets Date /// </summary> public string Date { get { return date; } set { if (date != value) { date = value; RaisePropertyChange(); } } } public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChange([CallerMemberName] string propertyname = null) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyname)); } } } /// <summary> /// Title color value converter /// </summary> public class TitleColorConverter : IValueConverter { string checkString = string.Empty; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Span span = parameter as Span; Color color = Color.FromHex("#6E6E6E"); if ((StepStatus)value == StepStatus.Completed) { if (checkString == string.Empty && span.Text != string.Empty) { checkString = span.Text; return color; } switch (span.ClassId) { case "1": color = Color.Black; break; } } else if ((StepStatus)value == StepStatus.NotStarted) { checkString = string.Empty; } return color; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return (Color)value == Color.Black; } } /// <summary> /// Sub title color value converter /// </summary> public class SubTitleColorConverter : IValueConverter { string checkString = string.Empty; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Span span = parameter as Span; Color color = Color.Transparent; if ((StepStatus)value == StepStatus.Completed) { color = Color.Black; } return color; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return (Color)value == Color.Black; } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/Model/CustomerDetails.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.ComponentModel; namespace SampleBrowser { public class CustomerDetails : INotifyPropertyChanged { #region private variables private string _customerID; private string _firstname; private string _lastname; private string _gender; private string _city; private string _country; #endregion #region Public Properties public string CustomerID { get { return _customerID; } set { this._customerID = value; RaisePropertyChanged ("CustomerID"); } } public string FirstName { get { return _firstname; } set { this._firstname = value; RaisePropertyChanged ("FirstName"); } } public string LastName { get { return _lastname; } set { this._lastname = value; RaisePropertyChanged ("LastName"); } } public string Gender { get { return _gender; } set { this._gender = value; RaisePropertyChanged ("Gender"); } } public string City { get { return _city; } set { this._city = value; RaisePropertyChanged ("City"); } } public string Country { get { return _country; } set { this._country = value; RaisePropertyChanged ("Country"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged (String Name) { if (PropertyChanged != null) this.PropertyChanged (this, new PropertyChangedEventArgs (Name)); } #endregion } }<file_sep>/Forms/AvatarView/AvatarView/Samples/VisualStyleSample/VisualStyleSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.AvatarView; using System.Collections.ObjectModel; using Avatar = Syncfusion.XForms.AvatarView; using Xamarin.Forms; using System; namespace SampleBrowser.SfAvatarView { #region Visual Style Sample public partial class VisualStyleSample : SampleView { private ContentType avatarType; public ContentType AvatarType { get { return avatarType; } set { avatarType = value; this.OnPropertyChanged(); } } public ObservableCollection<People> TotalPeople { get; set; } #region Constructor public VisualStyleSample() { InitializeComponent(); this.InitialAvatar.AvatarSize = this.DefaultAvatar.AvatarSize = this.CustomAvatar.AvatarSize = this.GroupAvatar.AvatarSize = AvatarSize.Large; this.DefaultAvatar.BorderColor = this.CustomAvatar.BorderColor = this.GroupAvatar.BorderColor = Color.White; this.DefaultAvatar.BorderWidth = this.CustomAvatar.BorderWidth = this.GroupAvatar.BorderWidth = 6; this.InitialAvatar.BorderWidth = 2; this.InitialAvatar.BorderColor = Color.Black; this.AddTapGestures(); this.TotalPeople = new ObservableCollection<People>(); this.TotalPeople.Add(new People() { Name = "Michael", Image = "People_Square30.png" }); this.TotalPeople.Add(new People() { Name = "Kyle", Image = "Avatar2.png" }); this.TotalPeople.Add(new People() { Name = "Nora" }); this.BindingContext = this; } #endregion private void AddTapGestures() { TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer(); tapGestureRecognizer.Tapped += TapGestureRecognizer_Tapped; this.InitialAvatar.GestureRecognizers.Add(tapGestureRecognizer); this.DefaultAvatar.GestureRecognizers.Add(tapGestureRecognizer); this.CustomAvatar.GestureRecognizers.Add(tapGestureRecognizer); this.GroupAvatar.GestureRecognizers.Add(tapGestureRecognizer); } private void TapGestureRecognizer_Tapped(object sender, EventArgs e) { this.InitialAvatar.BorderColor = this.DefaultAvatar.BorderColor = this.CustomAvatar.BorderColor = this.GroupAvatar.BorderColor = Color.White; this.InitialAvatar.BorderWidth = this.DefaultAvatar.BorderWidth = this.CustomAvatar.BorderWidth = this.GroupAvatar.BorderWidth = 6; Avatar.SfAvatarView tappedAvatar = (sender as Avatar.SfAvatarView); this.AvatarType = tappedAvatar.ContentType; tappedAvatar.BorderColor = Color.Black; tappedAvatar.BorderWidth = 2; } } #endregion }<file_sep>/Forms/Chart/Chart/Samples/Trendlines/ChartTrendlines.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfChart { public partial class ChartTrendlines : SampleView { public ChartTrendlines() { InitializeComponent(); } private void OnStepper3_ValueChanged(object sender, ValueChangedEventArgs e) { polynomialLabel.Text = "Polynomial Order: " + e.NewValue; } private void OnStepper2_ValueChanged(object sender, ValueChangedEventArgs e) { backwardForecast.Text = "Backward Forecast: " + e.NewValue; } private void OnStepper1_ValueChanged(object sender, ValueChangedEventArgs e) { forwardForecast.Text = "Forward Forecast: " + e.NewValue; } } public class VisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return !(bool)value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } }<file_sep>/Forms/Chart/Chart/Samples/AreaChart/AreaSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class AreaSeriesViewModel { public ObservableCollection<ChartDataModel> AreaData1 { get; set; } public ObservableCollection<ChartDataModel> AreaData2 { get; set; } public AreaSeriesViewModel() { AreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2000, 4), new ChartDataModel(2001, 3.0), new ChartDataModel(2002, 3.8), new ChartDataModel(2003, 4.4), new ChartDataModel(2004, 3.2), new ChartDataModel(2005, 3.9), }; AreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2000, 2.6), new ChartDataModel(2001, 2.8), new ChartDataModel(2002, 2.6), new ChartDataModel(2003, 3), new ChartDataModel(2004, 3.6), new ChartDataModel(2005, 3), }; } } } <file_sep>/Forms/Chart/Chart/Samples/CategoryAxis/CategoryAxis.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using Xamarin.Forms; namespace SampleBrowser.SfChart { public partial class CategoryAxis : SampleView { public CategoryAxis() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { axisLabelStyle.FontSize = 14; } } private void Switch_Toggled(object sender, ToggledEventArgs e) { if (e.Value) { primary.ArrangeByIndex = true; Chart.SideBySideSeriesPlacement = true; axisLabelStyle.MaxWidth = double.NaN; } else { primary.ArrangeByIndex = false; Chart.SideBySideSeriesPlacement = false; axisLabelStyle.WrappedLabelAlignment = ChartAxisLabelAlignment.Center; if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { axisLabelStyle.MaxWidth = 40; } else if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { axisLabelStyle.MaxWidth = 80; } } } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/CellTemplateModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "CellTemplateModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains properties /// </summary> public class CellTemplateModel { #region Private Variables [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int employeeID; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string firstName; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string designation; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DateTime birthDate; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string image; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string city; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string country; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string telePhone; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string about; #endregion /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the value of EmployeeID and notifies user when value gets changed /// </summary> public int EmployeeID { get { return this.employeeID; } set { this.employeeID = value; this.RaisePropertyChanged("EmployeeID"); } } /// <summary> /// Gets or sets the value of Designation and notifies user when value gets changed /// </summary> public string Designation { get { return this.designation; } set { this.designation = value; this.RaisePropertyChanged("Designation"); } } /// <summary> /// Gets or sets the value of Name and notifies user when value gets changed /// </summary> public string Name { get { return this.firstName; } set { this.firstName = value; this.RaisePropertyChanged("FirstName"); } } /// <summary> /// Gets or sets the value of DateOfBirth and notifies user when value gets changed /// </summary> public DateTime DateOfBirth { get { return this.birthDate; } set { this.birthDate = value; this.RaisePropertyChanged("DateOfBirth"); } } /// <summary> /// Gets or sets the value of Image and notifies user when value gets changed /// </summary> public string Image { get { return this.image; } set { this.image = value; this.RaisePropertyChanged("Address"); } } /// <summary> /// Gets or sets the value of City and notifies user when value gets changed /// </summary> public string City { get { return this.city; } set { this.city = value; this.RaisePropertyChanged("City"); } } /// <summary> /// Gets or sets the value of Country and notifies user when value gets changed /// </summary> public string Country { get { return this.country; } set { this.country = value; this.RaisePropertyChanged("Country"); } } /// <summary> /// Gets or sets the value of Telephone and notifies user when value gets changed /// </summary> public string Telephone { get { return this.telePhone; } set { this.telePhone = value; this.RaisePropertyChanged("Telephone"); } } /// <summary> /// Gets or sets the value of About and notifies user when value gets changed /// </summary> public string About { get { return this.about; } set { this.about = value; this.RaisePropertyChanged("About"); } } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } }<file_sep>/Forms/TabView/TabView/Samples/TabViewGettingStarted/Model/TabData.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.ComponentModel; using System.Runtime.CompilerServices; namespace SampleBrowser.SfTabView { public class TabData : INotifyPropertyChanged { private string category; public string Category { get { return category; } set { category = value; RaiseOnPropertyChanged(nameof(Category)); } } private string description; public string Description { get { return description; } set { description = value; RaiseOnPropertyChanged(nameof(Description)); } } private string imagePath; public string ImagePath { get { return imagePath; } set { imagePath = value; RaiseOnPropertyChanged(nameof(ImagePath)); } } private string name; public string Name { get { return name; } set { name = value; RaiseOnPropertyChanged(nameof(Name)); } } private double price; public double Price { get { return price; } set { price = value; RaiseOnPropertyChanged(nameof(Price)); } } private string offer; public string Offer { get { return offer; } set { offer = value; RaiseOnPropertyChanged(nameof(Offer)); } } private string rating; public string Rating { get { return rating; } set { rating = value; RaiseOnPropertyChanged(nameof(Rating)); } } /// <inheritdoc /> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// This method is called by the Set accessor of each property. /// The CallerMemberName attribute that is applied to the optional propertyName /// parameter causes the property name of the caller to be substituted as an argument. /// </summary> /// <param name="propertyName"></param> protected virtual void RaiseOnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/iOS/SampleBrowser/Controllers/HomeViewController.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Foundation; using UIKit; using Syncfusion.SfNavigationDrawer.iOS; using CoreAnimation; namespace SampleBrowser { public class HomeViewController : UIViewController { #region fields private CALayer overlay; private UIButton menuButton; private UIImageView userImg; private UILabel title, version, headerDetails; private UICollectionView collectionViewAllControls; private UICollectionViewFlowLayout flowLayoutAllControls; private UIView content, header, HeaderView, centerview, yellowSeperater; #endregion #region ctor public HomeViewController() { Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(string.Empty); this.View.BackgroundColor = Utility.BackgroundColor; } protected HomeViewController(IntPtr handle) : base(handle) { } #endregion #region properties public static SFNavigationDrawer NavigationDrawer { get; set; } public UITableView Table { get; set; } public NSMutableArray Controls { get; set; } public CALayer BottomBorder { get; set; } #endregion #region methods public override void ViewDidLoad() { base.ViewDidLoad(); content = new UIView { Frame = this.View.Frame }; this.ParseControlsPlist(); this.LoadHeaderView(); } public void DrawerEvent(int index) { switch (index) { case 0: UIApplication.SharedApplication.OpenUrl(new NSUrl("https://www.syncfusion.com/products/xamarin")); break; case 1: UIApplication.SharedApplication.OpenUrl(new NSUrl("https://www.syncfusion.com/products/whatsnew/xamarin-iOS")); break; case 2: UIApplication.SharedApplication.OpenUrl(new NSUrl("https://help.syncfusion.com/xamarin-ios/introduction/overview")); break; default: break; } HideDrawer(true); } public void HideDrawer(bool flag) { overlay.Hidden = flag; NavigationDrawer.ToggleDrawer(); } public void HideOverlay() { overlay.Hidden = true; } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); this.NavigationController.SetNavigationBarHidden(true, false); } public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); overlay.Hidden = true; } public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); content.Frame = this.View.Frame; overlay.Frame = this.View.Frame; NavigationDrawer.Frame = new CGRect(0, 0, this.View.Frame.Width, this.View.Frame.Height); HeaderView.Frame = new CGRect(0, 0, NavigationDrawer.DrawerWidth, (NavigationDrawer.Frame.Height * 65) / 100); nfloat yellowLineStart = (HeaderView.Frame.Height * 50) / 100; yellowSeperater.Frame = new CGRect(20, yellowLineStart, HeaderView.Frame.Width - 40, 3); headerDetails.Frame = new CGRect(20, yellowLineStart + 6, HeaderView.Frame.Width - 40, yellowLineStart - 50); nfloat x = 20, y = yellowLineStart - 100; float imageWidth = 200, imageHeight = 70, lblWidth = 140; userImg.Frame = new CGRect(x, y, imageWidth, imageHeight); version.Frame = new CGRect(HeaderView.Frame.Width - 120, HeaderView.Frame.Height - 50, 150, 50); centerview.Frame = new CGRect(0, lblWidth, NavigationDrawer.DrawerWidth, 500); NavigationDrawer.DrawerHeaderView = HeaderView; NavigationDrawer.DrawerHeaderView.Superview.BackgroundColor = UIColor.Clear; NavigationDrawer.DrawerContentView = centerview; NavigationDrawer.DrawerContentView.BackgroundColor = UIColor.FromRGBA(1.0f, 1.0f, 1.0f, 0.96f); NavigationDrawer.DrawerContentView.Superview.BackgroundColor = UIColor.Clear; NavigationDrawer.DrawerHeaderHeight = (NavigationDrawer.Frame.Height * 65) / 100; NavigationDrawer.DidClose += NavigationDrawer_DidClose; nfloat width = this.View.Frame.Size.Width; nfloat height = this.View.Frame.Size.Height; float itemSpace = Utility.IsIPad ? 15 : 10; nfloat startY = 30; menuButton.Frame = new CGRect(10, startY, 22, 22); title.Frame = new CGRect(40, startY, height, 22); startY += title.Frame.Height + itemSpace; header.Frame = new CGRect(0, 0, width, startY); startY += 10; collectionViewAllControls.Frame = new CGRect(0, startY, width, height - startY); flowLayoutAllControls.ItemSize = new CGSize(width - 20, 100); if (Utility.IsIPad) { nfloat cellWidth = (width / 2) - 60; collectionViewAllControls.Frame = new CGRect(50, startY, width - 100, height - startY); flowLayoutAllControls.ItemSize = new CGSize(cellWidth, 100); } } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); } private void NavigationDrawer_DidClose(object sender, EventArgs e) { overlay.Hidden = true; } private void ParseControlsPlist() { string controlListPathString = NSBundle.MainBundle.BundlePath + "/plist/ControlList.plist"; NSDictionary controlDict = new NSDictionary(); controlDict = NSDictionary.FromFile(controlListPathString); NSString controlDictKey = new NSString("Control"); NSArray controlDictArray = controlDict.ValueForKey(controlDictKey) as NSArray; Controls = new NSMutableArray(); if (controlDictArray.Count > 0) { for (nuint i = 0; i < controlDictArray.Count; i++) { NSDictionary dict = controlDictArray.GetItem<NSDictionary>(i); string image = dict.ValueForKey(new NSString("ControlName")).ToString(); image = "Controls/" + image; Control control = new Control { Name = new NSString(dict.ValueForKey(new NSString("ControlName")).ToString()), Description = new NSString(dict.ValueForKey(new NSString("Description")).ToString()), Image = UIImage.FromBundle(image) }; if (!UIDevice.CurrentDevice.CheckSystemVersion(9, 0) && control.Name == "PDFViewer") { continue; } if (dict.ValueForKey(new NSString("IsNew")) != null && dict.ValueForKey(new NSString("IsNew")).ToString() == "YES") { control.Tag = new NSString("NEW"); } else if (dict.ValueForKey(new NSString("IsUpdated")) != null && dict.ValueForKey(new NSString("IsUpdated")).ToString() == "YES") { control.Tag = new NSString("UPDATED"); } else if (dict.ValueForKey(new NSString("IsPreview")) != null && dict.ValueForKey(new NSString("IsPreview")).ToString() == "YES") { control.Tag = new NSString("PREVIEW"); } else { control.Tag = new NSString(string.Empty); } if (dict.ValueForKey(new NSString("Type1")) != null) { control.IsMultipleSampleView = true; control.Type1 = new NSString(dict.ValueForKey(new NSString("Type1")).ToString()); control.Type2 = new NSString(dict.ValueForKey(new NSString("Type2")).ToString()); } Controls.Add(control); } } } private static string[] GetTableItems() { return new string[] { "Product Page", "Whats New", "Documentation" }; } private void LoadHeaderView() { NavigationDrawer = new SFNavigationDrawer { BackgroundColor = UIColor.Clear, ContentView = content }; menuButton = new UIButton(); menuButton.SetBackgroundImage(new UIImage("Images/menu.png"), UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { NavigationDrawer.DrawerWidth = (this.View.Bounds.Width * 40) / 100; } else { NavigationDrawer.DrawerWidth = (this.View.Bounds.Width * 75) / 100; } NavigationDrawer.DrawerHeight = this.View.Bounds.Height; HeaderView = new UIView { BackgroundColor = UIColor.FromRGBA(249.0f / 255.0f, 78.0f / 255.0f, 56.0f / 255.0f, 0.97f) }; userImg = new UIImageView { Image = new UIImage("Controls/synclogo.png") }; version = new UILabel { Text = "Version " + NSUserDefaults.StandardUserDefaults.ValueForKey(new NSString("VersionNumber")), Font = UIFont.FromName("Helvetica", 12f), TextColor = UIColor.White, TextAlignment = UITextAlignment.Left }; HeaderView.AddSubview(version); yellowSeperater = new UIView { BackgroundColor = UIColor.FromRGB(255.0f / 255.0f, 198.0f / 255.0f, 14.0f / 255.0f) }; HeaderView.AddSubview(yellowSeperater); headerDetails = new UILabel { LineBreakMode = UILineBreakMode.WordWrap, Lines = 0, Text = "The toolkit contains all the components that are typically required for building line-of-business applications for IOS", TextColor = UIColor.White, Font = UIFont.FromName("Helvetica", 18f) }; HeaderView.AddSubview(headerDetails); HeaderView.AddSubview(userImg); Table = new UITableView(new CGRect(0, 20, NavigationDrawer.DrawerWidth, this.View.Frame.Height)) { SeparatorColor = UIColor.Clear }; NavigationTableSource tablesource = new NavigationTableSource(this, GetTableItems()) { Customize = false }; Table.Source = tablesource; Table.BackgroundColor = UIColor.Clear; centerview = new UIView { Table }; centerview.BackgroundColor = UIColor.Clear; NavigationDrawer.Position = SFNavigationDrawerPosition.SFNavigationDrawerPositionLeft; menuButton.TouchDown += (object sender, System.EventArgs e) => { HideDrawer(false); }; header = new UIView { BackgroundColor = UIColor.FromRGB(0, 122.0f / 255.0f, 238.0f / 255.0f) }; title = new UILabel { TextColor = UIColor.White, Text = "Syncfusion Xamarin Samples", Font = UIFont.FromName("HelveticaNeue-Medium", 16f) }; flowLayoutAllControls = new UICollectionViewFlowLayout { MinimumLineSpacing = 5, ScrollDirection = UICollectionViewScrollDirection.Vertical }; collectionViewAllControls = new UICollectionView(CGRect.Empty, flowLayoutAllControls); collectionViewAllControls.RegisterClassForCell(typeof(UICollectionViewCell), "controlCell"); collectionViewAllControls.DataSource = new AllControlsCollectionSource(Controls); collectionViewAllControls.Delegate = new AllControlsCollectionDelegate(this); collectionViewAllControls.BackgroundColor = Utility.BackgroundColor; UINib nibAllControls = UINib.FromName("ControlCell_9", null); collectionViewAllControls.RegisterNibForCell(nibAllControls, "controlCell"); BottomBorder = new CALayer { BorderWidth = 1, BorderColor = UIColor.FromRGB(213.0f / 255.0f, 213.0f / 255.0f, 213.0f / 255.0f).CGColor, Hidden = true }; content.AddSubview(header); content.AddSubview(menuButton); content.AddSubview(title); content.AddSubview(collectionViewAllControls); overlay = new CALayer { ZPosition = 1000, Hidden = true, BackgroundColor = UIColor.FromRGBA(0.0f / 255.0f, 0.0f / 255.0f, 0.0f / 255.0f, 0.05f).CGColor }; content.Layer.AddSublayer(overlay); this.View.AddSubview(NavigationDrawer); } #endregion } }<file_sep>/Forms/PdfViewer/PdfViewer/Samples/Form Filling/FillAndSign.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfPdfViewer.XForms; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.IO; namespace SampleBrowser.SfPdfViewer { [Preserve(AllMembers = true)] public partial class FillAndSign : SampleView { private float backUpVerticalOffset = 0; private float backUpHorizontalOffset = 0; private float backUpZoomFactor = 0; string currentDocument = "FormFillingDocument"; private bool canRestoreBackup = false; private bool isPageSwitched = false; public FillAndSign() { InitializeComponent(); pdfViewerControl.DocumentSaveInitiated += PdfViewerControl_DocumentSaved; pdfViewerControl.DocumentLoaded += PdfViewerControl_DocumentLoaded; (BindingContext as GettingStartedViewModel).DocumentName = currentDocument; isPageSwitched = true; } private void PdfViewerControl_DocumentLoaded(object sender, EventArgs args) { if (Device.RuntimePlatform == Device.Android) { if (canRestoreBackup) { pdfViewerControl.ZoomPercentage = backUpZoomFactor; pdfViewerControl.VerticalOffset = backUpVerticalOffset; pdfViewerControl.HorizontalOffset = backUpHorizontalOffset; canRestoreBackup = false; } } } public override void OnAppearing() { if (Device.RuntimePlatform == Device.Android) { string filePath = string.Empty; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif canRestoreBackup = !isPageSwitched; if (!isPageSwitched) { (BindingContext as GettingStartedViewModel).PdfDocumentStream = (typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath + "Assets." + currentDocument + ".pdf")); } } } public override void OnDisappearing() { if (Device.RuntimePlatform == Device.Android) { backUpHorizontalOffset = pdfViewerControl.HorizontalOffset; backUpVerticalOffset = pdfViewerControl.VerticalOffset; backUpZoomFactor = pdfViewerControl.ZoomPercentage; pdfViewerControl.Unload(); GC.Collect(); GC.WaitForPendingFinalizers(); isPageSwitched = false; } } private void PdfViewerControl_DocumentSaved(object sender, DocumentSaveInitiatedEventArgs args) { string filePath = DependencyService.Get<ISave>().Save(args.SaveStream as MemoryStream); string message = "The PDF has been saved to " + filePath; DependencyService.Get<IAlertView>().Show(message); } } } <file_sep>/iOS/SampleBrowser/Samples/Diagram/DataModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.ComponentModel; namespace SampleBrowser { public class DataModel { //Initialize Employee Class internal ObservableCollection<DiagramEmployee> employee = new ObservableCollection<DiagramEmployee>(); //Get Employee Details internal void Data() { employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2014", Name = "<NAME>", Designation = "Managing Director", ImageUrl = "Images/Diagram/eric.png", EmailId = "<EMAIL>", HasChild = true, }); //hierarchy 1 employee.Add(new DiagramEmployee() { ID = "84937", DOJ = "18/10/2011", Name = "<NAME>", Designation = "Senior Manager", ImageUrl = "Images/Diagram/Image0.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2010", Name = "<NAME>", Designation = "Senior Manager", ImageUrl = "Images/Diagram/Maria.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); //hierarchy 2 employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2014", Name = "<NAME>", Designation = "Project Manager", ImageUrl = "Images/Diagram/Image17.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Ana Trujillo" }); employee.Add(new DiagramEmployee() { ID = "03947", DOJ = "18/10/2013", Name = "<NAME>", Designation = "Project Manager", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2013", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/Image10.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "10101", DOJ = "01/03/2015", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/Image11.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); //hierarchy 3 employee.Add(new DiagramEmployee() { ID = "19287", DOJ = "18/10/2011", Name = "<NAME>", Designation = "Project Lead", ImageUrl = "Images/Diagram/Image12.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Philip Cramer" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2015", Name = "<NAME>", Designation = "Project Lead", ImageUrl = "Images/Diagram/Image14.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Philip Cramer" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2012", Name = "<NAME>", Designation = "Project Lead", ImageUrl = "Images/Diagram/Image18.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Anto Moreno" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2015", Name = "<NAME>", Designation = "Project Lead", ImageUrl = "Images/Diagram/Image15.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Anto Moreno" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2017", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/Image17.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Victoria Ash" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2012", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/Image29.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2016", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/images9.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Eduardo Roel" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "18/10/2011", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Eduardo Roel" }); //Hierarchy 4 employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "15/10/2015", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/Paul.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "C<NAME>y" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "15/10/2011", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/Image30.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "59305", DOJ = "15/10/2013", Name = "<NAME>", Designation = "Project Lead", ImageUrl = "Images/Diagram/image51.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "95836", DOJ = "15/10/2012", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/Image21.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "03993", DOJ = "15/10/2012", Name = "<NAME>", Designation = "Project Lead", ImageUrl = "Images/Diagram/Image26.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "01992", DOJ = "15/10/2015", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/Image30.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "H<NAME>" }); employee.Add(new DiagramEmployee() { ID = "95837", DOJ = "15/10/2016", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/image51.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Peter Citeaux" }); employee.Add(new DiagramEmployee() { ID = "93711", DOJ = "15/10/2015", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/image56.PNG", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Peter Citeaux" }); employee.Add(new DiagramEmployee() { ID = "04992", DOJ = "15/03/2015", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/images9.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "MartÌn Kloss" }); employee.Add(new DiagramEmployee() { ID = "83735", DOJ = "15/03/2012", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/images9.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "MartÌn Kloss" }); employee.Add(new DiagramEmployee() { ID = "81777", DOJ = "01/03/2011", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/images12.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "99994", DOJ = "01/03/2016", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/Clayton.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "98823", DOJ = "01/03/2011", Name = "<NAME>", Designation = "Software Engg", ImageUrl = "Images/Diagram/Thomas.PNG", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Francisco Yang" }); employee.Add(new DiagramEmployee() { ID = "20398", DOJ = "01/03/2016", Name = "<NAME>", Designation = "Software Engg", ImageUrl = "Images/Diagram/images9.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Francisco Yang" }); employee.Add(new DiagramEmployee() { ID = "77738", DOJ = "01/03/2017", Name = "<NAME>", Designation = "Software Engg", ImageUrl = "Images/Diagram/Image14.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Yang Wang" }); employee.Add(new DiagramEmployee() { ID = "91292", DOJ = "01/03/2010", Name = "<NAME>", Designation = "Software Engg", ImageUrl = "Images/Diagram/Image18.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Yang Wang" }); //hierarchy 5 employee.Add(new DiagramEmployee() { ID = "65522", DOJ = "01/03/2011", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/Clayton.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "99181", DOJ = "01/03/2012", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image29.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "03993", DOJ = "01/03/2011", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/Maria.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Elizabe<NAME>" }); employee.Add(new DiagramEmployee() { ID = "81918", DOJ = "01/03/2017", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Clayton.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "06999", DOJ = "17/03/2010", Name = "<NAME>", Designation = "Project Lead", ImageUrl = "Images/Diagram/Image16.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "73779", DOJ = "17/03/2010", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/image51.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "27222", DOJ = "17/03/2013", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "36339", DOJ = "17/08/2013", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image17.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "10295", DOJ = "17/08/2013", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/Clayton.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "95826", DOJ = "17/08/2012", Name = "<NAME>", Designation = "Team Lead", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Roland Mendel" }); employee.Add(new DiagramEmployee() { ID = "28291", DOJ = "17/08/2012", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "10395", DOJ = "17/08/2012", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image30.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Aria Cruz" }); employee.Add(new DiagramEmployee() { ID = "00041", DOJ = "17/08/2014", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/images12.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Martine RancÈ" }); employee.Add(new DiagramEmployee() { ID = "90906", DOJ = "09/08/2014", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/Image17.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Martine RancÈ" }); employee.Add(new DiagramEmployee() { ID = "77282", DOJ = "09/122014", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/Image26.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "19098", DOJ = "09/122014", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Maria Larsson" }); employee.Add(new DiagramEmployee() { ID = "75638", DOJ = "09/122016", Name = "<NAME>", Designation = "Software Engg", ImageUrl = "Images/Diagram/Image18.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Diego Roel" }); employee.Add(new DiagramEmployee() { ID = "60021", DOJ = "09/122016", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/images9.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Diego Roel" }); employee.Add(new DiagramEmployee() { ID = "50090", DOJ = "09/122016", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/Image30.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "80091", DOJ = "09/122012", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Clayton.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "78890", DOJ = "09/122012", Name = "<NAME>", Designation = "Software Engg", ImageUrl = "Images/Diagram/Image12.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Carine Schmitt" }); employee.Add(new DiagramEmployee() { ID = "62777", DOJ = "09/122012", Name = "<NAME>", Designation = "Senior S/W Engg", ImageUrl = "Images/Diagram/Image11.png", EmailId = "<EMAIL>", HasChild = true, ReportingPerson = "Carine Schmitt" }); employee.Add(new DiagramEmployee() { ID = "01973", DOJ = "28/122012", Name = "<NAME>", Designation = "Software Engg", ImageUrl = "Images/Diagram/Image19.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Paolo Accorti" }); employee.Add(new DiagramEmployee() { ID = "74891", DOJ = "28/122012", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Paolo Accorti" }); employee.Add(new DiagramEmployee() { ID = "66201", DOJ = "28/122012", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Maria.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "39846", DOJ = "28/122015", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image0.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "<NAME>" }); employee.Add(new DiagramEmployee() { ID = "18276", DOJ = "28/072015", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/images9.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Howard Snyd" }); employee.Add(new DiagramEmployee() { ID = "30497", DOJ = "28/072015", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Clayton.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Manu Pereira" }); employee.Add(new DiagramEmployee() { ID = "91811", DOJ = "28/072015", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image15.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Manu Pereira" }); employee.Add(new DiagramEmployee() { ID = "77777", DOJ = "28/072016", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image14.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Mario Pontes" }); employee.Add(new DiagramEmployee() { ID = "11786", DOJ = "28/06/2016", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Mario Pontes" }); //Hierarchy 6 employee.Add(new DiagramEmployee() { ID = "55555", DOJ = "18/072016", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image15.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Annette Roel" }); employee.Add(new DiagramEmployee() { ID = "11111", DOJ = "18/072017", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image22.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Annette Roel" }); employee.Add(new DiagramEmployee() { ID = "93018", DOJ = "18/072017", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Felipe Kloss" }); employee.Add(new DiagramEmployee() { ID = "83781", DOJ = "18/072017", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image29.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Felipe Kloss" }); employee.Add(new DiagramEmployee() { ID = "84902", DOJ = "18/05/2017", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Jean FresniËre" }); employee.Add(new DiagramEmployee() { ID = "83937", DOJ = "18/03/2017", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image21.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Jean FresniËre" }); employee.Add(new DiagramEmployee() { ID = "88729", DOJ = "18/04/2015", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/image54.PNG", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Yoshi Kenna" }); employee.Add(new DiagramEmployee() { ID = "98765", DOJ = "18/06/2015", Name = "Nancy", Designation = "Project Trainee", ImageUrl = "Images/Diagram/Image18.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Yoshi Kenna" }); employee.Add(new DiagramEmployee() { ID = "23456", DOJ = "23/12/2015", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Images/Diagram/image57.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Horst Kloss" }); employee.Add(new DiagramEmployee() { ID = "09876", DOJ = "23/12/2015", Name = "<NAME>", Designation = "Project Trainee", ImageUrl = "Image14.png", EmailId = "<EMAIL>", HasChild = false, ReportingPerson = "Horst Kloss" }); } } } /// <summary> /// Employee class /// </summary> public class DiagramEmployee : INotifyPropertyChanged { private string name; private double salary; private string destination; private string imageurl; private string doj; private string emailid; private double contactno; private string reportingPerson; private bool haschild; public DiagramEmployee() { } /// <summary> /// Get or set the haschild /// </summary> public bool HasChild { get { return haschild; } set { haschild = value; } } private string _mDesignation; private string id; /// <summary> /// Get or set the designation /// </summary> public string Designation { get { return _mDesignation; } set { if (_mDesignation != value) { _mDesignation = value; OnPropertyChanged("Designation"); } } } /// <summary> /// Get or set the name /// </summary> public string Name { get { return name; } set { if (name != value) { name = value; OnPropertyChanged(("Name")); } } } public string ID { get { return id; } set { if (id != value) { id = value; OnPropertyChanged(("ID")); } } } /// <summary> /// Get or set the reporting person /// </summary> public string ReportingPerson { get { return reportingPerson; } set { if (reportingPerson != value) { reportingPerson = value; OnPropertyChanged(("ReportingPerson")); } } } /// <summary> /// Get or set the reportingid /// </summary> public int ReportingId { get; set; } /// <summary> /// Get or set the salary /// </summary> public double Salary { get { return salary; } set { if (salary != value) { salary = value; OnPropertyChanged(("Salary")); } } } /// <summary> /// Get or set the destination /// </summary> public string Destination { get { return destination; } set { if (destination != value) { if (value != null) { destination = value; OnPropertyChanged(("Destination")); } } } } /// <summary> /// Get or set the imageurl /// </summary> public string ImageUrl { get { return imageurl; } set { if (imageurl != value) { if (value != null) { imageurl = value; OnPropertyChanged(("ImageUrl")); } } } } /// <summary> /// Get or set the DOJ /// </summary> public string DOJ { get { return doj; } set { if (doj != value) { doj = value; OnPropertyChanged(("Doj")); } } } /// <summary> /// Get or set the email id /// </summary> public string EmailId { get { return emailid; } set { if (emailid != value) { emailid = value; OnPropertyChanged(("EmailId")); } } } /// <summary> /// Get or set the ContactNo /// </summary> public double ContactNo { get { return contactno; } set { if (contactno != value) { contactno = value; OnPropertyChanged(("ContactNo")); } } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name)); } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/RangeBar.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; #endif namespace SampleBrowser { public class RangeBar : SampleView { SFChart chart; public RangeBar() { chart = new SFChart(); chart.Title.Text = new NSString("Pipeline Volume"); chart.Title.Font = UIFont.SystemFontOfSize(13); SFCategoryAxis categoryaxis = new SFCategoryAxis(); categoryaxis.ShowMajorGridLines = false; categoryaxis.AxisLineStyle.LineWidth = 0; categoryaxis.MajorTickStyle.LineSize = 0; categoryaxis.LabelStyle.Color = UIColor.Black; categoryaxis.LabelStyle.Font = UIFont.SystemFontOfSize(11); chart.PrimaryAxis = categoryaxis; SFNumericalAxis numericalaxis = new SFNumericalAxis(); numericalaxis.Visible = false; numericalaxis.ShowMajorGridLines = false; numericalaxis.AxisLineStyle.LineWidth = 0; numericalaxis.MajorTickStyle.LineSize = 0; chart.SecondaryAxis = numericalaxis; ChartViewModel dataModel = new ChartViewModel(); SFRangeColumnSeries rangeColumnSeries = new SFRangeColumnSeries(); rangeColumnSeries.ItemsSource = dataModel.RangeBarData; rangeColumnSeries.XBindingPath = "XValue"; rangeColumnSeries.High = "YValue"; rangeColumnSeries.Low = string.Empty; rangeColumnSeries.DataMarker.ShowLabel = true; NSNumberFormatter formatter = new NSNumberFormatter(); formatter.PositiveFormat = "$#,###"; rangeColumnSeries.DataMarker.LabelStyle.LabelFormatter = formatter; rangeColumnSeries.IsTransposed = true; rangeColumnSeries.ColorModel.Palette = SFChartColorPalette.Natural; chart.Series.Add(rangeColumnSeries); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } } <file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/BookmarkHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using CoreGraphics; using Foundation; using Syncfusion.Pdf.Interactive; using UIKit; namespace SampleBrowser { internal class BookmarkToolbar : UIView { internal UITableView bookmarkListView; private UILabel title; private UIButton backButton, bookmarkCloseButton; private UIView border, titleContainer; internal CustomToolbar parentView; internal BookmarkToolbar(CustomToolbar parent) { parentView = parent; border = new UIView(); border.BackgroundColor = UIColor.LightGray; titleContainer = new UIView(); titleContainer.BackgroundColor = new UIColor(red: 0.97f, green: 0.97f, blue: 0.97f, alpha: 1.0f); //Title label that displays "Bookmarks" title = new UILabel(); title.Text = "Bookmarks"; title.Font = UIFont.BoldSystemFontOfSize(14); title.TextColor = UIColor.Black; title.TextAlignment = UITextAlignment.Left; //Button to remove the bookmark toolbar (mobile only) backButton = new UIButton(); backButton.AccessibilityIdentifier = "backbutton"; backButton.Font = parentView.bookmarkFont; backButton.SetTitle("\ue709", UIControlState.Normal); backButton.SetTitleColor(UIColor.FromRGB(113, 113, 113), UIControlState.Normal); backButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; backButton.VerticalAlignment = UIControlContentVerticalAlignment.Center; backButton.TouchUpInside += BackButton_TouchUpInside; bookmarkCloseButton = new UIButton(); bookmarkCloseButton.AccessibilityIdentifier = "bookmarkCloseButton"; bookmarkCloseButton.Font = parentView.highFont; bookmarkCloseButton.SetTitle("\uE70f", UIControlState.Normal); bookmarkCloseButton.SetTitleColor(UIColor.FromRGB(113, 113, 113), UIControlState.Normal); bookmarkCloseButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; bookmarkCloseButton.VerticalAlignment = UIControlContentVerticalAlignment.Center; bookmarkCloseButton.TouchUpInside += bookmarkCloseButton_TouchUpInside; ; bookmarkListView = new UITableView(); bookmarkListView.RowHeight = 60; bookmarkListView.SeparatorStyle = UITableViewCellSeparatorStyle.None; bookmarkListView.Source = new BookmarkListSource(parentView, bookmarkListView); titleContainer.AddSubview(title); this.AddSubview(bookmarkListView); this.AddSubview(titleContainer); //Add back button or left border only if the device is mobile or tablet respectively if ((UIDevice.CurrentDevice).UserInterfaceIdiom != UIUserInterfaceIdiom.Pad) titleContainer.AddSubview(backButton); else { this.AddSubview(border); this.AddSubview(bookmarkCloseButton); } } //Handle the click event of close button on the title bar of tablet bookmark toolbar private void bookmarkCloseButton_TouchUpInside(object sender, EventArgs e) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { parentView.isBookmarkPaneVisible = false; //Remove the bookmark toolbar only if the device is a tablet if (parentView.bookmarkToolbar.Superview != null) parentView.bookmarkToolbar.RemoveFromSuperview(); } } //Handles the click event of back button on the title bar of mobile bookmark toolbar private void BackButton_TouchUpInside(object sender, EventArgs e) { if ((UIDevice.CurrentDevice).UserInterfaceIdiom != UIUserInterfaceIdiom.Pad) { parentView.isBookmarkPaneVisible = false; //Remove the bookmark toolbar only if the device is not a tablet if (parentView.bookmarkToolbar.Superview != null) parentView.bookmarkToolbar.RemoveFromSuperview(); } } //Sets the frames of the title, back button, tableview and left border(tablet only) public override void LayoutSubviews() { base.LayoutSubviews(); if ((UIDevice.CurrentDevice).UserInterfaceIdiom != UIUserInterfaceIdiom.Pad) { backButton.Frame = new CGRect(0, 0, 50, 60); title.Frame = new CGRect(50, 0, Frame.Width - 50, 60); titleContainer.Frame = new CGRect(0, 0, Frame.Width, 60); bookmarkListView.Frame = new CGRect(0, 60, Frame.Width, Frame.Height - 60); } else { bookmarkCloseButton.Frame = new CGRect(Frame.Width - 50.5, 0, 50, 60); title.Frame = new CGRect(50.5, 0, Frame.Width - 50.5, 60); titleContainer.Frame = new CGRect(0.5, 0, Frame.Width - 0.5, 60); border.Frame = new CGRect(0, 0, 0.5, Frame.Height); bookmarkListView.Frame = new CGRect(0.5, 60, Frame.Width - 0.5, Frame.Height - 60); } } } //Class that holds the bookmark data and properties that determin whether the expand button or back button should be visible. internal class CustomBookmark { public PdfBookmark Bookmark { get; set; } internal CustomBookmark(PdfBookmark bookmark, bool isBackToParentButtonVisible) { Bookmark = bookmark; IsBackToParentButtonVisible = isBackToParentButtonVisible; } //Expand button will be visible only if the current bookmark has children or it is not at the top of the list. public bool IsExpandButtonVisible { get { return Bookmark.Count != 0 && !IsBackToParentButtonVisible; } } //Backtoparent button will be visible for the cell at the top of the list. public bool IsBackToParentButtonVisible { get; set; } } //Source class for the tableview that lists bookmarks internal class BookmarkListSource : UITableViewSource { UITableView tableView; //Font that defines the icons for the bookmark toolbar buttons UIFont bookmarkFont; List<CustomBookmark> items; CustomToolbar parentView; private List<PdfBookmark> navigationQueue = new List<PdfBookmark>(); internal BookmarkListSource(CustomToolbar parent, UITableView table) { parentView = parent; items = parentView.listViewItemsSource; tableView = table; bookmarkFont = parent.bookmarkFont; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { BookmarkCell cell = tableView.DequeueReusableCell("ListCell") as BookmarkCell; if (cell == null) cell = new BookmarkCell((NSString)"ListCell", bookmarkFont, parentView, navigationQueue); CustomBookmark item = items[indexPath.Row]; //hide the backtoparent button based on the property of the CustomBookmark class cell.backToParentButton.Hidden = !item.IsBackToParentButtonVisible; cell.backToParentButton.Tag = indexPath.Row; //hide the expand button based on the property of the CustomBookmark class cell.expandButton.Hidden = !item.IsExpandButtonVisible; cell.expandButton.Tag = indexPath.Row; cell.title.Text = item.Bookmark.Title; return cell; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { //Obtain the selected bookmark and navigate to its destination parentView.pdfViewerControl.GoToBookmark(items[indexPath.Row].Bookmark); //Remove the bookmark toolbar from view for only mobile device if ((UIDevice.CurrentDevice).UserInterfaceIdiom != UIUserInterfaceIdiom.Pad) { parentView.isBookmarkPaneVisible = false; if(parentView.bookmarkToolbar.Superview != null) parentView.bookmarkToolbar.RemoveFromSuperview(); } } public override nint RowsInSection(UITableView tableview, nint section) { return items.Count; } } //Class that defines the cell design of the table view internal class BookmarkCell : UITableViewCell { internal UIButton backToParentButton, expandButton; private UIView customSeparatorBorder; internal UILabel title; CustomToolbar parentView; //List to maintain the previous bookmark list private List<PdfBookmark> navigationQueue; internal BookmarkCell(NSString cellID, UIFont bookmarkFont, CustomToolbar parent, List<PdfBookmark> forwardQue) : base(UITableViewCellStyle.Default, cellID) { this.navigationQueue = forwardQue; parentView = parent; title = new UILabel(); title.Font = UIFont.SystemFontOfSize(14); title.TextColor = UIColor.Black; title.BackgroundColor = UIColor.Clear; //Button to navigate to the parent bookmark of the current bookmark list backToParentButton = new UIButton(); backToParentButton.AccessibilityIdentifier = "backToParentButton"; backToParentButton.Font = bookmarkFont; backToParentButton.SetTitle("\ue709", UIControlState.Normal); backToParentButton.SetTitleColor(UIColor.FromRGB(113, 113, 113), UIControlState.Normal); backToParentButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; backToParentButton.TouchUpInside += BackToParentButton_TouchUpInside; //Button to navigate to the children of a bookmark. It is visible only the bookmark has children expandButton = new UIButton(); expandButton.AccessibilityIdentifier = "expandButton"; expandButton.Font = bookmarkFont; expandButton.SetTitle("\ue704", UIControlState.Normal); expandButton.SetTitleColor(UIColor.FromRGB(113, 113, 113), UIControlState.Normal); expandButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; expandButton.TouchUpInside += ExpandButton_TouchUpInside; //Border that separates the tableview cells customSeparatorBorder = new UIView(); customSeparatorBorder.BackgroundColor = UIColor.LightGray; ContentView.Add(backToParentButton); ContentView.Add(title); ContentView.Add(expandButton); ContentView.Add(customSeparatorBorder); } private void BackToParentButton_TouchUpInside(object sender, EventArgs e) { PdfBookmark bookmark = parentView.listViewItemsSource[0].Bookmark; parentView.listViewItemsSource.Clear(); if (navigationQueue.Count < 2) { for (int i = 0; i < parentView.loadedDocument.Bookmarks.Count; i++) parentView.listViewItemsSource.Add(new CustomBookmark(parentView.loadedDocument.Bookmarks[i], false)); parentView.bookmarkToolbar.bookmarkListView.ReloadData(); if(navigationQueue.Count != 0) navigationQueue.RemoveAt(navigationQueue.Count - 1); } else { //Get the bookmark that was added to the list when the expand button was clicked PdfBookmark parentBookmark = navigationQueue[navigationQueue.Count - 2]; navigationQueue.RemoveAt(navigationQueue.Count - 2); UpdateBookmarkList(parentBookmark); } } private void ExpandButton_TouchUpInside(object sender, EventArgs e) { int index = (int)(sender as UIButton).Tag; PdfBookmark bookmark = parentView.listViewItemsSource[index].Bookmark; //Add the current bookmark so that it can be used when back button is clicked later navigationQueue.Add(bookmark); UpdateBookmarkList(bookmark); } //Updates the tableview with the new bookmark list when backtoparent button or expand button is clicked internal void UpdateBookmarkList(PdfBookmark bookmark) { parentView.listViewItemsSource.Clear(); parentView.listViewItemsSource.Add(new CustomBookmark(bookmark, true)); for (int i = 0; i < bookmark.Count; i++) parentView.listViewItemsSource.Add(new CustomBookmark(bookmark[i], false)); parentView.bookmarkToolbar.bookmarkListView.ReloadData(); } //Sets the frame of the title, backtoparent button, expandbutton and the cell separator border. public override void LayoutSubviews() { base.LayoutSubviews(); title.Frame = new CoreGraphics.CGRect(50, 0, ContentView.Bounds.Width - 100, ContentView.Bounds.Height - 0.5); backToParentButton.Frame = new CoreGraphics.CGRect(0, 0, 50, ContentView.Bounds.Height - 0.5); expandButton.Frame = new CoreGraphics.CGRect(ContentView.Bounds.Width - 50, 0, 50, ContentView.Bounds.Height - 0.5); customSeparatorBorder.Frame = new CGRect(0, ContentView.Bounds.Height - 0.5, ContentView.Bounds.Width, 0.5); } } }<file_sep>/Forms/TextInputLayout/TextInputLayout/Samples/SignUpView/ContainerTypeConverter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.TextInputLayout; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfTextInputLayout { /// <summary> /// To get the ContainerType /// </summary> public class ContainerTypeConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var type = value as string; if (type == "Outlined") return ContainerType.Outlined; if (type == "Filled") return ContainerType.Filled; return ContainerType.None; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Forms/ParallaxView/ParallaxView/Samples/Weather/WeatherModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfParallaxView { using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains Properties and notifies when property value has changed /// </summary> public class WeatherModel : INotifyPropertyChanged { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string temperature; private string day; private ImageSource weatherConditions; private string weatherDetails; /// <summary> /// Initializes a new instance of the WeatherData class. /// </summary> /// <param name="day">string type parameter named as day</param> public WeatherModel(string day,string temperature,string conditions,string details) { this.Day = day; this.temperature = temperature+ "°C" ; this.WeatherConditions = ImageSource.FromFile(conditions.ToString()); this.weatherDetails = details; } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the value of Day and notifies user when collection value gets changed. /// </summary> public string Day { get { return this.day; } set { this.day = value; this.RaisePropertyChanged("Day"); } } /// <summary> /// Gets or sets the value of Day and notifies user when collection value gets changed. /// </summary> public string Temperature { get { return this.temperature; } set { this.temperature = value; this.RaisePropertyChanged("Temperature"); } } /// <summary> /// Gets or sets the value of Day and notifies user when collection value gets changed. /// </summary> public ImageSource WeatherConditions { get { return this.weatherConditions; } set { this.weatherConditions = value; this.RaisePropertyChanged("WeatherConditions"); } } /// <summary> /// Gets or sets the value of Day and notifies user when collection value gets changed. /// </summary> public string WeatherDetails { get { return this.weatherDetails; } set { this.weatherDetails = value; this.RaisePropertyChanged("WeatherDetails"); } } /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } } } <file_sep>/Android/SampleBrowser/Samples/AutoComplete/DiacriticSample/DiacriticSamplePage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Util; using System; using Android.Views; using SampleBrowser; using Android.Widget; using Com.Syncfusion.Autocomplete; namespace SampleBrowser { public class DiacriticSamplePage : SamplePage { LinearLayout mainLayout; int width; double density; public override View GetPropertyWindowLayout(Android.Content.Context context) { return null; } public override View GetSampleContent(Android.Content.Context con) { width = con.Resources.DisplayMetrics.WidthPixels; density = con.Resources.DisplayMetrics.Density; mainLayout = new LinearLayout(con); mainLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); mainLayout.Orientation = Orientation.Vertical; mainLayout.SetPadding(20, 20, 20, 20); LabelMethod(con); AutoCompleteMethod(con); return mainLayout; } private void LabelMethod(Android.Content.Context con) { TextView textView = new TextView(con); textView.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.95), (int)(30 * density)); textView.Hint = " AutoComplete"; textView.TextSize = 18; mainLayout.AddView(textView); } private void AutoCompleteMethod(Android.Content.Context con) { SfAutoComplete diacriticAutoComplete = new SfAutoComplete(con); diacriticAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.95), (int)(50)); diacriticAutoComplete.SetGravity(GravityFlags.Center); diacriticAutoComplete.DisplayMemberPath = "SongTitle"; diacriticAutoComplete.DataSource = new MusicInfoRepository().GetMusicInfo(); diacriticAutoComplete.MaximumDropDownHeight = 150; diacriticAutoComplete.Watermark = "Search here"; diacriticAutoComplete.SuggestionMode = SuggestionMode.Contains; diacriticAutoComplete.TextHighlightMode = OccurrenceMode.MultipleOccurrence; diacriticAutoComplete.DropDownItemHeight = 40; diacriticAutoComplete.IgnoreDiacritic = false; mainLayout.AddView(diacriticAutoComplete); } } }<file_sep>/Android/SampleBrowser/Samples/AutoComplete/AutoComplete.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Util; using System; using Android.Views; using SampleBrowser; namespace SampleBrowser { public class AutoComplete : SamplePage { AutoComplete_Mobile mobile; public AutoComplete() { } public override View GetSampleContent(Android.Content.Context con) { if (IsTabletDevice(con)) { AutoComplete_Tab tab = new AutoComplete_Tab(); return tab.GetSampleContent(con); } else { mobile = new AutoComplete_Mobile(); return mobile.GetSampleContent(con); } } public override View GetPropertyWindowLayout(Android.Content.Context context) { if (IsTabletDevice(context)) { return null; } else { return mobile.GetPropertyLayout(context); } } public override void OnApplyChanges() { mobile.ApplyChanges(); } public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = Math.Sqrt(Math.Pow(screenWidth, 2) + Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } } }<file_sep>/iOS/SampleBrowser/CollectionViewCell/PlainSampleViewCell.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Foundation; using UIKit; namespace SampleBrowser { public class PlainSampleViewCell : UICollectionViewCell { #region fields private UILabel label; private UIImageView imageView; #endregion #region ctor public PlainSampleViewCell() { } [Export("initWithFrame:")] public PlainSampleViewCell(CGRect frame) : base(frame) { BackgroundView = new UIView { BackgroundColor = UIColor.Orange }; SelectedBackgroundView = new UIView { BackgroundColor = UIColor.Green }; label = new UILabel { Center = ContentView.Center, TextColor = UIColor.Red, Frame = this.Frame }; imageView = new UIImageView(UIImage.FromBundle("menu.png")) { Transform = CGAffineTransform.MakeScale(0.7f, 0.7f), Frame = this.Frame }; ContentView.AddSubview(label); } protected PlainSampleViewCell(IntPtr handle) : base(handle) { } #endregion #region properties public UIImage Image { set { imageView.Image = value; } } public NSString Text { set { label.Text = value; } } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/PieChart/PieChart.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using Xamarin.Forms; using System.Globalization; using System.Linq; namespace SampleBrowser.SfChart { public partial class PieChart : SampleView { public PieChart() { InitializeComponent(); if (Device.RuntimePlatform == Device.macOS || Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { Chart.Legend.OverflowMode = ChartLegendOverflowMode.Scroll; } slider.MaximumTrackColor = Color.LightBlue; slider.MinimumTrackColor = Color.Blue; groupMode.SelectedIndex = 0; groupMode.SelectedIndexChanged += GroupMode_SelectedIndexChanged; slider.ValueChanged += Slider_ValueChanged; } private void Slider_ValueChanged(object sender, ValueChangedEventArgs e) { groupTo.Text = "GroupTo Value is " + ((int)e.NewValue).ToString(); pieSeries.GroupTo = (int)e.NewValue; } private void GroupMode_SelectedIndexChanged(object sender, EventArgs e) { switch(groupMode.SelectedIndex) { case 0: pieSeries.GroupMode = PieGroupMode.Value; break; case 1: pieSeries.GroupMode = PieGroupMode.Percentage; break; case 2: pieSeries.GroupMode = PieGroupMode.Angle; break; } } protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if ((Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS)) { if (height > 0 && width > 0) { if (height > width) { Chart.Legend.OverflowMode = ChartLegendOverflowMode.Wrap; Chart.Legend.DockPosition = LegendPlacement.Bottom; } else { Chart.Legend.DockPosition = LegendPlacement.Right; Chart.Legend.OverflowMode = ChartLegendOverflowMode.Scroll; } } } } } public class DataMarkerConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (parameter != null && parameter.ToString() == "Label") { if (value is List<object>) { return "Others"; } else { if (value != null) { return (value as ChartDataModel).Name; } } } else { if (value is List<object>) { return (value as List<object>).Sum(item => (item as ChartDataModel).Value).ToString() + "%"; } else { if (value != null) { return (value as ChartDataModel).Value + "%"; } } } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } } <file_sep>/Android/SampleBrowser/Common/Layouts/SamplesListView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Android.Content; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; namespace SampleBrowser { [Preserve(AllMembers = true)] [Register("SampleBrowser.SampleBrowser.horizontalScroll")] public class SamplesListView : HorizontalScrollView { Context listViewContext; public SamplesListView(Context context) : base(context) { listViewContext = context; } public SamplesListView(Context context, IAttributeSet attrs) : base(context, attrs) { listViewContext = context; } public SamplesListView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { listViewContext = context; } public SamplesListView(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes) { listViewContext = context; } protected SamplesListView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } public void Add(List<SampleBase> samples) { int count = samples.Count; for (int i = 0; i < samples.Count; i++) { AddView(GetView(samples[i].Title)); } } public TextView GetView(string sampleName) { if (string.IsNullOrEmpty(sampleName)) return null; TextView view = new TextView(listViewContext) { LayoutParameters = new ViewGroup.LayoutParams(200, 200) }; view.Text = sampleName; return view; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Calendar/CalendarViews_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfCalendar.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class CalendarViews_Tablet: SampleView { SFCalendar calendar; private string selectedType; UILabel label_calendarView; UIView subView = new UIView (); UIView calendarView = new UIView (); UIView contentView = new UIView (); UIButton button_calendarView = new UIButton (); UIButton showPropertyButton = new UIButton (); UIButton closeButton = new UIButton (); UILabel propertiesLabel = new UILabel (); UIButton doneButton=new UIButton(); UIPickerView picker_calendarView; UIView pickerSubView = new UIView (); public CalendarViews_Tablet () { //Calendar calendar= new SFCalendar (); calendar.ViewMode = SFCalendarViewMode.SFCalendarViewModeMonth; calendar.HeaderHeight = 40; calendarView.AddSubview(calendar); this.AddSubview (calendarView); this.loadOptionView(); } public void loadOptionView() { //Intializing configurationc controls label_calendarView = new UILabel(); button_calendarView = new UIButton(); picker_calendarView = new UIPickerView(); PickerModel model = new PickerModel(_calendarViewsCollection); picker_calendarView.Model = model; //label label_calendarView.Text = "View Mode "; label_calendarView.Font = UIFont.FromName("Helvetica", 14f); label_calendarView.TextColor = UIColor.Black; label_calendarView.TextAlignment = UITextAlignment.Left; //button button_calendarView.SetTitle("Month View", UIControlState.Normal); button_calendarView.SetTitleColor(UIColor.Black, UIControlState.Normal); button_calendarView.Font = UIFont.FromName("Helvetica", 14f); button_calendarView.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_calendarView.Layer.CornerRadius = 8; button_calendarView.Layer.BorderWidth = 2; button_calendarView.TouchUpInside += ShowPicker1; button_calendarView.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //doneButton doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.Font = UIFont.FromName("Helvetica", 14f); doneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); //picker model.PickerChanged += SelectedIndexChanged1; picker_calendarView.ShowSelectionIndicator = true; picker_calendarView.Hidden = true; picker_calendarView.BackgroundColor = UIColor.Gray; //adding to contentView contentView.AddSubview(label_calendarView); contentView.AddSubview(button_calendarView); pickerSubView.AddSubview(picker_calendarView); //pickerSubview pickerSubView.BackgroundColor = UIColor.Gray; pickerSubView.Hidden = true; contentView.AddSubview(pickerSubView); contentView.AddSubview(doneButton); contentView.BackgroundColor = UIColor.FromRGB(240, 240, 240); //adding to subView subView.AddSubview(contentView); subView.AddSubview(closeButton); subView.AddSubview(propertiesLabel); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); subView.AddSubview(closeButton); subView.AddSubview(propertiesLabel); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); this.AddSubview(subView); //ShowPropertyButton propertiesLabel.Text = "OPTIONS"; showPropertyButton.Hidden = true; showPropertyButton.SetTitle("OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = false; showPropertyButton.Hidden = true; }; this.AddSubview(showPropertyButton); //CloseButton closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; }; //AddingGesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer(() => { subView.Hidden = true; showPropertyButton.Hidden = false; } ); propertiesLabel.UserInteractionEnabled = true; propertiesLabel.AddGestureRecognizer(tapgesture); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = new CGRect(Frame.X, -2, Frame.Width, Frame.Height); subView.Frame = new CGRect (0, 4 * this.Frame.Size.Height / 5-25, this.Frame.Size.Width, 2 * this.Frame.Size.Height / 5); contentView.Frame=new CGRect(0,40,subView.Frame.Size.Width,subView.Frame.Size.Height-50); calendarView.Frame = new CGRect (0, 0,this.Frame.Size.Width, this.Frame.Size.Height-30); calendar.Frame = new CGRect (0, 0, this.Frame.Size.Width, this.Frame.Size.Height-30); label_calendarView.Frame = new CGRect ( 110, 70, this.Frame.Size.Width - 220, 30); button_calendarView.Frame = new CGRect (350, 70, contentView.Frame.Size.Width-520, 30); picker_calendarView.Frame = new CGRect (105, 0, pickerSubView.Frame.Size.Width-200 , 150); pickerSubView.Frame = new CGRect (100, 0, contentView.Frame.Size.Width - 200, 150); doneButton.Frame = new CGRect(100, 0, contentView.Frame.Size.Width-200, 30); showPropertyButton.Frame = new CGRect (0, this.Frame.Size.Height-25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect (this.Frame.Size.Width - 30, 5, 20, 30); propertiesLabel.Frame = new CGRect (10, 5, this.Frame.Width, 30); } base.LayoutSubviews (); } void ShowPicker1 (object sender, EventArgs e) { doneButton.Hidden = false; picker_calendarView.Hidden = false; button_calendarView.Hidden = true; label_calendarView.Hidden = false; pickerSubView.Hidden = false; } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; picker_calendarView.Hidden = true; button_calendarView.Hidden = false; label_calendarView.Hidden = false; pickerSubView.Hidden = true; } private void SelectedIndexChanged1(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; if (selectedType == "Month View") { calendar.ViewMode = SFCalendarViewMode.SFCalendarViewModeMonth; } else if (selectedType == "Year View") { calendar.ViewMode = SFCalendarViewMode.SFCalendarViewModeYear; } button_calendarView.SetTitle(selectedType.ToString(),UIControlState.Normal); } private readonly IList<string> _calendarViewsCollection = new List<string> { "Month View", "Year View", }; } } <file_sep>/Android/SampleBrowser/Samples/Diagram/MindMap.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Linq; using Android.App; using Android.Content; using Android.Graphics; using Android.Views; using Android.Widget; using Syncfusion.SfDiagram.Android; using System.IO; using System.Reflection; using System.Collections.Generic; using Point = System.Drawing.Point; namespace SampleBrowser { public partial class MindMap : SamplePage { SfDiagram diagram; Node RootNode; UserHandleCollection DefaultHandles; UserHandleCollection RightSideHandle=null; UserHandleCollection LeftSideHandles=null; internal Node SelectedNode; UserHandlePosition CurrentHandle; Random rnd = new Random(); AlertBox CommentBoxEntry; List<Color> FColor = new List<Color>(); List<Color> SColor = new List<Color>(); int index; float currentDensity = 1; private LinearLayout scrollLayout; List<NodeStyle> nodeStyleCollection = new List<NodeStyle>(); LineStyle lineStyle; object objShape1 = ShapeType.RoundedRectangle; object objShape2 = ShapeType.RoundedRectangle; object objShape3 = ShapeType.RoundedRectangle; object objShape4 = ShapeType.RoundedRectangle; object objShape5 = ShapeType.RoundedRectangle; SegmentType segment = SegmentType.CurveSegment; string simpleCurveTree = "default"; SfGraphics gra = new SfGraphics(); List<Point> point = new List<Point>(); DecoratorType Dectype = DecoratorType.None; Color connColor = Color.Gray; ApplyColorFrom connLineApplyColorFrom = ApplyColorFrom.TargetBorder; ApplyColorFrom connDecApplyColorFrom = ApplyColorFrom.TargetBorder; public override View GetSampleContent(Context context) { //Create SfDiagram. currentDensity = context.Resources.DisplayMetrics.Density; diagram = new SfDiagram(context); diagram.ContextMenuSettings.Visibility = false; int width = 150; int height = 75; width = (int)(125 * MainActivity.Factor); height = (int)(60 * MainActivity.Factor); var node = AddNode(300, 400, width, height, "Goals"); AddNodeStyle(node, GetColor("#d0ebff"), GetColor("#81bfea")); RootNode = node; diagram.AddNode(node); SColor.Add(GetColor("#d1afdf")); SColor.Add(GetColor("#90C8C2")); SColor.Add(GetColor("#8BC1B7")); SColor.Add(GetColor("#E2C180")); SColor.Add(GetColor("#BBBFD6")); SColor.Add(GetColor("#ACCBAA")); FColor.Add(GetColor("#e9d4f1")); FColor.Add(GetColor("#d4efed")); FColor.Add(GetColor("#c4f2e8")); FColor.Add(GetColor("#f7e0b3")); FColor.Add(GetColor("#DEE2FF")); FColor.Add(GetColor("#E5FEE4")); var ch1node = AddNode(100, 100, width, height, "Financial"); index = rnd.Next(5); AddNodeStyle(ch1node, FColor[index], SColor[index]); diagram.AddNode(ch1node); var ch1childnode = AddNode(100, 100, width, height, "Investment"); AddNodeStyle(ch1childnode, (ch1node.Style.Brush as SolidBrush).FillColor, (ch1node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch1childnode); var ch2node = AddNode(100, 600, width, height, "Social"); index = rnd.Next(5); AddNodeStyle(ch2node, FColor[index], SColor[index]); diagram.AddNode(ch2node); var ch2childnode1 = AddNode(100, 100, width, height, "Friends"); AddNodeStyle(ch2childnode1, (ch2node.Style.Brush as SolidBrush).FillColor, (ch2node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch2childnode1); var ch2childnode2 = AddNode(100, 100, width, height, "Family"); AddNodeStyle(ch2childnode2, (ch2node.Style.Brush as SolidBrush).FillColor, (ch2node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch2childnode2); var ch3node = AddNode(500, 100, width, height, "Personal"); index = rnd.Next(5); AddNodeStyle(ch3node, FColor[index], SColor[index]); diagram.AddNode(ch3node); var ch3childnode1 = AddNode(500, 100, width, height, "Sports"); AddNodeStyle(ch3childnode1, (ch3node.Style.Brush as SolidBrush).FillColor, (ch3node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch3childnode1); var ch3childnode2 = AddNode(500, 100, width, height, "Food"); AddNodeStyle(ch3childnode2, (ch3node.Style.Brush as SolidBrush).FillColor, (ch3node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch3childnode2); var ch4node = AddNode(500, 600, width, height, "Work"); index = rnd.Next(5); AddNodeStyle(ch4node, FColor[index], SColor[index]); diagram.AddNode(ch4node); var ch4childnode1 = AddNode(500, 100, width, height, "Project"); AddNodeStyle(ch4childnode1, (ch4node.Style.Brush as SolidBrush).FillColor, (ch4node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch4childnode1); var ch4childnode2 = AddNode(500, 100, width, height, "Career"); AddNodeStyle(ch4childnode2, (ch4node.Style.Brush as SolidBrush).FillColor, (ch4node.Style.StrokeBrush as SolidBrush).FillColor); diagram.AddNode(ch4childnode2); diagram.AddConnector(AddConnector(node, ch1node)); diagram.AddConnector(AddConnector(node, ch2node)); diagram.AddConnector(AddConnector(node, ch3node)); diagram.AddConnector(AddConnector(node, ch4node)); diagram.AddConnector(AddConnector(ch1node, ch1childnode)); diagram.AddConnector(AddConnector(ch2node, ch2childnode1)); diagram.AddConnector(AddConnector(ch2node, ch2childnode2)); diagram.AddConnector(AddConnector(ch3node, ch3childnode1)); diagram.AddConnector(AddConnector(ch3node, ch3childnode2)); diagram.AddConnector(AddConnector(ch4node, ch4childnode1)); diagram.AddConnector(AddConnector(ch4node, ch4childnode2)); diagram.UserHandleClicked += Diagram_UserHandleClicked; AddHandles(); diagram.NodeClicked += Diagram_NodeClicked; diagram.Clicked += Diagram_Clicked; diagram.Loaded += Diagram_Loaded; SelectedNode = node; diagram.ConnectorClicked += Diagram_ConnectorClicked; return diagram; } public override void Destroy() { if (diagram != null) diagram.Dispose(); base.Destroy(); } void Diagram_ConnectorClicked(object sender, ConnectorClickedEventArgs args) { diagram.ClearSelection(); } private void Diagram_Clicked(object sender, DiagramClickedEventArgs args) { if (CommentBoxEntry != null && CommentBoxEntry.alertBuilder != null) CommentBoxEntry.alertBuilder.SetCancelable(true); } public override View GetPropertyWindowLayout(Context context) { LinearLayout gridLinearLayout = new LinearLayout(context) { Orientation = Android.Widget.Orientation.Vertical }; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); layoutParams.TopMargin = (int)(25 * currentDensity); gridLinearLayout.LayoutParameters = layoutParams; gridLinearLayout.SetBackgroundResource(Resource.Drawable.LinearLayout_Border); int width = (int)(context.Resources.DisplayMetrics.WidthPixels - context.Resources.DisplayMetrics.Density) / 3; LinearLayout linearLayout4 = new LinearLayout(context); linearLayout4.Orientation = Android.Widget.Orientation.Vertical; linearLayout4.SetMinimumHeight((int)(190 * currentDensity)); linearLayout4.SetMinimumWidth(width); TextView selectText = new TextView(context) { Text = "Layout Schema", Gravity = GravityFlags.Start, TextSize = 5 * currentDensity }; selectText.SetMinimumHeight((int)(50 * currentDensity)); selectText.SetWidth((int)(width * 0.4 * currentDensity)); //Here theme styles starts HorizontalScrollView horizontalScroll = new HorizontalScrollView(context); //horizontalScroll.SetPadding(0, (int)(10 * currentDensity), 0, (int)(10 * currentDensity)); horizontalScroll.FillViewport = true; horizontalScroll.HorizontalScrollBarEnabled = true; horizontalScroll.SetMinimumHeight((int)(205 * currentDensity)); horizontalScroll.Layout(0, (int)(30 * currentDensity), (int)(175 * currentDensity * 4), (int)(180 * currentDensity)); scrollLayout = new LinearLayout(context); scrollLayout.SetPadding((int)(10 * currentDensity), (int)(10 * currentDensity), (int)(10 * currentDensity), (int)(10 * currentDensity)); scrollLayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); horizontalScroll.AddView(scrollLayout); LinearLayout freeFormLinearLayout = new LinearLayout(context); freeFormLinearLayout.SetPadding(0, (int)(10 * currentDensity), 0, (int)(10 * currentDensity)); freeFormLinearLayout.SetMinimumHeight((int)(30 * currentDensity)); TextView freeFormLayout = new TextView(context) { Text = "Free Form", Gravity = GravityFlags.Start, TextSize = 5 * currentDensity }; freeFormLayout.SetMinimumHeight((int)(25 * currentDensity)); freeFormLayout.SetWidth((int)(width * 0.4 * currentDensity)); Switch freeFormSwitch = new Switch(context); freeFormSwitch.CheckedChange += FreeFormSwitch_CheckedChange; freeFormSwitch.Gravity = GravityFlags.Right; freeFormSwitch.SetMinimumHeight((int)(25 * currentDensity)); freeFormSwitch.SetWidth((int)(width * 0.4 * currentDensity)); freeFormLinearLayout.AddView(freeFormLayout); freeFormLinearLayout.AddView(freeFormSwitch); linearLayout4.AddView(freeFormLinearLayout); linearLayout4.AddView(selectText); linearLayout4.AddView(horizontalScroll); AddThemes(); gridLinearLayout.AddView(linearLayout4); return gridLinearLayout; } private void FreeFormSwitch_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e) { if (e.IsChecked) { (diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm = true; } else { (diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm = false; } } private void AddThemes() { AddColor("mindmapDefault.png"); AddColor("mindmapconttree.png"); AddColor("mindmaportho.png"); AddColor("mindmapsimpletree.png"); } private void AddColor(string imageId) { ImageButtonView imageButton = new ImageButtonView(diagram.Context); imageButton.Click += ButtonTouch; imageButton.ImageId = imageId; //imageButton.SetPadding((int)(10 * currentDensity), 0, (int)(10 * currentDensity), 0); imageButton.LayoutParameters = new ViewGroup.LayoutParams((int)(220 * currentDensity), (int)(200 * currentDensity)); ImageView image = new ImageView(diagram.Context); if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); image.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } image.Layout((int)(15 * currentDensity), (int)(15 * currentDensity), (int)(520 * MainActivity.Factor), (int)(500 * MainActivity.Factor)); imageButton.AddView(image); scrollLayout.AddView(imageButton); } VerticalAlignment TextStyleVerticalAlignment = VerticalAlignment.Center; private void ButtonTouch(object sender, EventArgs e) { ImageButtonView view = sender as ImageButtonView; view.ButtonSelected = true; switch (view.ImageId) { case "mindmapconttree.png": simpleCurveTree = "contCurveTree"; SfGraphicsPath path = new SfGraphicsPath(); path.MoveTo(0, 0); path.MoveTo(0, 50); path.LineTo(100, 50); path.MoveTo(100, 100); gra.DrawPath(path); Pen pe = new Pen(); pe.StrokeBrush = new SolidBrush(Color.ParseColor("#949494")); pe.StrokeWidth = 5; point.Add(new Point(0, 50)); point.Add(new Point(100, 50)); gra.DrawLines(pe, point); objShape1 = ShapeType.Ellipse; objShape2 = gra; objShape3 = gra; objShape4 = gra; objShape5 = gra; segment = SegmentType.CurveSegment; TextStyleVerticalAlignment = VerticalAlignment.Top; Dectype = DecoratorType.None; connColor = Color.Black; connLineApplyColorFrom = ApplyColorFrom.TargetBorder; connDecApplyColorFrom = ApplyColorFrom.TargetBorder; break; case "mindmapDefault.png": simpleCurveTree = "default"; objShape1 = ShapeType.RoundedRectangle; objShape2 = ShapeType.RoundedRectangle; objShape3 = ShapeType.RoundedRectangle; objShape4 = ShapeType.RoundedRectangle; objShape5 = ShapeType.RoundedRectangle; segment = SegmentType.CurveSegment; TextStyleVerticalAlignment = VerticalAlignment.Center; Dectype = DecoratorType.None; connColor = Color.Black; connLineApplyColorFrom = ApplyColorFrom.TargetBorder; connDecApplyColorFrom = ApplyColorFrom.TargetBorder; break; case "mindmaportho.png": simpleCurveTree = "orthotree"; objShape1 = ShapeType.Rectangle; objShape2 = ShapeType.Rectangle; objShape3 = ShapeType.Rectangle; objShape4 = ShapeType.Rectangle; objShape5 = ShapeType.Rectangle; segment = SegmentType.OrthoSegment; TextStyleVerticalAlignment = VerticalAlignment.Center; Dectype = DecoratorType.None; connColor = Color.Black; connLineApplyColorFrom = ApplyColorFrom.TargetBorder; connDecApplyColorFrom = ApplyColorFrom.TargetBorder; break; case "mindmapsimpletree.png": simpleCurveTree = "simpleCurveTree"; objShape1 = ShapeType.RoundedRectangle; objShape2 = ShapeType.RoundedRectangle; objShape3 = ShapeType.RoundedRectangle; objShape4 = ShapeType.RoundedRectangle; objShape5 = ShapeType.RoundedRectangle; segment = SegmentType.CurveSegment; TextStyleVerticalAlignment = VerticalAlignment.Center; Dectype = DecoratorType.None; connColor = Color.ParseColor("#949494"); connLineApplyColorFrom = ApplyColorFrom.Custom; connDecApplyColorFrom = ApplyColorFrom.Custom; break; } UpdateTheme(); for (int i = 0; i < scrollLayout.ChildCount; i++) { ImageButtonView childView = (ImageButtonView)scrollLayout.GetChildAt(i); if (childView.ImageId == view.ImageId) continue; childView.ButtonSelected = false; } } internal void UpdateTheme() { bool m_repeatmode = true; nodeStyleCollection.Clear(); if (simpleCurveTree == "default") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#d7ebf6")), Color.ParseColor("#d7ebf6"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#ffebc4")), Color.ParseColor("#ffebc4"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#ffcdcd")), Color.ParseColor("#ffcdcd"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#e7eeb8")), Color.ParseColor("#e7eeb8"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#d7ebf6")), Color.ParseColor("#d7ebf6"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); } else if (simpleCurveTree == "orthotree") { nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#d7ebf6")), Color.ParseColor("#b4d6e8"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#ffebc4")), Color.ParseColor("#f2dcb1"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#ffcdcd")), Color.ParseColor("#ecb6b6"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#e7eeb8")), Color.ParseColor("#d6dda6"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#d7ebf6")), Color.ParseColor("#b4d6e8"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); } else if (simpleCurveTree == "simpleCurveTree") { m_repeatmode = false; nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#d7ebf6")), Color.ParseColor("#b4d6e8"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.Transparent), Color.Transparent, objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); } else if (simpleCurveTree == "contCurveTree") { m_repeatmode = false; nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#d7ebf6")), Color.ParseColor("#d7ebf6"), objShape1, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, VerticalAlignment.Center))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#949494")), Color.ParseColor("#949494"), objShape2, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#949494")), Color.ParseColor("#949494"), objShape3, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#949494")), Color.ParseColor("#949494"), objShape4, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); nodeStyleCollection.Add(new NodeStyle(new SolidBrush(Color.ParseColor("#949494")), Color.ParseColor("#949494"), objShape5, StrokeStyle.Default, new Syncfusion.SfDiagram.Android.TextStyle((int)(14 * MainActivity.Factor), Color.Black, ".SF UI Text", HorizontalAlignment.Center, TextStyleVerticalAlignment))); } lineStyle = new LineStyle(segment, StrokeStyle.Default, 2, connLineApplyColorFrom, Dectype, connDecApplyColorFrom, connDecApplyColorFrom) { Color = connColor }; (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayoutStyle(new LayoutStyle(nodeStyleCollection, lineStyle, ApplyNodeStyleBy.Branch, m_repeatmode)); } internal class ImageButtonView : ViewGroup { private bool m_buttonSelected; internal ImageButtonView(Context context) : base(context) { SetBackgroundColor(Color.Transparent); } public bool ButtonSelected { get { return m_buttonSelected; } set { m_buttonSelected = value; SetWillNotDraw(true); SetWillNotDraw(false); } } public string ImageId { get; internal set; } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); if (ButtonSelected) { Paint paint = new Paint(); paint.SetStyle(Paint.Style.Stroke); paint.Color = Color.Rgb(30, 144, 255); paint.StrokeWidth = 3 * Resources.DisplayMetrics.Density; canvas.DrawRect(GetChildAt(0).Left - 10 * Resources.DisplayMetrics.Density, GetChildAt(0).Top, GetChildAt(0).Right + 10 * Resources.DisplayMetrics.Density, GetChildAt(0).Bottom, paint); } else { Paint paint = new Paint(); paint.SetStyle(Paint.Style.Stroke); paint.Color = Color.Transparent; paint.StrokeWidth = 3 * Resources.DisplayMetrics.Density; canvas.DrawRect(GetChildAt(0).Left - 10 * Resources.DisplayMetrics.Density, GetChildAt(0).Top, GetChildAt(0).Right + 10 * Resources.DisplayMetrics.Density, GetChildAt(0).Bottom, paint); } } protected override void OnLayout(bool changed, int l, int t, int r, int b) { } } private void Diagram_NodeClicked(object sender, NodeClickedEventArgs args) { SelectedNode = args.Item; diagram.Alpha = 1; diagram.PageSettings.BackgroundColor = Color.White; UpdateHandle(); } private void AddExpCollHandle() { if (GetExpCollHandle(LeftSideHandles) == null) { LeftSideHandles.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, GetHandleImage("mindmapcollpase.png"))); } if (GetExpCollHandle(RightSideHandle) == null) { RightSideHandle.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, GetHandleImage("mindmapcollpase.png"))); } if (GetExpCollHandle(DefaultHandles) == null) { DefaultHandles.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, GetHandleImage("mindmapexpand.png"))); } } private UserHandle GetExpCollHandle(UserHandleCollection handleCollection) { for (int i = 0; i < handleCollection.Count; i++) { UserHandle handle = handleCollection[i]; if (handle.Name == "ExpColl") { return handle; } } return null; } internal MemoryStream LoadResource(string name) { MemoryStream aMem = new MemoryStream(); var assm = Assembly.GetExecutingAssembly(); var path = string.Format("SampleBrowser.Resources.drawable.{0}", name); var aStream = assm.GetManifestResourceStream(path); aStream.CopyTo(aMem); return aMem; } private void AddHandles() { DefaultHandles = new UserHandleCollection(diagram); DefaultHandles.Add(new UserHandle("Left", UserHandlePosition.Left, GetHandleImage("mindmapplus.png"))); DefaultHandles.Add(new UserHandle("Right", UserHandlePosition.Right, GetHandleImage("mindmapplus.png"))); DefaultHandles.Add(new UserHandle("ExpColl", UserHandlePosition.BottomLeft, GetHandleImage("mindmapexpand.png"))); DefaultHandles.Add(new UserHandle("Delete", UserHandlePosition.Bottom, GetHandleImage("mindmapdelete.png")) { Visible = false }); DefaultHandles.Add(new UserHandle("info", UserHandlePosition.TopRight, GetHandleImage("mindmapmore.png"))); diagram.UserHandles = DefaultHandles; } private ImageView GetHandleImage(string imageId) { var defExpandTemplate = new ImageView(diagram.Context); defExpandTemplate.Layout(0, 0, 25, 25); if (imageId != null) { var imageData = LoadResource(imageId).ToArray(); defExpandTemplate.SetImageBitmap(BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length)); } defExpandTemplate.SetPadding(0, (int)(10 * MainActivity.Factor), 0, 0); return defExpandTemplate; } private void Diagram_UserHandleClicked(object sender, UserHandleClickedEventArgs args) { SelectedNode = diagram.SelectedItems[0] as Node; if (args.Item.Name == "Delete") { diagram.RemoveNode(SelectedNode, true); if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayout(); } else if (args.Item.Name == "ExpColl") { if (SelectedNode.IsExpanded) { SelectedNode.IsExpanded = false; args.Item.Content = GetHandleImage("mindmapcollpase.png"); } else { SelectedNode.IsExpanded = true; args.Item.Content = GetHandleImage("mindmapexpand.png"); } if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateLayout(); UpdateHandle(); diagram.Select(SelectedNode); } else if (args.Item.Name == "info") { AddInfo(); } else { if (args.Item.Name == "Left") { CurrentHandle = UserHandlePosition.Left; ShowInfo(); } else if (args.Item.Name == "Right") { CurrentHandle = UserHandlePosition.Right; ShowInfo(); } } } private String GetNodeDirection(Node node) { string side = null; if (node != RootNode && node.OffsetX > RootNode.OffsetX) { side = "Right"; } else if (node != RootNode && node.OffsetX < RootNode.OffsetX) { side = "Left"; } else if (node == RootNode) { side = "Center"; } return side; } internal void UpdateHandle() { var side = GetNodeDirection(SelectedNode); if (side == "Right") { //Left add diagram.UserHandles[0].Visible = false; //Right add diagram.UserHandles[1].Visible = true; //ExpColl if (SelectedNode.IsExpanded) { diagram.UserHandles[2].Content = GetHandleImage("mindmapexpand.png"); } else { diagram.UserHandles[2].Content = GetHandleImage("mindmapcollpase.png"); } diagram.UserHandles[2].Visible = true; //Delete diagram.UserHandles[3].Visible = true; //Info diagram.UserHandles[4].Visible = true; if (!SelectedNode.IsExpanded) { diagram.UserHandles[1].Visible = false; } } else if (side == "Left") { //Left add diagram.UserHandles[0].Visible = true; //Right add diagram.UserHandles[1].Visible = false; //ExpColl if (SelectedNode.IsExpanded) { diagram.UserHandles[2].Content = GetHandleImage("mindmapcollpase.png"); } else { diagram.UserHandles[2].Content = GetHandleImage("mindmapexpand.png"); } diagram.UserHandles[2].Visible = true; //Delete diagram.UserHandles[3].Visible = true; //Info diagram.UserHandles[4].Visible = true; if (!SelectedNode.IsExpanded) { diagram.UserHandles[0].Visible = false; } } else if (side == "Center") { //Left add diagram.UserHandles[0].Visible = true; //Right add diagram.UserHandles[1].Visible = true; //ExpColl diagram.UserHandles[2].Visible = true; //Delete diagram.UserHandles[3].Visible = false; //Info diagram.UserHandles[4].Visible = true; if (!SelectedNode.IsExpanded) { diagram.UserHandles[0].Visible = false; diagram.UserHandles[1].Visible = false; } } if (SelectedNode.Children.Count() > 0) { diagram.UserHandles[2].Visible = true; } else { diagram.UserHandles[2].Visible = false; } } private void AddInfo() { string content = ""; if (SelectedNode.Content != null) { content = SelectedNode.Content as string; } CommentBoxEntry = new AlertBox(diagram.Context, this, content, diagram, CurrentHandle, SelectedNode, RootNode, index, rnd, LeftSideHandles, RightSideHandle, SColor, FColor); CommentBoxEntry.editText.Text = content; CommentBoxEntry.editText.SetPadding(0, 8, 0, 0); CommentBoxEntry.ShowPopUpForComments("Okay", "Cancel"); } void ShowInfo() { CommentBoxEntry = new AlertBox(diagram.Context, this, "", diagram, CurrentHandle, SelectedNode, RootNode, index, rnd, LeftSideHandles, RightSideHandle, SColor, FColor); CommentBoxEntry.editText.SetPadding(0, 8, 0, 0); CommentBoxEntry.ShowPopUp("Okay", "Cancel"); } void Ok_Clicked1(object sender, EventArgs e) { if (CommentBoxEntry.editText.Text != null) { SelectedNode.Content = CommentBoxEntry.editText.Text; } } private Color GetColor(string hex) { int r = Convert.ToInt32(hex.Substring(1, 2), 16); int g = Convert.ToInt32(hex.Substring(3, 2), 16); int b = Convert.ToInt32(hex.Substring(5, 2), 16); return new Color(r, g, b); } private Connector AddConnector(Node node, Node ch1node) { var c1 = new Connector(diagram.Context); c1.SourceNode = node; c1.TargetNode = ch1node; c1.Style.StrokeBrush = new SolidBrush((c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor); c1.Style.StrokeStyle = StrokeStyle.Dashed; c1.Style.StrokeWidth = 3; c1.TargetDecoratorStyle.Fill = (c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor; c1.TargetDecoratorStyle.StrokeColor = (node.Style.StrokeBrush as SolidBrush).FillColor; c1.SegmentType = SegmentType.CurveSegment; return c1; } private void AddNodeStyle(Node node, Color fill, Color Stroke) { node.Style.Brush = new SolidBrush(fill); node.Style.StrokeBrush = new SolidBrush(Stroke); } Node AddNode(int x, int y, int w, int h, string text) { var node = new Node(x, y, w, h, diagram.Context); node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 2; node.Annotations.Add(new Annotation() { Content = text, FontSize = 16 * MainActivity.Factor, TextBrush = new SolidBrush(Color.Black) }); return node; } private void Diagram_Loaded(object sender) { diagram.EnableDrag = false; diagram.ShowSelectorHandle(false, SelectorPosition.SourcePoint); diagram.ShowSelectorHandle(false, SelectorPosition.TargetPoint); diagram.ShowSelectorHandle(false, SelectorPosition.Rotator); diagram.ShowSelectorHandle(false, SelectorPosition.TopLeft); diagram.ShowSelectorHandle(false, SelectorPosition.TopRight); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleLeft); diagram.ShowSelectorHandle(false, SelectorPosition.MiddleRight); diagram.ShowSelectorHandle(false, SelectorPosition.BottomCenter); diagram.ShowSelectorHandle(false, SelectorPosition.BottomLeft); diagram.ShowSelectorHandle(false, SelectorPosition.BottomRight); diagram.ShowSelectorHandle(false, SelectorPosition.TopCenter); diagram.LayoutManager = new LayoutManager() { Layout = new MindMapLayout() { MindMapOrientation = Syncfusion.SfDiagram.Android.Orientation.Horizontal, HorizontalSpacing = 70, } }; (diagram.LayoutManager.Layout as MindMapLayout).HorizontalSpacing = 70 * MainActivity.Factor; if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) { diagram.LayoutManager.Layout.UpdateLayout(); } SelectedNode = RootNode; diagram.Select(RootNode); diagram.BringToView(RootNode); UpdateTheme(); } } internal class AlertBox { internal string _inputstring; internal AlertDialog.Builder alertBuilder; internal EditText editText; private SfDiagram diagram; private UserHandlePosition CurrentHandle; private Node SelectedNode; private Node RootNode; private int index; private Random rnd; private UserHandleCollection LeftSideHandles; private UserHandleCollection RightSideHandle; private List<Color> SColor; private List<Color> FColor; private MindMap m_mindmap; internal AlertBox(Context context, MindMap mindmap, string content, SfDiagram sfDiagram, UserHandlePosition CurrentHandle, Node selectedNode, Node rootNode, int index, Random rnd, UserHandleCollection left, UserHandleCollection right, List<Color> SColor, List<Color> FColor) { alertBuilder = new AlertDialog.Builder(context); m_mindmap = mindmap; editText = new EditText(context); _inputstring = content; diagram = sfDiagram; this.CurrentHandle = CurrentHandle; SelectedNode = selectedNode; RootNode = rootNode; this.index = index; this.rnd = rnd; LeftSideHandles = left; RightSideHandle = right; this.SColor = SColor; this.FColor = FColor; } internal void ShowPopUp(string positive, string negative) { alertBuilder.SetTitle("Enter Text"); editText.Text = _inputstring; editText.FocusableInTouchMode = true; editText.RequestFocus(); editText.SetBackgroundColor(Color.WhiteSmoke); editText.SetTextColor(Color.Black); alertBuilder.SetView(editText); alertBuilder.SetCancelable(false); alertBuilder.SetPositiveButton(positive, (senderAlert, args) => { diagram.Alpha = 1; diagram.PageSettings.BackgroundColor = Color.White; if (editText.Text == null) { editText.Text = ""; } var node = new Node(diagram.Context); if (CurrentHandle == UserHandlePosition.Left) { node.OffsetX = SelectedNode.OffsetX - SelectedNode.Width - 100; node.OffsetY = SelectedNode.OffsetY; } else if (CurrentHandle == UserHandlePosition.Right) { node.OffsetX = SelectedNode.OffsetX + SelectedNode.Width + 100; node.OffsetY = SelectedNode.OffsetY; } node.Width = SelectedNode.Width; node.Height = SelectedNode.Height; node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 3; if (SelectedNode == RootNode) { index = rnd.Next(5); node.Style.Brush = new SolidBrush(FColor[index]); node.Style.StrokeBrush = new SolidBrush(SColor[index]); } else { node.Style = SelectedNode.Style; } node.Annotations.Add(new Annotation() { Content = editText.Text, FontSize = 14 * MainActivity.Factor, TextBrush = new SolidBrush(Color.Black) }); diagram.AddNode(node); var c1 = new Connector(diagram.Context); c1.SourceNode = SelectedNode; c1.TargetNode = node; //c1.Style.StrokeBrush = node.Style.StrokeBrush; //c1.Style.StrokeWidth = 3; //c1.TargetDecoratorStyle.Fill = (node.Style.StrokeBrush as SolidBrush).FillColor; //c1.TargetDecoratorStyle.StrokeColor = (c1.TargetNode.Style.StrokeBrush as SolidBrush).FillColor; //c1.SegmentType = SegmentType.CurveSegment; //c1.Style.StrokeStyle = StrokeStyle.Dashed; diagram.AddConnector(c1); if (CurrentHandle == UserHandlePosition.Left) { if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateLeftOrTop(); } else if (CurrentHandle == UserHandlePosition.Right) { if (!(diagram.LayoutManager.Layout as MindMapLayout).EnableFreeForm) (diagram.LayoutManager.Layout as MindMapLayout).UpdateRightOrBottom(); } m_mindmap.SelectedNode = node; m_mindmap.UpdateHandle(); diagram.Select(node); diagram.BringToView(node); m_mindmap.UpdateTheme(); }); alertBuilder.SetNegativeButton(negative, (senderAlert, args) => { alertBuilder.SetCancelable(true); }); alertBuilder.Show(); } internal void ShowPopUpForComments(string positive, string negative) { alertBuilder.SetTitle("Enter Comments"); editText.Text = _inputstring; editText.FocusableInTouchMode = true; editText.RequestFocus(); editText.SetBackgroundColor(Color.WhiteSmoke); editText.SetTextColor(Color.Black); alertBuilder.SetView(editText); alertBuilder.SetCancelable(false); alertBuilder.SetPositiveButton(positive, (senderAlert, args) => { (diagram.SelectedItems[0] as Node).Content = editText.Text; }); alertBuilder.SetNegativeButton(negative, (senderAlert, args) => { alertBuilder.SetCancelable(true); }); alertBuilder.Show(); } } }<file_sep>/Forms/Schedule/Schedule/Samples/LoadOnDemand/Behaviors/LoadOnDemandBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Load On Demand Behavior class /// </summary> public class LoadOnDemandBehavior : Behavior<SampleView> { /// <summary> /// schedule initialize /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule schedule; /// <summary> /// subject collection /// </summary> private List<string> subjectCollection; /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(SampleView bindable) { base.OnAttachedTo(bindable); this.schedule = bindable.Content.FindByName<Syncfusion.SfSchedule.XForms.SfSchedule>("Schedule"); if (Device.RuntimePlatform == Device.Android) { this.schedule.ViewHeaderStyle.DateFontSize = 24; } this.CreateAppointmentSubjects(); this.schedule.VisibleDatesChangedEvent += this.Schedule_VisibleDatesChangedEvent; } /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable value</param> protected override void OnDetachingFrom(SampleView bindable) { base.OnDetachingFrom(bindable); this.schedule.VisibleDatesChangedEvent -= this.Schedule_VisibleDatesChangedEvent; this.schedule = null; } /// <summary> /// Schedules the visible dates changed event. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Visible Dates Changed Event Args</param> private void Schedule_VisibleDatesChangedEvent(object sender, VisibleDatesChangedEventArgs e) { this.IntializeAppoitments(e.visibleDates.Count, e.visibleDates); this.schedule.MoveToDate = DateTime.Now.Date.AddHours(9); } /// <summary> /// Initialize the appointment. /// </summary> /// <param name="count">Count</param> /// <param name="visibleDates">Visible dates</param> private void IntializeAppoitments(int count, List<DateTime> visibleDates) { ScheduleAppointmentCollection appointments = new ScheduleAppointmentCollection(); var random = new Random(); DateTime randomDate = new DateTime(); // Adding Appointment based on Visible dates count for (int i = 0; i < count; i++) { var date = visibleDates[i]; randomDate = visibleDates[random.Next(0, count)]; // Two appointments per day for (int a = 0; a < 2; a++) { var scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.StartTime = new DateTime(date.Year, date.Month, date.Day, random.Next(9, 18), 0, 0); scheduleAppointment.EndTime = scheduleAppointment.StartTime.AddHours(1); scheduleAppointment.Color = Color.FromRgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)); scheduleAppointment.Subject = this.subjectCollection[random.Next(0, 25)]; appointments.Add(scheduleAppointment); } } // Allday Appointment per view var alldayAppointment = new ScheduleAppointment(); alldayAppointment.StartTime = new DateTime(randomDate.Year, randomDate.Month, randomDate.Day, random.Next(9, 18), 0, 0); alldayAppointment.EndTime = alldayAppointment.StartTime.AddHours(1); alldayAppointment.Color = Color.FromRgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255)); alldayAppointment.Subject = this.subjectCollection[random.Next(0, 25)]; alldayAppointment.IsAllDay = true; appointments.Add(alldayAppointment); this.schedule.DataSource = appointments; } /// <summary> /// Creates the appointment subjects. /// </summary> private void CreateAppointmentSubjects() { this.subjectCollection = new List<string>(); this.subjectCollection.Add("General Meeting"); this.subjectCollection.Add("Plan Execution"); this.subjectCollection.Add("Project Plan"); this.subjectCollection.Add("Consulting"); this.subjectCollection.Add("Performance Check"); this.subjectCollection.Add("General Meeting"); this.subjectCollection.Add("Plan Execution"); this.subjectCollection.Add("Project Plan"); this.subjectCollection.Add("Consulting"); this.subjectCollection.Add("Performance Check"); this.subjectCollection.Add("Business Meeting"); this.subjectCollection.Add("Conference"); this.subjectCollection.Add("Project Status Discussion"); this.subjectCollection.Add("Auditing"); this.subjectCollection.Add("Client Meeting"); this.subjectCollection.Add("Generate Report"); this.subjectCollection.Add("Target Meeting"); this.subjectCollection.Add("Pay House Rent"); this.subjectCollection.Add("Car Service"); this.subjectCollection.Add("Feedback Meeting"); this.subjectCollection.Add("E-Bill due"); this.subjectCollection.Add("CheckUp"); this.subjectCollection.Add("Rating Meeting"); this.subjectCollection.Add("Sprint report"); this.subjectCollection.Add("Team outing"); } } } <file_sep>/Forms/TreeView/TreeView/Samples/GettingStarted/ViewModel/FoodSpeciesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeView { [Preserve(AllMembers = true)] public class FoodSpeciesViewModel { public ObservableCollection<SpeciesFamily> SpeciesFamilies { get; set; } public ObservableCollection<SpeciesType> SpeciesType { get; set; } public ObservableCollection<Species> Species { get; set; } public FoodSpeciesViewModel() { this.SpeciesFamilies= GenerateItems(); } private ObservableCollection<SpeciesFamily> GenerateItems() { var fruit = new SpeciesFamily() { SpeciesName = "Fruits" }; var vegetables = new SpeciesFamily() { SpeciesName = "Vegetables" }; var grains = new SpeciesFamily() { SpeciesName = "Grains" }; var oranges = new SpeciesType() { SpeciesName = "Oranges" }; var pineapple = new SpeciesType() { SpeciesName = "Pineapple" }; var apples = new SpeciesType() { SpeciesName = "Apples" }; var bananas = new SpeciesType() { SpeciesName = "Bananas" }; var pears = new SpeciesType() { SpeciesName = "Pears" }; var apple = new Species() { SpeciesName = "Apple" }; var macintosh = new Species() { SpeciesName = "Macintosh" }; var grannysmith = new Species() { SpeciesName = "<NAME>" }; var fuji = new Species() { SpeciesName = "Fuji" }; var anjou = new Species() { SpeciesName = "Anjou" }; var barlett = new Species() { SpeciesName = "Bartlett" }; var bosc = new Species() { SpeciesName = "Bosc" }; var concorde = new Species() { SpeciesName = "Concorde" }; var seckel = new Species() { SpeciesName = "Seckel" }; var starkrimson = new Species() { SpeciesName = "Starkrimson" }; var podded = new SpeciesType() { SpeciesName = "Podded Vegetables" }; var bulb = new SpeciesType() { SpeciesName = "Bulb and Stem Vegetables" }; var root = new SpeciesType() { SpeciesName = "Root and Tuberous Vegetables" }; var lentil = new Species() { SpeciesName = "Lentil" }; var pea = new Species() { SpeciesName = "Pea" }; var peanut = new Species() { SpeciesName = "Peanut" }; var asparagus = new Species() { SpeciesName = "Asparagus" }; var celery = new Species() { SpeciesName = "Celery" }; var leek = new Species() { SpeciesName = "Leek" }; var onion = new Species() { SpeciesName = "Onion" }; var carrot = new Species() { SpeciesName = "Carrot" }; var ginger = new Species() { SpeciesName = "Ginger" }; var parsnip = new Species() { SpeciesName = "Parsnip" }; var potato = new Species() { SpeciesName = "Potato" }; var cereals = new SpeciesType() { SpeciesName = "Cereals" }; var pseidocereals = new SpeciesType() { SpeciesName = "Pseudocereals" }; var oilseeds = new SpeciesType() { SpeciesName = "Oilseeds" }; var barley = new Species() { SpeciesName = "Barley" }; var oats = new Species() { SpeciesName = "Oats" }; var rice = new Species() { SpeciesName = "Rice" }; var amaranth = new Species() { SpeciesName = "Amaranth" }; var bucketwheat = new Species() { SpeciesName = "Buckwheat" }; var chia = new Species() { SpeciesName = "Chia" }; var quinoa = new Species() { SpeciesName = "Quinoa" }; var mustard = new Species() { SpeciesName = "India Mustard" }; var safflower = new Species() { SpeciesName = "Safflower" }; var flaxseed = new Species() { SpeciesName = "Flax Seed" }; var poppyseed = new Species() { SpeciesName = "Poppy Seed" }; fruit.SpeciesType = new ObservableCollection<SpeciesType>(); fruit.SpeciesType.Add(oranges); fruit.SpeciesType.Add(pineapple); fruit.SpeciesType.Add(apples); fruit.SpeciesType.Add(bananas); fruit.SpeciesType.Add(pears); apples.Species = new ObservableCollection<Species>(); apples.Species.Add(apple); apples.Species.Add(macintosh); apples.Species.Add(grannysmith); apples.Species.Add(fuji); pears.Species = new ObservableCollection<Species>(); pears.Species.Add(anjou); pears.Species.Add(barlett); pears.Species.Add(bosc); pears.Species.Add(concorde); pears.Species.Add(seckel); pears.Species.Add(starkrimson); vegetables.SpeciesType = new ObservableCollection<SpeciesType>(); vegetables.SpeciesType.Add(podded); vegetables.SpeciesType.Add(bulb); vegetables.SpeciesType.Add(root); podded.Species = new ObservableCollection<Species>(); podded.Species.Add(lentil); podded.Species.Add(pea); podded.Species.Add(peanut); bulb.Species = new ObservableCollection<Species>(); bulb.Species.Add(asparagus); bulb.Species.Add(celery); bulb.Species.Add(leek); bulb.Species.Add(onion); root.Species = new ObservableCollection<Species>(); root.Species.Add(carrot); root.Species.Add(ginger); root.Species.Add(parsnip); root.Species.Add(potato); grains.SpeciesType = new ObservableCollection<SpeciesType>(); grains.SpeciesType.Add(cereals); grains.SpeciesType.Add(pseidocereals); grains.SpeciesType.Add(oilseeds); cereals.Species = new ObservableCollection<Species>(); cereals.Species.Add(barley); cereals.Species.Add(oats); cereals.Species.Add(rice); pseidocereals.Species = new ObservableCollection<Species>(); pseidocereals.Species.Add(amaranth); pseidocereals.Species.Add(bucketwheat); pseidocereals.Species.Add(chia); pseidocereals.Species.Add(quinoa); oilseeds.Species = new ObservableCollection<Species>(); oilseeds.Species.Add(mustard); oilseeds.Species.Add(safflower); oilseeds.Species.Add(flaxseed); oilseeds.Species.Add(poppyseed); var sepciesList = new ObservableCollection<SpeciesFamily>(); sepciesList.Add(fruit); sepciesList.Add(vegetables); sepciesList.Add(grains); return sepciesList; } } } <file_sep>/Forms/Chart/Chart/Samples/LiveUpdate/LiveUpdateViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfChart { public class LiveUpdateViewModel { private bool canStopTimer; private int wave1; private int wave2 = 180; public ObservableCollection<ChartDataModel> liveData1 { get; set; } public ObservableCollection<ChartDataModel> liveData2 { get; set; } public LiveUpdateViewModel() { liveData1 = new ObservableCollection<ChartDataModel>(); liveData2 = new ObservableCollection<ChartDataModel>(); } public async void UpdateLiveData() { for (var i = 0; i < 180; i++) { liveData1.Add(new ChartDataModel(i, Math.Sin(wave1 * (Math.PI / 180.0)))); wave1++; } for (var i = 0; i < 180; i++) { liveData2.Add(new ChartDataModel(i, Math.Sin(wave2 * (Math.PI / 180.0)))); wave2++; } wave1 = liveData1.Count; await Task.Delay(200); } private bool UpdateData() { if (canStopTimer) return false; liveData1.RemoveAt(0); liveData1.Add(new ChartDataModel(wave1, Math.Sin(wave1 * (Math.PI / 180.0)))); liveData2.RemoveAt(0); liveData2.Add(new ChartDataModel(wave1, Math.Sin(wave2 * (Math.PI / 180.0)))); wave1++; wave2++; return true; } public void StopTimer() { canStopTimer = true; } public async void StartTimer() { await Task.Delay(500); Device.StartTimer(new TimeSpan(0, 0, 0, 0, 10), UpdateData); canStopTimer = false; } } }<file_sep>/Forms/TimePicker/TimePicker/Samples/TimePickerGettingStarted/TimePickerGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.ListView.XForms; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfTimePicker { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class TimePickerGettingStarted : SampleView { /// <summary> /// Time Picker GettingStarted /// </summary> public TimePickerGettingStarted() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP) { layoutRootGrid.WidthRequest = 500; } } /// <summary> /// ListView Swipe Ended event /// </summary> /// <param name="sender">sender value</param> /// <param name="e">Event args</param> private void ListView_SwipeEnded(object sender, Syncfusion.ListView.XForms.SwipeEndedEventArgs e) { if (e.SwipeDirection == Syncfusion.ListView.XForms.SwipeDirection.Right) { e.SwipeOffset = sfListView.Width; Device.BeginInvokeOnMainThread(async () => { await Task.Delay(500); viewModel.Alarms.RemoveAt(e.ItemIndex); }); } } } } <file_sep>/Forms/Chips/Chips/Converters/StringToColorConverter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Globalization; using Syncfusion.XForms.Buttons; using Xamarin.Forms; namespace SampleBrowser.Chips { #region Converter /// <summary> /// String to color converter. /// </summary> public class StringToColorConverter:IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { switch(value.ToString()) { case "Blue": return Color.Blue; case "Black": return Color.Black; case "Red": return Color.Red; case "Pink": return Color.Pink; case "Purple": return Color.Purple; case "Green": return Color.Green; case "White": return Color.White; case "Orange": return Color.Orange; } return Color.Transparent; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } #endregion } <file_sep>/Forms/Chart/Chart/Samples/DateTimeAxis/DateTimeAxisViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using System; namespace SampleBrowser.SfChart { public class DateTimeAxisViewModel { public ObservableCollection<Production> DateTimeData { get; set; } public DateTimeAxisViewModel() { DateTimeData = new ObservableCollection<Production>(); Random rand = new Random(); double value = 100; DateTime date = new DateTime(2017, 1, 1); for (int i = 0; i < 365; i++) { if (rand.NextDouble() > 0.5) value += rand.NextDouble(); else value -= rand.NextDouble(); DateTimeData.Add(new Production { Growth = value, Date = date }); date = date.AddDays(1); } } } public class Production { public double Growth { get; set; } public DateTime Date { get; set; } } }<file_sep>/iOS/SampleBrowser/Samples/PopupLayout/Popup Customizations/CustomView/MovieTile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Threading; using System.Threading.Tasks; using CoreGraphics; using Syncfusion.SfDataGrid; using Syncfusion.iOS.PopupLayout; using UIKit; namespace SampleBrowser { public class MovieTile : GridCell { MovieLayout movieLayout; UIImageView movieImage; UILabel movieTitle; UILabel movieCast; UILabel twoDLabel; UILabel threeDLabel; UILabel certificateLabel; UIButton book; UIImageView imageView; UIView backgroundView; UIView mainView; DateLayout dateLayout; SfPopupLayout animationPopup; SfDataGrid dataGrid; public MovieTile() { movieLayout = new MovieLayout(); movieImage = new UIImageView(); imageView = new UIImageView(); movieTitle = new UILabel(); movieTitle.Font = UIFont.PreferredCaption1; movieCast = new UILabel(); movieCast.Font = UIFont.PreferredFootnote; movieCast.TextColor = UIColor.LightGray; book = new UIButton(); book.SetTitle("Book", UIControlState.Normal); book.SetTitleColor(UIColor.White, UIControlState.Normal); book.BackgroundColor = UIColor.FromRGB(0, 124, 238); book.Font = UIFont.PreferredCaption1; book.TouchUpInside += Book_TouchUpInside; twoDLabel = new UILabel(); twoDLabel.Text = "2D"; twoDLabel.TextColor = UIColor.Gray; twoDLabel.Font = UIFont.PreferredCaption2; twoDLabel.TextAlignment = UITextAlignment.Center; twoDLabel.Layer.BorderColor = UIColor.DarkGray.CGColor; twoDLabel.Layer.BorderWidth = 0.5f; certificateLabel = new UILabel(); certificateLabel.Text = "UA"; certificateLabel.TextColor = UIColor.Gray; certificateLabel.Font = UIFont.PreferredCaption2; certificateLabel.TextAlignment = UITextAlignment.Center; certificateLabel.Layer.BorderColor = UIColor.DarkGray.CGColor; certificateLabel.Layer.BorderWidth = 0.5f; movieLayout.AddSubview(movieImage); movieLayout.AddSubview(movieTitle); movieLayout.AddSubview(movieCast); movieLayout.AddSubview(book); movieLayout.AddSubview(certificateLabel); movieLayout.AddSubview(twoDLabel); this.AddSubview(movieLayout); this.CanRendererUnload = false; } async void Book_TouchUpInside(object sender, EventArgs e) { dataGrid = this.DataColumn.Renderer.DataGrid; AddBackgroundView(); dataGrid.Columns.RemoveAt(0); dataGrid.HeaderRowHeight = 62; GridTextColumn theaterList = new GridTextColumn(); theaterList.HeaderText = "Movies List"; theaterList.HeaderTemplate = CreateDateViewTemplate(); theaterList.HeaderTextAlignment = UIKit.UITextAlignment.Center; theaterList.UserCellType = typeof(TheaterTile); dataGrid.Columns.Add(theaterList); await Task.Delay(100); LoopView(); } private async void LoopView() { System.Drawing.Point point1 = new System.Drawing.Point(0, 0); animationPopup = new SfPopupLayout(); animationPopup.PopupView.BackgroundColor = UIColor.Clear; animationPopup.PopupView.AnimationMode = AnimationMode.None; if (LoadImage("Images/Popup_DateSelected.png", new CGRect(10 + 5, 70 + 5, 175, 75))) await Task.Delay(1800); animationPopup.Dismiss(); await Task.Delay(300); animationPopup.PopupView.AnimationMode = AnimationMode.SlideOnLeft; if(LoadImage("Images/Popup_TheatrInfo.png", new CGRect(UIScreen.MainScreen.Bounds.Width - 200, 180, 150, 35))) await Task.Delay(1800); animationPopup.Dismiss(); await Task.Delay(300); animationPopup.PopupView.AnimationMode = AnimationMode.Zoom; if(LoadImage("Images/Popup_SelectSeats.png", new CGRect(10, 180 + 30, 175, 75))) await Task.Delay(1800); animationPopup.Dismiss(); await Task.Delay(200); backgroundView.RemoveFromSuperview(); } private bool LoadImage(string path, CGRect rect) { imageView = null; imageView = new UIImageView(); imageView.Image = UIImage.FromFile(path); animationPopup.PopupView.Frame = rect; imageView.Frame = new CGRect(animationPopup.PopupView.Frame.Left, animationPopup.PopupView.Frame.Top, animationPopup.PopupView.Frame.Width, animationPopup.PopupView.Frame.Height); animationPopup.PopupView.PopupStyle.BorderThickness = 0; animationPopup.PopupView.PopupStyle.BorderColor = UIColor.Clear; animationPopup.PopupView.ShowHeader = false; animationPopup.PopupView.ShowFooter = false; animationPopup.PopupView.ShowHeader = false; animationPopup.PopupView.ShowFooter = false; animationPopup.BackgroundColor = UIColor.Red; animationPopup.PopupView.ContentView = imageView; if (this.backgroundView.Window == null || dataGrid == null || dataGrid.Window == null) return false; animationPopup.IsOpen = true; return true; } private void AddBackgroundView() { backgroundView = new UIView(); backgroundView.Tag = 100; backgroundView.BackgroundColor = UIColor.Black; backgroundView.Alpha = 0.82f; mainView = this.dataGrid.Superview; this.mainView.AddSubview(backgroundView); backgroundView.Frame = new CGRect(0, 0, this.dataGrid.Frame.Width, this.dataGrid.Frame.Height); } private UIView CreateDateViewTemplate() { dateLayout = new DateLayout(); return dateLayout; } protected override void UnLoad() { this.RemoveFromSuperview(); } public override void LayoutSubviews() { base.LayoutSubviews(); var rowData = (this.DataColumn.RowData as TicketBookingInfo); movieImage.Image = rowData.MovieImage; movieTitle.Text = rowData.MovieName; movieCast.Text = rowData.Cast; if (rowData.MovieName == "A-Team" || rowData.MovieName == "Conjuring 2" || rowData.MovieName == "Insidious 2" || rowData.MovieName == "Clash Of The Titans") { threeDLabel = new UILabel(); threeDLabel.Text = "3D"; threeDLabel.TextColor = UIColor.Gray; threeDLabel.Font = UIFont.PreferredCaption2; threeDLabel.TextAlignment = UITextAlignment.Center; threeDLabel.Layer.BorderColor = UIColor.DarkGray.CGColor; threeDLabel.Layer.BorderWidth = 0.5f; movieLayout.AddSubview(threeDLabel); } this.movieLayout.Frame = new CGRect(Bounds.Left, Bounds.Top, Bounds.Width, Bounds.Height); } } public class MovieLayout : UIView { public MovieLayout() { } public override void LayoutSubviews() { this.Subviews[0].Frame = new CGRect(Bounds.Left + 5, Bounds.Top + 16, 65, 85); this.Subviews[1].Frame = new CGRect(this.Subviews[0].Frame.Right + 8, Bounds.Top + 16, Bounds.Width - 60 - this.Subviews[0].Frame.Right - 8, 25); this.Subviews[2].Frame = new CGRect(this.Subviews[0].Frame.Right + 8, Subviews[1].Frame.Bottom + 8, Bounds.Width - 60 - this.Subviews[0].Frame.Right - 8, 25); this.Subviews[3].Frame = new CGRect(this.Subviews[1].Frame.Right + 5, Bounds.Height / 2 - 15, Bounds.Width - this.Subviews[1].Frame.Right - 10, 30); this.Subviews[4].Frame = new CGRect(this.Subviews[0].Frame.Right + 8, Subviews[2].Frame.Bottom + 10, 30, 20); this.Subviews[5].Frame = new CGRect(this.Subviews[4].Frame.Right + 10, Subviews[2].Frame.Bottom + 10, 30, 20); if (this.Subviews.Length > 6) this.Subviews[6].Frame = new CGRect(this.Subviews[5].Frame.Right + 10, Subviews[2].Frame.Bottom + 10, 30, 20); } } public class DateLayout : UIView { UILabel dayLabel; UILabel dateLabel; public DateLayout() { UserInteractionEnabled = true; this.AddSubview(new UIView() { UserInteractionEnabled = true }); this.AddSubview(new UIView() { UserInteractionEnabled = true }); this.AddSubview(new UIView() { UserInteractionEnabled = true }); this.AddSubview(new UIView() { UserInteractionEnabled = true }); this.AddSubview(new UIView() { UserInteractionEnabled = true }); this.AddSubview(new UIView() { UserInteractionEnabled = true }); this.AddSubview(new UIView() { UserInteractionEnabled = true }); foreach (var v in this.Subviews) { var tapGesture = new UITapGestureRecognizer(DateSelected) { NumberOfTapsRequired = 1 }; v.AddGestureRecognizer(tapGesture); } this.BackgroundColor = UIColor.White; } void DateSelected(UITapGestureRecognizer tasture) { foreach (var v in tasture.View.Superview.Subviews) { foreach (var c in v.Subviews) { if ((c as UILabel).Text.Length > 2) (c as UILabel).TextColor = UIColor.Gray; else (c as UILabel).TextColor = UIColor.Black; c.BackgroundColor = UIColor.White; } } foreach (var v in tasture.View.Subviews) { v.BackgroundColor = UIColor.FromRGB(0, 124, 238); (v as UILabel).TextColor = UIColor.White; } } public override void LayoutSubviews() { nfloat temp = 0; for (int i = 0; i < this.Subviews.Length; i++) { this.Subviews[i].Add(CreateDayLabel(GetDay(i), i)); this.Subviews[i].Add(CreateDateLabel(i)); this.Subviews[i].Frame = new CGRect(Bounds.Left + temp, Bounds.Top, Bounds.Width / 7, 62); temp = temp + (Bounds.Width / 7); this.Subviews[i].Subviews[0].Frame = new CGRect(Bounds.Left, Bounds.Top, Bounds.Width / 7, 29); this.Subviews[i].Subviews[1].Frame = new CGRect(Bounds.Left, this.Subviews[i].Subviews[0].Frame.Bottom, Bounds.Width / 7, 29); } } private string GetDay(int i) { return DateTime.Now.AddDays(i).DayOfWeek.ToString().Substring(0, 3).ToUpper(); } private UILabel CreateDateLabel(int num) { dateLabel = new UILabel(); dateLabel.Text = DateTime.Now.AddDays(num).Day.ToString(); if (num == 0) { dateLabel.BackgroundColor = UIColor.FromRGB(0, 124, 238); dateLabel.TextColor = UIColor.White; } else { dateLabel.BackgroundColor = UIColor.White; dateLabel.TextColor = UIColor.Black; } dateLabel.UserInteractionEnabled = false; dateLabel.Font = UIFont.PreferredCaption1; dateLabel.TextAlignment = UITextAlignment.Center; return dateLabel; } private UILabel CreateDayLabel(string day, int position) { dayLabel = new UILabel(); dayLabel.Text = day; if (position == 0) { dayLabel.BackgroundColor = UIColor.FromRGB(0, 124, 238); dayLabel.TextColor = UIColor.White; } else { dayLabel.BackgroundColor = UIColor.White; if (dayLabel.Text.Length > 2) dayLabel.TextColor = UIColor.Gray; else dayLabel.TextColor = UIColor.Black; } dayLabel.UserInteractionEnabled = false; dayLabel.Font = UIFont.PreferredCaption1; dayLabel.TextAlignment = UITextAlignment.Center; return dayLabel; } } } <file_sep>/Forms/TreeMap/TreeMap/Samples/TreeMapGettingStarted/TreeMapGettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; namespace SampleBrowser.SfTreeMap { [Preserve(AllMembers = true)] public class PopulationViewModel { public PopulationViewModel() { this.PopulationDetails = new ObservableCollection<PopulationDetail>(); PopulationDetails.Add(new PopulationDetail() { Continent = "Asia", Country = "Indonesia", Growth = 3, Population = 237641326 }); PopulationDetails.Add(new PopulationDetail() { Continent = "Asia", Country = "Russia", Growth = 2, Population = 152518015 }); PopulationDetails.Add(new PopulationDetail() { Continent = "Asia", Country = "Malaysia", Growth = 1, Population = 29672000 }); PopulationDetails.Add(new PopulationDetail() { Continent = "North America", Country = "United States", Growth = 4, Population = 315645000 }); PopulationDetails.Add(new PopulationDetail() { Continent = "North America", Country = "Mexico", Growth = 2, Population = 112336538 }); PopulationDetails.Add(new PopulationDetail() { Continent = "North America", Country = "Canada", Growth = 1, Population = 35056064 }); PopulationDetails.Add(new PopulationDetail() { Continent = "South America", Country = "Colombia", Growth = 1, Population = 47000000 }); PopulationDetails.Add(new PopulationDetail() { Continent = "South America", Country = "Brazil", Growth = 3, Population = 193946886 }); PopulationDetails.Add(new PopulationDetail() { Continent = "Africa", Country = "Nigeria", Growth = 2, Population = 170901000 }); PopulationDetails.Add(new PopulationDetail() { Continent = "Africa", Country = "Egypt", Growth = 1, Population = 83661000 }); PopulationDetails.Add(new PopulationDetail() { Continent = "Europe", Country = "Germany", Growth = 1, Population = 81993000 }); PopulationDetails.Add(new PopulationDetail() { Continent = "Europe", Country = "France", Growth = 1, Population = 65605000 }); PopulationDetails.Add(new PopulationDetail() { Continent = "Europe", Country = "UK", Growth = 1, Population = 63181775 }); } public ObservableCollection<PopulationDetail> PopulationDetails { get; set; } } } <file_sep>/iOS/SampleBrowser/Samples/Rating/Rating_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfRating.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Rating_Mobile : SampleView { UILabel precisionLabel,toolTipLabel,itemCountLabel; UILabel movieRateLabel,walkLabel,timeLabel,descriptionLabel,rateLabel,valueLabel; UITextView itemCountTextfield; UIImageView image1; UIView customView; UIButton precisionButton = new UIButton (); UIButton toolTipButton = new UIButton (); UIButton doneButton=new UIButton(); UIPickerView precisionPicker, toolTipPicker; public UIView option=new UIView(); private string selectedType; SfRating rating2,rating1; private readonly IList<string> precisionList = new List<string> { "Standard", "Half", "Exact" }; private readonly IList<string> toottipplace = new List<string> { "TopLeft", "BottomRight", "None" }; public void optionView() { this.option.AddSubview (precisionLabel); this.option.AddSubview (toolTipLabel); this.option.AddSubview (precisionButton); this.option.AddSubview (itemCountLabel); this.option.AddSubview (toolTipButton); this.option.AddSubview (precisionPicker); this.option.AddSubview (toolTipPicker); this.option.AddSubview (doneButton); this.option.AddSubview (itemCountTextfield); } void Rating_ValueChanged(object sender, ValueChangedEventArgs e) { UpdateText(); } public Rating_Mobile() { SfRatingSettings ratingSetting1 = new SfRatingSettings(); ratingSetting1.RatedStrokeWidth = 2; ratingSetting1.UnRatedStrokeWidth = 2; //Rating 1 rating1 = new SfRating (); rating1.ItemCount=5; rating1.Precision= SFRatingPrecision.Standard; rating1.TooltipPlacement= SFRatingTooltipPlacement.None; rating1.ItemSize=30; rating1.RatingSettings = ratingSetting1; rating1.Value = 3; rating1.ItemSpacing = 5; rating1.EnableAutoSize = true; rating1.ValueChanged += Rating_ValueChanged; //RatingSettings SfRatingSettings ratingSetting = new SfRatingSettings (); ratingSetting.RatedFill = UIColor.FromRGB (251,209,10); ratingSetting.RatedStroke = UIColor.FromRGB (251,209,10); //Rating 2 rating2 = new SfRating(); rating2.ItemCount=5; rating2.RatingSettings = ratingSetting; rating2.Precision = SFRatingPrecision.Half; rating2.TooltipPlacement= SFRatingTooltipPlacement.None; rating2.ItemSize=10; rating2.Readonly=true; rating2.Value=(nfloat)3.5; rating2.ItemSpacing = 5; this.AddSubview (rating1); this.AddSubview (rating2); mainPageDesign(); } public void mainPageDesign() { customView = new UIView(); customView.BackgroundColor = UIColor.FromRGB(165, 165, 165); this.OptionView = new UIView(); image1 = new UIImageView(); precisionPicker = new UIPickerView(); toolTipPicker = new UIPickerView(); PickerModel model = new PickerModel(precisionList); precisionPicker.Model = model; PickerModel model1 = new PickerModel(toottipplace); toolTipPicker.Model = model1; precisionLabel = new UILabel(); toolTipLabel = new UILabel(); itemCountLabel = new UILabel(); movieRateLabel = new UILabel(); walkLabel = new UILabel(); timeLabel = new UILabel(); descriptionLabel = new UILabel(); rateLabel = new UILabel(); valueLabel = new UILabel(); precisionButton = new UIButton(); toolTipButton = new UIButton(); image1.Image = UIImage.FromBundle("Images/walk.png"); precisionLabel.Text = "Precision"; precisionLabel.TextColor = UIColor.Black; precisionLabel.TextAlignment = UITextAlignment.Left; toolTipLabel.Text = "ToolTip Placement"; toolTipLabel.TextColor = UIColor.Black; toolTipLabel.TextAlignment = UITextAlignment.Left; itemCountLabel.Text = "Item Count"; itemCountLabel.TextColor = UIColor.Black; itemCountLabel.TextAlignment = UITextAlignment.Left; itemCountLabel.Font = UIFont.FromName("Helvetica", 14f); movieRateLabel.Text = "Movie Rating"; movieRateLabel.TextColor = UIColor.Black; movieRateLabel.TextAlignment = UITextAlignment.Left; movieRateLabel.Font = UIFont.FromName("Helvetica", 22f); walkLabel.Text = "The Walk (2015)"; walkLabel.TextColor = UIColor.Black; walkLabel.TextAlignment = UITextAlignment.Left; walkLabel.Font = UIFont.FromName("Helvetica", 18f); timeLabel.Text = "PG | 2 h 20 min"; timeLabel.TextColor = UIColor.Black; timeLabel.TextAlignment = UITextAlignment.Left; timeLabel.Font = UIFont.FromName("Helvetica", 10f); descriptionLabel.Text = "In 1974, high-wire artist <NAME> recruits a team of people to help him realize his dream: to walk the immense void between the world Trade Centre towers."; descriptionLabel.TextColor = UIColor.Black; descriptionLabel.TextAlignment = UITextAlignment.Left; descriptionLabel.Font = UIFont.FromName("Helvetica", 12f); descriptionLabel.LineBreakMode = UILineBreakMode.WordWrap; descriptionLabel.Lines = 0; rateLabel.Text = "Rate"; rateLabel.TextColor = UIColor.Black; rateLabel.TextAlignment = UITextAlignment.Left; rateLabel.Font = UIFont.FromName("Helvetica", 18f); valueLabel.TextColor = UIColor.Black; valueLabel.TextAlignment = UITextAlignment.Left; valueLabel.Font = UIFont.FromName("Helvetica", 14f); UpdateText(); precisionButton.SetTitle("Standard", UIControlState.Normal); precisionButton.SetTitleColor(UIColor.Black, UIControlState.Normal); precisionButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; precisionButton.Layer.CornerRadius = 8; precisionButton.Layer.BorderWidth = 2; precisionButton.TouchUpInside += ShowPicker1; precisionButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; toolTipButton.SetTitle("None", UIControlState.Normal); toolTipButton.SetTitleColor(UIColor.Black, UIControlState.Normal); toolTipButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; toolTipButton.Layer.CornerRadius = 8; toolTipButton.Layer.BorderWidth = 2; toolTipButton.TouchUpInside += ShowPicker2; toolTipButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(246, 246, 246); model.PickerChanged += SelectedIndexChanged; model1.PickerChanged += SelectedIndexChanged1; precisionPicker.ShowSelectionIndicator = true; precisionPicker.Hidden = true; toolTipPicker.Hidden = true; //precisionPicker.BackgroundColor = UIColor.Gray; //toolTipPicker.BackgroundColor = UIColor.Gray; toolTipPicker.ShowSelectionIndicator = true; itemCountTextfield = new UITextView(); itemCountTextfield.TextAlignment = UITextAlignment.Center; itemCountTextfield.Layer.BorderColor = UIColor.Black.CGColor; itemCountTextfield.BackgroundColor = UIColor.FromRGB(246, 246, 246); itemCountTextfield.KeyboardType = UIKeyboardType.NumberPad; itemCountTextfield.Text = "5"; itemCountTextfield.Changed += (object sender, EventArgs e) => { if (itemCountTextfield.Text.Length > 0) { rating1.ItemCount = int.Parse(itemCountTextfield.Text); } else { rating1.ItemCount = 5; } UpdateText(); }; this.AddSubview(movieRateLabel); this.AddSubview(walkLabel); this.AddSubview(timeLabel); this.AddSubview(descriptionLabel); this.AddSubview(rateLabel); this.AddSubview(valueLabel); this.AddSubview(image1); this.AddSubview(itemCountTextfield); } private void UpdateText() { nint tempIntValue = (nint)rating1.Value; nfloat tempFloatValue = rating1.Value; nfloat differencevalue = tempFloatValue - tempIntValue; if(differencevalue == 0) valueLabel.Text = "Rating : "+tempIntValue+" / "+rating1.ItemCount; else valueLabel.Text = "Rating : "+ Math.Round (tempFloatValue,1)+" / "+rating1.ItemCount; } void ShowPicker1 (object sender, EventArgs e) { doneButton.Hidden = false; precisionPicker.Hidden = false; toolTipPicker.Hidden = true; itemCountLabel.Hidden = true; itemCountTextfield.Hidden = true; } void HidePicker (object sender, EventArgs e) { doneButton.Hidden = true; toolTipPicker.Hidden = true; precisionPicker.Hidden = true; itemCountLabel.Hidden = false; itemCountTextfield.Hidden = false; } void ShowPicker2 (object sender, EventArgs e) { doneButton.Hidden = false; precisionPicker.Hidden = true; toolTipPicker.Hidden = false; itemCountLabel.Hidden = true; itemCountTextfield.Hidden = true; } private void SelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; precisionButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Standard") { rating1.Precision = SFRatingPrecision.Standard; } else if (selectedType == "Half") { rating1.Precision = SFRatingPrecision.Half; } else if (selectedType == "Exact") { rating1.Precision = SFRatingPrecision.Exact; } } public override void TouchesBegan (NSSet touches, UIEvent evt){ this.EndEditing (true); } private void SelectedIndexChanged1(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; toolTipButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "TopLeft") { rating1.TooltipPlacement = SFRatingTooltipPlacement.TopLeft; } else if (selectedType == "BottomRight") { rating1.TooltipPlacement = SFRatingTooltipPlacement.BottomRight; } else if (selectedType == "None") { rating1.TooltipPlacement = SFRatingTooltipPlacement.None; } } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; this.OptionView.Frame = view.Frame; option.Frame = new CGRect (0, 90, Frame.Width, Frame.Height); customView.Frame = new CGRect (10, 260,view.Frame.Width-20, 1); rating1.Frame = new CGRect (10,320,270,50); rating2.Frame = new CGRect (235,80,200,20); movieRateLabel.Frame = new CGRect (10,10,200,30); walkLabel.Frame = new CGRect (160,50,160,30); timeLabel.Frame = new CGRect (160,71,80,30); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { descriptionLabel.Frame = new CGRect (160, 30, 400, 200); } else descriptionLabel.Frame = new CGRect (160, 70, 150, 200); rateLabel.Frame = new CGRect (10,280,200,30); valueLabel.Frame = new CGRect (10,370,200,30); image1.Frame = new CGRect (10, 50, 140, 180); precisionLabel.Frame = new CGRect (10,0, this.Frame.Size.Width-10, 30); toolTipLabel.Frame = new CGRect (10, 80, this.Frame.Size.Width-20, 30); itemCountLabel.Frame = new CGRect (10, 160,this.Frame.Size.Width-10 , 30); precisionButton.Frame=new CGRect (10, 40, this.Frame.Size.Width - 20, 30); toolTipButton.Frame=new CGRect (10, 120, this.Frame.Size.Width - 20, 30); itemCountTextfield.Frame = new CGRect (230, 160, this.Frame.Size.Width - 250, 30); precisionPicker.Frame = new CGRect (0, this.Frame.Size.Height/4+50, this.Frame.Size.Width, this.Frame.Size.Height/3-30); toolTipPicker.Frame = new CGRect (0, this.Frame.Size.Height/4+50, this.Frame.Size.Width , this.Frame.Size.Height/3-30); doneButton.Frame = new CGRect (0, this.Frame.Size.Height/4+50, this.Frame.Size.Width, 40); } this.optionView (); base.LayoutSubviews (); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/ReleaseInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser { public class ReleaseInfo :INotifyPropertyChanged { public ReleaseInfo() { } #region private variables private int sNo; private string platform; private string features; private string description; private string releaseVersion; #endregion #region Public Properties public int SNo { get { return this.sNo; } set { this.sNo = value; RaisePropertyChanged("SNo"); } } public string Platform { get { return this.platform; } set { this.platform = value; RaisePropertyChanged("Platform"); } } public string Features { get { return features; } set { features = value; RaisePropertyChanged("Features"); } } public string Description { get { return description; } set { description = value; RaisePropertyChanged("Description"); } } public string ReleaseVersion { get { return releaseVersion; } set { this.releaseVersion = value; RaisePropertyChanged("ReleaseVersion"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <file_sep>/Forms/CircularGauge/CircularGauge/ViewModel/PointerViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; namespace SampleBrowser.SfCircularGauge { public class PointerViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private double firstMarkerValue = 2; private double secondMarkerValue = 10; private double pointerSize = 30; public double PointerSize { get { return pointerSize; } set { pointerSize = value; OnPropertyChanged("PointerSize"); } } public double FirstMarkerValue { get { return firstMarkerValue; } set { firstMarkerValue = value; OnPropertyChanged("FirstMarkerValue"); } } public double SecondMarkerValue { get { return secondMarkerValue; } set { secondMarkerValue = value; OnPropertyChanged("SecondMarkerValue"); } } private void OnPropertyChanged(string name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } } <file_sep>/Forms/PopupLayout/PopupLayout.Android/SplashScreenActivity.cs // ------------------------------------------------------------------------------------ // <copyright file = "SplashScreenActivity.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ namespace SampleBrowser.SfPopupLayout.Droid { using System; using System.Diagnostics.CodeAnalysis; using Android.App; [Activity(Theme = "@style/Theme.Splash", MainLauncher = true, NoHistory = true, Icon = "@drawable/AppIcon")] /// <summary> /// The initial activity of the application. /// </summary> public class SplashScreenActivity : Core.Android.SplashScreenActivity { /// <summary> /// Gets the type of MainActivity /// </summary> /// <returns>returns type of MainActivity</returns> protected override Type GetMainActivityType() { return typeof(MainActivity); } } }<file_sep>/Forms/DataGrid/DataGrid.macOS/FormsViewRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "FormsViewRenderer.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion using System; using System.Collections.Generic; using System.Text; using Foundation; using SampleBrowser.SfDataGrid; using SampleBrowser.SfDataGrid.MacOS; using Xamarin.Forms; using Xamarin.Forms.Platform.MacOS; [assembly: Preserve] [assembly: ExportRenderer(typeof(FormsView), typeof(FormsViewRenderer))] namespace SampleBrowser.SfDataGrid.MacOS { /// <summary> /// A custom View renderer for MAC OS platform /// </summary> internal class FormsViewRenderer : ViewRenderer { /// <summary> /// Gets the value of the PCL View /// </summary> public FormsView FormsView { get { return this.Element as FormsView; } } /// <summary> /// Called while Element has changed in View /// </summary> /// <param name="e">Element Changed Event of View args e</param> protected override void OnElementChanged(ElementChangedEventArgs<View> e) { if (e.NewElement != null) { this.WantsLayer = true; this.Layer.BackgroundColor = this.FormsView.BackgroundColor.ToCGColor(); } base.OnElementChanged(e); } /// <summary> /// Called while Elements property has changed in View /// </summary> /// <param name="sender">Indicates sender of the event</param> /// <param name="e">Indicates PropertyChangedEvent args e</param> protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == "Visibility") { if (this.FormsView.Visibility) { this.Hidden = false; } else { this.Hidden = true; } } } } } <file_sep>/Forms/Chart/Chart/Samples/StackedBar100Chart/StackedBar100SeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class StackedBar100SeriesViewModel { public ObservableCollection<ChartDataModel> StackedBar100Data1 { get; set; } public ObservableCollection<ChartDataModel> StackedBar100Data2 { get; set; } public ObservableCollection<ChartDataModel> StackedBar100Data3 { get; set; } public StackedBar100SeriesViewModel() { StackedBar100Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 12), new ChartDataModel("Apr", 15), new ChartDataModel("May", 20), new ChartDataModel("Jun", 24), }; StackedBar100Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 11), new ChartDataModel("Apr", 16), new ChartDataModel("May", 21), new ChartDataModel("Jun", 25), }; StackedBar100Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 1), new ChartDataModel("Feb", 1.5), new ChartDataModel("Mar", 2), new ChartDataModel("Apr", 2.5), new ChartDataModel("May", 3), new ChartDataModel("Jun", 3.5), }; } } }<file_sep>/Forms/PdfViewer/PdfViewer.iOS/Renderer/EditBookmarkPopupiOSEffect.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using CoreGraphics; using Foundation; using SampleBrowser.SfPdfViewer.iOS; using Syncfusion.Pdf.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ResolutionGroupName("SampleBrowser.SfPdfViewer")] [assembly: ExportEffect(typeof(EditBookmarkPopupEffect), nameof(EditBookmarkPopupEffect))] namespace SampleBrowser.SfPdfViewer.iOS { public class EditBookmarkPopupEffect : PlatformEffect { NSObject _keyboardShowObserver; NSObject _keyboardHideObserver; private PdfUnitConverter unitConverter = new PdfUnitConverter(); protected override void OnAttached() { RegisterForKeyboardNotifications(); } void RegisterForKeyboardNotifications() { if (_keyboardShowObserver == null) _keyboardShowObserver = UIKeyboard.Notifications.ObserveWillShow(OnKeyboardShow); if (_keyboardHideObserver == null) _keyboardHideObserver = UIKeyboard.Notifications.ObserveWillHide(OnKeyboardHide); } void OnKeyboardShow(object sender, UIKeyboardEventArgs args) { NSValue result = (NSValue)args.Notification.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey)); CGSize keyboardSize = result.RectangleFValue.Size; if (Element != null && Element is EditBookmarkPopup editBookmarkPopupView && editBookmarkPopupView.IsRenamePopupOpened && editBookmarkPopupView.IsRenameEntryFocused) { (Element as EditBookmarkPopup).Margin = new Thickness(0, 0, 0, unitConverter.ConvertFromPixels((float)keyboardSize.Height, PdfGraphicsUnit.Point)); //push the remname dialog up to keyboard height when keyboard is activated } } void OnKeyboardHide(object sender, UIKeyboardEventArgs args) { if (Element != null && (Element as EditBookmarkPopup) != null) { (Element as EditBookmarkPopup).Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed } } void UnregisterForKeyboardNotifications() { if (_keyboardShowObserver != null) { _keyboardShowObserver.Dispose(); _keyboardShowObserver = null; } if (_keyboardHideObserver != null) { _keyboardHideObserver.Dispose(); _keyboardHideObserver = null; } } protected override void OnDetached() { UnregisterForKeyboardNotifications(); } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Model/SalesRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SalesRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class used to store the item values /// </summary> public class SalesRepository { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private readonly List<string> salesParsonNames = new List<string>() { "Gary", "Maciej", "Shelley", "Linda", "Carla", "Carol", "Shannon", "Jauna", "Michael", "Terry", "John", "Gail", "Mark", "Martha", "Julie", "Janeth", "Twanna" }; /// <summary> /// Generates days with given count /// </summary> /// <param name="days">generates row count</param> /// <returns>SalesByDate collection values</returns> public ObservableCollection<SalesByDate> GetSalesDetailsByDay(int days) { var collection = new ObservableCollection<SalesByDate>(); var r = new Random(); for (var i = 0; i < days; i++) { var dt = DateTime.Now; foreach (var person in this.salesParsonNames) { if (r.Next(0, 3) == 0) { continue; } { var s = new SalesByDate { Name = person, QS1 = r.Next(100000, 1000000) * 0.01, QS2 = r.Next(100000, 1000000) * 0.01, QS3 = r.Next(100000, 1000000) * 0.01, QS4 = r.Next(100000, 1000000) * 0.01, }; s.Total = s.QS1 + s.QS2 + s.QS3 + s.QS4; s.Date = dt.AddDays(-1 * i); collection.Add(s); } } } return collection; } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/ViewModel/TicketBookingViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "TicketBookingViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Syncfusion.XForms.PopupLayout; using Xamarin.Forms; /// <summary> /// A ViewModel for TicketBooking sample. /// </summary> public class TicketBookingViewModel : INotifyPropertyChanged { #region Fields /// <summary> /// backing field for TimingCommand. /// </summary> private Command<SfPopupLayout> timingCommand; /// <summary> /// backing field for BookingCommand. /// </summary> private Command<SfDataGrid> bookingCommand; /// <summary> /// backing field for ProceedCommand. /// </summary> private Command<SfPopupLayout> proceedCommand; /// <summary> /// backing field for AcceptCommand. /// </summary> private Command<SfPopupLayout> acceptCommand; /// <summary> /// backing field for DeclineCommand. /// </summary> private Command declineCommand; /// <summary> /// backing field for DeclineCommand. /// </summary> private Command<Label> seatSelectionCommand; /// <summary> /// backing field for OpenInfoCommand. /// </summary> private Command<InfoPopupParameters> openInfoCommand; /// <summary> /// Current Terms and Conditions Popup in view. /// </summary> private SfPopupLayout currentTermsAndConditionsPopup; /// <summary> /// Current TicketBooking popup. /// </summary> private SfPopupLayout currentTicketBookingPopup; #endregion #region Constructor /// <summary> /// Initializes a new instance of the TicketBookingViewModel class. /// </summary> public TicketBookingViewModel() { var details = new TicketInfoRepository(); this.TheaterInformation = details.GetDetails(); this.timingCommand = new Command<SfPopupLayout>(this.OnTimingButtonClicked); this.bookingCommand = new Command<SfDataGrid>(this.OnBookingButtonClicked); this.proceedCommand = new Command<SfPopupLayout>(this.OnProceedButtonClicked); this.acceptCommand = new Command<SfPopupLayout>(this.OnAcceptButtonClicked); this.declineCommand = new Command(this.OnDeclineButtonClicked); this.seatSelectionCommand = new Command<Label>(this.SelectSeat); this.openInfoCommand = new Command<InfoPopupParameters>(this.OpenInfoPopup); this.SetBindingImageSource(); } #endregion #region Events /// <summary> /// Event that triggers when the property is changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion #region Properties /// <summary> /// Gets or sets the Command that is called when the timing button is called. /// </summary> public Command<SfPopupLayout> TimingCommand { get { return this.timingCommand; } set { this.timingCommand = value; this.RaisePropertyChanged("TimingCommand"); } } /// <summary> /// Gets or sets the Command that will is called when the book button is clicked. /// </summary> public Command<SfDataGrid> BookingCommand { get { return this.bookingCommand; } set { this.bookingCommand = value; this.RaisePropertyChanged("BookingCommand"); } } /// <summary> /// Gets or sets the command that is executed when the Proceed button is clicked. /// </summary> public Command<SfPopupLayout> ProceedCommand { get { return this.proceedCommand; } set { this.proceedCommand = value; this.RaisePropertyChanged("ProceedCommand"); } } /// <summary> /// Gets or sets the command that is executed when the Accept button is clicked. /// </summary> public Command<SfPopupLayout> AcceptCommand { get { return this.acceptCommand; } set { this.acceptCommand = value; this.RaisePropertyChanged("AcceptCommand"); } } /// <summary> /// Gets or sets the command that is executed when the Decline button is clicked. /// </summary> public Command DeclineCommand { get { return this.declineCommand; } set { this.declineCommand = value; this.RaisePropertyChanged("DeclineCommand"); } } /// <summary> /// Gets or sets the command that is executed when the seat is selected. /// </summary> public Command<Label> SeatSelectionCommand { get { return this.seatSelectionCommand; } set { this.seatSelectionCommand = value; this.RaisePropertyChanged("SeatSelectionCommand"); } } /// <summary> /// Gets or sets the command that is executed when the information image is clicked. /// </summary> public Command<InfoPopupParameters> OpenInfoCommand { get { return this.openInfoCommand; } set { this.openInfoCommand = value; this.RaisePropertyChanged("OpenInfoCommand"); } } #region ItemsSource /// <summary> /// Gets or sets the TheaterInformation which is ObservableCollection of TicketBookingInfo type. /// </summary> public ObservableCollection<TicketBookingInfo> TheaterInformation { get; set; } #endregion #endregion #region Private Methods /// <summary> /// Action to be performed when timing button is clicked. /// </summary> /// <param name="termsAndConditionsPopup">Popup to be displayed.</param> private void OnTimingButtonClicked(SfPopupLayout termsAndConditionsPopup) { this.currentTermsAndConditionsPopup = termsAndConditionsPopup; this.currentTermsAndConditionsPopup.Show(); } /// <summary> /// Action to be performed when book button is clicked. /// </summary> /// <param name="dataGridObject">DataGrid's object in view</param> private void OnBookingButtonClicked(SfDataGrid dataGridObject) { if (dataGridObject != null) { (dataGridObject.Parent as SampleView).Navigation.PushAsync(new TicketBooking()); } } /// <summary> /// Action to be performed when proceed button is clicked. /// </summary> /// <param name="confirmationPopup">Confirmation popup to be displayed.</param> private async void OnProceedButtonClicked(SfPopupLayout confirmationPopup) { if (this.currentTicketBookingPopup != null) { this.currentTicketBookingPopup.Dismiss(); } await Task.Delay(200); confirmationPopup.Show(); } /// <summary> /// Action to be performed when accept button is clicked. /// </summary> /// <param name="ticketBookingPopup">Popup to be displayed.</param> private async void OnAcceptButtonClicked(SfPopupLayout ticketBookingPopup) { this.CloseCurrentTermsAndConditionsPopup(); await Task.Delay(200); this.currentTicketBookingPopup = ticketBookingPopup; this.currentTicketBookingPopup.Show(); } /// <summary> /// Action to be performed when decline button is clicked. /// </summary> private void OnDeclineButtonClicked() { this.CloseCurrentTermsAndConditionsPopup(); } /// <summary> /// Closes the current TermsAndConditionsPopup. /// </summary> private void CloseCurrentTermsAndConditionsPopup() { if (this.currentTermsAndConditionsPopup != null) { this.currentTermsAndConditionsPopup.Dismiss(); } } /// <summary> /// Action to be performed when seats is selected. /// </summary> /// <param name="label">The view that is clicked</param> private void SelectSeat(Label label) { foreach (var children in (label.Parent as StackLayout).Children) { children.BackgroundColor = Color.White; (children as Label).TextColor = Color.Black; } label.BackgroundColor = Color.FromHex("#007CEE"); label.TextColor = Color.White; } /// <summary> /// Action to be performed when Info image is clicked. /// </summary> /// <param name="infoPopupParameters">InfoPopupParameters needed for displaying InfoPopup</param> private void OpenInfoPopup(InfoPopupParameters infoPopupParameters) { infoPopupParameters.InfoPopup.PopupView.HeaderTitle = infoPopupParameters.TheatreLabel.Text; infoPopupParameters.InfoPopup.Show(); } /// <summary> /// Sets the ImageSource for the Images. /// </summary> private void SetBindingImageSource() { } #endregion #region INotifyPropertyChanged implementation /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion } } <file_sep>/Forms/AutoComplete/AutoComplete/Samples/MultiSelect/MultiSelect.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Xamarin.Forms; using SampleBrowser.Core; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; namespace SampleBrowser.SfAutoComplete { public partial class MultiSelect : SampleView { bool closeDropdownOnSelection; public MultiSelect() { InitializeComponent(); this.BindingContext = new MultiSelectViewModel(); } private void autocomplete_DropDownClosing(object sender, Syncfusion.SfAutoComplete.XForms.DropDownCancelEventArgs e) { if (!closeDropdownOnSelection) { if (e.IsItemSelected) { e.Cancel = true; } else { e.Cancel = false; } } else { e.Cancel = false; } } private void closeDropdownOnSelection_Toggled(object sender, ToggledEventArgs e) { if (e.Value) { closeDropdownOnSelection = true; } else { closeDropdownOnSelection = false; } } void ScrollView_Scrolled(System.Object sender, Xamarin.Forms.ScrolledEventArgs e) { if (Device.RuntimePlatform == Device.iOS) { scrollView.ScrollToAsync(0, 0, false); } } } public class StringToColorConverter : IValueConverter { object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { if (value.ToString() == "Blue") return Color.Blue; else if (value.ToString() == "Red") return Color.Red; else if (value.ToString() == "Green") return Color.Green; } return Color.Blue; } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Android/SampleBrowser/Samples/DataGrid/Styles/Purple.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Syncfusion.SfDataGrid; namespace SampleBrowser { public class Purple : DataGridStyle { public Purple() { } public override Color GetHeaderBackgroundColor() { return Color.ParseColor("#83538B"); } public override Color GetHeaderForegroundColor() { return Color.ParseColor("#FFFFFF"); } public override Color GetRecordForegroundColor() { return Color.ParseColor("#000000"); } public override Color GetAlternatingRowBackgroundColor() { return Color.ParseColor("#EDE7F6"); } public override Color GetSelectionBackgroundColor() { return Color.ParseColor("#9575CD"); } public override Color GetSelectionForegroundColor() { return Color.ParseColor("#FFFFFF"); } public override GridLinesVisibility GetGridLinesVisibility() { return GridLinesVisibility.Horizontal; } } }<file_sep>/iOS/SampleBrowser/Samples/CircularGauge/DirectionCompass.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfGauge.iOS; using System.Collections.ObjectModel; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using System.Drawing; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class DirectionCompass : SampleView { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } SFCircularGauge gauge; UIPickerView opposed; UIView option = new UIView(); SFNeedlePointer pointer2; public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } if (Utility.IsIPad) { gauge.Frame = new CGRect(50, 50, (float)this.Frame.Width - 100, (float)this.Frame.Height - 100); } else { gauge.Frame = new CGRect(10, 10, (float)this.Frame.Width - 20, (float)this.Frame.Height - 20); } base.LayoutSubviews(); } public DirectionCompass() { this.BackgroundColor = UIColor.White; gauge = new SFCircularGauge(); gauge.BackgroundColor = UIColor.White; opposed = new UIPickerView(); SFCircularScale scale = new SFCircularScale(); scale.StartValue = 0; scale.EndValue = 16; scale.Interval = 2; scale.LabelOffset = 0.75f; scale.StartAngle = 0; scale.SweepAngle = 360; scale.MinorTicksPerInterval = 1; scale.ShowLastLabel = false; scale.ScaleStartOffset = 0.99f; scale.ScaleEndOffSet = 0.9f; scale.MajorTickSettings.Offset = 0.9f; scale.MinorTickSettings.Offset = 0.9f; scale.MinorTickSettings.EndOffset = 0.4f; scale.RimColor = UIColor.FromRGB(224, 224, 224); scale.LabelColor = UIColor.FromRGB(75, 75, 75); SFNeedlePointer pointer1 = new SFNeedlePointer(); pointer1.Value = 14; pointer1.Color = UIColor.LightGray; pointer1.PointerType = SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle; pointer1.LengthFactor = 0.65f; pointer1.Width = 20; pointer1.KnobRadiusFactor = 0; pointer1.KnobRadius = 0; pointer1.KnobColor = UIColor.White; pointer1.KnobStrokeColor = UIColor.White; pointer1.KnobStrokeWidth = 3; pointer1.EnableAnimation = false; scale.Pointers.Add(pointer1); pointer2 = new SFNeedlePointer(); pointer2.Value = 6; pointer2.Color = UIColor.Red; pointer2.Width = 20; pointer2.KnobRadius = 20; pointer2.KnobColor = UIColor.White; pointer2.KnobStrokeColor = UIColor.White; pointer2.KnobStrokeWidth = 3; pointer2.LengthFactor = 0.65f; pointer2.PointerType = SFCiruclarGaugePointerType.SFCiruclarGaugePointerTypeTriangle; pointer2.EnableAnimation = false; scale.Pointers.Add(pointer2); gauge.Scales.Add(scale); gauge.Delegate = new CutomDelegate(); this.AddSubview(gauge); CreateOptionView(); this.OptionView = option; } private void CreateOptionView() { UILabel text1 = new UILabel(); text1.Text = "Pointer Color"; text1.TextAlignment = UITextAlignment.Left; text1.TextColor = UIColor.Black; text1.Frame = new CGRect(10, 10, 320, 40); text1.Font = UIFont.FromName("Helvetica", 14f); List<string> position = new List<string> { "Red", "Blue", "Orange" }; var picker = new DirectionPickerModel(position); opposed.Model = picker; opposed.SelectedRowInComponent(0); opposed.Frame = new CGRect(10, 25, 200, 70); picker.ValueChanged += (sender, e) => { if (picker.SelectedValue == "Red") pointer2.Color = UIColor.Red; else if (picker.SelectedValue == "Blue") pointer2.Color = UIColor.Blue; else if (picker.SelectedValue == "Orange") pointer2.Color = UIColor.Orange; }; this.option.AddSubview(text1); this.option.AddSubview(opposed); } protected override void Dispose(bool disposing) { // gauge.Delegate = null; //gauge.Scales[0].Pointers.Clear(); //gauge.Scales.Clear(); //gauge.Dispose(); base.Dispose(disposing); } } public class DirectionPickerModel : UIPickerViewModel { List<string> position; public EventHandler ValueChanged; public string SelectedValue; public DirectionPickerModel(List<string> position) { this.position = position; } public override nint GetRowsInComponent(UIPickerView pickerView, nint component) { return position.Count; } public override nint GetComponentCount(UIPickerView pickerView) { return 1; } public override string GetTitle(UIPickerView pickerView, nint row, nint component) { return position[(int)row]; ; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = new UILabel(new Rectangle(0, 0, 130, 40)); label.TextColor = UIColor.Black; label.Font = UIFont.FromName("Helvetica", 14f); label.TextAlignment = UITextAlignment.Center; label.Text = position[(int)row]; return label; } public override void Selected(UIPickerView pickerView, nint row, nint component) { var position1 = position[(int)row]; SelectedValue = position1; ValueChanged?.Invoke(null, null); } } public class CutomDelegate : SFCircularPointerDelegate { public override object OnLabelCreated(object labelContent, int scaleIndex) { switch ((NSString)labelContent) { case "0": labelContent = "S"; break; case "2": labelContent = "SW"; break; case "4": labelContent = "W"; break; case "6": labelContent = "NW"; break; case "8": labelContent = "N"; break; case "10": labelContent = "NE"; break; case "12": labelContent = "E"; break; case "14": labelContent = "SE"; break; } return base.OnLabelCreated(labelContent, scaleIndex); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Line.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Reflection.Emit; using Android.App; using Android.Graphics; using Android.OS; using Com.Syncfusion.Charts; using Android.Views; using Android.Content; using Android.Widget; using System.Collections.Generic; using System; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { public class Line : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Inflation - Consumer Price"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.ColorModel.ColorPalette = ChartColorPalette.Natural; chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.ToggleSeriesVisibility = true; CategoryAxis categoryaxis = new CategoryAxis(); categoryaxis.LabelPlacement = LabelPlacement.BetweenTicks; categoryaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; categoryaxis.ShowMajorGridLines = false; categoryaxis.AxisLineOffset = 10; categoryaxis.PlotOffset = 10; categoryaxis.MajorTickStyle.TickSize = 10; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Minimum = 0; numericalaxis.Maximum = 100; numericalaxis.Interval = 20; numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.TickSize = 0; numericalaxis.LabelStyle.LabelFormat = "#'%'"; chart.SecondaryAxis = numericalaxis; LineSeries lineSeries1 = new LineSeries(); lineSeries1.ItemsSource = MainPage.GetLineData1(); lineSeries1.XBindingPath = "XValue"; lineSeries1.YBindingPath = "YValue"; lineSeries1.DataMarker.ShowMarker = true; lineSeries1.DataMarker.MarkerColor = Color.White; lineSeries1.DataMarker.MarkerWidth = 10; lineSeries1.DataMarker.MarkerHeight = 10; lineSeries1.DataMarker.MarkerStrokeColor = Color.ParseColor("#00bdae"); lineSeries1.DataMarker.MarkerStrokeWidth = 2; lineSeries1.Label = "Germany"; lineSeries1.StrokeWidth = 3; lineSeries1.TooltipEnabled = true; LineSeries lineSeries2 = new LineSeries(); lineSeries2.ItemsSource = MainPage.GetLineData2(); lineSeries2.XBindingPath = "XValue"; lineSeries2.YBindingPath = "YValue"; lineSeries2.Label = "Japan"; lineSeries2.DataMarker.ShowMarker = true; lineSeries2.DataMarker.MarkerColor = Color.White; lineSeries2.DataMarker.MarkerWidth = 10; lineSeries2.DataMarker.MarkerHeight = 10; lineSeries2.DataMarker.MarkerStrokeColor = Color.ParseColor("#404041"); lineSeries2.DataMarker.MarkerStrokeWidth = 2; lineSeries2.StrokeWidth = 3; lineSeries2.TooltipEnabled = true; lineSeries1.EnableAnimation = true; lineSeries2.EnableAnimation = true; chart.Series.Add(lineSeries1); chart.Series.Add(lineSeries2); return chart; } } }<file_sep>/Android/SampleBrowser/Samples/RadialMenu/DoodleDraw.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; namespace SampleBrowser { public class DoodleDraw : View { private Paint mPaint; public DoodleDraw(Context context) : base(context) { mPath = new Path(); mBitmapPaint = new Paint(PaintFlags.Dither); } public int width; public int height; private Bitmap mBitmap; internal Canvas mCanvas; internal Path mPath; private Paint mBitmapPaint; protected override void OnSizeChanged(int w, int h, int oldw, int oldh) { base.OnSizeChanged(w, h, oldw, oldh); mBitmap = Bitmap.CreateBitmap(w, h, Bitmap.Config.Argb8888); mCanvas = new Canvas(mBitmap); } internal Color drawColor = Color.Green; internal int strokeWidth = 12; internal Paint.Style style = Paint.Style.Stroke; protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); mPaint = new Paint(); mPaint.AntiAlias = true; mPaint.Dither = true; mPaint.Color = drawColor; mPaint.SetStyle(style); mPaint.StrokeJoin = Paint.Join.Round; mPaint.StrokeCap = Paint.Cap.Round; mPaint.StrokeWidth = strokeWidth; if (!isPaintTapped) { canvas.DrawBitmap(mBitmap, 0, 0, mBitmapPaint); canvas.DrawPath(mPath, mPaint); } else { canvas.DrawColor(drawColor); } } private float mX, mY; private static float TOUCH_TOLERANCE = 4; internal bool isPaintTapped = false; private void touch_start(float x, float y) { mPath.Reset(); mPath.MoveTo(x, y); mX = x; mY = y; } private void touch_move(float x, float y) { float dx = Math.Abs(x - mX); float dy = Math.Abs(y - mY); if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) { mPath.QuadTo(mX, mY, (x + mX) / 2, (y + mY) / 2); mX = x; mY = y; } } private void touch_up() { mPath.LineTo(mX, mY); // commit the path to our offscreen mCanvas.DrawPath(mPath, mPaint); // kill this so we don't double draw mPath.Reset(); } public override bool OnTouchEvent(MotionEvent e) { float x = e.GetX(); float y = e.GetY(); switch (e.ActionMasked) { case MotionEventActions.Down: touch_start(x, y); Invalidate(); break; case MotionEventActions.Move: touch_move(x, y); Invalidate(); break; case MotionEventActions.Up: touch_up(); Invalidate(); break; } return true; } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/EmployeeDetails.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "EmployeeDetails.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class used to store the item values /// </summary> public class EmployeeDetails { #region DataSource [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int[] employeeID = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int[] salary = new int[] { 256787, 34455, 445545, 234567, 78434555, 93455, 3456674, 34567457, 23424, 655676, 2252459, 34368, 125436, 90558, 648489, 5537383 }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] company = new string[] { "ABC", "XYZ", "XXX", "YYY", "ZZZ", "ZXY", "KKK", "BCD", "XZY", "FDG", "BCA", "UTS", "KFI", "XXX", }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] title = new string[] { "Manager ", "Recruiter", "Security", "Supervisor", "Admin", "Admin", "Assistant", "President", "Designer", "Manager", "Marketing", "Stocker", "Clerk" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] customers = new string[] { "Kyle", "Gina", "Irene", "Katie", "Michael", "Oscar", "Ralph", "Torrey", "William", "Bill", "Daniel", "Frank", "Brenda", "Danielle", "Fiona", "Howard", "Jack", "Larry", "Holly", "Jennifer", "Liz", "Pete", "Steve", "Vince", "Zeke" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int[] age = new int[] { 21, 34, 45, 21, 23, 25, 43, 32, 22, 44, 25, 47, 35, 37, 41 }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double[] bonus = new double[] { 0.2, 0.3, 0.4, 0.1, 0.12, 0.13, 0.15, 0.18, 0.14, 0.6, 0.7 }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private List<string> employeeDates; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Random random = new Random(); #endregion /// <summary> /// Initializes a new instance of the EmployeeDetails class. /// </summary> public EmployeeDetails() { } #region GetEmployeeDetails /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">generates row count</param> /// <returns>added employee details</returns> public List<EmployeeInfo> GetEmployeeDetails(int count) { this.employeeDates = this.GetDateBetween(2000, 2014, count); List<EmployeeInfo> employeeDetails = new List<EmployeeInfo>(); for (int i = 1; i <= count; i++) { var ord = new EmployeeInfo() { EmployeeID = this.employeeID[this.random.Next(15)], Name = this.customers[this.random.Next(15)], Age = this.age[this.random.Next(10)], Company = this.company[this.random.Next(10)], Title = this.title[this.random.Next(10)], Salary = this.salary[this.random.Next(13)], Bonus = this.bonus[this.random.Next(7)], IsAvailable = (i % this.random.Next(1, 10) > 5) ? true : false, DOJ = this.employeeDates[i - 1], ImageName = this.GetImageName(this.random.Next(0, 2)), }; employeeDetails.Add(ord); } return employeeDetails; } #endregion /// <summary> /// Used to get Image name whether girl or boy depends on the Index /// </summary> /// <param name="index">integer type parameter index</param> /// <returns>returns the image</returns> private string GetImageName(int index) { if (index == 0) { return "GIRL" + this.random.Next(1, 24) + ".png"; } else { return "GUY" + this.random.Next(1, 24) + ".png"; } } /// <summary> /// Used to generate DateTime and returns the value /// </summary> /// <param name="startYear">integer type of parameter startYear</param> /// <param name="endYear">integer type of parameter endYear</param> /// <param name="count">integer type of parameter count</param> /// <returns>returns the generated DateTime</returns> private List<string> GetDateBetween(int startYear, int endYear, int count) { List<string> date = new List<string>(); Random d = new Random(1); Random m = new Random(2); Random y = new Random(startYear); for (int i = 0; i < count; i++) { int year = y.Next(startYear, endYear); int month = m.Next(3, 13); int day = d.Next(1, 31); date.Add((new DateTime(year, month, day)).ToString()); } return date; } } }<file_sep>/Android/SampleBrowser/Samples/TabView/ViewModel/TabDataViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser { internal class TabDataViewModel { internal ObservableCollection<TabData> Data = new ObservableCollection<TabData>(); internal ObservableCollection<string> Categories = new ObservableCollection<string>(); private ObservableCollection<string> NamesCollection = new ObservableCollection<string>(); private ObservableCollection<double> PriceCollection = new ObservableCollection<double>(); private ObservableCollection<double> OffersCollection = new ObservableCollection<double>(); private ObservableCollection<double> RatingCollection = new ObservableCollection<double>(); private ObservableCollection<string> ImageCollection = new ObservableCollection<string>(); private ObservableCollection<string> DescriptionCollection = new ObservableCollection<string>(); private int index = 0; public TabDataViewModel() { this.SetTabViewDataValuess(); this.AddTabData(); } private void SetTabViewDataValuess() { this.SetCategories(); this.SetNames(); this.SetPrices(); this.SetOffers(); this.SetRatings(); this.SetImages(); this.SetDescription(); } private void AddTabData() { index = 0; foreach (var category in Categories) { for (int j = 0; j < 5; j++) { Data.Add(new TabData { Category = category, Name = NamesCollection[index], Price = PriceCollection[index], Rating = RatingCollection[index], Offer = OffersCollection[index], ImagePath = ImageCollection[index], Description=DescriptionCollection[index] }); index++; } } } private void SetCategories() { Categories.Add("Furniture"); Categories.Add("Clothing"); Categories.Add("Shoes"); Categories.Add("Fruits"); Categories.Add("Toys"); } private void SetNames() { NamesCollection.Add("Leather Black Sofa"); NamesCollection.Add("Wooden Standing Drawer"); NamesCollection.Add("Semi Fabric Sofa"); NamesCollection.Add("Dinning Chair"); NamesCollection.Add("Fabric White Sofa"); NamesCollection.Add("Long Sleeve Cotton Shirt"); NamesCollection.Add("Denim Jeans"); NamesCollection.Add("Short Sleeve T-Shirt"); NamesCollection.Add("Casual Shirt Semi-Fit"); NamesCollection.Add("Classic Slim Fit Suit"); NamesCollection.Add("Light weight Shoes"); NamesCollection.Add("Trendy Grey Shoes"); NamesCollection.Add("Classic Formal Shoes"); NamesCollection.Add("White Sporty Shoes"); NamesCollection.Add("Trendy Brown Shoes"); NamesCollection.Add("Orange"); NamesCollection.Add("Blueberries (Imported)"); NamesCollection.Add("Apple"); NamesCollection.Add("Strawberry"); NamesCollection.Add("Banana"); NamesCollection.Add("Warriors"); NamesCollection.Add("Robots"); NamesCollection.Add("Minion collections"); NamesCollection.Add("Train simulation"); NamesCollection.Add("Icecream Truck"); } private void SetDescription() { DescriptionCollection.Add("Warrenty coverred upto 5 years.Its specialty is its bookcase headboard which serves as an easy access to users.Bring a new member into your family.Delivered in non - assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight."); DescriptionCollection.Add("Warrenty coverred upto 5 years.Its specialty is its bookcase headboard which serves as an easy access to users.Bring a new member into your family.Delivered in non - assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight."); DescriptionCollection.Add("High quality material has been used. Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight."); DescriptionCollection.Add("High quality material has been used. Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); DescriptionCollection.Add("Engineered wood is created by binding or glueing together at least three thin boards of wood. As a result, your engineered wood furniture will be stable and climate-resistant."); DescriptionCollection.Add("Particle boards are a type of engineered wood that are manufactured by binding together small wooden chips, sawdust or wood shavings with synthetic resin. Furniture made of particle boards are lightweight and sturdy."); DescriptionCollection.Add("Do not use an overly wet cloth. Wipe your engineered wood furniture clean with a lightly dampened cloth doused either with plain water or a mild cleaning product. Wipe dry with a clean cloth. Avoid exposure to sunlight."); DescriptionCollection.Add("High quality material has been used. Warrenty coverred upto 5 years. Its specialty is its bookcase headboard which serves as an easy access to users. Bring a new member into your family.Delivered in non-assembled pieces."); DescriptionCollection.Add("This versatile wardrobe which strikes the perfect balance between style and functionality. Equipped with a mirror and multiple shelves, this wardrobe is all you will need to store your never-ending wardrobe essentials."); } private void SetPrices() { PriceCollection.Add(99.50); PriceCollection.Add(299.40); PriceCollection.Add(149.90); PriceCollection.Add(129.40); PriceCollection.Add(199.50); PriceCollection.Add(9.50); PriceCollection.Add(7.97); PriceCollection.Add(4.55); PriceCollection.Add(5.97); PriceCollection.Add(18.47); PriceCollection.Add(25.11); PriceCollection.Add(20.21); PriceCollection.Add(11.29); PriceCollection.Add(35.75); PriceCollection.Add(74.32); PriceCollection.Add(59.11); PriceCollection.Add(12.44); PriceCollection.Add(16.37); PriceCollection.Add(29.45); PriceCollection.Add(29.97); PriceCollection.Add(43.11); PriceCollection.Add(2.44); PriceCollection.Add(6.37); PriceCollection.Add(9.45); PriceCollection.Add(9.97); PriceCollection.Add(3.11); } private void SetRatings() { RatingCollection.Add(3.9); RatingCollection.Add(4.1); RatingCollection.Add(4.4); RatingCollection.Add(3.7); RatingCollection.Add(4.5); RatingCollection.Add(4.7); RatingCollection.Add(4.2); RatingCollection.Add(3.5); RatingCollection.Add(3.9); RatingCollection.Add(4.1); RatingCollection.Add(4.9); RatingCollection.Add(4.1); RatingCollection.Add(4.5); RatingCollection.Add(4.3); RatingCollection.Add(4.1); RatingCollection.Add(4.4); RatingCollection.Add(3.9); RatingCollection.Add(3.7); RatingCollection.Add(4.3); RatingCollection.Add(4.1); RatingCollection.Add(4.5); RatingCollection.Add(3.9); RatingCollection.Add(4.1); RatingCollection.Add(4.9); RatingCollection.Add(4.1); RatingCollection.Add(4.5); } private void SetOffers() { OffersCollection.Add(5); OffersCollection.Add(1); OffersCollection.Add(10); OffersCollection.Add(15); OffersCollection.Add(20); OffersCollection.Add(5); OffersCollection.Add(15); OffersCollection.Add(20); OffersCollection.Add(15); OffersCollection.Add(10); OffersCollection.Add(5); OffersCollection.Add(10); OffersCollection.Add(10); OffersCollection.Add(10); OffersCollection.Add(20); OffersCollection.Add(30); OffersCollection.Add(15); OffersCollection.Add(20); OffersCollection.Add(35); OffersCollection.Add(10); OffersCollection.Add(5); OffersCollection.Add(15); OffersCollection.Add(20); OffersCollection.Add(15); OffersCollection.Add(10); OffersCollection.Add(5); } private void SetImages() { ImageCollection.Add("sofa2"); ImageCollection.Add("hall"); ImageCollection.Add("sofa"); ImageCollection.Add("chair"); ImageCollection.Add("hall2"); ImageCollection.Add("whiteshirt"); ImageCollection.Add("shirt"); ImageCollection.Add("tshirt"); ImageCollection.Add("redcoat"); ImageCollection.Add("silvercoat"); ImageCollection.Add("canvas"); ImageCollection.Add("graycanvas"); ImageCollection.Add("boots"); ImageCollection.Add("blackshoe"); ImageCollection.Add("leather"); ImageCollection.Add("orange"); ImageCollection.Add("blueberry"); ImageCollection.Add("apple"); ImageCollection.Add("strawberry"); ImageCollection.Add("banana"); ImageCollection.Add("friends"); ImageCollection.Add("robot"); ImageCollection.Add("minion"); ImageCollection.Add("train"); ImageCollection.Add("van"); } } } <file_sep>/Forms/Picker/Picker/Samples/PickerGettingStarted/GettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Xamarin.Forms; using SampleBrowser.Core; using Syncfusion.SfPicker.XForms; namespace SampleBrowser.SfPicker { public partial class PickerGettingStarted : SampleView { public PickerGettingStarted() { InitializeComponent(); if(Device.RuntimePlatform==Device.UWP) { layoutRoot.HorizontalOptions = LayoutOptions.Center; grid_layout.WidthRequest = 400; } Color c = Color.Navy; SelectedRowTextColorPicker.Items.Add("Yellow"); SelectedRowTextColorPicker.Items.Add("Green"); SelectedRowTextColorPicker.Items.Add("Navy"); SelectedRowTextColorPicker.Items.Add("Orange"); SelectedRowTextColorPicker.Items.Add("Lime"); SelectedRowTextColorPicker.Items.Add("Purple"); SelectedRowTextColorPicker.Items.Add("Pink"); SelectedRowTextColorPicker.Items.Add("Red"); SelectedRowTextColorPicker.Items.Add("Gray"); UnSelectedRowTextColorPicker.Items.Add("Yellow"); UnSelectedRowTextColorPicker.Items.Add("Green"); UnSelectedRowTextColorPicker.Items.Add("Navy"); UnSelectedRowTextColorPicker.Items.Add("Orange"); UnSelectedRowTextColorPicker.Items.Add("Lime"); UnSelectedRowTextColorPicker.Items.Add("Purple"); UnSelectedRowTextColorPicker.Items.Add("Pink"); UnSelectedRowTextColorPicker.Items.Add("Red"); UnSelectedRowTextColorPicker.Items.Add("Gray"); BorderColorPicker.Items.Add("Yellow"); BorderColorPicker.Items.Add("Green"); BorderColorPicker.Items.Add("Navy"); BorderColorPicker.Items.Add("Orange"); BorderColorPicker.Items.Add("Lime"); BorderColorPicker.Items.Add("Purple"); BorderColorPicker.Items.Add("Pink"); BorderColorPicker.Items.Add("Red"); BorderColorPicker.Items.Add("Gray"); var viewModel = new PickerGettingStartedViewModel(); this.BindingContext = this.PropertyView.BindingContext = viewModel; if (Device.RuntimePlatform == Device.iOS) { if (Device.Idiom == TargetIdiom.Phone) { picker.WidthRequest = 250; } picker.BackgroundColor = Color.FromRgba(c.R, c.G, c.B, 0.2); } else if(Device.RuntimePlatform == Device.Android) { picker.BackgroundColor = Color.FromRgba(c.R, c.G, c.B, 0.2); picker.PickerHeight = 200; } else if (Device.RuntimePlatform == Device.UWP) { ShowHeader.FontSize = 15; ShowColumnHeader.FontSize = 15; SelectedRowTextColorlbl.FontSize = 15; UnSelectedRowTextColorlbl.FontSize = 15; BorderColorlbl.FontSize = 15; if (Device.Idiom == TargetIdiom.Phone) { picker.ItemHeight = 50; rowheight.Height = 280; logname.Height = 25; } else { grid_layout.HorizontalOptions = LayoutOptions.Start; rowheight.Height = 322; } } } void Handle_Clicked(object sender, System.EventArgs e) { eventLogLayout.Children.Clear(); } void Handle_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e) { if (e.Value == true) { picker.SelectionBackgroundColor = color; } else picker.SelectionBackgroundColor = Color.Transparent; } void Handle_TextChanged1(object sender, Xamarin.Forms.TextChangedEventArgs e) { if (e.NewTextValue != "") picker.HeaderHeight = Convert.ToDouble(e.NewTextValue); else picker.HeaderHeight=0; } void Handle_TextChanged2(object sender, Xamarin.Forms.TextChangedEventArgs e) { if (e.NewTextValue != "") picker.ColumnHeaderHeight = Convert.ToDouble(e.NewTextValue); else picker.ColumnHeaderHeight = 0; } void Handle_SelectedIndexChanged3(object sender, System.EventArgs e) { picker.SelectedItemTextColor = PickerHelper.GetColor(SelectedRowTextColorPicker.Items[SelectedRowTextColorPicker.SelectedIndex]); } void Handle_SelectedIndexChanged5(object sender, System.EventArgs e) { picker.BorderColor = PickerHelper.GetColor(BorderColorPicker.Items[BorderColorPicker.SelectedIndex]); } void Handle_SelectedIndexChanged4(object sender, System.EventArgs e) { picker.UnSelectedItemTextColor = PickerHelper.GetColor(UnSelectedRowTextColorPicker.Items[UnSelectedRowTextColorPicker.SelectedIndex]); } internal Color color; void Picker_SelectionChanged(object sender, Syncfusion.SfPicker.XForms.SelectionChangedEventArgs e) { if (e.NewValue != null) { Label lbl = new Label(); lbl.Text = e.NewValue.ToString() + " " + "has been selected"; eventLogLayout.Children.Insert(0, lbl); color =PickerHelper.GetColor(e.NewValue); if (Device.RuntimePlatform == Device.UWP) picker.SelectionBackgroundColor = color; else picker.BackgroundColor = Color.FromRgba(color.R, color.G, color.B, 0.2); } } } public class SfPickerBehavior:Behavior<Syncfusion.SfPicker.XForms.SfPicker> { protected override void OnAttachedTo(Syncfusion.SfPicker.XForms.SfPicker bindable) { base.OnAttachedTo(bindable); } protected override void OnDetachingFrom(Syncfusion.SfPicker.XForms.SfPicker bindable) { if (Device.RuntimePlatform == Device.UWP) { (bindable as Syncfusion.SfPicker.XForms.SfPicker).Dispose(); } base.OnDetachingFrom(bindable); } } } <file_sep>/Forms/ListView/ListView/Helper/CustomBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using System.Globalization; namespace SampleBrowser.SfListView { public class CustomBehavior : Behavior<Syncfusion.ListView.XForms.SfListView> { public static readonly BindableProperty CommandProperty = BindableProperty.Create("Command", typeof(ICommand), typeof(CustomBehavior), null); public static readonly BindableProperty InputConverterProperty = BindableProperty.Create("Converter", typeof(IValueConverter), typeof(CustomBehavior), null); public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } } public IValueConverter Converter { get { return (IValueConverter)GetValue(InputConverterProperty); } set { SetValue(InputConverterProperty, value); } } public Syncfusion.ListView.XForms.SfListView AssociatedObject { get; private set; } protected override void OnAttachedTo(Syncfusion.ListView.XForms.SfListView bindable) { base.OnAttachedTo(bindable); AssociatedObject = bindable; bindable.BindingContextChanged += OnBindingContextChanged; } protected override void OnDetachingFrom(Syncfusion.ListView.XForms.SfListView bindable) { base.OnDetachingFrom(bindable); bindable.BindingContextChanged -= OnBindingContextChanged; AssociatedObject = null; } void OnBindingContextChanged(object sender, EventArgs e) { OnBindingContextChanged(); } protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); BindingContext = AssociatedObject.BindingContext; } } } <file_sep>/Android/SampleBrowser/Samples/ImageEditor/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Text; using Android.Content.Res; namespace SampleBrowser { public class Model : INotifyPropertyChanged { private int name; public int Name { get { return name; } set { name = value; RaisePropertyChanged("Name"); } } private Stream _stream; public Stream Strm { get { return _stream; } set { _stream = value; RaisePropertyChanged("Strm"); } } private string _imageName; public string ImageName { get { return _imageName; } set { _imageName = value; RaisePropertyChanged("ImageName"); } } private string _imagestream; public string Imagestream { get { return _imagestream; } set { _imagestream = value; RaisePropertyChanged("Imagestream"); } } public event PropertyChangedEventHandler PropertyChanged; void RaisePropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public class ViewModel { public ObservableCollection<Model> ModelList { get; set; } public ViewModel() { ModelList = new ObservableCollection<Model> { new Model { Name= Resource.Drawable.banner1,ImageName="Coffee",Imagestream="Ban1.txt"}, new Model { Name= Resource.Drawable.banner2,ImageName="Food",Imagestream="Ban2.txt"}, new Model { Name= Resource.Drawable.banner3,ImageName="Syncfusion",Imagestream="Ban3.txt"}, }; } } } <file_sep>/Android/SampleBrowser/Samples/RangeNavigator/readme.md The range navigator control provides an intuitive interface for selecting a smaller range from a larger collection. It is commonly used in financial dashboards to filter a date range for which the data needs to be visualized. The following samples are available for range navigator. | Sample | Description | | ------ | ----------- | | [Getting Started](RangeNavigator/Samples/RangeNavigator.cs) | This sample demonstrates how to configure range navigator and send notifications of range changes to the chart that is placed on the same page. | | [Customization] (RangeNavigator/Samples/CustomRangeNavigator.cs) | This sample demonstrates how to customize each element in a range navigator. | <file_sep>/Forms/NumericTextBox/NumericTextBox/Samples/NumericTextBox/NumericTextBox_Default.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfNumericTextBox.XForms; using Syncfusion.XForms.Editors; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfNumericTextBox { public partial class NumericTextBox_Default : SampleView { int precision = 0; public NumericTextBox_Default() { InitializeComponent(); OptionView(); clearButtonPicker.SelectedIndex = precision; } void Handle_Clicked(object sender, System.EventArgs e) { interestLayout.IsVisible = true; } Double rate = 0; Double princ = 0; Double term = 0; public void trimValue() { if (principalNumericTextBox.Value != null) { if (principalNumericTextBox.Value == null || interestRateNumericTextBox.Value == null || termNumericTextBox.Value == null) { interestNumericTextBox.Value = 0; if (interestRateNumericTextBox.Value == null) rate = 0; if (principalNumericTextBox.Value == null) princ = 0; if (termNumericTextBox.Value == null) term = 0; } else { if (principalNumericTextBox.Value.ToString().Length < 8) { princ = Convert.ToDouble(principalNumericTextBox.Value.ToString()); } if (interestRateNumericTextBox.Value.ToString().Length < 8) { rate = Convert.ToDouble(interestRateNumericTextBox.Value.ToString()); } if (termNumericTextBox.Value.ToString().Length < 8) { term = Convert.ToDouble(termNumericTextBox.Value.ToString()); } else { if (interestRateNumericTextBox.Value.ToString().Length > 7) rate = Convert.ToDouble(interestRateNumericTextBox.Value.ToString().Remove(7)); if (principalNumericTextBox.Value.ToString().Length > 7) princ = Convert.ToDouble(principalNumericTextBox.Value.ToString().Remove(7)); if (termNumericTextBox.Value.ToString().Length > 7) term = Convert.ToDouble(termNumericTextBox.Value.ToString().Remove(7)); } } } else { rate = princ = term = 0.0; } } public void OptionView() { double height = Bounds.Height; double width = Core.SampleBrowser.ScreenWidth; if (Device.Idiom == TargetIdiom.Tablet) width /= 2; //Toggle button allowNullToggle.Toggled += ToggleChanged; //Toggle button allowDefaultDecimalDigitsToggle.Toggled += AllowDefaultDecimalDigitsToggle_Toggled; //Localization termNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); principalNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); localePicker.Items.Add("United States"); localePicker.Items.Add("United Kingdom"); localePicker.Items.Add("Japan"); localePicker.Items.Add("France"); localePicker.Items.Add("Italy"); localePicker.SelectedIndex = precision; localePicker.SelectedIndexChanged += localePicker_Changed; //Value Changed principalNumericTextBox.ValueChanged += (object sender, ValueEventArgs e) => { interestLayout.IsVisible = false; trimValue(); interestNumericTextBox.Value = rate * princ * term; }; interestRateNumericTextBox.ValueChanged += (object sender, ValueEventArgs e) => { interestLayout.IsVisible = false; trimValue(); interestNumericTextBox.Value = princ * term * rate; }; termNumericTextBox.ValueChanged += (object sender, ValueEventArgs e) => { interestLayout.IsVisible = false; trimValue(); interestNumericTextBox.Value = princ * term * rate; }; //Device Settings if (Device.RuntimePlatform == Device.iOS) { principalNumericTextBox.WidthRequest = width / 2; interestRateNumericTextBox.WidthRequest = width / 2; termNumericTextBox.WidthRequest = width / 2; interestNumericTextBox.WidthRequest = width / 2; allowNullLabel.WidthRequest = width / 2; allowNullLabel.VerticalOptions = LayoutOptions.End; allowDefaultDecimalDigitsLabel.WidthRequest = width / 2; allowDefaultDecimalDigitsLabel.VerticalOptions = LayoutOptions.End; allowNullToggle.VerticalOptions = LayoutOptions.Start; allowDefaultDecimalDigitsToggle.VerticalOptions = LayoutOptions.Start; optionLayout.Padding = new Thickness(0, 0, 10, 0); interestNumericTextBox.BorderColor = Color.Transparent; } else if (Device.RuntimePlatform == Device.Android) { calculateButton.BackgroundColor = Color.FromHex("#2196f3"); calculateButton.CornerRadius = 1; calculateButton.BorderWidth = 0; calculateButton.TextColor = Color.White; calculateButton.FontFamily = "Roboto"; principalNumericTextBox.Margin = new Thickness(0, 0, 0, 0); interestNumericTextBox.Margin = new Thickness(0, 0, 0, 0); interestRateNumericTextBox.Margin = new Thickness(0, 0, 0, 0); termNumericTextBox.Margin = new Thickness(0, 0, 0, 0); numericTextBox1.Padding = new Thickness(-3, -15, 0, 0); numericTextBox2.Padding = new Thickness(-3, -15, 0, 0); numericTextBox3.Padding = new Thickness(-3, -15, 0, 0); numericTextBox4.Padding = new Thickness(-3, -15, 0, 0); principalLabel.HeightRequest = 25; interestRateLabel.HeightRequest = 25; termLabel.HeightRequest = 25; pickerLayout3.Padding = new Thickness(-2, 0, 0, 0); } else if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { principalNumericTextBox.WidthRequest = width / 2; interestRateNumericTextBox.WidthRequest = width / 2; termNumericTextBox.WidthRequest = width / 2; interestNumericTextBox.WidthRequest = width / 2; principalNumericTextBox.HeightRequest = 75; interestRateNumericTextBox.HeightRequest = 75; termNumericTextBox.HeightRequest = 75; interestNumericTextBox.HeightRequest = 75; localePicker.HeightRequest = 90; allowNullToggle.WidthRequest = width / 2; allowNullToggle.HorizontalOptions = LayoutOptions.End; allowDefaultDecimalDigitsToggle.WidthRequest = width / 2; allowDefaultDecimalDigitsToggle.HorizontalOptions = LayoutOptions.End; //interestRateNumericTextBox.FormatString = "0 %"; termNumericTextBox.FormatString = "0 years"; interestNumericTextBox.BorderColor = Color.Transparent; } else { principalNumericTextBox.WidthRequest = width / 3; interestRateNumericTextBox.WidthRequest = width / 3; termNumericTextBox.WidthRequest = width / 3; interestNumericTextBox.WidthRequest = width / 3; } if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { autoDecimalLabelColumn.Width = new GridLength(1, GridUnitType.Star); autoDecimalToggleColumn.Width = new GridLength(0, GridUnitType.Auto); } else if (Device.RuntimePlatform == Device.UWP) { simpleInterestCalculatorLabel.TextColor = Color.Gray; findingSimpleInterestLabel.TextColor = Color.Gray; formulaLabel.TextColor = Color.Gray; principalLabel.TextColor = Color.Gray; interestRateLabel.TextColor = Color.Gray; termLabel.TextColor = Color.Gray; interestLabel.TextColor = Color.Gray; //interestRateNumericTextBox.FormatString = "0 %"; termNumericTextBox.FormatString = "0 years"; interestNumericTextBox.IsEnabled = true; interestNumericTextBox.HeightRequest = 40; interestLabel.HeightRequest = 40; calculateButton.FontSize = 12; interestNumericTextBox.BorderColor = Color.Transparent; if (Device.Idiom == TargetIdiom.Phone) { interestRateLabel.WidthRequest = 150.0; termLabel.WidthRequest = 150.0; principalLabel.WidthRequest = 150.0; interestLabel.WidthRequest = 150.0; column1.Width = new GridLength(1, GridUnitType.Star); autoDecimalLabelColumn.Width = new GridLength(1, GridUnitType.Star); } if (Device.Idiom == TargetIdiom.Desktop) { sampleLayout.HorizontalOptions = LayoutOptions.Start; column1.Width = new GridLength(200.0, GridUnitType.Absolute); autoDecimalLabelColumn.Width = new GridLength(200.0, GridUnitType.Absolute); allowNullToggle.HorizontalOptions = LayoutOptions.Start; allowDefaultDecimalDigitsToggle.HorizontalOptions = LayoutOptions.Start; localePicker.HorizontalOptions = LayoutOptions.Start; localePicker.WidthRequest = 300.0; } } } private void AllowDefaultDecimalDigitsToggle_Toggled(object sender, ToggledEventArgs e) { principalNumericTextBox.AllowDefaultDecimalDigits = e.Value; interestRateNumericTextBox.AllowDefaultDecimalDigits = e.Value; } void ToggleChanged(object sender, ToggledEventArgs e) { principalNumericTextBox.AllowNull = e.Value; interestRateNumericTextBox.AllowNull = e.Value; termNumericTextBox.AllowNull = e.Value; interestNumericTextBox.AllowNull = e.Value; } public void localePicker_Changed(object c, EventArgs e) { switch (localePicker.SelectedIndex) { case 0: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("en-US"); precision = 0; } break; case 1: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("en-GB"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("en-GB"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("en-GB"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("en-GB"); precision = 1; } break; case 2: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("ja-JP"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("ja-JP"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("ja-JP"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("ja-JP"); precision = 2; } break; case 3: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("fr-FR"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("fr-FR"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("fr-FR"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("fr-FR"); precision = 3; } break; case 4: { principalNumericTextBox.Culture = new System.Globalization.CultureInfo("it-IT"); interestRateNumericTextBox.Culture = new System.Globalization.CultureInfo("it-IT"); termNumericTextBox.Culture = new System.Globalization.CultureInfo("it-IT"); interestNumericTextBox.Culture = new System.Globalization.CultureInfo("it-IT"); precision = 4; } break; } } public View getContent() { return this.Content; } public View getPropertyView() { return this.PropertyView; } private void OnClearButtonPicker_SelectedIndexChanged(object sender, EventArgs e) { switch (clearButtonPicker.SelectedIndex) { case 0: { principalNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; interestRateNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; termNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; interestNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.WhileEditing; } break; case 1: { principalNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.Never; interestRateNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.Never; termNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.Never; interestNumericTextBox.ClearButtonVisibility = ClearButtonVisibilityMode.Never; } break; } } } public class NumericTextBoxRenderer : Syncfusion.SfNumericTextBox.XForms.SfNumericTextBox { public NumericTextBoxRenderer() { } } public class NumericTextBoxRenderer2 : Syncfusion.SfNumericTextBox.XForms.SfNumericTextBox { public NumericTextBoxRenderer2() { } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/RadioButton/RadioButton.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; namespace SampleBrowser { public class RadioButton : SampleView { RadioButton_Mobile phoneView; public RadioButton() { phoneView = new RadioButton_Mobile(); this.AddSubview(phoneView); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } } } } <file_sep>/iOS/SampleBrowser/Samples/TreeView/TreeSelection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.iOS.TreeView; using Syncfusion.TreeView.Engine; using CoreGraphics; using System.Collections.Generic; using UIKit; using System.Collections.ObjectModel; namespace SampleBrowser { public class TreeSelection : SampleView { SfTreeView treeView; CountriesViewModel viewModel; UIView option = new UIView(); UIPickerView selectionPicker = new UIPickerView(); public TreeSelection() { treeView = new SfTreeView(); viewModel = new CountriesViewModel(); treeView.Indentation = 20; treeView.ExpanderWidth = 40; treeView.ItemHeight = 40; treeView.SelectionMode = SelectionMode.Multiple; treeView.AutoExpandMode = AutoExpandMode.AllNodesExpanded; treeView.ChildPropertyName = "States"; treeView.ItemsSource = viewModel.CountriesInfo; treeView.Adapter = new SelectionAdapter(); treeView.SelectedItems = viewModel.SelectedCountries; this.AddSubview(treeView); this.OptionView = option; } public override void LayoutSubviews() { this.treeView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); this.CreateOptionView(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } private void CreateOptionView() { List<string> index = new List<string> { "Multiple", "SingleDeselect", "Single", "None" }; var picker = new TreeViewPickerModel(index); selectionPicker.Model = picker; selectionPicker.SelectedRowInComponent(0); selectionPicker.ShowSelectionIndicator = true; selectionPicker.Frame = new CGRect(0, 100, this.Frame.Width, this.Frame.Height/3); picker.PickerChanged += (sender, e) => { if (e.SelectedValue == "Single") treeView.SelectionMode = SelectionMode.Single; else if (e.SelectedValue == "SingleDeselect") treeView.SelectionMode = SelectionMode.SingleDeselect; else if (e.SelectedValue == "Multiple") treeView.SelectionMode = SelectionMode.Multiple; else if (e.SelectedValue == "None") treeView.SelectionMode = SelectionMode.None; }; this.OptionView.AddSubview(selectionPicker); } } } <file_sep>/Android/SampleBrowser/Samples/Calendar/CalendarBlackOutDates.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Calendar; using Android.Graphics; using Com.Syncfusion.Calendar.Enums; using util = Java.Util; using Java.Util; namespace SampleBrowser { public class CalendarBlackOutDates : SamplePage, IDisposable { /********************************* **Local Variable Inizialisation** *********************************/ private FrameLayout mainView; private SfCalendar calendar; public override View GetSampleContent(Context context) { /************ **Calendar** ************/ calendar = new SfCalendar(context); calendar.ShowEventsInline = false; calendar.ViewMode = ViewMode.MonthView; calendar.BlackoutDates = GetBlackOutDates(); calendar.HeaderHeight = 100; //MonthViewSettings MonthViewLabelSetting labelSettings = new MonthViewLabelSetting(); labelSettings.DateLabelSize = 14; MonthViewSettings monthViewSettings = new MonthViewSettings(); monthViewSettings.MonthViewLabelSetting = labelSettings; monthViewSettings.SelectedDayTextColor = Color.Black; monthViewSettings.TodayTextColor = Color.ParseColor("#1B79D6"); monthViewSettings.InlineBackgroundColor = Color.ParseColor("#E4E8ED"); monthViewSettings.WeekDayBackgroundColor = Color.ParseColor("#F7F7F7"); calendar.MonthViewSettings = monthViewSettings; //Main View mainView = new FrameLayout(context); mainView.AddView(calendar); return mainView; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private List<util.Date> GetBlackOutDates() { List<util.Date> blackOutDates = new List<util.Date>(); var date = Calendar.Instance; date.Set(CalendarField.Date, 10); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 12); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 14); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 16); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 18); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 20); blackOutDates.Add(date.Time); date.Add(CalendarField.Month, 2); date.Set(CalendarField.Date, 12); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 14); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 16); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 18); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 20); blackOutDates.Add(date.Time); date.Add(CalendarField.Month, -1); date.Set(CalendarField.Date, 6); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 8); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 10); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 12); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 14); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 16); blackOutDates.Add(date.Time); date.Set(CalendarField.Date, 18); blackOutDates.Add(date.Time); return blackOutDates; } public void Dispose() { if(calendar != null) { calendar.Dispose(); calendar = null; } if (mainView != null) { mainView.Dispose(); mainView = null; } } } }<file_sep>/Forms/Cards/Cards/Samples/CardView/CardView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.Cards; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.Cards { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CardView : SampleView { private bool isToggled; private bool isRefreshed; CardViewTemplate firstCardView; CardViewTemplate secondCardView; CardViewTemplate thirdCardView; CardViewModel viewModel = new CardViewModel(); public CardView() { InitializeComponent(); grid.BindingContext = viewModel; propertyView.BindingContext = viewModel; var childCount = grid.Children.Count; for (int i = 0; i < childCount; i++) { grid.Children[i].BindingContext = viewModel.Data[i]; } if (Device.RuntimePlatform == Device.UWP) { mainGrid.HorizontalOptions = LayoutOptions.Center; mainGrid.WidthRequest = 500; } } private void CornerRadiusChanged(object sender, ValueChangedEventArgs e) { CornerRadiusValue.Text = "Corner radius : " + Math.Round(e.NewValue).ToString(); } private void RefreshButtonClicked(object sender, EventArgs e) { for (int i = 0; i < grid.Children.Count; i++) { grid.RowDefinitions[i].Height = GridLength.Auto; } var viewModel = grid.BindingContext as CardViewModel; if (viewModel.IsCardAlreadySwiped) { isRefreshed = true; firstCardView = new CardViewTemplate() { VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand }; firstCardView.IndicatorThickness = isToggled ? 5 : 0; firstCardView.IndicatorColor = Color.FromHex("#b1793b"); firstCardView.SetBinding(CardViewTemplate.FadeOutOnSwipingProperty, new Binding("IsToggled", source: fadeOutOnSwipingSwitch)); firstCardView.SetBinding(CardViewTemplate.SwipeToDismissProperty, new Binding("IsToggled", source: swipeToDismissSwitch)); firstCardView.SetBinding(CardViewTemplate.CornerRadiusProperty, new Binding("Value", source:slider)); firstCardView.BindingContext = viewModel.Data[0]; secondCardView = new CardViewTemplate() { VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand }; secondCardView.IndicatorThickness = isToggled ? 5 : 0; secondCardView.IndicatorColor = Color.FromHex("#606472"); secondCardView.SetBinding(CardViewTemplate.FadeOutOnSwipingProperty, new Binding("IsToggled", source: fadeOutOnSwipingSwitch)); secondCardView.SetBinding(CardViewTemplate.SwipeToDismissProperty, new Binding("IsToggled", source: swipeToDismissSwitch)); secondCardView.SetBinding(CardViewTemplate.CornerRadiusProperty, new Binding("Value", source: slider)); secondCardView.BindingContext = viewModel.Data[1]; thirdCardView = new CardViewTemplate() { VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand }; thirdCardView.IndicatorThickness = isToggled ? 5 : 0; thirdCardView.IndicatorColor = Color.FromHex("#23221d"); thirdCardView.SetBinding(CardViewTemplate.FadeOutOnSwipingProperty, new Binding("IsToggled", source: fadeOutOnSwipingSwitch)); thirdCardView.SetBinding(CardViewTemplate.SwipeToDismissProperty, new Binding("IsToggled", source: swipeToDismissSwitch)); thirdCardView.SetBinding(CardViewTemplate.CornerRadiusProperty, new Binding("Value", source: slider)); thirdCardView.BindingContext = viewModel.Data[2]; grid.Children.Clear(); grid.Children.Add(firstCardView, 0, 0); grid.Children.Add(secondCardView, 0, 1); grid.Children.Add(thirdCardView, 0, 2); viewModel.IsCardAlreadySwiped = false; } } private void Switch_Toggled(object sender, ToggledEventArgs e) { isToggled = (sender as Switch).IsToggled; var indicatorThickness = isToggled ? 5 : 0; if (isRefreshed) { firstCardView.IndicatorThickness = indicatorThickness; secondCardView.IndicatorThickness = indicatorThickness; thirdCardView.IndicatorThickness = indicatorThickness; } else { cardViewOne.IndicatorThickness = indicatorThickness; cardViewTwo.IndicatorThickness = indicatorThickness; cardViewThree.IndicatorThickness = indicatorThickness; } } private void FadeOutOnSwipingSwitch_Toggled(object sender, ToggledEventArgs e) { if (e.Value && !swipeToDismissSwitch.IsToggled) { swipeToDismissSwitch.IsToggled = e.Value; } } private void SwipeToDismissSwitch_Toggled(object sender, ToggledEventArgs e) { if (!e.Value) { fadeOutOnSwipingSwitch.IsToggled = e.Value; } } } }<file_sep>/Forms/BusyIndicator/BusyIndicator/Samples/BusyIndicator/BusyIndicator.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfBusyIndicator.XForms; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfBusyIndicator { public partial class BusyIndicator : SampleView { public BusyIndicator() { InitializeComponent(); if (Device.RuntimePlatform == Device.iOS) { sfbusyindicator.ViewBoxWidth = 75; sfbusyindicator.ViewBoxHeight = 75; } else { sfbusyindicator.ViewBoxWidth = 150; sfbusyindicator.ViewBoxHeight = 150; } sfbusyindicator.BackgroundColor = Color.White; sfbusyindicator.VerticalOptions = LayoutOptions.FillAndExpand; sfbusyindicator.Duration = 1; Optionview(); this.BackgroundColor = Color.FromRgb(236, 235, 242); } void animationPicker_SelectedIndexChanged(object sender, EventArgs e) { if (Device.RuntimePlatform == Device.Android) { switch (animationPicker.SelectedIndex) { case 0: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Cupertino; sfbusyindicator.TextColor = Color.FromHex("#757a7f"); break; case 1: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Material; sfbusyindicator.TextColor = Color.FromHex("#FF4081"); break; case 2: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Ball; sfbusyindicator.TextColor = Color.FromHex("#243FD9"); break; case 3: sfbusyindicator.Duration = 2; sfbusyindicator.AnimationType = AnimationTypes.Battery; sfbusyindicator.TextColor = Color.FromHex("#A70015"); break; case 4: sfbusyindicator.Duration = 1.4f; sfbusyindicator.AnimationType = AnimationTypes.DoubleCircle; sfbusyindicator.TextColor = Color.FromHex("#958C7B"); break; case 5: sfbusyindicator.Duration = 0.8f; sfbusyindicator.AnimationType = AnimationTypes.ECG; sfbusyindicator.TextColor = Color.FromHex("#DA901A"); break; case 6: sfbusyindicator.Duration = 0.6f; sfbusyindicator.AnimationType = AnimationTypes.Globe; sfbusyindicator.TextColor = Color.FromHex("#9EA8EE"); break; case 7: sfbusyindicator.Duration = 1f; sfbusyindicator.AnimationType = AnimationTypes.HorizontalPulsingBox; sfbusyindicator.TextColor = Color.FromHex("#E42E06"); break; case 8: sfbusyindicator.Duration = 0.5f; sfbusyindicator.AnimationType = AnimationTypes.Print; sfbusyindicator.TextColor = Color.FromHex("#5E6FF8"); break; case 9: sfbusyindicator.Duration = 0.3f; sfbusyindicator.AnimationType = AnimationTypes.Rectangle; sfbusyindicator.TextColor = Color.FromHex("#27AA9E"); break; case 10: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.SingleCircle; sfbusyindicator.TextColor = Color.FromHex("#AF2541"); break; case 11: sfbusyindicator.Duration = 5; sfbusyindicator.AnimationType = AnimationTypes.SlicedCircle; sfbusyindicator.TextColor = Color.FromHex("#779772"); break; case 12: sfbusyindicator.Duration = 1.5f; sfbusyindicator.AnimationType = AnimationTypes.Gear; sfbusyindicator.TextColor = Color.Gray; break; case 13: sfbusyindicator.Duration = 0.1f; sfbusyindicator.AnimationType = AnimationTypes.Box; sfbusyindicator.TextColor = Color.FromHex("#243FD9"); break; } } else if (Device.RuntimePlatform == Device.iOS) { sfbusyindicator.ViewBoxWidth = 150; sfbusyindicator.ViewBoxHeight = 150; switch (animationPicker.SelectedIndex) { case 0: sfbusyindicator.Duration = 1; if (Device.RuntimePlatform == Device.iOS) { sfbusyindicator.ViewBoxWidth = 75; sfbusyindicator.ViewBoxHeight = 75; } sfbusyindicator.AnimationType = AnimationTypes.Cupertino; sfbusyindicator.TextColor = Color.FromHex("#757a7f"); break; case 1: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Material; sfbusyindicator.TextColor = Color.FromHex("#FF4081"); break; case 2: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Ball; sfbusyindicator.TextColor = Color.FromHex("#243FD9"); break; case 3: sfbusyindicator.Duration = 2; sfbusyindicator.AnimationType = AnimationTypes.Battery; sfbusyindicator.TextColor = Color.FromHex("#A70015"); break; case 4: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.DoubleCircle; sfbusyindicator.TextColor = Color.FromHex("#958C7B"); break; case 5: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.ECG; sfbusyindicator.TextColor = Color.FromHex("#DA901A"); break; case 6: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Globe; sfbusyindicator.TextColor = Color.FromHex("#9EA8EE"); break; case 7: sfbusyindicator.Duration = 0.5f; sfbusyindicator.AnimationType = AnimationTypes.HorizontalPulsingBox; sfbusyindicator.TextColor = Color.FromHex("#E42E06"); break; case 8: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Print; sfbusyindicator.TextColor = Color.FromHex("#5E6FF8"); break; case 9: sfbusyindicator.Duration = 0.2f; sfbusyindicator.AnimationType = AnimationTypes.Rectangle; sfbusyindicator.TextColor = Color.FromHex("#27AA9E"); break; case 10: sfbusyindicator.Duration = 2; sfbusyindicator.AnimationType = AnimationTypes.SingleCircle; sfbusyindicator.TextColor = Color.FromHex("#AF2541"); break; case 11: sfbusyindicator.Duration = 2; sfbusyindicator.AnimationType = AnimationTypes.SlicedCircle; sfbusyindicator.TextColor = Color.FromHex("#779772"); break; case 12: sfbusyindicator.Duration = 1.5f; sfbusyindicator.AnimationType = AnimationTypes.Gear; sfbusyindicator.TextColor = Color.Gray; break; } } else { sfbusyindicator.ViewBoxWidth = 150; sfbusyindicator.ViewBoxHeight = 150; switch (animationPicker.SelectedIndex) { case 0: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Cupertino; sfbusyindicator.TextColor = Color.FromHex("#757a7f"); break; case 1: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Ball; sfbusyindicator.TextColor = Color.FromHex("#FF4081"); break; case 2: sfbusyindicator.Duration = 2; sfbusyindicator.AnimationType = AnimationTypes.Battery; sfbusyindicator.TextColor = Color.FromHex("#A70015"); break; case 3: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.DoubleCircle; sfbusyindicator.TextColor = Color.FromHex("#958C7B"); break; case 4: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.ECG; sfbusyindicator.TextColor = Color.FromHex("#DA901A"); break; case 5: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Globe; sfbusyindicator.TextColor = Color.FromHex("#9EA8EE"); break; case 6: sfbusyindicator.Duration = 0.5f; sfbusyindicator.AnimationType = AnimationTypes.HorizontalPulsingBox; sfbusyindicator.TextColor = Color.FromHex("#E42E06"); break; case 7: sfbusyindicator.Duration = 1; sfbusyindicator.AnimationType = AnimationTypes.Print; sfbusyindicator.TextColor = Color.FromHex("#5E6FF8"); break; case 8: sfbusyindicator.Duration = 0.2f; sfbusyindicator.AnimationType = AnimationTypes.Rectangle; sfbusyindicator.TextColor = Color.FromHex("#27AA9E"); break; case 9: sfbusyindicator.Duration = 2; sfbusyindicator.AnimationType = AnimationTypes.SingleCircle; sfbusyindicator.TextColor = Color.FromHex("#AF2541"); break; case 10: sfbusyindicator.Duration = 2; sfbusyindicator.AnimationType = AnimationTypes.SlicedCircle; sfbusyindicator.TextColor = Color.FromHex("#779772"); break; case 11: sfbusyindicator.Duration = 1.5f; sfbusyindicator.AnimationType = AnimationTypes.Gear; sfbusyindicator.TextColor = Color.Gray; break; } } } public void Optionview() { animationPicker.BackgroundColor = Color.White; if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) animationPicker.BackgroundColor = Color.Gray; animationPicker.Items.Add("Cupertino"); if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) { animationPicker.Items.Add("Material"); } animationPicker.Items.Add("Ball"); animationPicker.Items.Add("Battery"); animationPicker.Items.Add("DoubleCircle"); animationPicker.Items.Add("ECG"); animationPicker.Items.Add("Globe"); animationPicker.Items.Add("HorizontalPulsingBox"); animationPicker.Items.Add("Print"); animationPicker.Items.Add("Rectangle"); animationPicker.Items.Add("SingleCircle"); animationPicker.Items.Add("SlicedCircle"); animationPicker.Items.Add("Gear"); animationPicker.SelectedIndex = 0; animationPicker.SelectedIndexChanged += animationPicker_SelectedIndexChanged; if (Device.RuntimePlatform == Device.Android) { sfbusyindicator.Duration = 1; sfbusyindicator.ViewBoxWidth = 100; sfbusyindicator.ViewBoxHeight = 100; } if (Device.RuntimePlatform == Device.Android && Device.Idiom == TargetIdiom.Tablet) { animationLabel.FontSize = 24; } else if (Device.RuntimePlatform == Device.iOS) { animationPicker.HeightRequest = 40; sfbusyindicator.Duration = 1; animationPicker.BackgroundColor = Color.White; animationLabel = new Label() { Text = "\nAnimation Type", HeightRequest = 20, TextColor = Color.Black }; animationLabel.FontAttributes = FontAttributes.Bold; animationLabel.FontSize = 25; } else if (Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { animationLabel = new Label() { Text = "Animation Type", HeightRequest = 35, TextColor = Color.Black }; animationPicker.HeightRequest = 100; animationLabel.FontAttributes = FontAttributes.Bold; animationLabel.FontSize = 25; sfbusyindicator.Title = " "; } else { animationLabel = new Label() { Text = "Animation Type", HeightRequest = 35, TextColor = Color.Black }; animationLabel.FontAttributes = FontAttributes.Bold; animationLabel.FontSize = 25; } if (Device.RuntimePlatform == Device.UWP && Device.Idiom != TargetIdiom.Tablet) { animationPicker.BackgroundColor = Color.Gray; } } public View getContent() { return this.Content; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/XlsIO/PreviewControllerDS.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using QuickLook; namespace SampleBrowser { public class PreviewControllerDS : QLPreviewControllerDataSource { private QLPreviewItem _item; public PreviewControllerDS(QLPreviewItem item) { _item = item; } public override nint PreviewItemCount (QLPreviewController controller) { return (nint)1; } public override IQLPreviewItem GetPreviewItem (QLPreviewController controller, nint index) { return _item; } } } <file_sep>/Forms/Chart/Chart/Samples/OHLCChart/OHLCSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; using System; namespace SampleBrowser.SfChart { public class OHLCSeriesViewModel { public ObservableCollection<ChartDataModel> FinancialData { get; set; } public OHLCSeriesViewModel() { FinancialData = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2000, 01, 17), 125, 70, 90, 115), new ChartDataModel(new DateTime(2000, 02, 17), 150, 60, 120, 70), new ChartDataModel(new DateTime(2000, 03, 17), 200, 140, 190, 160), new ChartDataModel(new DateTime(2000, 04, 17), 160, 90, 110, 140), new ChartDataModel(new DateTime(2000, 05, 17), 200, 100, 120, 180), new ChartDataModel(new DateTime(2000, 06, 17), 100, 45, 70, 50) }; } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/Model/Model.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using Foundation; namespace SampleBrowser { public class ChartDataModel : INotifyPropertyChanged { IComparable xValue; public IComparable XValue { get { return xValue; } set { xValue = value; OnPropertyChanged("XValue"); } } NSDate date; public NSDate Date { get { return date; } set { date = value; OnPropertyChanged("Date"); } } double yValue; public double YValue { get { return yValue; } set { yValue = value; OnPropertyChanged("YValue"); } } List<double> employeeAges; public List<double> EmployeeAges { get { return employeeAges; } set { employeeAges = value; OnPropertyChanged("EmployeeAges"); } } string label; public string Label { get { return label; } set { label = value; OnPropertyChanged("Label"); } } double open; public double Open { get { return open; } set { open = value; OnPropertyChanged("Open"); } } double close; public double Close { get { return close; } set { close = value; OnPropertyChanged("Close"); } } double size; public double Size { get { return size; } set { size = value; OnPropertyChanged("Size"); } } double high; public double High { get { return high; } set { high = value; OnPropertyChanged("High"); } } double low; public double Low { get { return low; } set { low = value; OnPropertyChanged("Low"); } } double volume; public double Volume { get { return volume; } set { volume = value; OnPropertyChanged("Volume"); } } string department; public string Department { get { return department; } set { department = value; OnPropertyChanged("Department"); } } public string Image { get; set; } public ChartDataModel(string xValue, double yValue, string image) { XValue = xValue; YValue = yValue; Image = image; } public ChartDataModel() { } public ChartDataModel(IComparable xValue, double yValue) { XValue = xValue; YValue = yValue; } public ChartDataModel(NSDate xValue, double yValue) { Date = xValue; YValue = yValue; } public ChartDataModel(string department, List<double> employeeAges) { Department = department; EmployeeAges = employeeAges; } public ChartDataModel(IComparable xValue, double yValue, double horErrorValues, double verErrorValues) { XValue = xValue; YValue = yValue; High = horErrorValues; Low = verErrorValues; } public ChartDataModel(IComparable xValue, double value1, double value2) { XValue = xValue; High = value1; YValue = value1; Low = value2; Size = value2; } public ChartDataModel(IComparable xValue, double value1, double value2 , string label) { XValue = xValue; High = value1; YValue = value1; Low = value2; Size = value2; Label = label; } public ChartDataModel(IComparable xValue, double open, double high, double low, double close) { XValue = xValue; High = high; Low = low; Open = open; Close = close; } public ChartDataModel(IComparable xValue, double open, double high, double low, double close, double volume) { XValue = xValue; High = high; Low = low; Open = open; Close = close; Volume = volume; } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; } } <file_sep>/iOS/SampleBrowser/Samples/XlsIO/Charts.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XlsIO; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class Charts : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; public Charts () { label = new UILabel (); label1 = new UILabel (); button = new UIButton (UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates the creation of Excel document with bar chart."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); } label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width , 50); this.AddSubview (label); button.SetTitle("Generate Excel",UIControlState.Normal); button.Frame = new CGRect(0, 65, frameRect.Location.X + frameRect.Size.Width , 10); this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2013; #region Initializing Workbook string resourcePath = "SampleBrowser.Samples.XlsIO.Template.ChartData.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly (); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IWorkbook workbook = application.Workbooks.Open(fileStream); //The first worksheet object in the worksheets collection is accessed. IWorksheet sheet = workbook.Worksheets[0]; #endregion #region Generate Chart IChartShape chart = sheet.Charts.Add(); chart.DataRange = sheet["A16:E26"]; chart.ChartTitle = sheet["A15"].Text; chart.HasLegend = false; chart.TopRow = 3; chart.LeftColumn = 1; chart.RightColumn = 6; chart.BottomRow = 15; #endregion workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("Charts.xlsx", "application/msexcel", stream); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/CustomSorting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using CoreGraphics; using Foundation; using UIKit; using Syncfusion.Data; using Syncfusion.SfDataGrid; namespace SampleBrowser { public class CustomSorting : SampleView { #region Fields CustomerViewModel viewModel; SfDataGrid sfGrid; #endregion #region Static Methods static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } #endregion #region Constructor public CustomSorting() { sfGrid = new SfDataGrid(); this.sfGrid.SelectionMode = SelectionMode.Single; viewModel = new CustomerViewModel(); sfGrid.AutoGeneratingColumn += GridAutoGenerateColumns; sfGrid.ItemsSource = viewModel.CustomerInformation; sfGrid.AllowSorting = true; sfGrid.AllowTriStateSorting = true; this.sfGrid.HeaderRowHeight = 45; this.sfGrid.RowHeight = 45; sfGrid.GridStyle.AlternatingRowColor = UIColor.FromRGB(219, 219, 219); sfGrid.SortComparers.Add(new SortComparer() { Comparer = new CustomerInfo(), PropertyName = "FirstName" }); sfGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "FirstName" }); this.AddSubview(sfGrid); } #endregion #region Override Methods public override void LayoutSubviews() { this.sfGrid.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { if (disposing) { if (sfGrid != null) { sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumns; sfGrid.Dispose(); sfGrid = null; } viewModel = null; } base.Dispose(disposing); } #endregion #region CallBacks private void GridAutoGenerateColumns(object sender, AutoGeneratingColumnEventArgs e) { if (e.Column.MappingName == "CustomerID") { e.Column.HeaderText = "Customer ID"; e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "City") { e.Column.HeaderText = "City"; e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "Country") { e.Column.HeaderText = "Country"; e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "FirstName") { e.Column.HeaderText = "First Name"; e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "LastName") { e.Column.HeaderText = "Last Name"; e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = UITextAlignment.Left; e.Column.TextMargin = 15; } } #endregion } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/StackingLine.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; namespace SampleBrowser { public class StackingLine : SamplePage { SfChart chart; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Monthly Expenses of a Family"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.ColorModel.ColorPalette = ChartColorPalette.Natural; chart.Legend.Visibility = Visibility.Visible; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.ToggleSeriesVisibility = true; CategoryAxis categoryaxis = new CategoryAxis(); categoryaxis.LabelPlacement = LabelPlacement.BetweenTicks; categoryaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; categoryaxis.ShowMajorGridLines = false; categoryaxis.AxisLineOffset = 10; categoryaxis.PlotOffset = 10; categoryaxis.MajorTickStyle.TickSize = 10; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Minimum = 0; numericalaxis.Maximum = 200; numericalaxis.Interval = 20; numericalaxis.LineStyle.StrokeWidth = 0; numericalaxis.MajorTickStyle.TickSize = 0; numericalaxis.LabelStyle.LabelFormat = "'$'#"; chart.SecondaryAxis = numericalaxis; StackingLineSeries stackingline1 = new StackingLineSeries(); stackingline1.ItemsSource = MainPage.GetStackingLineData1(); stackingline1.XBindingPath = "XValue"; stackingline1.YBindingPath = "YValue"; stackingline1.DataMarker.ShowMarker = true; stackingline1.DataMarker.MarkerColor = Color.White; stackingline1.DataMarker.MarkerWidth = 10; stackingline1.DataMarker.MarkerHeight = 10; stackingline1.DataMarker.MarkerStrokeColor = Color.ParseColor("#00bdae"); stackingline1.DataMarker.MarkerStrokeWidth = 2; stackingline1.Label = "Daughter"; stackingline1.StrokeWidth = 3; stackingline1.TooltipEnabled = true; StackingLineSeries stackingline2 = new StackingLineSeries(); stackingline2.ItemsSource = MainPage.GetStackingLineData2(); stackingline2.XBindingPath = "XValue"; stackingline2.YBindingPath = "YValue"; stackingline2.Label = "Son"; stackingline2.DataMarker.ShowMarker = true; stackingline2.DataMarker.MarkerColor = Color.White; stackingline2.DataMarker.MarkerWidth = 10; stackingline2.DataMarker.MarkerHeight = 10; stackingline2.DataMarker.MarkerStrokeColor = Color.ParseColor("#404041"); stackingline2.DataMarker.MarkerStrokeWidth = 2; stackingline2.StrokeWidth = 3; stackingline2.TooltipEnabled = true; StackingLineSeries stackingline3 = new StackingLineSeries(); stackingline3.ItemsSource = MainPage.GetStackingLineData3(); stackingline3.XBindingPath = "XValue"; stackingline3.YBindingPath = "YValue"; stackingline3.DataMarker.ShowMarker = true; stackingline3.DataMarker.MarkerColor = Color.White; stackingline3.DataMarker.MarkerWidth = 10; stackingline3.DataMarker.MarkerHeight = 10; stackingline3.DataMarker.MarkerStrokeColor = Color.ParseColor("#357cd2"); stackingline3.DataMarker.MarkerStrokeWidth = 2; stackingline3.Label = "Mother"; stackingline3.StrokeWidth = 3; stackingline3.TooltipEnabled = true; StackingLineSeries stackingline4 = new StackingLineSeries(); stackingline4.ItemsSource = MainPage.GetStackingLineData4(); stackingline4.XBindingPath = "XValue"; stackingline4.YBindingPath = "YValue"; stackingline4.Label = "Father"; stackingline4.DataMarker.ShowMarker = true; stackingline4.DataMarker.MarkerColor = Color.White; stackingline4.DataMarker.MarkerWidth = 10; stackingline4.DataMarker.MarkerHeight = 10; stackingline4.DataMarker.MarkerStrokeColor = Color.ParseColor("#e56590"); stackingline4.DataMarker.MarkerStrokeWidth = 2; stackingline4.StrokeWidth = 3; stackingline4.TooltipEnabled = true; stackingline1.EnableAnimation = true; stackingline2.EnableAnimation = true; stackingline3.EnableAnimation = true; stackingline4.EnableAnimation = true; chart.Series.Add(stackingline1); chart.Series.Add(stackingline2); chart.Series.Add(stackingline3); chart.Series.Add(stackingline4); return chart; } } }<file_sep>/Forms/Schedule/Schedule/Samples/Themes/ThemesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Themes view model. /// </summary> [Preserve(AllMembers = true)] public class ThemesViewModel: INotifyPropertyChanged { /// <summary> /// collecions for meetings. /// </summary> private ObservableCollection<Meeting> meetings; /// <summary> /// blackout dates. /// </summary> private ObservableCollection<DateTime> blackoutDates; /// <summary> /// color collection. /// </summary> private List<Color> colorCollection; /// <summary> /// current day meeting. /// </summary> private List<string> currentDayMeetings; public ThemesViewModel() { this.Meetings = new ObservableCollection<Meeting>(); this.AddAppointmentDetails(); this.AddAppointments(); this.AddBlackouDates(); } /// <summary> /// Gets or sets meetings. /// </summary> public ObservableCollection<Meeting> Meetings { get { return this.meetings; } set { this.meetings = value; this.RaiseOnPropertyChanged("Meetings"); } } /// <summary> /// Gets or sets blackout dates. /// </summary> public ObservableCollection<DateTime> BlackoutDates { get { return this.blackoutDates; } set { this.blackoutDates = value; this.RaiseOnPropertyChanged("BlackoutDates"); } } /// <summary> /// method for add blackout dates /// </summary> private void AddBlackouDates() { this.BlackoutDates = new ObservableCollection<DateTime>(); var random = new Random(); for (int i = 0; i < 8; i++) { var date = DateTime.Now.Date.AddDays(random.Next(1, 28)).AddDays(i); this.BlackoutDates.Add(date); } } /// <summary> /// adding appointment details. /// </summary> private void AddAppointmentDetails() { this.currentDayMeetings = new List<string>(); this.currentDayMeetings.Add("General Meeting"); this.currentDayMeetings.Add("Plan Execution"); this.currentDayMeetings.Add("Project Plan"); this.currentDayMeetings.Add("Consulting"); this.currentDayMeetings.Add("Support"); this.currentDayMeetings.Add("Development Meeting"); this.currentDayMeetings.Add("Scrum"); this.currentDayMeetings.Add("Project Completion"); this.currentDayMeetings.Add("Release updates"); this.currentDayMeetings.Add("Performance Check"); this.colorCollection = new List<Color>(); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FFF09609")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); } /// <summary> /// Adds the appointments. /// </summary> private void AddAppointments() { var today = DateTime.Now.Date; var random = new Random(); for (int month = -1; month < 2; month++) { for (int day = -5; day < 5; day++) { for (int count = 0; count < 2; count++) { var meeting = new Meeting(); meeting.From = today.AddMonths(month).AddDays(random.Next(1, 28)).AddHours(random.Next(9, 18)); meeting.To = meeting.From.AddHours(2); meeting.EventName = this.currentDayMeetings[random.Next(7)]; meeting.Color = this.colorCollection[random.Next(14)]; this.Meetings.Add(meeting); } } } } /// <summary> /// Occurs when property changed. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Invoke method when property changed. /// </summary> /// <param name="propertyName">property name</param> private void RaiseOnPropertyChanged(string propertyName) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/Forms/Chart/Chart/Samples/StackedColumnChart/StackedColumnSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class StackedColumnSeriesViewModel { public ObservableCollection<ChartDataModel> StackedColumnData1 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData2 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData3 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData4 { get; set; } public StackedColumnSeriesViewModel() { StackedColumnData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2014", 111.1), new ChartDataModel("2015", 127.3), new ChartDataModel("2016", 143.4), new ChartDataModel("2017", 159.9) }; StackedColumnData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2014", 76.9), new ChartDataModel("2015", 99.5), new ChartDataModel("2016", 121.7), new ChartDataModel("2017", 142.5) }; StackedColumnData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2014", 66.1), new ChartDataModel("2015", 79.3), new ChartDataModel("2016", 91.3), new ChartDataModel("2017", 102.4) }; StackedColumnData4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2014", 34.1), new ChartDataModel("2015", 38.2), new ChartDataModel("2016", 44.0), new ChartDataModel("2017", 51.6) }; } } }<file_sep>/Android/SampleBrowser/Samples/Chart/Series/TooltipCustomization.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Android.Graphics; namespace SampleBrowser { public class TooltipCustomization : SamplePage { CustomTooltipBehavior tooltipBehavior; public override View GetSampleContent(Context con) { SfChart sfChart = new SfChart(con); sfChart.Title.Text = "Wheat Production in Tons"; sfChart.Title.TextSize = 15; sfChart.PrimaryAxis = new CategoryAxis() { PlotOffset = 10, MajorGridLineStyle = { StrokeWidth = 0.5f }, Interval = 2, ShowMajorGridLines = false, }; sfChart.SecondaryAxis = new NumericalAxis() { Maximum = 2.7f, Minimum = 1.5, Interval = 0.2, EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift, LineStyle = { StrokeWidth = 0 }, MajorGridLineStyle = { StrokeWidth = 0.5f }, }; sfChart.SecondaryAxis.LabelStyle.LabelFormat = "##.##M"; SplineSeries splineSeries = new SplineSeries() { Color = Color.Argb(255, 255, 150, 00), DataMarker = { ShowMarker = true, ShowLabel = false, MarkerColor = Color.Rgb(250, 0, 0) }, TooltipEnabled = true, }; splineSeries.EnableAnimation = true; splineSeries.ItemsSource = MainPage.GetTooltipData(); splineSeries.XBindingPath = "XValue"; splineSeries.YBindingPath = "YValue"; sfChart.Series.Add(splineSeries); tooltipBehavior = new CustomTooltipBehavior(con); tooltipBehavior.BackgroundColor = Color.Argb(255, 193, 39, 45); sfChart.Behaviors.Add(tooltipBehavior); sfChart.TooltipCreated += sfChart_TooltipCreated; return sfChart; } void sfChart_TooltipCreated(object sender, SfChart.TooltipCreatedEventArgs e) { tooltipBehavior.MarginLeft = 5; tooltipBehavior.MarginTop = 25; tooltipBehavior.MarginRight = 85; tooltipBehavior.MarginBottom = 20; tooltipBehavior.BackgroundColor = Color.Argb(255, 193, 39, 45); tooltipBehavior.TextColor = Color.Transparent; tooltipBehavior.StrokeWidth = 1f; } } } <file_sep>/Forms/RichTextEditor/RichTextEditor/Samples/Themes/Themes.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.XForms.RichTextEditor; using System.Globalization; using System.Resources; using System.Threading; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfRichTextEditor { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Themes : SampleView { public Themes() { InitializeComponent(); #if COMMONSB RichTextEditorResourceManager.Manager = new ResourceManager("SampleBrowser.Samples.RichTextEditor.Resources.Syncfusion.SfRichTextEditor.XForms", Application.Current.GetType().Assembly); #else RichTextEditorResourceManager.Manager = new ResourceManager("SampleBrowser.SfRichTextEditor.Resources.Syncfusion.SfRichTextEditor.XForms", Application.Current.GetType().Assembly); #endif if (Device.RuntimePlatform != Device.UWP) { Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } else { CultureInfo.CurrentUICulture = new CultureInfo("en-US"); } RTE.Text = "<p>Hi,<br><br>The rich text editor component is WYSIWYG (\"what you see is what you get\") editor that provides the best user experience to create and update the content.</p>"; } } }<file_sep>/Android/SampleBrowser/Samples/CheckBox/CheckBoxSample.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace SampleBrowser { class CheckBoxSample : SamplePage { CheckBox_Mobile mobile; public override View GetSampleContent(Context con) { mobile = new CheckBox_Mobile(); return mobile.GetSampleContent(con); } } }<file_sep>/Forms/AutoComplete/AutoComplete/Samples/MusicSearch/MusicSearch.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public partial class MusicSearch { public MusicSearch() { InitializeComponent(); this.BindingContext = new MusicViewModel(); if (Device.RuntimePlatform == Device.iOS) { MusicICon_B.VerticalTextAlignment = TextAlignment.Center; SearchedItem.VerticalTextAlignment = TextAlignment.Center; MusicIcon_F.VerticalTextAlignment = TextAlignment.Center; MusicIcon_M.VerticalTextAlignment = TextAlignment.Center; MusicIcon_R.VerticalTextAlignment = TextAlignment.Center; MusicIcon_E.VerticalTextAlignment = TextAlignment.Center; MusicIcon_V.VerticalTextAlignment = TextAlignment.Center; } if (Device.RuntimePlatform == Device.UWP) { sampleLayout.WidthRequest = 500; sampleLayout.HorizontalOptions = LayoutOptions.Center; sampleLayoutScrollView.HorizontalOptions = LayoutOptions.Center; } } protected override void OnSizeAllocated(double width, double height) { if (height < width && Device.RuntimePlatform == Device.iOS && Device.Idiom == TargetIdiom.Phone) { playerLabel.FontSize = 50; } else { playerLabel.FontSize = 80; } base.OnSizeAllocated(width, height); } } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/Helpers/CustomComparer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syncfusion.Data; using System.Globalization; using System.ComponentModel; namespace SampleBrowser { public class CustomerInfo : IComparer<Object>, ISortDirection { public int Compare(object x, object y) { int namX; int namY; //For Customers Type data if (x.GetType() == typeof(CustomerDetails)) { //Calculating the length of CustomerName if the object type is Customers namX = ((CustomerDetails)x).FirstName.Length; namY = ((CustomerDetails)y). FirstName.Length; } //For Group type Data else if (x.GetType() == typeof(Syncfusion.Data.Group)) { //Calculating the group key length namX = ((Syncfusion.Data.Group)x).Key.ToString().Length; namY = ((Syncfusion.Data.Group)y).Key.ToString().Length; } else { namX = x.ToString().Length; namY = y.ToString().Length; } // Objects are compared and return the SortDirection if (namX.CompareTo(namY) > 0) return SortDirection == ListSortDirection.Ascending ? 1 : -1; else if (namX.CompareTo(namY) == -1) return SortDirection == ListSortDirection.Ascending ? -1 : 1; else return 0; } //Get or Set the SortDirection value private ListSortDirection _SortDirection; public ListSortDirection SortDirection { get { return _SortDirection; } set { _SortDirection = value; } } } public class CustomSortComparer : IComparer<object>, ISortDirection { public ListSortDirection SortDirection { get; set; } public Comparer _comparer; public CustomSortComparer() { this._comparer = Comparer.Default; } private double ConverKeyToDouble(string Key) { if (Key.Equals("TOTAL SALE LESS THAN 100K")) return 0; else if (Key.Equals("TOTAL SALE GREATER THAN 100K LESS THAN 500K")) return 1; else if (Key.Equals("TOTAL SALE GREATER THAN 500K LESS THAN 1 MILLION")) return 2; else if (Key.Equals("TOTAL SALE GREATER THAN 1 MILLION LESS THAN 5 MILLION")) return 3; else if (Key.Equals("TOTAL SALE GREATER THAN 5 MILLION")) return 4; else if (Key.Equals("TOTAL SALE GREATER THAN 2 MILLION LESS THAN 5 MILLION")) return 5; return 0; } public int Compare(object x, object y) { double namX; double namY; if (x.GetType() == typeof(SalesByDate)) { namX = ((SalesByDate)x).Total; namY = ((SalesByDate)y).Total; } else if (x.GetType() == typeof(Syncfusion.Data.Group)) { namX = ConverKeyToDouble((string)((Syncfusion.Data.Group)x).Key); namY = ConverKeyToDouble((string)((Syncfusion.Data.Group)y).Key); } else { namX = (double)x; namY = (double)y; } // Objects are compared and return the SortDirection if (namX > namY) return SortDirection == ListSortDirection.Ascending ? 1 : -1; else return SortDirection == ListSortDirection.Ascending ? -1 : 1; } } public class GroupDataTimeConverter : IValueConverter { public GroupDataTimeConverter() { } public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) { var saleinfo = value as SalesByDate; if (saleinfo.Total > 100000 && saleinfo.Total < 500000) return "TOTAL SALE GREATER THAN 100K LESS THAN 500K"; else if (saleinfo.Total > 1000000 && saleinfo.Total < 5000000) return "TOTAL SALE GREATER THAN 1 MILLION LESS THAN 5 MILLION"; else if (saleinfo.Total > 500000 && saleinfo.Total < 1000000) return "TOTAL SALE GREATER THAN 500K LESS THAN 1 MILLION"; else if (saleinfo.Total > 5000000) return "TOTAL SALE GREATER THAN 5 MILLION"; else if (saleinfo.Total > 2000000 && saleinfo.Total < 5000000) return "TOTAL SALE GREATER THAN 2 MILLION LESS THAN 5 MILLION"; else return "TOTAL SALE LESS THAN 100K"; } public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) { throw new System.NotImplementedException(); } } }<file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/SfDataGridInPullToRefresh.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfDataGrid; using UIKit; using System.Globalization; using CoreGraphics; using Syncfusion.SfPullToRefresh; using System.Threading.Tasks; namespace SampleBrowser { public class SfDataGridInPullToRefresh : SampleView { #region Fields SfDataGrid SfGrid; SfPullToRefresh pullToRefresh; GridGettingStartedViewModel viewModel; #endregion static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public SfDataGridInPullToRefresh() { this.pullToRefresh = new SfPullToRefresh(); this.pullToRefresh.RefreshContentThreshold = 45; this.SfGrid = new SfDataGrid (); this.SfGrid.SelectionMode = SelectionMode.Single; this.SfGrid.AutoGenerateColumns = false; this.SfGrid.ColumnSizer = ColumnSizer.Star; this.GridGenerateColumns(); viewModel = new GridGettingStartedViewModel(); this.SfGrid.ItemsSource = viewModel.OrdersInfo; this.SfGrid.ShowRowHeader = false; this.SfGrid.HeaderRowHeight = 45; this.SfGrid.RowHeight = 45; this.SfGrid.GridStyle.AlternatingRowColor = UIColor.FromRGB (219, 219, 219); this.SfGrid.AllowResizingColumn = true; this.SfGrid.GridStyle = new CustomGridStyle(); this.pullToRefresh.PullableContent = SfGrid; this.pullToRefresh.Refreshing += PullToRefresh_Refreshing; this.AddSubview (this.pullToRefresh); this.OptionView = new Options(pullToRefresh); } private async void PullToRefresh_Refreshing(object sender, RefreshingEventArgs e) { await Task.Delay(3000); viewModel.ItemsSourceRefresh(); e.Refreshed = true; } void GridGenerateColumns() { this.SfGrid.Columns.Add(new GridTextColumn() { MappingName = "OrderID", HeaderText = "Order ID" }); this.SfGrid.Columns.Add(new GridTextColumn() { MappingName = "CustomerID", HeaderText = "Customer ID", TextMargin = 10, TextAlignment = UITextAlignment.Left }); this.SfGrid.Columns.Add(new GridTextColumn() { MappingName = "Freight", Format = "C", CultureInfo = new CultureInfo("en-US"), TextAlignment = UITextAlignment.Center }); this.SfGrid.Columns.Add(new GridTextColumn() { MappingName = "ShipCity", HeaderText = "Ship City", TextMargin = 10, TextAlignment = UITextAlignment.Left }); } public override void LayoutSubviews () { this.Superview.SendSubviewToBack(this); this.pullToRefresh.Frame = new CGRect (0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews (); } protected override void Dispose(bool disposing) { if(disposing) { if (SfGrid != null) SfGrid.Dispose(); if (pullToRefresh != null) { pullToRefresh.Refreshing -= PullToRefresh_Refreshing; pullToRefresh.Dispose(); } } base.Dispose(disposing); } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Axis/Date.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Android.OS; using Android.App; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Android.Graphics; using Android.Views; using System; namespace SampleBrowser { public class Date : SamplePage { int month = int.MaxValue; public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "Food Production - 2017"; chart.SetBackgroundColor(Color.White); chart.Scroll += (sender, e) => { month = int.MaxValue; }; DateTimeAxis dateTimeAxis = new DateTimeAxis(); dateTimeAxis.Title.Text = "Production Across Years"; dateTimeAxis.ZoomFactor = 0.2f; dateTimeAxis.ZoomPosition = 0.6f; dateTimeAxis.LabelCreated += (sender, e) => { var date = DateTime.Parse(e.AxisLabel.LabelContent.ToString()); if(date.Month != month) { ChartAxisLabelStyle labelStyle = new ChartAxisLabelStyle(); labelStyle.LabelFormat = "MMM-dd"; labelStyle.TextSize = 9; labelStyle.Typeface = Typeface.DefaultBold; e.AxisLabel.LabelStyle = labelStyle; month = date.Month; } else{ ChartAxisLabelStyle labelStyle = new ChartAxisLabelStyle(); labelStyle.LabelFormat = "dd"; e.AxisLabel.LabelStyle = labelStyle; } }; dateTimeAxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; chart.PrimaryAxis = dateTimeAxis; var numericalAxis = new NumericalAxis(); numericalAxis.Title.Text = "Growth (In Metric Tons)"; chart.SecondaryAxis = numericalAxis; FastLineSeries lineSeries = new FastLineSeries(); lineSeries.ColorModel.ColorPalette = ChartColorPalette.Natural; lineSeries.ItemsSource = Data.GetDateTimeValue(); lineSeries.XBindingPath = "Date"; lineSeries.YBindingPath = "YValue"; lineSeries.TooltipEnabled = true; chart.Series.Add(lineSeries); ChartZoomPanBehavior zoomPan = new ChartZoomPanBehavior(); zoomPan.SelectionZoomingEnabled = false; zoomPan.ZoomMode = ZoomMode.X; chart.Behaviors.Add(zoomPan); return chart; } } }<file_sep>/iOS/SampleBrowser/DataSource/TableSource.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; #if __UNIFIED__ using Foundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class NavigationTableSource : UITableViewSource { #region fields private string[] tableItems; private string cellIdentifier = "TableCell"; private HomeViewController controller; #endregion #region ctor public NavigationTableSource(HomeViewController controller, string[] items) { this.controller = controller; tableItems = items; } #endregion #region properties public bool Customize { get; set; } #endregion #region methods public override nint RowsInSection(UITableView tableview, nint section) { return tableItems.Length; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { controller.DrawerEvent((int)indexPath.Item); } public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath) { return 50; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier); string item = tableItems[indexPath.Row]; if (cell == null) { cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier); } cell.TextLabel.Font = UIFont.FromName("Helvetica-Light", 18f); cell.TextLabel.TextColor = UIColor.FromRGB(113.0f / 255.0f, 124.0f / 255.0f, 130.0f / 255.0f); cell.TextLabel.Text = item; if (indexPath.Row == 0) { cell.ImageView.Image = UIImage.FromBundle("Controls/productpage"); } else if (indexPath.Row == 1) { cell.ImageView.Image = UIImage.FromBundle("Controls/whatsnew"); } else if (indexPath.Row == 2) { cell.ImageView.Image = UIImage.FromBundle("Controls/documentation"); } cell.BackgroundColor = UIColor.Clear; return cell; } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/Chart/ViewModel/ChartViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; using System.Collections.ObjectModel; using System.Threading.Tasks; using Foundation; using System.Collections.Generic; namespace SampleBrowser { public class ChartViewModel { DateTime time = new DateTime(2015, 01, 01); DateTime dataTime = new DateTime(2015, 01, 1); Random random = new Random(); DateTime date = new DateTime(); public int wave1 = 0; public int wave2 = 180; public int verticalCount; public ObservableCollection<ChartDataModel> PolarData1 { get; set; } public ObservableCollection<ChartDataModel> DataMarkerData1 { get; set; } public ObservableCollection<ChartDataModel> DataMarkerData2 { get; set; } public ObservableCollection<ChartDataModel> PolarData2 { get; set; } public ObservableCollection<ChartDataModel> PolarData3 { get; set; } public ObservableCollection<ChartDataModel> AreaData { get; set; } public ObservableCollection<ChartDataModel> AreaData1 { get; set; } public ObservableCollection<ChartDataModel> AreaData2 { get; set; } public ObservableCollection<ChartDataModel> StepAreaData1 { get; set; } public ObservableCollection<ChartDataModel> StepAreaData2 { get; set; } public ObservableCollection<ChartDataModel> LineData { get; set; } public ObservableCollection<ChartDataModel> LineData1 { get; set; } public ObservableCollection<ChartDataModel> LineData2 { get; set; } public ObservableCollection<ChartDataModel> StepLineData1 { get; set; } public ObservableCollection<ChartDataModel> StepLineData2 { get; set; } public ObservableCollection<ChartDataModel> ColumnData1 { get; set; } public ObservableCollection<ChartDataModel> ColumnData2 { get; set; } public ObservableCollection<ChartDataModel> ColumnData3 { get; set; } public ObservableCollection<ChartDataModel> HistogramData { get; set; } public ObservableCollection<ChartDataModel> BarData1 { get; set; } public ObservableCollection<ChartDataModel> BarData2 { get; set; } public ObservableCollection<ChartDataModel> SplineData1 { get; set; } public ObservableCollection<ChartDataModel> SplineData2 { get; set; } public ObservableCollection<ChartDataModel> SplineData3 { get; set; } public ObservableCollection<ChartDataModel> SplineAreaData1 { get; set; } public ObservableCollection<ChartDataModel> SplineAreaData2 { get; set; } public ObservableCollection<ChartDataModel> SplineAreaData3 { get; set; } public ObservableCollection<ChartDataModel> RangeColumnData1 { get; set; } public ObservableCollection<ChartDataModel> RangeColumnData2 { get; set; } public ObservableCollection<ChartDataModel> RangeBarData { get; set; } public ObservableCollection<ChartDataModel> RangeAreaData { get; set; } public ObservableCollection<ChartDataModel> RangeAreaData1 { get; set; } public ObservableCollection<ChartDataModel> PieSeriesData { get; set; } public ObservableCollection<ChartDataModel> SemiCircularData { get; set; } public ObservableCollection<ChartDataModel> DoughnutSeriesData { get; set; } public ObservableCollection<ChartDataModel> PyramidData { get; set; } public ObservableCollection<ChartDataModel> FunnelData { get; set; } public ObservableCollection<ChartDataModel> StackedBarData1 { get; set; } public ObservableCollection<ChartDataModel> StackedBarData2 { get; set; } public ObservableCollection<ChartDataModel> StackedBarData3 { get; set; } public ObservableCollection<ChartDataModel> StackedBar100Data1 { get; set; } public ObservableCollection<ChartDataModel> StackedBar100Data2 { get; set; } public ObservableCollection<ChartDataModel> StackedBar100Data3 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData1 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData2 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData3 { get; set; } public ObservableCollection<ChartDataModel> StackedColumnData4 { get; set; } public ObservableCollection<ChartDataModel> StackedColumn100Data1 { get; set; } public ObservableCollection<ChartDataModel> StackedColumn100Data2 { get; set; } public ObservableCollection<ChartDataModel> StackedColumn100Data3 { get; set; } public ObservableCollection<ChartDataModel> StackedColumn100Data4 { get; set; } public ObservableCollection<ChartDataModel> StackedLineData1 { get; set; } public ObservableCollection<ChartDataModel> StackedLineData2 { get; set; } public ObservableCollection<ChartDataModel> StackedLineData3 { get; set; } public ObservableCollection<ChartDataModel> StackedLineData4 { get; set; } public ObservableCollection<ChartDataModel> StackedLine100Data1 { get; set; } public ObservableCollection<ChartDataModel> StackedLine100Data2 { get; set; } public ObservableCollection<ChartDataModel> StackedLine100Data3 { get; set; } public ObservableCollection<ChartDataModel> StackedLine100Data4 { get; set; } public ObservableCollection<ChartDataModel> StackedAreaData1 { get; set; } public ObservableCollection<ChartDataModel> StackedAreaData2 { get; set; } public ObservableCollection<ChartDataModel> StackedAreaData3 { get; set; } public ObservableCollection<ChartDataModel> StackedAreaData4 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data1 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data2 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data3 { get; set; } public ObservableCollection<ChartDataModel> StackedArea100Data4 { get; set; } public ObservableCollection<ChartDataModel> StepLineData { get; set; } public ObservableCollection<ChartDataModel> CircularData { get; set; } public ObservableCollection<ChartDataModel> MultipleAxisData { get; set; } public ObservableCollection<ChartDataModel> MultipleAxisData1 { get; set; } public ObservableCollection<ChartDataModel> BubbleData { get; set; } public ObservableCollection<ChartDataModel> ScatterMaleData { get; set; } public ObservableCollection<ChartDataModel> ScatterFemaleData { get; set; } public ObservableCollection<ChartDataModel> BoxAndWhiskerData { get; set; } public ObservableCollection<ChartDataModel> ErrorBarData { get; set; } public ObservableCollection<ChartDataModel> ScatterDataZoomPan { get { var items = new ObservableCollection<ChartDataModel>(); for (int i = 0; i < 300; i++) { double x = random.NextDouble() * 100; double y = random.NextDouble() * 500; double randomDouble = random.NextDouble(); if (randomDouble >= .25 && randomDouble < .5) { x *= -1; } else if (randomDouble >= .5 && randomDouble < .75) { y *= -1; } else if (randomDouble > .75) { x *= -1; y *= -1; } items.Add(new ChartDataModel(300 + (x * (random.NextDouble() + 0.12)), 100 + (y * (random.NextDouble() + 0.12)))); } return items; } } public ObservableCollection<ChartDataModel> Data1 { get; set; } public ObservableCollection<ChartDataModel> Data2 { get; set; } public ObservableCollection<ChartDataModel> datas1 { get; set; } public ObservableCollection<ChartDataModel> Data3 { get; set; } public ObservableCollection<ChartDataModel> CategoryData { get; set; } public ObservableCollection<ChartDataModel> LogarithmicData { get; set; } public ObservableCollection<ChartDataModel> RangeColumnData { get; set; } public ObservableCollection<ChartDataModel> FinancialData { get; set; } public ObservableCollection<ChartDataModel> NumericData { get; set; } public ObservableCollection<ChartDataModel> NumericData1 { get; set; } public ObservableCollection<ChartDataModel> DateTimeAxisData { get { var dateTime = new DateTime(2017, 1, 1); var datas = new ObservableCollection<ChartDataModel>(); System.Random random = new System.Random(); double value = 100; for (int i = 0; i < 365; i++) { if (random.NextDouble() > 0.5) value += random.NextDouble(); else value -= random.NextDouble(); datas.Add(new ChartDataModel(dateTime, value)); dateTime = dateTime.AddDays(1); } return datas; } } public ObservableCollection<ChartDataModel> GradientData { get { DateTime date = new DateTime(2017, 5, 1); ObservableCollection<ChartDataModel> gradientData = new ObservableCollection<ChartDataModel>(); gradientData.Add(new ChartDataModel(date, 29)); gradientData.Add(new ChartDataModel(date.AddDays(6), 33)); gradientData.Add(new ChartDataModel(date.AddDays(15), 24)); gradientData.Add(new ChartDataModel(date.AddDays(23), 28)); gradientData.Add(new ChartDataModel(date.AddDays(30), 26)); gradientData.Add(new ChartDataModel(date.AddDays(39), 38)); gradientData.Add(new ChartDataModel(date.AddDays(50), 32)); return gradientData; } } public ObservableCollection<ChartDataModel> DateTimeData { get; set; } public ObservableCollection<ChartDataModel> SelectionData { get; set; } public ObservableCollection<ChartDataModel> SelectionData1 { get; set; } public ObservableCollection<ChartDataModel> data { get; set; } public ObservableCollection<ChartDataModel> liveData1 { get { var items = new ObservableCollection<ChartDataModel>(); for (var i = 0; i <= 180; i++) { items.Add(new ChartDataModel(i, Math.Sin(wave1 * (Math.PI / 180.0)))); wave1++; } return items; } } public ObservableCollection<ChartDataModel> liveData2 { get { var items = new ObservableCollection<ChartDataModel>(); for (var i = 0; i <= 180; i++) { items.Add(new ChartDataModel(i, Math.Sin(wave2 * (Math.PI / 180.0)))); wave2++; } return items; } } public ObservableCollection<ChartDataModel> verticalData { get { var items = new ObservableCollection<ChartDataModel>(); date = new DateTime(2011, 3, 11, 14, 46, 0); for (int i = 0; i < 30; i++) { var verData = dataPointWithTimeInterval(0.15); items.Add(new ChartDataModel(verData.XValue, verData.YValue)); verticalCount = items.Count; } return items; } } public ObservableCollection<ChartDataModel> PieData { get; set; } public ObservableCollection<ChartDataModel> StripLineData { get; set; } public ObservableCollection<ChartDataModel> MultipleSeriesData1 { get; set; } public ObservableCollection<ChartDataModel> MultipleSeriesData2 { get; set; } public ObservableCollection<ChartDataModel> LineSeries1 { get; set; } public ObservableCollection<ChartDataModel> LineSeries2 { get; set; } public ObservableCollection<ChartDataModel> LineSeries3 { get; set; } public ObservableCollection<ChartDataModel> TriangularData { get; set; } public ObservableCollection<ChartDataModel> TooltipData { get; set; } public ObservableCollection<ChartDataModel> DateTimeRangeData { get; set; } public ObservableCollection<ChartDataModel> DateUsageData { get; set; } public ObservableCollection<ChartDataModel> TechnicalIndicatorData { get; set; } public ObservableCollection<ChartDataModel> AxisCrossingData { get; set; } public ObservableCollection<ChartDataModel> StackedDoughnutData { get; set; } public ChartViewModel() { DateTime calendar = new DateTime(2000, 1, 1); DateTime dt = new DateTime(2000, 1, 1); StackedDoughnutData = new ObservableCollection<ChartDataModel>(); StackedDoughnutData.Add(new ChartDataModel("Vehicle", 62.7, "Images/Car.png")); StackedDoughnutData.Add(new ChartDataModel("Education", 29.5, "Images/Chart_Book.png")); StackedDoughnutData.Add(new ChartDataModel("Home", 85.2, "Images/House.png")); StackedDoughnutData.Add(new ChartDataModel("Personal", 45.6, "Images/Personal.png")); AxisCrossingData = new ObservableCollection<ChartDataModel>() { new ChartDataModel{XValue = "2000",YValue = 70, Size = 5}, new ChartDataModel{XValue = "2001",YValue = 50, Size = 8}, new ChartDataModel{XValue = "2002",YValue = -30, Size = 30}, new ChartDataModel{XValue = "2003",YValue = -70, Size = 10}, new ChartDataModel{XValue = "2004",YValue = 40, Size = 12}, new ChartDataModel{XValue = "2005",YValue = 80, Size = 13}, new ChartDataModel{XValue = "2006",YValue = -70, Size = 6}, new ChartDataModel{XValue = "2007",YValue = 30, Size = 8}, new ChartDataModel{XValue = "2008",YValue = 80, Size = 3}, new ChartDataModel{XValue = "2009",YValue = -30, Size = 5}, new ChartDataModel{XValue = "2010",YValue = -80, Size = 7}, new ChartDataModel{XValue = "2011",YValue = 40, Size = 3}, new ChartDataModel{XValue = "2012",YValue = -50, Size = 8}, new ChartDataModel{XValue = "2013",YValue = -10, Size = 4}, new ChartDataModel{XValue = "2014",YValue = -80, Size = 9}, new ChartDataModel{XValue = "2015",YValue = 40, Size = 10}, new ChartDataModel{XValue = "2016",YValue = -50, Size = 6}, }; TechnicalIndicatorData = new ObservableCollection<ChartDataModel> { new ChartDataModel(calendar.AddMonths(1), 65.75, 67.27, 65.75, 65.98, 7938200), new ChartDataModel(calendar.AddMonths(2), 65.98, 65.70, 65.04, 65.11, 10185300), new ChartDataModel(calendar.AddMonths(3), 65.11, 65.05, 64.26, 64.97, 10835800), new ChartDataModel(calendar.AddMonths(4), 64.97, 65.16, 64.09, 64.29, 9613400), new ChartDataModel(calendar.AddMonths(5), 64.29, 62.73, 61.85, 62.44, 17175000), new ChartDataModel(calendar.AddMonths(6), 62.44, 62.02, 61.29, 61.47, 18040600), new ChartDataModel(calendar.AddMonths(7), 61.47, 62.75, 61.55, 61.59, 13456300), new ChartDataModel(calendar.AddMonths(8), 61.59, 64.78, 62.22, 64.64, 8045100), new ChartDataModel(calendar.AddMonths(9), 64.64, 64.50, 63.03, 63.28, 8608900), new ChartDataModel(calendar.AddMonths(10), 63.28, 63.70, 62.70, 63.59, 15025500), new ChartDataModel(calendar.AddMonths(11), 63.59, 64.45, 63.26, 63.61, 10065800), new ChartDataModel(calendar.AddMonths(12), 63.61, 64.56, 63.81, 64.52, 6178200), new ChartDataModel(calendar.AddMonths(13), 64.52, 64.84, 63.66, 63.91, 5478500), new ChartDataModel(calendar.AddMonths(14), 63.91, 65.30, 64.50, 65.22, 7964300), new ChartDataModel(calendar.AddMonths(15), 65.22, 65.36, 64.46, 65.06, 5679300), new ChartDataModel(calendar.AddMonths(16), 65.06, 64.54, 63.56, 63.65, 10758300), new ChartDataModel(calendar.AddMonths(17), 63.65, 64.03, 63.33, 63.73, 5665900), new ChartDataModel(calendar.AddMonths(18), 63.73, 63.40, 62.80, 62.83, 5833000), new ChartDataModel(calendar.AddMonths(19), 62.83, 63.75, 62.96, 63.60, 3500800), new ChartDataModel(calendar.AddMonths(20), 63.6, 63.64, 62.51, 63.51, 5044700), new ChartDataModel(calendar.AddMonths(21), 63.51, 64.03, 63.53, 63.76, 4871300), new ChartDataModel(calendar.AddMonths(22), 63.76, 63.77, 63.01, 63.65, 7040400), new ChartDataModel(calendar.AddMonths(23), 63.65, 63.95, 63.58, 63.79, 4727800), new ChartDataModel(calendar.AddMonths(24), 63.79, 63.47, 62.92, 63.25, 6334900), new ChartDataModel(calendar.AddMonths(25), 63.25, 63.96, 63.21, 63.48, 6823200), new ChartDataModel(calendar.AddMonths(26), 63.48, 63.63, 62.55, 63.50, 9718400), new ChartDataModel(calendar.AddMonths(27), 63.5, 63.25, 62.82, 62.90, 2827000), new ChartDataModel(calendar.AddMonths(28), 62.9, 62.34, 62.05, 62.18, 4942700), new ChartDataModel(calendar.AddMonths(29), 62.18, 62.86, 61.94, 62.81, 4582800), new ChartDataModel(calendar.AddMonths(30), 62.81, 63.06, 62.44, 62.83, 12423900), new ChartDataModel(calendar.AddMonths(31), 62.83, 63.16, 62.66, 63.09, 4940500), new ChartDataModel(calendar.AddMonths(32), 63.09, 62.89, 62.43, 62.66, 6132300), new ChartDataModel(calendar.AddMonths(33), 62.66, 62.39, 61.90, 62.25, 6263800), new ChartDataModel(calendar.AddMonths(34), 62.25, 61.69, 60.97, 61.50, 5008300), new ChartDataModel(calendar.AddMonths(35), 61.5, 61.87, 61.18, 61.79, 6662500), new ChartDataModel(calendar.AddMonths(36), 61.79, 63.41, 62.72, 63.16, 5254000), new ChartDataModel(calendar.AddMonths(37), 63.16, 64.40, 63.65, 63.89, 5356600), new ChartDataModel(calendar.AddMonths(38), 63.89, 63.45, 61.60, 61.87, 5052600), new ChartDataModel(calendar.AddMonths(39), 61.87, 62.35, 61.30, 61.54, 6266700), new ChartDataModel(calendar.AddMonths(40), 61.54, 61.49, 60.33, 61.06, 6190800), new ChartDataModel(calendar.AddMonths(41), 61.06, 60.78, 59.84, 60.09, 6452300), new ChartDataModel(calendar.AddMonths(42), 60.09, 59.62, 58.62, 58.80, 5954000), new ChartDataModel(calendar.AddMonths(43), 58.8, 59.60, 58.89, 59.53, 6250000), new ChartDataModel(calendar.AddMonths(44), 59.53, 60.96, 59.42, 60.68, 5307300), new ChartDataModel(calendar.AddMonths(45), 60.68, 61.12, 60.65, 60.73, 6192900), new ChartDataModel(calendar.AddMonths(46), 60.73, 61.19, 60.62, 61.19, 6355600), new ChartDataModel(calendar.AddMonths(47), 61.19, 61.07, 60.54, 60.97, 2946300), new ChartDataModel(calendar.AddMonths(48), 60.97, 61.05, 59.65, 59.75, 2257600), new ChartDataModel(calendar.AddMonths(49), 59.75, 60.58, 55.99, 59.93, 2872000), new ChartDataModel(calendar.AddMonths(50), 59.93, 60.12, 59.26, 59.73, 2737500), new ChartDataModel(calendar.AddMonths(51), 59.73, 60.11, 59.35, 59.57, 2589700), new ChartDataModel(calendar.AddMonths(52), 59.57, 60.40, 59.60, 60.10, 7315800), new ChartDataModel(calendar.AddMonths(53), 60.1, 60.31, 59.76, 60.28, 6883900), new ChartDataModel(calendar.AddMonths(54), 60.28, 61.68, 60.50, 61.50, 5570700), new ChartDataModel(calendar.AddMonths(55), 61.5, 62.72, 61.64, 62.26, 5976000), new ChartDataModel(calendar.AddMonths(56), 62.26, 64.08, 63.10, 63.70, 3641400), new ChartDataModel(calendar.AddMonths(57), 63.7, 64.60, 63.99, 64.39, 6711600), new ChartDataModel(calendar.AddMonths(58), 64.39, 64.45, 63.92, 64.25, 6427000), new ChartDataModel(calendar.AddMonths(59), 64.25, 65.40, 64.66, 64.70, 5863200), new ChartDataModel(calendar.AddMonths(60), 64.7, 65.86, 65.32, 65.75, 4711400), new ChartDataModel(calendar.AddMonths(61), 65.75, 65.22, 64.63, 64.75, 5930600), new ChartDataModel(calendar.AddMonths(62), 64.75, 65.39, 64.76, 65.04, 5602700), new ChartDataModel(calendar.AddMonths(63), 65.04, 65.30, 64.78, 65.18, 7487300), new ChartDataModel(calendar.AddMonths(64), 65.18, 65.09, 64.42, 65.09, 9085400), new ChartDataModel(calendar.AddMonths(65), 65.09, 65.64, 65.20, 65.25, 6455300), new ChartDataModel(calendar.AddMonths(66), 65.25, 65.59, 64.74, 64.84, 6135500), new ChartDataModel(calendar.AddMonths(67), 64.84, 65.84, 65.42, 65.82, 5846400), new ChartDataModel(calendar.AddMonths(68), 65.82, 66.75, 65.85, 66.00, 6681200), new ChartDataModel(calendar.AddMonths(69), 66, 67.41, 66.17, 67.41, 8780000), new ChartDataModel(calendar.AddMonths(70), 67.41, 68.61, 68.06, 68.41, 10780900), new ChartDataModel(calendar.AddMonths(71), 68.41, 68.91, 68.42, 68.76, 2336450), new ChartDataModel(calendar.AddMonths(72), 68.76, 69.58, 68.86, 69.01, 11902000), new ChartDataModel(calendar.AddMonths(73), 69.01, 69.14, 68.74, 68.94, 7513300), new ChartDataModel(calendar.AddMonths(74), 68.94, 68.73, 68.06, 68.65, 12074800), new ChartDataModel(calendar.AddMonths(75), 68.65, 68.79, 68.19, 68.67, 8785400), new ChartDataModel(calendar.AddMonths(76), 68.67, 69.75, 68.68, 68.74, 11373200), new ChartDataModel(calendar.AddMonths(77), 68.74, 68.82, 67.71, 67.76, 12378300), new ChartDataModel(calendar.AddMonths(78), 67.76, 69.05, 68.43, 69.00, 8458700), new ChartDataModel(calendar.AddMonths(79), 69, 68.39, 67.77, 68.02, 10779200), new ChartDataModel(calendar.AddMonths(80), 68.02, 67.94, 67.22, 67.72, 9665400), new ChartDataModel(calendar.AddMonths(81), 67.72, 68.15, 67.32, 67.32, 12258400), new ChartDataModel(calendar.AddMonths(82), 67.32, 67.95, 67.13, 67.32, 7563600), new ChartDataModel(calendar.AddMonths(83), 67.32, 68.00, 67.16, 67.96, 5509900), new ChartDataModel(calendar.AddMonths(84), 67.96, 68.89, 68.34, 68.61, 12135500), new ChartDataModel(calendar.AddMonths(85), 68.61, 69.47, 68.30, 68.51, 8462000), new ChartDataModel(calendar.AddMonths(86), 68.51, 68.69, 68.21, 68.62, 2011950), new ChartDataModel(calendar.AddMonths(87), 68.62, 68.39, 65.80, 68.37, 8536800), new ChartDataModel(calendar.AddMonths(88), 68.37, 67.75, 65.00, 62.00, 7624900), new ChartDataModel(calendar.AddMonths(89), 67.62, 67.04, 65.04, 67.00, 13694600), new ChartDataModel(calendar.AddMonths(90), 66, 66.83, 65.02, 67.60, 8911200), new ChartDataModel(calendar.AddMonths(91), 66.6, 66.98, 65.44, 66.73, 6679600), new ChartDataModel(calendar.AddMonths(92), 66.73, 66.84, 65.10, 66.11, 6451900), new ChartDataModel(calendar.AddMonths(93), 66.11, 66.59, 65.69, 66.38, 6739100), new ChartDataModel(calendar.AddMonths(94), 66.38, 67.98, 66.51, 67.67, 2103260), new ChartDataModel(calendar.AddMonths(95), 67.67, 69.21, 68.59, 68.90, 10551800), new ChartDataModel(calendar.AddMonths(96), 68.9, 69.96, 69.27, 69.44, 5261100), new ChartDataModel(calendar.AddMonths(97), 69.44, 69.01, 68.14, 68.18, 5905400), new ChartDataModel(calendar.AddMonths(98), 68.18, 68.93, 68.08, 68.14, 10283600), new ChartDataModel(calendar.AddMonths(99), 68.14, 68.60, 66.92, 67.25, 5006800), new ChartDataModel(calendar.AddMonths(100), 67.25, 67.77, 67.23, 67.77, 4110000) }; DateTimeRangeData = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2015, 01, 1), 14), new ChartDataModel(new DateTime(2015, 02, 1), 54), new ChartDataModel(new DateTime(2015, 03, 1), 23), new ChartDataModel(new DateTime(2015, 04, 1), 53), new ChartDataModel(new DateTime(2015, 05, 1), 25), new ChartDataModel(new DateTime(2015, 06, 1), 32), new ChartDataModel(new DateTime(2015, 07, 1), 78), new ChartDataModel(new DateTime(2015, 08, 1), 100), new ChartDataModel(new DateTime(2015, 09, 1), 55), new ChartDataModel(new DateTime(2015, 10, 1), 38), new ChartDataModel(new DateTime(2015, 11, 1), 27), new ChartDataModel(new DateTime(2015, 12, 1), 56), new ChartDataModel(new DateTime(2015, 12, 31), 35), }; DateUsageData = new ObservableCollection<ChartDataModel>(); DateUsageData.Add(new ChartDataModel(dataTime, 14)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 54)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 23)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 53)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 25)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 32)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 78)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 100)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 55)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 38)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 27)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 56)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 55)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 38)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 27)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 56)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 30)); addWeek(); DateUsageData.Add(new ChartDataModel(dataTime, 45)); PolarData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 4), new ChartDataModel("2001", 3.0), new ChartDataModel("2002", 3.8), new ChartDataModel("2003", 3.4), new ChartDataModel("2004", 3.2), new ChartDataModel("2005", 3.9), }; PolarData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 2.6), new ChartDataModel("2001", 2.8), new ChartDataModel("2002", 2.6), new ChartDataModel("2003", 3), new ChartDataModel("2004", 3.6), new ChartDataModel("2005", 3), }; PolarData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 2.8), new ChartDataModel("2001", 2.5), new ChartDataModel("2002", 2.8), new ChartDataModel("2003", 3.2), new ChartDataModel("2004", 2.9), new ChartDataModel("2005", 2), }; BoxAndWhiskerData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Development", new List<double> { 22, 22, 23, 25, 25, 25, 26, 27, 27, 28, 28, 29, 30, 32, 34, 32, 34, 36, 35, 38 }), new ChartDataModel("HR", new List<double> { 22, 24, 25, 30, 32, 34, 36, 38, 39, 41, 35, 36, 40, 56 }), new ChartDataModel("Testing", new List<double> { 22, 33, 23, 25, 26, 28, 29, 30, 34, 33, 32, 31, 50 }), new ChartDataModel("Finance", new List<double> { 26, 27, 28, 30, 32, 34, 35, 37, 35, 37, 45 }), new ChartDataModel("Sales", new List<double> { 26, 27, 29, 32, 34, 35, 36, 37, 38, 39, 41, 43, 58 }), }; ErrorBarData = new ObservableCollection<ChartDataModel> { new ChartDataModel("IND", 23, 0.5, 1), new ChartDataModel("AUS", 20, 0, 2), new ChartDataModel("USA", 35, 1, 2), new ChartDataModel("DEU", 28, 2, 0.5), new ChartDataModel("ITA", 30, 1, 0), new ChartDataModel("UK", 42, 1.5, 1), new ChartDataModel("RUS", 27, 0.5, 2) }; AreaData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 45), new ChartDataModel("2011", 56), new ChartDataModel("2012", 23), new ChartDataModel("2013", 43), new ChartDataModel("2014", double.NaN), new ChartDataModel("2015", 54), new ChartDataModel("2016", 43), new ChartDataModel("2017", 23), new ChartDataModel("2018", 34) }; StripLineData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 26), new ChartDataModel("Mon", 24), new ChartDataModel("Tue", 31), new ChartDataModel("Wed", 28), new ChartDataModel("Thu", 30), new ChartDataModel("Fri", 26), new ChartDataModel("Sat", 30), }; LineData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2005", 33), new ChartDataModel("2006", 28), new ChartDataModel("2007", 29), new ChartDataModel("2008", 35), new ChartDataModel("2009", 32), new ChartDataModel("2010", 35), new ChartDataModel("2011", 30) }; LineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2005", 21), new ChartDataModel("2006", 24), new ChartDataModel("2007", 36), new ChartDataModel("2008", 38), new ChartDataModel("2009", 54), new ChartDataModel("2010", 57), new ChartDataModel("2011", 70) }; LineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2005", 28), new ChartDataModel("2006", 44), new ChartDataModel("2007", 48), new ChartDataModel("2008", 50), new ChartDataModel("2009", 66), new ChartDataModel("2010", 78), new ChartDataModel("2011", 84) }; StepLineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(1975, 16), new ChartDataModel(1980, 12.5), new ChartDataModel(1985, 19), new ChartDataModel(1990, 14.4), new ChartDataModel(1995, 11.5), new ChartDataModel(2000, 14), new ChartDataModel(2005, 10), new ChartDataModel(2010, 16), }; StepLineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(1975, 10), new ChartDataModel(1980, 7.5), new ChartDataModel(1985, 11), new ChartDataModel(1990, 7), new ChartDataModel(1995, 8), new ChartDataModel(2000, 6), new ChartDataModel(2005, 3.5), new ChartDataModel(2010, 7), }; StepAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2000, 416), new ChartDataModel(2001, 490), new ChartDataModel(2002, 470), new ChartDataModel(2003, 500), new ChartDataModel(2004, 449), new ChartDataModel(2005, 470), new ChartDataModel(2006, 437), new ChartDataModel(2007, 458), new ChartDataModel(2008, 500), new ChartDataModel(2009, 473), new ChartDataModel(2010, 520), new ChartDataModel(2011, 509), }; StepAreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2000, 180), new ChartDataModel(2001, 240), new ChartDataModel(2002, 370), new ChartDataModel(2003, 200), new ChartDataModel(2004, 229), new ChartDataModel(2005, 210), new ChartDataModel(2006, 337), new ChartDataModel(2007, 258), new ChartDataModel(2008, 300), new ChartDataModel(2009, 173), new ChartDataModel(2010, 220), new ChartDataModel(2011, 309), }; ColumnData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("USA", 46), new ChartDataModel("GBR", 27), new ChartDataModel("CHN", 26), }; ColumnData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("USA", 37), new ChartDataModel("GBR", 23), new ChartDataModel("CHN", 18), }; ColumnData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("USA", 38), new ChartDataModel("GBR", 17), new ChartDataModel("CHN", 26), }; HistogramData = new ObservableCollection<ChartDataModel> { new ChartDataModel(0, 5.250), new ChartDataModel(0, 7.750), new ChartDataModel(0, 0), new ChartDataModel(0, 8.275), new ChartDataModel(0, 9.750), new ChartDataModel(0, 7.750), new ChartDataModel(0, 8.275), new ChartDataModel(0, 6.250), new ChartDataModel(0, 5.750), new ChartDataModel(0, 5.250), new ChartDataModel(0, 23.000), new ChartDataModel(0, 26.500), new ChartDataModel(0, 27.750), new ChartDataModel(0, 25.025), new ChartDataModel(0, 26.500), new ChartDataModel(0, 26.500), new ChartDataModel(0, 28.025), new ChartDataModel(0, 29.250), new ChartDataModel(0, 26.750), new ChartDataModel(0, 27.250), new ChartDataModel(0, 26.250), new ChartDataModel(0, 25.250), new ChartDataModel(0, 34.500), new ChartDataModel(0, 25.625), new ChartDataModel(0, 25.500), new ChartDataModel(0, 26.625), new ChartDataModel(0, 36.275), new ChartDataModel(0, 36.250), new ChartDataModel(0, 26.875), new ChartDataModel(0, 45.000), new ChartDataModel(0, 43.000), new ChartDataModel(0, 46.500), new ChartDataModel(0, 47.750), new ChartDataModel(0, 45.025), new ChartDataModel(0, 56.500), new ChartDataModel(0, 56.500), new ChartDataModel(0, 58.025), new ChartDataModel(0, 59.250), new ChartDataModel(0, 56.750), new ChartDataModel(0, 57.250), new ChartDataModel(0, 46.250), new ChartDataModel(0, 55.250), new ChartDataModel(0, 44.500), new ChartDataModel(0, 45.500), new ChartDataModel(0, 55.500), new ChartDataModel(0, 45.625), new ChartDataModel(0, 55.500), new ChartDataModel(0, 56.250), new ChartDataModel(0, 46.875), new ChartDataModel(0, 43.000), new ChartDataModel(0, 46.250), new ChartDataModel(0, 55.250), new ChartDataModel(0, 44.500), new ChartDataModel(0, 45.425), new ChartDataModel(0, 56.625), new ChartDataModel(0, 46.275), new ChartDataModel(0, 56.250), new ChartDataModel(0, 46.875), new ChartDataModel(0, 43.000), new ChartDataModel(0, 46.250), new ChartDataModel(0, 55.250), new ChartDataModel(0, 44.500), new ChartDataModel(0, 45.425), new ChartDataModel(0, 55.500), new ChartDataModel(0, 46.625), new ChartDataModel(0, 56.275), new ChartDataModel(0, 46.250), new ChartDataModel(0, 56.250), new ChartDataModel(0, 42.000), new ChartDataModel(0, 41.000), new ChartDataModel(0, 63.000), new ChartDataModel(0, 66.500), new ChartDataModel(0, 67.750), new ChartDataModel(0, 65.025), new ChartDataModel(0, 66.500), new ChartDataModel(0, 76.500), new ChartDataModel(0, 78.025), new ChartDataModel(0, 79.250), new ChartDataModel(0, 76.750), new ChartDataModel(0, 77.250), new ChartDataModel(0, 66.250), new ChartDataModel(0, 75.250), new ChartDataModel(0, 74.500), new ChartDataModel(0, 65.625), new ChartDataModel(0, 75.500), new ChartDataModel(0, 76.625), new ChartDataModel(0, 76.275), new ChartDataModel(0, 66.250), new ChartDataModel(0, 66.875), new ChartDataModel(0, 82.000), new ChartDataModel(0, 85.250), new ChartDataModel(0, 87.750), new ChartDataModel(0, 92.000), new ChartDataModel(0, 85.250), new ChartDataModel(0, 87.750), new ChartDataModel(0, 89.000), new ChartDataModel(0, 88.275), new ChartDataModel(0, 89.750), new ChartDataModel(0, 95.750), new ChartDataModel(0, 95.250), }; BarData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Egg", 2.2), new ChartDataModel("Fish", 2.4), new ChartDataModel("Misc", 3), new ChartDataModel("Tea", 3.1), }; BarData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Egg", 1.2), new ChartDataModel("Fish", 1.3), new ChartDataModel("Misc", 1.5), new ChartDataModel("Tea", 2.2), }; AreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2000, 4), new ChartDataModel(2001, 3.0), new ChartDataModel(2002, 3.8), new ChartDataModel(2003, 4.4), new ChartDataModel(2004, 3.2), new ChartDataModel(2005, 3.9), }; AreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2000, 2.6), new ChartDataModel(2001, 2.8), new ChartDataModel(2002, 2.6), new ChartDataModel(2003, 3), new ChartDataModel(2004, 3.6), new ChartDataModel(2005, 3), }; SplineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 15), new ChartDataModel("Mon", 22), new ChartDataModel("Tue", 32), new ChartDataModel("Wed", 31), new ChartDataModel("Thu", 29), new ChartDataModel("Fri", 26), new ChartDataModel("Sat", 18), }; SplineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 10), new ChartDataModel("Mon", 18), new ChartDataModel("Tue", 28), new ChartDataModel("Wed", 28), new ChartDataModel("Thu", 26), new ChartDataModel("Fri", 20), new ChartDataModel("Sat", 15), }; SplineData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 2), new ChartDataModel("Mon", 12), new ChartDataModel("Tue", 22), new ChartDataModel("Wed", 23), new ChartDataModel("Thu", 19), new ChartDataModel("Fri", 13), new ChartDataModel("Sat", 8), }; SplineAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2002, 2.2), new ChartDataModel(2003, 3.4), new ChartDataModel(2004, 2.8), new ChartDataModel(2005, 1.6), new ChartDataModel(2006, 2.3), new ChartDataModel(2007, 2.5), new ChartDataModel(2008, 2.9), new ChartDataModel(2009, 3.8), new ChartDataModel(2010, 1.4), new ChartDataModel(2011, 3.1), }; SplineAreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2002, 2.0), new ChartDataModel(2003, 1.7), new ChartDataModel(2004, 1.8), new ChartDataModel(2005, 2.1), new ChartDataModel(2006, 2.3), new ChartDataModel(2007, 1.7), new ChartDataModel(2008, 1.5), new ChartDataModel(2009, 2.8), new ChartDataModel(2010, 1.5), new ChartDataModel(2011, 2.3), }; SplineAreaData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel(2002, 0.8), new ChartDataModel(2003, 1.3), new ChartDataModel(2004, 1.1), new ChartDataModel(2005, 1.6), new ChartDataModel(2006, 2.0), new ChartDataModel(2007, 1.7), new ChartDataModel(2008, 2.3), new ChartDataModel(2009, 2.7), new ChartDataModel(2010, 1.1), new ChartDataModel(2011, 2.3), }; RangeColumnData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 10.8, 3.1), new ChartDataModel("Mon", 14.4, 5.7), new ChartDataModel("Tue", 16.9, 8.4), new ChartDataModel("Wed", 19.2, 10.6), new ChartDataModel("Thu", 16.1, 8.5), new ChartDataModel("Fri", 12.5, 6.0), new ChartDataModel("Sat", 6.9, 1.5) }; RangeColumnData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 9.8, 2.5), new ChartDataModel("Mon", 11.4, 4.7), new ChartDataModel("Tue", 14.4, 6.4), new ChartDataModel("Wed", 17.2, 9.6), new ChartDataModel("Thu", 15.1, 7.5), new ChartDataModel("Fri", 10.5, 3.0), new ChartDataModel("Sat", 7.9, 1.2) }; RangeBarData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jumbo", 119238), new ChartDataModel("FHA", 159595), new ChartDataModel("VA", 256398), new ChartDataModel("USDA", 356396), new ChartDataModel("Const", 456398), new ChartDataModel("Total", 559937) }; RangeAreaData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 45, 32), new ChartDataModel("Feb", 48, 34), new ChartDataModel("Mar", 46, 32), new ChartDataModel("Apr", 48, 36), new ChartDataModel("May", 46, 32), new ChartDataModel("Jun", 49, 34) }; RangeAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 30, 18), new ChartDataModel("Feb", 24, 12), new ChartDataModel("Mar", 29, 15), new ChartDataModel("Apr", 24, 10), new ChartDataModel("May", 30, 18), new ChartDataModel("Jun", 24, 10) }; StepLineData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2002", 36), new ChartDataModel("2003", 40), new ChartDataModel("2004", 34), new ChartDataModel("2005", 40), new ChartDataModel("2006", 44), new ChartDataModel("2007", 38), new ChartDataModel("2008", 30) }; PieSeriesData = new ObservableCollection<ChartDataModel> { new ChartDataModel("David", 30), new ChartDataModel("Steve", 35), new ChartDataModel("Micheal", 24), new ChartDataModel("John", 11), new ChartDataModel("Regev", 25), new ChartDataModel("Jack", 39), new ChartDataModel("Stephen", 15), }; DoughnutSeriesData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Labour", 10), new ChartDataModel("Legal", 8), new ChartDataModel("Production", 7), new ChartDataModel("License", 5), new ChartDataModel("Facilities", 10), new ChartDataModel("Taxes", 6), new ChartDataModel("Insurance", 18) }; PyramidData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sweet Treats", 120), new ChartDataModel("Milk, Youghnut, Cheese", 435), new ChartDataModel("Vegetables", 470), new ChartDataModel("Meat, Poultry, Fish", 475), new ChartDataModel("Fruits", 520), new ChartDataModel("Bread, Rice, Pasta", 930), }; FunnelData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Renewed", 18.2), new ChartDataModel("Subscribe", 27.3), new ChartDataModel("Support", 55.9), new ChartDataModel("Downloaded", 76.8), new ChartDataModel("Visited", 100), }; StackedBarData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 12), new ChartDataModel("Apr", 15.5), new ChartDataModel("May", 20), new ChartDataModel("Jun", 24), }; StackedBarData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 11), new ChartDataModel("Apr", 16), new ChartDataModel("May", 21), new ChartDataModel("Jun", 25), }; StackedBarData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", -1), new ChartDataModel("Feb", -1.5), new ChartDataModel("Mar", -2), new ChartDataModel("Apr", -2.5), new ChartDataModel("May", -3), new ChartDataModel("Jun", -3.5), }; StackedBar100Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 12), new ChartDataModel("Apr", 15), new ChartDataModel("May", 20), new ChartDataModel("Jun", 24), }; StackedBar100Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 6), new ChartDataModel("Feb", 8), new ChartDataModel("Mar", 11), new ChartDataModel("Apr", 16), new ChartDataModel("May", 21), new ChartDataModel("Jun", 25), }; StackedBar100Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 1), new ChartDataModel("Feb", 1.5), new ChartDataModel("Mar", 2), new ChartDataModel("Apr", 2.5), new ChartDataModel("May", 3), new ChartDataModel("Jun", 3.5), }; StackedColumnData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2014", 111.1), new ChartDataModel("2015", 127.3), new ChartDataModel("2016", 143.4), new ChartDataModel("2017", 159.9) }; StackedColumnData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2014", 76.9), new ChartDataModel("2015", 99.5), new ChartDataModel("2016", 121.7), new ChartDataModel("2017", 142.5) }; StackedColumnData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2014", 66.1), new ChartDataModel("2015", 79.3), new ChartDataModel("2016", 91.3), new ChartDataModel("2017", 102.4) }; StackedColumnData4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2014", 34.1), new ChartDataModel("2015", 38.2), new ChartDataModel("2016", 44.0), new ChartDataModel("2017", 51.6) }; StackedColumn100Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 900), new ChartDataModel("2007", 544), new ChartDataModel("2008", 880), new ChartDataModel("2009", 675) }; StackedColumn100Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 190), new ChartDataModel("2007", 226), new ChartDataModel("2008", 194), new ChartDataModel("2009", 250) }; StackedColumn100Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 250), new ChartDataModel("2007", 145), new ChartDataModel("2008", 190), new ChartDataModel("2009", 220) }; StackedColumn100Data4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2006", 150), new ChartDataModel("2007", 120), new ChartDataModel("2008", 115), new ChartDataModel("2009", 125) }; StackedLineData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 55), new ChartDataModel("Transport", 33), new ChartDataModel("Medical", 43), new ChartDataModel("Clothes", 32), new ChartDataModel("Books", 56), new ChartDataModel("Others", 23) }; StackedLineData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 40), new ChartDataModel("Transport", 45), new ChartDataModel("Medical", 23), new ChartDataModel("Clothes", 54), new ChartDataModel("Books", 18), new ChartDataModel("Others", 54) }; StackedLineData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 45), new ChartDataModel("Transport", 54), new ChartDataModel("Medical", 20), new ChartDataModel("Clothes", 23), new ChartDataModel("Books", 43), new ChartDataModel("Others", 33) }; StackedLineData4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 48), new ChartDataModel("Transport", 28), new ChartDataModel("Medical", 34), new ChartDataModel("Clothes", 84), new ChartDataModel("Books", 55), new ChartDataModel("Others", 56) }; StackedLine100Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 36), new ChartDataModel("Transport", 18), new ChartDataModel("Medical", 43), new ChartDataModel("Clothes", 32), new ChartDataModel("Books", 56), new ChartDataModel("Others", 23) }; StackedLine100Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 40), new ChartDataModel("Transport", 45), new ChartDataModel("Medical", 23), new ChartDataModel("Clothes", 54), new ChartDataModel("Books", 48), new ChartDataModel("Others", 54) }; StackedLine100Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 45), new ChartDataModel("Transport", 54), new ChartDataModel("Medical", 20), new ChartDataModel("Clothes", 73), new ChartDataModel("Books", 93), new ChartDataModel("Others", 54) }; StackedLine100Data4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Food", 48), new ChartDataModel("Transport", 28), new ChartDataModel("Medical", 34), new ChartDataModel("Clothes", 84), new ChartDataModel("Books", 55), new ChartDataModel("Others", 56) }; StackedAreaData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.61), new ChartDataModel("2001", 0.81), new ChartDataModel("2002", 0.91), new ChartDataModel("2003", 1), new ChartDataModel("2004", 1.19), new ChartDataModel("2005", 1.47), new ChartDataModel("2006", 1.74), new ChartDataModel("2007", 1.98), new ChartDataModel("2008", 1.99), new ChartDataModel("2009", 1.70), new ChartDataModel("2010", 1.48), new ChartDataModel("2011", 1.38), new ChartDataModel("2012", 1.66), new ChartDataModel("2013", 1.66), new ChartDataModel("2014", 1.67), }; StackedAreaData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.03), new ChartDataModel("2001", 0.05), new ChartDataModel("2002", 0.06), new ChartDataModel("2003", 0.09), new ChartDataModel("2004", 0.14), new ChartDataModel("2005", 0.20), new ChartDataModel("2006", 0.29), new ChartDataModel("2007", 0.46), new ChartDataModel("2008", 0.64), new ChartDataModel("2009", 0.75), new ChartDataModel("2010", 1.06), new ChartDataModel("2011", 1.25), new ChartDataModel("2012", 1.55), new ChartDataModel("2013", 1.55), new ChartDataModel("2014", 1.65), }; StackedAreaData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.48), new ChartDataModel("2001", 0.53), new ChartDataModel("2002", 0.57), new ChartDataModel("2003", 0.61), new ChartDataModel("2004", 0.63), new ChartDataModel("2005", 0.64), new ChartDataModel("2006", 0.66), new ChartDataModel("2007", 0.76), new ChartDataModel("2008", 0.77), new ChartDataModel("2009", 0.55), new ChartDataModel("2010", 0.54), new ChartDataModel("2011", 0.57), new ChartDataModel("2012", 0.61), new ChartDataModel("2013", 0.67), new ChartDataModel("2014", 0.67), }; StackedAreaData4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.23), new ChartDataModel("2001", 0.17), new ChartDataModel("2002", 0.17), new ChartDataModel("2003", 0.20), new ChartDataModel("2004", 0.23), new ChartDataModel("2005", 0.36), new ChartDataModel("2006", 0.43), new ChartDataModel("2007", 0.52), new ChartDataModel("2008", 0.72), new ChartDataModel("2009", 1.29), new ChartDataModel("2010", 1.38), new ChartDataModel("2011", 1.82), new ChartDataModel("2012", 2.16), new ChartDataModel("2013", 2.51), new ChartDataModel("2014", 2.61), }; StackedArea100Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.61), new ChartDataModel("2001", 0.81), new ChartDataModel("2002", 0.91), new ChartDataModel("2003", 1), new ChartDataModel("2004", 1.19), new ChartDataModel("2005", 1.47), new ChartDataModel("2006", 1.74), new ChartDataModel("2007", 1.98), new ChartDataModel("2008", 1.99), new ChartDataModel("2009", 1.70), new ChartDataModel("2010", 1.48), new ChartDataModel("2011", 1.38), new ChartDataModel("2012", 1.66), new ChartDataModel("2013", 1.66), new ChartDataModel("2014", 1.67), }; StackedArea100Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.03), new ChartDataModel("2001", 0.05), new ChartDataModel("2002", 0.06), new ChartDataModel("2003", 0.09), new ChartDataModel("2004", 0.14), new ChartDataModel("2005", 0.20), new ChartDataModel("2006", 0.29), new ChartDataModel("2007", 0.46), new ChartDataModel("2008", 0.64), new ChartDataModel("2009", 0.75), new ChartDataModel("2010", 1.06), new ChartDataModel("2011", 1.25), new ChartDataModel("2012", 1.55), new ChartDataModel("2013", 1.55), new ChartDataModel("2014", 1.65), }; StackedArea100Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.48), new ChartDataModel("2001", 0.53), new ChartDataModel("2002", 0.57), new ChartDataModel("2003", 0.61), new ChartDataModel("2004", 0.63), new ChartDataModel("2005", 0.64), new ChartDataModel("2006", 0.66), new ChartDataModel("2007", 0.76), new ChartDataModel("2008", 0.77), new ChartDataModel("2009", 0.55), new ChartDataModel("2010", 0.54), new ChartDataModel("2011", 0.57), new ChartDataModel("2012", 0.61), new ChartDataModel("2013", 0.67), new ChartDataModel("2014", 0.67), }; StackedArea100Data4 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2000", 0.23), new ChartDataModel("2001", 0.17), new ChartDataModel("2002", 0.17), new ChartDataModel("2003", 0.20), new ChartDataModel("2004", 0.23), new ChartDataModel("2005", 0.36), new ChartDataModel("2006", 0.43), new ChartDataModel("2007", 0.52), new ChartDataModel("2008", 0.72), new ChartDataModel("2009", 1.29), new ChartDataModel("2010", 1.38), new ChartDataModel("2011", 1.82), new ChartDataModel("2012", 2.16), new ChartDataModel("2013", 2.51), new ChartDataModel("2014", 2.61), }; CircularData = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 8000), new ChartDataModel("2011", 8100), new ChartDataModel("2012", 8250), new ChartDataModel("2013", 8600), new ChartDataModel("2014", 8700) }; MultipleAxisData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 35 ), new ChartDataModel("Mon", 40 ), new ChartDataModel("Tue", 80 ), new ChartDataModel("Wed", 70 ), new ChartDataModel("Thu", 65 ), new ChartDataModel("Fri", 55 ), new ChartDataModel("Sat", 50 ) }; MultipleAxisData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Sun", 30 ), new ChartDataModel("Mon", 28 ), new ChartDataModel("Tue", 29 ), new ChartDataModel("Wed", 30 ), new ChartDataModel("Thu", 33 ), new ChartDataModel("Fri", 32 ), new ChartDataModel("Sat", 34 ) }; SemiCircularData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Product A", 14), new ChartDataModel("Product B", 54), new ChartDataModel("Product C", 23), new ChartDataModel("Product D", 53), }; BubbleData = new ObservableCollection<ChartDataModel> { new ChartDataModel(92.2, 7.8, 1.347, "China"), new ChartDataModel(74, 6.5, 1.241, "India"), new ChartDataModel(90.4, 6.0, 0.238, "Indonesia"), new ChartDataModel(99.4, 2.2, 0.312, "US"), new ChartDataModel(88.6, 1.3, 0.197, "Brazil"), new ChartDataModel(99, 0.7, 0.0818, "Germany"), new ChartDataModel(72, 2.0, 0.0826, "Egypt"), new ChartDataModel(99.6, 3.4, 0.143, "Russia"), new ChartDataModel(99, 0.2, 0.128, "Japan"), new ChartDataModel(86.1, 4.0, 0.115, "Mexico"), new ChartDataModel(92.6, 6.6, 0.096, "Philippines"), new ChartDataModel(61.3, 1.45, 0.162, "Nigeria"), new ChartDataModel(82.2, 3.97, 0.7, "Hong Kong"), new ChartDataModel(79.2, 3.9,0.162, "Netherland"), new ChartDataModel(72.5, 4.5,0.7, "Jordan"), new ChartDataModel(81, 3.5, 0.21, "Australia"), new ChartDataModel(66.8, 3.9, 0.028, "Mongolia"), new ChartDataModel(79.2, 2.9, 0.231, "Taiwan"), }; ScatterMaleData = new ObservableCollection<ChartDataModel>() { new ChartDataModel(161, 65), new ChartDataModel(150, 65), new ChartDataModel(155, 65), new ChartDataModel(160, 65), new ChartDataModel(148, 66), new ChartDataModel(145, 66), new ChartDataModel(137, 66), new ChartDataModel(138, 66), new ChartDataModel(162, 66), new ChartDataModel(166, 66), new ChartDataModel(159, 66), new ChartDataModel(151, 66), new ChartDataModel(180, 66), new ChartDataModel(181, 66), new ChartDataModel(174, 66), new ChartDataModel(159, 66), new ChartDataModel(151, 67), new ChartDataModel(148, 67), new ChartDataModel(141, 67), new ChartDataModel(145, 67), new ChartDataModel(165, 67), new ChartDataModel(168, 67), new ChartDataModel(159, 67), new ChartDataModel(183, 67), new ChartDataModel(188, 67), new ChartDataModel(187, 67), new ChartDataModel(172, 67), new ChartDataModel(193, 67), new ChartDataModel(153, 68), new ChartDataModel(153, 68), new ChartDataModel(147, 68), new ChartDataModel(163, 68), new ChartDataModel(174, 68), new ChartDataModel(173, 68), new ChartDataModel(160, 68), new ChartDataModel(191, 68), new ChartDataModel(131, 62), new ChartDataModel(140, 62), new ChartDataModel(149, 62), new ChartDataModel(115, 62), new ChartDataModel(164, 63), new ChartDataModel(162, 63), new ChartDataModel(167, 63), new ChartDataModel(146, 63), new ChartDataModel(150, 64), new ChartDataModel(141, 64), new ChartDataModel(142, 64), new ChartDataModel(129, 64), new ChartDataModel(159, 64), new ChartDataModel(158, 64), new ChartDataModel(162, 64), new ChartDataModel(136, 64), new ChartDataModel(176, 64), new ChartDataModel(170, 64), new ChartDataModel(167, 64), new ChartDataModel(144, 64), new ChartDataModel(143, 65), new ChartDataModel(137, 65), new ChartDataModel(137, 65), new ChartDataModel(140, 65), new ChartDataModel(182, 65), new ChartDataModel(168, 65), new ChartDataModel(181, 65), new ChartDataModel(165, 65), new ChartDataModel(214, 74), new ChartDataModel(211, 74), new ChartDataModel(166, 74), new ChartDataModel(185, 74), new ChartDataModel(189, 68), new ChartDataModel(182, 68), new ChartDataModel(181, 68), new ChartDataModel(196, 68), new ChartDataModel(152, 69), new ChartDataModel(173, 69), new ChartDataModel(190, 69), new ChartDataModel(161, 69), new ChartDataModel(173, 69), new ChartDataModel(185, 69), new ChartDataModel(141, 69), new ChartDataModel(149, 69), new ChartDataModel(134, 62), new ChartDataModel(183, 62), new ChartDataModel(155, 62), new ChartDataModel(164, 62), new ChartDataModel(169, 62), new ChartDataModel(122, 62), new ChartDataModel(161, 62), new ChartDataModel(166, 62), new ChartDataModel(137, 63), new ChartDataModel(140, 63), new ChartDataModel(140, 63), new ChartDataModel(126, 63), new ChartDataModel(150, 63), new ChartDataModel(153, 63), new ChartDataModel(154, 63), new ChartDataModel(139, 63), new ChartDataModel(186, 69), new ChartDataModel(188, 69), new ChartDataModel(148, 69), new ChartDataModel(174, 69), new ChartDataModel(164, 70), new ChartDataModel(182, 70), new ChartDataModel(200, 70), new ChartDataModel(151, 70), new ChartDataModel(204, 74), new ChartDataModel(177, 74), new ChartDataModel(194, 74), new ChartDataModel(212, 74), new ChartDataModel(162, 70), new ChartDataModel(200, 70), new ChartDataModel(166, 70), new ChartDataModel(177, 70), new ChartDataModel(188, 70), new ChartDataModel(156, 70), new ChartDataModel(175, 70), new ChartDataModel(191, 70), new ChartDataModel(174, 71), new ChartDataModel(187, 71), new ChartDataModel(208, 71), new ChartDataModel(166, 71), new ChartDataModel(150, 71), new ChartDataModel(194, 71), new ChartDataModel(157, 71), new ChartDataModel(183, 71), new ChartDataModel(204, 71), new ChartDataModel(162, 71), new ChartDataModel(179, 71), new ChartDataModel(196, 71), new ChartDataModel(170, 72), new ChartDataModel(184, 72), new ChartDataModel(197, 72), new ChartDataModel(162, 72), new ChartDataModel(177, 72), new ChartDataModel(203, 72), new ChartDataModel(159, 72), new ChartDataModel(178, 72), new ChartDataModel(198, 72), new ChartDataModel(167, 72), new ChartDataModel(184, 72), new ChartDataModel(201, 72), new ChartDataModel(167, 73), new ChartDataModel(178, 73), new ChartDataModel(215, 73), new ChartDataModel(207, 73), new ChartDataModel(172, 73), new ChartDataModel(204, 73), new ChartDataModel(162, 73), new ChartDataModel(182, 73), new ChartDataModel(201, 73), new ChartDataModel(172, 73), new ChartDataModel(189, 73), new ChartDataModel(206, 73), new ChartDataModel(150, 74), new ChartDataModel(187, 74), new ChartDataModel(153, 74), new ChartDataModel(171, 74), }; ScatterFemaleData = new ObservableCollection<ChartDataModel>() { new ChartDataModel(115, 57 ), new ChartDataModel(138, 57 ), new ChartDataModel(166, 57 ), new ChartDataModel(122, 57 ), new ChartDataModel(126, 57 ), new ChartDataModel(130, 57 ), new ChartDataModel(125, 57 ), new ChartDataModel(144, 57 ), new ChartDataModel(150, 57 ), new ChartDataModel(120, 57 ), new ChartDataModel(125, 57 ), new ChartDataModel(130, 57 ), new ChartDataModel(103, 58 ), new ChartDataModel(116, 58 ), new ChartDataModel(130, 58 ), new ChartDataModel(126, 58 ), new ChartDataModel(136, 58 ), new ChartDataModel(148, 58 ), new ChartDataModel(119, 58 ), new ChartDataModel(141, 58 ), new ChartDataModel(159, 58 ), new ChartDataModel(120, 58 ), new ChartDataModel(135, 58 ), new ChartDataModel(163, 58 ), new ChartDataModel(119, 59 ), new ChartDataModel(131, 59 ), new ChartDataModel(148, 59 ), new ChartDataModel(123, 59 ), new ChartDataModel(137, 59 ), new ChartDataModel(149, 59 ), new ChartDataModel(121, 59 ), new ChartDataModel(142, 59 ), new ChartDataModel(160, 59 ), new ChartDataModel(118, 59 ), new ChartDataModel(130, 59 ), new ChartDataModel(146, 59 ), new ChartDataModel(119, 60 ), new ChartDataModel(133, 60 ), new ChartDataModel(150, 60 ), new ChartDataModel(133, 60 ), new ChartDataModel(149, 60 ), new ChartDataModel(165, 60 ), new ChartDataModel(130, 60 ), new ChartDataModel(139, 60 ), new ChartDataModel(154, 60 ), new ChartDataModel(118, 60 ), new ChartDataModel(152, 60 ), new ChartDataModel(154, 60 ), new ChartDataModel(130, 61 ), new ChartDataModel(145, 61 ), new ChartDataModel(166, 61 ), new ChartDataModel(131, 61 ), new ChartDataModel(143, 61 ), new ChartDataModel(162, 61 ), new ChartDataModel(131, 61 ), new ChartDataModel(145, 61 ), new ChartDataModel(162, 61 ), new ChartDataModel(115, 61 ), new ChartDataModel(149, 61 ), new ChartDataModel(183, 61 ), new ChartDataModel(121, 62 ), new ChartDataModel(139, 62 ), new ChartDataModel(159, 62 ), new ChartDataModel(135, 62 ), new ChartDataModel(152, 62 ), new ChartDataModel(178, 62 ), new ChartDataModel(130, 62 ), new ChartDataModel(153, 62 ), new ChartDataModel(172, 62 ), new ChartDataModel(114, 62 ), new ChartDataModel(135, 62 ), new ChartDataModel(154, 62 ), new ChartDataModel(126, 63 ), new ChartDataModel(141, 63 ), new ChartDataModel(160, 63 ), new ChartDataModel(135, 63 ), new ChartDataModel(149, 63 ), new ChartDataModel(180, 63 ), new ChartDataModel(132, 63 ), new ChartDataModel(144, 63 ), new ChartDataModel(163, 63 ), new ChartDataModel(122, 63 ), new ChartDataModel(146, 63 ), new ChartDataModel(156, 63 ), new ChartDataModel(133, 64 ), new ChartDataModel(150, 64 ), new ChartDataModel(176, 64 ), new ChartDataModel(133, 64 ), new ChartDataModel(149, 64 ), new ChartDataModel(176, 64 ), new ChartDataModel(136, 64 ), new ChartDataModel(157, 64 ), new ChartDataModel(174, 64 ), new ChartDataModel(131, 64 ), new ChartDataModel(155, 64 ), new ChartDataModel(191, 64 ), new ChartDataModel(136, 65 ), new ChartDataModel(149, 65 ), new ChartDataModel(177, 65 ), new ChartDataModel(143, 65 ), new ChartDataModel(149, 65 ), new ChartDataModel(184, 65 ), new ChartDataModel(128, 65 ), new ChartDataModel(146, 65 ), new ChartDataModel(157, 65 ), new ChartDataModel(133, 65 ), new ChartDataModel(153, 65 ), new ChartDataModel(173, 65 ), new ChartDataModel(141, 66 ), new ChartDataModel(156, 66 ), new ChartDataModel(175, 66 ), new ChartDataModel(125, 66 ), new ChartDataModel(138, 66 ), new ChartDataModel(165, 66 ), new ChartDataModel(122, 66 ), new ChartDataModel(164, 66 ), new ChartDataModel(182, 66 ), new ChartDataModel(137, 66 ), new ChartDataModel(157, 66 ), new ChartDataModel(176, 66 ), new ChartDataModel(149, 67 ), new ChartDataModel(159, 67 ), new ChartDataModel(179, 67 ), new ChartDataModel(156, 67 ), new ChartDataModel(179, 67 ), new ChartDataModel(186, 67 ), new ChartDataModel(147, 67 ), new ChartDataModel(166, 67 ), new ChartDataModel(185, 67 ), new ChartDataModel(140, 67 ), new ChartDataModel(160, 67 ), new ChartDataModel(180, 67 ), new ChartDataModel(145, 68 ), new ChartDataModel(155, 68 ), new ChartDataModel(170, 68 ), new ChartDataModel(129, 68 ), new ChartDataModel(164, 68 ), new ChartDataModel(189, 68 ), new ChartDataModel(150, 68 ), new ChartDataModel(157, 68 ), new ChartDataModel(183, 68 ), new ChartDataModel(144, 68 ), new ChartDataModel(170, 68 ), new ChartDataModel(180, 68 ) }; RangeColumnData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 35, 17), new ChartDataModel("Feb", 42, -11), new ChartDataModel("Mar", 25, 5), new ChartDataModel("Apr", 32, 10), new ChartDataModel("May", 20, 3), new ChartDataModel("Jun", 41, 30) }; FinancialData = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2000, 01, 17), 115, 125, 70, 90), new ChartDataModel(new DateTime(2000, 02, 17), 120, 150, 60, 70), new ChartDataModel(new DateTime(2000, 03, 17), 160, 200, 140, 190), new ChartDataModel(new DateTime(2000, 04, 17), 140, 160, 90, 110), new ChartDataModel(new DateTime(2000, 05, 17), 180, 200, 100, 120), new ChartDataModel(new DateTime(2000, 06, 17), 70, 100, 45, 50) }; Data1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 45), new ChartDataModel("2011", 89), new ChartDataModel("2012", 23), new ChartDataModel("2013", 43), new ChartDataModel("2014", 54) }; Data2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 54), new ChartDataModel("2011", 24), new ChartDataModel("2012", 53), new ChartDataModel("2013", 63), new ChartDataModel("2014", 35) }; Data3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 14), new ChartDataModel("2011", 54), new ChartDataModel("2012", 23), new ChartDataModel("2013", 53), new ChartDataModel("2014", 25) }; CategoryData = new ObservableCollection<ChartDataModel> { new ChartDataModel("South Korea", 39), new ChartDataModel("India", 20), new ChartDataModel("South Africa", 61), new ChartDataModel("China", 65), new ChartDataModel("France", 45), new ChartDataModel("Saudi Arabia", 10), new ChartDataModel("Japan", 16), new ChartDataModel("Mexico", 31) }; LogarithmicData = new ObservableCollection<ChartDataModel> { new ChartDataModel("1995", 80 ), new ChartDataModel("1996", 200 ), new ChartDataModel("1997", 400 ), new ChartDataModel("1998", 600 ), new ChartDataModel("1999", 700 ), new ChartDataModel("2000", 1400 ), new ChartDataModel("2001", 2000 ), new ChartDataModel("2002", 4000 ), new ChartDataModel("2003", 6000 ), new ChartDataModel("2004", 8000 ), new ChartDataModel("2005", 11000) }; NumericData = new ObservableCollection<ChartDataModel> { new ChartDataModel(16, 2 ), new ChartDataModel(17, 14), new ChartDataModel(18, 7 ), new ChartDataModel(19, 7 ), new ChartDataModel(20, 10), }; NumericData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel(16, 7 ), new ChartDataModel(17, 7 ), new ChartDataModel(18, 11), new ChartDataModel(19, 8 ), new ChartDataModel(20, 24), }; DateTimeData = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2014, 02, 1), 10), new ChartDataModel(new DateTime(2015, 03, 2), 30), new ChartDataModel(new DateTime(2016, 04, 3), 15), new ChartDataModel(new DateTime(2017, 05, 4), 65), new ChartDataModel(new DateTime(2018, 06, 5), 90), new ChartDataModel(new DateTime(2019, 07, 5), 85) }; datas1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2010", 6), new ChartDataModel("2011", 15), new ChartDataModel("2012", 35), new ChartDataModel("2013", 65), new ChartDataModel("2014", 75) }; DataMarkerData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2013", 1110), new ChartDataModel("2014", 1130), new ChartDataModel("2015", 1153), new ChartDataModel("2016", 1175), }; DataMarkerData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("2013", 1070), new ChartDataModel("2014", 1105), new ChartDataModel("2015", 1138), new ChartDataModel("2016", 1155), }; SelectionData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 42), new ChartDataModel("Feb", 44), new ChartDataModel("Mar", 53), new ChartDataModel("Apr", 64), new ChartDataModel("May", 75), new ChartDataModel("Jun", 83) }; SelectionData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("Jan", 38), new ChartDataModel("Feb", 40), new ChartDataModel("Mar", 60), new ChartDataModel("Apr", 60), new ChartDataModel("May", 80), new ChartDataModel("Jun", 77) }; MultipleSeriesData1 = new ObservableCollection<ChartDataModel>(); for (var i = 1; i <= 12; i++) { MultipleSeriesData1.Add(new ChartDataModel(new DateTime(2014, i, 1), random.Next(10, 100))); } MultipleSeriesData2 = new ObservableCollection<ChartDataModel>(); for (var i = 1; i <= 12; i++) { MultipleSeriesData2.Add(new ChartDataModel(new DateTime(2014, i, 1), random.Next(10, 100))); } PieData = new ObservableCollection<ChartDataModel> { new ChartDataModel(new DateTime(2014, 1, 1), 48), new ChartDataModel(new DateTime(2014, 2, 1), 38), new ChartDataModel(new DateTime(2014, 3, 1), 28), new ChartDataModel(new DateTime(2014, 4, 1), 33), new ChartDataModel(new DateTime(2014, 5, 1), 25), new ChartDataModel(new DateTime(2014, 6, 1), 34) }; TriangularData = new ObservableCollection<ChartDataModel> { new ChartDataModel("Bentley", 800), new ChartDataModel("Audi", 810), new ChartDataModel("BMW", 825), new ChartDataModel("Jaguar", 860), new ChartDataModel("Skoda", 875) }; data = new ObservableCollection<ChartDataModel>(); LineSeries1 = new ObservableCollection<ChartDataModel>() { new ChartDataModel(new DateTime(2000, 2, 11), 15), new ChartDataModel(new DateTime(2000, 9, 14), 20), new ChartDataModel(new DateTime(2001, 2, 11), 25), new ChartDataModel(new DateTime(2001, 9, 16), 21), new ChartDataModel(new DateTime(2002, 2, 07), 13), new ChartDataModel(new DateTime(2002, 9, 07), 18), new ChartDataModel(new DateTime(2003, 2, 11), 24), new ChartDataModel(new DateTime(2003, 9, 14), 23), new ChartDataModel(new DateTime(2004, 2, 06), 19), new ChartDataModel(new DateTime(2004, 9, 06), 31), new ChartDataModel(new DateTime(2005, 2, 11), 39), new ChartDataModel(new DateTime(2005, 9, 11), 50), new ChartDataModel(new DateTime(2006, 2, 11), 24) }; LineSeries2 = new ObservableCollection<ChartDataModel>() { new ChartDataModel(new DateTime(2000, 2, 11), 39), new ChartDataModel(new DateTime(2000, 9, 14), 30), new ChartDataModel(new DateTime(2001, 2, 11), 28), new ChartDataModel(new DateTime(2001, 9, 16), 35), new ChartDataModel(new DateTime(2002, 2, 07), 39), new ChartDataModel(new DateTime(2002, 9, 07), 41), new ChartDataModel(new DateTime(2003, 2, 11), 45), new ChartDataModel(new DateTime(2003, 9, 14), 48), new ChartDataModel(new DateTime(2004, 2, 06), 54), new ChartDataModel(new DateTime(2004, 9, 06), 55), new ChartDataModel(new DateTime(2005, 2, 11), 57), new ChartDataModel(new DateTime(2005, 9, 11), 60), new ChartDataModel(new DateTime(2006, 2, 11), 60) }; LineSeries3 = new ObservableCollection<ChartDataModel>() { new ChartDataModel(new DateTime(2000, 2, 11), 60), new ChartDataModel(new DateTime(2000, 9, 14), 55), new ChartDataModel(new DateTime(2001, 2, 11), 48), new ChartDataModel(new DateTime(2001, 9, 16), 57), new ChartDataModel(new DateTime(2002, 2, 07), 62), new ChartDataModel(new DateTime(2002, 9, 07), 64), new ChartDataModel(new DateTime(2003, 2, 11), 57), new ChartDataModel(new DateTime(2003, 9, 14), 53), new ChartDataModel(new DateTime(2004, 2, 06), 63), new ChartDataModel(new DateTime(2004, 9, 06), 50), new ChartDataModel(new DateTime(2005, 2, 11), 66), new ChartDataModel(new DateTime(2005, 9, 11), 65), new ChartDataModel(new DateTime(2006, 2, 11), 79) }; TooltipData = new ObservableCollection<ChartDataModel>(); TooltipData.Add(new ChartDataModel("2007", 1.61)); TooltipData.Add(new ChartDataModel("2008", 2.34)); TooltipData.Add(new ChartDataModel("2009", 2.16)); TooltipData.Add(new ChartDataModel("2010", 2.1)); TooltipData.Add(new ChartDataModel("2011", 1.61)); TooltipData.Add(new ChartDataModel("2012", 2.05)); TooltipData.Add(new ChartDataModel("2013", 2.5)); TooltipData.Add(new ChartDataModel("2014", 2.21)); TooltipData.Add(new ChartDataModel("2015", 2.34)); } public void LoadData() { for (int i = 1; i <= 30; i++) { NSNumber value = new NSNumber(random.Next(0, 9)); data.Add(new ChartDataModel(i, (double)value)); wave1++; } } public ChartDataModel dataPointWithTimeInterval(double time) { int count = verticalCount; NSNumber value; if (count > 320) { value = random.Next(0, 0); } else if (count > 280) { value = random.Next(-2, 2); } else if (count > 240) { value = random.Next(-3, 3); } else if (count > 200) { value = random.Next(-5, 5); } else if (count > 180) { value = random.Next(-6, 6); } else if (count > 120) { value = random.Next(-7, 7); } else if (count > 30) { value = random.Next(-9, 9); } else { value = random.Next(-3, 3); } date = date.AddSeconds(time); ChartDataModel datapoint = new ChartDataModel(); datapoint.XValue = date; datapoint.YValue = (double)value; return datapoint; } private void addWeek() { dataTime = dataTime.AddDays(7); } public static ObservableCollection<ChartDataModel> GetTrendlineDataSource1() { var yValue = new double[] { 10.11, 11.36, 12.34, 12.60, 12.95, 13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36, 41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41, 48.32, 45.65, 46.61, 53.34, 58.53, 59.02, 59.32, 61.24, 62.32, 62.43, 64.86, 63.42, 65.93, 66.99, 67.02, 68.43, 71.01 }; DateTime date = new DateTime(1977, 01, 02); var datas = new ObservableCollection<ChartDataModel>(); foreach (var y in yValue) { datas.Add(new ChartDataModel(date, y)); date = date.AddYears(1); } return datas; } public static ObservableCollection<ChartDataModel> GetTrendlineDataSource2() { var powerData = new ObservableCollection<ChartDataModel>(); powerData.Add(new ChartDataModel(1, 10)); powerData.Add(new ChartDataModel(2, 50)); powerData.Add(new ChartDataModel(3, 80)); powerData.Add(new ChartDataModel(4, 110)); powerData.Add(new ChartDataModel(5, 180)); powerData.Add(new ChartDataModel(6, 220)); powerData.Add(new ChartDataModel(7, 300)); powerData.Add(new ChartDataModel(8, 370)); powerData.Add(new ChartDataModel(9, 490)); powerData.Add(new ChartDataModel(10, 500)); return powerData; } } } <file_sep>/Forms/PopupLayout/PopupLayout/Samples/OnBoardHelps/ResizingBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "ResizingBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPopupLayout { using Xamarin.Forms; /// <summary> /// Resizing Behavior class performs resizing animation. /// </summary> public class ResizingBehavior : Behavior<Image> { /// <summary> /// Holds the resizing illustration image. /// </summary> private Image resizingIllustrationImage; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="image">Image which is attached.</param> protected override void OnAttachedTo(Image image) { base.OnAttachedTo(image); this.resizingIllustrationImage = image; this.AnimateResizingIllustrationImage(); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="image">Image which is attached.</param> protected override void OnDetachingFrom(Image image) { base.OnDetachingFrom(image); this.resizingIllustrationImage = null; } /// <summary> /// Used to for animate the resizing illustration image. /// </summary> private async void AnimateResizingIllustrationImage() { // Move to left xposition await this.resizingIllustrationImage.TranslateTo(100, 0, 1000); //// Move to initial xposition await this.resizingIllustrationImage.TranslateTo(0, 0, 0); this.AnimateResizingIllustrationImage(); } } }<file_sep>/iOS/SampleBrowser/Samples/PullToRefresh/PullToRefreshDemo Helper/WeatherView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Foundation; using UIKit; namespace SampleBrowser { public class WeatherView : UIView { internal WeatherModel model; UILabel label; UIImageView image; UILabel label1; internal BaseView baseView; public WeatherView(CGRect frame) : base(frame) { UITapGestureRecognizer gesture = new UITapGestureRecognizer(); // Wire up the event handler (have to use a selector) gesture.AddTarget(() => imageViewTapped(gesture)); AddGestureRecognizer(gesture); } internal void selectView() { label.TextColor = label1.TextColor = UIColor.FromRGBA(0.984f,0.69f,0.231f,1); image.Image = new UIImage(model.Type.ToString().Replace(".","-selected.")); } internal void unSelectView() { label.TextColor = label1.TextColor = UIColor.White; image.Image = new UIImage(model.Type); } internal void updateTemp() { label1.Text = (NSString)model.Temp.ToString() + "°"; } void imageViewTapped(UITapGestureRecognizer gr) { baseView.model = model; baseView.updateBaseView(); selectView(); if (baseView.selectedView != null) { baseView.selectedView.unSelectView(); } baseView.selectedView = this; } internal void drawView() { label = new UILabel(new CGRect(0, -15, Frame.Width, 30)); label.TextColor = UIColor.White; label.Font = UIFont.SystemFontOfSize(12); label.TextAlignment = UITextAlignment.Center; label.Text = model.Day; image = new UIImageView(); image.Image = new UIImage(model.Type); image.Frame = new CGRect(12, 25, 75, 50); AddSubview(label); AddSubview(image); label1 = new UILabel(new CGRect(0, 80, Frame.Width, 30)); label1.TextColor = UIColor.White; label1.Font = UIFont.SystemFontOfSize(12); label1.TextAlignment = UITextAlignment.Center; label1.Text = (NSString)model.Temp.ToString() + "°"; AddSubview(label1); } } } <file_sep>/Forms/Schedule/Schedule/Samples/ViewCustomization/HelperClass/AgendaViewItemTemplateSelector.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Globalization; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// AgendaViewItem Template Selector class /// </summary> [Preserve(AllMembers = true)] public class AgendaViewItemTemplateSelector : DataTemplateSelector { /// <summary> /// Initializes a new instance of the <see cref="AgendaViewItemTemplateSelector" /> class. /// </summary> public AgendaViewItemTemplateSelector() { this.AgendaViewItemTemplate = new DataTemplate(typeof(AgendaViewItemTemplate)); } /// <summary> /// Gets or sets Appointment Template /// </summary> public DataTemplate AgendaViewItemTemplate { get; set; } /// <summary> /// Template method /// </summary> /// <param name="item">return the object</param> /// <param name="container">return the bindable object</param> /// <returns>return the template</returns> protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { var schedule = container as Syncfusion.SfSchedule.XForms.SfSchedule; if (schedule == null) { return null; } if (!(item as ScheduleAppointment).IsAllDay) return this.AgendaViewItemTemplate; return null; } } /// <summary> /// Image format convertor method /// </summary> public class ImageConverter : IValueConverter { /// <summary> /// Convert method /// </summary> /// <param name="value">return the object</param> /// <param name="targetType">return the target type value</param> /// <param name="parameter">return the object</param> /// <param name="culture">return the culture value</param> /// <returns>return the value</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var subject = value.ToString(); if (subject == "Conference") return "Conference_schedule.png"; else if (subject == "Checkup") return "Stethoscope.png"; else if (subject == "System Troubleshoot") return "Troubleshoot.png"; else if (subject == "Jeni's Birthday") return "cake_schedule.png"; return value; } /// <summary> /// Convert back method /// </summary> /// <param name="value">return the object</param> /// <param name="targetType"> return the target type value</param> /// <param name="parameter">return the object</param> /// <param name="culture">return the culture value</param> /// <returns>return the value</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } } <file_sep>/Forms/ListView/ListView/Samples/GettingStarted/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Syncfusion.ListView.XForms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewGettingStartedViewModel { #region Fields private ObservableCollection<ListViewShoppingCategoryInfo> categoryInfo; #endregion #region Constructor public ListViewGettingStartedViewModel() { GenerateSource(); } #endregion #region Properties public ObservableCollection<ListViewShoppingCategoryInfo> CategoryInfo { get { return categoryInfo; } set { this.categoryInfo = value; } } #endregion #region Generate Source private void GenerateSource() { ShoppingCategoryInfoRepository categoryinfo = new ShoppingCategoryInfoRepository(); categoryInfo = categoryinfo.GetCategoryInfo(); } #endregion } } <file_sep>/iOS/SampleBrowser/Samples/XlsIO/Performance.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XlsIO; using System.IO; using COLOR = Syncfusion.Drawing; using Syncfusion.iOS.Buttons; using Syncfusion.iOS.MaskedEdit; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { class Performance : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UILabel label1; UILabel label2; UILabel label3; SfCheckBox importCheck; SfMaskedEdit textBox1; SfMaskedEdit textBox2; UIButton button; public Performance() { label = new UILabel(); label1 = new UILabel(); label2 = new UILabel(); label3 = new UILabel(); button = new UIButton(UIButtonType.System); textBox1 = new SfMaskedEdit(); textBox2 = new SfMaskedEdit(); importCheck = new SfCheckBox(); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates the performance of Syncfusion XlsIO library to create larger Excel files."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.SizeToFit(); label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } else { label.Frame = new CGRect(5, 5, frameRect.Size.Width, 70); } this.AddSubview(label); label2.Frame = new CGRect(10, 80, 300, 17); label2.Text = "Enter the no. of rows"; label2.Font = UIFont.SystemFontOfSize(14); label2.Lines = 0; label2.SizeToFit(); label2.LineBreakMode = UILineBreakMode.WordWrap; this.AddSubview(label2); textBox1.Value = 5000; textBox1.Frame = new CGRect(10, 100, 250, 20); this.AddSubview(textBox1); label3.Frame = new CGRect(10, 130, 300, 17); label3.Text = "Enter the no. of columns"; label3.Font = UIFont.SystemFontOfSize(14); label3.Lines = 0; label3.SizeToFit(); label3.LineBreakMode = UILineBreakMode.WordWrap; this.AddSubview(label3); textBox2.Value = 50; textBox2.Frame = new CGRect(10, 150, 250, 20); this.AddSubview(textBox2); importCheck.Frame = new CGRect(10, 180, 200, 20); importCheck.Font = UIFont.SystemFontOfSize(14); importCheck.CornerRadius = 5.0f; importCheck.SetTitle("Import on Save", UIControlState.Normal); this.AddSubview(importCheck); label1.Frame = new CGRect(10, 210, 300, 17); label1.Text = "Import on Save option directly serialize data while saving the workbook."; label1.Font = UIFont.SystemFontOfSize(12); label1.Lines = 0; label1.SizeToFit(); label1.LineBreakMode = UILineBreakMode.WordWrap; this.AddSubview(label1); button.SetTitle("Generate Excel", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect(0, 240, frameRect.Location.X + frameRect.Size.Width, 10); } else { button.Frame = new CGRect(5, 255, frameRect.Size.Width, 10); } this.AddSubview(button); } void OnButtonClicked(object sender, EventArgs e) { int rowCount = Convert.ToInt32(textBox1.Value); int colCount = Convert.ToInt32(textBox2.Value); //Step 1 : Instantiate the spreadsheet creation engine. ExcelEngine excelEngine = new ExcelEngine(); //Step 2 : Instantiate the excel application object. IApplication application = excelEngine.Excel; IWorkbook workbook; workbook = application.Workbooks.Create(1); IWorksheet sheet = workbook.Worksheets[0]; if (this.importCheck.IsChecked.Value) { workbook.Version = ExcelVersion.Excel2013; System.Data.DataTable dataTable = new System.Data.DataTable(); for (int column = 1; column <= colCount; column++) { dataTable.Columns.Add("Column: " + column.ToString(), typeof(int)); } //Adding data into data table for (int row = 1; row < rowCount; row++) { dataTable.Rows.Add(); for (int column = 1; column <= colCount; column++) { dataTable.Rows[row - 1][column - 1] = row * column; } } sheet.ImportDataTable(dataTable, 1, 1, true, true); } else { IMigrantRange migrantRange = sheet.MigrantRange; for (int column = 1; column <= colCount; column++) { migrantRange.ResetRowColumn(1, column); migrantRange.SetValue("Column: " + column.ToString()); } //Writing Data using normal interface for (int row = 2; row <= rowCount; row++) { //double columnSum = 0.0; for (int column = 1; column <= colCount; column++) { //Writing number migrantRange.ResetRowColumn(row, column); migrantRange.SetValue(row * column); } } } workbook.Version = ExcelVersion.Excel2013; MemoryStream stream = new MemoryStream(); workbook.SaveAs(stream); workbook.Close(); excelEngine.Dispose(); if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("CreateSheet.xlsx", "application/msexcel", stream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } } }<file_sep>/Forms/RadialMenu/RadialMenu.Android/MainActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Xamarin.Forms; using Android.Content; namespace SampleBrowser.SfRadialMenu.Droid { [Activity(Label = "SampleBrowser SfRadialMenu", MainLauncher = false, Icon = "@drawable/AppIcon", Theme = "@style/MainTheme", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { double statusBarHeight, navbarheight; protected override void OnCreate(Bundle bundle) { int navigationResID = Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (navigationResID > 0) { navbarheight = (Resources.GetDimensionPixelSize(navigationResID) / Resources.DisplayMetrics.Density); } int statusResID = Resources.GetIdentifier("status_bar_height", "dimen", "android"); if (statusResID > 0) { statusBarHeight = (Resources.GetDimensionPixelSize(statusResID) / Resources.DisplayMetrics.Density); } SetScreenSize((Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density), (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density)); TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); SampleBrowser.Core.Droid.CoreSampleBrowser.Init(Resources, null); LoadApplication(new App()); } public event EventHandler<ActivityResultEventArgs> ActivityResult; protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { if (resultCode == Result.Ok) { if (ActivityResult != null) ActivityResult(this, new ActivityResultEventArgs { Intent = data }); } } public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig) { base.OnConfigurationChanged(newConfig); if (newConfig.Orientation == Android.Content.Res.Orientation.Landscape) { SetScreenSize((Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density), (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density)); if (Device.Idiom == TargetIdiom.Phone) RequestedOrientation = ScreenOrientation.Portrait; else if (Device.Idiom == TargetIdiom.Tablet) { RequestedOrientation = ScreenOrientation.FullSensor; } } else if (newConfig.Orientation == Android.Content.Res.Orientation.Portrait) { SetScreenSize((Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density), (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density)); if (Device.Idiom == TargetIdiom.Phone) RequestedOrientation = ScreenOrientation.Portrait; else if (Device.Idiom == TargetIdiom.Tablet) RequestedOrientation = ScreenOrientation.FullSensor; } } void SetScreenSize(double width, double height) { App.StatusBarHeight = statusBarHeight; App.NavigationBarHeight = navbarheight; App.ScreenWidth = width; App.ScreenHeight = height - (statusBarHeight + navbarheight); App.Platform = Platforms.Android; App.Density = Resources.DisplayMetrics.Density; } } public class ActivityResultEventArgs : EventArgs { public Intent Intent { get; set; } } } <file_sep>/iOS/SampleBrowser/Samples/Maps/Drilldown.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Syncfusion.SfBusyIndicator.iOS; #endregion using System; using Syncfusion.SfMaps.iOS; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Drawing; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGPoint= System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class Drilldown : SampleView { internal SfBusyIndicator busyindicator; UIView view; internal UILabel label; internal UIButton button; internal UILabel label1; internal UILabel label3; internal UILabel header; internal SFMap maps; internal SFShapeFileLayer layer; internal UIView layout; bool isDisposed; public override void LayoutSubviews() { view.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X, 0, Frame.Size.Width, Frame.Size.Height); header.Frame = new CGRect(Frame.Location.X, Frame.Size.Height - 50, Frame.Size.Width , 50); SetNeedsDisplay(); } protected override void Dispose(bool disposing) { isDisposed = true; base.Dispose(disposing); } public Drilldown() { maps = new SFMap(); maps.EnableZooming = false; view = new UIView(); view.Frame = new CGRect(0, 0, 300, 400); busyindicator = new SfBusyIndicator(); busyindicator.ViewBoxWidth = 75; busyindicator.ViewBoxHeight = 75; busyindicator.Foreground = UIColor.FromRGB(0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType = SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; layout = new UIView(); layout.Frame = new CGRect(0, 0, 300, 50); button = new UIButton(); button.Frame = new CGRect(0, 0, 100, 50); button.TouchUpInside += Button_TouchUpInside; button.BackgroundColor = UIColor.Clear; button.UserInteractionEnabled = true; button.Hidden = true; view.AddSubview(button); label = new UILabel(); label.TextAlignment = UITextAlignment.Center; label.Text = "World Map"; label.TextColor = UIColor.Blue; label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(0, 0, 100, 50); layout.AddSubview(label); label1 = new UILabel(); label1.TextAlignment = UITextAlignment.Center; label1.Text = " >> "; label1.Font = UIFont.SystemFontOfSize(18); label1.Frame = new CGRect(80, 0, 50, 50); layout.AddSubview(label1); label3 = new UILabel(); label3.TextAlignment = UITextAlignment.Left; label3.Font = UIFont.SystemFontOfSize(18); label3.Frame = new CGRect(120, 0, 150, 50); layout.AddSubview(label3); layout.Hidden = true; AddSubview(layout); header = new UILabel(); header.TextAlignment = UITextAlignment.Center; header.Text = "Click on a shape to drill"; header.Font = UIFont.SystemFontOfSize(18); header.TextAlignment = UITextAlignment.Center; view.AddSubview(header); NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(0.3), delegate { if (isDisposed) return; maps.Frame = new CGRect(Frame.Location.X, 60, Frame.Size.Width - 6, Frame.Size.Height - 60); view.AddSubview(maps); }); layer = new SFShapeFileLayer(); layer.Uri = (NSString)NSBundle.MainBundle.PathForResource("world-map", "shp"); layer.ShapeIDPath = (NSString)"country"; layer.ShapeIDTableField = (NSString)"admin"; layer.ShowMapItems = true; layer.EnableSelection = true; layer.DataSource = GetDataSource(); SFShapeSetting shapeSettings = new SFShapeSetting(); shapeSettings.ColorValuePath = (NSString)"continent"; SetColorMapping(shapeSettings); layer.ShapeSettings = shapeSettings; ObservableCollection<SFMapMarker> markers = new ObservableCollection<SFMapMarker>(); LabelMarker marker1 = new LabelMarker(); marker1.Name = (NSString)"Asia"; marker1.Latitude = 63.34303378997662; marker1.Longitude = 102.07617561287645; markers.Add(marker1); LabelMarker marker2 = new LabelMarker(); marker2.Name = (NSString)"Australia"; marker2.Latitude = -25.74775493367931; marker2.Longitude = 136.80451417932431; markers.Add(marker2); LabelMarker marker3 = new LabelMarker(); marker3.Name = (NSString)"Africa"; marker3.Latitude = 19.025302093442327; marker3.Longitude = 15.157534554671087; markers.Add(marker3); LabelMarker marker4 = new LabelMarker(); marker4.Name = (NSString)"North America"; marker4.Latitude = 59.88893689676585; marker4.Longitude = -109.3359375; markers.Add(marker4); LabelMarker marker5 = new LabelMarker(); marker5.Name = (NSString)"Europe"; marker5.Latitude = 47.95121990866204; marker5.Longitude = 18.468749999999998; markers.Add(marker5); LabelMarker marker6 = new LabelMarker(); marker6.Name = (NSString)"South America"; marker6.Latitude = -6.64607562172573; marker6.Longitude = -55.54687499999999; markers.Add(marker6); layer.Markers = markers; layer.ShapeSelectionChanged += DrilldownSelectionChanged; SFShapeFileLayer layer1 = new SFShapeFileLayer(); layer1.Uri = (NSString)NSBundle.MainBundle.PathForResource("south-america", "shp"); layer1.ShapeIDPath = (NSString)"country"; layer1.ShapeIDTableField = (NSString)"admin"; SFShapeSetting shapeSettings1 = new SFShapeSetting(); shapeSettings1.Fill = UIColor.FromRGB(156, 51, 103); layer1.ShapeSettings = shapeSettings1; SFShapeFileLayer layer2 = new SFShapeFileLayer(); layer2.Uri = (NSString)NSBundle.MainBundle.PathForResource("north-america", "shp"); layer2.ShapeIDPath = (NSString)"country"; layer2.ShapeIDTableField = (NSString)"admin"; SFShapeSetting shapeSettings2 = new SFShapeSetting(); shapeSettings2.Fill = UIColor.FromRGB(193, 54, 100); layer2.ShapeSettings = shapeSettings2; SFShapeFileLayer layer3 = new SFShapeFileLayer(); layer3.Uri = (NSString)NSBundle.MainBundle.PathForResource("europe", "shp"); layer3.ShapeIDPath = (NSString)"country"; layer3.ShapeIDTableField = (NSString)"admin"; SFShapeSetting shapeSettings3 = new SFShapeSetting(); shapeSettings3.Fill = UIColor.FromRGB(98, 45, 108); layer3.ShapeSettings = shapeSettings3; SFShapeFileLayer layer4 = new SFShapeFileLayer(); layer4.Uri = (NSString)NSBundle.MainBundle.PathForResource("africa", "shp"); layer4.ShapeIDPath = (NSString)"country"; layer4.ShapeIDTableField = (NSString)"admin"; SFShapeSetting shapeSettings4 = new SFShapeSetting(); shapeSettings4.Fill = UIColor.FromRGB(128, 48, 106); layer4.ShapeSettings = shapeSettings4; SFShapeFileLayer layer5 = new SFShapeFileLayer(); layer5.Uri = (NSString)NSBundle.MainBundle.PathForResource("australia", "shp"); layer5.ShapeIDPath = (NSString)"country"; layer5.ShapeIDTableField = (NSString)"admin"; SFShapeSetting shapeSettings5 = new SFShapeSetting(); shapeSettings5.Fill = UIColor.FromRGB(42, 40, 112); layer5.ShapeSettings = shapeSettings5; SFShapeFileLayer layer6 = new SFShapeFileLayer(); layer6.Uri = (NSString)NSBundle.MainBundle.PathForResource("asia", "shp"); layer6.ShapeIDPath = (NSString)"country"; layer6.ShapeIDTableField = (NSString)"admin"; SFShapeSetting shapeSettings6 = new SFShapeSetting(); shapeSettings6.Fill = UIColor.FromRGB(70, 42, 109); layer6.ShapeSettings = shapeSettings6; maps.Layers.Add(layer); maps.Layers.Add(layer1); maps.Layers.Add(layer2); maps.Layers.Add(layer3); maps.Layers.Add(layer4); maps.Layers.Add(layer5); maps.Layers.Add(layer6); AddSubview(view); } void DrilldownSelectionChanged(object sender, ShapeSelectedEventArgs args)
 {
 if (args.Data != null)
 {
 NSDictionary dic = (NSDictionary)args.Data;
 NSString continent = (NSString)(dic["continent"]);
 label3.Text = continent;
 header.Hidden = true;
 layout.Hidden = false;
 button.Hidden = false;
 if (continent == "South America")
 {
 maps.BaseMapIndex = 1;
 layer.ShapeSettings.SelectedShapeColor = UIColor.FromRGB(156, 51, 103);
 }
 else if (continent == "North America")
 {
 maps.BaseMapIndex = 2;
 layer.ShapeSettings.SelectedShapeColor = UIColor.FromRGB(193, 54, 100);
 }
 else if (continent == "Europe")
 {
 maps.BaseMapIndex = 3;
 layer.ShapeSettings.SelectedShapeColor = UIColor.FromRGB(98, 45, 108);
 }
 else if (continent == "Africa")
 {
 maps.BaseMapIndex = 4;
 layer.ShapeSettings.SelectedShapeColor = UIColor.FromRGB(128, 48, 106);
 }
 else if (continent == "Australia")
 {
 maps.BaseMapIndex = 5;
 layer.ShapeSettings.SelectedShapeColor = UIColor.FromRGB(42, 40, 112);
 }
 else if (continent == "Asia")
 {
 maps.BaseMapIndex = 6;
 layer.ShapeSettings.SelectedShapeColor = UIColor.FromRGB(70, 42, 109);
 }
 }
 }

 void Button_TouchUpInside(object sender, EventArgs e) { maps.BaseMapIndex = 0; header.Hidden = false; layout.Hidden = true; button.Hidden = true; } NSMutableArray GetDataSource() { NSMutableArray data = new NSMutableArray(); data.Add(getDictionary("Afghanistan", "Asia")); data.Add(getDictionary("Angola", "Africa")); data.Add(getDictionary("Albania", "Europe")); data.Add(getDictionary("United Arab Emirates", "Asia")); data.Add(getDictionary("Argentina", "South America")); data.Add(getDictionary("Armenia", "Asia")); data.Add(getDictionary("French Southern and Antarctic Lands", "Seven seas (open ocean)")); data.Add(getDictionary("Australia", "Australia")); data.Add(getDictionary("Austria", "Europe")); data.Add(getDictionary("Azerbaijan", "Asia")); data.Add(getDictionary("Burundi", "Africa")); data.Add(getDictionary("Belgium", "Europe")); data.Add(getDictionary("Benin", "Africa")); data.Add(getDictionary("Burkina Faso", "Africa")); data.Add(getDictionary("Bangladesh", "Asia")); data.Add(getDictionary("Bulgaria", "Europe")); data.Add(getDictionary("The Bahamas", "North America")); data.Add(getDictionary("Bosnia and Herzegovina", "Europe")); data.Add(getDictionary("Belarus", "Europe")); data.Add(getDictionary("Belize", "North America")); data.Add(getDictionary("Bolivia", "South America")); data.Add(getDictionary("Brazil", "South America")); data.Add(getDictionary("Brunei", "Asia")); data.Add(getDictionary("Bhutan", "Asia")); data.Add(getDictionary("Botswana", "Africa")); data.Add(getDictionary("Central African Republic", "Africa")); data.Add(getDictionary("Canada", "North America")); data.Add(getDictionary("Switzerland", "Europe")); data.Add(getDictionary("Chile", "South America")); data.Add(getDictionary("China", "Asia")); data.Add(getDictionary("Ivory Coast", "Africa")); data.Add(getDictionary("Cameroon", "Africa")); data.Add(getDictionary("Democratic Republic of the Congo", "Africa")); data.Add(getDictionary("Republic of Congo", "Africa")); data.Add(getDictionary("Colombia", "South America")); data.Add(getDictionary("Costa Rica", "North America")); data.Add(getDictionary("Cuba", "North America")); data.Add(getDictionary("Northern Cyprus", "Asia")); data.Add(getDictionary("Cyprus", "Asia")); data.Add(getDictionary("Czech Republic", "Europe")); data.Add(getDictionary("Germany", "Europe")); data.Add(getDictionary("Djibouti", "Africa")); data.Add(getDictionary("Denmark", "Europe")); data.Add(getDictionary("Dominican Republic", "North America")); data.Add(getDictionary("Algeria", "Africa")); data.Add(getDictionary("Ecuador", "South America")); data.Add(getDictionary("Egypt", "Africa")); data.Add(getDictionary("Eritrea", "Africa")); data.Add(getDictionary("Spain", "Europe")); data.Add(getDictionary("Estonia", "Europe")); data.Add(getDictionary("Ethiopia", "Africa")); data.Add(getDictionary("Finland", "Europe")); data.Add(getDictionary("Fiji", "Australia")); data.Add(getDictionary("Falkland Islands", "South America")); data.Add(getDictionary("France", "Europe")); data.Add(getDictionary("Gabon", "Africa")); data.Add(getDictionary("United Kingdom", "Europe")); data.Add(getDictionary("Georgia", "Asia")); data.Add(getDictionary("Ghana", "Africa")); data.Add(getDictionary("Guinea", "Africa")); data.Add(getDictionary("Gambia", "Africa")); data.Add(getDictionary("Guinea Bissau", "Africa")); data.Add(getDictionary("Equatorial Guinea", "Africa")); data.Add(getDictionary("Greece", "Europe")); data.Add(getDictionary("Greenland", "North America")); data.Add(getDictionary("Guatemala", "North America")); data.Add(getDictionary("Guyana", "South America")); data.Add(getDictionary("Honduras", "North America")); data.Add(getDictionary("Croatia", "Europe")); data.Add(getDictionary("Haiti", "North America")); data.Add(getDictionary("Hungary", "Europe")); data.Add(getDictionary("Indonesia", "Asia")); data.Add(getDictionary("India", "Asia")); data.Add(getDictionary("Ireland", "Europe")); data.Add(getDictionary("Iran", "Asia")); data.Add(getDictionary("Iraq", "Asia")); data.Add(getDictionary("Iceland", "Europe")); data.Add(getDictionary("Israel", "Asia")); data.Add(getDictionary("Italy", "Europe")); data.Add(getDictionary("Jamaica", "North America")); data.Add(getDictionary("Jordan", "Asia")); data.Add(getDictionary("Japan", "Asia")); data.Add(getDictionary("Kazakhstan", "Asia")); data.Add(getDictionary("Kenya", "Africa")); data.Add(getDictionary("Kyrgyzstan", "Asia")); data.Add(getDictionary("Cambodia", "Asia")); data.Add(getDictionary("South Korea", "Asia")); data.Add(getDictionary("Kosovo", "Europe")); data.Add(getDictionary("Kuwait", "Asia")); data.Add(getDictionary("Laos", "Asia")); data.Add(getDictionary("Lebanon", "Asia")); data.Add(getDictionary("Liberia", "Africa")); data.Add(getDictionary("Libya", "Africa")); data.Add(getDictionary("Sri Lanka", "Asia")); data.Add(getDictionary("Lesotho", "Africa")); data.Add(getDictionary("Lithuania", "Europe")); data.Add(getDictionary("Luxembourg", "Europe")); data.Add(getDictionary("Latvia", "Europe")); data.Add(getDictionary("Morocco", "Africa")); data.Add(getDictionary("Moldova", "Europe")); data.Add(getDictionary("Madagascar", "Africa")); data.Add(getDictionary("Mexico", "North America")); data.Add(getDictionary("Macedonia", "Europe")); data.Add(getDictionary("Mali", "Africa")); data.Add(getDictionary("Myanmar", "Asia")); data.Add(getDictionary("Montenegro", "Europe")); data.Add(getDictionary("Mongolia", "Asia")); data.Add(getDictionary("Mozambique", "Africa")); data.Add(getDictionary("Mauritania", "Africa")); data.Add(getDictionary("Malawi", "Africa")); data.Add(getDictionary("Malaysia", "Asia")); data.Add(getDictionary("Namibia", "Africa")); data.Add(getDictionary("New Caledonia", "Australia")); data.Add(getDictionary("Niger", "Africa")); data.Add(getDictionary("Nigeria", "Africa")); data.Add(getDictionary("Nicaragua", "North America")); data.Add(getDictionary("Netherlands", "Europe")); data.Add(getDictionary("Norway", "Europe")); data.Add(getDictionary("Nepal", "Asia")); data.Add(getDictionary("New Zealand", "Australia")); data.Add(getDictionary("Oman", "Asia")); data.Add(getDictionary("Pakistan", "Asia")); data.Add(getDictionary("Panama", "North America")); data.Add(getDictionary("Peru", "South America")); data.Add(getDictionary("Philippines", "Asia")); data.Add(getDictionary("Papua New Guinea", "Australia")); data.Add(getDictionary("Poland", "Europe")); data.Add(getDictionary("Puerto Rico", "North America")); data.Add(getDictionary("North Korea", "Asia")); data.Add(getDictionary("Portugal", "Europe")); data.Add(getDictionary("Paraguay", "South America")); data.Add(getDictionary("Palestine", "Asia")); data.Add(getDictionary("Qatar", "Asia")); data.Add(getDictionary("Romania", "Europe")); data.Add(getDictionary("Russia", "Asia")); data.Add(getDictionary("Rwanda", "Africa")); data.Add(getDictionary("Western Sahara", "Africa")); data.Add(getDictionary("Saudi Arabia", "Asia")); data.Add(getDictionary("Sudan", "Africa")); data.Add(getDictionary("South Sudan", "Africa")); data.Add(getDictionary("Senegal", "Africa")); data.Add(getDictionary("Solomon Islands", "Australia")); data.Add(getDictionary("Sierra Leone", "Africa")); data.Add(getDictionary("El Salvador", "North America")); data.Add(getDictionary("Somaliland", "Africa")); data.Add(getDictionary("Somalia", "Africa")); data.Add(getDictionary("Republic of Serbia", "Europe")); data.Add(getDictionary("Suriname", "South America")); data.Add(getDictionary("Slovakia", "Europe")); data.Add(getDictionary("Slovenia", "Europe")); data.Add(getDictionary("Sweden", "Europe")); data.Add(getDictionary("Swaziland", "Africa")); data.Add(getDictionary("Syria", "Asia")); data.Add(getDictionary("Chad", "Africa")); data.Add(getDictionary("Togo", "Africa")); data.Add(getDictionary("Thailand", "Asia")); data.Add(getDictionary("Tajikistan", "Asia")); data.Add(getDictionary("Turkmenistan", "Asia")); data.Add(getDictionary("East Timor", "Asia")); data.Add(getDictionary("Trinidad and Tobago", "North America")); data.Add(getDictionary("Tunisia", "Africa")); data.Add(getDictionary("Turkey", "Asia")); data.Add(getDictionary("Taiwan", "Asia")); data.Add(getDictionary("United Republic of Tanzania", "Africa")); data.Add(getDictionary("Uganda", "Africa")); data.Add(getDictionary("Ukraine", "Europe")); data.Add(getDictionary("Uruguay", "South America")); data.Add(getDictionary("United States of America", "North America")); data.Add(getDictionary("Uzbekistan", "Asia")); data.Add(getDictionary("Venezuela", "South America")); data.Add(getDictionary("Vietnam", "Asia")); data.Add(getDictionary("Vanuatu", "Australia")); data.Add(getDictionary("Yemen", "Asia")); data.Add(getDictionary("South Africa", "Africa")); data.Add(getDictionary("Zambia", "Africa")); data.Add(getDictionary("Zimbabwe", "Africa")); return data; } NSDictionary getDictionary(string country, string continent) { NSString name1 = (NSString)country; NSString name2 = (NSString)continent; object[] objects = new object[2]; object[] keys = new object[2]; keys.SetValue("country", 0); keys.SetValue("continent", 1); objects.SetValue(name1, 0); objects.SetValue(name2, 1); return NSDictionary.FromObjectsAndKeys(objects, keys); } void SetColorMapping(SFShapeSetting setting) { ObservableCollection<SFMapColorMapping> colorMappings = new ObservableCollection<SFMapColorMapping>(); SFEqualColorMapping colorMapping1 = new SFEqualColorMapping(); colorMapping1.Value = (NSString)"North America"; colorMapping1.Color = UIColor.FromRGB(193, 54, 100); colorMappings.Add(colorMapping1); SFEqualColorMapping colorMapping2 = new SFEqualColorMapping(); colorMapping2.Value = (NSString)"South America"; colorMapping2.Color = UIColor.FromRGB(156, 51, 103); colorMappings.Add(colorMapping2); SFEqualColorMapping colorMapping3 = new SFEqualColorMapping(); colorMapping3.Value = (NSString)"Africa"; colorMapping3.Color = UIColor.FromRGB(128, 48, 106); colorMappings.Add(colorMapping3); SFEqualColorMapping colorMapping4 = new SFEqualColorMapping(); colorMapping4.Value = (NSString)"Europe"; colorMapping4.Color = UIColor.FromRGB(98, 45, 108); colorMappings.Add(colorMapping4); SFEqualColorMapping colorMapping5 = new SFEqualColorMapping(); colorMapping5.Value = (NSString)"Asia"; colorMapping5.Color = UIColor.FromRGB(70, 42, 109); colorMappings.Add(colorMapping5); SFEqualColorMapping colorMapping6 = new SFEqualColorMapping(); colorMapping6.Value = (NSString)"Australia"; colorMapping6.Color = UIColor.FromRGB(42, 40, 112); colorMappings.Add(colorMapping6); setting.ColorMappings = colorMappings; } } public class LabelMarker : SFMapMarker { public string Name; public LabelMarker() { } public override UIView GetView(CGPoint point) { UIView view = new UIView(); view.Frame = new CGRect(point.X - 50, point.Y - 15, 100, 50); int y = 0; var labels = Name.Split(' ', '\t'); for (int j = 0; j < labels.Length; j++) { UILabel labelView = new UILabel(new CGRect(0, y, 100, 20)); labelView.TextAlignment = UITextAlignment.Center; labelView.Text = labels[j]; labelView.TextColor = UIColor.FromRGB(190, 232, 162); labelView.Font = UIFont.SystemFontOfSize(12); view.AddSubview(labelView); y += 20; } return view; } } } <file_sep>/Android/SampleBrowser/Samples/ComboBox/ComboBox.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Util; using System; using Android.Views; using SampleBrowser; using Android.Widget; using Android.Graphics; using Syncfusion.Android.ComboBox; using System.Collections.Generic; namespace SampleBrowser { public class ComboBox : SamplePage { public ComboBox() { } LinearLayout mainLayout; public override View GetSampleContent(Android.Content.Context con) { SamplePageContents(con); ControlPageContents(con); mainLayout = new LinearLayout(con); mainLayout.SetPadding(20, 20, 20, 30); mainLayout.Orientation = Orientation.Vertical; mainLayout.FocusableInTouchMode = true; mainLayout.AddView(scaleLabel); mainLayout.AddView(scaleLabelSpacing); mainLayout.AddView(sizeLabel); mainLayout.AddView(sizeComboBox); mainLayout.AddView(sizeLabelSpacing); mainLayout.AddView(resolutionLabelSpacing); mainLayout.AddView(resolutionLabel); mainLayout.AddView(resolutionComboBox); mainLayout.AddView(controlSpacing1); mainLayout.AddView(controlSpacing2); mainLayout.AddView(orientationLabel); mainLayout.AddView(orientationComboBox); mainLayout.AddView(orientationLabelSpacing); return mainLayout; } public override View GetPropertyWindowLayout(Android.Content.Context context) { Editable(context); DiacriticMethod(context); AutoCompleteModeLayout(context); //SizeLayout(context); TextColorLayout(context); BackColorLayout(context); WaterMarkLayout(context); LinearLayout ln = new LinearLayout(context); ln.AddView(propertyLayout); return ln; } private TextView scaleLabel, sizeLabel, scaleLabelSpacing, sizeLabelSpacing; private TextView resolutionLabel, resolutionLabelSpacing, orientationLabel, orientationLabelSpacing; private TextView controlSpacing1, controlSpacing2; private void SamplePageContents(Android.Content.Context con) { //scaleLabel scaleLabel = new TextView(con); scaleLabel.Text = "Scale and layout"; scaleLabel.TextSize = 18; scaleLabel.Typeface = Typeface.DefaultBold; //jobSearchLabelSpacing scaleLabelSpacing = new TextView(con); scaleLabelSpacing.SetHeight(40); //sizeLabel sizeLabel = new TextView(con); sizeLabel.Text = "Change the size of the text, apps and other items"; sizeLabel.TextSize = 18; //countryLabelSpacing sizeLabelSpacing = new TextView(con); sizeLabelSpacing.SetHeight(10); //countryAutoCompleteSpacing controlSpacing1 = new TextView(con); controlSpacing1.SetHeight(30); //jobFieldLabel resolutionLabel = new TextView(con); resolutionLabel.Text = "Resolution"; resolutionLabel.TextSize = 18; //jobFieldLabelSpacing resolutionLabelSpacing = new TextView(con); resolutionLabelSpacing.SetHeight(30); //jobFieldAutoCompleteSpacing controlSpacing2 = new TextView(con); controlSpacing2.SetHeight(30); //orientationLabel orientationLabel = new TextView(con); orientationLabel.Text = "Orientation"; orientationLabel.TextSize = 18; //experienceLabelSpacing orientationLabelSpacing = new TextView(con); orientationLabelSpacing.SetHeight(10); } private SfComboBox sizeComboBox, orientationComboBox, resolutionComboBox; private void ControlPageContents(Android.Content.Context con) { List<string> sizeList = new List<string>(); sizeList.Add("100%"); sizeList.Add("125%"); sizeList.Add("150% (Recommended)"); sizeList.Add("175%"); List<string> resolutionList = new List<string>(); resolutionList.Add("1920 x 1080 (Recommended)"); resolutionList.Add("1680 x 1050"); resolutionList.Add("1600 x 900"); resolutionList.Add("1440 x 900"); resolutionList.Add("1400 x 1050"); resolutionList.Add("1366 x 768"); resolutionList.Add("1360 x 768"); resolutionList.Add("1280 x 1024"); resolutionList.Add("1280 x 960"); resolutionList.Add("1280 x 720"); resolutionList.Add("854 x 480"); resolutionList.Add("800 x 480"); resolutionList.Add("480 X 640"); resolutionList.Add("480 x 320"); resolutionList.Add("432 x 240"); resolutionList.Add("360 X 640"); resolutionList.Add("320 x 240"); List<string> orientationList = new List<string>(); orientationList.Add("Landscape"); orientationList.Add("Portrait"); orientationList.Add("Landscape (flipped)"); orientationList.Add("Portrait (flipped)"); sizeComboBox = new SfComboBox(con); sizeComboBox.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 45); sizeComboBox.Watermark = "Search Here"; sizeComboBox.GetAutoEditText().SetTextSize(ComplexUnitType.Sp, 16); sizeComboBox.Text = "150% (Recommended)"; sizeComboBox.DataSource = sizeList; resolutionComboBox = new SfComboBox(con); resolutionComboBox.MaximumDropDownHeight = 200; resolutionComboBox.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 45); resolutionComboBox.Watermark = "Search Here"; resolutionComboBox.GetAutoEditText().SetTextSize(ComplexUnitType.Sp, 16); resolutionComboBox.Text = "1920 x 1080 (Recommended)"; resolutionComboBox.DataSource = resolutionList; orientationComboBox = new SfComboBox(con); orientationComboBox.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 45); orientationComboBox.Watermark = "Search Here"; orientationComboBox.GetAutoEditText().SetTextSize(ComplexUnitType.Sp, 16); orientationComboBox.Text = "Landscape"; orientationComboBox.DataSource = orientationList; } private bool isEditable; private LinearLayout isEditableLayout, propertyLayout; int width; private void Editable(Android.Content.Context context) { width = context.Resources.DisplayMetrics.WidthPixels - 40; propertyLayout = new LinearLayout(context); //propertyLayout.SetBackgroundColor(Color.Red); propertyLayout.Orientation = Orientation.Vertical; /************* **IsEditable** *************/ TextView isEditableText = new TextView(context); isEditableText.Text = "IsEditable"; isEditableText.TextAlignment = TextAlignment.TextStart; isEditableText.Gravity = GravityFlags.Start; isEditableText.LayoutParameters = new LinearLayout.LayoutParams((int)(width - (100 * context.Resources.DisplayMetrics.Density)), LinearLayout.LayoutParams.MatchParent); isEditableText.TextSize = 20; //isEditableCheckBox Switch isEditableCheckBox = new Switch(context); isEditableCheckBox.LayoutParameters = new LinearLayout.LayoutParams((int)(100 * context.Resources.DisplayMetrics.Density), LinearLayout.LayoutParams.MatchParent); isEditableCheckBox.Checked = false; isEditableCheckBox.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { if (!eve.IsChecked) isEditable = false; else isEditable = true; }; TextView textSpacing = new TextView(context); textSpacing.LayoutParameters = new LinearLayout.LayoutParams((int)(width / 2.2), 10); TextView textSpacing1 = new TextView(context); propertyLayout.AddView(textSpacing1); //isEditableLayout isEditableLayout = new LinearLayout(context); isEditableLayout.LayoutParameters = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MatchParent); isEditableLayout.AddView(isEditableText); //isEditableLayout.AddView(textSpacing); isEditableLayout.AddView(isEditableCheckBox); isEditableLayout.Orientation = Orientation.Horizontal; propertyLayout.AddView(isEditableLayout); TextView textSpacing2 = new TextView(context); //propertyLayout.AddView(textSpacing2); } private bool diacritic = false; private void DiacriticMethod(Android.Content.Context context) { /************* **Diacritic** *************/ TextView diacriticText = new TextView(context); diacriticText.TextAlignment = TextAlignment.TextStart; diacriticText.Gravity = GravityFlags.Start; diacriticText.LayoutParameters = new LinearLayout.LayoutParams((int)(width - (100 * context.Resources.DisplayMetrics.Density)), LinearLayout.LayoutParams.MatchParent); diacriticText.Text = "Diacritic"; diacriticText.TextSize = 20; //isEditableCheckBox Switch diacriticCheckBox = new Switch(context); diacriticCheckBox.LayoutParameters = new LinearLayout.LayoutParams((int)(100 * context.Resources.DisplayMetrics.Density), LinearLayout.LayoutParams.MatchParent); diacriticCheckBox.Checked = false; diacriticCheckBox.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { if (!eve.IsChecked) diacritic = false; else diacritic = true; }; TextView textSpacing = new TextView(context); textSpacing.LayoutParameters = new LinearLayout.LayoutParams((int)(width / 2), 10); TextView textSpacing1 = new TextView(context); propertyLayout.AddView(textSpacing1); //isEditableLayout isEditableLayout = new LinearLayout(context); isEditableLayout.LayoutParameters = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MatchParent); isEditableLayout.AddView(diacriticText); //isEditableLayout.AddView(textSpacing); isEditableLayout.AddView(diacriticCheckBox); isEditableLayout.Orientation = Orientation.Horizontal; propertyLayout.AddView(isEditableLayout); } Spinner comboBoxModeSpinner; LinearLayout comboBoxModeLayout; ArrayAdapter<String> comboBoxModeDataAdapter; ComboBoxMode comboBoxMode; private void AutoCompleteModeLayout(Android.Content.Context context) { /******************* **AutoCompleteMode** ********************/ TextView comboBoxModeLabel = new TextView(context); comboBoxModeLabel.Text = "ComboBox Mode"; comboBoxModeLabel.TextSize = 20; comboBoxModeLabel.Gravity = GravityFlags.Left; TextView textSpacing1 = new TextView(context); propertyLayout.AddView(textSpacing1); comboBoxModeSpinner = new Spinner(context, SpinnerMode.Dialog); comboBoxModeSpinner.LayoutParameters = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MatchParent); comboBoxModeLayout = new LinearLayout(context); comboBoxModeLayout.AddView(comboBoxModeLabel); comboBoxModeLayout.AddView(comboBoxModeSpinner); comboBoxModeLayout.Orientation = Orientation.Vertical; propertyLayout.AddView(comboBoxModeLayout); //ComboBoxModeList List<String> comboBoxModeList = new List<String>(); comboBoxModeList.Add("Suggest"); comboBoxModeList.Add("SuggestAppend"); comboBoxModeList.Add("Append"); comboBoxModeDataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, comboBoxModeList); comboBoxModeDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); comboBoxModeSpinner.Adapter = comboBoxModeDataAdapter; //autoCompleteModeSpinner ItemSelected Listener comboBoxModeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = comboBoxModeDataAdapter.GetItem(e.Position); if (selectedItem.Equals("Suggest")) { comboBoxMode = ComboBoxMode.Suggest; } else if (selectedItem.Equals("SuggestAppend")) { comboBoxMode = ComboBoxMode.SuggestAppend; } else if (selectedItem.Equals("Append")) { comboBoxMode = ComboBoxMode.Append; } }; } Spinner sizeSpinner; LinearLayout sizeLayout; ArrayAdapter<String> sizeDataAdapter; int textSize = 18; private void SizeLayout(Android.Content.Context context) { /******************* **AutoCompleteMode** ********************/ TextView sizeLabel = new TextView(context); sizeLabel.Text = "Size"; sizeLabel.TextSize = 20; sizeLabel.Gravity = GravityFlags.Left; TextView textSpacing1 = new TextView(context); propertyLayout.AddView(textSpacing1); sizeSpinner = new Spinner(context, SpinnerMode.Dialog); sizeSpinner.LayoutParameters = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MatchParent); sizeLayout = new LinearLayout(context); sizeLayout.AddView(sizeLabel); sizeLayout.AddView(sizeSpinner); sizeLayout.Orientation = Orientation.Vertical; propertyLayout.AddView(sizeLayout); //ComboBoxModeList List<String> sizeList = new List<String>(); sizeList.Add("Small"); sizeList.Add("Medium"); sizeList.Add("Large"); sizeDataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, sizeList); sizeDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); sizeSpinner.Adapter = sizeDataAdapter; //autoCompleteModeSpinner ItemSelected Listener sizeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = comboBoxModeDataAdapter.GetItem(e.Position); if (selectedItem.Equals("Small")) { textSize = 14; } else if (selectedItem.Equals("Medium")) { textSize = 18; } else if (selectedItem.Equals("Large")) { textSize = 20; } }; } Spinner textColorSpinner; LinearLayout textColorLayout; ArrayAdapter<String> textColorDataAdapter; Color textColor = Color.Black; private void TextColorLayout(Android.Content.Context context) { /******************* **AutoCompleteMode** ********************/ TextView textColorLabel = new TextView(context); textColorLabel.Text = "Text Color"; textColorLabel.TextSize = 20; textColorLabel.Gravity = GravityFlags.Left; TextView textSpacing1 = new TextView(context); propertyLayout.AddView(textSpacing1); textColorSpinner = new Spinner(context, SpinnerMode.Dialog); textColorSpinner.LayoutParameters = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MatchParent); textColorLayout = new LinearLayout(context); textColorLayout.AddView(textColorLabel); textColorLayout.AddView(textColorSpinner); textColorLayout.Orientation = Orientation.Vertical; propertyLayout.AddView(textColorLayout); //ComboBoxModeList List<String> textColorList = new List<String>(); textColorList.Add("Black"); textColorList.Add("Blue"); textColorList.Add("Red"); textColorList.Add("Yellow"); textColorDataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, textColorList); textColorDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); textColorSpinner.Adapter = textColorDataAdapter; //autoCompleteModeSpinner ItemSelected Listener textColorSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = textColorDataAdapter.GetItem(e.Position); if (selectedItem.Equals("Black")) { textColor = Color.Black; } else if (selectedItem.Equals("Blue")) { textColor = Color.Blue; } else if (selectedItem.Equals("Red")) { textColor = Color.Red; } else if (selectedItem.Equals("Yellow")) { textColor = Color.Yellow; } }; } Spinner backColorSpinner; LinearLayout backColorLayout; ArrayAdapter<String> backColorDataAdapter; Color backColor = Color.Transparent; private void BackColorLayout(Android.Content.Context context) { /******************* **AutoCompleteMode** ********************/ TextView backColorLabel = new TextView(context); backColorLabel.Text = "Background Color"; backColorLabel.TextSize = 20; backColorLabel.Gravity = GravityFlags.Left; TextView textSpacing1 = new TextView(context); propertyLayout.AddView(textSpacing1); backColorSpinner = new Spinner(context, SpinnerMode.Dialog); backColorSpinner.LayoutParameters = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MatchParent); backColorLayout = new LinearLayout(context); backColorLayout.AddView(backColorLabel); backColorLayout.AddView(backColorSpinner); backColorLayout.Orientation = Orientation.Vertical; propertyLayout.AddView(backColorLayout); //ComboBoxModeList List<String> backColorList = new List<String>(); backColorList.Add("Transparent"); backColorList.Add("Blue"); backColorList.Add("Red"); backColorList.Add("Yellow"); backColorDataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, backColorList); backColorDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); backColorSpinner.Adapter = backColorDataAdapter; //autoCompleteModeSpinner ItemSelected Listener backColorSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = backColorDataAdapter.GetItem(e.Position); if (selectedItem.Equals("Transparent")) { backColor = Color.Transparent; } else if (selectedItem.Equals("Blue")) { backColor = Color.Blue; } else if (selectedItem.Equals("Red")) { backColor = Color.Red; } else if (selectedItem.Equals("Yellow")) { backColor = Color.Yellow; } }; } EditText watermarkText; string waterMark; LinearLayout watermarkLayout; private void WaterMarkLayout(Android.Content.Context context) { /************************ **Watermark** ************************/ TextView watermarkLabel = new TextView(context); watermarkLabel.LayoutParameters = new LinearLayout.LayoutParams((int)(width - (200 * context.Resources.DisplayMetrics.Density)), LinearLayout.LayoutParams.MatchParent); watermarkLabel.Text = "Watermark"; watermarkLabel.TextSize = 20; //watermarkText watermarkText = new EditText(context); watermarkText.LayoutParameters = new LinearLayout.LayoutParams((int)(200 * context.Resources.DisplayMetrics.Density), LinearLayout.LayoutParams.MatchParent); watermarkText.Text = "Search Here"; watermarkText.TextSize = 16; //watermarkText.SetWidth(450); watermarkText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { waterMark = e.Text.ToString(); }; TextView spacingText = new TextView(context); propertyLayout.AddView(spacingText); TextView spacingText2 = new TextView(context); spacingText2.LayoutParameters = new LinearLayout.LayoutParams((int)(width / 3), LinearLayout.LayoutParams.MatchParent); //MinPrefixCharaterStack watermarkLayout = new LinearLayout(context); watermarkLayout.LayoutParameters = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MatchParent); watermarkLayout.AddView(watermarkLabel); // watermarkLayout.AddView(spacingText2); watermarkLayout.AddView(watermarkText); watermarkLayout.Orientation = Orientation.Horizontal; propertyLayout.AddView(watermarkLayout); } public override void OnApplyChanges() { sizeComboBox.IsEditableMode = isEditable; resolutionComboBox.IsEditableMode = isEditable; orientationComboBox.IsEditableMode = isEditable; sizeComboBox.IgnoreDiacritic = !diacritic; resolutionComboBox.IgnoreDiacritic = !diacritic; orientationComboBox.IgnoreDiacritic = !diacritic; sizeComboBox.ComboBoxMode = comboBoxMode; resolutionComboBox.ComboBoxMode = comboBoxMode; orientationComboBox.ComboBoxMode = comboBoxMode; sizeComboBox.TextSize = textSize; resolutionComboBox.TextSize = textSize; orientationComboBox.TextSize = textSize; sizeComboBox.TextColor = textColor; resolutionComboBox.TextColor = textColor; orientationComboBox.TextColor = textColor; sizeComboBox.SetBackgroundColor(backColor); resolutionComboBox.SetBackgroundColor(backColor); orientationComboBox.SetBackgroundColor(backColor); sizeComboBox.Watermark = waterMark; resolutionComboBox.Watermark = waterMark; orientationComboBox.Watermark = waterMark; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Model/SalesByDate.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SalesByDate.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class used to store the item values /// </summary> public class SalesByDate : Employee { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string name; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double qS1; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double qS2; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double qS3; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double qS4; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double total; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DateTime year; /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public new string Name { get { return this.name; } set { this.name = value; this.RaisePropertyChanged("Name"); } } /// <summary> /// Gets or sets the Q s1. /// </summary> /// <value>The Q s1.</value> public double QS1 { get { return this.qS1; } set { this.qS1 = value; this.RaisePropertyChanged("QS1"); } } /// <summary> /// Gets or sets the Q s2. /// </summary> /// <value>The Q s2.</value> public double QS2 { get { return this.qS2; } set { this.qS2 = value; this.RaisePropertyChanged("QS2"); } } /// <summary> /// Gets or sets the Q s3. /// </summary> /// <value>The Q s3.</value> public double QS3 { get { return this.qS3; } set { this.qS3 = value; this.RaisePropertyChanged("QS3"); } } /// <summary> /// Gets or sets the Q s4. /// </summary> /// <value>The Q s4.</value> public double QS4 { get { return this.qS4; } set { this.qS4 = value; this.RaisePropertyChanged("QS4"); } } /// <summary> /// Gets or sets the total. /// </summary> /// <value>The total.</value> public double Total { get { return this.total; } set { this.total = value; this.RaisePropertyChanged("Total"); } } /// <summary> /// Gets or sets the year. /// </summary> /// <value>The year.</value> public DateTime Date { get { return this.year; } set { this.year = value; this.RaisePropertyChanged("Date"); } } } } <file_sep>/Forms/Maps/Maps/Samples/MapsTicketBooking/MapsTicketBooking.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfMaps.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] //[XamlCompilation(XamlCompilationOptions.Compile)] public partial class MapsTicketBooking : SampleView { public MapsTicketBooking() { InitializeComponent(); (this.Maps.Layers[0] as ShapeFileLayer).ItemsSource = GetDataSource(); (this.Maps.Layers[0] as ShapeFileLayer).ShapeSelectionChanged += MapsTicketBooking_ShapeSelectionChanged; (this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.CollectionChanged += (sender, e) => { UpdateSelection(); }; this.ClearButton.Clicked += (sender, e) => { if ((this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.Count != 0) { (this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.Clear(); SelectedLabel.Text = ""; SelectedLabelCount.Text = "" + (this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.Count; this.ClearButton.IsEnabled = false; this.ClearButton.Opacity = 0.5; } }; } private void MapsTicketBooking_ShapeSelectionChanged(object sender, ShapeSelectedEventArgs e) { TicketData data = e.Data as TicketData; if (data != null) { if (data.SeatNumber == "1" || data.SeatNumber == "2" || data.SeatNumber == "8" || data.SeatNumber == "9") { if ((this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.Contains(e.Data)) (this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.Remove(e.Data); } } } void UpdateSelection() { string selected = ""; if ((Maps.Layers[0] as ShapeFileLayer).SelectedItems.Count == 0) { SelectedLabel.Text = selected; SelectedLabelCount.Text = " "; this.ClearButton.IsEnabled = false; this.ClearButton.Opacity = 0.5; } else { int count = 0; for (int i = 0; i < (this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.Count; i++) { TicketData data = (this.Maps.Layers[0] as ShapeFileLayer).SelectedItems[i] as TicketData; if (data.SeatNumber == "1" || data.SeatNumber == "2" || data.SeatNumber == "8" || data.SeatNumber == "9") { } else { count++; if ((this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.Count <= 1 && (this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.Count != 0) { selected += ("S" + data.SeatNumber); } else if (i == (this.Maps.Layers[0] as ShapeFileLayer).SelectedItems.Count - 1) { selected += ("S" + data.SeatNumber); } else { selected += ("S" + data.SeatNumber + ", "); } this.ClearButton.Opacity = 1; this.ClearButton.IsEnabled = true; SelectedLabel.Text = selected; } } SelectedLabelCount.Text = "" + count; } } List<TicketData> GetDataSource() { List<TicketData> list = new List<TicketData>(); for (int i = 1; i < 22; i++) { list.Add(new TicketData("" + i)); } return list; } } public class TicketData { public TicketData(string seatNumber) { SeatNumber = seatNumber; } public string SeatNumber { get; set; } } } <file_sep>/Forms/ImageEditor/ImageEditor.iOS/Share.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Foundation; using System.Threading.Tasks; using UIKit; using Photos; using System.IO; using System; namespace SampleBrowser.SfImageEditor.iOS { public class Share : IShare { /// <summary> /// MUST BE CALLED FROM THE UI THREAD /// </summary> /// <param name="filePath"></param> /// <param name="title"></param> /// <param name="message"></param> /// <returns></returns> public void Show(string title, string message, string filePath) { string[] str = filePath.Split('/'); PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null); PHAsset asset = assetResult.firstObject as PHAsset; PHImageManager.DefaultManager.RequestImageData(asset, null, HandlePHImageDataHandler); } async void HandlePHImageDataHandler(NSData data, NSString dataUti, UIImageOrientation orientation, NSDictionary info) { UIImage newImage = new UIImage(data); var items = new NSObject[] { newImage }; var activityController = new UIActivityViewController(items, null); var vc = GetVisibleViewController(); NSString[] excludedActivityTypes = null; if (excludedActivityTypes != null && excludedActivityTypes.Length > 0) activityController.ExcludedActivityTypes = excludedActivityTypes; if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { if (activityController.PopoverPresentationController != null) { activityController.PopoverPresentationController.SourceView = vc.View; } } await vc.PresentViewControllerAsync(activityController, true); } static UIImage FromUrl(string uri) { using (var url = NSUrl.FromFilename(uri)) using (var data = NSData.FromUrl(url)) return UIImage.LoadFromData(data); } UIViewController GetVisibleViewController() { var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController; if (rootController.PresentedViewController == null) return rootController; if (rootController.PresentedViewController is UINavigationController) { return ((UINavigationController)rootController.PresentedViewController).TopViewController; } if (rootController.PresentedViewController is UITabBarController) { return ((UITabBarController)rootController.PresentedViewController).SelectedViewController; } return rootController.PresentedViewController; } } } <file_sep>/Forms/Chart/Chart/Samples/ErrorBarChart/ErrorBarChart.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfChart.XForms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfChart { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ErrorBarChart : SampleView { public ErrorBarChart () { InitializeComponent (); if (Device.RuntimePlatform == Device.UWP || Device.RuntimePlatform == Device.WPF) { secondaryAxisLabelStyle.LabelFormat = "0'%'"; } else { secondaryAxisLabelStyle.LabelFormat = "#'%'"; } HorizontalErrorValue.ValueChanged += Horizontal_ValueChanged; VerticalErrorValue.ValueChanged += Vertical_ValueChanged; HorizontalErrorValue.MaximumTrackColor = Color.LightBlue; HorizontalErrorValue.MinimumTrackColor = Color.Blue; VerticalErrorValue.MaximumTrackColor = Color.LightBlue; VerticalErrorValue.MinimumTrackColor = Color.Blue; ErrorBarTypeValue.SelectedIndex = 0; ErrorBarTypeValue.SelectedIndexChanged += ErrorBarType_SelectedIndexChanged; ErrorBarDrawingModeValue.SelectedIndex = 2; ErrorBarDrawingModeValue.SelectedIndexChanged += ErrorBarModeValue_SelectedIndexChanged; HorizontalDirectionValue.SelectedIndex = 0; HorizontalDirectionValue.SelectedIndexChanged += HorizontalDirectionValue_SelectedIndexChanged; VerticalDirectionValue.SelectedIndex = 0; VerticalDirectionValue.SelectedIndexChanged += VerticalDirectionValue_SelectedIndexChanged; } private void Vertical_ValueChanged(object sender, ValueChangedEventArgs e) { Series.VerticalErrorValue = e.NewValue; VerticalError.Text = "Vertical Error : " + e.NewValue.ToString(); } private void Horizontal_ValueChanged(object sender, ValueChangedEventArgs e) { Series.HorizontalErrorValue = e.NewValue; HorizontalError.Text = "Horizontal Error : " + e.NewValue.ToString(); } private void VerticalDirectionValue_SelectedIndexChanged(object sender, EventArgs e) { switch (VerticalDirectionValue.SelectedIndex) { case 0: Series.VerticalDirection = ErrorBarDirection.Both; break; case 1: Series.VerticalDirection = ErrorBarDirection.Minus; break; case 2: Series.VerticalDirection = ErrorBarDirection.Plus; break; } } private void HorizontalDirectionValue_SelectedIndexChanged(object sender, EventArgs e) { switch(HorizontalDirectionValue.SelectedIndex) { case 0: Series.HorizontalDirection = ErrorBarDirection.Both; break; case 1: Series.HorizontalDirection = ErrorBarDirection.Minus; break; case 2: Series.HorizontalDirection = ErrorBarDirection.Plus; break; } } private void ErrorBarModeValue_SelectedIndexChanged(object sender, EventArgs e) { switch(ErrorBarDrawingModeValue.SelectedIndex) { case 0: Series.Mode = ErrorBarMode.Both; break; case 1: Series.Mode = ErrorBarMode.Horizontal; break; case 2: Series.Mode = ErrorBarMode.Vertical; break; } } private void ErrorBarType_SelectedIndexChanged(object sender, EventArgs e) { switch(ErrorBarTypeValue.SelectedIndex) { case 0: Series.Type = ErrorBarType.Fixed; break; case 1: Series.Type = ErrorBarType.Percentage; break; case 2: Series.Type = ErrorBarType.StandardDeviation; break; case 3: Series.Type = ErrorBarType.StandardErrors; break; case 4: Series.Type = ErrorBarType.Custom; break; } } } }<file_sep>/Forms/ListView/ListView/Samples/Swiping/Model/ListViewInboxInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewInboxInfoRepository { #region Fields private Random random = new Random(); #endregion #region Constructor public ListViewInboxInfoRepository() { } #endregion #region GetEmployeeInfo internal ObservableCollection<ListViewInboxInfo> GetInboxInfo() { var empInfo = new ObservableCollection<ListViewInboxInfo>(); for (int i = 0; i < Subject.Count(); i++) { var record = new ListViewInboxInfo() { Title = Title[i], Subject = Subject[i], Description = Descriptions[i], Date = Month[i] + " " + (i + 8).ToString(), }; record.IsFavorite = (i < 7 && i % 2 == 0) ? true : false; empInfo.Add(record); } return empInfo; } #endregion #region Employee Info string[] Title = new string[] { "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" }; string[] Month = new string[] { "Jan", "Jan", "Feb", "Mar", "Mar", "Apr", "May", "May", "May", "June", "July", "Aug", "Aug", "Sep", "Sep" }; string[] Subject = new string[] { "Happy birthday to an amazing employee!", "Like a vintage auto, your value increases...", "Happy Anniversary! Happy Anniversary!", "We wish you an amazing year with accomplishment...", "No one could do a better job than...", "GET WELL SOON!!", "A cheery Christmas hold lots of happiness for you!", "BOO!!! Happy Halloween! Happy Halloween!", "Happy Turkey Day!!", "Wishing you Happy St Pat's Day!", "Congratulations on the move!", "Enjoy the new greener pastures!", "Happy Thanksgiving Day!", "Never doubt yourself. You’re always...", "The warmest wishes to a great member of our team...", }; string[] Descriptions = new string[] { "Wishing you great achievements in this career, And I hope that you have a great day today!", "Happy birthday to one of the best and most loyal employees ever!", "Congrats! May your life continue to be filled with love, laughter and happiness.", "We wish you an amazing year with accomplishment of the great goals that you have set!", "No one could do a better job than the job you do. We thank you for sticking with us!", "Card messages aren't my thing. Get well soon!", "Wishing you a happy Christmas. May it be all that you hope it will be! All the best", "Wishing you a killer Halloween, Don't forget to give us treat or else..", "Happy Turkey Day!. Don't forget to give thanks for being so blessed.", "It's all green which means its all good! HAPPY ST PAT'S", "Congratulations! May you find great happiness at your new address.", "Good luck with the new job and your career aspirations. All the best", "May you enjoy this special day. Happy Thanksgiving to you and your whole family!", "Never doubt yourself. You’re always the best! Just continue to be like that!", "Warmest wishes! May your special day be full of good emotions, fun and cheer!" }; #endregion } } <file_sep>/Android/SampleBrowser/Samples/XlsIO/ExcelToJSONPage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XlsIO; using System; using System.IO; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using System.Reflection; namespace SampleBrowser { public partial class ExcelToJSONPage : SamplePage { private Context m_context; Spinner spinner; CheckBox checkSchema; public override View GetSampleContent(Context con) { int numerHeight = getDimensionPixelSize(con, Resource.Dimension.numeric_txt_ht); int width = con.Resources.DisplayMetrics.WidthPixels - 40; LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample illustrates the conversion of Excel documents to JSON file."; text2.SetTextColor(Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; LinearLayout subLinearLayout = new LinearLayout(con); subLinearLayout.Orientation = Orientation.Horizontal; TextView convert = new TextView(con); convert.Text = "Convert"; convert.TextAlignment = TextAlignment.Center; convert.TextSize = 17; convert.SetTextColor(Color.ParseColor("#262626")); convert.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); subLinearLayout.AddView(convert); string[] list = { "Workbook", "Worksheet", "Range"}; ArrayAdapter<String> array = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleSpinnerItem, list); spinner = new Spinner(con); spinner.Adapter = array; spinner.SetSelection(0); subLinearLayout.AddView(spinner); linear.AddView(subLinearLayout); LinearLayout advancedLinear1; advancedLinear1 = new LinearLayout(con); advancedLinear1.Orientation = Orientation.Horizontal; TextView space4 = new TextView(con); space4.TextSize = 17; space4.TextAlignment = TextAlignment.Center; space4.Text = " "; space4.SetTextColor(Color.ParseColor("#262626")); space4.LayoutParameters = new ViewGroup.LayoutParams(width / 2, numerHeight); advancedLinear1.AddView(space4); checkSchema = new CheckBox(con); checkSchema.Text = "As Schema"; checkSchema.Checked = true; advancedLinear1.AddView(checkSchema); linear.AddView(advancedLinear1); TextView space6 = new TextView(con); space6.TextSize = 17; linear.AddView(space6); Button templateButton = new Button(con); templateButton.Text = "Input Template"; templateButton.Click += OnButtonClicked; linear.AddView(templateButton); Button convertButton = new Button(con); convertButton.Text = "Convert To JSON"; convertButton.Click += OnConvertButtonClicked; linear.AddView(convertButton); return linear; } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream filestream = null; filestream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.ExcelToJSON.xlsx"); MemoryStream stream = new MemoryStream(); filestream.CopyTo(stream); SaveAndView(stream, "application/msexcel"); } private void OnConvertButtonClicked(object sender, EventArgs e) { //Instantiate excel engine ExcelEngine excelEngine = new ExcelEngine(); //Excel application IApplication application = excelEngine.Excel; //Get assembly manifest resource Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.ExcelToJSON.xlsx"); //Open Workbook IWorkbook workbook = application.Workbooks.Open(fileStream); IWorksheet sheet = workbook.Worksheets[0]; IRange range = sheet.Range["A2:B10"]; bool isSchema = checkSchema.Checked; int index = spinner.SelectedItemPosition; MemoryStream stream = new MemoryStream(); if (index == 0) workbook.SaveAsJson(stream, isSchema); else if (index == 1) workbook.SaveAsJson(stream, sheet, isSchema); else if (index == 2) workbook.SaveAsJson(stream, range, isSchema); workbook.Close(); excelEngine.Dispose(); SaveAndView(stream, "application/json"); } void SaveAndView(MemoryStream stream, string contentType) { if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); if (contentType == "application/json") androidSave.Save("ExcelToJSON.json", contentType, stream, m_context); else androidSave.Save("Input Template.xlsx", contentType, stream, m_context); } } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } } }<file_sep>/Android/SampleBrowser/Samples/SparkLine/readme.md A sparkline is tiny chart that helps present trends and variations associated with a measurement– such as average temperature, stock market activity, etc.–in a simple, lightweight, and condensed manner. The following sample is available for sparkline to demonstrate the functionalities of its feature. | Sample | Description | | ------ | ----------- | | [Sparkline](SparkLine.cs)| A sparkline is a tiny chart that provides visual representation of the present trends and variations. This sample shows how to add area, line, column, and win/loss sparklines based on underlying data. | <file_sep>/Forms/Chat/Chat/Samples/FlightBooking/FlightBookingBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion namespace SampleBrowser.SfChat { using SampleBrowser.Core; using Syncfusion.XForms.Chat; using System.Collections.Specialized; using System.Threading.Tasks; using Xamarin.Essentials; using Xamarin.Forms; /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the flight booking sample. /// </summary> public class FlightBookingBehavior : Behavior<SampleView> { /// <summary> /// flight booking view model. /// </summary> private FlightBookingViewModel viewModel; /// <summary> /// sfChat control instance. /// </summary> private SfChat sfChat; /// <summary> /// Method will be called when the view is attached to the window /// </summary> /// <param name="bindable">SampleView type parameter as bindable</param> protected override void OnAttachedTo(SampleView bindable) { this.sfChat = bindable.FindByName<SfChat>("sfChat"); this.viewModel = bindable.FindByName<FlightBookingViewModel>("viewModel"); this.viewModel.Messages.CollectionChanged += OnMessagesCollectionChanged; base.OnAttachedTo(bindable); } /// <summary> /// Method will be called when the view is detached from window /// </summary> /// <param name="bindable">SampleView type of bindAble parameter</param> protected override void OnDetachingFrom(SampleView bindable) { this.viewModel.Messages.CollectionChanged -= OnMessagesCollectionChanged; Connectivity.ConnectivityChanged -= this.viewModel.BotService.OnConnectivityChanged; this.viewModel.Bot = null; if (this.sfChat != null) { this.sfChat.Dispose(); this.sfChat = null; } if (this.viewModel != null) { this.viewModel = null; } base.OnDetachingFrom(bindable); } /// <summary> /// Raised when message collection is changed. /// </summary> /// <param name="sender">The object as sender</param> /// <param name="e">NotifyCollectionChangedEventArgs as e.</param> private async void OnMessagesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach (var chatItem in e.NewItems) { TextMessage textMessage = chatItem as TextMessage; if (textMessage != null && textMessage.Author == this.viewModel.CurrentUser) { this.viewModel.ShowTypingIndicator = true; this.viewModel.BotService.SendMessageToBot(textMessage.Text); } else { await Task.Delay(50); this.sfChat.ScrollToMessage(chatItem); } } } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Chart/DataMarker.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Foundation; using Syncfusion.SfChart.iOS; using UIKit; namespace SampleBrowser { public class DataMarker : SampleView { SFChart chart; public DataMarker() { chart = new SFChart(); chart.Title.Text = new NSString("Unemployment Rate"); SFCategoryAxis primary = new SFCategoryAxis(); primary.ShowMajorGridLines = false; chart.PrimaryAxis = primary; chart.SecondaryAxis = new SFNumericalAxis(); chart.SecondaryAxis.ShowMajorGridLines = false; chart.SecondaryAxis.Maximum = new NSNumber(100); ChartViewModel dataModel = new ChartViewModel(); SFBarSeries series = new SFBarSeries(); series.ItemsSource = dataModel.DataMarkerData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.DataMarker.LabelStyle.LabelPosition = SFChartDataMarkerLabelPosition.Outer; //series.Color = UIColor.FromRGB(233.0f / 255.0f, 88.0f / 255.0f, 83.0f / 255.0f); series.DataMarker.ShowLabel = true; chart.Series.Add(series); chart.Delegate = new ChartDataMarkerDelegate(); chart.ColorModel.Palette = SFChartColorPalette.Natural; this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } public class ChartDataMarkerDelegate : SFChartDelegate { public override UIView ViewForDataMarkerLabel(SFChart chart, NSString label, nint index, SFSeries series) { var dataPoint = (series.ItemsSource as IList<ChartDataModel>); UIView customView = new UIView(); customView.Frame = new CGRect(0, 0, 60, 20); UIImageView imageView = new UIImageView(); imageView.Frame = new CGRect(35, 0, 20, 20); UILabel average = new UILabel(); average.Frame = new CGRect(3, 0, 40, 20); average.Font = UIFont.FromName("Helvetica", 15f); average.Text = label.ToString()+"%"; if ((dataPoint[(int)index].YValue) > 50) { imageView.Image = UIImage.FromBundle("Images/Up.png"); average.TextColor = UIColor.Green; } else { imageView.Image = UIImage.FromBundle("Images/Down.png"); average.TextColor = UIColor.Red; } customView.AddSubview(imageView); customView.AddSubview(average); return customView; } } } <file_sep>/Android/SampleBrowser/Samples/TabView/View/TabControl.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Android.Content; using Android.Graphics; using Android.Util; using Android.Views; using Android.Widget; using Syncfusion.Android.TabView; namespace SampleBrowser { internal class TabControl : SfTabView { private ObservableCollection<ListView> ListViewCollection = new ObservableCollection<ListView>(); private TabDataViewModel viewModel = new TabDataViewModel(); private List<string> fontstring = new List<string>(); TabDisplayMode displayMode; TabHeaderPosition tabheaderPosition; SelectionIndicatorPosition selectionindicatorPosition; //SelectionIndicatorSettings selectionindicatorSetting; Context appcontext; public TabControl(Context context) : base(context) { appcontext = context; fontstring.Add("A"); fontstring.Add("C"); fontstring.Add("F"); fontstring.Add("H"); fontstring.Add("K"); ConfigureListView(); ConfigureTabView(); } private void ConfigureTabView() { this.SetBackgroundColor(Color.ParseColor("#037ef3")); var index = 0; foreach (var category in viewModel.Categories) { var tabViewItem = new SfTabItem { Title = category, IconFont = fontstring[index], FontIconStyle = Typeface.CreateFromAsset(appcontext.Assets, "TabIcons.ttf"), Content = ListViewCollection[index], SelectionColor = Color.White, TitleFontColor = Color.White, FontIconFontColor = Color.White, }; this.Items.Add(tabViewItem); index++; } this.SelectionIndicatorSettings = new SelectionIndicatorSettings() { Position = SelectionIndicatorPosition.Bottom, Color = Color.White }; this.selectionindicatorPosition = SelectionIndicatorPosition.Bottom; this.displayMode = TabDisplayMode.Text; this.OverflowMode = OverflowMode.Scroll; this.VisibleHeaderCount = 4; this.tabheaderPosition = TabHeaderPosition.Top; } private void ConfigureListView() { int index = 0; foreach (var category in viewModel.Categories) { var data = from cust in viewModel.Data where cust.Category == category select cust; // var dataTemplate = new DataTemplate(typeof(ItemView)); if (index % 2 == 0) { // dataTemplate = new DataTemplate(typeof(ProductView)); } var listView = new ListView(Context); TabContentListAdapter tabContentListAdapter = new TabContentListAdapter(data); listView.DividerHeight = 0; listView.Divider = null; listView.Adapter=tabContentListAdapter; //{ // ItemsSource = data, //RowHeight = rowHeight, //HeightRequest = 500, // WidthRequest = 500, // BindingContext = viewModel, // ItemTemplate = dataTemplate, //HorizontalOptions = LayoutOptions.FillAndExpand, // VerticalOptions = LayoutOptions.FillAndExpand //}; //listView.Loaded += ListView_Loaded; // listView.LayoutManager = new GridLayout() { SpanCount = 3 }; ListViewCollection.Add(listView); index++; } } public void ApplyChanges() { this.displayMode = this.DisplayMode; if (this.displayMode == TabDisplayMode.ImageWithText) this.TabHeight = 72; else this.TabHeight = 48; this.tabheaderPosition = this.TabHeaderPosition; this.selectionindicatorPosition = this.SelectionIndicatorSettings.Position; } } }<file_sep>/iOS/SampleBrowser/Samples/AutoComplete/MultiSelection.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Foundation; using UIKit; using CoreGraphics; using Syncfusion.SfAutoComplete.iOS; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser { public class MultiSelection : SampleView { UILabel email, attach, send, ToLabel, ccLabel, bcclabel; UIView redpanel; SfAutoComplete toAutoComplete; SfAutoComplete ccAutoComplete; SfAutoComplete bccAutoComplete; UITextField messageBox; UITextField subjectBox; public UIView option = new UIView(); private readonly IList<string> cultureList = new List<string>(); public MultiSelection() { //ToAutoComplete toAutoComplete = new SfAutoComplete(); toAutoComplete.MultiSelectMode = MultiSelectMode.Token; toAutoComplete.TokensWrapMode = TokensWrapMode.Wrap; toAutoComplete.DataSource = new ContactsInfoCollection().GetContactDetails(); toAutoComplete.DisplayMemberPath = (NSString)"ContactName"; toAutoComplete.ImageMemberPath = "ContactImage"; toAutoComplete.ItemHeight = 60; toAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeStartsWith; toAutoComplete.DropDownItemChanged += NativeAutoComplete_DropDownItemChanged; this.AddSubview(toAutoComplete); //CCAutoComplete ccAutoComplete = new SfAutoComplete(); ccAutoComplete.MultiSelectMode = MultiSelectMode.Token; ccAutoComplete.TokensWrapMode = TokensWrapMode.Wrap; ccAutoComplete.DataSource = new ContactsInfoCollection().GetContactDetails(); ccAutoComplete.DisplayMemberPath = (NSString)"ContactName"; ccAutoComplete.ImageMemberPath = "ContactImage"; ccAutoComplete.ItemHeight = 60; ccAutoComplete.DropDownItemChanged += NativeAutoComplete_DropDownItemChanged; ccAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeStartsWith; this.AddSubview(ccAutoComplete); //BCCAutoComplete bccAutoComplete = new SfAutoComplete(); bccAutoComplete.MultiSelectMode = MultiSelectMode.Token; bccAutoComplete.TokensWrapMode = TokensWrapMode.Wrap; bccAutoComplete.DataSource = new ContactsInfoCollection().GetContactDetails(); bccAutoComplete.DisplayMemberPath = (NSString)"ContactName"; bccAutoComplete.ItemHeight = 60; bccAutoComplete.ImageMemberPath = "ContactImage"; bccAutoComplete.DropDownItemChanged += NativeAutoComplete_DropDownItemChanged; bccAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeStartsWith; this.AddSubview(bccAutoComplete); //SubjectBox subjectBox = new UITextField(); subjectBox.Placeholder = " Subject"; subjectBox.Font = UIFont.FromName("Helvetica", 15f); subjectBox.Layer.BorderWidth = 0.5f; subjectBox.Layer.CornerRadius = 5f; subjectBox.Layer.BorderColor = UIColor.FromRGB(200, 200, 200).CGColor; this.AddSubview(subjectBox); //MessageBox messageBox = new UITextField(); messageBox.Text = "Sent from my smart phone."; messageBox.Font = UIFont.FromName("Helvetica", 12f); this.AddSubview(messageBox); mainPageDesign(); } UIView NativeAutoComplete_DropDownItemChanged(object sender, DropDownItemEventArgs e) { UIView parentView = new UIView(); SfAutoComplete auto = (sender as SfAutoComplete); parentView.Frame = new CGRect(0, 0, auto.Bounds.Width, auto.ItemHeight); UIImageView imageView = new UIImageView(); imageView.Frame = new CGRect(5, 5, 50, auto.ItemHeight - 10); UILabel titleLabel = new UILabel(); titleLabel.Frame = new CGRect(60, 5, auto.Bounds.Width - 65, auto.ItemHeight / 2 - 5); titleLabel.TextAlignment = UITextAlignment.Left; UILabel resultLabel = new UILabel(); resultLabel.Frame = new CGRect(60, auto.ItemHeight / 2, auto.Bounds.Width - 65, auto.ItemHeight / 2 - 5); resultLabel.Font = UIFont.FromName("Helvetica", 12f); resultLabel.TextAlignment = UITextAlignment.Left; var item = auto.DataSource.ElementAt((int)e.Index); var selectedObject = (item as ContactsInfo); imageView.Image = new UIImage(selectedObject.ContactImage); titleLabel.Text = selectedObject.ContactName; resultLabel.Text = selectedObject.ContactNumber; parentView.AddSubview(imageView); parentView.AddSubview(titleLabel); parentView.AddSubview(resultLabel); e.View = parentView; return e.View; } public void mainPageDesign() { redpanel = new UIView(); redpanel.BackgroundColor = UIColor.FromRGB(42, 77, 114); this.AddSubview(redpanel); //emaill email = new UILabel(); email.TextColor = UIColor.White; email.BackgroundColor = UIColor.Clear; email.Text = @"Email - Compose"; email.TextAlignment = UITextAlignment.Left; email.Font = UIFont.FromName("Helvetica", 16f); redpanel.AddSubview(email); //attachl attach = new UILabel(); attach.TextColor = UIColor.White; attach.BackgroundColor = UIColor.Clear; attach.Text = @"ATTACH"; attach.TextAlignment = UITextAlignment.Left; attach.Font = UIFont.FromName("Helvetica", 14f); redpanel.AddSubview(attach); //send send = new UILabel(); send.TextColor = UIColor.White; send.BackgroundColor = UIColor.Clear; send.Text = @"SEND"; send.TextAlignment = UITextAlignment.Left; send.Font = UIFont.FromName("Helvetica", 14f); redpanel.AddSubview(send); //ToLabell ToLabel = new UILabel(); ToLabel.TextColor = UIColor.Black; ToLabel.BackgroundColor = UIColor.Clear; ToLabel.Text = @"To"; ToLabel.TextAlignment = UITextAlignment.Left; ToLabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(ToLabel); //ccLabell ccLabel = new UILabel(); ccLabel.TextColor = UIColor.Black; ccLabel.BackgroundColor = UIColor.Clear; ccLabel.Text = @"Cc"; ccLabel.TextAlignment = UITextAlignment.Left; ccLabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(ccLabel); //bcclabell bcclabel = new UILabel(); bcclabel.TextColor = UIColor.Black; bcclabel.BackgroundColor = UIColor.Clear; bcclabel.Text = @"Bcc"; bcclabel.TextAlignment = UITextAlignment.Left; bcclabel.Font = UIFont.FromName("Helvetica", 13f); this.AddSubview(bcclabel); this.BackgroundColor = UIColor.White; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; redpanel.Frame = new CGRect(0, 0, view.Frame.Width, 50); toAutoComplete.Frame = new CGRect(50, 60, view.Frame.Width - 60, 40); ccAutoComplete.Frame = new CGRect(50, 110, view.Frame.Width - 60, 40); bccAutoComplete.Frame = new CGRect(50, 160, view.Frame.Width - 60, 40); subjectBox.Frame = new CGRect(10, 210, view.Frame.Width - 20, 40); messageBox.Frame = new CGRect(10, 260, view.Frame.Width - 60, 30); email.Frame = new CGRect(15, 10, 180, 40); attach.Frame = new CGRect(this.Frame.Size.Width - 120, 10, 60, 40); send.Frame = new CGRect(this.Frame.Size.Width - 50, 10, 50, 40); ToLabel.Frame = new CGRect(15, 60, 60, 40); ccLabel.Frame = new CGRect(15, 110, this.Frame.Size.Width - 20, 40); bcclabel.Frame = new CGRect(15, 160, this.Frame.Size.Width - 20, 40); } } } public class ContactsInfo { #region Fields private string contactName; private string contactNo; private string image; #endregion #region Constructor public ContactsInfo() { } #endregion #region Public Properties public string ContactName { get { return this.contactName; } set { this.contactName = value; } } public string ContactNumber { get { return contactNo; } set { this.contactNo = value; } } public string ContactImage { get { return this.image; } set { this.image = value; } } #endregion } public class ContactsInfoCollection { #region Fields private Random random = new Random(); #endregion #region Constructor public ContactsInfoCollection() { } #endregion #region Get Contacts Details public ObservableCollection<ContactsInfo> GetContactDetails() { ObservableCollection<ContactsInfo> customerDetails = new ObservableCollection<ContactsInfo>(); for (int i = 0; i < CustomerNames2.Count(); i++) { var details = new ContactsInfo() { ContactName = CustomerNames2[i], ContactNumber = CustomerNames2[i].Replace(" ", "") + "@outlook.com", ContactImage = "b" + (i % 14) + ".png", }; customerDetails.Add(details); if (i < 23) { details = new ContactsInfo() { ContactName = CustomerNames1[i], ContactNumber = CustomerNames1[i].Replace(" ", "") + "@outlook.com", ContactImage = "a" + (i % 6) + ".png", }; customerDetails.Add(details); } } return customerDetails; } #endregion #region Contacts Information string[] CustomerNames1 = new string[] { "Kyle", "Gina", "Michael", "Oscar", "William", "Bill", "Daniel", "Frank", "Howard", "Jack", "Holly", "Steve", "Vince", "Zeke", "Aiden", "Jackson", "Mason", "Liam", "Jacob", "Jayden", "Ethan", "Alexander", "Sebastian", }; string[] CustomerNames2 = new string[] { "Clara", "Irene", "Ellie", "Gabriella", "Nora", "Lucy", "Arianna", "Sarah", "Kaylee", "Adriana", "Finley", "Daleyza", "Leila", "Mckenna", "Jacqueline", "Brynn", "Sawyer", "Rosalie", "Maci", "Miranda", "Talia", "Shelby", "Haven", "Yaretzi", "Zariah", "Karla", "Cassandra", "Pearl", "Irene", "Zelda", "Wren", "Yamileth", "Belen", "Briley", "Jada", "Jaden" }; #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/NumericUpDown/NumericUpDown_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfNumericUpDown.iOS; using System.Collections.Generic; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class NumericUpDown_Tablet : SampleView { UIPickerView spinPicker; UILabel minimumLabel,maximumLabel, adultLabel, infantLabel, spinLabel,autoReverse,propertyLabel; UISwitch autoSwitch; UITextView minimumText,maximumText; UIScrollView subView; UIView contentView = new UIView (); UIView controlView = new UIView (); UIButton cultureDoneButton,spinAlignmentButton,showPropertyButton,closeButton; private string cultureSelectedType; SFNumericUpDown adultNumericUpDown; SFNumericUpDown infantsNumericUpDown; private UIView activeview; // Controller that activated the keyboard private float scroll_amount = 0.0f; // amount to scroll private float bottom = 0.0f; // bottom point private float offset = 10.0f; // extra offset private bool moveViewUp = false; private readonly IList<string> cultureList = new List<string> (); public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; subView.Frame = new CGRect (0, view.Frame.Size.Height-view.Frame.Size.Height/3, view.Frame.Size.Width, view.Frame.Size.Height / 3); controlView.Frame=new CGRect(150,90,this.Frame.Size.Width-300,this.Frame.Size.Height-40); contentView.Frame=new CGRect(0,40,subView.Frame.Size.Width,subView.Frame.Size.Height-30); adultNumericUpDown.Frame = new CGRect(10, 60, controlView.Frame.Width-20, 32); infantsNumericUpDown.Frame = new CGRect(10, 170, controlView.Frame.Width-20,32); adultLabel.Frame = new CGRect(15, 20, this.Frame.Size.Width-20, 30); infantLabel.Frame = new CGRect(15, 130, this.Frame.Size.Width-20, 30); minimumText.Frame = new CGRect (330, 40, contentView.Frame.Size.Width - 520, 30); maximumText.Frame = new CGRect (330, 90, contentView.Frame.Size.Width - 520, 30); minimumLabel.Frame = new CGRect ( 110, 40,contentView.Frame.Size.Width-210 , 30); maximumLabel.Frame = new CGRect (110, 90, contentView.Frame.Size.Width - 210, 30); spinLabel.Frame=new CGRect(110,140, contentView.Frame.Size.Width-220, 30); spinAlignmentButton.Frame=new CGRect(330,140, contentView.Frame.Size.Width-520, 30); autoReverse.Frame=new CGRect(110, 190, contentView.Frame.Size.Width-220, 30); autoSwitch.Frame=new CGRect(330,190, contentView.Frame.Size.Width-220, 30); spinPicker.Frame=new CGRect(100,12, contentView.Frame.Size.Width-200,220); cultureDoneButton.Frame=new CGRect(100, 0, contentView.Frame.Size.Width-200, 30); showPropertyButton.Frame = new CGRect (0, this.Frame.Size.Height - 25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect (this.Frame.Size.Width - 30, 5, 20, 30); propertyLabel.Frame = new CGRect (10, 5, this.Frame.Width, 30); } base.LayoutSubviews (); } static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } public NumericUpDown_Tablet () { //adultNumericUpDown adultNumericUpDown= new SFNumericUpDown(); adultNumericUpDown.AllowNull = true; adultNumericUpDown.PercentDisplayMode = SFNumericUpDownPercentDisplayMode.Compute; adultNumericUpDown.ValueChangeMode = SFNumericUpDownValueChangeMode.OnLostFocus; adultNumericUpDown.Value = 5; adultNumericUpDown.Minimum = 0; adultNumericUpDown.Maximum = 100; adultNumericUpDown.MaximumDecimalDigits = 0; adultNumericUpDown.Culture = new NSLocale ("en_US"); controlView.AddSubview(adultNumericUpDown); //infantsNumericUpDown infantsNumericUpDown= new SFNumericUpDown(); infantsNumericUpDown.AllowNull = true; infantsNumericUpDown.PercentDisplayMode = SFNumericUpDownPercentDisplayMode.Compute; infantsNumericUpDown.Value = 3; infantsNumericUpDown.Minimum = 0; infantsNumericUpDown.Maximum = 100; infantsNumericUpDown.MaximumDecimalDigits = 0; infantsNumericUpDown.Culture = new NSLocale ("en_US"); controlView.AddSubview(infantsNumericUpDown); this.AddSubview(controlView); mainPageDesign(); autoHide(); loadOptionView(); } public void autoHide() { NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, KeyBoardUpNotification); NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillHideNotification, KeyBoardDownNotification); } private void KeyBoardUpNotification(NSNotification notification) { // get the keyboard size var r = UIKeyboard.BoundsFromNotification(notification); // Find what opened the keyboard foreach (UIView view in this.contentView.Subviews) { if (view.IsFirstResponder) activeview = view; } if(activeview!=null) // Bottom of the controller = initial position + height + offset bottom = ((float)(activeview.Frame.Y + activeview.Frame.Height + offset)); // Calculate how far we need to scroll scroll_amount = ((float)(r.Height - (contentView.Frame.Size.Height - bottom))); // Perform the scrolling if (scroll_amount > 0) { moveViewUp = true; ScrollTheView(moveViewUp); } else { moveViewUp = false; } } private void KeyBoardDownNotification(NSNotification notification) { if (moveViewUp) { ScrollTheView(false); } } private void ScrollTheView(bool move) { // scroll the view up or down UIView.BeginAnimations(string.Empty, System.IntPtr.Zero); UIView.SetAnimationDuration(0.1); var frame = contentView.Frame; if (move) { frame.Y -= scroll_amount; } else { frame.Y += scroll_amount; scroll_amount = 0; } contentView.Frame = frame; UIView.CommitAnimations(); } public void mainPageDesign() { //adding to cultureListt this.cultureList.Add((NSString)"Right"); this.cultureList.Add((NSString)"Left"); this.cultureList.Add((NSString)"Both"); //adultLabell adultLabel = new UILabel(); adultLabel.TextColor = UIColor.Black; adultLabel.BackgroundColor = UIColor.Clear; adultLabel.Text = @"Number of Adults"; adultLabel.TextAlignment = UITextAlignment.Left; adultLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(adultLabel); //infantLabell infantLabel = new UILabel(); infantLabel.TextColor = UIColor.Black; infantLabel.BackgroundColor = UIColor.Clear; infantLabel.Text = @"Number of Infants"; infantLabel.TextAlignment = UITextAlignment.Left; infantLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(infantLabel); } public void loadOptionView() { subView = new UIScrollView(); subView.ContentSize = new CGSize(Frame.Width, 400); //autoReverse autoReverse = new UILabel(); autoReverse.TextColor = UIColor.Black; autoReverse.BackgroundColor = UIColor.Clear; autoReverse.Text = @"Auto Reverse"; autoReverse.TextAlignment = UITextAlignment.Left; autoReverse.Font = UIFont.FromName("Helvetica", 14f); contentView.AddSubview(autoReverse); //autoSwitch autoSwitch = new UISwitch(); autoSwitch.ValueChanged += autoReverseToggleChanged; autoSwitch.On = false; autoSwitch.OnTintColor = UIColor.FromRGB(50, 150, 221); contentView.AddSubview(autoSwitch); //spinLabel spinLabel = new UILabel(); spinLabel.TextColor = UIColor.Black; spinLabel.BackgroundColor = UIColor.Clear; spinLabel.Text = @"Spin Alignment"; spinLabel.TextAlignment = UITextAlignment.Left; spinLabel.Font = UIFont.FromName("Helvetica", 14f); contentView.AddSubview(spinLabel); //spinAlignmentButton spinAlignmentButton = new UIButton(); spinAlignmentButton.SetTitle("Right", UIControlState.Normal); spinAlignmentButton.Font = UIFont.FromName("Helvetica", 14f); spinAlignmentButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; spinAlignmentButton.BackgroundColor = UIColor.Clear; spinAlignmentButton.SetTitleColor(UIColor.Black, UIControlState.Normal); spinAlignmentButton.Hidden = false; spinAlignmentButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; spinAlignmentButton.Layer.BorderWidth = 4; spinAlignmentButton.Layer.CornerRadius = 8; spinAlignmentButton.TouchUpInside += ShowSpinPicker; contentView.AddSubview(spinAlignmentButton); //minimumLabel minimumLabel = new UILabel(); minimumLabel.Text = "Minimum"; minimumLabel.TextColor = UIColor.Black; minimumLabel.TextAlignment = UITextAlignment.Left; minimumLabel.Font = UIFont.FromName("Helvetica", 14f); //maximumLabel maximumLabel = new UILabel(); maximumLabel.Text = "Maximum"; maximumLabel.TextColor = UIColor.Black; maximumLabel.TextAlignment = UITextAlignment.Left; maximumLabel.Font = UIFont.FromName("Helvetica", 14f); contentView.AddSubview(minimumLabel); contentView.AddSubview(maximumLabel); //minimumText minimumText = new UITextView(); minimumText.TextAlignment = UITextAlignment.Center; minimumText.Layer.BorderColor = UIColor.Black.CGColor; minimumText.BackgroundColor = UIColor.FromRGB(246, 246, 246); minimumText.KeyboardType = UIKeyboardType.NumberPad; minimumText.Text = "0"; minimumText.Font = UIFont.FromName("Helvetica", 14f); minimumText.Changed += (object sender, EventArgs e) => { if (minimumText.Text.Length > 0) { adultNumericUpDown.Minimum = nfloat.Parse(minimumText.Text); infantsNumericUpDown.Minimum = nfloat.Parse(minimumText.Text); } }; contentView.AddSubview(minimumText); //maximumText maximumText = new UITextView(); maximumText.TextAlignment = UITextAlignment.Center; maximumText.Layer.BorderColor = UIColor.Black.CGColor; maximumText.BackgroundColor = UIColor.FromRGB(246, 246, 246); maximumText.KeyboardType = UIKeyboardType.NumberPad; maximumText.Text = "100"; maximumText.Font = UIFont.FromName("Helvetica", 14f); maximumText.Changed += (object sender, EventArgs e) => { if (maximumText.Text.Length > 0) { adultNumericUpDown.Maximum = nfloat.Parse(maximumText.Text); infantsNumericUpDown.Maximum = nfloat.Parse(maximumText.Text); } }; contentView.AddSubview(maximumText); //spinPicker PickerModel culturePickermodel = new PickerModel(this.cultureList); culturePickermodel.PickerChanged += (sender, e) => { this.cultureSelectedType = e.SelectedValue; spinAlignmentButton.SetTitle(cultureSelectedType, UIControlState.Normal); if (cultureSelectedType == "Right") { adultNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Right; infantsNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Right; adultNumericUpDown.TextAlignment = UITextAlignment.Left; infantsNumericUpDown.TextAlignment = UITextAlignment.Left; } else if (cultureSelectedType == "Left") { adultNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Left; infantsNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Left; adultNumericUpDown.TextAlignment = UITextAlignment.Right; infantsNumericUpDown.TextAlignment = UITextAlignment.Right; } else if (cultureSelectedType == "Both") { adultNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Both; infantsNumericUpDown.SpinButtonAlignment = SFNumericUpDownSpinButtonAlignment.Both; adultNumericUpDown.TextAlignment = UITextAlignment.Center; infantsNumericUpDown.TextAlignment = UITextAlignment.Center; } }; spinPicker = new UIPickerView(); spinPicker.ShowSelectionIndicator = true; spinPicker.Hidden = true; spinPicker.Model = culturePickermodel; spinPicker.BackgroundColor = UIColor.Gray; contentView.AddSubview(spinPicker); //cultureDoneButton cultureDoneButton = new UIButton(); cultureDoneButton.SetTitle("Done\t", UIControlState.Normal); cultureDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; cultureDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); cultureDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureDoneButton.Hidden = true; cultureDoneButton.Font = UIFont.FromName("Helvetica", 14f); cultureDoneButton.TouchUpInside += HideSpinPicker; contentView.AddSubview(cultureDoneButton); //propertyLabel propertyLabel = new UILabel(); propertyLabel.Text = "OPTIONS"; subView.AddSubview(propertyLabel); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); contentView.BackgroundColor = UIColor.FromRGB(240, 240, 240); subView.AddSubview(contentView); this.AddSubview(subView); //ShowPropertyButton showPropertyButton = new UIButton(); showPropertyButton.Hidden = true; showPropertyButton.SetTitle(" OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = false; showPropertyButton.Hidden = true; }; this.AddSubview(showPropertyButton); //closeButton closeButton = new UIButton(); closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; ; }; subView.AddSubview(closeButton); //Adding Gesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer(() => { subView.Hidden = true; showPropertyButton.Hidden = false; } ); propertyLabel.UserInteractionEnabled = true; propertyLabel.AddGestureRecognizer(tapgesture); } void ShowSpinPicker (object sender, EventArgs e) { cultureDoneButton.Hidden = false; spinPicker.Hidden = false; spinAlignmentButton.Hidden = true; autoSwitch.Hidden = true; autoReverse.Hidden = true; this.BecomeFirstResponder (); } void HideSpinPicker (object sender, EventArgs e) { cultureDoneButton.Hidden = true; spinPicker.Hidden = true; spinAlignmentButton.Hidden = false; autoSwitch.Hidden = false; autoReverse.Hidden = false; this.BecomeFirstResponder (); } private void autoReverseToggleChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { adultNumericUpDown.AutoReverse = true; infantsNumericUpDown.AutoReverse = true; } else { adultNumericUpDown.AutoReverse = false; infantsNumericUpDown.AutoReverse = false; } } public override void TouchesBegan (NSSet touches, UIEvent evt){ this.EndEditing (true); } } } <file_sep>/Android/SampleBrowser/Samples/CircularGauge/CustomizationSample.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Com.Syncfusion.Gauges.SfCircularGauge; using System.Collections.ObjectModel; using Android.Graphics; using Com.Syncfusion.Gauges.SfCircularGauge.Enums; using Android.Renderscripts; using static Android.App.ActionBar; using Android.Util; namespace SampleBrowser { public class CustomizationSample : SamplePage { double value; NeedlePointer needlePointer; RangePointer rangePointer1; RangePointer rangePointer; List<String> adapter; List<String> adapter1; List<String> adapter2; CircularRange circularRange; CircularRange circularRange1; Header header; Header header1; LinearLayout optionsPage; public override View GetSampleContent (Context con) { DisplayMetrics displayMetrics = con.Resources.DisplayMetrics; float screenHeight = displayMetrics.HeightPixels; SfCircularGauge sfCircularGauge = new SfCircularGauge(con); ObservableCollection<Header> headers = new ObservableCollection<Header>(); header = new Header(); header.Text = Math.Round((double)800, 2) + " GB"; header.TextSize = 24; header.TextColor = Color.Black; header.Position = new PointF((float)0.5, (float)0.1); headers.Add(header); sfCircularGauge.Headers = headers; ObservableCollection<CircularScale> circularScales = new ObservableCollection<CircularScale>(); CircularScale scale = new CircularScale(); scale.StartAngle = 210; scale.SweepAngle = 120; scale.StartValue = 0; scale.EndValue = 1000; scale.Interval = 500; scale.ShowLabels = false; scale.ShowTicks = false; scale.ShowRim = false; scale.MinorTicksPerInterval = 0; ObservableCollection<CircularRange> ranges = new ObservableCollection<CircularRange>(); circularRange = new CircularRange(); circularRange.StartValue = 0; circularRange.EndValue = 1000; circularRange.Color = Color.ParseColor("#E0E0E0"); circularRange.Offset = 0.7; circularRange.Width = 30; ranges.Add(circularRange); scale.CircularRanges = ranges; ObservableCollection<CircularPointer> pointers = new ObservableCollection<CircularPointer>(); rangePointer = new RangePointer(); rangePointer.Value = 800; rangePointer.Color = Color.ParseColor("#FFDD00"); rangePointer.Width = 30; rangePointer.Offset = 0.7; rangePointer.EnableAnimation = false; pointers.Add(rangePointer); needlePointer = new NeedlePointer(); needlePointer.Value = 800; needlePointer.Color = Color.ParseColor("#424242"); needlePointer.Type = Com.Syncfusion.Gauges.SfCircularGauge.Enums.NeedleType.Triangle; needlePointer.LengthFactor = 0.7; needlePointer.Width = 10; needlePointer.KnobRadiusFactor = 0.1; needlePointer.KnobColor = Color.ParseColor("#424242"); pointers.Add(needlePointer); scale.CircularPointers = pointers; circularScales.Add(scale); sfCircularGauge.CircularScales = circularScales; sfCircularGauge.SetBackgroundColor(Color.White); SfCircularGauge circularGauge = new SfCircularGauge(con); ObservableCollection<Header> headers1 = new ObservableCollection<Header>(); header1 = new Header(); header1.Text = Math.Round((double)800, 2) + " GB"; header1.TextSize = 24; header1.TextColor = Color.Black; header1.Position = new PointF((float)0.5, (float)0.5); headers1.Add(header1); Header header2 = new Header(); header2.Text = "Used"; header2.TextSize = 18; header2.TextColor = Color.Gray; header2.Position = new PointF((float)0.5, (float)0.6); headers1.Add(header2); circularGauge.Headers = headers1; ObservableCollection<CircularScale> circularScales1 = new ObservableCollection<CircularScale>(); CircularScale scale1 = new CircularScale(); scale1.StartAngle = 90; scale1.SweepAngle = 360; scale1.StartValue = 0; scale1.EndValue = 1000; scale1.Interval = 500; scale1.ShowLabels = false; scale1.ShowTicks = false; scale1.ShowRim = false; scale1.MinorTicksPerInterval = 0; ObservableCollection<CircularRange> ranges1 = new ObservableCollection<CircularRange>(); circularRange1 = new CircularRange(); circularRange1.StartValue = 0; circularRange1.EndValue = 999.9; circularRange1.Color = Color.ParseColor("#E0E0E0"); circularRange1.Offset = 0.8; circularRange1.Width = 30; ranges1.Add(circularRange1); scale1.CircularRanges = ranges1; ObservableCollection<CircularPointer> pointers1 = new ObservableCollection<CircularPointer>(); rangePointer1 = new RangePointer(); rangePointer1.Value = 800; rangePointer1.Color = Color.ParseColor("#FFDD00"); rangePointer1.Width = 30; rangePointer1.Offset = 0.8; rangePointer1.EnableAnimation = false; pointers1.Add(rangePointer1); scale1.CircularPointers = pointers1; circularScales1.Add(scale1); circularGauge.CircularScales = circularScales1; circularGauge.SetBackgroundColor(Color.White); LinearLayout outerLinearLayout = (LinearLayout)sfCircularGauge.FindViewById(Resource.Id.linearLayout); LinearLayout linearLayout = new LinearLayout(con); linearLayout.Orientation = Orientation.Vertical; linearLayout.LayoutParameters = new LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent); linearLayout.AddView(sfCircularGauge, LayoutParams.WrapContent, (int)(screenHeight / 2.7)); linearLayout.AddView(circularGauge, LayoutParams.WrapContent, (int)(screenHeight / 2.7)); linearLayout.SetBackgroundColor(Color.White); linearLayout.SetPadding(30, 30, 30, 30); ScrollView mainView = new ScrollView(con); mainView.AddView(linearLayout); return mainView; } public override View GetPropertyWindowLayout(Android.Content.Context context) { TextView pointervalue = new TextView(context); pointervalue.Text = "Change Pointer Value"; pointervalue.Typeface = Typeface.DefaultBold; pointervalue.SetTextColor(Color.ParseColor("#262626")); pointervalue.TextSize = 20; SeekBar pointerSeek = new SeekBar(context); pointerSeek.Max = 1000; pointerSeek.Progress = 800; pointerSeek.ProgressChanged += pointerSeek_ProgressChanged; TextView pointervalue1 = new TextView(context); pointervalue1.Text = "RangePointer Color"; pointervalue1.Typeface = Typeface.DefaultBold; pointervalue1.SetTextColor(Color.ParseColor("#262626")); pointervalue1.TextSize = 20; Spinner selectLabelMode = new Spinner(context, SpinnerMode.Dialog); adapter = new List<String>() { "Yellow", "Green", "Pink" }; ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelMode.Adapter = dataAdapter; selectLabelMode.ItemSelected += SelectLabelMode_ItemSelected; TextView pointervalue2 = new TextView(context); pointervalue2.Text = "NeedlePointer Color"; pointervalue2.Typeface = Typeface.DefaultBold; pointervalue2.SetTextColor(Color.ParseColor("#262626")); pointervalue2.TextSize = 20; Spinner selectLabelModel1 = new Spinner(context, SpinnerMode.Dialog); adapter1 = new List<String>() { "Black", "Violet", "Brown" }; ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter1); dataAdapter1.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelModel1.Adapter = dataAdapter1; selectLabelModel1.ItemSelected += SelectLabelMode_ItemSelected1; TextView pointervalue3 = new TextView(context); pointervalue3.Text = "Range Color"; pointervalue3.Typeface = Typeface.DefaultBold; pointervalue3.SetTextColor(Color.ParseColor("#262626")); pointervalue3.TextSize = 20; Spinner selectLabelModel2 = new Spinner(context, SpinnerMode.Dialog); adapter2 = new List<String>() { "LightGray", "Blue", "Orange" }; ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, adapter2); dataAdapter2.SetDropDownViewResource(Android.Resource.Layout.SimpleDropDownItem1Line); selectLabelModel2.Adapter = dataAdapter2; selectLabelModel2.ItemSelected += SelectLabelMode_ItemSelected2; optionsPage = new LinearLayout(context); optionsPage.Orientation = Orientation.Vertical; optionsPage.AddView(pointervalue); optionsPage.AddView(pointerSeek); optionsPage.AddView(pointervalue1); optionsPage.AddView(selectLabelMode); optionsPage.AddView(pointervalue2); optionsPage.AddView(selectLabelModel1); optionsPage.AddView(pointervalue3); optionsPage.AddView(selectLabelModel2); optionsPage.SetPadding(10, 10, 10, 10); optionsPage.SetBackgroundColor(Color.White); return optionsPage; } private void SelectLabelMode_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter[e.Position]; if (selectedItem.Equals("Yellow")) { rangePointer.Color = Color.Yellow; rangePointer1.Color = Color.Yellow; } else if (selectedItem.Equals("Green")) { rangePointer.Color = Color.Green; rangePointer1.Color = Color.Green; } else if (selectedItem.Equals("Pink")) { rangePointer.Color = Color.Pink; rangePointer1.Color = Color.Pink; } } private void SelectLabelMode_ItemSelected1(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter1[e.Position]; if (selectedItem.Equals("Black")) { needlePointer.Color = Color.ParseColor("#424242"); needlePointer.KnobColor = Color.ParseColor("#424242"); } else if (selectedItem.Equals("Violet")) { needlePointer.Color = Color.Violet; needlePointer.KnobColor = Color.Violet; } else if (selectedItem.Equals("Brown")) { needlePointer.Color = Color.Brown; needlePointer.KnobColor = Color.Brown; } } private void SelectLabelMode_ItemSelected2(object sender, AdapterView.ItemSelectedEventArgs e) { String selectedItem = adapter2[e.Position]; if (selectedItem.Equals("LightGray")) { circularRange.Color = Color.LightGray; circularRange1.Color = Color.LightGray; } else if (selectedItem.Equals("Blue")) { circularRange.Color = Color.Blue; circularRange1.Color = Color.Blue; } else if (selectedItem.Equals("Orange")) { circularRange.Color = Color.Orange; circularRange1.Color = Color.Orange; } } void pointerSeek_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { value = e.Progress; header.Text = Math.Round(value, 2) + " GB"; header1.Text = Math.Round(value, 2) + " GB"; needlePointer.Value = value; rangePointer.Value = value; rangePointer1.Value = value; } } } <file_sep>/Forms/ListView/ListView/Samples/Swiping/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Syncfusion.ListView.XForms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewSwipingViewModel { #region Fields private ObservableCollection<ListViewInboxInfo> inboxInfo; private Command favoritesImageCommand; private Command deleteImageCommand; #endregion #region EventHandler public event EventHandler<ResetEventArgs> ResetSwipeView; protected virtual void OnResetSwipe(ResetEventArgs e) { EventHandler<ResetEventArgs> handler = ResetSwipeView; handler?.Invoke(this, e); } #endregion #region Constructor public ListViewSwipingViewModel() { GenerateSource(); } #endregion #region Properties public ObservableCollection<ListViewInboxInfo> InboxInfo { get { return inboxInfo; } set { this.inboxInfo = value; } } internal int ItemIndex { get; set; } public Command FavoritesImageCommand { get { return favoritesImageCommand; } protected set { favoritesImageCommand = value; } } public Command DeleteImageCommand { get { return deleteImageCommand; } protected set { deleteImageCommand = value; } } public Command<object> SwipeEndedCommand { get; set;} public Command<object> SwipeStartedCommand { get; set;} #endregion #region Generate Source private void GenerateSource() { ListViewInboxInfoRepository inboxinfo = new ListViewInboxInfoRepository(); SwipeStartedCommand = new Command<object>(OnSwipeStart); SwipeEndedCommand = new Command<object>(OnSwipeEnd); inboxInfo = inboxinfo.GetInboxInfo(); deleteImageCommand = new Command(Delete); favoritesImageCommand = new Command(SetFavorites); } private void OnSwipeEnd(object obj) { var e = obj as Syncfusion.ListView.XForms.SwipeEndedEventArgs; this.ItemIndex = e.ItemIndex; } private void OnSwipeStart(object obj) { this.ItemIndex = -1; } private void Delete() { Application.Current.MainPage.DisplayAlert("Deleted!", "Item successfully deleted", "OK"); if (ItemIndex >= 0) InboxInfo.RemoveAt(ItemIndex); OnResetSwipe(new ResetEventArgs()); } private void SetFavorites() { if (ItemIndex >= 0) { var item = InboxInfo[ItemIndex]; item.IsFavorite = !item.IsFavorite; } OnResetSwipe(new ResetEventArgs()); } #endregion } #region ResetEvent public class ResetEventArgs : EventArgs { } #endregion } <file_sep>/iOS/SampleBrowser/Resources/Samples/MaskedEdit/MaskedEdit_Tablet.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfRangeSlider.iOS; using System.Collections.Generic; using Syncfusion.SfMaskedEdit.iOS; using System.Globalization; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class MaskedEdit_Tablet : SampleView { UIView view; UIView subView = new UIView(); UIButton searchButton = new UIButton(); public UIView option = new UIView(); UILabel fundTransferLable, accountLabel, descriptionLabel, amountLabel, emailIDLabel, mobileNumberLabel, inputValidationModeLabel, cultureLabel, hidepromptLabel, promptcharLabel; SfMaskedEdit acccountmaskedEdit, descriptionmaskedEdit, amountmaskedEdit, emailIDmaskedEdit, mobileNumbermaskedEdit; UILabel accInputRejectLable, amtInputRejectLable, emailInputRejectLable, phoneInputRejectLable; private UIPickerView cutCopyPicker, promptPicker, culturePicker; private UIButton promptcharButton, validationDoneButton, promptDoneButton, validationButton, cultureDoneButton, cultureButton; private readonly IList<string> cultureList, inputValidationModeList, promptCharList; private string cultureSelectedType, validationSelectedType, promptSelectedType; private UISwitch hidepromptSwitch; UIScrollView scrollView = new UIScrollView(); UIView contentView = new UIView(); UIView controlView = new UIView(); UILabel propertiesLabel = new UILabel(); UIButton closeButton = new UIButton(); UIButton showPropertyButton = new UIButton(); nfloat accPoint = 0; nfloat amtPoint = 0; nfloat emailPoint = 0; nfloat phonePoint = 0; public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; subView.Frame = new CGRect(0, this.Frame.Size.Height - this.Frame.Size.Height / 3 + 75, this.Frame.Size.Width, this.Frame.Height / 3 - 75); controlView.Frame = new CGRect(150, 40, view.Frame.Size.Width - 300, view.Frame.Size.Height + 300); contentView.Frame = new CGRect(0, 40, subView.Frame.Size.Width, subView.Frame.Size.Height); fundTransferLable.Frame = new CGRect(10, 0, controlView.Frame.Size.Width - 20, 40); accountLabel.Frame = new CGRect(10, 50, controlView.Frame.Size.Width - 20, 40); acccountmaskedEdit.Frame = new CGRect(10, 85, controlView.Frame.Size.Width - 20, 40); accInputRejectLable.Frame = new CGRect(10, 125, this.Frame.Size.Width - 20, 20); descriptionLabel.Frame = new CGRect(10, 135 + accPoint, controlView.Frame.Size.Width - 20, 40); descriptionmaskedEdit.Frame = new CGRect(10, 170 + accPoint, controlView.Frame.Size.Width - 20, 40); amountLabel.Frame = new CGRect(10, 220 + accPoint, controlView.Frame.Size.Width - 20, 40); amountmaskedEdit.Frame = new CGRect(10, 255 + accPoint, controlView.Frame.Size.Width - 20, 40); amtInputRejectLable.Frame = new CGRect(10, 295 + accPoint, this.Frame.Size.Width - 20, 20); emailIDLabel.Frame = new CGRect(10, 305 + accPoint + amtPoint, controlView.Frame.Size.Width - 20, 40); emailIDmaskedEdit.Frame = new CGRect(10, 340 + accPoint + amtPoint, controlView.Frame.Size.Width - 20, 40); emailInputRejectLable.Frame = new CGRect(10, 380 + accPoint + amtPoint, this.Frame.Size.Width - 20, 20); mobileNumberLabel.Frame = new CGRect(10, 390 + accPoint + amtPoint + emailPoint, controlView.Frame.Size.Width - 20, 40); mobileNumbermaskedEdit.Frame = new CGRect(10 , 425 + accPoint + amtPoint + emailPoint, controlView.Frame.Size.Width - 20, 40); phoneInputRejectLable.Frame = new CGRect(10, 470 + accPoint + amtPoint + emailPoint, this.Frame.Size.Width - 20, 15); searchButton.Frame = new CGRect(10, 500 + accPoint + amtPoint + emailPoint+phonePoint, controlView.Frame.Size.Width - 20, 40); inputValidationModeLabel.Frame = new CGRect(110, 10, 200, 30); validationButton.Frame = new CGRect(340, 10, contentView.Frame.Size.Width - 520, 30); cutCopyPicker.Frame = new CGRect(100, 20, contentView.Frame.Size.Width - 200, 200); validationDoneButton.Frame = new CGRect(100, 20, contentView.Frame.Size.Width - 200, 30); cultureLabel.Frame = new CGRect(110, 60, 200, 30); cultureButton.Frame = new CGRect(340, 60, contentView.Frame.Size.Width - 520, 30); culturePicker.Frame = new CGRect(100, 20, contentView.Frame.Size.Width - 200, 200); cultureDoneButton.Frame = new CGRect(100, 20, contentView.Frame.Size.Width - 200, 30); promptcharLabel.Frame = new CGRect(110, 110, 200, 30); promptcharButton.Frame = new CGRect(340, 110, contentView.Frame.Size.Width - 520, 30); promptPicker.Frame = new CGRect(100, 20, contentView.Frame.Size.Width - 200, 200); promptDoneButton.Frame = new CGRect(100, 20, contentView.Frame.Size.Width - 200, 30); hidepromptLabel.Frame = new CGRect(110, 160, 200, 30); hidepromptSwitch.Frame = new CGRect(340, 160, contentView.Frame.Size.Width - 520, 30); showPropertyButton.Frame = new CGRect(0, this.Frame.Size.Height - 25, this.Frame.Size.Width, 30); closeButton.Frame = new CGRect(this.Frame.Size.Width - 30, 5, 20, 30); propertiesLabel.Frame = new CGRect(10, 5, this.Frame.Width, 30); } base.LayoutSubviews(); } public MaskedEdit_Tablet() { view = new UIView(); this.OptionView = new UIView(); this.cultureList = new List<string>() { (NSString)"United States", (NSString)"United Kingdom", (NSString)"Japan", (NSString)"France", (NSString)"Italy" }; this.inputValidationModeList = new List<string>() { (NSString)"Key Press", (NSString)"Lost Focus" }; this.promptCharList = new List<string>() { "_", "*", "~" }; fundTransferLable = new UILabel(); fundTransferLable.TextColor = UIColor.Black; fundTransferLable.BackgroundColor = UIColor.Clear; fundTransferLable.Text = @"Funds Transfer"; fundTransferLable.TextAlignment = UITextAlignment.Left; fundTransferLable.Font = UIFont.FromName("Helvetica-Bold", 20f); controlView.AddSubview(fundTransferLable); accountLabel = new UILabel(); accountLabel.Text = "To Account"; accountLabel.TextColor = UIColor.Black; accountLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(accountLabel); acccountmaskedEdit = new SfMaskedEdit(); acccountmaskedEdit.Mask = "0000 0000 0000 0000"; acccountmaskedEdit.Culture = new CultureInfo("en-us"); acccountmaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; acccountmaskedEdit.ClipsToBounds = true; acccountmaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; acccountmaskedEdit.HidePromptOnLeave = true; acccountmaskedEdit.ValidationMode = InputValidationMode.KeyPress; acccountmaskedEdit.MaskInputRejected += AcccountmaskedEdit_MaskInputRejected; acccountmaskedEdit.ValueChanged += AcccountmaskedEdit_ValueChanged1; acccountmaskedEdit.TextAlignment = UITextAlignment.Left; acccountmaskedEdit.Placeholder = "1234 1234 1234 1234"; controlView.AddSubview(acccountmaskedEdit); accInputRejectLable = new UILabel(); accInputRejectLable.Font = UIFont.FromName("Helvetica", 14f); accInputRejectLable.TextColor = UIColor.Red; accInputRejectLable.Hidden = true; controlView.AddSubview(accInputRejectLable); descriptionLabel = new UILabel(); descriptionLabel.Text = "Description"; descriptionLabel.TextColor = UIColor.Black; descriptionLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(descriptionLabel); descriptionmaskedEdit = new SfMaskedEdit(); descriptionmaskedEdit.Mask = ""; descriptionmaskedEdit.Culture = new CultureInfo("en-us"); descriptionmaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; descriptionmaskedEdit.Placeholder = "Enter description"; descriptionmaskedEdit.TextAlignment = UITextAlignment.Left; descriptionmaskedEdit.ClipsToBounds = true; descriptionmaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; controlView.AddSubview(descriptionmaskedEdit); amountLabel = new UILabel(); amountLabel.Text = "Amount"; amountLabel.TextColor = UIColor.Black; amountLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(amountLabel); amountmaskedEdit = new SfMaskedEdit(); amountmaskedEdit.Mask = "$ 0,000.00"; amountmaskedEdit.Culture = new CultureInfo("en-us"); amountmaskedEdit.ValueMaskFormat = MaskFormat.IncludeLiterals; amountmaskedEdit.Placeholder = "$ 3,874.00"; amountmaskedEdit.ValidationMode = InputValidationMode.KeyPress; amountmaskedEdit.MaskInputRejected += AmountmaskedEdit_MaskInputRejected; amountmaskedEdit.ValueChanged += AmountmaskedEdit_ValueChanged1; amountmaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; amountmaskedEdit.TextAlignment = UITextAlignment.Left; controlView.AddSubview(amountmaskedEdit); amtInputRejectLable = new UILabel(); amtInputRejectLable.Font = UIFont.FromName("Helvetica", 14f); amtInputRejectLable.TextColor = UIColor.Red; amtInputRejectLable.Hidden = true; controlView.AddSubview(amtInputRejectLable); emailIDLabel = new UILabel(); emailIDLabel.Text = "Email ID"; emailIDLabel.TextColor = UIColor.Black; emailIDLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(emailIDLabel); emailIDmaskedEdit = new SfMaskedEdit(); emailIDmaskedEdit.Mask = @"\w+@\w+\.\w+"; emailIDmaskedEdit.Culture = new CultureInfo("en-us"); emailIDmaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; emailIDmaskedEdit.Placeholder = "<EMAIL>"; emailIDmaskedEdit.ValidationMode = InputValidationMode.KeyPress; emailIDmaskedEdit.MaskInputRejected += EmailIDmaskedEdit_MaskInputRejected; emailIDmaskedEdit.ValueChanged += EmailIDmaskedEdit_ValueChanged1; emailIDmaskedEdit.MaskType = MaskType.RegEx; emailIDmaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; controlView.AddSubview(emailIDmaskedEdit); emailInputRejectLable = new UILabel(); emailInputRejectLable.Font = UIFont.FromName("Helvetica", 14f); emailInputRejectLable.TextColor = UIColor.Red; emailInputRejectLable.Hidden = true; controlView.AddSubview(emailInputRejectLable); mobileNumberLabel = new UILabel(); mobileNumberLabel.Text = "Mobile Number"; mobileNumberLabel.TextColor = UIColor.Black; mobileNumberLabel.Font = UIFont.FromName("Helvetica", 16f); controlView.AddSubview(mobileNumberLabel); mobileNumbermaskedEdit = new SfMaskedEdit(); mobileNumbermaskedEdit.Mask = "+1 000 000 0000"; mobileNumbermaskedEdit.Culture = new CultureInfo("en-us"); mobileNumbermaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; mobileNumbermaskedEdit.ClipsToBounds = true; mobileNumbermaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; mobileNumbermaskedEdit.ValidationMode = InputValidationMode.KeyPress; mobileNumbermaskedEdit.MaskInputRejected += MobileNumbermaskedEdit_MaskInputRejected; mobileNumbermaskedEdit.ValueChanged += MobileNumbermaskedEdit_ValueChanged1; mobileNumbermaskedEdit.Placeholder = "+1 323 339 3392"; mobileNumbermaskedEdit.TextAlignment = UITextAlignment.Left; controlView.AddSubview(mobileNumbermaskedEdit); phoneInputRejectLable = new UILabel(); phoneInputRejectLable.Font = UIFont.FromName("Helvetica", 14f); phoneInputRejectLable.TextColor = UIColor.Red; phoneInputRejectLable.Hidden = true; controlView.AddSubview(phoneInputRejectLable); //searchButtonn searchButton.SetTitle("Transfer Money", UIControlState.Normal); searchButton.SetTitleColor(UIColor.White, UIControlState.Normal); searchButton.BackgroundColor = UIColor.FromRGB(50, 150, 221); searchButton.SetTitleColor(UIColor.Black, UIControlState.Normal); searchButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; searchButton.Layer.CornerRadius = 8; searchButton.Layer.BorderWidth = 2; searchButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; searchButton.TouchUpInside += FoundTransfer; controlView.AddSubview(searchButton); this.AddSubview(controlView); mainPageDesign(); optionView(); } private void EmailIDmaskedEdit_ValueChanged1(object sender, ValueChangedEventArgs e) { emailInputRejectLable.Hidden = true; emailPoint = 0; LayoutSubviews(); } private void MobileNumbermaskedEdit_ValueChanged1(object sender, ValueChangedEventArgs e) { phoneInputRejectLable.Hidden = true; phonePoint = 0; LayoutSubviews(); } private void AmountmaskedEdit_ValueChanged1(object sender, ValueChangedEventArgs e) { amtInputRejectLable.Hidden = true; amtPoint = 0; LayoutSubviews(); } private void AcccountmaskedEdit_ValueChanged1(object sender, ValueChangedEventArgs e) { accInputRejectLable.Hidden = true; accPoint = 0; LayoutSubviews(); } private void MobileNumbermaskedEdit_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { phoneInputRejectLable.Hidden = false; phoneInputRejectLable.Text = GetRejectionHintText(e.RejectionHint); if (!string.IsNullOrEmpty(phoneInputRejectLable.Text)) phonePoint = 15; LayoutSubviews(); } private void EmailIDmaskedEdit_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { emailInputRejectLable.Hidden = false; emailInputRejectLable.Text = GetRejectionHintText(e.RejectionHint); if (!string.IsNullOrEmpty(emailInputRejectLable.Text)) emailPoint = 15; LayoutSubviews(); } private void AmountmaskedEdit_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { amtInputRejectLable.Hidden = false; amtInputRejectLable.Text = GetRejectionHintText(e.RejectionHint); if (!string.IsNullOrEmpty(amtInputRejectLable.Text)) amtPoint = 15; LayoutSubviews(); } private void AcccountmaskedEdit_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { accInputRejectLable.Hidden = false; accInputRejectLable.Text = GetRejectionHintText(e.RejectionHint); if (!string.IsNullOrEmpty(accInputRejectLable.Text)) accPoint = 15; LayoutSubviews(); } private string GetRejectionHintText(MaskedTextResultHint hint) { string hintText = string.Empty; switch (hint) { case MaskedTextResultHint.AlphanumericCharacterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.DigitExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.LetterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.SignedDigitExpected: hintText = "Invalid character!"; break; } return hintText; } private void FoundTransfer(object sender, EventArgs e) { if ((acccountmaskedEdit.Value == null || acccountmaskedEdit.Value.ToString() == string.Empty) || (descriptionmaskedEdit.Value == null || descriptionmaskedEdit.Value.ToString() == string.Empty) || (amountmaskedEdit.Value == null || amountmaskedEdit.Value.ToString() == string.Empty) || (emailIDmaskedEdit.Value == null || emailIDmaskedEdit.Value.ToString() == string.Empty) || (mobileNumbermaskedEdit.Value == null || mobileNumbermaskedEdit.Value.ToString() == string.Empty)) { UIAlertView v = new UIAlertView(); v.Title = "Results"; v.Message = "Please fill all the required data!"; v.AddButton("OK"); v.Show(); } else if (acccountmaskedEdit.HasError || descriptionmaskedEdit.HasError || amountmaskedEdit.HasError || emailIDmaskedEdit.HasError || mobileNumbermaskedEdit.HasError) { UIAlertView v = new UIAlertView(); v.Title = "Results"; v.Message = "Please enter valid details"; v.AddButton("OK"); v.Show(); } else { UIAlertView v1 = new UIAlertView(); v1.Title = "Results"; v1.AddButton("OK"); v1.Message = string.Format("Amount of {0} has been transferred successfully!", amountmaskedEdit.Text); v1.Show(); string mask1 = acccountmaskedEdit.Mask; acccountmaskedEdit.Mask = string.Empty; acccountmaskedEdit.Mask = mask1; mask1 = descriptionmaskedEdit.Mask; descriptionmaskedEdit.Mask = "0"; descriptionmaskedEdit.Mask = mask1; mask1 = amountmaskedEdit.Mask; amountmaskedEdit.Mask = string.Empty; amountmaskedEdit.Mask = mask1; mask1 = emailIDmaskedEdit.Mask; emailIDmaskedEdit.Mask = string.Empty; emailIDmaskedEdit.Mask = mask1; mask1 = mobileNumbermaskedEdit.Mask; mobileNumbermaskedEdit.Mask = string.Empty; mobileNumbermaskedEdit.Mask = mask1; } this.BecomeFirstResponder(); } public void mainPageDesign() { inputValidationModeLabel = new UILabel(); inputValidationModeLabel.TextColor = UIColor.Black; inputValidationModeLabel.BackgroundColor = UIColor.Clear; inputValidationModeLabel.Text = @"Validation On"; inputValidationModeLabel.TextAlignment = UITextAlignment.Left; inputValidationModeLabel.Font = UIFont.FromName("Helvetica", 16f); validationButton = new UIButton(); validationButton.SetTitle("Key Press", UIControlState.Normal); validationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; validationButton.BackgroundColor = UIColor.Clear; validationButton.SetTitleColor(UIColor.Black, UIControlState.Normal); validationButton.Hidden = false; validationButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; validationButton.Layer.BorderWidth = 2; validationButton.Layer.CornerRadius = 8; validationButton.TouchUpInside += CutCopyMaskFormatButton_TouchUpInside; ; PickerModel cutCopyPickermodel = new PickerModel(this.inputValidationModeList); cutCopyPickermodel.PickerChanged += (sender, e) => { this.validationSelectedType = e.SelectedValue; validationButton.SetTitle(validationSelectedType, UIControlState.Normal); if (validationSelectedType == "Key Press") { acccountmaskedEdit.ValidationMode = InputValidationMode.KeyPress; descriptionmaskedEdit.ValidationMode = InputValidationMode.KeyPress; amountmaskedEdit.ValidationMode = InputValidationMode.KeyPress; emailIDmaskedEdit.ValidationMode = InputValidationMode.KeyPress; mobileNumbermaskedEdit.ValidationMode = InputValidationMode.KeyPress; } else if (validationSelectedType == "Lost Focus") { acccountmaskedEdit.ValidationMode = InputValidationMode.LostFocus; descriptionmaskedEdit.ValidationMode = InputValidationMode.LostFocus; amountmaskedEdit.ValidationMode = InputValidationMode.LostFocus; emailIDmaskedEdit.ValidationMode = InputValidationMode.LostFocus; mobileNumbermaskedEdit.ValidationMode = InputValidationMode.LostFocus; } }; cutCopyPicker = new UIPickerView(); cutCopyPicker.ShowSelectionIndicator = true; cutCopyPicker.Hidden = true; cutCopyPicker.Model = cutCopyPickermodel; cutCopyPicker.BackgroundColor = UIColor.White; validationDoneButton = new UIButton(); validationDoneButton.SetTitle("Done\t", UIControlState.Normal); validationDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; validationDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); validationDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); validationDoneButton.Hidden = true; validationDoneButton.TouchUpInside += CutCopyDoneButton_TouchUpInside; cultureLabel = new UILabel(); cultureLabel.TextColor = UIColor.Black; cultureLabel.BackgroundColor = UIColor.Clear; cultureLabel.Text = @"Culture"; cultureLabel.TextAlignment = UITextAlignment.Left; cultureLabel.Font = UIFont.FromName("Helvetica", 15f); cultureButton = new UIButton(); cultureButton.SetTitle("United States", UIControlState.Normal); cultureButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; cultureButton.BackgroundColor = UIColor.Clear; cultureButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureButton.Hidden = false; cultureButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; cultureButton.Layer.BorderWidth = 2; cultureButton.Layer.CornerRadius = 8; cultureButton.TouchUpInside += ShowCulturePicker; PickerModel culturePickermodel = new PickerModel(this.cultureList); culturePickermodel.PickerChanged += (sender, e) => { this.cultureSelectedType = e.SelectedValue; cultureButton.SetTitle(cultureSelectedType, UIControlState.Normal); if (cultureSelectedType == "United States") { acccountmaskedEdit.Culture = new CultureInfo("en-us"); descriptionmaskedEdit.Culture = new CultureInfo("en-us"); amountmaskedEdit.Culture = new CultureInfo("en-us"); emailIDmaskedEdit.Culture = new CultureInfo("en-us"); mobileNumbermaskedEdit.Culture = new CultureInfo("en-us"); } else if (cultureSelectedType == "United Kingdom") { acccountmaskedEdit.Culture = new CultureInfo("en-GB"); descriptionmaskedEdit.Culture = new CultureInfo("en-GB"); amountmaskedEdit.Culture = new CultureInfo("en-GB"); emailIDmaskedEdit.Culture = new CultureInfo("en-GB"); mobileNumbermaskedEdit.Culture = new CultureInfo("en-GB"); } else if (cultureSelectedType == "Japan") { acccountmaskedEdit.Culture = new CultureInfo("ja-JP"); descriptionmaskedEdit.Culture = new CultureInfo("ja-JP"); amountmaskedEdit.Culture = new CultureInfo("ja-JP"); emailIDmaskedEdit.Culture = new CultureInfo("ja-JP"); mobileNumbermaskedEdit.Culture = new CultureInfo("ja-JP"); } else if (cultureSelectedType == "France") { acccountmaskedEdit.Culture = new CultureInfo("fr-FR"); descriptionmaskedEdit.Culture = new CultureInfo("fr-FR"); amountmaskedEdit.Culture = new CultureInfo("fr-FR"); emailIDmaskedEdit.Culture = new CultureInfo("fr-FR"); mobileNumbermaskedEdit.Culture = new CultureInfo("fr-FR"); } else if (cultureSelectedType == "Italy") { acccountmaskedEdit.Culture = new CultureInfo("it-IT"); descriptionmaskedEdit.Culture = new CultureInfo("it-IT"); amountmaskedEdit.Culture = new CultureInfo("it-IT"); emailIDmaskedEdit.Culture = new CultureInfo("it-IT"); mobileNumbermaskedEdit.Culture = new CultureInfo("it-IT"); } }; culturePicker = new UIPickerView(); culturePicker.ShowSelectionIndicator = true; culturePicker.Hidden = true; culturePicker.Model = culturePickermodel; culturePicker.BackgroundColor = UIColor.White; cultureDoneButton = new UIButton(); cultureDoneButton.SetTitle("Done\t", UIControlState.Normal); cultureDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; cultureDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); cultureDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureDoneButton.Hidden = true; cultureDoneButton.TouchUpInside += HideCulturePicker; hidepromptLabel = new UILabel(); hidepromptLabel.TextColor = UIColor.Black; hidepromptLabel.BackgroundColor = UIColor.Clear; hidepromptLabel.Text = @"Hide Prompt On Leave"; hidepromptLabel.TextAlignment = UITextAlignment.Left; hidepromptLabel.Font = UIFont.FromName("Helvetica", 16f); hidepromptSwitch = new UISwitch(); hidepromptSwitch.ValueChanged += AllowSwitch_ValueChanged; hidepromptSwitch.On = false; promptcharLabel = new UILabel(); promptcharLabel.TextColor = UIColor.Black; promptcharLabel.BackgroundColor = UIColor.Clear; promptcharLabel.Text = @"Prompt Character"; promptcharLabel.TextAlignment = UITextAlignment.Left; promptcharLabel.Font = UIFont.FromName("Helvetica", 16f); promptcharButton = new UIButton(); promptcharButton.SetTitle("_", UIControlState.Normal); promptcharButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; promptcharButton.BackgroundColor = UIColor.Clear; promptcharButton.SetTitleColor(UIColor.Black, UIControlState.Normal); promptcharButton.Hidden = false; promptcharButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; promptcharButton.Layer.BorderWidth = 2; promptcharButton.Layer.CornerRadius = 8; promptcharButton.TouchUpInside += ShowpromptPicker; PickerModel promptcharPickermodel = new PickerModel(this.promptCharList); promptcharPickermodel.PickerChanged += (sender, e) => { this.promptSelectedType = e.SelectedValue; promptcharButton.SetTitle(promptSelectedType, UIControlState.Normal); if (promptSelectedType == "*") { acccountmaskedEdit.PromptChar = '*'; descriptionmaskedEdit.PromptChar = '*'; amountmaskedEdit.PromptChar = '*'; emailIDmaskedEdit.PromptChar = '*'; mobileNumbermaskedEdit.PromptChar = '*'; } else if (promptSelectedType == "~") { acccountmaskedEdit.PromptChar = '~'; descriptionmaskedEdit.PromptChar = '~'; amountmaskedEdit.PromptChar = '~'; emailIDmaskedEdit.PromptChar = '~'; mobileNumbermaskedEdit.PromptChar = '~'; } else if (promptSelectedType == "_") { acccountmaskedEdit.PromptChar = '_'; descriptionmaskedEdit.PromptChar = '_'; amountmaskedEdit.PromptChar = '_'; emailIDmaskedEdit.PromptChar = '_'; mobileNumbermaskedEdit.PromptChar = '_'; } }; promptPicker = new UIPickerView(); promptPicker.ShowSelectionIndicator = true; promptPicker.Hidden = true; promptPicker.Model = promptcharPickermodel; promptPicker.BackgroundColor = UIColor.White; promptDoneButton = new UIButton(); promptDoneButton.SetTitle("Done\t", UIControlState.Normal); promptDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; promptDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); promptDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); promptDoneButton.Hidden = true; promptDoneButton.TouchUpInside += HidepromptPicker; //propertiesLabel propertiesLabel = new UILabel(); propertiesLabel.Text = "OPTIONS"; //showPropertyButton showPropertyButton = new UIButton(); showPropertyButton.Hidden = true; showPropertyButton.SetTitle(" OPTIONS\t", UIControlState.Normal); showPropertyButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; showPropertyButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); showPropertyButton.SetTitleColor(UIColor.Black, UIControlState.Normal); showPropertyButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = false; showPropertyButton.Hidden = true; }; this.AddSubview(showPropertyButton); //closeButton closeButton = new UIButton(); closeButton.SetTitle("X\t", UIControlState.Normal); closeButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Left; closeButton.BackgroundColor = UIColor.FromRGB(230, 230, 230); closeButton.SetTitleColor(UIColor.Black, UIControlState.Normal); closeButton.TouchUpInside += (object sender, EventArgs e) => { subView.Hidden = true; showPropertyButton.Hidden = false; }; //subVieww subView.AddSubview(closeButton); subView.AddSubview(propertiesLabel); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); contentView.BackgroundColor = UIColor.FromRGB(240, 240, 240); subView.AddSubview(contentView); this.AddSubview(subView); //AddingGesture UITapGestureRecognizer tapgesture = new UITapGestureRecognizer(() => { subView.Hidden = true; showPropertyButton.Hidden = false; } ); propertiesLabel.UserInteractionEnabled = true; propertiesLabel.AddGestureRecognizer(tapgesture); this.BackgroundColor = UIColor.White; } public void optionView() { contentView.AddSubview(inputValidationModeLabel); contentView.AddSubview(validationButton); contentView.AddSubview(cutCopyPicker); contentView.AddSubview(validationDoneButton); contentView.AddSubview(cultureLabel); contentView.AddSubview(cultureButton); contentView.AddSubview(culturePicker); contentView.AddSubview(cultureDoneButton); contentView.AddSubview(hidepromptLabel); contentView.AddSubview(hidepromptSwitch); contentView.AddSubview(promptcharLabel); contentView.AddSubview(promptcharButton); contentView.AddSubview(promptPicker); contentView.AddSubview(promptDoneButton); subView.AddSubview(closeButton); contentView.BackgroundColor = UIColor.FromRGB(240, 240, 240); subView.BackgroundColor = UIColor.FromRGB(230, 230, 230); subView.AddSubview(contentView); this.AddSubview(subView); } private void HidepromptPicker(object sender, EventArgs e) { promptDoneButton.Hidden = true; promptPicker.Hidden = true; validationButton.Hidden = false; inputValidationModeLabel.Hidden = false; cultureLabel.Hidden = false; hidepromptLabel.Hidden = false; promptcharLabel.Hidden = false; validationButton.Hidden = false; cultureButton.Hidden = false; promptcharButton.Hidden = false; hidepromptSwitch.Hidden = false; } private void ShowpromptPicker(object sender, EventArgs e) { promptDoneButton.Hidden = false; promptPicker.Hidden = false; validationButton.Hidden = true; inputValidationModeLabel.Hidden = true; cultureLabel.Hidden = true; hidepromptLabel.Hidden = true; promptcharLabel.Hidden = true; validationButton.Hidden = true; cultureButton.Hidden = true; promptcharButton.Hidden = true; hidepromptSwitch.Hidden = true; } private void CutCopyDoneButton_TouchUpInside(object sender, EventArgs e) { validationDoneButton.Hidden = true; cutCopyPicker.Hidden = true; validationButton.Hidden = false; inputValidationModeLabel.Hidden = false; cultureLabel.Hidden = false; hidepromptLabel.Hidden = false; promptcharLabel.Hidden = false; validationButton.Hidden = false; cultureButton.Hidden = false; promptcharButton.Hidden = false; hidepromptSwitch.Hidden = false; } private void CutCopyMaskFormatButton_TouchUpInside(object sender, EventArgs e) { validationDoneButton.Hidden = false; cutCopyPicker.Hidden = false; validationButton.Hidden = true; inputValidationModeLabel.Hidden = true; cultureLabel.Hidden = true; hidepromptLabel.Hidden = true; promptcharLabel.Hidden = true; validationButton.Hidden = true; cultureButton.Hidden = true; promptcharButton.Hidden = true; hidepromptSwitch.Hidden = true; } private void ShowCulturePicker(object sender, EventArgs e) { cultureDoneButton.Hidden = false; culturePicker.Hidden = false; validationButton.Hidden = true; inputValidationModeLabel.Hidden = true; cultureLabel.Hidden = true; hidepromptLabel.Hidden = true; promptcharLabel.Hidden = true; validationButton.Hidden = true; cultureButton.Hidden = true; promptcharButton.Hidden = true; hidepromptSwitch.Hidden = true; } private void AllowSwitch_ValueChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { acccountmaskedEdit.HidePromptOnLeave = true; descriptionmaskedEdit.HidePromptOnLeave = true; amountmaskedEdit.HidePromptOnLeave = true; emailIDmaskedEdit.HidePromptOnLeave = true; mobileNumbermaskedEdit.HidePromptOnLeave = true; } else { acccountmaskedEdit.HidePromptOnLeave = false; descriptionmaskedEdit.HidePromptOnLeave = false; amountmaskedEdit.HidePromptOnLeave = false; emailIDmaskedEdit.HidePromptOnLeave = false; mobileNumbermaskedEdit.HidePromptOnLeave = false; } } void HideCulturePicker(object sender, EventArgs e) { cultureDoneButton.Hidden = true; culturePicker.Hidden = true; validationButton.Hidden = false; inputValidationModeLabel.Hidden = false; cultureLabel.Hidden = false; hidepromptLabel.Hidden = false; promptcharLabel.Hidden = false; validationButton.Hidden = false; cultureButton.Hidden = false; promptcharButton.Hidden = false; hidepromptSwitch.Hidden = false; } } } <file_sep>/Forms/Maps/Maps/Samples/ColorMappings/ColorMappingsViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; namespace SampleBrowser.SfMaps { [Preserve(AllMembers = true)] public class ColorMappingsViewModel { public ColorMappingsViewModel() { DataSource = new ObservableCollection<AgricultureData>(); DataSource.Add(new AgricultureData("Alabama", "Vegetables", 42)); DataSource.Add(new AgricultureData("Alaska", "Vegetables", 0)); DataSource.Add(new AgricultureData("Arizona", "Rice", 36)); DataSource.Add(new AgricultureData("Arkansas", "Vegetables", 46)); DataSource.Add(new AgricultureData("California", "Rice", 24)); DataSource.Add(new AgricultureData("Colorado", "Rice", 31)); DataSource.Add(new AgricultureData("Connecticut", "Grains", 18)); DataSource.Add(new AgricultureData("Delaware", "Grains", 28)); DataSource.Add(new AgricultureData("District of Columbia", "Grains", 27)); DataSource.Add(new AgricultureData("Florida", "Rice", 48)); DataSource.Add(new AgricultureData("Georgia", "Rice", 44)); DataSource.Add(new AgricultureData("Hawaii", "Grains", 49)); DataSource.Add(new AgricultureData("Idaho", "Grains", 8)); DataSource.Add(new AgricultureData("Illinois", "Vegetables", 26)); DataSource.Add(new AgricultureData("Indiana", "Grains", 21)); DataSource.Add(new AgricultureData("Iowa", "Vegetables", 13)); DataSource.Add(new AgricultureData("Kansas", "Rice", 33)); DataSource.Add(new AgricultureData("Kentucky", "Grains", 32)); DataSource.Add(new AgricultureData("Louisiana", "Rice", 47)); DataSource.Add(new AgricultureData("Maine", "Grains", 3)); DataSource.Add(new AgricultureData("Maryland", "Grains", 30)); DataSource.Add(new AgricultureData("Massachusetts", "Grains", 14)); DataSource.Add(new AgricultureData("Michigan", "Grains", 50)); DataSource.Add(new AgricultureData("Minnesota", "Wheat", 10)); DataSource.Add(new AgricultureData("Mississippi", "Vegetables", 43)); DataSource.Add(new AgricultureData("Missouri", "Vegetables", 35)); DataSource.Add(new AgricultureData("Montana", "Grains", 2)); DataSource.Add(new AgricultureData("Nebraska", "Rice", 15)); DataSource.Add(new AgricultureData("Nevada", "Wheat", 22)); DataSource.Add(new AgricultureData("New Hampshire", "Grains", 12)); DataSource.Add(new AgricultureData("New Jersey", "Vegetables", 20)); DataSource.Add(new AgricultureData("New Mexico", "Rice", 41)); DataSource.Add(new AgricultureData("New York", "Vegetables", 16)); DataSource.Add(new AgricultureData("North Carolina", "Rice", 38)); DataSource.Add(new AgricultureData("North Dakota", "Grains", 4)); DataSource.Add(new AgricultureData("Ohio", "Vegetables", 25)); DataSource.Add(new AgricultureData("Oklahoma", "Rice", 37)); DataSource.Add(new AgricultureData("Oregon", "Wheat", 11)); DataSource.Add(new AgricultureData("Pennsylvania", "Vegetables", 17)); DataSource.Add(new AgricultureData("Rhode Island", "Grains", 19)); DataSource.Add(new AgricultureData("South Carolina", "Rice", 45)); DataSource.Add(new AgricultureData("South Dakota", "Grains", 5)); DataSource.Add(new AgricultureData("Tennessee", "Vegetables", 39)); DataSource.Add(new AgricultureData("Texas", "Vegetables", 40)); DataSource.Add(new AgricultureData("Utah", "Rice", 23)); DataSource.Add(new AgricultureData("Vermont", "Grains", 9)); DataSource.Add(new AgricultureData("Virginia", "Rice", 34)); DataSource.Add(new AgricultureData("Washington", "Vegetables", 1)); DataSource.Add(new AgricultureData("West Virginia", "Grains", 29)); DataSource.Add(new AgricultureData("Wisconsin", "Grains", 7)); DataSource.Add(new AgricultureData("Wyoming", "Wheat", 6)); } public ObservableCollection<AgricultureData> DataSource { get; set; } } } <file_sep>/Forms/Rating/Rating/Samples/Rating_Customization/MyView.xaml.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Xamarin.Forms; namespace SampleBrowser.SfRating { public partial class CustomRatingView : Grid { public CustomRatingView(string imageSource, string percentageText, string ratingText, Rating_Customization Parent) { InitializeComponent(); image.Source = imageSource; percentageLabel.Text = percentageText; this.ratingText.Text = ratingText; Parent.RatingLabel.Add(percentageLabel); if (Device.RuntimePlatform == "UWP") { percentageLabel.FontSize = 10; percentageLabel.Margin = new Thickness(2); percentageLabel.BackgroundColor = Color.FromHex("#FF5500"); } if (Device.RuntimePlatform == "Android" || Device.RuntimePlatform == "iOS") { percentageLabel.WidthRequest = 25; } } } } <file_sep>/Android/SampleBrowser/Samples/Kanban/Customization.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Syncfusion.SfKanban.Android; using System.Collections.Generic; using Android.Graphics; using Android.Graphics.Drawables; namespace SampleBrowser { internal class CustomizationAdapter: KanbanAdapter { internal CustomizationAdapter(SfKanban kanban) : base(kanban) { } protected override void BindItemView(KanbanColumn column, KanbanItemViewHolder viewHolder, object data, int position) { TextView description = viewHolder.ItemDescription; description.SetMaxLines(4); base.BindItemView(column, viewHolder, data, position); } } public class KanbanCustomization : SamplePage { KanbanColumn menu; KanbanColumn order; KanbanColumn ready; KanbanColumn delivery; public override View GetSampleContent(Context context) { var kanban = new SfKanban(context); kanban.SetBackgroundColor(Color.ParseColor("#F2F2F2")); kanban.PlaceholderStyle.SelectedBackgroundColor = Color.ParseColor("#FBC7AB"); menu = new KanbanColumn(context) { Categories = new List<object>() { "Menu" } }; menu.Title = "Menu"; menu.AllowDrop = false; menu.ErrorBarSettings.Color = Color.ParseColor("#D53130"); kanban.Columns.Add(menu); order = new KanbanColumn(context) { Categories = new List<object>() { "Dining", "Delivery" } }; order.Title = "Order"; order.ErrorBarSettings.Color = Color.ParseColor("#D53130"); kanban.Columns.Add(order); ready = new KanbanColumn(context) { Categories = new List<object>() { "Ready" } }; ready.Title = "Ready to Serve"; ready.AllowDrag = false; ready.ErrorBarSettings.Color = Color.ParseColor("#D53130"); kanban.Columns.Add(ready); delivery = new KanbanColumn(context) { Categories = new List<object>() { "Door Delivery" } }; delivery.Title = "Delivery"; delivery.AllowDrag = false; delivery.ErrorBarSettings.Color = Color.ParseColor("#D53130"); kanban.Columns.Add(delivery); kanban.ItemsSource = new KanbanData().Data; kanban.Workflows.Add(new KanbanWorkflow("Menu", new List<object> { "Dining", "Delivery" })); kanban.Workflows.Add(new KanbanWorkflow("Dining", new List<object> { "Ready" })); kanban.Workflows.Add(new KanbanWorkflow("Delivery", new List<object> { "Door Delivery" })); kanban.DragStart += Kanban_DragStart; kanban.DragEnd += Kanban_DragEnd; kanban.DragOver += Kanban_DragOver; kanban.Adapter = new CustomizationAdapter(kanban); return kanban; } private void Kanban_DragOver(object sender, KanbanDragOverEventArgs e) { if (e.SourceColumn == menu) e.Cancel = true; } private void Kanban_DragEnd(object sender, KanbanDragEndEventArgs e) { if (e.TargetColumn == order) { e.Cancel = true; if (e.TargetColumn.IsExpanded) { e.TargetColumn.InsertItem(CloneModel(e.Data as CustomKanbanModel, e.TargetCategory), 0); } } } CustomKanbanModel CloneModel(CustomKanbanModel model, object category) { CustomKanbanModel newModel = new CustomKanbanModel(); newModel.Category = category; newModel.ColorKey = model.ColorKey; newModel.Description = model.Description; newModel.ID = model.ID; newModel.Tags = model.Tags; newModel.Title = model.Title; newModel.Name = model.Name; newModel.ImageURL = model.ImageURL; return newModel; } private void Kanban_DragStart(object sender, KanbanDragStartEventArgs e) { if (e.SourceColumn == menu) { e.KeepItem = true; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/Recurrence.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; using System.Drawing; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using nfloat = System.Single; using System.Drawing; #endif namespace SampleBrowser { public class Recurrence : SampleView { SFSchedule schedule; UIPickerView scheduleTypePicker = new UIPickerView(); public Recurrence() { schedule = new SFSchedule(); schedule.ScheduleView = SFScheduleView.SFScheduleViewMonth; schedule.Appointments = CreateAppointments(); schedule.MonthViewSettings.ShowAppointmentsInline = true; schedule.MonthInlineLoaded += Schedule_MonthInlineLoaded; schedule.MonthInlineAppointmentLoaded += Schedule_MonthInlineAppointmentLoaded; this.AddSubview(schedule); //control = this; } private void Schedule_MonthInlineAppointmentLoaded(object sender, MonthInlineAppointmentLoadedEventArgs e) { UIView mainView = new UIView(); mainView.BackgroundColor = UIColor.FromRGB(221, 221, 221); mainView.Frame = new RectangleF(0, 0, (float)UIScreen.MainScreen.Bounds.Size.Width, 40); UIView view = new UIView(); view.BackgroundColor = UIColor.FromRGB(246, 246, 246); view.Frame = new RectangleF(0, 0, (float)mainView.Frame.Size.Width, 38); UITextView startTime = new UITextView(); startTime.Text = DateTime.Parse(e.Appointment.StartTime.ToString()).ToString("hh:mm tt"); startTime.BackgroundColor = UIColor.FromRGB(246, 246, 246); startTime.TextColor = UIColor.FromRGB(0, 0, 0); startTime.Frame = new RectangleF(0, 0, ((float)mainView.Frame.Size.Width), (float)17.5); startTime.Font = UIFont.SystemFontOfSize(8, UIFontWeight.Bold); UITextView endTime = new UITextView(); endTime.Text = DateTime.Parse((e.Appointment.EndTime.ToString())).ToString("hh:mm tt"); endTime.BackgroundColor = UIColor.FromRGB(246, 246, 246); endTime.TextColor = UIColor.FromRGB(0, 0, 0); endTime.Frame = new RectangleF(0, 20, ((float)mainView.Frame.Size.Width), (float)17.5); endTime.Font = UIFont.SystemFontOfSize(8, UIFontWeight.Bold); UITextView subject = new UITextView(); subject.Text = e.Appointment.Subject.ToString(); subject.TextColor = UIColor.FromRGB(0, 0, 0); subject.BackgroundColor = UIColor.FromRGB(246, 246, 246); subject.Frame = new RectangleF(100, 5, (float)mainView.Frame.Size.Width, 30); subject.Font = UIFont.SystemFontOfSize(12, UIFontWeight.Bold); view.AddSubview(startTime); view.AddSubview(endTime); view.AddSubview(subject); mainView.AddSubview(view); e.View = mainView; } private void Schedule_MonthInlineLoaded(object sender, MonthInlineLoadedEventArgs e) { e.MonthInlineViewStyle.BackgroundColor = UIColor.FromRGB(246, 246, 246); e.MonthInlineViewStyle.TextColor = UIColor.Black; } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = new CGRect(Frame.X, 0, Frame.Width, Frame.Height); } base.LayoutSubviews(); } protected override void Dispose(bool disposing) { if (schedule != null) { this.schedule.Dispose(); } this.schedule = null; } NSMutableArray CreateAppointments() { NSDate today = new NSDate(); NSMutableArray appCollection = new NSMutableArray(); NSCalendar calendar = NSCalendar.CurrentCalendar; //Client Meeting recusive appointments // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components.Hour = 10; components.Minute = 0; components.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents.Hour = 12; endDateComponents.Minute = 0; endDateComponents.Second = 0; NSDate startDate = calendar.DateFromComponents(components); NSDate endDate = calendar.DateFromComponents(endDateComponents); ScheduleAppointment ClientMeeting_Recurrence = new ScheduleAppointment(); ClientMeeting_Recurrence.StartTime = startDate; ClientMeeting_Recurrence.EndTime = endDate; ClientMeeting_Recurrence.Subject = (NSString)@"Occurs on Every 1 week"; //assinging RFC stardard recurring rule. ClientMeeting_Recurrence.RecurrenceRule = (NSString)@"FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;COUNT=10"; ClientMeeting_Recurrence.IsRecursive = true; // ClientMeeting_Recurrence.AppointmentBackground = UIColor.FromRGB(red:0.106, green:0.631, blue:0.886 ); ClientMeeting_Recurrence.AppointmentBackground = UIColor.FromRGB(0xD8, 0x00, 0x73); appCollection.Add(ClientMeeting_Recurrence); // Get the year, month, day from the date NSDateComponents components1 = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second components1.Hour = 12; components1.Minute = 0; components1.Second = 0; // Get the year, month, day from the date NSDateComponents endDateComponents1 = calendar.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second endDateComponents1.Hour = 13; endDateComponents1.Minute = 0; endDateComponents1.Second = 0; NSDate startDate1 = calendar.DateFromComponents(components1); NSDate endDate1 = calendar.DateFromComponents(endDateComponents1); ScheduleAppointment General_Meeting_Recurrence = new ScheduleAppointment(); General_Meeting_Recurrence.StartTime = startDate1; General_Meeting_Recurrence.EndTime = endDate1; General_Meeting_Recurrence.Subject = (NSString)@"Occurs on Every 2 days"; //assinging RFC stardard recurring rule. General_Meeting_Recurrence.RecurrenceRule = (NSString)@"FREQ=DAILY;INTERVAL=2;COUNT=25"; General_Meeting_Recurrence.IsRecursive = true; // ClientMeeting_Recurrence.AppointmentBackground = UIColor.FromRGB(red:0.106, green:0.631, blue:0.886 ); General_Meeting_Recurrence.AppointmentBackground = UIColor.FromRGB(0xA2, 0xC1, 0x39); appCollection.Add(General_Meeting_Recurrence); return appCollection; } } } <file_sep>/Forms/Carousel/Carousel/Samples/Carousel_View/Carousel_Tablet.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfCarousel.XForms; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfCarousel { /// <summary> /// Carousel tablet. /// </summary> public partial class Carousel_Tablet : SampleView { #region constructor /// <summary> /// Initializes a new instance of the <see cref="T:SampleBrowser.SfCarousel.Carousel_Tablet"/> class. /// </summary> public Carousel_Tablet() { InitializeComponent(); modePicker.SelectedIndex = 0; carousel.BindingContext = new CarouselViewModel(); DeviceChanges(); } #endregion #region device changes /// <summary> /// Devices the changes. /// </summary> void DeviceChanges() { if (Device.RuntimePlatform == Device.iOS) { carousel.ItemHeight = 200; carousel.ItemWidth = 150; } if (Device.RuntimePlatform == Device.Android) { carousel.ItemHeight = Convert.ToInt32(300); carousel.ItemWidth = Convert.ToInt32(180); carousel.ScaleOffset = (float)0.70; } } #endregion #region viewmode changes /// <summary> /// Viewmodes the picker selected index changed. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> void viewmodePicker_SelectedIndexChanged(object sender, EventArgs e) { switch (modePicker.SelectedIndex) { case 0: carousel.ViewMode = ViewMode.Default; break; case 1: carousel.ViewMode = ViewMode.Linear; break; } } #endregion #region offset changes /// <summary> /// Offsets the value changed. /// </summary> /// <param name="c">C.</param> /// <param name="e">E.</param> public void offsetValue_Changed(object c, TextChangedEventArgs e) { if (e.NewTextValue.Length > 0) { carousel.Offset = int.Parse(e.NewTextValue); } } #endregion #region scale changes /// <summary> /// Scales the value changed. /// </summary> /// <param name="c">C.</param> /// <param name="e">E.</param> public void ScaleValue_Changed(object c, TextChangedEventArgs e) { if (e.NewTextValue.Length > 0) { if (float.Parse(e.NewTextValue) <= 1) { carousel.ScaleOffset = float.Parse(e.NewTextValue); } else { carousel.ScaleOffset = 1.0f; } } } #endregion #region rotation changes /// <summary> /// Rotates the value changed. /// </summary> /// <param name="c">C.</param> /// <param name="e">E.</param> public void rotateValue_Changed(object c, TextChangedEventArgs e) { if (e.NewTextValue.Length > 0) { if (float.Parse(e.NewTextValue) > 0 && float.Parse(e.NewTextValue) <= 360) { carousel.RotationAngle = int.Parse(e.NewTextValue); } else { carousel.RotationAngle = 45; } } } #endregion #region SB view /// <summary> /// Gets the content. /// </summary> /// <returns>The content.</returns> public View getContent() { return this.Content; } #endregion #region Property view /// <summary> /// Gets the property view. /// </summary> /// <returns>The property view.</returns> public View getPropertyView() { return this.PropertyView; } #endregion } } <file_sep>/iOS/SampleBrowser/Resources/Samples/AutoComplete/AutoComplete_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfAutoComplete.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class AutoComplete_Mobile:SampleView { NSMutableArray countryList = new NSMutableArray(); UILabel suggestionModeLabel,autoCompleteModeLabel,minPrefixCharacterLabel,maxDropDownHeightLabel,popupDelayLabel; UIButton suggestionButton = new UIButton (); UIButton autoCompleteButton = new UIButton (); UIButton suggestionDoneButton=new UIButton(); UIPickerView suggestionModePicker, autoCompleteModePicker; UITextView minimumText,maximumText,popUpDelayText; private string selectedType; private readonly IList<string> exp = new List<string> (); private string experienceSelectedType; UIPickerView experiencePicker = new UIPickerView (); SFAutoComplete countryAutoComplete,jobFieldAutoComplete; UILabel jobSearchLabel,countryLabel,jobTitleLabel,experienceLabel; UIButton searchButton = new UIButton (); UIButton experienceButton = new UIButton (); UIButton autoCompleteDoneButton = new UIButton (); NSMutableArray jobTitle = new NSMutableArray (); PickerModel experienceModel,suggestionModel,autoCompleteModel; private readonly IList<string> suggestionModeList = new List<string>{ "StartsWith", "StartsWithCaseSensitive", "Contains", "ContainsWithCaseSensitive", "EndsWith", "EndsWithCaseSensitive", "Equals", "EqualsWithCaseSensitive" }; private readonly IList<string> autoCompleteModeList = new List<string>{ "Append", "Suggest", "SuggestAppend" }; private readonly IList<string> experienceList = new List<string>{ "1", "2" }; public UIView option = new UIView(); UIScrollView propertyScrollView; public void createOptionView() { propertyScrollView = new UIScrollView(); propertyScrollView.Frame = this.OptionView.Frame; propertyScrollView.ContentSize = new CGSize(propertyScrollView.Frame.Width,propertyScrollView.Frame.Height+120); this.propertyScrollView.AddSubview (maxDropDownHeightLabel); this.propertyScrollView.AddSubview (popupDelayLabel); this.propertyScrollView.AddSubview (minimumText); this.propertyScrollView.AddSubview (maximumText); this.propertyScrollView.AddSubview (popUpDelayText); this.propertyScrollView.AddSubview (suggestionModeLabel); this.propertyScrollView.AddSubview (autoCompleteModeLabel); this.propertyScrollView.AddSubview (suggestionButton); this.propertyScrollView.AddSubview (minPrefixCharacterLabel); this.propertyScrollView.AddSubview (autoCompleteButton); this.propertyScrollView.AddSubview (suggestionModePicker); this.propertyScrollView.AddSubview (autoCompleteModePicker); this.propertyScrollView.AddSubview (suggestionDoneButton); this.option.AddSubview(propertyScrollView); } public AutoComplete_Mobile() { //countryAutoComplete countryAutoComplete = new SFAutoComplete(); countryAutoComplete.AutoCompleteSource =countryList ; countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeStartsWith; countryAutoComplete.Watermark= (NSString)"Enter a country name"; countryAutoComplete.MaxDropDownHeight=90; countryAutoComplete.AutoCompleteMode= SFAutoCompleteAutoCompleteMode.SFAutoCompleteAutoCompleteModeSuggest; //jobFieldAutoComplete jobFieldAutoComplete = new SFAutoComplete(); jobFieldAutoComplete.AutoCompleteSource = jobTitle; jobFieldAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeStartsWith; jobFieldAutoComplete.Watermark=(NSString)"Starts with ’S’, ‘M’ or ‘B’"; jobFieldAutoComplete.MaxDropDownHeight=90; jobFieldAutoComplete.AutoCompleteMode= SFAutoCompleteAutoCompleteMode.SFAutoCompleteAutoCompleteModeSuggest; this.AddSubview(countryAutoComplete); this.AddSubview(jobFieldAutoComplete); mainPageDesign(); loadOptionView(); } public void mainPageDesign() { this.OptionView = new UIView(); experienceModel = new PickerModel(experienceList); this.addingCountryList(); suggestionModePicker = new UIPickerView(); autoCompleteModePicker = new UIPickerView(); suggestionModel = new PickerModel(suggestionModeList); suggestionModePicker.Model = suggestionModel; autoCompleteModel = new PickerModel(autoCompleteModeList); autoCompleteModePicker.Model = autoCompleteModel; suggestionModeLabel = new UILabel(); autoCompleteModeLabel = new UILabel(); minPrefixCharacterLabel = new UILabel(); maxDropDownHeightLabel = new UILabel(); popupDelayLabel = new UILabel(); suggestionButton = new UIButton(); autoCompleteButton = new UIButton(); //adding job fileds this.jobTitle.Add((NSString)"Banking"); this.jobTitle.Add((NSString)"Software"); this.jobTitle.Add((NSString)"Media"); this.jobTitle.Add((NSString)"Medical"); //adding experiencee this.exp.Add((NSString)"1"); this.exp.Add((NSString)"2"); jobSearchLabel = new UILabel(); countryLabel = new UILabel(); jobTitleLabel = new UILabel(); experienceLabel = new UILabel(); searchButton = new UIButton(); //jobSearchLabell jobSearchLabel.Text = "Job Search"; jobSearchLabel.TextColor = UIColor.Black; jobSearchLabel.TextAlignment = UITextAlignment.Left; jobSearchLabel.Font = UIFont.FromName("Helvetica-Bold", 20f); //countryLabell countryLabel.Text = "Country"; countryLabel.TextColor = UIColor.Black; countryLabel.TextAlignment = UITextAlignment.Left; countryLabel.Font = UIFont.FromName("Helvetica", 16f); //jobTitleLabell jobTitleLabel.Text = "Job Title"; jobTitleLabel.TextColor = UIColor.Black; jobTitleLabel.TextAlignment = UITextAlignment.Left; jobTitleLabel.Font = UIFont.FromName("Helvetica", 16f); //experienceLabell experienceLabel.Text = "Experience"; experienceLabel.TextColor = UIColor.Black; experienceLabel.TextAlignment = UITextAlignment.Left; experienceLabel.Font = UIFont.FromName("Helvetica", 16f); //searchButtonn searchButton.SetTitle("Search", UIControlState.Normal); searchButton.BackgroundColor = UIColor.FromRGB(50, 150, 221); searchButton.SetTitleColor(UIColor.Black, UIControlState.Normal); searchButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; searchButton.Layer.CornerRadius = 8; searchButton.Layer.BorderWidth = 2; searchButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; searchButton.TouchUpInside += SelectResults; //experienceButtonn experienceButton.SetTitle("1", UIControlState.Normal); experienceButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; experienceButton.BackgroundColor = UIColor.Clear; experienceButton.SetTitleColor(UIColor.Black, UIControlState.Normal); experienceButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; experienceButton.Layer.BorderWidth = 4; experienceButton.Layer.CornerRadius = 8; experienceButton.TouchUpInside += ShowExperiencePicker; this.AddSubview(experienceButton); PickerModel models = new PickerModel(this.exp); models.PickerChanged += (sender, e) => { this.experienceSelectedType = e.SelectedValue; experienceButton.SetTitle(experienceSelectedType, UIControlState.Normal); }; //experiencePickerr experiencePicker.ShowSelectionIndicator = true; experiencePicker.Hidden = true; experiencePicker.Model = experienceModel; experiencePicker.BackgroundColor = UIColor.White; //autoCompleteDoneButtonn autoCompleteDoneButton.SetTitle("Done\t", UIControlState.Normal); autoCompleteDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; autoCompleteDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); autoCompleteDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); autoCompleteDoneButton.Hidden = true; autoCompleteDoneButton.TouchUpInside += HideexperiencePicker; //add vieww this.AddSubview(experiencePicker); this.AddSubview(autoCompleteDoneButton); this.AddSubview(jobSearchLabel); this.AddSubview(countryLabel); this.AddSubview(jobTitleLabel); this.AddSubview(experienceLabel); this.AddSubview(searchButton); } public void loadOptionView() { //suggestionModeLabell suggestionModeLabel.Text = "Suggestion Mode"; suggestionModeLabel.TextColor = UIColor.Black; suggestionModeLabel.TextAlignment = UITextAlignment.Left; autoCompleteModeLabel.Text = "AutoComplete Mode"; autoCompleteModeLabel.TextColor = UIColor.Black; autoCompleteModeLabel.TextAlignment = UITextAlignment.Left; //minPrefixCharacterLabell minPrefixCharacterLabel.Text = "Min Prefix Character"; minPrefixCharacterLabel.TextColor = UIColor.Black; minPrefixCharacterLabel.TextAlignment = UITextAlignment.Left; minPrefixCharacterLabel.Font = UIFont.FromName("Helvetica", 14f); //maxDropDownHeightLabell maxDropDownHeightLabel.Text = "Max DropDownHeight"; maxDropDownHeightLabel.TextColor = UIColor.Black; maxDropDownHeightLabel.TextAlignment = UITextAlignment.Left; maxDropDownHeightLabel.Font = UIFont.FromName("Helvetica", 14f); //popupDelayLabel popupDelayLabel.Text = "Popup Delay"; popupDelayLabel.TextColor = UIColor.Black; popupDelayLabel.TextAlignment = UITextAlignment.Left; popupDelayLabel.Font = UIFont.FromName("Helvetica", 14f); //suggestionButtonn suggestionButton.SetTitle("StartsWith", UIControlState.Normal); suggestionButton.SetTitleColor(UIColor.Black, UIControlState.Normal); suggestionButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; suggestionButton.Layer.CornerRadius = 8; suggestionButton.Layer.BorderWidth = 2; suggestionButton.TouchUpInside += ShowsuggestionModePicker; suggestionButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //Text minimumText = new UITextView(); maximumText = new UITextView(); popUpDelayText = new UITextView(); minimumText.Layer.BorderColor = UIColor.Black.CGColor; maximumText.Layer.BorderColor = UIColor.Black.CGColor; popUpDelayText.Layer.BorderColor = UIColor.Black.CGColor; minimumText.BackgroundColor = UIColor.FromRGB(246, 246, 246); maximumText.BackgroundColor = UIColor.FromRGB(246, 246, 246); popUpDelayText.BackgroundColor = UIColor.FromRGB(246, 246, 246); minimumText.KeyboardType = UIKeyboardType.NumberPad; maximumText.KeyboardType = UIKeyboardType.NumberPad; popUpDelayText.KeyboardType = UIKeyboardType.NumberPad; minimumText.Text = "1"; maximumText.Text = "400"; popUpDelayText.Text = "100"; maximumText.Changed += (object sender, EventArgs e) => { if (maximumText.Text.Length > 0) { countryAutoComplete.MaxDropDownHeight = double.Parse(maximumText.Text); jobFieldAutoComplete.MaxDropDownHeight = double.Parse(maximumText.Text); } else { countryAutoComplete.MaxDropDownHeight = 200; jobFieldAutoComplete.MaxDropDownHeight = 200; } }; minimumText.Changed += (object sender, EventArgs e) => { if (minimumText.Text.Length > 0) { countryAutoComplete.MinimumPrefixCharacters = int.Parse(minimumText.Text); jobFieldAutoComplete.MinimumPrefixCharacters = int.Parse(minimumText.Text); } else { countryAutoComplete.MinimumPrefixCharacters = 1; jobFieldAutoComplete.MinimumPrefixCharacters = 1; } }; popUpDelayText.Changed += (object sender, EventArgs e) => { if (popUpDelayText.Text.Length > 0) { countryAutoComplete.PopUpDelay = double.Parse(popUpDelayText.Text); jobFieldAutoComplete.PopUpDelay = double.Parse(popUpDelayText.Text); } else { countryAutoComplete.PopUpDelay = 100; jobFieldAutoComplete.PopUpDelay = 100; } }; //autoCompleteButton autoCompleteButton.SetTitle("Suggest", UIControlState.Normal); autoCompleteButton.SetTitleColor(UIColor.Black, UIControlState.Normal); autoCompleteButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; autoCompleteButton.Layer.CornerRadius = 8; autoCompleteButton.Layer.BorderWidth = 2; autoCompleteButton.TouchUpInside += ShowautoCompleteModePicker; autoCompleteButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; //suggestionDoneButton suggestionDoneButton.SetTitle("Done\t", UIControlState.Normal); suggestionDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); suggestionDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; suggestionDoneButton.TouchUpInside += HidePicker; suggestionDoneButton.Hidden = true; suggestionDoneButton.BackgroundColor = UIColor.FromRGB(246, 246, 246); suggestionModel.PickerChanged += suggestionSelectedIndexChanged; autoCompleteModel.PickerChanged += autoCompleteSelectedIndexChanged; experienceModel.PickerChanged += experienceSelectedIndexChanged; suggestionModePicker.ShowSelectionIndicator = true; suggestionModePicker.Hidden = true; suggestionModePicker.BackgroundColor = UIColor.Gray; autoCompleteModePicker.BackgroundColor = UIColor.Gray; autoCompleteModePicker.ShowSelectionIndicator = true; autoCompleteModePicker.Hidden = true; } public void addingCountryList() { countryList.Add ((NSString)"Afghanistan"); countryList.Add ((NSString)"Akrotiri"); countryList.Add ((NSString)"Albania"); countryList.Add ((NSString)"Algeria"); countryList.Add ((NSString)"American Samoa"); countryList.Add ((NSString)"Andorra"); countryList.Add ((NSString)"Angola"); countryList.Add ((NSString)"Anguilla"); countryList.Add ((NSString)"Antarctica"); countryList.Add ((NSString)"Antigua and Barbuda"); countryList.Add ((NSString)"Argentina"); countryList.Add ((NSString)"Armenia"); countryList.Add ((NSString)"Aruba"); countryList.Add ((NSString)"Ashmore and Cartier Islands"); countryList.Add ((NSString)"Australia"); countryList.Add ((NSString)"Austria"); countryList.Add ((NSString)"Azerbaijan"); countryList.Add ((NSString)"Bahamas, The"); countryList.Add ((NSString)"Bahrain"); countryList.Add ((NSString)"Bangladesh"); countryList.Add ((NSString)"Barbados"); countryList.Add ((NSString)"Bassas da India"); countryList.Add ((NSString)"Belarus"); countryList.Add ((NSString)"Belgium"); countryList.Add ((NSString)"Belize"); countryList.Add ((NSString)"Benin"); countryList.Add ((NSString)"Bermuda"); countryList.Add ((NSString)"Bhutan"); countryList.Add ((NSString)"Bolivia"); countryList.Add ((NSString)"Bosnia and Herzegovina"); countryList.Add ((NSString)"Botswana"); countryList.Add ((NSString)"Bouvet Island"); countryList.Add ((NSString)"Brazil"); countryList.Add ((NSString)"British Indian Ocean Territory"); countryList.Add ((NSString)"British Virgin Islands"); countryList.Add ((NSString)"Brunei"); countryList.Add ((NSString)"Bulgaria"); countryList.Add ((NSString)"Burkina Faso"); countryList.Add ((NSString)"Burma"); countryList.Add ((NSString)"Burundi"); countryList.Add ((NSString)"Cambodia"); countryList.Add ((NSString)"Cameroon"); countryList.Add ((NSString)"Canada"); countryList.Add ((NSString)"Cape Verde"); countryList.Add ((NSString)"Cayman Islands"); countryList.Add ((NSString)"Central African Republic"); countryList.Add ((NSString)"Chad"); countryList.Add ((NSString)"Chile"); countryList.Add ((NSString)"China"); countryList.Add ((NSString)"Christmas Island"); countryList.Add ((NSString)"Clipperton Island"); countryList.Add ((NSString)"Cocos (Keeling) Islands"); countryList.Add ((NSString)"Colombia"); countryList.Add ((NSString)"Comoros"); countryList.Add ((NSString)"Congo"); countryList.Add ((NSString)"Congo, Republic of the"); countryList.Add ((NSString)"Cook Islands"); countryList.Add ((NSString)"Coral Sea Islands"); countryList.Add ((NSString)"Costa Rica"); countryList.Add ((NSString)"Cote d'Ivoire"); countryList.Add ((NSString)"Croatia"); countryList.Add ((NSString)"Cuba"); countryList.Add ((NSString)"Cyprus"); countryList.Add ((NSString)"Czech Republic"); countryList.Add ((NSString)"Denmark"); countryList.Add ((NSString)"Dhekelia"); countryList.Add ((NSString)"Djibouti"); countryList.Add ((NSString)"Dominica"); countryList.Add ((NSString)"Dominican Republic"); countryList.Add ((NSString)"Ecuador"); countryList.Add ((NSString)"Egypt"); countryList.Add ((NSString)"El Salvador"); countryList.Add ((NSString)"Equatorial Guinea"); countryList.Add ((NSString)"Eritrea"); countryList.Add ((NSString)"Estonia"); countryList.Add ((NSString)"Ethiopia"); countryList.Add ((NSString)"Europa Island"); countryList.Add ((NSString)"Falkland Islands"); countryList.Add ((NSString)"Faroe Islands"); countryList.Add ((NSString)"Fiji"); countryList.Add ((NSString)"Finland"); countryList.Add ((NSString)"France"); countryList.Add ((NSString)"French Guiana"); countryList.Add ((NSString)"French Polynesia"); countryList.Add ((NSString)"French Southern and Antarctic Lands"); countryList.Add ((NSString)"Gabon"); countryList.Add ((NSString)"Gambia, The"); countryList.Add ((NSString)"Gaza Strip"); countryList.Add ((NSString)"Georgia"); countryList.Add ((NSString)"Germany"); countryList.Add ((NSString)"Ghana"); countryList.Add ((NSString)"Gibraltar"); countryList.Add ((NSString)"Glorioso Islands"); countryList.Add ((NSString)"Greece"); countryList.Add ((NSString)"Greenland"); countryList.Add ((NSString)"Grenada"); countryList.Add ((NSString)"Guadeloupe"); countryList.Add ((NSString)"Guam"); countryList.Add ((NSString)"Guatemala"); countryList.Add ((NSString)"Guernsey"); countryList.Add ((NSString)"Guinea"); countryList.Add ((NSString)"Guinea-Bissau"); countryList.Add ((NSString)"Guyana"); countryList.Add ((NSString)"Haiti"); countryList.Add ((NSString)"Heard Island and McDonald Islands"); countryList.Add ((NSString)"Holy See"); countryList.Add ((NSString)"Honduras"); countryList.Add ((NSString)"Hong Kong"); countryList.Add ((NSString)"Hungary"); countryList.Add ((NSString)"Iceland"); countryList.Add ((NSString)"India"); countryList.Add ((NSString)"Indonesia"); countryList.Add ((NSString)"Iran"); countryList.Add ((NSString)"Iraq"); countryList.Add ((NSString)"Ireland"); countryList.Add ((NSString)"Isle of Man"); countryList.Add ((NSString)"Israel"); countryList.Add ((NSString)"Italy"); countryList.Add ((NSString)"Jamaica"); countryList.Add ((NSString)"Jan Mayen"); countryList.Add ((NSString)"Japan"); countryList.Add ((NSString)"Jersey"); countryList.Add ((NSString)"Jordan"); countryList.Add ((NSString)"Juan de Nova Island"); countryList.Add ((NSString)"Kazakhstan"); countryList.Add ((NSString)"Kenya"); countryList.Add ((NSString)"Kiribati"); countryList.Add ((NSString)"Korea, North"); countryList.Add ((NSString)"Korea, South"); countryList.Add ((NSString)"Kuwait"); countryList.Add ((NSString)"Kyrgyzstan"); countryList.Add ((NSString)"Laos"); countryList.Add ((NSString)"Latvia"); countryList.Add ((NSString)"Lebanon"); countryList.Add ((NSString)"Lesotho"); countryList.Add ((NSString)"Liberia"); countryList.Add ((NSString)"Libya"); countryList.Add ((NSString)"Liechtenstein"); countryList.Add ((NSString)"Lithuania"); countryList.Add ((NSString)"Luxembourg"); countryList.Add ((NSString)"Macau"); countryList.Add ((NSString)"Macedonia"); countryList.Add ((NSString)"Madagascar"); countryList.Add ((NSString)"Malawi"); countryList.Add ((NSString)"Malaysia"); countryList.Add ((NSString)"Maldives"); countryList.Add ((NSString)"Mali"); countryList.Add ((NSString)"Malta"); countryList.Add ((NSString)"Marshall Islands"); countryList.Add ((NSString)"Martinique"); countryList.Add ((NSString)"Mauritania"); countryList.Add ((NSString)"Mauritius"); countryList.Add ((NSString)"Mayotte"); countryList.Add ((NSString)"Mexico"); countryList.Add ((NSString)"Micronesia"); countryList.Add ((NSString)"Moldova"); countryList.Add ((NSString)"Monaco"); countryList.Add ((NSString)"Mongolia"); countryList.Add ((NSString)"Montserrat"); countryList.Add ((NSString)"Morocco"); countryList.Add ((NSString)"Mozambique"); countryList.Add ((NSString)"Namibia"); countryList.Add ((NSString)"Nauru"); countryList.Add ((NSString)"Navassa Island"); countryList.Add ((NSString)"Nepal"); countryList.Add ((NSString)"Netherlands"); countryList.Add ((NSString)"Netherlands Antilles"); countryList.Add ((NSString)"New Caledonia"); countryList.Add ((NSString)"New Zealand"); countryList.Add ((NSString)"Nicaragua"); countryList.Add ((NSString)"Niger"); countryList.Add ((NSString)"Nigeria"); countryList.Add ((NSString)"Niue"); countryList.Add ((NSString)"Norfolk Island"); countryList.Add ((NSString)"Northern Mariana Islands"); countryList.Add ((NSString)"Norway"); countryList.Add ((NSString)"Oman"); countryList.Add ((NSString)"Pakistan"); countryList.Add ((NSString)"Palau"); countryList.Add ((NSString)"Panama"); countryList.Add ((NSString)"Papua New Guinea"); countryList.Add ((NSString)"Paracel Islands"); countryList.Add ((NSString)"Paraguay"); countryList.Add ((NSString)"Peru"); countryList.Add ((NSString)"Philippines"); countryList.Add ((NSString)"Pitcairn Islands"); countryList.Add ((NSString)"Poland"); countryList.Add ((NSString)"Portugal"); countryList.Add ((NSString)"Puerto Rico"); countryList.Add ((NSString)"Qatar"); countryList.Add ((NSString)"Reunion"); countryList.Add ((NSString)"Romania"); countryList.Add ((NSString)"Russia"); countryList.Add ((NSString)"Rwanda"); countryList.Add ((NSString)"Saint Helena"); countryList.Add ((NSString)"Saint Kitts and Nevis"); countryList.Add ((NSString)"Saint Lucia"); countryList.Add ((NSString)"Saint Pierre and Miquelon"); countryList.Add ((NSString)"Saint Vincent"); countryList.Add ((NSString)"Samoa"); countryList.Add ((NSString)"San Marino"); countryList.Add ((NSString)"Sao Tome and Principe"); countryList.Add ((NSString)"Saudi Arabia"); countryList.Add ((NSString)"Senegal"); countryList.Add ((NSString)"Serbia and Montenegro"); countryList.Add ((NSString)"Seychelles"); countryList.Add ((NSString)"Sierra Leone"); countryList.Add ((NSString)"Singapore"); countryList.Add ((NSString)"Slovakia"); countryList.Add ((NSString)"Slovenia"); countryList.Add ((NSString)"Solomon Islands"); countryList.Add ((NSString)"Somalia"); countryList.Add ((NSString)"South Africa"); countryList.Add ((NSString)"South Georgia"); countryList.Add ((NSString)"Spain"); countryList.Add ((NSString)"Spratly Islands"); countryList.Add ((NSString)"Sri Lanka"); countryList.Add ((NSString)"Sudan"); countryList.Add ((NSString)"Suriname"); countryList.Add ((NSString)"Svalbard"); countryList.Add ((NSString)"Swaziland"); countryList.Add ((NSString)"Sweden"); countryList.Add ((NSString)"Switzerland"); countryList.Add ((NSString)"Syria"); countryList.Add ((NSString)"Taiwan"); countryList.Add ((NSString)"Tajikistan"); countryList.Add ((NSString)"Tanzania"); countryList.Add ((NSString)"Thailand"); countryList.Add ((NSString)"Timor-Leste"); countryList.Add ((NSString)"Togo"); countryList.Add ((NSString)"Tokelau"); countryList.Add ((NSString)"Tonga"); countryList.Add ((NSString)"Trinidad and Tobago"); countryList.Add ((NSString)"Tromelin Island"); countryList.Add ((NSString)"Tunisia"); countryList.Add ((NSString)"Turkey"); countryList.Add ((NSString)"Turkmenistan"); countryList.Add ((NSString)"Turks and Caicos Islands"); countryList.Add ((NSString)"Tuvalu"); countryList.Add ((NSString)"Uganda"); countryList.Add ((NSString)"Ukraine"); countryList.Add ((NSString)"United Arab Emirates"); countryList.Add ((NSString)"United Kingdom"); countryList.Add ((NSString)"United States"); countryList.Add ((NSString)"Uruguay"); countryList.Add ((NSString)"Uzbekistan"); countryList.Add ((NSString)"Vanuatu"); countryList.Add ((NSString)"Venezuela"); countryList.Add ((NSString)"Vietnam"); countryList.Add ((NSString)"Virgin Islands"); countryList.Add ((NSString)"Wake Island"); countryList.Add ((NSString)"Wallis and Futuna"); countryList.Add ((NSString)"West Bank"); countryList.Add ((NSString)"Western Sahara"); countryList.Add ((NSString)"Yemen"); countryList.Add ((NSString)"Zambia"); countryList.Add ((NSString)"Zimbabwe"); } void ShowExperiencePicker (object sender, EventArgs e) { searchButton.Hidden = true; autoCompleteDoneButton.Hidden = false; experiencePicker.Hidden = false; this.BecomeFirstResponder (); } public override void TouchesBegan (NSSet touches, UIEvent evt){ this.EndEditing (true); } void SelectResults (object sender, EventArgs e) { if (countryAutoComplete.TextField.Text != "" && jobFieldAutoComplete.TextField.Text != "") { NSString s1 = (NSString)countryAutoComplete.Text; NSString s2 = (NSString)jobFieldAutoComplete.Text; nint s4 = 0; if (s1 != null && s2 != null) { Random r = new Random(); s4 = r.Next (5,60); } UIAlertView v = new UIAlertView (); v.Title = "Results"; if (s4 > 0) v.Message = s4 + " Jobs found"; else v.Message = "0 Jobs found"; v.AddButton ("OK"); v.Show (); } else { UIAlertView v1 = new UIAlertView (); v1.Title = "Results"; v1.AddButton ("OK"); v1.Message = "0 Jobs found"; v1.Show (); } this.BecomeFirstResponder (); } void HideexperiencePicker (object sender, EventArgs e) { searchButton.Hidden = false; autoCompleteDoneButton.Hidden = true; experiencePicker.Hidden = true; this.BecomeFirstResponder (); } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; this.OptionView.Frame = view.Frame; option.Frame = new CGRect (0,60,Frame.Width,Frame.Height); suggestionModeLabel.Frame = new CGRect ( 10,10, this.Frame.Size.Width-10, 30); autoCompleteModeLabel.Frame = new CGRect ( 10, 100, this.Frame.Size.Width-20, 30); minPrefixCharacterLabel.Frame = new CGRect ( 10, 200,this.Frame.Size.Width-10 , 30); maxDropDownHeightLabel.Frame = new CGRect (10, 250, this.Frame.Size.Width - 10, 30); suggestionButton.Frame=new CGRect(10, 50, this.Frame.Size.Width - 20, 30); popupDelayLabel.Frame = new CGRect (10, 300, this.Frame.Size.Width - 10, 30); autoCompleteButton.Frame=new CGRect(10, 140, this.Frame.Size.Width - 20, 30); minimumText.Frame = new CGRect (230, 200, this.Frame.Size.Width - 250, 30); maximumText.Frame = new CGRect (230, 250, this.Frame.Size.Width - 250, 30); popUpDelayText.Frame = new CGRect (230, 300, this.Frame.Size.Width - 250, 30); suggestionModePicker.Frame = new CGRect (0, this.Frame.Size.Height/4, this.Frame.Size.Width, this.Frame.Size.Height/3); autoCompleteModePicker.Frame = new CGRect (0, this.Frame.Size.Height/4, this.Frame.Size.Width , this.Frame.Size.Height/3); suggestionDoneButton.Frame = new CGRect (0, this.Frame.Size.Height/4, this.Frame.Size.Width, 30); jobSearchLabel.Frame = new CGRect ( 10, 10, view.Frame.Width, 30); countryLabel.Frame = new CGRect ( 10, 50, view.Frame.Width, 30); jobTitleLabel.Frame = new CGRect ( 10,130 ,view.Frame.Width, 30); experienceLabel.Frame = new CGRect ( 10,210, view.Frame.Width, 30); countryAutoComplete.Frame = new CGRect ( 10, 80, this.Frame.Size.Width -20, 40); jobFieldAutoComplete.Frame = new CGRect ( 10, 160, this.Frame.Size.Width - 20, 40); experienceButton.Frame = new CGRect ( 10, 250, this.Frame.Size.Width - 20, 40); experiencePicker.Frame=new CGRect(0,this.Frame.Size.Height - (this.Frame.Size.Height / 3), this.Frame.Size.Width,this.Frame.Size.Height/3); autoCompleteDoneButton.Frame=new CGRect(0, this.Frame.Size.Height-(this.Frame.Size.Height/3), this.Frame.Size.Width, 40); searchButton.Frame = new CGRect ( 10,310, this.Frame.Size.Width -20, 40); } this.createOptionView (); base.LayoutSubviews (); } void ShowsuggestionModePicker (object sender, EventArgs e) { minimumText.EndEditing(true); maximumText.EndEditing(true); popUpDelayText.EndEditing(true); suggestionDoneButton.Hidden = false; suggestionModePicker.Hidden = false; autoCompleteModePicker.Hidden = true; } void HidePicker (object sender, EventArgs e) { suggestionDoneButton.Hidden = true; autoCompleteModePicker.Hidden = true; suggestionModePicker.Hidden = true; } void ShowautoCompleteModePicker (object sender, EventArgs e) { minimumText.EndEditing(true); maximumText.EndEditing(true); popUpDelayText.EndEditing(true); suggestionDoneButton.Hidden = false; suggestionModePicker.Hidden = true; autoCompleteModePicker.Hidden = false; } private void suggestionSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; suggestionButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "StartsWith") { countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeStartsWith; jobFieldAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeStartsWith; } else if (selectedType == "StartsWithCaseSensitive") { countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeStartsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeStartsWithCaseSensitive; } else if (selectedType == "Contains") { countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeContains; jobFieldAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeContains; } else if (selectedType == "ContainsWithCaseSensitive") { countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeContainsCaseSensitive; jobFieldAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeContainsCaseSensitive; } else if (selectedType == "EndsWith") { countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeEndsWith; jobFieldAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeEndsWith; } else if (selectedType == "EndsWithCaseSensitive") { countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeEndsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeEndsWithCaseSensitive; } else if (selectedType == "Equals") { countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeEquals; jobFieldAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeEquals; } else if (selectedType == "EqualsWithCaseSenstive"){ countryAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeEqualsCaseSensitive; jobFieldAutoComplete.SuggestionMode = SFAutoCompleteSuggestionMode.SFAutoCompleteSuggestionModeEqualsCaseSensitive; } } private void autoCompleteSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; autoCompleteButton.SetTitle (selectedType, UIControlState.Normal); if (selectedType == "Append") { countryAutoComplete.AutoCompleteMode = SFAutoCompleteAutoCompleteMode.SFAutoCompleteAutoCompleteModeAppend; jobFieldAutoComplete.AutoCompleteMode = SFAutoCompleteAutoCompleteMode.SFAutoCompleteAutoCompleteModeAppend; } else if (selectedType == "Suggest") { countryAutoComplete.AutoCompleteMode = SFAutoCompleteAutoCompleteMode.SFAutoCompleteAutoCompleteModeSuggest; jobFieldAutoComplete.AutoCompleteMode = SFAutoCompleteAutoCompleteMode.SFAutoCompleteAutoCompleteModeSuggest; } else if (selectedType == "SuggestAppend") { countryAutoComplete.AutoCompleteMode = SFAutoCompleteAutoCompleteMode.SFAutoCompleteAutoCompleteModeSuggestAppend; jobFieldAutoComplete.AutoCompleteMode = SFAutoCompleteAutoCompleteMode.SFAutoCompleteAutoCompleteModeSuggestAppend; } } private void experienceSelectedIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; experienceButton.SetTitle (selectedType, UIControlState.Normal); } } } <file_sep>/Android/SampleBrowser/Samples/RadialMenu/RadialShare.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content; using Android.Graphics; using Android.Util; using Android.Views; using Android.Widget; using Syncfusion.SfRadialMenu.Android; namespace SampleBrowser { public class RadialShare : SamplePage { public RadialShare() { } float density; Context con; LinearLayout mainLayout; SfRadialMenu radialMenu; Button touchDraw; public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = Math.Sqrt(Math.Pow(screenWidth, 2) + Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } public override View GetSampleContent(Context context) { mainLayout = new LinearLayout(context); mainLayout.Orientation = Orientation.Vertical; mainLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); con = context; density = con.Resources.DisplayMetrics.Density; TextView about = new TextView(context); about.Text = "About Syncfusion"; if (IsTabletDevice(context)) { about.SetPadding(0, 10, 0, 40); about.Gravity = GravityFlags.Center; } about.SetTextColor(Color.Black); about.SetBackgroundColor(Color.Transparent); about.TextSize = 10 * density; //TypedValue.ApplyDimension(ComplexUnitType.Pt, 5, context.Resources.DisplayMetrics); mainLayout.AddView(about); TextView desc = new TextView(context); if (density > 2) { mainLayout.SetPadding(10, 10, 10, 10); about.TextSize = 20; } else { about.TextSize = 17; mainLayout.SetPadding(5, 5, 5, 5); } if (IsTabletDevice(context)) desc.Text = "\tSyncfusion is the enterprise technology partner of choice for software development, delivering \n \n a broad range of web, mobile, and desktop controls coupled with a service-oriented approach \n \n throughout the entire application lifecycle. Syncfusion has established itself as the trusted\n\n partner worldwide for use in applications."; else desc.Text = "\tSyncfusion is the enterprise technology partner of choice for software development, delivering a broad range of web, mobile, and desktop controls coupled with a service-oriented approach throughout the entire application lifecycle. Syncfusion has established itself as the trusted partner worldwide for use in applications."; desc.SetTextColor(Color.Black); desc.SetBackgroundColor(Color.Transparent); //desc.TextSize =5 * density; //TypedValue.ApplyDimension(ComplexUnitType.Pt, 3.5f, context.Resources.DisplayMetrics); mainLayout.AddView(desc); FrameLayout backFrame = new FrameLayout(context); backFrame.SetBackgroundColor(Color.Gray); mainLayout.AddView(backFrame, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent)); FrameLayout frontFrame = new FrameLayout(context); frontFrame.SetBackgroundColor(Color.White); frontFrame.SetPadding(5, 5, 5, 5); touchDraw = new Button(context); touchDraw.Text = "Tap here to follow us"; touchDraw.SetTextColor(Color.Blue); touchDraw.SetBackgroundColor(Color.Transparent); //touchDraw.TextSize = 10 * density; //TypedValue.ApplyDimension(ComplexUnitType.Pt, 3, context.Resources.DisplayMetrics); frontFrame.AddView(touchDraw, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.Center)); Typeface typeface = Typeface.CreateFromAsset(context.Assets, "socialicons.ttf"); radialMenu = new SfRadialMenu(context); radialMenu.RimColor = Color.Transparent; radialMenu.SelectionColor = Color.Transparent; FrameLayout facebookLayout = new FrameLayout(context); facebookLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView facebookImage = new ImageView(context); facebookImage.LayoutParameters = facebookLayout.LayoutParameters; facebookImage.SetImageResource(Resource.Drawable.facebook); facebookImage.SetScaleType(ImageView.ScaleType.FitXy); TextView facebookText = new TextView(context); facebookText.LayoutParameters = facebookLayout.LayoutParameters; facebookText.Text = "\uE700"; facebookText.Typeface = typeface; facebookText.TextSize = 20; facebookText.TextAlignment = TextAlignment.Center; facebookText.Gravity = GravityFlags.Center; facebookText.SetTextColor(Color.White); facebookLayout.AddView(facebookImage); facebookLayout.AddView(facebookText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem facebookItem = new SfRadialMenuItem(context) { View = facebookLayout, ItemWidth = 50, ItemHeight = 50 }; facebookItem.ItemTapped += FacebookItem_ItemTapped; facebookItem.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(facebookItem); FrameLayout gplusLayout = new FrameLayout(context); gplusLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView gplusImage = new ImageView(context); gplusImage.LayoutParameters = gplusLayout.LayoutParameters; gplusImage.SetImageResource(Resource.Drawable.gplus); gplusImage.SetScaleType(ImageView.ScaleType.FitXy); TextView gplusText = new TextView(context); gplusText.LayoutParameters = gplusLayout.LayoutParameters; gplusText.Text = "\uE707"; gplusText.Typeface = typeface; gplusText.TextSize = 20; gplusText.TextAlignment = TextAlignment.Center; gplusText.Gravity = GravityFlags.Center; gplusText.SetTextColor(Color.White); gplusLayout.AddView(gplusImage); gplusLayout.AddView(gplusText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem gplusItem = new SfRadialMenuItem(context) { View = gplusLayout, ItemWidth = 50, ItemHeight = 50 }; gplusItem.ItemTapped += GplusItem_ItemTapped; gplusItem.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(gplusItem); FrameLayout twitterLayout = new FrameLayout(context); twitterLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView twitterImage = new ImageView(context); twitterImage.LayoutParameters = twitterLayout.LayoutParameters; twitterImage.SetImageResource(Resource.Drawable.twitter); twitterImage.SetScaleType(ImageView.ScaleType.FitXy); TextView twitterText = new TextView(context); twitterText.LayoutParameters = twitterLayout.LayoutParameters; twitterText.Text = "\uE704"; twitterText.Typeface = typeface; twitterText.TextSize = 20; twitterText.TextAlignment = TextAlignment.Center; twitterText.Gravity = GravityFlags.Center; twitterText.SetTextColor(Color.White); twitterLayout.AddView(twitterImage); twitterLayout.AddView(twitterText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem twitterItem = new SfRadialMenuItem(context) { View = twitterLayout, ItemWidth = 50, ItemHeight = 50 }; twitterItem.ItemTapped +=TwitterItem_ItemTapped; twitterItem.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(twitterItem); FrameLayout pinterestLayout = new FrameLayout(context); pinterestLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView pinterestImage = new ImageView(context); pinterestImage.LayoutParameters = pinterestLayout.LayoutParameters; pinterestImage.SetImageResource(Resource.Drawable.pinterest); pinterestImage.SetScaleType(ImageView.ScaleType.FitXy); TextView pinterestText = new TextView(context); pinterestText.LayoutParameters = pinterestLayout.LayoutParameters; pinterestText.Text = "\uE705"; pinterestText.Typeface = typeface; pinterestText.TextSize = 20; pinterestText.TextAlignment = TextAlignment.Center; pinterestText.Gravity = GravityFlags.Center; pinterestText.SetTextColor(Color.White); pinterestLayout.AddView(pinterestImage); pinterestLayout.AddView(pinterestText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem pinterestItem = new SfRadialMenuItem(context) { View = pinterestLayout, ItemWidth = 50, ItemHeight = 50 }; pinterestItem.ItemTapped += PinterestItem_ItemTapped; pinterestItem.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(pinterestItem); FrameLayout linkedInLayout = new FrameLayout(context); linkedInLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView linkedInImage = new ImageView(context); linkedInImage.LayoutParameters = linkedInLayout.LayoutParameters; linkedInImage.SetImageResource(Resource.Drawable.linkedin); linkedInImage.SetScaleType(ImageView.ScaleType.FitXy); TextView linkedInText = new TextView(context); linkedInText.LayoutParameters = linkedInLayout.LayoutParameters; linkedInText.Text = "\uE706"; linkedInText.Typeface = typeface; linkedInText.TextSize = 20; linkedInText.TextAlignment = TextAlignment.Center; linkedInText.Gravity = GravityFlags.Center; linkedInText.SetTextColor(Color.White); linkedInLayout.AddView(linkedInImage); linkedInLayout.AddView(linkedInText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem linkedInItem = new SfRadialMenuItem(context) { View = linkedInLayout, ItemWidth = 50, ItemHeight = 50 }; linkedInItem.ItemTapped +=LinkedInItem_ItemTapped; linkedInItem.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(linkedInItem); FrameLayout instagramLayout = new FrameLayout(context); instagramLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); ImageView instagramImage = new ImageView(context); instagramImage.LayoutParameters = instagramLayout.LayoutParameters; instagramImage.SetImageResource(Resource.Drawable.instagram); instagramImage.SetScaleType(ImageView.ScaleType.FitXy); TextView instagramText = new TextView(context); instagramText.LayoutParameters = instagramLayout.LayoutParameters; instagramText.Text = "\uE708"; instagramText.Typeface = typeface; instagramText.TextSize = 20; instagramText.TextAlignment = TextAlignment.Center; instagramText.Gravity = GravityFlags.Center; instagramText.SetTextColor(Color.White); instagramLayout.AddView(instagramImage); instagramLayout.AddView(instagramText, new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent)); SfRadialMenuItem instagramItem = new SfRadialMenuItem(context) { View = instagramLayout, ItemWidth = 50, ItemHeight = 50 }; instagramItem.ItemTapped += InstagramItem_ItemTapped; instagramItem.SetBackgroundColor(Color.Transparent); radialMenu.Items.Add(instagramItem); backFrame.AddView(frontFrame, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent)); TextView menuIcon = new TextView(context); menuIcon.Text = "\uE703"; menuIcon.TextSize = 20; menuIcon.Typeface = typeface; menuIcon.SetTextColor(Color.White); menuIcon.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); menuIcon.Gravity = GravityFlags.Center; radialMenu.Visibility = ViewStates.Invisible; radialMenu.CenterButtonView = menuIcon; radialMenu.IsDragEnabled = false; radialMenu.EnableRotation = false; radialMenu.OuterRimColor = Color.Transparent; radialMenu.CenterButtonBackground = Color.Rgb(41, 146, 247); radialMenu.CenterButtonRadius = 25; radialMenu.RimRadius = 100; radialMenu.Closed += RadialMenu_Closed; frontFrame.AddView(radialMenu); touchDraw.Click += (sender, e) => { radialMenu.Visibility = ViewStates.Visible; touchDraw.Visibility = ViewStates.Invisible; radialMenu.Show(); }; return mainLayout; } void FacebookItem_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { radialMenu.Close(); Toast.MakeText(con, "Shared with Facebook", ToastLength.Short).Show(); } void GplusItem_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { radialMenu.Close(); Toast.MakeText(con, "Shared with G+", ToastLength.Short).Show(); } void PinterestItem_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { radialMenu.Close(); Toast.MakeText(con, "Shared with Pinterest", ToastLength.Short).Show(); } void LinkedInItem_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { radialMenu.Close(); Toast.MakeText(con, "Shared with Linked in", ToastLength.Short).Show(); } void TwitterItem_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { radialMenu.Close(); Toast.MakeText(con, "Shared with Twitter", ToastLength.Short).Show(); } void InstagramItem_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { radialMenu.Close(); Toast.MakeText(con, "Shared with Instagram", ToastLength.Short).Show(); } void RadialMenu_Closed(object sender, ClosedEventArgs e) { radialMenu.Visibility = ViewStates.Invisible; touchDraw.Visibility = ViewStates.Visible; } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/StackingColumn.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; namespace SampleBrowser { [Activity(Label = "Stacked Columns")] public class StackingColumn : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.Title.Text = "Mobile Game Market by Country"; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis PrimaryAxis = new CategoryAxis(); PrimaryAxis.ShowMajorGridLines = false; PrimaryAxis.LabelPlacement = LabelPlacement.BetweenTicks; chart.PrimaryAxis = PrimaryAxis; NumericalAxis numericalAxis = new NumericalAxis(); numericalAxis.Title.Text = "Sales"; numericalAxis.Minimum = 0; numericalAxis.Maximum = 500; numericalAxis.Interval = 100; numericalAxis.LineStyle.StrokeWidth = 0; numericalAxis.MajorTickStyle.TickSize = 0; numericalAxis.LabelStyle.LabelFormat = "#'B'"; chart.SecondaryAxis = numericalAxis; StackingColumnSeries stackingColumnSeries = new StackingColumnSeries(); stackingColumnSeries.EnableAnimation = true; stackingColumnSeries.Label = "UK"; stackingColumnSeries.ItemsSource = MainPage.GetStackedColumnData1(); stackingColumnSeries.XBindingPath = "XValue"; stackingColumnSeries.YBindingPath = "YValue"; stackingColumnSeries.LegendIcon = ChartLegendIcon.SeriesType; StackingColumnSeries stackingColumnSeries1 = new StackingColumnSeries(); stackingColumnSeries1.EnableAnimation = true; stackingColumnSeries1.Label = "Germany"; stackingColumnSeries1.ItemsSource = MainPage.GetStackedColumnData2(); stackingColumnSeries1.XBindingPath = "XValue"; stackingColumnSeries1.YBindingPath = "YValue"; stackingColumnSeries1.LegendIcon = ChartLegendIcon.SeriesType; StackingColumnSeries stackingColumnSeries2 = new StackingColumnSeries(); stackingColumnSeries2.EnableAnimation = true; stackingColumnSeries2.Label = "France"; stackingColumnSeries2.ItemsSource = MainPage.GetStackedColumnData3(); stackingColumnSeries2.XBindingPath = "XValue"; stackingColumnSeries2.YBindingPath = "YValue"; stackingColumnSeries2.LegendIcon = ChartLegendIcon.SeriesType; StackingColumnSeries stackingColumnSeries3 = new StackingColumnSeries(); stackingColumnSeries3.EnableAnimation = true; stackingColumnSeries3.Label = "Italy"; stackingColumnSeries3.ItemsSource = MainPage.GetStackedColumnData4(); stackingColumnSeries3.XBindingPath = "XValue"; stackingColumnSeries3.YBindingPath = "YValue"; stackingColumnSeries3.LegendIcon = ChartLegendIcon.SeriesType; chart.Series.Add(stackingColumnSeries); chart.Series.Add(stackingColumnSeries1); chart.Series.Add(stackingColumnSeries2); chart.Series.Add(stackingColumnSeries3); stackingColumnSeries.TooltipEnabled = true; stackingColumnSeries1.TooltipEnabled = true; stackingColumnSeries2.TooltipEnabled = true; stackingColumnSeries3.TooltipEnabled = true; stackingColumnSeries.EnableAnimation = true; stackingColumnSeries1.EnableAnimation = true; stackingColumnSeries2.EnableAnimation = true; stackingColumnSeries3.EnableAnimation = true; return chart; } } }<file_sep>/iOS/SampleBrowser/Samples/Presentation/PPTXToImage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.Presentation; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using System.Xml; using System.Linq; using Syncfusion.iOS.Buttons; using Syncfusion.PresentationRenderer; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class PPTXToImage : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UILabel imageTypelabel; UIButton imageType; UIButton inputButton; UIButton convertButton; //RadioButton SfRadioGroup radioGroup = new SfRadioGroup(); SfRadioButton pngButton = new SfRadioButton(); SfRadioButton jpegButton = new SfRadioButton(); public PPTXToImage() { label = new UILabel(); imageTypelabel = new UILabel(); imageType = new UIButton(); inputButton = new UIButton(UIButtonType.System); inputButton.TouchUpInside += OnButtonClicked; convertButton = new UIButton(UIButtonType.System); convertButton.TouchUpInside += OnConvertClicked; } void LoadAllowedTextsLabel() { #region Description Label label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to convert the PowerPoint slide to an image."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 35); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } this.AddSubview(label); #endregion #region ImageFormat Label if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { imageTypelabel.Font = UIFont.SystemFontOfSize(18); imageTypelabel.Frame = new CGRect(10, 45, frameRect.Location.X + frameRect.Size.Width - 20, 50); imageType.Frame = new CGRect(10, 95, frameRect.Location.X + frameRect.Size.Width - 20, 40); } else { imageTypelabel.Frame = new CGRect(10, 50, frameRect.Location.X + frameRect.Size.Width - 20, 50); imageType.Frame = new CGRect(10, 100, frameRect.Location.X + frameRect.Size.Width - 20, 40); } //filter Label imageTypelabel.TextColor = UIColor.Black; imageTypelabel.BackgroundColor = UIColor.Clear; imageTypelabel.Text = "Image Format:"; imageTypelabel.TextAlignment = UITextAlignment.Left; imageTypelabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(imageTypelabel); #endregion #region Radio Buttons radioGroup.Axis = UILayoutConstraintAxis.Horizontal; pngButton.SetTitle("PNG", UIControlState.Normal); radioGroup.AddArrangedSubview(pngButton); jpegButton.SetTitle("JPEG", UIControlState.Normal); radioGroup.AddArrangedSubview(jpegButton); pngButton.IsChecked = true; radioGroup.Distribution = UIStackViewDistribution.FillProportionally; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { radioGroup.Frame = new CGRect(130, 55, frameRect.Width - 500, 30); } else { radioGroup.Frame = new CGRect(130, 60, frameRect.Width - 90, 30); } this.AddSubview(radioGroup); #endregion #region Input Template Button //button inputButton.SetTitle("Input Template", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { inputButton.Frame = new CGRect(0, 105, frameRect.Location.X + frameRect.Size.Width, 10); } else { inputButton.Frame = new CGRect(0, (this.Frame.Size.Height / 4) - 5, frameRect.Location.X + frameRect.Size.Width, 10); } this.AddSubview(inputButton); #endregion #region Convert Button convertButton.SetTitle("Convert", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { convertButton.Frame = new CGRect(0, 135, frameRect.Location.X + frameRect.Size.Width, 10); } else { convertButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 25, frameRect.Location.X + frameRect.Size.Width, 10); } this.AddSubview(convertButton); #endregion } void OnButtonClicked(object sender, EventArgs e) { //Load the input template from assembly. string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Template.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Create a new memory stream. MemoryStream stream = new MemoryStream(); //Copy input template to newly created memory stream. fileStream.CopyTo(stream); stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save("Template.pptx", "application/mspowerpoint", stream); } } void OnConvertClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Template.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open the existing PowerPoint Presentation. IPresentation presentation = Presentation.Open(fileStream); //Initialize PresentationRenderer to perform image conversion. presentation.PresentationRenderer = new PresentationRenderer(); string fileName = null; string ContentType = null; Syncfusion.Presentation.ExportImageFormat imageFormat; if (jpegButton != null && (bool)jpegButton.IsChecked) { imageFormat = ExportImageFormat.Jpeg; fileName = "Image.jpeg"; ContentType = "image/jpeg"; } else { imageFormat = ExportImageFormat.Png; fileName = "Image.png"; ContentType = "image/png"; } //Convert PowerPoint slide to image. Stream stream = presentation.Slides[0].ConvertToImage(imageFormat); //Reset the stream position stream.Position = 0; //Close the PowerPoint Presentation. presentation.Close(); if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save(fileName, ContentType, stream as MemoryStream); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/Android/SampleBrowser/Samples/NumericUpDown/NumericUpDown_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Com.Syncfusion.Numericupdown; #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Numerictextbox; using Android.Graphics; using Android.Views.InputMethods; using Android.Text; using Android.Text.Style; namespace SampleBrowser { public class NumericUpDown_Mobile { /********************************* **Local Variable Inizialisation** *********************************/ LinearLayout propertylayout, autoReverseLayout, minimumValueLayout, maximumValueLayout, fontSizeLayOut, selectAllOnFocusLayout; ArrayAdapter<String> spinButtonDataAdapter; Spinner spinButtonSpinner; bool autoReverse = false, selectAllOnFocus = false; EditText minimumText, maximumText, fontSizeText; SpinButtonAlignment spinButtonAlignment = SpinButtonAlignment.Right; double minimumValue = 0, maximumValue = 100, fontSizeValue = 18; Boolean maxNegative, minNegative, fontsizeNegative; SfNumericUpDown adultNumericUpDown, infantsNumericUpDown; TextView adultText, infantsText; Context context; int width; GravityFlags gravity=GravityFlags.CenterVertical; public View GetSampleContent(Context con) { int width = con.Resources.DisplayMetrics.WidthPixels - 40; float density = con.Resources.DisplayMetrics.Density; int numerHeight = (int)(density * 55); if (density >= 3) { numerHeight = (int)(density * 65); } SamplePageContent(con); //AdultNumericUpDown adultNumericUpDown = new SfNumericUpDown(con); adultNumericUpDown.FontSize = 18; adultNumericUpDown.TextGravity = GravityFlags.CenterVertical; adultNumericUpDown.LayoutParameters = new ViewGroup.LayoutParams(width, numerHeight); adultNumericUpDown.Minimum = 0; adultNumericUpDown.Maximum = 100; adultNumericUpDown.Value = 5; adultNumericUpDown.FormatString = "N"; adultNumericUpDown.AutoReverse = false; adultNumericUpDown.MaximumDecimalDigits = 0; adultNumericUpDown.StepValue = 1; //InfantsNumericUpDown infantsNumericUpDown = new SfNumericUpDown(con); infantsNumericUpDown.FontSize = 18; infantsNumericUpDown.TextGravity = GravityFlags.CenterVertical; infantsNumericUpDown.LayoutParameters = new ViewGroup.LayoutParams(width, numerHeight); infantsNumericUpDown.Minimum = 0; infantsNumericUpDown.Maximum = 100; infantsNumericUpDown.Value = 2; infantsNumericUpDown.FormatString = "N"; infantsNumericUpDown.AutoReverse = false; infantsNumericUpDown.MaximumDecimalDigits = 0; infantsNumericUpDown.StepValue = 1; //MainFrameLayout FrameLayout mainFrameLayout = new FrameLayout(con); mainFrameLayout.SetPadding(10, 10, 10, 10); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.FillVertical); mainFrameLayout.LayoutParameters = layoutParams; mainFrameLayout.AddView(GetView(con)); ScrollView mainScrollView = new ScrollView(con); mainScrollView.AddView(mainFrameLayout); return mainScrollView; } private LinearLayout GetView(Context con) { //mainLayout LinearLayout mainLayout = new LinearLayout(con); mainLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); mainLayout.SetGravity(GravityFlags.FillVertical); mainLayout.Orientation = Orientation.Vertical; mainLayout.AddView(adultText); mainLayout.AddView(adultNumericUpDown); mainLayout.AddView(infantsText); mainLayout.AddView(infantsNumericUpDown); //MainLayout Touch Event mainLayout.Touch += (object sender, View.TouchEventArgs e) => { if (adultNumericUpDown.IsFocused || infantsNumericUpDown.IsFocused) { Rect outRect = new Rect(); adultNumericUpDown.GetGlobalVisibleRect(outRect); infantsNumericUpDown.GetGlobalVisibleRect(outRect); if (!outRect.Contains((int)e.Event.RawX, (int)e.Event.RawY)) { adultNumericUpDown.ClearFocus(); infantsNumericUpDown.ClearFocus(); } hideSoftKeyboard((Activity)con); } }; return mainLayout; } private void SamplePageContent(Context con) { //AdultText adultText = new TextView(con); adultText.Text = "Number of adults"; adultText.TextSize = 18; //InfantsText infantsText = new TextView(con); infantsText.SetPadding(0, 15, 0, 0); infantsText.Text = "Number of infants"; infantsText.TextSize = 18; } //Apply Changes Method public void OnApplyChanges() { //adultNumericUpDown adultNumericUpDown.Minimum = minimumValue; adultNumericUpDown.Maximum = maximumValue; adultNumericUpDown.FontSize = fontSizeValue; adultNumericUpDown.AutoReverse = autoReverse; adultNumericUpDown.SelectAllOnFocus = selectAllOnFocus; adultNumericUpDown.SpinButtonAlignment = spinButtonAlignment; adultNumericUpDown.TextGravity = gravity; //infantsNumericUpDown infantsNumericUpDown.Minimum = minimumValue; infantsNumericUpDown.Maximum = maximumValue; infantsNumericUpDown.FontSize = fontSizeValue; infantsNumericUpDown.AutoReverse = autoReverse; infantsNumericUpDown.SelectAllOnFocus = selectAllOnFocus; infantsNumericUpDown.SpinButtonAlignment = spinButtonAlignment; infantsNumericUpDown.TextGravity = gravity; maxNegative = minNegative = fontsizeNegative = false; } public View GetPropertyWindowLayout(Context context1) { context = context1; width = (context.Resources.DisplayMetrics.WidthPixels) / 2; propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; MinimumLayout(); MaximumLayout(); FontSizeLayout(); SpinButtonLayout(); AutoReverseLayout(); SelectAllOnFocusLayout(); return propertylayout; } private void FontSizeLayout() { /*********** **FontSize** ***********/ double newNumber; TextView fontSizeLabel = new TextView(context); fontSizeLabel.Text = "FontSize"; fontSizeLabel.SetWidth(400); fontSizeLabel.TextSize = 20; //FontSize Text fontSizeText = new EditText(context); fontSizeText.Text = "18"; fontSizeText.TextSize = 16; fontSizeText.InputType = Android.Text.InputTypes.ClassPhone; // FontSizeText Changed Listener fontSizeText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (fontSizeText.Text.Length > 0) { String str = e.Text.ToString(); if (str.StartsWith("-") || str.EndsWith("-")) { str = str.Replace("-", ""); fontsizeNegative = true; } if (!str.Equals("")) { newNumber = Convert.ToDouble(str); if (fontsizeNegative) { newNumber = newNumber * -1; } fontSizeValue = newNumber; } } }; LinearLayout.LayoutParams fontsizeTextLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); fontsizeTextLayoutParams.SetMargins(0, 10, 0, 0); LinearLayout.LayoutParams fontsizeLabelLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); fontsizeLabelLayoutParams.SetMargins(0, 10, 0, 0); TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //FontSizeValueLayout fontSizeLayOut = new LinearLayout(context); fontSizeLayOut.AddView(fontSizeLabel, fontsizeLabelLayoutParams); fontSizeLayOut.AddView(fontSizeText, fontsizeTextLayoutParams); fontSizeLayOut.Orientation = Orientation.Horizontal; propertylayout.AddView(fontSizeLayOut); //FontSizeSeparate SeparatorView fontsizeSeparate = new SeparatorView(context, width * 2); fontsizeSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams fontsizeSeparateLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); fontsizeSeparateLayoutParams.SetMargins(0, 20, 15, 0); //propertylayout.AddView(fontsizeSeparate, fontsizeSeparateLayoutParams); } private void MinimumLayout() { /*********** **Minimum** ***********/ double newNumber; TextView minimumLabel = new TextView(context); minimumLabel.Text = "Minimum"; minimumLabel.SetWidth(400); minimumLabel.TextSize = 20; //Minimum Text minimumText = new EditText(context); minimumText.Text = "0"; minimumText.TextSize = 16; minimumText.InputType = Android.Text.InputTypes.ClassPhone; //Minimum Text Changed Listener minimumText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (minimumText.Text.Length > 0) { String str = e.Text.ToString(); if (str.StartsWith("-") || str.EndsWith("-")) { str = str.Replace("-", ""); minNegative = true; } if (!str.Equals("")) { newNumber = Convert.ToDouble(str); if (minNegative) { newNumber = newNumber * -1; } minimumValue = newNumber; } } }; LinearLayout.LayoutParams minimumTextLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); minimumTextLayoutParams.SetMargins(0, 10, 0, 0); LinearLayout.LayoutParams minimumLabelLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); minimumLabelLayoutParams.SetMargins(0, 10, 0, 0); //MinimumValueLayout minimumValueLayout = new LinearLayout(context); minimumValueLayout.AddView(minimumLabel, minimumLabelLayoutParams); minimumValueLayout.AddView(minimumText, minimumTextLayoutParams); minimumValueLayout.Orientation = Orientation.Horizontal; propertylayout.AddView(minimumValueLayout); //MinimumSeparate SeparatorView minimumSeparate = new SeparatorView(context, width * 2); minimumSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams minimumLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); minimumLayoutParams.SetMargins(0, 20, 15, 0); // propertylayout.AddView(minimumSeparate, minimumLayoutParams); } private void MaximumLayout() { /*********** **Maximum** ***********/ double newNumber; TextView maximumLabel = new TextView(context); maximumLabel.Text = "Maximum"; maximumLabel.SetWidth(400); maximumLabel.TextSize = 20; //MaximumText maximumText = new EditText(context); maximumText.Text = "100"; maximumText.TextSize = 16; maximumText.InputType = Android.Text.InputTypes.ClassPhone; //MaximumText TextChanged Listener maximumText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { if (maximumText.Text.Length > 0) { String str = e.Text.ToString(); if (str.StartsWith("-") || str.EndsWith("-")) { str = str.Replace("-", ""); maxNegative = true; } if (!str.Equals("")) { newNumber = Convert.ToDouble(str); if (maxNegative) { newNumber = newNumber * -1; } maximumValue = newNumber; } } }; LinearLayout.LayoutParams maximumTextLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); maximumTextLayoutParams.SetMargins(0, 10, 0, 0); LinearLayout.LayoutParams maximumLabelLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); maximumLabelLayoutParams.SetMargins(0, 10, 0, 0); TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //MaximumValueLayout maximumValueLayout = new LinearLayout(context); maximumValueLayout.AddView(maximumLabel, maximumLabelLayoutParams); maximumValueLayout.AddView(maximumText, maximumTextLayoutParams); maximumValueLayout.Orientation = Orientation.Horizontal; propertylayout.AddView(maximumValueLayout); //MaximumSeparate SeparatorView maximumSeparate = new SeparatorView(context, width * 2); maximumSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams maximumLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); maximumLayoutParams.SetMargins(0, 20, 15, 0); // propertylayout.AddView(maximumSeparate, maximumLayoutParams); } private void SpinButtonLayout() { /*********************** **SpinButtonAlignment** ***********************/ LinearLayout.LayoutParams spinButtonLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); spinButtonLayoutParams.SetMargins(0, 20, 0, 0); //SpinButtonText TextView spinButtonText = new TextView(context); spinButtonText.TextSize = 20; spinButtonText.Text = "SpinButtonAlignment"; //SpinButtonList List<String> spinButtonList = new List<String>(); spinButtonList.Add("Right"); spinButtonList.Add("Left"); spinButtonList.Add("Both"); spinButtonDataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, spinButtonList); spinButtonDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //SpinButtonSpinner spinButtonSpinner = new Spinner(context,SpinnerMode.Dialog); spinButtonSpinner.Adapter = spinButtonDataAdapter; TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //SpinButtonSpinner ItemSelected Listener spinButtonSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = spinButtonDataAdapter.GetItem(e.Position); if (selectedItem.Equals("Right")) { spinButtonAlignment = SpinButtonAlignment.Right; gravity = GravityFlags.CenterVertical; } if (selectedItem.Equals("Left")) { spinButtonAlignment = SpinButtonAlignment.Left; gravity=GravityFlags.End | GravityFlags.CenterVertical; } if (selectedItem.Equals("Both")) { spinButtonAlignment = SpinButtonAlignment.Both; gravity = GravityFlags.Center; } }; propertylayout.AddView(spinButtonText); propertylayout.AddView(spinButtonSpinner); //SpinButtonSeparate SeparatorView spinButtonSeparate = new SeparatorView(context, width * 2); spinButtonSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); // propertylayout.AddView(spinButtonSeparate, spinButtonLayoutParams); } private void AutoReverseLayout() { /*************** **AutoReverse** ***************/ TextView autoReverseText = new TextView(context); autoReverseText.Text = "AutoReverse"; autoReverseText.Gravity = GravityFlags.Center; autoReverseText.TextSize = 20; //AutoReverseCheckBox Switch autoReverseCheckBox = new Switch(context); autoReverseCheckBox.Checked = false; autoReverseCheckBox.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { if (!eve.IsChecked) autoReverse = false; else autoReverse = true; }; LinearLayout.LayoutParams autoReverseCheckBoxLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); autoReverseCheckBoxLayoutParams.SetMargins(0, 10, 0, 0); LinearLayout.LayoutParams autoReverseTextLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); autoReverseTextLayoutParams.SetMargins(0, 10, 0, 0); TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //AutoReverseLayout autoReverseLayout = new LinearLayout(context); autoReverseLayout.AddView(autoReverseText, autoReverseTextLayoutParams); autoReverseLayout.AddView(autoReverseCheckBox, autoReverseCheckBoxLayoutParams); autoReverseLayout.Orientation = Orientation.Horizontal; propertylayout.AddView(autoReverseLayout); //AutoReverseSeparate SeparatorView autoReverseSeparate = new SeparatorView(context, width * 2); autoReverseSeparate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); LinearLayout.LayoutParams autoReverseLayoutParams = new LinearLayout.LayoutParams(width * 2, 5); autoReverseLayoutParams.SetMargins(0, 20, 15, 0); // propertylayout.AddView(autoReverseSeparate, autoReverseLayoutParams); propertylayout.SetPadding(20, 20, 20, 20); } private void SelectAllOnFocusLayout() { /*************** **SelectAllOnFocus** ***************/ TextView selectAllOnFocusText = new TextView(context); selectAllOnFocusText.Text = "SelectAllOnFocus"; selectAllOnFocusText.Gravity = GravityFlags.Center; selectAllOnFocusText.TextSize = 20; //SelectAllOnFocusCheckBox Switch selectAllOnFocusCheckBox = new Switch(context); selectAllOnFocusCheckBox.Checked = false; selectAllOnFocusCheckBox.CheckedChange += (object send, CompoundButton.CheckedChangeEventArgs eve) => { if (!eve.IsChecked) selectAllOnFocus = false; else selectAllOnFocus = true; }; LinearLayout.LayoutParams selectAllOnFocusCheckBoxLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); selectAllOnFocusCheckBoxLayoutParams.SetMargins(0, 10, 0, 0); LinearLayout.LayoutParams selectAllOnFocusTextLayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); selectAllOnFocusTextLayoutParams.SetMargins(0, 10, 0, 0); TextView textSpacing = new TextView(context); propertylayout.AddView(textSpacing); //SelectAllOnFocusLayout selectAllOnFocusLayout = new LinearLayout(context); selectAllOnFocusLayout.AddView(selectAllOnFocusText, selectAllOnFocusTextLayoutParams); selectAllOnFocusLayout.AddView(selectAllOnFocusCheckBox, selectAllOnFocusCheckBoxLayoutParams); selectAllOnFocusLayout.Orientation = Orientation.Horizontal; propertylayout.AddView(selectAllOnFocusLayout); propertylayout.SetPadding(20, 20, 20, 20); } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); inputMethodManager.HideSoftInputFromWindow(activity.CurrentFocus.WindowToken, 0); } private int getDimensionPixelSize(Context con, int id) { return con.Resources.GetDimensionPixelSize(id); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/DiagonalScrolling/DiagonalScrollingBehaviors.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DiagonalScrollingBehaviors.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Xamarin.Forms; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the DiagonalScrolling samples /// </summary> public class DiagonalScrollingBehaviors : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid dataGrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Switch switch1; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">DataGrid type of bindAble parameter</param> protected override void OnAttachedTo(SampleView bindAble) { this.dataGrid = bindAble.FindByName<SfDataGrid>("dataGrid"); if (Device.Idiom == TargetIdiom.Phone) { this.dataGrid.DefaultColumnWidth = 120; } else { this.dataGrid.DefaultColumnWidth = 160; } this.dataGrid.AutoGeneratingColumn += this.DataGrid_AutoGeneratingColumn; this.switch1 = bindAble.FindByName<Switch>("switch1"); this.switch1.Toggled += this.Switch1_Toggled; base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">DataGrid type of bindAble parameter</param> protected override void OnDetachingFrom(SampleView bindAble) { this.dataGrid.AutoGeneratingColumn -= this.DataGrid_AutoGeneratingColumn; this.dataGrid = null; this.switch1.Toggled -= this.Switch1_Toggled; this.switch1 = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Triggers when switch state changed. /// </summary> /// <param name="sender">Switch1_Toggled event sender</param> /// <param name="e">Switch1_Toggled event args e</param> private void Switch1_Toggled(object sender, ToggledEventArgs e) { this.dataGrid.AllowDiagonalScrolling = e.Value; } /// <summary> /// Fired when column is generated in DataGrid /// </summary> /// <param name="sender">DataGrid_AutoGeneratingColumn sender</param> /// <param name="e">DataGrid_AutoGeneratingColumn event args e</param> private void DataGrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnEventArgs e) { e.Column.HeaderFontAttribute = FontAttributes.Bold; e.Column.Padding = new Thickness(5, 0, 5, 0); switch (Device.RuntimePlatform) { case Device.Android: e.Column.HeaderCellTextSize = 14; break; case Device.iOS: e.Column.HeaderCellTextSize = 12; break; case Device.UWP: e.Column.HeaderCellTextSize = 12; break; } switch (Device.RuntimePlatform) { case Device.Android: e.Column.CellTextSize = 14; break; case Device.iOS: e.Column.CellTextSize = 12; break; case Device.UWP: e.Column.CellTextSize = 12; break; } e.Column.HeaderTextAlignment = TextAlignment.Start; if (e.Column.MappingName == "Freight") { e.Column.TextAlignment = TextAlignment.End; e.Column.Format = "C"; } else if (e.Column.MappingName == "Gender") { e.Column.TextAlignment = TextAlignment.Start; } else if (e.Column.MappingName == "ShipCity") { e.Column.TextAlignment = TextAlignment.Start; e.Column.HeaderText = "Ship City"; } else if (e.Column.MappingName == "ShipCountry") { e.Column.TextAlignment = TextAlignment.Start; e.Column.HeaderText = "Ship Country"; } else if (e.Column.MappingName == "ShippingDate") { e.Column.TextAlignment = TextAlignment.Center; e.Column.HeaderText = "Shipping Date"; e.Column.Format = "d"; } else if (e.Column.MappingName == "IsClosed") { e.Column.HeaderText = "Is Closed"; e.Column.TextAlignment = TextAlignment.Start; } else if (e.Column.MappingName == "EmployeeID") { e.Column.HeaderText = "Employee ID"; e.Column.TextAlignment = TextAlignment.End; } } } } <file_sep>/Forms/StepProgressBar/StepProgressBar/Samples/UserRegistration/RotatorModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; namespace SampleBrowser.SfStepProgressBar { #region Rotator Model /// <summary> /// Rotator Model for Rotator View /// </summary> public class RotatorModel { /// <summary> /// Rotator Model Constructor. /// </summary> /// <param name="imagestr"></param> public RotatorModel(string imagestr) { Image = imagestr; } private string _image; /// <summary> /// Gets or sets the image for rotator model. /// </summary> public string Image { get { return _image; } set { _image = value; } } } #endregion #region Rotator View Model /// <summary> /// Rotator View Model for Rotator View /// </summary> public class RotatorViewModel { /// <summary> /// Rotator View Model Constructor. /// </summary> public RotatorViewModel() { ImageCollection.Add(new RotatorModel("image2.png")); ImageCollection.Add(new RotatorModel("image2.png")); ImageCollection.Add(new RotatorModel("image2.png")); } private List<RotatorModel> imageCollection = new List<RotatorModel>(); /// <summary> /// Gets or sets the imagecollection. /// </summary> public List<RotatorModel> ImageCollection { get { return imageCollection; } set { imageCollection = value; } } } #endregion } <file_sep>/Forms/ListView/ListView/Samples/LoadMore/ViewModel/LoadMoreViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class LoadMoreViewModel : INotifyPropertyChanged { private int totalItems = 22; private ProductRepository productRepository; private int totalOrderedItems = 0; private double totalPrice = 0; public ObservableCollection<Product> Products { get; set; } public ObservableCollection<Product> Products1 { get; set; } public ObservableCollection<Product> Orders { get; set; } public Command<object> AddCommand { get; set; } public Command<object> LoadMoreItemsCommand { get; set; } public Command<object> OrderListCommand { get; set; } public Command<object> RemoveOrderCommand { get; set; } public Command CheckoutCommand { get; set; } public int TotalOrderedItems { get { return totalOrderedItems; } set { if(totalOrderedItems != value) { totalOrderedItems = value; RaisePropertyChanged("TotalOrderedItems"); } } } public double TotalPrice { get { return totalPrice; } set { if (totalPrice != value) { totalPrice = value; RaisePropertyChanged("TotalPrice"); } } } public LoadMoreViewModel() { productRepository = new ProductRepository(); Products = new ObservableCollection<Product>(); Products1 = new ObservableCollection<Product>(); Orders = new ObservableCollection<Product>(); GenerateSource(); if (Device.Idiom == TargetIdiom.Tablet) AddProducts(0, 11); else AddProducts(0, 6); AddCommand = new Command<object>(AddQuantity); OrderListCommand = new Command<object>(NavigateOrdersPage); CheckoutCommand = new Command(CheckOut); RemoveOrderCommand = new Command<object>(RemoveOrder); LoadMoreItemsCommand = new Command<object>(LoadMoreItems, CanLoadMoreItems); } private void RemoveOrder(object obj) { var p = obj as Product; p.Quantity = 0; } private async void CheckOut(object obj) { var checkout = await Application.Current.MainPage.DisplayAlert("Checkout", "Do you want to checkout?", "Yes", "No"); if (checkout) { while(Orders.Count > 0) { Orders[Orders.Count-1].Quantity = 0; } await Application.Current.MainPage.DisplayAlert("", "Your order has been placed.", "OK"); Device.BeginInvokeOnMainThread(() => { if (obj != null) (obj as ContentPage).Navigation.PopAsync(); }); } } private void NavigateOrdersPage(object obj) { var sampleView = obj as SampleView; var ordersPage = new LoadMoreOrders(); ordersPage.BindingContext = this; sampleView.Navigation.PushAsync(ordersPage); } private void AddProducts(int index, int count) { for (int i = index; i < index + count; i++) { var name = productRepository.Names[i]; var p = new Product() { Name = name, Weight = productRepository.Weights[i], Price = productRepository.Prices[i], Image = productRepository.FruitNames[i] + ".jpg" }; p.PropertyChanged += (s, e) => { var product = s as Product; if(e.PropertyName == "Quantity") { if (Orders.Contains(product) && product.Quantity <= 0) Orders.Remove(product); else if (!Orders.Contains(product) && product.Quantity > 0) Orders.Add(product); TotalOrderedItems = Orders.Count; TotalPrice = 0; for(int j =0; j<Orders.Count;j++) { var order = Orders[j]; TotalPrice += order.TotalPrice; } } }; Products.Add(p); } } private void GenerateSource() { for (int i = 0; i < productRepository.Names.Count(); i++) { var name = productRepository.Names[i]; var p = new Product() { Name = name, Weight = productRepository.Weights[i], Price = productRepository.Prices[i], Image = productRepository.FruitNames[i] + ".jpg" }; Products1.Add(p); } } private bool CanLoadMoreItems(object obj) { if (Products.Count >= totalItems) return false; return true; } private async void LoadMoreItems(object obj) { var listview = obj as Syncfusion.ListView.XForms.SfListView; listview.IsBusy = true; await Task.Delay(2500); var index = Products.Count; var count = index + 3 >= totalItems ? totalItems - index : 3; AddProducts(index, count); listview.IsBusy = false; } private void AddQuantity(object obj) { var p = obj as Product; p.Quantity += 1; } private void RaisePropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } public event PropertyChangedEventHandler PropertyChanged; } } <file_sep>/iOS/SampleBrowser/Samples/DataGrid/Model/ReleaseInfoRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SampleBrowser { [Foundation.Preserve(AllMembers = true)] public class ReleaseInfoRepository { public ReleaseInfoRepository() { } #region private variables private Random random = new Random(); #endregion #region GetOrderDetails public ObservableCollection<ReleaseInfo> GetReleaseDetails(int count) { ObservableCollection<ReleaseInfo> releaseDetails = new ObservableCollection<ReleaseInfo>(); for (int i = 0; i < count; i++) { var details = new ReleaseInfo() { SNo = i+1, ReleaseVersion = ReleaseVersion[i], Description = Description[i], Platform = Platforms[i], Features = Features[i] }; releaseDetails.Add(details); } return releaseDetails; } #endregion string[] Platforms = new string[] { "Xamarin Forms", "Xamarin Android", "Xamarin iOS", "Xamarin Forms", "Xamarin Android", "Xamarin iOS", "Xamarin Forms", "Xamarin Forms", "Xamarin Android", "Xamarin iOS", "Xamarin Forms", "Xamarin Android", "Xamarin iOS", "Xamarin Forms", "Xamarin Android", "Xamarin iOS", "Xamarin Forms", "Xamarin Android", "Xamarin iOS", "Xamarin Forms", "Xamarin Android", "Xamarin iOS", "Xamarin Forms", "Xamarin Android", "Xamarin iOS", "Xamarin Forms", "Xamarin Android", "Xamarin iOS", }; string[] ReleaseVersion = new string[] { "2015 Volume 4", "2015 Volume 4", "2015 Volume 4", "2015 Volume 4 SP 1", "2015 Volume 4 SP 1", "2015 Volume 4 SP 1", "2015 Volume 4 SP 2", "2016 Volume 1", "2016 Volume 1", "2016 Volume 1", "2016 Volume 1 SP 1", "2016 Volume 1 SP 1", "2016 Volume 1 SP 1", "2016 Volume 2", "2016 Volume 2", "2016 Volume 2", "2016 Volume 2 SP 1", "2016 Volume 2 SP 1", "2016 Volume 2 SP 1", "2016 Volume 2 SP 2", "2016 Volume 2 SP 2", "2016 Volume 2 SP 2", "2016 Volume 3", "2016 Volume 3", "2016 Volume 3", "2016 Volume 3 SP 1", "2016 Volume 3 SP 1", "2016 Volume 3 SP 1", }; string[] Features = new string[] { "Swiping", "Pull To Refresh", "Paging", "Selection in row header", "Multiple selection color", "Animating the selected row", "Long press event", "Double click event", "Header Template", "Swiping", "Double click event", "Swiping", "Double click event", "Unbound column", "Multi-line text", "Cell border customization", "Scroll to a row/column index", "Group expand and collapse", "Customize SfDataPager", "Enabling / disabling the bouncing behavior", "Unbound column", "Group expand collapse", "Auto column width", "Column drag and drop", "Column drag and drop", "Export unbound columns", "Auto column width", "Row drag and drop" }; string[] Description = new string[] { "Enables the users to swipe the grid rows", "Pull To Refresh action refreshes the grid", "View the data in page segments", "Apply selection using row header", "Apply different selection colors for different rows", "Add an animation upon selecting a row", "Users can listen to LongPresses in the grid", "Users can listen to double taps in the grid", "Load custom views in header cells", "Enables the users to swipe the grid rows", "Users can listen to double taps in the grid", "Enables the users to swipe the grid rows", "Users can listen to double taps in the grid", "Assign values to column in runtime based on values of other cells", "Displays multi-line text for the record cells in its columns", "Customize the vertical, horizontal or both borders for the grid", "Scroll to a particular row and/or column index", "Expand or collapse groups in runtime", "Customize the appearance of the SfDataPager", "Enable/disable the bouncing of the grid when over-scrolled", "Assign values to column in runtime based on values of other cells", "Expand or collapse groups in runtime", "Automatically adjusts the width of the column to fit the content", "Rearrange the columns by dragging and dropping them", "Rearrange the columns by dragging and dropping them", "Export unbound columns to PDF or EXCEL", "Automatically adjusts the width of the column to fit the content", "Rearrange the rows by dragging and dropping them", }; } } <file_sep>/Forms/Chart/Chart/Samples/HistogramChart/HistogramSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class HistogramSeriesViewModel { public ObservableCollection<ChartDataModel> HistogramData { get; set; } public HistogramSeriesViewModel() { HistogramData = new ObservableCollection<ChartDataModel>(); HistogramData.Add(new ChartDataModel(5.250, 0)); HistogramData.Add(new ChartDataModel(7.750, 0)); HistogramData.Add(new ChartDataModel(0, 0)); HistogramData.Add(new ChartDataModel(8.275, 0)); HistogramData.Add(new ChartDataModel(9.750, 0)); HistogramData.Add(new ChartDataModel(7.750, 0)); HistogramData.Add(new ChartDataModel(8.275, 0)); HistogramData.Add(new ChartDataModel(6.250, 0)); HistogramData.Add(new ChartDataModel(5.750, 0)); HistogramData.Add(new ChartDataModel(5.250, 0)); HistogramData.Add(new ChartDataModel(23.000, 0)); HistogramData.Add(new ChartDataModel(26.500, 0)); HistogramData.Add(new ChartDataModel(27.750, 0)); HistogramData.Add(new ChartDataModel(25.025, 0)); HistogramData.Add(new ChartDataModel(26.500, 0)); HistogramData.Add(new ChartDataModel(26.500, 0)); HistogramData.Add(new ChartDataModel(28.025, 0)); HistogramData.Add(new ChartDataModel(29.250, 0)); HistogramData.Add(new ChartDataModel(26.750, 0)); HistogramData.Add(new ChartDataModel(27.250, 0)); HistogramData.Add(new ChartDataModel(26.250, 0)); HistogramData.Add(new ChartDataModel(25.250, 0)); HistogramData.Add(new ChartDataModel(34.500, 0)); HistogramData.Add(new ChartDataModel(25.625, 0)); HistogramData.Add(new ChartDataModel(25.500, 0)); HistogramData.Add(new ChartDataModel(26.625, 0)); HistogramData.Add(new ChartDataModel(36.275, 0)); HistogramData.Add(new ChartDataModel(36.250, 0)); HistogramData.Add(new ChartDataModel(26.875, 0)); HistogramData.Add(new ChartDataModel(45.000, 0)); HistogramData.Add(new ChartDataModel(43.000, 0)); HistogramData.Add(new ChartDataModel(46.500, 0)); HistogramData.Add(new ChartDataModel(47.750, 0)); HistogramData.Add(new ChartDataModel(45.025, 0)); HistogramData.Add(new ChartDataModel(56.500, 0)); HistogramData.Add(new ChartDataModel(56.500, 0)); HistogramData.Add(new ChartDataModel(58.025, 0)); HistogramData.Add(new ChartDataModel(59.250, 0)); HistogramData.Add(new ChartDataModel(56.750, 0)); HistogramData.Add(new ChartDataModel(57.250, 0)); HistogramData.Add(new ChartDataModel(46.250, 0)); HistogramData.Add(new ChartDataModel(55.250, 0)); HistogramData.Add(new ChartDataModel(44.500, 0)); HistogramData.Add(new ChartDataModel(45.500, 0)); HistogramData.Add(new ChartDataModel(55.500, 0)); HistogramData.Add(new ChartDataModel(45.625, 0)); HistogramData.Add(new ChartDataModel(55.500, 0)); HistogramData.Add(new ChartDataModel(56.250, 0)); HistogramData.Add(new ChartDataModel(46.875, 0)); HistogramData.Add(new ChartDataModel(43.000, 0)); HistogramData.Add(new ChartDataModel(46.250, 0)); HistogramData.Add(new ChartDataModel(55.250, 0)); HistogramData.Add(new ChartDataModel(44.500, 0)); HistogramData.Add(new ChartDataModel(45.425, 0)); HistogramData.Add(new ChartDataModel(56.625, 0)); HistogramData.Add(new ChartDataModel(46.275, 0)); HistogramData.Add(new ChartDataModel(56.250, 0)); HistogramData.Add(new ChartDataModel(46.875, 0)); HistogramData.Add(new ChartDataModel(43.000, 0)); HistogramData.Add(new ChartDataModel(46.250, 0)); HistogramData.Add(new ChartDataModel(55.250, 0)); HistogramData.Add(new ChartDataModel(44.500, 0)); HistogramData.Add(new ChartDataModel(45.425, 0)); HistogramData.Add(new ChartDataModel(55.500, 0)); HistogramData.Add(new ChartDataModel(46.625, 0)); HistogramData.Add(new ChartDataModel(56.275, 0)); HistogramData.Add(new ChartDataModel(46.250, 0)); HistogramData.Add(new ChartDataModel(56.250, 0)); HistogramData.Add(new ChartDataModel(42.000, 0)); HistogramData.Add(new ChartDataModel(41.000, 0)); HistogramData.Add(new ChartDataModel(63.000, 0)); HistogramData.Add(new ChartDataModel(66.500, 0)); HistogramData.Add(new ChartDataModel(67.750, 0)); HistogramData.Add(new ChartDataModel(65.025, 0)); HistogramData.Add(new ChartDataModel(66.500, 0)); HistogramData.Add(new ChartDataModel(76.500, 0)); HistogramData.Add(new ChartDataModel(78.025, 0)); HistogramData.Add(new ChartDataModel(79.250, 0)); HistogramData.Add(new ChartDataModel(76.750, 0)); HistogramData.Add(new ChartDataModel(77.250, 0)); HistogramData.Add(new ChartDataModel(66.250, 0)); HistogramData.Add(new ChartDataModel(75.250, 0)); HistogramData.Add(new ChartDataModel(74.500, 0)); HistogramData.Add(new ChartDataModel(65.625, 0)); HistogramData.Add(new ChartDataModel(75.500, 0)); HistogramData.Add(new ChartDataModel(76.625, 0)); HistogramData.Add(new ChartDataModel(76.275, 0)); HistogramData.Add(new ChartDataModel(66.250, 0)); HistogramData.Add(new ChartDataModel(66.875, 0)); HistogramData.Add(new ChartDataModel(82.000, 0)); HistogramData.Add(new ChartDataModel(85.250, 0)); HistogramData.Add(new ChartDataModel(87.750, 0)); HistogramData.Add(new ChartDataModel(92.000, 0)); HistogramData.Add(new ChartDataModel(85.250, 0)); HistogramData.Add(new ChartDataModel(87.750, 0)); HistogramData.Add(new ChartDataModel(89.000, 0)); HistogramData.Add(new ChartDataModel(88.275, 0)); HistogramData.Add(new ChartDataModel(89.750, 0)); HistogramData.Add(new ChartDataModel(95.750, 0)); HistogramData.Add(new ChartDataModel(95.250, 0)); } } }<file_sep>/Forms/TabView/TabView/Samples/CenterButton/CenterButtonPage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XForms.TabView; using Xamarin.Forms; using Xamarin.Forms.Xaml; using SampleBrowser.Core; using System.Collections.ObjectModel; using System.Linq; using System.Globalization; namespace SampleBrowser.SfTabView { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CenterButton : SampleView { public ObservableCollection<SampleBrowser.SfTabView.Model.ContactsInfo> PrimaryListSource { get; set; } public ObservableCollection<SampleBrowser.SfTabView.Model.ContactsInfo> SecondaryListSource { get; set; } public ObservableCollection<SampleBrowser.SfTabView.Model.ContactsInfo> ThirdListSource { get; set; } public CenterButton() { InitializeComponent(); this.composer.CenterButtonObject = this; this.PrimaryListSource = new SampleBrowser.SfTabView.Model.ContactsInfoRepository().GetContactDetails(7); this.SecondaryListSource = new SampleBrowser.SfTabView.Model.ContactsInfoRepository().GetContactDetails(4); this.ThirdListSource = new SampleBrowser.SfTabView.Model.ContactsInfoRepository().GetContactDetails(16); this.BindingContext = this; } void Handle_Tapped(object sender, System.EventArgs e) { var item = sender as Image; if (item.StyleId == "Tabimage") { TabView.SelectedIndex = 0; } else if (item.StyleId == "Tabimage1") { TabView.SelectedIndex = 1; } else if (item.StyleId == "Tabimage2") { TabView.SelectedIndex = 2; } else if (item.StyleId == "Tabimage3") { TabView.SelectedIndex = 3; } } void Handle_SelectionChanged(object sender, Syncfusion.XForms.TabView.SelectionChangedEventArgs e) { if (TabView.SelectedIndex == 3) { // Navigation.PushAsync(new Profile()); } } void CenterButton_Tapped(object sender, System.EventArgs e) { this.ComposeDialog.Opacity = 0; this.ComposeDialog.IsVisible = true; this.ComposeDialog.FadeTo(1, 600, Easing.Linear); } void Button_Clicked(object sender, System.EventArgs e) { TabView.SelectedIndex = 0; } void Grid_Tapped(object sender, System.EventArgs e) { if (this.ComposeDialog.IsVisible) { CloseDialog(); } } public void CloseDialog() { this.ComposeDialog.FadeTo(0, 600, Easing.Linear); this.ComposeDialog.IsVisible = false; TabView.SelectedIndex = 0; } } public class DateTimeToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var item = (DateTime)value; if (item != null) { return item.ToString("hh:mm tt"); } else { return null; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class ImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { if (value is string) { if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB return value; #else if (SampleBrowser.Core.SampleBrowser.IsIndividualSB) return value; else return "SampleBrowser.SfTabView.UWP\\" + value; #endif } } } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Rotator/Rotator.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using UIKit; using Foundation; using Syncfusion.SfRotator.iOS; using System.Collections.Generic; using CoreGraphics; namespace SampleBrowser { public class Rotator : SampleView { Rotator_Mobile phoneView; public Rotator () { if((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { this.AddSubview(new Rotator_Tablet()); } else{ phoneView = new Rotator_Mobile (); this.AddSubview (phoneView); } } public override void LayoutSubviews () { foreach (var view in this.Subviews) { view.Frame = Bounds; } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/Model/DealerInfo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace SampleBrowser { public class DealerInfo : INotifyPropertyChanged { #region private variables private int productNo; private int productID; private string dealerName; private bool isOnline; private int productprice; private DateTime shippedDate; #endregion #region Public Properties public int ProductID { get { return productID; } set { this.productID = value; RaisePropertyChanged("ProductID"); } } public string DealerName { get { return this.dealerName; } set { this.dealerName = value; RaisePropertyChanged("DealerName"); } } public bool IsOnline { get { return this.isOnline; } set { this.isOnline = value; RaisePropertyChanged("IsOnline"); } } public int ProductPrice { get { return productprice; } set { productprice = value; RaisePropertyChanged("ProductPrice"); } } public int ProductNo { get { return productNo; } set { this.productNo = value; RaisePropertyChanged("ProductNo"); } } public DateTime ShippedDate { get { return shippedDate; } set { shippedDate = value; RaisePropertyChanged("ShippedDate"); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } }<file_sep>/Forms/TreeMap/TreeMap/Samples/Hierarchical/Hierarchical.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfTreeMap { [Preserve(AllMembers = true)] //[XamlCompilation(XamlCompilationOptions.Compile)] public partial class Hierarchical : SampleView { public Hierarchical() { InitializeComponent(); this.BindingContext = this; //Title = "Hierarchical"; this.TreeMap.DataSource = new CountrySalesCollection(); } } } <file_sep>/Forms/PdfViewer/PdfViewer/Samples/ViewModel/GettingStartedViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xamarin.Forms.Internals; namespace SampleBrowser.SfPdfViewer { [Preserve(AllMembers = true)] internal class GettingStartedViewModel: INotifyPropertyChanged { private Stream m_pdfDocumentStream, m_pageByPageDocumentStream; private string m_documentName; string filePath = string.Empty; public event PropertyChangedEventHandler PropertyChanged; public string DocumentName { get { return m_documentName; } set { m_documentName = value; PdfDocumentStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath + "Assets." + DocumentName + ".pdf"); } } public GettingStartedViewModel() { #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif } public Stream PdfDocumentStream { get { return m_pdfDocumentStream; } set { m_pdfDocumentStream = value; NotifyPropertyChanged("PdfDocumentStream"); } } public Stream PageByPageDocumentStream { get { return m_pageByPageDocumentStream; } set { m_pageByPageDocumentStream = value; NotifyPropertyChanged("PageByPageDocumentStream"); } } private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private bool CanExecute(object parameter) { return true; } } } <file_sep>/Forms/DatePicker/DatePicker/Samples/DatePickerGettingStarted/DatePickerGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.ListView.XForms; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace SampleBrowser.SfDatePicker { /// <summary> /// Date Picker Getting Started class /// </summary> public partial class DatePickerGettingStarted : SampleView, INotifyPropertyChanged { /// <summary> /// Date Picker Getting Started /// </summary> public DatePickerGettingStarted() { InitializeComponent(); if (Device.RuntimePlatform == Device.UWP) { layoutRootGrid.WidthRequest = 500; } } /// <summary> /// ListView SwipeEnded event /// </summary> /// <param name="sender">sender value</param> /// <param name="e">Event args</param> private void ListView_SwipeEnded(object sender, Syncfusion.ListView.XForms.SwipeEndedEventArgs e) { if (e.SwipeDirection == Syncfusion.ListView.XForms.SwipeDirection.Right) { e.SwipeOffset = sfListView.Width; Device.BeginInvokeOnMainThread(async () => { await Task.Delay(500); viewModel.Tasks.RemoveAt(e.ItemIndex); }); } } } } <file_sep>/iOS/SampleBrowser/Samples/DataSource/Helper/TableViewSource.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DataSource; using Syncfusion.DataSource.Extensions; using System; using System.Collections.Generic; using System.Text; using UIKit; using Foundation; namespace SampleBrowser { public class TableViewSource : UITableViewSource { #region Field DataSource dataSource; #endregion #region Constructor public TableViewSource(DataSource sfDataSource ) { dataSource = sfDataSource; } #endregion #region implemented abstract members of UITableViewDataSource public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath) { var item = dataSource.DisplayItems[indexPath.Row]; if (item is BookDetails) { CustomTableCell cell = tableView.DequeueReusableCell("TableCell") as CustomTableCell; if (cell == null) cell = new CustomTableCell(); cell.UpdateCell(item); return cell; } else if (item is Contacts) { ContactCell cell = tableView.DequeueReusableCell("TableCell") as ContactCell; if (cell == null) cell = new ContactCell(); cell.UpdateValue(item); return cell; } else if (item is GroupResult) { var groupCell = new UITableViewCell(); var group = item as GroupResult; groupCell.TextLabel.Font = UIFont.BoldSystemFontOfSize(12); groupCell.TextLabel.Text = group.Key.ToString(); groupCell.BackgroundColor = UIColor.FromRGB(217, 217, 217); return groupCell; } return new UITableViewCell(); } public override nint RowsInSection(UITableView tableView, nint section) { return (nint)dataSource.DisplayItems.Count; } public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath) { if (dataSource.DisplayItems[indexPath.Row] is GroupResult) return 30; else return tableView.RowHeight; } #endregion } public class ColumnOptionsTableSource : UITableViewSource { public List<string> tableItems; string cellIdentifier = "TableCell"; string[] keys = new string[] { }; public string selectedItem = null; public ColumnOptionsTableSource(List<string> items) { tableItems = items; keys = new string[] { "ColumnName" }; } public override nint RowsInSection(UITableView tableview, nint section) { return tableItems.Count; } public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier); // if there are no cells to reuse, create a new one if (cell == null) cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier); cell.TextLabel.Text = tableItems[indexPath.Row]; cell.SelectionStyle = UITableViewCellSelectionStyle.Blue; return cell; } public override nint NumberOfSections(UITableView tableView) { return keys.Length; } public override void RowSelected(UITableView tableView, Foundation.NSIndexPath indexPath) { selectedItem = tableItems[indexPath.Row]; } public override string TitleForHeader(UITableView tableView, nint section) { return keys[section]; } } public class DataSourceFilterOptionsTableSource : UITableViewSource { public List<string> tableItems; string cellIdentifier = "TableCell"; string[] keys = new string[] { }; public string selecteditem = null; public DataSourceFilterOptionsTableSource(List<string> items) { tableItems = items; keys = new string[] { "Filter Condition Type" }; } public override nint RowsInSection(UITableView tableview, nint section) { return tableItems.Count; } public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier); // if there are no cells to reuse, create a new one if (cell == null) cell = new UITableViewCell(UITableViewCellStyle.Subtitle, cellIdentifier); cell.TextLabel.Text = tableItems[indexPath.Row]; cell.SelectionStyle = UITableViewCellSelectionStyle.Blue; return cell; } public override void WillDisplay(UITableView tableView, UITableViewCell cell, Foundation.NSIndexPath indexPath) { if (cell.Selected) { cell.BackgroundColor = UIColor.Red; } } public override nint NumberOfSections(UITableView tableView) { return keys.Length; } public override void RowSelected(UITableView tableView, Foundation.NSIndexPath indexPath) { selecteditem = tableItems[indexPath.Row]; } public override string TitleForHeader(UITableView tableView, nint section) { return keys[section]; } } } <file_sep>/Android/SampleBrowser/Samples/Schedule/ScheduleTypes.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Com.Syncfusion.Schedule; using Com.Syncfusion.Schedule.Enums; using Android.Views; using Android.Content; using Android.Widget; using System.Collections.Generic; using Android.Graphics; using Java.Util; using Android.App; using Java.Text; using Android.Util; namespace SampleBrowser { public class ScheduleTypes : SamplePage, IDisposable { private SfSchedule sfSchedule; private LinearLayout linearLayout; private IList<Calendar> visibleDates; private ScheduleCustomHeader scheduleCustomHeader; private ScheduleAppointmentEditor editor; private ScheduleViewOptionLayout viewOptionLayout; private ScheduleAppointment selectedAppointment; private int indexOfAppointment = -1; private DisplayMetrics density; private FrameLayout mainLayout; private FrameLayout propertylayout; private Context con; public override View GetSampleContent(Context context) { mainLayout = new FrameLayout(context); con = context; mainLayout.LayoutParameters = new ViewGroup.LayoutParams(FrameLayout.LayoutParams.MatchParent, FrameLayout.LayoutParams.MatchParent); density = con.Resources.DisplayMetrics; linearLayout = new LinearLayout(context); linearLayout.Orientation = Orientation.Vertical; linearLayout.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); //creating instance for Schedule sfSchedule = new SfSchedule(context); sfSchedule.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); sfSchedule.ScheduleView = ScheduleView.DayView; sfSchedule.HeaderHeight = 0; scheduleCustomHeader = new ScheduleCustomHeader(context); ViewHeaderStyle viewHeader = new ViewHeaderStyle(); viewHeader.BackgroundColor = Color.Argb(255, 242, 242, 242); sfSchedule.ViewHeaderStyle = viewHeader; //set the appointment collection GetAppointments(); sfSchedule.ItemsSource = appointmentCollection; linearLayout.AddView(scheduleCustomHeader.HeaderLayout); linearLayout.AddView(sfSchedule); editor = new ScheduleAppointmentEditor(context, sfSchedule); editor.EditorLayout.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); viewOptionLayout = new ScheduleViewOptionLayout(con, sfSchedule); //viewOptionLayout.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent); mainLayout.AddView(linearLayout); mainLayout.AddView(editor.EditorLayout); mainLayout.AddView(viewOptionLayout.OptionLayout); mainLayout.GetChildAt(2).SetY(density.HeightPixels / 14); editor.EditorLayout.Visibility = ViewStates.Invisible; viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; HookEvents(); propertylayout = SetOptionPage(context); return mainLayout; } public override View GetPropertyWindowLayout(Context context) { return propertylayout; } private FrameLayout SetOptionPage(Context context) { FrameLayout propertyLayout = new FrameLayout(context); LinearLayout layout = new LinearLayout(context); layout.Orientation = Android.Widget.Orientation.Vertical; layout.SetBackgroundColor(Color.White); TextView scheduleTimeZone = new TextView(con); scheduleTimeZone.Text = "Time Zone"; scheduleTimeZone.TextSize = 18; scheduleTimeZone.SetTextColor(Color.Black); Spinner timeZone_spinner = new Spinner(con, SpinnerMode.Dialog); timeZone_spinner.SetMinimumHeight(60); timeZone_spinner.SetBackgroundColor(Color.Gray); timeZone_spinner.DropDownWidth = 600; timeZone_spinner.SetGravity(GravityFlags.CenterHorizontal); layout.AddView(scheduleTimeZone); layout.AddView(timeZone_spinner); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleSpinnerItem, TimeZoneCollection.TimeZoneList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); timeZone_spinner.Adapter = dataAdapter; timeZone_spinner.ItemSelected += TimeZone_Spinner_ItemSelected; propertyLayout.AddView(layout); return propertyLayout; } private void TimeZone_Spinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Spinner spinner = (Spinner)sender; if ((e.Parent.GetChildAt(0) as TextView) != null) { (e.Parent.GetChildAt(0) as TextView).TextSize = 18; } string selectedItem = spinner.GetItemAtPosition(e.Position).ToString(); if (selectedItem != "Default") { sfSchedule.TimeZone = selectedItem; } } private void HookEvents() { scheduleCustomHeader.ScheduleCalendar.Click += ScheduleCalendar_Click; scheduleCustomHeader.SchedulePlus.Click += EditorLayout_Click; scheduleCustomHeader.ScheduleOption.Click += ScheduleOption_Click; sfSchedule.CellTapped += SfSchedule_CellTapped; sfSchedule.CellDoubleTapped += SfSchedule_DoubleTapped; sfSchedule.VisibleDatesChanged += SfSchedule_VisibleDatesChanged; editor.SaveButton.Click += SaveButton_Click; editor.CancelButton.Click += CancelButton_Click; viewOptionLayout.Day.Click += Day_Click; viewOptionLayout.Week.Click += Week_Click; viewOptionLayout.Workweek.Click += Workweek_Click; viewOptionLayout.Month.Click += Month_Click; } private void SfSchedule_CellTapped(object sender, CellTappedEventArgs e) { if (sfSchedule.ScheduleView == ScheduleView.MonthView) { sfSchedule.ScheduleView = ScheduleView.DayView; sfSchedule.MoveToDate = e.Calendar; } } private void SfSchedule_VisibleDatesChanged(object sender, VisibleDatesChangedEventArgs e) { visibleDates = e.VisibleDates; viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM yyyy", Locale.Us); if (sfSchedule.ScheduleView == ScheduleView.DayView) { scheduleCustomHeader.MonthText.Text = dateFormat.Format(visibleDates[0].Time); } else if (sfSchedule.ScheduleView == ScheduleView.WeekView) { scheduleCustomHeader.MonthText.Text = dateFormat.Format(visibleDates[visibleDates.Count / 2].Time); } else if (sfSchedule.ScheduleView == ScheduleView.WorkWeekView) { scheduleCustomHeader.MonthText.Text = dateFormat.Format(visibleDates[visibleDates.Count / 2].Time); } else { scheduleCustomHeader.MonthText.Text = dateFormat.Format(visibleDates[visibleDates.Count / 2].Time); } } private void SfSchedule_DoubleTapped(object sender, CellTappedEventArgs e) { viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; var schedule = sender as SfSchedule; if ((e.ScheduleAppointment as ScheduleAppointment) != null) { selectedAppointment = e.ScheduleAppointment as ScheduleAppointment; indexOfAppointment = (schedule.ItemsSource as ScheduleAppointmentCollection).IndexOf(e.ScheduleAppointment as ScheduleAppointment); } else { selectedAppointment = null; indexOfAppointment = -1; } linearLayout.Visibility = ViewStates.Invisible; editor.EditorLayout.Visibility = ViewStates.Visible; editor.ScrollView.ScrollTo(0, 0); editor.UpdateEditor(e.ScheduleAppointment as ScheduleAppointment, e.Calendar as Calendar); } private void ScheduleCalendar_Click(object sender, EventArgs e) { sfSchedule.MoveToDate = Calendar.GetInstance(Locale.English); viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; } private void EditorLayout_Click(object sender, EventArgs e) { linearLayout.Visibility = ViewStates.Invisible; editor.EditorLayout.Visibility = ViewStates.Visible; editor.UpdateEditor(null, visibleDates[0]); viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; } private void ScheduleOption_Click(object sender, EventArgs e) { ShowInputDialog(); } private void SaveButton_Click(object sender, EventArgs e) { linearLayout.Visibility = ViewStates.Visible; editor.EditorLayout.Visibility = ViewStates.Invisible; if (selectedAppointment != null) { (sfSchedule.ItemsSource as ScheduleAppointmentCollection).RemoveAt(indexOfAppointment); (sfSchedule.ItemsSource as ScheduleAppointmentCollection).Add(editor.SelectedAppointment); } else { (sfSchedule.ItemsSource as ScheduleAppointmentCollection).Add(editor.SelectedAppointment); } editor.SelectedAppointment = null; viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; } private void CancelButton_Click(object sender, EventArgs e) { linearLayout.Visibility = ViewStates.Visible; editor.EditorLayout.Visibility = ViewStates.Invisible; viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; } protected void ShowInputDialog() { viewOptionLayout.OptionLayout.Visibility = ViewStates.Visible; } private void Day_Click(object sender, EventArgs e) { sfSchedule.ScheduleView = ScheduleView.DayView; viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; } private void Month_Click(object sender, EventArgs e) { sfSchedule.ScheduleView = ScheduleView.MonthView; viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; } private void Workweek_Click(object sender, EventArgs e) { sfSchedule.ScheduleView = ScheduleView.WorkWeekView; viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; } private void Week_Click(object sender, EventArgs e) { sfSchedule.ScheduleView = ScheduleView.WeekView; viewOptionLayout.OptionLayout.Visibility = ViewStates.Invisible; } private List<string> subjectCollection = new List<string>(); private List<string> minTimeSubjectCollection = new List<string>(); private List<string> colorCollection = new List<string>(); private List<Calendar> startTimeCollection = new List<Calendar>(); private List<Calendar> minStartTimeCollection = new List<Calendar>(); private List<Calendar> endTimeCollection = new List<Calendar>(); private ScheduleAppointmentCollection appointmentCollection; //Creating appointments for ScheduleAppointmentCollection private void GetAppointments() { appointmentCollection = new ScheduleAppointmentCollection(); SetColors(); RandomNumbers(); SetSubjects(); SetStartTime(); SetEndTime(); for (int i = 0; i < 10; i++) { var scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[i]); scheduleAppointment.Subject = subjectCollection[i]; scheduleAppointment.StartTime = startTimeCollection[i]; scheduleAppointment.EndTime = endTimeCollection[i]; if (i == 4 || i == 9) { scheduleAppointment.IsAllDay = true; } appointmentCollection.Add(scheduleAppointment); } // Minimum Height Appointments for (int i = 0; i < 5; i++) { var scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = Color.ParseColor(colorCollection[i]); scheduleAppointment.Subject = minTimeSubjectCollection[i]; scheduleAppointment.StartTime = minStartTimeCollection[i]; scheduleAppointment.EndTime = minStartTimeCollection[i]; // Setting Mininmum Appointment Height for Schedule Appointments scheduleAppointment.MinHeight = 50; appointmentCollection.Add(scheduleAppointment); } } private void SetSubjects() { subjectCollection = new List<String>(); subjectCollection.Add("GoToMeeting"); subjectCollection.Add("Business Meeting"); subjectCollection.Add("Conference"); subjectCollection.Add("Project Status Discussion"); subjectCollection.Add("Auditing"); subjectCollection.Add("Client Meeting"); subjectCollection.Add("Generate Report"); subjectCollection.Add("Target Meeting"); subjectCollection.Add("General Meeting"); subjectCollection.Add("Pay House Rent"); subjectCollection.Add("Car Service"); subjectCollection.Add("Medical Check Up"); subjectCollection.Add("Wedding Anniversary"); subjectCollection.Add("Sam's Birthday"); subjectCollection.Add("Jenny's Birthday"); // MinimumHeight Appointment Subjects minTimeSubjectCollection.Add("Work log alert"); minTimeSubjectCollection.Add("Birthday wish alert"); minTimeSubjectCollection.Add("Task due date"); minTimeSubjectCollection.Add("Status mail"); minTimeSubjectCollection.Add("Start sprint alert"); } // adding colors collection private void SetColors() { colorCollection = new List<String>(); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FFF09609"); colorCollection.Add("#FF339933"); colorCollection.Add("#FF00ABA9"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF1BA1E2"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FFA2C139"); colorCollection.Add("#FFD80073"); colorCollection.Add("#FF339933"); colorCollection.Add("#FFE671B8"); colorCollection.Add("#FF00ABA9"); } private List<int> randomNums = new List<int>(); private void RandomNumbers() { randomNums = new List<int>(); Java.Util.Random rand = new Java.Util.Random(); for (int i = 0; i < 10; i++) { int randomNum = rand.NextInt((15 - 9) + 1) + 9; randomNums.Add(randomNum); } } // adding StartTime collection private void SetStartTime() { startTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -5; i < 5; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count], 0, 0); startTimeCollection.Add(startTime); count++; } // Zero duration Appoitments minStartTimeCollection = new List<Calendar>(); for (int i = 0; i < 5; i++) { Calendar startTime = (Calendar)currentDate.Clone(); startTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[i], 30, 0); minStartTimeCollection.Add(startTime); } } // adding EndTime collection private void SetEndTime() { endTimeCollection = new List<Calendar>(); Calendar currentDate = Calendar.Instance; int count = 0; for (int i = -5; i < 5; i++) { Calendar endTime = (Calendar)currentDate.Clone(); endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count] + 1, 0, 0); if (i == 4 || i == 2) { endTime.Set( currentDate.Get(CalendarField.Year), currentDate.Get(CalendarField.Month), currentDate.Get(CalendarField.DayOfMonth) + i, randomNums[count] + 20, 0, 0); } endTimeCollection.Add(endTime); count++; } } public void Dispose() { if (sfSchedule != null) { sfSchedule.CellTapped -= SfSchedule_CellTapped; sfSchedule.CellDoubleTapped -= SfSchedule_DoubleTapped; sfSchedule.VisibleDatesChanged -= SfSchedule_VisibleDatesChanged; sfSchedule.Dispose(); sfSchedule = null; } if (mainLayout != null) { mainLayout.Dispose(); mainLayout = null; } if (propertylayout != null) { propertylayout.Dispose(); propertylayout = null; } if (linearLayout != null) { linearLayout.Dispose(); linearLayout = null; } if (editor != null) { if (editor.SaveButton != null) { editor.SaveButton.Click -= SaveButton_Click; editor.SaveButton.Dispose(); editor.SaveButton = null; } if (editor.CancelButton != null) { editor.CancelButton.Click -= CancelButton_Click; editor.CancelButton.Dispose(); editor.CancelButton = null; } editor.Dispose(); editor = null; } if (scheduleCustomHeader != null) { if (scheduleCustomHeader.ScheduleCalendar != null) { scheduleCustomHeader.ScheduleCalendar.Click -= ScheduleCalendar_Click; scheduleCustomHeader.ScheduleCalendar.Dispose(); scheduleCustomHeader.ScheduleCalendar = null; } if (scheduleCustomHeader.SchedulePlus != null) { scheduleCustomHeader.SchedulePlus.Click -= EditorLayout_Click; scheduleCustomHeader.SchedulePlus.Dispose(); scheduleCustomHeader.SchedulePlus = null; } if (scheduleCustomHeader.ScheduleOption != null) { scheduleCustomHeader.ScheduleOption.Click -= ScheduleOption_Click; scheduleCustomHeader.ScheduleOption.Dispose(); scheduleCustomHeader.ScheduleOption = null; } scheduleCustomHeader.Dispose(); scheduleCustomHeader = null; } if (viewOptionLayout != null) { if (viewOptionLayout.Day != null) { viewOptionLayout.Day.Click -= Day_Click; viewOptionLayout.Day.Dispose(); viewOptionLayout.Day = null; } if (viewOptionLayout.Week != null) { viewOptionLayout.Week.Click -= Week_Click; viewOptionLayout.Week.Dispose(); viewOptionLayout.Week = null; } if (viewOptionLayout.Workweek != null) { viewOptionLayout.Workweek.Click -= Workweek_Click; viewOptionLayout.Workweek.Dispose(); viewOptionLayout.Workweek = null; } if (viewOptionLayout.Month != null) { viewOptionLayout.Month.Click -= Month_Click; viewOptionLayout.Month.Dispose(); viewOptionLayout.Month = null; } viewOptionLayout.Dispose(); viewOptionLayout = null; } if (minTimeSubjectCollection != null) { minTimeSubjectCollection.Clear(); minTimeSubjectCollection = null; } if (minStartTimeCollection != null) { minStartTimeCollection.Clear(); minStartTimeCollection = null; } } } public static class TimeZoneCollection { public static IList<string> TimeZoneList { get; set; } = new List<string>() { "Default", "AUS Central Standard Time", "AUS Eastern Standard Time", "Afghanistan Standard Time", "Alaskan Standard Time", "Arab Standard Time", "Arabian Standard Time", "Arabic Standard Time", "Argentina Standard Time", "Atlantic Standard Time", "Azerbaijan Standard Time", "Azores Standard Time", "Bahia Standard Time", "Bangladesh Standard Time", "Belarus Standard Time", "Canada Central Standard Time", "Cape Verde Standard Time", "Caucasus Standard Time", "Cen. Australia Standard Time", "Central America Standard Time", "Central Asia Standard Time", "Central Brazilian Standard Time", "Central Europe Standard Time", "Central European Standard Time", "Central Pacific Standard Time", "Central Standard Time", "China Standard Time", "Dateline Standard Time", "E. Africa Standard Time", "E. Australia Standard Time", "E. South America Standard Time", "Eastern Standard Time", "Egypt Standard Time", "Ekaterinburg Standard Time", "FLE Standard Time", "Fiji Standard Time", "GMT Standard Time", "GTB Standard Time", "Georgian Standard Time", "Greenland Standard Time", "Greenwich Standard Time", "Hawaiian Standard Time", "India Standard Time", "Iran Standard Time", "Israel Standard Time", "Jordan Standard Time", "Kaliningrad Standard Time", "Korea Standard Time", "Libya Standard Time", "Line Islands Standard Time", "Magadan Standard Time", "Mauritius Standard Time", "Middle East Standard Time", "Montevideo Standard Time", "Morocco Standard Time", "Mountain Standard Time", "Mountain Standard Time (Mexico)", "Myanmar Standard Time", "N. Central Asia Standard Time", "Namibia Standard Time", "Nepal Standard Time", "New Zealand Standard Time", "Newfoundland Standard Time", "North Asia East Standard Time", "North Asia Standard Time", "Pacific SA Standard Time", "Pacific Standard Time", "Pacific Standard Time (Mexico)", "Pakistan Standard Time", "Paraguay Standard Time", "Romance Standard Time", "Russia Time Zone 10", "Russia Time Zone 11", "Russia Time Zone 3", "Russian Standard Time", "SA Eastern Standard Time", "SA Pacific Standard Time", "SA Western Standard Time", "SE Asia Standard Time", "Samoa Standard Time", "Singapore Standard Time", "South Africa Standard Time", "Sri Lanka Standard Time", "Syria Standard Time", "Taipei Standard Time", "Tasmania Standard Time", "Tokyo Standard Time", "Tonga Standard Time", "Turkey Standard Time", "US Eastern Standard Time", "US Mountain Standard Time", "UTC", "UTC+12", "UTC-02", "UTC-11", "Ulaanbaatar Standard Time", "Venezuela Standard Time", "Vladivostok Standard Time", "W. Australia Standard Time", "W. Central Africa Standard Time", "W. Europe Standard Time", "West Asia Standard Time", "West Pacific Standard Time", "Yakutsk Standard Time" }; } }<file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/AnnotationHelper.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Reflection; using CoreGraphics; using Syncfusion.SfPdfViewer.iOS; using UIKit; namespace SampleBrowser { public class AnnotationHelper { CustomToolbar parent; internal const float DefaultToolbarHeight = 50f; private const int numberOfButtonsInAnnotationToolbar = 6; public AnnotationHelper(CustomToolbar customtoolbar) { parent = customtoolbar; } internal void AnnotationButton_TouchUpInside(object sender, EventArgs e) { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && parent.bookmarkToolbar != null && parent.bookmarkToolbar.Superview != null) { parent.bookmarkToolbar.RemoveFromSuperview(); parent.isBookmarkPaneVisible = false; } parent.isColorSelected = false; parent.isThicknessTouched = false; parent.isOpacityNeeded = false; parent.annotationToolbar.AutoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleWidth; if (parent.pdfViewerControl.AnnotationMode == AnnotationMode.Ink) { parent.pdfViewerControl.EndInkSession(false); } if (parent.annotation != null) { parent.inkThicknessButton.Frame = new CGRect(parent.parentView.Frame.Width - 55, 7, 35, 35); parent.inkAnnotationToolbar.Add(parent.inkThicknessButton); parent.inkColorButton.Frame = new CGRect(parent.parentView.Frame.Width - 100, 7, 35, 35); parent.inkAnnotationToolbar.Add(parent.inkColorButton); parent.inkdeleteButton.RemoveFromSuperview(); parent.annotation = null; } if (!parent.isAnnotationToolbarVisible) { int buttonSpacing = (int)((parent.annotationToolbar.Frame.Width - 100) / numberOfButtonsInAnnotationToolbar); int left = 80; parent.thicknessToolbar.RemoveFromSuperview(); parent.toolBar.RemoveFromSuperview(); parent.toolbar = parent.toolBar; parent.toolBarFrame.Height = DefaultToolbarHeight; parent.AddSubview(parent.toolbar); parent.searchToolBar.RemoveFromSuperview(); parent.annotationFrame = parent.Frame; parent.annotationFrame.Height = DefaultToolbarHeight; parent.annotationFrame.Y = parent.parentView.Frame.Height - parent.annotationFrame.Height + 4; parent.annotationToolbar.Frame = parent.annotationFrame; parent.annotationToolbar.BackgroundColor = UIColor.FromRGB(249, 249, 249); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.textMarkupAnnotationButton.Frame = new CGRect(left, 7, 35, 35); else parent.textMarkupAnnotationButton.Frame = new CGRect(0, 7, 35, 35); parent.textMarkupAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.textMarkupAnnotationButton.TouchUpInside += parent.helper.TextMarkupAnnotationButton_TouchUpInside; parent.textMarkupAnnotationButton.Font = parent.highFont; parent.textMarkupAnnotationButton.SetTitle("\ue70e", UIControlState.Normal); parent.textMarkupAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.annotationToolbar.Add(parent.textMarkupAnnotationButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.inkAnnotationButton.Frame = new CGRect(left + 4 * buttonSpacing, 7, 35, 35); else parent.inkAnnotationButton.Frame = new CGRect(105, 7, 35, 35); parent.inkAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.inkAnnotationButton.Font = parent.highFont; parent.inkAnnotationButton.SetTitle("\ue704", UIControlState.Normal); parent.inkAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.annotationToolbar.Add(parent.inkAnnotationButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.editTextAnnotationButton.Frame = new CGRect(left + buttonSpacing, 7, 35, 35); else parent.editTextAnnotationButton.Frame = new CGRect((165), 7, 35, 35); parent.editTextAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.editTextAnnotationButton.TouchUpInside += parent.edittextHelper.EditTextAnnotationButton_TouchUpInside; parent.editTextAnnotationButton.Font = parent.highFont; parent.editTextAnnotationButton.SetTitle("\ue700", UIControlState.Normal); parent.editTextAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.annotationToolbar.Add(parent.editTextAnnotationButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.shapeAnnotationButton.Frame = new CGRect(left + 2*buttonSpacing, 7, 35, 35); else parent.shapeAnnotationButton.Frame = new CGRect(45, 7, 35, 35); parent.shapeAnnotationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.shapeAnnotationButton.TouchUpInside += parent.shapeHelper.ShapeAnnotationButton_TouchUpInside; parent.shapeAnnotationButton.Font = parent.highFont; parent.shapeAnnotationButton.SetTitle("\ue721", UIControlState.Normal); parent.shapeAnnotationButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.annotationToolbar.Add(parent.shapeAnnotationButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.signatureButton.Frame = new CGRect(left + 3 * buttonSpacing, 7, 35, 35); else parent.signatureButton.Frame = new CGRect(225, 7, 35, 35); parent.signatureButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.signatureButton.VerticalAlignment = UIControlContentVerticalAlignment.Top; parent.signatureButton.TouchUpInside += SignatureButton_TouchUpInside; parent.signatureButton.Font = parent.signatureFont; parent.signatureButton.SetTitle("\ue702", UIControlState.Normal); parent.signatureButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.annotationToolbar.Add(parent.signatureButton); if ((UIDevice.CurrentDevice).UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) parent.stampButton.Frame = new CGRect(left + 5 * buttonSpacing, 7, 35, 35); else parent.stampButton.Frame = new CGRect(275, 7, 35, 35); parent.stampButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; parent.stampButton.VerticalAlignment = UIControlContentVerticalAlignment.Top; parent.stampButton.TouchUpInside += StampButton_TouchUpInside; parent.stampButton.Font = parent.stampFont; parent.stampButton.SetTitle("\ue701", UIControlState.Normal); parent.stampButton.SetTitleColor(UIColor.FromRGB(0, 118, 255), UIControlState.Normal); parent.annotationToolbar.Add(parent.stampButton); parent.annotationToolbar = parent.UpdateToolbarBorder(parent.annotationToolbar, parent.annotationFrame); parent.annotationToolbar = parent.UpdateToolbarBorder(parent.annotationToolbar, parent.annotationFrame); parent.Add(parent.annotationToolbar); parent.isAnnotationToolbarVisible = true; parent.highlightToolbar.RemoveFromSuperview(); parent.editStampAnnotationToolbar.RemoveFromSuperview(); parent.strikeOutToolbar.RemoveFromSuperview(); parent.underlineToolbar.RemoveFromSuperview(); parent.colorToolbar.RemoveFromSuperview(); } else { parent.annotHelper.RemoveAllToolbars(false); parent.pdfViewerControl.AnnotationMode = AnnotationMode.None; parent.isAnnotationToolbarVisible = false; } } private void StampButton_TouchUpInside(object sender, EventArgs e) { if(parent.stampView == null) parent.stampView = new StampAnnotationView(parent); parent.AddSubview(parent.stampView); parent.isStampViewVisible = true; } internal void RemoveAllToolbars(bool isBackButton) { parent.textAnnotationToolbar.RemoveFromSuperview(); if (!isBackButton) { parent.colorToolbar.RemoveFromSuperview(); parent.highlightToolbar.RemoveFromSuperview(); parent.strikeOutToolbar.RemoveFromSuperview(); parent.underlineToolbar.RemoveFromSuperview(); parent.editStampAnnotationToolbar.RemoveFromSuperview(); parent.opacityPanel.RemoveFromSuperview(); parent.inkAnnotationSessionToolbar.RemoveFromSuperview(); parent.textAnnotationToolbar.RemoveFromSuperview(); parent.inkAnnotationToolbar.RemoveFromSuperview(); parent.annotationToolbar.RemoveFromSuperview(); parent.thicknessToolbar.RemoveFromSuperview(); parent.editTextAnnotationToolbar.RemoveFromSuperview(); parent.lineToolbar.RemoveFromSuperview(); parent.arrowToolbar.RemoveFromSuperview(); parent.circleToolbar.RemoveFromSuperview(); parent.rectangleToolbar.RemoveFromSuperview(); parent.shapeAnnotationToolbar.RemoveFromSuperview(); parent.rangeSlider.RemoveFromSuperview(); parent.FontSizePanel.RemoveFromSuperview(); } parent.isAnnotationToolbarVisible = false; parent.isColorSelected = false; parent.isThicknessTouched = false; parent.isOpacityNeeded = false; } void SignatureButton_TouchUpInside(object sender, EventArgs e) { parent.pdfViewerControl.AnnotationMode = AnnotationMode.HandwrittenSignature; } internal void SaveButton_TouchUpInside(object sender, EventArgs e) { Stream stream = new MemoryStream(); stream = parent.pdfViewerControl.SaveDocument(); string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filepath = Path.Combine(path, "savedDocument.pdf"); FileStream outputFillStream = File.Open(filepath, FileMode.Create); stream.Position = 0; stream.CopyTo(outputFillStream); outputFillStream.Close(); UIAlertView alertview = new UIAlertView(); alertview.Frame = new CGRect(20, 100, 200, 200); alertview.Message = filepath; alertview.Title = "The modified document is saved in the below location."; alertview.AddButton("Ok"); alertview.Show(); parent.annotHelper.RemoveAllToolbars(false); } } }<file_sep>/Forms/DocIO/DocIO/Samples/BookmarkNavigation/BookmarkNavigation.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using SampleBrowser.Core; using Syncfusion.DocIO.DLS; using System; using System.IO; using System.Reflection; using Xamarin.Forms; namespace SampleBrowser.DocIO { public partial class BookmarkNavigation : SampleView { public BookmarkNavigation() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Content_1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; this.btnGenerate1.HorizontalOptions = LayoutOptions.Start; this.btnGenerate1.VerticalOptions = LayoutOptions.Center; this.btnGenerate1.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { //if (!SampleBrowser.DocIO.App.isUWP) //{ // this.Content_1.FontSize = 18.5; //} //else //{ this.Content_1.FontSize = 13.5; //} this.Content_1.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked1(object sender, EventArgs e) { Assembly assembly = typeof(BookmarkNavigation).GetTypeInfo().Assembly; #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif Stream inputStream = assembly.GetManifestResourceStream(rootPath + "Bookmark_Template.docx"); MemoryStream stream = new MemoryStream(); inputStream.CopyTo(stream); inputStream.Dispose(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Bookmark_Template.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("Bookmark_Template.docx", "application/msword", stream); } void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = typeof(BookmarkNavigation).GetTypeInfo().Assembly; // Creating a new document. WordDocument document = new WordDocument(); //Adds section with one empty paragraph to the Word document document.EnsureMinimal(); //sets the page margins document.LastSection.PageSetup.Margins.All = 72f; //Appends bookmark to the paragraph document.LastParagraph.AppendBookmarkStart("NorthwindDatabase"); document.LastParagraph.AppendText("Northwind database with relational data"); document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase"); // Open an existing template document with single section. WordDocument nwdInformation = new WordDocument(); #if COMMONSB string rootPath = "SampleBrowser.Samples.DocIO.Samples.Templates."; #else string rootPath = "SampleBrowser.DocIO.Samples.Templates."; #endif Stream inputStream = assembly.GetManifestResourceStream(rootPath + "Bookmark_Template.docx"); // Open an existing template document. nwdInformation.Open(inputStream, FormatType.Docx); inputStream.Dispose(); // Open an existing template document with multiple section. WordDocument templateDocument = new WordDocument(); inputStream = assembly.GetManifestResourceStream(rootPath + "BkmkDocumentPart_Template.docx"); // Open an existing template document. templateDocument.Open(inputStream, FormatType.Docx); inputStream.Dispose(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the template document. BookmarksNavigator bk = new BookmarksNavigator(templateDocument); // Move to the NorthWind bookmark in template document bk.MoveToBookmark("NorthWind"); //Gets the bookmark content as WordDocumentPart WordDocumentPart documentPart = bk.GetContent(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the Northwind information document. bk = new BookmarksNavigator(nwdInformation); // Move to the information bookmark bk.MoveToBookmark("Information"); // Get the content of information bookmark. TextBodyPart bodyPart = bk.GetBookmarkContent(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the destination document. bk = new BookmarksNavigator(document); // Move to the NorthWind database in the destination document bk.MoveToBookmark("NorthwindDatabase"); //Replace the bookmark content using word document parts bk.ReplaceContent(documentPart); // Move to the Northwind_Information in the destination document bk.MoveToBookmark("Northwind_Information"); // Replacing content of Northwind_Information bookmark. bk.ReplaceBookmarkContent(bodyPart); #region Bookmark selection for table // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the Northwind information document. bk = new BookmarksNavigator(nwdInformation); bk.MoveToBookmark("SuppliersTable"); //Sets the column index where the bookmark starts within the table bk.CurrentBookmark.FirstColumn = 1; //Sets the column index where the bookmark ends within the table bk.CurrentBookmark.LastColumn = 5; // Get the content of suppliers table bookmark. bodyPart = bk.GetBookmarkContent(); // Creating a bookmark navigator. Which help us to navigate through the // bookmarks in the destination document. bk = new BookmarksNavigator(document); bk.MoveToBookmark("Table"); bk.ReplaceBookmarkContent(bodyPart); #endregion // Move to the text bookmark bk.MoveToBookmark("Text"); //Deletes the bookmark content bk.DeleteBookmarkContent(true); // Inserting text inside the bookmark. This will preserve the source formatting bk.InsertText("Northwind Database contains the following table:"); #region tableinsertion WTable tbl = new WTable(document); tbl.TableFormat.Borders.BorderType = BorderStyle.None; tbl.TableFormat.IsAutoResized = true; tbl.ResetCells(8, 2); IWParagraph paragraph; tbl.Rows[0].IsHeader = true; paragraph = tbl[0, 0].AddParagraph(); paragraph.AppendText("Suppliers"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[0, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[1, 0].AddParagraph(); paragraph.AppendText("Customers"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[1, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[2, 0].AddParagraph(); paragraph.AppendText("Employees"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[2, 1].AddParagraph(); paragraph.AppendText("3"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[3, 0].AddParagraph(); paragraph.AppendText("Products"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[3, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[4, 0].AddParagraph(); paragraph.AppendText("Inventory"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[4, 1].AddParagraph(); paragraph.AppendText("2"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[5, 0].AddParagraph(); paragraph.AppendText("Shippers"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[5, 1].AddParagraph(); paragraph.AppendText("1"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[6, 0].AddParagraph(); paragraph.AppendText("PO Transactions"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[6, 1].AddParagraph(); paragraph.AppendText("3"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[7, 0].AddParagraph(); paragraph.AppendText("Sales Transactions"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; paragraph = tbl[7, 1].AddParagraph(); paragraph.AppendText("7"); paragraph.BreakCharacterFormat.FontName = "Calibri"; paragraph.BreakCharacterFormat.FontSize = 10; bk.InsertTable(tbl); #endregion bk.MoveToBookmark("Image"); bk.DeleteBookmarkContent(true); // Inserting image to the bookmark. IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture; inputStream = assembly.GetManifestResourceStream(rootPath + "Northwind.png"); pic.LoadImage(inputStream); inputStream.Dispose(); pic.WidthScale = 50f; // It reduce the image size because it don't fit pic.HeightScale = 75f; // in document page. #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("BookMarkNavigation.docx", "application/msword", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("BookMarkNavigation.docx", "application/msword", stream); #endregion } } } <file_sep>/Forms/AutoComplete/AutoComplete/Samples/HeaderFooterSample/HeaderFooterSample.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using SampleBrowser.Core; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public partial class HeaderFooterSample : SampleView, INotifyPropertyChanged { public ObservableCollection<HeaderFooter.ContactsInfo> Source { get; set; } public ObservableCollection<HeaderFooter.ContactsInfo> ListSource { get; set; } public string selectedItem; public string SelectedItem { get { return selectedItem; } set { selectedItem = value; SelectedItemValue = "Search for '" + selectedItem + "'"; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem")); } } } public string selectedItemValue; public string SelectedItemValue { get { return selectedItemValue; } set { selectedItemValue = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("SelectedItemValue")); } } } public bool isFocused; public new bool IsFocused { get { return isFocused; } set { isFocused = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("IsFocused")); } } } public string watermark = "Search here"; public string Watermark { get { return watermark; } set { watermark = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Watermark")); } } } Random random = new Random(); public new event PropertyChangedEventHandler PropertyChanged; public HeaderFooterSample() { InitializeComponent(); Source = new HeaderFooter.ContactsInfoRepository().GetContactDetails(); ListSource = new HeaderFooter.ContactsInfoRepository().GetContactDetails(); this.BindingContext = this; // this.autoComplete.SuggestionMode = Syncfusion.SfAutoComplete.XForms.SuggestionMode.c if (Device.RuntimePlatform == Device.UWP) { sampleLayout.WidthRequest = 500; sampleLayout.HorizontalOptions = LayoutOptions.Center; } } string hintText = "eve"; double hintCount = -0; public void Results(int value) { } public bool ShowHint() { if (hintCount < hintText.Length) { this.autoComplete.Text += hintText[(int)hintCount++]; return true; } return false; } } public class booltofontConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return FontAttributes.Bold; return FontAttributes.None; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class booltocolorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if ((bool)value) return Color.Black; return Color.Gray; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } public class AutoCompleteImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { if (value is string) { if (Device.RuntimePlatform == Device.UWP) { #if COMMONSB return value; #else if (SampleBrowser.Core.SampleBrowser.IsIndividualSB) return value; else return "SampleBrowser.SfAutoComplete.UWP\\" + value; #endif } } } return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Sparkline/Sparkline.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Syncfusion.SfSparkline.iOS; using UIKit; using Foundation; namespace SampleBrowser { public class Sparkline : SampleView { SfAreaSparkline area; SfLineSparkline line; SfColumnSparkline column; SfWinLossSparkline winLoss; UILabel areaLabel; UILabel lineLabel; UILabel columnLabel; UILabel winLossLabel; public Sparkline() { var AreaData = new List<SparklineModel> { new SparklineModel {Value = 0.8}, new SparklineModel {Value = 1.8}, new SparklineModel {Value = 1.3}, new SparklineModel {Value = 1.1}, new SparklineModel {Value = 1.6}, new SparklineModel {Value = 2.0}, new SparklineModel {Value = 1.7}, new SparklineModel {Value = 2.3}, new SparklineModel {Value = 2.7}, new SparklineModel {Value = 2.3}, new SparklineModel {Value = 1.9}, new SparklineModel {Value = 1.4}, new SparklineModel {Value = 1.2}, new SparklineModel {Value = 0.8}, }; var LineData = new List<SparklineModel> { new SparklineModel {Value = 1.1}, new SparklineModel {Value = 0.9}, new SparklineModel {Value = 1.1}, new SparklineModel {Value = 1.3}, new SparklineModel {Value = 1.1}, new SparklineModel {Value = 1.8}, new SparklineModel {Value = 2.1}, new SparklineModel {Value = 2.3}, new SparklineModel {Value = 1.7}, new SparklineModel {Value = 1.5}, new SparklineModel {Value = 2.5}, new SparklineModel {Value = 1.9}, new SparklineModel {Value = 1.3}, new SparklineModel {Value = 0.9}, }; var ColumnData = new List<SparklineModel> { new SparklineModel {Value = 34}, new SparklineModel {Value = 23}, new SparklineModel {Value = -31}, new SparklineModel {Value = 66}, new SparklineModel {Value = 26}, new SparklineModel {Value = 44} }; var WinLossData = new List<SparklineModel> { new SparklineModel {Value = 24}, new SparklineModel {Value = 32}, new SparklineModel {Value = 14}, new SparklineModel {Value = -29}, new SparklineModel {Value = 33}, new SparklineModel {Value = 44} }; areaLabel = new UILabel(); areaLabel.Text = "Area"; areaLabel.Font = UIFont.FromName("HelveticaNeue-Bold", 13f); areaLabel.TextAlignment = UITextAlignment.Center; lineLabel = new UILabel(); lineLabel.Text = "Line"; lineLabel.Font = UIFont.FromName("HelveticaNeue-Bold", 13f); lineLabel.TextAlignment = UITextAlignment.Center; columnLabel = new UILabel(); columnLabel.Text = "Column"; columnLabel.Font = UIFont.FromName("HelveticaNeue-Bold", 13f); columnLabel.TextAlignment = UITextAlignment.Center; winLossLabel = new UILabel(); winLossLabel.Text = "WinLoss"; winLossLabel.Font = UIFont.FromName("HelveticaNeue-Bold", 13f); winLossLabel.TextAlignment = UITextAlignment.Center; area = new SfAreaSparkline(); //area.Marker = new SparklineMarker() { IsVisible = true, Color= UIColor.Clear }; area.ItemsSource = AreaData; area.YBindingPath = "Value"; area.StrokeColor = UIColor.FromRGB(166.0f / 255.0f, 173.0f / 255.0f, 134.0f / 255.0f); //area.HighPointColor = UIColor.Green; //area.LowPointColor = UIColor.Red; area.Color = UIColor.FromRGBA(166.0f/255.0f, 173.0f/255.0f, 134.0f/255.0f,0.5f); line = new SfLineSparkline(); //line.Marker = new SparklineMarker() { IsVisible = true, Color = UIColor.Clear }; line.ItemsSource = LineData; line.StrokeColor = UIColor.FromRGB(166.0f / 255.0f, 173.0f / 255.0f, 134.0f / 255.0f); //line.HighPointColor = UIColor.Green; //line.LowPointColor = UIColor.Red; line.YBindingPath = "Value"; column = new SfColumnSparkline(); column.ItemsSource = ColumnData; column.YBindingPath = "Value"; column.Color = UIColor.FromRGB(86.0f / 255.0f, 140.0f / 255.0f, 233.0f / 255.0f); column.FirstPointColor = UIColor.FromRGB(86.0f / 255.0f, 140.0f / 255.0f, 233.0f / 255.0f); column.LastPointColor = UIColor.FromRGB(86.0f / 255.0f, 140.0f / 255.0f, 233.0f / 255.0f); column.HighPointColor = UIColor.FromRGBA(166.0f / 255.0f, 173.0f / 255.0f, 134.0f / 255.0f, 0.9f); column.LowPointColor = UIColor.FromRGB(252.0f / 255.0f, 98.0f / 255.0f, 93.0f / 255.0f); winLoss = new SfWinLossSparkline(); winLoss.ItemsSource = WinLossData; winLoss.YBindingPath = "Value"; winLoss.Color = UIColor.FromRGB(86.0f / 255.0f, 140.0f / 255.0f, 233.0f / 255.0f); winLoss.FirstPointColor = UIColor.FromRGB(86.0f / 255.0f, 140.0f / 255.0f, 233.0f / 255.0f); winLoss.LastPointColor = UIColor.FromRGB(86.0f / 255.0f, 140.0f / 255.0f, 233.0f / 255.0f); winLoss.HighPointColor = UIColor.FromRGBA(166.0f / 255.0f, 173.0f / 255.0f, 134.0f / 255.0f, 0.9f); winLoss.LowPointColor = UIColor.FromRGB(252.0f / 255.0f, 98.0f / 255.0f, 93.0f / 255.0f); ; winLoss.NeutralPointsColor = UIColor.FromRGB(86.0f / 255.0f, 140.0f / 255.0f, 233.0f / 255.0f); this.AddSubview(areaLabel); this.AddSubview(lineLabel); this.AddSubview(columnLabel); this.AddSubview(winLossLabel); this.AddSubview(area); this.AddSubview(line); this.AddSubview(column); this.AddSubview(winLoss); } public override void LayoutSubviews() { nfloat X = 40; nfloat Y = 0; nfloat height = (this.Frame.Size.Height - 120) / 4; nfloat width = this.Frame.Size.Width - 80; area.Frame = new CGRect(X, Y, width, height); areaLabel.Frame = new CGRect(X, Y+ area.Frame.Size.Height, width, 15); Y = Y + area.Frame.Size.Height + 20; line.Frame = new CGRect(X,Y, width, height); lineLabel.Frame = new CGRect(X, Y+line.Frame.Size.Height, width, 15); Y = Y + line.Frame.Size.Height + 25; column.Frame = new CGRect(X, Y, width, height); columnLabel.Frame = new CGRect(X, Y+column.Frame.Size.Height+5, width, 15); Y = Y + column.Frame.Size.Height + 35; winLoss.Frame = new CGRect(X, Y, width, height); winLossLabel.Frame = new CGRect(X, Y + column.Frame.Size.Height, width, 15); base.LayoutSubviews(); } } [Preserve(AllMembers = true)] public class SparklineModel { public double Value { get; set; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/TreeView/NodeWithImage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.TreeView.Engine; using Syncfusion.iOS.TreeView; using CoreGraphics; namespace SampleBrowser { public class NodeWithImage : SampleView { SfTreeView treeView; FileManagerViewModel viewModel; public NodeWithImage() { treeView = new SfTreeView(); viewModel = new FileManagerViewModel(); treeView.Indentation = 20; treeView.ExpanderWidth = 40; treeView.ItemHeight = 40; treeView.AutoExpandMode = AutoExpandMode.AllNodesExpanded; treeView.ChildPropertyName = "SubFolder"; treeView.ItemsSource = viewModel.Folders; treeView.Adapter = new NodeImageAdapter(); this.AddSubview(treeView); } public override void LayoutSubviews() { this.treeView.Frame = new CGRect(0, 0, this.Frame.Width, this.Frame.Height); base.LayoutSubviews(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }<file_sep>/Forms/AutoComplete/AutoComplete/Samples/AutoComplete/AutoComplete_Tablet.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using Syncfusion.SfAutoComplete.XForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfAutoComplete { public partial class AutoComplete_Tablet : SampleView, INotifyPropertyChanged { public List<string> JobList { get; set; } public List<string> CountryList { get; set; } List<String> jobList { get; set; } List<String> countryList { get; set; } List<String> experienceList { get; set; } String valueCountry, valueJobField; int minpref=1, maxDrop = 150, pop=100; public AutoComplete_Tablet() { InitializeComponent(); addCountryList(); this.Content.BindingContext = this; optionLayout.BindingContext = this; AddValueChangedEvent(); AddOptionPageItems(); } void addCountryList() { countryList = new List<string>(); countryList.Add("Afghanistan"); countryList.Add("Akrotiri"); countryList.Add("Albania"); countryList.Add("Algeria"); countryList.Add("American Samoa"); countryList.Add("Andorra"); countryList.Add("Angola"); countryList.Add("Anguilla"); countryList.Add("Antarctica"); countryList.Add("Antigua and Barbuda"); countryList.Add("Argentina"); countryList.Add("Armenia"); countryList.Add("Aruba"); countryList.Add("Ashmore and Cartier Islands"); countryList.Add("Australia"); countryList.Add("Austria"); countryList.Add("Azerbaijan"); countryList.Add("Bahrain"); countryList.Add("Bangladesh"); countryList.Add("Barbados"); countryList.Add("Bassas da India"); countryList.Add("Belarus"); countryList.Add("Belgium"); countryList.Add("Belize"); countryList.Add("Benin"); countryList.Add("Bermuda"); countryList.Add("Bhutan"); countryList.Add("Bolivia"); countryList.Add("Bosnia and Herzegovina"); countryList.Add("Botswana"); countryList.Add("Bouvet Island"); countryList.Add("Brazil"); countryList.Add("British Indian Ocean Territory"); countryList.Add("British Virgin Islands"); countryList.Add("Brunei"); countryList.Add("Bulgaria"); countryList.Add("Burkina Faso"); countryList.Add("Burma"); countryList.Add("Burundi"); countryList.Add("Cambodia"); countryList.Add("Cameroon"); countryList.Add("Canada"); countryList.Add("Cape Verde"); countryList.Add("Cayman Islands"); countryList.Add("Central African Republic"); countryList.Add("Chad"); countryList.Add("Chile"); countryList.Add("China"); countryList.Add("Christmas Island"); countryList.Add("Clipperton Island"); countryList.Add("Cocos (Keeling) Islands"); countryList.Add("Colombia"); countryList.Add("Comoros"); countryList.Add("Congo"); countryList.Add("Congo, Republic of the"); countryList.Add("Cook Islands"); countryList.Add("Coral Sea Islands"); countryList.Add("Costa Rica"); countryList.Add("Cote d'Ivoire"); countryList.Add("Croatia"); countryList.Add("Cuba"); countryList.Add("Cyprus"); countryList.Add("Czech Republic"); countryList.Add("Denmark"); countryList.Add("Dhekelia"); countryList.Add("Djibouti"); countryList.Add("Dominica"); countryList.Add("Dominican Republic"); countryList.Add("Ecuador"); countryList.Add("Egypt"); countryList.Add("El Salvador"); countryList.Add("Equatorial Guinea"); countryList.Add("Eritrea"); countryList.Add("Estonia"); countryList.Add("Ethiopia"); countryList.Add("Europa Island"); countryList.Add("Falkland Islands"); countryList.Add("Faroe Islands"); countryList.Add("Fiji"); countryList.Add("Finland"); countryList.Add("France"); countryList.Add("French Guiana"); countryList.Add("French Polynesia"); countryList.Add("French Southern and Antarctic Lands"); countryList.Add("Gabon"); countryList.Add("Gambia, The"); countryList.Add("Gaza Strip"); countryList.Add("Georgia"); countryList.Add("Germany"); countryList.Add("Ghana"); countryList.Add("Gibraltar"); countryList.Add("Glorioso Islands"); countryList.Add("Greece"); countryList.Add("Greenland"); countryList.Add("Grenada"); countryList.Add("Guadeloupe"); countryList.Add("Guam"); countryList.Add("Guatemala"); countryList.Add("Guernsey"); countryList.Add("Guinea"); countryList.Add("Guinea-Bissau"); countryList.Add("Guyana"); countryList.Add("Haiti"); countryList.Add("Heard Island and McDonald Islands"); countryList.Add("Holy See"); countryList.Add("Honduras"); countryList.Add("Hong Kong"); countryList.Add("Hungary"); countryList.Add("Iceland"); countryList.Add("India"); countryList.Add("Indonesia"); countryList.Add("Iran"); countryList.Add("Iraq"); countryList.Add("Ireland"); countryList.Add("Isle of Man"); countryList.Add("Israel"); countryList.Add("Italy"); countryList.Add("Jamaica"); countryList.Add("Jan Mayen"); countryList.Add("Japan"); countryList.Add("Jersey"); countryList.Add("Jordan"); countryList.Add("Juan de Nova Island"); countryList.Add("Kazakhstan"); countryList.Add("Kenya"); countryList.Add("Kiribati"); countryList.Add("Korea, North"); countryList.Add("Korea, South"); countryList.Add("Kuwait"); countryList.Add("Kyrgyzstan"); countryList.Add("Laos"); countryList.Add("Latvia"); countryList.Add("Lebanon"); countryList.Add("Lesotho"); countryList.Add("Liberia"); countryList.Add("Libya"); countryList.Add("Liechtenstein"); countryList.Add("Lithuania"); countryList.Add("Luxembourg"); countryList.Add("Macau"); countryList.Add("Macedonia"); countryList.Add("Madagascar"); countryList.Add("Malawi"); countryList.Add("Malaysia"); countryList.Add("Maldives"); countryList.Add("Mali"); countryList.Add("Malta"); countryList.Add("Marshall Islands"); countryList.Add("Martinique"); countryList.Add("Mauritania"); countryList.Add("Mauritius"); countryList.Add("Mayotte"); countryList.Add("Mexico"); countryList.Add("Micronesia"); countryList.Add("Moldova"); countryList.Add("Monaco"); countryList.Add("Mongolia"); countryList.Add("Montserrat"); countryList.Add("Morocco"); countryList.Add("Mozambique"); countryList.Add("Namibia"); countryList.Add("Nauru"); countryList.Add("Navassa Island"); countryList.Add("Nepal"); countryList.Add("Netherlands"); countryList.Add("Netherlands Antilles"); countryList.Add("New Caledonia"); countryList.Add("New Zealand"); countryList.Add("Nicaragua"); countryList.Add("Niger"); countryList.Add("Nigeria"); countryList.Add("Niue"); countryList.Add("Norfolk Island"); countryList.Add("Northern Mariana Islands"); countryList.Add("Norway"); countryList.Add("Oman"); countryList.Add("Pakistan"); countryList.Add("Palau"); countryList.Add("Panama"); countryList.Add("Papua New Guinea"); countryList.Add("Paracel Islands"); countryList.Add("Paraguay"); countryList.Add("Peru"); countryList.Add("Philippines"); countryList.Add("Pitcairn Islands"); countryList.Add("Poland"); countryList.Add("Portugal"); countryList.Add("Puerto Rico"); countryList.Add("Qatar"); countryList.Add("Reunion"); countryList.Add("Romania"); countryList.Add("Russia"); countryList.Add("Rwanda"); countryList.Add("Saint Helena"); countryList.Add("Saint Kitts and Nevis"); countryList.Add("Saint Lucia"); countryList.Add("Saint Pierre and Miquelon"); countryList.Add("Saint Vincent"); countryList.Add("Samoa"); countryList.Add("San Marino"); countryList.Add("Sao Tome and Principe"); countryList.Add("Saudi Arabia"); countryList.Add("Senegal"); countryList.Add("Serbia and Montenegro"); countryList.Add("Seychelles"); countryList.Add("Sierra Leone"); countryList.Add("Singapore"); countryList.Add("Slovakia"); countryList.Add("Slovenia"); countryList.Add("Solomon Islands"); countryList.Add("Somalia"); countryList.Add("South Africa"); countryList.Add("South Georgia"); countryList.Add("Spain"); countryList.Add("Spratly Islands"); countryList.Add("Sri Lanka"); countryList.Add("Sudan"); countryList.Add("Suriname"); countryList.Add("Svalbard"); countryList.Add("Swaziland"); countryList.Add("Sweden"); countryList.Add("Switzerland"); countryList.Add("Syria"); countryList.Add("Taiwan"); countryList.Add("Tajikistan"); countryList.Add("Tanzania"); countryList.Add("Thailand"); countryList.Add("The Bahamas"); countryList.Add("Timor-Leste"); countryList.Add("Togo"); countryList.Add("Tokelau"); countryList.Add("Tonga"); countryList.Add("Trinidad and Tobago"); countryList.Add("Tromelin Island"); countryList.Add("Tunisia"); countryList.Add("Turkey"); countryList.Add("Turkmenistan"); countryList.Add("Turks and Caicos Islands"); countryList.Add("Tuvalu"); countryList.Add("Uganda"); countryList.Add("Ukraine"); countryList.Add("United Arab Emirates"); countryList.Add("United Kingdom"); countryList.Add("United States"); countryList.Add("Uruguay"); countryList.Add("Uzbekistan"); countryList.Add("Vanuatu"); countryList.Add("Venezuela"); countryList.Add("Vietnam"); countryList.Add("Virgin Islands"); countryList.Add("Wake Island"); countryList.Add("Wallis and Futuna"); countryList.Add("West Bank"); countryList.Add("Western Sahara"); countryList.Add("Yemen"); countryList.Add("Zambia"); countryList.Add("Zimbabwe"); CountryList = this.countryList; jobList = new List<string>(); jobList.Add("Banking"); jobList.Add("Media"); jobList.Add("Medical"); jobList.Add("Software"); JobList = this.jobList; List<string> dataSource = new List<string>(); dataSource.Add("1 year"); dataSource.Add("2 years"); dataSource.Add("3 years"); experienceAutoComplete.DataSource = dataSource; } void Handle_Clicked(object sender, System.EventArgs e) { if (countryList.Contains(countryAutoComplete.Text) && jobList.Contains(jobFieldAutoComplete.Text)) { Random r = new Random(); Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Results", "There are " + r.Next(9, 50) + " " + jobFieldAutoComplete.Text + " jobs found in " + countryAutoComplete.Text + ".", "Ok"); } else { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Results", "0 job found", "OK"); } } void AddValueChangedEvent() { countryAutoComplete.ValueChanged += (object sender, Syncfusion.SfAutoComplete.XForms.ValueChangedEventArgs e) => { valueCountry = e.Value; }; jobFieldAutoComplete.ValueChanged += (object sender, Syncfusion.SfAutoComplete.XForms.ValueChangedEventArgs e) => { valueJobField = e.Value; }; countryAutoComplete.SelectionChanged += (sender, e) => { if (Device.RuntimePlatform == Device.iOS) valueCountry = e.Value.ToString(); }; jobFieldAutoComplete.SelectionChanged += (sender, e) => { if (Device.RuntimePlatform == Device.iOS) valueJobField = e.Value.ToString(); }; } public new event PropertyChangedEventHandler PropertyChanged; private bool isSelectAllOnFocus = false; public bool IsSelectAllOnFocus { get { return isSelectAllOnFocus; } set { isSelectAllOnFocus = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("IsSelectAllOnFocus")); } } } public void SelectionIndex_Changed(object c, EventArgs e) { if (suggestionModepicker != null) { switch (suggestionModepicker.SelectedIndex) { case 0: { countryAutoComplete.SuggestionMode = SuggestionMode.StartsWith; jobFieldAutoComplete.SuggestionMode = SuggestionMode.StartsWith; } break; case 1: { countryAutoComplete.SuggestionMode = SuggestionMode.StartsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SuggestionMode.StartsWithCaseSensitive; } break; case 2: { countryAutoComplete.SuggestionMode = SuggestionMode.Contains; jobFieldAutoComplete.SuggestionMode = SuggestionMode.Contains; } break; case 3: { countryAutoComplete.SuggestionMode = SuggestionMode.ContainsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SuggestionMode.ContainsWithCaseSensitive; } break; case 4: { countryAutoComplete.SuggestionMode = SuggestionMode.EndsWith; jobFieldAutoComplete.SuggestionMode = SuggestionMode.EndsWith; } break; case 5: { countryAutoComplete.SuggestionMode = SuggestionMode.EndsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SuggestionMode.EndsWithCaseSensitive; } break; case 6: { countryAutoComplete.SuggestionMode = SuggestionMode.Equals; jobFieldAutoComplete.SuggestionMode = SuggestionMode.Equals; } break; case 7: { countryAutoComplete.SuggestionMode = SuggestionMode.EqualsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SuggestionMode.EqualsWithCaseSensitive; } break; } } } public void autoCompleteModepicker_Changed(object c, EventArgs e) { if (autoCompleteModepicker != null) { switch (autoCompleteModepicker.SelectedIndex) { case 0: { countryAutoComplete.AutoCompleteMode = AutoCompleteMode.Suggest; jobFieldAutoComplete.AutoCompleteMode = AutoCompleteMode.Suggest; } break; case 1: { countryAutoComplete.AutoCompleteMode = AutoCompleteMode.Append; jobFieldAutoComplete.AutoCompleteMode = AutoCompleteMode.Append; } break; case 2: { countryAutoComplete.AutoCompleteMode = AutoCompleteMode.SuggestAppend; jobFieldAutoComplete.AutoCompleteMode = AutoCompleteMode.SuggestAppend; } break; } } } //autocomplete mode selected index change public void PrefixCharacter_Changed(object c, TextChangedEventArgs e) { if (minPrefixCharacterText != null) { if (e.NewTextValue.Length > 0) { int minimumPrefixCharacters; if (int.TryParse(e.NewTextValue, out minimumPrefixCharacters)) { countryAutoComplete.MinimumPrefixCharacters = minimumPrefixCharacters; jobFieldAutoComplete.MinimumPrefixCharacters = minimumPrefixCharacters; minpref = minimumPrefixCharacters; } } } } public void MaximumHeight_Changed(object c, TextChangedEventArgs e) { if (maximumDropDownHeightText != null) { if (e.NewTextValue.Length > 0) { int maximumDropDownHeight; if (int.TryParse(e.NewTextValue, out maximumDropDownHeight)) { countryAutoComplete.MaximumDropDownHeight = maximumDropDownHeight; jobFieldAutoComplete.MaximumDropDownHeight = maximumDropDownHeight; maxDrop = maximumDropDownHeight; } } } } public void PopUp_Changed(object c, TextChangedEventArgs e) { if (PopupDelayText != null) { if (e.NewTextValue.Length > 0) { int popupDelay; if (int.TryParse(e.NewTextValue, out popupDelay)) { countryAutoComplete.PopupDelay = popupDelay; jobFieldAutoComplete.PopupDelay = popupDelay; pop = popupDelay; } } } } public void search_Clicked(object c, EventArgs e) { if (valueCountry != "" && valueJobField != "") { Random r = new Random(); Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Results", r.Next(9, 50) + " Jobs found", "OK"); } else { Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Results", "0 Jobs found", "OK"); } } void AddOptionPageItems() { suggestionModepicker.Items.Add("StartsWith"); suggestionModepicker.Items.Add("StartsWithCaseSensitive"); suggestionModepicker.Items.Add("Contains"); suggestionModepicker.Items.Add("ContainsWithCaseSensitive"); suggestionModepicker.Items.Add("EndsWith"); suggestionModepicker.Items.Add("EndsWithCaseSensitive"); suggestionModepicker.Items.Add("Equals"); suggestionModepicker.Items.Add("EqualsWithCaseSensitive"); //AutoCompleteModePicker Items autoCompleteModepicker.Items.Add("Suggest"); autoCompleteModepicker.Items.Add("Append"); autoCompleteModepicker.Items.Add("SuggestAppend"); autoCompleteModepicker.SelectedIndex = 0; suggestionModepicker.SelectedIndex = 0; valueCountry = string.Empty; valueJobField = string.Empty; maximumDropDownHeightText.TextChanged += (object sender, TextChangedEventArgs e) => { if (e.NewTextValue.Length > 0) { int maximumDropDownHeight; if (int.TryParse(e.NewTextValue, out maximumDropDownHeight)) { countryAutoComplete.MaximumDropDownHeight = maximumDropDownHeight; jobFieldAutoComplete.MaximumDropDownHeight = maximumDropDownHeight; } } else { countryAutoComplete.MaximumDropDownHeight = 100; jobFieldAutoComplete.MaximumDropDownHeight = 100; } }; minPrefixCharacterText.TextChanged += (object sender, TextChangedEventArgs e) => { if (e.NewTextValue.Length > 0) { int minimumPrefixCharacters; if (int.TryParse(e.NewTextValue, out minimumPrefixCharacters)) { countryAutoComplete.MinimumPrefixCharacters = minimumPrefixCharacters; jobFieldAutoComplete.MinimumPrefixCharacters = minimumPrefixCharacters; } } else { countryAutoComplete.MinimumPrefixCharacters = 1; jobFieldAutoComplete.MinimumPrefixCharacters = 1; } }; PopupDelayText.TextChanged += (object sender, TextChangedEventArgs e) => { if (e.NewTextValue.Length > 0) { int popupDelay; if (int.TryParse(e.NewTextValue, out popupDelay)) { countryAutoComplete.PopupDelay = popupDelay; jobFieldAutoComplete.PopupDelay = popupDelay; } } else { countryAutoComplete.PopupDelay = 0; jobFieldAutoComplete.PopupDelay = 0; } }; // suggestion mode selected index change suggestionModepicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (suggestionModepicker.SelectedIndex) { case 0: { countryAutoComplete.SuggestionMode = SuggestionMode.StartsWith; jobFieldAutoComplete.SuggestionMode = SuggestionMode.StartsWith; } break; case 1: { countryAutoComplete.SuggestionMode = SuggestionMode.StartsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SuggestionMode.StartsWithCaseSensitive; } break; case 2: { countryAutoComplete.SuggestionMode = SuggestionMode.Contains; jobFieldAutoComplete.SuggestionMode = SuggestionMode.Contains; } break; case 3: { countryAutoComplete.SuggestionMode = SuggestionMode.ContainsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SuggestionMode.ContainsWithCaseSensitive; } break; case 4: { countryAutoComplete.SuggestionMode = SuggestionMode.EndsWith; jobFieldAutoComplete.SuggestionMode = SuggestionMode.EndsWith; } break; case 5: { countryAutoComplete.SuggestionMode = SuggestionMode.EndsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SuggestionMode.EndsWithCaseSensitive; } break; case 6: { countryAutoComplete.SuggestionMode = SuggestionMode.Equals; jobFieldAutoComplete.SuggestionMode = SuggestionMode.Equals; } break; case 7: { countryAutoComplete.SuggestionMode = SuggestionMode.EqualsWithCaseSensitive; jobFieldAutoComplete.SuggestionMode = SuggestionMode.EqualsWithCaseSensitive; } break; } }; //autocomplete mode selected index change autoCompleteModepicker.SelectedIndexChanged += (object sender, EventArgs e) => { switch (autoCompleteModepicker.SelectedIndex) { case 0: { countryAutoComplete.AutoCompleteMode = AutoCompleteMode.Suggest; jobFieldAutoComplete.AutoCompleteMode = AutoCompleteMode.Suggest; } break; case 1: { countryAutoComplete.AutoCompleteMode = AutoCompleteMode.Append; jobFieldAutoComplete.AutoCompleteMode = AutoCompleteMode.Append; } break; case 2: { countryAutoComplete.AutoCompleteMode = AutoCompleteMode.SuggestAppend; jobFieldAutoComplete.AutoCompleteMode = AutoCompleteMode.SuggestAppend; } break; } }; popupDelayLabel.WidthRequest = 220; searchButton.BackgroundColor = Color.FromHex("#2196f3"); searchButton.CornerRadius = 1; searchButton.BorderWidth = 0; searchButton.TextColor = Color.White; searchButton.FontFamily = "Roboto"; jobSearchLabel.TextColor = Color.FromHex("#666666"); countryAutoComplete.TextColor = Color.FromHex("#333333"); jobFieldAutoComplete.TextColor = Color.FromHex("#333333"); suggestionModeLabel.TextColor = Color.FromHex("#666666"); suggestionModepicker.TextColor = Color.FromHex("#333333"); autoCompleteModeLabel.TextColor = Color.FromHex("#666666"); autoCompleteModepicker.TextColor = Color.FromHex("#333333"); minimumPrefixCharacterLabel.TextColor = Color.FromHex("#666666"); minPrefixCharacterText.TextColor = Color.FromHex("#333333"); maximumDropDownHeightLabel.TextColor = Color.FromHex("#666666"); maximumDropDownHeightText.TextColor = Color.FromHex("#333333"); popupDelayLabel.TextColor = Color.FromHex("#666666"); PopupDelayText.TextColor = Color.FromHex("#333333"); pickerLayout1.Padding = new Thickness(-2, 0, 0, 0); pickerLayout2.Margin = new Thickness(-2, 0, 0, 0); } public View getContent() { return this.Content; } public View getPropertyView() { return this.PropertyView; } void Handle_SelectionChanged(object sender, Syncfusion.SfAutoComplete.XForms.SelectionChangedEventArgs e) { if (experienceAutoComplete.SelectedIndex == 0) { experienceAutoComplete.Text = "1 year"; } else if (experienceAutoComplete.SelectedIndex == 1) { experienceAutoComplete.Text = "2 years"; } else if (experienceAutoComplete.SelectedIndex == 2) { experienceAutoComplete.Text = "3 years"; } } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Axis/MultipleAxis.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.OS; using Android.Graphics; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Android.Views; using System.Collections.Generic; namespace SampleBrowser { public class MultipleAxis : SamplePage { public override View GetSampleContent(Context context) { var chart = new SfChart(context); chart.SetBackgroundColor(Color.White); chart.Legend.ToggleSeriesVisibility = true; chart.Title.Text = "Weather Condition JPN vs DEU"; chart.Legend.Visibility = Visibility.Visible; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.Legend.DockPosition = ChartDock.Bottom; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; var primary = new CategoryAxis(); primary.Title.Text = "Year"; primary.Title.TextColor = Color.Black; primary.LabelPlacement = LabelPlacement.BetweenTicks; primary.ShowMajorGridLines = false; chart.PrimaryAxis = primary; var secondaryAxis = new NumericalAxis() { Interval = 2, ShowMajorGridLines = false }; secondaryAxis.LabelStyle.LabelFormat = "##.##" + (char)0x00B0 + "F"; secondaryAxis.Maximum = 100; secondaryAxis.Minimum = 0; secondaryAxis.Interval = 20; chart.SecondaryAxis = secondaryAxis; var datas = new List<DataPoint>(); datas.Add(new DataPoint("Sun", 35)); datas.Add(new DataPoint("Mon",40 )); datas.Add(new DataPoint("Tue",80 )); datas.Add(new DataPoint("Wed",70 )); datas.Add(new DataPoint("Thu",65 )); datas.Add(new DataPoint("Fri",55 )); datas.Add(new DataPoint("Sat", 50 )); var datas1 = new List<DataPoint>(); datas1.Add(new DataPoint("Sun", 30)); datas1.Add(new DataPoint("Mon", 28)); datas1.Add(new DataPoint("Tue", 29)); datas1.Add(new DataPoint("Wed", 30)); datas1.Add(new DataPoint("Thu", 33)); datas1.Add(new DataPoint("Fri", 32)); datas1.Add(new DataPoint("Sat", 34)); chart.Series.Add(new ColumnSeries() { Label = "Germany", ItemsSource = datas, XBindingPath = "XValue", YBindingPath = "YValue", TooltipEnabled = true, EnableAnimation = true, }); var lineSeries = new FastLineSeries() { Label = "Japan", ItemsSource = datas1, XBindingPath = "XValue", YBindingPath = "YValue", EnableAnimation = true, YAxis = new NumericalAxis() { OpposedPosition = true, Minimum = 24, Maximum = 36, Interval = 2, ShowMajorGridLines = false, } }; lineSeries.DataMarker.ShowLabel = false; lineSeries.DataMarker.ShowMarker = true; lineSeries.DataMarker.MarkerColor = Color.White; lineSeries.DataMarker.MarkerWidth = 10; lineSeries.DataMarker.MarkerHeight = 10; lineSeries.DataMarker.MarkerStrokeColor = Color.ParseColor("#F8AB1D"); lineSeries.DataMarker.MarkerStrokeWidth = 2; lineSeries.YAxis.LabelStyle.LabelFormat = "##.##" + (char)0x00B0 + "C"; chart.Series.Add(lineSeries); lineSeries.TooltipEnabled = true; return chart; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/SunburstChart/SunburstChart.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSunburstChart.iOS; using CoreGraphics; using UIKit; using System.Collections.ObjectModel; using Foundation; namespace SampleBrowser { public class SunburstChart : SampleView { SfSunburstChart chart; public SunburstChart() { var Data = new ObservableCollection<SunburstModel>(); Data.Add(new SunburstModel() { Quarter = "Q1", Month = "Jan", Sales = 11 }); Data.Add(new SunburstModel() { Quarter = "Q1", Month = "Feb", Sales = 8 }); Data.Add(new SunburstModel() { Quarter = "Q1", Month = "Mar", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q2", Month = "Apr", Sales = 13 }); Data.Add(new SunburstModel() { Quarter = "Q2", Month = "May", Sales = 12 }); Data.Add(new SunburstModel() { Quarter = "Q2", Month = "Jun", Sales = 17 }); Data.Add(new SunburstModel() { Quarter = "Q3", Month = "Jul", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q3", Month = "Aug", Sales = 4 }); Data.Add(new SunburstModel() { Quarter = "Q3", Month = "Sep", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Oct", Sales = 7 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Nov", Sales = 18 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W1", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W2", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W3", Sales = 5 }); Data.Add(new SunburstModel() { Quarter = "Q4", Month = "Dec", Week = "W4", Sales = 5 }); chart = new SfSunburstChart(); chart.ItemsSource = Data; chart.Radius = 0.95; chart.ValueMemberPath = "Sales"; var levels = new SunburstLevelCollection() { new SunburstHierarchicalLevel() { GroupMemberPath = "Quarter"}, new SunburstHierarchicalLevel() { GroupMemberPath = "Month"}, new SunburstHierarchicalLevel() { GroupMemberPath = "Week"}, }; chart.Levels = levels; chart.Title.IsVisible = true; chart.Title.Text = "Sales Performance"; chart.Title.Font= UIFont.SystemFontOfSize(20); chart.Title.Margin = new UIEdgeInsets(10, 5, 5, 5); chart.Legend.IsVisible = true; chart.Legend.LegendPosition = SunburstDockPosition.Bottom; chart.Legend.LabelStyle.Font= UIFont.SystemFontOfSize(16); chart.Legend.IconHeight = 12; chart.Legend.IconWidth = 12; chart.DataLabel.ShowLabel = true; chart.EnableAnimation = true; chart.TooltipSettings = new CustomTooltip(); chart.TooltipSettings.ShowTooltip = true; this.AddSubview(chart); } public override void LayoutSubviews() { base.LayoutSubviews(); chart.Frame = new CGRect(Frame.Location.X, 0, this.Frame.Width, this.Frame.Height); } } public class CustomTooltip : SunburstTooltipSettings { public override UIView GetView(SunburstSegment segment) { UIView customView = new UIView(); customView.BackgroundColor = UIColor.Black; customView.Layer.CornerRadius = 5; UILabel label = new UILabel(); label.TextColor = UIColor.White; label.Font = UIFont.FromName("Helvetica", 13f); label.Text = "Category : " + segment.Category; var labelSize = label.SystemLayoutSizeFittingSize(UIKit.UIView.UILayoutFittingExpandedSize); label.Frame = new CGRect(7, 7, labelSize.Width, labelSize.Height); UILabel label1 = new UILabel(); label1.TextColor = UIColor.White; label1.Font = UIFont.FromName("Helvetica", 13f); label1.Text = "Value : " + segment.Value; var labelSize1 = label1.SystemLayoutSizeFittingSize(UIKit.UIView.UILayoutFittingExpandedSize); label1.Frame = new CGRect(7, labelSize.Height + 7, labelSize1.Width, labelSize1.Height); customView.AddSubview(label); customView.AddSubview(label1); var height = label.Frame.Height + label1.Frame.Height; var width = label.Frame.Width > label1.Frame.Width ? label.Frame.Width : label1.Frame.Width; customView.Frame = new CGRect(0, 0, width + 14, height + 14); return customView; } } [Preserve(AllMembers = true)] public class SunburstModel { public string Category { get; set; } public string Country { get; set; } public string JobDescription { get; set; } public string JobGroup { get; set; } public string JobRole { get; set; } public double EmployeesCount { get; set; } public string Continent { get; set; } public string State { get; set; } public double Population { get; set; } public string Quarter { get; set; } public string Month { get; set; } public string Week { get; set; } public double Sales { get; set; } } }<file_sep>/Forms/PDF/PDF/Samples/WatermarkAnnotation/WatermarkAnnotation.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Pdf; using System; using System.IO; using Xamarin.Forms; using System.Reflection; using SampleBrowser.Core; using Syncfusion.Pdf.Exporting; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Interactive; using Syncfusion.Drawing; namespace SampleBrowser.PDF { public partial class WatermarkAnnotation : SampleView { public WatermarkAnnotation() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { #if COMMONSB Stream documentStream = typeof(WatermarkAnnotation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.InvoiceTemplate.pdf"); #else Stream documentStream = typeof(WatermarkAnnotation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.InvoiceTemplate.pdf"); #endif //Load the existing PDF document. PdfLoadedDocument document = new PdfLoadedDocument(documentStream); //Get the existing PDF page. PdfLoadedPage page = document.Pages[0] as PdfLoadedPage; SizeF pageSize = page.Size; //Create new watermark annotation. PdfWatermarkAnnotation watermarkAnnotation = new PdfWatermarkAnnotation(new RectangleF(0, 0, pageSize.Width, pageSize.Height)); //Set opacity and annotation flags. watermarkAnnotation.Opacity = 0.25F; watermarkAnnotation.AnnotationFlags = PdfAnnotationFlags.Print; //Get the appearance graphics. PdfGraphics graphics = watermarkAnnotation.Appearance.Normal.Graphics; string watermarkText = "Confidential"; PdfFont watermarkFont = new PdfStandardFont(PdfFontFamily.Helvetica, 40); SizeF textSize = watermarkFont.MeasureString(watermarkText); //Find the center position. float x = pageSize.Width / 2 - textSize.Width / 2; float y = pageSize.Height / 2; graphics.Save(); graphics.TranslateTransform(x, y); graphics.RotateTransform(-45); //Draw the watermark content. graphics.DrawString(watermarkText, watermarkFont, PdfBrushes.Red, PointF.Empty); graphics.Restore(); if (flatten.IsChecked) { watermarkAnnotation.Flatten = true; } //Add the watermark annotation to the PDF page. page.Annotations.Add(watermarkAnnotation); MemoryStream stream = new MemoryStream(); //Saves the PDF to the memory stream. document.Save(stream); //Close the PDF document document.Close(true); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("WatermarkAnnotation.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("WatermarkAnnotation.pdf", "application/pdf", stream); } } } <file_sep>/Forms/TabView/TabView.iOS/CustomEntryRenderer.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Xamarin.Forms; using UIKit; using Xamarin.Forms.Platform.iOS; using SampleBrowser.SfTabView; using SampleBrowser.SfTabView.iOS; [assembly: ExportRenderer(typeof(CustomizedEntry), typeof(CustomEntryRenderer))] namespace SampleBrowser.SfTabView.iOS { public class CustomEntryRenderer : EntryRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Entry> e) { base.OnElementChanged(e); if (Control != null) { Control.BorderStyle = UITextBorderStyle.None; Control.Layer.CornerRadius = 10; } } } } <file_sep>/Android/SampleBrowser/Samples/Calendar/CalendarConfiguration/CalendarConfiguration_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Calendar; using Com.Syncfusion.Calendar.Enums; using Android.Graphics; using Java.Util; using Android.Text.Format; using Java.Text; namespace SampleBrowser { public class CalendarConfiguration_Tab : SamplePage, IDisposable { /********************************* **Local Variable Inizialisation** *********************************/ private int minYear = 2012, minMonth = 0, minDay = 1; private int maxYear = 2018, maxMonth = 11, maxDay = 1; private String minTextDate = "1/1/2012", maxTextDate = "1/12/2018"; private Button minDateButton, maxDateButton; private DatePickerDialog minDatePicker, maxDatePicker; private LinearLayout proprtyOptionsLayout; private FrameLayout mainLayout; private Calendar minPick, maxPick; private const int DATEDIALOGID = 0; private ArrayAdapter<String> dataAdapter; private Spinner modeSpinner; private SfCalendar calendar; private Context context; public override View GetSampleContent(Context context1) { context = context1; //calendar mainLayout = new FrameLayout(context); calendar = new SfCalendar(context); calendar.ShowEventsInline = false; calendar.ViewMode = ViewMode.MonthView; calendar.HeaderHeight = 100; MonthViewLabelSetting labelSettings = new MonthViewLabelSetting(); labelSettings.DateLabelSize = 14; MonthViewSettings monthViewSettings = new MonthViewSettings(); monthViewSettings.MonthViewLabelSetting = labelSettings; monthViewSettings.TodayTextColor = Color.ParseColor("#1B79D6"); monthViewSettings.SelectedDayTextColor = Color.Black; monthViewSettings.InlineBackgroundColor = Color.ParseColor("#E4E8ED"); monthViewSettings.CurrentMonthTextColor = Color.ParseColor("#F7F7F7"); monthViewSettings.WeekDayBackgroundColor = Color.ParseColor("#464646"); monthViewSettings.WeekDayTextColor = Color.ParseColor("#F9F9F9"); monthViewSettings.PreviousMonthTextColor = Color.ParseColor("#BFBFBF"); monthViewSettings.PreviousMonthBackgroundColor = Color.ParseColor("#F9F9F9"); calendar.MonthViewSettings = monthViewSettings; calendar.DrawMonthCell += Calendar_DrawMonthCell; mainLayout.AddView(calendar); return mainLayout; } public override View GetPropertyWindowLayout(Context context) { proprtyOptionsLayout = new LinearLayout(context); proprtyOptionsLayout.SetPadding(40, 40, 40, 0); proprtyOptionsLayout.Orientation = Android.Widget.Orientation.Vertical; SelectionModeLayout(); MinimumDateLayout(); MaximumDateLayout(); return proprtyOptionsLayout; } private void SelectionModeLayout() { //ViewMode TextView viewModeLabel = new TextView(context); viewModeLabel.SetPadding(0, 0, 0, 30); viewModeLabel.TextSize = 20; viewModeLabel.Text = "Selection Mode"; modeSpinner = new Spinner(context, SpinnerMode.Dialog); //Selection List List<String> selectionList = new List<String>(); selectionList.Add("Single Selection"); selectionList.Add("Multiple Selection"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, selectionList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); //ModeSpinner modeSpinner.Adapter = dataAdapter; modeSpinner.SetSelection(0); //Mode Spinner Item Changed Listener modeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Single Selection")) { calendar.SelectionMode = SelectionMode.SingleSelection; } if (selectedItem.Equals("Multiple Selection")) { calendar.SelectionMode = SelectionMode.MultiSelection; } }; LinearLayout viewModeLayout = new LinearLayout(context); viewModeLayout.Orientation = Android.Widget.Orientation.Vertical; viewModeLayout.SetPadding(0, 0, 0, 50); viewModeLayout.AddView(viewModeLabel); viewModeLayout.AddView(modeSpinner); proprtyOptionsLayout.AddView(viewModeLayout); } private void MinimumDateLayout() { minPick = Calendar.Instance; minPick.Set(2012, 0, 1); maxPick = Calendar.Instance; maxPick.Set(2018, 11, 1); //Minimum Date Text TextView minDate = new TextView(context); minDate.SetPadding(0, 0, 0, 30); minDate.Text = "Min Date"; minDate.TextSize = 20; minDate.Gravity = GravityFlags.Left; //minDateButton minDateButton = new Button(context); minDateButton.SetBackgroundColor(Color.ParseColor("#8CD4CF")); minDateButton.Text = minTextDate; minDateButton.TextSize = 16; minDatePicker = new DatePickerDialog(context, MinDateSetting, minYear, minMonth, minDay); minDateButton.Click += (object sender, EventArgs e) => { minDatePicker.Show(); }; //minDateLayout LinearLayout minDateLayout = new LinearLayout(context); minDateLayout.Orientation = Android.Widget.Orientation.Vertical; minDateLayout.SetPadding(0, 0, 0, 50); minDateLayout.AddView(minDate); minDateLayout.AddView(minDateButton); proprtyOptionsLayout.AddView(minDateLayout); } private void MaximumDateLayout() { //Maximum Date Text TextView maxDate = new TextView(context); maxDate.SetPadding(0, 0, 0, 50); maxDate.Text = "Max Date"; maxDate.TextSize = 20; maxDate.Gravity = GravityFlags.Left; //maxDateButton maxDateButton = new Button(context); maxDateButton.Text = maxTextDate; maxDateButton.TextSize = 16; maxDateButton.SetBackgroundColor(Color.ParseColor("#8CD4CF")); maxDatePicker = new DatePickerDialog(context, MaxDateSetting, maxYear, maxMonth, maxDay); maxDateButton.Click += (object sender, EventArgs e) => { maxDatePicker.Show(); }; //maxDateLayout LinearLayout maxDateLayout = new LinearLayout(context); maxDateLayout.Orientation = Android.Widget.Orientation.Vertical; maxDateLayout.SetPadding(0, 0, 0, 50); maxDateLayout.AddView(maxDate); maxDateLayout.AddView(maxDateButton); proprtyOptionsLayout.AddView(maxDateLayout); } //Minimum DateSelected Method private void MinDateSetting(object sender, DatePickerDialog.DateSetEventArgs e) { DateTime newMinDate = e.Date; minYear = newMinDate.Year; minMonth = newMinDate.Month; minDay = newMinDate.Day; minTextDate = minDay.ToString() + "/" + minMonth.ToString() + "/" + minYear.ToString(); Calendar minCal = Calendar.Instance; minCal.Set(newMinDate.Year, newMinDate.Month - 1, newMinDate.Day); if (calendar.MaxDate == null || (calendar.MaxDate != null && minCal.Before(calendar.MaxDate))) { calendar.MinDate = minCal; StringBuilder stringBuilder = new StringBuilder().Append(newMinDate.Day).Append("/").Append(newMinDate.Month).Append("/").Append(newMinDate.Year); minDateButton.Text = stringBuilder.ToString(); } } //Maximum DateSelected Method private void MaxDateSetting(object sender, DatePickerDialog.DateSetEventArgs e) { DateTime newMaxDate = e.Date; maxYear = newMaxDate.Year; maxMonth = newMaxDate.Month; maxDay = newMaxDate.Day; maxTextDate = maxDay.ToString() + "/" + maxMonth.ToString() + "/" + maxYear.ToString(); Calendar maxCal = Calendar.Instance; maxCal.Set(newMaxDate.Year, newMaxDate.Month - 1, newMaxDate.Day); if (calendar.MinDate == null || (calendar.MinDate != null && maxCal.After(calendar.MinDate))) { calendar.MaxDate = maxCal; StringBuilder stringBuilder = new StringBuilder().Append(newMaxDate.Day).Append("/").Append(newMaxDate.Month).Append("/").Append(newMaxDate.Year); maxDateButton.Text = stringBuilder.ToString(); } } private void Calendar_DrawMonthCell(object sender, DrawMonthCellEventArgs e) { SimpleDateFormat compareString = new SimpleDateFormat("dd/MM/yyyy"); String temp = new SimpleDateFormat("dd/MM/yyyy").Format(e.MonthCell.Date.Time); Java.Util.Date date = compareString.Parse(temp); string dayString = new SimpleDateFormat("EEEE").Format(date); if (dayString.ToLower().Equals("sunday") || dayString.ToLower().Equals("saturday")) { e.MonthCell.TextColor = Color.ParseColor("#0990e9"); e.MonthCell.FontAttribute = Typeface.Create(" ", TypefaceStyle.Bold); } else { e.MonthCell.TextColor = Color.ParseColor("#7F7F7F"); e.MonthCell.FontAttribute = Typeface.Create(" ", TypefaceStyle.Italic); } } public void Dispose() { if(calendar != null) { calendar.DrawMonthCell -= Calendar_DrawMonthCell; calendar.Dispose(); calendar = null; } if (modeSpinner != null) { modeSpinner.Dispose(); modeSpinner = null; } if (dataAdapter != null) { dataAdapter.Dispose(); dataAdapter = null; } if (minPick != null) { minPick.Dispose(); minPick = null; } if (maxPick != null) { maxPick.Dispose(); maxPick = null; } if (mainLayout != null) { mainLayout.Dispose(); mainLayout = null; } if (proprtyOptionsLayout != null) { proprtyOptionsLayout.Dispose(); proprtyOptionsLayout = null; } if (minDatePicker != null) { minDatePicker.Dispose(); minDatePicker = null; } if (maxDatePicker != null) { maxDatePicker.Dispose(); maxDatePicker = null; } if (minDateButton != null) { minDateButton.Dispose(); minDateButton = null; } if (maxDateButton != null) { maxDateButton.Dispose(); maxDateButton = null; } } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/Maps/ColorMapping.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. using Syncfusion.SfBusyIndicator.iOS; #endregion using System; using Syncfusion.SfMaps.iOS; using System.Collections.ObjectModel; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGPoint= System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class ColorMapping: SampleView { internal SFBusyIndicator busyindicator; UIView view; UILabel label; UIView markerView; UIView toastView; SFShapeFileLayer layer; public override void LayoutSubviews () { view.Frame = new CGRect(Frame.Location.X,0.0f,Frame.Size.Width,Frame.Size.Height); busyindicator.Frame = new CGRect(Frame.Location.X,0.0f,Frame.Size.Width,Frame.Size.Height);; markerView.Frame = new CGRect(Frame.Location.X+3,Frame.Size.Height-10,Frame.Size.Width-6,30); layer.LegendSettings.Position = new CGPoint (15, Frame.Height - 100); label.Frame=new CGRect(0f,0f,Frame.Size.Width,40); SetNeedsDisplay (); } public ColorMapping () { SFMap maps = new SFMap (); view = new UIView (); busyindicator = new SFBusyIndicator (); busyindicator.ViewBoxWidth=75; busyindicator.ViewBoxHeight=75; busyindicator.Foreground= UIColor.FromRGB (0x77, 0x97, 0x72); /*#779772*/ busyindicator.AnimationType=SFBusyIndicatorAnimationType.SFBusyIndicatorAnimationTypeSlicedCircle; view.AddSubview (busyindicator); NSTimer.CreateScheduledTimer (TimeSpan.FromSeconds (0.3), delegate { maps.Frame = new CGRect(Frame.Location.X,60,Frame.Size.Width-6,Frame.Size.Height-60); view.AddSubview (maps); }); view.Frame=new CGRect(0,0,300,400); markerView = new UIView (); label = new UILabel (); label.TextAlignment = UITextAlignment.Center; label.Text = "Primary Agricultural Activity of USA"; label.Font = UIFont.SystemFontOfSize (18); label.Frame=new CGRect(0,0,400,40); label.TextColor = UIColor.Black; view.AddSubview (label); layer = new SFShapeFileLayer(); layer.Uri = (NSString)NSBundle.MainBundle.PathForResource ("usa_state", "shp"); layer.DataSource = GetDataSource (); SetColorMapping(layer.ShapeSettings); layer.ShapeSettings.ColorValuePath =(NSString)"Type"; layer.ShapeSettings.StrokeColor = UIColor.White; layer.LegendSettings = new SFMapLegendSettings (); layer.LegendSettings.Position = new CGPoint(50, 5); layer.LegendSettings.ShowLegend = true; layer.EnableSelection = true; layer.LegendSettings.TextSize = 15; maps.Layers.Add (layer); AddSubview (view); maps.Delegate = new MapsColorMappingDelegate (this); } NSMutableArray GetDataSource() { NSMutableArray array = new NSMutableArray (); array.Add(getDictionary("Alabama" , "Vegetables" , 42)); array.Add(getDictionary( "Alaska" , "Vegetables" , 0 )); array.Add(getDictionary( "Arizona" , "Rice" , 36 )); array.Add(getDictionary( "Arkansas" , "Vegetables" , 46 )); array.Add(getDictionary( "California" , "Rice" , 24 )); array.Add(getDictionary( "Colorado" , "Rice" , 31)); array.Add(getDictionary( "Connecticut" , "Grains" , 18 )); array.Add(getDictionary( "Delaware" , "Grains" , 28 )); array.Add(getDictionary( "District of Columbia" , "Grains" , 27 )); array.Add(getDictionary( "Florida" , "Rice" , 48 )); array.Add(getDictionary( "Georgia" , "Rice" , 44)); array.Add(getDictionary( "Hawaii" , "Grains" , 49 )); array.Add(getDictionary( "Idaho" , "Grains" , 8 )); array.Add(getDictionary( "Illinois" , "Vegetables" , 26 )); array.Add(getDictionary( "Indiana" , "Grains" , 21 )); array.Add(getDictionary( "Iowa" , "Vegetables" , 13 )); array.Add(getDictionary( "Kansas" , "Rice" , 33 )); array.Add(getDictionary( "Kentucky" , "Grains" , 32 )); array.Add(getDictionary( "Louisiana" , "Rice" , 47 )); array.Add(getDictionary( "Maine" , "Grains" , 3 )); array.Add(getDictionary( "Maryland" , "Grains" , 30 )); array.Add(getDictionary( "Massachusetts" , "Grains" , 14 )); array.Add(getDictionary( "Michigan" , "Grains" , 50 )); array.Add(getDictionary( "Minnesota" , "Wheat" , 10 )); array.Add(getDictionary( "Mississippi" , "Vegetables" , 43 )); array.Add(getDictionary( "Missouri" , "Vegetables" , 35 )); array.Add(getDictionary( "Montana" , "Grains" , 2 )); array.Add(getDictionary( "Nebraska" , "Rice" , 15 )); array.Add(getDictionary( "Nevada" , "Wheat" , 22 )); array.Add(getDictionary( "New Hampshire" , "Grains" , 12 )); array.Add(getDictionary( "New Jersey" , "Vegetables" , 20 )); array.Add(getDictionary( "New Mexico" , "Rice" , 41 )); array.Add(getDictionary( "New York" , "Vegetables" , 16 )); array.Add(getDictionary( "North Carolina" , "Rice" , 38 )); array.Add(getDictionary( "North Dakota" , "Grains" , 4 )); array.Add(getDictionary( "Ohio" , "Vegetables" , 25 )); array.Add(getDictionary( "Oklahoma" , "Rice" , 37 )); array.Add(getDictionary( "Oregon" , "Wheat" , 11 )); array.Add(getDictionary( "Pennsylvania" , "Vegetables" , 17 )); array.Add(getDictionary( "Rhode Island" , "Grains" , 19 )); array.Add(getDictionary( "South Carolina" , "Rice" , 45 )); array.Add(getDictionary( "South Dakota" , "Grains" , 5 )); array.Add(getDictionary( "Tennessee" , "Vegetables" , 39 )); array.Add(getDictionary( "Texas" , "Vegetables" , 40 )); array.Add(getDictionary( "Utah" , "Rice" , 23 )); array.Add(getDictionary( "Vermont" , "Grains" , 9 )); array.Add(getDictionary( "Virginia" , "Rice" , 34 )); array.Add(getDictionary( "Washington" , "Vegetables" , 1 )); array.Add(getDictionary( "West Virginia" , "Grains" , 29 )); array.Add(getDictionary( "Wisconsin" , "Grains" , 7 )); array.Add(getDictionary( "Wyoming" , "Wheat" , 6 )); return array; } public void displayToastWithMessage(NSString toastMessage,NSString typeLabel) { UIWindow keyWindow = UIApplication.SharedApplication.KeyWindow; if(toastView!=null) { toastView.RemoveFromSuperview(); } toastView = new UIView (); UILabel label1 = new UILabel (); UILabel label2=new UILabel (); label1.TextColor = label2.TextColor = UIColor.White; label1.Font = UIFont.SystemFontOfSize (16); label1.Text= toastMessage; label2.Text = typeLabel; label2.Font =UIFont.SystemFontOfSize (12); label1.TextAlignment = label2.TextAlignment = UITextAlignment.Center;; toastView.AddSubview (label1); toastView.AddSubview (label2); toastView.Alpha =1; toastView.BackgroundColor = UIColor.Black.ColorWithAlpha (0.7f); toastView.Layer.CornerRadius = 10; CGSize expectedLabelSize1= toastMessage.GetSizeUsingAttributes (new UIStringAttributes() { Font = label1.Font }); CGSize expectedLabelSize2= typeLabel.GetSizeUsingAttributes (new UIStringAttributes() { Font = label2.Font }); keyWindow.AddSubview(toastView); toastView.Frame = new CGRect(0.0f, 0.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width)+20, 45.0f); label1.Frame = new CGRect(0.0f, 5.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width)+15, 15.0f); label2.Frame = new CGRect(0.0f, 25.0f, Math.Max(expectedLabelSize1.Width, expectedLabelSize2.Width)+15, 15.0f); toastView.Center = markerView.Center; UIView.Animate (4, 0, UIViewAnimationOptions.CurveEaseInOut, () => { toastView.Alpha= 0.7f; }, () => { toastView.RemoveFromSuperview(); } ); } NSDictionary getDictionary(string name,string type,int index) { NSString name1= (NSString)name; object[] objects= new object[3]; object[] keys=new object[3]; keys.SetValue ("Country", 0); keys.SetValue ("index", 1); keys.SetValue ("Type", 2); objects.SetValue (name1, 0); objects.SetValue (index, 1); objects.SetValue (type, 2); return NSDictionary.FromObjectsAndKeys (objects, keys); } void SetColorMapping(SFShapeSetting setting) { ObservableCollection<SFMapColorMapping> colorMappings = new ObservableCollection<SFMapColorMapping> (); SFEqualColorMapping colorMapping1= new SFEqualColorMapping(); colorMapping1.Value= (NSString)"Vegetables"; colorMapping1.LegendLabel= (NSString)"Vegetables"; colorMapping1.Color = UIColor.FromRGB (0x29, 0xBB, 0x9C); colorMappings.Add(colorMapping1); SFEqualColorMapping colorMapping2= new SFEqualColorMapping(); colorMapping2.Value=(NSString) "Rice"; colorMapping2.LegendLabel= (NSString)"Rice"; colorMapping2.Color = UIColor.FromRGB (0xFD, 0x8C, 0x48); colorMappings.Add(colorMapping2); SFEqualColorMapping colorMapping3= new SFEqualColorMapping(); colorMapping3.Value=(NSString) "Wheat"; colorMapping3.LegendLabel= (NSString)"Wheat"; colorMapping3.Color =UIColor.FromRGB (0xE5, 0x4D, 0x42); colorMappings.Add(colorMapping3); SFEqualColorMapping colorMapping4= new SFEqualColorMapping(); colorMapping4.Value= (NSString)"Grains"; colorMapping4.LegendLabel= (NSString)"Grains"; colorMapping4.Color =UIColor.FromRGB (0x3A, 0x99, 0xD9); colorMappings.Add(colorMapping4); setting.ColorMappings = colorMappings; } } public class MapsColorMappingDelegate:SFMapsDelegate { public MapsColorMappingDelegate(ColorMapping sample) { mapping= sample; } ColorMapping mapping; public override void DidLoad (SFMap map) { if (mapping.busyindicator != null) { mapping.busyindicator.RemoveFromSuperview (); mapping.busyindicator = null; } } public override void DidSelectShape (SFMap map, NSObject data) { if(data!=null) { NSDictionary dic = (NSDictionary)data; mapping.displayToastWithMessage ((NSString)(dic["Country"] +"\n") ,(NSString)dic["Type"]); } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Diagram/FlowDiagram.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using CoreGraphics; using Syncfusion.SfDiagram.iOS; using UIKit; namespace SampleBrowser { public partial class FlowDiagram : SampleView { SfDiagram diagram; public FlowDiagram() { diagram = new SfDiagram(); } public override void LayoutSubviews() { base.LayoutSubviews(); //Set diagram width and height diagram.Width = (float)Frame.Width; diagram.Height = (float)Frame.Height; diagram.EnableSelectors = false; //Create Node Node n1 = DrawNode(100, 30, 160, 55, ShapeType.RoundedRectangle, "New idea identified", 30, UIColor.FromRGB(49, 162, 255), UIColor.FromRGB(23, 132, 206)); diagram.AddNode(n1); Node n2 = DrawNode(100, 130, 160, 55, ShapeType.RoundedRectangle, "Meeting With Board", 4, UIColor.FromRGB(49, 162, 255), UIColor.FromRGB(23, 132, 206)); diagram.AddNode(n2); Node n3 = DrawNode(105, 230, 150, 150, ShapeType.Diamond, "Board decides \n whether to \n proceed ", 0, UIColor.FromRGB(0, 194, 192), UIColor.FromRGB(4, 142, 135)); diagram.AddNode(n3); Node n4 = DrawNode(105, 425, 150, 150, ShapeType.Diamond, "Find Project \n Manager, write \n specification", 0, UIColor.FromRGB(0, 194, 192), UIColor.FromRGB(4, 142, 135)); diagram.AddNode(n4); Node n5 = DrawNode(90, 620, 180, 60, ShapeType.RoundedRectangle, "Implement and deliver", 30, UIColor.FromRGB(49, 162, 255), UIColor.FromRGB(23, 132, 206)); diagram.AddNode(n5); Node n6 = DrawNode(320, 275, 200, 60, ShapeType.RoundedRectangle, "Reject and report the reason", 4, UIColor.FromRGB(239, 75, 93), UIColor.FromRGB(201, 32, 61)); diagram.AddNode(n6); Node n7 = DrawNode(320, 470, 200, 60, ShapeType.RoundedRectangle, "Hire new resources", 4, UIColor.FromRGB(239, 75, 93), UIColor.FromRGB(201, 32, 61)); diagram.AddNode(n7); //Create Connector Connector c1 = new Connector(n1, n2); diagram.AddConnector(c1); Connector c2 = new Connector(n2, n3); diagram.AddConnector(c2); Connector c3 = new Connector(n3, n4); c3.Annotations.Add(new Annotation() { Content = CreateConnectorLabel("Yes", -25, 10, 25, 20) }); diagram.AddConnector(c3); Connector c4 = new Connector(n4, n5); c4.Annotations.Add(new Annotation() { Content = CreateConnectorLabel("Yes", -25, 10, 25, 20) }); diagram.AddConnector(c4); Connector c5 = new Connector(n3, n6); c5.Annotations.Add(new Annotation() { Content = CreateConnectorLabel("No", 15, 15, 25, 20) }); diagram.AddConnector(c5); Connector c6 = new Connector(n4, n7); c6.Annotations.Add(new Annotation() { Content = CreateConnectorLabel("No", 15, 15, 25, 20) }); diagram.AddConnector(c6); for (int i = 0; i < diagram.Connectors.Count; i++) { diagram.Connectors[i].Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(127, 132, 133)); diagram.Connectors[i].TargetDecoratorStyle.Fill = (UIColor.FromRGB(127, 132, 133)); diagram.Connectors[i].TargetDecoratorStyle.StrokeColor = (UIColor.FromRGB(127, 132, 133)); diagram.Connectors[i].TargetDecoratorStyle.StrokeWidth = 1; diagram.Connectors[i].Style.StrokeWidth = 1; } this.AddSubview(diagram); } //Creates the Node with Specified input private Node DrawNode(float x, float y, float w, float h, ShapeType shape, string annotation, float CornerRadius, UIColor fill, UIColor stroke) { var node = new Node(); node.OffsetX = x; node.OffsetY = y; node.Width = w; node.Height = h; node.ShapeType = shape; node.CornerRadius = CornerRadius; node.Annotations.Add(new Annotation() { Content = CreateNodeLabel(annotation, node.Width, node.Height), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }); node.Style.Brush = new SolidBrush(fill); node.Style.StrokeBrush = new SolidBrush(stroke); node.Style.StrokeWidth = 1; return node; } //Create Node's Annotation UILabel CreateNodeLabel(string text, nfloat width, nfloat height) { var label = new UILabel() { Text = text, TextAlignment = UITextAlignment.Center, TextColor = UIColor.FromRGB(255, 255, 255), Font = UIFont.FromName(".SF UI Text", 14), LineBreakMode = UILineBreakMode.WordWrap, Lines = 0 }; label.Layer.ShouldRasterize = true; label.Layer.RasterizationScale = UIScreen.MainScreen.Scale; label.Frame = new CGRect(0, 0, width, label.Text.StringSize(label.Font).Height * 3); return label; } //Create Connector's Annotationn UILabel CreateConnectorLabel(string text, int x, int y, int w, int h) { var label = new UILabel() { Text = text, TextColor = UIColor.FromRGB(127, 132, 133), Font = UIFont.FromName("Arial", 14), Frame = new CGRect(x, y, w, h) }; label.Layer.RasterizationScale = UIScreen.MainScreen.Scale; label.Layer.ShouldRasterize = true; return label; } } }<file_sep>/Forms/DataGrid/DataGrid.UWP/SaveWindows.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SaveWindows.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser; using SampleBrowser.SfDataGrid.UWP; using Windows.ApplicationModel.Email; using Windows.Storage; using Windows.Storage.Pickers; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; [assembly: Dependency(typeof(SaveWindows))] namespace SampleBrowser.SfDataGrid.UWP { /// <summary> /// A dependency service to save a exported file in UWP /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1400:AccessModifierMustBeDeclared", Justification = "Reviewed.")] class SaveWindows : ISaveWindowsPhone { /// <summary> /// Used to Save a Exporting file in UWP device /// </summary> /// <param name="filename">string type of fileName</param> /// <param name="contentType">string type of contentType</param> /// <param name="stream">string type of stream</param> /// <returns>returns the saved file</returns> public async Task Save(string filename, string contentType, MemoryStream stream) { if (Device.Idiom != TargetIdiom.Desktop) { StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile outFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (Stream outStream = await outFile.OpenStreamForWriteAsync()) { outStream.Write(stream.ToArray(), 0, (int)stream.Length); } if (contentType != "application/html") { await Windows.System.Launcher.LaunchFileAsync(outFile); } } else { StorageFile storageFile = null; FileSavePicker savePicker = new FileSavePicker(); savePicker.SuggestedStartLocation = PickerLocationId.Desktop; savePicker.SuggestedFileName = filename; switch (contentType) { case "application/vnd.openxmlformats-officedocument.presentationml.presentation": savePicker.FileTypeChoices.Add("PowerPoint Presentation", new List<string>() { ".pptx", }); break; case "application/msexcel": savePicker.FileTypeChoices.Add("Excel Files", new List<string>() { ".xlsx", }); break; case "application/msword": savePicker.FileTypeChoices.Add("Word Document", new List<string>() { ".docx" }); break; case "application/pdf": savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string>() { ".pdf" }); break; case "application/html": savePicker.FileTypeChoices.Add("HTML Files", new List<string>() { ".html" }); break; } storageFile = await savePicker.PickSaveFileAsync(); using (Stream outStream = await storageFile.OpenStreamForWriteAsync()) { if (outStream.CanSeek) { outStream.SetLength(0); } outStream.Write(stream.ToArray(), 0, (int)stream.Length); outStream.Flush(); outStream.Dispose(); } stream.Flush(); stream.Dispose(); await Windows.System.Launcher.LaunchFileAsync(storageFile); } } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Schedule/Configuration.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.iOS; using Syncfusion.SfRangeSlider.iOS; using System.Collections.ObjectModel; using Foundation; using UIKit; using CoreGraphics; namespace SampleBrowser { public class Configuration : SampleView { public static SFSchedule schedule = new SFSchedule(); private ScheduleConfigurationViewModel viewModel = new ScheduleConfigurationViewModel(); private string selectedType; private UILabel label_scheduleView, label_workingHours, label_weekNumber, label_showNonAccess, label_blackOutDays; private SfRangeSlider _rangeslider; private UIButton button_scheduleView = new UIButton(); private UIButton doneButton = new UIButton(); private UIPickerView picker_scheduleView; private UISwitch switch_weekNumber, switch_nonAccessbleBlock, switch_blackOutDates; private DayViewSettings daySettings; private WeekViewSettings weekSettings; private WorkWeekViewSettings workWeekSettings; private MonthViewSettings monthSettings; public Configuration() { schedule = new SFSchedule(); schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; //Initializing configuration controls picker_scheduleView = new UIPickerView(); _rangeslider = new SfRangeSlider(); label_scheduleView = new UILabel(); button_scheduleView = new UIButton(); label_workingHours = new UILabel(); label_weekNumber = new UILabel(); label_showNonAccess = new UILabel(); label_blackOutDays = new UILabel(); switch_blackOutDates = new UISwitch(); switch_nonAccessbleBlock = new UISwitch(); switch_weekNumber = new UISwitch(); switch_nonAccessbleBlock.On = true; switch_blackOutDates.On = true; switch_weekNumber.On = true; SetNonWorkingHours(); SetMonthSettings(); schedule.ItemsSource = viewModel.CreateAppointments(); this.AddSubview(schedule); this.OptionView = new UIView(); } protected override void Dispose(bool disposing) { if (disposing) { if (schedule != null) { schedule.Dispose(); schedule = null; } if (OptionView != null) { this.OptionView.RemoveFromSuperview(); this.OptionView.Dispose(); this.OptionView = null; } if (button_scheduleView != null) { button_scheduleView.TouchUpInside -= ShowPicker1; button_scheduleView.Dispose(); button_scheduleView = null; } if (doneButton != null) { doneButton.TouchUpInside -= HidePicker; doneButton.Dispose(); doneButton = null; } if (_rangeslider != null) { _rangeslider.RangeValueChange -= Slider_RangeValueChange; _rangeslider.Dispose(); _rangeslider = null; } } base.Dispose(disposing); } private void SetNonWorkingHours() { daySettings = new DayViewSettings(); weekSettings = new WeekViewSettings(); workWeekSettings = new WorkWeekViewSettings(); //Non-AccessbleBlocks NonAccessibleBlock lunch_hour = new NonAccessibleBlock(); lunch_hour.StartHour = 13; lunch_hour.EndHour = 14; lunch_hour.Text = (NSString)"LUNCH"; daySettings.NonAccessibleBlockCollection = new NSMutableArray(); weekSettings.NonAccessibleBlockCollection = new NSMutableArray(); workWeekSettings.NonAccessibleBlockCollection = new NSMutableArray(); if (switch_nonAccessbleBlock != null && switch_nonAccessbleBlock.On) { daySettings.NonAccessibleBlockCollection.Add(lunch_hour); weekSettings.NonAccessibleBlockCollection.Add(lunch_hour); workWeekSettings.NonAccessibleBlockCollection.Add(lunch_hour); } schedule.DayViewSettings = daySettings; schedule.WeekViewSettings = weekSettings; schedule.WorkWeekViewSettings = workWeekSettings; } private void SetMonthSettings() { monthSettings = new MonthViewSettings(); NSDate today = new NSDate(); NSCalendar calendar = NSCalendar.CurrentCalendar; // Get the year, month, day from the date NSDateComponents components = calendar.Components( NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, today); // Set the hour, minute, second schedule.MonthViewSettings = monthSettings; monthSettings.BlackoutDates = new NSMutableArray(); if (switch_blackOutDates != null && switch_blackOutDates.On) { components.Day -= 3; for (int i = 0; i < 3; i++) { NSDate startDate = calendar.DateFromComponents(components); components.Day += 1; schedule.MonthViewSettings.BlackoutDates.Add(startDate); } } if (switch_weekNumber != null && switch_weekNumber.On) { schedule.MonthViewSettings.ShowWeekNumber = true; } else { schedule.MonthViewSettings.ShowWeekNumber = false; } } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } this.CreateOptionView(); base.LayoutSubviews(); } private readonly IList<string> _scheduleViewsCollection = new List<string> { "DayView", "WeekView", "WorkWeekView", "MonthView" }; private void Slider_RangeValueChange(object sender, RangeEventArgs e) { schedule.DayViewSettings.WorkStartHour = (int)e.RangeStart; schedule.DayViewSettings.WorkEndHour = (int)e.RangeEnd; schedule.WeekViewSettings.WorkStartHour = (int)e.RangeStart; schedule.WeekViewSettings.WorkEndHour = (int)e.RangeEnd; schedule.WorkWeekViewSettings.WorkStartHour = (int)e.RangeStart; schedule.WorkWeekViewSettings.WorkEndHour = (int)e.RangeEnd; } private void CreateOptionView() { //Schedule View Localization.SchedulePickerModel model = new Localization.SchedulePickerModel(_scheduleViewsCollection); picker_scheduleView.Model = model; label_scheduleView.Text = "Select the Schedule Type"; label_scheduleView.TextColor = UIColor.Black; label_scheduleView.TextAlignment = UITextAlignment.Left; button_scheduleView.SetTitle("WeekView", UIControlState.Normal); button_scheduleView.SetTitleColor(UIColor.Black, UIControlState.Normal); button_scheduleView.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; button_scheduleView.Layer.CornerRadius = 8; button_scheduleView.Layer.BorderWidth = 2; button_scheduleView.TouchUpInside += ShowPicker1; button_scheduleView.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(246, 246, 246); model.PickerChanged += Model_PickerChanged; picker_scheduleView.ShowSelectionIndicator = true; picker_scheduleView.Hidden = true; //working Hours label_workingHours.Text = "Working Hours "; label_workingHours.TextColor = UIColor.Black; label_workingHours.TextAlignment = UITextAlignment.Left; _rangeslider.Maximum = 24; _rangeslider.Minimum = 0; _rangeslider.RangeStart = (nfloat)schedule.WeekViewSettings.WorkStartHour; _rangeslider.RangeEnd = (nfloat)schedule.WeekViewSettings.WorkEndHour; _rangeslider.ShowRange = true; _rangeslider.ShowValueLabel = false; _rangeslider.SnapsTo = SFSnapsTo.SFSnapsToNone; _rangeslider.TickPlacement = SFTickPlacement.SFTickPlacementNone; _rangeslider.LabelColor = UIColor.Gray; _rangeslider.TickFrequency = 2; _rangeslider.ToolTipPlacement = SFToolTipPlacement.SFToolTipPlacementTopLeft; _rangeslider.KnobColor = UIColor.White; _rangeslider.RangeValueChange += Slider_RangeValueChange; // show week number label_weekNumber.Text = "Show Week number "; label_weekNumber.TextColor = UIColor.Black; label_weekNumber.TextAlignment = UITextAlignment.Left; switch_weekNumber.ValueChanged += (object sender, EventArgs e) => { SetMonthSettings(); }; //show non acceesible block label_showNonAccess.Text = "Show Non AccessibleBlocks "; label_showNonAccess.TextColor = UIColor.Black; label_showNonAccess.TextAlignment = UITextAlignment.Left; switch_nonAccessbleBlock.ValueChanged += (object sender, EventArgs e) => { SetNonWorkingHours(); }; //show black out dates label_blackOutDays.Text = "Show Blackout dates "; label_blackOutDays.TextColor = UIColor.Black; label_blackOutDays.TextAlignment = UITextAlignment.Left; switch_blackOutDates.On = true; switch_blackOutDates.ValueChanged += (object sender, EventArgs e) => { SetMonthSettings(); }; string deviceType = UIDevice.CurrentDevice.Model; if (deviceType == "iPhone" || deviceType == "iPod touch") { label_workingHours.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y - 70, this.Frame.Size.Width - 20, 30); _rangeslider.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y - 40, this.Frame.Size.Width - 20, 30); switch_weekNumber.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y, this.Frame.Size.Width / 9, 30); label_weekNumber.Frame = new CGRect(this.Frame.Size.Width / 9 + 30, this.Frame.Y, this.Frame.Size.Width - 20, 30); //switch_weekNumber switch_nonAccessbleBlock.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 40, this.Frame.Size.Width / 9, 30); label_showNonAccess.Frame = new CGRect(this.Frame.Size.Width / 9 + 30, this.Frame.Y + 40, this.Frame.Size.Width - 20, 30); //switch_nonAccessbleBlock switch_blackOutDates.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 80, this.Frame.Size.Width / 9, 30); label_blackOutDays.Frame = new CGRect(this.Frame.Size.Width / 9 + 30, this.Frame.Y + 80, this.Frame.Size.Width - 20, 30); //label_blackOutDays label_scheduleView.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 120, this.Frame.Size.Width - 20, 30); button_scheduleView.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 150, this.Frame.Size.Width - 20, 30); doneButton.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 180, this.Frame.Size.Width - 20, 30); picker_scheduleView.Frame = new CGRect(this.Frame.X + 10, this.Frame.Y + 170, this.Frame.Size.Width - 20, 150); } //settings frame size for sub views else { schedule.DayViewSettings.WorkStartHour = 7; schedule.DayViewSettings.WorkEndHour = 18; schedule.WeekViewSettings.WorkStartHour = 7; schedule.WeekViewSettings.WorkEndHour = 18; schedule.WorkWeekViewSettings.WorkStartHour = 7; schedule.WorkWeekViewSettings.WorkEndHour = 18; label_workingHours.Frame = new CGRect(10, 10, 320, 20); _rangeslider.Frame = new CGRect(0, 30, 320, 30); switch_weekNumber.Frame = new CGRect(10, 60, 30, 30); label_weekNumber.Frame = new CGRect(80, 60, 320, 30); //switch_weekNumber switch_nonAccessbleBlock.Frame = new CGRect(10, 100, 30, 30); label_showNonAccess.Frame = new CGRect(80, 100, 320, 30); //switch_nonAccessbleBlock switch_blackOutDates.Frame = new CGRect(10, 140, 30, 30); label_blackOutDays.Frame = new CGRect(80, 140, 320, 30); //label_blackOutDays label_scheduleView.Frame = new CGRect(10, 180, 320, 20); button_scheduleView.Frame = new CGRect(0, 210, 320, 30); doneButton.Frame = new CGRect(0, 250, 320, 30); picker_scheduleView.Frame = new CGRect(0, 270, 320, 100); } this.OptionView.AddSubview(label_workingHours); this.OptionView.AddSubview(_rangeslider); this.OptionView.AddSubview(label_weekNumber); this.OptionView.AddSubview(switch_weekNumber); this.OptionView.AddSubview(label_showNonAccess); this.OptionView.AddSubview(switch_nonAccessbleBlock); this.OptionView.AddSubview(label_blackOutDays); this.OptionView.AddSubview(switch_blackOutDates); this.OptionView.AddSubview(label_scheduleView); this.OptionView.AddSubview(button_scheduleView); this.OptionView.AddSubview(picker_scheduleView); this.OptionView.AddSubview(doneButton); } private void Model_PickerChanged(object sender, Localization.SchedulePickerChangedEventArgs e) { this.selectedType = e.SelectedValue; if (selectedType == "WeekView") { schedule.ScheduleView = SFScheduleView.SFScheduleViewWeek; } else if (selectedType == "DayView") { schedule.ScheduleView = SFScheduleView.SFScheduleViewDay; } else if (selectedType == "WorkWeekView") { schedule.ScheduleView = SFScheduleView.SFScheduleViewWorkWeek; } else { schedule.ScheduleView = SFScheduleView.SFScheduleViewMonth; } button_scheduleView.SetTitle(selectedType.ToString(), UIControlState.Normal); } private void ShowPicker1(object sender, EventArgs e) { doneButton.Hidden = false; picker_scheduleView.Hidden = false; button_scheduleView.Hidden = false; label_scheduleView.Hidden = false; label_workingHours.Hidden = false; } private void HidePicker(object sender, EventArgs e) { doneButton.Hidden = true; picker_scheduleView.Hidden = true; button_scheduleView.Hidden = false; label_scheduleView.Hidden = false; label_workingHours.Hidden = false; } } } <file_sep>/Forms/DataForm/DataForm/Samples/DynamicFormPage/Model/Ecommerce.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.XForms.DataForm; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Text; using Xamarin.Forms.Internals; using System.ComponentModel.DataAnnotations; namespace SampleBrowser.SfDataForm { /// <summary> /// Represents the Ecommerce information of the data form dynamicforms sample. /// </summary> [Preserve(AllMembers = true)] public class Ecommerce: INotifyPropertyChanged { #region Fields /// <summary> /// Represents the full name of the ecommerce information. /// </summary> private string fullname; /// <summary> /// Represents the card number of the ecommerce information. /// </summary> private string cardNumber; /// <summary> /// Represents the ccv of the ecommerce information. /// </summary> private string ccv; /// <summary> /// Represents the expiration date of the ecommerce information. /// </summary> private string expirationDate; /// <summary> /// Represents the first address line of the ecommerce information. /// </summary> private string addressline1; /// <summary> /// Represents the second address line of the ecommerce information. /// </summary> private string addressline2; /// <summary> /// Represents the city of the ecommerce information. /// </summary> private string city; /// <summary> /// Represents the state of the ecommerce information. /// </summary> private string state; /// <summary> /// Represents the country of the ecommerce information. /// </summary> private string ecommerceCountry; /// <summary> /// Represents the zip code of the ecommerce information. /// </summary> private string zipCode; /// <summary> /// Represents the comment of the ecommerce information. /// </summary> private string comment; #endregion public Ecommerce() { } /// <summary> /// Represents the method that will handle when a property is changed on a component. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #region Public Properties /// <summary> /// Gets or sets the full name field. /// </summary> [DisplayOptions(ColumnSpan = 4)] [Display(ShortName = "Full Name")] public string FullName { get { return this.fullname; } set { this.fullname = value; this.RaisePropertyChanged("FullName"); } } /// <summary> /// Gets or sets the card number field. /// </summary> [DisplayOptions(ColumnSpan = 3)] [Display(ShortName = "Card Number")] [Required(AllowEmptyStrings = false, ErrorMessage = "Card number should not be empty")] [StringLength(19, ErrorMessage = "Card number should not exceed 16 digits")] [DataType(DataType.PhoneNumber)] public string CardNumber { get { return this.cardNumber; } set { this.cardNumber = value; this.RaisePropertyChanged("CardNumber"); } } /// <summary> /// Gets or sets the ccv field. /// </summary> [DisplayOptions(ColumnSpan = 1)] [DataType(DataType.PhoneNumber)] public string CCV { get { return this.ccv; } set { this.ccv = value; this.RaisePropertyChanged("CCV"); } } /// <summary> /// Gets or sets the expiration date field. /// </summary> [DisplayOptions(ColumnSpan = 4)] [DataType(DataType.PhoneNumber)] [Display(ShortName = "Expiration Date")] public string ExpirationDate { get { return this.expirationDate; } set { this.expirationDate = value; this.RaisePropertyChanged("ExpirationDate"); } } /// <summary> /// Gets or sets the first address line field. /// </summary> [DisplayOptions(ColumnSpan = 4)] [Display(ShortName = "Address Line 1")] [DataType(DataType.MultilineText)] public string Addressline1 { get { return this.addressline1; } set { this.addressline1 = value; this.RaisePropertyChanged("Addressline1"); } } /// <summary> /// Gets or sets the second address line field. /// </summary> [DisplayOptions(ColumnSpan = 4)] [Display(ShortName = "Address Line 2")] [DataType(DataType.MultilineText)] public string Addressline2 { get { return this.addressline2; } set { this.addressline2 = value; this.RaisePropertyChanged("Addressline2"); } } /// <summary> /// Gets or sets the city field. /// </summary> [DisplayOptions(ColumnSpan = 4)] [Display(ShortName = "City")] public string EcommerceCity { get { return this.city; } set { this.city = value; this.RaisePropertyChanged("EcommerceCity"); } } /// <summary> /// Gets or sets the state field. /// </summary> [DisplayOptions(ColumnSpan = 4)] public string State { get { return this.state; } set { this.state = value; this.RaisePropertyChanged("State"); } } /// <summary> /// Gets or sets the country field. /// </summary> [DisplayOptions(ColumnSpan = 2)] [Display(ShortName = "Country")] public string EcommerceCountry { get { return this.ecommerceCountry; } set { this.ecommerceCountry = value; this.RaisePropertyChanged("EcommerceCountry"); } } /// <summary> /// Gets or sets the zip code field. /// </summary> [DisplayOptions(ColumnSpan = 2)] [DataType(DataType.PhoneNumber)] [Display(ShortName = "Zip code")] public string ZipCode { get { return this.zipCode; } set { this.zipCode = value; this.RaisePropertyChanged("ZipCode"); } } /// <summary> /// Gets or sets the comment field. /// </summary> [DisplayOptions(ColumnSpan = 4)] [DataType(DataType.MultilineText)] public string Comment { get { return this.comment; } set { this.comment = value; this.RaisePropertyChanged("Comment"); } } #endregion /// <summary> /// Occurs when propery value is changed. /// </summary> /// <param name="propName">Property name</param> private void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } <file_sep>/Forms/Border/Border/Samples/Customization/Customization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SampleBrowser.SfBorder { public partial class Customization : SampleView { double oldHeight = 0; double oldWidth = 0; public Customization() { InitializeComponent(); } /// <summary> /// Handles the orientation changed. /// </summary> /// <param name="width"></param> /// <param name="height"></param> protected override void OnSizeAllocated(double width, double height) { base.OnSizeAllocated(width, height); if ((Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS) && Device.Idiom == TargetIdiom.Phone) { if (width > height && oldWidth != width && oldHeight != height) { innserPart.IsVisible = false; labelPart.IsVisible = false; innerRow.Height = 50; topRow.Height = 60; topBorder.HeightRequest = 60; topBorder.WidthRequest = 60; topBorder.CornerRadius = 30; topBorder.Margin = new Thickness(0, 35, 0, 0); topLabel.FontSize = 15; numberPart.FontSize = 15; followLabel.FontSize = 8; number_part.FontSize = 15; followersLabel.FontSize = 8; } else { innserPart.IsVisible = true; labelPart.IsVisible = true; innerRow.Height = 170; topRow.Height = 120; topBorder.HeightRequest = 100; topBorder.WidthRequest = 100; topBorder.CornerRadius = 50; topBorder.Margin = new Thickness(0, 70, 0, 0); topLabel.FontSize = 20; numberPart.FontSize = 18; followLabel.FontSize = 11; number_part.FontSize = 18; followersLabel.FontSize = 11; } oldHeight = height; oldWidth = width; } } } } <file_sep>/Android/SampleBrowser/Samples/DocIO/CustomStyle.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; namespace SampleBrowser { public partial class CustomStyle : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to format the Word document contents with user defined styles."; text1.SetPadding(5, 5, 5, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } void OnButtonClicked(object sender, EventArgs e) { WordDocument document = new WordDocument(); IWParagraphStyle style = null; // Adding a new section to the document. WSection section = document.AddSection() as WSection; //Set Margin of the section section.PageSetup.Margins.All = 72; IWParagraph par = document.LastSection.AddParagraph(); WTextRange range = par.AppendText("Using CustomStyles") as WTextRange; range.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red; range.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; range.CharacterFormat.FontSize = 18f; document.LastParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; // Create Paragraph styles style = document.AddParagraphStyle("MyStyle_Normal"); style.CharacterFormat.FontName = "Bitstream Vera Serif"; style.CharacterFormat.FontSize = 10f; style.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify; style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(0, 21, 84); style = document.AddParagraphStyle("MyStyle_Low"); style.CharacterFormat.FontName = "Times New Roman"; style.CharacterFormat.FontSize = 16f; style.CharacterFormat.Bold = true; style = document.AddParagraphStyle("MyStyle_Medium"); style.CharacterFormat.FontName = "Monotype Corsiva"; style.CharacterFormat.FontSize = 18f; style.CharacterFormat.Bold = true; style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(51, 66, 125); style = document.AddParagraphStyle("Mystyle_High"); style.CharacterFormat.FontName = "Bitstream Vera Serif"; style.CharacterFormat.FontSize = 20f; style.CharacterFormat.Bold = true; style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(242, 151, 50); IWParagraph paragraph = null; for (int i = 1; i < document.Styles.Count; i++) { //Skip to apply the document default styles and also paragraph style. if(document.Styles[i].Name=="Normal"||document.Styles[i].Name=="Default Paragraph Font"||document.Styles[i].StyleType!=StyleType.ParagraphStyle) continue; // Getting styles from Document. style = (IWParagraphStyle)document.Styles[i]; // Adding a new paragraph section.AddParagraph(); paragraph = section.AddParagraph(); // Applying styles to the current paragraph. paragraph.ApplyStyle(style.Name); // Writing Text with the current style and formatting. paragraph.AppendText("Northwind Database with [" + style.Name + "] Style"); // Adding a new paragraph section.AddParagraph(); paragraph = section.AddParagraph(); // Applying another style to the current paragraph. paragraph.ApplyStyle("MyStyle_Normal"); // Writing text with current style. paragraph.AppendText("The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases. Using Northwind, you can become familiar with how a relational database is structured and how the database objects work together to help you enter, store, manipulate, and print your data."); } #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if(stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("CustomStyle.docx", "application/msword", stream, m_context); } #endregion } } } <file_sep>/Forms/Schedule/Schedule/Samples/AppointmentEditor/Behaviors/AppointmentEditorBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; namespace SampleBrowser.SfSchedule { /// <summary> /// Appointment Editor Behavior class. /// </summary> internal class AppointmentEditorBehavior : Behavior<SampleView> { #region Fields /// <summary> /// schedule view list. /// </summary> private ListView scheduleViewList; /// <summary> /// header label. /// </summary> private Label header; /// <summary> /// schedule view button. /// </summary> private Button scheduleViewButton; /// <summary> /// Schedule header grid. /// </summary> private Grid scheduleHeaderGrid; /// <summary> /// editor button. /// </summary> private Button editorButton; /// <summary> /// editor layout. /// </summary> private EditorLayout editorLayout; /// <summary> /// time zone picker. /// </summary> private Picker timeZonePicker; /// <summary> /// appointment index. /// </summary> private int indexOfAppointment = 0; /// <summary> /// new appointment. /// </summary> private bool isNewAppointment = false; /// <summary> /// Gets or sets schedule. /// </summary> private Syncfusion.SfSchedule.XForms.SfSchedule schedule { get; set; } #endregion #region OnAttached /// <summary> /// Begins when the behavior attached to the view. /// </summary> /// <param name="bindable">bindable value</param> protected override void OnAttachedTo(SampleView bindable) { this.scheduleHeaderGrid = ((bindable.Content as Grid).Children[0] as Grid); this.scheduleViewButton = ((bindable.Content as Grid).Children[0] as Grid).Children[0] as Button; this.header = ((bindable.Content as Grid).Children[0] as Grid).Children[1] as Label; this.editorButton = ((bindable.Content as Grid).Children[0] as Grid).Children[2] as Button; this.schedule = (bindable.Content as Grid).Children[1] as Syncfusion.SfSchedule.XForms.SfSchedule; this.scheduleViewList = (bindable.Content as Grid).Children[2] as ListView; this.editorLayout = (bindable.Content as Grid).Children[3] as EditorLayout; this.timeZonePicker = bindable.FindByName<Picker>("timeZonePicker"); this.timeZonePicker.ItemsSource = TimeZoneCollection.TimeZoneList; this.timeZonePicker.SelectedIndex = 0; this.timeZonePicker.SelectedIndexChanged += this.TimeZonePicker_SelectedIndexChanged; this.schedule.VisibleDatesChangedEvent += this.Schedule_VisibleDatesChangedEvent; this.schedule.MonthInlineAppointmentTapped += this.Schedule_MonthInlineAppointmentTapped; this.schedule.CellDoubleTapped += this.Schedule_CellDoubleTapped; this.schedule.CellTapped += this.Schedule_CellTapped; if (Device.RuntimePlatform == Device.Android) { this.schedule.ViewHeaderStyle.DateFontSize = 24; } this.scheduleViewList.ItemSelected += this.ScheduleViewList_ItemSelected; this.scheduleViewButton.Clicked += this.ScheduleViewButton_Clicked; this.editorButton.Clicked += this.EditorButton_Clicked; (this.editorLayout.BindingContext as EditorLayoutViewModel).AppointmentModified += this.EditorLayout_AppointmentModified; (this.editorLayout.Behaviors[0] as EditorLayoutBehavior).AddEditorElements(); if (Device.RuntimePlatform == "Android") { this.scheduleHeaderGrid.ColumnDefinitions[0].Width = new GridLength(0.1, GridUnitType.Star); this.header.FontSize = 20; } } #endregion #region OnDetachingFrom /// <summary> /// Begins when the behavior attached to the view /// </summary> /// <param name="bindable">bindable param</param> protected override void OnDetachingFrom(SampleView bindable) { this.schedule.VisibleDatesChangedEvent -= this.Schedule_VisibleDatesChangedEvent; this.schedule.MonthInlineAppointmentTapped -= this.Schedule_MonthInlineAppointmentTapped; this.schedule.CellDoubleTapped -= this.Schedule_CellDoubleTapped; this.schedule.CellTapped -= this.Schedule_CellTapped; this.scheduleViewList.ItemSelected -= this.ScheduleViewList_ItemSelected; this.scheduleViewButton.Clicked -= this.ScheduleViewButton_Clicked; this.editorButton.Clicked -= this.EditorButton_Clicked; (this.editorLayout.BindingContext as EditorLayoutViewModel).AppointmentModified -= this.EditorLayout_AppointmentModified; this.scheduleHeaderGrid = null; this.scheduleViewButton = null; this.header = null; this.editorButton = null; this.schedule = null; this.scheduleViewList = null; this.editorLayout = null; } #endregion #region EditorLayout_AppointmentModified /// <summary> /// editor layout /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Schedule Appointment Modified Event args</param> private void EditorLayout_AppointmentModified(object sender, ScheduleAppointmentModifiedEventArgs e) { this.editorLayout.IsVisible = false; if (e.IsModified) { if (this.isNewAppointment) { (this.schedule.DataSource as ObservableCollection<Meeting>).Add(e.Appointment); } else { (this.schedule.DataSource as ObservableCollection<Meeting>).RemoveAt(this.indexOfAppointment); (this.schedule.DataSource as ObservableCollection<Meeting>).Insert(this.indexOfAppointment, e.Appointment); } } } #endregion #region EditorButton_Clicked /// <summary> /// Method for editor button. /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void EditorButton_Clicked(object sender, EventArgs e) { this.scheduleViewList.IsVisible = false; this.editorLayout.IsVisible = true; (this.editorLayout.Behaviors[0] as EditorLayoutBehavior).OpenEditor(null, DateTime.Today); this.isNewAppointment = true; } #endregion #region ScheduleViewButton_Clicked /// <summary> /// Method for schedule view visible. /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void ScheduleViewButton_Clicked(object sender, EventArgs e) { if (this.scheduleViewList.IsVisible) { this.scheduleViewList.IsVisible = false; } else { this.scheduleViewList.IsVisible = true; } } #endregion #region TimeZone Picker_Selected /// <summary> /// Method for selecting time zone /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void TimeZonePicker_SelectedIndexChanged(object sender, EventArgs e) { if ((sender as Picker).SelectedItem as string == "Default") { this.schedule.TimeZone = string.Empty; } else { this.schedule.TimeZone = (sender as Picker).SelectedItem as string; } } #endregion #region ListItemSelected /// <summary> /// Method for selecting schedule view /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Event Args</param> private void ScheduleViewList_ItemSelected(object sender, SelectedItemChangedEventArgs e) { if (e.SelectedItem is ScheduleTypeClass) { if ((e.SelectedItem as ScheduleTypeClass).ScheduleType.Equals("Day view")) { this.schedule.ScheduleView = ScheduleView.DayView; } else if ((e.SelectedItem as ScheduleTypeClass).ScheduleType.Equals("Week view")) { this.schedule.ScheduleView = ScheduleView.WeekView; } else if ((e.SelectedItem as ScheduleTypeClass).ScheduleType.Equals("Work week view")) { this.schedule.ScheduleView = ScheduleView.WorkWeekView; } else if ((e.SelectedItem as ScheduleTypeClass).ScheduleType.Equals("Month view")) { this.schedule.ScheduleView = ScheduleView.MonthView; } else if((e.SelectedItem as ScheduleTypeClass).ScheduleType.Equals("Timeline view")) { this.schedule.ScheduleView = ScheduleView.TimelineView; } this.schedule.SelectionStyle = new Syncfusion.SfSchedule.XForms.SelectionStyle(); } (sender as ListView).IsVisible = false; } #endregion #region CellTapped /// <summary> /// Method for schedule cell tapped /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Cell Tapped Event Args</param> private void Schedule_CellTapped(object sender, CellTappedEventArgs e) { this.scheduleViewList.IsVisible = false; } #endregion #region CellDoubleTapped /// <summary> /// Method for cell double tapped /// </summary> /// <param name="sender">return the object</param> /// <param name="args">cell tapped event args</param> private void Schedule_CellDoubleTapped(object sender, Syncfusion.SfSchedule.XForms.CellTappedEventArgs args) { this.scheduleViewList.IsVisible = false; this.editorLayout.IsVisible = true; if (this.schedule.ScheduleView == ScheduleView.MonthView) { //create Apppointment (this.editorLayout.Behaviors[0] as EditorLayoutBehavior).OpenEditor(null, args.Datetime); this.isNewAppointment = true; } else { if (args.Appointment != null) { ObservableCollection<Meeting> appointment = new ObservableCollection<Meeting>(); appointment = (ObservableCollection<Meeting>)this.schedule.DataSource; this.indexOfAppointment = appointment.IndexOf((Meeting)args.Appointment); (this.editorLayout.Behaviors[0] as EditorLayoutBehavior).OpenEditor((Meeting)args.Appointment, args.Datetime); this.isNewAppointment = false; } else { //create Apppointment (this.editorLayout.Behaviors[0] as EditorLayoutBehavior).OpenEditor(null, args.Datetime); this.isNewAppointment = true; } } } #endregion #region MonthInlineAppointmentTapped /// <summary> /// Method for schedule inline tapped. /// </summary> /// <param name="sender">return the object</param> /// <param name="e">Month Inline Appointment Tapped Event Args</param> private void Schedule_MonthInlineAppointmentTapped(object sender, Syncfusion.SfSchedule.XForms.MonthInlineAppointmentTappedEventArgs e) { if (e.Appointment != null) { this.editorLayout.IsVisible = true; ObservableCollection<Meeting> appointment = new ObservableCollection<Meeting>(); appointment = (ObservableCollection<Meeting>)this.schedule.DataSource; this.indexOfAppointment = appointment.IndexOf((Meeting)e.Appointment); (this.editorLayout.Behaviors[0] as EditorLayoutBehavior).OpenEditor((Meeting)e.Appointment, e.selectedDate); this.isNewAppointment = false; } } #endregion #region VisibleDateChanged Event /// <summary> /// Method for visible dates changed. /// </summary> /// <param name="sender">sender</param> /// <param name="args">visible dates args</param> private void Schedule_VisibleDatesChangedEvent(object sender, Syncfusion.SfSchedule.XForms.VisibleDatesChangedEventArgs args) { this.scheduleViewList.IsVisible = false; if (this.schedule.ScheduleView == Syncfusion.SfSchedule.XForms.ScheduleView.DayView) { if (Device.RuntimePlatform == "UWP" && Device.Idiom == TargetIdiom.Phone) { this.header.Text = args.visibleDates[0].Date.ToString("dd MMMM yyyy"); } else { this.header.Text = args.visibleDates[0].Date.ToString("MMMM yyyy"); } } else { this.header.Text = args.visibleDates[args.visibleDates.Count / 2].Date.ToString("MMMM yyyy"); } } #endregion } } <file_sep>/Android/SampleBrowser/Samples/PDF/DigitalSignatureValidation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Java.IO; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.IO; using Syncfusion.Pdf.Parsing; using System.Threading.Tasks; using Syncfusion.Pdf; using System.Reflection; using Syncfusion.Pdf.Security; using Syncfusion.Drawing; using System.Security.Cryptography.X509Certificates; namespace SampleBrowser { public partial class DigitalSignatureValidation : SamplePage { private Context m_context; TextView resultView; public override View GetSampleContent(Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView space = new TextView(con); space.TextSize = 10; linear.AddView(space); TextView text2 = new TextView(con); text2.TextSize = 17; text2.TextAlignment = TextAlignment.Center; text2.Text = "This sample illustrates how to validate the digitally signed PDF document signature."; text2.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text2.SetPadding(5, 5, 5, 5); linear.AddView(text2); TextView space1 = new TextView(con); space1.TextSize = 10; linear.AddView(space1); m_context = con; TextView space2 = new TextView(con); space2.TextSize = 10; linear.AddView(space2); Button button1 = new Button(con); button1.Text = "Validate Signature"; button1.Click += OnButtonClicked; linear.AddView(button1); resultView = new TextView(con); resultView.TextSize = 17; resultView.TextAlignment = TextAlignment.Center; resultView.Text = ""; resultView.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); resultView.SetPadding(5, 5, 5, 5); linear.AddView(resultView); return linear; } void OnButtonClicked(object sender, EventArgs e) { StringBuilder builder = new StringBuilder(); //Get the stream from the document. Stream docStream = typeof(DigitalSignatureValidation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.SignedDocument.pdf"); //Load the PDF document into the loaded document object. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream); //Get signature field PdfLoadedSignatureField lSigFld = loadedDocument.Form.Fields[0] as PdfLoadedSignatureField; //Get the certificate stream from .pfx file. Stream certificateStream = typeof(DigitalSignatureValidation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.PDF.pfx"); byte[] data = new byte[certificateStream.Length]; certificateStream.Read(data, 0, data.Length); //Create new X509Certificate2 with the root certificate X509Certificate2 certificate = new X509Certificate2(data, "<PASSWORD>"); //X509Certificate2Collection to check the signer's identity using root certificates X509CertificateCollection collection = new X509CertificateCollection(); //Add the certificate to the collection collection.Add(certificate); //Validate signature and get the validation result PdfSignatureValidationResult result = lSigFld.ValidateSignature(collection); builder.AppendLine("Signature is " + result.SignatureStatus); builder.AppendLine(); builder.AppendLine("--------Validation Summary--------"); builder.AppendLine(); //Checks whether the document is modified or not bool isModified = result.IsDocumentModified; if (isModified) builder.AppendLine("The document has been altered or corrupted since the signature was applied."); else builder.AppendLine("The document has not been modified since the signature was applied."); //Signature details builder.AppendLine("Digitally signed by " + lSigFld.Signature.Certificate.IssuerName); builder.AppendLine("Valid From : " + lSigFld.Signature.Certificate.ValidFrom); builder.AppendLine("Valid To : " + lSigFld.Signature.Certificate.ValidTo); builder.AppendLine("Signature Algorithm : " + result.SignatureAlgorithm); builder.AppendLine("Hash Algorithm : " + result.DigestAlgorithm); //Revocation validation details builder.AppendLine("OCSP revocation status : " + result.RevocationResult.OcspRevocationStatus); if (result.RevocationResult.OcspRevocationStatus == RevocationStatus.None && result.RevocationResult.IsRevokedCRL) builder.AppendLine("CRL is revoked."); this.resultView.Text = builder.ToString(); //Close the document loadedDocument.Close(true); } } }<file_sep>/Forms/Chat/Chat.Android/SplashScreenActivity.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SplashScreenActivity.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfChat.Droid { using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; [Activity(Theme = "@style/Theme.Splash", MainLauncher = true, NoHistory = true, Icon = "@drawable/AppIcon")] /// <summary> /// The initial activity of the application. /// </summary> public class SplashScreenActivity : SampleBrowser.Core.Android.SplashScreenActivity { /// <summary> /// Gets the type of MainActivity /// </summary> /// <returns>MainActivity type</returns> protected override Type GetMainActivityType() { return typeof(MainActivity); } } }<file_sep>/Forms/Rating/Rating/Samples/Rating_Customization/Rating_Customization.xaml.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Syncfusion.SfRating.XForms; using Xamarin.Forms; using SampleBrowser.Core; namespace SampleBrowser.SfRating { public partial class Rating_Customization : SampleView { List<int> Votes = new List<int>(); bool isVoted = false; public List<Label> RatingLabel = new List<Label>(); int angryCount = 1, unHappyCount = 2, neutralCount = 2, happyCount = 1, excitedCount = 4; public Rating_Customization() { InitializeComponent(); if (Device.RuntimePlatform == Device.Android) { rating.ItemSize = 55; rating.ItemSpacing = 5; description.FontSize = 12; mButton.HeightRequest = 40; bottomStack.Margin = new Thickness(0, 5, 0, 0); } else if (Device.RuntimePlatform == Device.iOS) { rating.ItemSize = 50; bottomStack.Padding=new Thickness(0,0,0,0); rating.HeightRequest=50; } Votes.Add(1); Votes.Add(2); Votes.Add(2); Votes.Add(3); Votes.Add(4); Votes.Add(3); Votes.Add(5); Votes.Add(5); Votes.Add(5); Votes.Add(5); rating.ValueChanged += Rating_ValueChanged; ObservableCollection<SfRatingItem> customItems = new ObservableCollection<SfRatingItem>(); customItems.Add(new SfRatingItem() { SelectedView = new CustomRatingView("AngrySelected.png", "10%", "Angry", this), UnSelectedView = new CustomRatingView("AngryUnselected.png", "10%", "Angry", this) }); customItems.Add(new SfRatingItem() { SelectedView = new CustomRatingView("UnhappySelected.png", "20%", "Unhappy", this), UnSelectedView = new CustomRatingView("UnhappyUnselected.png", "20%", "Unhappy", this) }); customItems.Add(new SfRatingItem() { SelectedView = new CustomRatingView("NeutralSelected.png", "20%", "Neutral", this), UnSelectedView = new CustomRatingView("NeutralUnselected.png", "20%", "Neutral", this) }); customItems.Add(new SfRatingItem() { SelectedView = new CustomRatingView("HappySelected.png", "10%", "Happy", this), UnSelectedView = new CustomRatingView("HappyUnselected.png", "10%", "Happy", this) }); customItems.Add(new SfRatingItem() { SelectedView = new CustomRatingView("ExcitedSelected.png", "40%", "Excited", this), UnSelectedView = new CustomRatingView("ExcitedUnselected.png", "40%", "Excited", this) }); rating.Items = customItems; //headLineText.Text = "Linda, USA Sports . Wednesday ," + DateTime.Now.ToString("M") + ", " + DateTime.Now.Year.ToString(); if (Device.RuntimePlatform == Device.UWP) { rating.ItemSize = 55; rating.ItemSpacing = 5; //countButton.BackgroundColor = Color.FromHex("#FF5500"); //maincontent.Height = 180; } if(Device.RuntimePlatform == Device.UWP && Device.Idiom == TargetIdiom.Phone) { description.FontSize = 11; // maincontent.Height = 100; } mButton.BackgroundColor = Color.White; mButton.TextColor = Color.Black; } void Rating_ValueChanged(object sender, ValueEventArgs e) { if (!isVoted) { Votes.Add((int)e.Value); isVoted = true; if ((int)e.Value == 1) angryCount += 1; else if ((int)e.Value == 2) unHappyCount += 1; else if ((int)e.Value == 3) neutralCount += 1; else if ((int)e.Value == 4) happyCount += 1; else if ((int)e.Value == 5) excitedCount += 1; } else { if (Votes[Votes.Count - 1] == 1) angryCount -= 1; else if (Votes[Votes.Count - 1] == 2) unHappyCount -= 1; else if (Votes[Votes.Count - 1] == 3) neutralCount -= 1; else if (Votes[Votes.Count - 1] == 4) happyCount -= 1; else if (Votes[Votes.Count - 1] == 5) excitedCount -= 1; Votes.RemoveAt(Votes.Count - 1); Votes.Add((int)e.Value); if ((int)e.Value == 1) angryCount += 1; else if ((int)e.Value == 2) unHappyCount += 1; else if ((int)e.Value == 3) neutralCount += 1; else if ((int)e.Value == 4) happyCount += 1; else if ((int)e.Value == 5) excitedCount += 1; } } void Handle_Clicked(object sender, System.EventArgs e) { if (this.rating.Value != 0) { for (int i = 0; i < RatingLabel.Count; i = i + 2) { if (i == 0) { RatingLabel[i].Text = (((angryCount * 100) / Votes.Count)).ToString() + "%"; RatingLabel[i + 1].Text = (((angryCount * 100) / Votes.Count)).ToString() + "%"; } if (i == 2) { RatingLabel[i].Text = (((unHappyCount * 100) / Votes.Count)).ToString() + "%"; RatingLabel[i + 1].Text = (((unHappyCount * 100) / Votes.Count)).ToString() + "%"; } if (i == 4) { RatingLabel[i].Text = (((neutralCount * 100) / Votes.Count)).ToString() + "%"; RatingLabel[i + 1].Text = (((neutralCount * 100) / Votes.Count)).ToString() + "%"; } if (i == 6) { RatingLabel[i].Text = (((happyCount * 100) / Votes.Count)).ToString() + "%"; RatingLabel[i + 1].Text = (((happyCount * 100) / Votes.Count)).ToString() + "%"; } if (i == 8) { RatingLabel[i].Text = (((excitedCount * 100) / Votes.Count)).ToString() + "%"; RatingLabel[i + 1].Text = (((excitedCount * 100) / Votes.Count)).ToString() + "%"; } RatingLabel[i].HorizontalTextAlignment = TextAlignment.Center; } } isVoted = false; this.rating.Value = 0; } } } <file_sep>/Android/SampleBrowser/Samples/AutoComplete/TokensSample/TokensSamplePage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Util; using System; using Android.Views; using SampleBrowser; using Android.Widget; using Android.Graphics; using Com.Syncfusion.Autocomplete; using System.Linq; namespace SampleBrowser { public class TokensSamplePage : SamplePage { LinearLayout mainLayout; int width,height; double density; public override View GetPropertyWindowLayout(Android.Content.Context context) { return null; } public override View GetSampleContent(Android.Content.Context con) { width = con.Resources.DisplayMetrics.WidthPixels; height = con.Resources.DisplayMetrics.HeightPixels; density = con.Resources.DisplayMetrics.Density; mainLayout = new LinearLayout(con); mainLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); mainLayout.Orientation = Orientation.Vertical; mainLayout.SetGravity(GravityFlags.CenterHorizontal); HeaderMethod(con); ToMethod(con); CcMethod(con); BccMethod(con); SubjectMethod(con); ContentMethod(con); return mainLayout; } private void HeaderMethod(Android.Content.Context con) { LinearLayout hearderLayout = new LinearLayout(con); hearderLayout.LayoutParameters=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(50 * density)); hearderLayout.Orientation = Orientation.Horizontal; hearderLayout.SetBackgroundColor(Color.ParseColor("#2A4D72")); hearderLayout.SetGravity(GravityFlags.Center); TextView emailText = new TextView(con); emailText.SetPadding((int)(10 * density),0,0,0); emailText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.60), (int)(50 * density)); emailText.Text = "Email-Compose"; emailText.SetTextColor(Color.White); emailText.TextSize =16; emailText.Typeface = Typeface.DefaultBold; emailText.TextAlignment = TextAlignment.Center; emailText.Gravity = GravityFlags.CenterVertical; hearderLayout.AddView(emailText); TextView attachText = new TextView(con); attachText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.25), (int)(50 * density)); attachText.Text = "ATTACH"; attachText.SetTextColor(Color.White); attachText.TextSize = 16; attachText.Typeface = Typeface.DefaultBold; attachText.TextAlignment = TextAlignment.Center; attachText.Gravity = GravityFlags.CenterVertical; hearderLayout.AddView(attachText); TextView sendText = new TextView(con); sendText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(50 * density)); sendText.Text = "SEND"; sendText.SetTextColor(Color.White); sendText.TextSize = 16; sendText.Typeface = Typeface.DefaultBold; sendText.TextAlignment = TextAlignment.Center; sendText.Gravity = GravityFlags.CenterVertical; hearderLayout.AddView(sendText); mainLayout.AddView(hearderLayout); } private void ToMethod(Android.Content.Context con) { LinearLayout toLayout = new LinearLayout(con); toLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(50 * density)); toLayout.Orientation = Orientation.Horizontal; toLayout.SetGravity(GravityFlags.Center); toLayout.SetPadding(0,0,10,0); TextView toText = new TextView(con); toText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(50 * density)); toText.Text = "To"; toText.TextSize = 20; toText.TextAlignment = TextAlignment.Center; toText.Gravity = GravityFlags.Center; toLayout.AddView(toText); SfAutoComplete toAutoComplete = new SfAutoComplete(con); toAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.85), (int)(45 )); toAutoComplete.MultiSelectMode = MultiSelectMode.Token; toAutoComplete.SetGravity(GravityFlags.Center); toAutoComplete.DataSource = new AutoCompleteContactsInfoRepository().GetContactDetails(); toAutoComplete.DisplayMemberPath = "ContactName"; toAutoComplete.TokensWrapMode = TokensWrapMode.Wrap; toAutoComplete.DropDownCornerRadius = 4; toAutoComplete.ImageMemberPath = "ContactImage"; toAutoComplete.MaximumDropDownHeight = 150; toAutoComplete.DropDownItemHeight = 60; toAutoComplete.IsFocused = true; CustomAutoCompleteAdapterToken customAdapter = new CustomAutoCompleteAdapterToken(); customAdapter.autoComplete1 = toAutoComplete; toAutoComplete.Adapter = customAdapter; toLayout.AddView(toAutoComplete); toAutoComplete.FocusChanged += (sender, e) => { // if (e.HasFocus) // { // toLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(90 * density)); // toText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(90 * density)); // toAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.85), (int)(90 )); // } // else{ //toLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(50 * density)); //toText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(50 * density)); //toAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.85), (int)(50 )); //} }; mainLayout.AddView(toLayout); } private void CcMethod(Android.Content.Context con) { LinearLayout ccLayout = new LinearLayout(con); ccLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(50 * density)); ccLayout.Orientation = Orientation.Horizontal; ccLayout.SetGravity(GravityFlags.Center); ccLayout.SetPadding(0, 0, 10, 0); TextView ccText = new TextView(con); ccText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(50 * density)); ccText.Text = "Cc"; ccText.TextSize = 20; ccText.TextAlignment = TextAlignment.Center; ccText.Gravity = GravityFlags.Center; ccLayout.AddView(ccText); SfAutoComplete ccAutoComplete = new SfAutoComplete(con); ccAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.85), (int)(45 )); ccAutoComplete.MultiSelectMode = MultiSelectMode.Token; ccAutoComplete.SetGravity(GravityFlags.Center); ccAutoComplete.DataSource = new AutoCompleteContactsInfoRepository().GetContactDetails(); ccAutoComplete.DisplayMemberPath = "ContactName"; ccAutoComplete.TokensWrapMode = TokensWrapMode.Wrap; ccAutoComplete.DropDownCornerRadius = 4; ccAutoComplete.ImageMemberPath = "ContactImage"; ccAutoComplete.MaximumDropDownHeight = 150; ccAutoComplete.DropDownItemHeight = 60; CustomAutoCompleteAdapterToken customAdapter = new CustomAutoCompleteAdapterToken(); customAdapter.autoComplete1 = ccAutoComplete; ccAutoComplete.Adapter = customAdapter; ccLayout.AddView(ccAutoComplete); ccAutoComplete.FocusChanged += (sender, e) => { //if (e.HasFocus) //{ // ccLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(90 * density)); // ccText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(90 * density)); // ccAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.85), (int)(90 )); //} //else //{ // ccLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(50 * density)); // ccText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(50 * density)); // ccAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.85), (int)(45 )); //} }; mainLayout.AddView(ccLayout); } private void BccMethod(Android.Content.Context con) { LinearLayout bccLayout = new LinearLayout(con); bccLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(50 * density)); bccLayout.Orientation = Orientation.Horizontal; bccLayout.SetGravity(GravityFlags.Center); bccLayout.SetPadding(0, 0, 10, 0); TextView bccText = new TextView(con); bccText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(50 * density)); bccText.Text = "Bcc"; bccText.TextSize = 20; bccText.TextAlignment = TextAlignment.Center; bccText.Gravity = GravityFlags.Center; bccLayout.AddView(bccText); SfAutoComplete bccAutoComplete = new SfAutoComplete(con); bccAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.85), (int)(45 )); bccAutoComplete.MultiSelectMode = MultiSelectMode.Token; bccAutoComplete.SetGravity(GravityFlags.Center); bccAutoComplete.DataSource = new AutoCompleteContactsInfoRepository().GetContactDetails(); bccAutoComplete.DisplayMemberPath = "ContactName"; bccAutoComplete.TokensWrapMode = TokensWrapMode.Wrap; bccAutoComplete.DropDownCornerRadius = 4; bccAutoComplete.ImageMemberPath = "ContactImage"; bccAutoComplete.MaximumDropDownHeight = 150; bccAutoComplete.DropDownItemHeight = 60; CustomAutoCompleteAdapterToken customAdapter = new CustomAutoCompleteAdapterToken(); customAdapter.autoComplete1 = bccAutoComplete; bccAutoComplete.Adapter = customAdapter; bccLayout.AddView(bccAutoComplete); bccAutoComplete.FocusChanged += (sender, e) => { //if (e.HasFocus) //{ // bccLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(90 * density)); // bccText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(90 * density)); // bccAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.85), (int)(90 )); //} //else //{ // bccLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(50 * density)); // bccText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.15), (int)(50 * density)); // bccAutoComplete.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.85), (int)(50 )); //} }; mainLayout.AddView(bccLayout); } private void SubjectMethod(Android.Content.Context con) { EditText editText = new EditText(con); editText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.95), (int)(50 * density)); editText.Hint = "Subject"; editText.TextSize = 15; mainLayout.AddView(editText); } private void ContentMethod(Android.Content.Context con) { EditText editText = new EditText(con); editText.LayoutParameters = new LinearLayout.LayoutParams((int)(width * 0.95), (int)(height - (400 * density))); editText.Text = "Sent from my smartphone"; editText.TextSize = 12; editText.Gravity=GravityFlags.Start; mainLayout.AddView(editText); } } internal class CustomAutoCompleteAdapterToken : AutoCompleteAdapter { internal SfAutoComplete autoComplete1; public Android.Views.View GetView(Com.Syncfusion.Autocomplete.SfAutoComplete autoComplete, string text, int index) { GC.Collect(); string contactTypeValue="",contactImageValue="",contactNameValue="",contactNumberValue=""; var contactType = autoComplete.DataSource.ElementAt(index); foreach (var property in contactType.GetType().GetProperties()) { if (property.Name.Equals("ContactType")) { contactTypeValue=(property.GetValue(contactType).ToString().ToLower()); contactTypeValue = contactTypeValue.Split('.')[0]; } else if (property.Name.Equals("ContactImage")) { contactImageValue = (property.GetValue(contactType).ToString().ToLower()); contactImageValue = contactImageValue.Split('.')[0]; } else if (property.Name.Equals("ContactName")) { contactNameValue = (property.GetValue(contactType).ToString()); } else if (property.Name.Equals("ContactNumber")) { contactNumberValue = (property.GetValue(contactType).ToString()); } } ImageView contactTypeImage = new ImageView(autoComplete.Context); contactTypeImage.SetImageResource(autoComplete.GetImageResId(contactTypeValue)); LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams((int)(40 * autoComplete.GetDensity()), (int)(40 * autoComplete.GetDensity())); contactTypeImage.LayoutParameters = parms; ImageView contactImageImage = new ImageView(autoComplete.Context); contactImageImage.SetImageResource(autoComplete.GetImageResId(contactImageValue)); LinearLayout.LayoutParams parms12 = new LinearLayout.LayoutParams((int)(40 * autoComplete.GetDensity()), (int)(40 * autoComplete.GetDensity())); contactImageImage.LayoutParameters = parms12; FrameLayout frameLayout = new FrameLayout(autoComplete.Context); frameLayout.SetPadding((int)(10 * autoComplete.GetDensity()),(int)(3 * autoComplete.GetDensity()),0,0); FrameLayout.LayoutParams parmsFrame = new FrameLayout.LayoutParams((int)(50 * autoComplete.GetDensity()), (int)(43 * autoComplete.GetDensity())); frameLayout.LayoutParameters = parmsFrame; //frameLayout.AddView(contactTypeImage); frameLayout.AddView(contactImageImage); TextView nameText = new TextView(autoComplete.Context); nameText.Text = contactNameValue; nameText.TextSize = 16; TextView emailText = new TextView(autoComplete.Context); emailText.Text = contactNumberValue; emailText.TextSize = 12; LinearLayout textLayout = new LinearLayout(autoComplete.Context); textLayout.SetPadding((int)(10 * autoComplete.GetDensity()), (int)(3 * autoComplete.GetDensity()), (int)(3 * autoComplete.GetDensity()), (int)(3 * autoComplete.GetDensity())); textLayout.LayoutParameters = new ViewGroup.LayoutParams(autoComplete.LayoutParameters.Width, autoComplete.LayoutParameters.Height); textLayout.Orientation = Android.Widget.Orientation.Vertical; textLayout.AddView(nameText); textLayout.AddView(emailText); LinearLayout linearLayout = new LinearLayout(autoComplete.Context); linearLayout.SetPadding((int)(3 * autoComplete.GetDensity()), (int)(3 * autoComplete.GetDensity()), (int)(3 * autoComplete.GetDensity()), (int)(3 * autoComplete.GetDensity())); linearLayout.LayoutParameters = new ViewGroup.LayoutParams(autoComplete.LayoutParameters.Width, autoComplete.LayoutParameters.Height); linearLayout.Orientation = Android.Widget.Orientation.Horizontal; linearLayout.AddView(frameLayout); linearLayout.AddView(textLayout); linearLayout.SetGravity(GravityFlags.CenterVertical); return linearLayout; } } }<file_sep>/Android/SampleBrowser/Samples/Carousel/CarouselModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.IO; namespace SampleBrowser { public class CarouselPropertyClass { #region private properties /// <summary> /// The image. /// </summary> private string image; /// <summary> /// The name. /// </summary> private string name; /// <summary> /// The color of the item. /// </summary> private Android.Graphics.Color itemColor; /// <summary> /// /// </summary> private string checkValue = "C"; /// <summary> /// The grid visible. /// </summary> private bool gridVisible = false; #endregion #region Public properties /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public string Name { get { return name; } set { name = value.ToString().Replace("-WF", ""); } } /// <summary> /// Gets or sets the color of the item. /// </summary> /// <value>The color of the item.</value> public Android.Graphics.Color ItemColor { get { return itemColor; } set { itemColor = value; //RaisePropertyChanged("ItemColor"); } } /// <summary> /// Gets or sets the color of the item. /// </summary> /// <value>The color of the item.</value> public string CheckValue { get { return checkValue; } set { checkValue = value; //RaisePropertyChanged("CheckValue"); } } /// <summary> /// Gets or sets the tag. /// </summary> /// <value>The tag.</value> public string Tag { get; set; } /// <summary> /// Gets or sets the unicode. /// </summary> /// <value>The unicode.</value> public string Unicode { get; set; } /// <summary> /// Gets or sets the name of the watch. /// </summary> /// <value>The name of the watch.</value> public string ImageName { get { return image; } set { image = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="T:SampleBrowser.SfCarousel.CarouselModel"/> grid visible. /// </summary> /// <value><c>true</c> if grid visible; otherwise, <c>false</c>.</value> public bool GridVisible { get { return gridVisible; } set { gridVisible = value; //RaisePropertyChanged("GridVisible"); } } #endregion } public class CarouselModel { /// <summary> /// The data collection. /// </summary> public ObservableCollection<CarouselPropertyClass> dataCollection = new ObservableCollection<CarouselPropertyClass>(); /// <summary> /// The application collection. /// </summary> public ObservableCollection<CarouselPropertyClass> applicationCollection = new ObservableCollection<CarouselPropertyClass>(); /// <summary> /// The office collection. /// </summary> public ObservableCollection<CarouselPropertyClass> officeCollection = new ObservableCollection<CarouselPropertyClass>(); /// <summary> /// The transport collection. /// </summary> public ObservableCollection<CarouselPropertyClass> transportCollection = new ObservableCollection<CarouselPropertyClass>(); /// <summary> /// The temp collection. /// </summary> public ObservableCollection<CarouselPropertyClass> TempCollection = new ObservableCollection<CarouselPropertyClass>(); /// <summary> /// The dicItems. /// </summary> private Dictionary<string, string> s = new Dictionary<string, string>(); /// <summary> /// Gets or sets the data collection. /// </summary> /// <value>The data collection.</value> public ObservableCollection<CarouselPropertyClass> DataCollection { get { return dataCollection; } set { dataCollection = value; } } /// <summary> /// Gets or sets the application collection. /// </summary> /// <value>The application collection.</value> public ObservableCollection<CarouselPropertyClass> ApplicationCollection { get { return applicationCollection; } set { applicationCollection = value; } } /// <summary> /// Gets or sets the office collection. /// </summary> /// <value>The office collection.</value> public ObservableCollection<CarouselPropertyClass> OfficeCollection { get { return officeCollection; } set { officeCollection = value; } } /// <summary> /// Gets or sets the transport collection. /// </summary> /// <value>The transport collection.</value> public ObservableCollection<CarouselPropertyClass> TransportCollection { get { return transportCollection; } set { transportCollection = value; } } #region get color /// <summary> /// Gets the color. /// </summary> public void GetColor() { ColorCode.Add(Android.Graphics.Color.Violet); ColorCode.Add(Android.Graphics.Color.OrangeRed); ColorCode.Add(Android.Graphics.Color.Blue); ColorCode.Add(Android.Graphics.Color.MediumVioletRed); ColorCode.Add(Android.Graphics.Color.DeepSkyBlue); ColorCode.Add(Android.Graphics.Color.DarkOrange); ColorCode.Add(Android.Graphics.Color.PaleVioletRed); ColorCode.Add(Android.Graphics.Color.LightGreen); ColorCode.Add(Android.Graphics.Color.Gold); ColorCode.Add(Android.Graphics.Color.DeepSkyBlue); ColorCode.Add(Android.Graphics.Color.RoyalBlue); ColorCode.Add(Android.Graphics.Color.Orange); ColorCode.Add(Android.Graphics.Color.PaleVioletRed); ColorCode.Add(Android.Graphics.Color.CornflowerBlue); ColorCode.Add(Android.Graphics.Color.DeepPink); ColorCode.Add(Android.Graphics.Color.DarkOliveGreen); } #endregion /// <summary> /// The color code. /// </summary> public List<Android.Graphics.Color> ColorCode = new List<Android.Graphics.Color>(); /// <summary> /// The color count. /// </summary> public int ColorCount = 15; #region pick color /// <summary> /// Picks the color. /// </summary> /// <returns>The color.</returns> public Android.Graphics.Color PickColor() { ColorCount++; if (ColorCount >= 15) ColorCount = 0; return ColorCode[ColorCount]; } #endregion public CarouselModel() { GetColor(); GetIcon(); ObservableCollection<string> applicationicons = GetApplicationIcon(); ObservableCollection<string> officeicons = GetOfficeIcon(); ObservableCollection<string> transporticons = GetTransportCollection(); var assembly = typeof(CarouselModel).GetTypeInfo().Assembly; Stream stream = assembly.GetManifestResourceStream("SampleBrowser.Resources.CustomSearch.txt"); if (stream != null) { string text = ""; using (var reader = new System.IO.StreamReader(stream)) { while ((text = reader.ReadLine()) != null) { string[] splits = text.Split('*'); if (splits.Length == 3) { try { if (applicationicons.Contains(splits[0])) { CarouselPropertyClass model = new CarouselPropertyClass(); model.ItemColor = PickColor(); model.Name = splits[0]; model.Unicode = s[splits[1]]; model.Tag = splits[2]; ApplicationCollection.Add(model); DataCollection.Add(model); TempCollection.Add(model); } else if (officeicons.Contains(splits[0])) { CarouselPropertyClass model = new CarouselPropertyClass(); model.ItemColor = PickColor(); model.Name = splits[0]; model.Unicode = s[splits[1]]; model.Tag = splits[2]; OfficeCollection.Add(model); DataCollection.Add(model); TempCollection.Add(model); } else if (transporticons.Contains(splits[0])) { CarouselPropertyClass model = new CarouselPropertyClass(); model.ItemColor = PickColor(); model.Name = splits[0]; model.Unicode = s[splits[1]]; model.Tag = splits[2]; TransportCollection.Add(model); DataCollection.Add(model); TempCollection.Add(model); } else { CarouselPropertyClass model = new CarouselPropertyClass(); model.Name = splits[0]; model.Unicode = s[splits[1]]; model.Tag = splits[2]; DataCollection.Add(model); TempCollection.Add(model); } } catch (Exception e) { var ee = e.Message; } } } } } //for (int i = 0; i < 5; i++) //{ // PullBrandCollection.Add(BrandCollection[i]); // PullDataValueCollection.Add(datavalueCollection[i]); // PullGadgetCollection.Add(gadgetCollection[i]); //} for (int j = 0; j < 2; j++) { for (int i = 0; i < this.TempCollection.Count; i++) { DataCollection.Add(this.TempCollection[i]); } } } /// <summary> /// Gets the icon. /// </summary> private void GetIcon() { s.Add("e956", "\U0000E956"); s.Add("eb2e", "\U0000EB2E"); s.Add("eb27", "\U0000EB27"); s.Add("eb2d", "\U0000EB2D"); s.Add("ed25", "\U0000ED25"); s.Add("eb0b", "\U0000EB0B"); s.Add("eb4a", "\U0000EB4A"); s.Add("eafe", "\U0000EAFE"); s.Add("eb38", "\U0000EB38"); s.Add("ed23", "\U0000ED23"); s.Add("eb0c", "\U0000EB0C"); s.Add("ed27", "\U0000ED27"); s.Add("eb56", "\U0000EB56"); s.Add("eb48", "\U0000EB48"); s.Add("eb36", "\U0000EB36"); s.Add("eafd", "\U0000EAFD"); s.Add("eb54", "\U0000EB54"); s.Add("eaf7", "\U0000EAF7"); s.Add("ec67", "\U0000EC67"); s.Add("eabf", "\U0000EABF"); s.Add("eb4c", "\U0000EB4C"); s.Add("ec2b", "\U0000EC2B"); s.Add("eaba", "\U0000EABA"); s.Add("ec65", "\U0000EC65"); s.Add("eb55", "\U0000EB55"); s.Add("eb46", "\U0000EB46"); s.Add("eb26", "\U0000EB26"); s.Add("e9c9", "\U0000E9C9"); s.Add("eb44", "\U0000EB44"); s.Add("eaf5", "\U0000EAF5"); s.Add("eb3d", "\U0000EB3D"); s.Add("eb4e", "\U0000EB4E"); s.Add("ed24", "\U0000ED24"); s.Add("eb28", "\U0000EB28"); s.Add("eb3f", "\U0000EB3F"); s.Add("eb35", "\U0000EB35"); s.Add("eb33", "\U0000EB33"); s.Add("eaf6", "\U0000EAF6"); s.Add("eb5e", "\U0000EB5E"); s.Add("e9ca", "\U0000E9CA"); s.Add("eb42", "\U0000EB42"); s.Add("eb10", "\U0000EB10"); s.Add("ed26", "\U0000ED26"); s.Add("ec64", "\U0000EC64"); s.Add("eb04", "\U0000EB04"); s.Add("eb08", "\U0000EB08"); s.Add("eab9", "\U0000EAB9"); s.Add("eaff", "\U0000EAFF"); s.Add("eb52", "\U0000EB52"); s.Add("ec66", "\U0000EC66"); s.Add("eaf4", "\U0000EAF4"); s.Add("e9ee", "\U0000E9EE"); s.Add("eba1", "\U0000EBA1"); s.Add("eabb", "\U0000EABB"); s.Add("eb50", "\U0000EB50"); s.Add("eab3", "\U0000EAB3"); s.Add("eab2", "\U0000EAB2"); s.Add("eab1", "\U0000EAB1"); s.Add("e8ca", "\U0000E8CA"); s.Add("e93e", "\U0000E93E"); s.Add("eba0", "\U0000EBA0"); s.Add("eb39", "\U0000EB39"); s.Add("ec2a", "\U0000EC2A"); s.Add("e9ed", "\U0000E9ED"); s.Add("eb5d", "\U0000EB5D"); s.Add("ec38", "\U0000EC38"); s.Add("e954", "\U0000E954"); s.Add("ed15", "\U0000ED15"); s.Add("ed21", "\U0000ED21"); s.Add("ec45", "\U0000EC45"); s.Add("ed34", "\U0000ED34"); s.Add("ed37", "\U0000ED37"); s.Add("ebf5", "\U0000EBF5"); s.Add("ec4e", "\U0000EC4E"); s.Add("ecb9", "\U0000ECB9"); s.Add("e952", "\U0000E952"); s.Add("ebff", "\U0000EBFF"); s.Add("ed0f", "\U0000ED0F"); s.Add("ed1c", "\U0000ED1C"); s.Add("e955", "\U0000E955"); s.Add("ecc5", "\U0000ECC5"); s.Add("ecd6", "\U0000ECD6"); s.Add("ecec", "\U0000ECEC"); s.Add("ecf4", "\U0000ECF4"); s.Add("ecc2", "\U0000ECC2"); s.Add("e958", "\U0000E958"); s.Add("ec47", "\U0000EC47"); s.Add("e950", "\U0000E950"); s.Add("ed06", "\U0000ED06"); s.Add("ecc3", "\U0000ECC3"); s.Add("e948", "\U0000E948"); s.Add("ece7", "\U0000ECE7"); s.Add("ecd7", "\U0000ECD7"); s.Add("ed19", "\U0000ED19"); s.Add("ed18", "\U0000ED18"); s.Add("e949", "\U0000E949"); s.Add("ed28", "\U0000ED28"); s.Add("ed31", "\U0000ED31"); s.Add("ed3f", "\U0000ED3F"); s.Add("ed0a", "\U0000ED0A"); s.Add("e94b", "\U0000E94B"); s.Add("e98a", "\U0000E98A"); s.Add("e94a", "\U0000E94A"); s.Add("ecc4", "\U0000ECC4"); s.Add("ed13", "\U0000ED13"); s.Add("ec54", "\U0000EC54"); s.Add("ecc6", "\U0000ECC6"); s.Add("ed1e", "\U0000ED1E"); s.Add("ecd1", "\U0000ECD1"); s.Add("e986", "\U0000E986"); s.Add("ecd9", "\U0000ECD9"); s.Add("e953", "\U0000E953"); s.Add("ed08", "\U0000ED08"); s.Add("e9dd", "\U0000E9DD"); s.Add("ed0c", "\U0000ED0C"); s.Add("e94e", "\U0000E94E"); s.Add("e94f", "\U0000E94F"); s.Add("ecf2", "\U0000ECF2"); s.Add("ecdf", "\U0000ECDF"); s.Add("ecc7", "\U0000ECC7"); s.Add("e95a", "\U0000E95A"); s.Add("ecea", "\U0000ECEA"); s.Add("ecbf", "\U0000ECBF"); s.Add("ecb8", "\U0000ECB8"); s.Add("e95b", "\U0000E95B"); s.Add("eafa", "\U0000EAFA"); s.Add("ed40", "\U0000ED40"); s.Add("ecc1", "\U0000ECC1"); s.Add("ed11", "\U0000ED11"); s.Add("e959", "\U0000E959"); s.Add("ed07", "\U0000ED07"); s.Add("e957", "\U0000E957"); s.Add("ed10", "\U0000ED10"); s.Add("ed1d", "\U0000ED1D"); s.Add("ed0e", "\U0000ED0E"); s.Add("ecda", "\U0000ECDA"); s.Add("eceb", "\U0000ECEB"); s.Add("ece0", "\U0000ECE0"); s.Add("ecee", "\U0000ECEE"); s.Add("ecba", "\U0000ECBA"); s.Add("ecdd", "\U0000ECDD"); s.Add("ed12", "\U0000ED12"); s.Add("e94c", "\U0000E94C"); s.Add("ed32", "\U0000ED32"); s.Add("ec41", "\U0000EC41"); s.Add("ed43", "\U0000ED43"); s.Add("eced", "\U0000ECED"); s.Add("ecde", "\U0000ECDE"); s.Add("e951", "\U0000E951"); s.Add("ed46", "\U0000ED46"); s.Add("ed0d", "\U0000ED0D"); s.Add("ecdb", "\U0000ECDB"); s.Add("ed16", "\U0000ED16"); s.Add("ed14", "\U0000ED14"); s.Add("e9c3", "\U0000E9C3"); s.Add("ecdc", "\U0000ECDC"); s.Add("ec46", "\U0000EC46"); s.Add("e94d", "\U0000E94D"); s.Add("ed1f", "\U0000ED1F"); s.Add("ec53", "\U0000EC53"); s.Add("e947", "\U0000E947"); s.Add("ec21", "\U0000EC21"); s.Add("ec91", "\U0000EC91"); s.Add("ec8e", "\U0000EC8E"); s.Add("ec78", "\U0000EC78"); s.Add("eca5", "\U0000ECA5"); s.Add("ecb7", "\U0000ECB7"); s.Add("ecb0", "\U0000ECB0"); s.Add("ec24", "\U0000EC24"); s.Add("ec3f", "\U0000EC3F"); s.Add("eca1", "\U0000ECA1"); s.Add("ec84", "\U0000EC84"); s.Add("ebfe", "\U0000EBFE"); s.Add("ec87", "\U0000EC87"); s.Add("ec7c", "\U0000EC7C"); s.Add("ecad", "\U0000ECAD"); s.Add("ec9e", "\U0000EC9E"); s.Add("ec89", "\U0000EC89"); s.Add("ec9b", "\U0000EC9B"); s.Add("eca6", "\U0000ECA6"); s.Add("ec7e", "\U0000EC7E"); s.Add("ec8a", "\U0000EC8A"); s.Add("ecab", "\U0000ECAB"); s.Add("ec9f", "\U0000EC9F"); s.Add("ec80", "\U0000EC80"); s.Add("ec75", "\U0000EC75"); s.Add("ec7f", "\U0000EC7F"); s.Add("ec82", "\U0000EC82"); s.Add("ecb1", "\U0000ECB1"); s.Add("ecaa", "\U0000ECAA"); s.Add("ec26", "\U0000EC26"); s.Add("ec7b", "\U0000EC7B"); s.Add("eca4", "\U0000ECA4"); s.Add("ec86", "\U0000EC86"); s.Add("ec8c", "\U0000EC8C"); s.Add("ec1f", "\U0000EC1F"); s.Add("ec8f", "\U0000EC8F"); s.Add("ec20", "\U0000EC20"); s.Add("ec9c", "\U0000EC9C"); s.Add("eca2", "\U0000ECA2"); s.Add("ecae", "\U0000ECAE"); s.Add("ec1e", "\U0000EC1E"); s.Add("ec3e", "\U0000EC3E"); s.Add("ec76", "\U0000EC76"); s.Add("ec98", "\U0000EC98"); s.Add("ebb1", "\U0000EBB1"); s.Add("ebdc", "\U0000EBDC"); s.Add("ebac", "\U0000EBAC"); s.Add("ec6e", "\U0000EC6E"); s.Add("eb23", "\U0000EB23"); s.Add("eb67", "\U0000EB67"); s.Add("ebc3", "\U0000EBC3"); s.Add("ebf3", "\U0000EBF3"); s.Add("eb99", "\U0000EB99"); s.Add("ebd0", "\U0000EBD0"); s.Add("ebb0", "\U0000EBB0"); s.Add("ebb4", "\U0000EBB4"); s.Add("eb6e", "\U0000EB6E"); s.Add("ebb7", "\U0000EBB7"); s.Add("ebb3", "\U0000EBB3"); s.Add("eb66", "\U0000EB66"); s.Add("eb61", "\U0000EB61"); s.Add("eb7f", "\U0000EB7F"); s.Add("ebee", "\U0000EBEE"); s.Add("ebe8", "\U0000EBE8"); s.Add("eb74", "\U0000EB74"); s.Add("eb98", "\U0000EB98"); s.Add("ebae", "\U0000EBAE"); s.Add("ec07", "\U0000EC07"); s.Add("eb77", "\U0000EB77"); s.Add("eb59", "\U0000EB59"); s.Add("ebef", "\U0000EBEF"); s.Add("ebad", "\U0000EBAD"); s.Add("ebb5", "\U0000EBB5"); s.Add("ec05", "\U0000EC05"); s.Add("ec23", "\U0000EC23"); s.Add("ebe7", "\U0000EBE7"); s.Add("ec6d", "\U0000EC6D"); s.Add("eb9c", "\U0000EB9C"); s.Add("eb8c", "\U0000EB8C"); s.Add("eb68", "\U0000EB68"); s.Add("eb6a", "\U0000EB6A"); s.Add("eb8e", "\U0000EB8E"); s.Add("eb5f", "\U0000EB5F"); s.Add("eb24", "\U0000EB24"); s.Add("ebd5", "\U0000EBD5"); s.Add("eb65", "\U0000EB65"); s.Add("eb9b", "\U0000EB9B"); s.Add("eb64", "\U0000EB64"); s.Add("ebd4", "\U0000EBD4"); s.Add("eb6b", "\U0000EB6B"); s.Add("ebe5", "\U0000EBE5"); s.Add("ebaa", "\U0000EBAA"); s.Add("ebe3", "\U0000EBE3"); s.Add("eb25", "\U0000EB25"); s.Add("eba6", "\U0000EBA6"); s.Add("eb5c", "\U0000EB5C"); s.Add("ec0b", "\U0000EC0B"); s.Add("eba4", "\U0000EBA4"); s.Add("eb75", "\U0000EB75"); s.Add("eba8", "\U0000EBA8"); s.Add("eb58", "\U0000EB58"); s.Add("ebc1", "\U0000EBC1"); s.Add("eb69", "\U0000EB69"); s.Add("ebe1", "\U0000EBE1"); s.Add("eb9a", "\U0000EB9A"); s.Add("ec1d", "\U0000EC1D"); s.Add("eca8", "\U0000ECA8"); s.Add("ec39", "\U0000EC39"); s.Add("ec79", "\U0000EC79"); s.Add("ec92", "\U0000EC92"); s.Add("ec94", "\U0000EC94"); s.Add("ec95", "\U0000EC95"); s.Add("ec56", "\U0000EC56"); s.Add("ec8d", "\U0000EC8D"); s.Add("ec0d", "\U0000EC0D"); s.Add("ec3b", "\U0000EC3B"); s.Add("ec97", "\U0000EC97"); s.Add("ec99", "\U0000EC99"); s.Add("e7c3", "\U0000E7C3"); s.Add("e7d5", "\U0000E7D5"); s.Add("e703", "\U0000E703"); s.Add("e8ba", "\U0000E8BA"); s.Add("ea86", "\U0000EA86"); s.Add("e8b9", "\U0000E8B9"); s.Add("e74a", "\U0000E74A"); s.Add("ec68", "\U0000EC68"); s.Add("e7ab", "\U0000E7AB"); s.Add("e8e4", "\U0000E8E4"); s.Add("e93f", "\U0000E93F"); s.Add("ea70", "\U0000EA70"); s.Add("e73d", "\U0000E73D"); s.Add("e88e", "\U0000E88E"); s.Add("eae9", "\U0000EAE9"); s.Add("e8cc", "\U0000E8CC"); s.Add("e746", "\U0000E746"); s.Add("e81a", "\U0000E81A"); s.Add("e909", "\U0000E909"); s.Add("e994", "\U0000E994"); s.Add("e81c", "\U0000E81C"); s.Add("ea42", "\U0000EA42"); s.Add("e801", "\U0000E801"); s.Add("e883", "\U0000E883"); s.Add("eae8", "\U0000EAE8"); s.Add("ea7e", "\U0000EA7E"); s.Add("e803", "\U0000E803"); s.Add("ea53", "\U0000EA53"); s.Add("eab4", "\U0000EAB4"); s.Add("eaef", "\U0000EAEF"); s.Add("e735", "\U0000E735"); s.Add("e755", "\U0000E755"); s.Add("e884", "\U0000E884"); s.Add("ea00", "\U0000EA00"); s.Add("e7b0", "\U0000E7B0"); s.Add("e778", "\U0000E778"); s.Add("e740", "\U0000E740"); s.Add("e887", "\U0000E887"); s.Add("e9ff", "\U0000E9FF"); s.Add("e9ec", "\U0000E9EC"); s.Add("e8b6", "\U0000E8B6"); s.Add("e7eb", "\U0000E7EB"); s.Add("e98f", "\U0000E98F"); s.Add("e857", "\U0000E857"); s.Add("eaa5", "\U0000EAA5"); s.Add("e8df", "\U0000E8DF"); s.Add("ec69", "\U0000EC69"); s.Add("e76e", "\U0000E76E"); s.Add("e99d", "\U0000E99D"); s.Add("e734", "\U0000E734"); s.Add("e7ed", "\U0000E7ED"); s.Add("e7cc", "\U0000E7CC"); s.Add("ea91", "\U0000EA91"); s.Add("e8d5", "\U0000E8D5"); s.Add("ead0", "\U0000EAD0"); s.Add("eaa7", "\U0000EAA7"); s.Add("eae1", "\U0000EAE1"); s.Add("e862", "\U0000E862"); s.Add("e802", "\U0000E802"); s.Add("e88b", "\U0000E88B"); s.Add("e7a7", "\U0000E7A7"); s.Add("e736", "\U0000E736"); s.Add("e8e7", "\U0000E8E7"); s.Add("e763", "\U0000E763"); s.Add("ea6d", "\U0000EA6D"); s.Add("e864", "\U0000E864"); s.Add("e7cf", "\U0000E7CF"); s.Add("e8e3", "\U0000E8E3"); s.Add("e7d2", "\U0000E7D2"); s.Add("e9a0", "\U0000E9A0"); s.Add("ea6f", "\U0000EA6F"); s.Add("e88a", "\U0000E88A"); s.Add("e9c0", "\U0000E9C0"); s.Add("e888", "\U0000E888"); s.Add("e81d", "\U0000E81D"); s.Add("e89c", "\U0000E89C"); s.Add("e914", "\U0000E914"); s.Add("e80c", "\U0000E80C"); s.Add("ea34", "\U0000EA34"); s.Add("eae3", "\U0000EAE3"); s.Add("e9fe", "\U0000E9FE"); s.Add("e8e0", "\U0000E8E0"); s.Add("e9b7", "\U0000E9B7"); s.Add("ea90", "\U0000EA90"); s.Add("e744", "\U0000E744"); s.Add("e859", "\U0000E859"); s.Add("e872", "\U0000E872"); s.Add("e928", "\U0000E928"); s.Add("e839", "\U0000E839"); s.Add("e7be", "\U0000E7BE"); s.Add("e818", "\U0000E818"); s.Add("e7a5", "\U0000E7A5"); s.Add("e7fd", "\U0000E7FD"); s.Add("e9b8", "\U0000E9B8"); s.Add("e7d4", "\U0000E7D4"); s.Add("e8ad", "\U0000E8AD"); s.Add("e88c", "\U0000E88C"); s.Add("e7b7", "\U0000E7B7"); s.Add("ea27", "\U0000EA27"); s.Add("e7c9", "\U0000E7C9"); s.Add("e8c1", "\U0000E8C1"); s.Add("e776", "\U0000E776"); s.Add("ea1d", "\U0000EA1D"); s.Add("e9b4", "\U0000E9B4"); s.Add("e8c6", "\U0000E8C6"); s.Add("ead9", "\U0000EAD9"); s.Add("e99a", "\U0000E99A"); s.Add("e910", "\U0000E910"); s.Add("ea1a", "\U0000EA1A"); s.Add("ea5a", "\U0000EA5A"); s.Add("e87f", "\U0000E87F"); s.Add("e847", "\U0000E847"); s.Add("e9e5", "\U0000E9E5"); s.Add("e700", "\U0000E700"); s.Add("ea18", "\U0000EA18"); s.Add("e81b", "\U0000E81B"); s.Add("e774", "\U0000E774"); s.Add("e990", "\U0000E990"); s.Add("e73c", "\U0000E73C"); s.Add("eaca", "\U0000EACA"); s.Add("eac2", "\U0000EAC2"); s.Add("e71e", "\U0000E71E"); s.Add("e729", "\U0000E729"); s.Add("e757", "\U0000E757"); s.Add("eaa6", "\U0000EAA6"); s.Add("e7d6", "\U0000E7D6"); s.Add("ebbc", "\U0000EBBC"); s.Add("e8e8", "\U0000E8E8"); s.Add("e9ad", "\U0000E9AD"); s.Add("e768", "\U0000E768"); s.Add("e7d0", "\U0000E7D0"); s.Add("e7c8", "\U0000E7C8"); s.Add("e8ed", "\U0000E8ED"); s.Add("ea56", "\U0000EA56"); s.Add("e9a9", "\U0000E9A9"); s.Add("e8c7", "\U0000E8C7"); s.Add("ec29", "\U0000EC29"); s.Add("eae7", "\U0000EAE7"); s.Add("ea44", "\U0000EA44"); s.Add("e8ec", "\U0000E8EC"); s.Add("eb7e", "\U0000EB7E"); s.Add("e796", "\U0000E796"); s.Add("e9af", "\U0000E9AF"); s.Add("ea3a", "\U0000EA3A"); s.Add("e8ea", "\U0000E8EA"); s.Add("e9bf", "\U0000E9BF"); s.Add("e8e5", "\U0000E8E5"); s.Add("e8ac", "\U0000E8AC"); s.Add("e76a", "\U0000E76A"); s.Add("e7f0", "\U0000E7F0"); s.Add("e82f", "\U0000E82F"); s.Add("ea38", "\U0000EA38"); s.Add("ea3f", "\U0000EA3F"); s.Add("eaf8", "\U0000EAF8"); s.Add("e885", "\U0000E885"); s.Add("e91e", "\U0000E91E"); s.Add("eaee", "\U0000EAEE"); s.Add("e7f6", "\U0000E7F6"); s.Add("e817", "\U0000E817"); s.Add("e9c1", "\U0000E9C1"); s.Add("ea23", "\U0000EA23"); s.Add("eac8", "\U0000EAC8"); s.Add("e9b6", "\U0000E9B6"); s.Add("e83c", "\U0000E83C"); s.Add("eac6", "\U0000EAC6"); s.Add("ea94", "\U0000EA94"); s.Add("e924", "\U0000E924"); s.Add("e723", "\U0000E723"); s.Add("e804", "\U0000E804"); s.Add("e74e", "\U0000E74E"); s.Add("ea97", "\U0000EA97"); s.Add("e91c", "\U0000E91C"); s.Add("e84c", "\U0000E84C"); s.Add("ea71", "\U0000EA71"); s.Add("ea22", "\U0000EA22"); s.Add("e77a", "\U0000E77A"); s.Add("e9bd", "\U0000E9BD"); s.Add("ea24", "\U0000EA24"); s.Add("ea4b", "\U0000EA4B"); s.Add("e881", "\U0000E881"); s.Add("ea46", "\U0000EA46"); s.Add("e8eb", "\U0000E8EB"); s.Add("e766", "\U0000E766"); s.Add("eaa8", "\U0000EAA8"); s.Add("e92e", "\U0000E92E"); s.Add("e8a4", "\U0000E8A4"); s.Add("e8c9", "\U0000E8C9"); s.Add("eacd", "\U0000EACD"); s.Add("e7f5", "\U0000E7F5"); s.Add("eac4", "\U0000EAC4"); s.Add("eaf0", "\U0000EAF0"); s.Add("e83b", "\U0000E83B"); s.Add("e772", "\U0000E772"); s.Add("e7b4", "\U0000E7B4"); s.Add("ea60", "\U0000EA60"); s.Add("e7ae", "\U0000E7AE"); s.Add("e75a", "\U0000E75A"); s.Add("e732", "\U0000E732"); s.Add("e91a", "\U0000E91A"); s.Add("e8ab", "\U0000E8AB"); s.Add("e8e2", "\U0000E8E2"); s.Add("ea3c", "\U0000EA3C"); s.Add("e798", "\U0000E798"); s.Add("e7c0", "\U0000E7C0"); s.Add("e8e9", "\U0000E8E9"); s.Add("ea8f", "\U0000EA8F"); s.Add("e7d3", "\U0000E7D3"); s.Add("e81f", "\U0000E81F"); s.Add("eae5", "\U0000EAE5"); s.Add("e899", "\U0000E899"); s.Add("e8de", "\U0000E8DE"); s.Add("e9c2", "\U0000E9C2"); s.Add("e93d", "\U0000E93D"); s.Add("eaed", "\U0000EAED"); s.Add("e762", "\U0000E762"); s.Add("e8ce", "\U0000E8CE"); s.Add("e815", "\U0000E815"); s.Add("e75d", "\U0000E75D"); s.Add("e748", "\U0000E748"); s.Add("e81e", "\U0000E81E"); s.Add("e713", "\U0000E713"); s.Add("e84b", "\U0000E84B"); s.Add("e786", "\U0000E786"); s.Add("e8dc", "\U0000E8DC"); s.Add("e877", "\U0000E877"); s.Add("e790", "\U0000E790"); s.Add("eb1f", "\U0000EB1F"); s.Add("e7c7", "\U0000E7C7"); s.Add("e779", "\U0000E779"); s.Add("e75e", "\U0000E75E"); s.Add("ea0b", "\U0000EA0B"); s.Add("e7f4", "\U0000E7F4"); s.Add("e7a9", "\U0000E7A9"); s.Add("e7ac", "\U0000E7AC"); s.Add("e85b", "\U0000E85B"); s.Add("ea1b", "\U0000EA1B"); s.Add("ea05", "\U0000EA05"); s.Add("e747", "\U0000E747"); s.Add("ea03", "\U0000EA03"); s.Add("ea04", "\U0000EA04"); s.Add("ea01", "\U0000EA01"); s.Add("ea02", "\U0000EA02"); s.Add("e84f", "\U0000E84F"); s.Add("ea3e", "\U0000EA3E"); s.Add("eafc", "\U0000EAFC"); s.Add("ea5d", "\U0000EA5D"); s.Add("e9cd", "\U0000E9CD"); s.Add("e9ce", "\U0000E9CE"); s.Add("eb90", "\U0000EB90"); s.Add("e76c", "\U0000E76C"); s.Add("ea5c", "\U0000EA5C"); s.Add("ea4e", "\U0000EA4E"); s.Add("e9bc", "\U0000E9BC"); s.Add("e725", "\U0000E725"); s.Add("e9e6", "\U0000E9E6"); s.Add("e8e1", "\U0000E8E1"); s.Add("e7ce", "\U0000E7CE"); s.Add("e7bc", "\U0000E7BC"); s.Add("e897", "\U0000E897"); s.Add("e826", "\U0000E826"); s.Add("ea61", "\U0000EA61"); s.Add("e7c6", "\U0000E7C6"); s.Add("e75f", "\U0000E75F"); s.Add("ea8d", "\U0000EA8D"); s.Add("eaa4", "\U0000EAA4"); s.Add("e7b9", "\U0000E7B9"); s.Add("e78e", "\U0000E78E"); s.Add("e9ea", "\U0000E9EA"); s.Add("e8b1", "\U0000E8B1"); s.Add("e9df", "\U0000E9DF"); s.Add("ea1e", "\U0000EA1E"); s.Add("e9cf", "\U0000E9CF"); s.Add("ea06", "\U0000EA06"); s.Add("e890", "\U0000E890"); s.Add("e814", "\U0000E814"); s.Add("e7b2", "\U0000E7B2"); s.Add("e787", "\U0000E787"); s.Add("e9f0", "\U0000E9F0"); s.Add("e92c", "\U0000E92C"); s.Add("e880", "\U0000E880"); s.Add("e77b", "\U0000E77B"); s.Add("eacf", "\U0000EACF"); s.Add("ea76", "\U0000EA76"); s.Add("e752", "\U0000E752"); s.Add("e90f", "\U0000E90F"); s.Add("e835", "\U0000E835"); s.Add("e90b", "\U0000E90B"); s.Add("e770", "\U0000E770"); s.Add("e90d", "\U0000E90D"); s.Add("e7ba", "\U0000E7BA"); s.Add("e848", "\U0000E848"); s.Add("e92a", "\U0000E92A"); s.Add("e761", "\U0000E761"); s.Add("e8e6", "\U0000E8E6"); s.Add("e79e", "\U0000E79E"); s.Add("e72c", "\U0000E72C"); s.Add("ea0c", "\U0000EA0C"); s.Add("ea82", "\U0000EA82"); s.Add("ea19", "\U0000EA19"); s.Add("ec22", "\U0000EC22"); s.Add("ea5e", "\U0000EA5E"); s.Add("e8dd", "\U0000E8DD"); s.Add("e9a1", "\U0000E9A1"); s.Add("e7d1", "\U0000E7D1"); s.Add("ea58", "\U0000EA58"); s.Add("e753", "\U0000E753"); s.Add("e87c", "\U0000E87C"); s.Add("e819", "\U0000E819"); s.Add("e85e", "\U0000E85E"); s.Add("ea1f", "\U0000EA1F"); s.Add("eadf", "\U0000EADF"); s.Add("e882", "\U0000E882"); s.Add("ead5", "\U0000EAD5"); s.Add("e940", "\U0000E940"); s.Add("e820", "\U0000E820"); s.Add("ea5f", "\U0000EA5F"); s.Add("e8cf", "\U0000E8CF"); s.Add("ead7", "\U0000EAD7"); s.Add("e9ae", "\U0000E9AE"); s.Add("e8db", "\U0000E8DB"); s.Add("e706", "\U0000E706"); s.Add("eadd", "\U0000EADD"); s.Add("eaad", "\U0000EAAD"); s.Add("ead3", "\U0000EAD3"); s.Add("e920", "\U0000E920"); s.Add("e88f", "\U0000E88F"); s.Add("ea6e", "\U0000EA6E"); s.Add("e7ef", "\U0000E7EF"); s.Add("ea66", "\U0000EA66"); s.Add("e944", "\U0000E944"); s.Add("e8d7", "\U0000E8D7"); s.Add("e8d3", "\U0000E8D3"); s.Add("e7f9", "\U0000E7F9"); s.Add("e889", "\U0000E889"); s.Add("e886", "\U0000E886"); s.Add("e721", "\U0000E721"); s.Add("e922", "\U0000E922"); s.Add("ea7d", "\U0000EA7D"); s.Add("e849", "\U0000E849"); s.Add("e731", "\U0000E731"); s.Add("eaec", "\U0000EAEC"); s.Add("e891", "\U0000E891"); s.Add("e82a", "\U0000E82A"); s.Add("e75b", "\U0000E75B"); s.Add("e9aa", "\U0000E9AA"); s.Add("ea50", "\U0000EA50"); s.Add("ea1c", "\U0000EA1C"); s.Add("e743", "\U0000E743"); s.Add("e707", "\U0000E707"); s.Add("e927", "\U0000E927"); s.Add("e816", "\U0000E816"); s.Add("e916", "\U0000E916"); s.Add("e918", "\U0000E918"); s.Add("e88d", "\U0000E88D"); s.Add("eadb", "\U0000EADB"); s.Add("e9fd", "\U0000E9FD"); s.Add("e84a", "\U0000E84A"); s.Add("e906", "\U0000E906"); s.Add("ea28", "\U0000EA28"); s.Add("eaae", "\U0000EAAE"); s.Add("e892", "\U0000E892"); s.Add("ea2b", "\U0000EA2B"); s.Add("e8ee", "\U0000E8EE"); s.Add("e72e", "\U0000E72E"); s.Add("e7da", "\U0000E7DA"); s.Add("ea8a", "\U0000EA8A"); s.Add("e84e", "\U0000E84E"); s.Add("e791", "\U0000E791"); s.Add("ece1", "\U0000ECE1"); s.Add("ed39", "\U0000ED39"); s.Add("ed38", "\U0000ED38"); s.Add("ed3a", "\U0000ED3A"); s.Add("eb84", "\U0000EB84"); s.Add("eb83", "\U0000EB83"); s.Add("eb87", "\U0000EB87"); s.Add("eb86", "\U0000EB86"); s.Add("eb85", "\U0000EB85"); s.Add("e7c5", "\U0000E7C5"); s.Add("ec08", "\U0000EC08"); s.Add("e9a7", "\U0000E9A7"); s.Add("e9a6", "\U0000E9A6"); s.Add("e9a5", "\U0000E9A5"); s.Add("e855", "\U0000E855"); s.Add("e8c3", "\U0000E8C3"); s.Add("e936", "\U0000E936"); s.Add("e70e", "\U0000E70E"); s.Add("e980", "\U0000E980"); s.Add("e976", "\U0000E976"); s.Add("e96f", "\U0000E96F"); s.Add("e806", "\U0000E806"); s.Add("ebb2", "\U0000EBB2"); s.Add("eb1d", "\U0000EB1D"); s.Add("e73b", "\U0000E73B"); s.Add("eb63", "\U0000EB63"); s.Add("ec52", "\U0000EC52"); s.Add("e858", "\U0000E858"); s.Add("eba9", "\U0000EBA9"); s.Add("ec7a", "\U0000EC7A"); s.Add("ea74", "\U0000EA74"); s.Add("ea48", "\U0000EA48"); s.Add("ea72", "\U0000EA72"); s.Add("ea75", "\U0000EA75"); s.Add("ed2d", "\U0000ED2D"); s.Add("e8a5", "\U0000E8A5"); s.Add("e829", "\U0000E829"); s.Add("ecb6", "\U0000ECB6"); s.Add("ec61", "\U0000EC61"); s.Add("e937", "\U0000E937"); s.Add("e9ab", "\U0000E9AB"); s.Add("eb70", "\U0000EB70"); s.Add("eb9d", "\U0000EB9D"); s.Add("eb41", "\U0000EB41"); s.Add("eb22", "\U0000EB22"); s.Add("eb0a", "\U0000EB0A"); s.Add("e7f7", "\U0000E7F7"); s.Add("e896", "\U0000E896"); s.Add("e8f0", "\U0000E8F0"); s.Add("ed45", "\U0000ED45"); s.Add("eb92", "\U0000EB92"); s.Add("ea20", "\U0000EA20"); s.Add("ec93", "\U0000EC93"); s.Add("e8bd", "\U0000E8BD"); s.Add("ec28", "\U0000EC28"); s.Add("ea3d", "\U0000EA3D"); s.Add("e799", "\U0000E799"); s.Add("e9e8", "\U0000E9E8"); s.Add("e8f3", "\U0000E8F3"); s.Add("ed22", "\U0000ED22"); s.Add("ec43", "\U0000EC43"); s.Add("e7a6", "\U0000E7A6"); s.Add("ead4", "\U0000EAD4"); s.Add("e893", "\U0000E893"); s.Add("eca0", "\U0000ECA0"); s.Add("eb3e", "\U0000EB3E"); s.Add("ec73", "\U0000EC73"); s.Add("e993", "\U0000E993"); s.Add("e873", "\U0000E873"); s.Add("ebf2", "\U0000EBF2"); s.Add("eac3", "\U0000EAC3"); s.Add("e8b3", "\U0000E8B3"); s.Add("ec9d", "\U0000EC9D"); s.Add("e7a8", "\U0000E7A8"); s.Add("ec19", "\U0000EC19"); s.Add("ec1c", "\U0000EC1C"); s.Add("e989", "\U0000E989"); s.Add("e943", "\U0000E943"); s.Add("e91f", "\U0000E91F"); s.Add("e946", "\U0000E946"); s.Add("e733", "\U0000E733"); s.Add("ea52", "\U0000EA52"); s.Add("ea4c", "\U0000EA4C"); s.Add("e92d", "\U0000E92D"); s.Add("eccd", "\U0000ECCD"); s.Add("e8a3", "\U0000E8A3"); s.Add("e8f4", "\U0000E8F4"); s.Add("ea33", "\U0000EA33"); s.Add("e7bb", "\U0000E7BB"); s.Add("ea32", "\U0000EA32"); s.Add("e7aa", "\U0000E7AA"); s.Add("e8d8", "\U0000E8D8"); s.Add("e72d", "\U0000E72D"); s.Add("e742", "\U0000E742"); s.Add("eb8a", "\U0000EB8A"); s.Add("eb6d", "\U0000EB6D"); s.Add("eb2f", "\U0000EB2F"); s.Add("ece5", "\U0000ECE5"); s.Add("e823", "\U0000E823"); s.Add("e720", "\U0000E720"); s.Add("e9ba", "\U0000E9BA"); s.Add("e89b", "\U0000E89B"); s.Add("eb32", "\U0000EB32"); s.Add("e7b8", "\U0000E7B8"); s.Add("e765", "\U0000E765"); s.Add("ea98", "\U0000EA98"); s.Add("e984", "\U0000E984"); s.Add("e941", "\U0000E941"); s.Add("e764", "\U0000E764"); s.Add("ecce", "\U0000ECCE"); s.Add("e89f", "\U0000E89F"); s.Add("e85f", "\U0000E85F"); s.Add("ed05", "\U0000ED05"); s.Add("e8a8", "\U0000E8A8"); s.Add("e701", "\U0000E701"); s.Add("e8a9", "\U0000E8A9"); s.Add("ec4d", "\U0000EC4D"); s.Add("e751", "\U0000E751"); s.Add("ed09", "\U0000ED09"); s.Add("e788", "\U0000E788"); s.Add("e842", "\U0000E842"); s.Add("e841", "\U0000E841"); s.Add("ead2", "\U0000EAD2"); s.Add("eb07", "\U0000EB07"); s.Add("e769", "\U0000E769"); s.Add("eba7", "\U0000EBA7"); s.Add("e79d", "\U0000E79D"); s.Add("e79c", "\U0000E79C"); s.Add("eab6", "\U0000EAB6"); s.Add("ecf6", "\U0000ECF6"); s.Add("e8c0", "\U0000E8C0"); s.Add("eb49", "\U0000EB49"); s.Add("e925", "\U0000E925"); s.Add("e710", "\U0000E710"); s.Add("e73f", "\U0000E73F"); s.Add("eafb", "\U0000EAFB"); s.Add("eb20", "\U0000EB20"); s.Add("e96e", "\U0000E96E"); s.Add("eb40", "\U0000EB40"); s.Add("e97b", "\U0000E97B"); s.Add("ed35", "\U0000ED35"); s.Add("eb53", "\U0000EB53"); s.Add("e77d", "\U0000E77D"); s.Add("ebbd", "\U0000EBBD"); s.Add("ea9d", "\U0000EA9D"); s.Add("ecac", "\U0000ECAC"); s.Add("ed0b", "\U0000ED0B"); s.Add("e76d", "\U0000E76D"); s.Add("ed42", "\U0000ED42"); s.Add("e875", "\U0000E875"); s.Add("eb0f", "\U0000EB0F"); s.Add("e7df", "\U0000E7DF"); s.Add("eb8d", "\U0000EB8D"); s.Add("e7bd", "\U0000E7BD"); s.Add("ebd1", "\U0000EBD1"); s.Add("eae2", "\U0000EAE2"); s.Add("e7f3", "\U0000E7F3"); s.Add("e863", "\U0000E863"); s.Add("ea68", "\U0000EA68"); s.Add("e995", "\U0000E995"); s.Add("e8ef", "\U0000E8EF"); s.Add("e982", "\U0000E982"); s.Add("e9a4", "\U0000E9A4"); s.Add("ec62", "\U0000EC62"); s.Add("e97d", "\U0000E97D"); s.Add("e836", "\U0000E836"); s.Add("e780", "\U0000E780"); s.Add("e8b0", "\U0000E8B0"); s.Add("ed29", "\U0000ED29"); s.Add("ea64", "\U0000EA64"); s.Add("eab0", "\U0000EAB0"); s.Add("e9be", "\U0000E9BE"); s.Add("e942", "\U0000E942"); s.Add("e9bb", "\U0000E9BB"); s.Add("ec04", "\U0000EC04"); s.Add("ea63", "\U0000EA63"); s.Add("ec7d", "\U0000EC7D"); s.Add("eccc", "\U0000ECCC"); s.Add("e7a2", "\U0000E7A2"); s.Add("e8ff", "\U0000E8FF"); s.Add("ed1a", "\U0000ED1A"); s.Add("e902", "\U0000E902"); s.Add("ebfd", "\U0000EBFD"); s.Add("e8af", "\U0000E8AF"); s.Add("ea14", "\U0000EA14"); s.Add("e96d", "\U0000E96D"); s.Add("ecd4", "\U0000ECD4"); s.Add("e895", "\U0000E895"); s.Add("eb4b", "\U0000EB4B"); s.Add("eb6c", "\U0000EB6C"); s.Add("e7b6", "\U0000E7B6"); s.Add("e749", "\U0000E749"); s.Add("eac1", "\U0000EAC1"); s.Add("eb76", "\U0000EB76"); s.Add("e8f9", "\U0000E8F9"); s.Add("e92b", "\U0000E92B"); s.Add("ecc8", "\U0000ECC8"); s.Add("e8a6", "\U0000E8A6"); s.Add("ea36", "\U0000EA36"); s.Add("e7b1", "\U0000E7B1"); s.Add("e777", "\U0000E777"); s.Add("e935", "\U0000E935"); s.Add("ecc9", "\U0000ECC9"); s.Add("e745", "\U0000E745"); s.Add("e965", "\U0000E965"); s.Add("e966", "\U0000E966"); s.Add("e962", "\U0000E962"); s.Add("e963", "\U0000E963"); s.Add("e831", "\U0000E831"); s.Add("e971", "\U0000E971"); s.Add("e983", "\U0000E983"); s.Add("ec6c", "\U0000EC6C"); s.Add("e7c1", "\U0000E7C1"); s.Add("ec74", "\U0000EC74"); s.Add("ecb2", "\U0000ECB2"); s.Add("e824", "\U0000E824"); s.Add("ebcc", "\U0000EBCC"); s.Add("ecf7", "\U0000ECF7"); s.Add("e970", "\U0000E970"); s.Add("e93a", "\U0000E93A"); s.Add("ec55", "\U0000EC55"); s.Add("e8b8", "\U0000E8B8"); s.Add("e810", "\U0000E810"); s.Add("e878", "\U0000E878"); s.Add("e8d6", "\U0000E8D6"); s.Add("ea39", "\U0000EA39"); s.Add("eacb", "\U0000EACB"); s.Add("e77f", "\U0000E77F"); s.Add("e8cd", "\U0000E8CD"); s.Add("e843", "\U0000E843"); s.Add("ed00", "\U0000ED00"); s.Add("ec3d", "\U0000EC3D"); s.Add("e80d", "\U0000E80D"); s.Add("ebb8", "\U0000EBB8"); s.Add("eb3a", "\U0000EB3A"); s.Add("e76b", "\U0000E76B"); s.Add("ebd2", "\U0000EBD2"); s.Add("e7ca", "\U0000E7CA"); s.Add("e738", "\U0000E738"); s.Add("e99f", "\U0000E99F"); s.Add("ea92", "\U0000EA92"); s.Add("e833", "\U0000E833"); s.Add("e87b", "\U0000E87B"); s.Add("e8aa", "\U0000E8AA"); s.Add("eae0", "\U0000EAE0"); s.Add("ec12", "\U0000EC12"); s.Add("ec8b", "\U0000EC8B"); s.Add("ebd9", "\U0000EBD9"); s.Add("e70f", "\U0000E70F"); s.Add("e8d4", "\U0000E8D4"); s.Add("e8d2", "\U0000E8D2"); s.Add("ec1b", "\U0000EC1B"); s.Add("e969", "\U0000E969"); s.Add("eac7", "\U0000EAC7"); s.Add("ebc9", "\U0000EBC9"); s.Add("eaab", "\U0000EAAB"); s.Add("e9eb", "\U0000E9EB"); s.Add("eb47", "\U0000EB47"); s.Add("e967", "\U0000E967"); s.Add("e7ee", "\U0000E7EE"); s.Add("ec18", "\U0000EC18"); s.Add("eb72", "\U0000EB72"); s.Add("e7a4", "\U0000E7A4"); s.Add("ea5b", "\U0000EA5B"); s.Add("ece8", "\U0000ECE8"); s.Add("eb4d", "\U0000EB4D"); s.Add("eaa9", "\U0000EAA9"); s.Add("e811", "\U0000E811"); s.Add("e808", "\U0000E808"); s.Add("eb51", "\U0000EB51"); s.Add("ec27", "\U0000EC27"); s.Add("ebbb", "\U0000EBBB"); s.Add("ec25", "\U0000EC25"); s.Add("e97a", "\U0000E97A"); s.Add("e739", "\U0000E739"); s.Add("e83a", "\U0000E83A"); s.Add("e919", "\U0000E919"); s.Add("e830", "\U0000E830"); s.Add("e9b0", "\U0000E9B0"); s.Add("e784", "\U0000E784"); s.Add("ea95", "\U0000EA95"); s.Add("e7af", "\U0000E7AF"); s.Add("e7cd", "\U0000E7CD"); s.Add("e7cb", "\U0000E7CB"); s.Add("ea0f", "\U0000EA0F"); s.Add("e89a", "\U0000E89A"); s.Add("e730", "\U0000E730"); s.Add("e79f", "\U0000E79F"); s.Add("e903", "\U0000E903"); s.Add("ecfd", "\U0000ECFD"); s.Add("eb8f", "\U0000EB8F"); s.Add("e7db", "\U0000E7DB"); s.Add("e726", "\U0000E726"); s.Add("ea13", "\U0000EA13"); s.Add("e8b7", "\U0000E8B7"); s.Add("eabc", "\U0000EABC"); s.Add("ea80", "\U0000EA80"); s.Add("e9b2", "\U0000E9B2"); s.Add("e724", "\U0000E724"); s.Add("e973", "\U0000E973"); s.Add("ec13", "\U0000EC13"); s.Add("ea25", "\U0000EA25"); s.Add("e992", "\U0000E992"); s.Add("eab7", "\U0000EAB7"); s.Add("ec2f", "\U0000EC2F"); s.Add("e8b4", "\U0000E8B4"); s.Add("e975", "\U0000E975"); s.Add("ec2d", "\U0000EC2D"); s.Add("e80e", "\U0000E80E"); s.Add("ebed", "\U0000EBED"); s.Add("e8f6", "\U0000E8F6"); s.Add("eb5b", "\U0000EB5B"); s.Add("e850", "\U0000E850"); s.Add("e75c", "\U0000E75C"); s.Add("e822", "\U0000E822"); s.Add("ece2", "\U0000ECE2"); s.Add("eb78", "\U0000EB78"); s.Add("e767", "\U0000E767"); s.Add("ed2b", "\U0000ED2B"); s.Add("e8f8", "\U0000E8F8"); s.Add("eb2a", "\U0000EB2A"); s.Add("eb02", "\U0000EB02"); s.Add("e840", "\U0000E840"); s.Add("e915", "\U0000E915"); s.Add("ebe6", "\U0000EBE6"); s.Add("e90e", "\U0000E90E"); s.Add("e7e0", "\U0000E7E0"); s.Add("e861", "\U0000E861"); s.Add("e91d", "\U0000E91D"); s.Add("e8bf", "\U0000E8BF"); s.Add("ec0a", "\U0000EC0A"); s.Add("e9db", "\U0000E9DB"); s.Add("ebca", "\U0000EBCA"); s.Add("e8be", "\U0000E8BE"); s.Add("ecf1", "\U0000ECF1"); s.Add("e72b", "\U0000E72B"); s.Add("e8d0", "\U0000E8D0"); s.Add("e938", "\U0000E938"); s.Add("ecfa", "\U0000ECFA"); s.Add("e92f", "\U0000E92F"); s.Add("ea81", "\U0000EA81"); s.Add("eb06", "\U0000EB06"); s.Add("e9de", "\U0000E9DE"); s.Add("e9ac", "\U0000E9AC"); s.Add("ebf4", "\U0000EBF4"); s.Add("e9b5", "\U0000E9B5"); s.Add("ec0c", "\U0000EC0C"); s.Add("e7dd", "\U0000E7DD"); s.Add("eb21", "\U0000EB21"); s.Add("ea54", "\U0000EA54"); s.Add("e7e1", "\U0000E7E1"); s.Add("e93b", "\U0000E93B"); s.Add("e792", "\U0000E792"); s.Add("e78d", "\U0000E78D"); s.Add("e988", "\U0000E988"); s.Add("ec14", "\U0000EC14"); s.Add("eab5", "\U0000EAB5"); s.Add("e77e", "\U0000E77E"); s.Add("e7fc", "\U0000E7FC"); s.Add("ea2a", "\U0000EA2A"); s.Add("e80f", "\U0000E80F"); s.Add("e8fa", "\U0000E8FA"); s.Add("eb29", "\U0000EB29"); s.Add("e7a1", "\U0000E7A1"); s.Add("ece4", "\U0000ECE4"); s.Add("ec10", "\U0000EC10"); s.Add("ece3", "\U0000ECE3"); s.Add("e805", "\U0000E805"); s.Add("ecaf", "\U0000ECAF"); s.Add("e80a", "\U0000E80A"); s.Add("e91b", "\U0000E91B"); s.Add("e921", "\U0000E921"); s.Add("e8da", "\U0000E8DA"); s.Add("ebb6", "\U0000EBB6"); s.Add("ec63", "\U0000EC63"); s.Add("e987", "\U0000E987"); s.Add("e8b5", "\U0000E8B5"); s.Add("e800", "\U0000E800"); s.Add("e8ae", "\U0000E8AE"); s.Add("ea15", "\U0000EA15"); s.Add("e73a", "\U0000E73A"); s.Add("ebd3", "\U0000EBD3"); s.Add("eaac", "\U0000EAAC"); s.Add("e7c2", "\U0000E7C2"); s.Add("ea0e", "\U0000EA0E"); s.Add("e837", "\U0000E837"); s.Add("ed44", "\U0000ED44"); s.Add("ea57", "\U0000EA57"); s.Add("e9e7", "\U0000E9E7"); s.Add("ecd2", "\U0000ECD2"); s.Add("ea43", "\U0000EA43"); s.Add("e793", "\U0000E793"); s.Add("ebda", "\U0000EBDA"); s.Add("e90a", "\U0000E90A"); s.Add("eb30", "\U0000EB30"); s.Add("ecbe", "\U0000ECBE"); s.Add("ec85", "\U0000EC85"); s.Add("e930", "\U0000E930"); s.Add("e7e2", "\U0000E7E2"); s.Add("e74d", "\U0000E74D"); s.Add("ec2c", "\U0000EC2C"); s.Add("e9a2", "\U0000E9A2"); s.Add("eca9", "\U0000ECA9"); s.Add("e9cc", "\U0000E9CC"); s.Add("e78f", "\U0000E78F"); s.Add("e827", "\U0000E827"); s.Add("ebab", "\U0000EBAB"); s.Add("e82e", "\U0000E82E"); s.Add("ebe0", "\U0000EBE0"); s.Add("ec4f", "\U0000EC4F"); s.Add("e782", "\U0000E782"); s.Add("e961", "\U0000E961"); s.Add("ea59", "\U0000EA59"); s.Add("ea26", "\U0000EA26"); s.Add("ec90", "\U0000EC90"); s.Add("e8f7", "\U0000E8F7"); s.Add("e8d9", "\U0000E8D9"); s.Add("e834", "\U0000E834"); s.Add("ea9f", "\U0000EA9F"); s.Add("ecff", "\U0000ECFF"); s.Add("e964", "\U0000E964"); s.Add("e8b2", "\U0000E8B2"); s.Add("e71d", "\U0000E71D"); s.Add("ed02", "\U0000ED02"); s.Add("ecbd", "\U0000ECBD"); s.Add("eae4", "\U0000EAE4"); s.Add("ecbc", "\U0000ECBC"); s.Add("e825", "\U0000E825"); s.Add("ed01", "\U0000ED01"); s.Add("ec00", "\U0000EC00"); s.Add("e8c4", "\U0000E8C4"); s.Add("e89e", "\U0000E89E"); s.Add("ec11", "\U0000EC11"); s.Add("ea55", "\U0000EA55"); s.Add("ea9e", "\U0000EA9E"); s.Add("ec57", "\U0000EC57"); s.Add("e8bc", "\U0000E8BC"); s.Add("ea0a", "\U0000EA0A"); s.Add("e789", "\U0000E789"); s.Add("e79b", "\U0000E79B"); s.Add("e851", "\U0000E851"); s.Add("eadc", "\U0000EADC"); s.Add("e90c", "\U0000E90C"); s.Add("e7d9", "\U0000E7D9"); s.Add("ec3c", "\U0000EC3C"); s.Add("e8d1", "\U0000E8D1"); s.Add("e771", "\U0000E771"); s.Add("e865", "\U0000E865"); s.Add("ed3d", "\U0000ED3D"); s.Add("ea51", "\U0000EA51"); s.Add("ecd0", "\U0000ECD0"); s.Add("ec42", "\U0000EC42"); s.Add("e894", "\U0000E894"); s.Add("eaa2", "\U0000EAA2"); s.Add("e7de", "\U0000E7DE"); s.Add("e7ec", "\U0000E7EC"); s.Add("ec17", "\U0000EC17"); s.Add("e985", "\U0000E985"); s.Add("e852", "\U0000E852"); s.Add("ecf8", "\U0000ECF8"); s.Add("eacc", "\U0000EACC"); s.Add("e812", "\U0000E812"); s.Add("eb1c", "\U0000EB1C"); s.Add("ea9b", "\U0000EA9B"); s.Add("e8c8", "\U0000E8C8"); s.Add("e82d", "\U0000E82D"); s.Add("e974", "\U0000E974"); s.Add("ed03", "\U0000ED03"); s.Add("e785", "\U0000E785"); s.Add("ea6a", "\U0000EA6A"); s.Add("ea41", "\U0000EA41"); s.Add("e705", "\U0000E705"); s.Add("ead1", "\U0000EAD1"); s.Add("eb7d", "\U0000EB7D"); s.Add("e98c", "\U0000E98C"); s.Add("e7bf", "\U0000E7BF"); s.Add("e968", "\U0000E968"); s.Add("ea10", "\U0000EA10"); s.Add("e874", "\U0000E874"); s.Add("ea35", "\U0000EA35"); s.Add("e737", "\U0000E737"); s.Add("eb05", "\U0000EB05"); s.Add("e934", "\U0000E934"); s.Add("e7d8", "\U0000E7D8"); s.Add("e727", "\U0000E727"); s.Add("eccb", "\U0000ECCB"); s.Add("eb34", "\U0000EB34"); s.Add("ea99", "\U0000EA99"); s.Add("e8a1", "\U0000E8A1"); s.Add("eb31", "\U0000EB31"); s.Add("e87d", "\U0000E87D"); s.Add("ebc6", "\U0000EBC6"); s.Add("e908", "\U0000E908"); s.Add("ec6b", "\U0000EC6B"); s.Add("e929", "\U0000E929"); s.Add("e807", "\U0000E807"); s.Add("e9a8", "\U0000E9A8"); s.Add("eaaa", "\U0000EAAA"); s.Add("eb37", "\U0000EB37"); s.Add("e97c", "\U0000E97C"); s.Add("eb91", "\U0000EB91"); s.Add("ec51", "\U0000EC51"); s.Add("ebaf", "\U0000EBAF"); s.Add("ea8b", "\U0000EA8B"); s.Add("e913", "\U0000E913"); s.Add("eb6f", "\U0000EB6F"); s.Add("e933", "\U0000E933"); s.Add("e712", "\U0000E712"); s.Add("eb5a", "\U0000EB5A"); s.Add("e9a3", "\U0000E9A3"); s.Add("ebe4", "\U0000EBE4"); s.Add("ea49", "\U0000EA49"); s.Add("ea37", "\U0000EA37"); s.Add("eaf9", "\U0000EAF9"); s.Add("ec77", "\U0000EC77"); s.Add("eaa0", "\U0000EAA0"); s.Add("e87a", "\U0000E87A"); s.Add("e704", "\U0000E704"); s.Add("e870", "\U0000E870"); s.Add("e8a2", "\U0000E8A2"); s.Add("e8f1", "\U0000E8F1"); s.Add("e821", "\U0000E821"); s.Add("e82c", "\U0000E82C"); s.Add("ed2a", "\U0000ED2A"); s.Add("eb17", "\U0000EB17"); s.Add("eaa3", "\U0000EAA3"); s.Add("ebcf", "\U0000EBCF"); s.Add("e775", "\U0000E775"); s.Add("e85d", "\U0000E85D"); s.Add("e781", "\U0000E781"); s.Add("e73e", "\U0000E73E"); s.Add("e8f2", "\U0000E8F2"); s.Add("eb73", "\U0000EB73"); s.Add("e722", "\U0000E722"); s.Add("ea9a", "\U0000EA9A"); s.Add("e797", "\U0000E797"); s.Add("e9e9", "\U0000E9E9"); s.Add("ec50", "\U0000EC50"); s.Add("ecf5", "\U0000ECF5"); s.Add("eaa1", "\U0000EAA1"); s.Add("e9c5", "\U0000E9C5"); s.Add("ea29", "\U0000EA29"); s.Add("eba3", "\U0000EBA3"); s.Add("eada", "\U0000EADA"); s.Add("ec60", "\U0000EC60"); s.Add("eabe", "\U0000EABE"); s.Add("eabd", "\U0000EABD"); s.Add("ec9a", "\U0000EC9A"); s.Add("e7a0", "\U0000E7A0"); s.Add("e904", "\U0000E904"); s.Add("e9dc", "\U0000E9DC"); s.Add("ec06", "\U0000EC06"); s.Add("e70c", "\U0000E70C"); s.Add("ed20", "\U0000ED20"); s.Add("ec40", "\U0000EC40"); s.Add("e93c", "\U0000E93C"); s.Add("e9b1", "\U0000E9B1"); s.Add("eb60", "\U0000EB60"); s.Add("eca7", "\U0000ECA7"); s.Add("e74b", "\U0000E74B"); s.Add("ea9c", "\U0000EA9C"); s.Add("e828", "\U0000E828"); s.Add("e87e", "\U0000E87E"); s.Add("ea88", "\U0000EA88"); s.Add("eb03", "\U0000EB03"); s.Add("e7d7", "\U0000E7D7"); s.Add("e8f5", "\U0000E8F5"); s.Add("e96b", "\U0000E96B"); s.Add("e79a", "\U0000E79A"); s.Add("ea47", "\U0000EA47"); s.Add("ed2f", "\U0000ED2F"); s.Add("e8c5", "\U0000E8C5"); s.Add("ea69", "\U0000EA69"); s.Add("e98b", "\U0000E98B"); s.Add("eb62", "\U0000EB62"); s.Add("e98e", "\U0000E98E"); s.Add("eac0", "\U0000EAC0"); s.Add("e9ef", "\U0000E9EF"); s.Add("ea4a", "\U0000EA4A"); s.Add("e8fb", "\U0000E8FB"); s.Add("ecf3", "\U0000ECF3"); s.Add("ecca", "\U0000ECCA"); s.Add("ec36", "\U0000EC36"); s.Add("eb45", "\U0000EB45"); s.Add("e97f", "\U0000E97F"); s.Add("ed3e", "\U0000ED3E"); s.Add("e754", "\U0000E754"); s.Add("ec44", "\U0000EC44"); s.Add("e981", "\U0000E981"); s.Add("eb43", "\U0000EB43"); s.Add("e979", "\U0000E979"); s.Add("ecfc", "\U0000ECFC"); s.Add("eb9e", "\U0000EB9E"); s.Add("eac9", "\U0000EAC9"); s.Add("ed1b", "\U0000ED1B"); s.Add("e854", "\U0000E854"); s.Add("ea3b", "\U0000EA3B"); s.Add("ece6", "\U0000ECE6"); s.Add("e85c", "\U0000E85C"); s.Add("e917", "\U0000E917"); s.Add("ecef", "\U0000ECEF"); s.Add("e7e9", "\U0000E7E9"); s.Add("eb3b", "\U0000EB3B"); s.Add("e759", "\U0000E759"); s.Add("ed41", "\U0000ED41"); s.Add("ec83", "\U0000EC83"); s.Add("eaea", "\U0000EAEA"); s.Add("e7c4", "\U0000E7C4"); s.Add("ecb3", "\U0000ECB3"); s.Add("ec3a", "\U0000EC3A"); s.Add("e9b9", "\U0000E9B9"); s.Add("ecfe", "\U0000ECFE"); s.Add("e85a", "\U0000E85A"); s.Add("ebcb", "\U0000EBCB"); s.Add("ed33", "\U0000ED33"); s.Add("e80b", "\U0000E80B"); s.Add("e8bb", "\U0000E8BB"); s.Add("ed2c", "\U0000ED2C"); s.Add("e923", "\U0000E923"); s.Add("ec09", "\U0000EC09"); s.Add("ecd8", "\U0000ECD8"); s.Add("e9b3", "\U0000E9B3"); s.Add("ea96", "\U0000EA96"); s.Add("ec0f", "\U0000EC0F"); s.Add("eb9f", "\U0000EB9F"); s.Add("e932", "\U0000E932"); s.Add("e978", "\U0000E978"); s.Add("ea7f", "\U0000EA7F"); s.Add("ed04", "\U0000ED04"); s.Add("ebcd", "\U0000EBCD"); s.Add("e832", "\U0000E832"); s.Add("eb71", "\U0000EB71"); s.Add("e86b", "\U0000E86B"); s.Add("e99e", "\U0000E99E"); s.Add("e96c", "\U0000E96C"); s.Add("ea87", "\U0000EA87"); s.Add("e77c", "\U0000E77C"); s.Add("e7ea", "\U0000E7EA"); s.Add("ec1a", "\U0000EC1A"); s.Add("e8fc", "\U0000E8FC"); s.Add("e7dc", "\U0000E7DC"); s.Add("ecd3", "\U0000ECD3"); s.Add("ecf0", "\U0000ECF0"); s.Add("ec31", "\U0000EC31"); s.Add("ebc7", "\U0000EBC7"); s.Add("eaaf", "\U0000EAAF"); s.Add("e84d", "\U0000E84D"); s.Add("ea31", "\U0000EA31"); s.Add("ecbb", "\U0000ECBB"); s.Add("ea7b", "\U0000EA7B"); s.Add("e82b", "\U0000E82B"); s.Add("e901", "\U0000E901"); s.Add("e9c4", "\U0000E9C4"); s.Add("e898", "\U0000E898"); s.Add("e813", "\U0000E813"); s.Add("e945", "\U0000E945"); s.Add("ecd5", "\U0000ECD5"); s.Add("eba5", "\U0000EBA5"); s.Add("e926", "\U0000E926"); s.Add("ebba", "\U0000EBBA"); s.Add("e8fe", "\U0000E8FE"); s.Add("e7ad", "\U0000E7AD"); s.Add("e8fd", "\U0000E8FD"); s.Add("ec88", "\U0000EC88"); s.Add("e912", "\U0000E912"); s.Add("e70d", "\U0000E70D"); s.Add("ea11", "\U0000EA11"); s.Add("eb4f", "\U0000EB4F"); s.Add("ea17", "\U0000EA17"); s.Add("ed30", "\U0000ED30"); s.Add("e7f8", "\U0000E7F8"); s.Add("e728", "\U0000E728"); s.Add("e8a0", "\U0000E8A0"); s.Add("ed2e", "\U0000ED2E"); s.Add("e76f", "\U0000E76F"); s.Add("ecb4", "\U0000ECB4"); s.Add("ea4f", "\U0000EA4F"); s.Add("e97e", "\U0000E97E"); s.Add("ed3c", "\U0000ED3C"); s.Add("eae6", "\U0000EAE6"); s.Add("e853", "\U0000E853"); s.Add("ec37", "\U0000EC37"); s.Add("e844", "\U0000E844"); s.Add("e711", "\U0000E711"); s.Add("e900", "\U0000E900"); s.Add("ec15", "\U0000EC15"); s.Add("eb16", "\U0000EB16"); s.Add("e750", "\U0000E750"); s.Add("e96a", "\U0000E96A"); s.Add("e95c", "\U0000E95C"); s.Add("e95d", "\U0000E95D"); s.Add("e95e", "\U0000E95E"); s.Add("e95f", "\U0000E95F"); s.Add("e960", "\U0000E960"); s.Add("e860", "\U0000E860"); s.Add("ea21", "\U0000EA21"); s.Add("ebe2", "\U0000EBE2"); s.Add("e741", "\U0000E741"); s.Add("e931", "\U0000E931"); s.Add("eba2", "\U0000EBA2"); s.Add("e783", "\U0000E783"); s.Add("ecfb", "\U0000ECFB"); s.Add("ec30", "\U0000EC30"); s.Add("ea4d", "\U0000EA4D"); s.Add("e71f", "\U0000E71F"); s.Add("ebc8", "\U0000EBC8"); s.Add("ec2e", "\U0000EC2E"); s.Add("ecf9", "\U0000ECF9"); s.Add("eb8b", "\U0000EB8B"); s.Add("eb00", "\U0000EB00"); s.Add("eaf3", "\U0000EAF3"); s.Add("eaeb", "\U0000EAEB"); s.Add("e809", "\U0000E809"); s.Add("e773", "\U0000E773"); s.Add("eb3c", "\U0000EB3C"); s.Add("e905", "\U0000E905"); s.Add("ead8", "\U0000EAD8"); s.Add("ec16", "\U0000EC16"); s.Add("ea45", "\U0000EA45"); s.Add("e8a7", "\U0000E8A7"); s.Add("ecb5", "\U0000ECB5"); s.Add("ece9", "\U0000ECE9"); s.Add("ed36", "\U0000ED36"); s.Add("e911", "\U0000E911"); s.Add("e702", "\U0000E702"); s.Add("eb01", "\U0000EB01"); s.Add("e9f3", "\U0000E9F3"); s.Add("ed3b", "\U0000ED3B"); s.Add("e9f5", "\U0000E9F5"); s.Add("e9f4", "\U0000E9F4"); s.Add("e9f7", "\U0000E9F7"); s.Add("e9f6", "\U0000E9F6"); s.Add("e9f9", "\U0000E9F9"); s.Add("e9f8", "\U0000E9F8"); s.Add("ea12", "\U0000EA12"); s.Add("e9f2", "\U0000E9F2"); s.Add("e907", "\U0000E907"); s.Add("eca3", "\U0000ECA3"); s.Add("ec0e", "\U0000EC0E"); s.Add("e972", "\U0000E972"); s.Add("eace", "\U0000EACE"); s.Add("eade", "\U0000EADE"); s.Add("e977", "\U0000E977"); s.Add("ea40", "\U0000EA40"); s.Add("eb1e", "\U0000EB1E"); s.Add("e89d", "\U0000E89D"); s.Add("ead6", "\U0000EAD6"); s.Add("e7a3", "\U0000E7A3"); s.Add("ea73", "\U0000EA73"); s.Add("eccf", "\U0000ECCF"); s.Add("ea65", "\U0000EA65"); s.Add("e760", "\U0000E760"); s.Add("e9c7", "\U0000E9C7"); s.Add("eab8", "\U0000EAB8"); s.Add("e8cb", "\U0000E8CB"); s.Add("ec81", "\U0000EC81"); s.Add("e9da", "\U0000E9DA"); s.Add("ed17", "\U0000ED17"); s.Add("ea16", "\U0000EA16"); s.Add("ea67", "\U0000EA67"); s.Add("ebce", "\U0000EBCE"); s.Add("e991", "\U0000E991"); s.Add("e7b5", "\U0000E7B5"); s.Add("ebfc", "\U0000EBFC"); s.Add("ebfb", "\U0000EBFB"); s.Add("e939", "\U0000E939"); s.Add("ebd7", "\U0000EBD7"); s.Add("ebd6", "\U0000EBD6"); s.Add("e838", "\U0000E838"); s.Add("ebd8", "\U0000EBD8"); s.Add("eac5", "\U0000EAC5"); s.Add("ec96", "\U0000EC96"); s.Add("e856", "\U0000E856"); s.Add("e758", "\U0000E758"); s.Add("ebdb", "\U0000EBDB"); s.Add("e7b3", "\U0000E7B3"); s.Add("e999", "\U0000E999"); s.Add("ea8c", "\U0000EA8C"); s.Add("ea8e", "\U0000EA8E"); s.Add("e998", "\U0000E998"); s.Add("eb57", "\U0000EB57"); s.Add("ea6b", "\U0000EA6B"); s.Add("ea77", "\U0000EA77"); s.Add("e99b", "\U0000E99B"); s.Add("ea7a", "\U0000EA7A"); s.Add("ea6c", "\U0000EA6C"); s.Add("ebec", "\U0000EBEC"); s.Add("ea85", "\U0000EA85"); s.Add("ea83", "\U0000EA83"); s.Add("ea78", "\U0000EA78"); s.Add("ea79", "\U0000EA79"); s.Add("ea84", "\U0000EA84"); s.Add("ea7c", "\U0000EA7C"); s.Add("e99c", "\U0000E99C"); s.Add("ea93", "\U0000EA93"); s.Add("ea89", "\U0000EA89"); s.Add("eb79", "\U0000EB79"); s.Add("eb97", "\U0000EB97"); s.Add("e71b", "\U0000E71B"); s.Add("e9f1", "\U0000E9F1"); s.Add("eb19", "\U0000EB19"); s.Add("e7e3", "\U0000E7E3"); s.Add("ebe9", "\U0000EBE9"); s.Add("e9d2", "\U0000E9D2"); s.Add("eb1b", "\U0000EB1B"); s.Add("ec6f", "\U0000EC6F"); s.Add("e9e4", "\U0000E9E4"); s.Add("eb0e", "\U0000EB0E"); s.Add("ebc5", "\U0000EBC5"); s.Add("e70b", "\U0000E70B"); s.Add("eb1a", "\U0000EB1A"); s.Add("ea62", "\U0000EA62"); s.Add("eb96", "\U0000EB96"); s.Add("ea2f", "\U0000EA2F"); s.Add("e714", "\U0000E714"); s.Add("ea09", "\U0000EA09"); s.Add("e7e8", "\U0000E7E8"); s.Add("e70a", "\U0000E70A"); s.Add("ebde", "\U0000EBDE"); s.Add("e719", "\U0000E719"); s.Add("e9e2", "\U0000E9E2"); s.Add("e9d4", "\U0000E9D4"); s.Add("ebbf", "\U0000EBBF"); s.Add("e7f1", "\U0000E7F1"); s.Add("e756", "\U0000E756"); s.Add("ebb9", "\U0000EBB9"); s.Add("ea0d", "\U0000EA0D"); s.Add("ecc0", "\U0000ECC0"); s.Add("e9d0", "\U0000E9D0"); s.Add("eb89", "\U0000EB89"); s.Add("e86a", "\U0000E86A"); s.Add("eb80", "\U0000EB80"); s.Add("e9e1", "\U0000E9E1"); s.Add("ebdf", "\U0000EBDF"); s.Add("e9d7", "\U0000E9D7"); s.Add("e717", "\U0000E717"); s.Add("ebbe", "\U0000EBBE"); s.Add("ebea", "\U0000EBEA"); s.Add("ebeb", "\U0000EBEB"); s.Add("ec58", "\U0000EC58"); s.Add("eb13", "\U0000EB13"); s.Add("eb14", "\U0000EB14"); s.Add("eb12", "\U0000EB12"); s.Add("e9e0", "\U0000E9E0"); s.Add("e86d", "\U0000E86D"); s.Add("eb88", "\U0000EB88"); s.Add("e997", "\U0000E997"); s.Add("eb18", "\U0000EB18"); s.Add("e9cb", "\U0000E9CB"); s.Add("e9fc", "\U0000E9FC"); s.Add("ea07", "\U0000EA07"); s.Add("ec34", "\U0000EC34"); s.Add("e866", "\U0000E866"); s.Add("ebf0", "\U0000EBF0"); s.Add("ea2e", "\U0000EA2E"); s.Add("ec33", "\U0000EC33"); s.Add("e7e5", "\U0000E7E5"); s.Add("e9d9", "\U0000E9D9"); s.Add("ebc0", "\U0000EBC0"); s.Add("eb09", "\U0000EB09"); s.Add("ec48", "\U0000EC48"); s.Add("e86f", "\U0000E86F"); s.Add("e708", "\U0000E708"); s.Add("e9e3", "\U0000E9E3"); s.Add("e795", "\U0000E795"); s.Add("ec02", "\U0000EC02"); s.Add("e846", "\U0000E846"); s.Add("e7e4", "\U0000E7E4"); s.Add("e9c8", "\U0000E9C8"); s.Add("eb2c", "\U0000EB2C"); s.Add("ea08", "\U0000EA08"); s.Add("ec5b", "\U0000EC5B"); s.Add("e9fa", "\U0000E9FA"); s.Add("e9d8", "\U0000E9D8"); s.Add("e9d3", "\U0000E9D3"); s.Add("eb2b", "\U0000EB2B"); s.Add("ebf8", "\U0000EBF8"); s.Add("e74c", "\U0000E74C"); s.Add("e845", "\U0000E845"); s.Add("e72f", "\U0000E72F"); s.Add("ea2d", "\U0000EA2D"); s.Add("ec5a", "\U0000EC5A"); s.Add("ec32", "\U0000EC32"); s.Add("e7fe", "\U0000E7FE"); s.Add("e86e", "\U0000E86E"); s.Add("e74f", "\U0000E74F"); s.Add("ec72", "\U0000EC72"); s.Add("e9d6", "\U0000E9D6"); s.Add("e71a", "\U0000E71A"); s.Add("eb95", "\U0000EB95"); s.Add("e9c6", "\U0000E9C6"); s.Add("e71c", "\U0000E71C"); s.Add("eb15", "\U0000EB15"); s.Add("ebf7", "\U0000EBF7"); s.Add("ec5d", "\U0000EC5D"); s.Add("ebf1", "\U0000EBF1"); s.Add("eb82", "\U0000EB82"); s.Add("e9d5", "\U0000E9D5"); s.Add("ea30", "\U0000EA30"); s.Add("e718", "\U0000E718"); s.Add("e8c2", "\U0000E8C2"); s.Add("e98d", "\U0000E98D"); s.Add("eb81", "\U0000EB81"); s.Add("ec35", "\U0000EC35"); s.Add("eb0d", "\U0000EB0D"); s.Add("e7e7", "\U0000E7E7"); s.Add("e716", "\U0000E716"); s.Add("eb11", "\U0000EB11"); s.Add("e996", "\U0000E996"); s.Add("ec01", "\U0000EC01"); s.Add("ebc4", "\U0000EBC4"); s.Add("e715", "\U0000E715"); s.Add("e83e", "\U0000E83E"); s.Add("e876", "\U0000E876"); s.Add("e879", "\U0000E879"); s.Add("ec03", "\U0000EC03"); s.Add("e83f", "\U0000E83F"); s.Add("ec70", "\U0000EC70"); s.Add("ebc2", "\U0000EBC2"); s.Add("ebf6", "\U0000EBF6"); s.Add("ec6a", "\U0000EC6A"); s.Add("e9d1", "\U0000E9D1"); s.Add("ec71", "\U0000EC71"); s.Add("e794", "\U0000E794"); s.Add("ec5e", "\U0000EC5E"); s.Add("e86c", "\U0000E86C"); s.Add("ec5f", "\U0000EC5F"); s.Add("e7f2", "\U0000E7F2"); s.Add("e7e6", "\U0000E7E6"); s.Add("ebf9", "\U0000EBF9"); s.Add("ebfa", "\U0000EBFA"); s.Add("e83d", "\U0000E83D"); s.Add("ec5c", "\U0000EC5C"); s.Add("e709", "\U0000E709"); s.Add("ec59", "\U0000EC59"); s.Add("ebdd", "\U0000EBDD"); s.Add("eb7a", "\U0000EB7A"); s.Add("e9fb", "\U0000E9FB"); s.Add("e7ff", "\U0000E7FF"); s.Add("edec", "\U0000EDEC"); s.Add("ee3a", "\U0000EE3A"); s.Add("ed80", "\U0000ED80"); s.Add("edb4", "\U0000EDB4"); s.Add("eddd", "\U0000EDDD"); s.Add("ed97", "\U0000ED97"); s.Add("ed5e", "\U0000ED5E"); s.Add("edcd", "\U0000EDCD"); s.Add("ee28", "\U0000EE28"); s.Add("ed57", "\U0000ED57"); s.Add("ed55", "\U0000ED55"); s.Add("edeb", "\U0000EDEB"); s.Add("edba", "\U0000EDBA"); s.Add("ed8b", "\U0000ED8B"); s.Add("ed7f", "\U0000ED7F"); s.Add("edff", "\U0000EDFF"); s.Add("edb3", "\U0000EDB3"); s.Add("ee0d", "\U0000EE0D"); s.Add("edab", "\U0000EDAB"); s.Add("edea", "\U0000EDEA"); s.Add("ed9d", "\U0000ED9D"); s.Add("ed5c", "\U0000ED5C"); s.Add("ed9f", "\U0000ED9F"); s.Add("ed6f", "\U0000ED6F"); s.Add("edf7", "\U0000EDF7"); s.Add("edc9", "\U0000EDC9"); s.Add("ee1c", "\U0000EE1C"); s.Add("edac", "\U0000EDAC"); s.Add("ede3", "\U0000EDE3"); s.Add("ee30", "\U0000EE30"); s.Add("ed8c", "\U0000ED8C"); s.Add("ed8d", "\U0000ED8D"); s.Add("eda9", "\U0000EDA9"); s.Add("ed82", "\U0000ED82"); s.Add("edca", "\U0000EDCA"); s.Add("edc1", "\U0000EDC1"); s.Add("ee3c", "\U0000EE3C"); s.Add("ee36", "\U0000EE36"); s.Add("ee3b", "\U0000EE3B"); s.Add("ed88", "\U0000ED88"); s.Add("ed87", "\U0000ED87"); s.Add("ed7d", "\U0000ED7D"); s.Add("ed86", "\U0000ED86"); s.Add("edf6", "\U0000EDF6"); s.Add("ee14", "\U0000EE14"); s.Add("edf5", "\U0000EDF5"); s.Add("edd1", "\U0000EDD1"); s.Add("ee23", "\U0000EE23"); s.Add("ee34", "\U0000EE34"); s.Add("ee39", "\U0000EE39"); s.Add("ee46", "\U0000EE46"); s.Add("ed51", "\U0000ED51"); s.Add("ee37", "\U0000EE37"); s.Add("ed85", "\U0000ED85"); s.Add("ede5", "\U0000EDE5"); s.Add("ede6", "\U0000EDE6"); s.Add("ed9a", "\U0000ED9A"); s.Add("ee1e", "\U0000EE1E"); s.Add("ee20", "\U0000EE20"); s.Add("edd6", "\U0000EDD6"); s.Add("ed4f", "\U0000ED4F"); s.Add("ed98", "\U0000ED98"); s.Add("edf4", "\U0000EDF4"); s.Add("ed92", "\U0000ED92"); s.Add("ee17", "\U0000EE17"); s.Add("edc7", "\U0000EDC7"); s.Add("edce", "\U0000EDCE"); s.Add("ede8", "\U0000EDE8"); s.Add("edc2", "\U0000EDC2"); s.Add("ee40", "\U0000EE40"); s.Add("ed47", "\U0000ED47"); s.Add("ed49", "\U0000ED49"); s.Add("ede2", "\U0000EDE2"); s.Add("ede0", "\U0000EDE0"); s.Add("ed99", "\U0000ED99"); s.Add("eda7", "\U0000EDA7"); s.Add("edbb", "\U0000EDBB"); s.Add("edb6", "\U0000EDB6"); s.Add("edd3", "\U0000EDD3"); s.Add("ed59", "\U0000ED59"); s.Add("edd4", "\U0000EDD4"); s.Add("ee3d", "\U0000EE3D"); s.Add("ed90", "\U0000ED90"); s.Add("ee2f", "\U0000EE2F"); s.Add("ed6b", "\U0000ED6B"); s.Add("ed96", "\U0000ED96"); s.Add("ee02", "\U0000EE02"); s.Add("ee31", "\U0000EE31"); s.Add("edc4", "\U0000EDC4"); s.Add("ed53", "\U0000ED53"); s.Add("ed76", "\U0000ED76"); s.Add("edb1", "\U0000EDB1"); s.Add("ede4", "\U0000EDE4"); s.Add("ed64", "\U0000ED64"); s.Add("ed70", "\U0000ED70"); s.Add("ed6e", "\U0000ED6E"); s.Add("edd7", "\U0000EDD7"); s.Add("edcc", "\U0000EDCC"); s.Add("edd9", "\U0000EDD9"); s.Add("ed74", "\U0000ED74"); s.Add("edd8", "\U0000EDD8"); s.Add("edc5", "\U0000EDC5"); s.Add("eda0", "\U0000EDA0"); s.Add("eda5", "\U0000EDA5"); s.Add("eda8", "\U0000EDA8"); s.Add("ee2d", "\U0000EE2D"); s.Add("edfe", "\U0000EDFE"); s.Add("edcf", "\U0000EDCF"); s.Add("ed7a", "\U0000ED7A"); s.Add("ee3f", "\U0000EE3F"); s.Add("ed79", "\U0000ED79"); s.Add("ee19", "\U0000EE19"); s.Add("ee33", "\U0000EE33"); s.Add("ed84", "\U0000ED84"); s.Add("ed56", "\U0000ED56"); s.Add("ed95", "\U0000ED95"); s.Add("ee0f", "\U0000EE0F"); s.Add("ee1b", "\U0000EE1B"); s.Add("edfa", "\U0000EDFA"); s.Add("ee38", "\U0000EE38"); s.Add("ede9", "\U0000EDE9"); s.Add("ed4d", "\U0000ED4D"); s.Add("ee07", "\U0000EE07"); s.Add("edbe", "\U0000EDBE"); s.Add("edf9", "\U0000EDF9"); s.Add("edd2", "\U0000EDD2"); s.Add("edc8", "\U0000EDC8"); s.Add("ee22", "\U0000EE22"); s.Add("eda4", "\U0000EDA4"); s.Add("edcb", "\U0000EDCB"); s.Add("ee47", "\U0000EE47"); s.Add("edd0", "\U0000EDD0"); s.Add("ee15", "\U0000EE15"); s.Add("ed94", "\U0000ED94"); s.Add("ed62", "\U0000ED62"); s.Add("ee11", "\U0000EE11"); s.Add("eda1", "\U0000EDA1"); s.Add("ee45", "\U0000EE45"); s.Add("ee0c", "\U0000EE0C"); s.Add("ee05", "\U0000EE05"); s.Add("edaf", "\U0000EDAF"); s.Add("edae", "\U0000EDAE"); s.Add("ee26", "\U0000EE26"); s.Add("ee29", "\U0000EE29"); s.Add("ed4b", "\U0000ED4B"); s.Add("ee01", "\U0000EE01"); s.Add("ed7e", "\U0000ED7E"); s.Add("ed6c", "\U0000ED6C"); s.Add("ed60", "\U0000ED60"); s.Add("eddb", "\U0000EDDB"); s.Add("ed8a", "\U0000ED8A"); s.Add("edbf", "\U0000EDBF"); s.Add("edb2", "\U0000EDB2"); s.Add("ed6d", "\U0000ED6D"); s.Add("ee0e", "\U0000EE0E"); s.Add("eddc", "\U0000EDDC"); s.Add("ee21", "\U0000EE21"); s.Add("eda6", "\U0000EDA6"); s.Add("ee2c", "\U0000EE2C"); s.Add("ed78", "\U0000ED78"); s.Add("ee10", "\U0000EE10"); s.Add("ee49", "\U0000EE49"); s.Add("edde", "\U0000EDDE"); s.Add("ed65", "\U0000ED65"); s.Add("ed61", "\U0000ED61"); s.Add("ee09", "\U0000EE09"); s.Add("ed73", "\U0000ED73"); s.Add("ee2e", "\U0000EE2E"); s.Add("ed9c", "\U0000ED9C"); s.Add("ee3e", "\U0000EE3E"); s.Add("ede7", "\U0000EDE7"); s.Add("ed7b", "\U0000ED7B"); s.Add("edf0", "\U0000EDF0"); s.Add("eda2", "\U0000EDA2"); s.Add("edd5", "\U0000EDD5"); s.Add("ee2a", "\U0000EE2A"); s.Add("ed77", "\U0000ED77"); s.Add("ede1", "\U0000EDE1"); s.Add("ed63", "\U0000ED63"); s.Add("ee16", "\U0000EE16"); s.Add("ee0b", "\U0000EE0B"); s.Add("edaa", "\U0000EDAA"); s.Add("edbc", "\U0000EDBC"); s.Add("ed50", "\U0000ED50"); s.Add("edf3", "\U0000EDF3"); s.Add("ed5a", "\U0000ED5A"); s.Add("ee48", "\U0000EE48"); s.Add("ed9e", "\U0000ED9E"); s.Add("edf8", "\U0000EDF8"); s.Add("ee12", "\U0000EE12"); s.Add("edef", "\U0000EDEF"); s.Add("ee1d", "\U0000EE1D"); s.Add("ed75", "\U0000ED75"); s.Add("ed54", "\U0000ED54"); s.Add("ed71", "\U0000ED71"); s.Add("ee00", "\U0000EE00"); s.Add("edc3", "\U0000EDC3"); s.Add("ed9b", "\U0000ED9B"); s.Add("ee1f", "\U0000EE1F"); s.Add("ed91", "\U0000ED91"); s.Add("ed69", "\U0000ED69"); s.Add("ed58", "\U0000ED58"); s.Add("edda", "\U0000EDDA"); s.Add("edfb", "\U0000EDFB"); s.Add("edbd", "\U0000EDBD"); s.Add("edad", "\U0000EDAD"); s.Add("ee08", "\U0000EE08"); s.Add("ee18", "\U0000EE18"); s.Add("ee44", "\U0000EE44"); s.Add("ed83", "\U0000ED83"); s.Add("ed4a", "\U0000ED4A"); s.Add("ee0a", "\U0000EE0A"); s.Add("ed4c", "\U0000ED4C"); s.Add("ed5f", "\U0000ED5F"); s.Add("ed4e", "\U0000ED4E"); s.Add("edf2", "\U0000EDF2"); s.Add("ed93", "\U0000ED93"); s.Add("edee", "\U0000EDEE"); s.Add("ed89", "\U0000ED89"); s.Add("ed6a", "\U0000ED6A"); s.Add("ed7c", "\U0000ED7C"); s.Add("ed5b", "\U0000ED5B"); s.Add("ed48", "\U0000ED48"); s.Add("ee25", "\U0000EE25"); s.Add("edb0", "\U0000EDB0"); s.Add("ed8f", "\U0000ED8F"); s.Add("ed8e", "\U0000ED8E"); s.Add("edc6", "\U0000EDC6"); s.Add("ee35", "\U0000EE35"); s.Add("eda3", "\U0000EDA3"); s.Add("ed52", "\U0000ED52"); s.Add("ee04", "\U0000EE04"); s.Add("ee03", "\U0000EE03"); s.Add("ed68", "\U0000ED68"); s.Add("ee32", "\U0000EE32"); s.Add("ee24", "\U0000EE24"); s.Add("ee13", "\U0000EE13"); s.Add("ed66", "\U0000ED66"); s.Add("eddf", "\U0000EDDF"); s.Add("ee27", "\U0000EE27"); s.Add("ee2b", "\U0000EE2B"); s.Add("ed72", "\U0000ED72"); s.Add("edb5", "\U0000EDB5"); s.Add("ee1a", "\U0000EE1A"); s.Add("ed81", "\U0000ED81"); s.Add("edf1", "\U0000EDF1"); s.Add("edb7", "\U0000EDB7"); s.Add("ed67", "\U0000ED67"); s.Add("ed5d", "\U0000ED5D"); s.Add("edc0", "\U0000EDC0"); s.Add("ef25", "\U0000EF25"); s.Add("ef23", "\U0000EF23"); s.Add("ee5b", "\U0000EE5B"); s.Add("eeb5", "\U0000EEB5"); s.Add("ee58", "\U0000EE58"); s.Add("ef05", "\U0000EF05"); s.Add("efcf", "\U0000EFCF"); s.Add("eeda", "\U0000EEDA"); s.Add("ee6a", "\U0000EE6A"); s.Add("eed5", "\U0000EED5"); s.Add("ee4f", "\U0000EE4F"); s.Add("ef03", "\U0000EF03"); s.Add("efc2", "\U0000EFC2"); s.Add("ee91", "\U0000EE91"); s.Add("ee5a", "\U0000EE5A"); s.Add("ee50", "\U0000EE50"); s.Add("ee5f", "\U0000EE5F"); s.Add("ef24", "\U0000EF24"); s.Add("ef34", "\U0000EF34"); s.Add("ef37", "\U0000EF37"); s.Add("ef73", "\U0000EF73"); s.Add("ef5f", "\U0000EF5F"); s.Add("ef97", "\U0000EF97"); s.Add("ef50", "\U0000EF50"); s.Add("ef60", "\U0000EF60"); s.Add("ee69", "\U0000EE69"); s.Add("eeb9", "\U0000EEB9"); s.Add("eed9", "\U0000EED9"); s.Add("eefd", "\U0000EEFD"); s.Add("ef6b", "\U0000EF6B"); s.Add("eea5", "\U0000EEA5"); s.Add("ee89", "\U0000EE89"); s.Add("ef62", "\U0000EF62"); s.Add("ee98", "\U0000EE98"); s.Add("ee7a", "\U0000EE7A"); s.Add("eeff", "\U0000EEFF"); s.Add("ef4a", "\U0000EF4A"); s.Add("ef67", "\U0000EF67"); s.Add("eecf", "\U0000EECF"); s.Add("eebb", "\U0000EEBB"); s.Add("ef1e", "\U0000EF1E"); s.Add("eed0", "\U0000EED0"); s.Add("efb5", "\U0000EFB5"); s.Add("eef6", "\U0000EEF6"); s.Add("efa7", "\U0000EFA7"); s.Add("ef0d", "\U0000EF0D"); s.Add("eefe", "\U0000EEFE"); s.Add("ef96", "\U0000EF96"); s.Add("ef33", "\U0000EF33"); s.Add("ee68", "\U0000EE68"); s.Add("eea8", "\U0000EEA8"); s.Add("efb1", "\U0000EFB1"); s.Add("eec6", "\U0000EEC6"); s.Add("ef42", "\U0000EF42"); s.Add("eec3", "\U0000EEC3"); s.Add("ee8c", "\U0000EE8C"); s.Add("eed3", "\U0000EED3"); s.Add("ee59", "\U0000EE59"); s.Add("ee65", "\U0000EE65"); s.Add("ef9e", "\U0000EF9E"); s.Add("ef3b", "\U0000EF3B"); s.Add("ee70", "\U0000EE70"); s.Add("eedf", "\U0000EEDF"); s.Add("eed1", "\U0000EED1"); s.Add("ee5c", "\U0000EE5C"); s.Add("ef77", "\U0000EF77"); s.Add("ef2d", "\U0000EF2D"); s.Add("ef94", "\U0000EF94"); s.Add("eee4", "\U0000EEE4"); s.Add("ef6f", "\U0000EF6F"); s.Add("eea1", "\U0000EEA1"); s.Add("ef64", "\U0000EF64"); s.Add("ef78", "\U0000EF78"); s.Add("eea2", "\U0000EEA2"); s.Add("ee71", "\U0000EE71"); s.Add("ef82", "\U0000EF82"); s.Add("ee6b", "\U0000EE6B"); s.Add("efd6", "\U0000EFD6"); s.Add("eee8", "\U0000EEE8"); s.Add("ef1c", "\U0000EF1C"); s.Add("efca", "\U0000EFCA"); s.Add("ef6e", "\U0000EF6E"); s.Add("eedc", "\U0000EEDC"); s.Add("ef5d", "\U0000EF5D"); s.Add("ef0e", "\U0000EF0E"); s.Add("ef8f", "\U0000EF8F"); s.Add("ef17", "\U0000EF17"); s.Add("eec9", "\U0000EEC9"); s.Add("ee6c", "\U0000EE6C"); s.Add("ee8d", "\U0000EE8D"); s.Add("eeaa", "\U0000EEAA"); s.Add("eef2", "\U0000EEF2"); s.Add("ef5a", "\U0000EF5A"); s.Add("ef61", "\U0000EF61"); s.Add("ee62", "\U0000EE62"); s.Add("ef2b", "\U0000EF2B"); s.Add("ef2e", "\U0000EF2E"); s.Add("ee9f", "\U0000EE9F"); s.Add("efb8", "\U0000EFB8"); s.Add("ee93", "\U0000EE93"); s.Add("ef7c", "\U0000EF7C"); s.Add("eec5", "\U0000EEC5"); s.Add("eeed", "\U0000EEED"); s.Add("eef0", "\U0000EEF0"); s.Add("ef20", "\U0000EF20"); s.Add("ef69", "\U0000EF69"); s.Add("ef7d", "\U0000EF7D"); s.Add("efa9", "\U0000EFA9"); s.Add("ef1a", "\U0000EF1A"); s.Add("ef22", "\U0000EF22"); s.Add("ef4c", "\U0000EF4C"); s.Add("ee75", "\U0000EE75"); s.Add("efa8", "\U0000EFA8"); s.Add("eeef", "\U0000EEEF"); s.Add("ee64", "\U0000EE64"); s.Add("ef6d", "\U0000EF6D"); s.Add("efa0", "\U0000EFA0"); s.Add("ef53", "\U0000EF53"); s.Add("ef72", "\U0000EF72"); s.Add("ef56", "\U0000EF56"); s.Add("efcc", "\U0000EFCC"); s.Add("eea7", "\U0000EEA7"); s.Add("eef7", "\U0000EEF7"); s.Add("ef65", "\U0000EF65"); s.Add("ef41", "\U0000EF41"); s.Add("eec2", "\U0000EEC2"); s.Add("ef26", "\U0000EF26"); s.Add("ef92", "\U0000EF92"); s.Add("efd4", "\U0000EFD4"); s.Add("eeee", "\U0000EEEE"); s.Add("ef52", "\U0000EF52"); s.Add("eede", "\U0000EEDE"); s.Add("ef2a", "\U0000EF2A"); s.Add("ef36", "\U0000EF36"); s.Add("eefb", "\U0000EEFB"); s.Add("ef2c", "\U0000EF2C"); s.Add("ef55", "\U0000EF55"); s.Add("eee5", "\U0000EEE5"); s.Add("ef81", "\U0000EF81"); s.Add("ef70", "\U0000EF70"); s.Add("ee9c", "\U0000EE9C"); s.Add("efae", "\U0000EFAE"); s.Add("ef1f", "\U0000EF1F"); s.Add("ee9e", "\U0000EE9E"); s.Add("ef8a", "\U0000EF8A"); s.Add("efb3", "\U0000EFB3"); s.Add("efcd", "\U0000EFCD"); s.Add("efaf", "\U0000EFAF"); s.Add("ee86", "\U0000EE86"); s.Add("ee8e", "\U0000EE8E"); s.Add("ef7e", "\U0000EF7E"); s.Add("efd3", "\U0000EFD3"); s.Add("eea4", "\U0000EEA4"); s.Add("ef57", "\U0000EF57"); s.Add("ef01", "\U0000EF01"); s.Add("ee7b", "\U0000EE7B"); s.Add("ee88", "\U0000EE88"); s.Add("ef46", "\U0000EF46"); s.Add("ee6e", "\U0000EE6E"); s.Add("efa6", "\U0000EFA6"); s.Add("efa2", "\U0000EFA2"); s.Add("eee9", "\U0000EEE9"); s.Add("ef90", "\U0000EF90"); s.Add("ef35", "\U0000EF35"); s.Add("ef71", "\U0000EF71"); s.Add("eea3", "\U0000EEA3"); s.Add("ef4b", "\U0000EF4B"); s.Add("efa5", "\U0000EFA5"); s.Add("eeb2", "\U0000EEB2"); s.Add("ef68", "\U0000EF68"); s.Add("ef3f", "\U0000EF3F"); s.Add("ef15", "\U0000EF15"); s.Add("ee95", "\U0000EE95"); s.Add("eef4", "\U0000EEF4"); s.Add("ee61", "\U0000EE61"); s.Add("ef66", "\U0000EF66"); s.Add("ef5e", "\U0000EF5E"); s.Add("efa4", "\U0000EFA4"); s.Add("ef0a", "\U0000EF0A"); s.Add("ef2f", "\U0000EF2F"); s.Add("ef00", "\U0000EF00"); s.Add("ef5c", "\U0000EF5C"); s.Add("ef30", "\U0000EF30"); s.Add("eeeb", "\U0000EEEB"); s.Add("efbf", "\U0000EFBF"); s.Add("ef07", "\U0000EF07"); s.Add("ee60", "\U0000EE60"); s.Add("ee7e", "\U0000EE7E"); s.Add("eec8", "\U0000EEC8"); s.Add("ef5b", "\U0000EF5B"); s.Add("ef86", "\U0000EF86"); s.Add("efc6", "\U0000EFC6"); s.Add("eebf", "\U0000EEBF"); s.Add("eeb0", "\U0000EEB0"); s.Add("eee0", "\U0000EEE0"); s.Add("ef11", "\U0000EF11"); s.Add("ee92", "\U0000EE92"); s.Add("ef18", "\U0000EF18"); s.Add("efad", "\U0000EFAD"); s.Add("eebe", "\U0000EEBE"); s.Add("efab", "\U0000EFAB"); s.Add("efb6", "\U0000EFB6"); s.Add("eec4", "\U0000EEC4"); s.Add("ef06", "\U0000EF06"); s.Add("ef9a", "\U0000EF9A"); s.Add("ef74", "\U0000EF74"); s.Add("efc1", "\U0000EFC1"); s.Add("ee80", "\U0000EE80"); s.Add("eeb1", "\U0000EEB1"); s.Add("ee99", "\U0000EE99"); s.Add("ef16", "\U0000EF16"); s.Add("eed8", "\U0000EED8"); s.Add("eeab", "\U0000EEAB"); s.Add("ee78", "\U0000EE78"); s.Add("ef0f", "\U0000EF0F"); s.Add("ee82", "\U0000EE82"); s.Add("ee56", "\U0000EE56"); s.Add("ef29", "\U0000EF29"); s.Add("eeb8", "\U0000EEB8"); s.Add("ef38", "\U0000EF38"); s.Add("ef49", "\U0000EF49"); s.Add("ee5e", "\U0000EE5E"); s.Add("ef0c", "\U0000EF0C"); s.Add("eedd", "\U0000EEDD"); s.Add("ef04", "\U0000EF04"); s.Add("ef12", "\U0000EF12"); s.Add("eef3", "\U0000EEF3"); s.Add("ee87", "\U0000EE87"); s.Add("ef54", "\U0000EF54"); s.Add("ee7d", "\U0000EE7D"); s.Add("eeaf", "\U0000EEAF"); s.Add("ef48", "\U0000EF48"); s.Add("eee3", "\U0000EEE3"); s.Add("efb7", "\U0000EFB7"); s.Add("ee97", "\U0000EE97"); s.Add("ee85", "\U0000EE85"); s.Add("ef7b", "\U0000EF7B"); s.Add("efd0", "\U0000EFD0"); s.Add("ef21", "\U0000EF21"); s.Add("ef7f", "\U0000EF7F"); s.Add("eecd", "\U0000EECD"); s.Add("ef0b", "\U0000EF0B"); s.Add("ef4e", "\U0000EF4E"); s.Add("efa1", "\U0000EFA1"); s.Add("ef9d", "\U0000EF9D"); s.Add("ee4d", "\U0000EE4D"); s.Add("ee4a", "\U0000EE4A"); s.Add("efd1", "\U0000EFD1"); s.Add("ee4e", "\U0000EE4E"); s.Add("ef8b", "\U0000EF8B"); s.Add("ee79", "\U0000EE79"); s.Add("eeb6", "\U0000EEB6"); s.Add("eeec", "\U0000EEEC"); s.Add("ef08", "\U0000EF08"); s.Add("ee73", "\U0000EE73"); s.Add("ee7f", "\U0000EE7F"); s.Add("ef98", "\U0000EF98"); s.Add("efd2", "\U0000EFD2"); s.Add("eecb", "\U0000EECB"); s.Add("eed2", "\U0000EED2"); s.Add("ee7c", "\U0000EE7C"); s.Add("ee8b", "\U0000EE8B"); s.Add("ef02", "\U0000EF02"); s.Add("eeca", "\U0000EECA"); s.Add("ef9b", "\U0000EF9B"); s.Add("ee81", "\U0000EE81"); s.Add("efb4", "\U0000EFB4"); s.Add("ef76", "\U0000EF76"); s.Add("eea6", "\U0000EEA6"); s.Add("efaa", "\U0000EFAA"); s.Add("ef99", "\U0000EF99"); s.Add("ef09", "\U0000EF09"); s.Add("efc4", "\U0000EFC4"); s.Add("ef51", "\U0000EF51"); s.Add("eef1", "\U0000EEF1"); s.Add("ee8a", "\U0000EE8A"); s.Add("eee7", "\U0000EEE7"); s.Add("eeb3", "\U0000EEB3"); s.Add("ee4c", "\U0000EE4C"); s.Add("eeb7", "\U0000EEB7"); s.Add("efbe", "\U0000EFBE"); s.Add("efcb", "\U0000EFCB"); s.Add("ef40", "\U0000EF40"); s.Add("eecc", "\U0000EECC"); s.Add("ef84", "\U0000EF84"); s.Add("ee5d", "\U0000EE5D"); s.Add("efce", "\U0000EFCE"); s.Add("eeea", "\U0000EEEA"); s.Add("efc0", "\U0000EFC0"); s.Add("eece", "\U0000EECE"); s.Add("efc3", "\U0000EFC3"); s.Add("ef28", "\U0000EF28"); s.Add("efc5", "\U0000EFC5"); s.Add("eea0", "\U0000EEA0"); s.Add("ef91", "\U0000EF91"); s.Add("ef1d", "\U0000EF1D"); s.Add("f079", "\U0000F079"); s.Add("f075", "\U0000F075"); s.Add("f02e", "\U0000F02E"); s.Add("f02b", "\U0000F02B"); s.Add("efff", "\U0000EFFF"); s.Add("f002", "\U0000F002"); s.Add("efdf", "\U0000EFDF"); s.Add("f077", "\U0000F077"); s.Add("f04f", "\U0000F04F"); s.Add("f038", "\U0000F038"); s.Add("efe8", "\U0000EFE8"); s.Add("efd8", "\U0000EFD8"); s.Add("f00e", "\U0000F00E"); s.Add("f037", "\U0000F037"); s.Add("f07f", "\U0000F07F"); s.Add("f040", "\U0000F040"); s.Add("f04e", "\U0000F04E"); s.Add("f066", "\U0000F066"); s.Add("f036", "\U0000F036"); s.Add("efe9", "\U0000EFE9"); s.Add("f004", "\U0000F004"); s.Add("f032", "\U0000F032"); s.Add("f060", "\U0000F060"); s.Add("efe7", "\U0000EFE7"); s.Add("f02f", "\U0000F02F"); s.Add("efdc", "\U0000EFDC"); s.Add("f06d", "\U0000F06D"); s.Add("effa", "\U0000EFFA"); s.Add("f042", "\U0000F042"); s.Add("f03e", "\U0000F03E"); s.Add("f051", "\U0000F051"); s.Add("efe0", "\U0000EFE0"); s.Add("effc", "\U0000EFFC"); s.Add("f001", "\U0000F001"); s.Add("f061", "\U0000F061"); s.Add("f00b", "\U0000F00B"); s.Add("f00a", "\U0000F00A"); s.Add("f00c", "\U0000F00C"); s.Add("f007", "\U0000F007"); s.Add("f031", "\U0000F031"); s.Add("f009", "\U0000F009"); s.Add("f008", "\U0000F008"); s.Add("f065", "\U0000F065"); s.Add("f076", "\U0000F076"); s.Add("f030", "\U0000F030"); s.Add("f064", "\U0000F064"); s.Add("f03b", "\U0000F03B"); s.Add("efda", "\U0000EFDA"); s.Add("f071", "\U0000F071"); s.Add("f05f", "\U0000F05F"); s.Add("f003", "\U0000F003"); s.Add("efe5", "\U0000EFE5"); s.Add("f03f", "\U0000F03F"); s.Add("f063", "\U0000F063"); s.Add("f06c", "\U0000F06C"); s.Add("f050", "\U0000F050"); s.Add("efea", "\U0000EFEA"); s.Add("f070", "\U0000F070"); s.Add("f006", "\U0000F006"); s.Add("f07e", "\U0000F07E"); s.Add("f06e", "\U0000F06E"); s.Add("efde", "\U0000EFDE"); s.Add("f035", "\U0000F035"); s.Add("f06f", "\U0000F06F"); s.Add("f052", "\U0000F052"); s.Add("effb", "\U0000EFFB"); s.Add("f02c", "\U0000F02C"); s.Add("effe", "\U0000EFFE"); s.Add("efe6", "\U0000EFE6"); s.Add("f000", "\U0000F000"); s.Add("f034", "\U0000F034"); s.Add("f033", "\U0000F033"); s.Add("f039", "\U0000F039"); s.Add("f041", "\U0000F041"); s.Add("f027", "\U0000F027"); s.Add("f03c", "\U0000F03C"); s.Add("f03d", "\U0000F03D"); s.Add("f03a", "\U0000F03A"); s.Add("effd", "\U0000EFFD"); s.Add("f00d", "\U0000F00D"); s.Add("f02a", "\U0000F02A"); s.Add("f062", "\U0000F062"); s.Add("f02d", "\U0000F02D"); s.Add("eff7", "\U0000EFF7"); s.Add("eff8", "\U0000EFF8"); s.Add("eff5", "\U0000EFF5"); s.Add("eff2", "\U0000EFF2"); s.Add("f01f", "\U0000F01F"); s.Add("efee", "\U0000EFEE"); s.Add("f011", "\U0000F011"); s.Add("f045", "\U0000F045"); s.Add("f015", "\U0000F015"); s.Add("f01e", "\U0000F01E"); s.Add("f020", "\U0000F020"); s.Add("f055", "\U0000F055"); s.Add("eff6", "\U0000EFF6"); s.Add("efe4", "\U0000EFE4"); s.Add("f048", "\U0000F048"); s.Add("f013", "\U0000F013"); s.Add("f078", "\U0000F078"); s.Add("efef", "\U0000EFEF"); s.Add("f043", "\U0000F043"); s.Add("f074", "\U0000F074"); s.Add("f024", "\U0000F024"); s.Add("efe3", "\U0000EFE3"); s.Add("f04b", "\U0000F04B"); s.Add("f05b", "\U0000F05B"); s.Add("efd7", "\U0000EFD7"); s.Add("f025", "\U0000F025"); s.Add("f047", "\U0000F047"); s.Add("f05c", "\U0000F05C"); s.Add("f06b", "\U0000F06B"); s.Add("f05e", "\U0000F05E"); s.Add("f026", "\U0000F026"); s.Add("f01a", "\U0000F01A"); s.Add("f01d", "\U0000F01D"); s.Add("efdb", "\U0000EFDB"); s.Add("eff1", "\U0000EFF1"); s.Add("f04c", "\U0000F04C"); s.Add("f053", "\U0000F053"); s.Add("f017", "\U0000F017"); s.Add("f04a", "\U0000F04A"); s.Add("f056", "\U0000F056"); s.Add("f057", "\U0000F057"); s.Add("f058", "\U0000F058"); s.Add("f059", "\U0000F059"); s.Add("f05a", "\U0000F05A"); s.Add("efe1", "\U0000EFE1"); s.Add("f07b", "\U0000F07B"); s.Add("eff9", "\U0000EFF9"); s.Add("f010", "\U0000F010"); s.Add("eff4", "\U0000EFF4"); s.Add("f06a", "\U0000F06A"); s.Add("f044", "\U0000F044"); s.Add("f005", "\U0000F005"); s.Add("f029", "\U0000F029"); s.Add("f014", "\U0000F014"); s.Add("f01c", "\U0000F01C"); s.Add("eff3", "\U0000EFF3"); s.Add("f01b", "\U0000F01B"); s.Add("eff0", "\U0000EFF0"); s.Add("f018", "\U0000F018"); s.Add("f012", "\U0000F012"); s.Add("efeb", "\U0000EFEB"); s.Add("f016", "\U0000F016"); s.Add("efdd", "\U0000EFDD"); s.Add("f069", "\U0000F069"); s.Add("f04d", "\U0000F04D"); s.Add("efec", "\U0000EFEC"); s.Add("f07d", "\U0000F07D"); s.Add("efd9", "\U0000EFD9"); s.Add("f022", "\U0000F022"); s.Add("f07a", "\U0000F07A"); s.Add("f028", "\U0000F028"); s.Add("f068", "\U0000F068"); s.Add("f07c", "\U0000F07C"); s.Add("f054", "\U0000F054"); s.Add("efed", "\U0000EFED"); s.Add("f021", "\U0000F021"); s.Add("f046", "\U0000F046"); s.Add("f023", "\U0000F023"); s.Add("f049", "\U0000F049"); s.Add("f067", "\U0000F067"); s.Add("f072", "\U0000F072"); s.Add("f073", "\U0000F073"); s.Add("f05d", "\U0000F05D"); s.Add("f00f", "\U0000F00F"); s.Add("efe2", "\U0000EFE2"); s.Add("f019", "\U0000F019"); s.Add("f2cc", "\U0000F2CC"); s.Add("f2aa", "\U0000F2AA"); s.Add("f23f", "\U0000F23F"); s.Add("f0b5", "\U0000F0B5"); s.Add("f0b7", "\U0000F0B7"); s.Add("f0b6", "\U0000F0B6"); s.Add("f0da", "\U0000F0DA"); s.Add("f0a3", "\U0000F0A3"); s.Add("f0a2", "\U0000F0A2"); s.Add("f0b1", "\U0000F0B1"); s.Add("f0e3", "\U0000F0E3"); s.Add("f09a", "\U0000F09A"); s.Add("f084", "\U0000F084"); s.Add("f0af", "\U0000F0AF"); s.Add("f0dd", "\U0000F0DD"); s.Add("f0a5", "\U0000F0A5"); s.Add("f0d4", "\U0000F0D4"); s.Add("f0c2", "\U0000F0C2"); s.Add("f087", "\U0000F087"); s.Add("f0e1", "\U0000F0E1"); s.Add("f08f", "\U0000F08F"); s.Add("f0d1", "\U0000F0D1"); s.Add("f0d3", "\U0000F0D3"); s.Add("f098", "\U0000F098"); s.Add("f091", "\U0000F091"); s.Add("f0c1", "\U0000F0C1"); s.Add("f0e7", "\U0000F0E7"); s.Add("f09b", "\U0000F09B"); s.Add("f0a1", "\U0000F0A1"); s.Add("f0e5", "\U0000F0E5"); s.Add("f0cf", "\U0000F0CF"); s.Add("f0a0", "\U0000F0A0"); s.Add("f09e", "\U0000F09E"); s.Add("f095", "\U0000F095"); s.Add("f090", "\U0000F090"); s.Add("f0ad", "\U0000F0AD"); s.Add("f0b3", "\U0000F0B3"); s.Add("f0b8", "\U0000F0B8"); s.Add("f0a6", "\U0000F0A6"); s.Add("f08b", "\U0000F08B"); s.Add("f0e4", "\U0000F0E4"); s.Add("f0aa", "\U0000F0AA"); s.Add("f0d8", "\U0000F0D8"); s.Add("f0de", "\U0000F0DE"); s.Add("f0e2", "\U0000F0E2"); s.Add("f086", "\U0000F086"); s.Add("f088", "\U0000F088"); s.Add("f0a4", "\U0000F0A4"); s.Add("f0c0", "\U0000F0C0"); s.Add("f089", "\U0000F089"); s.Add("f0c3", "\U0000F0C3"); s.Add("f0ba", "\U0000F0BA"); s.Add("f0b0", "\U0000F0B0"); s.Add("f0b2", "\U0000F0B2"); s.Add("f093", "\U0000F093"); s.Add("f0b9", "\U0000F0B9"); s.Add("f0ae", "\U0000F0AE"); s.Add("f0df", "\U0000F0DF"); s.Add("f09c", "\U0000F09C"); s.Add("f0ca", "\U0000F0CA"); s.Add("f0a8", "\U0000F0A8"); s.Add("f08d", "\U0000F08D"); s.Add("f0bb", "\U0000F0BB"); s.Add("f0e8", "\U0000F0E8"); s.Add("f0bc", "\U0000F0BC"); s.Add("f0ce", "\U0000F0CE"); s.Add("f0d5", "\U0000F0D5"); s.Add("f0d0", "\U0000F0D0"); s.Add("f097", "\U0000F097"); s.Add("f09d", "\U0000F09D"); s.Add("f0cc", "\U0000F0CC"); s.Add("f0bf", "\U0000F0BF"); s.Add("f0c6", "\U0000F0C6"); s.Add("f099", "\U0000F099"); s.Add("f0c7", "\U0000F0C7"); s.Add("f0ac", "\U0000F0AC"); s.Add("f094", "\U0000F094"); s.Add("f0dc", "\U0000F0DC"); s.Add("f085", "\U0000F085"); s.Add("f0d2", "\U0000F0D2"); s.Add("f0ab", "\U0000F0AB"); s.Add("f0cd", "\U0000F0CD"); s.Add("f0a7", "\U0000F0A7"); s.Add("f09f", "\U0000F09F"); s.Add("f0c8", "\U0000F0C8"); s.Add("f096", "\U0000F096"); s.Add("f0d6", "\U0000F0D6"); s.Add("f0cb", "\U0000F0CB"); s.Add("f08a", "\U0000F08A"); s.Add("f0c9", "\U0000F0C9"); s.Add("f0b4", "\U0000F0B4"); s.Add("f0e0", "\U0000F0E0"); s.Add("f0d9", "\U0000F0D9"); s.Add("f0bd", "\U0000F0BD"); s.Add("f0c5", "\U0000F0C5"); s.Add("f08c", "\U0000F08C"); s.Add("f0be", "\U0000F0BE"); s.Add("f0d7", "\U0000F0D7"); s.Add("f0e6", "\U0000F0E6"); s.Add("f0db", "\U0000F0DB"); s.Add("f0c4", "\U0000F0C4"); s.Add("f0a9", "\U0000F0A9"); s.Add("f08e", "\U0000F08E"); s.Add("f092", "\U0000F092"); s.Add("f1cc", "\U0000F1CC"); s.Add("f1cb", "\U0000F1CB"); s.Add("f19f", "\U0000F19F"); s.Add("f11e", "\U0000F11E"); s.Add("f1c8", "\U0000F1C8"); s.Add("f1c7", "\U0000F1C7"); s.Add("f10b", "\U0000F10B"); s.Add("f1ae", "\U0000F1AE"); s.Add("f192", "\U0000F192"); s.Add("f110", "\U0000F110"); s.Add("f1b2", "\U0000F1B2"); s.Add("f184", "\U0000F184"); s.Add("f16b", "\U0000F16B"); s.Add("f165", "\U0000F165"); s.Add("f122", "\U0000F122"); s.Add("f16f", "\U0000F16F"); s.Add("f1a6", "\U0000F1A6"); s.Add("f136", "\U0000F136"); s.Add("f19b", "\U0000F19B"); s.Add("f111", "\U0000F111"); s.Add("f169", "\U0000F169"); s.Add("f1b0", "\U0000F1B0"); s.Add("f117", "\U0000F117"); s.Add("f1c1", "\U0000F1C1"); s.Add("f109", "\U0000F109"); s.Add("f10c", "\U0000F10C"); s.Add("f10d", "\U0000F10D"); s.Add("f13b", "\U0000F13B"); s.Add("f141", "\U0000F141"); s.Add("f0ec", "\U0000F0EC"); s.Add("f168", "\U0000F168"); s.Add("f10f", "\U0000F10F"); s.Add("f126", "\U0000F126"); s.Add("f1b4", "\U0000F1B4"); s.Add("f14a", "\U0000F14A"); s.Add("f140", "\U0000F140"); s.Add("f1ca", "\U0000F1CA"); s.Add("f197", "\U0000F197"); s.Add("f158", "\U0000F158"); s.Add("f179", "\U0000F179"); s.Add("f11c", "\U0000F11C"); s.Add("f1bb", "\U0000F1BB"); s.Add("f16d", "\U0000F16D"); s.Add("f13a", "\U0000F13A"); s.Add("f182", "\U0000F182"); s.Add("f1c9", "\U0000F1C9"); s.Add("f16c", "\U0000F16C"); s.Add("f1a4", "\U0000F1A4"); s.Add("f13e", "\U0000F13E"); s.Add("f105", "\U0000F105"); s.Add("f143", "\U0000F143"); s.Add("f144", "\U0000F144"); s.Add("f17a", "\U0000F17A"); s.Add("f131", "\U0000F131"); s.Add("f172", "\U0000F172"); s.Add("f130", "\U0000F130"); s.Add("f177", "\U0000F177"); s.Add("f12f", "\U0000F12F"); s.Add("f113", "\U0000F113"); s.Add("f1b5", "\U0000F1B5"); s.Add("f10a", "\U0000F10A"); s.Add("f104", "\U0000F104"); s.Add("f1bf", "\U0000F1BF"); s.Add("f108", "\U0000F108"); s.Add("f188", "\U0000F188"); s.Add("f166", "\U0000F166"); s.Add("f18e", "\U0000F18E"); s.Add("f173", "\U0000F173"); s.Add("f159", "\U0000F159"); s.Add("f127", "\U0000F127"); s.Add("f102", "\U0000F102"); s.Add("f134", "\U0000F134"); s.Add("f1aa", "\U0000F1AA"); s.Add("f147", "\U0000F147"); s.Add("f10e", "\U0000F10E"); s.Add("f19d", "\U0000F19D"); s.Add("f181", "\U0000F181"); s.Add("f186", "\U0000F186"); s.Add("f129", "\U0000F129"); s.Add("f12b", "\U0000F12B"); s.Add("f19e", "\U0000F19E"); s.Add("f18f", "\U0000F18F"); s.Add("f13f", "\U0000F13F"); s.Add("f14f", "\U0000F14F"); s.Add("f11f", "\U0000F11F"); s.Add("f13c", "\U0000F13C"); s.Add("f11a", "\U0000F11A"); s.Add("f16e", "\U0000F16E"); s.Add("f146", "\U0000F146"); s.Add("f128", "\U0000F128"); s.Add("f1b9", "\U0000F1B9"); s.Add("f18c", "\U0000F18C"); s.Add("f115", "\U0000F115"); s.Add("f1be", "\U0000F1BE"); s.Add("f0ea", "\U0000F0EA"); s.Add("f138", "\U0000F138"); s.Add("f17e", "\U0000F17E"); s.Add("f112", "\U0000F112"); s.Add("f107", "\U0000F107"); s.Add("f178", "\U0000F178"); s.Add("f12e", "\U0000F12E"); s.Add("f167", "\U0000F167"); s.Add("f14c", "\U0000F14C"); s.Add("f18a", "\U0000F18A"); s.Add("f198", "\U0000F198"); s.Add("f1ab", "\U0000F1AB"); s.Add("f106", "\U0000F106"); s.Add("f1a1", "\U0000F1A1"); s.Add("f103", "\U0000F103"); s.Add("f16a", "\U0000F16A"); s.Add("f1b7", "\U0000F1B7"); s.Add("f15c", "\U0000F15C"); s.Add("f0ed", "\U0000F0ED"); s.Add("f150", "\U0000F150"); s.Add("f187", "\U0000F187"); s.Add("f15d", "\U0000F15D"); s.Add("f17b", "\U0000F17B"); s.Add("f193", "\U0000F193"); s.Add("f15b", "\U0000F15B"); s.Add("f1a3", "\U0000F1A3"); s.Add("f0f8", "\U0000F0F8"); s.Add("f1ba", "\U0000F1BA"); s.Add("f125", "\U0000F125"); s.Add("f15a", "\U0000F15A"); s.Add("f1b8", "\U0000F1B8"); s.Add("f101", "\U0000F101"); s.Add("f18b", "\U0000F18B"); s.Add("f0ff", "\U0000F0FF"); s.Add("f19c", "\U0000F19C"); s.Add("f132", "\U0000F132"); s.Add("f195", "\U0000F195"); s.Add("f119", "\U0000F119"); s.Add("f1b3", "\U0000F1B3"); s.Add("f120", "\U0000F120"); s.Add("f0f9", "\U0000F0F9"); s.Add("f135", "\U0000F135"); s.Add("f0f3", "\U0000F0F3"); s.Add("f0fd", "\U0000F0FD"); s.Add("f14b", "\U0000F14B"); s.Add("f11b", "\U0000F11B"); s.Add("f1b6", "\U0000F1B6"); s.Add("f17f", "\U0000F17F"); s.Add("f161", "\U0000F161"); s.Add("f0f1", "\U0000F0F1"); s.Add("f180", "\U0000F180"); s.Add("f174", "\U0000F174"); s.Add("f151", "\U0000F151"); s.Add("f164", "\U0000F164"); s.Add("f196", "\U0000F196"); s.Add("f15f", "\U0000F15F"); s.Add("f0f2", "\U0000F0F2"); s.Add("f1ac", "\U0000F1AC"); s.Add("f124", "\U0000F124"); s.Add("f118", "\U0000F118"); s.Add("f17d", "\U0000F17D"); s.Add("f0fa", "\U0000F0FA"); s.Add("f12a", "\U0000F12A"); s.Add("f163", "\U0000F163"); s.Add("f133", "\U0000F133"); s.Add("f185", "\U0000F185"); s.Add("f1a9", "\U0000F1A9"); s.Add("f123", "\U0000F123"); s.Add("f0fb", "\U0000F0FB"); s.Add("f0f4", "\U0000F0F4"); s.Add("f0eb", "\U0000F0EB"); s.Add("f149", "\U0000F149"); s.Add("f160", "\U0000F160"); s.Add("f1a2", "\U0000F1A2"); s.Add("f0ee", "\U0000F0EE"); s.Add("f100", "\U0000F100"); s.Add("f18d", "\U0000F18D"); s.Add("f0f5", "\U0000F0F5"); s.Add("f19a", "\U0000F19A"); s.Add("f0fc", "\U0000F0FC"); s.Add("f12d", "\U0000F12D"); s.Add("f0fe", "\U0000F0FE"); s.Add("f1bd", "\U0000F1BD"); s.Add("f1b1", "\U0000F1B1"); s.Add("f0f0", "\U0000F0F0"); s.Add("f1af", "\U0000F1AF"); s.Add("f171", "\U0000F171"); s.Add("f199", "\U0000F199"); s.Add("f17c", "\U0000F17C"); s.Add("f139", "\U0000F139"); s.Add("f170", "\U0000F170"); s.Add("f148", "\U0000F148"); s.Add("f116", "\U0000F116"); s.Add("f13d", "\U0000F13D"); s.Add("f12c", "\U0000F12C"); s.Add("f175", "\U0000F175"); s.Add("f162", "\U0000F162"); s.Add("f142", "\U0000F142"); s.Add("f137", "\U0000F137"); s.Add("f14d", "\U0000F14D"); s.Add("f11d", "\U0000F11D"); s.Add("f1a0", "\U0000F1A0"); s.Add("f0f6", "\U0000F0F6"); s.Add("f114", "\U0000F114"); s.Add("f15e", "\U0000F15E"); s.Add("f191", "\U0000F191"); s.Add("f0ef", "\U0000F0EF"); s.Add("f14e", "\U0000F14E"); s.Add("f176", "\U0000F176"); s.Add("f183", "\U0000F183"); s.Add("f1c0", "\U0000F1C0"); s.Add("f1ad", "\U0000F1AD"); s.Add("f1c3", "\U0000F1C3"); s.Add("f1c4", "\U0000F1C4"); s.Add("f189", "\U0000F189"); s.Add("f1c2", "\U0000F1C2"); s.Add("f190", "\U0000F190"); s.Add("f145", "\U0000F145"); s.Add("f1c5", "\U0000F1C5"); s.Add("f0f7", "\U0000F0F7"); s.Add("f1c6", "\U0000F1C6"); s.Add("f1a5", "\U0000F1A5"); s.Add("f121", "\U0000F121"); s.Add("f1bc", "\U0000F1BC"); s.Add("f2ed", "\U0000F2ED"); s.Add("f2a8", "\U0000F2A8"); s.Add("f1e4", "\U0000F1E4"); s.Add("f218", "\U0000F218"); s.Add("f1e6", "\U0000F1E6"); s.Add("f1ce", "\U0000F1CE"); s.Add("f23a", "\U0000F23A"); s.Add("f274", "\U0000F274"); s.Add("f281", "\U0000F281"); s.Add("f296", "\U0000F296"); s.Add("f2dc", "\U0000F2DC"); s.Add("f246", "\U0000F246"); s.Add("f20f", "\U0000F20F"); s.Add("f240", "\U0000F240"); s.Add("f258", "\U0000F258"); s.Add("f29e", "\U0000F29E"); s.Add("f27f", "\U0000F27F"); s.Add("f2c0", "\U0000F2C0"); s.Add("f2d7", "\U0000F2D7"); s.Add("f263", "\U0000F263"); s.Add("f23e", "\U0000F23E"); s.Add("f21e", "\U0000F21E"); s.Add("f213", "\U0000F213"); s.Add("f222", "\U0000F222"); s.Add("f236", "\U0000F236"); s.Add("f1f2", "\U0000F1F2"); s.Add("f2fa", "\U0000F2FA"); s.Add("f27a", "\U0000F27A"); s.Add("f283", "\U0000F283"); s.Add("f297", "\U0000F297"); s.Add("f247", "\U0000F247"); s.Add("f257", "\U0000F257"); s.Add("f215", "\U0000F215"); s.Add("f278", "\U0000F278"); s.Add("f268", "\U0000F268"); s.Add("f1f3", "\U0000F1F3"); s.Add("f1dd", "\U0000F1DD"); s.Add("f282", "\U0000F282"); s.Add("f2f7", "\U0000F2F7"); s.Add("f214", "\U0000F214"); s.Add("f256", "\U0000F256"); s.Add("f2ad", "\U0000F2AD"); s.Add("f25c", "\U0000F25C"); s.Add("f2bf", "\U0000F2BF"); s.Add("f292", "\U0000F292"); s.Add("f2a3", "\U0000F2A3"); s.Add("f1d8", "\U0000F1D8"); s.Add("f1d5", "\U0000F1D5"); s.Add("f211", "\U0000F211"); s.Add("f212", "\U0000F212"); s.Add("f1d3", "\U0000F1D3"); s.Add("f1d9", "\U0000F1D9"); s.Add("f23b", "\U0000F23B"); s.Add("f290", "\U0000F290"); s.Add("f2cb", "\U0000F2CB"); s.Add("f2d9", "\U0000F2D9"); s.Add("f2d5", "\U0000F2D5"); s.Add("f231", "\U0000F231"); s.Add("f249", "\U0000F249"); s.Add("f1f4", "\U0000F1F4"); s.Add("f2b7", "\U0000F2B7"); s.Add("f2de", "\U0000F2DE"); s.Add("f1ee", "\U0000F1EE"); s.Add("f23c", "\U0000F23C"); s.Add("f229", "\U0000F229"); s.Add("f22b", "\U0000F22B"); s.Add("f2da", "\U0000F2DA"); s.Add("f235", "\U0000F235"); s.Add("f24f", "\U0000F24F"); s.Add("f1f8", "\U0000F1F8"); s.Add("f27d", "\U0000F27D"); s.Add("f1d1", "\U0000F1D1"); s.Add("f28e", "\U0000F28E"); s.Add("f1f9", "\U0000F1F9"); s.Add("f2bc", "\U0000F2BC"); s.Add("f269", "\U0000F269"); s.Add("f24b", "\U0000F24B"); s.Add("f24d", "\U0000F24D"); s.Add("f2f9", "\U0000F2F9"); s.Add("f221", "\U0000F221"); s.Add("f2c2", "\U0000F2C2"); s.Add("f2b1", "\U0000F2B1"); s.Add("f204", "\U0000F204"); s.Add("f29c", "\U0000F29C"); s.Add("f1fe", "\U0000F1FE"); s.Add("f224", "\U0000F224"); s.Add("f2d8", "\U0000F2D8"); s.Add("f223", "\U0000F223"); s.Add("f2b2", "\U0000F2B2"); s.Add("f2fd", "\U0000F2FD"); s.Add("f253", "\U0000F253"); s.Add("f28a", "\U0000F28A"); s.Add("f300", "\U0000F300"); s.Add("f206", "\U0000F206"); s.Add("f288", "\U0000F288"); s.Add("f2be", "\U0000F2BE"); s.Add("f1dc", "\U0000F1DC"); s.Add("f2b3", "\U0000F2B3"); s.Add("f25b", "\U0000F25B"); s.Add("f2e5", "\U0000F2E5"); s.Add("f1fa", "\U0000F1FA"); s.Add("f251", "\U0000F251"); s.Add("f289", "\U0000F289"); s.Add("f2e3", "\U0000F2E3"); s.Add("f29b", "\U0000F29B"); s.Add("f2f2", "\U0000F2F2"); s.Add("f2f3", "\U0000F2F3"); s.Add("f1e2", "\U0000F1E2"); s.Add("f1e0", "\U0000F1E0"); s.Add("f2a6", "\U0000F2A6"); s.Add("f255", "\U0000F255"); s.Add("f1ff", "\U0000F1FF"); s.Add("f210", "\U0000F210"); s.Add("f21f", "\U0000F21F"); s.Add("f2db", "\U0000F2DB"); s.Add("f1e8", "\U0000F1E8"); s.Add("f2ac", "\U0000F2AC"); s.Add("f254", "\U0000F254"); s.Add("f22d", "\U0000F22D"); s.Add("f220", "\U0000F220"); s.Add("f2f0", "\U0000F2F0"); s.Add("f22f", "\U0000F22F"); s.Add("f200", "\U0000F200"); s.Add("f27b", "\U0000F27B"); s.Add("f2b6", "\U0000F2B6"); s.Add("f2ef", "\U0000F2EF"); s.Add("f2ee", "\U0000F2EE"); s.Add("f234", "\U0000F234"); s.Add("f20e", "\U0000F20E"); s.Add("f2c3", "\U0000F2C3"); s.Add("f267", "\U0000F267"); s.Add("f241", "\U0000F241"); s.Add("f25d", "\U0000F25D"); s.Add("f2d4", "\U0000F2D4"); s.Add("f2bd", "\U0000F2BD"); s.Add("f25a", "\U0000F25A"); s.Add("f2a5", "\U0000F2A5"); s.Add("f276", "\U0000F276"); s.Add("f2ce", "\U0000F2CE"); s.Add("f266", "\U0000F266"); s.Add("f2b9", "\U0000F2B9"); s.Add("f2d6", "\U0000F2D6"); s.Add("f2a1", "\U0000F2A1"); s.Add("f1ed", "\U0000F1ED"); s.Add("f295", "\U0000F295"); s.Add("f1cd", "\U0000F1CD"); s.Add("f2ff", "\U0000F2FF"); s.Add("f1eb", "\U0000F1EB"); s.Add("f2eb", "\U0000F2EB"); s.Add("f2bb", "\U0000F2BB"); s.Add("f2b8", "\U0000F2B8"); s.Add("f2ba", "\U0000F2BA"); s.Add("f272", "\U0000F272"); s.Add("f26d", "\U0000F26D"); s.Add("f270", "\U0000F270"); s.Add("f244", "\U0000F244"); s.Add("f2ec", "\U0000F2EC"); s.Add("f238", "\U0000F238"); s.Add("f26c", "\U0000F26C"); s.Add("f250", "\U0000F250"); s.Add("f2b4", "\U0000F2B4"); s.Add("f2e1", "\U0000F2E1"); s.Add("f275", "\U0000F275"); s.Add("f2d3", "\U0000F2D3"); s.Add("f2ea", "\U0000F2EA"); s.Add("f273", "\U0000F273"); s.Add("f228", "\U0000F228"); s.Add("f293", "\U0000F293"); s.Add("f284", "\U0000F284"); s.Add("f23d", "\U0000F23D"); s.Add("f286", "\U0000F286"); s.Add("f285", "\U0000F285"); s.Add("f2ab", "\U0000F2AB"); s.Add("f1f1", "\U0000F1F1"); s.Add("f1d6", "\U0000F1D6"); s.Add("f2e2", "\U0000F2E2"); s.Add("f287", "\U0000F287"); s.Add("f262", "\U0000F262"); s.Add("f239", "\U0000F239"); s.Add("f26e", "\U0000F26E"); s.Add("f2d0", "\U0000F2D0"); s.Add("f24a", "\U0000F24A"); s.Add("f294", "\U0000F294"); s.Add("f22c", "\U0000F22C"); s.Add("f216", "\U0000F216"); s.Add("f2c9", "\U0000F2C9"); s.Add("f2cf", "\U0000F2CF"); s.Add("f26a", "\U0000F26A"); s.Add("f20d", "\U0000F20D"); s.Add("f21a", "\U0000F21A"); s.Add("f2e0", "\U0000F2E0"); s.Add("f299", "\U0000F299"); s.Add("f298", "\U0000F298"); s.Add("f2f8", "\U0000F2F8"); s.Add("f2e4", "\U0000F2E4"); s.Add("f277", "\U0000F277"); s.Add("f25f", "\U0000F25F"); s.Add("f226", "\U0000F226"); s.Add("f2f4", "\U0000F2F4"); s.Add("f1d0", "\U0000F1D0"); s.Add("f291", "\U0000F291"); s.Add("f2a4", "\U0000F2A4"); s.Add("f201", "\U0000F201"); s.Add("f243", "\U0000F243"); s.Add("f232", "\U0000F232"); s.Add("f24c", "\U0000F24C"); s.Add("f27e", "\U0000F27E"); s.Add("f1f7", "\U0000F1F7"); s.Add("f1f6", "\U0000F1F6"); s.Add("f219", "\U0000F219"); s.Add("f25e", "\U0000F25E"); s.Add("f2f6", "\U0000F2F6"); s.Add("f1ea", "\U0000F1EA"); s.Add("f1e5", "\U0000F1E5"); s.Add("f21d", "\U0000F21D"); s.Add("f1d2", "\U0000F1D2"); s.Add("f2d2", "\U0000F2D2"); s.Add("f1e3", "\U0000F1E3"); s.Add("f2a9", "\U0000F2A9"); s.Add("f264", "\U0000F264"); s.Add("f2a7", "\U0000F2A7"); s.Add("f203", "\U0000F203"); s.Add("f2a0", "\U0000F2A0"); s.Add("f21b", "\U0000F21B"); s.Add("f2df", "\U0000F2DF"); s.Add("f1e7", "\U0000F1E7"); s.Add("f1e9", "\U0000F1E9"); s.Add("f1db", "\U0000F1DB"); s.Add("f2ca", "\U0000F2CA"); s.Add("f22e", "\U0000F22E"); s.Add("f245", "\U0000F245"); s.Add("f2f5", "\U0000F2F5"); s.Add("f2e6", "\U0000F2E6"); s.Add("f252", "\U0000F252"); s.Add("f217", "\U0000F217"); s.Add("f265", "\U0000F265"); s.Add("f2fb", "\U0000F2FB"); s.Add("f2fc", "\U0000F2FC"); s.Add("f20b", "\U0000F20B"); s.Add("f20a", "\U0000F20A"); s.Add("f28d", "\U0000F28D"); s.Add("f20c", "\U0000F20C"); s.Add("f207", "\U0000F207"); s.Add("f209", "\U0000F209"); s.Add("f208", "\U0000F208"); s.Add("f2c5", "\U0000F2C5"); s.Add("f261", "\U0000F261"); s.Add("f230", "\U0000F230"); s.Add("f242", "\U0000F242"); s.Add("f2e8", "\U0000F2E8"); s.Add("f2c4", "\U0000F2C4"); s.Add("f1f5", "\U0000F1F5"); s.Add("f2c1", "\U0000F2C1"); s.Add("f28f", "\U0000F28F"); s.Add("f28c", "\U0000F28C"); s.Add("f2b5", "\U0000F2B5"); s.Add("f2e9", "\U0000F2E9"); s.Add("f2c7", "\U0000F2C7"); s.Add("f233", "\U0000F233"); s.Add("f237", "\U0000F237"); s.Add("f2ae", "\U0000F2AE"); s.Add("f248", "\U0000F248"); s.Add("f2f1", "\U0000F2F1"); s.Add("f2cd", "\U0000F2CD"); s.Add("f26b", "\U0000F26B"); s.Add("f2af", "\U0000F2AF"); s.Add("f21c", "\U0000F21C"); s.Add("f1ec", "\U0000F1EC"); s.Add("f2b0", "\U0000F2B0"); s.Add("f1d4", "\U0000F1D4"); s.Add("f29a", "\U0000F29A"); s.Add("f22a", "\U0000F22A"); s.Add("f2a2", "\U0000F2A2"); s.Add("f27c", "\U0000F27C"); s.Add("f2dd", "\U0000F2DD"); s.Add("f202", "\U0000F202"); s.Add("f2c6", "\U0000F2C6"); s.Add("f205", "\U0000F205"); s.Add("f225", "\U0000F225"); s.Add("f26f", "\U0000F26F"); s.Add("f24e", "\U0000F24E"); s.Add("f2c8", "\U0000F2C8"); s.Add("f279", "\U0000F279"); s.Add("f28b", "\U0000F28B"); s.Add("f1d7", "\U0000F1D7"); s.Add("f1ef", "\U0000F1EF"); s.Add("f1da", "\U0000F1DA"); s.Add("f1de", "\U0000F1DE"); s.Add("f1f0", "\U0000F1F0"); s.Add("f271", "\U0000F271"); s.Add("f227", "\U0000F227"); s.Add("f259", "\U0000F259"); s.Add("f29f", "\U0000F29F"); s.Add("f1e1", "\U0000F1E1"); s.Add("f1fd", "\U0000F1FD"); s.Add("f2fe", "\U0000F2FE"); s.Add("f1fc", "\U0000F1FC"); s.Add("f1fb", "\U0000F1FB"); s.Add("f1df", "\U0000F1DF"); s.Add("f260", "\U0000F260"); s.Add("f2e7", "\U0000F2E7"); s.Add("f29d", "\U0000F29D"); s.Add("f2d1", "\U0000F2D1"); s.Add("f280", "\U0000F280"); s.Add("f1cf", "\U0000F1CF"); s.Add("f301", "\U0000F301"); s.Add("f30f", "\U0000F30F"); s.Add("f32b", "\U0000F32B"); s.Add("f334", "\U0000F334"); s.Add("f305", "\U0000F305"); s.Add("f309", "\U0000F309"); s.Add("f311", "\U0000F311"); s.Add("f319", "\U0000F319"); s.Add("f31a", "\U0000F31A"); s.Add("f31c", "\U0000F31C"); s.Add("f32e", "\U0000F32E"); s.Add("f303", "\U0000F303"); s.Add("f317", "\U0000F317"); s.Add("f307", "\U0000F307"); s.Add("f332", "\U0000F332"); s.Add("f331", "\U0000F331"); s.Add("f313", "\U0000F313"); s.Add("f32c", "\U0000F32C"); s.Add("f30c", "\U0000F30C"); s.Add("f314", "\U0000F314"); s.Add("f30a", "\U0000F30A"); s.Add("f32f", "\U0000F32F"); s.Add("f310", "\U0000F310"); s.Add("f304", "\U0000F304"); s.Add("f308", "\U0000F308"); s.Add("f30e", "\U0000F30E"); s.Add("f31b", "\U0000F31B"); s.Add("f336", "\U0000F336"); s.Add("f306", "\U0000F306"); s.Add("f30b", "\U0000F30B"); s.Add("f333", "\U0000F333"); s.Add("f318", "\U0000F318"); s.Add("f335", "\U0000F335"); s.Add("f32d", "\U0000F32D"); s.Add("f312", "\U0000F312"); s.Add("f30d", "\U0000F30D"); s.Add("f330", "\U0000F330"); } /// <summary> /// Gets the data icon. /// </summary> /// <returns>The data icon.</returns> private ObservableCollection<string> GetDataIcon() { ObservableCollection<string> Icons = new ObservableCollection<string>(); #region Add Data icons name Icons.Add("Note-Information"); Icons.Add("Data-Copy"); Icons.Add("Data-Add"); Icons.Add("Messages-Information"); Icons.Add("Business-Man-Settings"); Icons.Add("Briefcase - 02"); Icons.Add("Note-Memo-01"); Icons.Add("Filter - 01"); Icons.Add("Data-Warning"); Icons.Add("Digital - Six"); Icons.Add("Book-Add"); Icons.Add("Cupboard - Up"); Icons.Add("Data-Settings"); Icons.Add("Data-Connect"); Icons.Add("Data-Information"); Icons.Add("Profit-WF"); Icons.Add("Filter-Standard"); Icons.Add("Data-Replace"); Icons.Add("Bullets - 04"); Icons.Add("Calendar-Date"); Icons.Add("Data-Error"); Icons.Add("Filter-Ascending"); Icons.Add("Bullets - 02"); Icons.Add("Data-Delete"); Icons.Add("Book-Settings"); Icons.Add("Message-Delete"); Icons.Add("Business-Man-Search"); Icons.Add("Digital - Nine"); Icons.Add("Digital - Zero"); Icons.Add("Digital - Seven"); Icons.Add("Filter-Delete"); Icons.Add("Filter - 03"); Icons.Add("Briefcase - 03"); Icons.Add("Business-Man-Add-01"); Icons.Add("Business-Man-Delete"); Icons.Add("Business-Man-01"); Icons.Add("Cupboard - 05"); Icons.Add("Cupboard - 04"); Icons.Add("Cupboard - 06"); Icons.Add("Cupboard - 01"); Icons.Add("Data-Down"); Icons.Add("Fax-Machine"); Icons.Add("Cupboard - 02"); Icons.Add("Messages-Information-01"); Icons.Add("Note-Memo"); Icons.Add("Data-Disk"); Icons.Add("Digital - Four"); Icons.Add("Book-Delete"); Icons.Add("Filter-Descending"); Icons.Add("Filter-Add"); Icons.Add("Business-Man"); Icons.Add("Business-Man-Settings-01"); Icons.Add("Briefcase-Standard"); Icons.Add("Filter-Edit"); Icons.Add("Message-Add"); Icons.Add("Filter - 02"); Icons.Add("Business-Man-Delete-01"); Icons.Add("Bullets - 05"); Icons.Add("Cupboard"); Icons.Add("Digital - Five"); Icons.Add("Cupboard - Down"); Icons.Add("Sort-Ascending-01"); Icons.Add("Cupboard - 03"); Icons.Add("Bullets - 03"); Icons.Add("Data-Refresh"); Icons.Add("Message-Information"); Icons.Add("Filter - 04"); Icons.Add("Data-Edit"); Icons.Add("Sort-Ascending"); Icons.Add("Filter-Settings"); Icons.Add("Message-Edit"); Icons.Add("Bullets - 01"); Icons.Add("Business-Man-Find"); Icons.Add("Data-Previous"); Icons.Add("Data-Find"); Icons.Add("Digital - Three"); Icons.Add("Briefcase - 01"); Icons.Add("Digital - Two"); Icons.Add("Data Transfer -01"); Icons.Add("Data-Certificate"); Icons.Add("Digital - One"); Icons.Add("Filter-New"); Icons.Add("Business-Man-Add-02"); Icons.Add("Digital - Eight"); Icons.Add("Data-Access-Restricted"); Icons.Add("Sort-Descending-01"); Icons.Add("Sort-Descending"); #endregion return Icons; } /// <summary> /// Gets the application icon. /// </summary> /// <returns>The application icon.</returns> private ObservableCollection<string> GetApplicationIcon() { ObservableCollection<string> Icons = new ObservableCollection<string>(); #region Add Application icons name Icons.Add("Bookmark-Up"); Icons.Add("Product Box-02-WF"); Icons.Add("User OK-02-WF"); Icons.Add("Stack-02"); Icons.Add("Data-Collapse"); Icons.Add("User Modify1-WF"); Icons.Add("Pressure-01-WF"); Icons.Add("Cut"); Icons.Add("Text Decoration - 01"); Icons.Add("Share-03"); Icons.Add("Maximize - 02"); Icons.Add("Mobile-Phone-Message"); Icons.Add("Mail Settings"); Icons.Add("Calendar1-WF"); Icons.Add("Requirement-02-WF"); Icons.Add("Phonebook Info"); Icons.Add("File-Format-ZIP"); Icons.Add("User Delete-01-WF"); Icons.Add("Bullet-WF"); Icons.Add("Webpage Next-WF"); Icons.Add("Music Icon-WF"); Icons.Add("Pointer-WF"); Icons.Add("Forest Fire"); Icons.Add("WebPage Search"); Icons.Add("Task-01"); Icons.Add("Media Next-WF"); Icons.Add("Media Forward-WF"); Icons.Add("Arrowhead-Left-01"); Icons.Add("Computer that is Member of security goup-WF"); Icons.Add("Rope Lasso-WF"); Icons.Add("File Next-WF"); Icons.Add("Wind-03-WF"); Icons.Add("Search-WF"); Icons.Add("User Settings-02-WF"); Icons.Add("Text Decoration2-WF"); Icons.Add("Check-03"); Icons.Add("Phonebook Search-WF"); Icons.Add("Navigation-Down-Right"); Icons.Add("Cut-WF"); Icons.Add("Connection to Multiple Computer-WF"); Icons.Add("Textdecorations-01-WF"); Icons.Add("Margin - 01"); Icons.Add("Movie Next-WF"); Icons.Add("Networks-WF"); Icons.Add("Message Voice Mail2-WF"); Icons.Add("Link - 01"); Icons.Add("Link - 03"); Icons.Add("Link - 02"); Icons.Add("Link - 05"); Icons.Add("Link - 04"); Icons.Add("Link - 07"); Icons.Add("Link - 06"); Icons.Add("Temporary Folder"); Icons.Add("Contacts Save"); Icons.Add("Favorite Delete-WF"); Icons.Add("Send to back-WF"); Icons.Add("Calculator-02-WF"); Icons.Add("Vertical align Center-WF"); Icons.Add("Volume Down 1-WF"); Icons.Add("Bookmarks-WF"); Icons.Add("User Modify-WF"); Icons.Add("Message Mail-WF"); Icons.Add("User Favourite-01-WF"); Icons.Add("Move-WF"); Icons.Add("Text Decoration - 05"); Icons.Add("Folders-WF"); Icons.Add("Document-Settings-01"); Icons.Add("Text Decoration - 11"); Icons.Add("File-Format-EPS"); Icons.Add("Noise"); Icons.Add("Pressure-03-WF"); Icons.Add("DocumentCheck-WF"); Icons.Add("Mug-02-WF"); Icons.Add("Drag - 01"); Icons.Add("Disc-Error"); Icons.Add("Contacts Find"); Icons.Add("Favourites Delete"); Icons.Add("Document-Share-01"); Icons.Add("Calendar edit-WF"); Icons.Add("Bookmark Add-WF"); Icons.Add("Loading4-WF"); Icons.Add("Bookmark Remove-WF"); Icons.Add("Web Page Info"); Icons.Add("Mail-Box"); Icons.Add("ArrowHeadRight-WF"); Icons.Add("Contact Edit-WF"); Icons.Add("Folder Remove-WF"); Icons.Add("Lambda-WF"); Icons.Add("User Unlocked-02-WF"); Icons.Add("Add-New"); Icons.Add("Web Page Upload"); Icons.Add("Mail Unlocked-WF"); Icons.Add("Movie OK-WF"); Icons.Add("Phonebook remove-WF"); Icons.Add("Orientation Portrait-02-WF"); Icons.Add("MailRefresh-WF"); Icons.Add("Rating 1-WF"); Icons.Add("User Save -01-WF"); Icons.Add("Basket-WF"); Icons.Add("Find-Previous"); Icons.Add("Document-01"); Icons.Add("Stack add"); Icons.Add("Favorite Search-WF"); Icons.Add("File"); Icons.Add("Black List-WF"); Icons.Add("Mail Delete-WF"); Icons.Add("Clipboard Next-WF"); Icons.Add("Volume Up 1 -WF"); Icons.Add("Favourites Previous"); Icons.Add("Calendar-Next-WF"); Icons.Add("Movie Find"); Icons.Add("Active Directory"); Icons.Add("File-WF"); Icons.Add("CD Software-WF"); Icons.Add("Visual-Studio"); Icons.Add("Text Braille-WF"); Icons.Add("Folder-Open-01"); Icons.Add("Password-Text-01"); Icons.Add("Text Decoration - 09"); Icons.Add("Media Rewind -01"); Icons.Add("Movie Remove"); Icons.Add("File Upload"); Icons.Add("MS System settings Configuration Manger-01"); Icons.Add("Display Brightness-WF"); Icons.Add("Movie Info-WF"); Icons.Add("Horizontal-Align-Left"); Icons.Add("CD New-WF"); Icons.Add("Navigation UpLeft-WF"); Icons.Add("Movie Download-WF"); Icons.Add("Hook1-WF"); Icons.Add("Timer"); Icons.Add("Para Mark - 02"); Icons.Add("Folder Remove 2-WF"); Icons.Add("Document-02"); Icons.Add("Message Voice Mail1-WF"); Icons.Add("Mail -03"); Icons.Add("Contacts edit"); Icons.Add("File Setting-WF"); Icons.Add("File Sync-WF"); Icons.Add("Document ZoomIn-WF"); Icons.Add("Text-Mark"); Icons.Add("Phonebook UnLocked"); Icons.Add("DocumentSave-WF"); Icons.Add("Tsunami"); Icons.Add("Agreement-02"); Icons.Add("Top-WF"); Icons.Add("Mail Search"); Icons.Add("Webpage Sync-WF"); Icons.Add("Show"); Icons.Add("Phonebook , upload"); Icons.Add("Movie Refresh-WF"); Icons.Add("Blog-WF"); Icons.Add("User Help"); Icons.Add("Folder-Edit"); Icons.Add("Text-Braille"); Icons.Add("Phonebook- WF"); Icons.Add("Product-Box"); Icons.Add("File Next"); Icons.Add("Folder-Download-02"); Icons.Add("Data Erase-WF"); Icons.Add("Media Play1-WF"); Icons.Add("Network-01"); Icons.Add("Document ZoomOut-WF"); Icons.Add("CD-Pause-WF"); Icons.Add("Folder-Remove-03"); Icons.Add("MS System Setting3-WF"); Icons.Add("Align-Center"); Icons.Add("Pressure"); Icons.Add("Globe-01-WF"); Icons.Add("Key-Hash-WF"); Icons.Add("Favourites Search"); Icons.Add("Navigation-Up-Left"); Icons.Add("User Search-01-WF"); Icons.Add("Sync-WF"); Icons.Add("Media Previous"); Icons.Add("Rating - 03"); Icons.Add("Arrowhead-Down"); Icons.Add("Movie unlocked"); Icons.Add("Media-Play"); Icons.Add("Webpage Remove-WF"); Icons.Add("Black List"); Icons.Add("Web Page "); Icons.Add("Folder-Movie-03"); Icons.Add("Calender Refresh-WF"); Icons.Add("Document Warning-01-WF"); Icons.Add("MS system setting2-WF"); Icons.Add("File Refresh-WF"); Icons.Add("Zoom - corner - 04"); Icons.Add("Comodo Dragon"); Icons.Add("Network-Drives"); Icons.Add("Web Page Ok"); Icons.Add("Arrowhead-Top"); Icons.Add("Movie Lock1-WF"); Icons.Add("User Favourites-02-WF"); Icons.Add("Media Previous-WF"); Icons.Add("Phonebook Ok"); Icons.Add("Webpage Split-WF"); Icons.Add("UpArrow-01-WF"); Icons.Add("File Lock-WF"); Icons.Add("Favourites"); Icons.Add("Requirement-05-WF"); Icons.Add("Loading - 10"); Icons.Add("Calendar Delete"); Icons.Add("DataMerge-WF"); Icons.Add("Folder-Find-01"); Icons.Add("File Delete-WF"); Icons.Add("UpArrow-WF"); Icons.Add("Documents-01"); Icons.Add("Arrowhead-Right-01"); Icons.Add("Trash can - 03"); Icons.Add("Phonebook Refresh"); Icons.Add("Phonebook settings-WF"); Icons.Add("Web Search-WF"); Icons.Add("Mail Ok"); Icons.Add("DocumentRefresh-WF"); Icons.Add("Document-Delete-01"); Icons.Add("Media-Back"); Icons.Add("Folder-Remove-04"); Icons.Add("Single Quotation Mark-WF"); Icons.Add("Phonebook Favourites"); Icons.Add("Maximize4-WF"); Icons.Add("Folder Add 1-WF"); Icons.Add("Calendar Help"); Icons.Add("Webpage Favourites-WF"); Icons.Add("Calendar Save"); Icons.Add("User Remove"); Icons.Add("Media Eject"); Icons.Add("Phonebook refresh-WF"); Icons.Add("User Search"); Icons.Add("Phonebook Next"); Icons.Add("View Details 2-WF"); Icons.Add("Maximize1-WF"); Icons.Add("User Next-02-WF"); Icons.Add("Mail Favorite-WF"); Icons.Add("RSS-Feeds"); Icons.Add("CCleaner"); Icons.Add("Movie Save"); Icons.Add("Contact Next-WF"); Icons.Add("Blog"); Icons.Add("Message-Mail"); Icons.Add("Favorite Next-WF"); Icons.Add("Orientation Portrait-01-WF"); Icons.Add("Speaker - 04"); Icons.Add("Phonebook Edit-WF"); Icons.Add("Stop Media-01-WF"); Icons.Add("Wifi-WF"); Icons.Add("Sort Ascending-WF"); Icons.Add("Connection to multiple computer"); Icons.Add("Favourites locked"); Icons.Add("Bookmark Settings"); Icons.Add("Move - 01"); Icons.Add("Stack-04-WF"); Icons.Add("Text Decoration-04"); Icons.Add("Maximize -03"); Icons.Add("Mail Previous-WF"); Icons.Add("Mug-03-WF"); Icons.Add("List all security groups on computer"); Icons.Add("Visual-Studio-2011"); Icons.Add("Animation-01"); Icons.Add("User Sync-01-WF"); Icons.Add("Loading6-WF"); Icons.Add("Para Mark - 03"); Icons.Add("Folder-Zoom-Out-01"); Icons.Add("Login-01"); Icons.Add("Text Decoration - 10"); Icons.Add("Rating - 02"); Icons.Add("Folder-New"); Icons.Add("Link12-WF"); Icons.Add("User Refresh"); Icons.Add("Contacts Ok-WF"); Icons.Add("Phonebook favourite -WF"); Icons.Add("Wind-02-WF"); Icons.Add("Help - 01"); Icons.Add("Help - 02"); Icons.Add("Folder-Zoom-In"); Icons.Add("File Ok"); Icons.Add("Document-New"); Icons.Add("Contact Refresh-WF"); Icons.Add("Loading1-WF"); Icons.Add("Folder-Cube-01"); Icons.Add("Up Arrow - 02"); Icons.Add("Up Arrow - 03"); Icons.Add("Up Arrow - 01"); Icons.Add("Format-Bullets-02"); Icons.Add("Format-Bullets-01"); Icons.Add("Add Computer"); Icons.Add("Phonebook help-WF"); Icons.Add("Play once-02-WF"); Icons.Add("Bookmark Info"); Icons.Add("CD Catalog-01-WF"); Icons.Add("Sort-Descending"); Icons.Add("Mail,Find"); Icons.Add("Folder Zoom In -WF"); Icons.Add("Favorite-Remove-WF"); Icons.Add("Login-Arrow"); Icons.Add("User Globe-WF"); Icons.Add("Dialog box About-WF"); Icons.Add("Upload - 02"); Icons.Add("Window Horizontal Split-WF"); Icons.Add("Media-Start"); Icons.Add("User Edit-02-WF"); Icons.Add("Folder-Upload-02"); Icons.Add("Arrow Down-WF"); Icons.Add("Maximize3-WF"); Icons.Add("Favorite Add-WF"); Icons.Add("Favorite Ok-WF"); Icons.Add("Data-Exchange"); Icons.Add("User Settings"); Icons.Add("Window-Delete"); Icons.Add("Movie edit"); Icons.Add("Volume-Up"); Icons.Add("User Upload-02-WF"); Icons.Add("Calendar info-WF"); Icons.Add("Align-Horizontal-Center"); Icons.Add("Restore-02"); Icons.Add("Movie Next"); Icons.Add("Favourites Add"); Icons.Add("Vibration-WF"); Icons.Add("Movie Edit-WF"); Icons.Add("Movie Help-WF"); Icons.Add("Data-Export"); Icons.Add("Hide"); Icons.Add("Phonebook Find"); Icons.Add("Media Fast-forward - 01"); Icons.Add("Login2-WF"); Icons.Add("Water Recycling-WF"); Icons.Add("Mouse-Drag"); Icons.Add("Edit-WF"); Icons.Add("Row Selection-WF"); Icons.Add("Loading - 05"); Icons.Add("Maximize2-WF"); Icons.Add("Align-Left"); Icons.Add("Tasks"); Icons.Add("Arrowhead-Up"); Icons.Add("Folder OK-WF"); Icons.Add("Cloud"); Icons.Add("Shape cube-WF"); Icons.Add("Bookmarks Upload"); Icons.Add("Infrared"); Icons.Add("Google Drive"); Icons.Add("View-Incident"); Icons.Add("Row-Selection"); Icons.Add("Data-Information"); Icons.Add("Help"); Icons.Add("Stack-01"); Icons.Add("Contacts upload"); Icons.Add("Upload - 01"); Icons.Add("Folder-Picture"); Icons.Add("Mail - Sent"); Icons.Add("Web Page Refresh"); Icons.Add("Favourites Download"); Icons.Add("Bookmark-Settings"); Icons.Add("CD-Valid"); Icons.Add("File Search"); Icons.Add("Data Merge-WF"); Icons.Add("Bookmarks favourites"); Icons.Add("Product Box With Disc-01-WF"); Icons.Add("Command Undo-WF"); Icons.Add("Virtual Apps-WF"); Icons.Add("Tile shape - 01"); Icons.Add("Upload-01-WF"); Icons.Add("Upload-02-WF"); Icons.Add("Expansion-02-WF"); Icons.Add("Calendar-02"); Icons.Add("Basket"); Icons.Add("Media First"); Icons.Add("Conference-Call-03"); Icons.Add("Document-Error"); Icons.Add("Bookmark Delete01-WF"); Icons.Add("Expansion - 01"); Icons.Add("Phonebook Sync-WF"); Icons.Add("Folder-Share-01"); Icons.Add("Movie Delete"); Icons.Add("Contacts Upload-WF"); Icons.Add("Document-Check"); Icons.Add("Link"); Icons.Add("Graphics-Card"); Icons.Add("Volume Up-WF"); Icons.Add("CD-View"); Icons.Add("Requirement-04-WF"); Icons.Add("Paragraph-Indent-Increase"); Icons.Add("Adobe-Illustrator"); Icons.Add("Numbering "); Icons.Add("Earth Quake"); Icons.Add("Drag-02"); Icons.Add("Navigation-Right"); Icons.Add("Window-WF"); Icons.Add("Favourites Next -2"); Icons.Add("Speaker Audible-WF"); Icons.Add("Bookmark Save"); Icons.Add("Loading - 01"); Icons.Add("Bookmark Upload-WF"); Icons.Add("Loading - 08"); Icons.Add("Speaker low - 02"); Icons.Add("FavoriteSetting-WF"); Icons.Add("All software updates that are installed in computer"); Icons.Add("Command-Refresh-01"); Icons.Add("Tsunami-01-WF"); Icons.Add("Clipboard Next Down"); Icons.Add("Speaker Increase - 02"); Icons.Add("Speaker Increase - 01"); Icons.Add("Webpage Save-WF"); Icons.Add("Windows Tablet-WF"); Icons.Add("Mail Sync"); Icons.Add("Text Decoration - 04"); Icons.Add("Device Tablet-WF"); Icons.Add("RSS Feed-WF"); Icons.Add("Favourite-WF"); Icons.Add("Folder New -WF"); Icons.Add("Reload-WF"); Icons.Add("Contacts info"); Icons.Add("Folder Movie-WF"); Icons.Add("Check-04-WF"); Icons.Add("Bookmark Find"); Icons.Add("Add Computer-WF"); Icons.Add("Movie Search"); Icons.Add("Mug-04-WF"); Icons.Add("Windows-Environment"); Icons.Add("Folder-Delete-01"); Icons.Add("File-Format-PPT"); Icons.Add("Movie Settings"); Icons.Add("Listen-WF"); Icons.Add("File Share-WF"); Icons.Add("Folder-Music-02"); Icons.Add("View-Medium-Icons-01"); Icons.Add("Mail Previous"); Icons.Add("Display-Contrast-02"); Icons.Add("Burn-Disk-01-WF"); Icons.Add("Horizontal-Align-Right"); Icons.Add("To Do List 2-WF"); Icons.Add("Contact Remove-WF"); Icons.Add("Key-Access-01"); Icons.Add("Document-Warning-01"); Icons.Add("Garbage-Closed"); Icons.Add("Folder-Upload"); Icons.Add("Power-Off"); Icons.Add("Spell Check-WF"); Icons.Add("Format-Bullets"); Icons.Add("Brackets-square-WF"); Icons.Add("File-Format-Mp3"); Icons.Add("Data-Erase"); Icons.Add("Tile-04-WF"); Icons.Add("Globe"); Icons.Add("Bookmark Edit-WF"); Icons.Add("Folder Search-WF"); Icons.Add("Speaker-02"); Icons.Add("Gsm Tower"); Icons.Add("Bookmark Info-WF"); Icons.Add("Folder-Download"); Icons.Add("Database Connection"); Icons.Add("Media Rewind"); Icons.Add("Sort-Ascending"); Icons.Add("Document Favourite-WF"); Icons.Add("Text Decoration - 08"); Icons.Add("Mail Add"); Icons.Add("Hide-WF"); Icons.Add("Movie Save-WF"); Icons.Add("Computer-Desktop"); Icons.Add("Mail unlocked"); Icons.Add("Noise-02-WF"); Icons.Add("Phonebook , download"); Icons.Add("User Download-02-WF"); Icons.Add("Animation-1-WF"); Icons.Add("Wind"); Icons.Add("File Help-WF"); Icons.Add("Link11-WF"); Icons.Add("Bookmark-Down"); Icons.Add("List of all application installed on computer-WF"); Icons.Add("Braces-WF"); Icons.Add("Window-Information"); Icons.Add("Document-Warning"); Icons.Add("Attachment-01-WF"); Icons.Add("Message Warning-WF"); Icons.Add("CD View-WF"); Icons.Add("File-Format-TIFF"); Icons.Add("View Details-WF"); Icons.Add("Scale to Fit-02"); Icons.Add("Check-02"); Icons.Add("Align-Justify"); Icons.Add("Web Page Delete-WF"); Icons.Add("Calendar Ok-WF"); Icons.Add("Pen Line -WF"); Icons.Add("Phonebook Remove"); Icons.Add("Folder-Empty"); Icons.Add("Mouse Drag-WF"); Icons.Add("Document Edit-WF"); Icons.Add("Folder-Add"); Icons.Add("Document-Exchange"); Icons.Add("Horizontal Align Left-WF"); Icons.Add("Trash Can-WF"); Icons.Add("Movie Sync-WF"); Icons.Add("Mail info"); Icons.Add("To Do List-WF"); Icons.Add("Save"); Icons.Add("C Sharp-02"); Icons.Add("User Profile 1-WF"); Icons.Add("Expansion - 02"); Icons.Add("Mug"); Icons.Add("Contact info-WF"); Icons.Add("DocumentExchange-WF"); Icons.Add("User Upload-01-WF"); Icons.Add("Calender-03-WF"); Icons.Add("Calendar -01 "); Icons.Add("Command-Paste"); Icons.Add("Vertical-Align-Bottom"); Icons.Add("Contact Save-WF"); Icons.Add("Phonebook Search"); Icons.Add("File Delete"); Icons.Add("Search-Find"); Icons.Add("Tile shape - 02"); Icons.Add("Favorite Help-WF"); Icons.Add("Full-Screen-Expand"); Icons.Add("Volume Speaker 1-WF"); Icons.Add("Column-Selection-WF"); Icons.Add("Data-Files"); Icons.Add("Up arrow"); Icons.Add("Document-Edit"); Icons.Add("Zoom vertical - 02"); Icons.Add("Contacts Ok"); Icons.Add("Text Decoration-05"); Icons.Add("Login3-WF"); Icons.Add("Arrow"); Icons.Add("Arrow-Expand"); Icons.Add("User-Login"); Icons.Add("Tiles-03-WF"); Icons.Add("Media Pause"); Icons.Add("Data-Edit"); Icons.Add("Login-WF"); Icons.Add("Text-Edit"); Icons.Add("Mail info-WF"); Icons.Add("Full Screen Collapsed-WF"); Icons.Add("Window-New-Open"); Icons.Add("Contacts Locked"); Icons.Add("File favourite"); Icons.Add("Calculator-02"); Icons.Add("Calculator-01"); Icons.Add("User Favourites"); Icons.Add("Agreement-01"); Icons.Add("Money Coin-02-WF"); Icons.Add("Horizontal Align Right-WF"); Icons.Add("Warning Shield-WF"); Icons.Add("Measurement-WF"); Icons.Add("Calendar Add"); Icons.Add("Folder Share-WF"); Icons.Add("Calender Previous-WF"); Icons.Add("Text-Read"); Icons.Add("Document-Download-01"); Icons.Add("Loading - 11"); Icons.Add("User Previous-WF"); Icons.Add("File info"); Icons.Add("Phonebook Help"); Icons.Add("CD-Music"); Icons.Add("Web Page Favourites"); Icons.Add("Zoom Corner1-WF"); Icons.Add("Phonebook Add-WF"); Icons.Add("Bookmark Previous"); Icons.Add("Find-Replace-01"); Icons.Add("Webpage New open1-WF"); Icons.Add("Folder Download-WF"); Icons.Add("Windows Tablet"); Icons.Add("Expand-03"); Icons.Add("Contacts favourites"); Icons.Add("Expand-01"); Icons.Add("User Search--02WF"); Icons.Add("Data-Share"); Icons.Add("Security Group Member"); Icons.Add("Tiles"); Icons.Add("Mail -Open"); Icons.Add("Contacts Download"); Icons.Add("Bookmark Favourities-WF"); Icons.Add("Globe-02-WF"); Icons.Add("Favourites Refresh"); Icons.Add("Phonebook Next-WF"); Icons.Add("User Save"); Icons.Add("Mail Next-WF"); Icons.Add("Virtual-Apps"); Icons.Add("AlignRight-WF"); Icons.Add("Quotation Mark-WF"); Icons.Add("Scale-To-Fit"); Icons.Add("Share-02-WF"); Icons.Add("Data-Synchronize"); Icons.Add("File Unlock-WF"); Icons.Add("Clipboard1-WF"); Icons.Add("Rectangle-WF"); Icons.Add("Folder-New-01"); Icons.Add("Calendar Locked-WF"); Icons.Add("AlignCenter-WF"); Icons.Add("Contacts Refresh"); Icons.Add("Reload-01-WF"); Icons.Add("Favourites Upload"); Icons.Add("CD Music-WF"); Icons.Add("Tab History-WF"); Icons.Add("File-Format-Icon"); Icons.Add("Mail Upload-WF"); Icons.Add("Folder Upload-WF"); Icons.Add("Connection to a Computer"); Icons.Add("User"); Icons.Add("Connection to a Computer-WF"); Icons.Add("Adobe-Dreamweaver"); Icons.Add("User Add"); Icons.Add("User-Add"); Icons.Add("Ellipse-Selection"); Icons.Add("Bookmark Ok-WF"); Icons.Add("Installation-03"); Icons.Add("Measurements - 03"); Icons.Add("Measurements - 02"); Icons.Add("Measurements - 01"); Icons.Add("Text Decoration - 13"); Icons.Add("Calendar Ok"); Icons.Add("Measurements - 04"); Icons.Add("Orientation landscape-01-WF"); Icons.Add("Key-Hash"); Icons.Add("View-Tiles"); Icons.Add("Document-Find-02"); Icons.Add("Command-Undo"); Icons.Add("Message-Voice-Mail"); Icons.Add("File Remove-WF"); Icons.Add("Movie Upload-WF"); Icons.Add("User Save-02-WF"); Icons.Add("Arrowhead-01"); Icons.Add("Webpage Upload-WF"); Icons.Add("Phonebook Sync"); Icons.Add("User Download"); Icons.Add("MS System Setting-WF"); Icons.Add("Bookmark-Delete"); Icons.Add("Password-Text"); Icons.Add("Mug-01-WF"); Icons.Add("View List-WF"); Icons.Add("To do list - 03"); Icons.Add("Loading2-WF"); Icons.Add("Disc-Information"); Icons.Add("Movie Help"); Icons.Add("Hook"); Icons.Add("Zoom Horizontal - 02"); Icons.Add("Check-01"); Icons.Add("Document Sharing-WF"); Icons.Add("Favorite Sync-WF"); Icons.Add("Conference-Call-02"); Icons.Add("Link10-WF"); Icons.Add("Save-02-WF"); Icons.Add("Bookmark Refresh-WF"); Icons.Add("Device-Headphone"); Icons.Add("Contacts"); Icons.Add("User Sync"); Icons.Add("Calendar Next"); Icons.Add("File-Torrent"); Icons.Add("Bring to Front-WF"); Icons.Add("Windows"); Icons.Add("Movie Download"); Icons.Add("Favorite Download-WF"); Icons.Add("Connectivity-Error-WF"); Icons.Add("Folder-Open-03"); Icons.Add("Database-WF"); Icons.Add("Display-Contrast"); Icons.Add("BookMarks"); Icons.Add("Execute multiple queries"); Icons.Add("Gear--03WF"); Icons.Add("Arrowhead Top-WF"); Icons.Add("Tile-01-WF"); Icons.Add("File Ok-WF"); Icons.Add("Way-Board"); Icons.Add("Speaker low -01"); Icons.Add("File lock"); Icons.Add("Web Page Settings"); Icons.Add("Vertical-Align-Center"); Icons.Add("Document Next-WF"); Icons.Add("Clipboard-Next"); Icons.Add("Mail edit"); Icons.Add("Group Delete-WF"); Icons.Add("Web Page refresh"); Icons.Add("Calender Upload-WF"); Icons.Add("Column-Selection"); Icons.Add("Calendar Help-WF"); Icons.Add("Favourites Next"); Icons.Add("Webpage Info-WF"); Icons.Add("Mobile-Phone-Music"); Icons.Add("Folder Edit 1-WF"); Icons.Add("Document-Music-02"); Icons.Add("Attachment-02-WF"); Icons.Add("Money-Credit-Card"); Icons.Add("Document Music-02-WF"); Icons.Add("Installation-WF"); Icons.Add("Speaker Decrease - 01"); Icons.Add("Margin - 02"); Icons.Add("Lambda-01"); Icons.Add("Book-Close"); Icons.Add("Loading - 06"); Icons.Add("Audit"); Icons.Add("CD-Warning"); Icons.Add("User Ok-01-WF"); Icons.Add("Movie Fav"); Icons.Add("Active Dictionary-WF"); Icons.Add("Free Hand Selection-WF"); Icons.Add("Calendar -02"); Icons.Add("Movie Sync"); Icons.Add("File Settings"); Icons.Add("Volume-Mute"); Icons.Add("Mail next"); Icons.Add("Favourites Ok"); Icons.Add("Group-Add"); Icons.Add("Speaker - 03"); Icons.Add("Text Decoration - 03"); Icons.Add("User Remove-02-WF"); Icons.Add("Mail Favourites"); Icons.Add("Favorite upload-WF"); Icons.Add("Window-Earth"); Icons.Add("Folder-Upload-01"); Icons.Add("Loading5-WF"); Icons.Add("Mail download"); Icons.Add("MailBox-WF"); Icons.Add("Phonebook Locked"); Icons.Add("User Next"); Icons.Add("Text Decoration - 07"); Icons.Add("Tile-02"); Icons.Add("Media Last"); Icons.Add("Group-Modify"); Icons.Add("Calender Remove-WF"); Icons.Add("CD-Play"); Icons.Add("File-Format-TGA"); Icons.Add("Media-Play-02"); Icons.Add("User Info-01-WF"); Icons.Add("Media-Play-01"); Icons.Add("Window-Horizontal-Split"); Icons.Add("MS System Setting4-WF"); Icons.Add("Volume Icon"); Icons.Add("Vibration"); Icons.Add("Crop"); Icons.Add("Check-02-WF"); Icons.Add("User Refresh-01-WF"); Icons.Add("Calendar Find-WF"); Icons.Add("Movie Ok"); Icons.Add("Contacts Delete"); Icons.Add("Assign-WF"); Icons.Add("Garbage Full1-WF"); Icons.Add("Media-Fast-Forward"); Icons.Add("Favourites Info"); Icons.Add("Zoom Horizontal - 01"); Icons.Add("Favourites favourites"); Icons.Add("Phonebook Previous-WF"); Icons.Add("Contacts Add"); Icons.Add("User Previous1-WF"); Icons.Add("Webpage Find"); Icons.Add("Loading - 09"); Icons.Add("Trash can - 01"); Icons.Add("Favourites Download-2"); Icons.Add("Movie Add-WF"); Icons.Add("Contacts help"); Icons.Add("Gear-02-WF"); Icons.Add("Recycle-Bin "); Icons.Add("Web Page add"); Icons.Add("Pointer"); Icons.Add("Share-01"); Icons.Add("Layers-WF"); Icons.Add("Media-Player-Winamp"); Icons.Add("Format Bullet1-WF"); Icons.Add("Installation-02"); Icons.Add("Movie Previous"); Icons.Add("Money-Gold"); Icons.Add("Volume Mute 1-WF"); Icons.Add("Orientation-Landscape"); Icons.Add("Group Modify-WF"); Icons.Add("Zoom Vertical-WF"); Icons.Add("CD-Stop"); Icons.Add("Mail"); Icons.Add("Network-Signal"); Icons.Add("Mail Edit-WF"); Icons.Add("User Find"); Icons.Add("Bookmark Delete"); Icons.Add("List All Application installed on computer-WF"); Icons.Add("Document Unlocked-WF"); Icons.Add("Document-Zoom-Out-02"); Icons.Add("Margin-WF"); Icons.Add("Movie"); Icons.Add("Contacts-Delete-WF"); Icons.Add("Phonebook Download-WF"); Icons.Add("DataHistogram-WF"); Icons.Add("Device-Radio"); Icons.Add("Group-WF"); Icons.Add("Installation-01"); Icons.Add("Paragraph-Indent-Decrease"); Icons.Add("Bookmark Add1-WF"); Icons.Add("Zip file-03-WF"); Icons.Add("Arrowhead Right1-WF"); Icons.Add("UpArrow Line-03-WF"); Icons.Add("Save-01-WF"); Icons.Add("SCCM"); Icons.Add("Data Export-WF"); Icons.Add("Log Out-WF"); Icons.Add("Bookmark Search"); Icons.Add("Down Arrow-WF"); Icons.Add("Crop - 01"); Icons.Add("Add csv-02-WF"); Icons.Add("Web Page Delete"); Icons.Add("Calendar Upload"); Icons.Add("Text Decoration - 02"); Icons.Add("Contacts Remove"); Icons.Add("Stack-02-WF"); Icons.Add("Orientation-Portrait"); Icons.Add("Movie Upload"); Icons.Add("User Sync-02-WF"); Icons.Add("Speaker Low-WF"); Icons.Add("CD Catalog-02"); Icons.Add("CD Catalog-01"); Icons.Add("Submit-02"); Icons.Add("User Refresh-02-WF"); Icons.Add("Submit-01"); Icons.Add("Reqiurement-03-WF"); Icons.Add("Folder Edit-WF"); Icons.Add("Black List Folder-WF"); Icons.Add("Scale to Fi-03t-WF"); Icons.Add("Slash"); Icons.Add("Application-01"); Icons.Add("Document Download-WF"); Icons.Add("User Locked-02-WF"); Icons.Add("Phonebook Save-WF"); Icons.Add("View-Small-Icons-01"); Icons.Add("Stack Add-WF"); Icons.Add("CD Play-WF"); Icons.Add("User Unlocked-01-WF"); Icons.Add("Zoom - corner - 01"); Icons.Add("Brackets-Square"); Icons.Add("Web Page Next"); Icons.Add("Hide1-WF"); Icons.Add("DocumentPrevious-WF"); Icons.Add("Folder-Movie"); Icons.Add("Document Setting-WF"); Icons.Add("File unlock"); Icons.Add("Document-WF"); Icons.Add("Phonebook Settings"); Icons.Add("Money Coin-01-WF"); Icons.Add("Web Page Add-WF"); Icons.Add("View Medium icons-WF"); Icons.Add("Media Next"); Icons.Add("Bookmarks locked"); Icons.Add("Expand-02-WF"); Icons.Add("Expand-01-WF"); Icons.Add("Data-Split"); Icons.Add("Calendar Favourite"); Icons.Add("Folder-Add-04"); Icons.Add("Gear-01-WF"); Icons.Add("Favourite Previous-WF"); Icons.Add("Speaker Low1-WF"); Icons.Add("Mouse Wireless-01-WF"); Icons.Add("Link6-WF"); Icons.Add("DocumentDelete-01-WF"); Icons.Add("Animation-02"); Icons.Add("Single-Curly-Quotation-Marks"); Icons.Add("Calendar locked"); Icons.Add("Bookmark Help"); Icons.Add("Money-Coin"); Icons.Add("Trash can - 04"); Icons.Add("Arrowhead-Left"); Icons.Add("Indent Decrease-WF"); Icons.Add("Rating-WF"); Icons.Add("UpArrow Line-01-WF"); Icons.Add("Phonebook Add"); Icons.Add("Avalanche"); Icons.Add("Document Help-WF"); Icons.Add("Add csv-01"); Icons.Add("File Find"); Icons.Add("Mail delete"); Icons.Add("Folder-Remove-01"); Icons.Add("Burn-Disk-01"); Icons.Add("Webpage locked-WF"); Icons.Add("Infrared1-WF"); Icons.Add("Infrared2-WF"); Icons.Add("Mail locked"); Icons.Add("Vertical-Align-Top"); Icons.Add("CD-Software"); Icons.Add("Maximize -04"); Icons.Add("Parenthesis-01-WF"); Icons.Add("Increase intend"); Icons.Add("Movie Unlock-WF"); Icons.Add("File edit"); Icons.Add("Timer-WF"); Icons.Add("File remove"); Icons.Add("Sync - 03"); Icons.Add("Sync - 02"); Icons.Add("Sync - 01"); Icons.Add("Drag -02"); Icons.Add("Check-WF"); Icons.Add("Volume Mute-WF"); Icons.Add("Bookmark-Add"); Icons.Add("UpArrow Line-04-WF"); Icons.Add("CD Pause-WF"); Icons.Add("Drag-01-WF"); Icons.Add("User Remove-01-WF"); Icons.Add("Movie Search-WF"); Icons.Add("ArrowheadLeft1-WF"); Icons.Add("Loading7-WF"); Icons.Add("Movie1-WF"); Icons.Add("Ellipse Selection-WF"); Icons.Add("Sort Descending-WF"); Icons.Add("Volume Down-WF"); Icons.Add("Folder-01"); Icons.Add("Folder-02"); Icons.Add("Folder-03"); Icons.Add("Folder-04"); Icons.Add("Folder-05"); Icons.Add("Folder-Add-05"); Icons.Add("Folder-Add-01"); Icons.Add("Folder-Add-02"); Icons.Add("Folder-Add-03"); Icons.Add("Requirement-01-WF"); Icons.Add("File Previous-WF"); Icons.Add("Data-Merge"); Icons.Add("Document-Settings"); Icons.Add("Crop - 02"); Icons.Add("CD-Pause"); Icons.Add("Network Drives-WF"); Icons.Add("Folder-Movie-01"); Icons.Add("File-Format-SWF"); Icons.Add("Zoom Corner-WF"); Icons.Add("View Tiles-WF"); Icons.Add("Mail - 01"); Icons.Add("Internet Facilities-WF"); Icons.Add("Web Page Previous"); Icons.Add("Mail Help"); Icons.Add("Adobe-Photoshop"); Icons.Add("Media-Player-VLC"); Icons.Add("Command-Reset"); Icons.Add("File Download-WF"); Icons.Add("Mail Add-WF"); Icons.Add("CD Warning-WF"); Icons.Add("Command Redo-WF"); Icons.Add("Bookmark remove"); Icons.Add("Windows login-WF"); Icons.Add("User Edit-01-WF"); Icons.Add("Para Mark - 01"); Icons.Add("Document Error-WF"); Icons.Add("Movie-WF"); Icons.Add("Contact Add-WF"); Icons.Add("Full-Screen-Collapse"); Icons.Add("Speaker Mute - 03"); Icons.Add("Webpage 1-WF"); Icons.Add("Contact previous-WF"); Icons.Add("Speaker Mute - 04"); Icons.Add("Folder Add-WF"); Icons.Add("Garbage-Full"); Icons.Add("Zip file-02-WF"); Icons.Add("DataSplit-WF"); Icons.Add("Way Board 3-WF"); Icons.Add("Loading8-WF"); Icons.Add("Favourites Unlocked"); Icons.Add("Data-Histogram"); Icons.Add("Mail Download-WF"); Icons.Add("Contacts Settings"); Icons.Add("Calendar unlocked"); Icons.Add("Underline"); Icons.Add("Certificate-02"); Icons.Add("Favorite Locked-WF"); Icons.Add("Bookmark Favourite-WF"); Icons.Add("Loading - 02"); Icons.Add("Media-Stop"); Icons.Add("Maximize-WF"); Icons.Add("Favourites Sync"); Icons.Add("Multiple WebPage-WF"); Icons.Add("Vertical Align Bottom-WF"); Icons.Add("Text Decoration - 12"); Icons.Add("Document-Zoom-Out"); Icons.Add("Media Fast-forward"); Icons.Add("Login-Door"); Icons.Add("Calendar Info"); Icons.Add("Bookmark Sync-WF"); Icons.Add("Restore-01"); Icons.Add("Rectangle-Selection"); Icons.Add("Bookmark add"); Icons.Add("Phonebook Delete"); Icons.Add("Book Close-WF"); Icons.Add("To do list - 01"); Icons.Add("Software is Available to install"); Icons.Add("Calendar Add-WF"); Icons.Add("Money-Coin-01"); Icons.Add("Calendar Settings"); Icons.Add("Skew-WF"); Icons.Add("Login Door1-WF"); Icons.Add("View-Details-01"); Icons.Add("User Setting-01-WF"); Icons.Add("To do list - 02"); Icons.Add("Tiles-01"); Icons.Add("File Previous"); Icons.Add("Document-Zoom-In-01"); Icons.Add("Favorite Unlocked-WF"); Icons.Add("Webpage Refresh-WF"); Icons.Add("Fit to Size-WF"); Icons.Add("Bookmark Previous-WF"); Icons.Add("Link4-WF"); Icons.Add("Mouse Wireless-02-WF"); Icons.Add("View-Small-Icons"); Icons.Add("Contact Sync-WF"); Icons.Add("Document-Download"); Icons.Add("Folder-Movie-02"); Icons.Add("Indent Increase-WF"); Icons.Add("Spell Check"); Icons.Add("WebPage-WF"); Icons.Add("Webpage ok-WF"); Icons.Add("ArrowUp-WF"); Icons.Add("Skew"); Icons.Add("Minimize-WF"); Icons.Add("Volume Speaker-WF"); Icons.Add("Contact Download-WF"); Icons.Add("Media End-WF"); Icons.Add("Folder-Ok"); Icons.Add("View-Details"); Icons.Add("Text-Highlight"); Icons.Add("Mail Save-WF"); Icons.Add("Book-Open"); Icons.Add("Text Decoration - 16"); Icons.Add("Vertical align Top-WF"); Icons.Add("Web Page Download"); Icons.Add("Phonebook edit"); Icons.Add("Zoom vertical - 01"); Icons.Add("Phonebook "); Icons.Add("Document-Exchange-01"); Icons.Add("Listen2-WF"); Icons.Add("Mail-WF"); Icons.Add("Webpage Download-WF"); Icons.Add("View-Medium-Icons"); Icons.Add("Movie Favorite-WF"); Icons.Add("Bookmark Delete-WF"); Icons.Add("CD-New"); Icons.Add("Document Find-WF"); Icons.Add("Phonebook Delete-WF"); Icons.Add("Password-02-WF"); Icons.Add("Favourites edit"); Icons.Add("Volume-Down"); Icons.Add("Bullet"); Icons.Add("Flash-Player"); Icons.Add("Web Page Find"); Icons.Add("Way Board-WF"); Icons.Add("Calendar -05"); Icons.Add("Group Add-WF"); Icons.Add("Document-Zoom-In-02"); Icons.Add("Money Coin-03-WF"); Icons.Add("Speaker - 02"); Icons.Add("User Add-WF"); Icons.Add("Phonebook Previous"); Icons.Add("Document-Save"); Icons.Add("User Upload"); Icons.Add("Minimize - 01"); Icons.Add("Webpage New open-WF"); Icons.Add("Check"); Icons.Add("Text Decoration-03"); Icons.Add("Layers"); Icons.Add("Calender-02-WF"); Icons.Add("User Add-01-WF"); Icons.Add("CD Valid-WF"); Icons.Add("Bookmark Save-WF"); Icons.Add("User Info"); Icons.Add("Group-Cluster"); Icons.Add("Document Music-WF"); Icons.Add("Media Rewind/Back-WF"); Icons.Add("Login-02"); Icons.Add("Document-Add"); Icons.Add("Audit-WF"); Icons.Add("Login Door2-WF"); Icons.Add("Align-Right"); Icons.Add("Despeckle-01"); Icons.Add("MS system setting1-WF"); Icons.Add("DocumentAdd-WF"); Icons.Add("Document-Find"); Icons.Add("Arrow-WF"); Icons.Add("FIle Save"); Icons.Add("UpArrow Line-02-WF"); Icons.Add("Maximize - 01"); Icons.Add("Folder-Music-01"); Icons.Add("Speaker Audible - 01"); Icons.Add("Para Mark-WF"); Icons.Add("Favorite Save-WF"); Icons.Add("ArrowheadLeft-WF"); Icons.Add("Movie Delete-WF"); Icons.Add("Folder-Connect"); Icons.Add("Expand-03-WF"); Icons.Add("Clipboard"); Icons.Add("Movie Previous-WF"); Icons.Add("BookMarks Sync"); Icons.Add("Shape-Cube"); Icons.Add("User Info-WF"); Icons.Add("User Next -01-WF"); Icons.Add("Bookmark Help-WF"); Icons.Add("Media-Pause"); Icons.Add("Device-Tablet"); Icons.Add("Loading - 03"); Icons.Add("Command-Redo"); Icons.Add("CD Catalog-02-WF"); Icons.Add("Data Collapse-WF"); Icons.Add("Mail Setting-WF"); Icons.Add("File-Format-PNG"); Icons.Add("Zoom - corner - 02"); Icons.Add("View-List"); Icons.Add("Contacts Search-WF"); Icons.Add("Way Board 2-WF"); Icons.Add("Password-03-WF"); Icons.Add("Noise-01-WF"); Icons.Add("Send-To-Back"); Icons.Add("User Help-02-WF"); Icons.Add("Zoom Horizontal-WF"); Icons.Add("Document-Music"); Icons.Add("Text Decoration - 06"); Icons.Add("Contacts Sync"); Icons.Add("Share-02"); Icons.Add("Play once-01-WF"); Icons.Add("File-Format-JPEG"); Icons.Add("Text Highlight-WF"); Icons.Add("Document Locked-WF"); Icons.Add("Expander down - 01"); Icons.Add("Webpage edit"); Icons.Add("Favourites remove"); Icons.Add("File Save-WF"); Icons.Add("Full Screen Expand-WF"); Icons.Add("File Edit-WF"); Icons.Add("Submit-02-WF"); Icons.Add("Link9-WF"); Icons.Add("Fit-To-Size"); Icons.Add("Submit-01-WF"); Icons.Add("Top"); Icons.Add("Link5-WF"); Icons.Add("Link2-WF"); Icons.Add("Link3-WF"); Icons.Add("Link1-WF"); Icons.Add("Movie Remove-WF"); Icons.Add("Way Board 1-WF"); Icons.Add("File add"); Icons.Add("Web Page Search"); Icons.Add("Add csv-02"); Icons.Add("Drop box"); Icons.Add("MailSync-WF"); Icons.Add("Document-Zoom-Out-01"); Icons.Add("Document-Error-01"); Icons.Add("Contact Settings-WF"); Icons.Add("Document-Share"); Icons.Add("Burn-Disk-02"); Icons.Add("Expand-02"); Icons.Add("Share-04-WF"); Icons.Add("Windows Environment-WF"); Icons.Add("Dialog-Box-About"); Icons.Add("Infrared-WF"); Icons.Add("Calender save-WF"); Icons.Add("Garbage-Open"); Icons.Add("Bookmark edit"); Icons.Add("Speaker Mute - 01"); Icons.Add("C Sharp-01"); Icons.Add("Quotation-Marks"); Icons.Add("Product-Box-With-Disc"); Icons.Add("Hook-WF"); Icons.Add("Command-Refresh"); Icons.Add("File Add-WF"); Icons.Add("Clipboard-Next-Down"); Icons.Add("Window-New"); Icons.Add("Document-Zoom-In"); Icons.Add("Reload - 01"); Icons.Add("Play-Once"); Icons.Add("Text Decoration-WF"); Icons.Add("Text-Italic"); Icons.Add("User Help -01-WF"); Icons.Add("Document Find-02-WF"); Icons.Add("Calendar Favorite-WF"); Icons.Add("Textdecorations"); Icons.Add("Tab-History"); Icons.Add("Tiles-02-WF"); Icons.Add("File-Format-BitMap"); Icons.Add("Bookmark Settings-WF"); Icons.Add("Agreement-WF"); Icons.Add("Text Decoration-06"); Icons.Add("Team-Viewer"); Icons.Add("Calendar download"); Icons.Add("Calendar Previous"); Icons.Add("AlignLeft-WF"); Icons.Add("Volume-Speaker-02"); Icons.Add("Volume-Speaker-01"); Icons.Add("Data Split-WF"); Icons.Add("Text"); Icons.Add("MailOk-WF"); Icons.Add("User previous"); Icons.Add("Connectivity-Error"); Icons.Add("Media Play2-WF"); Icons.Add("DocumentRemove-WF"); Icons.Add("Volume Speaker 2-WF"); Icons.Add("Stop Media--02WF"); Icons.Add("Task-02"); Icons.Add("Key Hash-WF"); Icons.Add("Tile Shape-WF"); Icons.Add("File Sync"); Icons.Add("Bookmark Down-WF"); Icons.Add("Favorite Info-WF"); Icons.Add("Movie Settings-WF"); Icons.Add("Movie refresh"); Icons.Add("Folder-Information"); Icons.Add("Contacts Help-WF"); Icons.Add("DocumentSync-WF"); Icons.Add("Drop Box-WF"); Icons.Add("Arrowhead down-WF"); Icons.Add("Text-Normal"); Icons.Add("Animation-03"); Icons.Add("Bookmark Locked-WF"); Icons.Add("WebPage Sync -2"); Icons.Add("Decrease Intend"); Icons.Add("Mail Help-WF"); Icons.Add("Bring-To-Front"); Icons.Add("Braces-01"); Icons.Add("Find Previous-WF"); Icons.Add("Task-01-WF"); Icons.Add("Document-Music-01"); Icons.Add("Share-03-WF"); Icons.Add("Free-Hand-Selection"); Icons.Add("Web Page Help"); Icons.Add("Rope-Lasso"); Icons.Add("User-WF"); Icons.Add("Contacts Search"); Icons.Add("Certificate-01"); Icons.Add("Phonebook Info-WF"); Icons.Add("Folder-Delete"); Icons.Add("Stack-03"); Icons.Add("Webpage Help-WF"); Icons.Add("Edit"); Icons.Add("Temporary folder1-WF"); Icons.Add("DataFiles-WF"); Icons.Add("E Doc Solution-WF"); Icons.Add("Listen"); Icons.Add("Numbering-01-WF"); Icons.Add("View Small Icons-WF"); Icons.Add("Task-02-WF"); Icons.Add("Conference-Call"); Icons.Add("Calendar edit"); Icons.Add("Hash-WF"); Icons.Add("WebPage Sync"); Icons.Add("File-Format-Wave"); Icons.Add("User-Modify"); Icons.Add("Music Icon"); Icons.Add("User that is member of security group"); Icons.Add("Stop Media"); Icons.Add("Calendar -03"); Icons.Add("Arrowhead-Right"); Icons.Add("Orientation landscape-02-WF"); Icons.Add("Parenthesis-03-WF"); Icons.Add("Log file icon"); Icons.Add("Contacts Next"); Icons.Add("Media Play-WF"); Icons.Add("Contacts UnLocked"); Icons.Add("FavoriteRefresh-WF"); Icons.Add("Movie Locked"); Icons.Add("To Do List 1-WF"); Icons.Add("Cloud-WF"); Icons.Add("File refresh"); Icons.Add("Folder Upload 1-WF"); Icons.Add("Product Box-03-WF"); Icons.Add("Loading3-WF"); Icons.Add("Folder-Remove-02"); Icons.Add("Trash Can1-WF"); Icons.Add("Speaker-01"); Icons.Add("Bookmark Refresh"); Icons.Add("Favourites Find"); Icons.Add("Mail Refresh"); Icons.Add("Folder Music-WF"); Icons.Add("List All Application installed on cmputer"); Icons.Add("User Ok"); Icons.Add("Media Pause-WF"); Icons.Add("Web Page unlocked"); Icons.Add("Movie Add"); Icons.Add("File Download"); Icons.Add("User Delete-02-WF"); Icons.Add("Garbage Full-WF"); Icons.Add("Folder Save-WF"); Icons.Add("Product Box -01-WF"); Icons.Add("Conference-Call-01"); Icons.Add("Document New-01-WF"); Icons.Add("Mail - 02"); Icons.Add("Message-Warning"); Icons.Add("Power plant-01-WF"); Icons.Add("Zip file-01-WF"); Icons.Add("Parenthesis"); Icons.Add("Data-Import"); Icons.Add("Web Page Remove"); Icons.Add("User Download-01-WF"); Icons.Add("File Favorite-WF"); Icons.Add("Database Connection-WF"); Icons.Add("Web Page Locked"); Icons.Add("Internet Facilities"); Icons.Add("File Upload-WF"); Icons.Add("Password-04-WF"); Icons.Add("File Help"); Icons.Add("Wind-01-WF"); Icons.Add("Power plant"); Icons.Add("MS System settings Configuration Manger-02"); Icons.Add("Text Protected-02"); Icons.Add("Text Protected-01"); Icons.Add("Calendar Delete-WF"); Icons.Add("Bookmark Up-WF"); Icons.Add("Mail Save"); Icons.Add("Warning-Shield"); Icons.Add("Mail Locked-WF"); Icons.Add("Calendar settings-WF"); Icons.Add("Contacts Favorite-WF"); Icons.Add("Window-New-01"); Icons.Add("Documents-02"); Icons.Add("Multiple threads"); Icons.Add("Windows-8-Login"); Icons.Add("Wifi"); Icons.Add("Calendar remove"); Icons.Add("Arrow -WF"); Icons.Add("Calendar Download-WF"); Icons.Add("Mail Remove-WF"); Icons.Add("Folder-Edit-01"); Icons.Add("Media First-WF"); Icons.Add("Bookmark Ok"); Icons.Add("Wind-04-WF"); Icons.Add("Navigation Right-WF"); Icons.Add("Filter-WF"); Icons.Add("Power Off-01-WF"); Icons.Add("User unlocked"); Icons.Add("Favourites Settings"); Icons.Add("User Delete"); Icons.Add("TextDecoration1-WF"); Icons.Add("Folder 1- WF"); Icons.Add("Media Fast Forward/Last-WF"); Icons.Add("Folder-Download-01"); Icons.Add("Data-Text"); Icons.Add("Bookmark locked"); Icons.Add("Phonebook Upload-WF"); Icons.Add("BookmarkSettings-02-WF"); Icons.Add("Download-Error"); Icons.Add("Favorite Edit-WF"); Icons.Add("Log file icon 2"); Icons.Add("User locked"); Icons.Add("Phonebook OK-WF"); Icons.Add("Folder-Cube"); Icons.Add("Water Recycling"); Icons.Add("Navigation-Down"); Icons.Add("Mobile Phone Message-WF"); Icons.Add("Add csv-WF"); Icons.Add("Volume-Speaker"); Icons.Add("Command Refresh-WF"); Icons.Add("Earthquake-WF"); Icons.Add("Volume Icon-WF"); Icons.Add("Shrink-02-WF"); Icons.Add("Assign"); Icons.Add("Shrink-01-WF"); Icons.Add("Shrink - 01"); Icons.Add("Software-SAP"); Icons.Add("Web Page Save"); Icons.Add("All softwares Updates that are installed in computer-WF"); Icons.Add("Phonebook Unlocked-WF"); Icons.Add("Pressure-02-WF"); Icons.Add("Check-01-WF"); Icons.Add("Zoom - corner - 03"); Icons.Add("Webpage Previous-WF"); Icons.Add("Product Box With Disc-02-WF"); Icons.Add("MailSearch-WF"); Icons.Add("Mail upload"); Icons.Add("User edit-01"); Icons.Add("Mail remove"); Icons.Add("Folder-WF"); Icons.Add("Folder-Music"); Icons.Add("Document Upload-WF"); Icons.Add("DataSynchronize-WF"); Icons.Add("Document-Add-01"); Icons.Add("Black List Folder"); Icons.Add("Mail1-WF"); Icons.Add("Format Bullet-WF"); Icons.Add("DocumentWarning-WF"); Icons.Add("Webpage -WF"); Icons.Add("User Locked-01-WF"); Icons.Add("Stack-03-WF"); Icons.Add("Find Replace-WF"); Icons.Add("Clipboard-WF"); Icons.Add("Curve"); Icons.Add("User-Delete"); Icons.Add("Trash can - 02"); Icons.Add("Media-End"); Icons.Add("Bookmark-New"); Icons.Add("GSM Tower-WF"); Icons.Add("Show-01-WF"); Icons.Add("Calendar -04"); Icons.Add("Speaker Audible - 02"); Icons.Add("Calendar-01"); Icons.Add("Bookmark Search-WF"); Icons.Add("Speaker - 01"); Icons.Add("Favourites Save"); Icons.Add("Document-Delete"); Icons.Add("Adobe-Acrobat"); Icons.Add("Data-Defragmentation"); Icons.Add("File Info-WF"); Icons.Add("User-Profile"); Icons.Add("Webpage Settings-WF"); Icons.Add("DataImport-WF"); Icons.Add("Arrowhead-Down-01"); Icons.Add("Share-06-WF"); Icons.Add("Group-Delete"); Icons.Add("Folder Zoom Out- WF"); Icons.Add("Scale to Fit-01 -WF"); Icons.Add("Display-Brightness"); Icons.Add("Wind-05-WF"); Icons.Add("AlignJustify-WF"); Icons.Add("Visual-Studio-2012"); Icons.Add("Phonebook Save"); Icons.Add("Text Decoration - 15"); Icons.Add("Show-02-WF"); Icons.Add("Folder Information-WF"); Icons.Add("Data-Split-01"); Icons.Add("Window Earth-WF"); Icons.Add("Phone Book locked-WF"); Icons.Add("Folder Remove 1-WF"); Icons.Add("Key-Access"); Icons.Add("Key Access-WF"); Icons.Add("Computer that is Member of security goup"); Icons.Add("Parenthesis-02-WF"); Icons.Add("Contacts UnLocked-WF"); Icons.Add("Text Decoration-07"); Icons.Add("Find-Replace"); Icons.Add("Mouse-Wireless"); Icons.Add("Text-Bold"); Icons.Add("Rating - 01"); Icons.Add("Favourites Help"); Icons.Add("Contact Lock-WF"); Icons.Add("Navigation Down-WF"); Icons.Add("Favorite Favorite-WF"); Icons.Add("Contacts Previous"); Icons.Add("Loading - 04"); Icons.Add("Stack-01-WF"); Icons.Add("View Details1-WF"); Icons.Add("File-Format-GIF"); Icons.Add("Money Gold-WF"); Icons.Add("Movie Info"); #endregion return Icons; } /// <summary> /// Gets the office icon. /// </summary> /// <returns>The office icon.</returns> private ObservableCollection<string> GetOfficeIcon() { ObservableCollection<string> Icons = new ObservableCollection<string>(); Icons.Add("Won"); Icons.Add("Home-Loan-WF"); Icons.Add("Car-Loan"); Icons.Add("Finance-03"); Icons.Add("Transaction-Fee-WF"); Icons.Add("Lithuanian-Litas-02"); Icons.Add("Eritrean-Nakfa"); Icons.Add("Croatian-Kuna-02"); Icons.Add("ATM-03"); Icons.Add("Ugandan-Shilling"); Icons.Add("Somali-Shilling"); Icons.Add("Money-Transfer-WF"); Icons.Add("Coin-01-WF"); Icons.Add("Netherlands Antillean-Guilder"); Icons.Add("Cent"); Icons.Add("Australian-Dollar"); Icons.Add("Zambian-Kwacha"); Icons.Add("Franc"); Icons.Add("Chinese-Renminbi Yuan"); Icons.Add("Cape Verdean-Escudo"); Icons.Add("Paraguayan-Guarani"); Icons.Add("Finance-02"); Icons.Add("Pound"); Icons.Add("Savings1-WF"); Icons.Add("Euro"); Icons.Add("Money"); Icons.Add("Czech-Koruna"); Icons.Add("ATM-02"); Icons.Add("Bike-Loan-WF"); Icons.Add("Cash-WF"); Icons.Add("Djiboutian-Franc"); Icons.Add("Euro-Coin"); Icons.Add("Namibian-Dollar"); Icons.Add("Icelandic-Krone"); Icons.Add("Bhutanese-Chetrum"); Icons.Add("Finance-01"); Icons.Add("Malawian-Kwacha"); Icons.Add("Money-Bag-WF"); Icons.Add("Taiwanese-Dollar"); Icons.Add("Coin - 01"); Icons.Add("Vietnamese-Dong"); Icons.Add("Mexican-Peso"); Icons.Add("Cash"); Icons.Add("Indian-Rupee"); Icons.Add("Guatemalan-Quetzal"); Icons.Add("Complaint-Box-WF"); Icons.Add("Trinidad and Tobago-Dollar"); Icons.Add("Ukrainian-Hryvnia"); Icons.Add("Cheque-02"); Icons.Add("Cheque-01"); Icons.Add("Cambodian-Riel"); Icons.Add("ATM-02-WF"); Icons.Add("Central African-CFA Franc"); Icons.Add("Myanmar-Kyat"); Icons.Add("Mozambican-Metical"); Icons.Add("Finance-04-WF"); Icons.Add("Jewel-Loan"); Icons.Add("Exchange-02-WF"); Icons.Add("Payments-01-WF"); Icons.Add("Calculator-WF"); Icons.Add("Banker-01-WF"); Icons.Add("Banker-02-WF"); Icons.Add("Cheque-02-WF"); Icons.Add("Tunisian-Dinar"); Icons.Add("Safety-Box-01-WF"); Icons.Add("Stock-Exchange-03"); Icons.Add("Maldivian-Rufiyaa"); Icons.Add("Master-Card"); Icons.Add("Currency-Sign"); Icons.Add("Bike-Loan"); Icons.Add("Singapore-Dollar"); Icons.Add("Yen"); Icons.Add("Lao-Kip"); Icons.Add("Accounts-Receivable"); Icons.Add("Cuban-Convertible Peso"); Icons.Add("Accounts-Book-WF"); Icons.Add("Complaint-Box"); Icons.Add("Agricultural-Loan"); Icons.Add("Hong Kong-Dollar"); Icons.Add("Israeli-New Shekel"); Icons.Add("Guinean"); Icons.Add("Locker-WF"); Icons.Add("Payment-WF"); Icons.Add("Wallet-WF"); Icons.Add("Accounting-01"); Icons.Add("Accounting-02"); Icons.Add("Malagasy-Ariary"); Icons.Add("Macanese-Pataca"); Icons.Add("Cuban-Peso"); Icons.Add("Egyptian-Pound"); Icons.Add("Savings"); Icons.Add("Finance-04"); Icons.Add("Kenyan-Shilling"); Icons.Add("Sierra Leonean-Leone"); Icons.Add("ATM"); Icons.Add("Kuwaiti-Dinar"); Icons.Add("Samoan-Tala"); Icons.Add("Algerian-Dinar"); Icons.Add("Swiss-Franc"); Icons.Add("Barbadian-Dollar"); Icons.Add("Nigerian-Naira"); Icons.Add("Croatian-Kuna-01"); Icons.Add("Payments"); Icons.Add("Telephone"); Icons.Add("Account-Payable-WF"); Icons.Add("Chilean-Peso"); Icons.Add("Debit-Card"); Icons.Add("Haitian-Gourde"); Icons.Add("Albanian-Lek"); Icons.Add("British-Pennies"); Icons.Add("Fijian-Dollar"); Icons.Add("Malaysian-Ringgit"); Icons.Add("Sri Lankan-Rupee"); Icons.Add("Bhutanese-Ngultrum"); Icons.Add("Bermudian-Dollar"); Icons.Add("Latvian-Lats"); Icons.Add("Iranian-Rial"); Icons.Add("Stock-Exchange-07"); Icons.Add("Philippine-Peso"); Icons.Add("Lesotho-Loti"); Icons.Add("Botswana-Pula"); Icons.Add("Latvian-Santims"); Icons.Add("Home-Loan"); Icons.Add("Dobra"); Icons.Add("East Caribbean-Dollar"); Icons.Add("Employee"); Icons.Add("Swazi-Lilangeni"); Icons.Add("Panamanian-Balboa"); Icons.Add("Jamaican-Dollar"); Icons.Add("Stock-Exchange-06"); Icons.Add("Car-Loan-WF"); Icons.Add("Burundian-Franc"); Icons.Add("Accounting-02-WF"); Icons.Add("Venezuelan-Bolivar"); Icons.Add("Bulgarian-Lev"); Icons.Add("Account-Payable"); Icons.Add("Bank-WF"); Icons.Add("Scanner"); Icons.Add("Thai-Baht"); Icons.Add("Cayman Islands-Dollar"); Icons.Add("Angolan-Kwanza"); Icons.Add("Counting-Machine"); Icons.Add("Qatari-Riyal"); Icons.Add("Serbian-Dinar"); Icons.Add("Uruguayan-Peso"); Icons.Add("Turkish-Lira"); Icons.Add("Mill"); Icons.Add("Accounts-Book"); Icons.Add("Peruvian Nuevo-Sol"); Icons.Add("Ghana-Cedi"); Icons.Add("Stock-Exchange-04"); Icons.Add("Nicaraguan-Cordoba"); Icons.Add("Jordanian-Dinar"); Icons.Add("Hungarian-Forint"); Icons.Add("Gold-WF"); Icons.Add("Special-Drawing-Rights"); Icons.Add("Dominican-Peso"); Icons.Add("Moroccan-Dirham"); Icons.Add("Japanese-Yen"); Icons.Add("Seychellois-Rupee"); Icons.Add("Finance-03-WF"); Icons.Add("Telephone-WF"); Icons.Add("Costa Rican-Cólon"); Icons.Add("Bahamian-Dollar"); Icons.Add("Kyrgyzstani-Som"); Icons.Add("Rwandan-Franc"); Icons.Add("Dollar"); Icons.Add("Coin - 02"); Icons.Add("Polish-Zloty"); Icons.Add("Pending-Payment"); Icons.Add("Exchange - 02"); Icons.Add("Exchange - 01"); Icons.Add("Stock-Exchange-02"); Icons.Add("Transaction-Fee"); Icons.Add("Indonesian-Rupiah"); Icons.Add("Payment-02"); Icons.Add("Canadian-Dollar"); Icons.Add("Belarusian-Ruble"); Icons.Add("Colombian-Peso"); Icons.Add("Libyan-Dinar"); Icons.Add("United Arab Emirates-Dirham"); Icons.Add("Coin-02-WF"); Icons.Add("Stock-Exchange-01"); Icons.Add("Gold"); Icons.Add("Belize-Dollar"); Icons.Add("Pound-Coin"); Icons.Add("Phone-WF"); Icons.Add("Bangladeshi-Taka"); Icons.Add("United States-Dollar"); Icons.Add("South African-Rand"); Icons.Add("Bank-01-WF"); Icons.Add("Egyptian-Piastre"); Icons.Add("Stock-Exchange-05"); Icons.Add("ATM-01-WF"); Icons.Add("Brunei-Dollar"); Icons.Add("Rupee"); Icons.Add("Zimbabwean-Dollar"); Icons.Add("Locker"); Icons.Add("Stcok-Exchange-03-WF"); Icons.Add("Bank"); Icons.Add("Safety-Box-02"); Icons.Add("Phone"); Icons.Add("Bosnian and Herzegovina-Convertible Mark"); Icons.Add("Swedish-Krona"); Icons.Add("Czech-Haler"); Icons.Add("Vanuatu-Vatu"); Icons.Add("Mauritanian-Ouguiya"); Icons.Add("Calculator"); Icons.Add("Money-Transfer"); Icons.Add("Dollar-Coin"); Icons.Add("Money-Bag"); Icons.Add("British-Pounds"); Icons.Add("Accounting-01-WF"); Icons.Add("ATM-03-WF"); Icons.Add("Macedonian-Denar"); Icons.Add("Bahraini-Dinar"); Icons.Add("Saudi-Riyal"); Icons.Add("Polish-Grosz"); Icons.Add("Money-WF"); Icons.Add("Ethiopian-Birr"); Icons.Add("Gambian-Dalasi"); Icons.Add("Afghan-Afghani"); Icons.Add("Mongolian-Togrog"); Icons.Add("ATM-01"); Icons.Add("Surinamese-Dollar"); Icons.Add("New Zealand-Dollar"); Icons.Add("Safety-Box-01"); Icons.Add("Money-Deposit"); Icons.Add("Lithuanian-Litas-01"); Icons.Add("Brazilian-Real"); Icons.Add("Agricultural-Loan-WF"); Icons.Add("Iraqi-Dinar"); Icons.Add("Albanian-Qindarka"); Icons.Add("Dollar-Coin-WF"); Icons.Add("West African-CFA Franc"); Icons.Add("Payment-01"); Icons.Add("Guyanese-Dollar"); Icons.Add("Customer"); Icons.Add("Solomon Islands-Dollar"); Icons.Add("Fund"); Icons.Add("Comorian-Franc"); Icons.Add("Banking-Transaction"); Icons.Add("Aruban-Florin"); Icons.Add("Scanner-WF"); Icons.Add("Liberian-Dollar"); Icons.Add("Omani-Rial"); Icons.Add("Georgian-Lari"); Icons.Add("European-Euro"); Icons.Add("ATM-04"); return Icons; } #region Transport Collection /// <summary> /// Gets the transport collection. /// </summary> /// <returns>The transport collection.</returns> private ObservableCollection<string> GetTransportCollection() { ObservableCollection<string> Icons = new ObservableCollection<string>(); Icons.Add("Wine-Glass-06"); Icons.Add("Wine-Glass-05"); Icons.Add("Wine-Glass-04"); Icons.Add("Wine-Glass-03"); Icons.Add("Wine-Glass-02"); Icons.Add("Wine-Glass-01"); Icons.Add("Beverage-Juice-01"); Icons.Add("Vegetable-Carrot"); Icons.Add("Beverage-Milk-Shake"); Icons.Add("Milk-Bottle"); Icons.Add("Fruit-Lemon"); Icons.Add("Fruit-Apple"); Icons.Add("Candy-Lollipop"); Icons.Add("Tea-Bag"); Icons.Add("Chocolate-03"); Icons.Add("Cheese-01"); Icons.Add("Snack-Burger"); Icons.Add("Beverage-Tea"); Icons.Add("Fruit-Cherry"); Icons.Add("Vegetable-Onion"); Icons.Add("Bread-02"); Icons.Add("Bar"); Icons.Add("Beverage-Coffee-03"); Icons.Add("Restaurant"); Icons.Add("Beverage-Juice-03"); Icons.Add("Chocolate-01"); Icons.Add("Coffee - 01"); Icons.Add("Wine Glass - 01"); Icons.Add("Fruit-Banana-02"); Icons.Add("Milk"); Icons.Add("Cereal-Corn-01"); Icons.Add("Vegetable-Tomato-01"); Icons.Add("Vegetable-Capsicum-Pepper"); Icons.Add("Fruit-Orange-02"); Icons.Add("Cocktail-03"); Icons.Add("Seafood-Fish"); Icons.Add("Fork and Knife"); Icons.Add("Cooking-Gloves"); Icons.Add("Ice-Cream-03"); Icons.Add("Cake-Cookie"); Icons.Add("Vegetable-Tomato-02"); Icons.Add("Meat-Chicken-Kebab"); Icons.Add("Chocolate-05"); Icons.Add("Cereal-Wheat"); Icons.Add("Vegetable-Radish"); Icons.Add("Vegetable-Chilli"); Icons.Add("Cake-02"); Icons.Add("Strawberry1"); Icons.Add("Beverage-Cocktail-01"); Icons.Add("Coffee Cup - 01"); Icons.Add("Chicken-Egg"); Icons.Add("Fruit-Watermelon"); Icons.Add("Chicken-02"); Icons.Add("Ice-Cream-01"); Icons.Add("Chicken-01"); Icons.Add("Bowl"); Icons.Add("Vegetable-Pumpkin"); Icons.Add("Beverage-Coffee-04"); Icons.Add("Beverage-Beer-02"); Icons.Add("Beverage-Coffee-02"); Icons.Add("Noodles-02"); Icons.Add("Fruit-Apple-02"); Icons.Add("Bean-01"); Icons.Add("Beverage-Juice-02"); Icons.Add("Fork and Spoon"); Icons.Add("Cereal-Corn-02"); Icons.Add("Beverage-Alcohol"); Icons.Add("Chocolate-02"); Icons.Add("Vegetable-Brinjal-Eggplant"); Icons.Add("Soup-01"); Icons.Add("Beverage-Milk-01"); Icons.Add("Snack-Doughnut"); Icons.Add("Beverage-Coffee-01"); Icons.Add("Fruit-Strawberry"); Icons.Add("Cheese-02"); Icons.Add("Bread-01"); Icons.Add("Snack-French-Fries"); Icons.Add("Prawn-01"); Icons.Add("Cocktail-02"); Icons.Add("Cutlery-Fork-Knife"); Icons.Add("Cake-Slice-01"); Icons.Add("Chocolate-06"); Icons.Add("Cake-01"); Icons.Add("Fruit-Orange-03"); Icons.Add("Coffee-Bean"); Icons.Add("Jar"); Icons.Add("Hand-Fork"); Icons.Add("Pizza-02"); Icons.Add("Cocktail-01"); Icons.Add("Water-Drop"); Icons.Add("Cooker"); Icons.Add("Beverage-Milk-02"); Icons.Add("Wine Bottle - 01"); Icons.Add("Knife"); Icons.Add("Beverage-Wine"); Icons.Add("Chocolate-04"); Icons.Add("Noodles-01"); Icons.Add("Ice-Cream-02"); Icons.Add("Chef-Cap"); Icons.Add("Fruit-Orange-01"); Icons.Add("Cup-Cake"); Icons.Add("Pizza-01"); Icons.Add("Seafood-Shrimp"); Icons.Add("Beverage-Beer-01"); Icons.Add("Prawn"); Icons.Add("Vegetable-Cabbage"); Icons.Add("Beverage-Cocktail-02"); Icons.Add("Spices-Salt-Pepper"); Icons.Add("Coffee Cup - 02"); Icons.Add("Fruit-Grapes"); Icons.Add("Fruit-Banana-01"); return Icons; } #endregion } } <file_sep>/Forms/TabView/readme.md The `SfTabView` control provides a simple and intuitive interface for tab navigation in your mobile application that allows users to explore and switch among different views. The following sample is available for tab view to demonstrate the functionalities of each feature. | Sample | Description | | ------ | ----------- | |[Getting Started](TabView/Samples/TabViewGettingStarted)|It demonstrates customization of Tab view's header, positioning items and handling overflown tabs.| |[Nested Tabs](TabView/Samples/NestedTabs)|It demonstrates the nesting support of adding tabs inside another tab.| |[Center Button](TabView/Samples/CenterButton)|It shows one of the layout options demonstration.| |[Custom Header](TabView/Samples/CustomView)|It demonstrates the custom header view support in tab view item.| <file_sep>/iOS/SampleBrowser/Samples/Presentation/ImagesPresentation.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.Presentation; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class ImagesPresentation : SampleView { CGRect frameRect = new CGRect (); float frameMargin = 8.0f; UILabel label; UILabel label1; UIButton button; public ImagesPresentation() { label1 = new UILabel(); label = new UILabel(); button = new UIButton(UIButtonType.System); button.TouchUpInside += OnButtonClicked; } void LoadAllowedTextsLabel() { label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample demonstrates how to add an image in PowerPoint presentation."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect (5, 5,frameRect.Location.X + frameRect.Size.Width , 50); } else { label.Frame = new CGRect (frameRect.Location.X, 5, frameRect.Size.Width , 70); } this.AddSubview (label); button.SetTitle("Generate Presentation",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { button.Frame = new CGRect (0, 65, frameRect.Location.X + frameRect.Size.Width , 10); } else { button.Frame = new CGRect (frameRect.Location.X, 70, frameRect.Size.Width , 10); } this.AddSubview (button); } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = "SampleBrowser.Samples.Presentation.Templates.Images.pptx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); IPresentation presentation = Presentation.Open(fileStream); #region Slide1 ISlide slide1 = presentation.Slides[0]; IShape shape1 = (IShape)slide1.Shapes[0]; shape1.Left = 1.27 * 72; shape1.Top = 0.56 * 72; shape1.Width = 9.55 * 72; shape1.Height = 5.4 * 72; ITextBody textFrame = shape1.TextBody; IParagraphs paragraphs = textFrame.Paragraphs; paragraphs.Add(); IParagraph paragraph = paragraphs[0]; paragraph.HorizontalAlignment = HorizontalAlignmentType.Left; ITextParts textParts = paragraph.TextParts; textParts.Add(); ITextPart textPart = textParts[0]; textPart.Text = "Essential Presentation "; textPart.Font.CapsType = TextCapsType.All; textPart.Font.FontName = "Calibri Light (Headings)"; textPart.Font.FontSize = 80; textPart.Font.Color = ColorObject.Black; #endregion #region Slide2 ISlide slide2 = presentation.Slides.Add(SlideLayoutType.ContentWithCaption); slide2.Background.Fill.FillType = FillType.Solid; slide2.Background.Fill.SolidFill.Color = ColorObject.White; //Adds shape in slide shape1 = (IShape)slide2.Shapes[0]; shape1.Left = 0.47 * 72; shape1.Top = 1.15 * 72; shape1.Width = 3.5 * 72; shape1.Height = 4.91 * 72; ITextBody textFrame1 = shape1.TextBody; //Instance to hold paragraphs in textframe IParagraphs paragraphs1 = textFrame1.Paragraphs; IParagraph paragraph1 = paragraphs1.Add(); paragraph1.HorizontalAlignment = HorizontalAlignmentType.Left; ITextPart textpart1 = paragraph1.AddTextPart(); textpart1.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph2 = paragraphs1.Add(); paragraph2.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph2.AddTextPart(); textpart1.Text = "Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph3 = paragraphs1.Add(); paragraph3.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph3.AddTextPart(); textpart1.Text = "Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); IParagraph paragraph4 = paragraphs1.Add(); paragraph4.HorizontalAlignment = HorizontalAlignmentType.Left; textpart1 = paragraph4.AddTextPart(); textpart1.Text = "Lorem tortor neque, purus taciti quis id. Elementum integer orci accumsan minim phasellus vel."; textpart1.Font.Color = ColorObject.White; textpart1.Font.FontName = "Calibri (Body)"; textpart1.Font.FontSize = 15; paragraphs1.Add(); slide2.Shapes.RemoveAt(1); slide2.Shapes.RemoveAt(1); //Adds picture in the shape resourcePath = "SampleBrowser.Samples.Presentation.Templates.tablet.jpg"; assembly = Assembly.GetExecutingAssembly(); fileStream = assembly.GetManifestResourceStream(resourcePath); IPicture picture1 = slide2.Shapes.AddPicture(fileStream, 5.18 * 72, 1.15 * 72, 7.3 * 72, 5.31 * 72); fileStream.Close(); #endregion MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (stream != null) { SaveiOS iOSSave = new SaveiOS (); iOSSave.Save ("ImagesPresentation.pptx", "application/mspowerpoint", stream); } } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } } } <file_sep>/Forms/PdfViewer/PdfViewer.Droid/Renderer/EditBookmarkPopupDroidEffect.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using SampleBrowser.SfPdfViewer.Droid; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Rect = Android.Graphics.Rect; [assembly: ResolutionGroupName("SampleBrowser.SfPdfViewer")] [assembly: ExportEffect(typeof(EditBookmarkPopupEffect), nameof(EditBookmarkPopupEffect))] namespace SampleBrowser.SfPdfViewer.Droid { public class EditBookmarkPopupEffect : PlatformEffect { private LayoutListener layoutListener; [Obsolete] #pragma warning disable CS0809 // Obsolete member overrides non-obsolete member protected override void OnAttached() #pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { if ((Activity)Xamarin.Forms.Forms.Context != null && ((Activity)Xamarin.Forms.Forms.Context).Window != null && ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView != null && ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView.RootView != null) { layoutListener = new LayoutListener(this.Element); ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView.RootView.ViewTreeObserver?.AddOnGlobalLayoutListener(layoutListener); }; } [Obsolete] #pragma warning disable CS0809 // Obsolete member overrides non-obsolete member protected override void OnDetached() #pragma warning restore CS0809 // Obsolete member overrides non-obsolete member { if (this?.Element is SampleBrowser.SfPdfViewer.EditBookmarkPopup editBookmarkPopupView && !editBookmarkPopupView.IsRenameEntryFocused && !editBookmarkPopupView.IsRenamePopupOpened) { if ((Activity)Xamarin.Forms.Forms.Context != null && ((Activity)Xamarin.Forms.Forms.Context).Window != null && ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView != null && ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView.RootView != null) { ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView.RootView.ViewTreeObserver?.RemoveGlobalOnLayoutListener(layoutListener); } } } } internal class LayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener { [Obsolete] private EditBookmarkPopup editBookmarkPopupView; [Obsolete] internal LayoutListener(Element editBookmarkPopup) { editBookmarkPopupView = editBookmarkPopup as EditBookmarkPopup; } [Obsolete] public void OnGlobalLayout() { Rect rectangle = new Rect(); if ((Activity)Xamarin.Forms.Forms.Context != null && ((Activity)Xamarin.Forms.Forms.Context).Window != null && ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView != null && ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView.RootView != null) ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView.GetWindowVisibleDisplayFrame(rectangle); int screenHeight = ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView.RootView.Height; int keyboardSize = screenHeight - rectangle.Height(); if (editBookmarkPopupView != null) { if (keyboardSize > 0 && editBookmarkPopupView.IsRenamePopupOpened && editBookmarkPopupView.IsRenameEntryFocused) { editBookmarkPopupView.Children[0].Margin = new Thickness(0, 0, 0, keyboardSize / 4); //push the popup view up to keyboard height when keyboard is activated } else { editBookmarkPopupView.Children[0].Margin = new Thickness(0); //set the Padding to zero when keyboard is dismissed } } rectangle.Dispose(); } } }<file_sep>/iOS/SampleBrowser/Samples/Chart/Tooltip.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.SfChart.iOS; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; #endif namespace SampleBrowser { public class Tooltip : SampleView { public Tooltip() { SFChart chart = new SFChart(); chart.Title.Text = new NSString("Wheat Production in Tons"); //Primary Axis SFCategoryAxis primaryAxis = new SFCategoryAxis(); primaryAxis.PlotOffset = 10; primaryAxis.ShowMajorGridLines = false; primaryAxis.AxisLineStyle.LineWidth = new NSNumber(0.5); primaryAxis.Interval = new NSNumber(2); chart.PrimaryAxis = primaryAxis; // Secondary Axis SFNumericalAxis secondaryAxis = new SFNumericalAxis(); secondaryAxis.EdgeLabelsDrawingMode = SFChartAxisEdgeLabelsDrawingMode.Shift; secondaryAxis.Maximum = new NSNumber(2.701); secondaryAxis.Minimum = new NSNumber(1.5); secondaryAxis.Interval = new NSNumber(0.2); secondaryAxis.AxisLineStyle.LineWidth = new NSNumber(0); secondaryAxis.LabelStyle.Font = UIFont.FromName("Helvetica", 12f); secondaryAxis.Title.Font = UIFont.FromName("Helvetica", 15f); secondaryAxis.MajorTickStyle.LineSize = 0; secondaryAxis.MajorGridLineStyle.LineWidth = new NSNumber(0.25); chart.SecondaryAxis = secondaryAxis; ChartViewModel dataModel = new ChartViewModel(); SFSplineSeries series = new SFSplineSeries(); series.ItemsSource = dataModel.TooltipData; series.XBindingPath = "XValue"; series.YBindingPath = "YValue"; series.EnableTooltip = true; series.LineWidth = 2.5f; series.DataMarker.ShowMarker = true; series.DataMarker.MarkerType = SFChartDataMarkerType.Ellipse; series.DataMarker.MarkerHeight = 5; series.DataMarker.MarkerWidth = 5; series.DataMarker.MarkerBorderColor = UIColor.Black; series.DataMarker.MarkerColor = UIColor.FromRGBA(193.0f / 255.0f, 39.0f / 255.0f, 45.0f / 255.0f, 1.0f); series.EnableAnimation = true; chart.Series.Add(series); chart.Delegate = new ChartTooltipDelegate(); SFChartTooltipBehavior behavior = new SFChartTooltipBehavior(); behavior.BackgroundColor = UIColor.FromRGBA(193.0f / 255.0f, 39.0f / 255.0f, 45.0f / 255.0f, 1.0f); chart.AddChartBehavior(behavior); this.AddSubview(chart); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = Bounds; } base.LayoutSubviews(); } } public class ChartTooltipDelegate : SFChartDelegate { public override void WillShowTooltip(SFChart chart, SFChartTooltip tooltipView) { UIView customView = new UIView(); customView.Frame = new CGRect(0, 0, 80, 40); UIImageView imageView = new UIImageView(); imageView.Frame = new CGRect(0, 0, 40, 40); imageView.Image = UIImage.FromBundle("Images/grain.png"); UILabel xLabel = new UILabel(); xLabel.Frame = new CGRect(47, 0, 35, 18); xLabel.TextColor = UIColor.Orange; xLabel.Font = UIFont.FromName("Helvetica", 12f); xLabel.Text = (tooltipView.DataPoint as ChartDataModel).XValue.ToString(); UILabel yLabel = new UILabel(); yLabel.Frame = new CGRect(47, 20, 40, 18); yLabel.TextColor = UIColor.White; yLabel.Font = UIFont.FromName("Helvetica", 12f); yLabel.Text = tooltipView.Text +"M"; customView.AddSubview(imageView); customView.AddSubview(xLabel); customView.AddSubview(yLabel); tooltipView.CustomView = customView; } public override NSString GetFormattedAxisLabel(SFChart chart, NSString label, NSObject value, SFAxis axis) { if (axis == chart.SecondaryAxis) { String formattedLabel = label + "M"; label = new NSString(formattedLabel); return label; } return label; } } } <file_sep>/iOS/SampleBrowser/Samples/PDFViewer/Helpers/DropDownDataSource.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using UIKit; using CoreGraphics; using System.Linq; using Foundation; using System; namespace SampleBrowser { internal class DropDownDataSource : UITableViewSource { private DropDownMenuItem[] m_ListItems; private const string m_CellIdentifier = "DropDownListCell"; private UIColor m_TextColor; private UIColor m_CellColor; private UIColor m_BackgroundColor; public event DropDownMenuItemChangedHandler DropDownMenuItemChanged; public UIColor CellColor { get { return m_CellColor; } set { m_CellColor = value; } } public UIColor TextColor { get { return m_TextColor; } set { m_TextColor = value; } } public UIColor BackgroundColor { get { return m_BackgroundColor; } set { m_BackgroundColor = value; } } public DropDownDataSource(DropDownMenuItem[] listItems, UIColor textColor) { this.m_TextColor = textColor; this.m_ListItems = listItems; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var item = m_ListItems [indexPath.Row]; var cell = tableView.DequeueReusableCell (m_CellIdentifier) as UITableViewCell; if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Subtitle, m_CellIdentifier); } if (m_BackgroundColor != null) cell.BackgroundColor = m_BackgroundColor; if (this.m_TextColor != null) cell.TextLabel.TextColor = m_TextColor; cell.TextLabel.Text = item.DisplayText; if (this.m_CellColor != null) cell.TintColor = CellColor; return cell; } public override System.nint RowsInSection (UITableView tableview, System.nint section) { return this.m_ListItems.Length; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { var oldItem = m_ListItems.FirstOrDefault (x => x.IsSelected); if (oldItem != null) oldItem.IsSelected = false; var oldCell = tableView.VisibleCells.FirstOrDefault (c => ((UITableViewCell)c).Accessory == UITableViewCellAccessory.Checkmark) as UITableViewCell; if (oldCell != null) oldCell.Accessory = UITableViewCellAccessory.None; m_ListItems [indexPath.Row].IsSelected = true; var cell = tableView.CellAt (indexPath) as UITableViewCell; cell.Accessory = UITableViewCellAccessory.None; if (DropDownMenuItemChanged != null && oldItem.DisplayText != cell.TextLabel.Text) { DropDownMenuItemChanged (indexPath.Row, m_ListItems [indexPath.Row]); } } } } <file_sep>/Forms/CircularGauge/CircularGauge/ViewModel/CircularGaugeViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfCircularGauge { [Preserve(AllMembers = true)] public class CircularGaugeViewModel : INotifyPropertyChanged { Random random = new Random(); private bool canStopTimer; public CircularGaugeViewModel() { } #region Properties public event PropertyChangedEventHandler PropertyChanged; #region HeaderText private string headerText; public string HeaderText { get { return headerText; } set { headerText = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("HeaderText")); } } } #endregion PointerValue #region PointerValue private double pointerValue; public double PointerValue { get { return pointerValue; } set { pointerValue = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("PointerValue")); } } } #endregion PointerValue #region Scale1_StartAngle private double scale1_StartAngle; public double Scale1_StartAngle { get { return scale1_StartAngle; } set { scale1_StartAngle = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Scale1_StartAngle")); } } } #endregion Scale1_StartAngle #region Scale1_SweepAngle private double scale1_SweepAngle; public double Scale1_SweepAngle { get { return scale1_SweepAngle; } set { scale1_SweepAngle = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Scale1_SweepAngle")); } } } #endregion Scale1_SweepAngle #region Scale2_StartAngle private double scale2_StartAngle; public double Scale2_StartAngle { get { return scale2_StartAngle; } set { scale2_StartAngle = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Scale2_StartAngle")); } } } #endregion Scale2_StartAngle #region Scale2_SweepAngle private double scale2_SweepAngle; public double Scale2_SweepAngle { get { return scale2_SweepAngle; } set { scale2_SweepAngle = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Scale2_SweepAngle")); } } } #endregion Scale2_SweepAngle #region RangePointerColor private Color rangePointerColor; public Color RangePointerColor { get { return rangePointerColor; } set { rangePointerColor = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("RangePointerColor")); } } } #endregion RangePointerColor #region NeedlePointerColor private Color needlePointerColor; public Color NeedlePointerColor { get { return needlePointerColor; } set { needlePointerColor = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("NeedlePointerColor")); } } } #endregion NeedlePointerColor #region RangeColor private Color rangeColor; public Color RangeColor { get { return rangeColor; } set { rangeColor = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("RangeColor")); } } } #endregion RangeColor #endregion Properties public async void UpdateLiveData() { await Task.Delay(200); Device.StartTimer(new TimeSpan(0, 0, 0, 0, 1500), UpdateData); } private bool UpdateData() { if (canStopTimer) return false; PointerValue = random.Next(35, 100); return true; } public void StopTimer() { canStopTimer = true; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/DataGrid/ViewModel/CustomerViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; namespace SampleBrowser { public class CustomerViewModel : INotifyPropertyChanged { #region Constructor public CustomerViewModel() { CustomersRepository customerrep = new CustomersRepository(); customerInformation = customerrep.GetCutomerDetails(100); } #endregion #region ItemsSource private ObservableCollection<CustomerDetails> customerInformation; public ObservableCollection<CustomerDetails> CustomerInformation { get { return this.customerInformation; } set { this.customerInformation = value; } } #endregion #region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion } } <file_sep>/Android/SampleBrowser/Samples/PDFViewer/readme.md The Syncfusion PDF viewer for Xamarin Android platform is a native control for viewing and reviewing PDF documents. **Key Features** * High performance. * Select and copy text. * Search and highlight text. * PDF documents reviewable using shapes, highlight, underline, strike-through, ink, and free text annotations. * Localization support. * Fully customizable. The following samples are available to demonstrate the functionalities of SfPdfViewer. | Sample | Description | | ------ | ----------- | | [Getting Started](GettingStartedPDFViewer.cs) | This sample illustrates displaying a PDF document in the PDF viewer control in Xamarin Android application using the built-in toolbar. | | [Custom Toolbar](CustomToolBarGettingStartedPDFViewer.cs)| This sample illustrates designing a custom toolbar to perform all the operations using the built-in toolbar. | <file_sep>/Forms/BadgeView/BadgeView/Samples/Notification/NotificationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "BadgeViewModel.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfBadgeView { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; /// <summary> /// Notification View Model class. /// </summary> [Xamarin.Forms.Internals.Preserve(AllMembers = true)] [SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1027:TabsMustNotBeUsed", Justification = "Reviewed.")] public class NotificationViewModel { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="NotificationViewModel" /> class /// </summary> public NotificationViewModel() { this.Collection = new ObservableCollection<NotificationModel>(); this.Collection.Add(new NotificationModel() { Image = "People_Circle1.png", Name = "Blessy", Message = "Hi, I have sent you a photo", Time = "Monday", Count = string.Empty }); this.Collection.Add(new NotificationModel() { Image = "People_Circle5.png", Name = "Aaron", Message = "Family meeting tomorrow at 6:30 PM", Time = "11:30 PM", Count = "99+" }); this.Collection.Add(new NotificationModel() { Image = "People_Circle2.png", Name = "Tara", Message = "Hi, I am Tara, How are you?", Time = "11:12 PM", Count = "3" }); this.Collection.Add(new NotificationModel() { Image = "People_Circle3.png", Name = "Jeni", Message = "video", Time = "07:53 PM", Count = "137", }); this.Collection.Add(new NotificationModel() { Image = "People_Circle4.png", Name = "Flora", Message = "I have received your gift", Time = "04:40 PM", Count = string.Empty }); this.Collection.Add(new NotificationModel() { Image = "People_Circle6.png", Name = "Sara", Count = "47", Message = "done thanks", Time = "Yesterday" }); this.Collection.Add(new NotificationModel() { Image = "People_Circle8.png", Name = "Stephan", Count = string.Empty, Time = "07.46 PM", Message = "ok fine" }); this.Collection.Add(new NotificationModel() { Image = "People_Circle7.png", Name = "Maria", Count = string.Empty, Time = "07.46 PM", Message = "Hi, How are you?" }); this.Collection.Add(new NotificationModel() { Image = "People_Circle9.png", Name = "Ancy", Message = "Hi, i have sent you a photo", Time = "Monday", Count = "8" }); } #endregion Constructor #region Properties /// <summary> /// Gets or sets the collection of Badge Model /// </summary> public ObservableCollection<NotificationModel> Collection { get; set; } #endregion Properties } }<file_sep>/Forms/ListView/ListView/Samples/GridLayout/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Syncfusion.ListView.XForms; using Xamarin.Forms.Internals; using System.Reflection; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] public class ListViewGridLayoutViewModel : INotifyPropertyChanged { #region Fields private ObservableCollection<ListViewGalleryInfo> galleryinfo; private string headerInfo; private ObservableCollection<object> _selectedItems = new ObservableCollection<object>(); #endregion #region Constructor public ListViewGridLayoutViewModel() { FavoriteImageCommand = new Command(SetFavorite); DeleteImageCommand = new Command(DeleteImageTapped_tapped); SelectedItems.CollectionChanged += SelectedItems_CollectionChanged; GenerateSource(); UpdateHeaderStatus(); } #endregion #region Properties public ObservableCollection<object> SelectedItems { get { return _selectedItems; } set { _selectedItems = value; } } public Command FavoriteImageCommand { get; } public Command DeleteImageCommand { get; } public ObservableCollection<ListViewGalleryInfo> Gallerynfo { get { return galleryinfo; } set { this.galleryinfo = value; } } public string HeaderStatus { get { return headerInfo; } set { if (headerInfo != value) { headerInfo = value; OnPropertyChanged("HeaderStatus"); } } } #endregion public void GenerateSource() { ListViewGalleryInfoRepository bookRepository = new ListViewGalleryInfoRepository(); galleryinfo = bookRepository.GetGalleryInfo(); } private void UpdateHeaderStatus() { if (SelectedItems.Count > 0) { this.HeaderStatus = this.SelectedItems.Count == 1 ? this.SelectedItems.Count + " photo selected" : this.SelectedItems.Count + " photos selected"; } else { this.HeaderStatus = "Select Photos"; } } private void DeleteImageTapped_tapped(object obj) { var galleryInfo = SelectedItems.ToList(); foreach (ListViewGalleryInfo item in galleryInfo) { if (this.Gallerynfo.Contains(item)) this.Gallerynfo.Remove(item); } UpdateHeaderStatus(); } private void SetFavorite(object obj) { var item = obj as ListViewGalleryInfo; item.IsFavorite = !item.IsFavorite; } private void SelectedItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { for (int i = 0; e.NewItems != null && i < e.NewItems.Count; i++) { var item = e.NewItems[i]; (item as ListViewGalleryInfo).IsSelected = true; } for (int i = 0; e.OldItems != null && i < e.OldItems.Count; i++) { var item = e.OldItems[i]; (item as ListViewGalleryInfo).IsSelected = false; } UpdateHeaderStatus(); } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } } } <file_sep>/iOS/SampleBrowser/Samples/XlsIO/ExcelToPDF.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.XlsIO; using Syncfusion.XlsIORenderer; using System.IO; using System.Collections.Generic; using System.Reflection; using Syncfusion.Pdf; using Syncfusion.iOS.Buttons; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public class ExcelToPDF : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; private readonly IList<string> layoutList = new List<string>(); string selectedLayout; UILabel label ; UILabel pageSetuplabel; UIButton layoutDoneButton; UIButton layoutButton; UIPickerView layoutPicker; UIButton inputButton ; UIButton convertButton; UILabel SubstituteLabel; UILabel FontStreamLabel; UILabel FontNameLabel; SfCheckBox checkfontName; SfCheckBox checkfontStream; public ExcelToPDF() { this.layoutList.Add((NSString)"NoScaling"); this.layoutList.Add((NSString)"FitAllRowsOnOnePage"); this.layoutList.Add((NSString)"FitAllColumnsOnOnePage"); this.layoutList.Add((NSString)"FitSheetOnOnePage"); label = new UILabel (); inputButton = new UIButton(UIButtonType.System); inputButton.TouchUpInside += OnButtonClicked; convertButton = new UIButton(UIButtonType.System); convertButton.TouchUpInside += OnConvertClicked; layoutDoneButton = new UIButton(); layoutButton = new UIButton(); layoutPicker = new UIPickerView(); pageSetuplabel = new UILabel(); layoutPicker = new UIPickerView(); layoutDoneButton = new UIButton(); SubstituteLabel = new UILabel(); FontStreamLabel = new UILabel(); FontNameLabel = new UILabel(); checkfontName = new SfCheckBox(); checkfontStream = new SfCheckBox(); this.AddSubview(label); this.AddSubview(pageSetuplabel); this.AddSubview(layoutButton); this.AddSubview(layoutPicker); this.AddSubview(layoutDoneButton); this.AddSubview(SubstituteLabel); this.AddSubview(checkfontName); this.AddSubview(FontNameLabel); this.AddSubview(checkfontStream); this.AddSubview(FontStreamLabel); this.AddSubview(convertButton); this.AddSubview(inputButton); } void LoadAllowedTextsLabel() { #region Description Label label.Frame = frameRect; label.TextColor = UIColor.FromRGB (38/255.0f, 38/255.0f, 38/255.0f); label.Text = "This sample illustrates the conversion of a Excel document to PDF."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width , 35); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } #endregion #region Page Setup Options Label if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { pageSetuplabel.Font = UIFont.SystemFontOfSize(18); pageSetuplabel.Frame = new CGRect(10, 45, frameRect.Location.X + frameRect.Size.Width - 20, 50); layoutButton.Frame = new CGRect(10, 95, frameRect.Location.X + frameRect.Size.Width - 20, 50); } else { pageSetuplabel.Frame = new CGRect(10, 50, frameRect.Location.X + frameRect.Size.Width - 20, 50); layoutButton.Frame = new CGRect(10, 100, frameRect.Location.X + frameRect.Size.Width - 20, 50); } //filter Label pageSetuplabel.TextColor = UIColor.Black; pageSetuplabel.BackgroundColor = UIColor.Clear; pageSetuplabel.Text = "Page Setup Options :"; pageSetuplabel.TextAlignment = UITextAlignment.Left; pageSetuplabel.Font = UIFont.FromName("Helvetica", 16f); //filter button layoutButton.SetTitle("NoScaling", UIControlState.Normal); layoutButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; layoutButton.BackgroundColor = UIColor.Clear; layoutButton.SetTitleColor(UIColor.Black, UIControlState.Normal); layoutButton.Hidden = false; layoutButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; layoutButton.Layer.BorderWidth = 4; layoutButton.Layer.CornerRadius = 8; layoutButton.Font = UIFont.FromName("Helvetica", 16f); layoutButton.TouchUpInside += ShowFilterPicker; #endregion #region Layout Picker //filterpicker PickerModel filterPickermodel = new PickerModel(this.layoutList); filterPickermodel.PickerChanged += (sender, e) => { this.selectedLayout = e.SelectedValue; layoutButton.SetTitle(selectedLayout, UIControlState.Normal); }; layoutPicker.ShowSelectionIndicator = true; layoutPicker.Hidden = true; layoutPicker.Model = filterPickermodel; layoutPicker.BackgroundColor = UIColor.White; layoutDoneButton.SetTitle("Done\t", UIControlState.Normal); layoutDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; layoutDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); layoutDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); layoutDoneButton.Hidden = true; layoutDoneButton.TouchUpInside += HideFilterPicker; layoutPicker.Frame = new CGRect(0, this.Frame.Size.Height / 4 + 20, this.Frame.Size.Width, this.Frame.Size.Height / 3); layoutDoneButton.Frame = new CGRect(0, this.Frame.Size.Height / 4 - 20, this.Frame.Size.Width, 40); #endregion ////UI Substitute button if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { SubstituteLabel.Font = UIFont.SystemFontOfSize(16); SubstituteLabel.Frame = new CGRect(10, 170, frameRect.Location.X + frameRect.Size.Width - 20, 50); } else { SubstituteLabel.Frame = new CGRect(10, 175, frameRect.Location.X + frameRect.Size.Width - 20, 50); } //filter Label SubstituteLabel.TextColor = UIColor.Black; SubstituteLabel.BackgroundColor = UIColor.Clear; SubstituteLabel.Text = "Substitute Fonts:"; SubstituteLabel.TextAlignment = UITextAlignment.Left; SubstituteLabel.Font = UIFont.FromName("Helvetica", 16f); ///UI CheckBox checkfontName.SetTitle("Font Name", UIControlState.Normal); checkfontName.SetTitleColor(UIColor.Black, UIControlState.Normal); checkfontName.Frame = new CGRect(10, 205, frameRect.Location.X + frameRect.Size.Width - 20, 50); ////UI Font Name if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { FontNameLabel.Font = UIFont.SystemFontOfSize(18); FontNameLabel.Frame = new CGRect(10, 225, frameRect.Location.X + frameRect.Size.Width - 20, 50); } else { FontNameLabel.Frame = new CGRect(10, 230, frameRect.Location.X + frameRect.Size.Width - 20, 50); } //filter Label FontNameLabel.TextColor = UIColor.Black; FontNameLabel.BackgroundColor = UIColor.Clear; FontNameLabel.Text = "Missing fonts in the device will be substituted to Calibri."; FontNameLabel.TextAlignment = UITextAlignment.Left; FontNameLabel.Font = UIFont.FromName("Helvetica", 9f); ///UI CheckBox checkfontStream.SetTitle("Font stream", UIControlState.Normal); checkfontStream.SetTitleColor(UIColor.Black, UIControlState.Normal); checkfontStream.Frame = new CGRect(10, 255, frameRect.Location.X + frameRect.Size.Width - 20, 50); ////UI Font Stream if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { FontStreamLabel.Font = UIFont.SystemFontOfSize(18); FontStreamLabel.Frame = new CGRect(10, 270, frameRect.Location.X + frameRect.Size.Width - 20, 50); } else { FontStreamLabel.Frame = new CGRect(10, 275, frameRect.Location.X + frameRect.Size.Width - 20, 50); } //filter Label FontStreamLabel.TextColor = UIColor.Black; FontStreamLabel.BackgroundColor = UIColor.Clear; FontStreamLabel.Text = "Missing fonts in the device will be substituted from embedded resource."; FontStreamLabel.TextAlignment = UITextAlignment.Left; FontStreamLabel.Font = UIFont.FromName("Helvetica", 9f); #region Input Template Button //button inputButton.SetTitle("Input Template", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { inputButton.Frame = new CGRect(0, 320, frameRect.Location.X + frameRect.Size.Width, 10); } else { inputButton.Frame = new CGRect(0, 325, frameRect.Location.X + frameRect.Size.Width, 10); } #endregion #region Convert Button convertButton.SetTitle("Convert",UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { convertButton.Frame = new CGRect(0, 345, frameRect.Location.X + frameRect.Size.Width, 10); } else { convertButton.Frame = new CGRect(0, 350, frameRect.Location.X + frameRect.Size.Width, 10); } #endregion } void OnButtonClicked(object sender, EventArgs e) { string resourcePath; //Load the input template from assembly. if (this.checkfontName.IsChecked.Value || this.checkfontStream.IsChecked.Value) resourcePath = "SampleBrowser.Samples.XlsIO.Template.InvoiceTemplate.xlsx"; else resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExcelToPDF.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Create a new memory stream. MemoryStream stream = new MemoryStream(); //Copy input template to newly created memory stream. fileStream.CopyTo(stream); stream.Position = 0; SaveAndView(stream, "application/msexcel"); } void OnConvertClicked(object sender, EventArgs e) { //Instantiate excel engine ExcelEngine excelEngine = new ExcelEngine(); //Excel application IApplication application = excelEngine.Excel; string resourcePath; //Load the input template from assembly. if (this.checkfontName.IsChecked.Value || this.checkfontStream.IsChecked.Value) { application.SubstituteFont += new Syncfusion.XlsIO.Implementation.SubstituteFontEventHandler(SubstituteFont); resourcePath = "SampleBrowser.Samples.XlsIO.Template.InvoiceTemplate.xlsx"; } else resourcePath = "SampleBrowser.Samples.XlsIO.Template.ExcelToPDF.xlsx"; Assembly assembly = Assembly.GetExecutingAssembly(); Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open Workbook IWorkbook workbook = application.Workbooks.Open(fileStream); XlsIORenderer renderer = new XlsIORenderer(); XlsIORendererSettings settings = new XlsIORendererSettings(); settings.IsConvertBlankPage = false; int index = layoutList.IndexOf(selectedLayout); if (index == 0) settings.LayoutOptions = LayoutOptions.NoScaling; else if (index == 1) settings.LayoutOptions = LayoutOptions.FitAllRowsOnOnePage; else if (index == 2) settings.LayoutOptions = LayoutOptions.FitAllColumnsOnOnePage; else settings.LayoutOptions = LayoutOptions.FitSheetOnOnePage; PdfDocument pdfDocument = renderer.ConvertToPDF(workbook, settings); MemoryStream memoryStream = new MemoryStream(); pdfDocument.Save(memoryStream); pdfDocument.Close(true); workbook.Close(); excelEngine.Dispose(); //Save and view the generated file. SaveAndView(memoryStream, "application/pdf"); } void SaveAndView(MemoryStream stream, string contentType) { if (stream != null) { stream.Position = 0; SaveiOS iOSSave = new SaveiOS(); if (contentType == "application/pdf") iOSSave.Save("ExcelToPDF.pdf", contentType, stream); else iOSSave.Save("Input Template.xlsx", contentType, stream); } } void ShowFilterPicker(object sender, EventArgs e) { layoutDoneButton.Hidden = false; layoutPicker.Hidden = false; inputButton.Hidden = true; convertButton.Hidden = true; this.BecomeFirstResponder(); SubstituteLabel.Hidden = true; FontNameLabel.Hidden = true; FontStreamLabel.Hidden = true; checkfontName.Hidden = true; checkfontStream.Hidden = true; } void HideFilterPicker(object sender, EventArgs e) { layoutDoneButton.Hidden = true; layoutPicker.Hidden = true; inputButton.Hidden = false; convertButton.Hidden = false; this.BecomeFirstResponder(); layoutButton.Hidden = false; SubstituteLabel.Hidden = false; FontNameLabel.Hidden = false; FontStreamLabel.Hidden = false; checkfontName.Hidden = false; checkfontStream.Hidden = false; } public override void LayoutSubviews () { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint (frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel (); base.LayoutSubviews (); } private void SubstituteFont(object sender, Syncfusion.XlsIO.Implementation.SubstituteFontEventArgs args) { Assembly assembly = Assembly.GetExecutingAssembly(); if (checkfontName.IsChecked.Value && (args.OriginalFontName == "Bahnschrift Pro SemiBold" || args.OriginalFontName == "Georgia Pro Semibold")) { args.AlternateFontName = "Calibri"; } if (checkfontStream.IsChecked.Value) { if (args.OriginalFontName == "Georgia Pro Semibold") { Stream file = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.georgiab.ttf"); MemoryStream memoryStream = new MemoryStream(); file.CopyTo(memoryStream); file.Close(); args.AlternateFontStream = memoryStream; } else if (args.OriginalFontName == "Bahnschrift Pro SemiBold") { Stream file = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.bahnschrift.ttf"); MemoryStream memoryStream = new MemoryStream(); file.CopyTo(memoryStream); file.Close(); args.AlternateFontStream = memoryStream; } } } } } <file_sep>/Forms/DataGrid/DataGrid.macOS/SaveMacOS.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "SaveMacOS.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AppKit; using Foundation; using QuickLook; using SampleBrowser.SfDataGrid.MacOS; using Xamarin.Forms; using UIView = AppKit.NSView; [assembly: Dependency(typeof(SaveMacOS))] namespace SampleBrowser.SfDataGrid.MacOS { [Preserve(AllMembers = true)] /// <summary> /// A dependency service to save a exported file in UWP /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1400:AccessModifierMustBeDeclared", Justification = "Reviewed.")] class SaveMacOS : ISave { /// <summary> /// Used to Save a Exporting file in UWP device /// </summary> /// <param name="filename">string type parameter fileName</param> /// <param name="contentType">string type parameter content Type</param> /// <param name="stream">MemoryStream type parameter stream</param> public void Save(string filename, string contentType, MemoryStream stream) { string exception = string.Empty; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filePath = Path.Combine(path, filename); try { FileStream fileStream = File.Open(filePath, FileMode.Create); stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { exception = e.ToString(); } if (contentType == "application/html" || exception != string.Empty) { return; } NSWorkspace.SharedWorkspace.OpenFile(filePath); } } }<file_sep>/Forms/DataGrid/DataGrid.iOS/QLPreviewItemFileSystem.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "QLPreviewItemFileSystem.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ [module: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Reviewed.")] #endregion namespace SampleBrowser.SfDataGrid.iOS { using System; using System.Diagnostics.CodeAnalysis; using System.IO; using Foundation; using QuickLook; /// <summary> /// An item that can be previewed with a QuickLook.QLPreviewController. /// </summary> public class QLPreviewItemFileSystem : QLPreviewItem { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string fileName, filePath; /// <summary> /// Initializes a new instance of the QLPreviewItemFileSystem class. /// </summary> /// <param name="fileName">string type parameter fileName</param> /// <param name="filePath">string type parameter filePath</param> public QLPreviewItemFileSystem(string fileName, string filePath) { this.fileName = fileName; this.filePath = filePath; } /// <summary> /// Override this property to get and returns fileName /// </summary> public override string ItemTitle { get { return this.fileName; } } /// <summary> /// Override this property returns the FileName /// </summary> public override NSUrl ItemUrl { get { return NSUrl.FromFilename(this.filePath); } } } }<file_sep>/Forms/PdfViewer/PdfViewer/Samples/PDFViewerGettingStarted/PDFViewerGettingStarted.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfPdfViewer.XForms; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Xamarin.Forms; using Xamarin.Forms.Internals; using System.IO; namespace SampleBrowser.SfPdfViewer { [Preserve(AllMembers = true)] public partial class PDFViewerGettingStarted : SampleView { private float m_backUpVerticalOffset = 0; private float m_backUpHorizontalOffset = 0; private float m_backUpZoomFactor = 0; string currentDocument = "GIS Succinctly"; private bool m_canRestoreBackup = false; private bool m_isPageSwitched = false; public PDFViewerGettingStarted() { InitializeComponent(); pdfViewerControl.DocumentSaveInitiated += PdfViewerControl_DocumentSaved; pdfViewerControl.DocumentLoaded += PdfViewerControl_DocumentLoaded; (BindingContext as GettingStartedViewModel).DocumentName = currentDocument; m_isPageSwitched = true; } private void PdfViewerControl_DocumentLoaded(object sender, EventArgs args) { if (Device.RuntimePlatform == Device.Android) { if (m_canRestoreBackup) { pdfViewerControl.ZoomPercentage = m_backUpZoomFactor; pdfViewerControl.VerticalOffset = m_backUpVerticalOffset; pdfViewerControl.HorizontalOffset = m_backUpHorizontalOffset; m_canRestoreBackup = false; } } } public override void OnAppearing() { if (Device.RuntimePlatform == Device.Android) { string filePath = string.Empty; #if COMMONSB filePath = "SampleBrowser.Samples.PdfViewer.Samples."; #else filePath = "SampleBrowser.SfPdfViewer."; #endif m_canRestoreBackup = !m_isPageSwitched; if (!m_isPageSwitched) { (BindingContext as GettingStartedViewModel).PdfDocumentStream = (typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream(filePath+"Assets." + currentDocument + ".pdf")); } } } public override void OnDisappearing() { if (Device.RuntimePlatform == Device.Android) { m_backUpHorizontalOffset = pdfViewerControl.HorizontalOffset; m_backUpVerticalOffset = pdfViewerControl.VerticalOffset; m_backUpZoomFactor = pdfViewerControl.ZoomPercentage; pdfViewerControl.Unload(); GC.Collect(); GC.WaitForPendingFinalizers(); m_isPageSwitched = false; } } private void PdfViewerControl_DocumentSaved(object sender, DocumentSaveInitiatedEventArgs args) { string filePath = DependencyService.Get<ISave>().Save(args.SaveStream as MemoryStream); string message = "The PDF has been saved to " + filePath; DependencyService.Get<IAlertView>().Show(message); } } } <file_sep>/Forms/Calculate/Calculate/Samples/CalcQuick/CalcQuickCommand.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Forms.Internals; namespace SampleBrowser.Calculate { [Preserve(AllMembers = true)] public class CalcQuickCommand : ICommand { private CalcQuickViewModel viewModel; public CalcQuickCommand(CalcQuickViewModel _ViewModel) { viewModel = _ViewModel; } public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { viewModel.calcQuickBase["A"] = viewModel.TextA; viewModel.calcQuickBase["B"] = viewModel.TextB; viewModel.calcQuickBase["C"] = viewModel.TextC; viewModel.calcQuickBase.SetDirty(); viewModel.Result1 = viewModel.calcQuickBase["Exp1"]; viewModel.Result2 = viewModel.calcQuickBase["Exp2"]; viewModel.Result3 = viewModel.calcQuickBase["Exp3"]; } private void RaiseCanExcuteChanged() { if (CanExecuteChanged != null) CanExecuteChanged(this, new EventArgs()); } } } <file_sep>/Android/SampleBrowser/Samples/AutoComplete/AutoComplete_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Views.InputMethods; using Android.Util; using System; using Com.Syncfusion.Autocomplete; using Android.Widget; using Android.Views; using System.Runtime.Remoting.Contexts; using Android.Graphics; using System.Collections.ObjectModel; using System.Collections.Generic; using Android.App; using Android.Content; using SampleBrowser; namespace SampleBrowser { public class AutoComplete_Tab : SamplePage { /********************************* **Local Variable Inizialisation** *********************************/ Spinner suggestionModeSpinner, autoCompleteModeSpinner; EditText minPrefixCharacterText, maxDropDownHeightText, popUpDelayText; SuggestionMode suggestionModes = SuggestionMode.StartsWith; AutoCompleteMode autoCompleteMode = AutoCompleteMode.Suggest; LinearLayout propertylayout; int minimum = 1, popupdelay = 100, maximum = 150; ArrayAdapter<String> suggestionModeDataAdapter, autoCompleteModeDataAdapter; SfAutoComplete countryNameAutoComplete, jobFieldAutoComplete; TextView jobSearchLabel, countryLabel, jobFieldLabel, experienceLabel, jobSearchLabelSpacing; TextView countryLabelSpacing, countryAutoCompleteSpacing, jobFieldLabelSpacing, jobFieldAutoCompleteSpacing; TextView experienceLabelSpacing, experienceSpinnerSpacing, searchButtonSpacing, closeLabel; Button propertyButton; FrameLayout propertyFrameLayout, buttomButtonLayout; Button searchButton; int jobNumber = 0; Spinner experienceSpinner; AlertDialog.Builder resultsDialog; List<String> Title = new List<String>(); List<String> Country = new List<String>(); List<String> Experience = new List<String>(); int selectionPosition = 0, autoCompletModePosition = 0, totalWidth; int minPrefixCharPosition = 1, maxDropDownPosition = 200, popUpDelayPosition = 100; double actionBarHeight, navigationBarHeight, totalHeight; FrameLayout frame; Android.Content.Context con,context; ScrollView scrollView; public View GetPropertyLayout(Android.Content.Context context) { totalWidth = (context.Resources.DisplayMetrics.WidthPixels); propertylayout = new LinearLayout(context); propertylayout.Orientation = Orientation.Vertical; OptionViewLayout(); SuggestionModeLayout(); AutoCompleteModeLayout(); MinimumPrefixCharacterLayout(); MaximumDropHeightLayout(); PopUpDelayLayout(); return propertylayout; } FrameLayout topProperty; LinearLayout proprtyOptionsLayout; private void OptionViewLayout() { /**************** **Options View** ****************/ TextView propertyLabel = new TextView(context); propertyLabel.SetTextColor(Color.ParseColor("#282828")); propertyLabel.Gravity = GravityFlags.CenterVertical; propertyLabel.TextSize = 18; propertyLabel.SetPadding(0, 10, 0, 10); propertyLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent, GravityFlags.Left | GravityFlags.CenterHorizontal); propertyLabel.Text = " " + "OPTIONS"; //CloseLabel closeLabel = new TextView(context); closeLabel.SetBackgroundColor(Color.Transparent); closeLabel.Gravity = GravityFlags.CenterVertical; closeLabel.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLabel.SetBackgroundResource(Resource.Drawable.sfclosebutton); //CloseLayout FrameLayout closeLayout = new FrameLayout(context); closeLayout.SetBackgroundColor(Color.Transparent); closeLayout.SetPadding(0, 10, 0, 10); closeLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Right | GravityFlags.CenterHorizontal); closeLayout.AddView(closeLabel); //TopProperty topProperty = new FrameLayout(context); topProperty.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); topProperty.SetBackgroundColor(Color.Rgb(230, 230, 230)); topProperty.AddView(propertyLabel); topProperty.AddView(closeLayout); //topProperty Touch Event topProperty.Touch += (object sendar, View.TouchEventArgs e) => { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); buttomButtonLayout.AddView(propertyButton); }; proprtyOptionsLayout = new LinearLayout(context); proprtyOptionsLayout.Orientation = Android.Widget.Orientation.Vertical; //SpaceText TextView spaceText1 = new TextView(context); spaceText1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText1); } private void SuggestionModeLayout() { /****************** **SuggestionMode** ******************/ TextView suggestionModeLabel = new TextView(context); suggestionModeLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); suggestionModeLabel.Text = "Suggestion Mode"; suggestionModeLabel.TextSize = 15; suggestionModeLabel.Gravity = GravityFlags.Left; //SuggestionList List<String> suggestionModeList = new List<String>(); suggestionModeList.Add("StartsWith"); suggestionModeList.Add("StartsWithCaseSensitive"); suggestionModeList.Add("Contains"); suggestionModeList.Add("ContainsWithCaseSensitive"); suggestionModeList.Add("EndsWith"); suggestionModeList.Add("EndsWithCaseSensitive"); suggestionModeList.Add("Equals"); suggestionModeList.Add("EqualsWithCaseSensitive"); suggestionModeSpinner = new Spinner(context,SpinnerMode.Dialog); suggestionModeDataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, suggestionModeList); suggestionModeDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); suggestionModeSpinner.Adapter = suggestionModeDataAdapter; suggestionModeSpinner.SetSelection(selectionPosition); suggestionModeSpinner.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); //suggestionModeSpinner ItemSelected Listener suggestionModeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { selectionPosition = e.Position; String selectedItem = suggestionModeDataAdapter.GetItem(e.Position); if (selectedItem.Equals("StartsWith")) { suggestionModes = SuggestionMode.StartsWith; } else if (selectedItem.Equals("StartsWithCaseSensitive")) { suggestionModes = SuggestionMode.StartsWithCaseSensitive; } else if (selectedItem.Equals("Contains")) { suggestionModes = SuggestionMode.Contains; } else if (selectedItem.Equals("ContainsWithCaseSensitive")) { suggestionModes = SuggestionMode.ContainsWithCaseSensitive; } else if (selectedItem.Equals("EndsWith")) { suggestionModes = SuggestionMode.EndsWith; } else if (selectedItem.Equals("EndsWithCaseSensitive")) { suggestionModes = SuggestionMode.EndsWithCaseSensitive; } else if (selectedItem.Equals("Equals")) { suggestionModes = SuggestionMode.Equals; } else if (selectedItem.Equals("EqualsWithCaseSensitive")) { suggestionModes = SuggestionMode.EqualsWithCaseSensitive; } ApplyChanges(); }; LinearLayout suggestionModeLayout = new LinearLayout(context); suggestionModeLayout.Orientation = Android.Widget.Orientation.Horizontal; suggestionModeLayout.AddView(suggestionModeLabel); suggestionModeLayout.AddView(suggestionModeSpinner); proprtyOptionsLayout.AddView(suggestionModeLayout); TextView spaceText2 = new TextView(context); spaceText2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText2); } private void AutoCompleteModeLayout() { /******************* **AutoCompleteMode** ********************/ TextView autoCompleteModeLabel = new TextView(context); autoCompleteModeLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); autoCompleteModeLabel.Text = "AutoComplete Mode"; autoCompleteModeLabel.TextSize = 15; autoCompleteModeLabel.Gravity = GravityFlags.Left; //autoCompleteModeSpinner autoCompleteModeSpinner = new Spinner(context,SpinnerMode.Dialog); autoCompleteModeSpinner.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); List<String> autoCompleteModeList = new List<String>(); autoCompleteModeList.Add("Suggest"); autoCompleteModeList.Add("SuggestAppend"); autoCompleteModeList.Add("Append"); //autoCompleteModeDataAdapter autoCompleteModeDataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, autoCompleteModeList); autoCompleteModeDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); autoCompleteModeSpinner.Adapter = autoCompleteModeDataAdapter; autoCompleteModeSpinner.SetSelection(autoCompletModePosition); //autoCompleteModeSpinner ItemSelected Listener autoCompleteModeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { autoCompletModePosition = e.Position; String selectedItem = autoCompleteModeDataAdapter.GetItem(e.Position); if (selectedItem.Equals("Suggest")) { autoCompleteMode = AutoCompleteMode.Suggest; } else if (selectedItem.Equals("SuggestAppend")) { autoCompleteMode = AutoCompleteMode.SuggestAppend; } else if (selectedItem.Equals("Append")) { autoCompleteMode = AutoCompleteMode.Append; } ApplyChanges(); }; LinearLayout autoCompleteModeLayout = new LinearLayout(context); autoCompleteModeLayout.Orientation = Android.Widget.Orientation.Horizontal; autoCompleteModeLayout.AddView(autoCompleteModeLabel); autoCompleteModeLayout.AddView(autoCompleteModeSpinner); proprtyOptionsLayout.AddView(autoCompleteModeLayout); TextView spaceText3 = new TextView(context); spaceText3.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText3); } private void MinimumPrefixCharacterLayout() { /************************ **Min Prefix Character** ************************/ TextView minPrefixCharaterLabel = new TextView(context); minPrefixCharaterLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); minPrefixCharaterLabel.Text = "Min Prefix Character"; minPrefixCharaterLabel.TextSize = 15; //minPrefixCharacterText minPrefixCharacterText = new EditText(context); minPrefixCharacterText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); minPrefixCharacterText.Text = minPrefixCharPosition.ToString(); minPrefixCharacterText.TextSize = 16; minPrefixCharacterText.InputType = Android.Text.InputTypes.ClassPhone; minPrefixCharacterText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { try { if (minPrefixCharacterText.Text.Length > 0) minimum = Convert.ToInt32(e.Text.ToString()); else minimum = 1; } catch { } minPrefixCharPosition = minimum; ApplyChanges(); }; //minPrefixCharaterLayout LinearLayout minPrefixCharaterLayout = new LinearLayout(context); minPrefixCharaterLayout.Orientation = Android.Widget.Orientation.Horizontal; minPrefixCharaterLayout.AddView(minPrefixCharaterLabel); minPrefixCharaterLayout.AddView(minPrefixCharacterText); proprtyOptionsLayout.AddView(minPrefixCharaterLayout); TextView spaceText4 = new TextView(context); spaceText4.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText4); } private void MaximumDropHeightLayout() { /*********************** **max DropDown height** ***********************/ TextView maxDropDownHeightLabel = new TextView(context); maxDropDownHeightLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); maxDropDownHeightLabel.Text = "Max DropDown Height"; maxDropDownHeightLabel.TextSize = 15; //maxDropDownHeightText maxDropDownHeightText = new EditText(context); maxDropDownHeightText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); maxDropDownHeightText.Text = maxDropDownPosition.ToString(); maxDropDownHeightText.TextSize = 16; maxDropDownHeightText.InputType = Android.Text.InputTypes.ClassPhone; maxDropDownHeightText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { try { if (maxDropDownHeightText.Text.Length > 0) maximum = Convert.ToInt32(e.Text.ToString()); else maximum = 150; } catch { } maxDropDownPosition = maximum; ApplyChanges(); }; //maxDropDownHeightLayout LinearLayout maxDropDownHeightLayout = new LinearLayout(context); maxDropDownHeightLayout.Orientation = Android.Widget.Orientation.Horizontal; maxDropDownHeightLayout.AddView(maxDropDownHeightLabel); maxDropDownHeightLayout.AddView(maxDropDownHeightText); proprtyOptionsLayout.AddView(maxDropDownHeightLayout); TextView spaceText5 = new TextView(context); spaceText5.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 38, GravityFlags.Center); proprtyOptionsLayout.AddView(spaceText5); } private void PopUpDelayLayout() { /*************** **Popup Delay** ***************/ TextView popUpDelayLabel = new TextView(context); popUpDelayLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); popUpDelayLabel.Text = "PopUp Delay"; popUpDelayLabel.TextSize = 15; //popUpDelayText popUpDelayText = new EditText(context); popUpDelayText.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.33), ViewGroup.LayoutParams.WrapContent, GravityFlags.Center); popUpDelayText.Text = popUpDelayPosition.ToString(); popUpDelayText.TextSize = 16; popUpDelayText.InputType = Android.Text.InputTypes.ClassPhone; minPrefixCharacterText.SetWidth(50); maxDropDownHeightText.SetWidth(50); popUpDelayText.SetWidth(50); //popUpDelayText TextChanged Listener popUpDelayText.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => { try { if (popUpDelayText.Text.Length > 0) popupdelay = Convert.ToInt32(e.Text.ToString()); else popupdelay = 100; } catch { } popUpDelayPosition = popupdelay; ApplyChanges(); }; LinearLayout popUpDelayLayout = new LinearLayout(context); popUpDelayLayout.Orientation = Android.Widget.Orientation.Horizontal; popUpDelayLayout.AddView(popUpDelayLabel); popUpDelayLayout.AddView(popUpDelayText); proprtyOptionsLayout.AddView(popUpDelayLayout); TextView spaceLabel = new TextView(context); spaceLabel.LayoutParameters = new FrameLayout.LayoutParams((int)(totalWidth * 0.167), ViewGroup.LayoutParams.WrapContent); LinearLayout layout1 = new LinearLayout(context); layout1.Orientation = Android.Widget.Orientation.Horizontal; layout1.AddView(spaceLabel); layout1.AddView(proprtyOptionsLayout); propertylayout.AddView(topProperty); propertylayout.AddView(layout1); propertylayout.SetBackgroundColor(Color.Rgb(240, 240, 240)); } public override View GetSampleContent(Android.Content.Context con1) { con = context=con1; InitialMethod(); ResultsLayout(); ExperienceLayout(); LabelInitialization(); //countryNameAutoComplete ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleListItem1, new Countrylist().Country); countryNameAutoComplete.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 50); countryNameAutoComplete.AutoCompleteSource = countryAdapter; countryNameAutoComplete.SuggestionMode = SuggestionMode.StartsWith; countryNameAutoComplete.MaximumDropDownHeight = 150; countryNameAutoComplete.Watermark = "Enter a country name"; countryNameAutoComplete.GetAutoEditText().FocusChange += AutoEditText_FocusChange; countryNameAutoComplete.TextHighlightMode = OccurrenceMode.FirstOccurrence; countryNameAutoComplete.HighlightedTextColor = Color.Blue; //jobFieldAutoComplete ArrayAdapter<String> titleAdapter = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleListItem1, Title); jobFieldAutoComplete.AutoCompleteSource = titleAdapter; jobFieldAutoComplete.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 50); jobFieldAutoComplete.SuggestionMode = SuggestionMode.Contains; jobFieldAutoComplete.MaximumDropDownHeight = 150; jobFieldAutoComplete.Watermark = "Starts with ’S’, ‘M’ or ‘B’"; jobFieldAutoComplete.GetAutoEditText().FocusChange += AutoEditText_FocusChange1; countryNameAutoComplete.GetAutoEditText().SetTextSize(ComplexUnitType.Sp, 20); jobFieldAutoComplete.GetAutoEditText().SetTextSize(ComplexUnitType.Sp, 20); jobFieldAutoComplete.TextHighlightMode = OccurrenceMode.FirstOccurrence; jobFieldAutoComplete.HighlightedTextColor = Color.Blue; SearchButtonLayout(); MainLayout(); return frame; } private void InitialMethod() { frame = new FrameLayout(con); totalHeight = con.Resources.DisplayMetrics.HeightPixels; TypedValue tv = new TypedValue(); if (con.Theme.ResolveAttribute(Android.Resource.Attribute.ActionBarSize, tv, true)) { actionBarHeight = TypedValue.ComplexToDimensionPixelSize(tv.Data, con.Resources.DisplayMetrics); } navigationBarHeight = getNavigationBarHeight(con); totalHeight = totalHeight - navigationBarHeight - actionBarHeight; } private void ResultsLayout() { //resultsDialog resultsDialog = new AlertDialog.Builder(con); resultsDialog.SetTitle("Results"); resultsDialog.SetPositiveButton("OK", (object sender, DialogClickEventArgs e) => { }); resultsDialog.SetCancelable(true); Title.Add("Software"); Title.Add("Banking"); Title.Add("Media"); Title.Add("Medical"); } private void ExperienceLayout() { //experienceSpinner experienceSpinner = new Spinner(con,SpinnerMode.Dialog); experienceSpinner.DropDownWidth = 500; experienceSpinner.SetBackgroundColor(Color.Rgb(92, 178, 224)); ArrayAdapter<String> experienceDataAdapter = new ArrayAdapter<String> (con, Android.Resource.Layout.SimpleSpinnerItem, Experience); experienceDataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); experienceSpinner.Adapter = experienceDataAdapter; Country.Add("UAE"); Country.Add("Uruguay"); Country.Add("United States"); Country.Add("United Kingdom"); Country.Add("Ukraine"); Experience.Add("1"); Experience.Add("2"); } private void LabelInitialization() { //LabelInizialization countryNameAutoComplete = new SfAutoComplete(con); jobFieldAutoComplete = new SfAutoComplete(con); jobSearchLabel = new TextView(con); countryLabel = new TextView(con); jobFieldLabel = new TextView(con); experienceLabel = new TextView(con); jobSearchLabelSpacing = new TextView(con); countryLabelSpacing = new TextView(con); countryAutoCompleteSpacing = new TextView(con); jobFieldLabelSpacing = new TextView(con); jobFieldAutoCompleteSpacing = new TextView(con); experienceLabelSpacing = new TextView(con); experienceSpinnerSpacing = new TextView(con); searchButtonSpacing = new TextView(con); countryLabelSpacing.SetHeight(10); countryAutoCompleteSpacing.SetHeight(30); jobFieldLabelSpacing.SetHeight(10); jobFieldAutoCompleteSpacing.SetHeight(30); experienceLabelSpacing.SetHeight(10); experienceSpinnerSpacing.SetHeight(30); searchButtonSpacing.SetHeight(30); jobSearchLabel.Text = "Job Search"; jobSearchLabel.TextSize = 30; jobSearchLabel.Typeface = Typeface.DefaultBold; countryLabel.Text = "Country"; countryLabel.TextSize = 16; jobFieldLabel.Text = "Job Field"; jobFieldLabel.TextSize = 16; experienceLabel.Text = "Experience"; experienceLabel.TextSize = 16; jobSearchLabelSpacing.SetHeight(40); } private void SearchButtonLayout() { //searchButton searchButton = new Button(con); searchButton.SetWidth(ActionBar.LayoutParams.MatchParent); searchButton.SetHeight(40); searchButton.Text = "Search"; searchButton.SetTextColor(Color.White); searchButton.SetBackgroundColor(Color.Rgb(72, 178, 224)); searchButton.Click += (object sender, EventArgs e) => { GetResult(); resultsDialog.SetMessage(jobNumber + " Jobs Found"); resultsDialog.Create().Show(); }; } private void MainLayout() { ArrayAdapter<String> experienceAdapter = new ArrayAdapter<String>(con, Android.Resource.Layout.SimpleListItem1, Experience); experienceSpinner.Adapter = experienceAdapter; experienceSpinner.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, con.Resources.GetDimensionPixelSize(Resource.Dimension.auto_picker_ht)); //mainLayout LinearLayout mainLayout = new LinearLayout(con); mainLayout.SetPadding(20, 20, 20, 30); mainLayout.SetBackgroundColor(Color.White); mainLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.6), GravityFlags.Top | GravityFlags.CenterHorizontal); mainLayout.Orientation = Orientation.Vertical; mainLayout.AddView(jobSearchLabel); mainLayout.AddView(jobSearchLabelSpacing); mainLayout.AddView(countryLabel); mainLayout.AddView(countryLabelSpacing); mainLayout.AddView(countryNameAutoComplete); mainLayout.AddView(countryAutoCompleteSpacing); mainLayout.AddView(jobFieldLabel); mainLayout.AddView(jobFieldLabelSpacing); mainLayout.AddView(jobFieldAutoComplete); mainLayout.AddView(jobFieldAutoCompleteSpacing); mainLayout.AddView(experienceLabel); mainLayout.AddView(experienceLabelSpacing); mainLayout.AddView(experienceSpinner); mainLayout.AddView(experienceSpinnerSpacing); mainLayout.AddView(searchButtonSpacing); mainLayout.AddView(searchButton); mainLayout.Touch += (object sender, View.TouchEventArgs e) => { if (countryNameAutoComplete.IsFocused || jobFieldAutoComplete.IsFocused) { Rect outRect = new Rect(); countryNameAutoComplete.GetGlobalVisibleRect(outRect); jobFieldAutoComplete.GetGlobalVisibleRect(outRect); if (!outRect.Contains((int)e.Event.RawX, (int)e.Event.RawY)) { countryNameAutoComplete.ClearFocus(); jobFieldAutoComplete.ClearFocus(); } } hideSoftKeyboard((Activity)con); }; frame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); frame.SetBackgroundColor(Color.White); frame.SetPadding(10, 10, 10, 10); //scrollView1 ScrollView scrollView1 = new ScrollView(con); scrollView1.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.6), GravityFlags.Top | GravityFlags.CenterHorizontal); scrollView1.AddView(mainLayout); frame.AddView(scrollView1); //buttomButtonLayout buttomButtonLayout = new FrameLayout(con); buttomButtonLayout.SetBackgroundColor(Color.Transparent); buttomButtonLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1), GravityFlags.Bottom | GravityFlags.CenterHorizontal); //propertyButton propertyButton = new Button(con); propertyButton.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, GravityFlags.Bottom | GravityFlags.CenterHorizontal); propertyButton.Text = "OPTIONS"; propertyButton.Gravity = GravityFlags.Start; propertyFrameLayout = new FrameLayout(con); propertyFrameLayout.SetBackgroundColor(Color.Rgb(236, 236, 236)); propertyFrameLayout.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.4), GravityFlags.CenterHorizontal); propertyFrameLayout.AddView(GetPropertyLayout(con)); //propertyButton Click Listener propertyButton.Click += (object sender, EventArgs e) => { buttomButtonLayout.RemoveAllViews(); propertyFrameLayout.RemoveAllViews(); countryNameAutoComplete.ClearFocus(); jobFieldAutoComplete.ClearFocus(); scrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.4), GravityFlags.Bottom | GravityFlags.CenterHorizontal); propertyFrameLayout.AddView(GetPropertyLayout(con)); }; //scrollView scrollView = new ScrollView(con); scrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.4), GravityFlags.Bottom | GravityFlags.CenterHorizontal); scrollView.AddView(propertyFrameLayout); frame.AddView(scrollView); frame.AddView(buttomButtonLayout); frame.FocusableInTouchMode = true; } private void AutoEditText_FocusChange1(object sender, View.FocusChangeEventArgs e) { if ((sender as EditText).IsFocused) { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); scrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1), GravityFlags.Bottom | GravityFlags.CenterHorizontal); buttomButtonLayout.AddView(propertyButton); } } private void AutoEditText_FocusChange(object sender, View.FocusChangeEventArgs e) { if ((sender as EditText).IsFocused) { propertyFrameLayout.RemoveAllViews(); buttomButtonLayout.RemoveAllViews(); scrollView.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(totalHeight * 0.1), GravityFlags.Bottom | GravityFlags.CenterHorizontal); buttomButtonLayout.AddView(propertyButton); } } public void GetResult() { jobNumber = 0; if (countryNameAutoComplete.Text.ToString().Equals("") || jobFieldAutoComplete.Text.ToString().Equals("")) { } else { Random r = new Random(); jobNumber = r.Next(5, 60); } } public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.GetSystemService(Activity.InputMethodService); inputMethodManager.HideSoftInputFromWindow(activity.CurrentFocus.WindowToken, 0); } public void ApplyChanges() { countryNameAutoComplete.SuggestionMode = suggestionModes; countryNameAutoComplete.AutoCompleteMode = autoCompleteMode; countryNameAutoComplete.MinimumPrefixCharacters = minimum; countryNameAutoComplete.PopUpDelay = popupdelay; countryNameAutoComplete.MaximumDropDownHeight = maximum; jobFieldAutoComplete.SuggestionMode = suggestionModes; jobFieldAutoComplete.AutoCompleteMode = autoCompleteMode; jobFieldAutoComplete.MinimumPrefixCharacters = minimum; jobFieldAutoComplete.PopUpDelay = popupdelay; jobFieldAutoComplete.MaximumDropDownHeight = maximum; } private int getStatusBarHeight(Android.Content.Context con) { int barHeight = 0; int resourceId = con.Resources.GetIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { barHeight = con.Resources.GetDimensionPixelSize(resourceId); } return barHeight; } private int getNavigationBarHeight(Android.Content.Context con) { int navBarHeight = 0; int resourceId = con.Resources.GetIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { navBarHeight = con.Resources.GetDimensionPixelSize(resourceId); } return navBarHeight; } } }<file_sep>/Forms/Chart/Chart/Samples/PieChart/PieSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class PieSeriesViewModel { public ObservableCollection<ChartDataModel> PieSeriesData { get; set; } public PieSeriesViewModel() { PieSeriesData = new ObservableCollection<ChartDataModel> { new ChartDataModel("David", 30), new ChartDataModel("Steve", 35), new ChartDataModel("Micheal", 24), new ChartDataModel("John", 11), new ChartDataModel("Regev", 25), new ChartDataModel("Jack", 39), new ChartDataModel("Stephen", 15), }; } } } <file_sep>/Forms/Barcode/Barcode/Samples/QRBarcodeLogo/QRBarcodeLogo.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfBarcode.XForms; using Xamarin.Forms.Internals; using SampleBrowser.Core; using System.IO; using System.Reflection; namespace SampleBrowser.SfBarcode { [Preserve(AllMembers = true)] public partial class QRBarcodeLogo : SampleView { public QRBarcodeLogo() { InitializeComponent(); #if COMMONSB Stream imageStream = typeof(QRBarcodeLogo).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.Barcode.Assets.qrcodelogo.png"); #else Stream imageStream = typeof(QRBarcodeLogo).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.SfBarcode.Assets.qrcodelogo.png"); #endif QRCodeLogo logo = new QRCodeLogo(imageStream); QRBarcodeSettings settings = new QRBarcodeSettings(); settings.Logo = logo; settings.XDimension = 8; this.qrBarcode.SymbologySettings = settings; } } } <file_sep>/Android/SampleBrowser/Samples/Chart/Series/Column.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Com.Syncfusion.Charts; using Com.Syncfusion.Charts.Enums; using Com.Syncfusion.Navigationdrawer; namespace SampleBrowser { public class Column : SamplePage { SfChart chart; ColumnSeries columnSeries1; ColumnSeries columnSeries2; ColumnSeries columnSeries3; TextView spacingValue; TextView columnWidthValue; TextView cornerRadiusValue; public override View GetSampleContent(Context context) { chart = new SfChart(context); chart.Title.Text = "Olympic Medal Counts - RIO"; chart.Title.TextSize = 15; chart.SetBackgroundColor(Color.White); chart.Legend.Visibility = Visibility.Visible; chart.Legend.ToggleSeriesVisibility = true; chart.Legend.DockPosition = ChartDock.Bottom; chart.Legend.IconHeight = 14; chart.Legend.IconWidth = 14; chart.ColorModel.ColorPalette = ChartColorPalette.Natural; CategoryAxis categoryaxis = new CategoryAxis(); categoryaxis.LabelPlacement = LabelPlacement.BetweenTicks; categoryaxis.Title.Text = "Countries"; categoryaxis.EdgeLabelsDrawingMode = EdgeLabelsDrawingMode.Shift; categoryaxis.ShowMajorGridLines = false; chart.PrimaryAxis = categoryaxis; NumericalAxis numericalaxis = new NumericalAxis(); numericalaxis.Title.Text = "Medals"; numericalaxis.Visibility = Visibility.Gone; numericalaxis.ShowMajorGridLines = false; chart.SecondaryAxis = numericalaxis; columnSeries1 = new ColumnSeries(); columnSeries1.Label = "Gold"; columnSeries1.ItemsSource = MainPage.GetColumnData1(); columnSeries1.XBindingPath = "XValue"; columnSeries1.YBindingPath = "YValue"; columnSeries1.TooltipEnabled = true; columnSeries1.EnableAnimation = true; columnSeries1.LegendIcon = ChartLegendIcon.SeriesType; columnSeries1.DataMarker.ShowLabel = true; columnSeries1.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Inner; columnSeries2 = new ColumnSeries(); columnSeries2.Label = "Silver"; columnSeries2.ItemsSource = MainPage.GetColumnData2(); columnSeries2.XBindingPath = "XValue"; columnSeries2.YBindingPath = "YValue"; columnSeries2.TooltipEnabled = true; columnSeries2.EnableAnimation = true; columnSeries2.LegendIcon = ChartLegendIcon.SeriesType; columnSeries2.DataMarker.ShowLabel = true; columnSeries2.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Inner; columnSeries3 = new ColumnSeries(); columnSeries3.Label = "Bronze"; columnSeries3.ItemsSource = MainPage.GetColumnData3(); columnSeries3.XBindingPath = "XValue"; columnSeries3.YBindingPath = "YValue"; columnSeries3.TooltipEnabled = true; columnSeries3.EnableAnimation = true; columnSeries3.LegendIcon = ChartLegendIcon.SeriesType; columnSeries3.DataMarker.ShowLabel = true; columnSeries3.DataMarker.LabelStyle.LabelPosition = DataMarkerLabelPosition.Inner; chart.Series.Add(columnSeries1); chart.Series.Add(columnSeries2); chart.Series.Add(columnSeries3); return chart; } public override View GetPropertyWindowLayout(Android.Content.Context context) { /** * Property Window * */ int width = (context.Resources.DisplayMetrics.WidthPixels) / 2; LinearLayout propertylayout = new LinearLayout(context); //= new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams( width * 2, 5); layoutParams1.SetMargins(0, 20, 0, 0); spacingValue = new TextView(context); spacingValue.Text = "Spacing : 0.0"; spacingValue.SetPadding(5, 20, 0, 20); columnWidthValue = new TextView(context); columnWidthValue.Text = "Width : 0.8"; columnWidthValue.SetPadding(5, 20, 0, 20); cornerRadiusValue = new TextView(context); cornerRadiusValue.Text = "Corner Radious : 0"; cornerRadiusValue.SetPadding(5, 20, 0, 20); SeekBar spacing = new SeekBar(context); spacing.Max = 10; SeekBar columnWidth = new SeekBar(context); columnWidth.Max = 10; columnWidth.Progress = 8; SeekBar cornerRadius = new SeekBar(context); cornerRadius.Max = 15; cornerRadius.Progress = 0; spacing.ProgressChanged += Spacing_ProgressChanged; columnWidth.ProgressChanged += ColumnWidth_ProgressChanged; cornerRadius.ProgressChanged += CornerRadius_ProgressChanged; propertylayout.AddView(columnWidthValue); propertylayout.AddView(columnWidth); propertylayout.AddView(spacingValue); propertylayout.AddView(spacing); propertylayout.AddView(cornerRadiusValue); propertylayout.AddView(cornerRadius); SeparatorView separate = new SeparatorView(context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams(width * 2, 5); propertylayout.AddView(separate, layoutParams1); return propertylayout; } private void CornerRadius_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { double cornerRadious = 0; cornerRadious = (int)e.Progress; columnSeries1.CornerRadius = new ChartCornerRadius(cornerRadious, cornerRadious, 0, 0); columnSeries2.CornerRadius = new ChartCornerRadius(cornerRadious, cornerRadious, 0, 0); columnSeries3.CornerRadius = new ChartCornerRadius(cornerRadious, cornerRadious, 0, 0); cornerRadiusValue.Text = "Corner Radious : " + cornerRadious; } private void Spacing_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { float spacing = 0; spacing = (int)e.Progress; columnSeries1.Spacing = spacing / 10; columnSeries2.Spacing = spacing / 10; columnSeries3.Spacing = spacing / 10; spacingValue.Text = "Spacing : " + spacing / 10; } private void ColumnWidth_ProgressChanged(object sender, SeekBar.ProgressChangedEventArgs e) { float columnWidth = 0; columnWidth = (int)e.Progress; columnSeries1.Width = columnWidth / 10; columnSeries2.Width = columnWidth / 10; columnSeries3.Width = columnWidth / 10; columnWidthValue.Text = "Width : " + columnWidth / 10; } } }<file_sep>/iOS/SampleBrowser/Samples/DocIO/GroupShapes.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.Pdf; using Syncfusion.DocIORenderer; using Syncfusion.OfficeChart; using Syncfusion.Drawing; using System.IO; using COLOR = Syncfusion.Drawing; using System.Reflection; using Syncfusion.iOS.Buttons; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using ObjCRuntime; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; #endif namespace SampleBrowser { public partial class GroupShapes : SampleView { CGRect frameRect = new CGRect(); float frameMargin = 8.0f; UILabel label; UILabel imageTypelabel; UIButton imageType; UIButton generateButton; //RadioButton SfRadioGroup radioGroup = new SfRadioGroup(); SfRadioButton docxButton = new SfRadioButton(); SfRadioButton pdfButton = new SfRadioButton(); public GroupShapes() { label = new UILabel(); imageTypelabel = new UILabel(); imageType = new UIButton(); generateButton = new UIButton(UIButtonType.System); generateButton.TouchUpInside += OnConvertClicked; } void LoadAllowedTextsLabel() { #region Description Label label.Frame = frameRect; label.TextColor = UIColor.FromRGB(38 / 255.0f, 38 / 255.0f, 38 / 255.0f); label.Text = "This sample demonstrates how to create a Word document with Group shapes."; label.Font = UIFont.SystemFontOfSize(15); label.Lines = 0; label.LineBreakMode = UILineBreakMode.WordWrap; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { label.Font = UIFont.SystemFontOfSize(18); label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 35); } else { label.Frame = new CGRect(5, 5, frameRect.Location.X + frameRect.Size.Width, 50); } this.AddSubview(label); #endregion #region ImageFormat Label if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { imageTypelabel.Font = UIFont.SystemFontOfSize(18); imageTypelabel.Frame = new CGRect(10, 45, frameRect.Location.X + frameRect.Size.Width - 20, 50); imageType.Frame = new CGRect(10, 95, frameRect.Location.X + frameRect.Size.Width - 20, 40); } else { imageTypelabel.Frame = new CGRect(10, 50, frameRect.Location.X + frameRect.Size.Width - 20, 50); imageType.Frame = new CGRect(10, 100, frameRect.Location.X + frameRect.Size.Width - 20, 40); } //filter Label imageTypelabel.TextColor = UIColor.Black; imageTypelabel.BackgroundColor = UIColor.Clear; imageTypelabel.Text = "Save As:"; imageTypelabel.TextAlignment = UITextAlignment.Left; imageTypelabel.Font = UIFont.FromName("Helvetica", 16f); this.AddSubview(imageTypelabel); #endregion #region Radio Buttons radioGroup.Axis = UILayoutConstraintAxis.Horizontal; docxButton.SetTitle("DOCX", UIControlState.Normal); radioGroup.AddArrangedSubview(docxButton); pdfButton.SetTitle("PDF", UIControlState.Normal); radioGroup.AddArrangedSubview(pdfButton); docxButton.IsChecked = true; radioGroup.Distribution = UIStackViewDistribution.FillProportionally; if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { radioGroup.Frame = new CGRect(110, 55, frameRect.Width - 500, 30); } else { radioGroup.Frame = new CGRect(110, 60, frameRect.Width - 90, 30); } this.AddSubview(radioGroup); #endregion #region Convert Button generateButton.SetTitle("Generate", UIControlState.Normal); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { generateButton.Frame = new CGRect(0, 105, frameRect.Location.X + frameRect.Size.Width, 10); } else { generateButton.Frame = new CGRect(0, (this.Frame.Size.Height / 4) - 5, frameRect.Location.X + frameRect.Size.Width, 10); } this.AddSubview(generateButton); #endregion } void OnConvertClicked(object sender, EventArgs e) { //Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Sets page setup options section.PageSetup.Orientation = PageOrientation.Landscape; section.PageSetup.Margins.All = 72; section.PageSetup.PageSize = new SizeF(792f, 612f); //Adds new paragraph to the section WParagraph paragraph = section.AddParagraph() as WParagraph; //Creates new group shape GroupShape groupShape = new GroupShape(document); //Adds group shape to the paragraph. paragraph.ChildEntities.Add(groupShape); //Create a RoundedRectangle shape with "Management" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(324f, 107.7f, 144f, 45f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(50, 48, 142), "Management", groupShape, document); //Create a BentUpArrow shape to connect with "Development" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(177.75f, 176.25f, 210f, 50f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Sales" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(403.5f, 175.5f, 210f, 50f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a DownArrow shape to connect with "Production" shape CreateChildShape(AutoShapeType.DownArrow, new RectangleF(381f, 153f, 29.25f, 72.5f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a RoundedRectangle shape with "Development" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(135f, 226.45f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(104, 57, 157), "Development", groupShape, document); //Create a RoundedRectangle shape with "Production" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(341f, 226.5f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(149, 50, 118), "Production", groupShape, document); //Create a RoundedRectangle shape with "Sales" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(546.75f, 226.5f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(179, 63, 62), "Sales", groupShape, document); //Create a DownArrow shape to connect with "Software" and "Hardware" shape CreateChildShape(AutoShapeType.DownArrow, new RectangleF(177f, 265.5f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a DownArrow shape to connect with "Series" and "Parts" shape CreateChildShape(AutoShapeType.DownArrow, new RectangleF(383.25f, 265.5f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a DownArrow shape to connect with "North" and "South" shape CreateChildShape(AutoShapeType.DownArrow, new RectangleF(588.75f, 266.25f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Software" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(129.5f, 286.5f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Hardware" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(190.5f, 286.5f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Series" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(336f, 287.25f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "Parts" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(397f, 287.25f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "North" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(541.5f, 288f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a BentUpArrow shape to connect with "South" shape CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(602.5f, 288f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document); //Create a RoundedRectangle shape with "Software" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(93f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "Software", groupShape, document); //Create a RoundedRectangle shape with "Hardware" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(197.2f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "Hardware", groupShape, document); //Create a RoundedRectangle shape with "Series" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(299.25f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "Series", groupShape, document); //Create a RoundedRectangle shape with "Parts" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(404.2f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "Parts", groupShape, document); //Create a RoundedRectangle shape with "North" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(505.5f, 321.75f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "North", groupShape, document); //Create a RoundedRectangle shape with "South" text CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(609.7f, 321.75f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "South", groupShape, document); string fileName = null; string ContentType = null; MemoryStream ms = new MemoryStream(); if (pdfButton != null && (bool)pdfButton.IsChecked) { fileName = "GroupShapes.pdf"; ContentType = "application/pdf"; DocIORenderer renderer = new DocIORenderer(); PdfDocument pdfDoc = renderer.ConvertToPDF(document); pdfDoc.Save(ms); pdfDoc.Close(); } else { fileName = "GroupShapes.docx"; ContentType = "application/msword"; document.Save(ms, FormatType.Docx); } //Reset the stream position ms.Position = 0; //Close the document instance. document.Close(); if (ms != null) { SaveiOS iOSSave = new SaveiOS(); iOSSave.Save(fileName, ContentType, ms as MemoryStream); } } public override void LayoutSubviews() { if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { frameMargin = 0.0f; } frameRect = Bounds; frameRect.Location = new CGPoint(frameRect.Location.X + frameMargin, frameRect.Location.Y + 1.5f * frameMargin); frameRect.Size = new CGSize(frameRect.Size.Width - (frameRect.Location.X + frameMargin), frameRect.Size.Height - (frameRect.Location.Y + 1.5f * frameMargin)); LoadAllowedTextsLabel(); base.LayoutSubviews(); } /// <summary> /// Create a child shape with its specified properties and add into specified group shape /// </summary> /// <param name="autoShapeType">Represent the AutoShapeType of child shape</param> /// <param name="bounds">Represent the bounds of child shape to be placed</param> /// <param name="rotation">Represent the rotation of child shape</param> /// <param name="flipH">Represent the horizontal flip of child shape</param> /// <param name="flipV">Represent the vertical flip of child shape</param> /// <param name="fillColor">Represent the fill color of child shape</param> /// <param name="text">Represent the text that to be append in child shape</param> /// <param name="groupShape">Represent the group shape to add a child shape</param> /// <param name="wordDocument">Represent the Word document instance</param> private static void CreateChildShape(AutoShapeType autoShapeType, RectangleF bounds, float rotation, bool flipH, bool flipV, Syncfusion.Drawing.Color fillColor, string text, GroupShape groupShape, WordDocument wordDocument) { //Creates new shape to add into group Shape shape = new Shape(wordDocument, autoShapeType); //Sets height and width for shape shape.Height = bounds.Height; shape.Width = bounds.Width; //Sets horizontal and vertical position shape.HorizontalPosition = bounds.X; shape.VerticalPosition = bounds.Y; //Set rotation and flipH for the shape if (rotation != 0) shape.Rotation = rotation; if (flipH) shape.FlipHorizontal = true; if (flipV) shape.FlipVertical = true; //Applies fill color for shape if (fillColor != Syncfusion.Drawing.Color.White) { shape.FillFormat.Fill = true; shape.FillFormat.Color = fillColor; } //Set wrapping style for shape shape.WrapFormat.TextWrappingStyle = TextWrappingStyle.InFrontOfText; //Sets horizontal and vertical origin shape.HorizontalOrigin = HorizontalOrigin.Page; shape.VerticalOrigin = VerticalOrigin.Page; //Sets no line to RoundedRectangle shapes if (autoShapeType == AutoShapeType.RoundedRectangle) shape.LineFormat.Line = false; //Add paragraph for the shape textbody if (text != null) { IWParagraph paragraph = shape.TextBody.AddParagraph(); //Set required textbody alignments shape.TextFrame.TextVerticalAlignment = Syncfusion.DocIO.DLS.VerticalAlignment.Middle; //Set required paragraph alignments paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; IWTextRange textRange = paragraph.AppendText(text); //Applies a required text formatting's textRange.CharacterFormat.FontName = "Calibri"; textRange.CharacterFormat.FontSize = 15; textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White; textRange.CharacterFormat.Bold = true; textRange.CharacterFormat.Italic = true; } //Adds the specified shape to group shape groupShape.Add(shape); } } }<file_sep>/Forms/Schedule/Schedule/Samples/Localization/ViewModel/LocalizationViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.SfSchedule.XForms; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Localization View Model class /// </summary> [Preserve(AllMembers = true)] public class LocalizationViewModel { #region Properties /// <summary> /// japanese collection /// </summary> private List<string> japaneseCollection; /// <summary> /// english collection /// </summary> private List<string> englishCollection; /// <summary> /// french collection /// </summary> private List<string> frenchCollection; /// <summary> /// spanish collection /// </summary> private List<string> spanishCollection; /// <summary> /// color collection /// </summary> private List<Color> colorCollection; /// <summary> /// start time collection /// </summary> private List<DateTime> startTimeCollection; /// <summary> /// end time collection /// </summary> private List<DateTime> endTimeCollection; /// <summary> /// random numbers /// </summary> private List<int> randomNums = new List<int>(); #endregion Properties #region Constructor /// <summary> /// Initializes a new instance of the <see cref="LocalizationViewModel" /> class. /// </summary> public LocalizationViewModel() { this.JapaneseAppointments = new ScheduleAppointmentCollection(); this.EnglishAppointments = new ScheduleAppointmentCollection(); this.FrenchAppointments = new ScheduleAppointmentCollection(); this.SpanishAppointments = new ScheduleAppointmentCollection(); this.CreateRandomNumbersCollection(); this.CreateStartTimeCollection(); this.CreateEndTimeCollection(); this.CreateColorCollection(); this.AddJapaneseLanguageString(); this.AddEnglishLanguageString(); this.AddFrenchLanguageString(); this.AddSpanishLanguageString(); this.GetJapaneseAppoitments(10); this.GetFrenchAppoitments(10); this.GetEnglishAppoitments(10); this.GetSpanishAppoitments(10); } #endregion Constructor /// <summary> /// Gets or sets japanese appointments /// </summary> public ScheduleAppointmentCollection JapaneseAppointments { get; set; } /// <summary> /// Gets or sets english appointment /// </summary> public ScheduleAppointmentCollection EnglishAppointments { get; set; } /// <summary> /// Gets or sets french appointments /// </summary> public ScheduleAppointmentCollection FrenchAppointments { get; set; } /// <summary> /// Gets or sets spanish appointments /// </summary> public ScheduleAppointmentCollection SpanishAppointments { get; set; } #region Methods #region Appointments collection /// <summary> /// Gets the japanese appointments. /// </summary> /// <param name="count">Count value.</param> private void GetJapaneseAppoitments(int count) { for (int i = 0; i < count; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = this.colorCollection[i]; scheduleAppointment.Subject = this.japaneseCollection[i]; scheduleAppointment.StartTime = this.startTimeCollection[i]; scheduleAppointment.EndTime = this.endTimeCollection[i]; this.JapaneseAppointments.Add(scheduleAppointment); } // AllDay Appointment in current day ScheduleAppointment allDayAppointment = new ScheduleAppointment(); allDayAppointment.Color = Color.FromHex("#FFD80073"); allDayAppointment.Subject = "ジェニーの誕生日"; allDayAppointment.StartTime = this.startTimeCollection[5]; allDayAppointment.EndTime = this.endTimeCollection[5]; allDayAppointment.IsAllDay = true; this.JapaneseAppointments.Add(allDayAppointment); } /// <summary> /// Gets the english appointments. /// </summary> /// <param name="count">Count value.</param> private void GetEnglishAppoitments(int count) { for (int i = 0; i < count; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = this.colorCollection[i]; scheduleAppointment.Subject = this.englishCollection[i]; scheduleAppointment.StartTime = this.startTimeCollection[i]; scheduleAppointment.EndTime = this.endTimeCollection[i]; this.EnglishAppointments.Add(scheduleAppointment); } // AllDay Appointment in current day ScheduleAppointment allDayAppointment = new ScheduleAppointment(); allDayAppointment.Color = Color.FromHex("#FFD80073"); allDayAppointment.Subject = "Jeni's Birthday"; allDayAppointment.StartTime = this.startTimeCollection[5]; allDayAppointment.EndTime = this.endTimeCollection[5]; allDayAppointment.IsAllDay = true; this.EnglishAppointments.Add(allDayAppointment); } /// <summary> /// Gets the french appointments. /// </summary> /// <param name="count">Count value.</param> private void GetFrenchAppoitments(int count) { for (int i = 0; i < count; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = this.colorCollection[i]; scheduleAppointment.Subject = this.frenchCollection[i]; scheduleAppointment.StartTime = this.startTimeCollection[i]; scheduleAppointment.EndTime = this.endTimeCollection[i]; this.FrenchAppointments.Add(scheduleAppointment); } // AllDay Appointment in current day ScheduleAppointment allDayAppointment = new ScheduleAppointment(); allDayAppointment.Color = Color.FromHex("#FFD80073"); allDayAppointment.Subject = "L'anniversaire de Jeni"; allDayAppointment.StartTime = this.startTimeCollection[5]; allDayAppointment.EndTime = this.endTimeCollection[5]; allDayAppointment.IsAllDay = true; this.FrenchAppointments.Add(allDayAppointment); } /// <summary> /// Gets the spanish appointments. /// </summary> /// <param name="count">Count value.</param> private void GetSpanishAppoitments(int count) { for (int i = 0; i < count; i++) { ScheduleAppointment scheduleAppointment = new ScheduleAppointment(); scheduleAppointment.Color = this.colorCollection[i]; scheduleAppointment.Subject = this.spanishCollection[i]; scheduleAppointment.StartTime = this.startTimeCollection[i]; scheduleAppointment.EndTime = this.endTimeCollection[i]; this.SpanishAppointments.Add(scheduleAppointment); } // AllDay Appointment in current day ScheduleAppointment allDayAppointment = new ScheduleAppointment(); allDayAppointment.Color = Color.FromHex("#FFD80073"); allDayAppointment.Subject = "Cumpleaños de Jeni"; allDayAppointment.StartTime = this.startTimeCollection[5]; allDayAppointment.EndTime = this.endTimeCollection[5]; allDayAppointment.IsAllDay = true; this.SpanishAppointments.Add(allDayAppointment); } #endregion Appointments collection #region Language String /// <summary> /// Japanese appointment collection /// </summary> private void AddJapaneseLanguageString() { this.japaneseCollection = new List<string>(); this.japaneseCollection.Add("会議に行く"); this.japaneseCollection.Add("ビジネスミーティング"); this.japaneseCollection.Add("会議"); this.japaneseCollection.Add("議論ドラフト法"); this.japaneseCollection.Add("監査"); this.japaneseCollection.Add("顧客会議"); this.japaneseCollection.Add("レポートを生成する"); this.japaneseCollection.Add("対象会議"); this.japaneseCollection.Add("総会"); this.japaneseCollection.Add("ステータスの更新"); this.japaneseCollection.Add("プロジェクト計画"); } /// <summary> /// English appointment collection /// </summary> private void AddEnglishLanguageString() { this.englishCollection = new List<string>(); this.englishCollection.Add("GoToMeeting"); this.englishCollection.Add("Business Meeting"); this.englishCollection.Add("Conference"); this.englishCollection.Add("Project Status Discussion"); this.englishCollection.Add("Auditing"); this.englishCollection.Add("Client Meeting"); this.englishCollection.Add("Generate Report"); this.englishCollection.Add("Target Meeting"); this.englishCollection.Add("General Meeting"); this.englishCollection.Add("Pay House Rent"); this.englishCollection.Add("Car Service"); } /// <summary> /// french appointment collection /// </summary> private void AddFrenchLanguageString() { this.frenchCollection = new List<string>(); this.frenchCollection.Add("aller ‡ la rÈunion"); this.frenchCollection.Add("Un rendez-vous d'affaire"); this.frenchCollection.Add("ConfÈrence"); this.frenchCollection.Add("Discussion Projet de Statut"); this.frenchCollection.Add("audit"); this.frenchCollection.Add("RÈunion du client"); this.frenchCollection.Add("gÈnÈrer un rapport"); this.frenchCollection.Add("RÈunion cible"); this.frenchCollection.Add("AssemblÈe gÈnÈrale"); this.frenchCollection.Add("Pay Maison Louer"); this.frenchCollection.Add("Service automobile"); } /// <summary> /// spanish appointment collection /// </summary> private void AddSpanishLanguageString() { this.spanishCollection = new List<string>(); this.spanishCollection.Add("Ir a la reuniÛn"); this.spanishCollection.Add("ReuniÛn de negocios"); this.spanishCollection.Add("Conferencia"); this.spanishCollection.Add("SituaciÛn del proyecto DiscusiÛn"); this.spanishCollection.Add("AuditorÌa"); this.spanishCollection.Add("ReuniÛn Cliente"); this.spanishCollection.Add("Generar informe"); this.spanishCollection.Add("ReuniÛn Target"); this.spanishCollection.Add("ReuniÛn general"); this.spanishCollection.Add("Pago Casa Alquilar"); this.spanishCollection.Add("Servicio de auto"); } #endregion #region creating color collection /// <summary> /// color collection /// </summary> ////creating color collection private void CreateColorCollection() { this.colorCollection = new List<Color>(); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FFF09609")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF1BA1E2")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFA2C139")); this.colorCollection.Add(Color.FromHex("#FFD80073")); this.colorCollection.Add(Color.FromHex("#FF339933")); this.colorCollection.Add(Color.FromHex("#FFE671B8")); this.colorCollection.Add(Color.FromHex("#FF00ABA9")); } #endregion creating color collection #region CreateRandomNumbersCollection /// <summary> /// random number collection /// </summary> ////creating random number collection private void CreateRandomNumbersCollection() { this.randomNums = new List<int>(); Random rand = new Random(); for (int i = 0; i < 10; i++) { int random = rand.Next(9, 15); this.randomNums.Add(random); } } #endregion CreateRandomNumbersCollection #region CreateStartTimeCollection /// <summary> /// start time collection /// </summary> //// creating StartTime collection private void CreateStartTimeCollection() { this.startTimeCollection = new List<DateTime>(); DateTime currentDate = DateTime.Now; int count = 0; for (int i = -5; i < 5; i++) { DateTime startTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, this.randomNums[count], 0, 0); DateTime startDateTime = startTime.AddDays(i); this.startTimeCollection.Add(startDateTime); count++; } } #endregion CreateStartTimeCollection #region CreateEndTimeCollection /// <summary> /// end time collection /// </summary> //// creating EndTime collection private void CreateEndTimeCollection() { this.endTimeCollection = new List<DateTime>(); DateTime currentDate = DateTime.Now; int count = 0; for (int i = -5; i < 5; i++) { DateTime endTime = new DateTime(currentDate.Year, currentDate.Month, currentDate.Day, this.randomNums[count] + 1, 0, 0); DateTime endDateTime = endTime.AddDays(i); this.endTimeCollection.Add(endDateTime); count++; } } #endregion CreateEndTimeCollection #endregion Methods } }<file_sep>/iOS/SampleBrowser/Resources/Samples/PullToRefresh/PullToRefreshDemo.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Foundation; using SampleBrowser; using Syncfusion.SfPullToRefresh.iOS; using UIKit; namespace SampleBrowser { public class PullToRefreshDemo: SampleView { internal SFPullToRefresh pullToRefresh; UIView mainView; internal BaseView baseView; CustomScroll scrollView; public override void LayoutSubviews() { pullToRefresh.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); mainView.Frame = new CGRect(Frame.Location.X, 0, Frame.Width, Frame.Height); if (baseView == null) { load(); } pullToRefresh.PullableContent = mainView; SetNeedsDisplay(); } public PullToRefreshDemo() { mainView = new UIView(); pullToRefresh = new SFPullToRefresh(); mainView.BackgroundColor = UIColor.FromRGBA(0.012f,0.608f,0.898f,1); AddSubview(pullToRefresh); pullToRefresh.Delegate = new PullToRefreshDelegate(this); } void load() { scrollView = new CustomScroll(new CGRect(0, pullToRefresh.Frame.Height - 150, pullToRefresh.Frame.Width, 150)); mainView.AddSubview(scrollView); scrollView.BackgroundColor = UIColor.FromRGBA(0, 0.478f, 0.667f, 1); scrollView.ShowsHorizontalScrollIndicator = false; scrollView.ShowsVerticalScrollIndicator = false; int x = 0; List<WeatherModel> array = addPopulationData(); baseView = new BaseView(new CGRect(0, (Frame.Height / 4), Frame.Width, Frame.Height / 2)); baseView.model = array[0]; baseView.updateBaseView(); for (int i = 0; i < array.Count; i++) { WeatherView button = new WeatherView(new CGRect(x, 20, 100, 100)); button.model = array[i]; button.baseView = baseView; button.drawView(); if (i == 0) { baseView.selectedView = button; button.selectView(); } scrollView.AddSubview(button); x += (int)button.Frame.Width; } scrollView.ContentSize = new CGSize(x, 0); mainView.AddSubview(baseView); UILabel label = new UILabel(new CGRect(0, 20, pullToRefresh.Frame.Width, 50)); label.Text = @"MorrisVille"; label.TextColor = UIColor.White; label.Font = UIFont.SystemFontOfSize(14); label.TextAlignment = UITextAlignment.Center; mainView.AddSubview(label); } List<WeatherModel> addPopulationData() { List<WeatherModel> array = new List<WeatherModel>(); NSDate now = NSDate.Now; string[] imagesArray = new string[] { "Cloudy.png", "Humid.png", "Rainy.png", "Warm.png", "Windy.png", "Cloudy.png", "Humid.png" }; for (int i = 0; i < 7; i++) { int daysToAdd = i; NSDateComponents components = new NSDateComponents(); components.Day = daysToAdd; NSCalendar gregorian = NSCalendar.CurrentCalendar; NSDate newDate2 = gregorian.DateByAddingComponents(components, now, NSCalendarOptions.None); NSDateFormatter dateFormatter = new NSDateFormatter(); dateFormatter.DateFormat = "EEEE, MMMM dd"; NSDateFormatter dateFormatter1 = new NSDateFormatter(); dateFormatter1.DateFormat = "EEEE"; array.Add(new WeatherModel((NSString)dateFormatter.StringFor(newDate2), (NSString)imagesArray[i], (NSString)new Random().Next(10, 40).ToString(), (NSString)dateFormatter1.StringFor(newDate2))); } return array; } } public class PullToRefreshDelegate : SFPullToRefreshDelegate { public PullToRefreshDelegate(PullToRefreshDemo markers) { sample = markers; } PullToRefreshDemo sample; public override void Refreshed(SFPullToRefresh pulltorefresh) { NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(2), new Action<NSTimer>(delegate { sample.baseView.model.Temp = (NSString)new Random().Next(10, 40).ToString(); sample.baseView.updateBaseView(); sample.baseView.selectedView.selectView(); sample.baseView.selectedView.updateTemp(); sample.pullToRefresh.Refresh(); })); } } } <file_sep>/Forms/DataGrid/DataGrid/Samples/Model/DealerRepository.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "DealerRepository.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class Used to store the values /// </summary> public class DealerRepository { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] public string[] CustomersMale = new string[] { "Adams", "Owens", "Thomas", "Doran", "Jefferson", "Spencer", "Vargas", "Grimes", "Edwards", "Stark", "Cruise", "Fitz", "Chief", "Blanc", "Stone", "Williams", "Jobs", "Holmes" }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] public string[] CustomersFemale = new string[] { "Crowley", "Waddell", "Irvine", "Keefe", "Ellis", "Gable", "Mendoza", "Rooney", "Lane", "Landry", "Perry", "Perez", "Newberry", "Betts", "Fitzgerald", }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] public string[] Customers = new string[] { "Adams", "Owens", "Thomas", "Doran", "Jefferson", "Spencer", "Vargas", "Grimes", "Edwards", "Stark", "Cruise", "Fitz", "Chief", "Blanc", "Stone", "Williams", "Jobs", "Holmes", "Crowley", "Waddell", "Irvine", "Keefe", "Ellis", "Gable", "Mendoza", "Rooney", "Lane", "Landry", "Perry", "Perez", "Newberry", "Betts", "Fitzgerald", }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] public string[] ImageMale = new string[] { "People_Circle5.png", "People_Circle8.png", "People_Circle12.png", "People_Circle14.png", "People_Circle18.png", "People_Circle23.png", "People_Circle26.png", "People_Circle27.png", }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed")] [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Some fields must be public")] public string[] ImageFemale = new string[] { "People_Circle0.png", "People_Circle1.png", "People_Circle2.png", "People_Circle3.png", "People_Circle4.png", "People_Circle6.png", "People_Circle7.png", "People_Circle9.png", "People_Circle10.png", "People_Circle11.png", "People_Circle13.png", "People_Circle15.png", "People_Circle16.png", "People_Circle17.png", "People_Circle19.png", "People_Circle20.png", "People_Circle21.png", "People_Circle22.png", "People_Circle24.png", "People_Circle25.png", }; #region private variables [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Reviewed. Suppression is OK here.This field is used in outside this class")] [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] internal Dictionary<string, string[]> ShipCity = new Dictionary<string, string[]>(); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Random random = new Random(); [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private List<DateTime> shippedDate; #endregion [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private int[] productNo = new int[] { 1803, 1345, 4523, 4932, 9475, 5243, 4263, 2435, 3527, 3634, 2523, 3652, 3524, 6532, 2123 }; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string[] shipCountry = new string[] { "Argentina", "Austria", "Belgium", "Brazil", "Canada", "Denmark", "Finland", "France", "Germany", "Ireland", "Italy", "Mexico", "Norway", "Poland", "Portugal", "Spain", "Sweden", "UK", "USA", }; #region GetDealerDetails /// <summary> /// Generates record rows with given count /// </summary> /// <param name="count">generates row count</param> /// <returns>generated row records</returns> public ObservableCollection<DealerInfo> GetDealerDetails(int count) { ObservableCollection<DealerInfo> dealerDetails = new ObservableCollection<DealerInfo>(); var assembly = Assembly.GetAssembly(this.GetType()); this.SetShipCity(); this.shippedDate = this.GetDateBetween(2001, 2016, count); for (int i = 1; i <= count; i++) { var shipcountry = this.shipCountry[this.random.Next(5)]; var shipcitycoll = this.ShipCity[shipcountry]; var ord = new DealerInfo() { ProductID = 1100 + i, ProductNo = this.productNo[this.random.Next(15)], DealerName = (i % 2 == 0) ? this.CustomersMale[this.random.Next(15)] : this.CustomersFemale[this.random.Next(14)], ProductPrice = this.random.Next(2000, 10000), IsOnline = (i % this.random.Next(1, 10) > 2) ? true : false, DealerImage = (i % 2 == 0) ? this.ImageMale[this.random.Next(7)] : this.ImageFemale[this.random.Next(15)], ShippedDate = this.shippedDate[i - 1], ShipCountry = shipcountry, ShipCity = shipcitycoll[this.random.Next(shipcitycoll.Length - 1)], }; dealerDetails.Add(ord); } return dealerDetails; } #endregion /// <summary> /// Used to generate DateTime and returns the value /// </summary> /// <param name="startYear">integer type of parameter startYear</param> /// <param name="endYear">integer type of parameter endYear</param> /// <param name="count">integer type of parameter count</param> /// <returns>returns the generated DateTime</returns> private List<DateTime> GetDateBetween(int startYear, int endYear, int count) { List<DateTime> date = new List<DateTime>(); Random d = new Random(1); Random m = new Random(2); Random y = new Random(startYear); for (int i = 0; i < count; i++) { int year = y.Next(startYear, endYear); int month = m.Next(3, 13); int day = d.Next(1, 31); date.Add(new DateTime(year, month, day)); } return date; } /// <summary> /// This method used to store the string items collections Value /// </summary> private void SetShipCity() { string[] argentina = new string[] { "Rosario", "Catamarca", "Formosa", "Salta" }; string[] austria = new string[] { "Graz", "Salzburg", "Linz", "Wels" }; string[] belgium = new string[] { "Bruxelles", "Charleroi", "Namur", "Mons" }; string[] brazil = new string[] { "Campinas", "Resende", "Recife", "Manaus" }; string[] canada = new string[] { "Alberta", "Montral", "Tsawassen", "Vancouver" }; string[] denmark = new string[] { "Svendborg", "Farum", "rhus", "Kbenhavn" }; string[] finland = new string[] { "Helsinki", "Helsinki", "Espoo", "Oulu" }; string[] france = new string[] { "Lille", "Lyon", "Marseille", "Nantes", "Paris", "Reims", "Strasbourg", "Toulouse", "Versailles" }; string[] germany = new string[] { "Aachen", "Berlin", "Brandenburg", "Cunewalde", "Frankfurt", "Kln", "Leipzig", "Mannheim", "Mnchen", "Mnster", "Stuttgart" }; string[] ireland = new string[] { "Cork", "Waterford", "Bray", "Athlone" }; string[] italy = new string[] { "Bergamo", "Reggio", "Torino", "Genoa" }; string[] mexico = new string[] { "<NAME>.", "Puebla", "León", "Zapopan" }; string[] norway = new string[] { "Stavern", "Hamar", "Harstad", "Narvik" }; string[] poland = new string[] { "Warszawa", "Gdynia", "Rybnik", "Legnica" }; string[] portugal = new string[] { "Lisboa", "Albufeira", "Elvas", "Estremoz" }; string[] spain = new string[] { "Barcelona", "Madrid", "Sevilla", "Biscay" }; string[] sweden = new string[] { "Brcke", "Pitea", "Robertsfors ", "Lule" }; string[] switzerland = new string[] { "Bern", "Genve", "Charrat", "Châtillens" }; string[] uk = new string[] { "Colchester", "Hedge End", "London", "Bristol" }; string[] usa = new string[] { "Albuquerque", "Anchorage", "Boise", "Butte", "Elgin", "Eugene", "Kirkland", "Lander", "Portland", "San Francisco", "Seattle", }; string[] venezuela = new string[] { "Barquisimeto", "Caracas", "I. <NAME>", "San Cristbal", "Cantaura" }; this.ShipCity.Add("Argentina", argentina); this.ShipCity.Add("Austria", austria); this.ShipCity.Add("Belgium", belgium); this.ShipCity.Add("Brazil", brazil); this.ShipCity.Add("Canada", canada); this.ShipCity.Add("Denmark", denmark); this.ShipCity.Add("Finland", finland); this.ShipCity.Add("France", france); this.ShipCity.Add("Germany", germany); this.ShipCity.Add("Ireland", ireland); this.ShipCity.Add("Italy", italy); this.ShipCity.Add("Mexico", mexico); this.ShipCity.Add("Norway", norway); this.ShipCity.Add("Poland", poland); this.ShipCity.Add("Portugal", portugal); this.ShipCity.Add("Spain", spain); this.ShipCity.Add("Sweden", sweden); this.ShipCity.Add("Switzerland", switzerland); this.ShipCity.Add("UK", uk); this.ShipCity.Add("USA", usa); this.ShipCity.Add("Venezuela", venezuela); } } }<file_sep>/iOS/SampleBrowser/Utility/Utility.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using CoreGraphics; using Foundation; using UIKit; namespace SampleBrowser { public static class Utility { #region interface public interface ISpecialDisposable { void SpecialDispose(); } #endregion #region properties public static UIColor ThemeColor { get; set; } = UIColor.FromRGB(3.0f / 255.0f, 126.0f / 255.0f, 249.0f / 255.0f); public static UIColor BackgroundColor { get; set; } = UIColor.FromRGB(242.0f / 255.0f, 242.0f / 255.0f, 242.0f / 255.0f); public static UIFont TitleFont { get; set; } = UIFont.FromName("Helvetica", 14f); public static UIFont SmallFont { get; set; } = UIFont.FromName("Helvetica", 10f); public static bool IsIPad { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad; } } #endregion #region methods public static CGSize SizeForStringWithFont(string text, UIFont font) { NSString value = new NSString(text); UIStringAttributes attribs = new UIStringAttributes { Font = font }; CGSize size = value.GetSizeUsingAttributes(attribs); return size; } public static void DisposeEx(UIView view) { try { var disposeView = true; var disconnectFromSuperView = true; var disposeSubviews = true; var removeGestureRecognizers = false; var removeLayerAnimations = true; var associatedViewsToDispose = new List<UIView>(); var otherDisposables = new List<IDisposable>(); var activityIndicatorView = view as UIActivityIndicatorView; var tableView = view as UITableView; var tableViewCell = view as UITableViewCell; var collectionView = view as UICollectionView; var collectionViewCell = view as UICollectionViewCell; var webView = view as UIWebView; var imageView = view as UIImageView; if (activityIndicatorView != null) { if (activityIndicatorView.IsAnimating) { activityIndicatorView.StopAnimating(); } } else if (tableView != null) { if (tableView.DataSource != null) { otherDisposables.Add(tableView.DataSource); } if (tableView.BackgroundView != null) { associatedViewsToDispose.Add(tableView.BackgroundView); } tableView.Source = null; tableView.Delegate = null; tableView.DataSource = null; tableView.WeakDelegate = null; tableView.WeakDataSource = null; associatedViewsToDispose.AddRange(tableView.VisibleCells ?? new UITableViewCell[0]); } else if (tableViewCell != null) { disposeView = false; disconnectFromSuperView = false; if (tableViewCell.ImageView != null) { associatedViewsToDispose.Add(tableViewCell.ImageView); } } else if (collectionView != null) { disposeView = false; if (collectionView.DataSource != null) { otherDisposables.Add(collectionView.DataSource); } if (!(collectionView.BackgroundView == null)) { associatedViewsToDispose.Add(collectionView.BackgroundView); } collectionView.Source = null; collectionView.Delegate = null; collectionView.DataSource = null; collectionView.WeakDelegate = null; collectionView.WeakDataSource = null; } else if (collectionViewCell != null) { disposeView = false; disconnectFromSuperView = false; if (collectionViewCell.BackgroundView != null) { associatedViewsToDispose.Add(collectionViewCell.BackgroundView); } } else if (webView != null) { if (webView.IsLoading) { webView.StopLoading(); } webView.LoadHtmlString(string.Empty, null); // clear display webView.Delegate = null; webView.WeakDelegate = null; } else if (imageView != null) { if (imageView.Image != null) { otherDisposables.Add(imageView.Image); imageView.Image = null; } } var gestures = view.GestureRecognizers; if (removeGestureRecognizers && gestures != null) { foreach (var gr in gestures) { view.RemoveGestureRecognizer(gr); gr.Dispose(); } } if (removeLayerAnimations && view.Layer != null) { view.Layer.RemoveAllAnimations(); } if (disconnectFromSuperView && view.Superview != null) { view.RemoveFromSuperview(); } var constraints = view.Constraints; if (constraints != null && constraints.Any() && constraints.All(c => c.Handle != IntPtr.Zero)) { view.RemoveConstraints(constraints); foreach (var constraint in constraints) { constraint.Dispose(); } } foreach (var otherDisposable in otherDisposables) { otherDisposable.Dispose(); } foreach (var otherView in associatedViewsToDispose) { DisposeEx(otherView); } var subViews = view.Subviews; if (disposeSubviews && subViews != null) { foreach (UIView subview in subViews) { DisposeEx(subview); } } var disposableView = view as ISpecialDisposable; if (disposableView != null) { disposableView.SpecialDispose(); } else if (disposeView) { if (view.Handle != IntPtr.Zero) { view.Dispose(); } } } catch { } } public static bool IsDisposedOrNull(UIView view) { if (view == null) { return true; } if (view.Handle == IntPtr.Zero) { return true; } return false; } #endregion } } <file_sep>/Forms/Chart/Chart/Samples/ColumnChart/ColumnSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class ColumnSeriesViewModel { public ObservableCollection<ChartDataModel> ColumnData1 { get; set; } public ObservableCollection<ChartDataModel> ColumnData2 { get; set; } public ObservableCollection<ChartDataModel> ColumnData3 { get; set; } public ColumnSeriesViewModel() { ColumnData1 = new ObservableCollection<ChartDataModel> { new ChartDataModel("USA", 46), new ChartDataModel("GBR", 27), new ChartDataModel("CHN", 26), }; ColumnData2 = new ObservableCollection<ChartDataModel> { new ChartDataModel("USA", 37), new ChartDataModel("GBR", 23), new ChartDataModel("CHN", 18), }; ColumnData3 = new ObservableCollection<ChartDataModel> { new ChartDataModel("USA", 38), new ChartDataModel("GBR", 17), new ChartDataModel("CHN", 26), }; } } }<file_sep>/Forms/DataGrid/DataGrid/Samples/Paging/PagingBehavior.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "PagingBehavior.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfDataGrid { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using SampleBrowser.Core; using Syncfusion.SfDataGrid.XForms; using Syncfusion.SfDataGrid.XForms.DataPager; using Syncfusion.XForms.Themes; using Xamarin.Forms; using Xamarin.Forms.Internals; [Xamarin.Forms.Internals.Preserve(AllMembers = true)] /// <summary> /// Base generic class for generalized user-defined behaviors that can respond to arbitrary conditions and events. /// Type parameters:T: The type of the objects with which this Forms.Behavior`1 can be associated in the Paging samples /// </summary> public class PagingBehavior : Behavior<SampleView> { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private Syncfusion.SfDataGrid.XForms.SfDataGrid datagrid; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SfDataPager datapager; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private DataPagerViewModel viewModel; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private PickerExt selectionPicker; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private SampleView samplePage; /// <summary> /// You can override this method to subscribe to AssociatedObject events and initialize properties. /// </summary> /// <param name="bindAble">SampleView type of bindAble</param> protected override void OnAttachedTo(SampleView bindAble) { this.viewModel = new DataPagerViewModel(); this.samplePage = bindAble; bindAble.BindingContext = this.viewModel; this.InitPager(bindAble); base.OnAttachedTo(bindAble); } /// <summary> /// You can override this method while View was detached from window /// </summary> /// <param name="bindAble">A sampleView type of bindAble</param> protected override void OnDetachingFrom(SampleView bindAble) { if (this.selectionPicker != null) { this.selectionPicker.SelectedIndexChanged -= this.SelectionPicker_SelectedIndexChanged; } (this.datapager.Children[1] as ScrollView).Scrolled -= this.PagingBehavior_Scrolled; this.datagrid = null; this.datapager = null; this.viewModel = null; base.OnDetachingFrom(bindAble); } /// <summary> /// Initializes the required properties of the data pager. /// </summary> /// <param name="bindAble">The sample view that hosts the data grid and the data pager.</param> private void InitPager(SampleView bindAble) { this.datagrid = bindAble.FindByName<Syncfusion.SfDataGrid.XForms.SfDataGrid>("dataGrid"); this.datapager = bindAble.FindByName<SfDataPager>("dataPager"); this.selectionPicker = bindAble.FindByName<PickerExt>("SelectionPicker"); if (this.selectionPicker != null) { this.selectionPicker.Items.Add("Rectangle"); this.selectionPicker.Items.Add("Circle"); this.selectionPicker.SelectedIndexChanged += this.SelectionPicker_SelectedIndexChanged; this.datapager.AppearanceManager = new PagerAppearance(); } else { this.datapager.PropertyChanged += this.DatapagerPropertyChanged; } this.datapager.PageSize = 20; this.datapager.Source = this.viewModel.OrdersInfo; this.datagrid.ItemsSource = this.datapager.PagedSource; (this.datapager.Children[1] as ScrollView).Scrolled += this.PagingBehavior_Scrolled; if (Device.RuntimePlatform == Device.UWP || Device.Idiom == TargetIdiom.Tablet || Device.RuntimePlatform == Device.macOS) { this.datapager.NumericButtonCount = 12; } else if (Device.Idiom == TargetIdiom.Phone || Device.RuntimePlatform == Device.WPF) { this.datapager.NumericButtonCount = 6; } if (Device.RuntimePlatform == Device.UWP) { this.datapager.HeightRequest = 50; } } /// <summary> /// Triggers while selected Index was changed, used to set a button shape. /// </summary> /// <param name="sender">OnSelectionChanged event sender</param> /// <param name="e">EventArgs e</param> private void SelectionPicker_SelectedIndexChanged(object sender, EventArgs e) { if (this.datagrid != null && this.datagrid.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name.Equals("IsGridLoaded")) != null && (bool)this.datagrid.GetType().GetRuntimeFields().FirstOrDefault(x => x.Name.Equals("IsGridLoaded")).GetValue(this.datagrid) == true) { if (this.selectionPicker.SelectedIndex == 0) { (this.datapager.Children[1] as ScrollView).Scrolled -= this.PagingBehavior_Scrolled; this.samplePage.Content = null; this.samplePage.Content = new Paging("Rectangle").Content; } else if (this.selectionPicker.SelectedIndex == 1) { (this.datapager.Children[1] as ScrollView).Scrolled -= this.PagingBehavior_Scrolled; this.samplePage.Content = null; this.samplePage.Content = new Paging("Circle").Content; } } } /// <summary> /// Raises when the <see cref="SfDataPager"/> property gets changed. /// </summary> /// <param name="sender"><see cref="SfDataPager"/> instance.</param> /// <param name="e">Event args.</param> private void DatapagerPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == "AppearanceManager") { var pager = sender as SfDataPager; ICollection<ResourceDictionary> mergedDictionaries = null; #if COMMONSB var parent = ((pager.Parent as Grid).Parent as Grid).Parent; while (parent != null) { if (parent is ThemesPage) { mergedDictionaries = (parent as Page).Resources.MergedDictionaries; break; } parent = parent.Parent; } parent = null; #else mergedDictionaries = ((sender as SfDataPager).Parent.Parent.Parent as SampleView).Resources.MergedDictionaries; #endif var boxView = ((sender as SfDataPager).Parent.Parent as Grid).Children[1] as BoxView; var darkTheme = (mergedDictionaries != null) ? mergedDictionaries.OfType<DarkTheme>().FirstOrDefault() : null; var lightTheme = (mergedDictionaries != null) ? mergedDictionaries.OfType<LightTheme>().FirstOrDefault() : null; var darkThemeIndex = mergedDictionaries.IndexOf(darkTheme); var lightThemeIndex = mergedDictionaries.IndexOf(lightTheme); if (darkTheme != null && darkThemeIndex > lightThemeIndex) { boxView.Color = Color.FromHex("#414141"); } else { boxView.Color = Color.FromHex("#E0E0E0"); } mergedDictionaries = null; pager = null; boxView = null; } } /// <summary> /// Event handler that is fired when scrolling happens in pager. /// </summary> /// <param name="sender">The scroll view inside the pager.</param> /// <param name="e">Scrolling event arguments</param> private async void PagingBehavior_Scrolled(object sender, ScrolledEventArgs e) { var scrollView = sender as ScrollView; if (e.ScrollX > scrollView.ContentSize.Width - scrollView.Width - 3) { await(sender as ScrollView).ScrollToAsync(scrollView.ContentSize.Width - scrollView.Width - 3, 0, false); } scrollView = null; } } } <file_sep>/Forms/Presentation/Presentation.iOS/SaveIOS.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Foundation; using UIKit; using QuickLook; using Xamarin.Forms; using SampleBrowser.Presentation.iOS; using MessageUI; [assembly: Dependency(typeof(SaveIOS))] [assembly: Dependency(typeof(MailService))] namespace SampleBrowser.Presentation.iOS { class SaveIOS: ISave { public void Save(string filename, string contentType, MemoryStream stream) { string exception = string.Empty; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filePath = Path.Combine(path, filename); try { FileStream fileStream = File.Open(filePath, FileMode.Create); stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { exception = e.ToString(); } if (contentType == "application/html" || exception != string.Empty) return; UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController; while (currentController.PresentedViewController != null) currentController = currentController.PresentedViewController; UIView currentView = currentController.View; QLPreviewController qlPreview = new QLPreviewController(); QLPreviewItem item = new QLPreviewItemBundle(filename, filePath); qlPreview.DataSource = new PreviewControllerDS(item); //UIViewController uiView = currentView as UIViewController; currentController.PresentViewController((UIViewController)qlPreview, true, (Action)null); } } public class MailService : IMailService { public MailService() { } public void ComposeMail(string fileName, string[] recipients, string subject, string messagebody, MemoryStream stream) { if (MFMailComposeViewController.CanSendMail) { var mailer = new MFMailComposeViewController(); mailer.SetMessageBody(messagebody ?? string.Empty, false); mailer.SetSubject(subject ?? subject); mailer.Finished += (s, e) => ((MFMailComposeViewController)s).DismissViewController(true, () => { }); string exception = string.Empty; string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string filePath = Path.Combine(path, fileName); try { FileStream fileStream = File.Open(filePath, FileMode.Create); stream.Position = 0; stream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); } catch (Exception e) { exception = e.ToString(); } finally { } mailer.AddAttachmentData(NSData.FromFile(filePath), GetMimeType(fileName), Path.GetFileName(fileName)); UIViewController vc = UIApplication.SharedApplication.KeyWindow.RootViewController; while (vc.PresentedViewController != null) { vc = vc.PresentedViewController; } vc.PresentViewController(mailer, true, null); } } private string GetMimeType(string filename) { if (string.IsNullOrEmpty(filename)) { return null; } var extension = Path.GetExtension(filename.ToLowerInvariant()); switch (extension) { case "png": return "image/png"; case "doc": return "application/msword"; case "pdf": return "application/pdf"; case "jpeg": case "jpg": return "image/jpeg"; case "zip": case "docx": case "xlsx": case "pptx": return "application/zip"; case "htm": case "html": return "text/html"; } return "application/octet-stream"; } } }<file_sep>/iOS/SampleBrowser/Resources/Samples/ImageEditor/ImageEditorCustomView.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.Collections.Generic; using UIKit; using CoreGraphics; using Syncfusion.SfImageEditor.iOS; using Foundation; namespace SampleBrowser { public class ImageEditorCustomView : SampleView { UINavigationController navigationController; public ImageEditorCustomView() { } public override void MovedToSuperview() { base.MovedToSuperview(); var view = Superview; var window = UIApplication.SharedApplication.KeyWindow; navigationController = window.RootViewController as UINavigationController; } public override void LayoutSubviews() { base.LayoutSubviews(); UIView mainView = new UIView(); nfloat TotalWidth = Frame.Width - 10; mainView.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); int padding = 3; /*------Header Label-------*/ UILabel label = new UILabel(new CGRect(20, 50, TotalWidth, 25)); label.BackgroundColor = UIColor.Clear; label.Font = UIFont.SystemFontOfSize(25); label.TextAlignment = UITextAlignment.Left; label.TextColor = UIColor.Gray; label.Text = "Sample Pictures"; UIButton imageView1 = new UIButton(new CGRect(padding, 100, (TotalWidth / 3) - padding, 150)); imageView1.SetImage(UIImage.FromBundle("Images/ImageEditor/CustomViewImage1.png"), UIControlState.Normal); imageView1.ImageView.ContentMode = UIViewContentMode.ScaleToFill; imageView1.Layer.BorderColor = UIColor.LightGray.CGColor; imageView1.Layer.BorderWidth = 0.5f; imageView1.TouchDown += (sender, e) => { navigationController.PushViewController(new CustomViewViewController(imageView1.CurrentImage, 0), false); }; mainView.AddSubview(imageView1); UIButton imageView2 = new UIButton(new CGRect((TotalWidth / 3) + (1 * padding), 100, (TotalWidth / 3) - padding, 150)); imageView2.SetImage(UIImage.FromBundle("Images/ImageEditor/CustomViewImage2.png"), UIControlState.Normal); imageView2.ImageView.ContentMode = UIViewContentMode.ScaleToFill; imageView2.Layer.BorderColor = UIColor.LightGray.CGColor; imageView2.Layer.BorderWidth = 0.5f; mainView.AddSubview(imageView2); imageView2.TouchDown += (sender, e) => { navigationController.PushViewController(new CustomViewViewController(imageView2.CurrentImage, 1), false); }; UIButton imageView3 = new UIButton(new CGRect((2 * (TotalWidth / 3)) + (1 * padding), 100, (TotalWidth / 3) - padding, 150)); imageView3.SetImage(UIImage.FromBundle("Images/ImageEditor/CustomViewImage3.png"), UIControlState.Normal); imageView3.ImageView.ContentMode = UIViewContentMode.ScaleToFill; imageView3.Layer.BorderColor = UIColor.LightGray.CGColor; imageView3.Layer.BorderWidth = 0.5f; imageView3.TouchDown += (sender, e) => { navigationController.PushViewController(new CustomViewViewController(imageView3.CurrentImage, 2), false); }; mainView.AddSubview(imageView3); AddSubview(label); AddSubview(mainView); } } public class CustomViewViewController : UIViewController { UIImage image; public CustomViewViewController(UIImage image, int index) { this.image = image; selectedIndex = index; } SfImageEditor imageEditor; UIViewController presentController; UIView CropSelectionMenu; int selectedIndex = 0; List<ToolbarItem> CustomViewItems; CustomViewSettings customViewSettings; bool isReplaced; string imageName; public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); presentController = GetVisibleViewController(); imageEditor = new SfImageEditor(new CGRect(View.Frame.Location.X, 60, View.Frame.Size.Width, View.Frame.Size.Height - 60)); imageEditor.SetToolbarItemVisibility("text,transform,shape,path", false); CustomViewItems = new List<ToolbarItem>() { new CustomToolbarItem(){ CustomName = "Typogy1",Icon=UIImage.FromBundle("Images/ImageEditor/ITypogy1.png"),IconHeight=70 }, new CustomToolbarItem(){CustomName = "Typogy2",Icon=UIImage.FromBundle("Images/ImageEditor/ITypogy2.png"),IconHeight=70 }, new CustomToolbarItem(){CustomName = "Typogy3",Icon=UIImage.FromBundle("Images/ImageEditor/ITypogy3.png"),IconHeight=70 }, new CustomToolbarItem(){CustomName = "Typogy4",Icon=UIImage.FromBundle("Images/ImageEditor/ITypogy4.png"),IconHeight=70 }, new CustomToolbarItem(){CustomName = "Typogy5",Icon=UIImage.FromBundle("Images/ImageEditor/ITypogy5.png"),IconHeight=70 }, new CustomToolbarItem(){CustomName = "Typogy6",Icon=UIImage.FromBundle("Images/ImageEditor/ITypogy6.png"),IconHeight=70 }, }; // Add the custom tool bar items var item1 = new FooterToolbarItem() { Text = "Add", Icon = UIImage.FromBundle("Images/ImageEditor/AddIcon.png"), SubItems = CustomViewItems, TextHeight = 20, }; var item2 = new FooterToolbarItem() { Text = "Replace", Icon = UIImage.FromBundle("Images/ImageEditor/ReplaceIcon.png"), SubItems = CustomViewItems, TextHeight = 20 }; var item3 = new FooterToolbarItem() { Icon = UIImage.FromBundle("Images/ImageEditor/BringFrontIcon"), Text = "Bring Front", TextHeight = 20 }; var item4 = new FooterToolbarItem() { Icon = UIImage.FromBundle("Images/ImageEditor/SendBack"), Text = "Send Back", TextHeight = 20 }; imageEditor.ToolBarSettings.ToolbarItems.Add(item1); imageEditor.ToolBarSettings.ToolbarItems.Add(item2); imageEditor.ToolBarSettings.ToolbarItems.Add(item3); imageEditor.ToolBarSettings.ToolbarItems.Add(item4); imageEditor.ToolBarSettings.SubItemToolbarHeight = 70; imageEditor.ItemSelected += ImageEditor_ItemSelected; imageEditor.ToolBarSettings.ToolbarItemSelected += OnToolbarItemSelected; imageEditor.Image = image; this.View.AddSubview(imageEditor); } private void ImageEditor_ItemSelected(object sender, ItemSelectedEventArgs args) { if (args.Settings != null && args.Settings is CustomViewSettings) { customViewSettings = args.Settings as CustomViewSettings; } } private void OnToolbarItemSelected(object sender, ToolbarItemSelectedEventArgs e) { string text = string.Empty; //e.ToolbarItem.Name; if (text != "back") { if (e.ToolbarItem is FooterToolbarItem) { text = e.ToolbarItem.Text; e.MoveSubItemsToFooterToolbar = true; } else if (e.ToolbarItem is CustomToolbarItem) text = (e.ToolbarItem as CustomToolbarItem).CustomName; else text = e.ToolbarItem.Text; if (text == "Replace") { isReplaced = true; //imageEditor.ToolbarSettings.FooterToolbarHeight = 70; } else if (text == "back") { isReplaced = false; //imageEditor.ToolbarSettings.FooterToolbarHeight = 50; } else if (text == "Add") { isReplaced = false; //imageEditor.ToolbarSettings.FooterToolbarHeight = 70; } if (isReplaced && imageEditor.IsSelected && (text == "Typogy1" || text == "Typogy2" || text == "Typogy3" || text == "Typogy4" || text == "Typogy5" || text == "Typogy6")) { imageEditor.Delete(); AddImage(text); } else if (text == "Typogy1" || text == "Typogy2" || text == "Typogy3" || text == "Typogy4" || text == "Typogy5" || text == "Typogy6") AddImage(text); if (text == "Bring Front") imageEditor.BringToFront(); else if (text == "Send Back") imageEditor.SendToBack(); } else { isReplaced = false; } } private void AddImage(string text) { imageName = text; CustomWebView webView = new CustomWebView() { Frame = new CGRect(0, 0, 150, 150), }; var path = NSBundle.MainBundle.PathForResource("Images/ImageEditor/" + imageName, "svg"); var url = new NSUrl(path); var urlreq = new NSUrlRequest(url); webView.LoadRequest(urlreq); if (isReplaced) { if(customViewSettings!=null) imageEditor.AddCustomView(webView, new CustomViewSettings() { Bounds = customViewSettings.Bounds }); } else { imageEditor.AddCustomView(webView, new CustomViewSettings() { }); } } internal static UIViewController GetVisibleViewController() { var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController; if (rootController.PresentedViewController == null) return rootController; if (rootController.PresentedViewController is UINavigationController) { return ((UINavigationController)rootController.PresentedViewController).TopViewController; } if (rootController.PresentedViewController is UITabBarController) { return ((UITabBarController)rootController.PresentedViewController).SelectedViewController; } return rootController.PresentedViewController; } } public class CustomWebView : UIWebView { public CustomWebView() { BackgroundColor = UIColor.Clear; Opaque = false; UserInteractionEnabled = false; ScalesPageToFit = false; } public override CGRect Frame { get { return base.Frame; } set { var tempFrame = base.Frame; base.Frame = value; if (tempFrame != value && value != CGRect.Empty) UpdateScrollViewFrame(); } } void UpdateScrollViewFrame() { if (ScrollView != null) { ScrollView.Frame = new CGRect(0, 0, Frame.Width, Frame.Height); ScrollView.ContentSize = new CGSize(Frame.Width, Frame.Height); if (ScrollView.Subviews.Length > 0) { ScrollView.Subviews[0].Frame = new CGRect(0, 0, Frame.Width, Frame.Height); } } } } public class CustomToolbarItem : ToolbarItem { public string CustomName { get; set; } public CustomToolbarItem() { } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Diagram/Connectors.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Syncfusion.SfDiagram.iOS; using UIKit; namespace SampleBrowser { public class Connectors : SampleView { SfDiagram diagram = new SfDiagram(); UIPickerView selectionPicker1; UILabel connectorStyle; UIButton connectorStyleButton = new UIButton(); UILabel connectorSize; UIButton doneButton = new UIButton(); UIView HeaderBar = new UIView(); UIButton straight; UIButton curve; UIButton ortho; UIButton plus; UIButton minus; UILabel sizeindicator; UIImageView plusimg; UIImageView minusimg; public Connectors() { HeaderBar.BackgroundColor = UIColor.FromRGB(245, 245, 245); var label = new UILabel(); label.Text = "Connector Types: "; label.TextColor = UIColor.Black; label.BackgroundColor = UIColor.Clear; label.TextAlignment = UITextAlignment.Center; label.Frame = new CGRect(20, 0, 180, 60); HeaderBar.AddSubview(label); straight = AddButton(220, "Images/Diagram/CSStraight.png"); straight.TouchUpInside+= Straight_TouchUpInside; HeaderBar.AddSubview(straight); curve = AddButton(280, "Images/Diagram/CSCurve.png"); curve.TouchUpInside += Curve_TouchUpInside;; HeaderBar.AddSubview(curve); ortho = AddButton(340, "Images/Diagram/CSOrtho.png"); ortho.TouchUpInside += Ortho_TouchUpInside; ortho.BackgroundColor = UIColor.FromRGB(30, 144, 255); HeaderBar.AddSubview(ortho); selectionPicker1 = new UIPickerView(); this.OptionView = new UIView(); PickerModel model = new PickerModel(verticalOrientationlist); selectionPicker1.Model = model; connectorStyle = new UILabel(); connectorStyle.Text = "Connector Style"; connectorStyle.TextColor = UIColor.Black; connectorStyle.TextAlignment = UITextAlignment.Left; connectorSize = new UILabel(); connectorSize.Text = "Connector Size"; connectorSize.TextColor = UIColor.Black; connectorSize.TextAlignment = UITextAlignment.Left; //Represent the vertical button connectorStyleButton = new UIButton(); connectorStyleButton.SetTitle("Default", UIControlState.Normal); connectorStyleButton.SetTitleColor(UIColor.Black, UIControlState.Normal); connectorStyleButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; connectorStyleButton.Layer.CornerRadius = 8; connectorStyleButton.Layer.BorderWidth = 2; connectorStyleButton.TouchUpInside += ShowPicker1; connectorStyleButton.BackgroundColor = UIColor.LightGray; connectorStyleButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; plus = new UIButton(); plus.BackgroundColor = UIColor.White; plus.Layer.CornerRadius = 8; plus.Layer.BorderWidth = 0.5f; plus.TouchUpInside+= Plus_TouchUpInside; plusimg = new UIImageView(); plusimg.Image = UIImage.FromBundle("Images/Diagram/CSplus.png"); plus.AddSubview(plusimg); minus = new UIButton(); minus.BackgroundColor = UIColor.White; minus.Layer.CornerRadius = 8; minus.Layer.BorderWidth = 0.5f; minus.TouchUpInside += Minus_TouchUpInside; minusimg = new UIImageView(); minusimg.Image = UIImage.FromBundle("Images/Diagram/CSsub.png"); minus.AddSubview(minusimg); sizeindicator =new UILabel(); sizeindicator.Text = width.ToString(); sizeindicator.BackgroundColor = UIColor.Clear; sizeindicator.TextColor = UIColor.Black; sizeindicator.TextAlignment = UITextAlignment.Center; //Represent the button doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.TouchUpInside += HidePicker; doneButton.Hidden = true; doneButton.BackgroundColor = UIColor.FromRGB(246, 246, 246); selectionPicker1.ShowSelectionIndicator = true; selectionPicker1.Hidden = true; Node node1 = new Node(); Node node2 = new Node(); Node node3 = new Node(); Node node4 = new Node(); Node node5 = new Node(); Node node6 = new Node(); Node node7 = new Node(); Node node8 = new Node(); Node node9 = new Node(); Node node10 = new Node(); Node node11 = new Node(); diagram.IsReadOnly = true; node1 = AddNode(456, 180, "CEO", UIColor.FromRGB(201, 32, 61)); node2 = AddNode(286, 396, "Manager", UIColor.FromRGB(23, 132, 206)); node3 = AddNode(646, 396, "Manager", UIColor.FromRGB(23, 132, 206)); node4 = AddNode(204, 612, "Team Lead", UIColor.FromRGB(4, 142, 135)); node5 = AddNode(384, 612, "Team Lead", UIColor.FromRGB(4, 142, 135)); node6 = AddNode(564, 612, "Team Lead", UIColor.FromRGB(4, 142, 135)); node7 = AddNode(744, 612, "Team Lead", UIColor.FromRGB(4, 142, 135)); node8 = AddNode(108, 828, "Trainee", UIColor.FromRGB(206, 98, 9)); node9 = AddNode(324, 828, "Trainee", UIColor.FromRGB(206, 98, 9)); node10 = AddNode(648, 828, "Trainee", UIColor.FromRGB(206, 98, 9)); node11 = AddNode(864, 828, "Trainee", UIColor.FromRGB(206, 98, 9)); diagram.AddNode(node1); diagram.AddNode(node2); diagram.AddNode(node3); diagram.AddNode(node4); diagram.AddNode(node5); diagram.AddNode(node6); diagram.AddNode(node7); diagram.AddNode(node8); diagram.AddNode(node9); diagram.AddNode(node10); diagram.AddNode(node11); diagram.AddConnector(AddConnector(node1, node2)); diagram.AddConnector(AddConnector(node1, node3)); diagram.AddConnector(AddConnector(node2, node4)); diagram.AddConnector(AddConnector(node2, node5)); diagram.AddConnector(AddConnector(node3, node6)); diagram.AddConnector(AddConnector(node3, node7)); diagram.AddConnector(AddConnector(node4, node8)); diagram.AddConnector(AddConnector(node4, node9)); diagram.AddConnector(AddConnector(node7, node10)); diagram.AddConnector(AddConnector(node7, node11)); diagram.Loaded += Diagram_Loaded; this.AddSubview(diagram); HeaderBar.Frame = new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, 60); this.AddSubview(HeaderBar); model.PickerChanged += SelectedIndexChanged; } int width = 1; void Plus_TouchUpInside(object sender, EventArgs e) { if (width < 5) { width = (int)diagram.Connectors[0].Style.StrokeWidth + 1; sizeindicator.Text = width.ToString(); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeWidth += 1; } } void Minus_TouchUpInside(object sender, EventArgs e) { if (width > 1) { width = (int)diagram.Connectors[0].Style.StrokeWidth - 1; sizeindicator.Text = width.ToString(); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeWidth -= 1; } } void HidePicker(object sender, EventArgs e) { doneButton.Hidden = true; selectionPicker1.Hidden = true; } private void SelectedIndexChanged(object sender, PickerChangedEventArgs e) { //this.selectedType = selectedorientation + e.SelectedValue; if(e.SelectedValue=="Default") { for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeStyle = StrokeStyle.Default; } else if (e.SelectedValue == "Dashed") { for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeStyle = StrokeStyle.Dashed; } else if (e.SelectedValue == "Dotted") { for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].Style.StrokeStyle = StrokeStyle.Dotted; } } public override void LayoutSubviews() { base.LayoutSubviews(); foreach (var view in this.Subviews) { connectorStyle.Frame = new CGRect(this.Frame.X + 10, 0, PopoverSize.Width - 20, 30); connectorStyleButton.Frame = new CGRect(this.Frame.X + 10, 40, PopoverSize.Width - 20, 30); connectorSize.Frame = new CGRect(this.Frame.X + 10, 80, PopoverSize.Width - 20, 30); plus.Frame = new CGRect(this.Frame.X + 60, 120, 30, 30); plusimg.Frame = new CGRect(0,0, 30, 30); minus.Frame = new CGRect(this.Frame.X + 160, 120, 30, 30); minusimg.Frame = new CGRect(0, 0, 30, 30); sizeindicator.Frame = new CGRect(this.Frame.X + 110, 120, 30, 30); selectionPicker1.Frame = new CGRect(0, PopoverSize.Height / 2, PopoverSize.Width, PopoverSize.Height / 3); doneButton.Frame = new CGRect(0, PopoverSize.Height / 2.5, PopoverSize.Width, 40); } optionView(); } public void optionView() { this.OptionView.AddSubview(connectorStyle); this.OptionView.AddSubview(connectorStyleButton); this.OptionView.AddSubview(connectorSize); this.OptionView.AddSubview(plus); this.OptionView.AddSubview(minus); this.OptionView.AddSubview(sizeindicator); this.OptionView.AddSubview(selectionPicker1); this.OptionView.AddSubview(doneButton); } private void ShowPicker1(object sender, EventArgs e) { (sender as UIButton).BackgroundColor = UIColor.LightGray; doneButton.Hidden = false; selectionPicker1.Hidden = false; } private UIButton AddButton(int v1, string v2) { UIButton straight = new UIButton(); straight.BackgroundColor = UIColor.White; straight.TouchUpInside += Straight_TouchUpInside; straight.Frame = new CGRect(v1, 10, 40, 40); straight.Layer.CornerRadius = 20; straight.Layer.BorderColor = UIColor.Black.CGColor; straight.Layer.BorderWidth = 1.5f; UIImageView img = new UIImageView(); img.Frame = new CGRect(10, 10, 20, 20); img.BackgroundColor = UIColor.Clear; img.Image = UIImage.FromBundle(v2); straight.AddSubview(img); return straight; } private readonly IList<string> verticalOrientationlist = new List<string> { "Default", "Dashed", "Dotted" }; private Connector AddConnector(Port port1, Port port2) { var c1 = new Connector(); c1.SourcePort = port1; c1.TargetPort = port2; c1.Style.StrokeWidth = 1; c1.Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(127, 132, 133)); c1.TargetDecoratorType = DecoratorType.None; return c1; } private void Diagram_Loaded(object sender) { diagram.BringToView(diagram.Nodes[0]); } private Connector AddConnector(Node sourceNode, Node targetNode) { var c1 = new Connector(); c1.SourceNode = sourceNode; c1.TargetNode = targetNode; c1.Style.StrokeWidth = 1 ; c1.Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(127, 132, 133)); c1.TargetDecoratorType = DecoratorType.None; return c1; } Node AddNode(int x, int y, string text, UIColor nodeColor) { Node node = new Node(); node = new Node(x, y, 144, 108); node.ShapeType = ShapeType.RoundedRectangle; node.Style.StrokeWidth = 1; node.Style.Brush = new SolidBrush(nodeColor); node.Style.StrokeBrush = new SolidBrush(UIColor.FromRGB(127, 132, 133)); node.Annotations.Add(new Annotation() { Content = text, FontSize = 15, TextBrush = new SolidBrush(UIColor.White) }); return node; } void Straight_TouchUpInside(object sender, EventArgs e) { (sender as UIButton).BackgroundColor = UIColor.FromRGB(30, 144, 255); ((sender as UIButton).Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSStraight1"); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].SegmentType = SegmentType.StraightSegment; curve.BackgroundColor = UIColor.White; ortho.BackgroundColor = UIColor.White; (curve.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSCurve"); (ortho.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSOrtho"); } void Ortho_TouchUpInside(object sender, EventArgs e) { (sender as UIButton).BackgroundColor = UIColor.FromRGB(30, 144, 255); ((sender as UIButton).Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSOrtho1"); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].SegmentType = SegmentType.OrthoSegment; curve.BackgroundColor = UIColor.White; (curve.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSCurve"); straight.BackgroundColor = UIColor.White; (straight.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSStraight"); } void Curve_TouchUpInside(object sender, EventArgs e) { (sender as UIButton).BackgroundColor = UIColor.FromRGB(30, 144, 255); ((sender as UIButton).Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSCurve1"); for (int i = 0; i < diagram.Connectors.Count; i++) diagram.Connectors[i].SegmentType = SegmentType.CurveSegment; straight.BackgroundColor = UIColor.White; ortho.BackgroundColor = UIColor.White; (ortho.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSOrtho"); (straight.Subviews[0] as UIImageView).Image = UIImage.FromBundle("Images/Diagram/CSStraight"); } } }<file_sep>/Forms/Maps/Maps.UWP/NetConnection_UWP.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.SfMaps.UWP; using System.Threading.Tasks; using Windows.Networking.Connectivity; [assembly: Xamarin.Forms.Dependency(typeof(NetConnection_UWP))] namespace SampleBrowser.SfMaps.UWP { public class NetConnection_UWP : OSMINetwork { public bool IsConnected { get; set; } public async Task CheckNetworkConnection() { var connectionProfile = NetworkInformation.GetInternetConnectionProfile(); if (connectionProfile != null && connectionProfile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess) { IsConnected = true; } else IsConnected = false; await Task.Delay(10); } } } <file_sep>/iOS/SampleBrowser/Utility/AllControlsViewCell.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Foundation; using UIKit; using CoreGraphics; namespace SampleBrowser { public class AllControlsViewCell : UITableViewCell { #region fields public static NSString Key { get; set; } = new NSString("AllControlsViewCell"); #endregion #region ctor public AllControlsViewCell() : base(UITableViewCellStyle.Value1, Key) { } #endregion #region methods public override void LayoutSubviews() { base.LayoutSubviews(); this.DetailTextLabel.Frame = new CGRect( this.DetailTextLabel.Frame.X - 20, this.DetailTextLabel.Frame.Y - 5, this.DetailTextLabel.Frame.Width + 20, this.DetailTextLabel.Frame.Height + 10); this.DetailTextLabel.TextColor = UIColor.White; if (this.DetailTextLabel.Text == "NEW") { this.DetailTextLabel.BackgroundColor = UIColor.FromRGB(30, 199, 192); } else if (this.DetailTextLabel.Text == "UPDATED") { this.DetailTextLabel.BackgroundColor = UIColor.FromRGB(51, 61, 71); } else if (this.DetailTextLabel.Text == "PREVIEW") { this.DetailTextLabel.BackgroundColor = UIColor.FromRGB(255, 180, 0); } this.DetailTextLabel.Layer.CornerRadius = 10; this.DetailTextLabel.ClipsToBounds = true; this.DetailTextLabel.TextAlignment = UITextAlignment.Center; } #endregion } }<file_sep>/Android/SampleBrowser/Samples/RadialMenu/RadialMenuGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023 // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Sfrangeslider; using Syncfusion.SfRadialMenu.Android; namespace SampleBrowser { public class RadialMenuGettingStarted : SamplePage { #region Properties float height, width, density; ScrollView scrollviewer; LinearLayout textFrame; Context con; #endregion string[] fontIcons = new string[] { "\uE800", "\uF0C5", "\uE804", "\uE805", "\uF0CD", "\uF12B", "\uF12C", "\uF0CC", "\uF0C5", "\uE800" }; string[] strings1 = new string[] { "Wifi", "BlueTooth", "Alarm", "Brightness", "Battery", "Power" }; string[] layer = new string[] { "\uE701", "\uE702", "\uEA8F", "\uE706", "\uEBAA", "\uE7E8" }; string[] wifi = new string[] { "\uEC3B", "\uEC3A", "\uEC39", "\uEC38", "\uEC37" }; string[] wifis = new string[] { "High", "Moderate", "Medium", "Low", "\uEC37" }; string[] battery = new string[] { "\uEBB8", "\uEBBC", "\uEBC0" }; string[] batterys = new string[] { "Low", "Medium", "High" }; string[] brightness = new string[] { "\uEC8A", "\uEC8A", "\uE706" }; string[] brightnesss = new string[] { "Low", "Medium", "High" }; string[] profile = new string[] { "\uE7ED", "\uE877", "\uEA8F" }; string[] profiles = new string[] { "Silent", "Vibrate", "Loud" }; string[] power = new string[] { "\uE708", "\uE777", "\uE7E8" }; string[] powers = new string[] { "Sleep", "Restart", "PowerOff" }; TextView text; LinearLayout mainLayout; SfRadialMenu radialMenu; public override View GetSampleContent(Context context) { height = context.Resources.DisplayMetrics.HeightPixels; width = context.Resources.DisplayMetrics.WidthPixels; con = context; density = con.Resources.DisplayMetrics.Density; ImageView image = new ImageView(context); image.SetImageResource(Resource.Drawable.Font); FrameLayout frame = new FrameLayout(context); frame.LayoutParameters = new Android.Views.ViewGroup.LayoutParams(400, 400); mainLayout = new LinearLayout(con); mainLayout.Orientation = Android.Widget.Orientation.Vertical; mainLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); FrameLayout radialFrame = new FrameLayout(con); radialFrame.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(height * 0.60)); radialMenu = new SfRadialMenu(con); ///radialMenu.MenuIcon = image; ImageView back = new ImageView(con); back.SetImageResource(Resource.Drawable.Previous); //radialMenu.BackIcon = back; radialMenu.RimColor = Color.LightGray; radialMenu.OuterRimColor = Color.Transparent; Typeface tf = Typeface.CreateFromAsset(con.Assets, "Segoe_MDL2_Assets.ttf"); for (int i = 0; i < 6; i++) { SfRadialMenuItem item = new SfRadialMenuItem(con) { IconFont = tf, FontIconSize = 20, FontIconText = layer[i], FontIconColor = Color.Black, ItemWidth = 45, ItemHeight = 45 }; item.ItemTapped += Item_ItemTapped; radialMenu.Items.Add(item); } for (int i = 0; i < 4; i++) { SfRadialMenuItem item = new SfRadialMenuItem(con) { IconFont = tf, FontIconSize = 20, FontIconText = wifi[i], FontIconColor = Color.Black }; item.ItemTapped += Item_ItemTapped; (radialMenu.Items[0] as SfRadialMenuItem).Items.Add(item); } for (int i = 0; i < 4; i++) { SfRadialMenuItem item = new SfRadialMenuItem(con) { IconFont = tf, FontIconSize = 20, FontIconText = wifi[i], FontIconColor = Color.Black }; item.ItemTapped += Item_ItemTapped; (radialMenu.Items[1] as SfRadialMenuItem).Items.Add(item); } for (int i = 0; i < 3; i++) { SfRadialMenuItem item = new SfRadialMenuItem(con) { IconFont = tf, FontIconSize = 20, FontIconText = profile[i], FontIconColor = Color.Black }; item.ItemTapped += Item_ItemTapped; (radialMenu.Items[2] as SfRadialMenuItem).Items.Add(item); } for (int i = 0; i < 3; i++) { SfRadialMenuItem item = new SfRadialMenuItem(con) { IconFont = tf, FontIconSize = 20, FontIconText = brightness[i], FontIconColor = Color.Black }; item.ItemTapped += Item_ItemTapped; (radialMenu.Items[3] as SfRadialMenuItem).Items.Add(item); } for (int i = 0; i < 3; i++) { SfRadialMenuItem item = new SfRadialMenuItem(con) { IconFont = tf, FontIconSize = 20, FontIconText = battery[i], FontIconColor = Color.Black, ItemWidth = 45, ItemHeight = 45 }; item.ItemTapped += Item_ItemTapped; (radialMenu.Items[4] as SfRadialMenuItem).Items.Add(item); } for (int i = 0; i < 3; i++) { SfRadialMenuItem item = new SfRadialMenuItem(con) { IconFont = tf, FontIconSize = 20, FontIconText = power[i], FontIconColor = Color.Black, ItemWidth = 45, ItemHeight = 45 }; item.ItemTapped += Item_ItemTapped; (radialMenu.Items[5] as SfRadialMenuItem).Items.Add(item); } radialMenu.RimRadius = radialRadius; radialMenu.CenterButtonRadius = 30; radialMenu.Opening += RadialMenu_Opening; radialMenu.Opened += RadialMenu_Opened; radialMenu.Closing += RadialMenu_Closing; radialMenu.Closed += RadialMenu_Closed; radialMenu.Navigating += RadialMenu_Navigating; radialMenu.Navigated += RadialMenu_Navigated; radialMenu.CenterButtonBackTapped += RadialMenu_CenterButtonBackTapped; radialFrame.AddView(radialMenu); mainLayout.AddView(radialFrame); scrollviewer = new ScrollView(con); textFrame = new LinearLayout(con); TextView menuIcon = new TextView(con); menuIcon.LayoutParameters= new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); menuIcon.Text = "\uE713"; menuIcon.Typeface = tf; menuIcon.TextSize = 30; menuIcon.SetTextColor(Color.White); menuIcon.Gravity = GravityFlags.Center; radialMenu.CenterButtonView = menuIcon; TextView backIcon = new TextView(con); backIcon.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); backIcon.Text = "\uE72B"; backIcon.TextSize = 25; backIcon.Typeface = tf; backIcon.SetTextColor(Color.White); backIcon.Gravity = GravityFlags.Center; radialMenu.CenterButtonBackIcon = backIcon; TextView textview = new TextView(con); textview.Text = "Event Log"; textview.Typeface = tf; textview.SetTextColor(Color.Black); textview.TextSize = 20; if(density>2) textview.SetPadding(20, 0, 0, 20); else textview.SetPadding(10, 0, 0, 10); mainLayout.AddView(textview); textFrame.Orientation = Android.Widget.Orientation.Vertical; textFrame.SetScrollContainer(true); scrollviewer.AddView(textFrame); scrollviewer.VerticalScrollBarEnabled = true; FrameLayout bottomFrame = new FrameLayout(con); bottomFrame.SetScrollContainer(true); bottomFrame.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, (int)(height * 0.40)); bottomFrame.SetBackgroundColor(Color.Silver); bottomFrame.AddView(scrollviewer); bottomFrame.SetPadding(10, 0, 10, 0); mainLayout.AddView(bottomFrame); mainLayout.SetBackgroundColor(Color.White); radialMenu.EnableRotation = rotate; radialMenu.IsDragEnabled = drag; return mainLayout; } void RadialMenu_Opening(object sender, OpeningEventArgs e) { if (textFrame.ChildCount == 10) textFrame.RemoveView(textFrame.GetChildAt(10)); text = new TextView(con); text.SetTextColor(Color.Black); textFrame.AddView(text,0); text.Text = "RadialMenu is Opening"; scrollviewer.ScrollTo(textFrame.Bottom, 0); } void RadialMenu_Opened(object sender, OpenedEventArgs e) { if (textFrame.ChildCount == 10) textFrame.RemoveView(textFrame.GetChildAt(10)); text = new TextView(con); text.SetTextColor(Color.Black); textFrame.AddView(text,0); text.Text = "RadialMenu is Opened"; scrollviewer.ScrollTo(textFrame.Bottom, 0); } void RadialMenu_Closing(object sender, ClosingEventArgs e) { if (textFrame.ChildCount == 10) textFrame.RemoveView(textFrame.GetChildAt(10)); text = new TextView(con); text.SetTextColor(Color.Black); textFrame.AddView(text,0); text.Text = "RadialMenu is Closing"; scrollviewer.ScrollTo(textFrame.Bottom, 0); } void RadialMenu_Closed(object sender, ClosedEventArgs e) { if (textFrame.ChildCount == 10) textFrame.RemoveView(textFrame.GetChildAt(10)); text = new TextView(con); text.SetTextColor(Color.Black); textFrame.AddView(text,0); text.Text = "RadialMenu is Closed"; scrollviewer.ScrollTo(textFrame.Bottom, 0); } void RadialMenu_Navigating(object sender, NavigatingEventArgs e) { if (textFrame.ChildCount == 10) textFrame.RemoveView(textFrame.GetChildAt(10)); text = new TextView(con); text.SetTextColor(Color.Black); textFrame.AddView(text,0); text.Text = "RadialMenu is Navigating"; scrollviewer.ScrollTo(textFrame.Bottom, 0); } void RadialMenu_Navigated(object sender, NavigatedEventArgs e) { if (textFrame.ChildCount == 10) textFrame.RemoveView(textFrame.GetChildAt(10)); text = new TextView(con); text.SetTextColor(Color.Black); textFrame.AddView(text,0); text.Text = "RadialMenu is Navigated"; scrollviewer.ScrollTo(textFrame.Bottom, 0); } void RadialMenu_CenterButtonBackTapped(object sender, CenterButtonBackTappedEventArgs e) { if (textFrame.ChildCount == 10) textFrame.RemoveView(textFrame.GetChildAt(10)); text = new TextView(con); text.SetTextColor(Color.Black); textFrame.AddView(text,0); text.Text = "RadialMenu CenterButtonBack is Tapped"; scrollviewer.ScrollTo(textFrame.Bottom, 0); } void Item_ItemTapped(object sender, RadialMenuItemTappedEventArgs e) { if (textFrame.ChildCount == 10) textFrame.RemoveView(textFrame.GetChildAt(10)); text = new TextView(con); text.SetTextColor(Color.Black); textFrame.AddView(text,0); text.Text = "RadialMenu Item is Tapped"; scrollviewer.ScrollTo(textFrame.Bottom,0); } TextView enableRotation; LinearLayout propertylayout, stackView3, stackView4; public override View GetPropertyWindowLayout(Context context) { propertylayout = new LinearLayout(context); propertylayout.Orientation = Android.Widget.Orientation.Vertical; width = context.Resources.DisplayMetrics.WidthPixels / 2; TextView textView = new TextView(context); textView.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); textView.Text = "Rim Radius"; if (IsTabletDevice(context)) textView.SetPadding(3, 0, 0, 0); textView.TextSize = 16; propertylayout.AddView(textView); SfRangeSlider seekBar = new SfRangeSlider(context); seekBar.Minimum = 100; seekBar.Maximum = 200; seekBar.Value = 100; seekBar.ShowRange = false; seekBar.ShowValueLabel = false; seekBar.TickPlacement = TickPlacement.None; seekBar.ToolTipPlacement = ToolTipPlacement.None; seekBar.ValueChanged += SeekBar_ValueChanged; seekBar.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, 200); propertylayout.AddView(seekBar); SnapsToLayout(context); ShowLabelLayout(context); return propertylayout; } int radialRadius = 100; void SeekBar_ValueChanged(object sender, ValueChangedEventArgs e) { radialRadius = (int)e.Value; } bool rotate = true; bool drag = true; private void SnapsToLayout(Context context) { enableRotation = new TextView(context); enableRotation.Text = " " + "Enable Rotation"; enableRotation.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); enableRotation.Gravity = GravityFlags.Center; enableRotation.TextSize = 16; Switch checkBox2 = new Switch(context); checkBox2.Checked = true; checkBox2.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { rotate = e.IsChecked; }; //layoutParams LinearLayout.LayoutParams layoutParams5 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams5.SetMargins(0, 20, 0, 0); LinearLayout.LayoutParams layoutParams6 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, 55); layoutParams6.SetMargins(0, 20, 0, 0); //stackView stackView4 = new LinearLayout(context); stackView4.AddView(enableRotation); stackView4.AddView(checkBox2, layoutParams5); stackView4.Orientation = Android.Widget.Orientation.Horizontal; propertylayout.AddView(stackView4); SeparatorView separate4 = new SeparatorView(context, width * 2); separate4.LayoutParameters = new ViewGroup.LayoutParams((int)(width * 2), 5); LinearLayout.LayoutParams layoutParams8 = new LinearLayout.LayoutParams((int)(width * 2), 5); if (IsTabletDevice(context)) layoutParams8.SetMargins(0, 30, 0, 200); else layoutParams8.SetMargins(0, 30, 0, 0); propertylayout.AddView(separate4, layoutParams8); } public static bool IsTabletDevice(Android.Content.Context context) { try { DisplayMetrics displayMetrics = context.Resources.DisplayMetrics; float screenWidth = displayMetrics.WidthPixels / displayMetrics.Xdpi; float screenHeight = displayMetrics.HeightPixels / displayMetrics.Ydpi; double size = Math.Sqrt(Math.Pow(screenWidth, 2) + Math.Pow(screenHeight, 2)); return size >= 6; } catch { return false; } } private void ShowLabelLayout(Context context) { //showLabel TextView showLabel = new TextView(context); showLabel.Text = " " + "Enable Dragging"; showLabel.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); showLabel.Gravity = GravityFlags.Center; showLabel.TextSize = 16; //checkBox Switch checkBox = new Switch(context); checkBox.Checked = true; checkBox.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { drag = e.IsChecked; }; //layoutParams LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams3.SetMargins(0, 10, 0, 0); LinearLayout.LayoutParams layoutParams4 = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WrapContent, 55); layoutParams4.SetMargins(0, 10, 0, 0); //stackView stackView3 = new LinearLayout(context); stackView3.AddView(showLabel); stackView3.AddView(checkBox, layoutParams3); stackView3.Orientation = Android.Widget.Orientation.Horizontal; propertylayout.AddView(stackView3); SeparatorView separate3 = new SeparatorView(context, width * 2); separate3.LayoutParameters = new ViewGroup.LayoutParams((int)(width * 2), 5); LinearLayout.LayoutParams layoutParams7 = new LinearLayout.LayoutParams((int)(width * 2), 5); layoutParams7.SetMargins(0, 30, 0, 0); propertylayout.AddView(separate3, layoutParams7); } public override void OnApplyChanges() { radialMenu.RimRadius = radialRadius; radialMenu.EnableRotation = rotate; radialMenu.IsDragEnabled = drag; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/Picker/PickerGettingStarted.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using CoreGraphics; using Syncfusion.SfPicker.iOS; using UIKit; namespace SampleBrowser { public class PickerGettingStarted : SampleView { SfPicker pickerControl; List<string> collectionStrings; UITableView table; string[] tableItems; UILabel eventLog; int i = 0; void PickerControl_ValueChanged(object sender, SelectionChangedEventArgs e) { if (i > 99) { i = 0; tableItems = new string[100]; } tableItems[i] = e.NewValue.ToString() + "color has been selected"; table.ReloadData(); i++; } public PickerGettingStarted() { collectionStrings = new List<string>(); collectionStrings.Add("Blue"); collectionStrings.Add("Black"); collectionStrings.Add("Red"); collectionStrings.Add("Pink"); collectionStrings.Add("Orange"); collectionStrings.Add("Magenta"); collectionStrings.Add("Yellow"); collectionStrings.Add("Purple"); collectionStrings.Add("Green"); collectionStrings.Add("Gray"); collectionStrings.Add("LightGray"); collectionStrings.Add("Brown"); pickerControl = new SfPicker(); pickerControl.SelectionChanged += PickerControl_ValueChanged; pickerControl.ItemsSource = collectionStrings; this.Add(pickerControl); eventLog = new UILabel(); eventLog.Lines = 0; eventLog.Text = "Event Log :"; eventLog.BackgroundColor = UIColor.White; eventLog.LineBreakMode = UILineBreakMode.WordWrap; table = new UITableView(this.Bounds); // defaults to Plain style tableItems = new string[100]; Add(eventLog); table.Source = new TableSourceCollection(tableItems); Add(table); } public override void LayoutSubviews() { foreach (var view in this.Subviews) { pickerControl.Frame = new CGRect(20, 30, this.Frame.Size.Width-40, 200); eventLog.Frame = new CGRect(16, Frame.Height - 250, Frame.Width, 30); table.Frame = new CGRect(0, Frame.Height - 220, Frame.Width - 18, 200); } base.LayoutSubviews(); } } } <file_sep>/Forms/ListView/ListView/Samples/DataTemplateSelector/HelperClass/MessageDataTemplateSelector.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using SampleBrowser.SfListView; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using SampleBrowser.Core; using Xamarin.Forms.Internals; namespace SampleBrowser.SfListView { [Preserve(AllMembers = true)] #region MessageTemplateSelector public class MessageDataTemplateSelector : Xamarin.Forms.DataTemplateSelector { #region Properties public DataTemplate IncomingTextTemplate { get; set; } public DataTemplate OutgoingTextTemplate { get; set; } public DataTemplate IncomingImageTemplate { get; set; } #endregion #region Constructor public MessageDataTemplateSelector() { IncomingTextTemplate = new DataTemplate(typeof(IncomingTextTemplate)); OutgoingTextTemplate = new DataTemplate(typeof(OutgoingTextTemplate)); IncomingImageTemplate = new DataTemplate(typeof(IncomingImageMessageTemplate)); } #endregion #region OnSelectTemplate protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { if (((MessageInfo)item).TemplateType == TemplateType.OutGoingText) return OutgoingTextTemplate; else if (((MessageInfo)item).TemplateType == TemplateType.IncomingText) return IncomingTextTemplate; else return IncomingImageTemplate; } #endregion } #endregion #region CustomContentView [Preserve(AllMembers = true)] public class IncomingCustomContentView : ContentView { } [Preserve(AllMembers = true)] public class OutgoingCustomContentView : ContentView { } #endregion } <file_sep>/Android/SampleBrowser/Samples/Barcode/readme.md Barcode provides a perfect approach to encode texts by using the supported symbol types that comprises one dimensional and two dimensional barcodes. The basic structure of a barcode consists of one or more data characters, optionally one or two check characters, a start pattern as well as a stop pattern. The following samples are available for Barcode control to demonstrate the functionalities of each feature: | Sample | Description | | ------ | ----------- | | [QR Barcode](QRCode.cs) | QR Code is a two dimensional symbology that is used in automotive industry. | | [DataMatrix Barcode](DataMatrix.cs) | DataMatrix symbology is widely used in printed media such as labels and letters. | | [CodaBar Barcode](Codabar.cs) | Codabar is a discrete numeric symbology that is used in libraries and information processing applications. | | [Code11 Barcode](Code11.cs) | Code11 symbology is used mainly for labeling the telecommunications equipment. | | [Upc Barcode](UpcBarcode.cs) | Upc barcode is mainly used for coding pharmaceuticals, cosmetics and dietetics. | | [Code32 Barcode](Code32.cs) | Code32 is mainly used for coding pharmaceuticals, cosmetics and dietetics. | | [Code39 Barcode](Code39.cs) | Code39 is a symbology of Barcode that encodes alphanumeric characters into a series of bars. | | [Code39 Extended Barcode](Code39Extended.cs) | Code39 extended symbology is an extended version of Code39 that supports full ASCII character set. | | [Code93 Barcode](Code93.cs) | Code93 represents the full ASCII character set by using the combination of 2 characters. | | [Code93 Extended Barcode](Code93Extended.cs) | Code93 extended is designed to complement and improve upon Code 39. | | [Code128A Barcode](Code128A.cs) | Code128A includes all the standard upper case alphanumeric characters, punctuation, and special characters. | | [Code128B Barcode](Code128B.cs) | Code128B includes all the standard upper and lower case alphanumeric characters, punctuation and special characters. | | [Code128C Barcode](Code128C.cs) | Code128C includes a set of 100 digit pairs from 00 to 99 inclusive, as well as three special characters. |<file_sep>/Forms/PullToRefresh/PullToRefresh/Samples/PullToRefreshView/Model/WeatherData.cs #region Copyright Syncfusion Inc. 2001-2023. // ------------------------------------------------------------------------------------ // <copyright file = "WeatherData.cs" company="Syncfusion.com"> // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. // </copyright> // ------------------------------------------------------------------------------------ #endregion namespace SampleBrowser.SfPullToRefresh { using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using Xamarin.Forms; using Xamarin.Forms.Internals; [Preserve(AllMembers = true)] /// <summary> /// A class contains Properties and notifies when property value has changed /// </summary> public class WeatherData : INotifyPropertyChanged { [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string id; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string day; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string imageName; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string month; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string selectedType; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private double temperature; [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.Private field does not need documentation")] private string type; /// <summary> /// Initializes a new instance of the WeatherData class. /// </summary> /// <param name="day">string type parameter named as day</param> /// <param name="month">string type parameter named as month</param> /// <param name="temperature">string type parameter named as temperature</param> /// <param name="type">string type parameter named as type</param> /// <param name="selectedType">string type parameter named as selectedType</param> public WeatherData(string day, string month, double temperature, string type, string selectedType) { this.Day = day; this.Month = month; this.Temperature = temperature; this.SelectedType = selectedType; this.Type = type; this.ID = type; } /// <summary> /// Represents the method that will handle the <see cref="E:System.ComponentModel.INotifyPropertyChanged.PropertyChanged"></see> event raised when a property is changed on a component /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the value of Day and notifies user when collection value gets changed. /// </summary> public string Day { get { return this.day; } set { this.day = value; this.RaisePropertyChanged("Day"); } } /// <summary> /// Gets or sets the value of Month and notifies user when collection value gets changed. /// </summary> public string Month { get { return this.month; } set { this.month = value; this.RaisePropertyChanged("Month"); } } /// <summary> /// Gets or sets the value of Temperature and notifies user when collection value gets changed. /// </summary> public double Temperature { get { return this.temperature; } set { this.temperature = value; this.RaisePropertyChanged("Temperature"); } } /// <summary> /// Gets or sets the value of SelectedType and notifies user when collection value gets changed. /// </summary> public string SelectedType { get { return this.selectedType; } set { this.selectedType = value; this.RaisePropertyChanged("SelectedType"); } } /// <summary> /// Gets or sets the value of ID and notifies user when collection value gets changed. /// </summary> public string ID { get { return this.id; } set { this.id = value; this.RaisePropertyChanged("ID"); } } /// <summary> /// Gets or sets the value of Type and notifies user when collection value gets changed. /// </summary> public string Type { get { return this.type; } set { this.type = value; this.ImageName = this.type; } } /// <summary> /// Gets or sets the value of ImageName and notifies user when collection value gets changed. /// </summary> public string ImageName { get { return this.imageName; } set { this.imageName = value; this.RaisePropertyChanged("ImageName"); } } /// <summary> /// Triggers when Items Collections Changed. /// </summary> /// <param name="name">string type parameter named as name</param> private void RaisePropertyChanged(string name) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } } } }<file_sep>/Forms/Schedule/Schedule/Samples/AppointmentEditor/Model/Meeting.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.ObjectModel; using System.ComponentModel; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace SampleBrowser.SfSchedule { /// <summary> /// Meeting class /// </summary> [Preserve(AllMembers = true)] public class Meeting { /// <summary> /// Gets or sets event name /// </summary> public string EventName { get; set; } /// <summary> /// Gets or sets organizer /// </summary> public string Organizer { get; set; } /// <summary> /// Gets or sets contact ID /// </summary> public string ContactID { get; set; } /// <summary> /// Gets or sets capacity /// </summary> public int Capacity { get; set; } /// <summary> /// Gets or sets date /// </summary> public DateTime From { get; set; } /// <summary> /// Gets or sets date /// </summary> public DateTime To { get; set; } /// <summary> /// Gets or sets color /// </summary> public Color Color { get; set; } /// <summary> /// Gets or sets minimum height /// </summary> public double MinimumHeight { get; set; } /// <summary> /// Gets or sets all day /// </summary> public bool IsAllDay { get; set; } /// <summary> /// Gets or sets start time zone /// </summary> public string StartTimeZone { get; set; } /// <summary> /// Gets or sets end time zone /// </summary> public string EndTimeZone { get; set; } public ObservableCollection<object> Resources { get; set; } } public class Employees : INotifyPropertyChanged { private string name; private object id; private Color color; public string Name { get { return name; } set { name = value; this.OnPropertyChanged("Name"); } } public object ID { get { return id; } set { id = value; this.OnPropertyChanged("ID"); } } public Color Color { get { return color; } set { color = value; this.OnPropertyChanged("Color"); } } public string Image { get; set; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }<file_sep>/Android/SampleBrowser/Samples/DocIO/BarChart.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Android.Content; using Android.Views; using Android.Widget; using Android.Graphics; using Syncfusion.DocIO.DLS; using Syncfusion.DocIO; using Syncfusion.Drawing; using Syncfusion.OfficeChart; namespace SampleBrowser { public partial class BarChart : SamplePage { private Context m_context; public override View GetSampleContent (Context con) { LinearLayout linear = new LinearLayout(con); linear.SetBackgroundColor(Android.Graphics.Color.White); linear.Orientation = Orientation.Vertical; linear.SetPadding(10, 10, 10, 10); TextView text1 = new TextView(con); text1.TextSize = 17; text1.TextAlignment = TextAlignment.Center; text1.SetTextColor(Android.Graphics.Color.ParseColor("#262626")); text1.Text = "This sample demonstrates how to create a bar chart in a Word document with the data from an existing Excel file."; text1.SetPadding(5, 5, 5, 5); linear.AddView(text1); TextView space1 = new TextView (con); space1.TextSize = 10; linear.AddView (space1); m_context = con; TextView space2 = new TextView (con); space2.TextSize = 10; linear.AddView (space2); Button button1 = new Button (con); button1.Text = "Generate Word"; button1.Click += OnButtonClicked; linear.AddView (button1); return linear; } private void OnButtonClicked(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly (); //A new document is created. WordDocument document = new WordDocument(); //Add new section to the Word document IWSection section = document.AddSection(); //Set page margins of the section section.PageSetup.Margins.All = 72; //Add new paragraph to the section IWParagraph paragraph = section.AddParagraph(); //Apply heading style to the title paragraph paragraph.ApplyStyle(BuiltinStyle.Heading1); //Apply center alignment to the paragraph paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; //Append text to the paragraph paragraph.AppendText("Northwind Management Report").CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(46, 116, 181); //Add new paragraph paragraph = section.AddParagraph(); //Set before spacing to the paragraph paragraph.ParagraphFormat.BeforeSpacing = 20; //Load the excel template as stream Stream excelStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.DocIO.Templates.Excel_Template.xlsx"); //Create and Append chart to the paragraph with excel stream as parameter WChart barChart = paragraph.AppendChart(excelStream, 1, "B2:C6", 470, 300); //Set chart data barChart.ChartType = OfficeChartType.Bar_Clustered; barChart.ChartTitle = "Purchase Details"; barChart.ChartTitleArea.FontName = "Calibri (Body)"; barChart.ChartTitleArea.Size = 14; //Set name to chart series barChart.Series[0].Name = "Sum of Purchases"; barChart.Series[1].Name = "Sum of Future Expenses"; //Set Chart Data table barChart.HasDataTable = true; barChart.DataTable.HasBorders = true; barChart.DataTable.HasHorzBorder = true; barChart.DataTable.HasVertBorder = true; barChart.DataTable.ShowSeriesKeys = true; barChart.HasLegend = false; //Setting background color barChart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(208, 206, 206); barChart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(208, 206, 206); //Setting line pattern to the chart area barChart.PrimaryCategoryAxis.Border.LinePattern = OfficeChartLinePattern.None; barChart.PrimaryValueAxis.Border.LinePattern = OfficeChartLinePattern.None; barChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None; barChart.PrimaryValueAxis.MajorGridLines.Border.LineColor = Syncfusion.Drawing.Color.FromArgb(175, 171, 171); //Set label for primary catagory axis barChart.PrimaryCategoryAxis.CategoryLabels = barChart.ChartData[2, 1, 6, 1]; #region Saving Document MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Word2013); document.Close(); if (stream != null) { SaveAndroid androidSave = new SaveAndroid (); androidSave.Save ("BarChart.docx", "application/msword", stream, m_context); } #endregion } } }<file_sep>/Forms/PDF/PDF/Samples/RemoveImage/RemoveImage.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Pdf; using System; using System.IO; using Xamarin.Forms; using System.Reflection; using SampleBrowser.Core; using Syncfusion.Pdf.Exporting; using Syncfusion.Pdf.Parsing; namespace SampleBrowser.PDF { public partial class RemoveImage : SampleView { public RemoveImage() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.BackgroundColor = Xamarin.Forms.Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; } } private void ButtonView_Click(object sender, EventArgs e) { #if COMMONSB Stream documentStream = typeof(RemoveImage).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.RemoveImageTemplate.pdf"); #else Stream documentStream = typeof(RemoveImage).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.RemoveImageTemplate.pdf"); #endif MemoryStream stream = new MemoryStream(); documentStream.CopyTo(stream); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("RemoveImageTemplate.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("RemoveImageTemplate.pdf", "application/pdf", stream); } void OnButtonClicked(object sender, EventArgs e) { #if COMMONSB Stream documentStream = typeof(RemoveImage).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.RemoveImageTemplate.pdf"); #else Stream documentStream = typeof(RemoveImage).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.RemoveImageTemplate.pdf"); #endif //Load the PDF document from stream. PdfLoadedDocument document = new PdfLoadedDocument(documentStream); //Load the first page. PdfPageBase page = document.Pages[0]; //Extract images from the first page. PdfImageInfo[] imageInfo = page.GetImagesInfo(); //Remove the Image. page.RemoveImage(imageInfo[0]); MemoryStream stream = new MemoryStream(); //Saves the PDF to the memory stream. document.Save(stream); //Close the PDF document document.Close(true); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("RemoveImage.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("RemoveImage.pdf", "application/pdf", stream); } } } <file_sep>/Forms/Maps/Maps/Samples/Drilldown/DrilldownModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Text; namespace SampleBrowser.SfMaps { public class DrilldownModel { public DrilldownModel(string contry, string con) { this.Country = contry; this.Continent = con; } public string Continent { get; set; } public string Country { get; set; } } } <file_sep>/Forms/PdfViewer/PdfViewer/Samples/Helper/PopupIconConverter.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.SfPdfViewer.XForms; using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Xamarin.Forms; namespace SampleBrowser.SfPdfViewer { internal class PopupIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is PopupIcon icon) { switch (icon) { case PopupIcon.Comment: return FontMappingHelper.Comment; case PopupIcon.Note: return FontMappingHelper.Note; case PopupIcon.Help: return FontMappingHelper.Help; case PopupIcon.Key: return FontMappingHelper.Key; case PopupIcon.Paragraph: return FontMappingHelper.Paragraph; case PopupIcon.NewParagraph: return FontMappingHelper.NewParagraph; case PopupIcon.Insert: return FontMappingHelper.Insert; } } return null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } } <file_sep>/Forms/Chart/Chart/Samples/BubbleChart/BubbleSeriesViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System.Collections.ObjectModel; namespace SampleBrowser.SfChart { public class BubbleSeriesViewModel { public ObservableCollection<ChartDataModel> BubbleData { get; set; } public BubbleSeriesViewModel() { BubbleData = new ObservableCollection<ChartDataModel> { new ChartDataModel(92.2, 7.8, 1.347, "China"), new ChartDataModel(74, 6.5, 1.241, "India"), new ChartDataModel(90.4, 6.0, 0.238, "Indonesia"), new ChartDataModel(99.4, 2.2, 0.312, "US"), new ChartDataModel(88.6, 1.3, 0.197, "Brazil"), new ChartDataModel(99, 0.7, 0.0818, "Germany"), new ChartDataModel(72, 2.0, 0.0826, "Egypt"), new ChartDataModel(99.6, 3.4, 0.143, "Russia"), new ChartDataModel(99, 0.2, 0.128, "Japan"), new ChartDataModel(86.1, 4.0, 0.115, "Mexico"), new ChartDataModel(92.6, 6.6, 0.096, "Philippines"), new ChartDataModel(61.3, 1.45, 0.162, "Nigeria"), new ChartDataModel(82.2, 3.97, 0.7, "Hong Kong"), new ChartDataModel(79.2, 3.9,0.162, "Netherland"), new ChartDataModel(72.5, 4.5,0.7, "Jordan"), new ChartDataModel(81, 3.5, 0.21, "Australia"), new ChartDataModel(66.8, 3.9, 0.028, "Mongolia"), new ChartDataModel(79.2, 2.9, 0.231, "Taiwan"), }; } } }<file_sep>/iOS/SampleBrowser/Samples/MaskedEdit/MaskedEdit_Mobile.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using Syncfusion.iOS.MaskedEdit; using System.Globalization; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; using nint = System.Int32; using nuint = System.Int32; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace SampleBrowser { public class MaskedEdit_Mobile : SampleView { UIView view; UIButton searchButton = new UIButton(); public UIView option = new UIView(); UILabel visibilityLabel, fundTransferLable, accountLabel, descriptionLabel, amountLabel, emailIDLabel, mobileNumberLabel, inputValidationModeLabel, cultureLabel, hidepromptLabel, promptcharLabel; UILabel accInputRejectLable, amtInputRejectLable, emailInputRejectLable, phoneInputRejectLable; SfMaskedEdit acccountmaskedEdit, descriptionmaskedEdit, amountmaskedEdit, emailIDmaskedEdit, mobileNumbermaskedEdit; private UIPickerView visibilityPicker, cutCopyPicker, promptPicker, culturePicker; private UIButton visibilityDoneButton, visibilityButton, promptcharButton, validationDoneButton, promptDoneButton, validationButton, cultureDoneButton, cultureButton; private readonly IList<string> cultureList, inputValidationModeList, promptCharList, visibilityList; private string cultureSelectedType, validationSelectedType, promptSelectedType, visibilityType; private UISwitch hidepromptSwitch; UIScrollView scrollView = new UIScrollView(); nfloat accPoint = 0; nfloat amtPoint = 0; nfloat emailPoint = 0; nfloat phonePoint = 0; public override void LayoutSubviews() { foreach (var view in this.Subviews) { view.Frame = new CGRect(Frame.Location.X, 0.0f, Frame.Size.Width, Frame.Size.Height); this.OptionView.Frame = view.Frame; this.option.Frame = new CGRect(0, 20, Frame.Width, Frame.Height); scrollView.Frame = new CGRect(Frame.Location.X, 0.0f, Frame.Width, Frame.Height); scrollView.ContentSize = new CGSize(scrollView.Frame.Width, scrollView.Frame.Height + 255); fundTransferLable.Frame = new CGRect(10, 0, this.Frame.Size.Width - 20, 40); accountLabel.Frame = new CGRect(10, 30, this.Frame.Size.Width - 20, 40); acccountmaskedEdit.Frame = new CGRect(10, 65, this.Frame.Size.Width - 20, 40); accInputRejectLable.Frame = new CGRect(10, 105, this.Frame.Size.Width - 20, 20); descriptionLabel.Frame = new CGRect(10, 105 + accPoint, view.Frame.Width - 10, 40); descriptionmaskedEdit.Frame = new CGRect(10, 140 + accPoint, view.Frame.Width - 20, 40); amountLabel.Frame = new CGRect(10, 180 + accPoint, view.Frame.Width - 20, 40); amountmaskedEdit.Frame = new CGRect(10, 215 + accPoint, view.Frame.Width - 20, 40); amtInputRejectLable.Frame = new CGRect(10, 255 + accPoint, this.Frame.Size.Width - 20, 20); emailIDLabel.Frame = new CGRect(10, 255 + accPoint + amtPoint, view.Frame.Width - 20, 40); emailIDmaskedEdit.Frame = new CGRect(10, 290 + accPoint + amtPoint, view.Frame.Width - 20, 40); emailInputRejectLable.Frame = new CGRect(10, 330 + accPoint + amtPoint, this.Frame.Size.Width - 20, 20); mobileNumberLabel.Frame = new CGRect(10, 330 + accPoint + amtPoint + emailPoint, view.Frame.Width - 20, 40); mobileNumbermaskedEdit.Frame = new CGRect(10, 365 + accPoint + amtPoint + emailPoint, view.Frame.Width - 20, 40); phoneInputRejectLable.Frame = new CGRect(10, 405 + accPoint + amtPoint + emailPoint, this.Frame.Size.Width - 20, 15); searchButton.Frame = new CGRect(10, 430 + accPoint + amtPoint + emailPoint + phonePoint, this.Frame.Size.Width - 20, 40); inputValidationModeLabel.Frame = new CGRect(10, 20, this.Frame.Size.Width - 10, 30); validationButton.Frame = new CGRect(10, 50, this.Frame.Size.Width - 20, 20); cutCopyPicker.Frame = new CGRect(10, 260, this.Frame.Size.Width, 100); validationDoneButton.Frame = new CGRect(10, 255, this.Frame.Size.Width - 20, 30); cultureLabel.Frame = new CGRect(10, 70, this.Frame.Size.Width - 20, 30); cultureButton.Frame = new CGRect(10, 100, this.Frame.Size.Width - 20, 20); culturePicker.Frame = new CGRect(10, 260, this.Frame.Size.Width, 100); cultureDoneButton.Frame = new CGRect(10, 255, this.Frame.Size.Width - 20, 30); visibilityLabel.Frame = new CGRect(10, 125, this.Frame.Size.Width - 20, 30); visibilityButton.Frame = new CGRect(10, 155, this.Frame.Size.Width - 20, 20); visibilityPicker.Frame = new CGRect(10, 260, this.Frame.Size.Width, 100); visibilityDoneButton.Frame = new CGRect(10, 255, this.Frame.Size.Width - 20, 30); hidepromptLabel.Frame = new CGRect(10, 175, this.Frame.Size.Width - 20, 40); hidepromptSwitch.Frame = new CGRect(250, 180, this.Frame.Size.Width - 20, 15); promptcharLabel.Frame = new CGRect(10, 215, this.Frame.Size.Width - 20, 40); promptcharButton.Frame = new CGRect(200, 220, this.Frame.Size.Width - 215, 30); promptPicker.Frame = new CGRect(10, 260, this.Frame.Size.Width, 100); promptDoneButton.Frame = new CGRect(10, 255, this.Frame.Size.Width - 20, 30); } this.optionView(); base.LayoutSubviews(); } public void optionView() { option.AddSubview(inputValidationModeLabel); option.AddSubview(validationButton); option.AddSubview(cutCopyPicker); option.AddSubview(validationDoneButton); option.AddSubview(cultureLabel); option.AddSubview(cultureButton); option.AddSubview(culturePicker); option.AddSubview(cultureDoneButton); option.AddSubview(visibilityLabel); option.AddSubview(visibilityButton); option.AddSubview(visibilityPicker); option.AddSubview(visibilityDoneButton); option.AddSubview(hidepromptLabel); option.AddSubview(hidepromptSwitch); option.AddSubview(promptcharLabel); option.AddSubview(promptcharButton); option.AddSubview(promptPicker); option.AddSubview(promptDoneButton); } public MaskedEdit_Mobile() { view = new UIView(); this.OptionView = new UIView(); this.cultureList = new List<string>() { (NSString)"United States", (NSString)"United Kingdom", (NSString)"Japan", (NSString)"France", (NSString)"Italy" }; this.inputValidationModeList = new List<string>() { (NSString)"Key Press", (NSString)"Lost Focus" }; this.visibilityList = new List<string> { (NSString)"While Editing", (NSString)"Never", }; this.promptCharList = new List<string>() { "_", "*", "~" }; fundTransferLable = new UILabel(); fundTransferLable.TextColor = UIColor.Black; fundTransferLable.BackgroundColor = UIColor.Clear; fundTransferLable.Text = @"Funds Transfer"; fundTransferLable.TextAlignment = UITextAlignment.Left; fundTransferLable.Font = UIFont.FromName("Helvetica-Bold", 20f); scrollView.AddSubview(fundTransferLable); accountLabel = new UILabel(); accountLabel.Text = "To Account"; accountLabel.TextColor = UIColor.Black; accountLabel.Font = UIFont.FromName("Helvetica", 16f); scrollView.AddSubview(accountLabel); acccountmaskedEdit = new SfMaskedEdit(); acccountmaskedEdit.Mask = "0000 0000 0000 0000"; acccountmaskedEdit.Culture = new CultureInfo("en-us"); acccountmaskedEdit.ClipsToBounds = true; acccountmaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; acccountmaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; acccountmaskedEdit.TextAlignment = UITextAlignment.Left; acccountmaskedEdit.ValidationMode = InputValidationMode.KeyPress; acccountmaskedEdit.MaskInputRejected += AcccountmaskedEdit_MaskInputRejected; acccountmaskedEdit.ValueChanged += AcccountmaskedEdit_ValueChanged; acccountmaskedEdit.Placeholder = "1234 1234 1234 1234"; acccountmaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; scrollView.AddSubview(acccountmaskedEdit); accInputRejectLable = new UILabel(); accInputRejectLable.Font = UIFont.FromName("Helvetica", 12f); accInputRejectLable.TextColor = UIColor.Red; accInputRejectLable.Hidden = true; scrollView.AddSubview(accInputRejectLable); descriptionLabel = new UILabel(); descriptionLabel.Text = "Description"; descriptionLabel.TextColor = UIColor.Black; descriptionLabel.Font = UIFont.FromName("Helvetica", 16f); scrollView.AddSubview(descriptionLabel); descriptionmaskedEdit = new SfMaskedEdit(); descriptionmaskedEdit.Mask = ""; descriptionmaskedEdit.Culture = new CultureInfo("en-us"); descriptionmaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; descriptionmaskedEdit.Placeholder = "Enter description"; descriptionmaskedEdit.TextAlignment = UITextAlignment.Left; descriptionmaskedEdit.ClipsToBounds = true; descriptionmaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; descriptionmaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; scrollView.AddSubview(descriptionmaskedEdit); amountLabel = new UILabel(); amountLabel.Text = "Amount"; amountLabel.TextColor = UIColor.Black; amountLabel.Font = UIFont.FromName("Helvetica", 16f); scrollView.AddSubview(amountLabel); amountmaskedEdit = new SfMaskedEdit(); amountmaskedEdit.Mask = "$ 0,000.00"; amountmaskedEdit.Culture = new CultureInfo("en-us"); amountmaskedEdit.Placeholder = "$ 3,874.00"; amountmaskedEdit.ValueMaskFormat = MaskFormat.IncludeLiterals; amountmaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; amountmaskedEdit.ValidationMode = InputValidationMode.KeyPress; amountmaskedEdit.MaskInputRejected += AmountmaskedEdit_MaskInputRejected; amountmaskedEdit.ValueChanged += AmountmaskedEdit_ValueChanged; amountmaskedEdit.TextAlignment = UITextAlignment.Left; amountmaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; scrollView.AddSubview(amountmaskedEdit); amtInputRejectLable = new UILabel(); amtInputRejectLable.Font = UIFont.FromName("Helvetica", 12f); amtInputRejectLable.TextColor = UIColor.Red; amtInputRejectLable.Hidden = true; scrollView.AddSubview(amtInputRejectLable); emailIDLabel = new UILabel(); emailIDLabel.Text = "Email ID"; emailIDLabel.TextColor = UIColor.Black; emailIDLabel.Font = UIFont.FromName("Helvetica", 16f); scrollView.AddSubview(emailIDLabel); emailIDmaskedEdit = new SfMaskedEdit(); emailIDmaskedEdit.Mask = @"\w+@\w+\.\w+"; emailIDmaskedEdit.Culture = new CultureInfo("en-us"); emailIDmaskedEdit.Placeholder = "<EMAIL>"; emailIDmaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; emailIDmaskedEdit.ValidationMode = InputValidationMode.KeyPress; emailIDmaskedEdit.MaskInputRejected += EmailIDmaskedEdit_MaskInputRejected; emailIDmaskedEdit.ValueChanged += EmailIDmaskedEdit_ValueChanged; emailIDmaskedEdit.MaskType = MaskType.RegEx; emailIDmaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; emailIDmaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; scrollView.AddSubview(emailIDmaskedEdit); emailInputRejectLable = new UILabel(); emailInputRejectLable.Font = UIFont.FromName("Helvetica", 12f); emailInputRejectLable.TextColor = UIColor.Red; emailInputRejectLable.Hidden = true; scrollView.AddSubview(emailInputRejectLable); mobileNumberLabel = new UILabel(); mobileNumberLabel.Text = "Mobile Number"; mobileNumberLabel.TextColor = UIColor.Black; mobileNumberLabel.Font = UIFont.FromName("Helvetica", 16f); scrollView.AddSubview(mobileNumberLabel); mobileNumbermaskedEdit = new SfMaskedEdit(); mobileNumbermaskedEdit.Mask = "+1 000 000 0000"; mobileNumbermaskedEdit.Culture = new CultureInfo("en-us"); mobileNumbermaskedEdit.ClipsToBounds = true; mobileNumbermaskedEdit.ValueMaskFormat = MaskFormat.ExcludePromptAndLiterals; mobileNumbermaskedEdit.Layer.BorderColor = UIColor.LightGray.CGColor; mobileNumbermaskedEdit.ValidationMode = InputValidationMode.KeyPress; mobileNumbermaskedEdit.MaskInputRejected += MobileNumbermaskedEdit_MaskInputRejected; mobileNumbermaskedEdit.ValueChanged += MobileNumbermaskedEdit_ValueChanged; mobileNumbermaskedEdit.Placeholder = "+1 323 339 3392"; mobileNumbermaskedEdit.TextAlignment = UITextAlignment.Left; mobileNumbermaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; scrollView.AddSubview(mobileNumbermaskedEdit); phoneInputRejectLable = new UILabel(); phoneInputRejectLable.Font = UIFont.FromName("Helvetica", 12f); phoneInputRejectLable.TextColor = UIColor.Red; phoneInputRejectLable.Hidden = true; scrollView.AddSubview(phoneInputRejectLable); //searchButtonn searchButton.SetTitle("Transfer Money", UIControlState.Normal); searchButton.SetTitleColor(UIColor.White, UIControlState.Normal); searchButton.BackgroundColor = UIColor.FromRGB(50, 150, 221); searchButton.SetTitleColor(UIColor.Black, UIControlState.Normal); searchButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; searchButton.Layer.CornerRadius = 8; searchButton.Layer.BorderWidth = 2; searchButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; searchButton.TouchUpInside += FoundTransfer; scrollView.AddSubview(searchButton); AddSubview(scrollView); mainPageDesign(); } private void MobileNumbermaskedEdit_ValueChanged(object sender, ValueChangedEventArgs e) { phoneInputRejectLable.Hidden = true; phonePoint = 0; LayoutSubviews(); } private void MobileNumbermaskedEdit_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { phoneInputRejectLable.Hidden = false; phoneInputRejectLable.Text = GetRejectionHintText(e.RejectionHint); if (!string.IsNullOrEmpty(phoneInputRejectLable.Text)) phonePoint = 15; LayoutSubviews(); } private void EmailIDmaskedEdit_ValueChanged(object sender, ValueChangedEventArgs e) { emailInputRejectLable.Hidden = true; emailPoint = 0; LayoutSubviews(); } private void EmailIDmaskedEdit_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { emailInputRejectLable.Hidden = false; emailInputRejectLable.Text = GetRejectionHintText(e.RejectionHint); if (!string.IsNullOrEmpty(emailInputRejectLable.Text)) emailPoint = 15; LayoutSubviews(); } private void AmountmaskedEdit_ValueChanged(object sender, ValueChangedEventArgs e) { amtInputRejectLable.Hidden = true; amtPoint = 0; LayoutSubviews(); } private void AmountmaskedEdit_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { amtInputRejectLable.Hidden = false; amtInputRejectLable.Text = GetRejectionHintText(e.RejectionHint); if (!string.IsNullOrEmpty(amtInputRejectLable.Text)) amtPoint = 15; LayoutSubviews(); } private void AcccountmaskedEdit_ValueChanged(object sender, ValueChangedEventArgs e) { accInputRejectLable.Hidden = true; accPoint = 0; LayoutSubviews(); } private void AcccountmaskedEdit_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { accInputRejectLable.Hidden = false; accInputRejectLable.Text = GetRejectionHintText(e.RejectionHint); if (!string.IsNullOrEmpty(accInputRejectLable.Text)) accPoint = 15; LayoutSubviews(); } private string GetRejectionHintText(MaskedTextResultHint hint) { string hintText = string.Empty; switch (hint) { case MaskedTextResultHint.AlphanumericCharacterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.DigitExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.LetterExpected: hintText = "Invalid character!"; break; case MaskedTextResultHint.SignedDigitExpected: hintText = "Invalid character!"; break; } return hintText; } private void FoundTransfer(object sender, EventArgs e) { if ((acccountmaskedEdit.Value == null || acccountmaskedEdit.Value.ToString() == string.Empty) || (descriptionmaskedEdit.Value == null || descriptionmaskedEdit.Value.ToString() == string.Empty) || (amountmaskedEdit.Value == null || amountmaskedEdit.Value.ToString() == string.Empty) || (emailIDmaskedEdit.Value == null || emailIDmaskedEdit.Value.ToString() == string.Empty) || (mobileNumbermaskedEdit.Value == null || mobileNumbermaskedEdit.Value.ToString() == string.Empty)) { UIAlertView v = new UIAlertView(); v.Title = "Results"; v.Message = "Please fill all the required data!"; v.AddButton("OK"); v.Show(); } else if (acccountmaskedEdit.HasError || descriptionmaskedEdit.HasError || amountmaskedEdit.HasError || emailIDmaskedEdit.HasError || mobileNumbermaskedEdit.HasError) { UIAlertView v = new UIAlertView(); v.Title = "Results"; v.Message = "Please enter valid details"; v.AddButton("OK"); v.Show(); } else { UIAlertView v1 = new UIAlertView(); v1.Title = "Results"; v1.AddButton("OK"); v1.Message = string.Format("Amount of {0} has been transferred successfully!", amountmaskedEdit.Text); v1.Show(); acccountmaskedEdit.Value = string.Empty; descriptionmaskedEdit.Value = string.Empty; amountmaskedEdit.Value = string.Empty; emailIDmaskedEdit.Value = string.Empty; mobileNumbermaskedEdit.Value = string.Empty; } this.BecomeFirstResponder(); } public void mainPageDesign() { inputValidationModeLabel = new UILabel(); inputValidationModeLabel.TextColor = UIColor.Black; inputValidationModeLabel.BackgroundColor = UIColor.Clear; inputValidationModeLabel.Text = @"Validation On"; inputValidationModeLabel.TextAlignment = UITextAlignment.Left; inputValidationModeLabel.Font = UIFont.FromName("Helvetica", 13f); validationButton = new UIButton(); validationButton.SetTitle("Key Press", UIControlState.Normal); validationButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; validationButton.BackgroundColor = UIColor.Clear; validationButton.SetTitleColor(UIColor.Black, UIControlState.Normal); validationButton.Hidden = false; validationButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; validationButton.Layer.BorderWidth = 2; validationButton.TitleLabel.Font = UIFont.SystemFontOfSize(13f); validationButton.Layer.CornerRadius = 8; validationButton.TouchUpInside += CutCopyMaskFormatButton_TouchUpInside; ; PickerModel cutCopyPickermodel = new PickerModel(this.inputValidationModeList); cutCopyPickermodel.PickerChanged += (sender, e) => { this.validationSelectedType = e.SelectedValue; validationButton.SetTitle(validationSelectedType, UIControlState.Normal); if (validationSelectedType == "Key Press") { acccountmaskedEdit.ValidationMode = InputValidationMode.KeyPress; descriptionmaskedEdit.ValidationMode = InputValidationMode.KeyPress; amountmaskedEdit.ValidationMode = InputValidationMode.KeyPress; emailIDmaskedEdit.ValidationMode = InputValidationMode.KeyPress; mobileNumbermaskedEdit.ValidationMode = InputValidationMode.KeyPress; } else if (validationSelectedType == "Lost Focus") { acccountmaskedEdit.ValidationMode = InputValidationMode.LostFocus; descriptionmaskedEdit.ValidationMode = InputValidationMode.LostFocus; amountmaskedEdit.ValidationMode = InputValidationMode.LostFocus; emailIDmaskedEdit.ValidationMode = InputValidationMode.LostFocus; mobileNumbermaskedEdit.ValidationMode = InputValidationMode.LostFocus; } }; cutCopyPicker = new UIPickerView(); cutCopyPicker.ShowSelectionIndicator = true; cutCopyPicker.Hidden = true; cutCopyPicker.Model = cutCopyPickermodel; cutCopyPicker.BackgroundColor = UIColor.White; validationDoneButton = new UIButton(); validationDoneButton.SetTitle("Done\t", UIControlState.Normal); validationDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; validationDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); validationDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); validationDoneButton.Hidden = true; validationDoneButton.TitleLabel.Font = UIFont.SystemFontOfSize(13f); validationDoneButton.TouchUpInside += CutCopyDoneButton_TouchUpInside; cultureLabel = new UILabel(); cultureLabel.TextColor = UIColor.Black; cultureLabel.BackgroundColor = UIColor.Clear; cultureLabel.Text = @"Culture"; cultureLabel.TextAlignment = UITextAlignment.Left; cultureLabel.Font = UIFont.FromName("Helvetica", 13f); cultureButton = new UIButton(); cultureButton.SetTitle("United States", UIControlState.Normal); cultureButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; cultureButton.BackgroundColor = UIColor.Clear; cultureButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureButton.Hidden = false; cultureButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; cultureButton.Layer.BorderWidth = 2; cultureButton.Layer.CornerRadius = 8; cultureButton.TitleLabel.Font = UIFont.SystemFontOfSize(13f); cultureButton.TouchUpInside += ShowCulturePicker; PickerModel culturePickermodel = new PickerModel(this.cultureList); culturePickermodel.PickerChanged += (sender, e) => { this.cultureSelectedType = e.SelectedValue; cultureButton.SetTitle(cultureSelectedType, UIControlState.Normal); if (cultureSelectedType == "United States") { acccountmaskedEdit.Culture = new CultureInfo("en-us"); descriptionmaskedEdit.Culture = new CultureInfo("en-us"); amountmaskedEdit.Culture = new CultureInfo("en-us"); emailIDmaskedEdit.Culture = new CultureInfo("en-us"); mobileNumbermaskedEdit.Culture = new CultureInfo("en-us"); } else if (cultureSelectedType == "United Kingdom") { acccountmaskedEdit.Culture = new CultureInfo("en-GB"); descriptionmaskedEdit.Culture = new CultureInfo("en-GB"); amountmaskedEdit.Culture = new CultureInfo("en-GB"); emailIDmaskedEdit.Culture = new CultureInfo("en-GB"); mobileNumbermaskedEdit.Culture = new CultureInfo("en-GB"); } else if (cultureSelectedType == "Japan") { acccountmaskedEdit.Culture = new CultureInfo("ja-JP"); descriptionmaskedEdit.Culture = new CultureInfo("ja-JP"); amountmaskedEdit.Culture = new CultureInfo("ja-JP"); emailIDmaskedEdit.Culture = new CultureInfo("ja-JP"); mobileNumbermaskedEdit.Culture = new CultureInfo("ja-JP"); } else if (cultureSelectedType == "France") { acccountmaskedEdit.Culture = new CultureInfo("fr-FR"); descriptionmaskedEdit.Culture = new CultureInfo("fr-FR"); amountmaskedEdit.Culture = new CultureInfo("fr-FR"); emailIDmaskedEdit.Culture = new CultureInfo("fr-FR"); mobileNumbermaskedEdit.Culture = new CultureInfo("fr-FR"); } else if (cultureSelectedType == "Italy") { acccountmaskedEdit.Culture = new CultureInfo("it-IT"); descriptionmaskedEdit.Culture = new CultureInfo("it-IT"); amountmaskedEdit.Culture = new CultureInfo("it-IT"); emailIDmaskedEdit.Culture = new CultureInfo("it-IT"); mobileNumbermaskedEdit.Culture = new CultureInfo("it-IT"); } }; culturePicker = new UIPickerView(); culturePicker.ShowSelectionIndicator = true; culturePicker.Hidden = true; culturePicker.Model = culturePickermodel; culturePicker.BackgroundColor = UIColor.White; cultureDoneButton = new UIButton(); cultureDoneButton.SetTitle("Done\t", UIControlState.Normal); cultureDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; cultureDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); cultureDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); cultureDoneButton.Hidden = true; cultureDoneButton.TitleLabel.Font = UIFont.SystemFontOfSize(13f); cultureDoneButton.TouchUpInside += HideCulturePicker; visibilityLabel = new UILabel(); visibilityLabel.TextColor = UIColor.Black; visibilityLabel.BackgroundColor = UIColor.Clear; visibilityLabel.Text = @"Clear Button Visibility"; visibilityLabel.TextAlignment = UITextAlignment.Left; visibilityLabel.Font = UIFont.FromName("Helvetica", 13f); visibilityButton = new UIButton(); visibilityButton.SetTitle("While Editing", UIControlState.Normal); visibilityButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; visibilityButton.BackgroundColor = UIColor.Clear; visibilityButton.SetTitleColor(UIColor.Black, UIControlState.Normal); visibilityButton.Hidden = false; visibilityButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; visibilityButton.Layer.BorderWidth = 2; visibilityButton.Layer.CornerRadius = 8; visibilityButton.TitleLabel.Font = UIFont.SystemFontOfSize(13f); visibilityButton.TouchUpInside += VisibilityButton_TouchUpInside; PickerModel VisibilityPickermodel = new PickerModel(this.visibilityList); VisibilityPickermodel.PickerChanged += (sender, e) => { this.visibilityType = e.SelectedValue; visibilityButton.SetTitle(visibilityType, UIControlState.Normal); if (visibilityType == "Never") { acccountmaskedEdit.ClearButtonMode = UITextFieldViewMode.Never; descriptionmaskedEdit.ClearButtonMode = UITextFieldViewMode.Never; amountmaskedEdit.ClearButtonMode = UITextFieldViewMode.Never; emailIDmaskedEdit.ClearButtonMode = UITextFieldViewMode.Never; mobileNumbermaskedEdit.ClearButtonMode = UITextFieldViewMode.Never; } else if (visibilityType == "While Editing") { acccountmaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; descriptionmaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; amountmaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; emailIDmaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; mobileNumbermaskedEdit.ClearButtonMode = UITextFieldViewMode.WhileEditing; } }; visibilityPicker = new UIPickerView(); visibilityPicker.ShowSelectionIndicator = true; visibilityPicker.Hidden = true; visibilityPicker.Model = VisibilityPickermodel; visibilityPicker.BackgroundColor = UIColor.White; visibilityDoneButton = new UIButton(); visibilityDoneButton.SetTitle("Done\t", UIControlState.Normal); visibilityDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; visibilityDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); visibilityDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); visibilityDoneButton.Hidden = true; visibilityDoneButton.TitleLabel.Font = UIFont.SystemFontOfSize(13f); visibilityDoneButton.TouchUpInside += visibilityDoneButton_TouchUpInside; hidepromptLabel = new UILabel(); hidepromptLabel.TextColor = UIColor.Black; hidepromptLabel.BackgroundColor = UIColor.Clear; hidepromptLabel.Text = @"Hide Prompt On Leave"; hidepromptLabel.TextAlignment = UITextAlignment.Left; hidepromptLabel.Font = UIFont.FromName("Helvetica", 13f); hidepromptSwitch = new UISwitch(); hidepromptSwitch.ValueChanged += AllowSwitch_ValueChanged; hidepromptSwitch.On = false; promptcharLabel = new UILabel(); promptcharLabel.TextColor = UIColor.Black; promptcharLabel.BackgroundColor = UIColor.Clear; promptcharLabel.Text = @"Prompt Character"; promptcharLabel.TextAlignment = UITextAlignment.Left; promptcharLabel.Font = UIFont.FromName("Helvetica", 13f); promptcharButton = new UIButton(); promptcharButton.SetTitle("_", UIControlState.Normal); promptcharButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; promptcharButton.BackgroundColor = UIColor.Clear; promptcharButton.SetTitleColor(UIColor.Black, UIControlState.Normal); promptcharButton.Hidden = false; promptcharButton.Layer.BorderColor = UIColor.FromRGB(246, 246, 246).CGColor; promptcharButton.Layer.BorderWidth = 2; promptcharButton.Layer.CornerRadius = 8; promptcharButton.TitleLabel.Font = UIFont.SystemFontOfSize(13f); promptcharButton.TouchUpInside += ShowpromptPicker; PickerModel promptcharPickermodel = new PickerModel(this.promptCharList); promptcharPickermodel.PickerChanged += (sender, e) => { this.promptSelectedType = e.SelectedValue; promptcharButton.SetTitle(promptSelectedType, UIControlState.Normal); if (promptSelectedType == "*") { acccountmaskedEdit.PromptChar = '*'; descriptionmaskedEdit.PromptChar = '*'; amountmaskedEdit.PromptChar = '*'; emailIDmaskedEdit.PromptChar = '*'; mobileNumbermaskedEdit.PromptChar = '*'; } else if (promptSelectedType == "~") { acccountmaskedEdit.PromptChar = '~'; descriptionmaskedEdit.PromptChar = '~'; amountmaskedEdit.PromptChar = '~'; emailIDmaskedEdit.PromptChar = '~'; mobileNumbermaskedEdit.PromptChar = '~'; } else if (promptSelectedType == "_") { acccountmaskedEdit.PromptChar = '_'; descriptionmaskedEdit.PromptChar = '_'; amountmaskedEdit.PromptChar = '_'; emailIDmaskedEdit.PromptChar = '_'; mobileNumbermaskedEdit.PromptChar = '_'; } }; promptPicker = new UIPickerView(); promptPicker.ShowSelectionIndicator = true; promptPicker.Hidden = true; promptPicker.Model = promptcharPickermodel; promptPicker.BackgroundColor = UIColor.White; promptDoneButton = new UIButton(); promptDoneButton.SetTitle("Done\t", UIControlState.Normal); promptDoneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; promptDoneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); promptDoneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); promptDoneButton.Hidden = true; promptDoneButton.TitleLabel.Font = UIFont.SystemFontOfSize(13f); promptDoneButton.TouchUpInside += HidepromptPicker; this.BackgroundColor = UIColor.White; } private void HidepromptPicker(object sender, EventArgs e) { promptDoneButton.Hidden = true; promptPicker.Hidden = true; } private void ShowpromptPicker(object sender, EventArgs e) { promptDoneButton.Hidden = false; promptPicker.Hidden = false; } private void CutCopyDoneButton_TouchUpInside(object sender, EventArgs e) { validationDoneButton.Hidden = true; cutCopyPicker.Hidden = true; } private void CutCopyMaskFormatButton_TouchUpInside(object sender, EventArgs e) { validationDoneButton.Hidden = false; cutCopyPicker.Hidden = false; } private void VisibilityButton_TouchUpInside(object sender, EventArgs e) { visibilityDoneButton.Hidden = false; visibilityPicker.Hidden = false; } private void visibilityDoneButton_TouchUpInside(object sender, EventArgs e) { visibilityDoneButton.Hidden = true; visibilityPicker.Hidden = true; } private void ShowCulturePicker(object sender, EventArgs e) { cultureDoneButton.Hidden = false; culturePicker.Hidden = false; } private void AllowSwitch_ValueChanged(object sender, EventArgs e) { if (((UISwitch)sender).On) { acccountmaskedEdit.HidePromptOnLeave = true; descriptionmaskedEdit.HidePromptOnLeave = true; amountmaskedEdit.HidePromptOnLeave = true; emailIDmaskedEdit.HidePromptOnLeave = true; mobileNumbermaskedEdit.HidePromptOnLeave = true; } else { acccountmaskedEdit.HidePromptOnLeave = false; descriptionmaskedEdit.HidePromptOnLeave = false; amountmaskedEdit.HidePromptOnLeave = false; emailIDmaskedEdit.HidePromptOnLeave = false; mobileNumbermaskedEdit.HidePromptOnLeave = false; } } void HideCulturePicker(object sender, EventArgs e) { cultureDoneButton.Hidden = true; culturePicker.Hidden = true; } } } <file_sep>/iOS/SampleBrowser/Resources/Samples/TabView/TabViewOptionsPage.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using CoreGraphics; using Syncfusion.SfTabView.iOS; using UIKit; namespace SampleBrowser { internal class CustomTextDelegate : UITextFieldDelegate { TabViewOptionsPage optionsPage; public CustomTextDelegate(TabViewOptionsPage page) { optionsPage = page; } public override bool ShouldBeginEditing(UITextField textField) { optionsPage.HandleAction((int)textField.Tag); return false; } } public class TabViewOptionsPage : UIView { UILabel tabdisplaymodelabel; UILabel tabpositionlabel; UILabel selectionindicatorlabel; UILabel overflowmodelabel; UITextField tabdisplaymodeEntry; UITextField tabpositionEntry; UITextField selectionindicatorEntry; UITextField overflowmodeEntry; internal UIPickerView picker; internal UIButton doneButton; internal PickerModel model; internal SfTabView sftabView; int clickedtag = 0; private string selectedType; internal IList<string> displaymodelist = new List<string>(); internal IList<string> positionlist = new List<string>(); internal IList<string> selectionindicatorlist = new List<string>(); internal IList<string> overflowlist = new List<string>(); public TabViewOptionsPage() { var customDelegate = new CustomTextDelegate(this); AddData(); tabdisplaymodelabel = new UILabel(); tabdisplaymodelabel.Text = "Tab Display Mode"; tabpositionlabel = new UILabel(); tabpositionlabel.Text = "Tab Position"; selectionindicatorlabel = new UILabel(); selectionindicatorlabel.Text = "Selection Type"; overflowmodelabel = new UILabel(); overflowmodelabel.Text = "Overflow Mode"; tabdisplaymodeEntry = new UITextField(); tabdisplaymodeEntry.Tag = 1; tabdisplaymodeEntry.Layer.BorderColor = UIColor.LightGray.CGColor; tabdisplaymodeEntry.Layer.BorderWidth = 1; tabdisplaymodeEntry.Layer.CornerRadius = 5; tabdisplaymodeEntry.TextAlignment = UITextAlignment.Center; tabdisplaymodeEntry.Delegate = customDelegate; tabdisplaymodeEntry.Text = "Image"; tabpositionEntry = new UITextField(); tabpositionEntry.Tag = 2; tabpositionEntry.Layer.BorderColor = UIColor.LightGray.CGColor; tabpositionEntry.Layer.BorderWidth = 1; tabpositionEntry.Layer.CornerRadius = 5; tabpositionEntry.TextAlignment = UITextAlignment.Center; tabpositionEntry.Delegate = customDelegate; tabpositionEntry.Text = "Top"; selectionindicatorEntry = new UITextField(); selectionindicatorEntry.Tag = 3; selectionindicatorEntry.Layer.BorderColor = UIColor.LightGray.CGColor; selectionindicatorEntry.Layer.BorderWidth = 1; selectionindicatorEntry.Layer.CornerRadius = 5; selectionindicatorEntry.TextAlignment = UITextAlignment.Center; selectionindicatorEntry.Delegate = customDelegate; selectionindicatorEntry.Text = "Bottom"; overflowmodeEntry = new UITextField(); overflowmodeEntry.Tag = 4; overflowmodeEntry.Layer.BorderColor = UIColor.LightGray.CGColor; overflowmodeEntry.Layer.BorderWidth = 1; overflowmodeEntry.Layer.CornerRadius = 5; overflowmodeEntry.TextAlignment = UITextAlignment.Center; overflowmodeEntry.Delegate = customDelegate; overflowmodeEntry.Text = "Scroll"; Add(tabdisplaymodelabel); Add(tabpositionlabel); Add(selectionindicatorlabel); Add(overflowmodelabel); Add(tabdisplaymodeEntry); Add(tabpositionEntry); Add(selectionindicatorEntry); Add(overflowmodeEntry); InitializePicker(); } void InitializePicker() { model = new PickerModel(displaymodelist); model.PickerChanged += PickerIndexChanged; picker = new UIPickerView(); picker.Model = model; picker.ShowSelectionIndicator = true; picker.Hidden = true; picker.BackgroundColor = UIColor.White; //DoneButton doneButton = new UIButton(); doneButton.SetTitle("Done\t", UIControlState.Normal); doneButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Right; doneButton.BackgroundColor = UIColor.FromRGB(240, 240, 240); doneButton.SetTitleColor(UIColor.Black, UIControlState.Normal); doneButton.Hidden = true; doneButton.TouchUpInside += HidePicker; Add(picker); Add(doneButton); } void AddData() { displaymodelist.Add("Image"); displaymodelist.Add("Text"); displaymodelist.Add("Image with Text"); displaymodelist.Add("No Header"); positionlist.Add("Top"); positionlist.Add("Bottom"); selectionindicatorlist.Add("Top"); selectionindicatorlist.Add("Bottom"); selectionindicatorlist.Add("Fill"); overflowlist.Add("Scroll"); overflowlist.Add("DropDown"); } public override void LayoutSubviews() { var height = this.Frame.Height; picker.Frame = new CGRect(0, height/3 - 5, this.Frame.Size.Width, height / 3); doneButton.Frame = new CGRect(0,(height / 3)-5, this.Frame.Size.Width, 40); tabdisplaymodelabel.Frame = new CGRect(10, 0, this.Frame.Width - 20, 30); tabdisplaymodeEntry.Frame = new CGRect(10, 30, this.Frame.Width - 20, 30); tabpositionlabel.Frame = new CGRect(10, 80, this.Frame.Width - 20, 30); tabpositionEntry.Frame = new CGRect(10, 110, this.Frame.Width - 20, 30); overflowmodelabel.Frame = new CGRect(10, 160, this.Frame.Width - 20, 30); overflowmodeEntry.Frame = new CGRect(10, 190, this.Frame.Width - 20, 30); selectionindicatorlabel.Frame = new CGRect(10, 240, this.Frame.Width - 20, 30); selectionindicatorEntry.Frame = new CGRect(10, 270, this.Frame.Width - 20, 30); base.LayoutSubviews(); } private void PickerIndexChanged(object sender, PickerChangedEventArgs e) { this.selectedType = e.SelectedValue; } void HidePicker(object sender, EventArgs e) { switch(clickedtag) { case 1: if (this.selectedType == "Image") sftabView.DisplayMode = TabDisplayMode.Image; else if (this.selectedType == "Text") sftabView.DisplayMode = TabDisplayMode.Text; else if (this.selectedType == "Image with Text") sftabView.DisplayMode = TabDisplayMode.ImageWithText; else sftabView.DisplayMode = TabDisplayMode.NoHeader; break; case 2: if (this.selectedType == "Top") sftabView.TabHeaderPosition = TabHeaderPosition.Top; else sftabView.TabHeaderPosition = TabHeaderPosition.Bottom; break; case 3: if (this.selectedType == "Top") sftabView.SelectionIndicatorSettings.Position = SelectionIndicatorPosition.Top; else if (this.selectedType == "Fill") sftabView.SelectionIndicatorSettings.Position = SelectionIndicatorPosition.Fill; else sftabView.SelectionIndicatorSettings.Position = SelectionIndicatorPosition.Bottom; break; case 4: if (this.selectedType == "Scroll") sftabView.OverflowMode = OverflowMode.Scroll; else sftabView.OverflowMode = OverflowMode.DropDown; break; } doneButton.Hidden = true; picker.Hidden = true; this.BecomeFirstResponder(); } internal void HandleAction(int tag) { clickedtag = tag; switch (tag) { case 1: model = new PickerModel(displaymodelist); break; case 2: model = new PickerModel(positionlist); break; case 3: model = new PickerModel(selectionindicatorlist); break; case 4: model = new PickerModel(overflowlist); break; } model.PickerChanged -= PickerIndexChanged; model.PickerChanged += PickerIndexChanged; picker.Model = model; picker.ReloadAllComponents(); doneButton.Hidden = false; picker.Hidden = false; BecomeFirstResponder(); } } } <file_sep>/Forms/Presentation/Presentation/Samples/WriteProtection/WriteProtection.xaml.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using Syncfusion.Presentation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using COLOR = Syncfusion.Drawing; using Xamarin.Forms; using System.IO; using System.Reflection; using System.Xml; using System.Xml.Linq; using SampleBrowser.Core; namespace SampleBrowser.Presentation { public partial class WriteProtection : SampleView { public WriteProtection() { InitializeComponent(); if (Device.Idiom != TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.HorizontalOptions = LayoutOptions.Start; this.btnGenerate.HorizontalOptions = LayoutOptions.Start; this.passwordLabel.HorizontalOptions = LayoutOptions.Start; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.passwordLabel.VerticalOptions = LayoutOptions.Center; this.btnGenerate.BackgroundColor = Color.Gray; } else if (Device.Idiom == TargetIdiom.Phone && Device.RuntimePlatform == Device.UWP) { this.Description.FontSize = 13.5; this.Description.VerticalOptions = LayoutOptions.Center; this.btnGenerate.VerticalOptions = LayoutOptions.Center; this.passwordLabel.VerticalOptions = LayoutOptions.Center; } } void OnButtonClicked(object sender, EventArgs e) { string resourcePath = ""; #if COMMONSB resourcePath = "SampleBrowser.Samples.Presentation.Samples.Templates.Transition.pptx"; #else resourcePath = "SampleBrowser.Presentation.Samples.Templates.Transition.pptx"; #endif Assembly assembly = typeof(WriteProtection).GetTypeInfo().Assembly; Stream fileStream = assembly.GetManifestResourceStream(resourcePath); //Open a existing PowerPoint presentation IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStream); string protectPassward = string.Empty; if (password != null && password.Text != null) protectPassward = password.Text; //Set the write protection for presentation instance presentation.SetWriteProtection(protectPassward); MemoryStream stream = new MemoryStream(); presentation.Save(stream); presentation.Close(); stream.Position = 0; if (Device.RuntimePlatform == Device.UWP) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("WriteProtection.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("WriteProtection.pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation", stream); } } } <file_sep>/Android/SampleBrowser/Samples/Calendar/CalendarGettingStarted/CalendarGettingStarted_Tab.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Com.Syncfusion.Calendar; using Com.Syncfusion.Calendar.Enums; using Android.Graphics; namespace SampleBrowser { public class CalendarGettingStarted_Tab : SamplePage, IDisposable { /********************************* **Local Variable Inizialisation** *********************************/ private SfCalendar calendar; private ArrayAdapter<String> dataAdapter; private Spinner modeSpinner; private Context context; private FrameLayout mainView; private LinearLayout proprtyOptionsLayout; public CalendarGettingStarted_Tab() { } public override View GetSampleContent(Context context1) { context = context1; calendar = new SfCalendar(context); calendar.ShowEventsInline = false; calendar.HeaderHeight = 100; MonthViewLabelSetting labelSettings = new MonthViewLabelSetting(); labelSettings.DateLabelSize = 14; MonthViewSettings monthViewSettings = new MonthViewSettings(); monthViewSettings.MonthViewLabelSetting = labelSettings; monthViewSettings.SelectedDayTextColor = Color.Black; monthViewSettings.TodayTextColor = Color.ParseColor("#1B79D6"); monthViewSettings.InlineBackgroundColor = Color.ParseColor("#E4E8ED"); monthViewSettings.WeekDayBackgroundColor = Color.ParseColor("#F7F7F7"); calendar.MonthViewSettings = monthViewSettings; mainView = new FrameLayout(context); mainView.AddView(calendar); return mainView; } public override View GetPropertyWindowLayout(Context context) { proprtyOptionsLayout = new LinearLayout(context); proprtyOptionsLayout.SetPadding(40, 40, 40, 0); proprtyOptionsLayout.Orientation = Android.Widget.Orientation.Vertical; ViewModeLayout(); return proprtyOptionsLayout; } private void ViewModeLayout() { //ViewMode TextView viewModeLabel = new TextView(context); viewModeLabel.SetPadding(0, 0, 0, 50); viewModeLabel.TextSize = 20; viewModeLabel.Text = "ViewMode"; modeSpinner = new Spinner(context, SpinnerMode.Dialog); //Vie Mode List List<String> viewModeList = new List<String>(); viewModeList.Add("Month View"); viewModeList.Add("Year View"); //Data Adapter dataAdapter = new ArrayAdapter<String>(context, Android.Resource.Layout.SimpleSpinnerItem, viewModeList); dataAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem); modeSpinner.Adapter = dataAdapter; modeSpinner.SetSelection(0); //Mode Spinner Item Selected Listener modeSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem(e.Position); if (selectedItem.Equals("Month View")) { calendar.ViewMode = ViewMode.MonthView; } if (selectedItem.Equals("Year View")) { calendar.ViewMode = ViewMode.YearView; } }; //viewModeLayout LinearLayout viewModeLayout = new LinearLayout(context); viewModeLayout.Orientation = Android.Widget.Orientation.Vertical; viewModeLayout.AddView(viewModeLabel); viewModeLayout.AddView(modeSpinner); proprtyOptionsLayout.AddView(viewModeLayout); } public void Dispose() { if (calendar != null) { calendar.Dispose(); calendar = null; } if (dataAdapter != null) { dataAdapter.Dispose(); dataAdapter = null; } if (modeSpinner != null) { modeSpinner.Dispose(); modeSpinner = null; } if (mainView != null) { mainView.Dispose(); mainView = null; } if (proprtyOptionsLayout != null) { proprtyOptionsLayout.Dispose(); proprtyOptionsLayout = null; } } } }<file_sep>/Android/SampleBrowser/Samples/DataGrid/ViewModel/ViewModel.cs #region Copyright Syncfusion Inc. 2001-2023. // Copyright Syncfusion Inc. 2001-2023. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // <EMAIL>. Any infringement will be prosecuted under // applicable laws. #endregion using System; using System.ComponentModel; using IncrementalLoading.NorthwindService; using Syncfusion.SfDataGrid; using System.Data.Services.Client; using System.Linq; using System.Threading.Tasks; using System.Net; using Android.App; using Android.Content; using Android.Views; using System.Collections.ObjectModel; using System.Collections.Generic; using Syncfusion.Data; using System.Timers; using System.Text; using Android.Widget; using Syncfusion.Data.Extensions; using Syncfusion.Android.ProgressBar; using Syncfusion.Android.PopupLayout; namespace SampleBrowser { public class GettingStartedViewModel { #region Fields private Random random = new Random(); private OrderInfoRepository order; #endregion public GettingStartedViewModel() { SetRowstoGenerate(100); } #region ItemsSource private ObservableCollection<OrderInfo> ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { order = new OrderInfoRepository(); ordersInfo = order.GetOrderDetails(count); } #endregion internal void ItemsSourceRefresh() { var count = random.Next(1, 6); for (int i = 11000; i < 11000 + count; i++) { int val = i + random.Next(100, 150); this.OrdersInfo.Insert(0, order.RefreshItemsource(val)); } } } public class SortingViewModel { public SortingViewModel() { } #region ItemsSource private ObservableCollection<Products> products; public ObservableCollection<Products> Products { get { return products; } set { this.products = value; } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { ProductRepository product = new ProductRepository(); products = product.GetProductDetails(100); } #endregion } public class IncrementalLoadingViewModel : INotifyPropertyChanged { #region Members NorthwindEntities northwindEntity; private SfLinearProgressBar progress; private SfPopupLayout popup; #endregion #region Constructor public IncrementalLoadingViewModel(Context context) { progress = new SfLinearProgressBar(context); popup = new SfPopupLayout(context); string uri = "http://services.odata.org/Northwind/Northwind.svc/"; if (CheckConnection(uri).Result) { popup.PopupView.ContentView = progress; popup.PopupView.HeaderTitle = "Fetching Data... "; popup.PopupView.ShowCloseButton = false; popup.PopupView.ShowFooter = false; popup.PopupView.HeightRequest = 125; popup.StaysOpen = true; progress.Progress = 100; progress.IsIndeterminate = true; popup.Show(); gridSource = new IncrementalList<Order>(LoadMoreItems) { MaxItemsCount = 1000 }; northwindEntity = new NorthwindEntities(new Uri(uri)); } else { NoNetwork = true; IsBusy = false; } } #endregion #region Properties private IncrementalList<Order> gridSource; public IncrementalList<Order> GridSource { get { return gridSource; } set { gridSource = value; RaisePropertyChanged("GridSource"); } } private bool isBusy; public bool IsBusy { get { return isBusy; } set { isBusy = value; if (progress != null) { if (isBusy) { } else { if (noNetwork) { popup.PopupView.ContentView = progress; popup.PopupView.ShowCloseButton = false; popup.PopupView.ShowFooter = false; popup.PopupView.HeaderHeight = 90; popup.PopupView.HeightRequest = 125; popup.PopupView.HeaderTitle = "No Network Found..! \n\nSearching for a network..."; progress.Progress = 100; progress.IsIndeterminate = true; popup.Show(); } else popup.Dismiss(); } } RaisePropertyChanged("IsBusy"); } } private bool noNetwork; public bool NoNetwork { get { return noNetwork; } set { noNetwork = value; RaisePropertyChanged("NoNetwork"); } } #endregion #region Methods void LoadMoreItems(uint count, int baseIndex) { BackgroundWorker worker = new BackgroundWorker(); //worker.RunWorkerAsync (); worker.DoWork += (o, ae) => { DataServiceQuery<Order> query = northwindEntity.Orders.Expand("Customer"); query = query.Skip<Order>(baseIndex).Take<Order>(50) as DataServiceQuery<Order>; IAsyncResult ar = query.BeginExecute(null, null); var items = query.EndExecute(ar); var list = items.ToList(); Android.OS.Handler mainHandler = new Android.OS.Handler(Android.OS.Looper.MainLooper); Java.Lang.Runnable myRunnable = new Java.Lang.Runnable(() => { GridSource.LoadItems(list); }); mainHandler.Post(myRunnable); }; worker.RunWorkerCompleted += (o, ae) => { IsBusy = false; }; IsBusy = true; worker.RunWorkerAsync(); } private async Task<bool> CheckConnection(String URL) { try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URL)); request.Timeout = 5000; request.Credentials = CredentialCache.DefaultNetworkCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); await Task.Delay(0); if (response.StatusCode == HttpStatusCode.OK) return true; else return false; } catch { return false; } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion #region Dispose public void Dispose() { northwindEntity = null; popup = null; progress.Dispose(); progress = null; } #endregion } public class SelectionViewModel : NotificationObject { public SelectionViewModel() { ProductInfoRespository products = new ProductInfoRespository(); ProductDetails = products.GetProductDetails(100); } private List<ProductInfo> productDetails; /// <summary> /// Gets or sets the product details. /// </summary> /// <value>The product details.</value> public List<ProductInfo> ProductDetails { get { return productDetails; } set { productDetails = value; RaisePropertyChanged("ProductDetails"); } } } public class FilteringViewModel : INotifyPropertyChanged { #region Fields Context context; #endregion #region Constructor public FilteringViewModel(Context context) { this.context = context; } #endregion #region Filtering #region Fields private string filtertext = ""; private string selectedcolumn = "All Columns"; private string selectedcondition = "Equals"; internal delegate void FilterChanged(); internal FilterChanged filtertextchanged; #endregion #region Property public string FilterText { get { return filtertext; } set { filtertext = value; OnFilterTextChanged(); RaisePropertyChanged("FilterText"); } } public string SelectedCondition { get { return selectedcondition; } set { selectedcondition = value; } } public string SelectedColumn { get { return selectedcolumn; } set { selectedcolumn = value; } } #endregion #region Private Methods private void OnFilterTextChanged() { filtertextchanged(); } private bool MakeStringFilter(BookInfo o, string option, string condition) { var value = o.GetType().GetProperty(option); var exactValue = value.GetValue(o, null); exactValue = exactValue.ToString().ToLower(); string text = FilterText.ToLower(); var methods = typeof(string).GetMethods(); if (methods.Count() != 0) { if (condition == "Contains") { var methodInfo = methods.FirstOrDefault(method => method.Name == condition); bool result1 = (bool)methodInfo.Invoke(exactValue, new object[] { text }); return result1; } else if (exactValue.ToString() == text.ToString()) { bool result1 = String.Equals(exactValue.ToString(), text.ToString()); if (condition == "Equals") return result1; else if (condition == "NotEquals") return false; } else if (condition == "NotEquals") { return true; } return false; } else return false; } private bool MakeNumericFilter(BookInfo o, string option, string condition) { var value = o.GetType().GetProperty(option); var exactValue = value.GetValue(o, null); double res; bool checkNumeric = double.TryParse(exactValue.ToString(), out res); if (checkNumeric) { switch (condition) { case "Equals": try { if (exactValue.ToString() == FilterText) { if (Convert.ToDouble(exactValue) == (Convert.ToDouble(FilterText))) return true; } } catch (Exception e) { Console.WriteLine(e); Toast.MakeText(this.context, "Invalid input", ToastLength.Short).Show(); } break; case "NotEquals": try { if (Convert.ToDouble(FilterText) != Convert.ToDouble(exactValue)) return true; } catch (Exception e) { Console.WriteLine(e); Toast.MakeText(this.context, "Invalid input", ToastLength.Short).Show(); return true; } break; } } return false; } #endregion #region Public Methods public bool FilerRecords(object o) { double res; bool checkNumeric = double.TryParse(FilterText, out res); var item = o as BookInfo; if (item != null && FilterText.Equals("")) { return true; } else { if (item != null) { if (checkNumeric && !SelectedColumn.Equals("All Columns")) { bool result = MakeNumericFilter(item, SelectedColumn, SelectedCondition); return result; } else if (SelectedColumn.Equals("All Columns")) { if (item.BookName.ToLower().Contains(FilterText.ToLower()) || item.Country.ToLower().Contains(FilterText.ToLower()) || item.FirstName.ToString().ToLower().Contains(FilterText.ToLower()) || item.LastName.ToString().ToLower().Contains(FilterText.ToLower()) || item.CustomerID.ToString().ToLower().Contains(FilterText.ToLower()) || item.Price.ToString().ToLower().Contains(FilterText.ToLower()) || item.BookID.ToString().ToLower().Contains(FilterText.ToLower())) return true; return false; } else { bool result = MakeStringFilter(item, SelectedColumn, SelectedCondition); return result; } } } return false; } #endregion #endregion #region ItemsSource private List<BookInfo> bookInfo; public List<BookInfo> BookInfo { get { return bookInfo; } set { this.bookInfo = value; } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { BookRepository bookrepository = new BookRepository(); bookInfo = bookrepository.GetBookDetails(count); } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } public class GroupingViewModel : NotificationObject { public GroupingViewModel() { ProductInfoRespository products = new ProductInfoRespository(); ProductDetails = products.GetProductDetails(100); } private List<ProductInfo> productDetails; /// <summary> /// Gets or sets the product details. /// </summary> /// <value>The product details.</value> public List<ProductInfo> ProductDetails { get { return productDetails; } set { productDetails = value; RaisePropertyChanged("ProductDetails"); } } } public class RenderingDynamicDataViewModel : INotifyPropertyChanged, IDisposable { #region Members ObservableCollection<StockData> data; Random r = new Random(123345345); internal Timer timer; private bool enableTimer = false; private double timerValue; private string buttonContent; private int noOfUpdates = 500; List<string> StockSymbols = new List<string>(); string[] accounts = new string[] { "American Funds", "College Savings", "Day Trading", "Mountain Range", "Fidelity Funds", "Mortages", "Housing Loans" }; string[] product = new string[] { "Crab", "Bag", "Cashew", "Syrup", "Meat", "Lax", "Filo" }; #endregion /// <summary> /// Gets the stocks. /// </summary> /// <value>The stocks.</value> public ObservableCollection<StockData> Stocks { get { return this.data; } } #region Constructor /// <summary> /// Initializes a new instance of the <see cref="StocksViewModel"/> class. /// </summary> public RenderingDynamicDataViewModel() { this.data = new ObservableCollection<StockData>(); this.AddRows(2000); this.timer = new Timer(); this.ResetRefreshFrequency(2500); timer.Interval = (double)TimeSpan.FromMilliseconds(200).Milliseconds; ButtonContent = "Start Timer"; timer.Elapsed += timer_Tick; ButtonClicked(); } #endregion #region Timer and updating code /// <summary> /// Sets the interval. /// </summary> /// <param name="time">The time.</param> public void SetInterval(TimeSpan time) { this.timer.Interval = Convert.ToDouble(time); } /// <summary> /// Starts the timer. /// </summary> public void StartTimer() { if (!this.timer.Enabled) { this.timer.Start(); this.ButtonContent = "Stop Timer"; } } /// <summary> /// Gets or sets the timer value. /// </summary> /// <value>The timer value.</value> public double TimeSpanValue { get { return timerValue; } set { timerValue = value; this.timer.Interval = Convert.ToDouble(TimeSpan.FromMilliseconds(timerValue)); RaisePropertyChanged("TimeSpanValue"); } } /// <summary> /// Gets or sets the button contnt. /// </summary> /// <value>The button contnt.</value> public string ButtonContent { get { return buttonContent; } set { buttonContent = value; RaisePropertyChanged("ButtonContent"); } } /// <summary> /// Determines whether this instance [can button click]. /// </summary> /// <returns> /// <c>true</c> if this instance [can button click]; otherwise, <c>false</c>. /// </returns> bool CanButtonClick(object param) { return true; } /// <summary> /// Buttons the clicked. /// </summary> public void ButtonClicked() { if (ButtonContent.Equals("Start Timer")) { this.EnableTimer = true; this.StartTimer(); ButtonContent = "Stop Timer"; } else { this.EnableTimer = false; this.StopTimer(); ButtonContent = "Start Timer"; } } /// <summary> /// Stops the timer. /// </summary> public void StopTimer() { this.timer.Stop(); } /// <summary> /// Handles the Tick event of the timer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void timer_Tick(object sender, object e) { int startTime = DateTime.Now.Millisecond; noOfUpdates = 100; ChangeRows(noOfUpdates); } /// <summary> /// Gets or sets a value indicating whether [enable timer]. /// </summary> /// <value><c>true</c> if [enable timer]; otherwise, <c>false</c>.</value> public bool EnableTimer { get { return this.enableTimer; } set { this.enableTimer = value; } } /// <summary> /// Adds the rows. /// </summary> /// <param name="count">The count.</param> private void AddRows(int count) { for (int i = 0; i < count; ++i) { var newRec = new StockData(); newRec.Symbol = ChangeSymbol(); newRec.Account = ChangeAccount(i); newRec.Open = Math.Round(r.NextDouble() * 30, 2); newRec.LastTrade = Math.Round((1 + r.NextDouble() * 50)); double d = r.NextDouble(); if (d < .5) newRec.StockChange = Math.Round(d, 2); else newRec.StockChange = Math.Round(d, 2) * -1; newRec.PreviousClose = Math.Round(r.NextDouble() * 30, 2); newRec.Product = ChangeProduct(i); newRec.Volume = r.Next(); data.Add(newRec); } } /// <summary> /// Changes the symbol. /// </summary> /// <returns></returns> private String ChangeSymbol() { StringBuilder builder = new StringBuilder(); Random random = new Random(); char ch; do { builder = new StringBuilder(); for (int i = 0; i < 4; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } } while (StockSymbols.Contains(builder.ToString())); StockSymbols.Add(builder.ToString()); return builder.ToString(); } /// <summary> /// Changes the account. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> private String ChangeAccount(int index) { return accounts[index % accounts.Length]; } /// <summary> /// Changes the Product. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> private String ChangeProduct(int index) { return product[index % product.Length]; } /// <summary> /// Resets the refresh frequency. /// </summary> /// <param name="changesPerTick">The changes per tick.</param> public void ResetRefreshFrequency(int changesPerTick) { if (this.timer == null) { return; } if (!this.noOfUpdates.Equals(changesPerTick)) { this.StopTimer(); this.noOfUpdates = changesPerTick; if (enableTimer) this.StartTimer(); } } public object SelectedItem { get { return noOfUpdates; } set { noOfUpdates = 2; RaisePropertyChanged("SelectedItem"); } } public List<int> ComboCollection { get { return new List<int> { 500, 5000, 50000, 500000 }; } } /// <summary> /// Changes the rows. /// </summary> /// <param name="count">The count.</param> private void ChangeRows(int count) { if (data.Count < count) count = data.Count; for (int i = 0; i < count; ++i) { int recNo = r.Next(data.Count); StockData recRow = data[recNo]; data[recNo].LastTrade = Math.Round((1 + r.NextDouble() * 50)); double d = r.NextDouble(); if (d < .5) { data[recNo].StockChange = Math.Round(d, 2); } else { data[recNo].StockChange = Math.Round(d, 2) * -1; } data[recNo].Open = Math.Round(r.NextDouble() * 50, 2); data[recNo].PreviousClose = Math.Round(r.NextDouble() * 30, 2); data[recNo].Volume = r.Next(); } } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (this.timer != null) { this.timer.Elapsed -= timer_Tick; this.StopTimer(); } } #endregion } public class FormattingViewModel { public FormattingViewModel() { SetRowstoGenerate(100); } #region ItemsSource private List<BankInfo> bankInfo; public List<BankInfo> BankInfo { get { return bankInfo; } set { this.bankInfo = value; } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { BankRepository bank = new BankRepository(); bankInfo = bank.GetBankDetails(100); } #endregion public void Dispose() { foreach (var item in bankInfo) { item.CustomerImage.Recycle(); item.CustomerImage.Dispose(); item.CustomerImage = null; } } } public class StylesViewModel : NotificationObject { public StylesViewModel() { OrderInfoRepository order = new OrderInfoRepository(); ordersInfo = order.GetOrderDetails(100); } #region ItemsSource private ObservableCollection<OrderInfo> ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; } } #endregion } public class AutoRowHeightViewModel : INotifyPropertyChanged { public AutoRowHeightViewModel() { ReleaseInfoRepository details = new ReleaseInfoRepository(); releaseInformation = details.GetReleaseDetails(28); } #region ItemsSource private ObservableCollection<ReleaseInfo> releaseInformation; public ObservableCollection<ReleaseInfo> ReleaseInformation { get { return this.releaseInformation; } set { this.releaseInformation = value; } } #endregion #region Property Changed public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion } public class CustomerViewModel { #region Constructor public CustomerViewModel() { CustomersRepository customerrep = new CustomersRepository(); customerInformation = customerrep.GetCutomerDetails(100); } #endregion #region ItemsSource private ObservableCollection<CustomerDetails> customerInformation; public ObservableCollection<CustomerDetails> CustomerInformation { get { return this.customerInformation; } set { this.customerInformation = value; } } #endregion #region Property Changed public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion } public class SalesInfoViewModel { #region Constructor public SalesInfoViewModel() { } #endregion #region ItemsSource private ObservableCollection<SalesByDate> dailySalesDetails = null; public ObservableCollection<SalesByDate> DailySalesDetails { get { if (dailySalesDetails == null) return new SalesInfoRepository().GetSalesDetailsByDay(100); else return dailySalesDetails; } } #endregion } public class FrozenViewViewModel { #region Constructor public FrozenViewViewModel() { SetRowstoGenerate(100); } #endregion #region ItemsSource private ObservableCollection<Products> products; public ObservableCollection<Products> Products { get { return products; } set { this.products = value; } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { ProductRepository product = new ProductRepository(); products = product.GetProductDetails(count); } #endregion } public class ExportingViewModel { #region Constructor public ExportingViewModel() { OrderInfoRepository order = new OrderInfoRepository(); OrdersInfo = order.GetOrderDetails(100); } #endregion #region ItemsSource private ObservableCollection<OrderInfo> _ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return _ordersInfo; } set { this._ordersInfo = value; } } #endregion } public class PullToRefreshViewModel : INotifyPropertyChanged { public PullToRefreshViewModel() { SetRowstoGenerate(100); } #region ItemsSource private OrderInfoRepository order; private ObservableCollection<OrderInfo> ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; RaisePropertyChanged("OrdersInfo"); } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { order = new OrderInfoRepository(); ordersInfo = order.GetOrderDetails(100); } #endregion private Random random = new Random(); internal void ItemsSourceRefresh() { var count = random.Next(1, 6); for (int i = 11000; i < 11000 + count; i++) { int val = i + random.Next(100, 150); this.OrdersInfo.Insert(0, order.RefreshItemsource(val)); } } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } public class LoadMoreViewModel : INotifyPropertyChanged { #region Fields private OrderInfoRepository order; private ObservableCollection<OrderInfo> ordersInfo; #endregion #region Constructor public LoadMoreViewModel() { SetRowstoGenerate(30); } #endregion #region ItemsSource public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; RaisePropertyChanged("OrdersInfo"); } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { order = new OrderInfoRepository(); ordersInfo = order.GetOrderDetails(count); } #endregion #region LoadMore Generator internal void LoadMoreItems() { for (int i = 0; i < 20; i++) this.OrdersInfo.Add(order.GenerateOrder(OrdersInfo.Count + 1)); } #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } public class PagingViewModel : INotifyPropertyChanged { public PagingViewModel() { SetRowstoGenerate(100); } #region ItemsSource private OrderInfoRepository order; private ObservableCollection<OrderInfo> ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; RaisePropertyChanged("OrdersInfo"); } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { order = new OrderInfoRepository(); ordersInfo = order.GetOrderDetails(count); } #endregion private Random random = new Random(); internal void ItemsSourceRefresh() { var count = random.Next(1, 6); for (int i = 11000; i < 11000 + count; i++) { int val = i + random.Next(100, 150); this.OrdersInfo.Insert(0, order.RefreshItemsource(val)); } } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } public class SwipingViewModel : INotifyPropertyChanged { public SwipingViewModel() { SetRowstoGenerate(100); } #region ItemsSource private OrderInfoRepository order; private ObservableCollection<OrderInfo> ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; RaisePropertyChanged("OrdersInfo"); } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { order = new OrderInfoRepository(); ordersInfo = order.GetOrderDetails(100); } #endregion private Random random = new Random(); internal void ItemsSourceRefresh() { var count = random.Next(1, 6); for (int i = 11000; i < 11000 + count; i++) { int val = i + random.Next(100, 150); this.OrdersInfo.Insert(0, order.RefreshItemsource(val)); } } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } public class DragAndDropViewModel : INotifyPropertyChanged { public DragAndDropViewModel() { SetRowstoGenerate(100); } #region ItemsSource private OrderInfoRepository order; private ObservableCollection<OrderInfo> ordersInfo; public ObservableCollection<OrderInfo> OrdersInfo { get { return ordersInfo; } set { this.ordersInfo = value; RaisePropertyChanged("OrdersInfo"); } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { order = new OrderInfoRepository(); ordersInfo = order.GetOrderDetails(count); } #endregion private Random random = new Random(); internal void ItemsSourceRefresh() { var count = random.Next(1, 6); for (int i = 11000; i < 11000 + count; i++) { int val = i + random.Next(100, 150); this.OrdersInfo.Insert(0, order.RefreshItemsource(val)); } } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(String name) { if (PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } public class UnboundColumnViewModel { public UnboundColumnViewModel() { } #region ItemsSource private ObservableCollection<Products> products; public ObservableCollection<Products> Products { get { return products; } set { this.products = value; } } #endregion #region ItemSource Generator public void SetRowstoGenerate(int count) { ProductRepository product = new ProductRepository(); products = product.GetProductDetails(100); } #endregion } public class EditingViewModel : INotifyPropertyChanged { #region Constructor public EditingViewModel() { DealerRepository dealerrep = new DealerRepository(); dealerInformation = dealerrep.GetDealerDetails(100); this.CustomerNames = dealerrep.Customers.ToObservableCollection(); } #endregion #region ItemsSource private ObservableCollection<DealerInfo> dealerInformation; public ObservableCollection<DealerInfo> DealerInformation { get { return this.dealerInformation; } set { this.dealerInformation = value; } } public ObservableCollection<string> CustomerNames { get; set; } #endregion #region Property Changed public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { var e = new PropertyChangedEventArgs(propertyName); handler(this, e); } } #endregion } public class ContextMenuModel { #region ItemSource private ObservableCollection<OrderInfo> _orderInfo; public ObservableCollection<OrderInfo> OrderInfo { get { return _orderInfo; } set { this._orderInfo = value; } } #endregion public ContextMenuModel() { OrderInfoRepository _orderInfoRepository = new OrderInfoRepository(); OrderInfo = _orderInfoRepository.GetOrderDetails(100); } } }
abc1c976b98dfdf6a8113fa80fbaf5f28f0215ad
[ "Markdown", "C#", "Shell" ]
1,474
C#
syncfusion/xamarin-demos
31c968af8304f2d65f15f542f73e5fdf9ba69a5b
1e5ba06a96f7bec5353e90917010bede7aef78c6
refs/heads/master
<repo_name>gitter-badger/gitbanner<file_sep>/src/3.bitmap2commits.sh #!/bin/sh echo "Going to create commits according to the bit value of each day"
ea27f5a036b08d0f0daad4f2f290bf7e9325fbf2
[ "Shell" ]
1
Shell
gitter-badger/gitbanner
ff50c4b38c895901397db12ba0033d01135ab277
4d2fb1a820d13b0125f729346f903849b37bcd15
refs/heads/master
<file_sep>import React, { Component } from 'react' import {View, TextInput,ListView, Text, StyleSheet, Platform, TouchableOpacity } from 'react-native' import { white } from '../utils/colors' import TextButton from './TextButton' import * as flashCardApi from '../utils/api' import {getQuestionsInOneDeck} from "../utils/api"; import {clearLocalNotification, setLocalNotification} from "../utils/notification" class CardDetail extends Component{ state ={ type:'question', currentQuestId:0, score:0, questions:[], finish: false } correct =() =>{ let score = this.state.score + 100/this.state.questions.length let currentQuestId = (this.state.currentQuestId < this.state.questions.length) && this.state.currentQuestId + 1 let finish = (currentQuestId === this.state.questions.length) ? true : false this.setState({score,currentQuestId,finish,type:'question'}) finish === true && clearLocalNotification().then(setLocalNotification()) } incorrect =() =>{ let currentQuestId = (this.state.currentQuestId< this.state.questions.length) && this.state.currentQuestId + 1 let finish = (currentQuestId === this.state.questions.length) ? true: false this.setState({currentQuestId,finish,type:'question'}) finish === true && clearLocalNotification().then(setLocalNotification()) } flipCard = (type) =>{ this.setState(()=>({ type:(type==='question')?'answer':'question' })) } startOver = () => { this.setState({ type:'question', currentQuestId:0, score:0, finish: false }) } componentDidMount() { const params = this.props.navigation.state.params const name = params ? params.name : '' getQuestionsInOneDeck(name).then( (arrReturn) => { this.setState({questions:arrReturn}) } ) } render(){ const {type, currentQuestId, score, questions} = this.state const {goBack} = this.props.navigation; return( <View> {!this.state.finish && this.state.questions.length > 0 && <View> <Text style={styles.progress}> {currentQuestId+1}/{questions.length} </Text> <Text style={styles.deckName}> {(questions.length > 0) && questions[currentQuestId][type]} </Text> <TextButton style={{margin: 20}} onPress={() => this.flipCard(type)}> {(type==='question')?'Answer':'Question'} </TextButton> <TextButton style={{margin: 20}} onPress={this.correct}> Correct </TextButton> <TextButton style={{margin: 20}} onPress={this.incorrect}> Incorrect </TextButton> </View>} {this.state.finish && this.state.questions.length > 0 &&<View> <Text style={styles.deckName}>Finish</Text> <Text style={styles.score}>Your score is {Math.round(this.state.score,0)}</Text> <TextButton style={{margin: 20}} onPress={this.startOver}> Restart Quiz </TextButton> <TextButton style={{margin: 20}} onPress={()=> goBack()}> Back to Deck </TextButton> </View> } {this.state.questions.length == 0 && <View> <Text style={styles.deckName}> Please Add Card first</Text> </View> } </View> ) } } const styles = StyleSheet.create({ progress: { fontSize: 20, paddingTop: 20, marginLeft: 10, marginRight: 10, }, deckName: { fontSize: 50, paddingTop: 50, justifyContent: 'center', alignItems: 'center', marginLeft: 10, marginRight: 10, textAlign: 'center' }, score: { fontSize: 20, paddingTop: 20, justifyContent: 'center', alignItems: 'center', marginLeft: 10, marginRight: 10, textAlign: 'center' }, deckCardNumber:{ fontSize: 20, paddingTop: 20, justifyContent: 'center', alignItems: 'center', marginLeft: 10, marginRight: 10, textAlign: 'center' } }) export default CardDetail<file_sep>#Mobile Flashcard ## Description This is a mobile application (Android or iOS - or both) that allows users to study collections of flashcards. The app will allow users to create different categories of flashcards called "decks", add flashcards to those decks, then take quizzes on those decks. This project was bootstrapped with [Create React Native App](https://github.com/react-community/create-react-native-app). ## Installation ### `npm install` You shall install all Dependency by running `npm install`. All dependency in `package.json` shall be installed. ### `npm start` Runs your app in development mode. Open it in the [Expo app](https://expo.io) on your phone to view it. It will reload if you save edits to your files, and you will see build errors and logs in the terminal. Sometimes you may need to reset or clear the React Native packager's cache. To do so, you can pass the `--reset-cache` flag to the start script: ``` npm start --reset-cache # or yarn start --reset-cache ``` ### Testing environment. This App is test with IOS simulator, and an android phone.<file_sep>import { AsyncStorage } from 'react-native' const DECK_NAME = 'MobileFlashcard:deckname' export function fetchDeckResults () { return AsyncStorage.getItem(DECK_NAME) } export function getQuestionsInOneDeck (key) { return AsyncStorage.getItem(DECK_NAME).then((results)=>{ const data = JSON.parse(results) return data[key]['questions'] }) } export function submitDeck (key) { return AsyncStorage.mergeItem(DECK_NAME, JSON.stringify({ [key]: {title:key, questions:[]} })).then(() => AsyncStorage.getItem(DECK_NAME)) } export function submitCard ( entry, key ) { return AsyncStorage.getItem(DECK_NAME) .then((results) => { const data = JSON.parse(results) data[key]['questions'].push(entry) AsyncStorage.setItem(DECK_NAME, JSON.stringify(data)) }).then(() => AsyncStorage.getItem(DECK_NAME)) } <file_sep>import { FETCH_DECK } from '../actions' function deckList (state = {}, action) { let arrReturn = {...state}; switch (action.type) { case FETCH_DECK : var {deckList} = action return { deckList } default : return state } } export default deckList<file_sep>import React, { Component } from 'react' import {View,ListView, Text, StyleSheet, Platform, TouchableOpacity } from 'react-native' import { white } from '../utils/colors' import { StackNavigator } from 'react-navigation'; import DeckEntry from "./DeckEntry"; import { fetchDeckResults } from '../utils/api' import { connect } from 'react-redux' import {fetchDeck} from "../actions"; class DeckList extends Component { componentDidMount (){ fetchDeckResults().then((items)=>{ items = JSON.parse(items) let deckList = [] Object.entries(items).map( (item) => { (1 in item ) && ('title' in item[1])&&(deckList.push({name:item[1].title, cardsNumbers:item[1].questions.length})) } ) this.props.fetchDeck(deckList) }) } renderDeck = ({name, cardsNumbers}) =>( <TouchableOpacity onPress={() => this.props.navigation.navigate( 'DeckEntry', {name} )} style ={styles.item}> <Text style={styles.deckName}> {name} </Text> <Text style={styles.deckCardNumber}> cards number: {cardsNumbers} </Text> </TouchableOpacity> ) render (){ const {deckList} = this.props const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); return ( <View> {deckList ? <ListView dataSource={ds.cloneWithRows(deckList)} renderRow={(rowData) => this.renderDeck(rowData)} /> :<Text style ={styles.deckName}> Please a new deck to start</Text> } </View> ) } } const styles = StyleSheet.create({ item: { backgroundColor: white, borderRadius: Platform.OS === 'ios' ? 16 : 2, padding: 20, marginLeft: 10, marginRight: 10, marginTop: 17, justifyContent: 'center', shadowRadius: 3, shadowOpacity: 0.8, shadowColor: 'rgba(0, 0, 0, 0.24)', shadowOffset: { width: 0, height: 3 }, alignItems: 'center', }, deckName: { fontSize: 25, paddingTop: 20, paddingBottom: 20, }, deckCardNumber:{ fontSize: 15, } }) function mapStateToProps({deckList}){ return {'deckList': deckList} } function mapDispatchToProps (dispatch) { return { fetchDeck: (deckList) => dispatch(fetchDeck(deckList)), } } export default connect( mapStateToProps, mapDispatchToProps )(DeckList) <file_sep>import React, { Component } from 'react' import {View, TextInput,ListView, Text, StyleSheet, Platform, TouchableOpacity } from 'react-native' import { white } from '../utils/colors' import TextButton from './TextButton' import * as flashCardApi from '../utils/api' import {fetchDeck} from "../actions"; import {connect} from "react-redux"; class DeckEntry extends Component{ addCard =(name) =>{ this.props.navigation.navigate( 'NewCard', {name} ) } startQuiz =(name) =>{ this.props.navigation.navigate( 'CardDetail', {name} ) } render(){ const params = this.props.navigation.state.params const name = params ? params.name : '' const {deckList} = this.props console.log(deckList); console.log(deckList.filter((deck) => deck.name === name)); const cardsNumbers = (deckList.length > 0 && deckList.filter((deck) => deck.name === name).length > 0) ? deckList.filter((deck) => deck.name === name)[0].cardsNumbers : 0 return( <View> <Text style={styles.deckName}> {name} </Text> <Text style={styles.deckCardNumber}> cards number: {cardsNumbers} </Text> <TextButton style={{margin: 20}} onPress={() => this.addCard(name)}> Add Card </TextButton> <TextButton style={{margin: 20}} onPress={() => this.startQuiz(name)}> Start Quiz </TextButton> </View> ) } } const styles = StyleSheet.create({ deckName: { fontSize: 50, paddingTop: 50, justifyContent: 'center', alignItems: 'center', marginLeft: 10, marginRight: 10, textAlign: 'center' }, deckCardNumber:{ fontSize: 20, paddingTop: 20, justifyContent: 'center', alignItems: 'center', marginLeft: 10, marginRight: 10, textAlign: 'center' } }) function mapStateToProps({deckList}){ return {'deckList': deckList} } function mapDispatchToProps (dispatch) { return { fetchDeck: (deckList) => dispatch(fetchDeck(deckList)), } } export default connect( mapStateToProps, mapDispatchToProps )(DeckEntry)<file_sep>import React, { Component } from 'react' import {View, TextInput,ListView, Text, StyleSheet, Platform, TouchableOpacity,KeyboardAvoidingView } from 'react-native' import { white } from '../utils/colors' import TextButton from './TextButton' import {submitDeck} from '../utils/api' import DeckEntry from "./DeckEntry"; import { connect } from 'react-redux' import {fetchDeck} from "../actions"; class NewDeck extends Component{ submit =(name) =>{ (name) && submitDeck(name).then((items)=>{items = JSON.parse(items) let deckList = [] Object.entries(items).map( (item) => { (1 in item ) && ('title' in item[1])&&(deckList.push({name:item[1].title, cardsNumbers:item[1].questions.length})) } ) this.props.fetchDeck(deckList)}).then(this.props.navigation.navigate( 'DeckEntry', {name} )) } render(){ let deckNameProps = ''; return( <KeyboardAvoidingView behavior="padding"> <Text style={styles.title}>What is the title of your new deck?</Text> <TextInput style={styles.content} onChangeText={(deckName) => {deckNameProps = deckName}} placeholder='Deck title' /> <TextButton style={{margin: 20}} onPress={() =>this.submit(deckNameProps)}> Submit </TextButton> </KeyboardAvoidingView> ) } } const styles = StyleSheet.create({ container:{ flex:1, alignItems: 'center', justifyContent:'center', paddingTop:30, }, title: { fontSize: 50, paddingBottom: 25, justifyContent: 'center', alignItems: 'center', marginLeft: 10, marginRight: 10, textAlign: 'center' }, content:{ height: 30, borderColor: 'gray', borderWidth: 1, marginLeft: 10, marginRight: 10, } }) function mapStateToProps({deckList}){ return {'deckList': deckList} } function mapDispatchToProps (dispatch) { return { fetchDeck: (deckList) => dispatch(fetchDeck(deckList)), } } export default connect( mapStateToProps, mapDispatchToProps )(NewDeck) <file_sep>import React from 'react'; import { StyleSheet, Text, View, Platform , StatusBar} from 'react-native'; import DeckList from './components/DeckList' import { TabNavigator, StackNavigator } from 'react-navigation' import NewDeck from './components/NewDeck' import { white, purple } from './utils/colors' import { FontAwesome, Ionicons } from '@expo/vector-icons' import { Constants } from 'expo' import CardDetail from './components/CardDetail' import DeckEntry from "./components/DeckEntry"; import NewCard from "./components/NewCard"; import reducer from './reducers' import { Provider } from 'react-redux' import { createStore } from 'redux' import {setLocalNotification} from "./utils/notification"; function UdaciStatusBar ({backgroundColor, ...props}) { return ( <View style={{ backgroundColor, height: Constants.statusBarHeight }}> <StatusBar translucent backgroundColor={backgroundColor} {...props} /> </View> ) } const Tabs = TabNavigator({ DeckList: { screen: DeckList, navigationOptions: { tabBarLabel: 'Decks', }, }, NewDeck: { screen: NewDeck, navigationOptions: { tabBarLabel: 'NEW DECK', }, }, }, { navigationOptions: { header: null }, tabBarOptions: { activeTintColor: Platform.OS === 'ios' ? purple : white, style: { height: 56, backgroundColor: Platform.OS === 'ios' ? white : purple, shadowColor: 'rgba(0, 0, 0, 0.24)', shadowOffset: { width: 0, height: 3 }, shadowRadius: 6, shadowOpacity: 1 } } }) const MainNavigator = StackNavigator({ Home: { screen: Tabs, navigationOptions: { title: "Deck List", headerTintColor: white, headerStyle: { backgroundColor: purple, } } }, CardDetail: { path: "Card Detail", screen: CardDetail, navigationOptions: { title: "Start Quiz", headerTintColor: white, headerStyle: { backgroundColor: purple, } } }, DeckEntry: { screen: DeckEntry, navigationOptions: { title: "Deck", headerTintColor: white, headerStyle: { backgroundColor: purple, } } }, NewCard: { screen: NewCard, navigationOptions: { title: "New Card", headerTintColor: white, headerStyle: { backgroundColor: purple, } } } }) export default class App extends React.Component { componentDidMount(){ setLocalNotification() } render() { return ( <Provider store={createStore(reducer)}> <View style={{flex: 1}}> <UdaciStatusBar backgroundColor={purple} barStyle="light-content" /> <MainNavigator /> </View> </Provider> ); } } <file_sep>import React, { Component } from 'react' import {View,ListView, Text, StyleSheet, Platform, TouchableOpacity,TextInput } from 'react-native' import { white } from '../utils/colors' import TextButton from './TextButton' import * as flashCardApi from '../utils/api' import {fetchDeck} from "../actions"; import {connect} from "react-redux"; class NewCard extends Component{ state ={ question:'', answer:'' } submit =(name,question,answer) =>{ const {goBack} = this.props.navigation; (question && answer) && flashCardApi.submitCard({question: question, answer: answer},name).then((items)=>{items = JSON.parse(items) let deckList = [] Object.entries(items).map( (item) => { (1 in item ) && ('title' in item[1])&&(deckList.push({name:item[1].title, cardsNumbers:item[1].questions.length})) } ) this.props.fetchDeck(deckList)}).then(()=>{goBack()}) } render(){ const params = this.props.navigation.state.params const name = params ? params.name : '' const cardsNumbers = params ? params.cardsNumbers : '' let thisAnswer = '' let thisQuestion = '' return( <View> <TextInput style={styles.input} onChangeText={(question) => thisQuestion = question } placeholder='Enter Question here' /> <TextInput style={styles.input} onChangeText={(answer) => thisAnswer = answer} placeholder='Enter Answer here' /> <TextButton style={{margin: 20}} onPress={() => this.submit(name,thisQuestion,thisAnswer)}> Submit </TextButton> </View> ) } } const styles = StyleSheet.create({ input: {height: 40, borderColor: 'gray', borderWidth: 1, justifyContent: 'center', alignItems: 'center', marginLeft: 10, marginRight: 10,} }) function mapStateToProps({deckList}){ return {'deckList': deckList} } function mapDispatchToProps (dispatch) { return { fetchDeck: (deckList) => dispatch(fetchDeck(deckList)), } } export default connect( mapStateToProps, mapDispatchToProps )(NewCard)
0b375a077644b035c1123cf2b5832c8cae2cda78
[ "JavaScript", "Markdown" ]
9
JavaScript
olivemz/mobile-flashcard
7b22a48822a03f21efc42da356a6a177dd75d3d7
fc2a52ad75380013af5d75243d66011e0be1ef6f
refs/heads/master
<repo_name>Oipo/xoroshirojs128plus<file_sep>/README.md xoroshirojs is a nodejs addon for http://xorshift.di.unimi.it/xoroshiro128plus.c. For more information see http://xorshift.di.unimi.it/. It's currently only tested on linux. # Usage `npm i --save xoroshirojs128plus` ```javascript var xoroshirojs = require('xoroshirojs128plus') var ret = xoroshirojs.seed(10, 11) for (var i = 0; i < 5; i++) { ret = xoroshirojs.next() console.log(ret) } ``` To seed the PRNG, we need a 64 bit unsigned integer. JS does not have a safe native 64 bit unsigned integer so instead we give 2 32 bit unsigned integers `xoroshirojs.seed(10, 11)`. Once seeded, use `val result = xoroshirojs.next()` to get an array of 2 32 bit unsigned integers since, again, xoroshirojs returns a 64 bit value. # Thanks Thanks to <NAME> for splitmix64 Thanks to <NAME> and <NAME> for xoroshiro128plus <file_sep>/binding.gyp { "targets": [ { "target_name": "xoroshirojs", "sources": [ "xoroshirojs.cc", "splitmix64.cc", "xoroshiro128plus.cc" ], "cflags": ["-fno-move-loop-invariants", "-fno-unroll-loops"], "include_dirs": [ "<!(node -e \"require('nan')\")" ] } ] } <file_sep>/xoroshiro128plus.cc /* Written in 2016 by <NAME> and <NAME> (<EMAIL>) To the extent possible under law, the author has dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. See <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include "xoroshiro128plus.h" /* This is the successor to xorshift128+. It is the fastest full-period generator passing BigCrush without systematic failures, but due to the relatively short period it is acceptable only for applications with a mild amount of parallelism; otherwise, use a xorshift1024* generator. Beside passing BigCrush, this generator passes the PractRand test suite up to (and included) 16TB, with the exception of binary rank tests, which fail due to the lowest bit being an LFSR; all other bits pass all tests. Note that the generator uses a simulated rotate operation, which most C compilers will turn into a single instruction. In Java, you can use Long.rotateLeft(). In languages that do not make low-level rotation instructions accessible xorshift128+ could be faster. The state must be seeded so that it is not everywhere zero. If you have a 64-bit seed, we suggest to seed a splitmix64 generator and use its output to fill s. */ uint64_t s[2]; static inline uint64_t rotl(const uint64_t x, int k) { return (x << k) | (x >> (64 - k)); } void xoroshiro_seed(uint64_t high, uint64_t low) { s[0] = high; s[1] = low; } uint64_t xoroshiro_next(void) { const uint64_t s0 = s[0]; uint64_t s1 = s[1]; const uint64_t result = s0 + s1; s1 ^= s0; s[0] = rotl(s0, 55) ^ s1 ^ (s1 << 14); // a, b s[1] = rotl(s1, 36); // c return result; } <file_sep>/package.json { "name": "xoroshirojs128plus", "version": "0.0.3", "description": "Node.js version of the PRNG xoroshiro128plus", "main": "xoroshiro.js", "private": false, "homepage": "https://github.com/Oipo/xoroshirojs128plus", "license": "MIT", "dependencies": { "bindings": "latest", "nan": "latest" }, "scripts": { "test": "node test/xoroshiro.js", "install": "node-gyp rebuild" }, "gypfile": true, "devDependencies": { "chai": "^3.5.0" }, "repository": { "type": "git", "url": "git+https://github.com/Oipo/xoroshirojs128plus.git" }, "author": "<NAME> (https://github.com/Oipo)", "bugs": { "url": "https://github.com/Oipo/xoroshirojs128plus/issues" } } <file_sep>/xoroshiro128plus.h #include <stdint.h> extern "C" { void xoroshiro_seed(uint64_t high, uint64_t low); uint64_t xoroshiro_next(void); } <file_sep>/xoroshiro.js var xoroshirojsBinding = require('bindings')('xoroshirojs.node') exports.seed = function (high, low) { return xoroshirojsBinding.seed(high, low); } exports.seedWithCurrentTime = function () { var ms = (new Date).getTime(); return xoroshirojsBinding.seed(ms%1000, ms); } exports.next = function () { return xoroshirojsBinding.next(); } <file_sep>/test/xoroshiro.js var xoroshirojs = require('../xoroshiro') var chai = require('chai'); chai.expect(xoroshirojs).to.not.be.undefined; chai.expect(xoroshirojs.seed).to.throw("Wrong arguments, expected number"); chai.expect(xoroshirojs.next).to.throw("Call Seed first before requesting a value"); var ret = xoroshirojs.seed(10, 11) chai.expect(ret).to.equal(true) for (var i = 0; i < 5; i++) { ret = xoroshirojs.next() console.log(ret) } <file_sep>/splitmix64.h #include <stdint.h> extern "C" { uint64_t splitmix64_next(uint64_t x); } <file_sep>/xoroshirojs.cc #include <nan.h> #include "splitmix64.h" #include "xoroshiro128plus.h" bool seeded = false; NAN_METHOD(Seed) { if (info.Length() != 2) { Nan::ThrowTypeError("Wrong number of arguments, expected 2"); return; } if (!info[0]->IsNumber()) { Nan::ThrowTypeError("Wrong arguments, expected number"); return; } if (!info[1]->IsNumber()) { Nan::ThrowTypeError("Wrong arguments, expected number"); return; } uint64_t arg0 = info[0]->Uint32Value(); uint64_t arg1 = info[1]->Uint32Value(); uint64_t seed = (arg0 << 32) + arg1; uint64_t seed2 = splitmix64_next(seed); xoroshiro_seed(seed, seed2); seeded = true; info.GetReturnValue().Set(true); } NAN_METHOD(Next) { if (info.Length() != 0) { Nan::ThrowTypeError("Wrong number of arguments, expected 0"); return; } if (!seeded) { Nan::ThrowTypeError("Call Seed first before requesting a value"); return; } uint64_t val = xoroshiro_next(); v8::Local<v8::Array> result = Nan::New<v8::Array>(2); Nan::Set(result, 0, Nan::New<v8::Number>((uint32_t)(val >> 32))); Nan::Set(result, 1, Nan::New<v8::Number>((uint32_t)val)); info.GetReturnValue().Set(result); } void Init(v8::Local<v8::Object> exports) { exports->Set(Nan::New("seed").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(Seed)->GetFunction()); exports->Set(Nan::New("next").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(Next)->GetFunction()); } NODE_MODULE(xoroshiro, Init)
e971cec6efd7fc00497ed941003711ee14995422
[ "JSON", "Markdown", "JavaScript", "Python", "C", "C++" ]
9
Markdown
Oipo/xoroshirojs128plus
47b1a38ef5ae913eb56e9672ac44a362d59ed5e7
c4419cc341ca34f9a46bfe3a7997ed1d972fe50e
refs/heads/master
<repo_name>offwork/custom-directive-pipe<file_sep>/src/app/custom-pipes/order-by.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'orderBy' }) export class OrderByPipe implements PipeTransform { transform(value: any | any[], key: string): any[] { if (!Array.isArray(value)) { return; } value.sort((a: any, b: any) => { if (a[key] < b[key]) { return -1; } else if (a[key] > b[key]) { return 1; } else { return 0; } }); return value; } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { TextHighlightDirective } from './custom-directives/attribute-directive/text-highlight.directive'; import { CustomForDirective } from './custom-directives/structural-directive/custom-structural.directive'; import { OrderByPipe } from './custom-pipes/order-by.pipe'; @NgModule({ declarations: [ CustomForDirective, TextHighlightDirective, OrderByPipe, AppComponent ], imports: [BrowserModule, AppRoutingModule], providers: [], bootstrap: [AppComponent] }) export class AppModule {} <file_sep>/src/app/custom-directives/attribute-directive/text-highlight.directive.ts import { Directive, Input, ElementRef, Renderer2, OnChanges, SimpleChanges } from '@angular/core'; @Directive({ selector: '[appTextHighlight]' }) export class TextHighlightDirective implements OnChanges { @Input('appTextHighlight') textToHighlight: string; @Input() color = 'yellow'; constructor(private elementRef: ElementRef, private renderer: Renderer2) {} ngOnChanges(changes: SimpleChanges): void { if (!this.elementRef.nativeElement.innerText) { return; } const innerText = this.elementRef.nativeElement.innerText; const markElement = `<mark style="background-color: ${this.color};">${ this.textToHighlight }</mark>`; const html = innerText.split(this.textToHighlight).join(markElement); this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', html); } } <file_sep>/src/app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { myCollection: any[] = [ { birthDay: 'April 15, 1968', firstName: 'Haluk', lastName: 'Levent' }, { birthDay: 'May 20, 1946', firstName: 'Müslüm', lastName: 'Gürses' }, { birthDay: 'July 12, 1942', firstName: 'Kemal', lastName: 'Sunal' }, { birthDay: 'Junuary 30, 1944', firstName: 'Hasan', lastName: 'Cemal' }, { birthDay: 'March 31, 1453', firstName: 'Ajda', lastName: 'Pekkan' }, { birthDay: 'September 10, 1990', firstName: 'Selma', lastName: 'Elma' } ]; maxElements = 4; movieQuote = ` The first rule of Fight Club is: You do not talk about Fight Club. The second rule of Fight Club is: You do not talk about Fight Club. Third rule of Fight Club: someone yells stop, goes limp, taps out, the fight is over. Fourth rule: only two guys to a fight. Fifth rule: one fight at a time, fellas. Sixth rule: no shirts, no shoes. Seventh rule: fights will go on as long as they have to. And the eighth and final rule: if this is your first night at Fight Club, you have to fight. `; } <file_sep>/src/app/custom-directives/structural-directive/custom-structural.directive.ts import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; interface RangeContext { $implicit: number; index: number; first: boolean; last: boolean; } @Directive({ selector: '[appCustomFor]' }) export class CustomForDirective { @Input() set appCustomFor(value: [number, number] | number) { this.viewContainerRef.clear(); const [from, to] = Array.isArray(value) ? value : [0, value]; const range = this.generateRange(from, to); range.forEach((itemNum, index) => this.viewContainerRef.createEmbeddedView(this.templateRef, { $implicit: itemNum, index, first: index === 0, last: index + 1 === range.length }) ); } constructor( private templateRef: TemplateRef<RangeContext>, private viewContainerRef: ViewContainerRef ) {} private generateRange(from: number = 0, to: number): number[] { return Array.from({ length: to - from }, (_, index) => index + from); } }
aff6771ed60cef43f147b3876d3f21cf398aef7d
[ "TypeScript" ]
5
TypeScript
offwork/custom-directive-pipe
2fba376a7f4299c68a09c84e373d93546975fc09
821b7b395118fcd90ce3afb4d13d15cc6bbf9b06
refs/heads/master
<file_sep>Step 1 Download the jacob DLL from below website for 64 Bit "jacob-1.18-x64.dll" 32 bit "jacob-1.18-x86.dll" https://sourceforge.net/projects/jacob-project/files/jacob-project Copy the .DLL file to your C:\Windows\System32\ folder. (32 bit) Copy the .DLL file to your C:\Windows\SysWOW64\ folder. (64 bit) Step2 Download the Jacob.jar Copy to both the below locations C:\Program Files\Java\jdk1.8.0_141\lib C:\Program Files\Java\jdk1.8.0_141\bin Refer the below website reference for development https://blogs.sap.com/2017/04/12/how-to-combine-sap-gui-scripting-and-selenium-webdriver/ For 64bit need to edit registry using following instructions https://erpinnews.com/how-to-make-sap-rot-wrapper-library-available-in-a-64-bit-environment <file_sep>package com.Samples; import java.io.IOException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.ComThread; import com.jacob.com.Dispatch; import com.jacob.com.Variant; import com.library.generic.SAPGeneric; import com.library.generic.SAPGuiClassName; public class Login extends SAPGuiClassName { /* * Declaring the ActiveXComponent Objects */ ActiveXComponent SAPROTWr, GUIApp, Connection, Session, Obj,SAPGIRD; Dispatch ROTEntry; Variant Value, ScriptEngine; private Process p; SAPGeneric sapGenric; /* * Opens the SAP Session and returns the Active Session Object */ @BeforeClass public void getSapSessionObject() throws InterruptedException{ String cnt = "0"; ComThread.InitSTA(); //Opening the SAP Logon try { p = Runtime.getRuntime().exec("C:\\Program Files\\SAP\\FrontEnd\\SAPgui\\saplogon.exe"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Thread.sleep(5000); //-Set SapGuiAuto = GetObject("SAPGUI")--------------------------- SAPROTWr = new ActiveXComponent("SapROTWr.SapROTWrapper"); ROTEntry = SAPROTWr.invoke("GetROTEntry", "SAPGUI").toDispatch(); //-Set application = SapGuiAuto.GetScriptingEngine------------ ScriptEngine = Dispatch.call(ROTEntry, "GetScriptingEngine"); GUIApp = new ActiveXComponent(ScriptEngine.toDispatch()); SAPROTWr = new ActiveXComponent("SapROTWr.SapROTWrapper"); //SAP Connection Name Connection = new ActiveXComponent( GUIApp.invoke("OpenConnection","QR1 - Retail").toDispatch()); //-Set session = connection.Children(0)----------------------- //Initialization for the SAPGeneric sapGenric = new SAPGeneric(Connection); sapGenric.setSession(new ActiveXComponent(sapGenric.getSession().invoke("FindById", "wnd[0]").toDispatch())); } /* * Logging to SAP GUI */ @Test public void LoginSAPGUI() throws InterruptedException { Thread.sleep(2000); sapGenric.SAPGUISetPasswordField("R<PASSWORD>", "username"); sapGenric.SAPGUITextFieldSet("RSYST-BNAME", "password"); sapGenric.SAPGUIEnter(); } /* * WorkBench exporting xml */ public void exportStorePosTransactions(String storenumber, String dateOfTrans, String filelocation, String filename) throws InterruptedException { Thread.sleep(5000L); sapGenric.SAPGUIOKCodeFiled("okcd", "/n/posdw/xmlo"); sapGenric.SAPGUIEnter(); Thread.sleep(2000L); sapGenric.SAPGUICTextFieldSendKeys("STORE", storenumber); sapGenric.SAPGUICTextFieldSendKeys("DAY", dateOfTrans); sapGenric.SAPGUIbtnClick("btn[8]"); } }
d3cdf2c65ce604455f2566d297e0a0915d80dde6
[ "Markdown", "Java" ]
2
Markdown
JustinH-EY/SAP-GuiClient-Automation
9eff701d8a361ce33e4b6f9a446730770aa4d16d
78dea25720c5f0c0dbb42722f0cc9df3d03063f6
refs/heads/master
<file_sep>Appium-Python-Client==0.49 selenium==4.0.0a3<file_sep>from appium.webdriver import Remote, WebElement from appium.webdriver.common.mobileby import MobileBy from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException, TimeoutException from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait class BaseElement: def __init__(self, driver: Remote, locator_value: str, locator_by: str = MobileBy.ID): self.driver = driver self.locator_value = locator_value self.locator_by = locator_by def wait_for_element(self, timeout: int = 3) -> WebElement: return WebDriverWait(driver=self.driver, timeout=timeout) \ .until(expected_conditions.presence_of_element_located((self.locator_by, self.locator_value))) def is_visible(self) -> bool: try: return self.wait_for_element().is_displayed() except (NoSuchElementException, StaleElementReferenceException, TimeoutException): return False class BaseButton(BaseElement): def __init__(self, driver: Remote, locator_value: str, locator_by: str = MobileBy.ID, return_view=None): super(BaseButton, self).__init__(driver=driver, locator_value=locator_value, locator_by=locator_by) self.return_view = return_view def click(self): self.wait_for_element().click() return self.return_view class BaseInput(BaseElement): def __init__(self, driver: Remote, locator_value: str, locator_by: str = MobileBy.ID): super(BaseInput, self).__init__(driver=driver, locator_value=locator_value, locator_by=locator_by) def set_value(self, value) -> None: self.wait_for_element().set_value(value) class BaseText(BaseElement): def __init__(self, driver: Remote, locator_value: str, locator_by: str = MobileBy.ID): super(BaseText, self).__init__(driver=driver, locator_value=locator_value, locator_by=locator_by) @property def text(self) -> str: return self.wait_for_element().text <file_sep>from appium.webdriver import Remote def setup_driver(): capabilities = dict() capabilities['deviceName'] = 'nexus_6' capabilities['platformName'] = 'Android' capabilities['appiumVersion'] = '1.15.1' capabilities['platformVersion'] = '9.0' capabilities['newCommandTimeout'] = 600 capabilities['automationName'] = 'UiAutomator2' capabilities['noReset'] = False capabilities['appPackage'] = 'com.truecaller' capabilities['appActivity'] = 'com.truecaller.ui.TruecallerInit' capabilities['appWaitActivity'] = 'com.truecaller.ui.*' driver = Remote('http://localhost:4723/wd/hub', capabilities) driver.reset() driver.start_activity(capabilities['appPackage'], capabilities['appActivity'], app_wait_activity=capabilities['appWaitActivity']) return driver <file_sep>import sys import json from driver_setup import setup_driver from views import StartView, CreateProfileView, CallsView, SearchView def get_truecaller_user_data(phone_number: str): driver = setup_driver() start_view = StartView(driver) start_view.get_started_button.click() start_view.allow_permissions() if start_view.number_button.is_visible(): start_view.number_button.click() start_view.agree_button.click() create_profile_view = CreateProfileView(driver) create_profile_view.fill_profile() calls_view = CallsView(driver) calls_view.truecaller_logo.click() search_view = SearchView(driver) search_view.search_input.set_value(phone_number) info_view = search_view.click_first_result() user_data = info_view.get_user_data() with open('output/user_data.json', 'w', encoding='utf-8') as f: json.dump(user_data, f, indent=4) driver.quit() if __name__ == "__main__": get_truecaller_user_data(sys.argv[1]) <file_sep>## Test Task This repository contains my solution to the Truecaller test task ### Required installations * Download and install Android SDK: https://developer.android.com/studio/ * Download, install and run Appium: http://appium.io/ * Having Python3 installed with pip clone the repo and navigate to the root directory. Install requirements: pip3 install requirements.txt * Install Truecaller app on a real Android device: https://play.google.com/store/apps/details?id=com.truecaller&hl=en ### How to run it * Connect your real Android device with PC via cable and enable USB debugging. Make sure WiFi or mobile data is turned on. Do NOT run the script on your real device if you are already using Truecaller app! All application data will be deleted before the run * Open command line and run truecaller.py file with a phone number as an argument ```python3 <path/to/the/file/truecaller.py> +1234567890``` Result file example: ```json { "first_name": "Test", "last_name": "Name", "email": "<EMAIL>", "location": "Ukraine" } ```<file_sep>import time from appium.webdriver import Remote from appium.webdriver.common.mobileby import MobileBy from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException, InvalidElementStateException from typing import Dict from elements import BaseButton, BaseInput, BaseText class BaseView: def __init__(self, driver: Remote): self.driver = driver self.next_button = BaseButton(driver=self.driver, locator_value='com.truecaller:id/nextButton') self.continue_button = BaseButton(driver=self.driver, locator_value='android:id/button1') self.cancel_button = BaseButton(driver=self.driver, locator_value='android:id/button2') self.next = BaseButton(driver=self.driver, locator_value='com.truecaller:id/next') class StartView(BaseView): def __init__(self, driver: Remote): super(StartView, self).__init__(driver) self.get_started_button = self.next_button self.allow_button = BaseButton(driver=self.driver, locator_value='com.android.packageinstaller:id/permission_allow_button') self.number_button = BaseButton(driver=self.driver, locator_value='com.truecaller:id/wizard_subscription_name', return_view=CreateProfileView) self.agree_button = BaseButton(driver=self.driver, locator_value='com.truecaller:id/agreeButton') def allow_permissions(self) -> None: if self.cancel_button.is_visible(): self.cancel_button.click() if self.continue_button.is_visible(): self.continue_button.click() if self.allow_button.is_visible(): for _ in range(4): self.allow_button.click() class CreateProfileView(BaseView): def __init__(self, driver: Remote): super(CreateProfileView, self).__init__(driver) self.type_name_button = BaseButton(driver=self.driver, locator_value='com.truecaller:id/manualInputButton') self.first_name_input = BaseInput(driver=self.driver, locator_value='com.truecaller:id/firstName') self.last_name_input = BaseInput(driver=self.driver, locator_value='com.truecaller:id/lastName') self.later_button = BaseButton(driver=self.driver, locator_value="//*[@text='LATER']", locator_by=MobileBy.XPATH, return_view=CallsView) def fill_profile(self) -> None: if not self.next.is_visible(): self.type_name_button.wait_for_element(timeout=30) self.type_name_button.click() self.first_name_input.set_value('Test') self.last_name_input.set_value('Name') self.next_button.click() for _ in range(3): self.next.click() self.cancel_button.click() time.sleep(1) self.cancel_button.click() self.next.click() self.later_button.click() class CallsView(BaseView): def __init__(self, driver: Remote): super(CallsView, self).__init__(driver) self.truecaller_logo = BaseButton(driver=self.driver, locator_value='com.truecaller:id/truecaller_logo', return_view=SearchView) class UserInfoView(BaseView): def __init__(self, driver: Remote): super(UserInfoView, self).__init__(driver) self.user_name_text = BaseText(driver=self.driver, locator_value='com.truecaller:id/name_or_number') self.email_text = BaseText( driver=self.driver, locator_value="(//*[contains(@resource-id,'callerDetailedUserInfoContainer')]//android.widget.TextView)[1]", locator_by=MobileBy.XPATH) self.location_text = BaseText( driver=self.driver, locator_value="(//*[contains(@resource-id,'callerDetailedUserInfoContainer')]//android.widget.TextView)[2]", locator_by=MobileBy.XPATH) def get_user_data(self) -> Dict[str, str]: user_data = dict() user_name = self.user_name_text.text.split() user_data['first_name'] = user_name[0] try: user_data['last_name'] = user_name[1] except KeyError: user_data['last_name'] = str() try: user_data['email'] = self.email_text.text except NoSuchElementException: user_data['email'] = str() try: user_data['location'] = self.location_text.text except NoSuchElementException: user_data['location'] = str() return user_data class SearchInput(BaseInput): def __init__(self, driver: Remote): super(SearchInput, self).__init__(driver=driver, locator_value='com.truecaller:id/search_field') self.camera_pop_up = BaseButton(driver=self.driver, locator_value="//*[contains(@text,'Point your camera at any phone')]", locator_by=MobileBy.XPATH) def set_value(self, value: str) -> None: if self.camera_pop_up.is_visible(): try: action = TouchAction(self.driver) action.tap(None, 241, 720).perform() except InvalidElementStateException: pass super(SearchInput, self).set_value(value=value) class SearchView(BaseView): def __init__(self, driver: Remote): super(SearchView, self).__init__(driver) self.search_input = SearchInput(driver=self.driver) def click_first_result(self) -> UserInfoView: time.sleep(3) element = BaseButton(driver=self.driver, locator_value='//androidx.recyclerview.widget.RecyclerView/android.view.ViewGroup[1]', locator_by=MobileBy.XPATH) element.click() return UserInfoView(self.driver)
9a337d490fcc0643838443504a4df36015eb2319
[ "Markdown", "Python", "Text" ]
6
Text
yevh-berdnyk/truecaller-test-task
1057a2d25bc2270ae0087c5adf9bce28b3724baf
1d62b7ce700a1ff59923c458db6ec41247b3ce46
refs/heads/master
<file_sep>/** * This library will allow the user to plot a 'SmokeChart' onto a html5 canvas element. * See the examples in '\examples' on how to use the object */ var SmokeChart = (function () { /** * Initializes a new SmokeChart object */ function SmokeChart() { // Variables-Private this._canvas = null; this._chartBox = null; this._ylabelBox = null; this._xlabelBox = null; this._yValueAverages = new Array(); } SmokeChart.prototype = { // Variables-Public XGridLinesEnabled: true, YGridLinesEnabled: true, PlotAverageEnabled: true, PlotDataEnabled: true, XLabels: new Array(), YInterval: -1.0, XLegendEnabled: true, YLegendEnabled: true, YLegendUnit: "", Data: null, Bounds: null, Parent: null, Width: 0, Height: 0, /** * Loads the data and prepares for charting * @param {} data - the data to plot in two columns (x y) */ LoadData: function (data) { var sum = new Array(); var cnt = new Array(); // initialize the arrays for (var i = 0; i < data.length; i++) { sum[data[i][0]] = 0.0; cnt[data[i][0]] = 0; } // aggregate the data for (var i = 0; i < data.length; i++) { sum[data[i][0]] += parseFloat(data[i][1]); cnt[data[i][0]]++; } // calculate the average for (var key in sum) { this._yValueAverages[key] = sum[key] / cnt[key]; } this.Data = data; }, /** * Draws the entire smoke chart. * This should be called after all settings are configured. */ Draw: function () { if (this._canvas != null) this.Parent.removeChild(this._canvas); this._canvas = document.createElement('canvas'); this._canvas.width = this.Width; this._canvas.height = this.Height; // Setup the bounds CalculateBoxes.call(this); // Plot the YStuff DrawY.call(this); // Plot the XStuff DrawX.call(this); // Plot the data DrawData.call(this); // add the chart this.Parent.appendChild(this._canvas); } } /** * Calculates the bounding boxes for the chart, before drawing. * This should be called before any 'draw' command */ function CalculateBoxes() { this._chartBox = new SmokeChartBoundingBox(0, 0, this._canvas.width, this._canvas.height); this._ylabelBox = new SmokeChartBoundingBox(0, 0, 0, this._canvas.height); this._xlabelBox = new SmokeChartBoundingBox(0, this._canvas.height, this._canvas.width, 0); // Define the Ylegend box if (this.YLegendEnabled) { var maxTextWidth = 0; var ylabel = new SmokeChartYLabel(this._canvas, this.Bounds, this._ylabelBox); for (var yline = this.Bounds.YMin; yline < this.Bounds.YMax; yline += this.YInterval) { var text = yline.toString() + this.YLegendUnit; if (ylabel.Width(text) > maxTextWidth) maxTextWidth = ylabel.Width(text); } this._ylabelBox = new SmokeChartBoundingBox(this._ylabelBox.x, this._ylabelBox.y, maxTextWidth, this._ylabelBox.height); this._xlabelBox = new SmokeChartBoundingBox(maxTextWidth, this._xlabelBox.y, this._xlabelBox.width - maxTextWidth, this._xlabelBox.height); this._chartBox = new SmokeChartBoundingBox(maxTextWidth, this._chartBox.y, this._chartBox.width - maxTextWidth, this._chartBox.height); } // Define the Xlegend box if (this.XLegendEnabled) { var maxTextHeight = 0; for (var i = 0; i < this.XLabels.length; i++) { var xlabel = new SmokeChartXLabel(this._canvas, this.Bounds, this._xlabelBox); if (xlabel.Height(this.XLabels[i].toString()) > maxTextHeight) maxTextHeight = xlabel.Height(this.XLabels[i].toString()); } this._xlabelBox = new SmokeChartBoundingBox(this._xlabelBox.x, this._xlabelBox.y - maxTextHeight, this._xlabelBox.width, maxTextHeight); this._ylabelBox = new SmokeChartBoundingBox(this._ylabelBox.x, maxTextHeight, this._ylabelBox.width, this._ylabelBox.height - maxTextHeight); this._chartBox = new SmokeChartBoundingBox(this._chartBox.x, maxTextHeight, this._chartBox.width, this._chartBox.height - maxTextHeight); } } /** * Will plot the X legend, X labels, and vertical gridlines */ function DrawX() { // Plot the text if (this.XLegendEnabled) { var xlabel = new SmokeChartXLabel(this._canvas, this.Bounds, this._xlabelBox); for (var i = 0; i < this.XLabels.length; i++) { xlabel.Draw(i + 1, this.XLabels[i].toString()); } } } /** * Will plot the Y legend, Y labels, and horizontal gridlines */ function DrawY() { if (this.YInterval < 0) { this.YInterval = this.Bounds.YRange / 10.0; } // Plot the text if (this.YLegendEnabled) { var ylabel = new SmokeChartYLabel(this._canvas, this.Bounds, this._ylabelBox); for (var yline = this.Bounds.YMin; yline < this.Bounds.YMax; yline += this.YInterval) { var text = yline.toString() + this.YLegendUnit; ylabel.Draw(yline, text); } } // Plot the gridlines if (this.YGridLinesEnabled) { var gridline = new SmokeChartLineHoriz(this._canvas, this.Bounds, this._chartBox); for (var yline = this.Bounds.YMin; yline < this.Bounds.YMax; yline += this.YInterval) { gridline.Draw(yline); } } } /** * Plot the data onto the chart */ function DrawData() { var valueAverage = new SmokeChartValueLine(this._canvas, this.Bounds, this._chartBox); var valueBox = new SmokeChartValueBox(this._canvas, this.Bounds, this._chartBox); for (var i = 1; i < this.Data.length; i++) { if (this.PlotDataEnabled) valueBox.Draw(this.Data[i][1], this._yValueAverages[this.Data[i][0]], this.Data[i][0]); if (this.PlotAverageEnabled) valueAverage.Draw(this._yValueAverages[this.Data[i][0]], this.Data[i][0]); } } return SmokeChart; })(); var SmokeChartValueLine = (function () { /** * Initializes a new instance of the SmokeChartValueLine class * @param {} canvas - The html5 canvas element to draw on * @param {} bounds - The graph bounds (x/y scales) * @param {} box - The drawing boundry box, pixel based */ function SmokeChartValueLine(canvas, bounds, box) { this._canvas = canvas; this._bounds = bounds; this._box = box; } SmokeChartValueLine.prototype = { // Public Variables style: "rgba(0, 200, 50, 1.0)", lineWidth: 1, /** * Draws a smoke line at the specified X/Y value * @param {} yValue - The y-value to draw the line at * @param {} xIndex - The x-index to draw the line at */ Draw: function (yValue, xIndex) { // calculate the bounds of the line var widthPixel = this._box.width / this._bounds.XRange; var leftPixel = this._box.left + (xIndex - this._bounds.XMin) * widthPixel; var rightPixel = this._box.left + (xIndex - this._bounds.XMin + 1) * widthPixel; var heightPixel = this._box.height - (((yValue - this._bounds.YMin) / this._bounds.YRange) * this._box.height); // force the heightPixel to be 0.5, to get a crisp line on the canvas var heightPixel = Math.round(heightPixel) + 0.5; // draw the line var content = this._canvas.getContext("2d"); content.beginPath(); content.moveTo(leftPixel, heightPixel); content.lineTo(rightPixel, heightPixel); content.lineWidth = this.lineWidth; content.strokeStyle = this.style; content.stroke(); } } return SmokeChartValueLine; })(); var SmokeChartBoundingBox = (function() { /** * Initializes a new instance of the SmokeChartBoundingBox class * @param {} x - The x coordinate of the bounding box * @param {} y - The y coordinate of the bounding box * @param {} width - The width of the bounding box * @param {} height - The height of the bounding box */ function SmokeChartBoundingBox(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; } SmokeChartBoundingBox.prototype = { x: 0, y: 0, width: 0, height: 0, get top() { return this.y; }, get bottom() { return this.y + this.height; }, get left() { return this.x; }, get right() { return this.x + this.width; } } return SmokeChartBoundingBox; })(); var SmokeChartLineHoriz = (function () { /** * Initializes a new instance of the SmokeChartLineHoriz class * @param {} canvas - The html5 canvas element to draw on * @param {} bounds - The graph bounds (x/y scales) * @param {} box - The drawing boundry box, pixel based */ function SmokeChartLineHoriz(canvas, bounds, box) { this._canvas = canvas; this._bounds = bounds; this._box = box; } SmokeChartLineHoriz.prototype = { // Public Variables style: "rgba(10, 10, 10, 0.15)", lineWidth: 1, /** * Draws a gridline specified Y value * @param {} yValue - The y-value to draw the line at */ Draw: function (yvalue) { // calculate the bounds of the line var heightPixel = this._box.height - (((yvalue - this._bounds.YMin) / this._bounds.YRange) * this._box.height); // force the heightPixel to be 0.5, to get a crisp line var heightPixel = Math.round(heightPixel) + 0.5; // draw the line var content = this._canvas.getContext("2d"); content.beginPath(); content.moveTo(this._box.x, heightPixel); content.lineTo(this._box.x + this._box.width, heightPixel); content.lineWidth = this.lineWidth; content.strokeStyle = this.style; content.stroke(); } } return SmokeChartLineHoriz; })(); var SmokeChartYLabel = (function() { /** * Initializes a new instance of the SmokeChartLineHoriz class * @param {} canvas - The html5 canvas element to draw on * @param {} bounds - The graph bounds (x/y scales) * @param {} box - The drawing boundry box, pixel based */ function SmokeChartYLabel(canvas, bounds, box) { this._canvas = canvas; this._bounds = bounds; this._box = box; } SmokeChartYLabel.prototype = { font: "12px sans-serif", /** * Draws a label at the specified Y value * @param {} yValue - The y-value to draw the text at * @param {} text - The text to draw */ Draw: function (yValue, text) { var heightPixel = this._box.height - (((yValue - this._bounds.YMin) / this._bounds.YRange) * this._box.height); var content = this._canvas.getContext("2d"); content.font = this.font; content.textBaseline = 'middle'; content.fillText(text, this._box.left, heightPixel); }, /** * Gets the width of the text * @param {} text - The text to get the width of */ Width: function (text) { var content = this._canvas.getContext("2d"); content.font = this.font; return content.measureText(this.Text).width; } } return SmokeChartYLabel; })(); var SmokeChartXLabel = (function() { /** * Initializes a new instance of the class * @param {} canvas - The html5 canvas element to draw on * @param {} bounds - The graph bounds (x/y scales) * @param {} box - The drawing boundry box, pixel based */ function SmokeChartXLabel(canvas, bounds, box) { this._canvas = canvas; this._bounds = bounds; this._box = box; } SmokeChartXLabel.prototype = { font: "12px sans-serif", /** * Draws a label at the specified X value * @param {} xIndex - The x-value to draw the text at * @param {} text - The text to draw */ Draw: function (xIndex, text) { var widthPixel = this._box.width / this._bounds.XRange; var leftPixel = this._box.left + (xIndex - this._bounds.XMin) * widthPixel; var rightPixel = this._box.left + (xIndex - this._bounds.XMin + 1) * widthPixel; var content = this._canvas.getContext("2d"); content.font = this.font; content.textAlign = 'center'; content.textBaseline = 'bottom'; content.fillText(text, (leftPixel + rightPixel) / 2, this._box.bottom); }, Height: function (canvas) { return 12 + 2; } } return SmokeChartXLabel; })(); var SmokeChartValueBox = (function() { /** * Initializes a new instance of the class * @param {} canvas - The html5 canvas element to draw on * @param {} bounds - The graph bounds (x/y scales) * @param {} box - The drawing boundry box, pixel based */ function SmokeChartValueBox(canvas, bounds, box) { this._canvas = canvas; this._bounds = bounds; this._box = box; } SmokeChartValueBox.prototype = { fillStyle: "rgba(10, 10, 10, 0.1)", /** * Draws a value box at the coordinates specified * @param {} xIndex - The x-value to draw the box at * @param {} lower - The lower value to start the box * @param {} upper - The upper value to start the box */ Draw: function(lower, upper, xIndex) { var widthPixel = this._box.width / this._bounds.XRange; var heightPixels = this._box.height / this._bounds.YRange; var leftPixel = this._box.left + (xIndex - this._bounds.XMin) * widthPixel; var rightPixel = this._box.left + (xIndex - this._bounds.XMin + 1) * widthPixel; var upperPixel = this._box.height - (((upper - this._bounds.YMin) / this._bounds.YRange) * this._box.height); var lowerPixel = this._box.height - (((lower - this._bounds.YMin) / this._bounds.YRange) * this._box.height); var content = this._canvas.getContext("2d"); var gradFill = content.createLinearGradient(leftPixel, upperPixel, leftPixel, lowerPixel); gradFill.addColorStop(0.0, "rgba(40, 40, 40, 0.5)"); gradFill.addColorStop(0.5, "rgba(40, 40, 40, 0.3)"); gradFill.addColorStop(1.0, "rgba(40, 40, 40, 0.00)"); content.fillStyle = gradFill; content.fillRect(leftPixel, lowerPixel, rightPixel - leftPixel, upperPixel - lowerPixel); } } return SmokeChartValueBox; })(); var SmokeChartBounds = (function() { /** * Initializes a new instance of the class * @param {} xmin - the lowest x value * @param {} xmax - the largest x value * @param {} ymin - the lowest y value * @param {} ymax - the largest y value */ function SmokeChartBounds(xmin, xmax, ymin, ymax) { this.XMin = Math.max(xmin, 0); this.XMax = Math.max(xmax, 0); this.YMin = Math.max(ymin, 0); this.YMax = Math.max(ymax, 0); } SmokeChartBounds.prototype = { XMin: 0, XMax: 0, YMin: 0, YMax: 0, get YRange() { return Math.abs(this.YMax - this.YMin) + 1; }, get XRange() { return Math.abs(this.XMax - this.XMin) + 1; } } return SmokeChartBounds; })(); <file_sep># SmokeChartJS This library provides an easy way to draw 'Smoke Chart' style charts. I really liked the 'Smoke Ping' style charts provided by [DslReports.com](https://www.dslreports.com/smokeping) and wasn't able to find a library to generate such a chart (I was probably looking for the wrong name of chart...). So I made this. ## Example Output This is the output from loading 'index.html' in the examples folder. It shows the kilometers and MPG that I have tracked for my 2007 Honda Fit over the years. ![Cool Chart](/screenshot.png?raw=true "Example Output")
619f16aa19be30193446568c2621dd596ba07316
[ "JavaScript", "Markdown" ]
2
JavaScript
smpickett/SmokeChartJS
af87515d54bd33ccd9fe3abe9262e36fab420029
47474ac13f3e47524cd63fae18d8ec5639763acd
refs/heads/master
<repo_name>fifteen1/ZhangShuaiKang20180709<file_sep>/app/src/main/java/view/myView.java package view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import bwie.com.zhangshuaikang20180709.R; public class myView extends View{ private Paint paint; private Bitmap bpBackground; private Bitmap bpForeground; private Canvas canvas; private Paint contentPaint; private String content = "刮刮看~"; private Path path; public myView(Context context) { super(context); init(); } public myView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } private void init(){ paint = new Paint(); paint.setAlpha(0); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(50); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); paint.setStrokeJoin(Paint.Join.ROUND); paint.setStrokeCap(Paint.Cap.ROUND); path = new Path(); bpBackground = BitmapFactory.decodeResource(getResources(), R.drawable.text); bpForeground = Bitmap.createBitmap(bpBackground.getWidth(), bpBackground.getHeight(), Bitmap.Config.ARGB_8888); canvas = new Canvas(bpForeground); contentPaint = new Paint(); contentPaint.setColor(Color.WHITE); contentPaint.setTextSize(100); contentPaint.setStrokeWidth(20); canvas.drawColor(Color.GRAY); canvas.drawText(content,canvas.getWidth(),canvas.getHeight(),contentPaint); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: path.reset(); path.moveTo(event.getX(),event.getY()); break; case MotionEvent.ACTION_MOVE: path.lineTo(event.getX(),event.getY()); break; } canvas.drawPath(path,paint); invalidate(); return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(bpBackground,0,0,null); canvas.drawBitmap(bpForeground,0,0,null); } }
9e3622ff2399a0585ccb70956f089a2bd262f9c1
[ "Java" ]
1
Java
fifteen1/ZhangShuaiKang20180709
4180cd6617e89481c1fde982d5d1829b90a625da
303100869f1cf9d510630611b3a1642560f0dcf2
refs/heads/master
<file_sep>import sys from shutil import which import os from os import path, getcwd from flask import Flask, request, jsonify from flask_cors import CORS import config from util import read_csv_file, parse_date, is_git_dir from cli import CLI working_dir = sys.argv[1] if len(sys.argv) > 1 else getcwd() app = Flask(__name__) CORS(app) app.config.from_object(config) app.config['GIT_DIR'] = working_dir # Check setting if not which(app.config['JAVA_COMMAND']): raise AssertionError("Java command, %s, does not exist." % app.config['JAVA_COMMAND']) if not which(app.config['GIT_COMMAND']): raise AssertionError("Git command, %s, does not exist." % app.config['GIT_COMMAND']) if not path.isfile(app.config['CODE_MAAT_JAR_FILE']): raise AssertionError("Code Maat jar file, %s, does not exist." % app.config['CODE_MAAT_JAR_FILE']) if not is_git_dir(working_dir): raise AssertionError("Directory, %s, is not a git repo." % app.config['GIT_DIR']) # Object cli = CLI( code_maat_jar_file=app.config['CODE_MAAT_JAR_FILE'], git_command=app.config['GIT_COMMAND'], java_command=app.config['JAVA_COMMAND'], git_dir=app.config['GIT_DIR']) # Routing @app.route('/api/', methods=['GET']) def blank(): pass @app.route('/api/commits', methods=['GET']) def commit_entries(): return jsonify(cli.get_commits()) def delete_dir_files(cache_dir): filelist = [f for f in os.listdir(cache_dir)] for f in filelist: os.remove(path.join(cache_dir, f)) @app.route('/api/code-maat', methods=['DELETE']) def clear_log_files(): cache_dir = cli.log_dir delete_dir_files(cache_dir) return jsonify({ "message": "Log directory is now cleared.", "logDir": cache_dir}) @app.route('/api/code-maat', methods=['GET']) def log_file(): analysis = request.args.get('analysis') start_date = request.args.get('start-date') end_date = request.args.get('end-date') # Parameter try: start_date = parse_date(start_date) except: return ("ERROR: Start date can't be parsed by YYYY-MM-DD format.", 400) try: end_date = parse_date(end_date) except: return ("ERROR: End date can't be parsed by YYYY-MM-DD format.", 400) # Validate if start_date > end_date: return ("ERROR: Start date can't be ahead of the end date.", 400) # Logic log_file = cli.generate_log_file(start_date, end_date) if analysis is None or analysis == 'summary': return jsonify(read_csv_file(cli.generate_summary_file(log_file))) elif analysis == 'revision': return jsonify(read_csv_file(cli.generate_revision_file(log_file))) elif analysis == 'coupling': return jsonify(read_csv_file(cli.generate_coupling_file(log_file))) elif analysis == 'age': return jsonify(read_csv_file(cli.generate_age_file(log_file))) elif analysis == 'abs-churn': return jsonify( read_csv_file(cli.generate_absolute_churn_file(log_file))) elif analysis == 'author-churn': return jsonify( read_csv_file(cli.generate_author_churn_file(log_file))) elif analysis == 'entity-churn': return jsonify( read_csv_file(cli.generate_entity_churn_file(log_file))) elif analysis == 'entity-ownership': return jsonify( read_csv_file(cli.generate_entity_ownership_file(log_file))) elif analysis == 'entity-effort': return jsonify( read_csv_file(cli.generate_entity_effort_file(log_file))) else: return ("ERROR: Analysis type not in selection.", 400) app_port = 30080 if __name__ == '__main__': app.run(host='0.0.0.0', port=app_port) <file_sep>from werkzeug.routing import BaseConverter from datetime import datetime class PeriodConverter(BaseConverter): _period_format = "%Y%m%d" def to_python(self, text): return datetime.strptime(text, PeriodConverter._period_format) def to_url(self, date): return datetime.strftime(date, PeriodConverter._period_format) <file_sep>aniso8601==1.2.1 appdirs==1.4.3 click==6.7 Flask==0.12.1 Flask-Cors==3.0.2 itsdangerous==0.24 Jinja2==2.9.6 MarkupSafe==1.0 packaging==16.8 pyparsing==2.2.0 python-dateutil==2.6.0 pytz==2017.2 six==1.10.0 tornado==4.5.1 Werkzeug==0.12.1 <file_sep>from os.path import join from os import getcwd DEBUG = True GIT_COMMAND = 'git' JAVA_COMMAND = 'java' CODE_MAAT_JAR_FILE = join(getcwd(), 'code-maat.jar') <file_sep>from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from app import app, app_port server = HTTPServer(WSGIContainer(app)) server.listen(app_port) IOLoop.instance().start() <file_sep>from datetime import datetime as dt from os.path import join, isdir import csv import json def read_csv_file(csv_file): with open(csv_file, 'r') as f: reader = csv.reader(f) headers = next(reader) return [dict(zip(headers, row)) for row in reader] def parse_date(text): return dt.strptime(text, "%Y-%m-%d") def is_git_dir(git_dir): git_dot_dir = join(git_dir, ".git") return isdir(git_dot_dir) <file_sep>from datetime import datetime from os.path import join, isfile, isdir, splitext from os import getcwd, makedirs, chdir from subprocess import check_output class CLI: def __init__(self, code_maat_jar_file=join(getcwd(), 'code-maat.jar'), git_command='git', java_command='java', log_dir=None, git_dir=getcwd(), **_keywords): self.git_dir = git_dir self.log_dir = log_dir if log_dir else join(git_dir, '.logs') self.git_command = git_command self.java_command = java_command self.code_maat_jar_file = code_maat_jar_file self.cache = True if not isdir(self.log_dir): makedirs(self.log_dir) def generate_log_file(self, start_date=datetime.now(), end_date=datetime.now()): start_format = datetime.strftime(start_date, "%Y-%m-%d") end_format = datetime.strftime(end_date, "%Y-%m-%d") log_file_name = "log--%s--%s.log" % (start_format, end_format) log_file = join(self.log_dir, log_file_name) if self.cache and isfile(log_file): return log_file log_output = self._execute_git( "log", "--pretty=format:[%h] %aN %ad %s", "--date=short", "--numstat", ("--after=%s" % start_format), ("--before=%s" % end_format)) with open(log_file, 'wb') as f: f.write(log_output) return log_file def generate_summary_file(self, log_file): command_file = self._rename_extension(log_file, "--summary.csv") if self.cache and isfile(command_file): return command_file command_output = self._execute_code_maat( log_file, "summary") with open(command_file, 'wb') as f: f.write(command_output) return command_file def generate_coupling_file(self, log_file): command_file = self._rename_extension(log_file, "--coupling.csv") if self.cache and isfile(command_file): return command_file command_output = self._execute_code_maat( log_file, "coupling") with open(command_file, 'wb') as f: f.write(command_output) return command_file def generate_revision_file(self, log_file): command_file = self._rename_extension(log_file, "--revision.csv") if self.cache and isfile(command_file): return command_file command_output = self._execute_code_maat( log_file, "revisions") with open(command_file, 'wb') as f: f.write(command_output) return command_file def generate_age_file(self, log_file): command_file = self._rename_extension(log_file, "--age.csv") if self.cache and isfile(command_file): return command_file command_output = self._execute_code_maat( log_file, "age") with open(command_file, 'wb') as f: f.write(command_output) return command_file def generate_absolute_churn_file(self, log_file): command_file = self._rename_extension(log_file, "--absolute-churn.csv") if self.cache and isfile(command_file): return command_file command_output = self._execute_code_maat( log_file, "abs-churn") with open(command_file, 'wb') as f: f.write(command_output) return command_file def generate_author_churn_file(self, log_file): command_file = self._rename_extension(log_file, "--author-churn.csv") if self.cache and isfile(command_file): return command_file command_output = self._execute_code_maat( log_file, "author-churn") with open(command_file, 'wb') as f: f.write(command_output) return command_file def generate_entity_churn_file(self, log_file): command_file = self._rename_extension(log_file, "--entity-churn.csv") if self.cache and isfile(command_file): return command_file command_output = self._execute_code_maat( log_file, "entity-churn") with open(command_file, 'wb') as f: f.write(command_output) return command_file def generate_entity_ownership_file(self, log_file): command_file = self._rename_extension( log_file, "--entity-ownership.csv") if self.cache and isfile(command_file): return command_file command_output = self._execute_code_maat( log_file, "entity-ownership") with open(command_file, 'wb') as f: f.write(command_output) return command_file def generate_entity_effort_file(self, log_file): command_file = self._rename_extension( log_file, "--entity-effort.csv") if self.cache and isfile(command_file): return command_file command_output = self._execute_code_maat( log_file, "entity-effort") with open(command_file, 'wb') as f: f.write(command_output) return command_file def get_commits(self): text = self._execute_git('log', '--format=%cI,%H').decode('utf-8') lines = text.split("\n") entries = [line.split(",") for line in lines] return [dict([ ['commitDate', entry[0]], ['commitHash', entry[1]] ]) for entry in entries] def _rename_extension(self, raw_file, new_extension): return splitext(raw_file)[0] + new_extension def _execute_git(self, command, *cli_args): temp_dir = getcwd() chdir(self.git_dir) output = check_output([ self.git_command, command, *cli_args]).strip() chdir(temp_dir) return output def _execute_code_maat(self, log_file, command, *extra_args): temp_dir = getcwd() chdir(self.git_dir) output = check_output([ self.java_command, "-jar", self.code_maat_jar_file, "-l", log_file, "-c", "git", "-a", command, *extra_args]).strip() chdir(temp_dir) return output
42f10e19936beee99788353720d2ab2d591109e6
[ "Python", "Text" ]
7
Python
Rada75/code_maat_server
eb61492370d4d9a6107d0755042f1f098e84490b
aca307bce8b6141b330542140f550e037aeb915f
refs/heads/master
<file_sep>import { createServer } from 'http' import * as next from 'next' import * as path from 'path' import { parse } from 'url' import { validateStaticPath } from './static_assets' const port = parseInt(process.env.PORT, 10) || 3000 const dev = process.env.NODE_ENV !== 'production' const app = next({ dev }) const handle = app.getRequestHandler() app.prepare().then(() => { createServer((req, res) => { const parsedUrl = parse(req.url, true) const { pathname } = parsedUrl // Next.js server-rendered routes: // if (pathname === '/path') app.render(req, res, '/path', query) const resolveStatic = validateStaticPath( path.join(__dirname, '../static', pathname), ) if (!!resolveStatic) { app.serveStatic(req, res, resolveStatic) } else { handle(req, res, parsedUrl) } }).listen(port, () => { console.log(`> Ready on http://localhost:${port}`) }) }) <file_sep>import MapboxGL from 'mapbox-gl' export const setAccessToken = (token: string | undefined) => { if (token) { (MapboxGL as any).accessToken = token return true } else { throw new Error('Mapbox token is unset.') } } <file_sep>export const skills = [ { label: 'TypeScript', url: 'https://www.typescriptlang.org/', }, { label: 'Elixir', url: 'https://elixir-lang.org/', }, { label: 'Phoenix', url: 'https://phoenixframework.org/', }, { label: 'React.js', url: 'https://reactjs.org/', }, { label: 'PostgreSQL', url: 'https://www.postgresql.org/', }, { label: 'SQL', }, { label: 'Elm', url: 'https://elm-lang.org/', }, { label: 'Node.js', url: 'https://nodejs.org/', }, { label: 'Ruby', url: 'https://www.ruby-lang.org/', }, { label: 'Rails', url: 'https://rubyonrails.org/', }, { label: 'PHP', url: 'http://www.php.net/', }, { label: 'Bash', url: 'https://www.gnu.org/software/bash/', }, { label: 'GraphQL', url: 'https://graphql.org/', }, { label: 'RESTful Design', }, { label: 'webpack', url: 'https://webpack.js.org/', }, { label: 'npm', url: 'https://www.npmjs.com/', }, { label: 'Amazon Web Services', url: 'https://aws.amazon.com/', }, { label: 'Docker', url: 'https://www.docker.com/', }, { label: 'CI/CD', }, { label: 'Unit & Integration Testing', }, { label: 'Functional Programming', url: 'https://wikipedia.org/wiki/Functional_programming', }, { label: 'Scrum & Kanban Methodologies', }, { label: 'Test Driven Development', }, { label: 'UX Design', }, { label: 'WordPress', url: 'https://wordpress.org/', }, { label: 'Google Analytics', url: 'https://analytics.google.com/', }, ] export const interests = [ '✈️Travel', '🐠Scuba Diving', '🏋🏼‍♂️CrossFit', '🚴🏼‍♂️Cycling', '🏄🏼‍♂️ Surfing', '🛶 Kayaking', '🌳 Outdoors', '🐘Alabama Football 🏈', '🐷 BBQ', '🌴 <NAME>', '🎸 Music History', ] <file_sep>export const IS_PROD = process.env.NODE_ENV === 'production' export const GTM_CONTAINER_ID = '133182568-1' export const GTM_SRC_URL = `https://www.googletagmanager.com/gtag/js?id=${GTM_CONTAINER_ID}` export const GOOGLE_FONTS_BASE_URL = 'https://fonts.googleapis.com/css?family=' export const GOOGLE_FONTS = [ 'Ubuntu+Mono', 'Playfair+Display', 'Raleway:400,600,800', ] <file_sep>// // @todo: iOS app in React Native to persist coordinates // from phone locations services, once data store configured. // type Cities = | 'bogota' | 'london' | 'medellin' | 'summerdale' | 'dc' | 'sanandres' | 'santamarta' | 'cartagena' | 'cdmx' | 'cabo' export interface ICoord { lat: number lng: number } export type ICoordinates = { [key in Cities]: ICoord } export const coordinates: ICoordinates = { bogota: { lat: 4.711, lng: -74.072, }, london: { lat: 51.489, lng: -0.144, }, medellin: { lat: 6.244, lng: -75.581, }, summerdale: { lat: 30.4877, lng: -87.6997, }, dc: { lat: 38.9, lng: -77.03, }, sanandres: { lat: 12.57, lng: -81.7, }, santamarta: { lat: 11.24, lng: -74.21, }, cartagena: { lat: 10.39, lng: -75.48, }, cdmx: { lat: 19.43, lng: -99.13, }, cabo: { lat: 22.89, lng: -109.91, }, } const CURRENT_CITY = process.env.CURRENT_CITY as Cities export const current = coordinates[CURRENT_CITY] || coordinates.london export default coordinates <file_sep>import { existsSync } from 'fs' import * as path from 'path' const ALLOWED_STATIC_EXT = [ '.ico', '.png', '.jpg', '.gif', '.webmanifest', '.txt', '.xml', ] export const validateStaticPath = (pathname: string): false | string => { const ext = path.extname(pathname) const exists = existsSync(pathname) if (ALLOWED_STATIC_EXT.includes(ext) && exists) { return pathname } else { return false } } <file_sep># <NAME> > Personal Portfolio Web Application [https://jaredhugh.es](https://jaredhugh.es) Based on [Next.js Custom server with TypeScript + Nodemon example](https://github.com/zeit/next.js/tree/canary/examples/custom-server-typescript). ### Usage - `npm run dev`: Start the application locally in development mode - `npm run build`: Compile and output static application to `dist` - `npm start`: Compile the application and start the HTTP server
5e98b7aa5410c1bb8d06a0ccee04485e4eca70ef
[ "Markdown", "TypeScript" ]
7
TypeScript
jaredhughes/jaredhugh.es
4b5d29807348eb49b6ea589aeac2a19e12c27e20
9d0fd2e7b9ce75ccd7aba2ab2107cc235c7df8a2
refs/heads/master
<file_sep>from flask import Flask, render_template, request, redirect, session from flask_sqlalchemy import SQLAlchemy from datetime import datetime import json # Opening and reading the json file. with open('config.json', 'r') as jsonfile: params = json.load(jsonfile)["params"] # Creating a Flask application object app = Flask(__name__) app.secret_key = 'secret-key' local_server = True # adding DATABASE to flask app if (local_server): app.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri'] else: app.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri'] # Creating an object of SQLAlchemy class with application object as the parameter. db = SQLAlchemy(app) @app.route("/index") def home(): return render_template('index.html', params=params) @app.route("/about") def about(): return render_template('about.html', params=params) class Contacts(db.Model): sno = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=False, nullable=False) number = db.Column(db.String(12), unique=True, nullable=False) email = db.Column(db.String(50), unique=True, nullable=False) msg = db.Column(db.String(100), unique=False, nullable=True) date = db.Column(db.String(12), unique=False, nullable=False) @app.route("/contact", methods=['GET', 'POST']) def contact(): if request.method == 'POST': '''Add entry to database''' # fetching values from the form filled by user name = request.form.get('name') email = request.form.get('email') message = request.form.get('msg') phone = request.form.get('number') # storing the fetched data from form during run time to the database entry = Contacts(name=name, email=email, msg=message, number=phone, date=datetime.now()) db.session.add(entry) db.session.commit() return render_template('contact.html', params=params) class Posts(db.Model): sno = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(50), unique=False, nullable=False) slug = db.Column(db.String(25), unique=True, nullable=False) content = db.Column(db.String(120), unique=True, nullable=False) date = db.Column(db.String(12), unique=False, nullable=False) blogger = db.Column(db.String(25), unique=True, nullable=False) @app.route("/post/<string:post_slug>", methods=['GET']) def post_route(post_slug): # query to connect to sql_alchemy database fetched_post = Posts.query.filter_by(slug=post_slug).first() # returning the fetched "post" from DB to the frontend return render_template('post.html', params=params, post=fetched_post) @app.route("/dashboard", methods=['GET', 'POST']) def dash(): # Before starting session dont forget to set the secret key # Checking in casae user is already logged in if 'users' in session and session['users'] == 'shaurya@singh': # If user is logged he mush able to see all the post with edit and delete options # Fetching data from the Posts Table by executing below query posts_db = Posts.query.all() # passing 'params' from config.json and 'post' query results from DB to dashboard.html return render_template('dashboard.html', params=params, posts=posts_db) # In case of post request if request.method == 'POST': # getting the entered user and password from frontend user_mail = request.form.get('email') password = request.form.get('password') if user_mail == 'sha<EMAIL>' and password == '<PASSWORD>': # Starting SESSION in case user is authenticated session['users'] = user_mail post = Posts.query.all() return render_template('dashboard.html', params=params,post=post) else: return render_template('login.html', params=params) # In case of GET(default one) request else: return render_template('login.html', params=params) @app.route("/edit/<string : sno>" , methds=['GET','POST']) def post_edit(sno): # If User is logged in only then EDIT is allowed if 'users' in session and session['users'] == 'shaurya@singh': if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True) <file_sep># Blog-writting-app-using-FLASK
ba8bbd0dedb581d66cac40d8a5d9f1de07221216
[ "Markdown", "Python" ]
2
Python
shaurya2611/Blog-writting-app-using-FLASK
c11e5dfc7d9a07e9d1d6feeab5a98b776d0182c7
19697eb2fe7898d530863643892439ae7a52ed54
refs/heads/master
<file_sep># <NAME>'s vim distribution ## Usage git clone git://github.com/ancorcruz/vimfiles.git ~/.vim cd ~/.vim rake install ### Helptags To generate tags at first usage of vim invoke: :Helptags This makes all plugins documentations available thru :help ### Updating cd ~/.vim rake update ## Customization Add your local customizations in ~/.vimrc.local and ~/.gvimrc.local ## Mappings * Leader + p => Toggle NERDTree * Leader + c => Clean out all trailing whitespace or tabs * Leader + t => Open Command-t dialog * Tab => Next tab * Shift + Tab => Previous tab * Alt + (1-9) => Switch tabs * Ctrl + n => New tab (Leader = \\) ## Bundled plugins ### Command-t The Command-T plug-in for VIM provides an extremely fast, intuitive mechanism for opening files with a minimal number of keystrokes. It's named "Command-T" because it is inspired by the "Go to File" window bound to Command-T in TextMate. https://github.com/wincent/Command-T http://www.vim.org/scripts/script.php?script_id=3025 ### delimitMate Provides insert mode auto-completion for quotes, parens, brackets, etc https://github.com/Raimondi/delimitMate ### Endwise Wisely add "end" in ruby, endfunction/endif/more in vim script, etc https://github.com/tpope/vim-endwise ### Fugitive A Git wrapper so awesome. https://github.com/tpope/vim-fugitive ### NerdTree Tree explorer. Open with leader+p http://www.vim.org/scripts/script.php?script_id=1658 ### Pathogen Makes it super easy to install plugins and runtime files in their own private directories. https://github.com/tpope/vim-pathogen ### Rails Rails support for vim https://github.com/tpope/vim-rails http://www.vim.org/scripts/script.php?script_id=1567 ### Ruby Ruby support for vim https://github.com/vim-ruby/vim-ruby https://github.com/vim-ruby/vim-ruby/wiki ### RVM Switch Ruby versions from inside Vim https://github.com/tpope/vim-rvm ### Solarized Precision colors for machines and people https://github.com/altercation/vim-colors-solarized ### Supertab Pseudo auto-complete with tab http://www.vim.org/scripts/script.php?script_id=1643 https://github.com/ervandew/supertab ### Syntastic Syntax checking hacks for vim https://github.com/scrooloose/syntastic/ http://www.vim.org/scripts/script.php?script_id=2736 ### Vividchalk A colorscheme strangely reminiscent of Vibrant Ink for a certain OS X editor https://github.com/tpope/vim-vividchalk ## ToDo * Add some mappings * Add snipets * And more ## Credits <NAME>'s Vimfiles released under MIT License<br/> Special thanks to <NAME>, <NAME>, <NAME>, <NAME>, etc. <file_sep>desc "Install Vimfiles" task :install do system "git submodule update --init" system "ln -sf ~/.vim/vimrc ~/.vimrc" system "ln -sf ~/.vim/gvimrc ~/.gvimrc" compile_command_t end desc "Update Vimfiles" task :update do system "git pull" system "git submodule sync" system "git submodule update --init --recursive" compile_command_t end # Compile Command-t plugin def compile_command_t system "cd #{File.join File.dirname(__FILE__), 'bundle', 'command-t'} && rake make" end
e1d28d7d5fe229ca33e679472e6d8b7c3a08b062
[ "Markdown", "Ruby" ]
2
Markdown
crguezl/vimfiles
214b53b13baca1ed723946d5976a11403c588cd5
39eb0693fc7c35d0b26e415e3862944a730ad434
refs/heads/main
<repo_name>NGowthamKumar/FoodFactoryApp<file_sep>/src/controller/userController.js import User from "../model/userSchema"; var md5 = require("md5"); export const userLogin = (req, res) => { req.body.password = md5(req.body.password); User.findOne({ $and: [{ email: req.body.email }, { password: req.body.password }], }).exec((error, result) => { if (error || result == null) { res.send("Incorrect username or password." + error); } else { res.send("User login successful"); } }); }; export const userSignup = (req, res) => { User.findOne({ email: req.body.email }).exec((error, result) => { if (error === null) { req.body.password = md5(req.body.password); const user = new User(req.body); user.save((error, result) => { if (error) res.send("Error in saving User :" + error); else res.send("User registered" + result); }); } else { res.send("User already registered"); } }); }; export const updatePassword = (req, res) => { req.body.password = md5(<PASSWORD>); User.updateOne( { email: req.body.email }, { $set: { password: req.body.<PASSWORD> } } ).exec((error, result) => { if (error) { res.send("Error in updating user password:" + error); } else { res.send("User password updated"); } }); }; export const updateUser = (req, res) => { User.updateOne( { email: req.body.email }, { $set: { name: req.body.name, password: req.body.password } } ).exec((error, result) => { if (error) { res.send("Error in updating User:" + error); } else { res.send("User updated"); } }); }; export const updateUserStatus = (req, res) => { User.updateOne( { email: req.body.email }, { $set: { status: req.body.status } } ).exec((error, result) => { if (error) { res.send("Error in updating User Status:" + error); } else { res.send("User Status updated"); } }); }; export const deactivateUser = (req, res) => { User.updateOne( { email: req.body.email }, { $set: { status: "Deactive" } } ).exec((error, result) => { if (error) { res.send("Error in deactivating User" + error); } else { res.send("User deactivated"); } }); }; <file_sep>/src/index.js import app from "./config/express"; require("./config/mongoose"); const PORT = 8000; app.use("/user", require("./routes/userRoutes")); app.use("/food", require("./routes/foodRoutes")); app.use("/ingredients", require("./routes/ingredientsRoutes")); app.use("/order", require("./routes/orderRoutes")); app.listen(PORT, () => { console.log("Running on port " + PORT + "..."); }); <file_sep>/src/controller/ingredientsController.js import Ingredients from "../model/ingredientsSchema"; export const getIngredients = (req, res) => { Ingredients.findOne({ lotNumber: req.params.lotNumber }).exec( (error, result) => { if (error || result == null) { res.send("Error in getting Ingredients :" + error); } else { res.send("Ingredients found " + result); } } ); }; export const getLessAvailableIngredients = (req, res) => { let lessAvailable = []; Ingredients.find({}).exec((error, result) => { if (error || result == null) { res.send("Error in getting Ingredients :" + error); } else { lessAvailable = result.filter( (Ingredients) => Ingredients.availableQuantity < Ingredients.thresholdQuantity ); res.send( lessAvailable.length + " Ingredients have less Availability " + lessAvailable ); } }); }; export const getIngredientsOfVendor = (req, res) => { Ingredients.find({ vendorName: req.params.vendorName }).exec( (error, result) => { if (error || result == null) { res.send("Error in getting Ingredients :" + error); } else { res.send("Vendor have " + result.length + " Ingredients " + result); } } ); }; export const createIngredients = (req, res) => { const ingredients = new Ingredients(req.body); ingredients.save((error, result) => { if (error) { res.send("Error in adding Ingredients :" + error); } else { res.send("Ingredients added " + result); } }); }; export const updateIngredients = (req, res) => { Ingredients.updateOne( { lotNumber: req.body.lotNumber }, { $set: req.body } ).exec((error, result) => { if (error) { res.send("Error in updating Ingredients :" + error); } else { res.send("Ingredients updated"); } }); }; export const deleteIngredients = (req, res) => { Ingredients.deleteOne({ lotNumber: req.params.lotNumber }).exec( (error, result) => { if (error) { res.send("Error in deleting Ingredients :" + error); } else { res.send("Ingredients deleted"); } } ); }; <file_sep>/src/model/ingredientsSchema.js const mongoose = require("mongoose"); const ingredientsSchema = new mongoose.Schema( { name: String, lotNumber: { type: Number, unique: true, required: true }, availableQuantity: Number, thresholdQuantity: Number, price: Number, vendorName: String, vendorEmail: String, }, { versionKey: false } ); module.exports = mongoose.model("Ingredients", ingredientsSchema); <file_sep>/src/routes/foodRoutes.js import router from "../config/router"; import * as foodController from "../controller/foodController"; router.get("/getFood/:lotNumber", foodController.getFood); router.get("/getHighExpensiveFoods", foodController.getHighExpensiveFoods); router.post("/createFood", foodController.createFood); router.put("/updateFood", foodController.updateFood); router.delete("/deleteFood/:lotNumber", foodController.deleteFood); module.exports = router; <file_sep>/src/model/foodSchema.js const mongoose = require("mongoose"); const foodSchema = new mongoose.Schema( { name: String, createdAt: Date, cuisine: String, ingredients: String, lotNumber: { type: Number, unique: true, required: true }, costOfProduction: Number, sellingCost: Number, }, { versionKey: false } ); module.exports = mongoose.model("Food", foodSchema); <file_sep>/src/routes/orderRoutes.js import router from "../config/router"; import * as orderController from "../controller/orderController"; router.get("/getOrder/:orderNum", orderController.getOrder); router.get("/getAllOrdersOfUser/:email", orderController.getAllOrdersOfUser); router.post("/createOrder", orderController.createOrder); router.put("/updateOrder", orderController.updateOrder); router.delete("/deleteOrder/:orderNum", orderController.deleteOrder); module.exports = router; <file_sep>/src/routes/ingredientsRoutes.js import router from "../config/router"; import * as ingredientsController from "../controller/ingredientsController"; router.get("/getIngredients/:lotNumber", ingredientsController.getIngredients); router.get( "/getLessAvailableIngredients", ingredientsController.getLessAvailableIngredients ); router.get( "/getIngredientsOfVendor/:vendorName", ingredientsController.getIngredientsOfVendor ); router.post("/createIngredients", ingredientsController.createIngredients); router.put("/updateIngredients", ingredientsController.updateIngredients); router.delete( "/deleteIngredients/:lotNumber", ingredientsController.deleteIngredients ); module.exports = router; <file_sep>/src/controller/orderController.js import Order from "../model/orderSchema"; import User from "../model/userSchema"; import Food from "../model/foodSchema"; export const getOrder = (req, res) => { Order.findOne({ orderNum: req.params.orderNum }) .populate("user") .populate("food") .exec((error, result) => { if (error) { res.send("Error in getting Order :" + error); } else { res.send("Order found " + result); } }); }; export const getAllOrdersOfUser = (req, res) => { User.findOne({ email: req.params.email }).exec((error, userResult) => { if (error) { res.send("User not Found : " + error); } else { Order.find({ user: userResult._id }).exec((error, result) => { if (error) { res.send("Error in getting Orders :" + error); } else { res.send(result.length + " Orders found " + result); } }); } }); }; export const createOrder = (req, res) => { const userEmail = req.body.email; User.findOne({ email: req.body.email }).exec((error, userResult) => { if (error || userResult == null) { res.send("User not Found : " + error); } else { Food.findOne({ lotNumber: req.body.lotNumber }).exec( (error, foodResult) => { if (error || foodResult == null) { res.send("Food not Found : " + error); } else { req.body.user = userResult._id; req.body.food = foodResult._id; const order = new Order(req.body); order.save((error, result) => { if (error) { res.send("Error in creating Order :" + error); } else { res.send("Order created " + result); } }); } } ); } }); }; export const updateOrder = (req, res) => { Order.updateOne({ orderNum: req.body.orderNum }, { $set: req.body }).exec( (error, result) => { if (error) { res.send("Error in updating Order :" + error); } else { res.send("Order updated"); } } ); }; export const deleteOrder = (req, res) => { Order.deleteOne({ orderNum: req.params.orderNum }).exec((error, result) => { if (error) { res.send("Error in deleting Order :" + error); } else { res.send("Order deleted"); } }); };
f028eb1d3117e590ea578837d4ed68bdf8eb50db
[ "JavaScript" ]
9
JavaScript
NGowthamKumar/FoodFactoryApp
28eef7c3f28aa3da1d372cdd6c15ae338bbb4e45
323f3b83c2df13eaaf3e82915aac465d018a8310
refs/heads/master
<repo_name>mgingras/sorbet<file_sep>/test/helpers/expectations.cc #include "doctest.h" // Include first as it uses poisoned things #include "absl/strings/match.h" #include "absl/strings/str_split.h" #include "common/FileOps.h" #include "common/sort.h" #include "dtl/dtl.hpp" #include "test/helpers/expectations.h" #include <sstream> using namespace std; namespace sorbet::test { namespace { bool compareNames(string_view left, string_view right) { auto lsplit = left.find("__"); if (lsplit == string::npos) { lsplit = left.find("."); } auto rsplit = right.find("__"); if (rsplit == string::npos) { rsplit = right.find("."); } string_view lbase(left.data(), lsplit == string::npos ? left.size() : lsplit); string_view rbase(right.data(), rsplit == string::npos ? right.size() : rsplit); if (lbase != rbase) { return left < right; } // If the base names match, make files with the ".rb" extension come before all others. // The remaining files will be sorted by reverse order on extension. auto lext = FileOps::getExtension(left); auto rext = FileOps::getExtension(right); if (lext != rext) { if (lext == "rb") { return true; } else if (rext == "rb") { return false; } else { return rext < lext; } } // Sort multi-part tests return left < right; } string rbFile2BaseTestName(string rbFileName) { auto basename = rbFileName; auto lastDirSeparator = basename.find_last_of("/"); if (lastDirSeparator != string::npos) { basename = basename.substr(lastDirSeparator + 1); } auto split = basename.rfind("."); if (split != string::npos) { basename = basename.substr(0, split); } split = basename.find("__"); if (split != string::npos) { basename = basename.substr(0, split); } string testName = basename; if (lastDirSeparator != string::npos) { testName = rbFileName.substr(0, lastDirSeparator + 1 + testName.length()); } return testName; } vector<Expectations> listDir(const char *name) { vector<Expectations> result; vector<string> names = sorbet::FileOps::listFilesInDir(name, {".rb", ".rbi", ".rbupdate", ".exp"}, false, {}, {}); const int prefixLen = strnlen(name, 1024) + 1; // Trim off the input directory from the name. transform(names.begin(), names.end(), names.begin(), [&prefixLen](auto &name) -> string { return name.substr(prefixLen); }); fast_sort(names, compareNames); Expectations current; for (auto &s : names) { if (absl::EndsWith(s, ".rb") || absl::EndsWith(s, ".rbi")) { auto basename = rbFile2BaseTestName(s); if (basename != s) { if (basename == current.basename) { current.sourceFiles.emplace_back(s); continue; } } if (!current.basename.empty()) { result.emplace_back(current); current = Expectations(); } current.basename = basename; current.sourceFiles.emplace_back(s); current.folder = name; current.folder += "/"; current.testName = current.folder + current.basename; } else if (absl::EndsWith(s, ".exp")) { if (absl::StartsWith(s, current.basename)) { auto kind_start = s.rfind(".", s.size() - strlen(".exp") - 1); string kind = s.substr(kind_start + 1, s.size() - kind_start - strlen(".exp") - 1); string source_file_path = string(name) + "/" + s.substr(0, kind_start); current.expectations[kind][source_file_path] = s; } } else if (absl::EndsWith(s, ".rbupdate")) { if (absl::StartsWith(s, current.basename)) { // Should be `.[number].rbupdate` auto pos = s.rfind('.', s.length() - 10); if (pos != string::npos) { int version = stoi(s.substr(pos + 1, s.length() - 9)); current.sourceLSPFileUpdates[version].emplace_back(absl::StrCat(s.substr(0, pos), ".rb"), s); } else { cout << "Ignoring " << s << ": No version number provided (expected .[number].rbupdate).\n"; } } } } if (!current.basename.empty()) { result.emplace_back(current); current = Expectations(); } return result; } } // namespace Expectations Expectations::getExpectations(std::string singleTest) { vector<Expectations> result; if (singleTest.empty()) { Exception::raise("No test specified. Pass one with --single_test=<test_path>"); } string parentDir; { auto lastDirSeparator = singleTest.find_last_of("/"); if (lastDirSeparator == string::npos) { parentDir = "."; } else { parentDir = singleTest.substr(0, lastDirSeparator); } } auto scan = listDir(parentDir.c_str()); auto lookingFor = rbFile2BaseTestName(singleTest); for (Expectations &f : scan) { if (f.testName == lookingFor) { for (auto &file : f.sourceFiles) { string filename = f.folder + file; string fileContents = FileOps::read(filename); f.sourceFileContents[filename] = make_shared<core::File>(move(filename), move(fileContents), core::File::Type::Normal); } result.emplace_back(f); } } if (result.size() != 1) { Exception::raise("Expected exactly one test, found {}", result.size()); } return result.front(); } // A variant of CHECK_EQ that prints a diff on failure. void CHECK_EQ_DIFF(std::string_view expected, std::string_view actual, std::string_view errorMessage) { if (expected == actual) { return; } vector<string> expectedLines = absl::StrSplit(expected, '\n'); vector<string> actualLines = absl::StrSplit(actual, '\n'); dtl::Diff<string, vector<string>> diff(expectedLines, actualLines); diff.compose(); diff.composeUnifiedHunks(); stringstream ss; diff.printUnifiedFormat(ss); FAIL_CHECK(fmt::format("{}\n{}", errorMessage, ss.str())); } } // namespace sorbet::test
b95524f81f2a8f1ad52aeb5ef648a7f6f5d699e1
[ "C++" ]
1
C++
mgingras/sorbet
016a3686df86f9888f89df02bd81055d119c87a6
af85100fa0701d77508e48186c43bfd7f2f0f784
refs/heads/master
<repo_name>NikonMcFly/Go-Concurrency<file_sep>/daily-walk/main.go package main import ( "fmt" // "math/rand" "time" ) func main() { aliceReadyChannel := make(chan bool) bobReadyChannel := make(chan bool) // Let's go! fmt.Println("Let's go for a walk!") // Let everyone get ready go doSomething("Alice", "getting ready", 60, 90, aliceReadyChannel) go doSomething("Bob", "getting ready", 60, 90, bobReadyChannel) // Wait for each other select { case <-aliceReadyChannel: <-bobReadyChannel case <-bobReadyChannel: <-aliceReadyChannel } // THEN arm alarm fmt.Println("Arming alarm") go armAlarm() // Let everyone put on shoes go doSomething("Alice", "putting on shoes", 35, 45, aliceReadyChannel) go doSomething("Bob", "putting on shoes", 35, 45, bobReadyChannel) // Wait for each other again select { case <-aliceReadyChannel: <-bobReadyChannel case <-bobReadyChannel: <-aliceReadyChannel } // Leave the house fmt.Println("Exiting and locking the door") // Wait so program doesn't exit and armAlarm can finish time.Sleep(100 * time.Second) } func doSomething(name string, action string, min int, max int, ch chan bool) { fmt.Println(name, " started ", action) dur := min + rand.Intn(max-min) time.Sleep(time.Duration(dur) * time.Second) fmt.Println(name, " spent ", dur, " seconds ", action) ch <- true } func armAlarm() { fmt.Println("Alarm is counting down.") time.Sleep(60 * time.Second) fmt.Println("Alarm is armed") } <file_sep>/README.md # Go-Concurrency 3 Trivial Concurrency Exercises from http://whipperstacker.com/2015/10/05/3-trivial-concurrency-exercises-for-the-confused-newbie-gopher/ to practice and get a clear understanding of concurrency in Golang
66ae07e000820bc791cbf4cc170b138f22c23107
[ "Markdown", "Go" ]
2
Go
NikonMcFly/Go-Concurrency
14f0d03d28c346df4362296e0b1392bf9d06275c
5a3d6ef353b79a12c462efcab3b2f1977830bde7
refs/heads/main
<repo_name>jaewoong0119/smart<file_sep>/20210427/src/package06/Ex29.java package package06; public abstract class Ex29 { //추상 클래스 abstract void method1(int dante); //추상 메서드 public void method2() { //일반 메서드 System.out.println("MyInterface-method2 실행"); } } <file_sep>/20210427/src/package5/Ex25.java package package5; public interface Ex25 { //추상 메서드 void method1(int dante); //default 메서드 default void method2() { System.out.println("MyInterface-method2 실행"); } }
64acf11f1198b6b3d8a28cfbfbf034e6cadbfcea
[ "Java" ]
2
Java
jaewoong0119/smart
5f9b3cf12531070d0ecf1badab8b688312560e16
3470bc04bc4bd1ce30d403fe989efb70473a7aa2
refs/heads/master
<repo_name>ajduberstein/grid_pen<file_sep>/grid_pen.sql CREATE TABLE squares AS SELECT ('polygon ((' || (x)::text || ' ' || (y)::text || ',' || (x)::text || ' ' || (.01 + y)::text || ',' || (.01 + x)::text || ' ' || (.01 + y)::text || ',' || (.01 + x)::text || ' ' || (y)::text || ',' || x::text || ' ' || (y)::text || '))')::geometry FROM (SELECT -122.5 + .01*generate_series(0,100) AS x) a --last digit provides number of squares, decimal provides granularity, first digit provides origin CROSS JOIN (SELECT 37.92 + .01*generate_series(0,100) AS y) b;
38ca6dd6d2ca12ed772ce7acd786580acfc191f4
[ "SQL" ]
1
SQL
ajduberstein/grid_pen
38d232619890110ac12ad5fc2cc3c687f0c3f159
f38001afc05bd393178963db752c40b319bf9b59
refs/heads/main
<repo_name>panost/StringCache<file_sep>/Bench/Intern.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using ecl.Collections; namespace Bench { [SimpleJob( RuntimeMoniker.Net50 )] public class InternTest { private string[] _array; public const int Count = 100; private Dictionary<string, string> _map; private StringCache _cache; [ GlobalSetup] public void GlobalSetup() { List<string> list = new List<string>(); var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var random = new Random( 1253 ); _map = new Dictionary<string, string>(); _cache = new StringCache(); char[] buffer = new char[ 32 ]; while (true ) { int len = random.Next( 4, 30 ); for ( int i = 0; i < len; i++ ) { buffer[ i ] = chars[ random.Next( chars.Length ) ]; } string str = new string( buffer, 0, len ); if ( string.IsInterned( str ) == null ) { if ( list.Count < Count ) { string.Intern( str ); str = new string( buffer, 0, len ); list.Add( str ); _map.Add( str, str ); _cache.GetOrAdd( str ); } else if ( list.Count < Count*2 ) { list.Add( str ); } else { break; } } } _array = list.ToArray(); } [Benchmark] public int Dictionary() { int found = 0; foreach ( string s in _array ) { if ( _map.TryGetValue( s, out string f ) ) { found++; } } return found; } [Benchmark] public int Intern() { int found = 0; foreach ( string s in _array ) { if ( string.IsInterned( s ) != null ) { found++; } } return found; } [Benchmark] public int StringCache() { int found = 0; foreach ( string s in _array ) { if ( _cache.GetF( s ) != null ) { found++; } } return found; } } } <file_sep>/README.md # StringCache A thread safe string cache that supports ReadOnlySpan <file_sep>/StringCache/StringCache.Slot.cs using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace ecl.Collections { partial class StringCache { [DebuggerDisplay( "Entry:{Key}, {HashCode}, {Next}" )] internal struct Entry { public int HashCode; public int Next; public string Key; public void Set( string key, int hashCode, int next ) { Key = key; HashCode = hashCode; Next = next; } } [MethodImpl( MethodImplOptions.AggressiveInlining )] public static uint FastMod( uint value, uint divisor, ulong multiplier ) { return (uint)( ( ( ( ( multiplier * value ) >> 32 ) + 1 ) * divisor ) >> 32 ); } public static ulong GetFastModMultiplier( uint divisor ) => ulong.MaxValue / divisor + 1; public static int NextOdd( int i ) { i |= 1; while ( i % 3 == 0 || i % 5 == 0 || i % 7 == 0 ) { i += 2; } return i; } private class Slot { public int Count; private readonly Entry[] _entries; private readonly int[] _buckets; private readonly ulong _fastModBucketsMultiplier; public Slot( int capacity, int prime ) { _fastModBucketsMultiplier = IntPtr.Size == 8 ? GetFastModMultiplier( (uint)prime ) : 0; _buckets = new int[ prime ]; _entries = new Entry[ capacity ]; } public Slot( HashSet<string> set ) { int capacity = set.Count; if ( capacity < 16 ) { capacity = 16; } _entries = new Entry[ capacity ]; _buckets = new int[ NextOdd( capacity ) ]; _fastModBucketsMultiplier = IntPtr.Size == 8 ? GetFastModMultiplier( (uint)_buckets.Length ) : 0; foreach ( string s in set ) { Add( s, GetOrdinalHashCode( s ) ); } } public string this[ int index ] => _entries[ index ].Key; [MethodImpl( MethodImplOptions.AggressiveInlining )] private ref int GetBucketSlot( int hashCode ) { int[] buckets = _buckets; if ( IntPtr.Size == 8 ) { return ref buckets[ FastMod( (uint)hashCode, (uint)buckets.Length, _fastModBucketsMultiplier ) ]; } return ref buckets[ (uint)hashCode % (uint)buckets.Length ]; } private void Add( string key, int hashCode ) { ref int i = ref GetBucketSlot( hashCode ); _entries[ Count++ ].Set( key, hashCode, i ); i = Count; } private void Add( Entry[] entries ) { for ( int j = 0; j < entries.Length; j++ ) { ref Entry ptr = ref entries[ j ]; Add( ptr.Key, ptr.HashCode ); } } public int IndexOf( ReadOnlySpan<char> key, int hashCode ) { int i = GetBucketSlot( hashCode ); while ( i > 0 ) { i--; ref var ptr = ref _entries[ i ]; if ( ptr.HashCode == hashCode && key.SequenceEqual( ptr.Key ) ) return i; i = ptr.Next; } return -1; } public string Find( ReadOnlySpan<char> key, int hashCode ) { int i = GetBucketSlot( hashCode ); while ( i > 0 ) { i--; ref var ptr = ref _entries[ i ]; if ( ptr.HashCode == hashCode && key.SequenceEqual( ptr.Key ) ) return ptr.Key; i = ptr.Next; } return null; } private Slot Resize() { int newCapacity = _entries.Length * 2; var slot = new Slot( newCapacity, NextOdd( newCapacity ) ); slot.Add( _entries ); return slot; } public string Insert( StringCache owner, ReadOnlySpan<char> key, int hashCode, string str ) { ref int lead = ref GetBucketSlot( hashCode ); int i = lead; while ( i > 0 ) { i--; ref var ptr = ref _entries[ i ]; if ( ptr.HashCode == hashCode && key.SequenceEqual( ptr.Key ) ) return ptr.Key; i = ptr.Next; } str ??= new string( key ); if ( Count == _entries.Length ) { var slot = Resize(); slot.Add( str, hashCode ); owner._slot = slot; } else { _entries[ Count++ ].Set( str, hashCode, lead ); lead = Count; } return str; } public Enumerator GetEnumerator() { return new Enumerator( _entries, Count ); } } } }<file_sep>/StringCache/StringCache.cs using System; using System.Collections; using System.Collections.Generic; using System.Numerics; using System.Text; using System.Threading; namespace ecl.Collections { public partial class StringCache : IEnumerable<string> { public readonly StringCache Parent; private Slot _slot; public StringCache( StringCache parent ) { Parent = parent; _slot = new Slot( 16, 13 ); } public StringCache() : this( (StringCache)null ) { } public int Count => _slot.Count; public StringCache( IEnumerable<string> str, StringCache parent ) { HashSet<string> set; if ( parent != null ) { Parent = parent; set = new HashSet<string>(); foreach ( var s in str ) { if ( parent.Get( s ) == null ) { set.Add( s ); } } } else { set = new HashSet<string>( str ); } _slot = set.Count > 0 ? new Slot( set ) : new Slot( 16, 13 ); } public StringCache( params string[] args ) : this( args, (StringCache)null ) { } internal static readonly uint CaseSensitiveSeed = GetRandomUint( 0x15051505 ); private static uint GetRandomUint( int someSeed ) { #if DEBUG return (uint)someSeed; #else var rnd = new Random( Environment.TickCount ^ someSeed ); return (uint)HashCode.Combine( rnd.Next(), rnd.Next() ); #endif } public static int GetOrdinalHashCode( ReadOnlySpan<char> span ) { uint hash = CaseSensitiveSeed; foreach ( var ch in span ) { hash = ( BitOperations.RotateLeft( hash, 5 ) + hash ) ^ ch; } return (int)hash; } public string Get( ReadOnlySpan<byte> key ) { if ( key.Length < 256 ) { Span<char> name = stackalloc char[ 512 ]; if ( Encoding.UTF8.GetChars( key, name ) == key.Length ) { return Get( name ); } } return null; } public string GetF( ReadOnlySpan<char> key, int hashCode ) { return _slot.Find( key, hashCode ) ?? Parent?.GetF( key, hashCode ); } public string GetF( ReadOnlySpan<char> key ) { int hashCode = GetOrdinalHashCode( key ); return GetF( key, hashCode ); } private string Get( ReadOnlySpan<char> key, int hashCode ) { var slot = Volatile.Read( ref _slot ); int idx = slot.IndexOf( key, hashCode ); return idx >= 0 ? slot[ idx ] : Parent?.Get( key, hashCode ); } public string Get( ReadOnlySpan<char> key ) { return Get( key, GetOrdinalHashCode( key ) ); } public string GetOrAdd( ReadOnlySpan<char> key ) { var hashCode = GetOrdinalHashCode( key ); return Get( key, hashCode ) ?? Add( key, hashCode ); } public string GetOrAdd( ReadOnlySpan<byte> key ) { if ( key.Length < 256 ) { Span<char> name = stackalloc char[ 512 ]; if ( Encoding.UTF8.GetChars( key, name ) == key.Length ) { return GetOrAdd( name ); } } return null; } public string GetOrAdd( string key ) { var hashCode = GetOrdinalHashCode( key ); return Get( key, hashCode ) ?? Add( key, hashCode ); } private readonly object _addition = new(); private string Add( ReadOnlySpan<char> key, int hashCode ) { lock ( _addition ) { return _slot.Insert( this, key, hashCode, null ); } } private string Add( string key, int hashCode ) { lock ( _addition ) { return _slot.Insert( this, key, hashCode, key ); } } public struct Enumerator : IEnumerator<string> { private readonly Entry[] _entries; private readonly int _count; private int _index; internal Enumerator( Entry[] entries, int count ) { _entries = entries; _count = count; _index = -1; } public bool MoveNext() { int idx = _index + 1; if ( idx < _count ) { _index = idx; return true; } return false; } public void Reset() { _index = -1; } public string Current => (uint)_index < (uint)_entries.Length? _entries[ _index ].Key:null; object IEnumerator.Current => Current; void IDisposable.Dispose() { } } public Enumerator GetEnumerator() { return _slot.GetEnumerator(); } #region Implementation of IEnumerable IEnumerator<string> IEnumerable<string>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }<file_sep>/Bench/Program.cs using System; using System.Diagnostics; using BenchmarkDotNet.Running; namespace Bench { class Program { static void Main( string[] args ) { #if DEBUG Test(); #else BenchmarkRunner.Run( typeof( InternTest ) ); #endif } static void Test() { var t = new InternTest(); t.GlobalSetup(); if ( t.Dictionary() != InternTest.Count ) { Debug.WriteLine( "Dictionary" ); } if ( t.Intern() != InternTest.Count ) { Debug.WriteLine( "Intern" ); } if ( t.StringCache() != InternTest.Count ) { Debug.WriteLine( "StringCache" ); } } } }
8e984956eb782c0edafd66dd3e1e65db982651d4
[ "Markdown", "C#" ]
5
C#
panost/StringCache
75ba8db40a10e61d194f78461389c3b1256d62a5
6dc04834e0add469b72e1f8c61ec1a9da1bfc0c3
refs/heads/master
<file_sep># -*- coding: utf-8 -*-` """api.py - Create and configure the Game API exposing the resources. This can also contain game logic. For more complex games it would be wise to move game logic to another file. Ideally the API will be simple, concerned primarily with communication to/from the API's users.""" import sys import logging import endpoints import time from protorpc import remote, messages from protorpc import message_types from google.appengine.api import memcache from google.appengine.api import taskqueue from google.appengine.ext import ndb from models import User, Game, Score, Move from models import StringMessage, NewGameForm, GameForm, MakeMoveForm,\ ScoreForms from utils import get_by_urlsafe # NEW_GAME_REQUEST = endpoints.ResourceContainer(NewGameForm) # GET_GAME_REQUEST = endpoints.ResourceContainer( # urlsafe_game_key=messages.StringField(1),) # MAKE_MOVE_REQUEST = endpoints.ResourceContainer( # MakeMoveForm, # urlsafe_game_key=messages.StringField(1),) # USER_REQUEST = endpoints.ResourceContainer(user_name=messages.StringField(1), # email=messages.StringField(2)) START_GAME = endpoints.ResourceContainer(game_id = messages.StringField(1), player1=messages.StringField(2), player2=messages.StringField(3)) GAME_ID = endpoints.ResourceContainer(game_id = messages.StringField(1)) MAKE_NEXT_MOVE_REQUEST = endpoints.ResourceContainer( x = messages.IntegerField(1), y = messages.IntegerField(2), user_id=messages.StringField(3), game_id=messages.StringField(4)) MEMCACHE_MOVES_REMAINING = 'MOVES_REMAINING' @endpoints.api(name='guess_a_number', version='v1') class GuessANumberApi(remote.Service): """Game API""" @endpoints.method(request_message=START_GAME, response_message=StringMessage, path='start_game', name='start_game', http_method='POST') def startGame(self, request): """ Initializes all 9 posible moves using provided game_id """ game_id = request.game_id player1 = request.player1 player2 = request.player2 if request.game_id == None: return StringMessage(message = "Failed, Empty game_id. Please enter a valid unique game_id") if request.player1 == None or request.player2 == None: return StringMessage(message = "Failed, Missing Players. Make sure both player ids are present") if request.player1 == request.player2: return StringMessage(message = "Failed, Player Ids must be different") game_exists = len(Move.query(Move.game_id == game_id).fetch()) > 0 if game_exists: return StringMessage(message = "Game Creation Failed, Game ID already exists: {0}".format( game_id ) ) # Creating Game game = Game(game_id = game_id, player1 = request.player1, player2 = request.player2) game.put() print("New Game Created: {0}".format(game)) mv1 = Move(x = 0, y = 0, game_id = game_id, available = True, description = "[0,0]") mv2 = Move(x = 0, y = 1, game_id = game_id, available = True, description = "[0,1]") mv3 = Move(x = 0, y = 2, game_id = game_id, available = True, description = "[0,2]") mv4 = Move(x = 1, y = 0, game_id = game_id, available = True, description = "[1,0]") mv5 = Move(x = 1, y = 1, game_id = game_id, available = True, description = "[1,1]") mv6 = Move(x = 1, y = 2, game_id = game_id, available = True, description = "[1,2]") mv7 = Move(x = 2, y = 0, game_id = game_id, available = True, description = "[2,0]") mv8 = Move(x = 2, y = 1, game_id = game_id, available = True, description = "[2,1]") mv9 = Move(x = 2, y = 2, game_id = game_id, available = True, description = "[2,2]") # ndb.put_multi([ mv1, mv2, mv3, mv4, mv5, mv6, mv7, mv8, mv9]) for m in [ mv1, mv2, mv3, mv4, mv5, mv6, mv7, mv8, mv9]: print(" saving: {0}".format(m) ) m.put() return StringMessage(message = "New Game Created, ID: {0} | Player 1: {1} | Player 2: {2}".format( game_id, player1, player2 ) ) @endpoints.method(request_message = GAME_ID, response_message = StringMessage, path = "game_reset", name = "game_reset", http_method = "POST") def resetGameState(self, request): # Remove move ownership for all users # Resets move availablities to True game_id = request.game_id # for the moment, resets every move for provided game_id moves = Move.query().fetch() moves_deleted = Move.query(Move.game_id == game_id).fetch() game = Game.query(Game.game_id == game_id).get() if game == None: return StringMessage(message = "No Game found for ID: {0} ".format(game_id)) print("game id is {0} {1}".format(game_id, moves[0].game_id )) # Deleting Game game.key.delete() # Deleting Moves for move in moves_deleted: print("Deleting moves, {0}".format(move)) move.key.delete() return StringMessage(message = "Game Reset Complete, deleted {0} moves for Game: {1} ".format(len(moves_deleted), game_id)) @endpoints.method(request_message= MAKE_NEXT_MOVE_REQUEST, response_message = StringMessage, name = "make_move", path="make_move", http_method="POST" ) def makeMove(self, request): """ Asigns specific move to a user for a specific game_id, as long as its available """ x = request.x y = request.y game_id = request.game_id user_id = request.user_id game = Game.query(Game.game_id == game_id).get() queried_move = Move.query(Move.x == x, Move.y == y, Move.game_id == game_id).fetch(1) if game == None : print("\n\nInvalid Move, Wrong Game ID\n\n") return StringMessage(message = "Invalid Move, Wrong Game ID" ) winner_id = GuessANumberApi._check_winning_condition(game_id) if winner_id != False: print("\n\n Game Won By {0} \n\n".format(winner_id)) return StringMessage(message = "\n\n Game Won By {0} \n\n".format(winner_id)) available_moves = Move.query(Move.available == True, Move.game_id == game_id).fetch() if len(available_moves) == 0: print("\n\n Game Ended, No more moves left {0} \n\n".format(game_id)) return "no_more_moves" if user_id == None or user_id not in [game.player1, game.player2]: print("\n\nInvalid move parameters\n\n") return StringMessage(message = "Invalid Move, Wrong User ID" ) if len(queried_move) == 0: print("\n\nInvalid move parameters\n\n") return StringMessage(message = "Invalid move parameters, Wrong Game ID or Move out of range" ) if user_id == game.last_play_user_id: print("\n\n This Player already moved\n\n") return StringMessage(message = "Invalid move, This Player already moved" ) move = queried_move[0] if move.available != True: print("\n\nMove already done by: {0} \n\n".format(move.user_id)) return StringMessage(message = "Move {0} has already been made by User with ID: : {1}" .format(move.description, move.user_id) ) move.user_id = user_id move.available = False move.put() game.last_play_user_id = user_id game.put() GuessANumberApi._show_game_picture(game_id) GuessANumberApi._check_game_state(game_id) return StringMessage(message = "Move {0} assign to {1} for game_id: {2}, x:{3} and y:{4}".format(move.description, user_id, game_id, x, y) ) @endpoints.method(request_message = GAME_ID, response_message = StringMessage, path = "check_game_state", name = "check_game_state", http_method = "POST") def checkGameState(self, request): game_id = request.game_id game = Game.query(Game.game_id == game_id).get() if game == None: print("\n\n Game doesnt exist for ID: {0} \n\n".format(game_id)) return StringMessage(message = "Game doesnt exist for ID: {0} " .format(game_id) ) state = GuessANumberApi._check_game_state(game_id) if state == "no_more_moves": print("\n\n Game Ended, No Winners: {0} \n\n".format(game_id)) return StringMessage(message = "Game Ended, No Winners: {0} " .format(game_id) ) if state == "no_winners_yet": print("\n\n No Winners Yet, Game Continues: {0} \n\n".format(game_id)) return StringMessage(message = "No Winners Yet, Game Continues: {0} " .format(game_id) ) print("\n\n Game Won By: {0} \n\n".format(state)) return StringMessage(message = "Game Won By: {0} " .format(state) ) @endpoints.method(message_types.VoidMessage, response_message = StringMessage, path="show_game_ids", name="show_game_ids", http_method='GET') def show_game_ids(self, request): moves = Move.query().fetch() game_ids = [] for move in moves: game_id = move.game_id if game_id not in game_ids: game_ids.append(game_id) #Showing game moves per game GuessANumberApi._show_game_picture(game_id) GuessANumberApi._check_game_state(game_id) print( "\n\n Total Game IDS: {0}, IDS: {1} \n\n".format( len(game_ids), str(game_ids) ) ) return StringMessage(message= "Total Moves: {0}, Total Game IDS: {1}, IDS: {2}".format( len(moves), len(game_ids), str(game_ids) ) ) # @endpoints.method(request_message = START_GAME, response_message = StringMessage) @staticmethod def _show_game_picture(game_id): """ Print visual representation of game state """ moves = Move.query(Move.game_id == game_id).order(Move.x, Move.y).fetch() if len(moves) == 0: print("\n\nCant print game state, Invalid game_id {0}\n\n".format(game_id)) return StringMessage(message = "Invalid move parameters. no game found" ) player1,player2 = GuessANumberApi._get_players_in_game(game_id) print("Current Players for Game ID {0}: {1}, {2}".format(game_id, player1, player2) ) m_00 = Move.query(Move.x == 0, Move.y == 0, Move.game_id == game_id).fetch(1)[0] m_01 = Move.query(Move.x == 0, Move.y == 1, Move.game_id == game_id).fetch(1)[0] m_02 = Move.query(Move.x == 0, Move.y == 2, Move.game_id == game_id).fetch(1)[0] m_10 = Move.query(Move.x == 1, Move.y == 0, Move.game_id == game_id).fetch(1)[0] m_11 = Move.query(Move.x == 1, Move.y == 1, Move.game_id == game_id).fetch(1)[0] m_12 = Move.query(Move.x == 1, Move.y == 2, Move.game_id == game_id).fetch(1)[0] m_20 = Move.query(Move.x == 2, Move.y == 0, Move.game_id == game_id).fetch(1)[0] m_21 = Move.query(Move.x == 2, Move.y == 1, Move.game_id == game_id).fetch(1)[0] m_22 = Move.query(Move.x == 2, Move.y == 2, Move.game_id == game_id).fetch(1)[0] m_00 = m_00.user_id or m_00.description m_01 = m_01.user_id or m_01.description m_02 = m_02.user_id or m_02.description m_10 = m_10.user_id or m_10.description m_11 = m_11.user_id or m_11.description m_12 = m_12.user_id or m_12.description m_20 = m_20.user_id or m_20.description m_21 = m_21.user_id or m_21.description m_22 = m_22.user_id or m_22.description print("\n\n\n") print("TIC TAC TOE GAME") print("\n") print(" {0} | {1} | {2} ".format(m_00, m_01, m_02)) print("-----------------------------") print(" {0} | {1} | {2} ".format(m_10, m_11, m_12)) print("-----------------------------") print(" {0} | {1} | {2} ".format(m_20, m_21, m_22)) print("\n\n\n") @staticmethod def _check_game_state(game_id): """ Checks whether there's a victory condition, losing condition, or no more available moves """ print("\n\nInside check game state, game_id: " + game_id) moves = Move.query(Move.game_id == game_id).fetch() available_moves = Move.query(Move.available == True, Move.game_id == game_id).fetch() if len(moves) == 0: print("\n\n game_id not found {0} \n\n".format(game_id)) return "game_id_not_found" winner_id = GuessANumberApi._check_winning_condition(game_id) if winner_id != False: print("\n\n############### Game won by:" + winner_id + " ###############\n\n") return winner_id if len(available_moves) == 0: print("\n\n Game Ended, No more moves left {0} \n\n".format(game_id)) return "no_more_moves" print("\n\nNo winners yet for game: {0} \n\n".format(game_id)) return "no_winners_yet" @staticmethod def _check_winning_condition(game_id): """ Checks whether there's a victory condition and returns winner user_id if there is, else false""" # Find game with only 2 allowed users, to be done... moves = Move.query(Move.game_id == game_id).fetch() user_ids = GuessANumberApi._get_players_in_game(game_id) if len(moves) == 0: print("\n\n game_id not found {0} \n\n".format(game_id)) return False return "game_id not found" if None in user_ids: print("\n\n not all users have played a move: {0} \n\n".format(user_ids)) return False return "not all users have played a move" print("\n\nChecking winning condition for game id: " + game_id) user_1 = user_ids[0] user_2 = user_ids[1] for i in range(0,3): # Checking for Horizontal Wins horizontal_moves = Move.query(Move.game_id == game_id, Move.x == i) horizontal_moves = [h.user_id for h in horizontal_moves] unique_owner = list( set(horizontal_moves) ) if None not in unique_owner and len(unique_owner) == 1: winner_id = unique_owner[0] print("\n\nHorizontal Winning condition met, User: {0} Won! Row: {1} \n\n".format(winner_id, i)) return winner_id # Checking for Vertical Wins vertical_moves = Move.query(Move.game_id == game_id, Move.y == i) vertical_moves = [h.user_id for h in vertical_moves] unique_owner = list( set(vertical_moves) ) if None not in unique_owner and len(unique_owner) == 1: winner_id = unique_owner[0] print("\n\n Vertical Winning condition met, User: {0} Won!, Column: {1} \n\n".format(winner_id, i)) return winner_id # Checking Cross Wins diagonal_moves = [] for i in range(0,3): m = Move.query(Move.x == i, Move.y == i).fetch()[0] unique_owner = list(set(diagonal_moves)) if None not in unique_owner and len(unique_owner) == 1: winner_id = unique_owner[0] print("\n\n Diagonal Winning condition met, User: {0} Won!, Column: {1} \n\n".format(winner_id, i)) return winner_id # Checking Cross Wins diagonal_moves = [] for i in range(0,3): m = Move.query(Move.x == i, Move.y == 2-i).fetch()[0] diagonal_moves.append(m.user_id) diagonal_moves.append(m.user_id) unique_owner = list(set(diagonal_moves)) if None not in unique_owner and len(unique_owner) == 1: winner_id = unique_owner[0] print("\n\n Diagonal Winning condition met, User: {0} Won!, Column: {1} \n\n".format(winner_id, i)) return winner_id print("\n\n No winning conditions met \n\n") return False @staticmethod def _get_players_in_game(game_id): moves = Move.query(Move.game_id == game_id).fetch() if len(moves) == 0: return StringMessage(message = "Invalid move parameters. no game found" ) print("Getting players in game...") user_ids = [] for move in moves: user_id = move.user_id # print("checking for ID: {0}".format( user_id) ) if user_id not in user_ids and user_id != None: # print("ID: {0} was inserted".format( user_id) ) user_ids.append(user_id) print(user_ids) if len(user_ids) == 2: player1 = user_ids[0] player2 = user_ids[1] elif len(user_ids) == 1: player1 = user_ids[0] player2 = None else: player1 = None player2 = None print(player2, player1) return [player1, player2] # @endpoints.method(request_message=USER_REQUEST, # response_message=StringMessage, # path='user', # name='create_user', # http_method='POST') # def create_user(self, request): # """Create a User. Requires a unique username""" # if User.query(User.name == request.user_name).get(): # raise endpoints.ConflictException( # 'A User with that name already exists!') # user = User(name=request.user_name, email=request.email) # user.put() # return StringMessage(message='User {} created!'.format( # request.user_name)) # @endpoints.method(request_message=NEW_GAME_REQUEST, # response_message=GameForm, # path='game', # name='new_game', # http_method='POST') # def new_game(self, request): # """Creates new game""" # user = User.query(User.name == request.user_name).get() # if not user: # raise endpoints.NotFoundException( # 'A User with that name does not exist!') # try: # game = Game.new_game(user.key, request.min, # request.max, request.attempts) # except ValueError: # raise endpoints.BadRequestException('Maximum must be greater ' # 'than minimum!') # # Use a task queue to update the average attempts remaining. # # This operation is not needed to complete the creation of a new game # # so it is performed out of sequence. # taskqueue.add(url='/tasks/cache_average_attempts') # return game.to_form('Good luck playing Guess a Number!') # @endpoints.method(request_message=GET_GAME_REQUEST, # response_message=GameForm, # path='game/{urlsafe_game_key}', # name='get_game', # http_method='GET') # def get_game(self, request): # """Return the current game state.""" # game = get_by_urlsafe(request.urlsafe_game_key, Game) # if game: # return game.to_form('Time to make a move!') # else: # raise endpoints.NotFoundException('Game not found!') # # @endpoints.method(request_message=MAKE_MOVE_REQUEST, # # response_message=GameForm, # # path='game/{urlsafe_game_key}', # # name='make_move', # # http_method='PUT') # # def make_move(self, request): # # """Makes a move. Returns a game state with message""" # # game = get_by_urlsafe(request.urlsafe_game_key, Game) # # if game.game_over: # # return game.to_form('Game already over!') # # game.attempts_remaining -= 1 # # if request.guess == game.target: # # game.end_game(True) # # return game.to_form('You win!') # # if request.guess < game.target: # # msg = 'Too low!' # # else: # # msg = 'Too high!' # # if game.attempts_remaining < 1: # # game.end_game(False) # # return game.to_form(msg + ' Game over!') # # else: # # game.put() # # return game.to_form(msg) # @endpoints.method(response_message=ScoreForms, # path='scores', # name='get_scores', # http_method='GET') # def get_scores(self, request): # """Return all scores""" # return ScoreForms(items=[score.to_form() for score in Score.query()]) # @endpoints.method(request_message=USER_REQUEST, # response_message=ScoreForms, # path='scores/user/{user_name}', # name='get_user_scores', # http_method='GET') # def get_user_scores(self, request): # """Returns all of an individual User's scores""" # user = User.query(User.name == request.user_name).get() # if not user: # raise endpoints.NotFoundException( # 'A User with that name does not exist!') # scores = Score.query(Score.user == user.key) # return ScoreForms(items=[score.to_form() for score in scores]) # @endpoints.method(response_message=StringMessage, # path='games/average_attempts', # name='get_average_attempts_remaining', # http_method='GET') # def get_average_attempts(self, request): # """Get the cached average moves remaining""" # return StringMessage(message=memcache.get(MEMCACHE_MOVES_REMAINING) or '') @staticmethod def _cache_average_attempts(): """Populates memcache with the average moves remaining of Games""" games = Game.query(Game.game_over == False).fetch() if games: count = len(games) total_attempts_remaining = sum([game.attempts_remaining for game in games]) average = float(total_attempts_remaining)/count memcache.set(MEMCACHE_MOVES_REMAINING, 'The average moves remaining is {:.2f}'.format(average)) api = endpoints.api_server([GuessANumberApi])
549eff48e656d4408d06d9753abf380a7401d6ce
[ "Python" ]
1
Python
Ascariel/UdacityGameDesignProject4
43d2ba13d535f9a75a3428b668d12c8f137eddf4
0759fdc226234e2f4992a06a06b774c6197fe92d
refs/heads/master
<file_sep>##################################################################################################### # Matrix inversion is usually a costly computation and # there may be some benefit to caching the inverse of a matrix rather than # computing it repeatedly. There is a pair of functions that cache the inverse of a matrix. ##################################################################################################### ##################################################################################################### # 1. This function takes a matrix, saved in the private variable x and # creates a special "matrix" object that can cache its inverse ##################################################################################################### makeCacheMatrix <- function(x = matrix()) { # initialize the matrix to NULL during the first call to makeCacheMatrix # this is needed because if getinverse() is called immediately after # the makeCacheMatrix funciton is constructed, without a call to setinverse # we know we must first calculate the matrix invesion in cacheSolve. inverse_m <- NULL # funciton to set a new value for the underlying matrix # this invalidates the cached inverse matrix, inversed_m; # the <<- operator is used to set the value of x and inverse_m because we want # to modify x and inverse_m defined in the enclosing environment (created # when makeCacheMatrix was first called), not in the environment local to set(), # in which x and inverse_m are undefined. # we must reset inverse_m to NULL since we are modifying the underlying # matrix and the cached value is no longer valid set <- function(y) { x <<- y inverse_m <<- NULL } # getter function for underlying matrix # in R the return value of a function is the last statement. get <- function() x # set the inverse of the matrix x. Called by cachSolve, # the <<- operator is used because we want to modify the inverse_m defined # in the enclosing function makeCacheMatrix, not the inverse_m local to setinverse, # which would be undefined. setinverse <- function(inverse) inverse_m <<- inverse # returns the inverse matrix. Will be null if setinverse has not been called or # if set is called after the last call to setinverse getinverse <- function() inverse_m # return value of the makeCacheMatrix function is a list # of functions (and variables if we wish) that we want to expose # as public. these are accessed with the $ operator. Any variables # declared inside makeCacheMatrix but not exported as part of this list # are private...they are inaccessible to any caller of makeCacheMatrix list(set = set, get = get, setinverse = setinverse, getinverse = getinverse) } ############################################################################################################ # 2. This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. # If the inverse has already been calculated (and the matrix has not changed), then cacheSolve # should retrieve the inverse from the cache. cacheSolve takes a caching matrix created with makeCacheMatrix ############################################################################################################# cacheSolve <- function(x, ...) { # get the inverse of the matrix defined inside x. # we can use the $ operator to access the function since it was # defined in the list of function pointers returned by the call to # makeCacheMatrix inverse_m <- x$getinverse() # if we've already computed the inverse matrix and stored it via setinverse(), # and have not invalidated the cache by calling set(), return the cached # version of x if(!is.null(inverse_m)) { message("getting cached data") # we have to explicily use return here otherwise we'd keep # executing the code after the if conditional ends. Since # the cached version is good, just return it and we are done. return(inverse_m) } # either we haven't computed the cached version yet, or we've called # set() previously and invalidated the cache. # call get() to get the underlying inverse matrix data <- x$get() # calculate the inverse of the underlying matrix, passing with it # any var args passed to cacheSolve inverse_m <- solve(data, ...) # now set the inverse matrix in x so we cache it and dont need to needlessly # recompute it x$setinverse(inverse_m) # return the caching matrix inverse_m } # TEST: generate matrix, and the inverse of the matrix. size <- 1000 # size of the matrix edge test_matrix <- matrix(rnorm(size^2), nrow=size, ncol=size) test_matrix_inverse <- solve(test_matrix) # solve the matrix via the cache method special_matrix <- makeCacheMatrix(test_matrix) # this should take longer than the next call since there will be # an inverse computation performed for the first time special_matrix_inverse1 <- cacheSolve(special_matrix) # this should retrieve cached matrix calculated in the first call, # 'getting cached data' should get displayed to confirm the logic special_matrix_inverse2 <- cacheSolve(special_matrix) # this returns TRUE to confirm that all solved matrices are identical identical(test_matrix_inverse, special_matrix_inverse1) & identical(test_matrix_inverse, special_matrix_inverse2)
77f593af39aa55e41166afb2b62896c9bb8f29d2
[ "R" ]
1
R
marileksa/ProgrammingAssignment2
3c829e5a49f007b6ad5b00b4a3d503062a8a7834
cbc079cc1045140c55e83061b0b046d66ede8d38
refs/heads/master
<file_sep> require(ggplot2) require(gridExtra) require(RColorBrewer) require(pracma) require(scales) get.mfARI <- function(Ks, Delta.tau, Phi) { # # From regression on bounded mfARI parameters made # on mar 06 2015 # # Call: # lm(formula = ATARI ~ Ks + Delta.tau + Phi, data = params) # # Residuals: # Min 1Q Median 3Q Max # -0.24540 -0.08135 0.01454 0.07764 0.19562 # # Coefficients: # Estimate Std. Error t value Pr(>|t|) # (Intercept) 1.48740 0.31454 4.729 8.65e-06 *** # Ks 3.85688 0.11339 34.014 < 2e-16 *** # Delta.tau -0.12420 0.02910 -4.269 4.99e-05 *** # Phi 0.10999 0.00608 18.091 < 2e-16 *** # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # Residual standard error: 0.1161 on 87 degrees of freedom # Multiple R-squared: 0.9981, Adjusted R-squared: 0.9981 # F-statistic: 1.55e+04 on 3 and 87 DF, p-value: < 2.2e-16 invisible(1.48740 + 3.85688 * Ks - 0.12420 * Delta.tau + 0.10999 * Phi) } get.mfARI.no.Phi <- function(Ks, Delta.tau) { # From regression on bounded mfARI parameters (discarding Phi) # made on mar 10 2015 # # Call: # lm(formula = ATARI ~ Ks + Delta.tau, data = params) # # Residuals: # Min 1Q Median 3Q Max # -0.56369 -0.15209 -0.03217 0.16018 0.60636 # # Coefficients: # Estimate Std. Error t value Pr(>|t|) # (Intercept) 6.75148 0.25915 26.05 <2e-16 *** # Ks 2.51501 0.18608 13.52 <2e-16 *** # Delta.tau -0.61895 0.02155 -28.72 <2e-16 *** # --- # Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 # # Residual standard error: 0.2519 on 88 degrees of freedom # Multiple R-squared: 0.9911, Adjusted R-squared: 0.9909 # F-statistic: 4904 on 2 and 88 DF, p-value: < 2.2e-16 invisible(6.75148 + 2.51501 * Ks - 0.61895 * Delta.tau) } # # Returns a plot with the CBFV parameters for a specific Delta-Tau. # get.plot.CBFV.parameters.search <- function( time.instants, normalised.CBFV.signal, min.CBFV.sample, min.CBFV.time.instant, search.results, cbfv.palette = brewer.pal(n = 9, name = "Blues"), id = NULL, ... ) { ymin <- min(normalised.CBFV.signal) ymax <- max(normalised.CBFV.signal) dy <- (ymax - ymin) / 100 dx <- (tail(time.instants, 1) - time.instants[1]) / 100 # Plots CBFV d <- data.frame(Time = time.instants, CBFV = normalised.CBFV.signal) p <- ggplot(data = d, mapping = aes(x = Time, y = CBFV)) p <- p + geom_line(colour = cbfv.palette[4]) p <- p + geom_point(colour = cbfv.palette[4]) # If a transient and a steady CBFV were found if(is.finite(search.results[["CBFV.response.MSE"]])) { # Plots transient CBFV line dtl <- data.frame( Time = search.results[["transient.CBFV.time.instants"]], CBFV = search.results[["transient.CBFV.line"]] ) p <- p + geom_line(data = dtl, colour = cbfv.palette[7]) # Plots initial and final points of the transient CBFV dti <- data.frame( Time = search.results[["transient.CBFV.time.instants"]][1], CBFV = search.results[["transient.normalised.CBFV.signal"]][1] ) p <- p + geom_point(data = dti, colour = cbfv.palette[7]) dtf <- data.frame( Time = tail(search.results[["transient.CBFV.time.instants"]], 1), CBFV = tail(search.results[["transient.normalised.CBFV.signal"]], 1) ) p <- p + geom_point(data = dtf, colour = cbfv.palette[7]) # Adds time annotations d <- dti d[["CBFV"]] <- d[["CBFV"]] - 2 * dy d <- cbind(d, Text = sprintf("%.1f", min.CBFV.time.instant)) p <- p + geom_text( data = d, mapping = aes(label = Text), colour = cbfv.palette[7], size = 2, hjust = 0.5, vjust = 1 ) d <- dtf u <- ifelse(dti[["CBFV"]] < dtf[["CBFV"]], -2 * dy, 3 * dy) d[["CBFV"]] <- dti[["CBFV"]] + u d <- cbind(d, Text = sprintf("%.1f", search.results[["tau"]])) p <- p + geom_text( data = d, mapping = aes(label = Text), colour = cbfv.palette[7], size = 2, hjust = 0.5, vjust = 1 ) d <- dtf d[["Time"]] <- d[["Time"]] - dx u <- ifelse(dti[["CBFV"]] < dtf[["CBFV"]], 2 * dy, -3 * dy) d[["CBFV"]] <- d[["CBFV"]] + u d <- cbind(d, Text = "Tau") p <- p + geom_text( data = d, mapping = aes(label = Text), colour = cbfv.palette[7], size = 2, hjust = 0.5, vjust = 0 ) # Adds lines to annotations d <- rbind(dtf, dtf) d[["CBFV"]][2] <- dti[["CBFV"]] p <- p + geom_line( data = d, colour = cbfv.palette[7], linetype = "dashed" ) # Plots steady CBFV dsl <- data.frame( Time = search.results[["steady.CBFV.time.instants"]], CBFV = search.results[["steady.CBFV.line"]] ) p <- p + geom_line(data = dsl, colour = cbfv.palette[7]) # Adds time annotations d <- tail(dsl, 1) u <- ifelse(dti[["CBFV"]] < dtf[["CBFV"]], -2 * dy, 3 * dy) d[["CBFV"]] <- dti[["CBFV"]] + u s <- sprintf("%.1f", d[["Time"]]) d <- cbind(d, Text = s) p <- p + geom_text( data = d, mapping = aes(label = Text), colour = cbfv.palette[7], size = 2, hjust = 0.5, vjust = 1 ) # Adds lines to annotations u <- ifelse(dti[["CBFV"]] < dtf[["CBFV"]], 2 * dy, -3 * dy) d[["CBFV"]] <- d[["CBFV"]] + u d <- rbind(d[, c(1, 2)], tail(dsl, 1)) p <- p + geom_line( data = d, colour = cbfv.palette[7], linetype = "dashed" ) # Adds summary table s <- sprintf("%.1fs", search.results[["Delta.tau"]]) t <- data.frame(l = "Delta Tau", d = s) s <- sprintf("%.3f", search.results[["Ks"]]) t <- rbind(t, data.frame(l = "Ks", d = s)) s <- sprintf("%.2f°", atan(search.results[["transient.CBFV.slope"]]) * 180 / pi ) t <- rbind(t, data.frame(l = "Angle", d = s)) s <- sprintf("%.4f", search.results[["transient.CBFV.MSE"]]) t <- rbind(t, data.frame(l = "Trans. MSE", d = s)) s <- sprintf("%.4f", search.results[["steady.CBFV.MSE"]]) t <- rbind(t, data.frame(l = "Steady MSE", d = s)) s <- sprintf("%.4f", search.results[["CBFV.response.MSE"]]) t <- rbind(t, data.frame(l = "Total MSE", d = s)) gt <- tableGrob( d = t, show.rownames = FALSE, show.colnames = FALSE, gpar.coretext = gpar(col = cbfv.palette[7], cex = 0.5), padding.v = unit(2, "mm") ) p <- p + annotation_custom( grob = gt, xmin = time.instants[1], xmax = time.instants[1] + 9, ymin = ymin, ymax = ymin + 25 * dy ) } if(!is.null(id)) p <- p + ggtitle(id) p <- p + xlab("Time") + ylab("Normalised CBFV") p } # # Returns a plot with the CBFV parameters for a specific Delta-Tau. # get.plots.mfARI.parameters <- function( time.instants, ABP.signal, CBFV.signal, parameter.results, index.estimation.function = NULL, abp.palette = brewer.pal(n = 9, name = "Reds"), cbfv.palette = brewer.pal(n = 9, name = "Blues"), ann.palette = brewer.pal(n = 9, name = "Greens")[seq(3, 9, 2)], time.tol = min(diff(time.instants)) / 100, id = NULL, ... ) { # # Plot 1 (original signals) # abp.ymin <- min(ABP.signal, na.rm = TRUE) abp.ymax <- max(ABP.signal, na.rm = TRUE) abp.ry <- abp.ymax - abp.ymin abp.dy <- abp.ry / 100 cbfv.ymin <- min(CBFV.signal, na.rm = TRUE) cbfv.ymax <- max(CBFV.signal, na.rm = TRUE) cbfv.ry <- cbfv.ymax - cbfv.ymin cbfv.dy <- cbfv.ry / 100 rx <- tail(time.instants, 1) - time.instants[1] dx <- rx / 100 # Plots ABP dabp <- data.frame( Time = time.instants, Signal = ABP.signal, Segment = "ABP Signal" ) p1 <- ggplot( data = dabp, mapping = aes(x = Time, y = Signal, colour = Segment) ) p1 <- p1 + geom_line(linetype = "dashed") # Plots CBFV dcbfv <- data.frame( Time = time.instants, Signal = CBFV.signal, Segment = "CBFV Signal" ) p2 <- ggplot( data = dabp, mapping = aes(x = Time, y = Signal, colour = Segment) ) p2 <- p2 + geom_line(data = dcbfv, linetype = "dashed") # Plots ABP baseline d <- dabp[parameter.results[["ABP.baseline.samples"]], ] d[["Segment"]] <- "Baseline" p1 <- p1 + geom_point(data = d) d[["Signal"]] <- parameter.results[["ABP.baseline.value"]] p1 <- p1 + geom_line(data = d) # Plots CBFV baseline d <- dcbfv[parameter.results[["CBFV.baseline.samples"]], ] d[["Segment"]] <- "Baseline" p2 <- p2 + geom_point(data = d) d[["Signal"]] <- parameter.results[["CBFV.baseline.value"]] p2 <- p2 + geom_line(data = d) # Plots min ABP window d <- dabp[parameter.results[["min.ABP.samples"]], ] d[["Segment"]] <- "Min. Search Window" p1 <- p1 + geom_point(data = d) d[["Signal"]] <- parameter.results[["min.ABP.value"]] p1 <- p1 + geom_line(data = d, linetype = "dashed") # Plots min CBFV window d <- dcbfv[parameter.results[["min.CBFV.samples"]], ] d[["Segment"]] <- "Min. Search Window" p2 <- p2 + geom_point(data = d) # Adds min ABP time annotation d <- dabp[parameter.results[["min.ABP.sample"]], ] d[["Signal"]] <- d[["Signal"]] - 2 * abp.dy d[["Segment"]] <- "Min. Search Window" d <- cbind(d, Text = sprintf("%.1f", d[["Time"]])) p1 <- p1 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0.5, vjust = 1 ) # Adds min CBFV time annotation d <- dcbfv[parameter.results[["min.CBFV.sample"]], ] d[["Signal"]] <- d[["Signal"]] - 2 * cbfv.dy d[["Segment"]] <- "Min. Search Window" d <- cbind(d, Text = sprintf("%.1f", d[["Time"]])) p2 <- p2 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0.5, vjust = 1 ) # Adds min ABP drop annotation d <- dabp[parameter.results[["min.ABP.samples"]][1], ] d[["Segment"]] <- "Min. Search Window" d[["Signal"]] <- parameter.results[["min.ABP.value"]] - 4 * cbfv.dy d <- cbind( d, Text = sprintf("%.1f%% drop", parameter.results[["min.ABP.drop.pc"]]) ) p1 <- p1 + geom_text( data = d, mapping = aes(label = Text), size = 2, hjust = 0.5, vjust = 1 ) p1 <- p1 + xlab("Time") + ylab("ABP") p2 <- p2 + xlab("Time") + ylab("CBFV") cmatch1 <- c( "ABP Signal" = abp.palette[4], "CBFV Signal" = cbfv.palette[4], "Baseline" = ann.palette[2], "Min. Search Window" = ann.palette[3] ) p1 <- p1 + scale_colour_manual(values = cmatch1, breaks = names(cmatch1)) p2 <- p2 + scale_colour_manual(values = cmatch1, breaks = names(cmatch1)) p1 <- p1 + theme( legend.justification = c(1, 1), legend.background = element_rect(fill = alpha('grey90', 0.0)), legend.position = c(1, 1), legend.key.size = unit(0.3, "cm"), legend.title = element_text(size = 7), legend.text = element_text(size = 6) ) p2 <- p2 + theme( legend.justification = c(1, 1), legend.background = element_rect(fill = alpha('grey90', 0.0)), legend.position = c(1, 1), legend.key.size = unit(0.4, "cm"), legend.title = element_text(size = 7), legend.text = element_text(size = 6) ) # # Plot 3 (normalised signals) # ABP.time <- time.instants - time.instants[parameter.results[["min.ABP.sample"]]] ABP.signal <- parameter.results[["normalised.ABP.signal"]] CBFV.time <- time.instants - time.instants[parameter.results[["min.CBFV.sample"]]] CBFV.signal <- parameter.results[["normalised.CBFV.signal"]] xmin <- min(c(ABP.time, CBFV.time)) xmax <- max(c(ABP.time, CBFV.time)) rx <- xmax - xmin dx <- rx / 100 ymin <- min(c(ABP.signal, CBFV.signal)) ymax <- max(c(ABP.signal, CBFV.signal)) ry <- ymax - ymin dy <- ry / 100 # Plots CBFV dcbfv <- data.frame( Time = CBFV.time, Signal = CBFV.signal, Segment = "Normalised CBFV" ) p3 <- ggplot( data = dcbfv, mapping = aes(x = Time, y = Signal, colour = Segment) ) d <- dcbfv[1:(parameter.results[["transient.CBFV.samples"]][1]), ] p3 <- p3 + geom_line(data = d, linetype = "dashed") r <- tail(parameter.results[["transient.CBFV.samples"]], 1) d <- dcbfv[r:nrow(dcbfv), ] p3 <- p3 + geom_line(data = d, linetype = "dashed") # Plots ABP dabp <- data.frame( Time = ABP.time, Signal = ABP.signal, Segment = "Normalised ABP" ) d <- dabp[1:(parameter.results[["transient.ABP.samples"]][1]), ] p3 <- p3 + geom_line(data = d, linetype = "dashed") r <- tail(parameter.results[["transient.ABP.samples"]], 1) d <- dabp[r:nrow(dabp), ] p3 <- p3 + geom_line(data = d, linetype = "dashed") # Plots ABP transient segment d <- dabp[parameter.results[["transient.ABP.samples"]], ] p3 <- p3 + geom_line(data = d, linetype = "11") d[["Signal"]] <- parameter.results[["transient.ABP.line"]] d[["Segment"]] <- "Transient Line" p3 <- p3 + geom_line(data = d) # Plots CBFV transient segment d <- dcbfv[parameter.results[["transient.CBFV.samples"]], ] p3 <- p3 + geom_line(data = d, linetype = "11") d[["Signal"]] <- parameter.results[["transient.CBFV.line"]] d[["Segment"]] <- "Transient Line" p3 <- p3 + geom_line(data = d) # Plots CBFV steady segment d <- dcbfv[parameter.results[["steady.CBFV.samples"]], ] d[["Signal"]] <- parameter.results[["steady.CBFV.line"]] d[["Segment"]] <- "Steady Line" p3 <- p3 + geom_line(data = d, linetype = "dashed") # Plots and annotates Delta Tau s2 <- parameter.results[["transient.CBFV.samples"]] d2 <- dcbfv[s2, ] y <- min(d2[["Signal"]], na.rm = TRUE) tini2 <- CBFV.time[s2[1]] tfin2 <- CBFV.time[tail(s2, 1)] tini1 <- ABP.time > tini2 - time.tol tfin1 <- ABP.time < tfin2 + time.tol s1 <- which(tini1 & tfin1) d1 <- dabp[s1, ] y <- min(c(d1[["Signal"]], y), na.rm = TRUE) d2[["Signal"]] <- y - 2 * dy d2[["Segment"]] <- "Transient Line" p3 <- p3 + geom_line(data = d2) m <- round(nrow(d2) / 2) d <- d2[m, ] d[["Signal"]] <- d[["Signal"]] - dy s <- paste( "Delta*tau", "==", sprintf("%.1f", parameter.results[["Delta.tau"]]) ) d <- cbind(d, Text = s) p3 <- p3 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0.4, vjust = 1, parse = TRUE ) # Annotates Ks d2 <- dcbfv[parameter.results[["steady.CBFV.samples"]], ] i <- d2[["Signal"]] < parameter.results[["Ks"]] d2[["Signal"]] <- parameter.results[["Ks"]] d2[["Segment"]] <- "Steady Line" p3 <- p3 + geom_line(data = d2) u <- 2 * dy vjust <- 0 if(sum(i) - sum(!i) < 0) { u <- -u vjust <- 1 - vjust } m <- round(nrow(d2) / 2) d <- d2[m, ] d[["Signal"]] <- d[["Signal"]] + u s <- paste("K[s]", "==", sprintf("%.4f", parameter.results[["Ks"]])) d <- cbind(d, Text = s) p3 <- p3 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0.5, vjust = vjust, parse = TRUE ) # Plots and annotates Phi if(!is.null(ABP.signal)) { d1 <- dabp[parameter.results[["transient.ABP.samples"]], ] d1[["Signal"]] <- parameter.results[["transient.ABP.line"]] d2 <- dcbfv[parameter.results[["transient.CBFV.samples"]], ] d2[["Signal"]] <- parameter.results[["transient.CBFV.line"]] m <- round(min(nrow(d1), nrow(d2)) * 0.8) #d <- rbind(d1[m, ], d2[m, ]) #d[["Segment"]] <- "Angle" #p3 <- p3 + geom_point(data = d) r <- d1[["Time"]][m] tt <- seq(-90, 90, length.out = 100) xx <- r * cos(tt * pi / 180) yy <- (sin(tt * pi / 180) + 1) / 2 yy <- sin(tt * pi / 180) #d <- data.frame(Time = xx, Signal = yy, Segment = "Angle") #p3 <- p3 + geom_path(data = d, linetype = "dotted") .dist <- function(x, y) sqrt((x - xx)^2 + (y - yy)^2) .tmp.fun <- function(x, y) min(.dist(x, y)) s1 <- mapply(.tmp.fun, d1[["Time"]], d1[["Signal"]]) s1 <- which.min(s1) s2 <- mapply(.tmp.fun, d2[["Time"]], d2[["Signal"]]) s2 <- which.min(s2) t1 <- ABP.time[parameter.results[["transient.ABP.samples"]][s1]] t2 <- CBFV.time[parameter.results[["transient.CBFV.samples"]][s2]] y1 <- parameter.results[["transient.ABP.line"]][s1] y2 <- parameter.results[["transient.CBFV.line"]][s2] d <- data.frame(Time = c(t1, t2), Signal = c(y1, y2), Segment = "BLA") #p3 <- p3 + geom_point(data = d) i <- yy < max(y1, y2) j <- yy > min(y1, y2) if(sum(i & j) > 0) { d <- data.frame( Time = xx[i & j], Signal = yy[i & j], Segment = "Angle" ) p3 <- p3 + geom_path(data = d, linetype = "11") } i <- yy < max(y1, y2) & yy < 1 j <- yy > min(y1, y2) & yy > 0 if(sum(i & j) > 0) { xx <- xx[i & j] yy <- yy[i & j] d <- data.frame(Time = xx, Signal = yy, Segment = "Angle") p3 <- p3 + geom_path(data = d) } m <- round(nrow(d) / 2) d <- d[m, ] d[["Time"]] <- d[["Time"]] + dx d[["Segment"]] <- "Angle" s <- paste( "varphi", "==", sprintf("%.2f*degree", parameter.results[["Phi"]]) ) d <- cbind(d, Text = s) p3 <- p3 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0, vjust = 0.5, parse = TRUE ) } p3 <- p3 + xlab("Time") + ylab("Normalised Signals") cmatch2 <- c( "Normalised ABP" = abp.palette[4], "Normalised CBFV" = cbfv.palette[4], "Transient Line" = ann.palette[2], "Steady Line" = ann.palette[3], "Angle" = ann.palette[4] ) p3 <- p3 + scale_colour_manual( values = cmatch2, breaks = names(cmatch2) ) p3 <- p3 + theme( legend.justification = c(0, 0), legend.background = element_rect(fill = alpha('grey90', 0.0)), legend.position = c(0, 0), legend.key.size = unit(0.4, "cm"), legend.title = element_text(size = 7), legend.text = element_text(size = 6) ) # # Joins plots # main <- NULL if(!is.null(parameter.results[["mfARI"]])) main <- sprintf("mfARI = %.1f", parameter.results[["mfARI"]]) else if(!is.null(index.estimation.function)) { mfari <- index.estimation.function( Ks = parameter.results[["Ks"]], Delta.tau = parameter.results[["Delta.tau"]], Phi = parameter.results[["Phi"]] ) main <- sprintf("estimated mfARI = %.1f", mfari) } if(!is.null(id)) if(is.null(main)) main <- id else main <- paste(id, main, sep = ", ") p <- arrangeGrob( arrangeGrob(p1, p2, nrow = 2), p3, nrow = 2, main = main ) p } get.plots.mfARI.parameters.fixed.coord <- function( time.instants, ABP.signal, CBFV.signal, parameter.results, time.until.min, time.after.min, min.normalised.intensity, max.normalised.intensity, index.estimation.function = NULL, abp.palette = brewer.pal(n = 9, name = "Reds"), cbfv.palette = brewer.pal(n = 9, name = "Blues"), ann.palette = brewer.pal(n = 9, name = "Greens")[seq(3, 9, 2)], time.tol = min(diff(time.instants)) / 100, id = NULL, ... ) { # # Plot 1 (original signals) # abp.ymin <- min(ABP.signal, na.rm = TRUE) abp.ymax <- max(ABP.signal, na.rm = TRUE) abp.ry <- abp.ymax - abp.ymin abp.dy <- abp.ry / 100 cbfv.ymin <- min(CBFV.signal, na.rm = TRUE) cbfv.ymax <- max(CBFV.signal, na.rm = TRUE) cbfv.ry <- cbfv.ymax - cbfv.ymin cbfv.dy <- cbfv.ry / 100 rx <- tail(time.instants, 1) - time.instants[1] dx <- rx / 100 # Plots ABP dabp <- data.frame( Time = time.instants, Signal = ABP.signal, Segment = "ABP Signal" ) p1 <- ggplot( data = dabp, mapping = aes(x = Time, y = Signal, colour = Segment) ) p1 <- p1 + geom_line(linetype = "dashed") # Plots CBFV dcbfv <- data.frame( Time = time.instants, Signal = CBFV.signal, Segment = "CBFV Signal" ) p2 <- ggplot( data = dabp, mapping = aes(x = Time, y = Signal, colour = Segment) ) p2 <- p2 + geom_line(data = dcbfv, linetype = "dashed") # Plots ABP baseline d <- dabp[parameter.results[["ABP.baseline.samples"]], ] d[["Segment"]] <- "Baseline" p1 <- p1 + geom_point(data = d) d[["Signal"]] <- parameter.results[["ABP.baseline.value"]] p1 <- p1 + geom_line(data = d) # Plots CBFV baseline d <- dcbfv[parameter.results[["CBFV.baseline.samples"]], ] d[["Segment"]] <- "Baseline" p2 <- p2 + geom_point(data = d) d[["Signal"]] <- parameter.results[["CBFV.baseline.value"]] p2 <- p2 + geom_line(data = d) # Plots min ABP window d <- dabp[parameter.results[["min.ABP.samples"]], ] d[["Segment"]] <- "Min. Search Window" p1 <- p1 + geom_point(data = d) d[["Signal"]] <- parameter.results[["min.ABP.value"]] p1 <- p1 + geom_line(data = d, linetype = "dashed") # Plots min CBFV window d <- dcbfv[parameter.results[["min.CBFV.samples"]], ] d[["Segment"]] <- "Min. Search Window" p2 <- p2 + geom_point(data = d) # Adds min ABP time annotation d <- dabp[parameter.results[["min.ABP.sample"]], ] d[["Signal"]] <- d[["Signal"]] - 2 * abp.dy d[["Segment"]] <- "Min. Search Window" d <- cbind(d, Text = sprintf("%.1f", d[["Time"]])) p1 <- p1 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0.5, vjust = 1 ) # Adds min CBFV time annotation d <- dcbfv[parameter.results[["min.CBFV.sample"]], ] d[["Signal"]] <- d[["Signal"]] - 2 * cbfv.dy d[["Segment"]] <- "Min. Search Window" d <- cbind(d, Text = sprintf("%.1f", d[["Time"]])) p2 <- p2 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0.5, vjust = 1 ) # Adds min ABP drop annotation d <- dabp[parameter.results[["min.ABP.samples"]][1], ] d[["Segment"]] <- "Min. Search Window" d[["Signal"]] <- parameter.results[["min.ABP.value"]] - 4 * cbfv.dy d <- cbind( d, Text = sprintf("%.1f%% drop", parameter.results[["min.ABP.drop.pc"]]) ) p1 <- p1 + geom_text( data = d, mapping = aes(label = Text), size = 2, hjust = 0.5, vjust = 1 ) p1 <- p1 + xlab("Time") + ylab("ABP") p2 <- p2 + xlab("Time") + ylab("CBFV") cmatch1 <- c( "ABP Signal" = abp.palette[4], "CBFV Signal" = cbfv.palette[4], "Baseline" = ann.palette[2], "Min. Search Window" = ann.palette[3] ) p1 <- p1 + scale_colour_manual(values = cmatch1, breaks = names(cmatch1)) p2 <- p2 + scale_colour_manual(values = cmatch1, breaks = names(cmatch1)) p1 <- p1 + theme( legend.justification = c(1, 1), legend.background = element_rect(fill = alpha('grey90', 0.0)), legend.position = c(1, 1), legend.key.size = unit(0.3, "cm"), legend.title = element_text(size = 7), legend.text = element_text(size = 6) ) p2 <- p2 + theme( legend.justification = c(1, 1), legend.background = element_rect(fill = alpha('grey90', 0.0)), legend.position = c(1, 1), legend.key.size = unit(0.4, "cm"), legend.title = element_text(size = 7), legend.text = element_text(size = 6) ) # # Plot 3 (normalised signals) # ABP.time <- time.instants - time.instants[parameter.results[["min.ABP.sample"]]] ABP.signal <- parameter.results[["normalised.ABP.signal"]] CBFV.time <- time.instants - time.instants[parameter.results[["min.CBFV.sample"]]] CBFV.signal <- parameter.results[["normalised.CBFV.signal"]] time.ini <- 0 - time.until.min - time.tol time.fin <- 0 + time.after.min + time.tol rx <- time.fin - time.ini dx <- rx / 100 ry <- max.normalised.intensity - min.normalised.intensity dy <- ry / 100 # Plots CBFV dcbfv <- data.frame( Time = CBFV.time, Signal = CBFV.signal, Segment = "Normalised CBFV" ) p3 <- ggplot( data = dcbfv, mapping = aes(x = Time, y = Signal, colour = Segment) ) d <- dcbfv[1:(parameter.results[["transient.CBFV.samples"]][1]), ] p3 <- p3 + geom_line(data = d, linetype = "dashed") r <- tail(parameter.results[["transient.CBFV.samples"]], 1):nrow(dcbfv) d <- dcbfv[r, ] p3 <- p3 + geom_line(data = d, linetype = "dashed") # Plots ABP, if corresponds dabp <- data.frame( Time = ABP.time, Signal = ABP.signal, Segment = "Normalised ABP" ) d <- dabp[1:(parameter.results[["transient.ABP.samples"]][1]), ] p3 <- p3 + geom_line(data = d, linetype = "dashed") d <-dabp[tail(parameter.results[["transient.ABP.samples"]], 1):nrow(dabp), ] p3 <- p3 + geom_line(data = d, linetype = "dashed") # Plots ABP transient segment d <- dabp[parameter.results[["transient.ABP.samples"]], ] p3 <- p3 + geom_line(data = d, linetype = "11") d[["Signal"]] <- parameter.results[["transient.ABP.line"]] d[["Segment"]] <- "Transient Line" p3 <- p3 + geom_line(data = d) # Plots CBFV transient segment d <- dcbfv[parameter.results[["transient.CBFV.samples"]], ] p3 <- p3 + geom_line(data = d, linetype = "11") d[["Signal"]] <- parameter.results[["transient.CBFV.line"]] d[["Segment"]] <- "Transient Line" p3 <- p3 + geom_line(data = d) # Plots CBFV steady segment d <- dcbfv[parameter.results[["steady.CBFV.samples"]], ] d[["Signal"]] <- parameter.results[["steady.CBFV.line"]] d[["Segment"]] <- "Steady Line" p3 <- p3 + geom_line(data = d, linetype = "dashed") # Plots and annotates Delta Tau s2 <- parameter.results[["transient.CBFV.samples"]] d2 <- dcbfv[s2, ] y2 <- min(d2[["Signal"]], na.rm = TRUE) tini2 <- CBFV.time[s2[1]] tfin2 <- CBFV.time[tail(s2, 1)] tini1 <- ABP.time > tini2 - time.tol tfin1 <- ABP.time < tfin2 + time.tol s1 <- which(tini1 & tfin1) d1 <- dabp[s1, ] y1 <- min(d1[["Signal"]], na.rm = TRUE) y <- min(y1, y2) d2[["Signal"]] <- y - 2 * dy d2[["Segment"]] <- "Transient Line" p3 <- p3 + geom_line(data = d2) m <- round(nrow(d2) / 2) d <- d2[m, ] d[["Signal"]] <- d[["Signal"]] - dy s <- paste( "Delta*tau", "==", sprintf("%.1f", parameter.results[["Delta.tau"]]) ) d <- cbind(d, Text = s) p3 <- p3 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0.4, vjust = 1, parse = TRUE ) # Annotates Ks d2 <- dcbfv[parameter.results[["steady.CBFV.samples"]], ] i <- d2[["Signal"]] < parameter.results[["Ks"]] d2[["Signal"]] <- parameter.results[["Ks"]] d2[["Segment"]] <- "Steady Line" p3 <- p3 + geom_line(data = d2) u <- 2 * dy vjust <- 0 if(sum(i) - sum(!i) < 0) { u <- -u vjust <- 1 - vjust } m <- round(nrow(d2) / 2) d <- d2[m, ] d[["Signal"]] <- d[["Signal"]] + u s <- paste("K[s]", "==", sprintf("%.4f", parameter.results[["Ks"]])) d <- cbind(d, Text = s) p3 <- p3 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0.5, vjust = vjust, parse = TRUE ) # Plots and annotates Phi d1 <- dabp[parameter.results[["transient.ABP.samples"]], ] d1[["Signal"]] <- parameter.results[["transient.ABP.line"]] d2 <- dcbfv[parameter.results[["transient.CBFV.samples"]], ] d2[["Signal"]] <- parameter.results[["transient.CBFV.line"]] m <- round(min(nrow(d1), nrow(d2)) * 0.8) #d <- rbind(d1[m, ], d2[m, ]) #d[["Segment"]] <- "Angle" #p3 <- p3 + geom_point(data = d) r <- d1[["Time"]][m] tt <- seq(-90, 90, length.out = 100) xx <- r * cos(tt * pi / 180) yy <- (sin(tt * pi / 180) + 1) / 2 yy <- sin(tt * pi / 180) #d <- data.frame(Time = xx, Signal = yy, Segment = "Angle") #p3 <- p3 + geom_path(data = d, linetype = "dotted") .dist <- function(x, y) sqrt((x - xx)^2 + (y - yy)^2) .tmp.fun <- function(x, y) min(.dist(x, y)) s1 <- mapply(.tmp.fun, d1[["Time"]], d1[["Signal"]]) s1 <- which.min(s1) s2 <- mapply(.tmp.fun, d2[["Time"]], d2[["Signal"]]) s2 <- which.min(s2) t1 <- ABP.time[parameter.results[["transient.ABP.samples"]][s1]] t2 <- CBFV.time[parameter.results[["transient.CBFV.samples"]][s2]] y1 <- parameter.results[["transient.ABP.line"]][s1] y2 <- parameter.results[["transient.CBFV.line"]][s2] #d <- data.frame(Time = c(t1, t2), Signal = c(y1, y2), Segment = "BLA") #p3 <- p3 + geom_point(data = d) i <- yy < max(y1, y2) j <- yy > min(y1, y2) d <- data.frame( Time = xx[i & j], Signal = yy[i & j], Segment = "Angle" ) p3 <- p3 + geom_path(data = d, linetype = "11") i <- yy < max(y1, y2) & yy < 1 j <- yy > min(y1, y2) & yy > 0 if(sum(i & j) > 0) { xx <- xx[i & j] yy <- yy[i & j] d <- data.frame(Time = xx, Signal = yy, Segment = "Angle") p3 <- p3 + geom_path(data = d) } m <- round(nrow(d) / 2) d <- d[m, ] d[["Time"]] <- d[["Time"]] + dx s <- paste( "varphi", "==", sprintf("%.2f*degree", parameter.results[["Phi"]]) ) d <- cbind(d, Text = s) p3 <- p3 + geom_text( data = d, mapping = aes(label = Text), size = 3, hjust = 0, vjust = 0.5, parse = TRUE ) p3 <- p3 + xlab("Time") + ylab("Normalised Signals") cmatch2 <- c( "Normalised ABP" = abp.palette[4], "Normalised CBFV" = cbfv.palette[4], "Transient Line" = ann.palette[2], "Steady Line" = ann.palette[3], "Angle" = ann.palette[4] ) p3 <- p3 + scale_colour_manual( values = cmatch2, breaks = names(cmatch2) ) p3 <- p3 + theme( legend.justification = c(0, 0), legend.background = element_rect(fill = alpha('grey90', 0.0)), legend.position = c(0, 0), legend.key.size = unit(0.4, "cm"), legend.title = element_text(size = 7), legend.text = element_text(size = 6) ) p3 <- p3 + coord_cartesian( xlim = c(time.ini, time.fin), ylim = c(min.normalised.intensity, max.normalised.intensity) ) # # Joins plots # main <- NULL if(!is.null(parameter.results[["mfARI"]])) main <- sprintf("mfARI = %.1f", parameter.results[["mfARI"]]) else if(!is.null(index.estimation.function)) { mfari <- index.estimation.function( Ks = parameter.results[["Ks"]], Delta.tau = parameter.results[["Delta.tau"]], Phi = parameter.results[["Phi"]] ) main <- sprintf("estimated mfARI = %.1f", mfari) } if(!is.null(id)) if(is.null(main)) main <- id else main <- paste(id, main, sep = ", ") p <- arrangeGrob( arrangeGrob(p1, p2, nrow = 2), p3, nrow = 2, main = main ) p } # # Estimates the MSE for specified duration of the transient CBFV signal # In this version, Ks is the value of the normalised CBFV at the end # of the transient period. # # # Would be better to limit the CBFV angle here? # # This would affect the slope and straight line, # # affecting the transient MSE... # # estimate.mfARI.CBFV.parameters.type.2 <- function( time.instants, normalised.CBFV.signal, min.CBFV.sample, min.CBFV.time.instant, transient.CBFV.duration, steady.CBFV.duration, time.tol = min(diff(time.instants)) / 100, ... ) { ans <- list() ans[["Delta.tau"]] <- transient.CBFV.duration ans[["tau"]] <- min.CBFV.time.instant + transient.CBFV.duration ans[["transient.CBFV.samples"]] <- which( time.instants >= min.CBFV.time.instant - time.tol & time.instants <= ans[["tau"]] + time.tol ) ans[["transient.CBFV.time.instants"]] <- time.instants[ans[["transient.CBFV.samples"]]] ans[["transient.normalised.CBFV.signal"]] <- normalised.CBFV.signal[ans[["transient.CBFV.samples"]]] ans[["transient.CBFV.slope"]] <- mean(ans[["transient.normalised.CBFV.signal"]]) / mean(ans[["transient.CBFV.time.instants"]] - min.CBFV.time.instant) ans[["transient.CBFV.line"]] <- ans[["transient.CBFV.slope"]] * (time.instants[ans[["transient.CBFV.samples"]]] - min.CBFV.time.instant) if(length(ans[["transient.normalised.CBFV.signal"]]) > 0) ans[["transient.CBFV.MSE"]] <- get.MSE( sim = ans[["transient.CBFV.line"]], obs = ans[["transient.normalised.CBFV.signal"]] ) else ans[["transient.CBFV.MSE"]] <- Inf ans[["Ks"]] <- tail(ans[["transient.normalised.CBFV.signal"]], 1) ans[["nominal.steady.CBFV.duration"]] <- steady.CBFV.duration ans[["steady.CBFV.samples"]] <- which( time.instants >= ans[["tau"]] - time.tol & time.instants <= ans[["tau"]] + steady.CBFV.duration + time.tol ) ans[["steady.CBFV.time.instants"]] <- time.instants[ans[["steady.CBFV.samples"]]] steady.CBFV.length <- length(ans[["steady.CBFV.samples"]]) ans[["steady.CBFV.duration"]] <- ans[["steady.CBFV.time.instants"]][length(ans[["steady.CBFV.time.instants"]])] - ans[["tau"]] ans[["steady.normalised.CBFV.signal"]] <- normalised.CBFV.signal[ans[["steady.CBFV.samples"]]] ans[["steady.CBFV.line"]] <- rep(ans[["Ks"]], steady.CBFV.length) if(steady.CBFV.length > 0) ans[["steady.CBFV.MSE"]] <- get.MSE( sim = ans[["steady.CBFV.line"]], obs = ans[["steady.normalised.CBFV.signal"]] ) else ans[["steady.CBFV.MSE"]] <- Inf ans[["CBFV.response.duration"]] <- ans[["Delta.tau"]] + ans[["steady.CBFV.duration"]] if(is.finite(ans[["transient.CBFV.MSE"]]) && is.finite(ans[["steady.CBFV.MSE"]])) ans[["CBFV.response.MSE"]] <- (ans[["Delta.tau"]] / ans[["CBFV.response.duration"]]) * ans[["transient.CBFV.MSE"]] + (ans[["steady.CBFV.duration"]] / ans[["CBFV.response.duration"]]) * ans[["steady.CBFV.MSE"]] else ans[["CBFV.response.MSE"]] <- Inf return(ans) } # # Estimates the parameters and MSE for each possible duration of the # transient CBFV signal. # # # Here, if the signal is too short to cover the specified maximum # # transient CBFV duration, this maximum is reduced (keeping the # # specified duration of the steady CBFV signal). # # # For equal MSE values, it prefers the one with lower transient CBFV # # duration. # search.mfARI.CBFV.parameters <- function( time.instants, normalised.CBFV.signal, min.CBFV.sample, min.CBFV.time.instant, min.transient.CBFV.duration, max.transient.CBFV.duration, steady.CBFV.duration, time.tol = min(diff(time.instants)) / 100, estimation.function = estimate.mfARI.CBFV.parameters.type.2, keep.search.results = FALSE, add.search.plots = FALSE, id = NULL, ... ) { min.delta.tau <- min.CBFV.time.instant + min.transient.CBFV.duration max.delta.tau <- min.CBFV.time.instant + max.transient.CBFV.duration last.time <- max.delta.tau + steady.CBFV.duration last.instant <-time.instants[length(time.instants)] if(last.time > last.instant + time.tol) { last.time <- last.instant max.delta.tau <- last.time - steady.CBFV.duration max.transient.CBFV.duration <- max.delta.tau - min.CBFV.time.instant if(is.null(id)) msg <- "Warning: signal is too short for specified parameters;" else msg <- sprintf( "Warning: signal is too short for specified parameters (%s);", id ) msg <- paste( msg, "maximum transient CBFV signal duration was reduced to") msg <- paste( msg, sprintf('%.1f seconds', max.transient.CBFV.duration) ) warning(msg) } i <- which( time.instants >= min.delta.tau - time.tol & time.instants <= max.delta.tau + time.tol ) ans <- list() ans[["Delta.tau.values"]] <- time.instants[i] - min.CBFV.time.instant plots <- list() results <- list() best.result <- list(CBFV.response.MSE = Inf) for(delta.tau in ans[["Delta.tau.values"]]) { current.estimation <- estimation.function( time.instants = time.instants, normalised.CBFV.signal = normalised.CBFV.signal, min.CBFV.sample = min.CBFV.sample, min.CBFV.time.instant = min.CBFV.time.instant, transient.CBFV.duration = delta.tau, steady.CBFV.duration = steady.CBFV.duration, time.tol = time.tol, ... ) if(current.estimation[["CBFV.response.MSE"]] < best.result[["CBFV.response.MSE"]]) best.result <- current.estimation str.delta.tau <- as.character(delta.tau) if(keep.search.results) { lce <- list(current.estimation) names(lce) <- str.delta.tau results <- c(results, lce) } if(add.search.plots) { p <- get.plot.CBFV.parameters.search( time.instants, normalised.CBFV.signal, min.CBFV.sample, min.CBFV.time.instant, current.estimation, id = id, ... ) lp <- list(p) names(lp) <- str.delta.tau plots <- c(plots, lp) } } if(keep.search.results) ans[["search.results"]] <- results if(add.search.plots) ans[["search.plots"]] <- plots ans <- c(ans, best.result) return(ans) } normalise.ABP.signal <- function( time.instants, ABP.signal, sample.release, sampling.time, baseline.initial.time = time.instants[1], baseline.final.time = time.instants[sample.release], min.ABP.max.delta.time = 5 * 0.8, time.tol = sampling.time / 100 ) { ans <- list() valid <- !is.na(ABP.signal) time.release <- time.instants[sample.release] # Adds baseline data to answer if(baseline.final.time < baseline.initial.time) stop("final time for the ABP baseline cannot be ", "before its initial time") if(baseline.final.time > time.release) stop("final time for the ABP baseline cannot be ", "after the release of the thigh cuffs") i <- which(valid & time.instants >= baseline.initial.time - time.tol) if(length(i) == 0) stop("no time instant for the beginning of the ABP baseline could be determined") i <- i[1] ans[["ABP.baseline.initial.time"]] <- time.instants[i] ans[["ABP.baseline.initial.sample"]] <- i i <- which(valid & time.instants <= baseline.final.time + time.tol) if(length(i) == 0) stop("no time instant for the end of the ABP baseline could be determined") i <- tail(i, 1) ans[["ABP.baseline.final.time"]] <- time.instants[i] ans[["ABP.baseline.final.sample"]] <- i ans[["ABP.baseline.samples"]] <- ans[["ABP.baseline.initial.sample"]]:ans[["ABP.baseline.final.sample"]] ans[["ABP.baseline.duration"]] <- ans[["ABP.baseline.final.time"]] - ans[["ABP.baseline.initial.time"]] ans[["ABP.baseline.value"]] <- mean( ABP.signal[ans[["ABP.baseline.samples"]]], na.rm = TRUE ) # Sets min ABP window ans[["min.ABP.max.delta.time"]] <- min.ABP.max.delta.time i <- time.instants > time.release + time.tol j <- time.instants < time.release + ans[["min.ABP.max.delta.time"]] + time.tol ans[["min.ABP.samples"]] <- which(valid & i & j) if(length(ans[["min.ABP.samples"]]) == 0) stop("no candidates for min ABP") # Gets minimum ABP ans[["min.ABP.window"]] <- ABP.signal[ans[["min.ABP.samples"]]] min.sample.in.window <- which.min(ans[["min.ABP.window"]]) min.ABP.sample <- min.sample.in.window + ans[["min.ABP.samples"]][1] - 1 ans[["min.ABP.time.instant"]] <- time.instants[min.ABP.sample] ans[["min.ABP.sample"]] <- min.ABP.sample ans[["min.ABP.value"]] <- ABP.signal[min.ABP.sample] # Gets min ABP type min.info <- findpeaks( -ans[["min.ABP.window"]], zero = "-", sortstr = TRUE ) ans[["min.ABP.type"]] <- "minimum value in window" if(!is.null(min.info) && min.info[1, 2] == min.sample.in.window) ans[["min.ABP.type"]] <- "local minimum" # Measures min ABP drop ans[["min.ABP.drop"]] <- ans[["ABP.baseline.value"]] - ans[["min.ABP.value"]] ans[["min.ABP.drop.pc"]] <- ans[["min.ABP.drop"]] / ans[["ABP.baseline.value"]] ans[["min.ABP.drop.pc"]] <- round(ans[["min.ABP.drop.pc"]] * 100, 2) # Normalises the signal ans[["normalised.ABP.signal"]] <- normalise.signal( signal = ABP.signal, signal.baseline.value = ans[["ABP.baseline.value"]], signal.min.value = ans[["min.ABP.value"]] ) invisible(ans) } normalise.CBFV.signal <- function( time.instants, CBFV.signal, sample.release, sampling.time, baseline.initial.time = time.instants[1], baseline.final.time = time.instants[sample.release], min.CBFV.max.delta.time = 8 * 0.8, time.tol = sampling.time / 100 ) { ans <- list() valid <- !is.na(CBFV.signal) time.release <- time.instants[sample.release] # Adds baseline data to answer if(baseline.final.time < baseline.initial.time) stop("final time for the CBFV baseline cannot be before its initial time") if(baseline.final.time > time.release) stop("final time for the CBFV baseline cannot be after the release of the thigh cuffs") i <- which(valid & time.instants >= baseline.initial.time - time.tol) if(length(i) == 0) stop("no time instant for the beginning of the CBFV baseline could be determined") i <- i[1] ans[["CBFV.baseline.initial.time"]] <- time.instants[i] ans[["CBFV.baseline.initial.sample"]] <- i i <- which(valid & time.instants <= baseline.final.time + time.tol) if(length(i) == 0) stop("no time instant for the end of the CBFV baseline could be determined") i <- tail(i, 1) ans[["CBFV.baseline.final.time"]] <- time.instants[i] ans[["CBFV.baseline.final.sample"]] <- i ans[["CBFV.baseline.samples"]] <- ans[["CBFV.baseline.initial.sample"]]:ans[["CBFV.baseline.final.sample"]] ans[["CBFV.baseline.duration"]] <- ans[["CBFV.baseline.final.time"]] - ans[["CBFV.baseline.initial.time"]] # Gets baseline value ans[["CBFV.baseline.value"]] <- mean(CBFV.signal[ans[["CBFV.baseline.samples"]]], na.rm = TRUE) # Sets min CBFV window ans[["min.CBFV.max.delta.time"]] <- min.CBFV.max.delta.time i <- time.instants > time.release + time.tol j <- time.instants < time.release + ans[["min.CBFV.max.delta.time"]] + time.tol ans[["min.CBFV.samples"]] <- which(valid & i & j) if(length(ans[["min.CBFV.samples"]]) == 0) stop("no candidates for min CBFV") # Gets minimum CBFV ans[["min.CBFV.window"]] <- CBFV.signal[ans[["min.CBFV.samples"]]] min.sample.in.window <- which.min(ans[["min.CBFV.window"]]) min.CBFV.sample <- min.sample.in.window + ans[["min.CBFV.samples"]][1] - 1 ans[["min.CBFV.time.instant"]] <- time.instants[min.CBFV.sample] ans[["min.CBFV.sample"]] <- min.CBFV.sample ans[["min.CBFV.value"]] <- CBFV.signal[min.CBFV.sample] # Gets min CBFV type min.info <- findpeaks( -ans[["min.CBFV.window"]], zero = "-", sortstr = TRUE ) ans[["min.CBFV.type"]] <- "minimum value in window" if(!is.null(min.info) && min.info[1, 2] == min.sample.in.window) ans[["min.CBFV.type"]] <- "local minimum" # Normalises the signal ans[["normalised.CBFV.signal"]] <- normalise.signal( signal = CBFV.signal, signal.baseline.value = ans[["CBFV.baseline.value"]], signal.min.value = ans[["min.CBFV.value"]] ) invisible(ans) } get.mfARI.parameters <- function( time.instants, ABP.signal, CBFV.signal, sampling.time, time.release, baseline.initial.time = time.instants[1], baseline.final.time = time.release, min.ABP.max.delta.time = 5 * 0.8, transient.ABP.duration = 6, min.CBFV.max.delta.time = 8 * 0.8, min.transient.CBFV.duration = 1.5, max.transient.CBFV.duration = 10, steady.CBFV.duration = 6, min.Ks = 0.0, max.Ks = 1.022095, min.ABP.angle = 0.0, max.ABP.angle = 90.0, min.CBFV.angle = 0.0, max.CBFV.angle = 90.0, min.Phi = 0.0, max.Phi = 35.238932, keep.details = TRUE, ABP.rounding.digits = 2, normalised.ABP.rounding.digits = ABP.rounding.digits * 2, CBFV.rounding.digits = 2, normalised.CBFV.rounding.digits = CBFV.rounding.digits * 2, Ks.rounding.digits = 4, Phi.rounding.digits = 2, time.tol = sampling.time / 100, ... # Passed to search.mfARI.CBFV.parameters ) { # Simple validations if(transient.ABP.duration < sampling.time) stop("duration of the transient ABP signal is too short") if(steady.CBFV.duration < sampling.time) stop("duration of the steady CBFV signal is too short") if(max.transient.CBFV.duration < min.transient.CBFV.duration) stop("maximum duration of the transient CBFV signal must be equal or higher than the specified minimum duration") if(max.Ks < min.Ks) stop("maximum value for Ks must be equal or higher than the specified minimum value") if(max.ABP.angle < min.ABP.angle) stop("maximum value for the ABP recovery angle must be equal or higher than the specified minimum value") if(max.CBFV.angle < min.CBFV.angle) stop("maximum value for the CBFV recovery angle must be equal or higher than the specified minimum value") if(max.Phi < min.Phi) stop("maximum value for the difference between ABP and CBFV recovery angles must be equal or higher than the specified minimum value") # Validates the lengths of the signals if(length(ABP.signal) != length(CBFV.signal)) stop("ABP and CBFV signals must be of the same length") if(length(ABP.signal) != length(time.instants)) stop("number of time instants must coincide with the signals") # Validates sampling time if(sampling.time < 0.1 - time.tol) stop("sampling time must be equal or higher than 0.1") # Defines the detailed answer list dans <- list() # Copies the original signals dans[["time.instants"]] <- round(time.instants, 1) dans[["ABP.signal"]] <- round(ABP.signal, ABP.rounding.digits) dans[["CBFV.signal"]] <- round(CBFV.signal, CBFV.rounding.digits) # Sets frequency dans[["sampling.time"]] <- round(sampling.time, 1) dans[["frequency"]] <- 1 / sampling.time # Sets release sample dans[["time.release"]] <- time.release i <- which(are.tolerably.equal(time.instants, time.release, time.tol)) if(length(i) != 1) stop("a unique time instant for the thigh-cuff release could not be determined") dans[["sample.release"]] <- i if(!is.finite(ABP.signal[i])) stop("invalid ABP signal value at the time of thigh-cuff release") if(!is.finite(CBFV.signal[i])) stop("invalid CBFV signal value at the time of thigh-cuff release") # Normalises ABP nabp <- normalise.ABP.signal( time.instants = dans[["time.instants"]], ABP.signal = dans[["ABP.signal"]], sample.release = dans[["sample.release"]], sampling.time = dans[["sampling.time"]], baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.ABP.max.delta.time = min.ABP.max.delta.time, time.tol = time.tol ) nabp[["normalised.ABP.signal"]] <- round( nabp[["normalised.ABP.signal"]], normalised.ABP.rounding.digits ) dans <- c(dans, nabp) # Normalises CBFV ncbfv <- normalise.CBFV.signal( time.instants = dans[["time.instants"]], CBFV.signal = dans[["CBFV.signal"]], sample.release = dans[["sample.release"]], sampling.time = dans[["sampling.time"]], baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.CBFV.max.delta.time = min.CBFV.max.delta.time, time.tol = time.tol ) ncbfv[["normalised.CBFV.signal"]] <- round( ncbfv[["normalised.CBFV.signal"]], normalised.CBFV.rounding.digits ) dans <- c(dans, ncbfv) if(any(nabp[["ABP.baseline.samples"]] != ncbfv[["CBFV.baseline.samples"]])) warning("baseline samples are different for ABP and CBFV") # Search for best Ks and delta-tau search.results <- search.mfARI.CBFV.parameters( time.instants = time.instants, normalised.CBFV.signal = dans[["normalised.CBFV.signal"]], min.CBFV.sample = dans[["min.CBFV.sample"]], min.CBFV.time.instant = dans[["min.CBFV.time.instant"]], min.transient.CBFV.duration = min.transient.CBFV.duration, max.transient.CBFV.duration = max.transient.CBFV.duration, steady.CBFV.duration = steady.CBFV.duration, time.tol = time.tol, ...) dans <- c(dans, search.results) dans[["Delta.tau"]] <- round(dans[["Delta.tau"]], 1) # Bounds Ks parameter if(dans[["Ks"]] < min.Ks) dans[["Ks"]] <- min.Ks if(dans[["Ks"]] > max.Ks) dans[["Ks"]] <- max.Ks dans[["Ks"]] <- round(dans[["Ks"]], Ks.rounding.digits) # Gets transient ABP representation dans[["nominal.transient.ABP.duration"]] <- transient.ABP.duration nominal.transient.ABP.end.time <- dans[["min.ABP.time.instant"]] + transient.ABP.duration dans[["transient.ABP.samples"]] <- which(time.instants >= dans[["min.ABP.time.instant"]] & time.instants <= nominal.transient.ABP.end.time) dans[["transient.ABP.time.instants"]] <- time.instants[dans[["transient.ABP.samples"]]] dans[["transient.ABP.duration"]] <- dans[["transient.ABP.time.instants"]][length(dans[["transient.ABP.time.instants"]])] - dans[["min.ABP.time.instant"]] dans[["transient.normalised.ABP.signal"]] <- dans[["normalised.ABP.signal"]][dans[["transient.ABP.samples"]]] dans[["transient.ABP.slope"]] <- mean(dans[["transient.normalised.ABP.signal"]]) / mean(dans[["transient.ABP.time.instants"]] - dans[["min.ABP.time.instant"]]) dans[["transient.ABP.line"]] <- dans[["transient.ABP.slope"]] * (time.instants[dans[["transient.ABP.samples"]]] - dans[["min.ABP.time.instant"]]) # Gets transient ABP angle dans[["transient.ABP.angle"]] <- atan(dans[["transient.ABP.slope"]]) * 180 / pi dans[["bounded.transient.ABP.angle"]] <- dans[["transient.ABP.angle"]] if(dans[["bounded.transient.ABP.angle"]] < min.ABP.angle) dans[["bounded.transient.ABP.angle"]] <- min.ABP.angle if(dans[["bounded.transient.ABP.angle"]] > max.ABP.angle) dans[["bounded.transient.ABP.angle"]] <- max.ABP.angle # Gets transient CBFV angle dans[["transient.CBFV.angle"]] <- atan(dans[["transient.CBFV.slope"]]) * 180 / pi dans[["bounded.transient.CBFV.angle"]] <- dans[["transient.CBFV.angle"]] if(dans[["bounded.transient.CBFV.angle"]] < min.CBFV.angle) dans[["bounded.transient.CBFV.angle"]] <- min.CBFV.angle if(dans[["bounded.transient.CBFV.angle"]] > max.CBFV.angle) dans[["bounded.transient.CBFV.angle"]] <- max.CBFV.angle # Gets Phi parameter dans[["transient.angles.difference"]] <- dans[["transient.CBFV.angle"]] - dans[["transient.ABP.angle"]] dans[["bounded.transient.angles.difference"]] <- dans[["bounded.transient.CBFV.angle"]] - dans[["bounded.transient.ABP.angle"]] dans[["Phi"]] <- dans[["bounded.transient.angles.difference"]] if(dans[["Phi"]] < min.Phi) dans[["Phi"]] <- min.Phi if(dans[["Phi"]] > max.Phi) dans[["Phi"]] <- max.Phi dans[["Phi"]] <- round(dans[["Phi"]], Phi.rounding.digits) if(!keep.details) { ans <- list() ans[["ABP.baseline.samples"]] <- dans[["ABP.baseline.samples"]] ans[["ABP.baseline.value"]] <- dans[["ABP.baseline.value"]] ans[["min.ABP.samples"]] <- dans[["min.ABP.samples"]] ans[["min.ABP.sample"]] <- dans[["min.ABP.sample"]] ans[["min.ABP.value"]] <- dans[["min.ABP.value"]] ans[["min.ABP.type"]] <- dans[["min.ABP.type"]] ans[["min.ABP.drop.pc"]] <- dans[["min.ABP.drop.pc"]] ans[["CBFV.baseline.samples"]] <- dans[["CBFV.baseline.samples"]] ans[["CBFV.baseline.value"]] <- dans[["CBFV.baseline.value"]] ans[["min.CBFV.samples"]] <- dans[["min.CBFV.samples"]] ans[["min.CBFV.sample"]] <- dans[["min.CBFV.sample"]] ans[["min.CBFV.value"]] <- dans[["min.CBFV.value"]] ans[["min.CBFV.type"]] <- dans[["min.CBFV.type"]] ans[["normalised.ABP.signal"]] <- dans[["normalised.ABP.signal"]] ans[["normalised.CBFV.signal"]] <- dans[["normalised.CBFV.signal"]] ans[["transient.ABP.samples"]] <- dans[["transient.ABP.samples"]] ans[["transient.ABP.slope"]] <- dans[["transient.ABP.slope"]] ans[["transient.ABP.line"]] <- dans[["transient.ABP.line"]] ans[["transient.CBFV.samples"]] <- dans[["transient.CBFV.samples"]] ans[["transient.CBFV.slope"]] <- dans[["transient.CBFV.slope"]] ans[["transient.CBFV.line"]] <- dans[["transient.CBFV.line"]] ans[["steady.CBFV.samples"]] <- dans[["steady.CBFV.samples"]] ans[["steady.CBFV.line"]] <- dans[["steady.CBFV.line"]] ans[["steady.CBFV.duration"]] <- dans[["steady.CBFV.duration"]] ans[["Delta.tau"]] <- dans[["Delta.tau"]] ans[["Ks"]] <- dans[["Ks"]] ans[["Phi"]] <- dans[["Phi"]] } else ans <- dans invisible(ans) } get.unbounded.mfARI.parameters.for.AT.decimal <- function() { sampling.time <- 0.1 time.until.release <- 10 time.after.release <- 20 smooth.step.stimulus <- FALSE filter.order <- 2 cutoff.frequency <- 0.20 left.stabilisation.time <- ifelse(smooth.step.stimulus, 30, 0) time.rounding.digits <- 1 stabilisation.time <- 1 rounding.digits <- 6 min.ABP.max.delta.time <- 5 * 0.8 transient.ABP.duration <- 6 min.CBFV.max.delta.time <- 8 * 0.8 min.transient.CBFV.duration <- 0.1 max.transient.CBFV.duration <- 20 - 6 - 0.1 steady.CBFV.duration <- 6 min.Ks <- -Inf max.Ks <- Inf min.ABP.angle <- -Inf max.ABP.angle <- Inf min.CBFV.angle <- -Inf max.CBFV.angle <- Inf min.Phi <- -Inf max.Phi <- Inf params <- get.AT.decimal.templates.parameters(rounding.digits = rounding.digits) curves <- get.AT.decimal.templates(sampling.time = sampling.time, time.until.release = time.until.release, time.after.release = time.after.release, smooth.step.stimulus = smooth.step.stimulus, filter.order = filter.order, cutoff.frequency = cutoff.frequency, left.stabilisation.time = left.stabilisation.time, time.rounding.digits = time.rounding.digits, stabilisation.time = stabilisation.time, rounding.digits = rounding.digits) .tmp.fun <- function(i) get.mfARI.parameters( time.instants = curves[[i]][["time.instants"]], ABP.signal = curves[[i]][["ABP.normalised"]], CBFV.signal = curves[[i]][["CBFV.step.response"]], sampling.time = curves[[i]][["sampling.time"]], time.release = curves[[i]][["time.release"]], baseline.initial.time = curves[[i]][["time.instants"]][1], baseline.final.time = curves[[i]][["time.release"]], min.ABP.max.delta.time = min.ABP.max.delta.time, transient.ABP.duration = transient.ABP.duration, min.CBFV.max.delta.time = min.CBFV.max.delta.time, min.transient.CBFV.duration = min.transient.CBFV.duration, max.transient.CBFV.duration = max.transient.CBFV.duration, steady.CBFV.duration = steady.CBFV.duration, min.Ks = min.Ks, max.Ks = max.Ks, min.ABP.angle = min.ABP.angle, max.ABP.angle = max.ABP.angle, min.CBFV.angle = min.CBFV.angle, max.CBFV.angle = max.CBFV.angle, min.Phi = min.Phi, max.Phi = max.Phi, rounding.digits = rounding.digits, keep.details = FALSE ) mfARI.curves <- lapply(1:length(curves), .tmp.fun) ATARI <- params[["ARI"]] Ks <- sapply(mfARI.curves, function(c) c[["Ks"]]) Delta.tau <- sapply(mfARI.curves, function(c) c[["Delta.tau"]]) Phi <- sapply(mfARI.curves, function(c) c[["Phi"]]) data.frame(ATARI, Ks, Delta.tau, Phi) } get.bounds.of.mfARI.parameters.for.AT.decimal <- function() { table <- get.unbounded.mfARI.parameters.for.AT.decimal() table[["Delta.tau"]][1] <- max(table[["Delta.tau"]][-1]) mins <- c(min(table[["Ks"]]), min(table[["Delta.tau"]]), min(table[["Phi"]])) maxs <- c(max(table[["Ks"]]), max(table[["Delta.tau"]]), max(table[["Phi"]])) ans <- data.frame(matrix(c(mins, maxs), nrow = 3)) rownames(ans) <- c("Ks", "Delta.tau", "Phi") colnames(ans) <- c("Min", "Max") ans } get.bounded.mfARI.parameters.for.AT.decimal <- function() { sampling.time <- 0.1 time.until.release <- 10 time.after.release <- 20 smooth.step.stimulus <- FALSE filter.order <- 2 cutoff.frequency <- 0.20 left.stabilisation.time <- ifelse(smooth.step.stimulus, 30, 0) time.rounding.digits <- 1 stabilisation.time <- 1 rounding.digits <- 6 min.ABP.max.delta.time <- 5 * 0.8 transient.ABP.duration <- 6 min.CBFV.max.delta.time <- 8 * 0.8 min.transient.CBFV.duration <- 1.5 max.transient.CBFV.duration <- 10.0 steady.CBFV.duration <- 6 min.Ks <- 0.0 max.Ks <- 1.022095 min.ABP.angle <- 0 max.ABP.angle <- 90 min.CBFV.angle <- 0 max.CBFV.angle <- 90 min.Phi <- 0.0 max.Phi <- 35.238932 params <- get.AT.decimal.templates.parameters(rounding.digits = rounding.digits) curves <- get.AT.decimal.templates(sampling.time = sampling.time, time.until.release = time.until.release, time.after.release = time.after.release, smooth.step.stimulus = smooth.step.stimulus, filter.order = filter.order, cutoff.frequency = cutoff.frequency, left.stabilisation.time = left.stabilisation.time, time.rounding.digits = time.rounding.digits, stabilisation.time = stabilisation.time, rounding.digits = rounding.digits) .tmp.fun <- function(i) get.mfARI.parameters( time.instants = curves[[i]][["time.instants"]], ABP.signal = curves[[i]][["ABP.normalised"]], CBFV.signal = curves[[i]][["CBFV.step.response"]], sampling.time = curves[[i]][["sampling.time"]], time.release = curves[[i]][["time.release"]], baseline.initial.time = curves[[i]][["time.instants"]][1], baseline.final.time = curves[[i]][["time.release"]], min.ABP.max.delta.time = min.ABP.max.delta.time, transient.ABP.duration = transient.ABP.duration, min.CBFV.max.delta.time = min.CBFV.max.delta.time, min.transient.CBFV.duration = min.transient.CBFV.duration, max.transient.CBFV.duration = max.transient.CBFV.duration, steady.CBFV.duration = steady.CBFV.duration, min.Ks = min.Ks, max.Ks = max.Ks, min.ABP.angle = min.ABP.angle, max.ABP.angle = max.ABP.angle, min.CBFV.angle = min.CBFV.angle, max.CBFV.angle = max.CBFV.angle, min.Phi = min.Phi, max.Phi = max.Phi, rounding.digits = rounding.digits, keep.details = FALSE ) n <- length(curves) mfARI.curves <- lapply(1:n, .tmp.fun) ATARI <- params[["ARI"]] Ks <- sapply(mfARI.curves, function(c) c[["Ks"]]) Delta.tau <- sapply(mfARI.curves, function(c) c[["Delta.tau"]]) Delta.tau[1] <- max.transient.CBFV.duration Phi <- sapply(mfARI.curves, function(c) c[["Phi"]]) data.frame(ATARI, Ks, Delta.tau, Phi) } get.ATARI.mfARI.linear.relationship <- function() { params <<- get.bounded.mfARI.parameters.for.AT.decimal() model <- lm(ATARI ~ Ks + Delta.tau + Phi, data = params) print(summary(model)) predictions <- stats::predict(model, newdata = params, interval = "confidence") colnames(predictions) <- c("mfARI", "lwr", "upr") params <- cbind(params, predictions) p1 <- ggplot(params, aes(x = ATARI, y = Ks)) p1 <- p1 + geom_line() + geom_point() p2 <- ggplot(params, aes(x = ATARI, y = Delta.tau)) p2 <- p2 + geom_line() + geom_point() p3 <- ggplot(params, aes(x = ATARI, y = Phi)) p3 <- p3 + geom_line() + geom_point() i <- complete.cases(params) print(params[!i]) print(params) g <- ggplot(data = params, aes(x=ATARI, y = mfARI)) g <- g + geom_point() g <- g + stat_smooth(method = "lm", colour = "red") g <- g + xlim(0, 9) + ylim(0, 9) p <- arrangeGrob(p1, p2, p3, g) #capture.output(print(summary(m), prmsd=TRUE, digits=1)) list(model, p) } get.ATARI.mfARI.linear.relationship.no.Phi <- function() { params <<- get.bounded.mfARI.parameters.for.AT.decimal() model <- lm(ATARI ~ Ks + Delta.tau, data = params) print(summary(model)) predictions <- stats::predict(model, newdata = params, interval = "confidence") colnames(predictions) <- c("mfARI", "lwr", "upr") params <- cbind(params, predictions) p1 <- ggplot(params, aes(x = ATARI, y = Ks)) p1 <- p1 + geom_line() + geom_point() p2 <- ggplot(params, aes(x = ATARI, y = Delta.tau)) p2 <- p2 + geom_line() + geom_point() p3 <- ggplot(params, aes(x = ATARI, y = Phi)) p3 <- p3 + geom_line() + geom_point() g <- ggplot(data = params, aes(x=ATARI, y = mfARI)) g <- g + geom_point() g <- g + stat_smooth(method = "lm", colour = "red") g <- g + xlim(0, 9) + ylim(0, 9) p <- arrangeGrob(p1, p2, p3, g) #capture.output(print(summary(m), prmsd=TRUE, digits=1)) list(model, p) } <file_sep># Create remote compute target from azureml.core.compute import BatchAiCompute from azureml.core.compute import ComputeTarget import os import Workspace_Experiment as we ws = we.load_workspace # choose a name for your cluster batchai_cluster_name = os.environ.get("BATCHAI_CLUSTER_NAME", ws.name + "gpu") cluster_min_nodes = os.environ.get("BATCHAI_CLUSTER_MIN_NODES", 1) cluster_max_nodes = os.environ.get("BATCHAI_CLUSTER_MAX_NODES", 3) vm_size = os.environ.get("BATCHAI_CLUSTER_SKU", "STANDARD_NC6") autoscale_enabled = os.environ.get("BATCHAI_CLUSTER_AUTOSCALE_ENABLED", True) if batchai_cluster_name in ws.compute_targets: compute_target = ws.compute_targets[batchai_cluster_name] if compute_target and type(compute_target) is BatchAiCompute: print('found compute target. just use it. ' + batchai_cluster_name) else: print('creating a new compute target...') provisioning_config = BatchAiCompute.provisioning_configuration(vm_size = vm_size, # NC6 is GPU-enabled vm_priority = 'lowpriority', # optional autoscale_enabled = autoscale_enabled, cluster_min_nodes = cluster_min_nodes, cluster_max_nodes = cluster_max_nodes) # create the cluster compute_target = ComputeTarget.create(ws, batchai_cluster_name, provisioning_config) # can poll for a minimum number of nodes and for a specific timeout. # if no min node count is provided it will use the scale settings for the cluster compute_target.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) # For a more detailed view of current BatchAI cluster status, use the 'status' property print(compute_target.status.serialize()) <file_sep> # Change accordingly VERSION <- "v15.9.10" WORK.DIR <- file.path("", "research", "Memoristas", VERSION) CARSIG.SCRIPT.BASENAME <- paste("carSignal", VERSION, sep = "-") CARSIG.SCRIPT.BASENAME <- paste(CARSIG.SCRIPT.BASENAME, "R", sep = ".") CARSIG.SCRIPT.NAME <- file.path(WORK.DIR, CARSIG.SCRIPT.BASENAME) source(CARSIG.SCRIPT.NAME) METRIC.UTILS.SCRIPT.BASENAME <- paste("Metric", "utils", VERSION, sep = "-") METRIC.UTILS.SCRIPT.BASENAME <- paste(METRIC.UTILS.SCRIPT.BASENAME, "R", sep = ".") METRIC.UTILS.SCRIPT.NAME <- file.path(WORK.DIR, METRIC.UTILS.SCRIPT.BASENAME) source(METRIC.UTILS.SCRIPT.NAME) MFARI.SCRIPT.BASENAME <- paste("mfARI", VERSION, sep = "-") MFARI.SCRIPT.BASENAME <- paste(MFARI.SCRIPT.BASENAME, "R", sep = ".") MFARI.SCRIPT.NAME <- file.path(WORK.DIR, MFARI.SCRIPT.BASENAME) source(MFARI.SCRIPT.NAME) ROUND.UTILS.SCRIPT.BASENAME <- paste("Rounding", "utils", VERSION, sep = "-") ROUND.UTILS.SCRIPT.BASENAME <- paste(ROUND.UTILS.SCRIPT.BASENAME, "R", sep = ".") ROUND.UTILS.SCRIPT.NAME <- file.path(WORK.DIR, ROUND.UTILS.SCRIPT.BASENAME) source(ROUND.UTILS.SCRIPT.NAME) plot.manoeuvre.signals <- function( tgt.plot.filename, tgt.plot.id, time.instants, abp.signal, cbfv.signal, sampling.time, time.release, ... ) { mfari <- get.mfARI.parameters( time.instants = time.instants, ABP.signal = abp.signal, CBFV.signal = cbfv.signal, sampling.time = sampling.time, time.release = time.release, keep.details = FALSE, ... ) mfari[["mfARI"]] <- get.mfARI( Ks = mfari[["Ks"]], Delta.tau = mfari[["Delta.tau"]], Phi = mfari[["Phi"]] ) p <- get.plots.mfARI.parameters( time.instants = time.instants, ABP.signal = abp.signal, CBFV.signal = cbfv.signal, parameter.results = mfari, id = tgt.plot.id, ... ) ggsave( filename = tgt.plot.filename, plot = p, width = 11, height = 8, units = "in" ) } plot.subject.signals <- function( subject, src.subject.dir, src.ext = "txt", header = TRUE, tgt.subject.dir, tgt.suffix, tgt.ext = "txt", overwrite = FALSE, manoeuvres, time.col.name = "Time", abp.col.name = "ABP", left.cbfv.col.name = "LCBFV", right.cbfv.col.name = "RCBFV", sampling.time = 0.2, time.release = 0, left.plot.suffix = "Izq", right.plot.suffix = "Der", indent = "", ... ) { plot.created <- FALSE next.indent <- paste0(indent , " ") for(mvre in manoeuvres) { cat(indent, "-- ", mvre, " --\n", sep = "") # Sets the subject source file src.basename <- paste(subject, mvre, sep = "-") src.basename <- paste(src.basename, src.ext, sep = ".") src.filename <- file.path(src.subject.dir, src.basename) if(!file.exists(src.filename)) { cat( next.indent, "Warning: file ", src.filename, " does not exists\n", sep = "" ) next } # Reads the manoeuvre signals mvre.data <- read.table(src.filename, header = header) # Sets plot titles mvre.id <- paste(subject, mvre, sep = ", ") # # Creates the plot for the left hemisphere # cat(next.indent, "-- Left hemisphere --\n", sep = "") # Sets target plot filename tgt.basename <- paste(subject, mvre, tgt.suffix, left.plot.suffix, sep = "-") tgt.basename <- paste(tgt.basename, tgt.ext, sep = ".") tgt.filename <- file.path(tgt.subject.dir, tgt.basename) # If the target plot does not exists or it should not be overwritten if(any(!file.exists(tgt.filename), overwrite)) { # Makes sure the target directory exists dir.create( path = tgt.subject.dir, showWarnings = FALSE, recursive = TRUE, mode = "0711" ) plot.manoeuvre.signals( tgt.plot.filename = tgt.filename, tgt.plot.id = paste(mvre.id, left.plot.suffix, sep = ", "), time.instants = mvre.data[[time.col.name]], abp.signal = mvre.data[[abp.col.name]], cbfv.signal = mvre.data[[left.cbfv.col.name]], sampling.time = sampling.time, time.release = time.release, ... ) plot.created <- TRUE } else cat( next.indent, "Warning: target plot already exist and not overwritten\n", sep = "" ) # # Creates the plot for the right hemisphere # cat(next.indent, "-- Right hemisphere --\n", sep = "") # Sets target plot filename tgt.basename <- paste(subject, mvre, tgt.suffix, right.plot.suffix, sep = "-") tgt.basename <- paste(tgt.basename, tgt.ext, sep = ".") tgt.filename <- file.path(tgt.subject.dir, tgt.basename) # If the target plot does not exists or it should not be overwritten if(any(!file.exists(tgt.filename), overwrite)) { # Makes sure the target directory exists dir.create( path = tgt.subject.dir, showWarnings = FALSE, recursive = TRUE, mode = "0711" ) plot.manoeuvre.signals( tgt.plot.filename = tgt.filename, tgt.plot.id = paste(mvre.id, right.plot.suffix, sep = ", "), time.instants = mvre.data[[time.col.name]], abp.signal = mvre.data[[abp.col.name]], cbfv.signal = mvre.data[[right.cbfv.col.name]], sampling.time = sampling.time, time.release = time.release, ... ) plot.created <- TRUE } else cat( next.indent, "Warning: target plot already exist and not overwritten\n", sep = "" ) } plot.created } run <- function( src.dir = file.path(WORK.DIR, "Data"), src.ext = "txt", header = TRUE, tgt.suffix = paste("mfARI", "plots", sep = "-"), tgt.dir = file.path(WORK.DIR, tgt.suffix), tgt.ext = "pdf", overwrite = FALSE, subjects = c("Sujeto1", "Sujeto2", "Sujeto3"), manoeuvres = c("maniobra1", "maniobra2", "maniobra3"), time.col.name = "Time", abp.col.name = "ABP", left.cbfv.col.name = "LCBFV", right.cbfv.col.name = "RCBFV", left.plot.suffix = "Izq", right.plot.suffix = "Der", sampling.time = 0.2, time.release = 0, baseline.initial.time = -5, baseline.final.time = time.release, min.ABP.max.delta.time = 5 * 0.8, min.CBFV.max.delta.time = 8 * 0.8, time.tol = sampling.time / 100, indent = "" ) { plot.created <- FALSE for(subject in subjects) { cat(indent, "-- ", subject, " --\n", sep = "") # Sets subject directories src.subject.dir <- file.path(src.dir, subject) tgt.subject.dir <- file.path(tgt.dir, subject) subject.plot.created <- plot.subject.signals( subject = subject, src.subject.dir = src.subject.dir, src.ext = src.ext, tgt.subject.dir = tgt.subject.dir, tgt.suffix = tgt.suffix, tgt.ext = tgt.ext, overwrite = overwrite, manoeuvres = manoeuvres, time.col.name = time.col.name, abp.col.name = abp.col.name, left.cbfv.col.name = left.cbfv.col.name, right.cbfv.col.name = right.cbfv.col.name, left.plot.suffix = left.plot.suffix, right.plot.suffix = right.plot.suffix, indent = paste0(indent, " "), header = header, sampling.time = sampling.time, time.release = time.release, baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.ABP.max.delta.time = min.ABP.max.delta.time, min.CBFV.max.delta.time = min.CBFV.max.delta.time, time.tol = time.tol ) plot.created <- any(plot.created, subject.plot.created) } plot.created } <file_sep><<<<<<< HEAD <<<<<<< HEAD import pandas import numpy import scipy.stats import seaborn import matplotlib.pyplot as plt data = pandas.read_csv(‘addhealth_pds.csv’, low_memory=False) data['BIO_SEX’]=data['BIO_SEX’].replace(0, numpy.nan) data['H1GH28’]=data['H1GH28’].replace(0, numpy.nan) data['BIO_SEX’] = pandas.to_numeric(data['BIO_SEX’], errors='coerce’) data['H1GH28’] = pandas.to_numeric(data['H1GH28’], errors='coerce’) #There is a six within the data data = data[(data['BIO_SEX’] == 1) | (data['BIO_SEX’] == 2)] ct=pandas.crosstab(data['BIO_SEX’], data['H1GH28’]) print (ct) # column percentages colsum=ct.sum(axis=0) colpct=ct/colsum print(colpct) # chi-square print ('chi-square value, p value, expected counts’) cs= scipy.stats.chi2_contingency(ct) print (cs) # set variable types data[“H1GH28”] = data[“H1GH28”].astype('category’) # new code for setting variables to numeric: data['BIO_SEX’] = pandas.to_numeric(data['BIO_SEX’], errors='coerce’) # graph percent with nicotine dependence within each smoking frequency group seaborn.factorplot(x=“H1GH28”, y=“BIO_SEX”, data=data, kind=“bar”, ci=None) plt.xlabel('Thougts of Weight’) plt.ylabel('Bio Sex’) ###################Post Hoc Analysis #make a copy of my new subsetted data sub = data.copy() for a in [1, 2, 3, 4, 5, 6]: for b in range((a + 1),9): if b != 7: print (’———————–’) recode1 = {a: a, b: b} sub['COMP1v2’]= data['H1GH28’].map(recode1) # contingency table of observed counts ct1=pandas.crosstab(sub['BIO_SEX’], sub['COMP1v2’]) cs1= scipy.stats.chi2_contingency(ct1) if (cs1[0] > 3.84) & (cs1[1] < 0.003) : print ('chi-square value %f’%cs1[0]) print ('p value %.2E’%cs1[1]) print (ct1) # column percentages colsum=ct1.sum(axis=0) colpct=ct1/colsum print(colpct) ======= import pandas import numpy import scipy.stats import seaborn import matplotlib.pyplot as plt data = pandas.read_csv(‘addhealth_pds.csv’, low_memory=False) data['BIO_SEX’]=data['BIO_SEX’].replace(0, numpy.nan) data['H1GH28’]=data['H1GH28’].replace(0, numpy.nan) data['BIO_SEX’] = pandas.to_numeric(data['BIO_SEX’], errors='coerce’) data['H1GH28’] = pandas.to_numeric(data['H1GH28’], errors='coerce’) #There is a six within the data data = data[(data['BIO_SEX’] == 1) | (data['BIO_SEX’] == 2)] ct=pandas.crosstab(data['BIO_SEX’], data['H1GH28’]) print (ct) # column percentages colsum=ct.sum(axis=0) colpct=ct/colsum print(colpct) # chi-square print ('chi-square value, p value, expected counts’) cs= scipy.stats.chi2_contingency(ct) print (cs) # set variable types data[“H1GH28”] = data[“H1GH28”].astype('category’) # new code for setting variables to numeric: data['BIO_SEX’] = pandas.to_numeric(data['BIO_SEX’], errors='coerce’) # graph percent with nicotine dependence within each smoking frequency group seaborn.factorplot(x=“H1GH28”, y=“BIO_SEX”, data=data, kind=“bar”, ci=None) plt.xlabel('Thougts of Weight’) plt.ylabel('Bio Sex’) ###################Post Hoc Analysis #make a copy of my new subsetted data sub = data.copy() for a in [1, 2, 3, 4, 5, 6]: for b in range((a + 1),9): if b != 7: print (’———————–’) recode1 = {a: a, b: b} sub['COMP1v2’]= data['H1GH28’].map(recode1) # contingency table of observed counts ct1=pandas.crosstab(sub['BIO_SEX’], sub['COMP1v2’]) cs1= scipy.stats.chi2_contingency(ct1) if (cs1[0] > 3.84) & (cs1[1] < 0.003) : print ('chi-square value %f’%cs1[0]) print ('p value %.2E’%cs1[1]) print (ct1) # column percentages colsum=ct1.sum(axis=0) colpct=ct1/colsum print(colpct) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= import pandas import numpy import scipy.stats import seaborn import matplotlib.pyplot as plt data = pandas.read_csv(‘addhealth_pds.csv’, low_memory=False) data['BIO_SEX’]=data['BIO_SEX’].replace(0, numpy.nan) data['H1GH28’]=data['H1GH28’].replace(0, numpy.nan) data['BIO_SEX’] = pandas.to_numeric(data['BIO_SEX’], errors='coerce’) data['H1GH28’] = pandas.to_numeric(data['H1GH28’], errors='coerce’) #There is a six within the data data = data[(data['BIO_SEX’] == 1) | (data['BIO_SEX’] == 2)] ct=pandas.crosstab(data['BIO_SEX’], data['H1GH28’]) print (ct) # column percentages colsum=ct.sum(axis=0) colpct=ct/colsum print(colpct) # chi-square print ('chi-square value, p value, expected counts’) cs= scipy.stats.chi2_contingency(ct) print (cs) # set variable types data[“H1GH28”] = data[“H1GH28”].astype('category’) # new code for setting variables to numeric: data['BIO_SEX’] = pandas.to_numeric(data['BIO_SEX’], errors='coerce’) # graph percent with nicotine dependence within each smoking frequency group seaborn.factorplot(x=“H1GH28”, y=“BIO_SEX”, data=data, kind=“bar”, ci=None) plt.xlabel('Thougts of Weight’) plt.ylabel('Bio Sex’) ###################Post Hoc Analysis #make a copy of my new subsetted data sub = data.copy() for a in [1, 2, 3, 4, 5, 6]: for b in range((a + 1),9): if b != 7: print (’———————–’) recode1 = {a: a, b: b} sub['COMP1v2’]= data['H1GH28’].map(recode1) # contingency table of observed counts ct1=pandas.crosstab(sub['BIO_SEX’], sub['COMP1v2’]) cs1= scipy.stats.chi2_contingency(ct1) if (cs1[0] > 3.84) & (cs1[1] < 0.003) : print ('chi-square value %f’%cs1[0]) print ('p value %.2E’%cs1[1]) print (ct1) # column percentages colsum=ct1.sum(axis=0) colpct=ct1/colsum print(colpct) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep><<<<<<< HEAD <<<<<<< HEAD #Ejemplo de entrenmiento: #https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/ #Elegir cantidad de hidden layesr: #https://wiki.inf.ed.ac.uk/twiki/pub/CSTR/ListenTerm1201415/sak2.pdf #Mejores parametros: #https://arxiv.org/pdf/1709.05206.pdf ##Tuning the Number of Epochs ##Tuning the Batch Size ##Tuning the Number of Neurons ##Tuning the Number of Hidden Layers from __future__ import print_function import pandas as pd import numpy import matplotlib.pyplot as plt import math from keras.models import load_model, Model, Sequential from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.initializers import glorot_uniform from keras.utils import to_categorical from keras.optimizers import Adam from keras import backend as K from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from pandas import DataFrame from pandas.plotting import table class Entrenaiento_1: # evaluate the model on a dataset, returns RMSE in transformed units def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast yhat = list() for i in range(len(output)): # store forecast yhat.append(output[i,0]) # report performance rmse = math.sqrt(mean_squared_error(Y[:,0], yhat)) return rmse # fit an LSTM network to training data def fit_lstm(trainX, trainY, testX, testY, n_batch, n_epochs, n_neurons): # prepare model model = Sequential() model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True, return_sequences=True)) model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') # fit model train_rmse, test_rmse = list(), list() for i in range(n_epochs): model.fit(trainX, trainY, epochs=1, batch_size=n_batch, verbose=0, shuffle=False) model.reset_states() # evaluate model on train data train_rmse.append(Entrenaiento_1.evaluate(model, trainX, trainY, n_batch)) model.reset_states() # evaluate model on test data test_rmse.append(Entrenaiento_1.evaluate(model, testX, testY, n_batch)) model.reset_states() history = DataFrame() history['train'], history['test'] = train_rmse, test_rmse return history def run(trainX, trainY, testX, testY): repeats = 10 n_batch = 2 # (n_batch%trainX.shape[0]) == 0 n_epochs = 50 n_neurons = 10 # run diagnostic tests for i in range(repeats): history = Entrenaiento_1.fit_lstm(trainX, trainY, testX, testY, n_batch, n_epochs, n_neurons) plt.plot(history['train'], color='blue') plt.plot(history['test'], color='orange') print('%d) TrainRMSE=%f, TestRMSE=%f' % (i, history['train'].iloc[-1], history['test'].iloc[-1])) plt.savefig('epochs_diagnostic.png') class Entrenaiento_2: # fit an LSTM network to training data def fit_lstm(trainX, trainY, n_batch, n_epochs, n_neurons): model = Sequential() model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True, return_sequences=True)) model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') for i in range(n_epochs): model.fit(trainX, trainY, epochs=1, batch_size=n_batch, verbose=0, shuffle=False) model.reset_states() return model #Evaluate the Model def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast yhat = list() for i in range(len(output)): # store forecast yhat.append(output[i,0]) # report performance rmse = math.sqrt(mean_squared_error(Y[:,0], yhat)) return rmse # Guardar en formato PNG los resultados def save_results(results, nombre_archivo_resultados): desc = results.describe() #create a subplot without frame plot = plt.subplot(111, frame_on=False) #remove axis plot.xaxis.set_visible(False) plot.yaxis.set_visible(False) #create the table plot and position it in the upper left corner table(plot, desc,loc='upper right') #save the plot as a png file plt.savefig('desc_%s.png'%(nombre_archivo_resultados)) plt.close() results.boxplot() plt.savefig('boxplot_%s.png'%(nombre_archivo_resultados)) plt.close() # run a repeated experiment def experiment(trainX, trainY, testX, testY, repeats, epochs, batch_size, n_neurons): # run experiment error_scores = list() for r in range(repeats): # fit the model lstm_model = Entrenaiento_2.fit_lstm(trainX, trainY, batch_size, epochs, n_neurons) lstm_model.predict(trainX, batch_size=batch_size) # report performance rmse = Entrenaiento_2.evaluate(lstm_model, testX, testY, batch_size) print('%d) Test RMSE: %.3f' % (r+1, rmse)) error_scores.append(rmse) return error_scores def run_epochs(trainX, trainY, testX, testY, nombre_archivo_resultados): nombre_experimento = "_epochs_" results = DataFrame() repeats = 2 # experiment # vary training epochs epochs = [2, 3, 4] batch_size = 1 n_neurons = 1 for e in epochs: results[str(e)] = Entrenaiento_2.experiment(trainX, trainY, testX, testY, repeats, e, batch_size, n_neurons) # summarize results print(results.describe()) # save boxplot Entrenaiento_2.save_results(results, nombre_archivo_resultados+nombre_experimento) ########################################################################################################### nombre_sujeto = "AC" nombre_postura = "ACOSTADO" nombre_emisferio = "DERECHO" PATH = ("C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) # fix random seed for reproducibility numpy.random.seed(7) #Dar formato float a las señales PAMn, VFSCd = PAMn.astype('float32'), VFSCd.astype('float32') PAMn, VFSCd = numpy.array(PAMn), numpy.array(VFSCd) # Validacion Valanceada train_size = int(len(PAMn) * 0.5) test_size = len(PAMn) - train_size train_PAM, train_VFSCd = PAMn[0:train_size], VFSCd[0:train_size] test_PAM, test_VFSCd = PAMn[train_size:len(PAMn)], VFSCd[train_size:len(VFSCd)] # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] train_PAM = numpy.reshape(train_PAM, (train_PAM.shape[0], 1, train_PAM.shape[1])) test_PAM = numpy.reshape(test_PAM, (test_PAM.shape[0], 1, test_PAM.shape[1])) # create and fit the LSTM network ############################################################################################################################################################## nombre_archivo_resultados = nombre_sujeto+"_"+nombre_postura+"_"+nombre_emisferio Entrenaiento_2.run_epochs(train_PAM, train_VFSCd, test_PAM, test_VFSCd, nombre_archivo_resultados+"_MODELO1") Entrenaiento_2.run_epochs(test_PAM, test_VFSCd, train_PAM, train_VFSCd, nombre_archivo_resultados+"_MODELO2") ############################################################################################################################################################## ''' model = Sequential() model.add(LSTM(7, input_shape=(1, 1))) model.add(Dense(1))#activation='sigmoid' model.compile(loss='mse', optimizer='adam') history = model.fit(trainX, trainY, validation_data=(testX, testY), epochs=800, batch_size=50, verbose=0, shuffle=False) # make predictions trainPredict = model.predict(trainX) testPredict = model.predict(testX) # invert predictions trainPredict = scaler.inverse_transform(trainPredict) trainY = scaler.inverse_transform(trainY) testPredict = scaler.inverse_transform(testPredict) testY = scaler.inverse_transform(testY) # calculate root mean squared error trainScore = math.sqrt(mean_squared_error(trainY[:,0], trainPredict[:,0])) print('Train Score: %.2f RMSE' % (trainScore)) testScore = math.sqrt(mean_squared_error(testY[:,0], testPredict[:,0])) print('Test Score: %.2f RMSE' % (testScore)) # shift train predictions for plotting trainPredictPlot = numpy.empty_like(trainPredict) trainPredictPlot[:, :] = numpy.nan trainPredictPlot = trainPredict # shift test predictions for plotting testPredictPlot = numpy.empty_like(testPredict) testPredictPlot[:, :] = numpy.nan testPredictPlot = testPredict #plot loss function plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() ''' # plot baseline and predictions ''' plt.plot(scaler.inverse_transform(VFSCd)) plt.plot(trainPredictPlot) plt.plot(testPredictPlot) plt.show() ''' ''' import plotly.plotly as py import plotly.graph_objs as go import plotly plotly.tools.set_credentials_file(username='luis.orellana777', api_key='<KEY>') trace_high = go.Scatter( x=list(range(1, len(VFSCd))), y=scaler.inverse_transform(VFSCd), name = "VFSCd", line = dict(color = '#17BECF'), opacity = 0.8) trace_low = go.Scatter( x=list(range(1, len(VFSCd))), y=numpy.concatenate((trainPredictPlot, testPredictPlot)), name = "VFSCd Predicted", line = dict(color = '#7F7F7F'), opacity = 0.8) data = [trace_high,trace_low] layout = dict( title = "LSTM VFSCd", xaxis = dict( range = [1, len(VFSCd)]) ) fig = dict(data=data, layout=layout) py.iplot(fig, filename = "LSTM VFSCd") ======= #Ejemplo de entrenmiento: #https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/ #Elegir cantidad de hidden layesr: #https://wiki.inf.ed.ac.uk/twiki/pub/CSTR/ListenTerm1201415/sak2.pdf #Mejores parametros: #https://arxiv.org/pdf/1709.05206.pdf ##Tuning the Number of Epochs ##Tuning the Batch Size ##Tuning the Number of Neurons ##Tuning the Number of Hidden Layers from __future__ import print_function import pandas as pd import numpy import matplotlib.pyplot as plt import math from keras.models import load_model, Model, Sequential from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.initializers import glorot_uniform from keras.utils import to_categorical from keras.optimizers import Adam from keras import backend as K from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from pandas import DataFrame from pandas.plotting import table class Entrenaiento_1: # evaluate the model on a dataset, returns RMSE in transformed units def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast yhat = list() for i in range(len(output)): # store forecast yhat.append(output[i,0]) # report performance rmse = math.sqrt(mean_squared_error(Y[:,0], yhat)) return rmse # fit an LSTM network to training data def fit_lstm(trainX, trainY, testX, testY, n_batch, n_epochs, n_neurons): # prepare model model = Sequential() model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True, return_sequences=True)) model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') # fit model train_rmse, test_rmse = list(), list() for i in range(n_epochs): model.fit(trainX, trainY, epochs=1, batch_size=n_batch, verbose=0, shuffle=False) model.reset_states() # evaluate model on train data train_rmse.append(Entrenaiento_1.evaluate(model, trainX, trainY, n_batch)) model.reset_states() # evaluate model on test data test_rmse.append(Entrenaiento_1.evaluate(model, testX, testY, n_batch)) model.reset_states() history = DataFrame() history['train'], history['test'] = train_rmse, test_rmse return history def run(trainX, trainY, testX, testY): repeats = 10 n_batch = 2 # (n_batch%trainX.shape[0]) == 0 n_epochs = 50 n_neurons = 10 # run diagnostic tests for i in range(repeats): history = Entrenaiento_1.fit_lstm(trainX, trainY, testX, testY, n_batch, n_epochs, n_neurons) plt.plot(history['train'], color='blue') plt.plot(history['test'], color='orange') print('%d) TrainRMSE=%f, TestRMSE=%f' % (i, history['train'].iloc[-1], history['test'].iloc[-1])) plt.savefig('epochs_diagnostic.png') class Entrenaiento_2: # fit an LSTM network to training data def fit_lstm(trainX, trainY, n_batch, n_epochs, n_neurons): model = Sequential() model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True, return_sequences=True)) model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') for i in range(n_epochs): model.fit(trainX, trainY, epochs=1, batch_size=n_batch, verbose=0, shuffle=False) model.reset_states() return model #Evaluate the Model def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast yhat = list() for i in range(len(output)): # store forecast yhat.append(output[i,0]) # report performance rmse = math.sqrt(mean_squared_error(Y[:,0], yhat)) return rmse # Guardar en formato PNG los resultados def save_results(results, nombre_archivo_resultados): desc = results.describe() #create a subplot without frame plot = plt.subplot(111, frame_on=False) #remove axis plot.xaxis.set_visible(False) plot.yaxis.set_visible(False) #create the table plot and position it in the upper left corner table(plot, desc,loc='upper right') #save the plot as a png file plt.savefig('desc_%s.png'%(nombre_archivo_resultados)) plt.close() results.boxplot() plt.savefig('boxplot_%s.png'%(nombre_archivo_resultados)) plt.close() # run a repeated experiment def experiment(trainX, trainY, testX, testY, repeats, epochs, batch_size, n_neurons): # run experiment error_scores = list() for r in range(repeats): # fit the model lstm_model = Entrenaiento_2.fit_lstm(trainX, trainY, batch_size, epochs, n_neurons) lstm_model.predict(trainX, batch_size=batch_size) # report performance rmse = Entrenaiento_2.evaluate(lstm_model, testX, testY, batch_size) print('%d) Test RMSE: %.3f' % (r+1, rmse)) error_scores.append(rmse) return error_scores def run_epochs(trainX, trainY, testX, testY, nombre_archivo_resultados): nombre_experimento = "_epochs_" results = DataFrame() repeats = 2 # experiment # vary training epochs epochs = [2, 3, 4] batch_size = 1 n_neurons = 1 for e in epochs: results[str(e)] = Entrenaiento_2.experiment(trainX, trainY, testX, testY, repeats, e, batch_size, n_neurons) # summarize results print(results.describe()) # save boxplot Entrenaiento_2.save_results(results, nombre_archivo_resultados+nombre_experimento) ########################################################################################################### nombre_sujeto = "AC" nombre_postura = "ACOSTADO" nombre_emisferio = "DERECHO" PATH = ("C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) # fix random seed for reproducibility numpy.random.seed(7) #Dar formato float a las señales PAMn, VFSCd = PAMn.astype('float32'), VFSCd.astype('float32') PAMn, VFSCd = numpy.array(PAMn), numpy.array(VFSCd) # Validacion Valanceada train_size = int(len(PAMn) * 0.5) test_size = len(PAMn) - train_size train_PAM, train_VFSCd = PAMn[0:train_size], VFSCd[0:train_size] test_PAM, test_VFSCd = PAMn[train_size:len(PAMn)], VFSCd[train_size:len(VFSCd)] # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] train_PAM = numpy.reshape(train_PAM, (train_PAM.shape[0], 1, train_PAM.shape[1])) test_PAM = numpy.reshape(test_PAM, (test_PAM.shape[0], 1, test_PAM.shape[1])) # create and fit the LSTM network ############################################################################################################################################################## nombre_archivo_resultados = nombre_sujeto+"_"+nombre_postura+"_"+nombre_emisferio Entrenaiento_2.run_epochs(train_PAM, train_VFSCd, test_PAM, test_VFSCd, nombre_archivo_resultados+"_MODELO1") Entrenaiento_2.run_epochs(test_PAM, test_VFSCd, train_PAM, train_VFSCd, nombre_archivo_resultados+"_MODELO2") ############################################################################################################################################################## ''' model = Sequential() model.add(LSTM(7, input_shape=(1, 1))) model.add(Dense(1))#activation='sigmoid' model.compile(loss='mse', optimizer='adam') history = model.fit(trainX, trainY, validation_data=(testX, testY), epochs=800, batch_size=50, verbose=0, shuffle=False) # make predictions trainPredict = model.predict(trainX) testPredict = model.predict(testX) # invert predictions trainPredict = scaler.inverse_transform(trainPredict) trainY = scaler.inverse_transform(trainY) testPredict = scaler.inverse_transform(testPredict) testY = scaler.inverse_transform(testY) # calculate root mean squared error trainScore = math.sqrt(mean_squared_error(trainY[:,0], trainPredict[:,0])) print('Train Score: %.2f RMSE' % (trainScore)) testScore = math.sqrt(mean_squared_error(testY[:,0], testPredict[:,0])) print('Test Score: %.2f RMSE' % (testScore)) # shift train predictions for plotting trainPredictPlot = numpy.empty_like(trainPredict) trainPredictPlot[:, :] = numpy.nan trainPredictPlot = trainPredict # shift test predictions for plotting testPredictPlot = numpy.empty_like(testPredict) testPredictPlot[:, :] = numpy.nan testPredictPlot = testPredict #plot loss function plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() ''' # plot baseline and predictions ''' plt.plot(scaler.inverse_transform(VFSCd)) plt.plot(trainPredictPlot) plt.plot(testPredictPlot) plt.show() ''' ''' import plotly.plotly as py import plotly.graph_objs as go import plotly plotly.tools.set_credentials_file(username='luis.orellana777', api_key='<KEY>') trace_high = go.Scatter( x=list(range(1, len(VFSCd))), y=scaler.inverse_transform(VFSCd), name = "VFSCd", line = dict(color = '#17BECF'), opacity = 0.8) trace_low = go.Scatter( x=list(range(1, len(VFSCd))), y=numpy.concatenate((trainPredictPlot, testPredictPlot)), name = "VFSCd Predicted", line = dict(color = '#7F7F7F'), opacity = 0.8) data = [trace_high,trace_low] layout = dict( title = "LSTM VFSCd", xaxis = dict( range = [1, len(VFSCd)]) ) fig = dict(data=data, layout=layout) py.iplot(fig, filename = "LSTM VFSCd") >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= #Ejemplo de entrenmiento: #https://machinelearningmastery.com/time-series-prediction-lstm-recurrent-neural-networks-python-keras/ #Elegir cantidad de hidden layesr: #https://wiki.inf.ed.ac.uk/twiki/pub/CSTR/ListenTerm1201415/sak2.pdf #Mejores parametros: #https://arxiv.org/pdf/1709.05206.pdf ##Tuning the Number of Epochs ##Tuning the Batch Size ##Tuning the Number of Neurons ##Tuning the Number of Hidden Layers from __future__ import print_function import pandas as pd import numpy import matplotlib.pyplot as plt import math from keras.models import load_model, Model, Sequential from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.initializers import glorot_uniform from keras.utils import to_categorical from keras.optimizers import Adam from keras import backend as K from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from pandas import DataFrame from pandas.plotting import table class Entrenaiento_1: # evaluate the model on a dataset, returns RMSE in transformed units def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast yhat = list() for i in range(len(output)): # store forecast yhat.append(output[i,0]) # report performance rmse = math.sqrt(mean_squared_error(Y[:,0], yhat)) return rmse # fit an LSTM network to training data def fit_lstm(trainX, trainY, testX, testY, n_batch, n_epochs, n_neurons): # prepare model model = Sequential() model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True, return_sequences=True)) model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') # fit model train_rmse, test_rmse = list(), list() for i in range(n_epochs): model.fit(trainX, trainY, epochs=1, batch_size=n_batch, verbose=0, shuffle=False) model.reset_states() # evaluate model on train data train_rmse.append(Entrenaiento_1.evaluate(model, trainX, trainY, n_batch)) model.reset_states() # evaluate model on test data test_rmse.append(Entrenaiento_1.evaluate(model, testX, testY, n_batch)) model.reset_states() history = DataFrame() history['train'], history['test'] = train_rmse, test_rmse return history def run(trainX, trainY, testX, testY): repeats = 10 n_batch = 2 # (n_batch%trainX.shape[0]) == 0 n_epochs = 50 n_neurons = 10 # run diagnostic tests for i in range(repeats): history = Entrenaiento_1.fit_lstm(trainX, trainY, testX, testY, n_batch, n_epochs, n_neurons) plt.plot(history['train'], color='blue') plt.plot(history['test'], color='orange') print('%d) TrainRMSE=%f, TestRMSE=%f' % (i, history['train'].iloc[-1], history['test'].iloc[-1])) plt.savefig('epochs_diagnostic.png') class Entrenaiento_2: # fit an LSTM network to training data def fit_lstm(trainX, trainY, n_batch, n_epochs, n_neurons): model = Sequential() model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True, return_sequences=True)) model.add(LSTM(n_neurons, batch_input_shape=(n_batch, trainX.shape[1], trainX.shape[2]), stateful=True)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') for i in range(n_epochs): model.fit(trainX, trainY, epochs=1, batch_size=n_batch, verbose=0, shuffle=False) model.reset_states() return model #Evaluate the Model def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast yhat = list() for i in range(len(output)): # store forecast yhat.append(output[i,0]) # report performance rmse = math.sqrt(mean_squared_error(Y[:,0], yhat)) return rmse # Guardar en formato PNG los resultados def save_results(results, nombre_archivo_resultados): desc = results.describe() #create a subplot without frame plot = plt.subplot(111, frame_on=False) #remove axis plot.xaxis.set_visible(False) plot.yaxis.set_visible(False) #create the table plot and position it in the upper left corner table(plot, desc,loc='upper right') #save the plot as a png file plt.savefig('desc_%s.png'%(nombre_archivo_resultados)) plt.close() results.boxplot() plt.savefig('boxplot_%s.png'%(nombre_archivo_resultados)) plt.close() # run a repeated experiment def experiment(trainX, trainY, testX, testY, repeats, epochs, batch_size, n_neurons): # run experiment error_scores = list() for r in range(repeats): # fit the model lstm_model = Entrenaiento_2.fit_lstm(trainX, trainY, batch_size, epochs, n_neurons) lstm_model.predict(trainX, batch_size=batch_size) # report performance rmse = Entrenaiento_2.evaluate(lstm_model, testX, testY, batch_size) print('%d) Test RMSE: %.3f' % (r+1, rmse)) error_scores.append(rmse) return error_scores def run_epochs(trainX, trainY, testX, testY, nombre_archivo_resultados): nombre_experimento = "_epochs_" results = DataFrame() repeats = 2 # experiment # vary training epochs epochs = [2, 3, 4] batch_size = 1 n_neurons = 1 for e in epochs: results[str(e)] = Entrenaiento_2.experiment(trainX, trainY, testX, testY, repeats, e, batch_size, n_neurons) # summarize results print(results.describe()) # save boxplot Entrenaiento_2.save_results(results, nombre_archivo_resultados+nombre_experimento) ########################################################################################################### nombre_sujeto = "AC" nombre_postura = "ACOSTADO" nombre_emisferio = "DERECHO" PATH = ("C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) # fix random seed for reproducibility numpy.random.seed(7) #Dar formato float a las señales PAMn, VFSCd = PAMn.astype('float32'), VFSCd.astype('float32') PAMn, VFSCd = numpy.array(PAMn), numpy.array(VFSCd) # Validacion Valanceada train_size = int(len(PAMn) * 0.5) test_size = len(PAMn) - train_size train_PAM, train_VFSCd = PAMn[0:train_size], VFSCd[0:train_size] test_PAM, test_VFSCd = PAMn[train_size:len(PAMn)], VFSCd[train_size:len(VFSCd)] # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] train_PAM = numpy.reshape(train_PAM, (train_PAM.shape[0], 1, train_PAM.shape[1])) test_PAM = numpy.reshape(test_PAM, (test_PAM.shape[0], 1, test_PAM.shape[1])) # create and fit the LSTM network ############################################################################################################################################################## nombre_archivo_resultados = nombre_sujeto+"_"+nombre_postura+"_"+nombre_emisferio Entrenaiento_2.run_epochs(train_PAM, train_VFSCd, test_PAM, test_VFSCd, nombre_archivo_resultados+"_MODELO1") Entrenaiento_2.run_epochs(test_PAM, test_VFSCd, train_PAM, train_VFSCd, nombre_archivo_resultados+"_MODELO2") ############################################################################################################################################################## ''' model = Sequential() model.add(LSTM(7, input_shape=(1, 1))) model.add(Dense(1))#activation='sigmoid' model.compile(loss='mse', optimizer='adam') history = model.fit(trainX, trainY, validation_data=(testX, testY), epochs=800, batch_size=50, verbose=0, shuffle=False) # make predictions trainPredict = model.predict(trainX) testPredict = model.predict(testX) # invert predictions trainPredict = scaler.inverse_transform(trainPredict) trainY = scaler.inverse_transform(trainY) testPredict = scaler.inverse_transform(testPredict) testY = scaler.inverse_transform(testY) # calculate root mean squared error trainScore = math.sqrt(mean_squared_error(trainY[:,0], trainPredict[:,0])) print('Train Score: %.2f RMSE' % (trainScore)) testScore = math.sqrt(mean_squared_error(testY[:,0], testPredict[:,0])) print('Test Score: %.2f RMSE' % (testScore)) # shift train predictions for plotting trainPredictPlot = numpy.empty_like(trainPredict) trainPredictPlot[:, :] = numpy.nan trainPredictPlot = trainPredict # shift test predictions for plotting testPredictPlot = numpy.empty_like(testPredict) testPredictPlot[:, :] = numpy.nan testPredictPlot = testPredict #plot loss function plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.show() ''' # plot baseline and predictions ''' plt.plot(scaler.inverse_transform(VFSCd)) plt.plot(trainPredictPlot) plt.plot(testPredictPlot) plt.show() ''' ''' import plotly.plotly as py import plotly.graph_objs as go import plotly plotly.tools.set_credentials_file(username='luis.orellana777', api_key='<KEY>') trace_high = go.Scatter( x=list(range(1, len(VFSCd))), y=scaler.inverse_transform(VFSCd), name = "VFSCd", line = dict(color = '#17BECF'), opacity = 0.8) trace_low = go.Scatter( x=list(range(1, len(VFSCd))), y=numpy.concatenate((trainPredictPlot, testPredictPlot)), name = "VFSCd Predicted", line = dict(color = '#7F7F7F'), opacity = 0.8) data = [trace_high,trace_low] layout = dict( title = "LSTM VFSCd", xaxis = dict( range = [1, len(VFSCd)]) ) fig = dict(data=data, layout=layout) py.iplot(fig, filename = "LSTM VFSCd") >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 '''<file_sep>import azureml import matplotlib import matplotlib.pyplot as plt import numpy as np from azureml.core import Run, Workspace from azureml.core import Experiment # load workspace configuration from the config.json file in the current folder. ws = Workspace.from_config() def load_workspace(): return ws def load_experiment(): # create a new experiment experiment_name = 'MNIST_Logistic_Regression' exp = Experiment(workspace=ws, name=experiment_name) return exp<file_sep><<<<<<< HEAD <<<<<<< HEAD # -*- coding: utf-8 -*- """ Editor de Spyder Este es un archivo temporal """ import numpy as np import pandas as pd from scipy import stats from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import silhouette_score from sklearn import preprocessing X = pd.read_csv(r"C:/Users/Luis.O.A/Documents/Analisis Clientes/Dataset2.csv", sep=";") min_max_scaler = preprocessing.MinMaxScaler() df_tr = min_max_scaler.fit_transform(X) df_tr #Verificar Cantidad de Clusters Nc = range(2, 15) kmeans = [KMeans(n_clusters=i) for i in Nc] score = [kmeans[i].fit(df_tr).score(df_tr) for i in range(len(kmeans))] plt.plot(Nc,score) plt.xlabel('Numero de Clusters') plt.ylabel('Score') plt.title('Curva del Codo') plt.show() silhouette_score_values = [silhouette_score(df_tr,kmeans[i].labels_ ,metric='euclidean', sample_size=None, random_state=None) for i in range(len(kmeans))] plt.plot(Nc, silhouette_score_values) plt.title("Silhouette score values vs Numbers of Clusters ") plt.show() kmeans = KMeans(n_clusters=3, random_state=0).fit(df_tr) labels = kmeans.labels_ #Glue back to originaal data X['clusters'] = labels clmns = ['TIPO_EMPRESA', 'FAMILIA', 'CANTIDAD_EMPLEADOS', 'CARTERA', 'REGION', 'ESTADO_SERVICIOS', 'Q_ACUERDOS', 'COMISION', 'DEUDA', 'Q_MESES_COMPRA', 'MES_PRIMERA_COMPRA', 'MES_ULTIMA_COMPRA', 'DIAS_CREDITO', 'CONDICION_ENTREGA', 'PUNTOS', 'PORCENTAJE_NO_PERSONALIZADO', 'MESES_CON_PEDIDOS', 'VF_PROMEDIO', '%_COBERTURA_SUPERMERCADOS', '%_COBERTURA_RESTAURANT', '%_COBERTURA_BV', '%_COBERTURA_MERCHANTS', '$_COBERTURA_SUPERMERCADOS'] #Add the column into our list clmns.extend(['clusters']) print (X[clmns].groupby(['clusters']).mean()) C = kmeans.cluster_centers_ colores=['red','green','blue','cyan','yellow'] asignar=[] for row in labels: asignar.append(colores[row]) pca = PCA(n_components=2, whiten=True).fit(df_tr) X_pca = pca.transform(df_tr) pca_C = PCA(n_components=2, whiten=True).fit(C) X_pca_C = pca_C.transform(C) plt.scatter(X_pca[:, 0], X_pca[:, 1], c=asignar, s=5, cmap='viridis') plt.scatter(X_pca_C[:, 0], X_pca_C[:, 1], c='black', s=20, alpha=0.5); ''' pca = PCA(n_components=2, whiten=True).fit(X) X_pca = pca.transform(X) #Verificar Cantidad de Clusters Nc = range(1, 10) kmeans = [KMeans(n_clusters=i) for i in Nc] score = [kmeans[i].fit(X_pca).score(X_pca) for i in range(len(kmeans))] score plt.plot(Nc,score) plt.xlabel('Numero de Clusters') plt.ylabel('Score') plt.title('Curva del Codo') plt.show() #Aplicar optimo de Numero de Clusters kmeans = KMeans(n_clusters=3).fit(X) labels = kmeans.predict(X) C = kmeans.cluster_centers_ colores=['red','green','blue','cyan','yellow'] asignar=[] for row in labels: asignar.append(colores[row]) ################################ plt.scatter(X_pca[:, 0], X_pca[:, 1], c=asignar, s=10, cmap='viridis') plt.scatter(C[:, 0], C[:, 1], c='black', s=50, alpha=0.5); ################################ #Mostrar Centroides en sus dimensiones originales centers = pca.inverse_transform(kmeans.cluster_centers_) print(centers) #Instancias mas cercanas a clusters closest, _ = pairwise_distances_argmin_min(kmeans.cluster_centers_, X) print(closest)#indices del dataset cobertura=X['PESOS_COBERTURA_SUPERMERCADOS'].values for row in closest: print(cobertura[row]) #Predecir con el modelo ya entrenado X_in = np.array([[-1.30357739e-02,2.28489484e-01,5.18036247e-03,5.15420989e-02,3.05902670e-02,9.99349161e-01,2.60555288e-04,1.95107905e-01,2.11808226e-03,4.26917188e-02,1.58504804e-02,6.45018308e-01,6.03258340e-01,6.35717578e-01,1.29403368e-02,2.49905384e-01,5.10030389e-03,1.03674421e-02,3.62927127e-03,1.07621551e-02,9.89237856e-01,8.57144911e-01,2.27023458e-03,9.26154934e-01,8.09486133e-01,8.69697378e-01,8.21334173e-01,3.97226057e-03,6.62009214e-03]]) X_pca_in = pca.transform(X_in) print(X_pca_in) label_in = kmeans.predict(X_pca_in) print(label_in)#Cluster predicho ''' ''' CON EL DATASET SIN NORMALIZAR (Pre-Procesado Datos con Formulas.csv) import numpy as np import pandas as pd from scipy import stats from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import pairwise_distances_argmin_min from scipy.sparse import csr_matrix from sklearn import preprocessing df = pd.read_csv('C:/Users/luis.orellana.ext/Documents/Analisis de Clientes/Datos Pro-Procesados.csv',sep=';') min_max_scaler = preprocessing.MinMaxScaler() df_tr = min_max_scaler.fit_transform(df) df_tr #Cluster the data kmeans = KMeans(n_clusters=2, random_state=0).fit(df_tr) labels = kmeans.labels_ #Glue back to originaal data df['clusters'] = labels clmns = ['ESTADO_EMPRESA','TIPO_EMPRESA', 'FAMILIA', 'CANTIDAD_EMPLEADOS','CARTERA'] #Add the column into our list clmns.extend(['clusters']) #Lets analyze the clusters print (df[clmns].groupby(['clusters']).mean()) ''' ======= # -*- coding: utf-8 -*- """ Editor de Spyder Este es un archivo temporal """ import numpy as np import pandas as pd from scipy import stats from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import silhouette_score from sklearn import preprocessing X = pd.read_csv(r"C:/Users/Luis.O.A/Documents/Analisis Clientes/Dataset2.csv", sep=";") min_max_scaler = preprocessing.MinMaxScaler() df_tr = min_max_scaler.fit_transform(X) df_tr #Verificar Cantidad de Clusters Nc = range(2, 15) kmeans = [KMeans(n_clusters=i) for i in Nc] score = [kmeans[i].fit(df_tr).score(df_tr) for i in range(len(kmeans))] plt.plot(Nc,score) plt.xlabel('Numero de Clusters') plt.ylabel('Score') plt.title('Curva del Codo') plt.show() silhouette_score_values = [silhouette_score(df_tr,kmeans[i].labels_ ,metric='euclidean', sample_size=None, random_state=None) for i in range(len(kmeans))] plt.plot(Nc, silhouette_score_values) plt.title("Silhouette score values vs Numbers of Clusters ") plt.show() kmeans = KMeans(n_clusters=3, random_state=0).fit(df_tr) labels = kmeans.labels_ #Glue back to originaal data X['clusters'] = labels clmns = ['TIPO_EMPRESA', 'FAMILIA', 'CANTIDAD_EMPLEADOS', 'CARTERA', 'REGION', 'ESTADO_SERVICIOS', 'Q_ACUERDOS', 'COMISION', 'DEUDA', 'Q_MESES_COMPRA', 'MES_PRIMERA_COMPRA', 'MES_ULTIMA_COMPRA', 'DIAS_CREDITO', 'CONDICION_ENTREGA', 'PUNTOS', 'PORCENTAJE_NO_PERSONALIZADO', 'MESES_CON_PEDIDOS', 'VF_PROMEDIO', '%_COBERTURA_SUPERMERCADOS', '%_COBERTURA_RESTAURANT', '%_COBERTURA_BV', '%_COBERTURA_MERCHANTS', '$_COBERTURA_SUPERMERCADOS'] #Add the column into our list clmns.extend(['clusters']) print (X[clmns].groupby(['clusters']).mean()) C = kmeans.cluster_centers_ colores=['red','green','blue','cyan','yellow'] asignar=[] for row in labels: asignar.append(colores[row]) pca = PCA(n_components=2, whiten=True).fit(df_tr) X_pca = pca.transform(df_tr) pca_C = PCA(n_components=2, whiten=True).fit(C) X_pca_C = pca_C.transform(C) plt.scatter(X_pca[:, 0], X_pca[:, 1], c=asignar, s=5, cmap='viridis') plt.scatter(X_pca_C[:, 0], X_pca_C[:, 1], c='black', s=20, alpha=0.5); ''' pca = PCA(n_components=2, whiten=True).fit(X) X_pca = pca.transform(X) #Verificar Cantidad de Clusters Nc = range(1, 10) kmeans = [KMeans(n_clusters=i) for i in Nc] score = [kmeans[i].fit(X_pca).score(X_pca) for i in range(len(kmeans))] score plt.plot(Nc,score) plt.xlabel('Numero de Clusters') plt.ylabel('Score') plt.title('Curva del Codo') plt.show() #Aplicar optimo de Numero de Clusters kmeans = KMeans(n_clusters=3).fit(X) labels = kmeans.predict(X) C = kmeans.cluster_centers_ colores=['red','green','blue','cyan','yellow'] asignar=[] for row in labels: asignar.append(colores[row]) ################################ plt.scatter(X_pca[:, 0], X_pca[:, 1], c=asignar, s=10, cmap='viridis') plt.scatter(C[:, 0], C[:, 1], c='black', s=50, alpha=0.5); ################################ #Mostrar Centroides en sus dimensiones originales centers = pca.inverse_transform(kmeans.cluster_centers_) print(centers) #Instancias mas cercanas a clusters closest, _ = pairwise_distances_argmin_min(kmeans.cluster_centers_, X) print(closest)#indices del dataset cobertura=X['PESOS_COBERTURA_SUPERMERCADOS'].values for row in closest: print(cobertura[row]) #Predecir con el modelo ya entrenado X_in = np.array([[-1.30357739e-02,2.28489484e-01,5.18036247e-03,5.15420989e-02,3.05902670e-02,9.99349161e-01,2.60555288e-04,1.95107905e-01,2.11808226e-03,4.26917188e-02,1.58504804e-02,6.45018308e-01,6.03258340e-01,6.35717578e-01,1.29403368e-02,2.49905384e-01,5.10030389e-03,1.03674421e-02,3.62927127e-03,1.07621551e-02,9.89237856e-01,8.57144911e-01,2.27023458e-03,9.26154934e-01,8.09486133e-01,8.69697378e-01,8.21334173e-01,3.97226057e-03,6.62009214e-03]]) X_pca_in = pca.transform(X_in) print(X_pca_in) label_in = kmeans.predict(X_pca_in) print(label_in)#Cluster predicho ''' ''' CON EL DATASET SIN NORMALIZAR (Pre-Procesado Datos con Formulas.csv) import numpy as np import pandas as pd from scipy import stats from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import pairwise_distances_argmin_min from scipy.sparse import csr_matrix from sklearn import preprocessing df = pd.read_csv('C:/Users/luis.orellana.ext/Documents/Analisis de Clientes/Datos Pro-Procesados.csv',sep=';') min_max_scaler = preprocessing.MinMaxScaler() df_tr = min_max_scaler.fit_transform(df) df_tr #Cluster the data kmeans = KMeans(n_clusters=2, random_state=0).fit(df_tr) labels = kmeans.labels_ #Glue back to originaal data df['clusters'] = labels clmns = ['ESTADO_EMPRESA','TIPO_EMPRESA', 'FAMILIA', 'CANTIDAD_EMPLEADOS','CARTERA'] #Add the column into our list clmns.extend(['clusters']) #Lets analyze the clusters print (df[clmns].groupby(['clusters']).mean()) ''' >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= # -*- coding: utf-8 -*- """ Editor de Spyder Este es un archivo temporal """ import numpy as np import pandas as pd from scipy import stats from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import silhouette_score from sklearn import preprocessing X = pd.read_csv(r"C:/Users/Luis.O.A/Documents/Analisis Clientes/Dataset2.csv", sep=";") min_max_scaler = preprocessing.MinMaxScaler() df_tr = min_max_scaler.fit_transform(X) df_tr #Verificar Cantidad de Clusters Nc = range(2, 15) kmeans = [KMeans(n_clusters=i) for i in Nc] score = [kmeans[i].fit(df_tr).score(df_tr) for i in range(len(kmeans))] plt.plot(Nc,score) plt.xlabel('Numero de Clusters') plt.ylabel('Score') plt.title('Curva del Codo') plt.show() silhouette_score_values = [silhouette_score(df_tr,kmeans[i].labels_ ,metric='euclidean', sample_size=None, random_state=None) for i in range(len(kmeans))] plt.plot(Nc, silhouette_score_values) plt.title("Silhouette score values vs Numbers of Clusters ") plt.show() kmeans = KMeans(n_clusters=3, random_state=0).fit(df_tr) labels = kmeans.labels_ #Glue back to originaal data X['clusters'] = labels clmns = ['TIPO_EMPRESA', 'FAMILIA', 'CANTIDAD_EMPLEADOS', 'CARTERA', 'REGION', 'ESTADO_SERVICIOS', 'Q_ACUERDOS', 'COMISION', 'DEUDA', 'Q_MESES_COMPRA', 'MES_PRIMERA_COMPRA', 'MES_ULTIMA_COMPRA', 'DIAS_CREDITO', 'CONDICION_ENTREGA', 'PUNTOS', 'PORCENTAJE_NO_PERSONALIZADO', 'MESES_CON_PEDIDOS', 'VF_PROMEDIO', '%_COBERTURA_SUPERMERCADOS', '%_COBERTURA_RESTAURANT', '%_COBERTURA_BV', '%_COBERTURA_MERCHANTS', '$_COBERTURA_SUPERMERCADOS'] #Add the column into our list clmns.extend(['clusters']) print (X[clmns].groupby(['clusters']).mean()) C = kmeans.cluster_centers_ colores=['red','green','blue','cyan','yellow'] asignar=[] for row in labels: asignar.append(colores[row]) pca = PCA(n_components=2, whiten=True).fit(df_tr) X_pca = pca.transform(df_tr) pca_C = PCA(n_components=2, whiten=True).fit(C) X_pca_C = pca_C.transform(C) plt.scatter(X_pca[:, 0], X_pca[:, 1], c=asignar, s=5, cmap='viridis') plt.scatter(X_pca_C[:, 0], X_pca_C[:, 1], c='black', s=20, alpha=0.5); ''' pca = PCA(n_components=2, whiten=True).fit(X) X_pca = pca.transform(X) #Verificar Cantidad de Clusters Nc = range(1, 10) kmeans = [KMeans(n_clusters=i) for i in Nc] score = [kmeans[i].fit(X_pca).score(X_pca) for i in range(len(kmeans))] score plt.plot(Nc,score) plt.xlabel('Numero de Clusters') plt.ylabel('Score') plt.title('Curva del Codo') plt.show() #Aplicar optimo de Numero de Clusters kmeans = KMeans(n_clusters=3).fit(X) labels = kmeans.predict(X) C = kmeans.cluster_centers_ colores=['red','green','blue','cyan','yellow'] asignar=[] for row in labels: asignar.append(colores[row]) ################################ plt.scatter(X_pca[:, 0], X_pca[:, 1], c=asignar, s=10, cmap='viridis') plt.scatter(C[:, 0], C[:, 1], c='black', s=50, alpha=0.5); ################################ #Mostrar Centroides en sus dimensiones originales centers = pca.inverse_transform(kmeans.cluster_centers_) print(centers) #Instancias mas cercanas a clusters closest, _ = pairwise_distances_argmin_min(kmeans.cluster_centers_, X) print(closest)#indices del dataset cobertura=X['PESOS_COBERTURA_SUPERMERCADOS'].values for row in closest: print(cobertura[row]) #Predecir con el modelo ya entrenado X_in = np.array([[-1.30357739e-02,2.28489484e-01,5.18036247e-03,5.15420989e-02,3.05902670e-02,9.99349161e-01,2.60555288e-04,1.95107905e-01,2.11808226e-03,4.26917188e-02,1.58504804e-02,6.45018308e-01,6.03258340e-01,6.35717578e-01,1.29403368e-02,2.49905384e-01,5.10030389e-03,1.03674421e-02,3.62927127e-03,1.07621551e-02,9.89237856e-01,8.57144911e-01,2.27023458e-03,9.26154934e-01,8.09486133e-01,8.69697378e-01,8.21334173e-01,3.97226057e-03,6.62009214e-03]]) X_pca_in = pca.transform(X_in) print(X_pca_in) label_in = kmeans.predict(X_pca_in) print(label_in)#Cluster predicho ''' ''' CON EL DATASET SIN NORMALIZAR (Pre-Procesado Datos con Formulas.csv) import numpy as np import pandas as pd from scipy import stats from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import pairwise_distances_argmin_min from scipy.sparse import csr_matrix from sklearn import preprocessing df = pd.read_csv('C:/Users/luis.orellana.ext/Documents/Analisis de Clientes/Datos Pro-Procesados.csv',sep=';') min_max_scaler = preprocessing.MinMaxScaler() df_tr = min_max_scaler.fit_transform(df) df_tr #Cluster the data kmeans = KMeans(n_clusters=2, random_state=0).fit(df_tr) labels = kmeans.labels_ #Glue back to originaal data df['clusters'] = labels clmns = ['ESTADO_EMPRESA','TIPO_EMPRESA', 'FAMILIA', 'CANTIDAD_EMPLEADOS','CARTERA'] #Add the column into our list clmns.extend(['clusters']) #Lets analyze the clusters print (df[clmns].groupby(['clusters']).mean()) ''' >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep>#api= https://biopython.org/DIST/docs/api/Bio.Entrez-module.html #ejemplos url = https://www.ncbi.nlm.nih.gov/books/NBK25499/ from Bio import Entrez import pandas as pd import re # For preprocessing from time import time # To time our operations import spacy # For preprocessing Entrez.email = '<EMAIL>' #Bases de datos = https://www.ncbi.nlm.nih.gov/books/NBK25499/table/chapter4.T._valid_values_of__retmode_and/ #Obtener lista de id por tema y periodo de tiempo #https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=cancer&reldate=99999&datetype=edat&retmax=10&usehistory=y #Sinonimos: https://pubchem.ncbi.nlm.nih.gov/compound/Oxime-_-methoxy-phenyl#section=Synonyms&fullscreen=true #crear lista de palabras claves a buscar y agregar todos los ids encontrados a la lista "pmids" key_words = list() key_words.append("oxime-methoxy-phenyl") key_words.append("SCHEMBL8530447") key_words.append("<KEY>") key_words.append("Methyl N-hydroxybenzenecarboximidoate") key_words.append("methyl (z)-N-hydroxybenzenecarboximidate") key_words.append("Methyl") key_words.append("hydroxybenzenecarboximidoate") key_words.append("hydroxybenzenecarboximidate") key_words.append("methoxy") key_words.append("Oxime") key_words.append("phenyl") #key_words.append("Curcumin") #key_words.append("Diferuloylmethane") #key_words.append("Turmeric Yellow") #key_words.append("Turmeric") pmids = list() for key_word in key_words: handle = Entrez.esearch(db="pubmed", retmax=9999999, term=key_word) records = Entrez.read(handle) # Obtener abstract por id if len(records['IdList']) > 0: pmids.extend(records['IdList']) pmids = (list(pmids)) print(pmids) handle = Entrez.efetch(db="pubmed", id=','.join(map(str, pmids)), retmode="json", rettype="xml") records = Entrez.read(handle) abstracts = list() pmids = list() for pubmed_article in records['PubmedArticle']: try: abstracts.append(pubmed_article['MedlineCitation']['Article']['Abstract']['AbstractText'][0]) pmids.append(pubmed_article['MedlineCitation']['PMID']) except Exception: #abstracts.append("-") #pmids.append("-") pass df = pd.DataFrame({"Ids":pmids, "Abstract":abstracts}) df.to_csv (r'D:\Investigacion Word2Vec\Modelo\pubmed_abstracts.csv', index = None, header=True) print(df) ############LIMPIEZA DE LOS DATOS df.isnull().sum() df = df.dropna().reset_index(drop=True) df.isnull().sum() nlp = spacy.load('en', disable=['ner', 'parser']) # disabling Named Entity Recognition for speed def cleaning(doc): # Lemmatizes and removes stopwords # doc needs to be a spacy Doc object txt = [token.lemma_ for token in doc if not token.is_stop] # Word2Vec uses context words to learn the vector representation of a target word, # if a sentence is only one or two words long, # the benefit for the training is very small if len(txt) > 2: return ' '.join(txt) brief_cleaning = (re.sub("<..........>|<.........>|<........>|<.......>|<......>|<.....>|<....>|<...>|<..>|<.>|[^A-Za-z]+", ' ', str(row)).lower() for row in df['Abstract']) t = time() txt = [cleaning(doc) for doc in nlp.pipe(brief_cleaning, batch_size=5000, n_threads=-1)] print('Time to clean up everything: {} mins'.format(round((time() - t) / 60, 2))) df_clean = pd.DataFrame({'clean': txt}) df_clean = df_clean.dropna().drop_duplicates() df_clean.shape df_clean.to_csv (r'D:\Investigacion Word2Vec\Modelo\pubmed_sentences.csv', index = None, header=True) handle.close()<file_sep># make sure utils.py is in the same directory as this code import matplotlib.pyplot as plt import numpy as np import Load_Dataset as ld # note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the model converge faster. X_train, y_train, X_test, y_test = ld.get_data() # now let's show some randomly chosen images from the traininng set. count = 0 sample_size = 30 plt.figure(figsize = (16, 6)) for i in np.random.permutation(X_train.shape[0])[:sample_size]: count = count + 1 plt.subplot(1, sample_size, count) plt.axhline('') plt.axvline('') plt.text(x=10, y=-10, s=y_train[i], fontsize=18) plt.imshow(X_train[i].reshape(28, 28), cmap=plt.cm.Greys) plt.show()<file_sep>import pandas as pd from pandas.io import gbq import plotly.plotly as py import plotly.graph_objs as go from plotly.tools import FigureFactory as FF project_id = 'titanic-231219' top10_active_users_query = "SELECT * FROM [titanic-231219.titanic.titanic_passenger] LIMIT 10" top10_active_users_df = gbq.to_gbq(top10_active_users_query, project_id=project_id) print (top10_active_users_df) <file_sep># download dataset import os import urllib.request os.makedirs('./Python/Regresion Logistica - Clasificacion Imagenes/data', exist_ok = True) urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz', filename='./Python/Regresion Logistica - Clasificacion Imagenes/data/train-images.gz') urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz', filename='./Python/Regresion Logistica - Clasificacion Imagenes/data/train-labels.gz') urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz', filename='./Python/Regresion Logistica - Clasificacion Imagenes/data/test-images.gz') urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz', filename='./Python/Regresion Logistica - Clasificacion Imagenes/data/test-labels.gz') <file_sep><<<<<<< HEAD <<<<<<< HEAD install.packages('randomForest', dep = TRUE) library(randomForest) install.packages('party', dep = TRUE) library(party) setwd("C:/Users/Luis.O.A/Documents/USACH/Mineria de Datos/grupo 6 Wine Quality") wine <- read.csv('winequality-red.csv', sep=';') ##Mostrar variable con mas outliers source("http://goo.gl/UUyEzD") outlierKD(wine, wine$residual.sugar) remove_outliers <- function(x, na.rm = TRUE, ...) { qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...) H <- 1.5 * IQR(x, na.rm = na.rm) y <- x y[x < (qnt[1] - H)] <- mean(x)#NA y[x > (qnt[2] + H)] <- mean(x)#NA y } wine$alcohol <- remove_outliers(wine$alcohol) wine$sulphates <- remove_outliers(wine$sulphates) wine$pH <- remove_outliers(wine$pH) wine$free.sulfur.dioxid <- remove_outliers(wine$free.sulfur.dioxid) wine$chlorides <- remove_outliers(wine$chlorides) wine$residual.sugar <- remove_outliers(wine$residual.sugar) wine$citric.acid <- remove_outliers(wine$citric.acid) wine$volatile.acidity <- remove_outliers(wine$volatile.acidity) wine$fixed.acidity <- remove_outliers(wine$fixed.acidity) #Normalizacion dataNorm <- as.data.frame( scale(wine[1:12] )) #Etiquetar instancias dataNorm$taste <- ifelse(dataNorm$quality <= -2.02586, 'malo', 'regular') dataNorm$taste[dataNorm$quality >= 1.68899] <- 'bueno' dataNorm$taste <- as.factor(dataNorm$taste) barplot(table(dataNorm$taste)) ############ Ramdom Forest ############ set.seed(123) samp <- sample(nrow(dataNorm), 0.75 * nrow(dataNorm)) train <- dataNorm[samp, ] test <- dataNorm[-samp, ] model <- randomForest(taste ~ . - quality, data = train, importance=TRUE, proximity=TRUE, ntree=1000) model ####Con outliers: OOB estimate of error rate: 10.93% ####Sin outliers: OOB estimate of error rate: 11.01% pred <- predict(model, newdata = test) table(pred, test$taste) ################# ##Sin Outliers #Accuracy (29 + 0 + 344) / nrow(test) #0.9109375 = 91% #P = 29/(29+19) = 0.604 #R = 29/(29+5) = 0.853 #FScore (2*0.604*0.853)/(0.604 + 0.853) # 0.7072231 ################# ##Con Outliers #Accuracy (29 + 0 + 342) / nrow(test) #P = 29/(29+19) = 0.604 #R = 29/(29+7) = 0.8055556 #FScore (2*0.604*0.8055556)/(0.604 + 0.8055556) #0.6903674 ################# #Configuracion optima model <- randomForest(taste ~ . - quality, data = train, importance=TRUE, proximity=TRUE, ntree=1000, mtry=8) # Grafica de error vs arboles plot(model) legend("bottomright", colnames(model$err.rate),col=1:4,cex=0.8,fill=1:4) ############## #Ver calidad de las variables round(importance(model), 2) varImpPlot(model) mds <- cmdscale(1 - model$proximity, eig=TRUE) op <- par(pty="s") pairs(cbind(train[1:11], mds$points), cex=0.6, gap=0, col=c("red", "green", "blue")[as.numeric(test$taste)], main="Wine Data: Predictors and MDS of Proximity Based on RandomForest") par(op) print(mds$GOF) MDSplot(model, test$taste) ======= install.packages('randomForest', dep = TRUE) library(randomForest) install.packages('party', dep = TRUE) library(party) setwd("C:/Users/Luis.O.A/Documents/USACH/Mineria de Datos/grupo 6 Wine Quality") wine <- read.csv('winequality-red.csv', sep=';') ##Mostrar variable con mas outliers source("http://goo.gl/UUyEzD") outlierKD(wine, wine$residual.sugar) remove_outliers <- function(x, na.rm = TRUE, ...) { qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...) H <- 1.5 * IQR(x, na.rm = na.rm) y <- x y[x < (qnt[1] - H)] <- mean(x)#NA y[x > (qnt[2] + H)] <- mean(x)#NA y } wine$alcohol <- remove_outliers(wine$alcohol) wine$sulphates <- remove_outliers(wine$sulphates) wine$pH <- remove_outliers(wine$pH) wine$free.sulfur.dioxid <- remove_outliers(wine$free.sulfur.dioxid) wine$chlorides <- remove_outliers(wine$chlorides) wine$residual.sugar <- remove_outliers(wine$residual.sugar) wine$citric.acid <- remove_outliers(wine$citric.acid) wine$volatile.acidity <- remove_outliers(wine$volatile.acidity) wine$fixed.acidity <- remove_outliers(wine$fixed.acidity) #Normalizacion dataNorm <- as.data.frame( scale(wine[1:12] )) #Etiquetar instancias dataNorm$taste <- ifelse(dataNorm$quality <= -2.02586, 'malo', 'regular') dataNorm$taste[dataNorm$quality >= 1.68899] <- 'bueno' dataNorm$taste <- as.factor(dataNorm$taste) barplot(table(dataNorm$taste)) ############ Ramdom Forest ############ set.seed(123) samp <- sample(nrow(dataNorm), 0.75 * nrow(dataNorm)) train <- dataNorm[samp, ] test <- dataNorm[-samp, ] model <- randomForest(taste ~ . - quality, data = train, importance=TRUE, proximity=TRUE, ntree=1000) model ####Con outliers: OOB estimate of error rate: 10.93% ####Sin outliers: OOB estimate of error rate: 11.01% pred <- predict(model, newdata = test) table(pred, test$taste) ################# ##Sin Outliers #Accuracy (29 + 0 + 344) / nrow(test) #0.9109375 = 91% #P = 29/(29+19) = 0.604 #R = 29/(29+5) = 0.853 #FScore (2*0.604*0.853)/(0.604 + 0.853) # 0.7072231 ################# ##Con Outliers #Accuracy (29 + 0 + 342) / nrow(test) #P = 29/(29+19) = 0.604 #R = 29/(29+7) = 0.8055556 #FScore (2*0.604*0.8055556)/(0.604 + 0.8055556) #0.6903674 ################# #Configuracion optima model <- randomForest(taste ~ . - quality, data = train, importance=TRUE, proximity=TRUE, ntree=1000, mtry=8) # Grafica de error vs arboles plot(model) legend("bottomright", colnames(model$err.rate),col=1:4,cex=0.8,fill=1:4) ############## #Ver calidad de las variables round(importance(model), 2) varImpPlot(model) mds <- cmdscale(1 - model$proximity, eig=TRUE) op <- par(pty="s") pairs(cbind(train[1:11], mds$points), cex=0.6, gap=0, col=c("red", "green", "blue")[as.numeric(test$taste)], main="Wine Data: Predictors and MDS of Proximity Based on RandomForest") par(op) print(mds$GOF) MDSplot(model, test$taste) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= install.packages('randomForest', dep = TRUE) library(randomForest) install.packages('party', dep = TRUE) library(party) setwd("C:/Users/Luis.O.A/Documents/USACH/Mineria de Datos/grupo 6 Wine Quality") wine <- read.csv('winequality-red.csv', sep=';') ##Mostrar variable con mas outliers source("http://goo.gl/UUyEzD") outlierKD(wine, wine$residual.sugar) remove_outliers <- function(x, na.rm = TRUE, ...) { qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...) H <- 1.5 * IQR(x, na.rm = na.rm) y <- x y[x < (qnt[1] - H)] <- mean(x)#NA y[x > (qnt[2] + H)] <- mean(x)#NA y } wine$alcohol <- remove_outliers(wine$alcohol) wine$sulphates <- remove_outliers(wine$sulphates) wine$pH <- remove_outliers(wine$pH) wine$free.sulfur.dioxid <- remove_outliers(wine$free.sulfur.dioxid) wine$chlorides <- remove_outliers(wine$chlorides) wine$residual.sugar <- remove_outliers(wine$residual.sugar) wine$citric.acid <- remove_outliers(wine$citric.acid) wine$volatile.acidity <- remove_outliers(wine$volatile.acidity) wine$fixed.acidity <- remove_outliers(wine$fixed.acidity) #Normalizacion dataNorm <- as.data.frame( scale(wine[1:12] )) #Etiquetar instancias dataNorm$taste <- ifelse(dataNorm$quality <= -2.02586, 'malo', 'regular') dataNorm$taste[dataNorm$quality >= 1.68899] <- 'bueno' dataNorm$taste <- as.factor(dataNorm$taste) barplot(table(dataNorm$taste)) ############ Ramdom Forest ############ set.seed(123) samp <- sample(nrow(dataNorm), 0.75 * nrow(dataNorm)) train <- dataNorm[samp, ] test <- dataNorm[-samp, ] model <- randomForest(taste ~ . - quality, data = train, importance=TRUE, proximity=TRUE, ntree=1000) model ####Con outliers: OOB estimate of error rate: 10.93% ####Sin outliers: OOB estimate of error rate: 11.01% pred <- predict(model, newdata = test) table(pred, test$taste) ################# ##Sin Outliers #Accuracy (29 + 0 + 344) / nrow(test) #0.9109375 = 91% #P = 29/(29+19) = 0.604 #R = 29/(29+5) = 0.853 #FScore (2*0.604*0.853)/(0.604 + 0.853) # 0.7072231 ################# ##Con Outliers #Accuracy (29 + 0 + 342) / nrow(test) #P = 29/(29+19) = 0.604 #R = 29/(29+7) = 0.8055556 #FScore (2*0.604*0.8055556)/(0.604 + 0.8055556) #0.6903674 ################# #Configuracion optima model <- randomForest(taste ~ . - quality, data = train, importance=TRUE, proximity=TRUE, ntree=1000, mtry=8) # Grafica de error vs arboles plot(model) legend("bottomright", colnames(model$err.rate),col=1:4,cex=0.8,fill=1:4) ############## #Ver calidad de las variables round(importance(model), 2) varImpPlot(model) mds <- cmdscale(1 - model$proximity, eig=TRUE) op <- par(pty="s") pairs(cbind(train[1:11], mds$points), cex=0.6, gap=0, col=c("red", "green", "blue")[as.numeric(test$taste)], main="Wine Data: Predictors and MDS of Proximity Based on RandomForest") par(op) print(mds$GOF) MDSplot(model, test$taste) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 legend("bottomright", colnames(model$classes),col=1:3,cex=0.8,fill=1:3, legend=model$classes)<file_sep>from utils import load_data def get_data(): # note we also shrink the intensity values (X) from 0-255 to 0-1. This helps the model converge faster. X_train = load_data('./Python/Regresion Logistica - Clasificacion Imagenes/data/train-images.gz', False) / 255.0 y_train = load_data('./Python/Regresion Logistica - Clasificacion Imagenes/data/train-labels.gz', True).reshape(-1) X_test = load_data('./Python/Regresion Logistica - Clasificacion Imagenes/data/test-images.gz', False) / 255.0 y_test = load_data('./Python/Regresion Logistica - Clasificacion Imagenes/data/test-labels.gz', True).reshape(-1) return X_train, y_train, X_test, y_test <file_sep><<<<<<< HEAD <<<<<<< HEAD #<NAME> #Carga dataset ZOO data_zoo = read.csv("zoo-tree1.csv") #Discretiza datos data_zoo["animal_name"] <- NULL data_zoo <- data.frame(sapply(data_zoo,as.factor)) # Clasifica los modelos de árbol usando el algoritmo de Quinlan C5.0 c50_result<-C5.0(class_type~.,data=data_zoo) # Despliega resumen detallado para los modelos C.50 summary(c50_result) # calcula y despliega la importancia de la variable para el modelo C5.0 importanceC5imp(c50_result,metric='usage') #REGLAS. # Generar reglas a partir del arcol de decisión de los modelos C.50 ruleModel <- C5.0(type ~ ., data = data_zoo, rules = TRUE) ruleModel # Despliega resumen detallado para las reglas de los modelos C.50 summary(ruleModel) #VALIDACION CRUZADA. library(arulesViz) install.packages('partykit', dep = TRUE) install.packages('gmodels', dep = TRUE) library(partykit) library(C50) library(gmodels) library(plyr) data_zoo = read.csv("zoo-tree1.csv") #Carga dataset data_zoo["animal_name"] <- NULL data_zoo <- data.frame(sapply(data_zoo,as.factor)) #Discretiza datos form <- "class_type ~ hair+feathers+eggs+milk+airborne+aquatic+predator+toothed+backbone+breathes+venomous+fins+legs0+legs2+legs4+legs5+legs6+legs8+tail+domestic+catsize" folds <- split(data_zoo , cut(sample(1:nrow(data_zoo)),10)) length(folds) folds errs.c50 <- rep(NA, length(folds)) for (i in 1:length(folds)) { test <- ldply(folds[i], data.frame) train <- ldply(folds[-i], data.frame) tmp.model <- C5.0(as.formula(form), train) tmp.predict <- predict(tmp.model, newdata=test) conf.mat <- table(test$class_type , tmp.predict) errs.c50[i] <- 1 - sum(diag(conf.mat))/sum(conf.mat) } print(sprintf("El promedio de error usando la validación cruzada k-fold y el algoritmo de arbol de decision C5.0 es: %.3f percent", 100*mean(errs.c50))) ======= #ARBOL BINARIO #Carga dataset ZOO data_zoo = read.csv("zoo-tree1.csv") #Discretiza datos data_zoo["animal_name"] <- NULL data_zoo <- data.frame(sapply(data_zoo,as.factor)) # Clasifica los modelos de árbol usando el algoritmo de Quinlan C5.0 c50_result<-C5.0(class_type~.,data=data_zoo) # Despliega resumen detallado para los modelos C.50 summary(c50_result) # calcula y despliega la importancia de la variable para el modelo C5.0 importanceC5imp(c50_result,metric='usage') #REGLAS. # Generar reglas a partir del arcol de decisión de los modelos C.50 ruleModel <- C5.0(type ~ ., data = data_zoo, rules = TRUE) ruleModel # Despliega resumen detallado para las reglas de los modelos C.50 summary(ruleModel) #VALIDACION CRUZADA. library(arulesViz) install.packages('partykit', dep = TRUE) install.packages('gmodels', dep = TRUE) library(partykit) library(C50) library(gmodels) library(plyr) data_zoo = read.csv("zoo-tree1.csv") #Carga dataset data_zoo["animal_name"] <- NULL data_zoo <- data.frame(sapply(data_zoo,as.factor)) #Discretiza datos form <- "class_type ~ hair+feathers+eggs+milk+airborne+aquatic+predator+toothed+backbone+breathes+venomous+fins+legs0+legs2+legs4+legs5+legs6+legs8+tail+domestic+catsize" folds <- split(data_zoo , cut(sample(1:nrow(data_zoo)),10)) length(folds) folds errs.c50 <- rep(NA, length(folds)) for (i in 1:length(folds)) { test <- ldply(folds[i], data.frame) train <- ldply(folds[-i], data.frame) tmp.model <- C5.0(as.formula(form), train) tmp.predict <- predict(tmp.model, newdata=test) conf.mat <- table(test$class_type , tmp.predict) errs.c50[i] <- 1 - sum(diag(conf.mat))/sum(conf.mat) } print(sprintf("El promedio de error usando la validación cruzada k-fold y el algoritmo de arbol de decision C5.0 es: %.3f percent", 100*mean(errs.c50))) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= #ARBOL BINARIO #Carga dataset ZOO data_zoo = read.csv("zoo-tree1.csv") #Discretiza datos data_zoo["animal_name"] <- NULL data_zoo <- data.frame(sapply(data_zoo,as.factor)) # Clasifica los modelos de árbol usando el algoritmo de Quinlan C5.0 c50_result<-C5.0(class_type~.,data=data_zoo) # Despliega resumen detallado para los modelos C.50 summary(c50_result) # calcula y despliega la importancia de la variable para el modelo C5.0 importanceC5imp(c50_result,metric='usage') #REGLAS. # Generar reglas a partir del arcol de decisión de los modelos C.50 ruleModel <- C5.0(type ~ ., data = data_zoo, rules = TRUE) ruleModel # Despliega resumen detallado para las reglas de los modelos C.50 summary(ruleModel) #VALIDACION CRUZADA. library(arulesViz) install.packages('partykit', dep = TRUE) install.packages('gmodels', dep = TRUE) library(partykit) library(C50) library(gmodels) library(plyr) data_zoo = read.csv("zoo-tree1.csv") #Carga dataset data_zoo["animal_name"] <- NULL data_zoo <- data.frame(sapply(data_zoo,as.factor)) #Discretiza datos form <- "class_type ~ hair+feathers+eggs+milk+airborne+aquatic+predator+toothed+backbone+breathes+venomous+fins+legs0+legs2+legs4+legs5+legs6+legs8+tail+domestic+catsize" folds <- split(data_zoo , cut(sample(1:nrow(data_zoo)),10)) length(folds) folds errs.c50 <- rep(NA, length(folds)) for (i in 1:length(folds)) { test <- ldply(folds[i], data.frame) train <- ldply(folds[-i], data.frame) tmp.model <- C5.0(as.formula(form), train) tmp.predict <- predict(tmp.model, newdata=test) conf.mat <- table(test$class_type , tmp.predict) errs.c50[i] <- 1 - sum(diag(conf.mat))/sum(conf.mat) } print(sprintf("El promedio de error usando la validación cruzada k-fold y el algoritmo de arbol de decision C5.0 es: %.3f percent", 100*mean(errs.c50))) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep>from sklearn.linear_model import LogisticRegression import Load_Dataset as ld import numpy as np X_train, y_train, X_test, y_test = ld.get_data() clf = LogisticRegression() clf.fit(X_train, y_train) y_hat = clf.predict(X_test) print(np.average(y_hat == y_test))<file_sep># Change accordingly VERSION <- "v15.9.10" WORK.DIR <- file.path("C:", "Users/Luis/Documents/DataScience/Tesis", "Calculo ARI", VERSION) CARSIG.SCRIPT.BASENAME <- paste("carSignal", VERSION, sep = "-") CARSIG.SCRIPT.BASENAME <- paste(CARSIG.SCRIPT.BASENAME, "R", sep = ".") CARSIG.SCRIPT.NAME <- file.path(WORK.DIR, CARSIG.SCRIPT.BASENAME) source(CARSIG.SCRIPT.NAME) DARI.SCRIPT.BASENAME <- paste("atARI", VERSION, sep = "-") DARI.SCRIPT.BASENAME <- paste(DARI.SCRIPT.BASENAME, "R", sep = ".") DARI.SCRIPT.NAME <- file.path(WORK.DIR, DARI.SCRIPT.BASENAME) source(DARI.SCRIPT.NAME) METRIC.UTILS.SCRIPT.BASENAME <- paste("Metric", "utils", VERSION, sep = "-") METRIC.UTILS.SCRIPT.BASENAME <- paste(METRIC.UTILS.SCRIPT.BASENAME, "R", sep = ".") METRIC.UTILS.SCRIPT.NAME <- file.path(WORK.DIR, METRIC.UTILS.SCRIPT.BASENAME) source(METRIC.UTILS.SCRIPT.NAME) MFARI.SCRIPT.BASENAME <- paste("mfARI", VERSION, sep = "-") MFARI.SCRIPT.BASENAME <- paste(MFARI.SCRIPT.BASENAME, "R", sep = ".") MFARI.SCRIPT.NAME <- file.path(WORK.DIR, MFARI.SCRIPT.BASENAME) source(MFARI.SCRIPT.NAME) ROUND.UTILS.SCRIPT.BASENAME <- paste("Rounding", "utils", VERSION, sep = "-") ROUND.UTILS.SCRIPT.BASENAME <- paste(ROUND.UTILS.SCRIPT.BASENAME, "R", sep = ".") ROUND.UTILS.SCRIPT.NAME <- file.path(WORK.DIR, ROUND.UTILS.SCRIPT.BASENAME) source(ROUND.UTILS.SCRIPT.NAME) get.normalised.dari.templates <- function( time.instants, abp.signal, sample.release, sampling.time, baseline.initial.time = time.instants[1], baseline.final.time = time.instants[sample.release], min.abp.max.delta.time = 5 * 0.8, min.cbfv.max.delta.time = 8 * 0.8, stabilisation.time = 1, at.param.rounding.digits = 6, normalised.cbfv.rounding.digits = 4, time.tol = sampling.time / 100, ... # Not used ) { # Gets normalised ABP normalised.abp.signal <- normalise.ABP.signal( time.instants = time.instants, ABP.signal = abp.signal, sample.release = sample.release, sampling.time = sampling.time, baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.ABP.max.delta.time = min.abp.max.delta.time, time.tol = time.tol ) # Gets 91 Aaslid-Tiecks parameters at.params <- get.AT.decimal.templates.parameters( rounding.digits = at.param.rounding.digits ) .tmp.fun <- function(i) get.theoretical.CBFV.response( T = at.params[i, 1], D = at.params[i, 2], K = at.params[i, 3], time.instants = time.instants, ABP.normalised = normalised.abp.signal[["normalised.ABP.signal"]], sampling.time = sampling.time, stabilisation.time = stabilisation.time ) r <- 1:nrow(at.params) templates <- lapply(r, .tmp.fun) .tmp.fun <- function(t) normalise.CBFV.signal( time.instants = time.instants, CBFV.signal = t[["CBFV.theoretical.response"]], sample.release = sample.release, sampling.time = sampling.time, baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.CBFV.max.delta.time = min.cbfv.max.delta.time, time.tol = time.tol ) normalised.dari.templates <- lapply(templates, .tmp.fun) .tmp.fun <- function(t) round(t[["normalised.CBFV.signal"]], normalised.cbfv.rounding.digits) normalised.dari.templates <- lapply(normalised.dari.templates, .tmp.fun) names(normalised.dari.templates) <- sapply(r, function(i) sprintf("%.1f", at.params[i, 4])) normalised.dari.templates } get.mfari.stats <- function( time.instants, abp.signal, cbfv.signal, sampling.time, time.release, keep.details = FALSE, ... # Passed to get.mfARI.parameters ) { mfari.params <- get.mfARI.parameters( time.instants = time.instants, ABP.signal = abp.signal, CBFV.signal = cbfv.signal, sampling.time = sampling.time, time.release = time.release, keep.details = keep.details, ... ) mfari <- get.mfARI( Ks = mfari.params[["Ks"]], Delta.tau = mfari.params[["Delta.tau"]], Phi = mfari.params[["Phi"]] ) data.frame( Ks = mfari.params[["Ks"]], Delta.tau = mfari.params[["Delta.tau"]], Phi = mfari.params[["Phi"]], mfARI = round(mfari, 1) ) } get.dari.stats <- function( time.instants, cbfv.signal, sample.release, sampling.time, normalised.dari.templates, baseline.initial.time = time.instants[1], baseline.final.time = time.instants[sample.release], min.cbfv.max.delta.time = 8 * 0.8, fitting.value.name = "GoF", fitting.value.rounding.digits = 4, time.tol = sampling.time / 100, ... # Passed to get.best.templates() ) { normalised.cbfv.signal <- normalise.CBFV.signal( time.instants = time.instants, CBFV.signal = cbfv.signal, sample.release = sample.release, sampling.time = sampling.time, baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.CBFV.max.delta.time = min.cbfv.max.delta.time, time.tol = time.tol ) dari.search <- get.best.templates( time.instants = time.instants, signal = normalised.cbfv.signal[["normalised.CBFV.signal"]], templates = normalised.dari.templates, keep.details = FALSE, time.tol = time.tol, ... ) ibest <- dari.search[["best.template.index"]] error <- dari.search[["best.fit.value"]] error <- round(error, fitting.value.rounding.digits) dari <- as.numeric(names(normalised.dari.templates)[ibest]) d <- data.frame(error, dari) colnames(d) <- c(fitting.value.name, "dARI") d } get.signal.stats <- function( time.instants, abp.signal, cbfv.signal, sampling.time, sample.release, normalised.dari.templates, time.release = time.instants[sample.release], ... # Passed to get.mfari.stats & get.ari.stats ) { mfari.stats <- get.mfari.stats( time.instants = time.instants, abp.signal = abp.signal, cbfv.signal = cbfv.signal, sampling.time = sampling.time, time.release = time.release, ... ) dari.stats <- get.dari.stats( time.instants = time.instants, cbfv.signal = cbfv.signal, sample.release = sample.release, sampling.time = sampling.time, normalised.dari.templates = normalised.dari.templates, ... ) cbind(mfari.stats, dari.stats) } get.mvre.stats <- function( mvre.data, time.col.name = "Time", abp.col.name = "ABP", left.cbfv.col.name = "LCBFV", right.cbfv.col.name = "RCBFV", sampling.time = 0.2, time.release = 0, time.tol = sampling.time / 100, indent = "", ... # Passed to get.signal.stats ) { # Gets sample of release sample.release <- which(are.tolerably.equal( mvre.data[[time.col.name]], time.release, time.tol )) # Gets dARI templates normalised.dari.templates <- get.normalised.dari.templates( time.instants = mvre.data[[time.col.name]], abp.signal = mvre.data[[abp.col.name]], sample.release = sample.release, sampling.time = sampling.time, time.tol = time.tol, ... ) # Left hemisphere cat(indent, "-- Left hemisphere --\n", sep = "") left.signal.stats <- get.signal.stats( time.instants = mvre.data[[time.col.name]], abp.signal = mvre.data[[abp.col.name]], cbfv.signal = mvre.data[[left.cbfv.col.name]], sampling.time = sampling.time, sample.release = sample.release, normalised.dari.templates = normalised.dari.templates, time.release = time.release, time.tol = time.tol, ... ) left.signal.stats <- cbind( data.frame(Side = "Left"), left.signal.stats ) # Right hemisphere cat(indent, "-- Right hemisphere --\n", sep = "") right.signal.stats <- get.signal.stats( time.instants = mvre.data[[time.col.name]], abp.signal = mvre.data[[abp.col.name]], cbfv.signal = mvre.data[[right.cbfv.col.name]], sampling.time = sampling.time, sample.release = sample.release, normalised.dari.templates = normalised.dari.templates, time.release = time.release, time.tol = time.tol, ... ) right.signal.stats <- cbind( data.frame(Side = "Right"), right.signal.stats ) # Joins stats rbind(left.signal.stats, right.signal.stats) } get.subject.stats.by.mvre <- function( subject, manoeuvres, src.subject.dir, src.ext = "txt", header = TRUE, indent = "", ... # Passed to get.mvre.stats ) { stats <- NULL for(mvre in manoeuvres) { cat(indent, "-- ", mvre, " --\n", sep = "") # Sets the subject source file src.basename <- paste(subject, mvre, sep = "-") src.basename <- paste(src.basename, src.ext, sep = ".") src.filename <- file.path(src.subject.dir, src.basename) if(!file.exists(src.filename)) { cat( paste(indent, " "), "Warning: file ", src.filename, " does not exists\n", sep = "" ) next } # Reads the manoeuvre signals mvre.data <- read.table(src.filename, header = header) # Gets manoeuvre stats mvre.stats <- get.mvre.stats( mvre.data = mvre.data, indent = paste0(indent, " "), ... # Passed to get.signal.stats ) mvre.stats <- cbind( data.frame(Manoeuvre = mvre), mvre.stats ) # Joins manoeuvre's stats stats <- rbind(stats, mvre.stats) } stats } get.stats.by.mvre <- function( src.dir, subjects, manoeuvres, indent = "", ... # Passed to get.subject.stats.by.mvre ) { stats <- NULL for(subject in subjects) { cat(indent, "-- ", subject, " --\n", sep = "") # Sets subject source directory src.subject.dir <- file.path(src.dir, subject) # Gets the subject's stats subject.stats <- get.subject.stats.by.mvre( subject = subject, manoeuvres = manoeuvres, src.subject.dir = src.subject.dir, indent = paste(indent, " "), ... # Passed to get.mvre.stats ) subject.stats <- cbind( data.frame(Subject = subject), subject.stats ) # Joins subject's stats stats <- rbind(stats, subject.stats) } stats } get.stats.by.subject <- function(stats.by.mvre, index.name) { col.names <- c("Subject", "Manoeuvre", "Side", index.name) table.index <- stats.by.mvre[, col.names] table.index <- reshape( data = table.index, idvar = c("Subject", "Side"), timevar = "Manoeuvre", direction = "wide" ) col.names <- colnames(table.index)[3:ncol(table.index)] col.names <- gsub(paste0(index.name, "."), "", col.names) colnames(table.index)[3:ncol(table.index)] <- col.names means <- apply(table.index[, col.names], 1, mean) sds <- apply(table.index[, col.names], 1, sd) covs = round(100 * sds / means, 2) covs table.index[["Mean"]] <- round(means, 1) table.index[["SD"]] <- round(sds, 2) table.index[["CoV"]] <- round(covs, 2) table.index } run <- function( src.dir = file.path(WORK.DIR, "Data"), src.ext = "txt", header = TRUE, tgt.suffix = paste("stats", VERSION, sep = "-"), tgt.dir = file.path(WORK.DIR, "stats"), tgt.ext = "csv", overwrite = TRUE, subjects = c("AC","AP","AV","CC","CS","DM","DS","GP","HF","HS","IH","MM","MR","MV","ND","PC","RO", "VT"), manoeuvres = c("ACOSTADO", "PIE", "SENTADO"), time.col.name = "Time", abp.col.name = "ABP", left.cbfv.col.name = "LCBFV", right.cbfv.col.name = "RCBFV", left.plot.suffix = "Izq", right.plot.suffix = "Der", sampling.time = 0.4, time.release = 0,#5 segundos antes de la caida baseline.initial.time = -10.0,#5 segundos antes de la caida baseline.final.time = time.release, min.ABP.max.delta.time = 20 * 0.8,#a partir de time.release busca el minimo min.CBFV.max.delta.time = 20 * 0.8,#a partir de time.release busca el minimo stabilisation.time = 20,#cuanto dura la señal para que se recupere nuevamente referential.time.instant = time.release, delta.time.before.ref = 0, delta.time.after.ref = round(floor(20 * 0.8 / sampling.time) * sampling.time, 1), comparison.function = get.MSE, fitting.value.name = "MSE", fitting.value.rounding.digits = 4, at.param.rounding.digits = 6, time.tol = sampling.time / 100, indent = "" ) { # Makes sure the target directory exists dir.create( path = tgt.dir, showWarnings = FALSE, recursive = TRUE, mode = "0711" ) next.indent <- paste0(indent, " ") # # Results by manoeuvre (English format) # cat( indent, "-- CSV file with stats by manoeuvre (English)\n", sep = "" ) tgt.basename <- paste("manoeuvres", tgt.suffix, sep = "-") tgt.csv.name <- paste(tgt.basename, tgt.ext, sep = ".") tgt.csv.filename <- file.path(tgt.dir, tgt.csv.name) # If the target CSV file exists and it should not be overwritten if(all(file.exists(tgt.csv.filename), !overwrite)) { cat( next.indent, "-- Target CSV file already exist and not overwritten...\n", next.indent, " Using these data for any other missing file.\n", sep = "" ) stats.by.mvre <- read.csv(tgt.csv.filename) } else { stats.by.mvre <- get.stats.by.mvre( src.dir = src.dir, src.ext = src.ext, header = header, subjects = subjects, manoeuvres = manoeuvres, time.col.name = time.col.name, abp.col.name = abp.col.name, left.cbfv.col.name = left.cbfv.col.name, right.cbfv.col.name = right.cbfv.col.name, left.plot.suffix = left.plot.suffix, right.plot.suffix = right.plot.suffix, sampling.time = sampling.time, time.release = time.release, baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.ABP.max.delta.time = min.ABP.max.delta.time, min.CBFV.max.delta.time = min.CBFV.max.delta.time, stabilisation.time = stabilisation.time, referential.time.instant = referential.time.instant, delta.time.before.ref = delta.time.before.ref, delta.time.after.ref = delta.time.after.ref, comparison.function = comparison.function, fitting.value.name = fitting.value.name, fitting.value.rounding.digits = fitting.value.rounding.digits, at.param.rounding.digits = at.param.rounding.digits, time.tol = time.tol, indent = next.indent ) write.csv(stats.by.mvre, file = tgt.csv.filename, row.names = FALSE) cat(next.indent, " CSV file created.\n", sep = "") } # # Results by manoeuvre (Spanish format) # cat( indent, "-- CSV file with stats by manoeuvre (Spanish)\n", sep = "" ) tgt.basename <- paste("maniobras", tgt.suffix, sep = "-") tgt.csv.name <- paste(tgt.basename, tgt.ext, sep = ".") tgt.csv.filename <- file.path(tgt.dir, tgt.csv.name) # If the target CSV file exists and it should not be overwritten if(all(file.exists(tgt.csv.filename), !overwrite)) cat( next.indent, "-- Target CSV file already exist and not overwritten\n", sep = "" ) else { english <- c("Subject", "Manoeuvre", "Side") spanish <- c("Sujeto", "Maniobra", "Hemisferio") col.names <- mapply(gsub, english, spanish, colnames(stats.by.mvre)) stats.by.mvre.es <- stats.by.mvre colnames(stats.by.mvre.es) <- col.names write.csv2( x = stats.by.mvre.es, file = tgt.csv.filename, row.names = FALSE ) cat(next.indent, " CSV file created.\n", sep = "") } # # Gets stats by subject # cat(indent, "-- Getting dARI stats by subject\n", sep = "") subject.dari.stats <- get.stats.by.subject(stats.by.mvre, "dARI") cat(indent, "-- Getting mfARI stats by subject\n", sep = "") subject.mfari.stats <- get.stats.by.subject(stats.by.mvre, "mfARI") # # Results by subject: dARI (English format) # cat( indent, "-- CSV file with dARI stats by subject (English)\n", sep = "" ) tgt.basename <- paste("subjects", "dARI", tgt.suffix, sep = "-") tgt.csv.name <- paste(tgt.basename, tgt.ext, sep = ".") tgt.csv.filename <- file.path(tgt.dir, tgt.csv.name) # If the target CSV file exists and it should not be overwritten if(all(file.exists(tgt.csv.filename), !overwrite)) cat( next.indent, "-- Target CSV file already exist and not overwritten\n", sep = "" ) else { write.csv( x = subject.dari.stats, file = tgt.csv.filename, row.names = FALSE ) cat(next.indent, " CSV file created.\n", sep = "") } # # Results by subject: mfARI (English format) # cat( indent, "-- CSV file with mfARI stats by subject (English)\n", sep = "" ) tgt.basename <- paste("subjects", "mfARI", tgt.suffix, sep = "-") tgt.csv.name <- paste(tgt.basename, tgt.ext, sep = ".") tgt.csv.filename <- file.path(tgt.dir, tgt.csv.name) # If the target CSV file exists and it should not be overwritten if(all(file.exists(tgt.csv.filename), !overwrite)) cat( next.indent, "-- Target CSV file already exist and not overwritten\n", sep = "" ) else { write.csv( x = subject.mfari.stats, file = tgt.csv.filename, row.names = FALSE ) cat(next.indent, " CSV file created.\n", sep = "") } # # Results by subject: dARI (Spanish format) # cat( indent, "-- CSV file with dARI stats by subject (Spanish)\n", sep = "" ) tgt.basename <- paste("sujetos", "dARI", tgt.suffix, sep = "-") tgt.csv.name <- paste(tgt.basename, tgt.ext, sep = ".") tgt.csv.filename <- file.path(tgt.dir, tgt.csv.name) # If the target CSV file exists and it should not be overwritten if(all(file.exists(tgt.csv.filename), !overwrite)) cat( next.indent, "-- Target CSV file already exist and not overwritten\n", sep = "" ) else { english <- c("Subject", "Side") spanish <- c("Sujeto", "Hemisferio") col.names <- mapply( FUN = gsub, english, spanish, colnames(subject.dari.stats) ) subject.dari.stats.es <- subject.dari.stats colnames(subject.dari.stats.es) <- col.names write.csv2( x = subject.dari.stats.es, file = tgt.csv.filename, row.names = FALSE ) cat(next.indent, " CSV file created.\n", sep = "") } stats.by.mvre } <file_sep><<<<<<< HEAD <<<<<<< HEAD import numpy import pandas import statsmodels.formula.api as smf import statsmodels.stats.multicomp as multi import scipy.stats import seaborn import matplotlib.pyplot as plt data = pandas.read_csv(‘addhealth_pds.csv’, low_memory=False) data['H1FS11’]=data['H1FS11’].replace(0, numpy.nan) data['H1ED12’]=data['H1ED12’].replace(0, numpy.nan) data['H1FS11’] = pandas.to_numeric(data['H1FS11’], errors='coerce’) data['H1ED12’] = pandas.to_numeric(data['H1ED12’], errors='coerce’) ct=pandas.crosstab(data['H1FS11’], data['H1ED12’]) print (ct) # column percentages colsum=ct.sum(axis=0) colpct=ct/colsum print(colpct) # chi-square cs= scipy.stats.chi2_contingency(ct) print ('chi-square value %f’%cs[0]) print ('p value %f’%cs[1]) ###################Post Hoc Analysis sub = data.copy() for a in [1, 2, 3, 4, 5, 6, 7, 8, 9]: for b in range((a + 1),10): bb = b aa = a if b == 7: bb = 96 if b == 8: bb = 97 if b == 9: bb = 98 if a == 7: aa = 96 if a == 8: aa = 97 print (’———————–’) recode1 = {aa: aa, bb: bb} sub['COMP1v2’]= data['H1ED12’].map(recode1) # contingency table of observed counts ct1=pandas.crosstab(sub['H1FS11’], sub['COMP1v2’]) cs1= scipy.stats.chi2_contingency(ct1) if (cs1[0] > 3.84) & (cs1[1] < 0.003) : print ('chi-square value %f’%cs1[0]) print ('p value %.2E’%cs1[1]) print (ct1) # column percentages colsum=ct1.sum(axis=0) colpct=ct1/colsum print(colpct) “’ The Best one ———————– chi-square value 1150.361891 p value 4.31E-249 COMP1v2 1.0 96.0 H1FS11 1.0 237 1 2.0 605 0 3.0 687 0 6.0 0 3 COMP1v2 1.0 96.0 H1FS11 1.0 0.155003 0.25 2.0 0.395683 0.00 3.0 0.449313 0.00 6.0 0.000000 0.75 ———————– ”’ ################### Moderation Analysis for a in range(1, 6): print ('How close do you feel to your mother? = %d’%a) sub2=data[(data['H1WP9’]==a)] ct=pandas.crosstab(sub2['H1FS11’], sub2['H1ED12’]) colsum=ct.sum(axis=0) colpct=ct/colsum # chi-square cs= scipy.stats.chi2_contingency(ct) print ('chi-square value %f’%cs[0]) print ('p value %f’%cs[1]) ======= import numpy import pandas import statsmodels.formula.api as smf import statsmodels.stats.multicomp as multi import scipy.stats import seaborn import matplotlib.pyplot as plt data = pandas.read_csv(‘addhealth_pds.csv’, low_memory=False) data['H1FS11’]=data['H1FS11’].replace(0, numpy.nan) data['H1ED12’]=data['H1ED12’].replace(0, numpy.nan) data['H1FS11’] = pandas.to_numeric(data['H1FS11’], errors='coerce’) data['H1ED12’] = pandas.to_numeric(data['H1ED12’], errors='coerce’) ct=pandas.crosstab(data['H1FS11’], data['H1ED12’]) print (ct) # column percentages colsum=ct.sum(axis=0) colpct=ct/colsum print(colpct) # chi-square cs= scipy.stats.chi2_contingency(ct) print ('chi-square value %f’%cs[0]) print ('p value %f’%cs[1]) ###################Post Hoc Analysis sub = data.copy() for a in [1, 2, 3, 4, 5, 6, 7, 8, 9]: for b in range((a + 1),10): bb = b aa = a if b == 7: bb = 96 if b == 8: bb = 97 if b == 9: bb = 98 if a == 7: aa = 96 if a == 8: aa = 97 print (’———————–’) recode1 = {aa: aa, bb: bb} sub['COMP1v2’]= data['H1ED12’].map(recode1) # contingency table of observed counts ct1=pandas.crosstab(sub['H1FS11’], sub['COMP1v2’]) cs1= scipy.stats.chi2_contingency(ct1) if (cs1[0] > 3.84) & (cs1[1] < 0.003) : print ('chi-square value %f’%cs1[0]) print ('p value %.2E’%cs1[1]) print (ct1) # column percentages colsum=ct1.sum(axis=0) colpct=ct1/colsum print(colpct) “’ The Best one ———————– chi-square value 1150.361891 p value 4.31E-249 COMP1v2 1.0 96.0 H1FS11 1.0 237 1 2.0 605 0 3.0 687 0 6.0 0 3 COMP1v2 1.0 96.0 H1FS11 1.0 0.155003 0.25 2.0 0.395683 0.00 3.0 0.449313 0.00 6.0 0.000000 0.75 ———————– ”’ ################### Moderation Analysis for a in range(1, 6): print ('How close do you feel to your mother? = %d’%a) sub2=data[(data['H1WP9’]==a)] ct=pandas.crosstab(sub2['H1FS11’], sub2['H1ED12’]) colsum=ct.sum(axis=0) colpct=ct/colsum # chi-square cs= scipy.stats.chi2_contingency(ct) print ('chi-square value %f’%cs[0]) print ('p value %f’%cs[1]) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= import numpy import pandas import statsmodels.formula.api as smf import statsmodels.stats.multicomp as multi import scipy.stats import seaborn import matplotlib.pyplot as plt data = pandas.read_csv(‘addhealth_pds.csv’, low_memory=False) data['H1FS11’]=data['H1FS11’].replace(0, numpy.nan) data['H1ED12’]=data['H1ED12’].replace(0, numpy.nan) data['H1FS11’] = pandas.to_numeric(data['H1FS11’], errors='coerce’) data['H1ED12’] = pandas.to_numeric(data['H1ED12’], errors='coerce’) ct=pandas.crosstab(data['H1FS11’], data['H1ED12’]) print (ct) # column percentages colsum=ct.sum(axis=0) colpct=ct/colsum print(colpct) # chi-square cs= scipy.stats.chi2_contingency(ct) print ('chi-square value %f’%cs[0]) print ('p value %f’%cs[1]) ###################Post Hoc Analysis sub = data.copy() for a in [1, 2, 3, 4, 5, 6, 7, 8, 9]: for b in range((a + 1),10): bb = b aa = a if b == 7: bb = 96 if b == 8: bb = 97 if b == 9: bb = 98 if a == 7: aa = 96 if a == 8: aa = 97 print (’———————–’) recode1 = {aa: aa, bb: bb} sub['COMP1v2’]= data['H1ED12’].map(recode1) # contingency table of observed counts ct1=pandas.crosstab(sub['H1FS11’], sub['COMP1v2’]) cs1= scipy.stats.chi2_contingency(ct1) if (cs1[0] > 3.84) & (cs1[1] < 0.003) : print ('chi-square value %f’%cs1[0]) print ('p value %.2E’%cs1[1]) print (ct1) # column percentages colsum=ct1.sum(axis=0) colpct=ct1/colsum print(colpct) “’ The Best one ———————– chi-square value 1150.361891 p value 4.31E-249 COMP1v2 1.0 96.0 H1FS11 1.0 237 1 2.0 605 0 3.0 687 0 6.0 0 3 COMP1v2 1.0 96.0 H1FS11 1.0 0.155003 0.25 2.0 0.395683 0.00 3.0 0.449313 0.00 6.0 0.000000 0.75 ———————– ”’ ################### Moderation Analysis for a in range(1, 6): print ('How close do you feel to your mother? = %d’%a) sub2=data[(data['H1WP9’]==a)] ct=pandas.crosstab(sub2['H1FS11’], sub2['H1ED12’]) colsum=ct.sum(axis=0) colpct=ct/colsum # chi-square cs= scipy.stats.chi2_contingency(ct) print ('chi-square value %f’%cs[0]) print ('p value %f’%cs[1]) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep><<<<<<< HEAD <<<<<<< HEAD library(bnlearn) library(plotly) packageVersion('plotly') source('http://bioconductor.org/biocLite.R') biocLite('Rgraphviz') library(xlsx) data.alarm <- data.frame(alarm) # create and plot the network structure. modelstring = paste("[HIST|LVF][CVP|LVV][PCWP|LVV][HYP][LVV|HYP:LVF]", "[LVF][STKV|HYP:LVF][ERLO][HRBP|ERLO:HR][HREK|ERCA:HR][ERCA]", "[HRSA|ERCA:HR][ANES][APL][TPR|APL][ECO2|ACO2:VLNG][KINK]", "[MINV|INT:VLNG][FIO2][PVS|FIO2:VALV][SAO2|PVS:SHNT][PAP|PMB][PMB]", "[SHNT|INT:PMB][INT][PRSS|INT:KINK:VTUB][DISC][MVS][VMCH|MVS]", "[VTUB|DISC:VMCH][VLNG|INT:KINK:VTUB][VALV|INT:VLNG][ACO2|VALV]", "[CCHL|ACO2:ANES:SAO2:TPR][HR|CCHL][CO|HR:STKV][BP|CO:TPR]", sep = "") dag = model2network(modelstring) #se comparan los 3 metodos set.seed(6) res = hc(data.alarm)##MEJOR MODELO unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #22 31 24 #BIC: -220761.7 set.seed(6) res = mmhc(data.alarm) unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #16 13 30 #BIC: -311189.8 set.seed(6) res = mmpc(data.alarm) unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #0 29 46 #the graph is only partially directed tp <- c() Restart <- c() Seed <- c() maximoTp = 0 bestRest = 0; bestSeed = 0; for(seed in 1:500){ for(i in 1:100){ if((seed%%10) == 0 & (i%%10) == 0){ set.seed(seed) res = hc(data.alarm,restart = i) tph = unlist(compare(dag, res))["tp"] tp <- c(tp, tph) Restart <- c(Restart, i) Seed <- c(Seed, seed) if(maximoTp < tph){ maximoTp = tph bestRest = i bestSeed = seed } } } } ##Grafico Curva Arendizaje datos <- data.frame(Restart, Seed, tp, co = as.numeric(c(1:length(Restart)))) setwd("C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\Trabajos\\4") write.xlsx(datos, "Ajuste_TP.xlsx", sheetName="Sheet1") p <- plot_ly(datos, x = ~Restart, y = ~Seed, z = ~tp, type = 'scatter3d', mode = 'lines', line = list(color = '#1f77b4', width = 1)) p ##MEJOR MODELO set.seed(bestSeed)#Seed=40 res = hc(data.alarm,restart = bestRest)#Restart=90 unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #34 17 12 #BIC: -218690.1 ##Grafico de la mejor red graphviz.plot(res) ###################################################################33CONSULTAS ORACULO fittedbn <- bn.fit(res, data = data.alarm) #¿Qué tipo de entubación se le suministra a pacientes con anafilaxis? (PPT 15) set.seed(6) cpquery(fittedbn, event = (INT=="NORMAL"), evidence = (APL=="TRUE") ) #0.9194631 #¿Cuál es la probabilidad de que el paciente padezca de embolia pulmonar (PMB) si la catecolamina es alta(CCHL) y el ritmo cardiaco es alto (HR)? #PPT 16 set.seed(6) cpquery(fittedbn, event = (HR=="HIGH" & CCHL == "HIGH"), evidence = (PMB=="TRUE") ) #0.6923077 #¿Cuál es la probabilidad de que el paciente padezca de embolia pulmonar (PMB) si la catecolamina es alta(CCHL), si el ritmo cardiaco es alto (HR) y el CO es alto? #PPT 17 set.seed(6) cpquery(fittedbn, event = (HR=="HIGH" & CCHL == "HIGH" & CO == "HIGH"), evidence = (PMB=="TRUE") ) #0.5605096 #¿Cuál es la probabilidad de que un paciente con ritmo cardiaco alto, catecolamina alta e irrigación sanguínea pulmonar baja padezca de anafilaxis? #PPT 18 set.seed(6) cpquery(fittedbn, event = (HR =="HIGH" & CCHL =="HIGH" & TPR == "LOW"), evidence = (APL=="TRUE") ) #0.8636364 ======= library(bnlearn) library(plotly) packageVersion('plotly') source('http://bioconductor.org/biocLite.R') biocLite('Rgraphviz') library(xlsx) data.alarm <- data.frame(alarm) # create and plot the network structure. modelstring = paste("[HIST|LVF][CVP|LVV][PCWP|LVV][HYP][LVV|HYP:LVF]", "[LVF][STKV|HYP:LVF][ERLO][HRBP|ERLO:HR][HREK|ERCA:HR][ERCA]", "[HRSA|ERCA:HR][ANES][APL][TPR|APL][ECO2|ACO2:VLNG][KINK]", "[MINV|INT:VLNG][FIO2][PVS|FIO2:VALV][SAO2|PVS:SHNT][PAP|PMB][PMB]", "[SHNT|INT:PMB][INT][PRSS|INT:KINK:VTUB][DISC][MVS][VMCH|MVS]", "[VTUB|DISC:VMCH][VLNG|INT:KINK:VTUB][VALV|INT:VLNG][ACO2|VALV]", "[CCHL|ACO2:ANES:SAO2:TPR][HR|CCHL][CO|HR:STKV][BP|CO:TPR]", sep = "") dag = model2network(modelstring) #se comparan los 3 metodos set.seed(6) res = hc(data.alarm)##MEJOR MODELO unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #22 31 24 #BIC: -220761.7 set.seed(6) res = mmhc(data.alarm) unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #16 13 30 #BIC: -311189.8 set.seed(6) res = mmpc(data.alarm) unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #0 29 46 #the graph is only partially directed tp <- c() Restart <- c() Seed <- c() maximoTp = 0 bestRest = 0; bestSeed = 0; for(seed in 1:500){ for(i in 1:100){ if((seed%%10) == 0 & (i%%10) == 0){ set.seed(seed) res = hc(data.alarm,restart = i) tph = unlist(compare(dag, res))["tp"] tp <- c(tp, tph) Restart <- c(Restart, i) Seed <- c(Seed, seed) if(maximoTp < tph){ maximoTp = tph bestRest = i bestSeed = seed } } } } ##Grafico Curva Arendizaje datos <- data.frame(Restart, Seed, tp, co = as.numeric(c(1:length(Restart)))) setwd("C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\Trabajos\\4") write.xlsx(datos, "Ajuste_TP.xlsx", sheetName="Sheet1") p <- plot_ly(datos, x = ~Restart, y = ~Seed, z = ~tp, type = 'scatter3d', mode = 'lines', line = list(color = '#1f77b4', width = 1)) p ##MEJOR MODELO set.seed(bestSeed)#Seed=40 res = hc(data.alarm,restart = bestRest)#Restart=90 unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #34 17 12 #BIC: -218690.1 ##Grafico de la mejor red graphviz.plot(res) ###################################################################33CONSULTAS ORACULO fittedbn <- bn.fit(res, data = data.alarm) #¿Qué tipo de entubación se le suministra a pacientes con anafilaxis? (PPT 15) set.seed(6) cpquery(fittedbn, event = (INT=="NORMAL"), evidence = (APL=="TRUE") ) #0.9194631 #¿Cuál es la probabilidad de que el paciente padezca de embolia pulmonar (PMB) si la catecolamina es alta(CCHL) y el ritmo cardiaco es alto (HR)? #PPT 16 set.seed(6) cpquery(fittedbn, event = (HR=="HIGH" & CCHL == "HIGH"), evidence = (PMB=="TRUE") ) #0.6923077 #¿Cuál es la probabilidad de que el paciente padezca de embolia pulmonar (PMB) si la catecolamina es alta(CCHL), si el ritmo cardiaco es alto (HR) y el CO es alto? #PPT 17 set.seed(6) cpquery(fittedbn, event = (HR=="HIGH" & CCHL == "HIGH" & CO == "HIGH"), evidence = (PMB=="TRUE") ) #0.5605096 #¿Cuál es la probabilidad de que un paciente con ritmo cardiaco alto, catecolamina alta e irrigación sanguínea pulmonar baja padezca de anafilaxis? #PPT 18 set.seed(6) cpquery(fittedbn, event = (HR =="HIGH" & CCHL =="HIGH" & TPR == "LOW"), evidence = (APL=="TRUE") ) #0.8636364 >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= library(bnlearn) library(plotly) packageVersion('plotly') source('http://bioconductor.org/biocLite.R') biocLite('Rgraphviz') library(xlsx) data.alarm <- data.frame(alarm) # create and plot the network structure. modelstring = paste("[HIST|LVF][CVP|LVV][PCWP|LVV][HYP][LVV|HYP:LVF]", "[LVF][STKV|HYP:LVF][ERLO][HRBP|ERLO:HR][HREK|ERCA:HR][ERCA]", "[HRSA|ERCA:HR][ANES][APL][TPR|APL][ECO2|ACO2:VLNG][KINK]", "[MINV|INT:VLNG][FIO2][PVS|FIO2:VALV][SAO2|PVS:SHNT][PAP|PMB][PMB]", "[SHNT|INT:PMB][INT][PRSS|INT:KINK:VTUB][DISC][MVS][VMCH|MVS]", "[VTUB|DISC:VMCH][VLNG|INT:KINK:VTUB][VALV|INT:VLNG][ACO2|VALV]", "[CCHL|ACO2:ANES:SAO2:TPR][HR|CCHL][CO|HR:STKV][BP|CO:TPR]", sep = "") dag = model2network(modelstring) #se comparan los 3 metodos set.seed(6) res = hc(data.alarm)##MEJOR MODELO unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #22 31 24 #BIC: -220761.7 set.seed(6) res = mmhc(data.alarm) unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #16 13 30 #BIC: -311189.8 set.seed(6) res = mmpc(data.alarm) unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #0 29 46 #the graph is only partially directed tp <- c() Restart <- c() Seed <- c() maximoTp = 0 bestRest = 0; bestSeed = 0; for(seed in 1:500){ for(i in 1:100){ if((seed%%10) == 0 & (i%%10) == 0){ set.seed(seed) res = hc(data.alarm,restart = i) tph = unlist(compare(dag, res))["tp"] tp <- c(tp, tph) Restart <- c(Restart, i) Seed <- c(Seed, seed) if(maximoTp < tph){ maximoTp = tph bestRest = i bestSeed = seed } } } } ##Grafico Curva Arendizaje datos <- data.frame(Restart, Seed, tp, co = as.numeric(c(1:length(Restart)))) setwd("C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\Trabajos\\4") write.xlsx(datos, "Ajuste_TP.xlsx", sheetName="Sheet1") p <- plot_ly(datos, x = ~Restart, y = ~Seed, z = ~tp, type = 'scatter3d', mode = 'lines', line = list(color = '#1f77b4', width = 1)) p ##MEJOR MODELO set.seed(bestSeed)#Seed=40 res = hc(data.alarm,restart = bestRest)#Restart=90 unlist(compare(dag, res)) sc<-score(res,data.alarm) print(sc) #tp fp fn #34 17 12 #BIC: -218690.1 ##Grafico de la mejor red graphviz.plot(res) ###################################################################33CONSULTAS ORACULO fittedbn <- bn.fit(res, data = data.alarm) #¿Qué tipo de entubación se le suministra a pacientes con anafilaxis? (PPT 15) set.seed(6) cpquery(fittedbn, event = (INT=="NORMAL"), evidence = (APL=="TRUE") ) #0.9194631 #¿Cuál es la probabilidad de que el paciente padezca de embolia pulmonar (PMB) si la catecolamina es alta(CCHL) y el ritmo cardiaco es alto (HR)? #PPT 16 set.seed(6) cpquery(fittedbn, event = (HR=="HIGH" & CCHL == "HIGH"), evidence = (PMB=="TRUE") ) #0.6923077 #¿Cuál es la probabilidad de que el paciente padezca de embolia pulmonar (PMB) si la catecolamina es alta(CCHL), si el ritmo cardiaco es alto (HR) y el CO es alto? #PPT 17 set.seed(6) cpquery(fittedbn, event = (HR=="HIGH" & CCHL == "HIGH" & CO == "HIGH"), evidence = (PMB=="TRUE") ) #0.5605096 #¿Cuál es la probabilidad de que un paciente con ritmo cardiaco alto, catecolamina alta e irrigación sanguínea pulmonar baja padezca de anafilaxis? #PPT 18 set.seed(6) cpquery(fittedbn, event = (HR =="HIGH" & CCHL =="HIGH" & TPR == "LOW"), evidence = (APL=="TRUE") ) #0.8636364 >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep> require(ggplot2) require(gridExtra) require(pracma) require(signal) # This function obtains the CBFV response to an ABP stimulus # according to the Aaslid-Tiecks (A-T) model with the specified # parameters. # The function receives the following arguments: # # T, D and K: the model parameters. # Default value: values that generates a response with # A-T ARI = 5. # # time.instants: the time instants in which the input ABP stimulus was # sampled. # # ABP.normalised: the normalised ABP stimulus to be used as input to the # A-T model. # # sampling.time: the sampling time used in the input ABP stimulus. # Default value: the smallest difference between time # instants (rounded to 3 decimal places - max. 1000 Hz). # # stabilisation.time: the time to be used for stabilisation of the model, # before and after the input stimulus. # Default value: 1 s # # The function's answer is a list with the following: # .$T, .$D, .$K: the parameters of the model used # .$time.instants: a copy of the specified time instants. # .$sampling.time: a copy of the specified sampling time of the signals. # .$ABP.normalised: the specified normalised ABP stimulus. # .$CBFV.theoretical.response: the CBFV response given by the A-T model # with the specified parameters to the given # ABP stimulus. # get.theoretical.CBFV.response <- function( T = 1.9, D = 0.75, K = 0.9, time.instants, ABP.normalised, sampling.time = min(round(diff(time.instants), 3)), stabilisation.time = 1 ) { # Initialises the answer ans <- list() ans[["T"]] <- T ans[["D"]] <- D ans[["K"]] <- K ans[["time.instants"]] <- time.instants ans[["sampling.time"]] <- sampling.time ans[["ABP.normalised"]] <- ABP.normalised frequency <- 1 / ans[["sampling.time"]] nsamples <- length(ans[["time.instants"]]) nsamples.stabilisation <- round(stabilisation.time / ans[["sampling.time"]]) P <- c( rep(ans[["ABP.normalised"]][1], nsamples.stabilisation), ans[["ABP.normalised"]], rep(ans[["ABP.normalised"]][nsamples], nsamples.stabilisation) ) # Gets dP dP <- P - 1 # Applies Tiecks' equations to obtain the CBFV signal X1 <- vector(mode = "numeric", length = length(P)) X2 <- vector(mode = "numeric", length = length(P)) CBFV <- vector(mode = "numeric", length = length(P)) divisor <- frequency * ans[["T"]] X1[1] <- 0 X2[1] <- 0 CBFV[1] <- 1 for(t in 2:length(P)) { X1[t] <- X1[t-1] + (dP[t] - X2[t-1]) / divisor X2[t] <- X2[t-1] + (X1[t] - 2 * ans[["D"]] * X2[t-1]) / divisor CBFV[t] <- 1 + dP[t] - ans[["K"]] * X2[t] } if(nsamples.stabilisation > 0) CBFV <- CBFV[-(1:nsamples.stabilisation)] CBFV <- CBFV[1:nsamples] ans[["CBFV.theoretical.response"]] <- CBFV invisible(ans) } # This function creates a normalised ABP step stimulus and obtains the # CBFV response according to the Aaslid-Tiecks (A-T) model with a # specific level of efficiency. # The function receives the following arguments: # # sampling.time, # time.until.release, # time.after.release, # smooth.step.stimulus, # filter.order, # cutoff.frequency, # left.stabilisation.time, # time.rounding.digits: the parameters required to generate a normalised # ABP stimulus. # Default values: as in function # get.normalised.ABP.stimulus() # # T, D, K, stabilisation.time: the parameters necessary to obtain the # CBFV response to the ABP stimulus # generated. # Default values: as in function # get.theoretical.CBFV.response() # # The function's answer is a list with the following: # .$T, .$D, .$K: the parameters of the model used # .$time.instants: the specified time instants. # .$sampling.time: the sampling time of the signals. # .$ABP.normalised: the specified normalised ABP stimulus. # .$CBFV.step.response: the CBFV response given by the model to the # specified ABP stimulus. # .$time.release: the time instant in which the thigh-cuffs are # supposedly released # get.AT.curve <- function( sampling.time = 0.1, time.until.release = 10, time.after.release = 20, smooth.step.stimulus = FALSE, filter.order = 2, cutoff.frequency = 0.20, left.stabilisation.time = ifelse(smooth.step.stimulus, 30, 0), time.rounding.digits = format.info(sampling.time)[2], T = 1.9, D = 0.75, K = 0.9, stabilisation.time = 1 ) { ans.abp <- get.normalised.ABP.stimulus( sampling.time = sampling.time, time.until.release = time.until.release, time.after.release = time.after.release, smooth.step.stimulus = smooth.step.stimulus, filter.order = filter.order, cutoff.frequency = cutoff.frequency, left.stabilisation.time = left.stabilisation.time, time.rounding.digits = time.rounding.digits ) ans.cbfv <- get.theoretical.CBFV.response( T = T, D = D, K = K, time.instants = ans.abp$time.instants, ABP.normalised = ans.abp$ABP.normalised, sampling.time = ans.abp$sampling.time, stabilisation.time = stabilisation.time ) ans.cbfv[["CBFV.step.response"]] <- ans.cbfv[["CBFV.theoretical.response"]] ans.cbfv[["CBFV.theoretical.response"]] <- NULL ans.cbfv[["time.release"]] <- ans.abp[["time.release"]] invisible(ans.cbfv) } # This function creates a plot of the signals generated with an # Aaslid-Tiecks (A-T) model. # The function receives the following arguments: # curve: a list with the A-T curve, as returned by the function # get.AT.curve() # title: the title for the plot. # Default value: NULL # Specifically: # - plots curve$ABP.normalised and curve$CBFV.step.response signals using # curve$time.instants as x-axis # - annotates the plot with the values of curve$T, curve$D, curve$K and # curve$sampling.time # - annotates the plot with a vertical grey line marking the time of # thigh-cuff release # - uses the argument title (if specified) as the plot's title # # The function returns the resulting plot # get.AT.curve.plot <- function(curve, title = NULL) { tab <- data.frame( Parameters = c( curve[["T"]], curve[["D"]], curve[["K"]], curve[["sampling.time"]] )) tab[["Parameters"]] <- format(tab[["Parameters"]]) g <- tableGrob(tab, gp = gpar(fontsize = 5)) xrange <- range(curve[["time.instants"]]) xrange <- (xrange[2] - xrange[1]) / 5 yrange <- 0.5 df1 <- data.frame( Time = curve[["time.instants"]], Value = curve[["ABP.normalised"]], Signal = "ABP" ) df2 <- data.frame( Time = curve[["time.instants"]], Value = curve[["CBFV.step.response"]], Signal = "CBFV" ) df <- rbind(df1, df2) p <- ggplot(data = df, aes(x = Time, y = Value, colour = Signal)) p <- p + geom_line() + geom_point() p <- p + geom_vline(xintercept = curve[["time.release"]], colour = "grey") n <- length(curve[["time.instants"]]) xmax <- curve[["time.instants"]][n] y <- curve[["CBFV.step.response"]][n] if(y > yrange) y <- c(0, yrange) else y <- c(yrange, 2 * yrange) p <- p + annotation_custom( g, xmin = xmax - xrange, xmax = xmax, ymin = y[1], ymax = y[2] ) if(!is.null(title)) p <- p + labs(title = title, x = "Time [s]", y = "Signals [a.u.]") else p <- p + labs(x = "Time [s]", y = "Signals [a.u.]") p } get.AT.templates.parameters <- function() { K <- c(0.00, 0.20, 0.40, 0.60, 0.80, 0.90, 0.94, 0.96, 0.97, 0.98) D <- c(1.60, 1.60, 1.50, 1.15, 0.90, 0.75, 0.65, 0.55, 0.52, 0.50) T <- c(2.00, 2.00, 2.00, 2.00, 2.00, 1.90, 1.60, 1.20, 0.87, 0.65) ARI <- 0:9 data.frame(T, D, K, ARI) } get.AT.templates <- function( sampling.time = 0.1, time.until.release = 10, time.after.release = 20, smooth.step.stimulus = FALSE, filter.order = 2, cutoff.frequency = 0.20, left.stabilisation.time = ifelse(smooth.step.stimulus, 30, 0), time.rounding.digits = format.info(sampling.time)[2], stabilisation.time = 1 ) { ans.abp <- get.normalised.ABP.stimulus( sampling.time = sampling.time, time.until.release = time.until.release, time.after.release = time.after.release, smooth.step.stimulus = smooth.step.stimulus, filter.order = filter.order, cutoff.frequency = cutoff.frequency, left.stabilisation.time = left.stabilisation.time, time.rounding.digits = time.rounding.digits ) params <- get.AT.templates.parameters() .tmp.fun <- function(row) get.theoretical.CBFV.response( T = row[["T"]], D = row[["D"]], K = row[["K"]], time.instants = ans.abp$time.instants, ABP.normalised = ans.abp$ABP.normalised, sampling.time = ans.abp$sampling.time, stabilisation.time = stabilisation.time ) templates <- apply(params, 1, .tmp.fun) .tmp.fun <- function(ans) { ans[["CBFV.step.response"]] <- ans[["CBFV.theoretical.response"]] ans[["CBFV.theoretical.response"]] <- NULL ans[["time.release"]] <- ans.abp[["time.release"]] ans } templates <- lapply(templates, .tmp.fun) .tmp.fun <- function(i) { templates[[i]][["ARI.value"]] <- params[i, "ARI"] templates[[i]] } templates <- lapply(1:length(templates), .tmp.fun) names(templates) <- paste("ARI", params[["ARI"]], sep = " = ") templates } get.AT.decimal.templates <- function( sampling.time = 0.1, time.until.release = 10, time.after.release = 20, smooth.step.stimulus = FALSE, filter.order = 2, cutoff.frequency = 0.20, left.stabilisation.time = ifelse(smooth.step.stimulus, 30, 0), time.rounding.digits = format.info(sampling.time)[2], stabilisation.time = 1, rounding.digits = 6 ) { ans.abp <- get.normalised.ABP.stimulus( sampling.time = sampling.time, time.until.release = time.until.release, time.after.release = time.after.release, smooth.step.stimulus = smooth.step.stimulus, filter.order = filter.order, cutoff.frequency = cutoff.frequency, left.stabilisation.time = left.stabilisation.time, time.rounding.digits = time.rounding.digits ) params <- get.AT.decimal.templates.parameters( rounding.digits = rounding.digits ) .tmp.fun <- function(row) get.theoretical.CBFV.response( T = row[["T"]], D = row[["D"]], K = row[["K"]], time.instants = ans.abp$time.instants, ABP.normalised = ans.abp$ABP.normalised, sampling.time = ans.abp$sampling.time, stabilisation.time = stabilisation.time ) templates <- apply(params, 1, .tmp.fun) .tmp.fun <- function(ans) { ans[["CBFV.step.response"]] <- ans[["CBFV.theoretical.response"]] ans[["CBFV.theoretical.response"]] <- NULL ans[["time.release"]] <- ans.abp[["time.release"]] ans } templates <- lapply(templates, .tmp.fun) .tmp.fun <- function(i) { templates[[i]][["ARI.value"]] <- params[i, "ARI"] templates[[i]] } templates <- lapply(1:length(templates), .tmp.fun) names(templates) <- paste("ARI", sprintf("%.1f", params[["ARI"]]), sep = " = ") templates } get.AT.decimal.templates.parameters <- function(rounding.digits = 6) { orig <- get.AT.templates.parameters() ARI.decimal <- round(seq(0, 9, 0.1), 1) K.decimal <- pracma::interp1(orig[["ARI"]], orig[["K"]], ARI.decimal, 'spline') K.decimal <- round(K.decimal, rounding.digits) D.decimal <- pracma::interp1(orig[["ARI"]], orig[["D"]], ARI.decimal, 'spline') D.decimal <- round(D.decimal, rounding.digits) T.decimal <- pracma::interp1(orig[["ARI"]], orig[["T"]], ARI.decimal, 'spline') T.decimal <- round(T.decimal, rounding.digits) data.frame( T = T.decimal, D = D.decimal, K = K.decimal, ARI = ARI.decimal ) } # This function creates a plot with CBFV responses generated by # Aaslid-Tiecks (A-T) models (normally for the same ABP stimulus). # The function receives the following argument: # curves: a list in which each element is a list with an A-T curve as # returned by the function get.AT.curve() # label.name: the name for the legend of the plot. If NULL, no legend is # added and curves are plotted in black. # Default value: NULL # labels: a vector of the same length as curves, containing the label for # each curve. If label.name is not NULL, these labels are used as # the colour aesthetic and for labelling the curves in the legend. # Default value: NULL # title: the title for the plot. # Default value: NULL # # The function returns the resulting plot # get.AT.curves.plot <- function( curves, label.name = NULL, labels = NULL, title = NULL ) { n <- length(curves) if(is.null(labels)) labels <- 1:n group.name <- "Response" if(!is.null(label.name)) group.name <- label.name times <- c(sapply(1:n, function(i) curves[[i]][["time.instants"]])) values <- c(sapply(1:n, function(i) curves[[i]][["CBFV.step.response"]])) lengths <- c(sapply(1:n, function(i) length(curves[[i]][["time.instants"]]))) groups <- rep(labels, times = lengths) df <- data.frame(Time = times, CBFV = values, groups) names(df)[ncol(df)] <- group.name p <- ggplot(df, aes_string(x = "Time", y = "CBFV", group = group.name)) if(is.null(label.name)) p <- p + geom_line() else p <- p + geom_line(aes_string(colour = group.name)) if(!is.null(title)) p <- p + labs(title = title, x = "Time [s]", y = "CBFV responses [a.u.]") else p <- p + labs(x = "Time [s]", y = "CBFV responses [a.u.]") p } <file_sep><<<<<<< HEAD <<<<<<< HEAD """ Created on Wed Oct 17 15:08:50 2018 @author: Luis.Orellana.EXT Dataset: https://www.kaggle.com/dragonheir/logistic-regression """ import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.externals import joblib from azureml.core import Workspace, Experiment, Run import math, random, pickle from azureml.core.compute import ComputeTarget class Scal: #Escala de -1 a 1 scaler = MinMaxScaler(feature_range=(0, 1)) def __init__(self, X): self.X = X Scal.scaler.fit(X) def scaling(self): self.X_Scaled = Scal.scaler.transform(self.X) return self.X_Scaled def undo_scaling(self): X_un_Scaled = Scal.scaler.inverse_transform(self.X_Scaled) return X_un_Scaled def transform(column): wcdict = {} wcdict['Male'] = 0 wcdict['Female'] = 1 col_num = pd.DataFrame(column).applymap(lambda s: wcdict.get(s) if s in wcdict else s) return col_num def init(): ws = Workspace.from_config() experiment = Experiment(workspace = ws, name = "Experiment_RL_VentaOnline") run = Run.get_context() ds = ws.get_default_datastore() X = pd.read_csv(r"./Python/Regresion Logistica - Venta Online/Social_Network_Ads.csv", sep=",") Y = X.Purchased X = X.drop('Purchased', axis=1) X = X.drop('User ID', axis=1) X.Gender = transform(X.Gender) scal = Scal(X) X = scal.scaling() #scal.undo_scaling() ########################################################################################### X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = .3, random_state=25) C_param_range = [0.001,0.01,0.1,1.0,10.0,100.0] run.log("Parameters",C_param_range) LogReg for i in C_param_range: LogReg = LogisticRegression(penalty = 'l2', C = i,random_state = 0) LogReg.fit(X_train, y_train) y_pred = LogReg.predict(X_test) matriz_confu = confusion_matrix(y_test, y_pred) print("------------------------------------------------------") print("Parametro: ", i) print(matriz_confu) print(classification_report(y_test, y_pred)) print(accuracy_score(y_test, y_pred)) print("------------------------------------------------------") run.log("accuracy",accuracy_score(y_test, y_pred)) run.log("Parametro: ", i) joblib.dump(value=LogReg, filename='./Python/Regresion Logistica - Venta Online/outputs/LogReg.pkl') print("Run completed") run = experiment.submit() ======= """ Created on Wed Oct 17 15:08:50 2018 @author: Luis.Orellana.EXT Dataset: https://www.kaggle.com/dragonheir/logistic-regression """ import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.externals import joblib from azureml.core import Workspace, Experiment, Run import math, random, pickle from azureml.core.compute import ComputeTarget class Scal: #Escala de -1 a 1 scaler = MinMaxScaler(feature_range=(0, 1)) def __init__(self, X): self.X = X Scal.scaler.fit(X) def scaling(self): self.X_Scaled = Scal.scaler.transform(self.X) return self.X_Scaled def undo_scaling(self): X_un_Scaled = Scal.scaler.inverse_transform(self.X_Scaled) return X_un_Scaled def transform(column): wcdict = {} wcdict['Male'] = 0 wcdict['Female'] = 1 col_num = pd.DataFrame(column).applymap(lambda s: wcdict.get(s) if s in wcdict else s) return col_num def init(): ws = Workspace.from_config() experiment = Experiment(workspace = ws, name = "Experiment_RL_VentaOnline") run = Run.get_context() ds = ws.get_default_datastore() X = pd.read_csv(r"./Python/Regresion Logistica - Venta Online/Social_Network_Ads.csv", sep=",") Y = X.Purchased X = X.drop('Purchased', axis=1) X = X.drop('User ID', axis=1) X.Gender = transform(X.Gender) scal = Scal(X) X = scal.scaling() #scal.undo_scaling() ########################################################################################### X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = .3, random_state=25) C_param_range = [0.001,0.01,0.1,1.0,10.0,100.0] run.log("Parameters",C_param_range) LogReg for i in C_param_range: LogReg = LogisticRegression(penalty = 'l2', C = i,random_state = 0) LogReg.fit(X_train, y_train) y_pred = LogReg.predict(X_test) matriz_confu = confusion_matrix(y_test, y_pred) print("------------------------------------------------------") print("Parametro: ", i) print(matriz_confu) print(classification_report(y_test, y_pred)) print(accuracy_score(y_test, y_pred)) print("------------------------------------------------------") run.log("accuracy",accuracy_score(y_test, y_pred)) run.log("Parametro: ", i) joblib.dump(value=LogReg, filename='./Python/Regresion Logistica - Venta Online/outputs/LogReg.pkl') print("Run completed") run = experiment.submit() >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= """ Created on Wed Oct 17 15:08:50 2018 @author: Luis.Orellana.EXT Dataset: https://www.kaggle.com/dragonheir/logistic-regression """ import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.externals import joblib from azureml.core import Workspace, Experiment, Run import math, random, pickle from azureml.core.compute import ComputeTarget class Scal: #Escala de -1 a 1 scaler = MinMaxScaler(feature_range=(0, 1)) def __init__(self, X): self.X = X Scal.scaler.fit(X) def scaling(self): self.X_Scaled = Scal.scaler.transform(self.X) return self.X_Scaled def undo_scaling(self): X_un_Scaled = Scal.scaler.inverse_transform(self.X_Scaled) return X_un_Scaled def transform(column): wcdict = {} wcdict['Male'] = 0 wcdict['Female'] = 1 col_num = pd.DataFrame(column).applymap(lambda s: wcdict.get(s) if s in wcdict else s) return col_num def init(): ws = Workspace.from_config() experiment = Experiment(workspace = ws, name = "Experiment_RL_VentaOnline") run = Run.get_context() ds = ws.get_default_datastore() X = pd.read_csv(r"./Python/Regresion Logistica - Venta Online/Social_Network_Ads.csv", sep=",") Y = X.Purchased X = X.drop('Purchased', axis=1) X = X.drop('User ID', axis=1) X.Gender = transform(X.Gender) scal = Scal(X) X = scal.scaling() #scal.undo_scaling() ########################################################################################### X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = .3, random_state=25) C_param_range = [0.001,0.01,0.1,1.0,10.0,100.0] run.log("Parameters",C_param_range) LogReg for i in C_param_range: LogReg = LogisticRegression(penalty = 'l2', C = i,random_state = 0) LogReg.fit(X_train, y_train) y_pred = LogReg.predict(X_test) matriz_confu = confusion_matrix(y_test, y_pred) print("------------------------------------------------------") print("Parametro: ", i) print(matriz_confu) print(classification_report(y_test, y_pred)) print(accuracy_score(y_test, y_pred)) print("------------------------------------------------------") run.log("accuracy",accuracy_score(y_test, y_pred)) run.log("Parametro: ", i) joblib.dump(value=LogReg, filename='./Python/Regresion Logistica - Venta Online/outputs/LogReg.pkl') print("Run completed") run = experiment.submit() >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 init()<file_sep> get.MSE <-function(sim, obs, ...) UseMethod("get.MSE") get.MSE.default <- function(sim, obs, ...) { valid.classes <- c("integer", "numeric", "ts") if(!all(inherits(sim, valid.classes), inherits(obs, valid.classes))) stop("Invalid argument type: 'sim' & 'obs' have to be of class ", valid.classes) mse <- mean((sim - obs)^2, ...) return(mse) } get.MSE.matrix <- function(sim, obs, ...) { # Check that 'sim' and 'obs' have the same dimensions if(!all.equal(dim(sim), dim(obs))) stop(paste0("Invalid argument: dim(sim) != dim(obs) ", "(", "[", paste(dim(sim), collapse = " "), "]", " != ", "[", paste(dim(obs), collapse = " "), "]", ")")) mse <- colMeans((sim - obs)^2, ...) return(mse) } get.MSE.data.frame <- function(sim, obs, ...) { sim <- as.matrix(sim) obs <- as.matrix(obs) get.MSE.matrix(sim = sim, obs = obs, ...) } <file_sep>import os #FORZAR USO DE CPU os.environ['CUDA_VISIBLE_DEVICES'] = '0' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import time from math import sqrt, log, exp import math import pandas as pd import numpy import matplotlib.pyplot as plt from keras import Sequential from keras import backend as K from keras.models import Model from keras.layers import LSTM, Dense from sklearn.preprocessing import MinMaxScaler import gc from scipy import stats import plotly.plotly as py import plotly.graph_objs as go import plotly from numpy.random import seed from tensorflow import set_random_seed import tensorflow as tf from functools import reduce CPU_USAGE = 7 GPU_USAGE = 1 PATH_SUJETOS = ("C:/Users/Luis/Documents/DataScience/Tesis/Datos/SUJETOS/%s/%s-%s-VE.csv") PATH_ESCALON = ("C:/Users/Luis/Documents/DataScience/Tesis/Datos/ESCALON_PRESION/ESCALON.csv") PATH_RESULTADO = ("C:/Users/Luis/Documents/DataScience/Tesis/Resultados/Escalon/%s") PATH_RESULTADO_ESCALON = (PATH_RESULTADO%("%s/%s_%s")) OPTIMUM_NEURONS = 10 def create_dataset(nombre_sujeto, nombre_postura): X = pd.read_csv(PATH_SUJETOS%(nombre_sujeto, nombre_sujeto, nombre_postura), sep=" ") data_escalon = pd.read_csv(PATH_ESCALON) # normalize the dataset scaler_VFSCd = MinMaxScaler(feature_range=(-1, 1)) scaler_VFSCi = MinMaxScaler(feature_range=(-1, 1)) scaler_PAMn = MinMaxScaler(feature_range=(-1, 1)) scaler_escalon = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler_VFSCd.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler_VFSCi.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler_PAMn.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) Escalon = scaler_escalon.fit_transform(data_escalon.ESCALON.values.reshape((len(data_escalon.ESCALON.values), 1))) #Dar formato float a las señales PAMn, VFSCd, VFSCi, Escalon = PAMn.astype('float32'), VFSCd.astype('float32'), VFSCi.astype('float32'), Escalon.astype('float32') PAMn, VFSCd, VFSCi, Escalon = numpy.array(PAMn), numpy.array(VFSCd), numpy.array(VFSCi), numpy.array(Escalon) # Validacion Valanceada train_size = int(len(PAMn) * 0.5) train_PAM, train_VFSCd, train_VFSCi = PAMn[0:train_size], VFSCd[0:train_size], VFSCi[0:train_size] test_PAM, test_VFSCd, test_VFSCi = PAMn[train_size:len(PAMn)], VFSCd[train_size:len(VFSCd)], VFSCi[train_size:len(VFSCi)] # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] train_PAM = numpy.reshape(train_PAM, (train_PAM.shape[0], 1, train_PAM.shape[1])) test_PAM = numpy.reshape(test_PAM, (test_PAM.shape[0], 1, test_PAM.shape[1])) Escalon = numpy.reshape(Escalon, (Escalon.shape[0], 1, Escalon.shape[1])) return train_PAM, train_VFSCd, train_VFSCi, test_PAM, test_VFSCd, test_VFSCi, Escalon, scaler_VFSCd, scaler_VFSCi, scaler_escalon # fit an LSTM network to training data def fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout): use_cpu_gpu() ret_seq = False model = Sequential() model.add(LSTM(64, return_sequences=True, input_shape=(198, 1))) model.add(LSTM(128, return_sequences=True)) model.add(LSTM(256, return_sequences=True)) model.add(LSTM(128, return_sequences=True)) model.add(LSTM(64, return_sequences=True)) model.add(LSTM(2, return_sequences=True)) model.compile(loss='mse', optimizer='adam') model.fit(trainX[0:198], trainY[0:198], epochs=1000, batch_size=1, verbose=2, validation_data=(trainX,trainY)) return model def fit_lstm2(trainX, trainY, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout): use_cpu_gpu() ret_seq = False if hidden_layers > 1: ret_seq = True model = Sequential() model.add(LSTM(neurons, batch_input_shape=(batch_size, trainX.shape[1], trainX.shape[2]), return_sequences=ret_seq, stateful=True, recurrent_activation=activation, recurrent_dropout=dropout)) for i in range (hidden_layers-1): if i == (hidden_layers-2): ret_seq = False #neurons = OPTIMUM_NEURONS model.add(LSTM(neurons, return_sequences=ret_seq, stateful = True, recurrent_activation=activation, recurrent_dropout=dropout)) model.add(Dense(trainX.shape[1], activation=activation)) model.compile(loss='mean_squared_error', optimizer=optimization) for i in range(epochs): model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=0, shuffle=False) model.reset_states() return model from keras import backend as K def correlation_coefficient_loss(y_true, y_pred): x = y_true y = y_pred mx = K.mean(x) my = K.mean(y) xm, ym = x-mx, y-my r_num = K.sum(tf.multiply(xm,ym)) r_den = K.sqrt(tf.multiply(K.sum(K.square(xm)), K.sum(K.square(ym)))) r = r_num / r_den r = K.maximum(K.minimum(r, 1.0), -1.0) return ((1 - K.square(r))*-1)+1 #Evaluate the Model def evaluate(model, X, Y, batch_size): output = model.predict(X) # invert data transforms on forecast # report performance rmse = stats.pearsonr(Y[:,0], output[:,0]) return rmse[0] def evaluate2(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast # report performance rmse = stats.pearsonr(Y[:,0], output[:,0]) return rmse[0] #Evaluate the Model def evaluate_stair(model, Escalon, batch_size): output = model.predict(Escalon, batch_size=batch_size) return output #Transfomracion de Fisher def fisher_transform(r): z = 0.5*log((1+r)/(1-r)) return z def inverse_fisher_transform(z): r = (exp(2*z)-1)/(exp(2*z)+1) return r # run a repeated experiment def experiment(trainX, trainY, testX, testY, repeats, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout): # run experiment lista_z = list() repetir_error = 0 i = 1 del_level_hyp = False while i <= repeats: # fit the model lstm_model = fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout) # report performance r = evaluate(lstm_model, testX, testY, batch_size) if math.isnan(r) and repetir_error < 3: repetir_error = repetir_error + 1 if repetir_error == 3: del_level_hyp = True break else: if repetir_error != 3: lista_z.append(fisher_transform(r)) repetir_error = 0 i = i + 1 K.clear_session() del lstm_model gc.collect() if del_level_hyp: mean_z = float('nan') mean_corr = float('nan') else: mean_z = reduce(lambda x, y: x + y, lista_z) / len(lista_z) mean_corr = inverse_fisher_transform(mean_z) print('epochs=%d, dropout=%.1f, activation=%s, optimization=%s neurons=%d, batch_size=%d, hidden_layers=%d:::::::::: RESULT=%.3f' % (epochs, dropout, activation, optimization, neurons, batch_size, hidden_layers, mean_corr)) return mean_corr def run_experiment(trainX, trainY, testX, testY, batch_size=[1], epochs=[65], optimization=["RMSprop"], activation=["tanh"], hidden_layers=[3], neurons=[10], dropout=[0.9]): columnas = ['epochs','dropout','activation','optimization','neurons','batch_size','hidden_layers','RESULT'] filas = len(batch_size) * len(epochs) * len(optimization) * len(activation) * len(hidden_layers) * len(neurons) * len(dropout) results = numpy.chararray((filas,8), itemsize=20, unicode=True) row = 0 repeats = 5 for b in batch_size: for e in epochs: for o in optimization: for a in activation: for h in hidden_layers: for n in neurons: for d in dropout: result = experiment(trainX, trainY, testX, testY, repeats, b, e, o, a, h, n, d) results[row][0] = e results[row][1] = d results[row][2] = a results[row][3] = o results[row][4] = n results[row][5] = b results[row][6] = h results[row][7] = result row = row + 1 df = pd.DataFrame(results, columns=columnas) df = df.sort_values(by='RESULT', ascending=False) return df def best_model(df_1, df_2, ruta_archivo): balance_extencion = "_1.csv" best_balance = 1 max_df_1 = float(df_1.iat[0,7]) max_df_2 = float(df_2.iat[0,7]) df = df_1 if(max_df_1<max_df_2): df = df_2 best_balance = 2 balance_extencion = "_2.csv" print('++++++++++++++++++++++++++++++++++++++ Mejor Balance: ') print(df) df.to_csv(ruta_archivo+balance_extencion, index=False) #df.to_excel(writer,'Resultados') #writer.save() print('################################################################################### Archivo |||'+ruta_archivo+'||| Creado') return df, best_balance def plotting(escalon, output, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout, result_r): re_escalon = numpy.reshape(escalon, (escalon.shape[0], 1)) re_output = numpy.reshape(output, (output.shape[0], 1)) plotly.tools.set_credentials_file(username='luis.orellana777', api_key='pCEXLd20Nqi47WlLGYGk') trace_high = go.Scatter( x=list(range(1, len(re_escalon))), y=re_escalon, name = "Escalon", line = dict(color = '#17BECF'), opacity = 0.8) trace_low = go.Scatter( x=list(range(1, len(re_output))), y=re_output, name = "VFSC Respuesta Escalon", line = dict(color = '#7F7F7F'), opacity = 0.8) data = [trace_high,trace_low] layout = dict( title = ("LSTM - Respuesta a Escalon"), xaxis = dict( range = [1, len(re_output)], title="Batch=%d ; Epoch=%d ; Optimization=%s ; Activation=%s ; Layers=%d ; Units=%d ; Dropout=%.2f ; Correlation=%.3f"%(batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout, result_r)) ) fig = dict(data=data, layout=layout) py.plot(fig, filename = "LSTM VFSC") def plotting_mathplot(escalon, output, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout, result_r): re_escalon = numpy.reshape(escalon, (escalon.shape[0])) re_output = numpy.reshape(output, (output.shape[0])) fig, ax = plt.subplots() # Using set_dashes() to modify dashing of an existing line line1, = ax.plot(list(range(1, len(re_escalon)+1)), re_escalon, label='Escalon') # Using plot(..., dashes=...) to set the dashing when creating a line line2, = ax.plot(list(range(1, len(re_output)+1)), re_output, label='VFSC Respuesta Escalon') title="Batch=%d ; Epoch=%d ; Optimization=%s ; Activation=%s ; Layers=%d ; Units=%d ; Dropout=%.2f ; Correlation=%.3f"%(batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout, result_r) ax.set_xlabel(title) ax.set_title("LSTM - Respuesta a Escalon") ax.legend() plt.show() def use_cpu_gpu(): config = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=10, inter_op_parallelism_threads=10, device_count = {'CPU' : CPU_USAGE, 'GPU' : GPU_USAGE} ) config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.9 #config.gpu_options.allow_growth = True session = tf.compat.v1.Session(config=config) K.set_session(session) def apply_stair(df, trainX, trainY, testX, testY, escalon, scaler_VFSC, scaler_escalon, sujeto, postura, hemisferio): for row in range(df.shape[0]):#Cantidad de registros en el dataframe resultados batch_size = int(df.iat[row,5]) epochs = int(df.iat[row,0]) optimization = df.iat[row,3] activation = df.iat[row,2] hidden_layers = int(df.iat[row,6]) neurons = int(df.iat[row,4]) dropout = float(df.iat[row,1]) result_r = float(df.iat[row,7]) if hemisferio == "Izquierdo": pregunta_seguir = "¿Finalizar (3)?\n" else: pregunta_seguir = "¿Seguir con el Otro Hemisferio (3)?\n" for dropouts in [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0]: for execution in range(1,100): opcion = input("Ejecucion %d. \nHemisferio %s. \n¿Deseas continuar? (0) \n¿Deseas Cambiar DropOut? (1) \n¿Deseas Probar Con Otros Hiperparametros (2)?\n%s"%(execution,hemisferio,pregunta_seguir)) if opcion == "1": break elif opcion == "2": break elif opcion == "3": return use_cpu_gpu() lstm_model = fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout) output = evaluate_stair(lstm_model, escalon, batch_size) r = evaluate(lstm_model, testX, testY, batch_size) plotting_mathplot(escalon, output, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout, r) quedar = input("¿Te quedas con esta? \nSi(1) \nNo(0) \n") if quedar == "1": save_hidden_states(lstm_model, neurons, layer=0, sujeto=sujeto, postura=postura, hemisferio=hemisferio) save_hidden_states(lstm_model, neurons, layer=1, sujeto=sujeto, postura=postura, hemisferio=hemisferio) save_hidden_states(lstm_model, neurons, layer=2, sujeto=sujeto, postura=postura, hemisferio=hemisferio) save_signal(scaler_VFSC.inverse_transform(output), sujeto=sujeto, postura=postura, hemisferio=hemisferio) save_model(lstm_model, sujeto=sujeto, postura=postura, hemisferio=hemisferio) #save_hidden_output(lstm_model, escalon, sujeto, postura, hemisferio) K.clear_session() del lstm_model gc.collect() if opcion == "0": continue seguir = input("dropout = %.1f \nSeguir si(0) no(2):"%dropout) if seguir == "2": dropout = 1.0 break if opcion == "1": continue elif opcion == "2" or seguir == "2": break def save_model(model, sujeto, postura, hemisferio): directory = PATH_RESULTADO%(sujeto)+'/models' if not os.path.exists(directory): os.makedirs(directory) model_json = model.to_json() with open(directory+"/model_"+str(postura)+'_'+str(hemisferio)+".json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights(directory+"/model_"+str(postura)+'_'+str(hemisferio)+".h5") def save_signal(output, sujeto, postura, hemisferio): df = pd.DataFrame(output.tolist(), columns=['Output']) df.to_csv(PATH_RESULTADO_ESCALON%(sujeto, postura, hemisferio)+'_output.csv',index=False) def save_hidden_output(model, escalon, sujeto, postura, hemisferio): intermediate_layer_model = Model(inputs=model.layers[0].input, outputs=model.layers[0].output) intermediate_output = intermediate_layer_model.predict(escalon) df = pd.DataFrame({'Output': intermediate_output}) writer = pd.ExcelWriter(PATH_RESULTADO_ESCALON%(sujeto, postura, hemisferio)+'_output_hidden_layer.xlsx') df.to_excel(writer, sheet_name='Kernel') writer.save() def save_hidden_states(model, units, layer, sujeto, postura, hemisferio): W = model.layers[layer].get_weights()[0] U = model.layers[layer].get_weights()[1] b = model.layers[layer].get_weights()[2] W_i = W[:, :units] W_f = W[:, units: units * 2] W_c = W[:, units * 2: units * 3] W_o = W[:, units * 3:] U_i = U[:, :units] U_f = U[:, units: units * 2] U_c = U[:, units * 2: units * 3] U_o = U[:, units * 3:] b_i = b[:units] b_f = b[units: units * 2] b_c = b[units * 2: units * 3] b_o = b[units * 3:] column_W = ['W_i', 'W_f', 'W_c', 'W_o'] column_U = ['U_i', 'U_f', 'U_c', 'U_o'] column_b = ['b_i', 'b_f', 'b_c', 'b_o'] # Create some Pandas dataframes from some data. if layer == 0: data_W_i = list(zip(W_i.reshape(units,1).tolist(), W_f.reshape(units,1).tolist(), W_c.reshape(units,1).tolist(), W_o.reshape(units,1).tolist())) data_U_i = list(zip(U_i.reshape(units*units,1).tolist(), U_f.reshape(units*units,1).tolist(), U_c.reshape(units*units,1).tolist(), U_o.reshape(units*units,1).tolist())) data_b_i = list(zip(b_i.reshape(units,1).tolist(), b_f.reshape(units,1).tolist(), b_c.reshape(units,1).tolist(), b_o.reshape(units,1).tolist())) else: data_W_i = list(zip(W_i.reshape(units*units,1).tolist(), W_f.reshape(units*units,1).tolist(), W_c.reshape(units*units,1).tolist(), W_o.reshape(units*units,1).tolist())) data_U_i = list(zip(U_i.reshape(units*units,1).tolist(), U_f.reshape(units*units,1).tolist(), U_c.reshape(units*units,1).tolist(), U_o.reshape(units*units,1).tolist())) data_b_i = list(zip(b_i.reshape(units,1).tolist(), b_f.reshape(units,1).tolist(), b_c.reshape(units,1).tolist(), b_o.reshape(units,1).tolist())) df1 = pd.DataFrame(data_W_i, columns=column_W) df2 = pd.DataFrame(data_U_i, columns=column_U) df3 = pd.DataFrame(data_b_i, columns=column_b) # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter(PATH_RESULTADO_ESCALON%(sujeto, postura, hemisferio)+'_layer_'+str(layer)+'.xlsx',index=False) # Write each dataframe to a different worksheet. df1.to_excel(writer, sheet_name='Kernel') df2.to_excel(writer, sheet_name='Recurrent Kernel') df3.to_excel(writer, sheet_name='Bias') # Close the Pandas Excel writer and output the Excel file. writer.save() def run (sujeto, postura, proceso_escalon = False, hemisferio_derecho=True, hemisferio_izquierdo=True): print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') path = PATH_RESULTADO%(sujeto) if not os.path.exists(path): os.makedirs(path) train_PAM, train_VFSCd, train_VFSCi, test_PAM, test_VFSCd, test_VFSCi, Escalon, scaler_VFSCd, scaler_VFSCi, scaler_escalon = create_dataset(sujeto, postura) activation = ['softplus','sigmoid', 'hard_sigmoid'] neurons = [5,10,15,20,30,40] hidden_layers = [3, 4, 5] dropout = [0.6, 0.7, 0.8, 0.9] optimization = ['RMSprop'] epochs = [10] batch_size = [198] ''' batch_size = [] for i in range(1,train_PAM.shape[0]+1): if (train_PAM.shape[0]%i)==0: batch_size.append(199) ''' if hemisferio_derecho == True: hemisferio = "Derecho" PATH_RESULTADO_CONTEXTO = PATH_RESULTADO_ESCALON%(sujeto, postura, hemisferio) exists_1 = os.path.isfile(PATH_RESULTADO_CONTEXTO+"_1.csv") exists_2 = os.path.isfile(PATH_RESULTADO_CONTEXTO+"_2.csv") best_balance = 0 if exists_1 == False and exists_2 == False: ################################################################################### Balance 1 print('++++++++++++++++++++++++++++++++++++++ Sujeto: ' + sujeto + ' Posicion: ' + postura + ' Balance: 1, Emisferio: Derecho') df_1 = run_experiment(train_PAM, train_VFSCd, test_PAM, test_VFSCd, batch_size=batch_size, epochs=epochs, optimization=optimization, activation=activation, hidden_layers=hidden_layers, neurons=neurons, dropout=dropout) ################################################################################### Balance 2 print('++++++++++++++++++++++++++++++++++++++ Sujeto: ' + sujeto + ' Posicion: ' + postura + ' Balance: 2, Emisferio: Derecho') df_2 = run_experiment(test_PAM, test_VFSCd, train_PAM, train_VFSCd, batch_size=batch_size, epochs=epochs, optimization=optimization, activation=activation, hidden_layers=hidden_layers, neurons=neurons, dropout=dropout) df, best_balance = best_model(df_1, df_2, PATH_RESULTADO_CONTEXTO) if (best_balance == 1 or exists_1 == True) and proceso_escalon == True: df = pd.read_csv(PATH_RESULTADO_CONTEXTO+"_1.csv", dtype='S') apply_stair(df, train_PAM, train_VFSCd, test_PAM, test_VFSCd, Escalon, scaler_VFSCd, scaler_escalon, sujeto, postura, hemisferio) elif (best_balance == 2 or exists_2 == True) and proceso_escalon == True: df = pd.read_csv(PATH_RESULTADO_CONTEXTO+"_2.csv", dtype='S') apply_stair(df, test_PAM, test_VFSCd, train_PAM, train_VFSCd, Escalon, scaler_VFSCd, scaler_escalon, sujeto, postura, hemisferio) ########################################################################################## HEMISFERIO IZQUIERDO ################################################################################### Balance 1 if hemisferio_izquierdo == True: hemisferio = "Izquierdo" PATH_RESULTADO_CONTEXTO = PATH_RESULTADO_ESCALON%(sujeto, postura, hemisferio) exists_1 = os.path.isfile(PATH_RESULTADO_CONTEXTO+"_1.csv") exists_2 = os.path.isfile(PATH_RESULTADO_CONTEXTO+"_2.csv") best_balance = 0 print('++++++++++++++++++++++++++++++++++++++ Sujeto: ' + sujeto + ' Posicion: ' + postura + ' Balance: 1, Emisferio: Izquierdo') if exists_1 == False and exists_2 == False: df_1 = run_experiment(train_PAM, train_VFSCi, test_PAM, test_VFSCi, batch_size=batch_size, epochs=epochs, optimization=optimization, activation=activation, hidden_layers=hidden_layers, neurons=neurons, dropout=dropout) ################################################################################### Balance 2 print('++++++++++++++++++++++++++++++++++++++ Sujeto: ' + sujeto + ' Posicion: ' + postura + ' Balance: 2, Emisferio: Izquierdo') df_2 = run_experiment(test_PAM, test_VFSCi, train_PAM, train_VFSCi, batch_size=batch_size, epochs=epochs, optimization=optimization, activation=activation, hidden_layers=hidden_layers, neurons=neurons, dropout=dropout) df, best_balance = best_model(df_1, df_2, PATH_RESULTADO_CONTEXTO) ########################################################################################## ENTRENAR MODELO A PARTIR DE "df" Y GRAFICAR RESPUESTA ESCALON if (best_balance == 1 or exists_1 == True) and proceso_escalon == True: df = pd.read_csv(PATH_RESULTADO_CONTEXTO+"_1.csv") apply_stair(df, train_PAM, train_VFSCi, test_PAM, test_VFSCi, Escalon, scaler_VFSCi, scaler_escalon, sujeto, postura, hemisferio) elif (best_balance == 2 or exists_2 == True) and proceso_escalon == True: df = pd.read_csv(PATH_RESULTADO_CONTEXTO+"_2.csv") apply_stair(df, test_PAM, test_VFSCi, train_PAM, train_VFSCi, Escalon, scaler_VFSCi, scaler_escalon, sujeto, postura, hemisferio) #Repitable Experiment seed(1) set_random_seed(2) #run(sujeto='AP', postura='PIE', proceso_escalon=False, hemisferio_derecho=False) #run(sujeto='AV', postura='ACOSTADO', proceso_escalon = False, hemisferio_izquierdo=False) #run(sujeto='AV', postura='PIE', proceso_escalon = False, hemisferio_derecho=False) #run(sujeto='CC', postura='ACOSTADO', proceso_escalon = False, hemisferio_derecho=False) #run(sujeto='CC', postura='PIE', proceso_escalon = True)#falta emisferio ezquierdo #################################################### #take time t0 = time.time() run(sujeto='AC', postura='ACOSTADO', proceso_escalon = True) print ('###################################################################################',time.time() - t0, "segundos tardo")<file_sep> is.wholenumber <- function(x, tol, ...) UseMethod("is.wholenumber") is.wholenumber.default <- function(x, tol = .Machine$double.eps^0.5, ...) { abs(x - round(x)) < tol } is.divisible <- function(x, y, tol, ...) UseMethod("is.divisible") is.divisible.default <- function(x, y, tol = .Machine$double.eps^0.5, ...) { is.wholenumber( x / y, tol, ...) } are.tolerably.equal <- function(x, y, tol, ...) UseMethod("tolerably.equal") are.tolerably.equal <- function(x, y, tol = .Machine$double.eps^0.5, ...) { abs(x - y) < tol } <file_sep>from gensim.models import Word2Vec import pandas as pd w2v_model = Word2Vec.load("w2v_model") print(w2v_model.wv.most_similar(positive=["methoxy"])) ######################################################################################## import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") from sklearn.decomposition import PCA from sklearn.manifold import TSNE def tsnescatterplot(model, word, list_names): arrays = np.empty((0, 200), dtype='f') word_labels = [word] color_list = ['red'] arrays = np.append(arrays, model.wv.__getitem__([word]), axis=0) close_words = model.wv.most_similar([word]) for wrd_score in close_words: wrd_vector = model.wv.__getitem__([wrd_score[0]]) word_labels.append(wrd_score[0]) color_list.append('blue') arrays = np.append(arrays, wrd_vector, axis=0) for wrd in list_names: wrd_vector = model.wv.__getitem__([wrd]) word_labels.append(wrd) color_list.append('green') arrays = np.append(arrays, wrd_vector, axis=0) reduc = PCA(n_components=21).fit_transform(arrays) np.set_printoptions(suppress=True) Y = TSNE(n_components=2, random_state=0, perplexity=15).fit_transform(reduc) df = pd.DataFrame({'x': [x for x in Y[:, 0]], 'y': [y for y in Y[:, 1]], 'words': word_labels, 'color': color_list}) fig, _ = plt.subplots() fig.set_size_inches(9, 9) p1 = sns.regplot(data=df, x="x", y="y", fit_reg=False, marker="o", scatter_kws={'s': 40, 'facecolors': df['color'] } ) for line in range(0, df.shape[0]): p1.text(df["x"][line], df['y'][line], ' ' + df["words"][line].title(), horizontalalignment='left', verticalalignment='bottom', size='medium', color=df['color'][line], weight='normal' ).set_size(15) plt.xlim(Y[:, 0].min()-50, Y[:, 0].max()+50) plt.ylim(Y[:, 1].min()-50, Y[:, 1].max()+50) plt.title('t-SNE visualization for {}'.format(word.title())) tsnescatterplot(w2v_model, 'curcumin', [i[0] for i in w2v_model.wv.most_similar(negative=["curcumin"])]) tsnescatterplot(w2v_model, "oxime", [t[0] for t in w2v_model.wv.most_similar(positive=["oxime"], topn=20)][10:])<file_sep><<<<<<< HEAD <<<<<<< HEAD setwd(choose.dir())#Entregar ruta de trabajo #Instala paquete “aruleViz” install.packages('arulesViz', dep = TRUE) library(arulesViz) data = read.csv("zoo.csv") #Carga dataset summary(data) #Resumen estadístico data <- data.frame(sapply(data,as.factor)) #Discretiza datos rules <- apriori(data, parameter=list(support=0.37, confidence=0.5, maxlen=50))#5736 Encontradas inspect(head(sort(rules, by ="lift"),3))#Tres primeras reglas plot(rules, measure=c("support", "lift"), shading="confidence")#Diagrama de dispersión inspect(head(sort(rules, by ="lift"),260)) #Visualizar reglas para seleccionar subrules <- rules[quality(rules)$lift > 1.46]#Visualizar reglas que tengan más de “1.46” lift subrules #Número de reglas obtenidas: 1928 #Matrices de reglas plot(subrules, method="matrix", measure="lift", control=list(reorder=TRUE)) plot(subrules, method="matrix3D", measure="lift", control=list(reorder=TRUE)) plot(subrules, method="matrix3D", measure="support", control=list(reorder=TRUE)) plot(subrules, method="matrix", measure=c("lift", "confidence"),control=list(reorder=TRUE)) #Matriz de agrupación (5.736 reglas). Siete agrupadores de reglas en eje “X”. plot(rules, method="grouped", control=list(k=7)) subrules2 <- head(sort(rules, by="lift"), 10)#Sub Set de 10 reglas. plot(subrules2, method="graph")#Grafico de vértices para diez reglas. #Grafico de coordenadas paralelas para diez reglas. plot(subrules2, method="paracoord", control=list(reorder=TRUE)) ======= setwd(choose.dir())#Entregar ruta de trabajo #Instala paquete “aruleViz” install.packages('arulesViz', dep = TRUE) library(arulesViz) data = read.csv("zoo.csv") #Carga dataset summary(data) #Resumen estadístico data <- data.frame(sapply(data,as.factor)) #Discretiza datos rules <- apriori(data, parameter=list(support=0.37, confidence=0.5, maxlen=50))#5736 Encontradas inspect(head(sort(rules, by ="lift"),3))#Tres primeras reglas plot(rules, measure=c("support", "lift"), shading="confidence")#Diagrama de dispersión inspect(head(sort(rules, by ="lift"),260)) #Visualizar reglas para seleccionar subrules <- rules[quality(rules)$lift > 1.46]#Visualizar reglas que tengan más de “1.46” lift subrules #Número de reglas obtenidas: 1928 #Matrices de reglas plot(subrules, method="matrix", measure="lift", control=list(reorder=TRUE)) plot(subrules, method="matrix3D", measure="lift", control=list(reorder=TRUE)) plot(subrules, method="matrix3D", measure="support", control=list(reorder=TRUE)) plot(subrules, method="matrix", measure=c("lift", "confidence"),control=list(reorder=TRUE)) #Matriz de agrupación (5.736 reglas). Siete agrupadores de reglas en eje “X”. plot(rules, method="grouped", control=list(k=7)) subrules2 <- head(sort(rules, by="lift"), 10)#Sub Set de 10 reglas. plot(subrules2, method="graph")#Grafico de vértices para diez reglas. #Grafico de coordenadas paralelas para diez reglas. plot(subrules2, method="paracoord", control=list(reorder=TRUE)) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= setwd(choose.dir())#Entregar ruta de trabajo #Instala paquete “aruleViz” install.packages('arulesViz', dep = TRUE) library(arulesViz) data = read.csv("zoo.csv") #Carga dataset summary(data) #Resumen estadístico data <- data.frame(sapply(data,as.factor)) #Discretiza datos rules <- apriori(data, parameter=list(support=0.37, confidence=0.5, maxlen=50))#5736 Encontradas inspect(head(sort(rules, by ="lift"),3))#Tres primeras reglas plot(rules, measure=c("support", "lift"), shading="confidence")#Diagrama de dispersión inspect(head(sort(rules, by ="lift"),260)) #Visualizar reglas para seleccionar subrules <- rules[quality(rules)$lift > 1.46]#Visualizar reglas que tengan más de “1.46” lift subrules #Número de reglas obtenidas: 1928 #Matrices de reglas plot(subrules, method="matrix", measure="lift", control=list(reorder=TRUE)) plot(subrules, method="matrix3D", measure="lift", control=list(reorder=TRUE)) plot(subrules, method="matrix3D", measure="support", control=list(reorder=TRUE)) plot(subrules, method="matrix", measure=c("lift", "confidence"),control=list(reorder=TRUE)) #Matriz de agrupación (5.736 reglas). Siete agrupadores de reglas en eje “X”. plot(rules, method="grouped", control=list(k=7)) subrules2 <- head(sort(rules, by="lift"), 10)#Sub Set de 10 reglas. plot(subrules2, method="graph")#Grafico de vértices para diez reglas. #Grafico de coordenadas paralelas para diez reglas. plot(subrules2, method="paracoord", control=list(reorder=TRUE)) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep><<<<<<< HEAD <<<<<<< HEAD RUTA_DATASET <- "C:/Users/Luis.O.A/Documents/USACH/Mineria de Datos/Trabajos/6" CANTIDAD_NUCLEOS <- 4 setwd(RUTA_DATASET) #install.packages('plotly', dep = TRUE) library(e1071) #install.packages('doParallel', dep = TRUE) library(doParallel) #install.packages('xlsx', dep = TRUE) library('xlsx') library(plotly) library(plyr) registerDoParallel(cores = CANTIDAD_NUCLEOS) retardos_multi <- function( signalData, lags){ signal.uni <- signalData max.lag <- max(unlist(lags)) + 1 indices <- 1:nrow(signal.uni) lag.mat <- embed(indices, max.lag) col.names <- list("PAMn","VFSCn") columns <- NULL lagged.columns.names <- c() for(colname in col.names){ lag.order <- lags[[colname]] columns[[colname]] <- signal.uni[lag.mat[, 1], colname] if(!is.null(lag.order) && lag.order > 0) for(i in 1:lag.order){ new.colname <- paste(colname, paste0("lag", i), sep = ".") lagged.columns.names <- c(lagged.columns.names, new.colname) columns[[new.colname]] <- signal.uni[lag.mat[, i+1], colname] } } folded.signal <- data.frame(columns) sorting <- order(lag.mat[, 1]) folded.signal <- folded.signal[sorting, ] list(folded.signal = folded.signal, lagged.columns.names = lagged.columns.names) } entrenar <- function(data.1, data.2, parms, retardos_multi){ salida <- (c( foreach(i = 1:nrow(parms), combine = rbind, .inorder = FALSE) %dopar% { c <- parms[i, ]$cost n <- parms[i, ]$nu g <- parms[i, ]$gamma l <- parms[i, ]$lagsList lag<-list(PAMn = l,VFSCn = 0) #Etrenamiento 1 signal.train.1 <- retardos_multi(data.1, lag) retDataset1=signal.train.1$folded.signal x.1=subset(retDataset1, select = -VFSCn) y.1=retDataset1$VFSCn modelo <- e1071::svm(x.1, y.1, type = "nu-regression", kernel = "radial", cost = c, nu = n, gamma=g) #Test 2 signal.train.2 <- retardos_multi(data.2, lag) retDataset2=signal.train.2$folded.signal x.2=subset(retDataset2, select = -VFSCn) pred <- predict(modelo, x.2) y.2=retDataset2$VFSCn corr_pred<-cor(pred,y.2,method = "pearson") c(l, c, n, g, corr_pred) })) output <- matrix(unlist(salida), ncol = 5, byrow = TRUE) mejoresModelos<-output[order(output[,5], decreasing = TRUE),] return(mejoresModelos) } plot.signal <- function(datos, retardos_multi, mejoresModelos, i){ Ts=0.2 inverseStep=matrix(1,180/Ts,1) inverseStep[(90/Ts):(180/Ts),1]=0 if(i == 0){ for (i in 1:length(mejoresModelos[,1])){ lag<-list(PAMn = mejoresModelos[i,1],VFSCn = 0) signal.train <- retardos_multi(datos, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn mejorModelo <- svm(x, y, kernel = "radial",type = "nu-regression", cost = mejoresModelos[i,2], nu = mejoresModelos[i,3], gamma=mejoresModelos[i,4]) #PAMn=inverseStep #VFSCn=inverseStep ##################PRUEBA CON LOS ESCALONES data.esc = read.table("esc.txt") PAMn = matrix(data.esc$V1) VFSCn = matrix(1,length(PAMn),1) ############# data <- data.frame(PAMn,VFSCn) signal.train <- retardos_multi(data, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn stepTime=seq(Ts,(length(retDataset1$PAMn))*Ts,Ts) stepResponse <- predict(mejorModelo, x ) plot(stepTime,retDataset1$PAMn,type="l", col="red") lines(stepTime,stepResponse, col = "blue") legend("topright", c("Escalon de presión", "respuesta al escalon", paste("i = ",i)), title = "autorregulacion", pch = 1, col=c("red","blue"),lty=c(1,1),inset = 0.01) print(paste("corr=",mejoresModelos[i,5])) readline(prompt="Press [enter] to continue") } }else if(i > 0){ lag<-list(PAMn = mejoresModelos[i,1],VFSCn = 0) signal.train <- retardos_multi(datos, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn mejorModelo <- svm(x, y, kernel = "radial",type = "nu-regression", cost = mejoresModelos[i,2], nu = mejoresModelos[i,3], gamma=mejoresModelos[i,4]) #PAMn=inverseStep #VFSCn=inverseStep ##################PRUEBA CON LOS ESCALONES data.esc = read.table("esc.txt") PAMn = matrix(data.esc$V1) VFSCn = matrix(1,length(PAMn),1) ############# data <- data.frame(PAMn,VFSCn) signal.train <- retardos_multi(data, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn stepTime=seq(Ts,(length(retDataset1$PAMn))*Ts,Ts) stepResponse <- predict(mejorModelo, x ) data.escalon <- data.frame(Time = stepTime, PAM = retDataset1$PAMn, z = stepResponse) p <- plot_ly(data.escalon, x = ~Time, y = ~PAM, name = 'Escalon de presión', type = 'scatter', mode = 'lines') %>% add_trace(y = ~z, name = 'respuesta al escalon', mode = 'lines') p } } cost <- 2^(-4:12) nu <- seq(0.1, 1.0, 0.1) gamma<- 2^(-4:12) lagsList<-(1:8) Dataset1=read.csv("G5_002.csv") set.seed(100) trainingRows <- sample(1:nrow(Dataset1), 0.5*nrow(Dataset1)) A <- Dataset1[trainingRows, ] B <- Dataset1[-trainingRows, ] data.1 <- data.frame(PAMn = (A$PAM-min(A$PAM))/(max(A$PAM)-min(A$PAM)),VFSCn = (A$VFSC-min(A$VFSC))/(max(A$VFSC)-min(A$VFSC))) data.2 <- data.frame(PAMn = (B$PAM-min(B$PAM))/(max(B$PAM)-min(B$PAM)),VFSCn = (B$VFSC-min(B$VFSC))/(max(B$VFSC)-min(B$VFSC))) parms <- expand.grid(lagsList=lagsList, cost = cost, nu = nu, gamma=gamma) mejoresModelos.1 <- entrenar(data.1, data.2, parms, retardos_multi) mejoresModelos.2 <- entrenar(data.2, data.1, parms, retardos_multi) write.xlsx(data.frame(LagList = mejoresModelos.1[,1], Cost = mejoresModelos.1[,2], Nu = mejoresModelos.1[,3], Gamma = mejoresModelos.1[,4], Correlacion = mejoresModelos.1[,5]), "mejoresModelos_1.xlsx", sheetName="Sheet1", append = FALSE) write.xlsx(data.frame(LagList = mejoresModelos.2[,1], Cost = mejoresModelos.2[,2], Nu = mejoresModelos.2[,3], Gamma = mejoresModelos.2[,4], Correlacion = mejoresModelos.2[,5]), "mejoresModelos_2.xlsx", sheetName="Sheet1", append = FALSE) ############################CORRER HASTA ESTA LINEA mm1=read.csv("mm1.csv") mm1 <- as.matrix(setNames(mm1,NULL)) #sano mm2=read.csv("mm2.csv") mm2 <- as.matrix(setNames(mm2,NULL)) #Enfermo ######### Eleccion de modelos. Si el ultimo parametro es 0, se veran todos los modelos generados. Si el parametro es mayor a 0 se visualizara el modelo ingresado plot.signal(data.1, retardos_multi, mm1, 85)#17-21-25(mejor)-39-40(mejor)-44(mejor)-56-59-85(mejor) plot.signal(data.2, retardos_multi, mm2, 22)#4-8-22(mejor) ####################GRAFICA SEÑAL Dataset1=read.csv("G5_002.csv") largo.d1 = length(Dataset1$PAM) Dataset2=read.csv("G6_001.csv")[1:largo.d1,] largo.d2 = length(Dataset2$PAM) data.escalon <- data.frame(Time = c(1:largo.d2), PAM = Dataset1$PAM, PAM_Sujeto_2 = Dataset2$PAM) p <- plot_ly(data.escalon, x = ~Time, y = ~PAM, name = 'PAM Sujeto 1', type = 'scatter', mode = 'lines') %>% add_trace(y = ~PAM_Sujeto_2, name = 'PAM Sujeto 2', mode = 'lines') p data.escalon <- data.frame(Time = c(1:largo.d2), VFSC_Sujeto_1 = Dataset1$VFSC, VFSC_Sujeto_2 = Dataset2$VFSC) p <- plot_ly(data.escalon, x = ~Time, y = ~VFSC_Sujeto_1, name = 'VFSC Sujeto 1', type = 'scatter', mode = 'lines') %>% add_trace(y = ~VFSC_Sujeto_2, name = 'VFSC Sujeto 2', mode = 'lines') p ======= RUTA_DATASET <- "C:/Users/Luis.O.A/Documents/USACH/Mineria de Datos/Trabajos/6" CANTIDAD_NUCLEOS <- 4 setwd(RUTA_DATASET) #install.packages('plotly', dep = TRUE) library(e1071) #install.packages('doParallel', dep = TRUE) library(doParallel) #install.packages('xlsx', dep = TRUE) library('xlsx') library(plotly) library(plyr) registerDoParallel(cores = CANTIDAD_NUCLEOS) retardos_multi <- function( signalData, lags){ signal.uni <- signalData max.lag <- max(unlist(lags)) + 1 indices <- 1:nrow(signal.uni) lag.mat <- embed(indices, max.lag) col.names <- list("PAMn","VFSCn") columns <- NULL lagged.columns.names <- c() for(colname in col.names){ lag.order <- lags[[colname]] columns[[colname]] <- signal.uni[lag.mat[, 1], colname] if(!is.null(lag.order) && lag.order > 0) for(i in 1:lag.order){ new.colname <- paste(colname, paste0("lag", i), sep = ".") lagged.columns.names <- c(lagged.columns.names, new.colname) columns[[new.colname]] <- signal.uni[lag.mat[, i+1], colname] } } folded.signal <- data.frame(columns) sorting <- order(lag.mat[, 1]) folded.signal <- folded.signal[sorting, ] list(folded.signal = folded.signal, lagged.columns.names = lagged.columns.names) } entrenar <- function(data.1, data.2, parms, retardos_multi){ salida <- (c( foreach(i = 1:nrow(parms), combine = rbind, .inorder = FALSE) %dopar% { c <- parms[i, ]$cost n <- parms[i, ]$nu g <- parms[i, ]$gamma l <- parms[i, ]$lagsList lag<-list(PAMn = l,VFSCn = 0) #Etrenamiento 1 signal.train.1 <- retardos_multi(data.1, lag) retDataset1=signal.train.1$folded.signal x.1=subset(retDataset1, select = -VFSCn) y.1=retDataset1$VFSCn modelo <- e1071::svm(x.1, y.1, type = "nu-regression", kernel = "radial", cost = c, nu = n, gamma=g) #Test 2 signal.train.2 <- retardos_multi(data.2, lag) retDataset2=signal.train.2$folded.signal x.2=subset(retDataset2, select = -VFSCn) pred <- predict(modelo, x.2) y.2=retDataset2$VFSCn corr_pred<-cor(pred,y.2,method = "pearson") c(l, c, n, g, corr_pred) })) output <- matrix(unlist(salida), ncol = 5, byrow = TRUE) mejoresModelos<-output[order(output[,5], decreasing = TRUE),] return(mejoresModelos) } plot.signal <- function(datos, retardos_multi, mejoresModelos, i){ Ts=0.2 inverseStep=matrix(1,180/Ts,1) inverseStep[(90/Ts):(180/Ts),1]=0 if(i == 0){ for (i in 1:length(mejoresModelos[,1])){ lag<-list(PAMn = mejoresModelos[i,1],VFSCn = 0) signal.train <- retardos_multi(datos, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn mejorModelo <- svm(x, y, kernel = "radial",type = "nu-regression", cost = mejoresModelos[i,2], nu = mejoresModelos[i,3], gamma=mejoresModelos[i,4]) #PAMn=inverseStep #VFSCn=inverseStep ##################PRUEBA CON LOS ESCALONES data.esc = read.table("esc.txt") PAMn = matrix(data.esc$V1) VFSCn = matrix(1,length(PAMn),1) ############# data <- data.frame(PAMn,VFSCn) signal.train <- retardos_multi(data, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn stepTime=seq(Ts,(length(retDataset1$PAMn))*Ts,Ts) stepResponse <- predict(mejorModelo, x ) plot(stepTime,retDataset1$PAMn,type="l", col="red") lines(stepTime,stepResponse, col = "blue") legend("topright", c("Escalon de presión", "respuesta al escalon", paste("i = ",i)), title = "autorregulacion", pch = 1, col=c("red","blue"),lty=c(1,1),inset = 0.01) print(paste("corr=",mejoresModelos[i,5])) readline(prompt="Press [enter] to continue") } }else if(i > 0){ lag<-list(PAMn = mejoresModelos[i,1],VFSCn = 0) signal.train <- retardos_multi(datos, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn mejorModelo <- svm(x, y, kernel = "radial",type = "nu-regression", cost = mejoresModelos[i,2], nu = mejoresModelos[i,3], gamma=mejoresModelos[i,4]) #PAMn=inverseStep #VFSCn=inverseStep ##################PRUEBA CON LOS ESCALONES data.esc = read.table("esc.txt") PAMn = matrix(data.esc$V1) VFSCn = matrix(1,length(PAMn),1) ############# data <- data.frame(PAMn,VFSCn) signal.train <- retardos_multi(data, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn stepTime=seq(Ts,(length(retDataset1$PAMn))*Ts,Ts) stepResponse <- predict(mejorModelo, x ) data.escalon <- data.frame(Time = stepTime, PAM = retDataset1$PAMn, z = stepResponse) p <- plot_ly(data.escalon, x = ~Time, y = ~PAM, name = 'Escalon de presión', type = 'scatter', mode = 'lines') %>% add_trace(y = ~z, name = 'respuesta al escalon', mode = 'lines') p } } cost <- 2^(-4:12) nu <- seq(0.1, 1.0, 0.1) gamma<- 2^(-4:12) lagsList<-(1:8) Dataset1=read.csv("G5_002.csv") set.seed(100) trainingRows <- sample(1:nrow(Dataset1), 0.5*nrow(Dataset1)) A <- Dataset1[trainingRows, ] B <- Dataset1[-trainingRows, ] data.1 <- data.frame(PAMn = (A$PAM-min(A$PAM))/(max(A$PAM)-min(A$PAM)),VFSCn = (A$VFSC-min(A$VFSC))/(max(A$VFSC)-min(A$VFSC))) data.2 <- data.frame(PAMn = (B$PAM-min(B$PAM))/(max(B$PAM)-min(B$PAM)),VFSCn = (B$VFSC-min(B$VFSC))/(max(B$VFSC)-min(B$VFSC))) parms <- expand.grid(lagsList=lagsList, cost = cost, nu = nu, gamma=gamma) mejoresModelos.1 <- entrenar(data.1, data.2, parms, retardos_multi) mejoresModelos.2 <- entrenar(data.2, data.1, parms, retardos_multi) write.xlsx(data.frame(LagList = mejoresModelos.1[,1], Cost = mejoresModelos.1[,2], Nu = mejoresModelos.1[,3], Gamma = mejoresModelos.1[,4], Correlacion = mejoresModelos.1[,5]), "mejoresModelos_1.xlsx", sheetName="Sheet1", append = FALSE) write.xlsx(data.frame(LagList = mejoresModelos.2[,1], Cost = mejoresModelos.2[,2], Nu = mejoresModelos.2[,3], Gamma = mejoresModelos.2[,4], Correlacion = mejoresModelos.2[,5]), "mejoresModelos_2.xlsx", sheetName="Sheet1", append = FALSE) ############################CORRER HASTA ESTA LINEA mm1=read.csv("mm1.csv") mm1 <- as.matrix(setNames(mm1,NULL)) #sano mm2=read.csv("mm2.csv") mm2 <- as.matrix(setNames(mm2,NULL)) #Enfermo ######### Eleccion de modelos. Si el ultimo parametro es 0, se veran todos los modelos generados. Si el parametro es mayor a 0 se visualizara el modelo ingresado plot.signal(data.1, retardos_multi, mm1, 85)#17-21-25(mejor)-39-40(mejor)-44(mejor)-56-59-85(mejor) plot.signal(data.2, retardos_multi, mm2, 22)#4-8-22(mejor) ####################GRAFICA SEÑAL Dataset1=read.csv("G5_002.csv") largo.d1 = length(Dataset1$PAM) Dataset2=read.csv("G6_001.csv")[1:largo.d1,] largo.d2 = length(Dataset2$PAM) data.escalon <- data.frame(Time = c(1:largo.d2), PAM = Dataset1$PAM, PAM_Sujeto_2 = Dataset2$PAM) p <- plot_ly(data.escalon, x = ~Time, y = ~PAM, name = 'PAM Sujeto 1', type = 'scatter', mode = 'lines') %>% add_trace(y = ~PAM_Sujeto_2, name = 'PAM Sujeto 2', mode = 'lines') p data.escalon <- data.frame(Time = c(1:largo.d2), VFSC_Sujeto_1 = Dataset1$VFSC, VFSC_Sujeto_2 = Dataset2$VFSC) p <- plot_ly(data.escalon, x = ~Time, y = ~VFSC_Sujeto_1, name = 'VFSC Sujeto 1', type = 'scatter', mode = 'lines') %>% add_trace(y = ~VFSC_Sujeto_2, name = 'VFSC Sujeto 2', mode = 'lines') p >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= RUTA_DATASET <- "C:/Users/Luis.O.A/Documents/USACH/Mineria de Datos/Trabajos/6" CANTIDAD_NUCLEOS <- 4 setwd(RUTA_DATASET) #install.packages('plotly', dep = TRUE) library(e1071) #install.packages('doParallel', dep = TRUE) library(doParallel) #install.packages('xlsx', dep = TRUE) library('xlsx') library(plotly) library(plyr) registerDoParallel(cores = CANTIDAD_NUCLEOS) retardos_multi <- function( signalData, lags){ signal.uni <- signalData max.lag <- max(unlist(lags)) + 1 indices <- 1:nrow(signal.uni) lag.mat <- embed(indices, max.lag) col.names <- list("PAMn","VFSCn") columns <- NULL lagged.columns.names <- c() for(colname in col.names){ lag.order <- lags[[colname]] columns[[colname]] <- signal.uni[lag.mat[, 1], colname] if(!is.null(lag.order) && lag.order > 0) for(i in 1:lag.order){ new.colname <- paste(colname, paste0("lag", i), sep = ".") lagged.columns.names <- c(lagged.columns.names, new.colname) columns[[new.colname]] <- signal.uni[lag.mat[, i+1], colname] } } folded.signal <- data.frame(columns) sorting <- order(lag.mat[, 1]) folded.signal <- folded.signal[sorting, ] list(folded.signal = folded.signal, lagged.columns.names = lagged.columns.names) } entrenar <- function(data.1, data.2, parms, retardos_multi){ salida <- (c( foreach(i = 1:nrow(parms), combine = rbind, .inorder = FALSE) %dopar% { c <- parms[i, ]$cost n <- parms[i, ]$nu g <- parms[i, ]$gamma l <- parms[i, ]$lagsList lag<-list(PAMn = l,VFSCn = 0) #Etrenamiento 1 signal.train.1 <- retardos_multi(data.1, lag) retDataset1=signal.train.1$folded.signal x.1=subset(retDataset1, select = -VFSCn) y.1=retDataset1$VFSCn modelo <- e1071::svm(x.1, y.1, type = "nu-regression", kernel = "radial", cost = c, nu = n, gamma=g) #Test 2 signal.train.2 <- retardos_multi(data.2, lag) retDataset2=signal.train.2$folded.signal x.2=subset(retDataset2, select = -VFSCn) pred <- predict(modelo, x.2) y.2=retDataset2$VFSCn corr_pred<-cor(pred,y.2,method = "pearson") c(l, c, n, g, corr_pred) })) output <- matrix(unlist(salida), ncol = 5, byrow = TRUE) mejoresModelos<-output[order(output[,5], decreasing = TRUE),] return(mejoresModelos) } plot.signal <- function(datos, retardos_multi, mejoresModelos, i){ Ts=0.2 inverseStep=matrix(1,180/Ts,1) inverseStep[(90/Ts):(180/Ts),1]=0 if(i == 0){ for (i in 1:length(mejoresModelos[,1])){ lag<-list(PAMn = mejoresModelos[i,1],VFSCn = 0) signal.train <- retardos_multi(datos, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn mejorModelo <- svm(x, y, kernel = "radial",type = "nu-regression", cost = mejoresModelos[i,2], nu = mejoresModelos[i,3], gamma=mejoresModelos[i,4]) #PAMn=inverseStep #VFSCn=inverseStep ##################PRUEBA CON LOS ESCALONES data.esc = read.table("esc.txt") PAMn = matrix(data.esc$V1) VFSCn = matrix(1,length(PAMn),1) ############# data <- data.frame(PAMn,VFSCn) signal.train <- retardos_multi(data, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn stepTime=seq(Ts,(length(retDataset1$PAMn))*Ts,Ts) stepResponse <- predict(mejorModelo, x ) plot(stepTime,retDataset1$PAMn,type="l", col="red") lines(stepTime,stepResponse, col = "blue") legend("topright", c("Escalon de presión", "respuesta al escalon", paste("i = ",i)), title = "autorregulacion", pch = 1, col=c("red","blue"),lty=c(1,1),inset = 0.01) print(paste("corr=",mejoresModelos[i,5])) readline(prompt="Press [enter] to continue") } }else if(i > 0){ lag<-list(PAMn = mejoresModelos[i,1],VFSCn = 0) signal.train <- retardos_multi(datos, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn mejorModelo <- svm(x, y, kernel = "radial",type = "nu-regression", cost = mejoresModelos[i,2], nu = mejoresModelos[i,3], gamma=mejoresModelos[i,4]) #PAMn=inverseStep #VFSCn=inverseStep ##################PRUEBA CON LOS ESCALONES data.esc = read.table("esc.txt") PAMn = matrix(data.esc$V1) VFSCn = matrix(1,length(PAMn),1) ############# data <- data.frame(PAMn,VFSCn) signal.train <- retardos_multi(data, lag) retDataset1=signal.train$folded.signal x=subset(retDataset1, select = -VFSCn) y=retDataset1$VFSCn stepTime=seq(Ts,(length(retDataset1$PAMn))*Ts,Ts) stepResponse <- predict(mejorModelo, x ) data.escalon <- data.frame(Time = stepTime, PAM = retDataset1$PAMn, z = stepResponse) p <- plot_ly(data.escalon, x = ~Time, y = ~PAM, name = 'Escalon de presión', type = 'scatter', mode = 'lines') %>% add_trace(y = ~z, name = 'respuesta al escalon', mode = 'lines') p } } cost <- 2^(-4:12) nu <- seq(0.1, 1.0, 0.1) gamma<- 2^(-4:12) lagsList<-(1:8) Dataset1=read.csv("G5_002.csv") set.seed(100) trainingRows <- sample(1:nrow(Dataset1), 0.5*nrow(Dataset1)) A <- Dataset1[trainingRows, ] B <- Dataset1[-trainingRows, ] data.1 <- data.frame(PAMn = (A$PAM-min(A$PAM))/(max(A$PAM)-min(A$PAM)),VFSCn = (A$VFSC-min(A$VFSC))/(max(A$VFSC)-min(A$VFSC))) data.2 <- data.frame(PAMn = (B$PAM-min(B$PAM))/(max(B$PAM)-min(B$PAM)),VFSCn = (B$VFSC-min(B$VFSC))/(max(B$VFSC)-min(B$VFSC))) parms <- expand.grid(lagsList=lagsList, cost = cost, nu = nu, gamma=gamma) mejoresModelos.1 <- entrenar(data.1, data.2, parms, retardos_multi) mejoresModelos.2 <- entrenar(data.2, data.1, parms, retardos_multi) write.xlsx(data.frame(LagList = mejoresModelos.1[,1], Cost = mejoresModelos.1[,2], Nu = mejoresModelos.1[,3], Gamma = mejoresModelos.1[,4], Correlacion = mejoresModelos.1[,5]), "mejoresModelos_1.xlsx", sheetName="Sheet1", append = FALSE) write.xlsx(data.frame(LagList = mejoresModelos.2[,1], Cost = mejoresModelos.2[,2], Nu = mejoresModelos.2[,3], Gamma = mejoresModelos.2[,4], Correlacion = mejoresModelos.2[,5]), "mejoresModelos_2.xlsx", sheetName="Sheet1", append = FALSE) ############################CORRER HASTA ESTA LINEA mm1=read.csv("mm1.csv") mm1 <- as.matrix(setNames(mm1,NULL)) #sano mm2=read.csv("mm2.csv") mm2 <- as.matrix(setNames(mm2,NULL)) #Enfermo ######### Eleccion de modelos. Si el ultimo parametro es 0, se veran todos los modelos generados. Si el parametro es mayor a 0 se visualizara el modelo ingresado plot.signal(data.1, retardos_multi, mm1, 85)#17-21-25(mejor)-39-40(mejor)-44(mejor)-56-59-85(mejor) plot.signal(data.2, retardos_multi, mm2, 22)#4-8-22(mejor) ####################GRAFICA SEÑAL Dataset1=read.csv("G5_002.csv") largo.d1 = length(Dataset1$PAM) Dataset2=read.csv("G6_001.csv")[1:largo.d1,] largo.d2 = length(Dataset2$PAM) data.escalon <- data.frame(Time = c(1:largo.d2), PAM = Dataset1$PAM, PAM_Sujeto_2 = Dataset2$PAM) p <- plot_ly(data.escalon, x = ~Time, y = ~PAM, name = 'PAM Sujeto 1', type = 'scatter', mode = 'lines') %>% add_trace(y = ~PAM_Sujeto_2, name = 'PAM Sujeto 2', mode = 'lines') p data.escalon <- data.frame(Time = c(1:largo.d2), VFSC_Sujeto_1 = Dataset1$VFSC, VFSC_Sujeto_2 = Dataset2$VFSC) p <- plot_ly(data.escalon, x = ~Time, y = ~VFSC_Sujeto_1, name = 'VFSC Sujeto 1', type = 'scatter', mode = 'lines') %>% add_trace(y = ~VFSC_Sujeto_2, name = 'VFSC Sujeto 2', mode = 'lines') p >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep><<<<<<< HEAD <<<<<<< HEAD install.packages('lime', dep = TRUE) install.packages('maxent', dep = TRUE) install.packages('tm', dep = TRUE) install.packages('SnowballC', dep = TRUE) install.packages('xlsx', dep = TRUE) install.packages('wordcloud', dep = TRUE) rm(list=ls(all=TRUE)) library(lime) library(maxent) library(tm) library(SnowballC) library(xlsx) library(wordcloud) data(train_sentences) data(test_sentences) train_corpus <- Corpus(VectorSource(train_sentences$text)) test_corpus <- Corpus(VectorSource(test_sentences$text)) for (i in 1:10) print (train_corpus[[i]]$content) #Remover Puntuación xx train_corpus <- tm_map(train_corpus, content_transformer(removePunctuation)) test_corpus <- tm_map(test_corpus, content_transformer(removePunctuation)) #Remover Stop Words xx train_corpus <- tm_map(train_corpus, content_transformer(removeWords), stopwords("english")) test_corpus <- tm_map(test_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case xx train_corpus <- tm_map(train_corpus, content_transformer(tolower)) train_corpus <- tm_map(train_corpus, content_transformer(removeWords), stopwords("english")) test_corpus <- tm_map(test_corpus, content_transformer(tolower)) test_corpus <- tm_map(test_corpus, content_transformer(removeWords), stopwords("english")) #Stremming xx train_corpus <- tm_map(train_corpus, stemDocument) test_corpus <- tm_map(test_corpus, stemDocument) #Remover White Space xx train_corpus <- tm_map(train_corpus, stripWhitespace) test_corpus <- tm_map(test_corpus, stripWhitespace) #Remover Números xx train_corpus <- tm_map(train_corpus, content_transformer(removeNumbers)) test_corpus <- tm_map(test_corpus, content_transformer(removeNumbers)) train_matrix <- DocumentTermMatrix(train_corpus) test_matrix <- DocumentTermMatrix(test_corpus) train_sparse <- as.compressed.matrix(train_matrix) test_sparse <- as.compressed.matrix(test_matrix) f <- tune.maxent(train_sparse,train_sentences$class.text,nfold=3,showall=TRUE, verbose=TRUE) print(f) model<-maxent(train_sparse,train_sentences$class.text, l1_regularizer=0.0, l2_regularizer=0.8, use_sgd=FALSE, set_heldout=0, verbose=TRUE) results <- predict(model,test_sparse) out = matrix(, nrow = length(results[,1]), ncol = 2) for(i in 1:length(results[,1])){ value <- results[i,2] mejorJ <- 2 for(j in 3:16){ if(value > results[i,j]){ #results[i,j] <- FALSE }else{ value <- results[i,j] mejorJ <- j #results[i,2] <- FALSE } } out[i, 1] <- results[i,1] if(results[i,1] == substr(names(results[i,mejorJ]), 1, 4)){ out[i, 2] <- 1 }else{ out[i, 2] <- 0 } #results[i,mejorJ] <- TRUE } out_charts_correcto = matrix(unique(substr(names(results[1,])[2:16], 1, 4)),, nrow = length(unique(substr(names(results[1,])[2:16], 1, 4))), ncol = 2) out_charts_noCorrecto = matrix(unique(substr(names(results[1,])[2:16], 1, 4)),, nrow = length(unique(substr(names(results[1,])[2:16], 1, 4))), ncol = 2) out_charts_correcto[,2] <- 0 out_charts_noCorrecto[,2] <- 0 cantDatosCorrectos = 0 cantDatosIncorrectos = 0 for(i in 1:length(out_charts_correcto[,1])){ cantUnos = 0 cantCeros = 0 for(j in 1:length(results[,1])){ if(substr(out_charts_correcto[i,1], 1, 4) == substr(out[j,1], 1, 4) && out[j,2] == 1){ cantUnos = cantUnos + 1 out_charts_correcto[i, 2] <- cantUnos }else if(substr(out_charts_correcto[i,1], 1, 4) == substr(out[j,1], 1, 4) && out[j,2] == 0){ cantCeros = cantCeros + 1 out_charts_noCorrecto[i, 2] <- cantCeros } } cantDatosCorrectos <- cantDatosCorrectos + as.numeric(out_charts_correcto[i, 2]) cantDatosIncorrectos <- cantDatosIncorrectos + as.numeric(out_charts_noCorrecto[i, 2]) } out_charts_noCorrecto[1:5,] out_charts_correcto[1:5,] ##grafico de distribucion de etiquetas - TRAIN distribucion_etiquetas_train <- matrix(names(results[1,])[2:6],, nrow = length(names(results[1,])[2:6]), ncol = 2) distribucion_etiquetas_train[,2] <- 0 for(i in 1:length(distribucion_etiquetas_train[,1])){ for(j in 1:length(train_sentences$class.text)){ if(distribucion_etiquetas_train[i,1] == substr(train_sentences$class.text[j], 1, 4)){ distribucion_etiquetas_train[i,2] = as.numeric(distribucion_etiquetas_train[i,2]) + 1 } } } barplot(as.numeric(distribucion_etiquetas_train[1:5,2]), main=paste("Distribución Train", toString(length(train_sentences$class.text)), sep=" - "), xlab="Etiquetas",names.arg = distribucion_etiquetas_train[1:5,1]) ##grafico de distribucion de etiquetas - TEST distribucion_etiquetas_test = matrix(names(results[1,])[2:6],, nrow = length(names(results[1,])[2:6]), ncol = 2) distribucion_etiquetas_test[,2] <- 0 for(i in 1:length(results[1:5,1])){ distribucion_etiquetas_test[i,2] <- as.numeric(out_charts_correcto[i,2]) + as.numeric(out_charts_noCorrecto[i,2]) } barplot(as.numeric(distribucion_etiquetas_test[1:5,2]), main=paste("Distribución Test", toString(length(test_sentences$class.text)), sep=" - "), xlab="Etiquetas",names.arg = distribucion_etiquetas_test[1:5,1]) ##grafico de frecuencia de palabras por etiqueta etiquetas <- c("OWNX", "MISC", "CONT", "AIMX", "BASE") n_Text = 1 #_--------------OWNX m_OWNX = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[1]){ m_OWNX[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } OWNX_corpus <- Corpus(VectorSource(m_OWNX)) #Remover Puntuación OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removePunctuation)) #Remover Stop Words OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(tolower)) OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removeWords), stopwords("english")) #Stremming OWNX_corpus <- tm_map(OWNX_corpus, stemDocument) #Remover White Space OWNX_corpus <- tm_map(OWNX_corpus, stripWhitespace) #Remover Números OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removeNumbers)) tdm_OWNX <- TermDocumentMatrix(OWNX_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_OWNX) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------MISC m_MISC = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[2]){ m_MISC[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } MISC_corpus <- Corpus(VectorSource(m_MISC)) #Remover Puntuación MISC_corpus <- tm_map(MISC_corpus, content_transformer(removePunctuation)) #Remover Stop Words MISC_corpus <- tm_map(MISC_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case MISC_corpus <- tm_map(MISC_corpus, content_transformer(tolower)) MISC_corpus <- tm_map(MISC_corpus, content_transformer(removeWords), stopwords("english")) #Stremming MISC_corpus <- tm_map(MISC_corpus, stemDocument) #Remover White Space MISC_corpus <- tm_map(MISC_corpus, stripWhitespace) #Remover Números MISC_corpus <- tm_map(MISC_corpus, content_transformer(removeNumbers)) tdm_MISC <- TermDocumentMatrix(MISC_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_MISC) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------CONT m_CONT = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[3]){ m_CONT[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } CONT_corpus <- Corpus(VectorSource(m_CONT)) #Remover Puntuación CONT_corpus <- tm_map(CONT_corpus, content_transformer(removePunctuation)) #Remover Stop Words CONT_corpus <- tm_map(CONT_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case CONT_corpus <- tm_map(CONT_corpus, content_transformer(tolower)) CONT_corpus <- tm_map(CONT_corpus, content_transformer(removeWords), stopwords("english")) #Stremming CONT_corpus <- tm_map(CONT_corpus, stemDocument) #Remover White Space CONT_corpus <- tm_map(CONT_corpus, stripWhitespace) #Remover Números CONT_corpus <- tm_map(CONT_corpus, content_transformer(removeNumbers)) tdm_CONT <- TermDocumentMatrix(CONT_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_CONT) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------AIMX m_AIMX = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[4]){ m_AIMX[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } AIMX_corpus <- Corpus(VectorSource(m_AIMX)) #Remover Puntuación AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removePunctuation)) #Remover Stop Words AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(tolower)) AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removeWords), stopwords("english")) #Stremming AIMX_corpus <- tm_map(AIMX_corpus, stemDocument) #Remover White Space AIMX_corpus <- tm_map(AIMX_corpus, stripWhitespace) #Remover Números AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removeNumbers)) tdm_AIMX <- TermDocumentMatrix(AIMX_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_AIMX) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------BASE m_BASE = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[5]){ m_BASE[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } BASE_corpus <- Corpus(VectorSource(m_BASE)) #Remover Puntuación BASE_corpus <- tm_map(BASE_corpus, content_transformer(removePunctuation)) #Remover Stop Words BASE_corpus <- tm_map(BASE_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case BASE_corpus <- tm_map(BASE_corpus, content_transformer(tolower)) BASE_corpus <- tm_map(BASE_corpus, content_transformer(removeWords), stopwords("english")) #Stremming BASE_corpus <- tm_map(BASE_corpus, stemDocument) #Remover White Space BASE_corpus <- tm_map(BASE_corpus, stripWhitespace) #Remover Números BASE_corpus <- tm_map(BASE_corpus, content_transformer(removeNumbers)) tdm_BASE <- TermDocumentMatrix(BASE_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_BASE) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) #################### ################## ##grafico de torta Incorectos pie(as.numeric(out_charts_noCorrecto[1:5,2]), labels = out_charts_noCorrecto[1:5,2], main=paste("Pie Chart Predicción Incorrecta", toString(cantDatosIncorrectos), sep=" - "),col = rainbow(length(out_charts_noCorrecto[1:5,1]))) legend("topright", out_charts_noCorrecto[1:5,1], cex = 0.8, fill = rainbow(length(out_charts_noCorrecto[1:5,1]))) ##grafio de lineas entre correctos e incorrectos plot(as.numeric(out_charts_correcto[1:5,2]),type = "o",col = "blue", xlab = "Etiquetas", ylab = "Cantidad Predicciones", main = "Clasificación") lines(out_charts_noCorrecto[1:5,2], type = "o", col = "red") legend("topright", out_charts_correcto[1:5,1], cex = 0.8) ##grafico de barra entre correctos e incorrectos set.union <- function(a, b) { u <- a for (i in 1:length(b)) { u <- append(u, b[i]) } return(u) } Values <- matrix(set.union(as.numeric(out_charts_correcto[1:5,2]), as.numeric(out_charts_noCorrecto[1:5,2])),nrow = 2,ncol = 5,byrow = TRUE) colors <- c("green","red") et <- c(paste("Correctas", toString(cantDatosCorrectos), sep=" "),paste("Incorrectos", toString(cantDatosIncorrectos), sep=" ")) barplot(Values, main="Predicción", ylab="Número de Predicciones",names.arg = out_charts_correcto[1:5,1], xlab = "Etiquetas",col = colors) legend("topright", et, cex = 1.3, fill = colors) ############# MATRIZ DE CONFUCION Labels <- c("MISC", "OWNX", "AIMX", "BASE", "CONT"); for(l in 1:length(Labels)){ m_confucion = matrix(nrow = 3, ncol = 3) m_confucion[,] <- 0 m_confucion[1,1] <- "" m_confucion[1,2] <- "Relevantes" m_confucion[1,3] <- "No Relevantes" m_confucion[2,1] <- "Recuperados" m_confucion[3,1] <- "No Recuperados" #Recuperados for(i in 1:length(out_charts_correcto[1:5,1])){ #Relevante# if(out_charts_correcto[i,1] == Labels[l]){ if(as.numeric(out_charts_correcto[i,2])>0){ #Verdadero Positivo m_confucion[2,2] <- as.numeric(m_confucion[2,2]) + as.numeric(out_charts_correcto[i,2]) } }else{ #No Relevante# if(as.numeric(out_charts_correcto[i,2])>0){ #Falso Positivo m_confucion[2,3] <- as.numeric(m_confucion[2,3]) + as.numeric(out_charts_correcto[i,2]) } } } #No Recuperados for(i in 1:length(out_charts_noCorrecto[1:5,1])){ #Relevante# if(out_charts_noCorrecto[i,1] == Labels[l]){ if(as.numeric(out_charts_noCorrecto[i,2])>0){ #Falso Negativo m_confucion[3,2] <- as.numeric(m_confucion[3,2]) + as.numeric(out_charts_noCorrecto[i,2]) } }else{ #No Relevante# if(as.numeric(out_charts_noCorrecto[i,2])>0){ #Verdadero Negativo m_confucion[3,3] <- as.numeric(m_confucion[3,3]) + as.numeric(out_charts_noCorrecto[i,2]) } } } print(Labels[l]) print(m_confucion) #Precision Precision <- as.numeric(m_confucion[2,2])/(as.numeric(m_confucion[2,2]) + as.numeric(m_confucion[2,3])) #Recall Recall <- as.numeric(m_confucion[2,2])/(as.numeric(m_confucion[2,2]) + as.numeric(m_confucion[3,2])) ##Fscore Fscore = (2*Precision*Recall)/(Precision+Recall) print("Fscore") print(Fscore) print("Precision") print(Precision) print("Recall") print(Recall) print("-----------------------------------------"); } ########################################################### ##Grafico Resultados Fscore fScore <- c(0.0685155,0.06896552,0.096,0.07830343,0.09888357, 0.09888357, 0.1032258, 0.08064516) Etiquetas <- c("1- Sin Pre-Pro", "2- Remover Puntuación", "3- Remover Stop Words","4- To Lower Case","5- Stremming","6- Remover White Space","7- Remover Números", "8- Sin To Lower Case") plot(fScore,type = "o", col = "red", xlab = "Procesamiento", ylab = "Fscore", main = "Procesamiento") legend("bottomright", Etiquetas, cex = 0.8) setwd("C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\Trabajos\\5") write.xlsx(as.data.frame(results), "Prediccion.xlsx", sheetName="Sheet1") ##Grafico de Lineas Nuevo library(plotly) MISC <- c(0.7673216, 0.7983952, 0.7549531, 0.7431579, 0.7214514, 0.7241747, 0.7983952) OWNX <- c(0.3541076, 0.3239437, 0.4717949, 0.498094, 0.4627451, 0.4728682, 0.3638889) AIMX <- c(0.1855346, 0.17737, 0.06168831, 0.05280528, 0.1064516, 0.09983897, 0.08780488) BASE <- c(0.003460208, 0.01666667, 0.01666667, 0.01013514, 0.02356902, 0.02013423, 0.03672788) CONT <- c(0.07023411, 0.06188925, 0.08064516, 0.06885246, 0.1033926, 0.09677419, 0.06896552) x <- c(1:7) data <- data.frame(x, MISC, OWNX, AIMX, BASE, CONT) p <- plot_ly(data, x = ~x, y = ~MISC, name = 'MISC', type = 'scatter', mode = 'lines+markers') %>% add_trace(y = ~OWNX, name = 'OWNX', mode = 'lines+markers') %>% add_trace(y = ~AIMX, name = 'AIMX', mode = 'lines+markers') %>% add_trace(y = ~BASE, name = 'BASE', mode = 'lines+markers') %>% add_trace(y = ~CONT, name = 'CONT', mode = 'lines+markers') %>% layout(title = "Fscore Segun Pre-Procesamiento", xaxis = list(title = "Pre-Procesamiento"), yaxis = list (title = "Fscore")) p ## 7 - Remover Números [1] "MISC" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "398" "190" [3,] "No Recuperados" "11" "1" [1] "Fscore" [1] 0.7983952 [1] "Precision" [1] 0.6768707 [1] "Recall" [1] 0.9731051 [1] "-----------------------------------------" [1] "OWNX" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "131" "457" [3,] "No Recuperados" "1" "11" [1] "Fscore" [1] 0.3638889 [1] "Precision" [1] 0.2227891 [1] "Recall" [1] 0.9924242 [1] "-----------------------------------------" [1] "AIMX" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "27" "561" [3,] "No Recuperados" "0" "12" [1] "Fscore" [1] 0.08780488 [1] "Precision" [1] 0.04591837 [1] "Recall" [1] 1 [1] "-----------------------------------------" [1] "BASE" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "11" "577" [3,] "No Recuperados" "0" "12" [1] "Fscore" [1] 0.03672788 [1] "Precision" [1] 0.01870748 [1] "Recall" [1] 1 [1] "-----------------------------------------" [1] "CONT" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "21" "567" [3,] "No Recuperados" "0" "12" [1] "Fscore" [1] 0.06896552 [1] "Precision" [1] 0.03571429 [1] "Recall" [1] 1 [1] "-----------------------------------------" ======= install.packages('lime', dep = TRUE) install.packages('maxent', dep = TRUE) install.packages('tm', dep = TRUE) install.packages('SnowballC', dep = TRUE) install.packages('xlsx', dep = TRUE) install.packages('wordcloud', dep = TRUE) rm(list=ls(all=TRUE)) library(lime) library(maxent) library(tm) library(SnowballC) library(xlsx) library(wordcloud) data(train_sentences) data(test_sentences) train_corpus <- Corpus(VectorSource(train_sentences$text)) test_corpus <- Corpus(VectorSource(test_sentences$text)) for (i in 1:10) print (train_corpus[[i]]$content) #Remover Puntuación xx train_corpus <- tm_map(train_corpus, content_transformer(removePunctuation)) test_corpus <- tm_map(test_corpus, content_transformer(removePunctuation)) #Remover Stop Words xx train_corpus <- tm_map(train_corpus, content_transformer(removeWords), stopwords("english")) test_corpus <- tm_map(test_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case xx train_corpus <- tm_map(train_corpus, content_transformer(tolower)) train_corpus <- tm_map(train_corpus, content_transformer(removeWords), stopwords("english")) test_corpus <- tm_map(test_corpus, content_transformer(tolower)) test_corpus <- tm_map(test_corpus, content_transformer(removeWords), stopwords("english")) #Stremming xx train_corpus <- tm_map(train_corpus, stemDocument) test_corpus <- tm_map(test_corpus, stemDocument) #Remover White Space xx train_corpus <- tm_map(train_corpus, stripWhitespace) test_corpus <- tm_map(test_corpus, stripWhitespace) #Remover Números xx train_corpus <- tm_map(train_corpus, content_transformer(removeNumbers)) test_corpus <- tm_map(test_corpus, content_transformer(removeNumbers)) train_matrix <- DocumentTermMatrix(train_corpus) test_matrix <- DocumentTermMatrix(test_corpus) train_sparse <- as.compressed.matrix(train_matrix) test_sparse <- as.compressed.matrix(test_matrix) f <- tune.maxent(train_sparse,train_sentences$class.text,nfold=3,showall=TRUE, verbose=TRUE) print(f) model<-maxent(train_sparse,train_sentences$class.text, l1_regularizer=0.0, l2_regularizer=0.8, use_sgd=FALSE, set_heldout=0, verbose=TRUE) results <- predict(model,test_sparse) out = matrix(, nrow = length(results[,1]), ncol = 2) for(i in 1:length(results[,1])){ value <- results[i,2] mejorJ <- 2 for(j in 3:16){ if(value > results[i,j]){ #results[i,j] <- FALSE }else{ value <- results[i,j] mejorJ <- j #results[i,2] <- FALSE } } out[i, 1] <- results[i,1] if(results[i,1] == substr(names(results[i,mejorJ]), 1, 4)){ out[i, 2] <- 1 }else{ out[i, 2] <- 0 } #results[i,mejorJ] <- TRUE } out_charts_correcto = matrix(unique(substr(names(results[1,])[2:16], 1, 4)),, nrow = length(unique(substr(names(results[1,])[2:16], 1, 4))), ncol = 2) out_charts_noCorrecto = matrix(unique(substr(names(results[1,])[2:16], 1, 4)),, nrow = length(unique(substr(names(results[1,])[2:16], 1, 4))), ncol = 2) out_charts_correcto[,2] <- 0 out_charts_noCorrecto[,2] <- 0 cantDatosCorrectos = 0 cantDatosIncorrectos = 0 for(i in 1:length(out_charts_correcto[,1])){ cantUnos = 0 cantCeros = 0 for(j in 1:length(results[,1])){ if(substr(out_charts_correcto[i,1], 1, 4) == substr(out[j,1], 1, 4) && out[j,2] == 1){ cantUnos = cantUnos + 1 out_charts_correcto[i, 2] <- cantUnos }else if(substr(out_charts_correcto[i,1], 1, 4) == substr(out[j,1], 1, 4) && out[j,2] == 0){ cantCeros = cantCeros + 1 out_charts_noCorrecto[i, 2] <- cantCeros } } cantDatosCorrectos <- cantDatosCorrectos + as.numeric(out_charts_correcto[i, 2]) cantDatosIncorrectos <- cantDatosIncorrectos + as.numeric(out_charts_noCorrecto[i, 2]) } out_charts_noCorrecto[1:5,] out_charts_correcto[1:5,] ##grafico de distribucion de etiquetas - TRAIN distribucion_etiquetas_train <- matrix(names(results[1,])[2:6],, nrow = length(names(results[1,])[2:6]), ncol = 2) distribucion_etiquetas_train[,2] <- 0 for(i in 1:length(distribucion_etiquetas_train[,1])){ for(j in 1:length(train_sentences$class.text)){ if(distribucion_etiquetas_train[i,1] == substr(train_sentences$class.text[j], 1, 4)){ distribucion_etiquetas_train[i,2] = as.numeric(distribucion_etiquetas_train[i,2]) + 1 } } } barplot(as.numeric(distribucion_etiquetas_train[1:5,2]), main=paste("Distribución Train", toString(length(train_sentences$class.text)), sep=" - "), xlab="Etiquetas",names.arg = distribucion_etiquetas_train[1:5,1]) ##grafico de distribucion de etiquetas - TEST distribucion_etiquetas_test = matrix(names(results[1,])[2:6],, nrow = length(names(results[1,])[2:6]), ncol = 2) distribucion_etiquetas_test[,2] <- 0 for(i in 1:length(results[1:5,1])){ distribucion_etiquetas_test[i,2] <- as.numeric(out_charts_correcto[i,2]) + as.numeric(out_charts_noCorrecto[i,2]) } barplot(as.numeric(distribucion_etiquetas_test[1:5,2]), main=paste("Distribución Test", toString(length(test_sentences$class.text)), sep=" - "), xlab="Etiquetas",names.arg = distribucion_etiquetas_test[1:5,1]) ##grafico de frecuencia de palabras por etiqueta etiquetas <- c("OWNX", "MISC", "CONT", "AIMX", "BASE") n_Text = 1 #_--------------OWNX m_OWNX = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[1]){ m_OWNX[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } OWNX_corpus <- Corpus(VectorSource(m_OWNX)) #Remover Puntuación OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removePunctuation)) #Remover Stop Words OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(tolower)) OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removeWords), stopwords("english")) #Stremming OWNX_corpus <- tm_map(OWNX_corpus, stemDocument) #Remover White Space OWNX_corpus <- tm_map(OWNX_corpus, stripWhitespace) #Remover Números OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removeNumbers)) tdm_OWNX <- TermDocumentMatrix(OWNX_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_OWNX) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------MISC m_MISC = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[2]){ m_MISC[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } MISC_corpus <- Corpus(VectorSource(m_MISC)) #Remover Puntuación MISC_corpus <- tm_map(MISC_corpus, content_transformer(removePunctuation)) #Remover Stop Words MISC_corpus <- tm_map(MISC_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case MISC_corpus <- tm_map(MISC_corpus, content_transformer(tolower)) MISC_corpus <- tm_map(MISC_corpus, content_transformer(removeWords), stopwords("english")) #Stremming MISC_corpus <- tm_map(MISC_corpus, stemDocument) #Remover White Space MISC_corpus <- tm_map(MISC_corpus, stripWhitespace) #Remover Números MISC_corpus <- tm_map(MISC_corpus, content_transformer(removeNumbers)) tdm_MISC <- TermDocumentMatrix(MISC_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_MISC) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------CONT m_CONT = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[3]){ m_CONT[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } CONT_corpus <- Corpus(VectorSource(m_CONT)) #Remover Puntuación CONT_corpus <- tm_map(CONT_corpus, content_transformer(removePunctuation)) #Remover Stop Words CONT_corpus <- tm_map(CONT_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case CONT_corpus <- tm_map(CONT_corpus, content_transformer(tolower)) CONT_corpus <- tm_map(CONT_corpus, content_transformer(removeWords), stopwords("english")) #Stremming CONT_corpus <- tm_map(CONT_corpus, stemDocument) #Remover White Space CONT_corpus <- tm_map(CONT_corpus, stripWhitespace) #Remover Números CONT_corpus <- tm_map(CONT_corpus, content_transformer(removeNumbers)) tdm_CONT <- TermDocumentMatrix(CONT_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_CONT) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------AIMX m_AIMX = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[4]){ m_AIMX[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } AIMX_corpus <- Corpus(VectorSource(m_AIMX)) #Remover Puntuación AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removePunctuation)) #Remover Stop Words AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(tolower)) AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removeWords), stopwords("english")) #Stremming AIMX_corpus <- tm_map(AIMX_corpus, stemDocument) #Remover White Space AIMX_corpus <- tm_map(AIMX_corpus, stripWhitespace) #Remover Números AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removeNumbers)) tdm_AIMX <- TermDocumentMatrix(AIMX_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_AIMX) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------BASE m_BASE = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[5]){ m_BASE[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } BASE_corpus <- Corpus(VectorSource(m_BASE)) #Remover Puntuación BASE_corpus <- tm_map(BASE_corpus, content_transformer(removePunctuation)) #Remover Stop Words BASE_corpus <- tm_map(BASE_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case BASE_corpus <- tm_map(BASE_corpus, content_transformer(tolower)) BASE_corpus <- tm_map(BASE_corpus, content_transformer(removeWords), stopwords("english")) #Stremming BASE_corpus <- tm_map(BASE_corpus, stemDocument) #Remover White Space BASE_corpus <- tm_map(BASE_corpus, stripWhitespace) #Remover Números BASE_corpus <- tm_map(BASE_corpus, content_transformer(removeNumbers)) tdm_BASE <- TermDocumentMatrix(BASE_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_BASE) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) #################### ################## ##grafico de torta Incorectos pie(as.numeric(out_charts_noCorrecto[1:5,2]), labels = out_charts_noCorrecto[1:5,2], main=paste("Pie Chart Predicción Incorrecta", toString(cantDatosIncorrectos), sep=" - "),col = rainbow(length(out_charts_noCorrecto[1:5,1]))) legend("topright", out_charts_noCorrecto[1:5,1], cex = 0.8, fill = rainbow(length(out_charts_noCorrecto[1:5,1]))) ##grafio de lineas entre correctos e incorrectos plot(as.numeric(out_charts_correcto[1:5,2]),type = "o",col = "blue", xlab = "Etiquetas", ylab = "Cantidad Predicciones", main = "Clasificación") lines(out_charts_noCorrecto[1:5,2], type = "o", col = "red") legend("topright", out_charts_correcto[1:5,1], cex = 0.8) ##grafico de barra entre correctos e incorrectos set.union <- function(a, b) { u <- a for (i in 1:length(b)) { u <- append(u, b[i]) } return(u) } Values <- matrix(set.union(as.numeric(out_charts_correcto[1:5,2]), as.numeric(out_charts_noCorrecto[1:5,2])),nrow = 2,ncol = 5,byrow = TRUE) colors <- c("green","red") et <- c(paste("Correctas", toString(cantDatosCorrectos), sep=" "),paste("Incorrectos", toString(cantDatosIncorrectos), sep=" ")) barplot(Values, main="Predicción", ylab="Número de Predicciones",names.arg = out_charts_correcto[1:5,1], xlab = "Etiquetas",col = colors) legend("topright", et, cex = 1.3, fill = colors) ############# MATRIZ DE CONFUCION Labels <- c("MISC", "OWNX", "AIMX", "BASE", "CONT"); for(l in 1:length(Labels)){ m_confucion = matrix(nrow = 3, ncol = 3) m_confucion[,] <- 0 m_confucion[1,1] <- "" m_confucion[1,2] <- "Relevantes" m_confucion[1,3] <- "No Relevantes" m_confucion[2,1] <- "Recuperados" m_confucion[3,1] <- "No Recuperados" #Recuperados for(i in 1:length(out_charts_correcto[1:5,1])){ #Relevante# if(out_charts_correcto[i,1] == Labels[l]){ if(as.numeric(out_charts_correcto[i,2])>0){ #Verdadero Positivo m_confucion[2,2] <- as.numeric(m_confucion[2,2]) + as.numeric(out_charts_correcto[i,2]) } }else{ #No Relevante# if(as.numeric(out_charts_correcto[i,2])>0){ #Falso Positivo m_confucion[2,3] <- as.numeric(m_confucion[2,3]) + as.numeric(out_charts_correcto[i,2]) } } } #No Recuperados for(i in 1:length(out_charts_noCorrecto[1:5,1])){ #Relevante# if(out_charts_noCorrecto[i,1] == Labels[l]){ if(as.numeric(out_charts_noCorrecto[i,2])>0){ #Falso Negativo m_confucion[3,2] <- as.numeric(m_confucion[3,2]) + as.numeric(out_charts_noCorrecto[i,2]) } }else{ #No Relevante# if(as.numeric(out_charts_noCorrecto[i,2])>0){ #Verdadero Negativo m_confucion[3,3] <- as.numeric(m_confucion[3,3]) + as.numeric(out_charts_noCorrecto[i,2]) } } } print(Labels[l]) print(m_confucion) #Precision Precision <- as.numeric(m_confucion[2,2])/(as.numeric(m_confucion[2,2]) + as.numeric(m_confucion[2,3])) #Recall Recall <- as.numeric(m_confucion[2,2])/(as.numeric(m_confucion[2,2]) + as.numeric(m_confucion[3,2])) ##Fscore Fscore = (2*Precision*Recall)/(Precision+Recall) print("Fscore") print(Fscore) print("Precision") print(Precision) print("Recall") print(Recall) print("-----------------------------------------"); } ########################################################### ##Grafico Resultados Fscore fScore <- c(0.0685155,0.06896552,0.096,0.07830343,0.09888357, 0.09888357, 0.1032258, 0.08064516) Etiquetas <- c("1- Sin Pre-Pro", "2- Remover Puntuación", "3- Remover Stop Words","4- To Lower Case","5- Stremming","6- Remover White Space","7- Remover Números", "8- Sin To Lower Case") plot(fScore,type = "o", col = "red", xlab = "Procesamiento", ylab = "Fscore", main = "Procesamiento") legend("bottomright", Etiquetas, cex = 0.8) setwd("C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\Trabajos\\5") write.xlsx(as.data.frame(results), "Prediccion.xlsx", sheetName="Sheet1") ##Grafico de Lineas Nuevo library(plotly) MISC <- c(0.7673216, 0.7983952, 0.7549531, 0.7431579, 0.7214514, 0.7241747, 0.7983952) OWNX <- c(0.3541076, 0.3239437, 0.4717949, 0.498094, 0.4627451, 0.4728682, 0.3638889) AIMX <- c(0.1855346, 0.17737, 0.06168831, 0.05280528, 0.1064516, 0.09983897, 0.08780488) BASE <- c(0.003460208, 0.01666667, 0.01666667, 0.01013514, 0.02356902, 0.02013423, 0.03672788) CONT <- c(0.07023411, 0.06188925, 0.08064516, 0.06885246, 0.1033926, 0.09677419, 0.06896552) x <- c(1:7) data <- data.frame(x, MISC, OWNX, AIMX, BASE, CONT) p <- plot_ly(data, x = ~x, y = ~MISC, name = 'MISC', type = 'scatter', mode = 'lines+markers') %>% add_trace(y = ~OWNX, name = 'OWNX', mode = 'lines+markers') %>% add_trace(y = ~AIMX, name = 'AIMX', mode = 'lines+markers') %>% add_trace(y = ~BASE, name = 'BASE', mode = 'lines+markers') %>% add_trace(y = ~CONT, name = 'CONT', mode = 'lines+markers') %>% layout(title = "Fscore Segun Pre-Procesamiento", xaxis = list(title = "Pre-Procesamiento"), yaxis = list (title = "Fscore")) p ## 7 - Remover Números [1] "MISC" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "398" "190" [3,] "No Recuperados" "11" "1" [1] "Fscore" [1] 0.7983952 [1] "Precision" [1] 0.6768707 [1] "Recall" [1] 0.9731051 [1] "-----------------------------------------" [1] "OWNX" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "131" "457" [3,] "No Recuperados" "1" "11" [1] "Fscore" [1] 0.3638889 [1] "Precision" [1] 0.2227891 [1] "Recall" [1] 0.9924242 [1] "-----------------------------------------" [1] "AIMX" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "27" "561" [3,] "No Recuperados" "0" "12" [1] "Fscore" [1] 0.08780488 [1] "Precision" [1] 0.04591837 [1] "Recall" [1] 1 [1] "-----------------------------------------" [1] "BASE" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "11" "577" [3,] "No Recuperados" "0" "12" [1] "Fscore" [1] 0.03672788 [1] "Precision" [1] 0.01870748 [1] "Recall" [1] 1 [1] "-----------------------------------------" [1] "CONT" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "21" "567" [3,] "No Recuperados" "0" "12" [1] "Fscore" [1] 0.06896552 [1] "Precision" [1] 0.03571429 [1] "Recall" [1] 1 [1] "-----------------------------------------" >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= install.packages('lime', dep = TRUE) install.packages('maxent', dep = TRUE) install.packages('tm', dep = TRUE) install.packages('SnowballC', dep = TRUE) install.packages('xlsx', dep = TRUE) install.packages('wordcloud', dep = TRUE) rm(list=ls(all=TRUE)) library(lime) library(maxent) library(tm) library(SnowballC) library(xlsx) library(wordcloud) data(train_sentences) data(test_sentences) train_corpus <- Corpus(VectorSource(train_sentences$text)) test_corpus <- Corpus(VectorSource(test_sentences$text)) for (i in 1:10) print (train_corpus[[i]]$content) #Remover Puntuación xx train_corpus <- tm_map(train_corpus, content_transformer(removePunctuation)) test_corpus <- tm_map(test_corpus, content_transformer(removePunctuation)) #Remover Stop Words xx train_corpus <- tm_map(train_corpus, content_transformer(removeWords), stopwords("english")) test_corpus <- tm_map(test_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case xx train_corpus <- tm_map(train_corpus, content_transformer(tolower)) train_corpus <- tm_map(train_corpus, content_transformer(removeWords), stopwords("english")) test_corpus <- tm_map(test_corpus, content_transformer(tolower)) test_corpus <- tm_map(test_corpus, content_transformer(removeWords), stopwords("english")) #Stremming xx train_corpus <- tm_map(train_corpus, stemDocument) test_corpus <- tm_map(test_corpus, stemDocument) #Remover White Space xx train_corpus <- tm_map(train_corpus, stripWhitespace) test_corpus <- tm_map(test_corpus, stripWhitespace) #Remover Números xx train_corpus <- tm_map(train_corpus, content_transformer(removeNumbers)) test_corpus <- tm_map(test_corpus, content_transformer(removeNumbers)) train_matrix <- DocumentTermMatrix(train_corpus) test_matrix <- DocumentTermMatrix(test_corpus) train_sparse <- as.compressed.matrix(train_matrix) test_sparse <- as.compressed.matrix(test_matrix) f <- tune.maxent(train_sparse,train_sentences$class.text,nfold=3,showall=TRUE, verbose=TRUE) print(f) model<-maxent(train_sparse,train_sentences$class.text, l1_regularizer=0.0, l2_regularizer=0.8, use_sgd=FALSE, set_heldout=0, verbose=TRUE) results <- predict(model,test_sparse) out = matrix(, nrow = length(results[,1]), ncol = 2) for(i in 1:length(results[,1])){ value <- results[i,2] mejorJ <- 2 for(j in 3:16){ if(value > results[i,j]){ #results[i,j] <- FALSE }else{ value <- results[i,j] mejorJ <- j #results[i,2] <- FALSE } } out[i, 1] <- results[i,1] if(results[i,1] == substr(names(results[i,mejorJ]), 1, 4)){ out[i, 2] <- 1 }else{ out[i, 2] <- 0 } #results[i,mejorJ] <- TRUE } out_charts_correcto = matrix(unique(substr(names(results[1,])[2:16], 1, 4)),, nrow = length(unique(substr(names(results[1,])[2:16], 1, 4))), ncol = 2) out_charts_noCorrecto = matrix(unique(substr(names(results[1,])[2:16], 1, 4)),, nrow = length(unique(substr(names(results[1,])[2:16], 1, 4))), ncol = 2) out_charts_correcto[,2] <- 0 out_charts_noCorrecto[,2] <- 0 cantDatosCorrectos = 0 cantDatosIncorrectos = 0 for(i in 1:length(out_charts_correcto[,1])){ cantUnos = 0 cantCeros = 0 for(j in 1:length(results[,1])){ if(substr(out_charts_correcto[i,1], 1, 4) == substr(out[j,1], 1, 4) && out[j,2] == 1){ cantUnos = cantUnos + 1 out_charts_correcto[i, 2] <- cantUnos }else if(substr(out_charts_correcto[i,1], 1, 4) == substr(out[j,1], 1, 4) && out[j,2] == 0){ cantCeros = cantCeros + 1 out_charts_noCorrecto[i, 2] <- cantCeros } } cantDatosCorrectos <- cantDatosCorrectos + as.numeric(out_charts_correcto[i, 2]) cantDatosIncorrectos <- cantDatosIncorrectos + as.numeric(out_charts_noCorrecto[i, 2]) } out_charts_noCorrecto[1:5,] out_charts_correcto[1:5,] ##grafico de distribucion de etiquetas - TRAIN distribucion_etiquetas_train <- matrix(names(results[1,])[2:6],, nrow = length(names(results[1,])[2:6]), ncol = 2) distribucion_etiquetas_train[,2] <- 0 for(i in 1:length(distribucion_etiquetas_train[,1])){ for(j in 1:length(train_sentences$class.text)){ if(distribucion_etiquetas_train[i,1] == substr(train_sentences$class.text[j], 1, 4)){ distribucion_etiquetas_train[i,2] = as.numeric(distribucion_etiquetas_train[i,2]) + 1 } } } barplot(as.numeric(distribucion_etiquetas_train[1:5,2]), main=paste("Distribución Train", toString(length(train_sentences$class.text)), sep=" - "), xlab="Etiquetas",names.arg = distribucion_etiquetas_train[1:5,1]) ##grafico de distribucion de etiquetas - TEST distribucion_etiquetas_test = matrix(names(results[1,])[2:6],, nrow = length(names(results[1,])[2:6]), ncol = 2) distribucion_etiquetas_test[,2] <- 0 for(i in 1:length(results[1:5,1])){ distribucion_etiquetas_test[i,2] <- as.numeric(out_charts_correcto[i,2]) + as.numeric(out_charts_noCorrecto[i,2]) } barplot(as.numeric(distribucion_etiquetas_test[1:5,2]), main=paste("Distribución Test", toString(length(test_sentences$class.text)), sep=" - "), xlab="Etiquetas",names.arg = distribucion_etiquetas_test[1:5,1]) ##grafico de frecuencia de palabras por etiqueta etiquetas <- c("OWNX", "MISC", "CONT", "AIMX", "BASE") n_Text = 1 #_--------------OWNX m_OWNX = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[1]){ m_OWNX[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } OWNX_corpus <- Corpus(VectorSource(m_OWNX)) #Remover Puntuación OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removePunctuation)) #Remover Stop Words OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(tolower)) OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removeWords), stopwords("english")) #Stremming OWNX_corpus <- tm_map(OWNX_corpus, stemDocument) #Remover White Space OWNX_corpus <- tm_map(OWNX_corpus, stripWhitespace) #Remover Números OWNX_corpus <- tm_map(OWNX_corpus, content_transformer(removeNumbers)) tdm_OWNX <- TermDocumentMatrix(OWNX_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_OWNX) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------MISC m_MISC = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[2]){ m_MISC[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } MISC_corpus <- Corpus(VectorSource(m_MISC)) #Remover Puntuación MISC_corpus <- tm_map(MISC_corpus, content_transformer(removePunctuation)) #Remover Stop Words MISC_corpus <- tm_map(MISC_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case MISC_corpus <- tm_map(MISC_corpus, content_transformer(tolower)) MISC_corpus <- tm_map(MISC_corpus, content_transformer(removeWords), stopwords("english")) #Stremming MISC_corpus <- tm_map(MISC_corpus, stemDocument) #Remover White Space MISC_corpus <- tm_map(MISC_corpus, stripWhitespace) #Remover Números MISC_corpus <- tm_map(MISC_corpus, content_transformer(removeNumbers)) tdm_MISC <- TermDocumentMatrix(MISC_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_MISC) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------CONT m_CONT = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[3]){ m_CONT[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } CONT_corpus <- Corpus(VectorSource(m_CONT)) #Remover Puntuación CONT_corpus <- tm_map(CONT_corpus, content_transformer(removePunctuation)) #Remover Stop Words CONT_corpus <- tm_map(CONT_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case CONT_corpus <- tm_map(CONT_corpus, content_transformer(tolower)) CONT_corpus <- tm_map(CONT_corpus, content_transformer(removeWords), stopwords("english")) #Stremming CONT_corpus <- tm_map(CONT_corpus, stemDocument) #Remover White Space CONT_corpus <- tm_map(CONT_corpus, stripWhitespace) #Remover Números CONT_corpus <- tm_map(CONT_corpus, content_transformer(removeNumbers)) tdm_CONT <- TermDocumentMatrix(CONT_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_CONT) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------AIMX m_AIMX = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[4]){ m_AIMX[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } AIMX_corpus <- Corpus(VectorSource(m_AIMX)) #Remover Puntuación AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removePunctuation)) #Remover Stop Words AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(tolower)) AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removeWords), stopwords("english")) #Stremming AIMX_corpus <- tm_map(AIMX_corpus, stemDocument) #Remover White Space AIMX_corpus <- tm_map(AIMX_corpus, stripWhitespace) #Remover Números AIMX_corpus <- tm_map(AIMX_corpus, content_transformer(removeNumbers)) tdm_AIMX <- TermDocumentMatrix(AIMX_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_AIMX) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) n_Text = 1 #_--------------BASE m_BASE = matrix() for(i in 1:length(test_sentences$class.text)){ if(substr(test_sentences$class.text[i], 1, 4) == etiquetas[5]){ m_BASE[n_Text] <- test_sentences$text[i] n_Text = n_Text + 1 } } BASE_corpus <- Corpus(VectorSource(m_BASE)) #Remover Puntuación BASE_corpus <- tm_map(BASE_corpus, content_transformer(removePunctuation)) #Remover Stop Words BASE_corpus <- tm_map(BASE_corpus, content_transformer(removeWords), stopwords("english")) #To Lower Case BASE_corpus <- tm_map(BASE_corpus, content_transformer(tolower)) BASE_corpus <- tm_map(BASE_corpus, content_transformer(removeWords), stopwords("english")) #Stremming BASE_corpus <- tm_map(BASE_corpus, stemDocument) #Remover White Space BASE_corpus <- tm_map(BASE_corpus, stripWhitespace) #Remover Números BASE_corpus <- tm_map(BASE_corpus, content_transformer(removeNumbers)) tdm_BASE <- TermDocumentMatrix(BASE_corpus, control = list(wordLengths = c(1, Inf))) m <- as.matrix(tdm_BASE) # calculate the frequency of words and sort it by frequency word.freq <- sort(rowSums(m), decreasing = T) wordcloud(main = "Clasificación", words = names(word.freq), freq = word.freq, min.freq = 3, random.order = F) #################### ################## ##grafico de torta Incorectos pie(as.numeric(out_charts_noCorrecto[1:5,2]), labels = out_charts_noCorrecto[1:5,2], main=paste("Pie Chart Predicción Incorrecta", toString(cantDatosIncorrectos), sep=" - "),col = rainbow(length(out_charts_noCorrecto[1:5,1]))) legend("topright", out_charts_noCorrecto[1:5,1], cex = 0.8, fill = rainbow(length(out_charts_noCorrecto[1:5,1]))) ##grafio de lineas entre correctos e incorrectos plot(as.numeric(out_charts_correcto[1:5,2]),type = "o",col = "blue", xlab = "Etiquetas", ylab = "Cantidad Predicciones", main = "Clasificación") lines(out_charts_noCorrecto[1:5,2], type = "o", col = "red") legend("topright", out_charts_correcto[1:5,1], cex = 0.8) ##grafico de barra entre correctos e incorrectos set.union <- function(a, b) { u <- a for (i in 1:length(b)) { u <- append(u, b[i]) } return(u) } Values <- matrix(set.union(as.numeric(out_charts_correcto[1:5,2]), as.numeric(out_charts_noCorrecto[1:5,2])),nrow = 2,ncol = 5,byrow = TRUE) colors <- c("green","red") et <- c(paste("Correctas", toString(cantDatosCorrectos), sep=" "),paste("Incorrectos", toString(cantDatosIncorrectos), sep=" ")) barplot(Values, main="Predicción", ylab="Número de Predicciones",names.arg = out_charts_correcto[1:5,1], xlab = "Etiquetas",col = colors) legend("topright", et, cex = 1.3, fill = colors) ############# MATRIZ DE CONFUCION Labels <- c("MISC", "OWNX", "AIMX", "BASE", "CONT"); for(l in 1:length(Labels)){ m_confucion = matrix(nrow = 3, ncol = 3) m_confucion[,] <- 0 m_confucion[1,1] <- "" m_confucion[1,2] <- "Relevantes" m_confucion[1,3] <- "No Relevantes" m_confucion[2,1] <- "Recuperados" m_confucion[3,1] <- "No Recuperados" #Recuperados for(i in 1:length(out_charts_correcto[1:5,1])){ #Relevante# if(out_charts_correcto[i,1] == Labels[l]){ if(as.numeric(out_charts_correcto[i,2])>0){ #Verdadero Positivo m_confucion[2,2] <- as.numeric(m_confucion[2,2]) + as.numeric(out_charts_correcto[i,2]) } }else{ #No Relevante# if(as.numeric(out_charts_correcto[i,2])>0){ #Falso Positivo m_confucion[2,3] <- as.numeric(m_confucion[2,3]) + as.numeric(out_charts_correcto[i,2]) } } } #No Recuperados for(i in 1:length(out_charts_noCorrecto[1:5,1])){ #Relevante# if(out_charts_noCorrecto[i,1] == Labels[l]){ if(as.numeric(out_charts_noCorrecto[i,2])>0){ #Falso Negativo m_confucion[3,2] <- as.numeric(m_confucion[3,2]) + as.numeric(out_charts_noCorrecto[i,2]) } }else{ #No Relevante# if(as.numeric(out_charts_noCorrecto[i,2])>0){ #Verdadero Negativo m_confucion[3,3] <- as.numeric(m_confucion[3,3]) + as.numeric(out_charts_noCorrecto[i,2]) } } } print(Labels[l]) print(m_confucion) #Precision Precision <- as.numeric(m_confucion[2,2])/(as.numeric(m_confucion[2,2]) + as.numeric(m_confucion[2,3])) #Recall Recall <- as.numeric(m_confucion[2,2])/(as.numeric(m_confucion[2,2]) + as.numeric(m_confucion[3,2])) ##Fscore Fscore = (2*Precision*Recall)/(Precision+Recall) print("Fscore") print(Fscore) print("Precision") print(Precision) print("Recall") print(Recall) print("-----------------------------------------"); } ########################################################### ##Grafico Resultados Fscore fScore <- c(0.0685155,0.06896552,0.096,0.07830343,0.09888357, 0.09888357, 0.1032258, 0.08064516) Etiquetas <- c("1- Sin Pre-Pro", "2- Remover Puntuación", "3- Remover Stop Words","4- To Lower Case","5- Stremming","6- Remover White Space","7- Remover Números", "8- Sin To Lower Case") plot(fScore,type = "o", col = "red", xlab = "Procesamiento", ylab = "Fscore", main = "Procesamiento") legend("bottomright", Etiquetas, cex = 0.8) setwd("C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\Trabajos\\5") write.xlsx(as.data.frame(results), "Prediccion.xlsx", sheetName="Sheet1") ##Grafico de Lineas Nuevo library(plotly) MISC <- c(0.7673216, 0.7983952, 0.7549531, 0.7431579, 0.7214514, 0.7241747, 0.7983952) OWNX <- c(0.3541076, 0.3239437, 0.4717949, 0.498094, 0.4627451, 0.4728682, 0.3638889) AIMX <- c(0.1855346, 0.17737, 0.06168831, 0.05280528, 0.1064516, 0.09983897, 0.08780488) BASE <- c(0.003460208, 0.01666667, 0.01666667, 0.01013514, 0.02356902, 0.02013423, 0.03672788) CONT <- c(0.07023411, 0.06188925, 0.08064516, 0.06885246, 0.1033926, 0.09677419, 0.06896552) x <- c(1:7) data <- data.frame(x, MISC, OWNX, AIMX, BASE, CONT) p <- plot_ly(data, x = ~x, y = ~MISC, name = 'MISC', type = 'scatter', mode = 'lines+markers') %>% add_trace(y = ~OWNX, name = 'OWNX', mode = 'lines+markers') %>% add_trace(y = ~AIMX, name = 'AIMX', mode = 'lines+markers') %>% add_trace(y = ~BASE, name = 'BASE', mode = 'lines+markers') %>% add_trace(y = ~CONT, name = 'CONT', mode = 'lines+markers') %>% layout(title = "Fscore Segun Pre-Procesamiento", xaxis = list(title = "Pre-Procesamiento"), yaxis = list (title = "Fscore")) p ## 7 - Remover Números [1] "MISC" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "398" "190" [3,] "No Recuperados" "11" "1" [1] "Fscore" [1] 0.7983952 [1] "Precision" [1] 0.6768707 [1] "Recall" [1] 0.9731051 [1] "-----------------------------------------" [1] "OWNX" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "131" "457" [3,] "No Recuperados" "1" "11" [1] "Fscore" [1] 0.3638889 [1] "Precision" [1] 0.2227891 [1] "Recall" [1] 0.9924242 [1] "-----------------------------------------" [1] "AIMX" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "27" "561" [3,] "No Recuperados" "0" "12" [1] "Fscore" [1] 0.08780488 [1] "Precision" [1] 0.04591837 [1] "Recall" [1] 1 [1] "-----------------------------------------" [1] "BASE" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "11" "577" [3,] "No Recuperados" "0" "12" [1] "Fscore" [1] 0.03672788 [1] "Precision" [1] 0.01870748 [1] "Recall" [1] 1 [1] "-----------------------------------------" [1] "CONT" [,1] [,2] [,3] [1,] "" "Relevantes" "No Relevantes" [2,] "Recuperados" "21" "567" [3,] "No Recuperados" "0" "12" [1] "Fscore" [1] 0.06896552 [1] "Precision" [1] 0.03571429 [1] "Recall" [1] 1 [1] "-----------------------------------------" >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep><<<<<<< HEAD <<<<<<< HEAD setwd(choose.dir()) install.packages('cluster', dep = TRUE) library(cluster) install.packages('factoextra', dep = TRUE) library(factoextra) install.packages('FactoMineR', dep = TRUE) library(FactoMineR) install.packages('ggplot2', dep = TRUE) library(ggplot2) data_norm = read.csv("zoo-cluster - class_type.csv") data = read.csv("zoo-cluster - class_type.csv") data_norm["animal_name"] <- NULL #-------------------------------------------------------------- #modelo con 7 clusters #Distancia Hamming data_cluster <- dist(data_norm, method = "binary", diag = FALSE, upper = FALSE, p = 2) data_matrix <- as.matrix(data_cluster) data_kmeans <- pam(data_matrix, 7) data$class_type[data_kmeans$id.med] # centroides con distancia hamming #-------------------------------------------------------------- #Distancia manhattan o euclidea # datos dicotomicos a variables cuantitativas por medio de "multiple correspondence analysis" for (i in 1:ncol(data_norm)) data_norm[,i]=as.factor(data_norm[,i]) mca1 = MCA(data_norm, graph = FALSE) data_matrix <- as.matrix(mca1) #hacer tabla que explique a que especie corresponde cada cluster (para las dos distancias ("hamming" y "manhattan")) data_kmeans <- pam(mca1$ind$cos2, 7, metric = "manhattan") data$class_type[data_kmeans$id.med] #-------------------------------------------------------------- #Desaprobar 7 clusters para clasificar dataset fviz_silhouette(silhouette(data_kmeans)) sil <- silhouette(data_kmeans) # se seleccionan los animales con altas probabilidades de pertenecer a otro cluster neg_sil_index <- which(sil[, 'sil_width'] < 0.2) sil[neg_sil_index, , drop = FALSE] #-------------------------------------------------------------- #modelo con 6 clusters data_cluster <- dist(data_norm, method = "binary", diag = FALSE, upper = FALSE, p = 2) data_matrix <- as.matrix(data_cluster) data_kmeans <- pam(data_matrix, 6)#se ha elegido 6 clusters data$class_type[data_kmeans$id.med] # centroides con distancia hamming data[data_kmeans$id.med,23:29]#informacion centroides #Grafica de siluetas fviz_silhouette(silhouette(data_kmeans)) #Agrupaciones sin nombres fviz_cluster(data_kmeans, stand = FALSE, geom = "point", ellipse.type = "norm", show.clust.cent = TRUE) # Agrupaciones de animales en particular fviz_cluster(data_kmeans, stand = FALSE, data = data_norm, ellipse.type = "norm", show.clust.cent = TRUE) #Graficas de agrupacion y silueta plot(data$class_type, col = data_kmeans$cluster) plot(data[data_kmeans$id.med,23:29], col = data_kmeans$cluster) #Informacion global de clusters summary(data_kmeans) plot(data_kmeans) names(data_kmeans) table(data_kmeans$clustering) #BONUS-Algoritmo jerarquico data = read.csv("zoo-cluster.csv") data_norm["animal_name"] <- NULL data_cluster <- dist(data_norm, method = "manhattan", diag = FALSE, upper = FALSE, p = 2) clusters <- hclust(data_cluster) plot(clusters) clusterCut <- cutree(clusters, 6) # a distancia 0.78 en el dendrograma table(clusterCut, data$class_type) plot(clusterCut, data$class_type) ======= setwd(choose.dir()) install.packages('cluster', dep = TRUE) library(cluster) install.packages('factoextra', dep = TRUE) library(factoextra) install.packages('FactoMineR', dep = TRUE) library(FactoMineR) install.packages('ggplot2', dep = TRUE) library(ggplot2) data_norm = read.csv("zoo-cluster - class_type.csv") data = read.csv("zoo-cluster - class_type.csv") data_norm["animal_name"] <- NULL #-------------------------------------------------------------- #modelo con 7 clusters #Distancia Hamming data_cluster <- dist(data_norm, method = "binary", diag = FALSE, upper = FALSE, p = 2) data_matrix <- as.matrix(data_cluster) data_kmeans <- pam(data_matrix, 7) data$class_type[data_kmeans$id.med] # centroides con distancia hamming #-------------------------------------------------------------- #Distancia manhattan o euclidea # datos dicotomicos a variables cuantitativas por medio de "multiple correspondence analysis" for (i in 1:ncol(data_norm)) data_norm[,i]=as.factor(data_norm[,i]) mca1 = MCA(data_norm, graph = FALSE) data_matrix <- as.matrix(mca1) #hacer tabla que explique a que especie corresponde cada cluster (para las dos distancias ("hamming" y "manhattan")) data_kmeans <- pam(mca1$ind$cos2, 7, metric = "manhattan") data$class_type[data_kmeans$id.med] #-------------------------------------------------------------- #Desaprobar 7 clusters para clasificar dataset fviz_silhouette(silhouette(data_kmeans)) sil <- silhouette(data_kmeans) # se seleccionan los animales con altas probabilidades de pertenecer a otro cluster neg_sil_index <- which(sil[, 'sil_width'] < 0.2) sil[neg_sil_index, , drop = FALSE] #-------------------------------------------------------------- #modelo con 6 clusters data_cluster <- dist(data_norm, method = "binary", diag = FALSE, upper = FALSE, p = 2) data_matrix <- as.matrix(data_cluster) data_kmeans <- pam(data_matrix, 6)#se ha elegido 6 clusters data$class_type[data_kmeans$id.med] # centroides con distancia hamming data[data_kmeans$id.med,23:29]#informacion centroides #Grafica de siluetas fviz_silhouette(silhouette(data_kmeans)) #Agrupaciones sin nombres fviz_cluster(data_kmeans, stand = FALSE, geom = "point", ellipse.type = "norm", show.clust.cent = TRUE) # Agrupaciones de animales en particular fviz_cluster(data_kmeans, stand = FALSE, data = data_norm, ellipse.type = "norm", show.clust.cent = TRUE) #Graficas de agrupacion y silueta plot(data$class_type, col = data_kmeans$cluster) plot(data[data_kmeans$id.med,23:29], col = data_kmeans$cluster) #Informacion global de clusters summary(data_kmeans) plot(data_kmeans) names(data_kmeans) table(data_kmeans$clustering) #BONUS-Algoritmo jerarquico data = read.csv("zoo-cluster.csv") data_norm["animal_name"] <- NULL data_cluster <- dist(data_norm, method = "manhattan", diag = FALSE, upper = FALSE, p = 2) clusters <- hclust(data_cluster) plot(clusters) clusterCut <- cutree(clusters, 6) # a distancia 0.78 en el dendrograma table(clusterCut, data$class_type) plot(clusterCut, data$class_type) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= setwd(choose.dir()) install.packages('cluster', dep = TRUE) library(cluster) install.packages('factoextra', dep = TRUE) library(factoextra) install.packages('FactoMineR', dep = TRUE) library(FactoMineR) install.packages('ggplot2', dep = TRUE) library(ggplot2) data_norm = read.csv("zoo-cluster - class_type.csv") data = read.csv("zoo-cluster - class_type.csv") data_norm["animal_name"] <- NULL #-------------------------------------------------------------- #modelo con 7 clusters #Distancia Hamming data_cluster <- dist(data_norm, method = "binary", diag = FALSE, upper = FALSE, p = 2) data_matrix <- as.matrix(data_cluster) data_kmeans <- pam(data_matrix, 7) data$class_type[data_kmeans$id.med] # centroides con distancia hamming #-------------------------------------------------------------- #Distancia manhattan o euclidea # datos dicotomicos a variables cuantitativas por medio de "multiple correspondence analysis" for (i in 1:ncol(data_norm)) data_norm[,i]=as.factor(data_norm[,i]) mca1 = MCA(data_norm, graph = FALSE) data_matrix <- as.matrix(mca1) #hacer tabla que explique a que especie corresponde cada cluster (para las dos distancias ("hamming" y "manhattan")) data_kmeans <- pam(mca1$ind$cos2, 7, metric = "manhattan") data$class_type[data_kmeans$id.med] #-------------------------------------------------------------- #Desaprobar 7 clusters para clasificar dataset fviz_silhouette(silhouette(data_kmeans)) sil <- silhouette(data_kmeans) # se seleccionan los animales con altas probabilidades de pertenecer a otro cluster neg_sil_index <- which(sil[, 'sil_width'] < 0.2) sil[neg_sil_index, , drop = FALSE] #-------------------------------------------------------------- #modelo con 6 clusters data_cluster <- dist(data_norm, method = "binary", diag = FALSE, upper = FALSE, p = 2) data_matrix <- as.matrix(data_cluster) data_kmeans <- pam(data_matrix, 6)#se ha elegido 6 clusters data$class_type[data_kmeans$id.med] # centroides con distancia hamming data[data_kmeans$id.med,23:29]#informacion centroides #Grafica de siluetas fviz_silhouette(silhouette(data_kmeans)) #Agrupaciones sin nombres fviz_cluster(data_kmeans, stand = FALSE, geom = "point", ellipse.type = "norm", show.clust.cent = TRUE) # Agrupaciones de animales en particular fviz_cluster(data_kmeans, stand = FALSE, data = data_norm, ellipse.type = "norm", show.clust.cent = TRUE) #Graficas de agrupacion y silueta plot(data$class_type, col = data_kmeans$cluster) plot(data[data_kmeans$id.med,23:29], col = data_kmeans$cluster) #Informacion global de clusters summary(data_kmeans) plot(data_kmeans) names(data_kmeans) table(data_kmeans$clustering) #BONUS-Algoritmo jerarquico data = read.csv("zoo-cluster.csv") data_norm["animal_name"] <- NULL data_cluster <- dist(data_norm, method = "manhattan", diag = FALSE, upper = FALSE, p = 2) clusters <- hclust(data_cluster) plot(clusters) clusterCut <- cutree(clusters, 6) # a distancia 0.78 en el dendrograma table(clusterCut, data$class_type) plot(clusterCut, data$class_type) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep> # Change accordingly VERSION <- "v15.9.10" WORK.DIR <- file.path("", "research", "Memoristas", VERSION) CARSIG.SCRIPT.BASENAME <- paste("carSignal", VERSION, sep = "-") CARSIG.SCRIPT.BASENAME <- paste(CARSIG.SCRIPT.BASENAME, "R", sep = ".") CARSIG.SCRIPT.NAME <- file.path(WORK.DIR, CARSIG.SCRIPT.BASENAME) source(CARSIG.SCRIPT.NAME) DARI.SCRIPT.BASENAME <- paste("atARI", VERSION, sep = "-") DARI.SCRIPT.BASENAME <- paste(DARI.SCRIPT.BASENAME, "R", sep = ".") DARI.SCRIPT.NAME <- file.path(WORK.DIR, DARI.SCRIPT.BASENAME) source(DARI.SCRIPT.NAME) METRIC.UTILS.SCRIPT.BASENAME <- paste("Metric", "utils", VERSION, sep = "-") METRIC.UTILS.SCRIPT.BASENAME <- paste(METRIC.UTILS.SCRIPT.BASENAME, "R", sep = ".") METRIC.UTILS.SCRIPT.NAME <- file.path(WORK.DIR, METRIC.UTILS.SCRIPT.BASENAME) source(METRIC.UTILS.SCRIPT.NAME) MFARI.SCRIPT.BASENAME <- paste("mfARI", VERSION, sep = "-") MFARI.SCRIPT.BASENAME <- paste(MFARI.SCRIPT.BASENAME, "R", sep = ".") MFARI.SCRIPT.NAME <- file.path(WORK.DIR, MFARI.SCRIPT.BASENAME) source(MFARI.SCRIPT.NAME) ROUND.UTILS.SCRIPT.BASENAME <- paste("Rounding", "utils", VERSION, sep = "-") ROUND.UTILS.SCRIPT.BASENAME <- paste(ROUND.UTILS.SCRIPT.BASENAME, "R", sep = ".") ROUND.UTILS.SCRIPT.NAME <- file.path(WORK.DIR, ROUND.UTILS.SCRIPT.BASENAME) source(ROUND.UTILS.SCRIPT.NAME) get.normalised.dari.templates <- function( time.instants, normalised.abp.signal, sampling.time, sample.release, baseline.initial.time = time.instants[1], baseline.final.time = time.instants[sample.release], min.cbfv.max.delta.time = 8 * 0.8, stabilisation.time = 30, at.param.rounding.digits = 6, cbfv.rounding.digits = 2, time.tol = sampling.time / 100, ... # Not used ) { at.params <- get.AT.decimal.templates.parameters( rounding.digits = at.param.rounding.digits ) .tmp.fun <- function(i) get.theoretical.CBFV.response( T = at.params[i, 1], D = at.params[i, 2], K = at.params[i, 3], time.instants = time.instants, ABP.normalised = normalised.abp.signal, sampling.time = sampling.time, stabilisation.time = stabilisation.time ) r <- 1:nrow(at.params) templates <- lapply(r, .tmp.fun) .tmp.fun <- function(t) normalise.CBFV.signal( time.instants = time.instants, CBFV.signal = t[["CBFV.theoretical.response"]], sample.release = sample.release, sampling.time = sampling.time, baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.CBFV.max.delta.time = min.cbfv.max.delta.time, time.tol = time.tol ) normalised.templates <- lapply(templates, .tmp.fun) .tmp.fun <- function(t) t[["normalised.CBFV.signal"]] normalised.templates <- lapply(normalised.templates, .tmp.fun) names(normalised.templates) <- sapply(r, function(i) sprintf("%.1f", at.params[i, 4])) normalised.templates } get.plot.dARI <- function( time.instants, normalised.abp.signal, normalised.cbfv.signal, template.search.results, abp.palette = brewer.pal(n = 9, name = "Reds"), cbfv.palette = brewer.pal(n = 9, name = "Blues"), template.palette = brewer.pal(n = 9, name = "Greens"), time.tol = min(diff(time.instants)) / 100, plot.id = NULL, fiting.value.name = "Fitting", fiting.value.rounding.digits = 3, ... # Not used ) { # Rebuilds the original signals abp.baseline <- attr(normalised.abp.signal, "baseline.value") abp.min <- attr(normalised.abp.signal, "min.value") abp <- normalised.abp.signal * (abp.baseline - abp.min) + abp.min cbfv.baseline <- attr(normalised.cbfv.signal, "baseline.value") cbfv.min <- attr(normalised.cbfv.signal, "min.value") .tmp.fun <- function(x) x * (cbfv.baseline - cbfv.min) + cbfv.min cbfv <- .tmp.fun(normalised.cbfv.signal) # Plots CBFV dcbfv <- data.frame(Time = time.instants, Signal = cbfv, Segment = "CBFV") p <- ggplot(dcbfv, aes(x = Time, y = Signal, colour = Segment)) p <- p + geom_line(linetype = "dashed") d <- dcbfv[template.search.results[["relevant.samples"]], ] p <- p + geom_line(data = d) # Plots ABP dabp <- data.frame(Time = time.instants, Signal = abp, Segment = "ABP") p <- p + geom_line(data = dabp, linetype = "dashed") # Gets relevant time instants relevant.time.instants <- time.instants[template.search.results[["relevant.samples"]]] # Plots representative templates i <- seq(11, 91, 20) temps <- template.search.results[["relevant.template.segments"]][i] values <- c(sapply(temps, .tmp.fun)) lengths <- c(sapply(temps, function(t) length(t))) aris <- paste("ARI", "=", names(temps)) aris <- rep(aris, times = lengths) times <- rep(relevant.time.instants, times = length(i)) d <- data.frame(Time = times, Signal = values, Segment = aris) p <- p + geom_line(data = d, linetype = "dashed") # Plots best template ibest <- template.search.results[["ranking"]][1] best <- template.search.results[["relevant.template.segments"]][[ibest]] d <- data.frame( Time = relevant.time.instants, Signal = .tmp.fun(best), Segment = "Best template" ) p <- p + geom_line(data = d) p <- p + xlab("Time") + ylab("Signals") cmatch <- c("ABP" = abp.palette[4], "CBFV" = cbfv.palette[4]) cmatch <- c(cmatch, "Best template" = template.palette[9]) subpal <- template.palette[3:7] aris <- paste("ARI", "=", names(temps)) names(subpal) <- aris cmatch <- c(cmatch, subpal) p <- p + scale_colour_manual(values = cmatch, breaks = names(cmatch)) p <- p + theme( legend.justification = c(0, 0), legend.background = element_rect(fill = alpha('grey90', 0.0)), legend.position = c(0, 0), legend.key.size = unit(0.4, "cm"), legend.title = element_blank(), legend.text = element_text(size = 8) ) # Adds annotation table l1 <- "Time of release" v1 <- sprintf( "t = %.1f", template.search.results[["referential.time.instant"]] ) l2 <- "Compared window" v2 <- sprintf( "t in [%.1f, %.1f]", template.search.results[["initial.time.instant"]], template.search.results[["final.time.instant"]] ) l3 <- paste("Best", fiting.value.name) v3 <- sprintf( "%.*f", fiting.value.rounding.digits, template.search.results[["fit.values"]][ibest] ) ann.table <- data.frame(label = c(l1, l2, l3), values = c(v1, v2, v3)) gt <- tableGrob( d = ann.table, show.rownames = FALSE, show.colnames = FALSE, gpar.coretext = gpar(col = cbfv.palette[7], cex = 0.6), padding.v = unit(2, "mm") ) xmin <- time.instants[1] xmax <- tail(time.instants, 1) rx <- xmax - xmin dx <- rx / 100 ymin <- min(abp, cbfv) ymax <- max(abp, cbfv) ry <- ymax - ymin dy <- ry / 100 p <- p + annotation_custom( grob = gt, xmin = xmax - 25 * dx, xmax = xmax, ymin = ymin, ymax = ymin + 10 * dy ) # Sets the plot title best.ari <- paste( "dARI", names(template.search.results[["relevant.template.segments"]])[ibest], sep = " = " ) if(is.null(plot.id)) p <- p + ggtitle(best.ari) else p <- p + ggtitle(paste(plot.id, best.ari, sep = ", ")) p } plot.manoeuvre.signals <- function( time.instants, normalised.abp.signal, normalised.cbfv.signal, normalised.cbfv.templates, tgt.plot.filename, tgt.plot.id, ... ) { dari.search <- get.best.templates( time.instants = time.instants, signal = normalised.cbfv.signal, templates = normalised.cbfv.templates, keep.details = TRUE, ... ) p <- get.plot.dARI( time.instants = time.instants, normalised.abp.signal = normalised.abp.signal, normalised.cbfv.signal = normalised.cbfv.signal, template.search.results = dari.search, time.tol = time.tol, plot.id = tgt.plot.id, ... ) ggsave( filename = tgt.plot.filename, plot = p, width = 11, height = 8, units = "in" ) } get.manoeuvre.normalised.abp <- function( time.instants, abp.signal, sampling.time, sample.release, baseline.initial.time = time.instants[1], baseline.final.time = time.instants[sample.release], min.abp.max.delta.time = 5 * 0.8, time.tol = sampling.time / 100, ... # Not used ) { normalised.signal <- normalise.ABP.signal( time.instants = time.instants, ABP.signal = abp.signal, sample.release = sample.release, sampling.time = sampling.time, baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.ABP.max.delta.time = min.abp.max.delta.time, time.tol = time.tol ) normalised.abp.signal <- normalised.signal[["normalised.ABP.signal"]] attr(normalised.abp.signal, "baseline.value") <- normalised.signal[["ABP.baseline.value"]] attr(normalised.abp.signal, "min.value") <- normalised.signal[["min.ABP.value"]] normalised.abp.signal } get.manoeuvre.normalised.cbfv <- function( time.instants, cbfv.signal, sampling.time, sample.release, baseline.initial.time = time.instants[1], baseline.final.time = time.instants[sample.release], min.cbfv.max.delta.time = 8 * 0.8, time.tol = sampling.time / 100, ... # Not used ) { normalised.signal <- normalise.CBFV.signal( time.instants = time.instants, CBFV.signal = cbfv.signal, sample.release = sample.release, sampling.time = sampling.time, baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.CBFV.max.delta.time = min.cbfv.max.delta.time, time.tol = time.tol ) normalised.cbfv.signal <- normalised.signal[["normalised.CBFV.signal"]] attr(normalised.cbfv.signal, "baseline.value") <- normalised.signal[["CBFV.baseline.value"]] attr(normalised.cbfv.signal, "min.value") <- normalised.signal[["min.CBFV.value"]] normalised.cbfv.signal } plot.subject.signals <- function( subject, src.subject.dir, src.ext = "txt", header = TRUE, tgt.subject.dir, tgt.suffix, tgt.ext = "txt", overwrite = FALSE, manoeuvres, time.col.name = "Time", abp.col.name = "ABP", left.cbfv.col.name = "LCBFV", right.cbfv.col.name = "RCBFV", sampling.time = 0.2, time.release = 0, left.plot.suffix = "Izq", right.plot.suffix = "Der", indent = "", time.tol = sampling.time / 100, ... ) { plot.created <- FALSE next.indent <- paste0(indent , " ") for(mvre in manoeuvres) { cat(indent, "-- ", mvre, " --\n", sep = "") # Sets the subject source file src.basename <- paste(subject, mvre, sep = "-") src.basename <- paste(src.basename, src.ext, sep = ".") src.filename <- file.path(src.subject.dir, src.basename) if(!file.exists(src.filename)) { cat( next.indent, "Warning: file ", src.filename, " does not exists\n", sep = "" ) next } # Reads the manoeuvre signals mvre.data <- read.table(src.filename, header = header) # Sets subject and manoeuvre as initial plot titles mvre.id <- paste(subject, mvre, sep = ", ") # Gets sample of release sample.release <- which(are.tolerably.equal( mvre.data[[time.col.name]], time.release, time.tol )) # Gets normalised ABP normalised.abp.signal <- get.manoeuvre.normalised.abp( time.instants = mvre.data[[time.col.name]], abp.signal = mvre.data[[abp.col.name]], sampling.time = sampling.time, sample.release = sample.release, time.tol = time.tol, ... ) # Gets dARI templates normalised.dari.templates <- get.normalised.dari.templates( time.instants = mvre.data[[time.col.name]], normalised.abp.signal = normalised.abp.signal, sampling.time = sampling.time, sample.release = sample.release, time.tol = time.tol, ... ) # # Creates the plot for the left hemisphere # cat(next.indent, "-- Left hemisphere --\n", sep = "") # Sets target plot filename tgt.basename <- paste(subject, mvre, tgt.suffix, left.plot.suffix, sep = "-") tgt.basename <- paste(tgt.basename, tgt.ext, sep = ".") tgt.filename <- file.path(tgt.subject.dir, tgt.basename) # If the target plot does not exists or it should not be overwritten if(any(!file.exists(tgt.filename), overwrite)) { # Makes sure the target directory exists dir.create( path = tgt.subject.dir, showWarnings = FALSE, recursive = TRUE, mode = "0711" ) normalised.cbfv.signal <- get.manoeuvre.normalised.cbfv( time.instants = mvre.data[[time.col.name]], cbfv.signal = mvre.data[[left.cbfv.col.name]], sampling.time = sampling.time, sample.release = sample.release, time.tol = time.tol, ... ) plot.manoeuvre.signals( time.instants = mvre.data[[time.col.name]], normalised.abp.signal = normalised.abp.signal, normalised.cbfv.signal = normalised.cbfv.signal, normalised.cbfv.templates = normalised.dari.templates, tgt.plot.filename = tgt.filename, tgt.plot.id = paste(mvre.id, left.plot.suffix, sep = ", "), ... ) plot.created <- TRUE } else cat( paste(next.indent, " "), "Warning: target plot already exist and not overwritten\n", sep = "" ) # # Creates the plot for the right hemisphere # cat(next.indent, "-- Right hemisphere --\n", sep = "") # Sets target plot filename tgt.basename <- paste(subject, mvre, tgt.suffix, right.plot.suffix, sep = "-") tgt.basename <- paste(tgt.basename, tgt.ext, sep = ".") tgt.filename <- file.path(tgt.subject.dir, tgt.basename) # If the target plot does not exists or it should not be overwritten if(any(!file.exists(tgt.filename), overwrite)) { # Makes sure the target directory exists dir.create( path = tgt.subject.dir, showWarnings = FALSE, recursive = TRUE, mode = "0711" ) normalised.cbfv.signal <- get.manoeuvre.normalised.cbfv( time.instants = mvre.data[[time.col.name]], cbfv.signal = mvre.data[[right.cbfv.col.name]], sampling.time = sampling.time, sample.release = sample.release, time.tol = time.tol, ... ) plot.manoeuvre.signals( time.instants = mvre.data[[time.col.name]], normalised.abp.signal = normalised.abp.signal, normalised.cbfv.signal = normalised.cbfv.signal, normalised.cbfv.templates = normalised.dari.templates, tgt.plot.filename = tgt.filename, tgt.plot.id = paste(mvre.id, right.plot.suffix, sep = ", "), ... ) plot.created <- TRUE } else cat( paste(next.indent, " "), "Warning: target plot already exist and not overwritten\n", sep = "" ) } plot.created } run <- function( src.dir = file.path(WORK.DIR, "Data"), src.ext = "txt", header = TRUE, tgt.suffix = paste("dARI", "search", "plots", sep = "-"), tgt.dir = file.path(WORK.DIR, tgt.suffix), tgt.ext = "pdf", overwrite = FALSE, subjects = c("Sujeto1", "Sujeto2", "Sujeto3"), manoeuvres = c("maniobra1", "maniobra2", "maniobra3"), time.col.name = "Time", abp.col.name = "ABP", left.cbfv.col.name = "LCBFV", right.cbfv.col.name = "RCBFV", left.plot.suffix = "Izq", right.plot.suffix = "Der", sampling.time = 0.2, time.release = 0, baseline.initial.time = -5, baseline.final.time = time.release, min.abp.max.delta.time = 5 * 0.8, min.cbfv.max.delta.time = 8 * 0.8, stabilisation.time = 30, referential.time.instant = time.release, delta.time.before.ref = 0, delta.time.after.ref = round(floor(20 * 0.8 / sampling.time) * sampling.time, 1), comparison.function = get.MSE, fiting.value.name = "MSE", fiting.value.rounding.digits = 4, at.param.rounding.digits = 6, time.tol = sampling.time / 100, indent = "" ) { plot.created <- FALSE for(subject in subjects) { cat(indent, "-- ", subject, " --\n", sep = "") # Sets subject directories src.subject.dir <- file.path(src.dir, subject) tgt.subject.dir <- file.path(tgt.dir, subject) subject.plot.created <- plot.subject.signals( subject = subject, src.subject.dir = src.subject.dir, src.ext = src.ext, header = header, tgt.subject.dir = tgt.subject.dir, tgt.suffix = tgt.suffix, tgt.ext = tgt.ext, overwrite = overwrite, manoeuvres = manoeuvres, time.col.name = time.col.name, abp.col.name = abp.col.name, left.cbfv.col.name = left.cbfv.col.name, right.cbfv.col.name = right.cbfv.col.name, left.plot.suffix = left.plot.suffix, right.plot.suffix = right.plot.suffix, sampling.time = sampling.time, time.release = time.release, baseline.initial.time = baseline.initial.time, baseline.final.time = baseline.final.time, min.abp.max.delta.time = min.abp.max.delta.time, min.cbfv.max.delta.time = min.cbfv.max.delta.time, stabilisation.time = stabilisation.time, referential.time.instant = referential.time.instant, delta.time.before.ref = delta.time.before.ref, delta.time.after.ref = delta.time.after.ref, comparison.function = comparison.function, fiting.value.name = fiting.value.name, fiting.value.rounding.digits = fiting.value.rounding.digits, at.param.rounding.digits = at.param.rounding.digits, time.tol = time.tol, indent = paste0(indent, " ") ) plot.created <- any(plot.created, subject.plot.created) } plot.created } <file_sep>setwd("C:/Users/Luis/Documents/DataScience/Tesis/Calculo ARI/v15.9.10/stats") data <- read.csv('maniobras-stats-v15.9.10.csv', sep=';') left <- data[data$Hemisferio=="Left",]$mfARI right <- data[data$Hemisferio=="Right",]$mfARI #Kolmogorov-Smirnov ya que son 54 datos pero tiene valores repetidos #ks.test(left, "pnorm")#no normal #ks.test(right, "pnorm")#no normal #no normal #wilcox.test(left, right, alternative = "two.sided")#Los hemisferios son similares shapiro.test(left)#normal shapiro.test(right)#normal hist(left) hist(right) #normal t.test(left, right, alternative = "two.sided") #Los hemisferios son similares por quep-value > 0.05 ############################################## #mean mfARI mfARI <- rowMeans(data.frame(left, right)) dat = data.frame("Maniobra" = data[data$Hemisferio=="Left",]$Maniobra, "mfARI" = mfARI) fm = aov( dat$mfARI ~ dat$Maniobra, data = dat ) summary(fm) tuk <- TukeyHSD(fm) plot (tuk) boxplot(dat$mfARI ~ dat$Maniobra, main="Comparacion de Posiciones mfARI", col= rainbow(3), horizontal = TRUE) #Conclusion ##La mayor diferencia de posiciones van en este orde: ### PIE-ACOSTADO = 0.7775675 ### SENTADO-ACOSTADO = 0.8830272 ### SENTADO-PIE = 0.9778065 ###############################mejor esto que el calculo anterior del post hoc -> es mejor pairwise tyres.aov<- aov(mfARI~Maniobra, dat) class(tyres.aov) summary(tyres.aov) pairwise.t.test(dat$mfARI,dat$Maniobra,p.adjust.method = "none") ## model = lm(mfARI ~ Maniobra, data=dat) Anova(model, type="III") summary(model) boxplot(mfARI ~ Maniobra, data = dat, ylab="aam / height", xlab="Location") <file_sep><<<<<<< HEAD <<<<<<< HEAD import pandas import numpy import seaborn import scipy import matplotlib.pyplot as plt import seaborn as sns data = pandas.read_csv(‘marscrater_pds.csv’, low_memory=False) data['DIAM_CIRCLE_IMAGE’] = data['DIAM_CIRCLE_IMAGE’].convert_objects(convert_numeric=True) data['DEPTH_RIMFLOOR_TOPOG’] = data['DEPTH_RIMFLOOR_TOPOG’].convert_objects(convert_numeric=True) data['DIAM_CIRCLE_IMAGE’]=data['DIAM_CIRCLE_IMAGE’].replace(’ ’, numpy.nan) data['DEPTH_RIMFLOOR_TOPOG’]=data['DEPTH_RIMFLOOR_TOPOG’].replace(’ ’, numpy.nan) data_clean=data.dropna() print ('association between urbanrate and internetuserate’) print (scipy.stats.pearsonr(data_clean['DIAM_CIRCLE_IMAGE’], data_clean['DEPTH_RIMFLOOR_TOPOG’])) scat1 = seaborn.regplot(x=“DIAM_CIRCLE_IMAGE”, y=“DEPTH_RIMFLOOR_TOPOG”, fit_reg=True, data=data_clean) plt.xlabel('Crater Diameter (km)’) plt.ylabel('Crater Elevation (km)’) plt.title('Scatterplot for the Association Between Diameter and Elevation’) corr = data_clean.corr() sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns) ======= import pandas import numpy import seaborn import scipy import matplotlib.pyplot as plt import seaborn as sns data = pandas.read_csv(‘marscrater_pds.csv’, low_memory=False) data['DIAM_CIRCLE_IMAGE’] = data['DIAM_CIRCLE_IMAGE’].convert_objects(convert_numeric=True) data['DEPTH_RIMFLOOR_TOPOG’] = data['DEPTH_RIMFLOOR_TOPOG’].convert_objects(convert_numeric=True) data['DIAM_CIRCLE_IMAGE’]=data['DIAM_CIRCLE_IMAGE’].replace(’ ’, numpy.nan) data['DEPTH_RIMFLOOR_TOPOG’]=data['DEPTH_RIMFLOOR_TOPOG’].replace(’ ’, numpy.nan) data_clean=data.dropna() print ('association between urbanrate and internetuserate’) print (scipy.stats.pearsonr(data_clean['DIAM_CIRCLE_IMAGE’], data_clean['DEPTH_RIMFLOOR_TOPOG’])) scat1 = seaborn.regplot(x=“DIAM_CIRCLE_IMAGE”, y=“DEPTH_RIMFLOOR_TOPOG”, fit_reg=True, data=data_clean) plt.xlabel('Crater Diameter (km)’) plt.ylabel('Crater Elevation (km)’) plt.title('Scatterplot for the Association Between Diameter and Elevation’) corr = data_clean.corr() sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= import pandas import numpy import seaborn import scipy import matplotlib.pyplot as plt import seaborn as sns data = pandas.read_csv(‘marscrater_pds.csv’, low_memory=False) data['DIAM_CIRCLE_IMAGE’] = data['DIAM_CIRCLE_IMAGE’].convert_objects(convert_numeric=True) data['DEPTH_RIMFLOOR_TOPOG’] = data['DEPTH_RIMFLOOR_TOPOG’].convert_objects(convert_numeric=True) data['DIAM_CIRCLE_IMAGE’]=data['DIAM_CIRCLE_IMAGE’].replace(’ ’, numpy.nan) data['DEPTH_RIMFLOOR_TOPOG’]=data['DEPTH_RIMFLOOR_TOPOG’].replace(’ ’, numpy.nan) data_clean=data.dropna() print ('association between urbanrate and internetuserate’) print (scipy.stats.pearsonr(data_clean['DIAM_CIRCLE_IMAGE’], data_clean['DEPTH_RIMFLOOR_TOPOG’])) scat1 = seaborn.regplot(x=“DIAM_CIRCLE_IMAGE”, y=“DEPTH_RIMFLOOR_TOPOG”, fit_reg=True, data=data_clean) plt.xlabel('Crater Diameter (km)’) plt.ylabel('Crater Elevation (km)’) plt.title('Scatterplot for the Association Between Diameter and Elevation’) corr = data_clean.corr() sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep> require(ggplot2) require(gridExtra) require(signal) require(pracma) # This function creates an normalised ABP step stimulus. # The function receives the following arguments: # # sampling.time: sampling time for the ABP stimulus (in seconds). # Default value: 0.1 s # # time.until.release: time included in the resulting signal until the # time of cuff release (in seconds). # Default value: 10 s # # time.after.release: time included in the resulting signals after the # time of cuff release. # Default value: 20 s # # smooth.step.stimulus: logical, whether the ABP step stimulus should # be smoothed (filtered). # Default value: FALSE # # filter.order: the order of the low-pass Butterworth filter used to # smooth the ABP step stimulus. # Default value: 2 # # cutoff.frequency: the cutoff frequency for the low-pass Butterworth # filter used to smooth the ABP step stimulus (in Hz). # Default value: 0.20 Hz # # left.stabilisation.time: the time to be used for stabilisation of the # step. This time is included in the step when # a filter is applied, but removed after that. # Default value: 30 s when a filter will be # applied, 0 s otherwise. # # time.rounding.digits: the number of decimal when time instants are # used. # Default value: the number of decimals in the # sampling time # # The function's answer is a list with the following: # .$time.instants: the time instants in which the signal is sampled. # .$ABP.normalised: the normalised ABP stimulus generated # .$sampling.time: the sampling time used # .$time.release: the time instant in which the thigh cuffs are # supposedly released. Currently at the second 0.0. # get.normalised.ABP.stimulus <- function( sampling.time = 0.1, time.until.release = 10, time.after.release = 20, smooth.step.stimulus = FALSE, filter.order = 2, cutoff.frequency = 0.20, left.stabilisation.time = ifelse(smooth.step.stimulus, 30, 0), time.rounding.digits = format.info(sampling.time)[2], time.tol = sampling.time / 100 ) { if(!is.divisible(time.until.release, sampling.time, time.tol)) stop("time until release must be a multiple of the target sampling time") if(!is.divisible(time.after.release, sampling.time, time.tol)) stop("time after release must be a multiple of the target sampling time") frequency <- 1 / sampling.time nsamples.stabilisation.left <- round(left.stabilisation.time / sampling.time) nsamples.until.release <- round(time.until.release / sampling.time) + 1 nsamples.left <- nsamples.stabilisation.left + nsamples.until.release nsamples.after.release <- round(time.after.release / sampling.time) nsamples <- nsamples.until.release + nsamples.after.release # ABP step stimulus P <- c(rep(1, nsamples.left), rep(0, nsamples.after.release)) # Smooths ABP step stimulus if corresponds if(smooth.step.stimulus) { wn <- cutoff.frequency / (frequency / 2) b <- butter(filter.order, wn) P <- as.numeric(filter(b, P)) } if(nsamples.stabilisation.left > 0) P <- P[-(1:nsamples.stabilisation.left)] tini <- -time.until.release time <- seq(tini, length.out = nsamples, by = sampling.time) # Creates the answer ans <- list() ans[["time.instants"]] <- round(time, time.rounding.digits) ans[["ABP.normalised"]] <- P ans[["sampling.time"]] <- sampling.time ans[["time.release"]] <- ans[["time.instants"]][nsamples.until.release] invisible(ans) } normalise.signal <- function( signal, signal.baseline.value, signal.min.value ) { (signal - signal.min.value) / abs(signal.baseline.value - signal.min.value) } get.best.templates <- function( time.instants, signal, templates, referential.time.instant = 0, delta.time.before.ref = 0, delta.time.after.ref = 20 * 0.8, comparison.function = get.MSE, keep.details = TRUE, time.tol = min(diff(time.instants)) / 100, ... # Pass over to comparison.function() ) { # Validates lengths lengths <- c(length(time.instants), length(signal)) lengths <- c(lengths, sapply(templates, length)) lengths <- unique(lengths) if(length(lengths) != 1) stop("time, signal and templates must have the same length") # Initialises detailed answer ans <- list() ans[["time.instants"]] <- time.instants ans[["signal"]] <- signal ans[["templates"]] <- templates ans[["referential.time.instant"]] <- referential.time.instant # Finds referential sample i <- which(are.tolerably.equal( time.instants, referential.time.instant, time.tol )) if(length(i) != 1) stop("a unique referential time instant could not be determined") ans[["referential.sample"]] <- i # Finds initial sample ans[["delta.time.before.ref"]] <- delta.time.before.ref ans[["initial.time.instant"]] <- referential.time.instant - delta.time.before.ref i <- which(are.tolerably.equal( time.instants, ans[["initial.time.instant"]], time.tol )) if(length(i) != 1) stop("initial time instant could not be found in specified time instants") ans[["initial.sample"]] <- i # Finds final sample ans[["delta.time.after.ref"]] <- delta.time.after.ref ans[["final.time.instant"]] <- referential.time.instant + delta.time.after.ref i <- which(are.tolerably.equal( time.instants, ans[["final.time.instant"]], time.tol )) if(length(i) != 1) stop("final time instant could not be found in specified time instants") ans[["final.sample"]] <- i # Sets relevant interval ans[["relevant.samples"]] <- ans[["initial.sample"]]:ans[["final.sample"]] # Gets relevant segments .tmp.fun <- function(s) s[ans[["relevant.samples"]]] ans[["relevant.signal.segment"]] <- .tmp.fun(ans[["signal"]]) ans[["relevant.template.segments"]] <- lapply(ans[["templates"]], .tmp.fun) # Gets fit values .tmp.fun <- function(t) comparison.function(ans[["relevant.signal.segment"]], t, ...) ans[["fit.values"]] <- sapply(ans[["relevant.template.segments"]], .tmp.fun) # Orders templates and determines the best one ans[["ranking"]] <- order(ans[["fit.values"]]) # Deletes details if corresponds if(!keep.details) { i <- ans[["ranking"]][1] e <- ans[["fit.values"]][i] ans <- list(best.template.index = i, best.fit.value = e) } ans } <file_sep><<<<<<< HEAD <<<<<<< HEAD install.packages('modeest', dep = TRUE) library(modeest) install.packages('ggplot2', dep = TRUE) library(ggplot2) install.packages('corrplot', dep = TRUE) library('corrplot') install.packages('mclust', dep = TRUE) library(mclust) library('corrplot') library(ggplot2) library(modeest) library(mclust) setwd("C:/Users/Luis.O.A/Documents/USACH/Mineria de Datos/grupo 6 Wine Quality") data <- read.csv('winequality-red.csv', sep=';') ############ Estadistica Descriptiva ############ ######## Medida de Tendencias Centrales ## Media ## mean(data$fixed.acidity) 8.319637 mean(data$volatile.acidity) 0.5278205 mean(data$citric.acid) 0.2709756 mean(data$residual.sugar) 2.538806 mean(data$chlorides) 0.08746654 mean(data$free.sulfur.dioxide) 15.87492 mean(data$total.sulfur.dioxide) 46.46779 mean(data$density) 0.9967467 mean(data$pH) 3.311113 mean(data$sulphates) 0.6581488 mean(data$alcohol) 10.42298 ## Moda ## mlv(data$fixed.acidity, method = "mfv")[1] 7.2 mlv(data$volatile.acidity, method = "mfv")[1] 0.6 mlv(data$citric.acid, method = "mfv")[1] 0 mlv(data$residual.sugar, method = "mfv")[1] 2 mlv(data$chlorides, method = "mfv")[1] 0.08 mlv(data$free.sulfur.dioxide, method = "mfv")[1] 6 mlv(data$density, method = "mfv")[1] 0.9972 mlv(data$pH, method = "mfv")[1] 3.3 mlv(data$sulphates, method = "mfv")[1] 0.6 mlv(data$alcohol, method = "mfv")[1] 9.5 ## Mediana ## median(data$fixed.acidity) 7.9 median(data$volatile.acidity) 0.52 median(data$citric.acid) 0.26 median(data$residual.sugar) 2.2 median(data$chlorides) 0.079 median(data$free.sulfur.dioxide) 14 median(data$density) 0.99675 median(data$pH) 3.31 median(data$sulphates) 0.62 median(data$alcohol) 10.2 ######## Medidas de Dispersion ## Rango ## range(data$fixed.acidity) 4.6 15.9 range(data$volatile.acidity) 0.12 1.58 range(data$citric.acid) 0 1 range(data$residual.sugar) 0.9 15.5 range(data$chlorides) 0.012 0.611 range(data$free.sulfur.dioxide) 1 72 range(data$density) 0.99007 1.00369 range(data$pH) 2.74 4.01 range(data$sulphates) 0.33 2.00 range(data$alcohol) 8.4 14.9 summary(data)# Vista resumida de lo anteriormente visto. Seria util presentarlo en una tabla boxplot(data$nombre_variable)# grafico de caja por variable ## Cuartiles ## #El siguiente grafico sera muy util para explicr que incidencia tiene cada una de las variables e la calidad del vino. boxplot(data$nombre_variable ~ data$quality, xlab = "Calidad", ylab = "Acides Fijada", col = c("red")) ## Varianza ## var(data$fixed.acidity) 3.031416 var(data$volatile.acidity) 0.03206238 var(data$citric.acid) 0.03794748 var(data$residual.sugar) 1.987897 var(data$chlorides) 0.002215143 var(data$free.sulfur.dioxide) 109.4149 var(data$density) 3.562029e-06 var(data$pH) 0.02383518 var(data$sulphates) 0.02873262 var(data$alcohol) 1.135647 ## Distribucion ## #Nos servira para saber de manera mas grafica el rango y la mayor dispercion de cada una de las variables hist(data$Nombre_variable, main = "Nombre_variable", xlab = "Acides Fijada", col = "grey", breaks = 40, xlim = c(0,300)) ############ Estadistica Inferencial ############ ## Prueba de chi-cuadrado ## #NOTA: # "p-value" = 0 Alta dependencia entre variables # "p-value" = 1 Nula dependencia entre variables # "p-value" < 0.05 Alta dependencia entre variables (95% de dependencia) summary(table(data$fixed.acidity,data$quality)) p-value = 1.416e-13 summary(table(data$volatile.acidity,data$quality)) p-value = 3.429e-69 summary(table(data$citric.acid,data$quality)) p-value = 6.425e-19 summary(table(data$residual.sugar,data$quality)) p-value = 1.649e-28 summary(table(data$chlorides,data$quality)) p-value = 1.181e-34 summary(table(data$free.sulfur.dioxide,data$quality)) p-value = 0.2399 #Esta es la unica variable que tiene una baja dependencia summary(table(data$density,data$quality)) p-value = 7.547e-33 summary(table(data$pH,data$quality)) p-value = 8.719e-10 summary(table(data$sulphates,data$quality)) p-value = 2.382e-31 summary(table(data$alcohol,data$quality)) p-value = 5.345e-90 ## Correlacion ## M <- cor(data) corrplot(M, method="circle") ################################### Noralizacion de los datos ################################### # NOTA: # Cuando los rangos de las variables son muy dispares (ver "Rango") se aplica el siguiente modelo: # X1 = (X1 - Media X1) / (max X1 - min X1) dataNorm <- as.data.frame( scale(data[1:11] )) # no se normaliza la clase ##https://www.analyticsvidhya.com/blog/2015/10/inferential-descriptive-statistics-beginners-r/ BIC = mclustBIC(dataNorm) plot(BIC) Mclust(dataNorm, modelNames ="VVV", G = 3)$BIC Mclust(dataNorm, modelNames ="VVV", G = 4)$BIC Mclust(dataNorm, modelNames ="VVV", G = 5)$BIC Mclust(dataNorm, modelNames ="VVV", G = 6)$BIC Mclust(dataNorm, modelNames ="VVV", G = 7)$BIC Mclust(dataNorm, modelNames ="VEV", G = 3)$BIC Mclust(dataNorm, modelNames ="VEV", G = 4)$BIC Mclust(dataNorm, modelNames ="VEV", G = 5)$BIC Mclust(dataNorm, modelNames ="VEV", G = 6)$BIC Mclust(dataNorm, modelNames ="VEV", G = 7)$BIC Mclust(dataNorm, modelNames ="VVE", G = 3)$BIC Mclust(dataNorm, modelNames ="VVE", G = 4)$BIC Mclust(dataNorm, modelNames ="VVE", G = 5)$BIC Mclust(dataNorm, modelNames ="VVE", G = 6)$BIC Mclust(dataNorm, modelNames ="VVE", G = 7)$BIC # Mclust(dataNorm, prior = priorControl(functionName="defaultPrior", shrinkage=0.1), G = 4, modelNames ="VEV")$BIC # Comprabar el error de clasificacion m = Mclust(dataNorm, modelNames ="VVE", G = 7) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 7) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 6) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 5) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 4) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VVV", G = 4) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VVV", G = 7) classError(data$quality, m$classification)$errorRate ################################### Sin Noralizacion de los datos ################################### dataS = data[1:11] BIC = mclustBIC(dataS) plot(BIC) m1 = Mclust(dataS, modelNames ="VVE", G = 3) m2 = Mclust(dataS, modelNames ="VVE", G = 4) m3 = Mclust(dataS, modelNames ="VVE", G = 5) m4 = Mclust(dataS, modelNames ="VVE", G = 6) m5 = Mclust(dataS, modelNames ="EEV", G = 3) m6 = Mclust(dataS, modelNames ="EEV", G = 4) m7 = Mclust(dataS, modelNames ="EEV", G = 5) m8 = Mclust(dataS, modelNames ="EEV", G = 6) m9 = Mclust(dataS, modelNames ="VEV", G = 3) m10 = Mclust(dataS, modelNames ="VEV", G = 4) m11 = Mclust(dataS, modelNames ="VEV", G = 5) m12 = Mclust(dataS, modelNames ="VEV", G = 6) m13 = Mclust(dataS, modelNames ="EVV", G = 3) m14 = Mclust(dataS, modelNames ="EVV", G = 4) m15 = Mclust(dataS, modelNames ="EVV", G = 5) m16 = Mclust(dataS, modelNames ="EVV", G = 6) m1$BIC m2$BIC m3$BIC m4$BIC m5$BIC m6$BIC m7$BIC m8$BIC m9$BIC m10$BIC m11$BIC m12$BIC m13$BIC m14$BIC m15$BIC m16$BIC # Comprabar el error de clasificacion classError(data$quality, m4$classification)$errorRate classError(data$quality, m3$classification)$errorRate classError(data$quality, m12$classification)$errorRate classError(data$quality, m2$classification)$errorRate classError(data$quality, m11$classification)$errorRate classError(data$quality, m15$classification)$errorRate classError(data$quality, m14$classification)$errorRate classError(data$quality, m10$classification)$errorRate # Mejor Cluster -> m14 # Grafico de clusters drmod <- MclustDR(m14, lambda = 1) plot(drmod, what = "contour") plot(drmod, what = "boundaries", ngrid = 200) #Grafica de densidad plot(drmod, what = "density", type = "persp", theta = -25, phi = 20, border = adjustcolor(grey(0.1), alpha.f = 0.3)) table(data$quality, m14$classification) ##comprobar ERRORES segun quality ######################################## install.packages('plotly', dep = TRUE) # segun calidad data$quality.cut <- cut(data$quality, breaks = c(0,4,6,10)) table(data$quality.cut, m14$classification) # segun pH table(cut(data$pH, breaks = c(2.5, 3, 3.5, 4)), m14$classification) library(plotly) p <- plot_ly( x = data$quality.cut, y = data$pH, name = "pH", type = "bar" ) # segun acides citrica table(cut(data$citric.acid, breaks = c(0, 0.25, 0.5, 0.75, 1)), m14$classification) library(plotly) p <- plot_ly( x = data$quality.cut, y = data$citric.acid, name = "citric.acid", type = "bar" ) # segun alcohol table(cut(data$alcohol, breaks = c(8, 9, 10, 11, 12, 13 ,14, 15)), m14$classification) library(plotly) p <- plot_ly( x = data$quality.cut, y = data$alcohol, name = "alcohol", type = "bar" ) ########################################### source("http://goo.gl/UUyEzD") outlierKD(dataS, dataS$fixed.acidity) outlierKD(dataS, dataS$volatile.acidity) outlierKD(dataNorm, dataNorm$citric.acid) outlierKD(dataNorm, dataNorm$residual.sugar) outlierKD(dataNorm, dataNorm$chlorides) outlierKD(dataNorm, dataNorm$free.sulfur.dioxide) outlierKD(dataNorm, dataNorm$pH) outlierKD(dataNorm, dataNorm$sulphates) outlierKD(dataNorm, dataNorm$alcohol) ## install.packages('outliers', dep = TRUE) library(outliers) dataS = data[1:11] remove_outliers <- function(x, na.rm = TRUE, ...) { qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...) H <- 1.5 * IQR(x, na.rm = na.rm) y <- x y[x < (qnt[1] - H)] <- mean(x)#NA y[x > (qnt[2] + H)] <- mean(x)#NA y } dataS$alcohol <- remove_outliers(dataS$alcohol) dataS$sulphates <- remove_outliers(dataS$sulphates) dataS$pH <- remove_outliers(dataS$pH) dataS$free.sulfur.dioxid <- remove_outliers(dataS$free.sulfur.dioxid) dataS$chlorides <- remove_outliers(dataS$chlorides) dataS$residual.sugar <- remove_outliers(dataS$residual.sugar) dataS$citric.acid <- remove_outliers(dataS$citric.acid) dataS$volatile.acidity <- remove_outliers(dataS$volatile.acidity) dataS$fixed.acidity <- remove_outliers(dataS$fixed.acidity) ======= install.packages('modeest', dep = TRUE) library(modeest) install.packages('ggplot2', dep = TRUE) library(ggplot2) install.packages('corrplot', dep = TRUE) library('corrplot') install.packages('mclust', dep = TRUE) library(mclust) library('corrplot') library(ggplot2) library(modeest) library(mclust) setwd("C:/Users/Luis.O.A/Documents/USACH/Mineria de Datos/grupo 6 Wine Quality") data <- read.csv('winequality-red.csv', sep=';') ############ Estadistica Descriptiva ############ ######## Medida de Tendencias Centrales ## Media ## mean(data$fixed.acidity) 8.319637 mean(data$volatile.acidity) 0.5278205 mean(data$citric.acid) 0.2709756 mean(data$residual.sugar) 2.538806 mean(data$chlorides) 0.08746654 mean(data$free.sulfur.dioxide) 15.87492 mean(data$total.sulfur.dioxide) 46.46779 mean(data$density) 0.9967467 mean(data$pH) 3.311113 mean(data$sulphates) 0.6581488 mean(data$alcohol) 10.42298 ## Moda ## mlv(data$fixed.acidity, method = "mfv")[1] 7.2 mlv(data$volatile.acidity, method = "mfv")[1] 0.6 mlv(data$citric.acid, method = "mfv")[1] 0 mlv(data$residual.sugar, method = "mfv")[1] 2 mlv(data$chlorides, method = "mfv")[1] 0.08 mlv(data$free.sulfur.dioxide, method = "mfv")[1] 6 mlv(data$density, method = "mfv")[1] 0.9972 mlv(data$pH, method = "mfv")[1] 3.3 mlv(data$sulphates, method = "mfv")[1] 0.6 mlv(data$alcohol, method = "mfv")[1] 9.5 ## Mediana ## median(data$fixed.acidity) 7.9 median(data$volatile.acidity) 0.52 median(data$citric.acid) 0.26 median(data$residual.sugar) 2.2 median(data$chlorides) 0.079 median(data$free.sulfur.dioxide) 14 median(data$density) 0.99675 median(data$pH) 3.31 median(data$sulphates) 0.62 median(data$alcohol) 10.2 ######## Medidas de Dispersion ## Rango ## range(data$fixed.acidity) 4.6 15.9 range(data$volatile.acidity) 0.12 1.58 range(data$citric.acid) 0 1 range(data$residual.sugar) 0.9 15.5 range(data$chlorides) 0.012 0.611 range(data$free.sulfur.dioxide) 1 72 range(data$density) 0.99007 1.00369 range(data$pH) 2.74 4.01 range(data$sulphates) 0.33 2.00 range(data$alcohol) 8.4 14.9 summary(data)# Vista resumida de lo anteriormente visto. Seria util presentarlo en una tabla boxplot(data$nombre_variable)# grafico de caja por variable ## Cuartiles ## #El siguiente grafico sera muy util para explicr que incidencia tiene cada una de las variables e la calidad del vino. boxplot(data$nombre_variable ~ data$quality, xlab = "Calidad", ylab = "Acides Fijada", col = c("red")) ## Varianza ## var(data$fixed.acidity) 3.031416 var(data$volatile.acidity) 0.03206238 var(data$citric.acid) 0.03794748 var(data$residual.sugar) 1.987897 var(data$chlorides) 0.002215143 var(data$free.sulfur.dioxide) 109.4149 var(data$density) 3.562029e-06 var(data$pH) 0.02383518 var(data$sulphates) 0.02873262 var(data$alcohol) 1.135647 ## Distribucion ## #Nos servira para saber de manera mas grafica el rango y la mayor dispercion de cada una de las variables hist(data$Nombre_variable, main = "Nombre_variable", xlab = "Acides Fijada", col = "grey", breaks = 40, xlim = c(0,300)) ############ Estadistica Inferencial ############ ## Prueba de chi-cuadrado ## #NOTA: # "p-value" = 0 Alta dependencia entre variables # "p-value" = 1 Nula dependencia entre variables # "p-value" < 0.05 Alta dependencia entre variables (95% de dependencia) summary(table(data$fixed.acidity,data$quality)) p-value = 1.416e-13 summary(table(data$volatile.acidity,data$quality)) p-value = 3.429e-69 summary(table(data$citric.acid,data$quality)) p-value = 6.425e-19 summary(table(data$residual.sugar,data$quality)) p-value = 1.649e-28 summary(table(data$chlorides,data$quality)) p-value = 1.181e-34 summary(table(data$free.sulfur.dioxide,data$quality)) p-value = 0.2399 #Esta es la unica variable que tiene una baja dependencia summary(table(data$density,data$quality)) p-value = 7.547e-33 summary(table(data$pH,data$quality)) p-value = 8.719e-10 summary(table(data$sulphates,data$quality)) p-value = 2.382e-31 summary(table(data$alcohol,data$quality)) p-value = 5.345e-90 ## Correlacion ## M <- cor(data) corrplot(M, method="circle") ################################### Noralizacion de los datos ################################### # NOTA: # Cuando los rangos de las variables son muy dispares (ver "Rango") se aplica el siguiente modelo: # X1 = (X1 - Media X1) / (max X1 - min X1) dataNorm <- as.data.frame( scale(data[1:11] )) # no se normaliza la clase ##https://www.analyticsvidhya.com/blog/2015/10/inferential-descriptive-statistics-beginners-r/ BIC = mclustBIC(dataNorm) plot(BIC) Mclust(dataNorm, modelNames ="VVV", G = 3)$BIC Mclust(dataNorm, modelNames ="VVV", G = 4)$BIC Mclust(dataNorm, modelNames ="VVV", G = 5)$BIC Mclust(dataNorm, modelNames ="VVV", G = 6)$BIC Mclust(dataNorm, modelNames ="VVV", G = 7)$BIC Mclust(dataNorm, modelNames ="VEV", G = 3)$BIC Mclust(dataNorm, modelNames ="VEV", G = 4)$BIC Mclust(dataNorm, modelNames ="VEV", G = 5)$BIC Mclust(dataNorm, modelNames ="VEV", G = 6)$BIC Mclust(dataNorm, modelNames ="VEV", G = 7)$BIC Mclust(dataNorm, modelNames ="VVE", G = 3)$BIC Mclust(dataNorm, modelNames ="VVE", G = 4)$BIC Mclust(dataNorm, modelNames ="VVE", G = 5)$BIC Mclust(dataNorm, modelNames ="VVE", G = 6)$BIC Mclust(dataNorm, modelNames ="VVE", G = 7)$BIC # Mclust(dataNorm, prior = priorControl(functionName="defaultPrior", shrinkage=0.1), G = 4, modelNames ="VEV")$BIC # Comprabar el error de clasificacion m = Mclust(dataNorm, modelNames ="VVE", G = 7) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 7) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 6) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 5) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 4) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VVV", G = 4) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VVV", G = 7) classError(data$quality, m$classification)$errorRate ################################### Sin Noralizacion de los datos ################################### dataS = data[1:11] BIC = mclustBIC(dataS) plot(BIC) m1 = Mclust(dataS, modelNames ="VVE", G = 3) m2 = Mclust(dataS, modelNames ="VVE", G = 4) m3 = Mclust(dataS, modelNames ="VVE", G = 5) m4 = Mclust(dataS, modelNames ="VVE", G = 6) m5 = Mclust(dataS, modelNames ="EEV", G = 3) m6 = Mclust(dataS, modelNames ="EEV", G = 4) m7 = Mclust(dataS, modelNames ="EEV", G = 5) m8 = Mclust(dataS, modelNames ="EEV", G = 6) m9 = Mclust(dataS, modelNames ="VEV", G = 3) m10 = Mclust(dataS, modelNames ="VEV", G = 4) m11 = Mclust(dataS, modelNames ="VEV", G = 5) m12 = Mclust(dataS, modelNames ="VEV", G = 6) m13 = Mclust(dataS, modelNames ="EVV", G = 3) m14 = Mclust(dataS, modelNames ="EVV", G = 4) m15 = Mclust(dataS, modelNames ="EVV", G = 5) m16 = Mclust(dataS, modelNames ="EVV", G = 6) m1$BIC m2$BIC m3$BIC m4$BIC m5$BIC m6$BIC m7$BIC m8$BIC m9$BIC m10$BIC m11$BIC m12$BIC m13$BIC m14$BIC m15$BIC m16$BIC # Comprabar el error de clasificacion classError(data$quality, m4$classification)$errorRate classError(data$quality, m3$classification)$errorRate classError(data$quality, m12$classification)$errorRate classError(data$quality, m2$classification)$errorRate classError(data$quality, m11$classification)$errorRate classError(data$quality, m15$classification)$errorRate classError(data$quality, m14$classification)$errorRate classError(data$quality, m10$classification)$errorRate # Mejor Cluster -> m14 # Grafico de clusters drmod <- MclustDR(m14, lambda = 1) plot(drmod, what = "contour") plot(drmod, what = "boundaries", ngrid = 200) #Grafica de densidad plot(drmod, what = "density", type = "persp", theta = -25, phi = 20, border = adjustcolor(grey(0.1), alpha.f = 0.3)) table(data$quality, m14$classification) ##comprobar ERRORES segun quality ######################################## install.packages('plotly', dep = TRUE) # segun calidad data$quality.cut <- cut(data$quality, breaks = c(0,4,6,10)) table(data$quality.cut, m14$classification) # segun pH table(cut(data$pH, breaks = c(2.5, 3, 3.5, 4)), m14$classification) library(plotly) p <- plot_ly( x = data$quality.cut, y = data$pH, name = "pH", type = "bar" ) # segun acides citrica table(cut(data$citric.acid, breaks = c(0, 0.25, 0.5, 0.75, 1)), m14$classification) library(plotly) p <- plot_ly( x = data$quality.cut, y = data$citric.acid, name = "citric.acid", type = "bar" ) # segun alcohol table(cut(data$alcohol, breaks = c(8, 9, 10, 11, 12, 13 ,14, 15)), m14$classification) library(plotly) p <- plot_ly( x = data$quality.cut, y = data$alcohol, name = "alcohol", type = "bar" ) ########################################### source("http://goo.gl/UUyEzD") outlierKD(dataS, dataS$fixed.acidity) outlierKD(dataS, dataS$volatile.acidity) outlierKD(dataNorm, dataNorm$citric.acid) outlierKD(dataNorm, dataNorm$residual.sugar) outlierKD(dataNorm, dataNorm$chlorides) outlierKD(dataNorm, dataNorm$free.sulfur.dioxide) outlierKD(dataNorm, dataNorm$pH) outlierKD(dataNorm, dataNorm$sulphates) outlierKD(dataNorm, dataNorm$alcohol) ## install.packages('outliers', dep = TRUE) library(outliers) dataS = data[1:11] remove_outliers <- function(x, na.rm = TRUE, ...) { qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...) H <- 1.5 * IQR(x, na.rm = na.rm) y <- x y[x < (qnt[1] - H)] <- mean(x)#NA y[x > (qnt[2] + H)] <- mean(x)#NA y } dataS$alcohol <- remove_outliers(dataS$alcohol) dataS$sulphates <- remove_outliers(dataS$sulphates) dataS$pH <- remove_outliers(dataS$pH) dataS$free.sulfur.dioxid <- remove_outliers(dataS$free.sulfur.dioxid) dataS$chlorides <- remove_outliers(dataS$chlorides) dataS$residual.sugar <- remove_outliers(dataS$residual.sugar) dataS$citric.acid <- remove_outliers(dataS$citric.acid) dataS$volatile.acidity <- remove_outliers(dataS$volatile.acidity) dataS$fixed.acidity <- remove_outliers(dataS$fixed.acidity) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= install.packages('modeest', dep = TRUE) library(modeest) install.packages('ggplot2', dep = TRUE) library(ggplot2) install.packages('corrplot', dep = TRUE) library('corrplot') install.packages('mclust', dep = TRUE) library(mclust) library('corrplot') library(ggplot2) library(modeest) library(mclust) setwd("C:/Users/Luis.O.A/Documents/USACH/Mineria de Datos/grupo 6 Wine Quality") data <- read.csv('winequality-red.csv', sep=';') ############ Estadistica Descriptiva ############ ######## Medida de Tendencias Centrales ## Media ## mean(data$fixed.acidity) 8.319637 mean(data$volatile.acidity) 0.5278205 mean(data$citric.acid) 0.2709756 mean(data$residual.sugar) 2.538806 mean(data$chlorides) 0.08746654 mean(data$free.sulfur.dioxide) 15.87492 mean(data$total.sulfur.dioxide) 46.46779 mean(data$density) 0.9967467 mean(data$pH) 3.311113 mean(data$sulphates) 0.6581488 mean(data$alcohol) 10.42298 ## Moda ## mlv(data$fixed.acidity, method = "mfv")[1] 7.2 mlv(data$volatile.acidity, method = "mfv")[1] 0.6 mlv(data$citric.acid, method = "mfv")[1] 0 mlv(data$residual.sugar, method = "mfv")[1] 2 mlv(data$chlorides, method = "mfv")[1] 0.08 mlv(data$free.sulfur.dioxide, method = "mfv")[1] 6 mlv(data$density, method = "mfv")[1] 0.9972 mlv(data$pH, method = "mfv")[1] 3.3 mlv(data$sulphates, method = "mfv")[1] 0.6 mlv(data$alcohol, method = "mfv")[1] 9.5 ## Mediana ## median(data$fixed.acidity) 7.9 median(data$volatile.acidity) 0.52 median(data$citric.acid) 0.26 median(data$residual.sugar) 2.2 median(data$chlorides) 0.079 median(data$free.sulfur.dioxide) 14 median(data$density) 0.99675 median(data$pH) 3.31 median(data$sulphates) 0.62 median(data$alcohol) 10.2 ######## Medidas de Dispersion ## Rango ## range(data$fixed.acidity) 4.6 15.9 range(data$volatile.acidity) 0.12 1.58 range(data$citric.acid) 0 1 range(data$residual.sugar) 0.9 15.5 range(data$chlorides) 0.012 0.611 range(data$free.sulfur.dioxide) 1 72 range(data$density) 0.99007 1.00369 range(data$pH) 2.74 4.01 range(data$sulphates) 0.33 2.00 range(data$alcohol) 8.4 14.9 summary(data)# Vista resumida de lo anteriormente visto. Seria util presentarlo en una tabla boxplot(data$nombre_variable)# grafico de caja por variable ## Cuartiles ## #El siguiente grafico sera muy util para explicr que incidencia tiene cada una de las variables e la calidad del vino. boxplot(data$nombre_variable ~ data$quality, xlab = "Calidad", ylab = "Acides Fijada", col = c("red")) ## Varianza ## var(data$fixed.acidity) 3.031416 var(data$volatile.acidity) 0.03206238 var(data$citric.acid) 0.03794748 var(data$residual.sugar) 1.987897 var(data$chlorides) 0.002215143 var(data$free.sulfur.dioxide) 109.4149 var(data$density) 3.562029e-06 var(data$pH) 0.02383518 var(data$sulphates) 0.02873262 var(data$alcohol) 1.135647 ## Distribucion ## #Nos servira para saber de manera mas grafica el rango y la mayor dispercion de cada una de las variables hist(data$Nombre_variable, main = "Nombre_variable", xlab = "Acides Fijada", col = "grey", breaks = 40, xlim = c(0,300)) ############ Estadistica Inferencial ############ ## Prueba de chi-cuadrado ## #NOTA: # "p-value" = 0 Alta dependencia entre variables # "p-value" = 1 Nula dependencia entre variables # "p-value" < 0.05 Alta dependencia entre variables (95% de dependencia) summary(table(data$fixed.acidity,data$quality)) p-value = 1.416e-13 summary(table(data$volatile.acidity,data$quality)) p-value = 3.429e-69 summary(table(data$citric.acid,data$quality)) p-value = 6.425e-19 summary(table(data$residual.sugar,data$quality)) p-value = 1.649e-28 summary(table(data$chlorides,data$quality)) p-value = 1.181e-34 summary(table(data$free.sulfur.dioxide,data$quality)) p-value = 0.2399 #Esta es la unica variable que tiene una baja dependencia summary(table(data$density,data$quality)) p-value = 7.547e-33 summary(table(data$pH,data$quality)) p-value = 8.719e-10 summary(table(data$sulphates,data$quality)) p-value = 2.382e-31 summary(table(data$alcohol,data$quality)) p-value = 5.345e-90 ## Correlacion ## M <- cor(data) corrplot(M, method="circle") ################################### Noralizacion de los datos ################################### # NOTA: # Cuando los rangos de las variables son muy dispares (ver "Rango") se aplica el siguiente modelo: # X1 = (X1 - Media X1) / (max X1 - min X1) dataNorm <- as.data.frame( scale(data[1:11] )) # no se normaliza la clase ##https://www.analyticsvidhya.com/blog/2015/10/inferential-descriptive-statistics-beginners-r/ BIC = mclustBIC(dataNorm) plot(BIC) Mclust(dataNorm, modelNames ="VVV", G = 3)$BIC Mclust(dataNorm, modelNames ="VVV", G = 4)$BIC Mclust(dataNorm, modelNames ="VVV", G = 5)$BIC Mclust(dataNorm, modelNames ="VVV", G = 6)$BIC Mclust(dataNorm, modelNames ="VVV", G = 7)$BIC Mclust(dataNorm, modelNames ="VEV", G = 3)$BIC Mclust(dataNorm, modelNames ="VEV", G = 4)$BIC Mclust(dataNorm, modelNames ="VEV", G = 5)$BIC Mclust(dataNorm, modelNames ="VEV", G = 6)$BIC Mclust(dataNorm, modelNames ="VEV", G = 7)$BIC Mclust(dataNorm, modelNames ="VVE", G = 3)$BIC Mclust(dataNorm, modelNames ="VVE", G = 4)$BIC Mclust(dataNorm, modelNames ="VVE", G = 5)$BIC Mclust(dataNorm, modelNames ="VVE", G = 6)$BIC Mclust(dataNorm, modelNames ="VVE", G = 7)$BIC # Mclust(dataNorm, prior = priorControl(functionName="defaultPrior", shrinkage=0.1), G = 4, modelNames ="VEV")$BIC # Comprabar el error de clasificacion m = Mclust(dataNorm, modelNames ="VVE", G = 7) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 7) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 6) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 5) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VEV", G = 4) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VVV", G = 4) classError(data$quality, m$classification)$errorRate m = Mclust(dataNorm, modelNames ="VVV", G = 7) classError(data$quality, m$classification)$errorRate ################################### Sin Noralizacion de los datos ################################### dataS = data[1:11] BIC = mclustBIC(dataS) plot(BIC) m1 = Mclust(dataS, modelNames ="VVE", G = 3) m2 = Mclust(dataS, modelNames ="VVE", G = 4) m3 = Mclust(dataS, modelNames ="VVE", G = 5) m4 = Mclust(dataS, modelNames ="VVE", G = 6) m5 = Mclust(dataS, modelNames ="EEV", G = 3) m6 = Mclust(dataS, modelNames ="EEV", G = 4) m7 = Mclust(dataS, modelNames ="EEV", G = 5) m8 = Mclust(dataS, modelNames ="EEV", G = 6) m9 = Mclust(dataS, modelNames ="VEV", G = 3) m10 = Mclust(dataS, modelNames ="VEV", G = 4) m11 = Mclust(dataS, modelNames ="VEV", G = 5) m12 = Mclust(dataS, modelNames ="VEV", G = 6) m13 = Mclust(dataS, modelNames ="EVV", G = 3) m14 = Mclust(dataS, modelNames ="EVV", G = 4) m15 = Mclust(dataS, modelNames ="EVV", G = 5) m16 = Mclust(dataS, modelNames ="EVV", G = 6) m1$BIC m2$BIC m3$BIC m4$BIC m5$BIC m6$BIC m7$BIC m8$BIC m9$BIC m10$BIC m11$BIC m12$BIC m13$BIC m14$BIC m15$BIC m16$BIC # Comprabar el error de clasificacion classError(data$quality, m4$classification)$errorRate classError(data$quality, m3$classification)$errorRate classError(data$quality, m12$classification)$errorRate classError(data$quality, m2$classification)$errorRate classError(data$quality, m11$classification)$errorRate classError(data$quality, m15$classification)$errorRate classError(data$quality, m14$classification)$errorRate classError(data$quality, m10$classification)$errorRate # Mejor Cluster -> m14 # Grafico de clusters drmod <- MclustDR(m14, lambda = 1) plot(drmod, what = "contour") plot(drmod, what = "boundaries", ngrid = 200) #Grafica de densidad plot(drmod, what = "density", type = "persp", theta = -25, phi = 20, border = adjustcolor(grey(0.1), alpha.f = 0.3)) table(data$quality, m14$classification) ##comprobar ERRORES segun quality ######################################## install.packages('plotly', dep = TRUE) # segun calidad data$quality.cut <- cut(data$quality, breaks = c(0,4,6,10)) table(data$quality.cut, m14$classification) # segun pH table(cut(data$pH, breaks = c(2.5, 3, 3.5, 4)), m14$classification) library(plotly) p <- plot_ly( x = data$quality.cut, y = data$pH, name = "pH", type = "bar" ) # segun acides citrica table(cut(data$citric.acid, breaks = c(0, 0.25, 0.5, 0.75, 1)), m14$classification) library(plotly) p <- plot_ly( x = data$quality.cut, y = data$citric.acid, name = "citric.acid", type = "bar" ) # segun alcohol table(cut(data$alcohol, breaks = c(8, 9, 10, 11, 12, 13 ,14, 15)), m14$classification) library(plotly) p <- plot_ly( x = data$quality.cut, y = data$alcohol, name = "alcohol", type = "bar" ) ########################################### source("http://goo.gl/UUyEzD") outlierKD(dataS, dataS$fixed.acidity) outlierKD(dataS, dataS$volatile.acidity) outlierKD(dataNorm, dataNorm$citric.acid) outlierKD(dataNorm, dataNorm$residual.sugar) outlierKD(dataNorm, dataNorm$chlorides) outlierKD(dataNorm, dataNorm$free.sulfur.dioxide) outlierKD(dataNorm, dataNorm$pH) outlierKD(dataNorm, dataNorm$sulphates) outlierKD(dataNorm, dataNorm$alcohol) ## install.packages('outliers', dep = TRUE) library(outliers) dataS = data[1:11] remove_outliers <- function(x, na.rm = TRUE, ...) { qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...) H <- 1.5 * IQR(x, na.rm = na.rm) y <- x y[x < (qnt[1] - H)] <- mean(x)#NA y[x > (qnt[2] + H)] <- mean(x)#NA y } dataS$alcohol <- remove_outliers(dataS$alcohol) dataS$sulphates <- remove_outliers(dataS$sulphates) dataS$pH <- remove_outliers(dataS$pH) dataS$free.sulfur.dioxid <- remove_outliers(dataS$free.sulfur.dioxid) dataS$chlorides <- remove_outliers(dataS$chlorides) dataS$residual.sugar <- remove_outliers(dataS$residual.sugar) dataS$citric.acid <- remove_outliers(dataS$citric.acid) dataS$volatile.acidity <- remove_outliers(dataS$volatile.acidity) dataS$fixed.acidity <- remove_outliers(dataS$fixed.acidity) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep>import os #FORZAR USO DE CPU os.environ['CUDA_VISIBLE_DEVICES'] = '0' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import time import pandas as pd import numpy import matplotlib.pyplot as plt from keras import Sequential from keras.models import load_model, Model from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.initializers import glorot_uniform from keras.utils import to_categorical from keras.optimizers import Adam from keras import backend as K from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from pandas import DataFrame from pandas.plotting import table from math import sqrt, log, exp import math from joblib import Parallel, delayed import tensorflow as tf import gc from statistics import mean,stdev from functools import reduce from scipy import stats from numpy.random import seed from tensorflow import set_random_seed CPU_USAGE = 7 GPU_USAGE = 1 def create_dataset(nombre_sujeto, nombre_postura): PATH = ("C:/Users/Luis/Documents/DataScience/Tesis/Datos/SUJETOS/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(0, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) #Dar formato float a las señales PAMn, VFSCd = PAMn.astype('float32'), VFSCd.astype('float32') PAMn, VFSCd = numpy.array(PAMn), numpy.array(VFSCd) # Validacion Valanceada train_size = int(len(PAMn) * 0.5) test_size = len(PAMn) - train_size train_PAM, train_VFSCd = PAMn[0:train_size], VFSCd[0:train_size] test_PAM, test_VFSCd = PAMn[train_size:len(PAMn)], VFSCd[train_size:len(VFSCd)] # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] train_PAM = numpy.reshape(train_PAM, (train_PAM.shape[0], 1, train_PAM.shape[1])) test_PAM = numpy.reshape(test_PAM, (test_PAM.shape[0], 1, test_PAM.shape[1])) return train_PAM, train_VFSCd, test_PAM, test_VFSCd def correlation_coefficient_loss_metric(y_true, y_pred): x = y_true y = y_pred mx = K.mean(x) my = K.mean(y) xm, ym = x-mx, y-my r_num = K.sum(tf.multiply(xm,ym)) r_den = K.sqrt(tf.multiply(K.sum(K.square(xm)), K.sum(K.square(ym)))) r = r_num / r_den r = K.maximum(K.minimum(r, 1.0), -1.0) return 1 - K.square(r) # fit an LSTM network to training data def fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout): ret_seq = False if hidden_layers > 1: ret_seq = True model = Sequential() model.add(LSTM(neurons, batch_input_shape=(batch_size, trainX.shape[1], trainX.shape[2]), return_sequences=ret_seq, stateful=True, recurrent_activation=activation, recurrent_dropout=dropout)) for i in range (hidden_layers-1): if i == (hidden_layers-2): ret_seq = False model.add(LSTM(neurons, return_sequences=ret_seq, stateful = True, recurrent_activation=activation, recurrent_dropout=dropout)) model.add(Dense(trainX.shape[1], activation=activation)) model.compile(loss='mean_squared_error', optimizer=optimization) for i in range(epochs): model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=0, shuffle=False) model.reset_states() return model #Evaluate the Model def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast # report performance rmse = stats.pearsonr(Y[:,0], output[:,0]) return rmse # Guardar en formato PNG los resultados def save_results(results, nombre_archivo_resultados): desc = results.describe() #create a subplot without frame plot = plt.subplot(111, frame_on=False) #remove axis plot.xaxis.set_visible(False) plot.yaxis.set_visible(False) #create the table plot and position it in the upper left corner table(plot, desc,loc='upper right') #save the plot as a png file plt.savefig('desc_%s.png'%(nombre_archivo_resultados)) plt.close() results.boxplot() plt.savefig('boxplot_%s.png'%(nombre_archivo_resultados)) plt.close() # run a repeated experiment def experiment(trainX, trainY, testX, testY, repeats, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout): # run experiment lista_z = list() repetir_error = 0 i = 1 del_level_hyp = False while i <= repeats: # fit the model use_cpu_gpu() lstm_model = fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, hidden_layers, neurons, dropout) # report performance r = evaluate(lstm_model, testX, testY, batch_size)[0] if math.isnan(r) and repetir_error < 3: repetir_error = repetir_error + 1 if repetir_error == 3: del_level_hyp = True break else: if repetir_error != 3: lista_z.append(fisher_transform(r)) repetir_error = 0 i = i + 1 K.clear_session() del lstm_model gc.collect() if del_level_hyp: mean_z = float('nan') mean_corr = float('nan') else: mean_z = reduce(lambda x, y: x + y, lista_z) / len(lista_z) mean_corr = inverse_fisher_transform(mean_z) print('batch_size=%d, neurons=%d, hidden_layers=%d, dropout=%.1f, epochs=%d, optimization=%s, activation=%s:::::::::: RESULT CORR=%.3f, RESULT Z=%.3f' % (batch_size, neurons, hidden_layers, dropout, epochs, optimization, activation, mean_corr, mean_z)) return mean_corr, mean_z #Transfomracion de Fisher def fisher_transform(r): z = 0.5*log((1+r)/(1-r)) return z def inverse_fisher_transform(z): r = (exp(2*z)-1)/(exp(2*z)+1) return r def use_cpu_gpu(): config = tf.ConfigProto(intra_op_parallelism_threads=10, inter_op_parallelism_threads=10, allow_soft_placement=True, device_count = {'CPU' : CPU_USAGE, 'GPU' : GPU_USAGE} ) #config.gpu_options.allow_growth = True session = tf.Session(config=config) K.set_session(session) def run_experiment(experimento, sujeto, postura, balance, trainX, trainY, testX, testY, hyperparameter, batch_size=[2], epochs=[10], optimization=["RMSprop"], activation=["tanh"], hidden_layers=[2], neurons=[10], dropout=[0.9]): #take time t0 = time.time() print("################################################################################### " + hyperparameter) columnas = ['batch_size','neurons','hidden_layers','dropout','epochs','optimization','activation','CORRELATION','FISHER'] filas = len(batch_size) * len(epochs) * len(optimization) * len(activation) * len(hidden_layers) * len(neurons) * len(dropout) results = numpy.chararray((filas,9), itemsize=40) row = 0 repeats = 10 best_result = -1 best_row = 0 for b in batch_size: for e in epochs: for o in optimization: for a in activation: for h in hidden_layers: for n in neurons: for d in dropout: mean_corr, mean_z = experiment(trainX, trainY, testX, testY, repeats, b, e, o, a, h, n, d) results[row][0] = b results[row][1] = n results[row][2] = h results[row][3] = d results[row][4] = e results[row][5] = o results[row][6] = a results[row][7] = mean_corr results[row][8] = mean_z if best_result <= mean_corr: best_result = mean_corr best_row = row row = row + 1 df = pd.DataFrame(results, columns=columnas) df = df.sort_values(by='CORRELATION', ascending=False) print(df) nombre_archivo = sujeto+'_'+postura+'/Sujeto_Posicion_'+hyperparameter+'_'+str(balance)+'.xlsx' writer = pd.ExcelWriter('C:/Users/Luis/Documents/DataScience/Tesis/Resultados/Fundamentacion Ajuste Modelo/Resultados_'+experimento+'/'+nombre_archivo) df.to_excel(writer,'Resultados') writer.save() print('################################################################################### Archivo |||'+nombre_archivo+'||| Creado') print ('###################################################################################',time.time() - t0, "segundos tardo") if hyperparameter == "epochs": return results[best_row][4] if hyperparameter == "dropout": return results[best_row][3] if hyperparameter == "activation": return results[best_row][6].decode("utf-8") if hyperparameter == "optimization": return results[best_row][5].decode("utf-8") if hyperparameter == "neurons": return results[best_row][1] if hyperparameter == "batch_size": return results[best_row][0] if hyperparameter == "hidden_layers": return results[best_row][2] if hyperparameter == "deep_network": return [int(results[best_row][2])],[int(results[best_row][1])],[str(results[best_row][6].decode("utf-8"))] def run_rango (sujeto, postura, balance): print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('++++++++++++++++++++++++++++++++++++++ Sujeto: ' + sujeto + ' Posicion: ' + postura + ' Balance: ' + str(balance)) # load dataset # split into input (X) and output (Y) variables train_PAM, train_VFSCd, test_PAM, test_VFSCd = create_dataset(sujeto, postura) if balance == 2: train_PAM_temp = train_PAM train_PAM = test_PAM test_PAM = train_PAM_temp del train_PAM_temp train_VFSCd_temp = train_VFSCd train_VFSCd = test_VFSCd test_VFSCd = train_VFSCd_temp del train_VFSCd_temp ################################################################################### batch_size batch_size = [] for i in range(1,train_PAM.shape[0]+1): if (train_PAM.shape[0]%i)==0 and i>1: batch_size.append(i) batch_size_result = [int(run_experiment('Rango', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="batch_size", batch_size=batch_size))] batch_size_result = [198] ################################################################################### neurons #neurons = [10,20,30,40,50,60,70,80,90,100] #neurons_result = [int(run_experiment('Rango', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="neurons", neurons=neurons, batch_size=batch_size_result))] ################################################################################### dropout dropout = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] dropout_result = [float(run_experiment('Rango', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="dropout", dropout=dropout, batch_size=batch_size_result))] ################################################################################### deep network (hidden_layers, neurons, activation) hidden_layers = [2, 3, 4, 5] neurons = [10,20,30,40,50,60,70,80,90,100] activation = ['softplus', 'softsign', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear'] hidden_layers_result, neurons_result, activation_result = run_experiment('Rango', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="deep_network", hidden_layers=hidden_layers, neurons=neurons, activation=activation, dropout=dropout_result, batch_size=batch_size_result) ################################################################################### activation #activation = ['softplus', 'softsign', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear'] #activation_result = [str(run_experiment('Rango', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="activation", activation=activation, dropout=dropout_result, neurons=neurons_result, batch_size=batch_size_result))] #activation_result = ['tanh']#Es el unico que puede modelar respuesta a escalones (de 2 capas) ################################################################################### optimization optimization = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam'] optimization_result = [str(run_experiment('Rango', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="optimization", optimization=optimization, hidden_layers=hidden_layers_result, activation=activation_result, dropout=dropout_result, neurons=neurons_result, batch_size=batch_size_result))] ################################################################################### epochs epochs = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] epochs_result = [int(run_experiment('Rango', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="epochs", epochs=epochs, optimization=optimization_result, hidden_layers=hidden_layers_result, activation=activation_result, dropout=dropout_result, neurons=neurons_result, batch_size=batch_size_result))] def run_hiperparametro (sujeto, postura, balance): print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++') print('++++++++++++++++++++++++++++++++++++++ Sujeto: ' + sujeto + ' Posicion: ' + postura + ' Balance: ' + str(balance)) # load dataset # split into input (X) and output (Y) variables train_PAM, train_VFSCd, test_PAM, test_VFSCd = create_dataset(sujeto, postura) if balance == 2: train_PAM_temp = train_PAM train_PAM = test_PAM test_PAM = train_PAM_temp del train_PAM_temp train_VFSCd_temp = train_VFSCd train_VFSCd = test_VFSCd test_VFSCd = train_VFSCd_temp del train_VFSCd_temp ################################################################################### Base run_experiment('Hiperparametro', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="Base") ################################################################################### epochs epochs = [10, 20, 30, 40, 50] run_experiment('Hiperparametro', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="epochs", epochs=epochs) ################################################################################### activation activation = ['softplus', 'softsign', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear'] run_experiment('Hiperparametro', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="activation", activation=activation) ################################################################################### optimization optimization = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam'] run_experiment('Hiperparametro', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="optimization", optimization=optimization) ################################################################################### neurons neurons = [10,20,30,40,50,60,70,80,90,100] run_experiment('Hiperparametro', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="neurons", neurons=neurons) ################################################################################### batch_size batch_size = [] for i in range(1,train_PAM.shape[0]+1): if (train_PAM.shape[0]%i)==0: batch_size.append(i) run_experiment('Hiperparametro', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="batch_size", batch_size=batch_size) ################################################################################### hidden_layers hidden_layers = [2, 3, 4, 5] run_experiment('Hiperparametro', sujeto, postura, balance, train_PAM, train_VFSCd, test_PAM, test_VFSCd, hyperparameter="hidden_layers", hidden_layers=hidden_layers) #Repitable Experiment seed(1) set_random_seed(2) run_rango(sujeto='AC', postura='ACOSTADO', balance=1) #run_rango(sujeto='AC', postura='ACOSTADO', balance=2) #run_rango(sujeto='DM', postura='PIE', balance=1) #run_rango(sujeto='DM', postura='PIE', balance=2) #run_rango(sujeto='PC', postura='SENTADO', balance=1) #run_rango(sujeto='PC', postura='SENTADO', balance=2) #run_rango(sujeto='AV', postura='ACOSTADO', balance=1) #run_rango(sujeto='AV', postura='ACOSTADO', balance=2) #run_rango(sujeto='CC', postura='PIE', balance=1) #run_rango(sujeto='CC', postura='PIE', balance=2) #run_rango(sujeto='CS', postura='SENTADO', balance=1) #run_rango(sujeto='CS', postura='SENTADO', balance=2) <file_sep><<<<<<< HEAD <<<<<<< HEAD library(nnet) #https://www.kaggle.com/vmalyi/run-or-walk/data setwd("C:/Users/Luis.O.A/Documents/Charla ML/DataScience") wr <- read.csv('dataset.csv', sep=',') wr <- wr[,-c(1,2,3)] normalize <- function(x) { x = (x-min(x))/(max(x)-min(x)) x } #hist(wine$fixed.acidity,breaks=10, xlab="wine",col="lightblue", main="") wr$activity <- factor(wr$activity, levels=sort(unique(wr$activity))) wr$wrist <- normalize(wr$wrist) wr$acceleration_x <- normalize(wr$acceleration_x) wr$acceleration_y <- normalize(wr$acceleration_y) wr$acceleration_z <- normalize(wr$acceleration_z) wr$gyro_x <- normalize(wr$gyro_x) wr$gyro_y <- normalize(wr$gyro_y) wr$gyro_z <- normalize(wr$gyro_z) set.seed(100) trainingRows <- sample(1:nrow(wr), 0.7*nrow(wr)) training <- wr[trainingRows, ] test <- wr[-trainingRows, -2] test.activity <- wr[-trainingRows, -c(1,3,4,5,6,7, 8)]#Solo la clase model <- multinom(activity ~ ., data = training) ##Prueba de clasificacion con las 10 primeras instancias predicted=predict(model,wr[750:760,], 'probs') predicted ##Verificar las clases wr[750:760,] ############################################# predicted=predict(model,test) result <- table(predicted, test.activity) #Correctos (result[1,1] + result[2,2]) * 100 / (result[1,1] + result[1,2] + result[2,1] + result[2,2]) #86.12334 #Error mean(as.character(predicted) != as.character(test.activity)) * 100 #13.87666 Precision <- as.numeric(result[1,1])/(as.numeric(result[1,1]) + as.numeric(result[1,2])) #Recall Recall <- as.numeric(result[1,1])/(as.numeric(result[1,1]) + as.numeric(result[2,1])) ##Fscore Fscore = (2*Precision*Recall)/(Precision+Recall) print("Fscore") print(Fscore) print("Precision") print(Precision) print("Recall") print(Recall) ======= library(nnet) #https://www.kaggle.com/vmalyi/run-or-walk/data setwd("C:/Users/Luis.O.A/Documents/Charla ML/DataScience") wr <- read.csv('dataset.csv', sep=',') wr <- wr[,-c(1,2,3)] normalize <- function(x) { x = (x-min(x))/(max(x)-min(x)) x } #hist(wine$fixed.acidity,breaks=10, xlab="wine",col="lightblue", main="") wr$activity <- factor(wr$activity, levels=sort(unique(wr$activity))) wr$wrist <- normalize(wr$wrist) wr$acceleration_x <- normalize(wr$acceleration_x) wr$acceleration_y <- normalize(wr$acceleration_y) wr$acceleration_z <- normalize(wr$acceleration_z) wr$gyro_x <- normalize(wr$gyro_x) wr$gyro_y <- normalize(wr$gyro_y) wr$gyro_z <- normalize(wr$gyro_z) set.seed(100) trainingRows <- sample(1:nrow(wr), 0.7*nrow(wr)) training <- wr[trainingRows, ] test <- wr[-trainingRows, -2] test.activity <- wr[-trainingRows, -c(1,3,4,5,6,7, 8)]#Solo la clase model <- multinom(activity ~ ., data = training) ##Prueba de clasificacion con las 10 primeras instancias predicted=predict(model,wr[750:760,], 'probs') predicted ##Verificar las clases wr[750:760,] ############################################# predicted=predict(model,test) result <- table(predicted, test.activity) #Correctos (result[1,1] + result[2,2]) * 100 / (result[1,1] + result[1,2] + result[2,1] + result[2,2]) #86.12334 #Error mean(as.character(predicted) != as.character(test.activity)) * 100 #13.87666 Precision <- as.numeric(result[1,1])/(as.numeric(result[1,1]) + as.numeric(result[1,2])) #Recall Recall <- as.numeric(result[1,1])/(as.numeric(result[1,1]) + as.numeric(result[2,1])) ##Fscore Fscore = (2*Precision*Recall)/(Precision+Recall) print("Fscore") print(Fscore) print("Precision") print(Precision) print("Recall") print(Recall) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= library(nnet) #https://www.kaggle.com/vmalyi/run-or-walk/data setwd("C:/Users/Luis.O.A/Documents/Charla ML/DataScience") wr <- read.csv('dataset.csv', sep=',') wr <- wr[,-c(1,2,3)] normalize <- function(x) { x = (x-min(x))/(max(x)-min(x)) x } #hist(wine$fixed.acidity,breaks=10, xlab="wine",col="lightblue", main="") wr$activity <- factor(wr$activity, levels=sort(unique(wr$activity))) wr$wrist <- normalize(wr$wrist) wr$acceleration_x <- normalize(wr$acceleration_x) wr$acceleration_y <- normalize(wr$acceleration_y) wr$acceleration_z <- normalize(wr$acceleration_z) wr$gyro_x <- normalize(wr$gyro_x) wr$gyro_y <- normalize(wr$gyro_y) wr$gyro_z <- normalize(wr$gyro_z) set.seed(100) trainingRows <- sample(1:nrow(wr), 0.7*nrow(wr)) training <- wr[trainingRows, ] test <- wr[-trainingRows, -2] test.activity <- wr[-trainingRows, -c(1,3,4,5,6,7, 8)]#Solo la clase model <- multinom(activity ~ ., data = training) ##Prueba de clasificacion con las 10 primeras instancias predicted=predict(model,wr[750:760,], 'probs') predicted ##Verificar las clases wr[750:760,] ############################################# predicted=predict(model,test) result <- table(predicted, test.activity) #Correctos (result[1,1] + result[2,2]) * 100 / (result[1,1] + result[1,2] + result[2,1] + result[2,2]) #86.12334 #Error mean(as.character(predicted) != as.character(test.activity)) * 100 #13.87666 Precision <- as.numeric(result[1,1])/(as.numeric(result[1,1]) + as.numeric(result[1,2])) #Recall Recall <- as.numeric(result[1,1])/(as.numeric(result[1,1]) + as.numeric(result[2,1])) ##Fscore Fscore = (2*Precision*Recall)/(Precision+Recall) print("Fscore") print(Fscore) print("Precision") print(Precision) print("Recall") print(Recall) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep><<<<<<< HEAD <<<<<<< HEAD import os import csv import math import numpy as np import pandas as pd from scipy import stats from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import silhouette_score from sklearn import preprocessing from matplotlib import pyplot as plt from scipy import signal class Signal: PATH = "C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/CO2_HIPERCAPNIA" def __init__(self, filePath): self.filePath = filePath def reesampling(self, var): x_resampled = signal.resample(var, math.ceil(var.shape[0]*0.26675603217158176943699731903485)) return x_resampled def process(self): X = pd.read_csv(self.filePath, sep=" ") VFSCd = self.reesampling(X['VFSCd']) VFSCi = self.reesampling(X['VFSCi']) PAMn = self.reesampling(X['PAMn']) reesampled_data = zip(VFSCd,VFSCi, PAMn) with open(self.filePath[:(len(self.filePath)-3)] + "csv", 'w', newline='') as f: writer = csv.writer(f, delimiter='\t') writer.writerow(["VFSCd", "VFSCi", "PAMn"]) writer.writerows(reesampled_data) def run_signal(): listOfFolders = os.listdir(Signal.PATH) folderPath = Signal.PATH for file in listOfFolders: filePath = folderPath+"/"+file signal = Signal(filePath) signal.process() class Stair: def __init__(self, file_stair): self.file_stair = file_stair def reesampling(self, var): x_resampled = signal.resample(var, math.ceil(var.shape[0]*0.26533333333333333333333333333333))#199 ==> 50% return x_resampled def process(self): X = pd.read_csv(self.file_stair, sep=" ") escalon = self.reesampling(X['ESCALON']) reesampled_data = zip(escalon) with open(self.file_stair[:(len(self.file_stair)-4)] + "_04.csv", 'w', newline='') as f: writer = csv.writer(f, delimiter='\t') writer.writerow(["ESCALON"]) writer.writerows(reesampled_data) def run_stair(): file_stair = "C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/esc.csv" stair = Stair(file_stair) stair.process() ======= import os import csv import math import numpy as np import pandas as pd from scipy import stats from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import silhouette_score from sklearn import preprocessing from matplotlib import pyplot as plt from scipy import signal class Signal: PATH = "C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/CO2_HIPERCAPNIA" def __init__(self, filePath): self.filePath = filePath def reesampling(self, var): x_resampled = signal.resample(var, math.ceil(var.shape[0]*0.26675603217158176943699731903485)) return x_resampled def process(self): X = pd.read_csv(self.filePath, sep=" ") VFSCd = self.reesampling(X['VFSCd']) VFSCi = self.reesampling(X['VFSCi']) PAMn = self.reesampling(X['PAMn']) reesampled_data = zip(VFSCd,VFSCi, PAMn) with open(self.filePath[:(len(self.filePath)-3)] + "csv", 'w', newline='') as f: writer = csv.writer(f, delimiter='\t') writer.writerow(["VFSCd", "VFSCi", "PAMn"]) writer.writerows(reesampled_data) def run_signal(): listOfFolders = os.listdir(Signal.PATH) folderPath = Signal.PATH for file in listOfFolders: filePath = folderPath+"/"+file signal = Signal(filePath) signal.process() class Stair: def __init__(self, file_stair): self.file_stair = file_stair def reesampling(self, var): x_resampled = signal.resample(var, math.ceil(var.shape[0]*0.26533333333333333333333333333333))#199 ==> 50% return x_resampled def process(self): X = pd.read_csv(self.file_stair, sep=" ") escalon = self.reesampling(X['ESCALON']) reesampled_data = zip(escalon) with open(self.file_stair[:(len(self.file_stair)-4)] + "_04.csv", 'w', newline='') as f: writer = csv.writer(f, delimiter='\t') writer.writerow(["ESCALON"]) writer.writerows(reesampled_data) def run_stair(): file_stair = "C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/esc.csv" stair = Stair(file_stair) stair.process() >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= import os import csv import math import numpy as np import pandas as pd from scipy import stats from sklearn.cluster import KMeans from sklearn.decomposition import PCA import matplotlib.pyplot as plt import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics import silhouette_score from sklearn import preprocessing from matplotlib import pyplot as plt from scipy import signal class Signal: PATH = "C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/CO2_HIPERCAPNIA" def __init__(self, filePath): self.filePath = filePath def reesampling(self, var): x_resampled = signal.resample(var, math.ceil(var.shape[0]*0.26675603217158176943699731903485)) return x_resampled def process(self): X = pd.read_csv(self.filePath, sep=" ") VFSCd = self.reesampling(X['VFSCd']) VFSCi = self.reesampling(X['VFSCi']) PAMn = self.reesampling(X['PAMn']) reesampled_data = zip(VFSCd,VFSCi, PAMn) with open(self.filePath[:(len(self.filePath)-3)] + "csv", 'w', newline='') as f: writer = csv.writer(f, delimiter='\t') writer.writerow(["VFSCd", "VFSCi", "PAMn"]) writer.writerows(reesampled_data) def run_signal(): listOfFolders = os.listdir(Signal.PATH) folderPath = Signal.PATH for file in listOfFolders: filePath = folderPath+"/"+file signal = Signal(filePath) signal.process() class Stair: def __init__(self, file_stair): self.file_stair = file_stair def reesampling(self, var): x_resampled = signal.resample(var, math.ceil(var.shape[0]*0.26533333333333333333333333333333))#199 ==> 50% return x_resampled def process(self): X = pd.read_csv(self.file_stair, sep=" ") escalon = self.reesampling(X['ESCALON']) reesampled_data = zip(escalon) with open(self.file_stair[:(len(self.file_stair)-4)] + "_04.csv", 'w', newline='') as f: writer = csv.writer(f, delimiter='\t') writer.writerow(["ESCALON"]) writer.writerows(reesampled_data) def run_stair(): file_stair = "C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/esc.csv" stair = Stair(file_stair) stair.process() >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 run_signal()<file_sep><<<<<<< HEAD <<<<<<< HEAD from __future__ import print_function import pandas as pd import numpy import matplotlib.pyplot as plt import math from keras.models import load_model, Model, Sequential from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.initializers import glorot_uniform from keras.utils import to_categorical from keras.optimizers import Adam from keras import backend as K from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from pandas import DataFrame from pandas.plotting import table from math import sqrt from joblib import Parallel, delayed import tensorflow as tf from scipy import stats class Entrenamiento: ''' #Por batch def correlation_coefficient_loss(y_true, y_pred): fsp = y_pred - K.mean(y_pred) #being K.mean a scalar here, it will be automatically subtracted from all elements in y_pred fst = y_true - K.mean(y_true) devP = K.std(y_pred) devT = K.std(y_true) return K.mean(fsp*fst)/(devP*devT) #Por cada ejemplo def correlation_coefficient_loss(y_true, y_pred): #original shapes: (batch, 10) fsp = y_pred - K.mean(y_pred,axis=0) #you take the mean over the batch, keeping the features separate. fst = y_true - K.mean(y_true,axis=0) #mean shape: (1,10) #fst shape keeps (batch,10) devP = K.std(y_pred,axis=0) devt = K.std(y_true,axis=0) #dev shape: (1,10) #mean shape: (1,10), making all tensors in the expression be (1,10). #sum is only necessary because we need a single loss value return K.sum(K.mean(fsp*fst,axis=0)/(devP*devT)) ''' def correlation_coefficient_loss(y_true, y_pred): x = y_true y = y_pred mx = K.mean(x) my = K.mean(y) xm, ym = x-mx, y-my r_num = K.sum(tf.multiply(xm,ym)) r_den = K.sqrt(tf.multiply(K.sum(K.square(xm)), K.sum(K.square(ym)))) r = r_num / r_den r = K.maximum(K.minimum(r, 1.0), -1.0) return 1 - K.square(r) # fit an LSTM network to training data def fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, dropout, hidden_layers, neurons): model = Sequential() model.add(LSTM(neurons, batch_input_shape=(batch_size, trainX.shape[1], trainX.shape[2]), stateful=True, return_sequences=True)) for i in range (hidden_layers-1): model.add(LSTM(neurons, batch_input_shape=(batch_size, trainX.shape[1], trainX.shape[2]), stateful=True)) model.add(Dropout(dropout)) model.add(Dense(1, activation=activation)) model.compile(loss=Entrenamiento.correlation_coefficient_loss, optimizer=optimization) for i in range(epochs): model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False) model.reset_states() return model #Evaluate the Model def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast yhat = list() for i in range(len(output)): # store forecast yhat.append(output[i,0]) # report performance rmse = stats.pearsonr(Y[:,0], yhat) return rmse # Guardar en formato PNG los resultados def save_results(results, nombre_archivo_resultados): desc = results.describe() #create a subplot without frame plot = plt.subplot(111, frame_on=False) #remove axis plot.xaxis.set_visible(False) plot.yaxis.set_visible(False) #create the table plot and position it in the upper left corner table(plot, desc,loc='upper right') #save the plot as a png file plt.savefig('desc_%s.png'%(nombre_archivo_resultados)) plt.close() results.boxplot() plt.savefig('boxplot_%s.png'%(nombre_archivo_resultados)) plt.close() # run a repeated experiment def experiment(trainX, trainY, testX, testY, repeats, batch_size, epochs, optimization, activation, dropout, hidden_layers, neurons): # run experiment error_scores = list() for r in range(repeats): # fit the model lstm_model = Entrenamiento.fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, dropout, hidden_layers, neurons) lstm_model.predict(trainX, batch_size=batch_size) # report performance rmse = Entrenamiento.evaluate(lstm_model, testX, testY, batch_size) print('%d) Test RMSE: %.3f' % (r+1, rmse)) error_scores.append(neurons) return error_scores #QUITAR PARALEL DE ESTE METODO PARA CORRER LAS PRUEBAS def run_experiment(trainX, trainY, testX, testY, batch_size=[1], epochs=[1], optimization=["adam"], activation=["sigmoid"], dropout=[0], hidden_layers=[1], neurons=[1]): results = [] results_data_frame = DataFrame() repeats = 1 if (len(batch_size) > 1): for b in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, b, epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) if (len(epochs) > 1): for e in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], e, optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) if (len(optimization) > 1): for o in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], o, activation[0], dropout[0], hidden_layers[0], neurons[0]) if (len(activation) > 1): for a in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], a, dropout[0], hidden_layers[0], neurons[0]) if (len(dropout) > 1): for d in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], d, hidden_layers[0], neurons[0]) if (len(hidden_layers) > 1): for h in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], h, neurons[0]) if (len(neurons) > 1): for n in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], n) ''' if (len(batch_size) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, b, epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) for b in batch_size) elif (len(epochs) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], e, optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) for e in epochs) elif (len(optimization) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], o, activation[0], dropout[0], hidden_layers[0], neurons[0]) for o in optimization) elif (len(activation) > 1): results = Parallel(n_jobs=4)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], a, dropout[0], hidden_layers[0], neurons[0]) for a in activation) elif (len(dropout) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], d, hidden_layers[0], neurons[0]) for d in dropout) elif (len(hidden_layers) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], h, neurons[0]) for h in hidden_layers) elif (len(neurons) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], n) for n in neurons) ''' for i in range(len(results)): results_data_frame[str(i)] = results[i] # summarize results print(results); #print(results_data_frame.describe()) # save boxplot #Entrenamiento.save_results(results_data_frame, "nombre_archivo") ########################################################################################################### nombre_sujeto = "AC" nombre_postura = "ACOSTADO" nombre_emisferio = "DERECHO" PATH = ("C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) # fix random seed for reproducibility numpy.random.seed(7) #Dar formato float a las señales PAMn, VFSCd = PAMn.astype('float32'), VFSCd.astype('float32') PAMn, VFSCd = numpy.array(PAMn), numpy.array(VFSCd) # Validacion Valanceada train_size = int(len(PAMn) * 0.75) test_size = len(PAMn) - train_size train_PAM, train_VFSCd = PAMn[0:train_size], VFSCd[0:train_size] test_PAM, test_VFSCd = PAMn[train_size:len(PAMn)], VFSCd[train_size:len(VFSCd)] # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] train_PAM = numpy.reshape(train_PAM, (train_PAM.shape[0], 1, train_PAM.shape[1])) test_PAM = numpy.reshape(test_PAM, (test_PAM.shape[0], 1, test_PAM.shape[1])) # create and fit the LSTM network ############################################################################################################################################################## ##Hyperparametros numpy.random.uniform(low=0.5, high=13.3, size=(5,)) ################# nombre_archivo_resultados = nombre_sujeto+"_"+nombre_postura+"_"+nombre_emisferio Entrenamiento.run_experiment(train_PAM, train_VFSCd, test_PAM, test_VFSCd, epochs = [2,3]) ############################################################################################################################################################## ########################################################################################################################### #random search #https://github.com/llSourcell/hyperparameter_optimization_strategies/blob/master/random_search.py Parallel(n_jobs=2)(delayed(sqrt)(i ** 2) for i in range(10)) ################# # Use scikit-learn to grid search the batch size and epochs import pandas as pd import numpy import keras.backend as K import tensorflow as tf import math from scipy import stats from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.wrappers.scikit_learn import KerasRegressor def correlation_coefficient_loss(y_true, y_pred): fsp = y_pred - K.mean(y_pred,axis=0) #you take the mean over the batch, keeping the features separate. fst = y_true - K.mean(y_true,axis=0) #mean shape: (1,10) #fst shape keeps (batch,10) devP = K.std(y_pred,axis=0) devT = K.std(y_true,axis=0) #dev shape: (1,10) return K.sum(K.mean(fsp*fst,axis=0)/(devP*devT)) # Function to create model, required for KerasClassifier def create_model(neurons=1): # create model model = Sequential() #model.add(LSTM(1, return_sequences=True)) model.add(LSTM(neurons)) model.add(Dense(1)) # Compile model model.compile(loss=correlation_coefficient_loss, optimizer='adam') return model def create_dataset(): nombre_sujeto = "AC" nombre_postura = "ACOSTADO" nombre_emisferio = "DERECHO" PATH = ("C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) # fix random seed for reproducibility numpy.random.seed(7) #Dar formato float a las señales PAMn, VFSCd, VFSCi = PAMn.astype('float32'), VFSCd.astype('float32'), VFSCi.astype('float32') PAMn, VFSCd, VFSCi = numpy.array(PAMn), numpy.array(VFSCd), numpy.array(VFSCi) # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] PAMn = numpy.reshape(PAMn, (PAMn.shape[0], 1, PAMn.shape[1])) return PAMn, VFSCd, VFSCi def run_experiment(hyperparam_grid): # create model model = KerasRegressor(build_fn=create_model, verbose=0) grid = GridSearchCV(estimator=model, param_grid=hyperparam_grid, cv=5, n_jobs=1) grid_result = grid.fit(X, Y1) # summarize results print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) means = grid_result.cv_results_['mean_test_score'] stds = grid_result.cv_results_['std_test_score'] params = grid_result.cv_results_['params'] for mean, stdev, param in zip(means, stds, params): print("%f (%f) with: %r" % (mean, stdev, param)) # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) # load dataset # split into input (X) and output (Y) variables X, Y1, Y2 = create_dataset() # define the grid search parameters ##Tuning the Number of Epochs ##Tuning the Batch Size ##Tuning the Number of Neurons ##Tuning the Number of Hidden Layers #################################################################### batch_size batch_size = [] for i in range(1,500): if (math.floor(X.shape[0] - (X.shape[0]/5))%i)==0: batch_size.append(i) hyperparam_grid = dict(batch_size=batch_size) run_experiment(hyperparam_grid) ######################################################################## epochs #epochs = numpy.random.randint(low=1, high=10000, size=(10,)) epochs = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000] hyperparam_grid = dict(epochs=epochs) run_experiment(hyperparam_grid) ####################################################################### neurons neurons = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] hyperparam_grid = dict(neurons=neurons) run_experiment(hyperparam_grid) ################################################################## dropout_rate dropout_rate = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] hyperparam_grid = dict(dropout_rate=dropout_rate) run_experiment(hyperparam_grid) batch_size = [1] epochs = [100] neurons = [10] hyperparam_grid = dict(batch_size=batch_size, epochs=epochs, neurons=neurons) ======= from __future__ import print_function import pandas as pd import numpy import matplotlib.pyplot as plt import math from keras.models import load_model, Model, Sequential from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.initializers import glorot_uniform from keras.utils import to_categorical from keras.optimizers import Adam from keras import backend as K from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from pandas import DataFrame from pandas.plotting import table from math import sqrt from joblib import Parallel, delayed import tensorflow as tf from scipy import stats class Entrenamiento: ''' #Por batch def correlation_coefficient_loss(y_true, y_pred): fsp = y_pred - K.mean(y_pred) #being K.mean a scalar here, it will be automatically subtracted from all elements in y_pred fst = y_true - K.mean(y_true) devP = K.std(y_pred) devT = K.std(y_true) return K.mean(fsp*fst)/(devP*devT) #Por cada ejemplo def correlation_coefficient_loss(y_true, y_pred): #original shapes: (batch, 10) fsp = y_pred - K.mean(y_pred,axis=0) #you take the mean over the batch, keeping the features separate. fst = y_true - K.mean(y_true,axis=0) #mean shape: (1,10) #fst shape keeps (batch,10) devP = K.std(y_pred,axis=0) devt = K.std(y_true,axis=0) #dev shape: (1,10) #mean shape: (1,10), making all tensors in the expression be (1,10). #sum is only necessary because we need a single loss value return K.sum(K.mean(fsp*fst,axis=0)/(devP*devT)) ''' def correlation_coefficient_loss(y_true, y_pred): x = y_true y = y_pred mx = K.mean(x) my = K.mean(y) xm, ym = x-mx, y-my r_num = K.sum(tf.multiply(xm,ym)) r_den = K.sqrt(tf.multiply(K.sum(K.square(xm)), K.sum(K.square(ym)))) r = r_num / r_den r = K.maximum(K.minimum(r, 1.0), -1.0) return 1 - K.square(r) # fit an LSTM network to training data def fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, dropout, hidden_layers, neurons): model = Sequential() model.add(LSTM(neurons, batch_input_shape=(batch_size, trainX.shape[1], trainX.shape[2]), stateful=True, return_sequences=True)) for i in range (hidden_layers-1): model.add(LSTM(neurons, batch_input_shape=(batch_size, trainX.shape[1], trainX.shape[2]), stateful=True)) model.add(Dropout(dropout)) model.add(Dense(1, activation=activation)) model.compile(loss=Entrenamiento.correlation_coefficient_loss, optimizer=optimization) for i in range(epochs): model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False) model.reset_states() return model #Evaluate the Model def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast yhat = list() for i in range(len(output)): # store forecast yhat.append(output[i,0]) # report performance rmse = stats.pearsonr(Y[:,0], yhat) return rmse # Guardar en formato PNG los resultados def save_results(results, nombre_archivo_resultados): desc = results.describe() #create a subplot without frame plot = plt.subplot(111, frame_on=False) #remove axis plot.xaxis.set_visible(False) plot.yaxis.set_visible(False) #create the table plot and position it in the upper left corner table(plot, desc,loc='upper right') #save the plot as a png file plt.savefig('desc_%s.png'%(nombre_archivo_resultados)) plt.close() results.boxplot() plt.savefig('boxplot_%s.png'%(nombre_archivo_resultados)) plt.close() # run a repeated experiment def experiment(trainX, trainY, testX, testY, repeats, batch_size, epochs, optimization, activation, dropout, hidden_layers, neurons): # run experiment error_scores = list() for r in range(repeats): # fit the model lstm_model = Entrenamiento.fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, dropout, hidden_layers, neurons) lstm_model.predict(trainX, batch_size=batch_size) # report performance rmse = Entrenamiento.evaluate(lstm_model, testX, testY, batch_size) print('%d) Test RMSE: %.3f' % (r+1, rmse)) error_scores.append(neurons) return error_scores #QUITAR PARALEL DE ESTE METODO PARA CORRER LAS PRUEBAS def run_experiment(trainX, trainY, testX, testY, batch_size=[1], epochs=[1], optimization=["adam"], activation=["sigmoid"], dropout=[0], hidden_layers=[1], neurons=[1]): results = [] results_data_frame = DataFrame() repeats = 1 if (len(batch_size) > 1): for b in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, b, epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) if (len(epochs) > 1): for e in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], e, optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) if (len(optimization) > 1): for o in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], o, activation[0], dropout[0], hidden_layers[0], neurons[0]) if (len(activation) > 1): for a in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], a, dropout[0], hidden_layers[0], neurons[0]) if (len(dropout) > 1): for d in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], d, hidden_layers[0], neurons[0]) if (len(hidden_layers) > 1): for h in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], h, neurons[0]) if (len(neurons) > 1): for n in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], n) ''' if (len(batch_size) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, b, epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) for b in batch_size) elif (len(epochs) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], e, optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) for e in epochs) elif (len(optimization) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], o, activation[0], dropout[0], hidden_layers[0], neurons[0]) for o in optimization) elif (len(activation) > 1): results = Parallel(n_jobs=4)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], a, dropout[0], hidden_layers[0], neurons[0]) for a in activation) elif (len(dropout) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], d, hidden_layers[0], neurons[0]) for d in dropout) elif (len(hidden_layers) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], h, neurons[0]) for h in hidden_layers) elif (len(neurons) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], n) for n in neurons) ''' for i in range(len(results)): results_data_frame[str(i)] = results[i] # summarize results print(results); #print(results_data_frame.describe()) # save boxplot #Entrenamiento.save_results(results_data_frame, "nombre_archivo") ########################################################################################################### nombre_sujeto = "AC" nombre_postura = "ACOSTADO" nombre_emisferio = "DERECHO" PATH = ("C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) # fix random seed for reproducibility numpy.random.seed(7) #Dar formato float a las señales PAMn, VFSCd = PAMn.astype('float32'), VFSCd.astype('float32') PAMn, VFSCd = numpy.array(PAMn), numpy.array(VFSCd) # Validacion Valanceada train_size = int(len(PAMn) * 0.75) test_size = len(PAMn) - train_size train_PAM, train_VFSCd = PAMn[0:train_size], VFSCd[0:train_size] test_PAM, test_VFSCd = PAMn[train_size:len(PAMn)], VFSCd[train_size:len(VFSCd)] # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] train_PAM = numpy.reshape(train_PAM, (train_PAM.shape[0], 1, train_PAM.shape[1])) test_PAM = numpy.reshape(test_PAM, (test_PAM.shape[0], 1, test_PAM.shape[1])) # create and fit the LSTM network ############################################################################################################################################################## ##Hyperparametros numpy.random.uniform(low=0.5, high=13.3, size=(5,)) ################# nombre_archivo_resultados = nombre_sujeto+"_"+nombre_postura+"_"+nombre_emisferio Entrenamiento.run_experiment(train_PAM, train_VFSCd, test_PAM, test_VFSCd, epochs = [2,3]) ############################################################################################################################################################## ########################################################################################################################### #random search #https://github.com/llSourcell/hyperparameter_optimization_strategies/blob/master/random_search.py Parallel(n_jobs=2)(delayed(sqrt)(i ** 2) for i in range(10)) ################# # Use scikit-learn to grid search the batch size and epochs import pandas as pd import numpy import keras.backend as K import tensorflow as tf import math from scipy import stats from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.wrappers.scikit_learn import KerasRegressor def correlation_coefficient_loss(y_true, y_pred): fsp = y_pred - K.mean(y_pred,axis=0) #you take the mean over the batch, keeping the features separate. fst = y_true - K.mean(y_true,axis=0) #mean shape: (1,10) #fst shape keeps (batch,10) devP = K.std(y_pred,axis=0) devT = K.std(y_true,axis=0) #dev shape: (1,10) return K.sum(K.mean(fsp*fst,axis=0)/(devP*devT)) # Function to create model, required for KerasClassifier def create_model(neurons=1): # create model model = Sequential() #model.add(LSTM(1, return_sequences=True)) model.add(LSTM(neurons)) model.add(Dense(1)) # Compile model model.compile(loss=correlation_coefficient_loss, optimizer='adam') return model def create_dataset(): nombre_sujeto = "AC" nombre_postura = "ACOSTADO" nombre_emisferio = "DERECHO" PATH = ("C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) # fix random seed for reproducibility numpy.random.seed(7) #Dar formato float a las señales PAMn, VFSCd, VFSCi = PAMn.astype('float32'), VFSCd.astype('float32'), VFSCi.astype('float32') PAMn, VFSCd, VFSCi = numpy.array(PAMn), numpy.array(VFSCd), numpy.array(VFSCi) # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] PAMn = numpy.reshape(PAMn, (PAMn.shape[0], 1, PAMn.shape[1])) return PAMn, VFSCd, VFSCi def run_experiment(hyperparam_grid): # create model model = KerasRegressor(build_fn=create_model, verbose=0) grid = GridSearchCV(estimator=model, param_grid=hyperparam_grid, cv=5, n_jobs=1) grid_result = grid.fit(X, Y1) # summarize results print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) means = grid_result.cv_results_['mean_test_score'] stds = grid_result.cv_results_['std_test_score'] params = grid_result.cv_results_['params'] for mean, stdev, param in zip(means, stds, params): print("%f (%f) with: %r" % (mean, stdev, param)) # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) # load dataset # split into input (X) and output (Y) variables X, Y1, Y2 = create_dataset() # define the grid search parameters ##Tuning the Number of Epochs ##Tuning the Batch Size ##Tuning the Number of Neurons ##Tuning the Number of Hidden Layers #################################################################### batch_size batch_size = [] for i in range(1,500): if (math.floor(X.shape[0] - (X.shape[0]/5))%i)==0: batch_size.append(i) hyperparam_grid = dict(batch_size=batch_size) run_experiment(hyperparam_grid) ######################################################################## epochs #epochs = numpy.random.randint(low=1, high=10000, size=(10,)) epochs = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000] hyperparam_grid = dict(epochs=epochs) run_experiment(hyperparam_grid) ####################################################################### neurons neurons = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] hyperparam_grid = dict(neurons=neurons) run_experiment(hyperparam_grid) ################################################################## dropout_rate dropout_rate = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] hyperparam_grid = dict(dropout_rate=dropout_rate) run_experiment(hyperparam_grid) batch_size = [1] epochs = [100] neurons = [10] hyperparam_grid = dict(batch_size=batch_size, epochs=epochs, neurons=neurons) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= from __future__ import print_function import pandas as pd import numpy import matplotlib.pyplot as plt import math from keras.models import load_model, Model, Sequential from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.initializers import glorot_uniform from keras.utils import to_categorical from keras.optimizers import Adam from keras import backend as K from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from pandas import DataFrame from pandas.plotting import table from math import sqrt from joblib import Parallel, delayed import tensorflow as tf from scipy import stats class Entrenamiento: ''' #Por batch def correlation_coefficient_loss(y_true, y_pred): fsp = y_pred - K.mean(y_pred) #being K.mean a scalar here, it will be automatically subtracted from all elements in y_pred fst = y_true - K.mean(y_true) devP = K.std(y_pred) devT = K.std(y_true) return K.mean(fsp*fst)/(devP*devT) #Por cada ejemplo def correlation_coefficient_loss(y_true, y_pred): #original shapes: (batch, 10) fsp = y_pred - K.mean(y_pred,axis=0) #you take the mean over the batch, keeping the features separate. fst = y_true - K.mean(y_true,axis=0) #mean shape: (1,10) #fst shape keeps (batch,10) devP = K.std(y_pred,axis=0) devt = K.std(y_true,axis=0) #dev shape: (1,10) #mean shape: (1,10), making all tensors in the expression be (1,10). #sum is only necessary because we need a single loss value return K.sum(K.mean(fsp*fst,axis=0)/(devP*devT)) ''' def correlation_coefficient_loss(y_true, y_pred): x = y_true y = y_pred mx = K.mean(x) my = K.mean(y) xm, ym = x-mx, y-my r_num = K.sum(tf.multiply(xm,ym)) r_den = K.sqrt(tf.multiply(K.sum(K.square(xm)), K.sum(K.square(ym)))) r = r_num / r_den r = K.maximum(K.minimum(r, 1.0), -1.0) return 1 - K.square(r) # fit an LSTM network to training data def fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, dropout, hidden_layers, neurons): model = Sequential() model.add(LSTM(neurons, batch_input_shape=(batch_size, trainX.shape[1], trainX.shape[2]), stateful=True, return_sequences=True)) for i in range (hidden_layers-1): model.add(LSTM(neurons, batch_input_shape=(batch_size, trainX.shape[1], trainX.shape[2]), stateful=True)) model.add(Dropout(dropout)) model.add(Dense(1, activation=activation)) model.compile(loss=Entrenamiento.correlation_coefficient_loss, optimizer=optimization) for i in range(epochs): model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False) model.reset_states() return model #Evaluate the Model def evaluate(model, X, Y, batch_size): output = model.predict(X, batch_size=batch_size) # invert data transforms on forecast yhat = list() for i in range(len(output)): # store forecast yhat.append(output[i,0]) # report performance rmse = stats.pearsonr(Y[:,0], yhat) return rmse # Guardar en formato PNG los resultados def save_results(results, nombre_archivo_resultados): desc = results.describe() #create a subplot without frame plot = plt.subplot(111, frame_on=False) #remove axis plot.xaxis.set_visible(False) plot.yaxis.set_visible(False) #create the table plot and position it in the upper left corner table(plot, desc,loc='upper right') #save the plot as a png file plt.savefig('desc_%s.png'%(nombre_archivo_resultados)) plt.close() results.boxplot() plt.savefig('boxplot_%s.png'%(nombre_archivo_resultados)) plt.close() # run a repeated experiment def experiment(trainX, trainY, testX, testY, repeats, batch_size, epochs, optimization, activation, dropout, hidden_layers, neurons): # run experiment error_scores = list() for r in range(repeats): # fit the model lstm_model = Entrenamiento.fit_lstm(trainX, trainY, batch_size, epochs, optimization, activation, dropout, hidden_layers, neurons) lstm_model.predict(trainX, batch_size=batch_size) # report performance rmse = Entrenamiento.evaluate(lstm_model, testX, testY, batch_size) print('%d) Test RMSE: %.3f' % (r+1, rmse)) error_scores.append(neurons) return error_scores #QUITAR PARALEL DE ESTE METODO PARA CORRER LAS PRUEBAS def run_experiment(trainX, trainY, testX, testY, batch_size=[1], epochs=[1], optimization=["adam"], activation=["sigmoid"], dropout=[0], hidden_layers=[1], neurons=[1]): results = [] results_data_frame = DataFrame() repeats = 1 if (len(batch_size) > 1): for b in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, b, epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) if (len(epochs) > 1): for e in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], e, optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) if (len(optimization) > 1): for o in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], o, activation[0], dropout[0], hidden_layers[0], neurons[0]) if (len(activation) > 1): for a in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], a, dropout[0], hidden_layers[0], neurons[0]) if (len(dropout) > 1): for d in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], d, hidden_layers[0], neurons[0]) if (len(hidden_layers) > 1): for h in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], h, neurons[0]) if (len(neurons) > 1): for n in batch_size: Entrenamiento.experiment(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], n) ''' if (len(batch_size) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, b, epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) for b in batch_size) elif (len(epochs) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], e, optimization[0], activation[0], dropout[0], hidden_layers[0], neurons[0]) for e in epochs) elif (len(optimization) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], o, activation[0], dropout[0], hidden_layers[0], neurons[0]) for o in optimization) elif (len(activation) > 1): results = Parallel(n_jobs=4)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], a, dropout[0], hidden_layers[0], neurons[0]) for a in activation) elif (len(dropout) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], d, hidden_layers[0], neurons[0]) for d in dropout) elif (len(hidden_layers) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], h, neurons[0]) for h in hidden_layers) elif (len(neurons) > 1): results = Parallel(n_jobs=3)(delayed (Entrenamiento.experiment)(trainX, trainY, testX, testY, repeats, batch_size[0], epochs[0], optimization[0], activation[0], dropout[0], hidden_layers[0], n) for n in neurons) ''' for i in range(len(results)): results_data_frame[str(i)] = results[i] # summarize results print(results); #print(results_data_frame.describe()) # save boxplot #Entrenamiento.save_results(results_data_frame, "nombre_archivo") ########################################################################################################### nombre_sujeto = "AC" nombre_postura = "ACOSTADO" nombre_emisferio = "DERECHO" PATH = ("C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) # fix random seed for reproducibility numpy.random.seed(7) #Dar formato float a las señales PAMn, VFSCd = PAMn.astype('float32'), VFSCd.astype('float32') PAMn, VFSCd = numpy.array(PAMn), numpy.array(VFSCd) # Validacion Valanceada train_size = int(len(PAMn) * 0.75) test_size = len(PAMn) - train_size train_PAM, train_VFSCd = PAMn[0:train_size], VFSCd[0:train_size] test_PAM, test_VFSCd = PAMn[train_size:len(PAMn)], VFSCd[train_size:len(VFSCd)] # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] train_PAM = numpy.reshape(train_PAM, (train_PAM.shape[0], 1, train_PAM.shape[1])) test_PAM = numpy.reshape(test_PAM, (test_PAM.shape[0], 1, test_PAM.shape[1])) # create and fit the LSTM network ############################################################################################################################################################## ##Hyperparametros numpy.random.uniform(low=0.5, high=13.3, size=(5,)) ################# nombre_archivo_resultados = nombre_sujeto+"_"+nombre_postura+"_"+nombre_emisferio Entrenamiento.run_experiment(train_PAM, train_VFSCd, test_PAM, test_VFSCd, epochs = [2,3]) ############################################################################################################################################################## ########################################################################################################################### #random search #https://github.com/llSourcell/hyperparameter_optimization_strategies/blob/master/random_search.py Parallel(n_jobs=2)(delayed(sqrt)(i ** 2) for i in range(10)) ################# # Use scikit-learn to grid search the batch size and epochs import pandas as pd import numpy import keras.backend as K import tensorflow as tf import math from scipy import stats from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, Input, LSTM, Reshape, Lambda, RepeatVector from keras.wrappers.scikit_learn import KerasRegressor def correlation_coefficient_loss(y_true, y_pred): fsp = y_pred - K.mean(y_pred,axis=0) #you take the mean over the batch, keeping the features separate. fst = y_true - K.mean(y_true,axis=0) #mean shape: (1,10) #fst shape keeps (batch,10) devP = K.std(y_pred,axis=0) devT = K.std(y_true,axis=0) #dev shape: (1,10) return K.sum(K.mean(fsp*fst,axis=0)/(devP*devT)) # Function to create model, required for KerasClassifier def create_model(neurons=1): # create model model = Sequential() #model.add(LSTM(1, return_sequences=True)) model.add(LSTM(neurons)) model.add(Dense(1)) # Compile model model.compile(loss=correlation_coefficient_loss, optimizer='adam') return model def create_dataset(): nombre_sujeto = "AC" nombre_postura = "ACOSTADO" nombre_emisferio = "DERECHO" PATH = ("C:/Users/Luis.O.A/Documents/USACH/Tesis/Dataset/Sujetos/Muestreo 0.4/%s/%s-%s-VE.csv"%(nombre_sujeto, nombre_sujeto, nombre_postura)) X = pd.read_csv(PATH, sep=" ") # normalize the dataset scaler = MinMaxScaler(feature_range=(-1, 1)) VFSCd = scaler.fit_transform(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) VFSCi = scaler.fit_transform(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) PAMn = scaler.fit_transform(X.PAMn.values.reshape((len(X.PAMn.values), 1))) # fix random seed for reproducibility numpy.random.seed(7) #Dar formato float a las señales PAMn, VFSCd, VFSCi = PAMn.astype('float32'), VFSCd.astype('float32'), VFSCi.astype('float32') PAMn, VFSCd, VFSCi = numpy.array(PAMn), numpy.array(VFSCd), numpy.array(VFSCi) # Reshape segun el formato que acepta Keras # reshape input to be [samples, time steps, features] PAMn = numpy.reshape(PAMn, (PAMn.shape[0], 1, PAMn.shape[1])) return PAMn, VFSCd, VFSCi def run_experiment(hyperparam_grid): # create model model = KerasRegressor(build_fn=create_model, verbose=0) grid = GridSearchCV(estimator=model, param_grid=hyperparam_grid, cv=5, n_jobs=1) grid_result = grid.fit(X, Y1) # summarize results print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) means = grid_result.cv_results_['mean_test_score'] stds = grid_result.cv_results_['std_test_score'] params = grid_result.cv_results_['params'] for mean, stdev, param in zip(means, stds, params): print("%f (%f) with: %r" % (mean, stdev, param)) # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) # load dataset # split into input (X) and output (Y) variables X, Y1, Y2 = create_dataset() # define the grid search parameters ##Tuning the Number of Epochs ##Tuning the Batch Size ##Tuning the Number of Neurons ##Tuning the Number of Hidden Layers #################################################################### batch_size batch_size = [] for i in range(1,500): if (math.floor(X.shape[0] - (X.shape[0]/5))%i)==0: batch_size.append(i) hyperparam_grid = dict(batch_size=batch_size) run_experiment(hyperparam_grid) ######################################################################## epochs #epochs = numpy.random.randint(low=1, high=10000, size=(10,)) epochs = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000] hyperparam_grid = dict(epochs=epochs) run_experiment(hyperparam_grid) ####################################################################### neurons neurons = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] hyperparam_grid = dict(neurons=neurons) run_experiment(hyperparam_grid) ################################################################## dropout_rate dropout_rate = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] hyperparam_grid = dict(dropout_rate=dropout_rate) run_experiment(hyperparam_grid) batch_size = [1] epochs = [100] neurons = [10] hyperparam_grid = dict(batch_size=batch_size, epochs=epochs, neurons=neurons) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 run_experiment(hyperparam_grid)<file_sep>import os script_folder = './Python/Regresion Logistica - Clasificacion Imagenes/sklearn-mnist' os.makedirs(script_folder, exist_ok=True)<file_sep>import Workspace_Experiment as we ds = we.load_workspace.get_default_datastore() print(ds.datastore_type, ds.account_name, ds.container_name) ds.upload(src_dir='./Python/Regresion Logistica - Venta Online/Social_Network_Ads.csv', target_path='mnist', overwrite=True, show_progress=True)<file_sep><<<<<<< HEAD <<<<<<< HEAD #Ruta del Dataset RUTA_DATASET <- "C:/Users/Luis.O.A/Documents/Analisis Cervezas" setwd(RUTA_DATASET) #Leer Dataset data=read.csv("beer_reviews.csv") #Eliminar datos NA data= na.omit(data) #Resumen medidas de tendencia summary(data) #Desviacion estandar para observar desviacion con respecto a la media sd(data$review_appearance) sd(data$review_aroma) sd(data$review_palate) sd(data$review_taste) #¿Qué cervecería produce la cerveza más fuerte según ABV? unique(data$brewery_name[data$beer_abv == max(data$beer_abv)]) #¿Si tuviera que elegir 3 cervezas para recomendar usando sólo estos datos, cuáles elegiría? #El siguente sumatoria de los campos "review" es equivalente al campo "review_overall" new_data <- data.frame(nom = data$beer_name, suma = data$review_aroma + data$review_appearance + data$review_palate + data$review_taste) grupo <- aggregate(new_data$suma, by=list(nom=new_data$nom), FUN=sum) head(grupo[order(grupo$x, decreasing = TRUE),], 3) #¿Cual de los factores (aroma, taste, aperance, palete) es ams importante para #determinar la calidad general de una cerveza? hist(data$review_aroma, xlab="review_aroma", main="review_aroma") hist(data$review_taste, xlab="review_taste", main="review_taste") hist(data$review_appearance, xlab="review_appearance", main="review_appearance") hist(data$review_palate, xlab="review_palate", main="review_palate") hist(data$review_overall, xlab="review_overall", main="review_overall") d <- data.frame(data$review_aroma, data$review_taste, data$review_appearance, data$review_palate) cor(d, data$review_overall, method = "pearson") #Si yo tipicamente disfruto una cerveza debido a su #aroma y apariencia, ¿que estilo de cerveza deberia probar? new_ar_ap <- data.frame(nom = data$beer_style, suma = data$review_aroma + data$review_appearance) grupo <- aggregate(new_ar_ap$suma, by=list(nom=new_ar_ap$nom), FUN=sum) head(grupo[order(grupo$x, decreasing = TRUE),], 1) ======= #Ruta del Dataset RUTA_DATASET <- "C:/Users/Luis.O.A/Documents/Analisis Cervezas" setwd(RUTA_DATASET) #Leer Dataset data=read.csv("beer_reviews.csv") #Eliminar datos NA data= na.omit(data) #Resumen medidas de tendencia summary(data) #Desviacion estandar para observar desviacion con respecto a la media sd(data$review_appearance) sd(data$review_aroma) sd(data$review_palate) sd(data$review_taste) #¿Qué cervecería produce la cerveza más fuerte según ABV? unique(data$brewery_name[data$beer_abv == max(data$beer_abv)]) #¿Si tuviera que elegir 3 cervezas para recomendar usando sólo estos datos, cuáles elegiría? #El siguente sumatoria de los campos "review" es equivalente al campo "review_overall" new_data <- data.frame(nom = data$beer_name, suma = data$review_aroma + data$review_appearance + data$review_palate + data$review_taste) grupo <- aggregate(new_data$suma, by=list(nom=new_data$nom), FUN=sum) head(grupo[order(grupo$x, decreasing = TRUE),], 3) #¿Cual de los factores (aroma, taste, aperance, palete) es ams importante para #determinar la calidad general de una cerveza? hist(data$review_aroma, xlab="review_aroma", main="review_aroma") hist(data$review_taste, xlab="review_taste", main="review_taste") hist(data$review_appearance, xlab="review_appearance", main="review_appearance") hist(data$review_palate, xlab="review_palate", main="review_palate") hist(data$review_overall, xlab="review_overall", main="review_overall") d <- data.frame(data$review_aroma, data$review_taste, data$review_appearance, data$review_palate) cor(d, data$review_overall, method = "pearson") #Si yo tipicamente disfruto una cerveza debido a su #aroma y apariencia, ¿que estilo de cerveza deberia probar? new_ar_ap <- data.frame(nom = data$beer_style, suma = data$review_aroma + data$review_appearance) grupo <- aggregate(new_ar_ap$suma, by=list(nom=new_ar_ap$nom), FUN=sum) head(grupo[order(grupo$x, decreasing = TRUE),], 1) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= #Ruta del Dataset RUTA_DATASET <- "C:/Users/Luis.O.A/Documents/Analisis Cervezas" setwd(RUTA_DATASET) #Leer Dataset data=read.csv("beer_reviews.csv") #Eliminar datos NA data= na.omit(data) #Resumen medidas de tendencia summary(data) #Desviacion estandar para observar desviacion con respecto a la media sd(data$review_appearance) sd(data$review_aroma) sd(data$review_palate) sd(data$review_taste) #¿Qué cervecería produce la cerveza más fuerte según ABV? unique(data$brewery_name[data$beer_abv == max(data$beer_abv)]) #¿Si tuviera que elegir 3 cervezas para recomendar usando sólo estos datos, cuáles elegiría? #El siguente sumatoria de los campos "review" es equivalente al campo "review_overall" new_data <- data.frame(nom = data$beer_name, suma = data$review_aroma + data$review_appearance + data$review_palate + data$review_taste) grupo <- aggregate(new_data$suma, by=list(nom=new_data$nom), FUN=sum) head(grupo[order(grupo$x, decreasing = TRUE),], 3) #¿Cual de los factores (aroma, taste, aperance, palete) es ams importante para #determinar la calidad general de una cerveza? hist(data$review_aroma, xlab="review_aroma", main="review_aroma") hist(data$review_taste, xlab="review_taste", main="review_taste") hist(data$review_appearance, xlab="review_appearance", main="review_appearance") hist(data$review_palate, xlab="review_palate", main="review_palate") hist(data$review_overall, xlab="review_overall", main="review_overall") d <- data.frame(data$review_aroma, data$review_taste, data$review_appearance, data$review_palate) cor(d, data$review_overall, method = "pearson") #Si yo tipicamente disfruto una cerveza debido a su #aroma y apariencia, ¿que estilo de cerveza deberia probar? new_ar_ap <- data.frame(nom = data$beer_style, suma = data$review_aroma + data$review_appearance) grupo <- aggregate(new_ar_ap$suma, by=list(nom=new_ar_ap$nom), FUN=sum) head(grupo[order(grupo$x, decreasing = TRUE),], 1) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep><<<<<<< HEAD <<<<<<< HEAD import numpy import pandas import statsmodels.formula.api as smf import statsmodels.stats.multicomp as multi import matplotlib.pyplot as plt import seaborn as sns data = pandas.read_csv(‘addhealth_pds.csv’, low_memory=False) data = data[['IYEAR’, 'H1GI1Y’, 'H1FS15’]].dropna() data['AGE’]=data['IYEAR’] - data['H1GI1Y’] data['AGE’]= data['AGE’].convert_objects(convert_numeric=True) sub1 = data[['AGE’, 'H1FS15’]].dropna() sub1=sub1[(sub1['AGE’] >= 13)&(sub1['AGE’] <= 17)] print ('means for AGE by feeling tired status’) m1= sub1.groupby('H1FS15’).mean() print (m1) print ('standard deviations for AGE by feeling tired status’) sd1 = sub1.groupby('H1FS15’).std() print (sd1) mc1 = multi.MultiComparison(sub1['AGE’], sub1['H1FS15’]) res1 = mc1.tukeyhsd() print(res1.summary()) sns.distplot(sub1['AGE’]); ======= import numpy import pandas import statsmodels.formula.api as smf import statsmodels.stats.multicomp as multi import matplotlib.pyplot as plt import seaborn as sns data = pandas.read_csv(‘addhealth_pds.csv’, low_memory=False) data = data[['IYEAR’, 'H1GI1Y’, 'H1FS15’]].dropna() data['AGE’]=data['IYEAR’] - data['H1GI1Y’] data['AGE’]= data['AGE’].convert_objects(convert_numeric=True) sub1 = data[['AGE’, 'H1FS15’]].dropna() sub1=sub1[(sub1['AGE’] >= 13)&(sub1['AGE’] <= 17)] print ('means for AGE by feeling tired status’) m1= sub1.groupby('H1FS15’).mean() print (m1) print ('standard deviations for AGE by feeling tired status’) sd1 = sub1.groupby('H1FS15’).std() print (sd1) mc1 = multi.MultiComparison(sub1['AGE’], sub1['H1FS15’]) res1 = mc1.tukeyhsd() print(res1.summary()) sns.distplot(sub1['AGE’]); >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= import numpy import pandas import statsmodels.formula.api as smf import statsmodels.stats.multicomp as multi import matplotlib.pyplot as plt import seaborn as sns data = pandas.read_csv(‘addhealth_pds.csv’, low_memory=False) data = data[['IYEAR’, 'H1GI1Y’, 'H1FS15’]].dropna() data['AGE’]=data['IYEAR’] - data['H1GI1Y’] data['AGE’]= data['AGE’].convert_objects(convert_numeric=True) sub1 = data[['AGE’, 'H1FS15’]].dropna() sub1=sub1[(sub1['AGE’] >= 13)&(sub1['AGE’] <= 17)] print ('means for AGE by feeling tired status’) m1= sub1.groupby('H1FS15’).mean() print (m1) print ('standard deviations for AGE by feeling tired status’) sd1 = sub1.groupby('H1FS15’).std() print (sd1) mc1 = multi.MultiComparison(sub1['AGE’], sub1['H1FS15’]) res1 = mc1.tukeyhsd() print(res1.summary()) sns.distplot(sub1['AGE’]); >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep>#https://www.kaggle.com/pierremegret/gensim-word2vec-tutorial import re # For preprocessing import pandas as pd # For data handling from time import time # To time our operations from collections import defaultdict # For word frequency import spacy # For preprocessing import logging # Setting up the loggings to monitor gensim logging.basicConfig(format="%(levelname)s - %(asctime)s: %(message)s", datefmt= '%H:%M:%S', level=logging.INFO) df_clean = pd.read_csv(r'D:\Investigacion Word2Vec\Modelo\pubmed_sentences.csv') #Bigrams from gensim.models.phrases import Phrases, Phraser sent = [row.split() for row in df_clean['clean']] phrases = Phrases(sent, min_count=30, progress_per=10000) bigram = Phraser(phrases) sentences = bigram[sent] #Most Frequent Words: word_freq = defaultdict(int) for sent in sentences: for i in sent: word_freq[i] += 1 len(word_freq) print(sorted(word_freq, key=word_freq.get, reverse=True)[:10]) #Training the model import multiprocessing from gensim.models import Word2Vec cores = multiprocessing.cpu_count() # Count the number of cores in a computer w2v_model = Word2Vec(min_count=20, window=8, size=200, sample=6e-5, alpha=0.01, min_alpha=0.0001, negative=20, workers=cores-1, sg=1) #Building the Vocabulary Table t = time() w2v_model.build_vocab(sentences, progress_per=10000) print('Time to build vocab: {} mins'.format(round((time() - t) / 60, 2))) #Training of the model: t = time() w2v_model.train(sentences, total_examples=w2v_model.corpus_count, epochs=30, report_delay=1) print('Time to train the model: {} mins'.format(round((time() - t) / 60, 2))) w2v_model.init_sims(replace=True) #Save the Model w2v_model.save("w2v_model") model = Word2Vec.load("w2v_model") #Exploring the model #print(w2v_model.wv.most_similar(positive=["homer"])) <file_sep><<<<<<< HEAD <<<<<<< HEAD install.packages('e1071', dep = TRUE) install.packages('xlsx', dep = TRUE) install.packages('caret', dep = TRUE) install.packages('caTools', dep = TRUE) install.packages('plotly', dep = TRUE) library(e1071) library(xlsx) library(caret) library(caTools) library(plotly) #Modifica estas rutas segun tu ambiente de desarrollo (la variable RUTA_TXT_XLS esta explicada en el correo) RUTA_DATASET <- "C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\grupo 6 Wine Quality" RUTA_TXT_XLS <- "C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\Trabajos\\5" setwd(RUTA_DATASET) wine <- read.csv('winequality-red.csv', sep=';') #Funcion que permite normalizar los datos entre 0 a 1 normalize <- function(x) { x = (x-min(x))/(max(x)-min(x)) x } #Se normalizan los datos menos la clase (wine quality) wine$fixed.acidity <- NULL wine$volatile.acidity = normalize(wine$volatile.acidity) wine$citric.acid = normalize(wine$citric.acid) wine$residual.sugar = normalize(wine$residual.sugar) wine$chlorides = normalize(wine$chlorides) wine$free.sulfur.dioxide = normalize(wine$free.sulfur.dioxide) wine$total.sulfur.dioxide = normalize(wine$total.sulfur.dioxide) wine$density = normalize(wine$density) wine$pH = normalize(wine$pH) wine$sulphates = normalize(wine$sulphates) wine$alcohol = normalize(wine$alcohol) #hist(wine$fixed.acidity,breaks=10, xlab="wine",col="lightblue", main="") #la clase es transformada a factor. wine$quality = factor(wine$quality,labels=c("III", "IV", "V", "VI", "VII", "VIII")) #Se comprobara el error con cada uno de los tipos de kernel #Los rangos de los parametros de cada kernel estan sugeridos aqui: (rstudio) #http://rstudio-pubs-static.s3.amazonaws.com/252840_176bda2bbab2428cbf042f8282d717e1.html modelo <- function(wine, k){ #Semilla para no obtener casos destintos en cada ejecucion set.seed(123) #No es necesario separar los datos en test y training porque el metodo ya provee validacion cruzada if(k == "radial"){ # Kernel radial obj <- tune(svm, quality~., data = wine, kernel = k, ranges = list(gamma = 2^(-7:12), cost = 2^(-7:14) ), tunecontrol = tune.control(sampling = "cross", cross = 2)) }else if(k == "polynomial"){ # Kernel polynomial obj <- tune(svm, quality~., data = wine, kernel = k, degree = 2, ranges = list(cost = 2^(-2:9)), tunecontrol = tune.control(sampling = "cross", cross = 2)) #obj <- tune(svm, quality~., data = wine, kernel = k, degree = 2, ranges = list(cost=10^seq(-2, 1, by=0.25)), tunecontrol = tune.control(sampling = "cross", cross = 2)) }else if(k == "linear"){ # Kernel linear obj <- tune(svm, quality~., data = wine, kernel = k, ranges = list(cost = 2^(-3:6)), tunecontrol = tune.control(sampling = "cross", cross = 2)) }else{ # Kernel sigmoid obj <- tune(svm, quality~., data = wine, kernel = k, ranges=list(gamma = 2^(-7:12), cost = 2^(-7:14)), tunecontrol = tune.control(sampling = "cross", cross = 2)) } summary(obj) x <- subset(wine, select = -quality) y <- wine$quality pred <- predict(obj$best.model, x) tabla.resultados <- table(pred, y) #Almacena los resultados en un excel para luego analizarlos setwd(RUTA_TXT_XLS) write.xlsx(obj$performances, paste(k, "xlsx", sep = "."), sheetName="Sheet1", append = FALSE) escribir.tabla <- function(x,row.names=FALSE,col.names=TRUE,...) { write.table(x,paste(k, "txt", sep = "."),sep="\t",row.names=row.names,col.names=col.names,...) } #Almacena la tabla de resultados de clasificacion en txt para luego analizarlos escribir.tabla(tabla.resultados) return(obj) } #Grafica el error de cada uno de los modelos segun su kernel graficar <- function(model, k){ #Ordeno los errores de mayor a menor paraque el grafico no sea tan feo Error <- sort(model$performances$error, decreasing = TRUE) x <- c(1:length(model$performances$error)) data <- data.frame(x, sort(model$performances$error, decreasing = TRUE)) plot_ly(data, x = ~x, y = ~Error, name = k, type = 'scatter', mode = 'lines+markers') } #Mejor modelo = radial; gamma = 0.5; cost = 2 model.r <- modelo(wine, "radial") #Porcentaje de Error en la clasificacion de wine error.r <- mean(model.r$best.model$fitted!=wine$quality)*100 #Error = 8.380238 graficar(model.r, "radial"); #Al eliminar "" 10.69418 model.p <- modelo(wine, "polynomial") #Porcentaje de Error en la clasificacion de wine error.p <- mean(model.p$best.model$fitted!=wine$quality)*100#Error = 39.27455 graficar(model.p, "polynomial"); model.l <- modelo(wine, "linear") #Porcentaje de Error en la clasificacion de wine error.l <- mean(model.l$best.model$fitted!=wine$quality)*100#Error = 41.2758 graficar(model.l, "linear"); model.s <- modelo(wine, "sigmoid") #Porcentaje de Error en la clasificacion de wine error.s <- mean(model.s$best.model$fitted!=wine$quality)*100#Error = 43.15197 graficar(model.s, "sigmoid"); #Grafico de los porcentajes de error plot_ly( x = c("radial","polynomial","linear","sigmoid"), y = c(error.r, error.p, error.l, error.s), name = "% Error Segun Kernel", type = "bar" ) ======= install.packages('e1071', dep = TRUE) install.packages('xlsx', dep = TRUE) install.packages('caret', dep = TRUE) install.packages('caTools', dep = TRUE) install.packages('plotly', dep = TRUE) library(e1071) library(xlsx) library(caret) library(caTools) library(plotly) #Modifica estas rutas segun tu ambiente de desarrollo (la variable RUTA_TXT_XLS esta explicada en el correo) RUTA_DATASET <- "C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\grupo 6 Wine Quality" RUTA_TXT_XLS <- "C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\Trabajos\\5" setwd(RUTA_DATASET) wine <- read.csv('winequality-red.csv', sep=';') #Funcion que permite normalizar los datos entre 0 a 1 normalize <- function(x) { x = (x-min(x))/(max(x)-min(x)) x } #Se normalizan los datos menos la clase (wine quality) wine$fixed.acidity <- NULL wine$volatile.acidity = normalize(wine$volatile.acidity) wine$citric.acid = normalize(wine$citric.acid) wine$residual.sugar = normalize(wine$residual.sugar) wine$chlorides = normalize(wine$chlorides) wine$free.sulfur.dioxide = normalize(wine$free.sulfur.dioxide) wine$total.sulfur.dioxide = normalize(wine$total.sulfur.dioxide) wine$density = normalize(wine$density) wine$pH = normalize(wine$pH) wine$sulphates = normalize(wine$sulphates) wine$alcohol = normalize(wine$alcohol) #hist(wine$fixed.acidity,breaks=10, xlab="wine",col="lightblue", main="") #la clase es transformada a factor. wine$quality = factor(wine$quality,labels=c("III", "IV", "V", "VI", "VII", "VIII")) #Se comprobara el error con cada uno de los tipos de kernel #Los rangos de los parametros de cada kernel estan sugeridos aqui: (rstudio) #http://rstudio-pubs-static.s3.amazonaws.com/252840_176bda2bbab2428cbf042f8282d717e1.html modelo <- function(wine, k){ #Semilla para no obtener casos destintos en cada ejecucion set.seed(123) #No es necesario separar los datos en test y training porque el metodo ya provee validacion cruzada if(k == "radial"){ # Kernel radial obj <- tune(svm, quality~., data = wine, kernel = k, ranges = list(gamma = 2^(-7:12), cost = 2^(-7:14) ), tunecontrol = tune.control(sampling = "cross", cross = 2)) }else if(k == "polynomial"){ # Kernel polynomial obj <- tune(svm, quality~., data = wine, kernel = k, degree = 2, ranges = list(cost = 2^(-2:9)), tunecontrol = tune.control(sampling = "cross", cross = 2)) #obj <- tune(svm, quality~., data = wine, kernel = k, degree = 2, ranges = list(cost=10^seq(-2, 1, by=0.25)), tunecontrol = tune.control(sampling = "cross", cross = 2)) }else if(k == "linear"){ # Kernel linear obj <- tune(svm, quality~., data = wine, kernel = k, ranges = list(cost = 2^(-3:6)), tunecontrol = tune.control(sampling = "cross", cross = 2)) }else{ # Kernel sigmoid obj <- tune(svm, quality~., data = wine, kernel = k, ranges=list(gamma = 2^(-7:12), cost = 2^(-7:14)), tunecontrol = tune.control(sampling = "cross", cross = 2)) } summary(obj) x <- subset(wine, select = -quality) y <- wine$quality pred <- predict(obj$best.model, x) tabla.resultados <- table(pred, y) #Almacena los resultados en un excel para luego analizarlos setwd(RUTA_TXT_XLS) write.xlsx(obj$performances, paste(k, "xlsx", sep = "."), sheetName="Sheet1", append = FALSE) escribir.tabla <- function(x,row.names=FALSE,col.names=TRUE,...) { write.table(x,paste(k, "txt", sep = "."),sep="\t",row.names=row.names,col.names=col.names,...) } #Almacena la tabla de resultados de clasificacion en txt para luego analizarlos escribir.tabla(tabla.resultados) return(obj) } #Grafica el error de cada uno de los modelos segun su kernel graficar <- function(model, k){ #Ordeno los errores de mayor a menor paraque el grafico no sea tan feo Error <- sort(model$performances$error, decreasing = TRUE) x <- c(1:length(model$performances$error)) data <- data.frame(x, sort(model$performances$error, decreasing = TRUE)) plot_ly(data, x = ~x, y = ~Error, name = k, type = 'scatter', mode = 'lines+markers') } #Mejor modelo = radial; gamma = 0.5; cost = 2 model.r <- modelo(wine, "radial") #Porcentaje de Error en la clasificacion de wine error.r <- mean(model.r$best.model$fitted!=wine$quality)*100 #Error = 8.380238 graficar(model.r, "radial"); #Al eliminar "" 10.69418 model.p <- modelo(wine, "polynomial") #Porcentaje de Error en la clasificacion de wine error.p <- mean(model.p$best.model$fitted!=wine$quality)*100#Error = 39.27455 graficar(model.p, "polynomial"); model.l <- modelo(wine, "linear") #Porcentaje de Error en la clasificacion de wine error.l <- mean(model.l$best.model$fitted!=wine$quality)*100#Error = 41.2758 graficar(model.l, "linear"); model.s <- modelo(wine, "sigmoid") #Porcentaje de Error en la clasificacion de wine error.s <- mean(model.s$best.model$fitted!=wine$quality)*100#Error = 43.15197 graficar(model.s, "sigmoid"); #Grafico de los porcentajes de error plot_ly( x = c("radial","polynomial","linear","sigmoid"), y = c(error.r, error.p, error.l, error.s), name = "% Error Segun Kernel", type = "bar" ) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 ======= install.packages('e1071', dep = TRUE) install.packages('xlsx', dep = TRUE) install.packages('caret', dep = TRUE) install.packages('caTools', dep = TRUE) install.packages('plotly', dep = TRUE) library(e1071) library(xlsx) library(caret) library(caTools) library(plotly) #Modifica estas rutas segun tu ambiente de desarrollo (la variable RUTA_TXT_XLS esta explicada en el correo) RUTA_DATASET <- "C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\grupo 6 Wine Quality" RUTA_TXT_XLS <- "C:\\Users\\Luis.O.A\\Documents\\USACH\\Mineria de Datos\\Trabajos\\5" setwd(RUTA_DATASET) wine <- read.csv('winequality-red.csv', sep=';') #Funcion que permite normalizar los datos entre 0 a 1 normalize <- function(x) { x = (x-min(x))/(max(x)-min(x)) x } #Se normalizan los datos menos la clase (wine quality) wine$fixed.acidity <- NULL wine$volatile.acidity = normalize(wine$volatile.acidity) wine$citric.acid = normalize(wine$citric.acid) wine$residual.sugar = normalize(wine$residual.sugar) wine$chlorides = normalize(wine$chlorides) wine$free.sulfur.dioxide = normalize(wine$free.sulfur.dioxide) wine$total.sulfur.dioxide = normalize(wine$total.sulfur.dioxide) wine$density = normalize(wine$density) wine$pH = normalize(wine$pH) wine$sulphates = normalize(wine$sulphates) wine$alcohol = normalize(wine$alcohol) #hist(wine$fixed.acidity,breaks=10, xlab="wine",col="lightblue", main="") #la clase es transformada a factor. wine$quality = factor(wine$quality,labels=c("III", "IV", "V", "VI", "VII", "VIII")) #Se comprobara el error con cada uno de los tipos de kernel #Los rangos de los parametros de cada kernel estan sugeridos aqui: (rstudio) #http://rstudio-pubs-static.s3.amazonaws.com/252840_176bda2bbab2428cbf042f8282d717e1.html modelo <- function(wine, k){ #Semilla para no obtener casos destintos en cada ejecucion set.seed(123) #No es necesario separar los datos en test y training porque el metodo ya provee validacion cruzada if(k == "radial"){ # Kernel radial obj <- tune(svm, quality~., data = wine, kernel = k, ranges = list(gamma = 2^(-7:12), cost = 2^(-7:14) ), tunecontrol = tune.control(sampling = "cross", cross = 2)) }else if(k == "polynomial"){ # Kernel polynomial obj <- tune(svm, quality~., data = wine, kernel = k, degree = 2, ranges = list(cost = 2^(-2:9)), tunecontrol = tune.control(sampling = "cross", cross = 2)) #obj <- tune(svm, quality~., data = wine, kernel = k, degree = 2, ranges = list(cost=10^seq(-2, 1, by=0.25)), tunecontrol = tune.control(sampling = "cross", cross = 2)) }else if(k == "linear"){ # Kernel linear obj <- tune(svm, quality~., data = wine, kernel = k, ranges = list(cost = 2^(-3:6)), tunecontrol = tune.control(sampling = "cross", cross = 2)) }else{ # Kernel sigmoid obj <- tune(svm, quality~., data = wine, kernel = k, ranges=list(gamma = 2^(-7:12), cost = 2^(-7:14)), tunecontrol = tune.control(sampling = "cross", cross = 2)) } summary(obj) x <- subset(wine, select = -quality) y <- wine$quality pred <- predict(obj$best.model, x) tabla.resultados <- table(pred, y) #Almacena los resultados en un excel para luego analizarlos setwd(RUTA_TXT_XLS) write.xlsx(obj$performances, paste(k, "xlsx", sep = "."), sheetName="Sheet1", append = FALSE) escribir.tabla <- function(x,row.names=FALSE,col.names=TRUE,...) { write.table(x,paste(k, "txt", sep = "."),sep="\t",row.names=row.names,col.names=col.names,...) } #Almacena la tabla de resultados de clasificacion en txt para luego analizarlos escribir.tabla(tabla.resultados) return(obj) } #Grafica el error de cada uno de los modelos segun su kernel graficar <- function(model, k){ #Ordeno los errores de mayor a menor paraque el grafico no sea tan feo Error <- sort(model$performances$error, decreasing = TRUE) x <- c(1:length(model$performances$error)) data <- data.frame(x, sort(model$performances$error, decreasing = TRUE)) plot_ly(data, x = ~x, y = ~Error, name = k, type = 'scatter', mode = 'lines+markers') } #Mejor modelo = radial; gamma = 0.5; cost = 2 model.r <- modelo(wine, "radial") #Porcentaje de Error en la clasificacion de wine error.r <- mean(model.r$best.model$fitted!=wine$quality)*100 #Error = 8.380238 graficar(model.r, "radial"); #Al eliminar "" 10.69418 model.p <- modelo(wine, "polynomial") #Porcentaje de Error en la clasificacion de wine error.p <- mean(model.p$best.model$fitted!=wine$quality)*100#Error = 39.27455 graficar(model.p, "polynomial"); model.l <- modelo(wine, "linear") #Porcentaje de Error en la clasificacion de wine error.l <- mean(model.l$best.model$fitted!=wine$quality)*100#Error = 41.2758 graficar(model.l, "linear"); model.s <- modelo(wine, "sigmoid") #Porcentaje de Error en la clasificacion de wine error.s <- mean(model.s$best.model$fitted!=wine$quality)*100#Error = 43.15197 graficar(model.s, "sigmoid"); #Grafico de los porcentajes de error plot_ly( x = c("radial","polynomial","linear","sigmoid"), y = c(error.r, error.p, error.l, error.s), name = "% Error Segun Kernel", type = "bar" ) >>>>>>> 4966aae922150d281e7f47d431009d8054258bc0 <file_sep>import pandas as pd from sklearn.preprocessing import MinMaxScaler import numpy import matplotlib.pyplot as plt import numpy as np import csv import os PATH_SUJETOS = ("C:/Users/Luis/Documents/DataScience/Tesis/Datos/SUJETOS/%s/%s-%s-VE.csv") PATH_ESCALON = ("C:/Users/Luis/Documents/DataScience/Tesis/Datos/ESCALON_PRESION/ESCALON.csv") PATH_RESULTADO = ("C:/Users/Luis/Documents/DataScience/Tesis/Resultados/Escalon/%s") PATH_RESULTADO_MFARI = ("C:/Users/Luis/Documents/DataScience/Tesis/Calculo ARI/v15.9.10/Data/%s") PATH_RESULTADO_FORMATEADO = ("C:/Users/Luis/Documents/DataScience/Tesis/Calculo ARI/v15.9.10/Data/%s/%s-%s.txt") PATH_RESULTADO_IMAGE = ("C:/Users/Luis/Documents/DataScience/Tesis/Calculo ARI/v15.9.10/Data/%s/%s-%s-%s.png") PATH_RESULTADO_ESCALON = (PATH_RESULTADO%("%s/%s_%s")) def create_scalers(nombre_sujeto, nombre_postura): X = pd.read_csv(PATH_SUJETOS%(nombre_sujeto, nombre_sujeto, nombre_postura), sep=" ") data_escalon = pd.read_csv(PATH_ESCALON) # normalize the dataset scaler_VFSCd = MinMaxScaler(feature_range=(0, 1)) scaler_VFSCi = MinMaxScaler(feature_range=(0, 1)) scaler_escalon = MinMaxScaler(feature_range=(0, 1)) scaler_VFSCd.fit(X.VFSCd.values.reshape((len(X.VFSCd.values), 1))) scaler_VFSCi.fit(X.VFSCi.values.reshape((len(X.VFSCi.values), 1))) Escalon = scaler_escalon.fit_transform(data_escalon.ESCALON.values.reshape((len(data_escalon.ESCALON.values), 1))) return scaler_VFSCd, scaler_VFSCi, Escalon def read_output(nombre_sujeto, nombre_postura, hemisferio, scaler_VFSCd, scaler_VFSCi): X = pd.read_csv(PATH_RESULTADO_ESCALON%(nombre_sujeto, nombre_postura, hemisferio)+'_output.csv', sep=" ") if hemisferio == "Izquierdo": out = scaler_VFSCi.transform(X.Output.values.reshape((len(X.Output.values), 1))) return out elif hemisferio == "Derecho": out = scaler_VFSCd.transform(X.Output.values.reshape((len(X.Output.values), 1))) return out def plotting_mathplot(hemisferio, sujeto, postura, escalon, output): time = np.round(np.arange(-78.0, 81.2, 0.4),1) re_escalon = numpy.reshape(escalon, (escalon.shape[0])) re_output = numpy.reshape(output, (output.shape[0])) fig, ax = plt.subplots() # Using set_dashes() to modify dashing of an existing line line1, = ax.plot(time, re_escalon, label='Escalon') # Using plot(..., dashes=...) to set the dashing when creating a line line2, = ax.plot(time, re_output, label='VFSC Respuesta Escalon') title="" ax.set_xlabel(title) ax.set_title("LSTM - Respuesta a Escalon") ax.margins(x=-0.35, y=0) ax.legend() #plt.show() plt.tight_layout() plt.savefig(PATH_RESULTADO_IMAGE%(sujeto, sujeto, postura, hemisferio), quality = 95, pad_inches =0, bbox_inches= 'tight') def save_signal(sujeto, postura, escalon, output_izquierdo, output_derecho): time = np.round(np.arange(-78.0, 81.2, 0.4),1) df = list(zip(time.tolist(), escalon[:,0].tolist(), output_izquierdo[:,0].tolist(), output_derecho[:,0].tolist())) df1 = pd.DataFrame(df, columns=['Time', 'ABP', 'LCBFV', 'RCBFV']) if not os.path.exists(PATH_RESULTADO_MFARI%(sujeto)): os.makedirs(PATH_RESULTADO_MFARI%(sujeto)) df1.to_csv(PATH_RESULTADO_FORMATEADO%(sujeto, sujeto, postura),index=False, sep=" ", quoting=csv.QUOTE_NONE) def run(sujeto, postura): scaler_VFSCd, scaler_VFSCi, escalon = create_scalers(sujeto, postura) output_izquierdo = read_output(sujeto, postura, "Izquierdo", scaler_VFSCd, scaler_VFSCi) output_derecho = read_output(sujeto, postura, "Derecho", scaler_VFSCd, scaler_VFSCi) save_signal(sujeto, postura, escalon, output_izquierdo, output_derecho) plotting_mathplot("izquiero", sujeto, postura, escalon, output_izquierdo) plotting_mathplot("derecho", sujeto, postura, escalon, output_derecho) run("AC", "ACOSTADO") run("AC", "PIE") run("AC", "SENTADO") run(sujeto='AP', postura='ACOSTADO') run(sujeto='AP', postura='PIE') run(sujeto='AP', postura='SENTADO') run(sujeto='AV', postura='ACOSTADO') run(sujeto='AV', postura='PIE') run(sujeto='AV', postura='SENTADO') run(sujeto='CC', postura='ACOSTADO') run(sujeto='CC', postura='PIE') run(sujeto='CC', postura='SENTADO') run(sujeto='CS', postura='ACOSTADO') run(sujeto='CS', postura='PIE') run(sujeto='CS', postura='SENTADO') run(sujeto='DM', postura='ACOSTADO') run(sujeto='DM', postura='PIE') run(sujeto='DM', postura='SENTADO') run(sujeto='DS', postura='ACOSTADO') run(sujeto='DS', postura='PIE') run(sujeto='DS', postura='SENTADO') run(sujeto='GP', postura='ACOSTADO') run(sujeto='GP', postura='PIE') run(sujeto='GP', postura='SENTADO') run(sujeto='HF', postura='ACOSTADO') run(sujeto='HF', postura='PIE') run(sujeto='HF', postura='SENTADO') run(sujeto='HS', postura='ACOSTADO') run(sujeto='HS', postura='PIE') run(sujeto='HS', postura='SENTADO') run(sujeto='IH', postura='ACOSTADO') run(sujeto='IH', postura='PIE') run(sujeto='IH', postura='SENTADO') run(sujeto='MM', postura='ACOSTADO') run(sujeto='MM', postura='PIE') run(sujeto='MM', postura='SENTADO') run(sujeto='MR', postura='ACOSTADO') run(sujeto='MR', postura='PIE') run(sujeto='MR', postura='SENTADO') run(sujeto='MV', postura='ACOSTADO') run(sujeto='MV', postura='PIE') run(sujeto='MV', postura='SENTADO') run(sujeto='ND', postura='ACOSTADO') run(sujeto='ND', postura='PIE') run(sujeto='ND', postura='SENTADO') run(sujeto='PC', postura='ACOSTADO') run(sujeto='PC', postura='PIE') run(sujeto='PC', postura='SENTADO') run(sujeto='RO', postura='ACOSTADO') run(sujeto='RO', postura='PIE') run(sujeto='RO', postura='SENTADO') run(sujeto='VT', postura='ACOSTADO') run(sujeto='VT', postura='PIE') run(sujeto='VT', postura='SENTADO')
7838b2d5a69ef228134d0709a52529fcf3a591c8
[ "Python", "R" ]
44
R
luisorellana777/DataScience
5142e5ae4c8d952f2f766f93b311a018266d832d
05a3b363d0e98bb0e16d01aa613174e63449d50e
refs/heads/master
<repo_name>igenoe/Second<file_sep>/app/enrollmentUpload/index.jsx import React, { useState, useEffect } from 'react'; const EnrollmentUpload = () => { return ( <div> EnrollmentUpload </div> ) } export default EnrollmentUpload;<file_sep>/app/paymentUpload/index.jsx import React, { useState, useEffect } from 'react'; const PaymentUpload = () => { return ( <div> PaymentUpload </div> ) } export default PaymentUpload;<file_sep>/app/app.js import React, { Component } from 'react'; import { Route, Link ,Switch} from 'react-router-dom'; import ReactDOM from 'react-dom'; import EnrollmentUpload from './enrollmentUpload/index.jsx'; import PaymentUpload from './paymentUpload/index.jsx'; // import {Navbar,Nav} from "react-bootstrap"; import Navbar from './navBar'; // import { library } from '@fortawesome/fontawesome-svg-core'; // import { faBars } from '@fortawesome/free-solid-svg-icons' // import './index.css'; // library.add(faBars); class App extends Component { render() { return ( // <div className="navbar navbar-default" role="navigation"> // <button className="fa-bars-size" type="button"> // <i className="fa fa-bars"></i> // </button> // <ul> // <li><Link to="/">Home</Link></li> // <li><Link to="/enrollmentUpload">EnrollmentUpload</Link></li> // <li><Link to="/paymentUpload">PaymentUpload</Link></li> // </ul> // <Route path="/" component={PaymentUpload} exact /> // <Route path="/enrollmentUpload" component={EnrollmentUpload} /> // <Route path="/paymentUpload" component={PaymentUpload} /> // </div> <main> <Navbar /> <Switch> <Route path="/" component={PaymentUpload} exact /> <Route path="/enrollmentUpload" component={EnrollmentUpload} /> <Route path="/paymentUpload" component={PaymentUpload} /> </Switch> </main> ); } } export default App; // function App() { // return ( // <main> // <Navbar /> // {/* <Switch> // <Route path="/" component={Home} exact /> // <Route path="/about" component={About} /> // <Route path="/shop" component={Shop} /> // <Route component={Error} /> // </Switch> */} // <Switch> // <Route path="/" component={PaymentUpload} exact /> // <Route path="/enrollmentUpload" component={EnrollmentUpload} /> // <Route path="/paymentUpload" component={PaymentUpload} /> // </Switch> // </main> // ) // }<file_sep>/app/navBar.js import React from "react"; import {Link} from "react-router-dom"; import { library } from '@fortawesome/fontawesome-svg-core'; import { faBars } from '@fortawesome/free-solid-svg-icons' import './index.css'; library.add(faBars); function Navbar() { return ( <div className="navbar navbar-default" role="navigation"> <button className="fa-bars-size" type="button"> <i className="fa fa-bars"></i> </button> <Link to="/">Home</Link> <Link to="/enrollmentUpload">EnrollmentUpload</Link> <Link to="/paymentUpload">PaymentUpload</Link> </div> ); }; export default Navbar;
690299879844cd71ded262fc70d4681ecd168f11
[ "JavaScript" ]
4
JavaScript
igenoe/Second
ef048c48827cf419f93173681430b4e07630a289
78f1d0d981bbbd19004e99b9856874b2dbfd9874
refs/heads/master
<repo_name>IainMeeke/distributed_lab2<file_sep>/server.py import socket import sys from threading import Thread from Queue import Queue import os HOST = '' #host becomes any address the machine happens to have PORT = int(sys.argv[1]) #get the port from the command line arguments and convert to int STUDENT_ID = '39e95f0efebef82542626bd6c3c28765726768817d45d38b2d911b26eb5d0b37' class Worker(Thread): """individual thread that handles the clients requests""" def __init__(self, tasks): Thread.__init__(self) self.tasks = tasks #each task will be an individual connection self.daemon = True self.start() def run(self): #run forever while True: conn = self.tasks.get() #take a connection from the queue while True: data = conn.recv(2048) if data == "KILL_SERVICE\n": os._exit(0) elif data.startswith("HELO") and data.endswith("\n"): reply = '{}IP:52.30.22.92\nPort:{}\nStudentID:{}\n'.format(data,PORT,STUDENT_ID) else: reply = ''#any other message conn.sendall(reply) self.tasks.task_done() class ThreadPool: """pool of worker threads all consuming tasks""" def __init__(self,num_thread): self.tasks = Queue(num_thread) for _ in range(num_thread): Worker(self.tasks) def add_tasks(self, conn): #put a new connection on the queue self.tasks.put((conn)) #socket binding: my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: my_socket.bind((HOST,PORT)) except socket.error , msg: print 'binding failed, error: ' + str(msg[0]) sys.exit() print 'succesful bind' my_socket.listen(20) print 'listening now' #init a thread pool: pool = ThreadPool(20) #keep the server alive while True: connection, addr = my_socket.accept() #blocking call to wait for a connection print 'connected with ' + addr[0] + ' port: ' + str(addr[1]) pool.add_tasks(connection) my_socket.close() <file_sep>/README.md #Distributed Systems lab 2 - Multithreaded Server ###Libraries Used: * socket (to create TCP sockets) * sys * Thread (to create individual worker threads) * Queue (to create the thread pool) * os (needed for exiting)
4fe1aa235f37e13664a1d7be8fcf2905b175bd80
[ "Markdown", "Python" ]
2
Python
IainMeeke/distributed_lab2
64c1ebc966e043358f392dd7637ce8148e31303d
4c34917b0c8c36882b72fbef38f7ad92f3ba3e55
refs/heads/master
<file_sep># TDNET TD 6 : mise en place du web service http://www.dneonline.com/calculator.asmx ![alt text]( https://github.com/edossantos241/TDNET/tree/master/TD/Image/TD6.png) <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RemotingObjects { public interface IRemotingObjects { String sayHello(String name); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using WebApplicationCalculator.ServiceReference1; namespace WebApplicationCalculator { public partial class WebForm1 : System.Web.UI.Page { private CalculatorSoapClient calculatorSoapReference; protected void Page_Load(object sender, EventArgs e) { calculatorSoapReference = new CalculatorSoapClient(); } protected void Button1_Click(object sender, EventArgs e) { if (this.Add.Checked == true) { this.Label3.Text = calculatorSoapReference.Add(int.Parse(TextBox1.Text), int.Parse(this.TextBox2.Text)).ToString(); } else if (this.Divide.Checked == true) { this.Label3.Text = calculatorSoapReference.Divide(int.Parse(TextBox1.Text), int.Parse(this.TextBox2.Text)).ToString(); } else if (this.Multiply.Checked == true) { this.Label3.Text = calculatorSoapReference.Multiply(int.Parse(TextBox1.Text), int.Parse(this.TextBox2.Text)).ToString(); } else { this.Label3.Text = calculatorSoapReference.Subtract(int.Parse(TextBox1.Text), int.Parse(this.TextBox2.Text)).ToString(); } } protected void TextBox1_TextChanged(object sender, EventArgs e) { } protected void RadioButton1_CheckedChanged(object sender, EventArgs e) { } } }
9d31dd6dcd829949efe96c6ea6c4ff55b190b9c4
[ "Markdown", "C#" ]
3
Markdown
edossantos241/TDNET
f25d05a30a2041ec25097564c4c7c727824ae5a4
b2600eb48364b2ee67bd49a54027433819d81634
refs/heads/master
<repo_name>aameen951/simple_compressor<file_sep>/src/file.h #include <stdio.h> struct ReadFileResult { bool succeeded; DataView data; }; ReadFileResult read_input_file(char *file_path){ auto file = fopen(file_path, "rb"); if(file) { fseek(file, 0, SEEK_END); auto size = ftell(file); fseek(file, 0, SEEK_SET); auto buffer = (u8 *)malloc(size); fread(buffer, size, 1, file); fclose(file); return {true, {buffer, (um)size}}; } return {false}; } void read_file_result_free(DataView *data){ free(data->data); data->data = NULL; data->count = 0; } bool write_output_file(char *file_path, DataView data){ auto file = fopen(file_path, "wb"); if(file) { fwrite(data.data, data.count, 1, file); fclose(file); return true; } return false; } <file_sep>/src/LZ.cpp struct FindPrefixResult { um run_start; um run_len; }; FindPrefixResult find_best_prefix_match(DataView data, um a_idx, um b_idx, um max_run_size) { FindPrefixResult result = {}; for(um j=a_idx; j<b_idx; j++) { um run_len = 0; while(b_idx+run_len < data.count && run_len < max_run_size) { if(data.data[j+run_len] != data.data[b_idx+run_len]) { break; } run_len++; } if(run_len >= result.run_len) { result.run_len = run_len; result.run_start = j; } } return result; } COMPRESS_DEF(lz_compress) { um MAX_RUN_SIZE = (1 << 16) - 1; sm MAX_LOOKBACK = (1 << 8) - 1; um MIN_RUN_LEN = 8; sm last_copy_idx = -1; sm last_copy_len = 0; for(sm i=0; i<input.count; ) { um start = MAX(0, i-MAX_LOOKBACK); auto best_match = find_best_prefix_match(input, start, i, MAX_RUN_SIZE); if(best_match.run_len < MIN_RUN_LEN) { if(last_copy_idx == -1 || last_copy_len >= MAX_RUN_SIZE) { last_copy_idx = output->count+1; last_copy_len = 0; data_buffer_append(output, (u8)0x00); data_buffer_append(output, (u16)0x0000); } last_copy_len++; data_buffer_append(output, input.data[i]); *(u16 *)(output->data+last_copy_idx) = last_copy_len; i++; } else { data_buffer_append(output, (u8)(i-best_match.run_start)); data_buffer_append(output, (u16)best_match.run_len); last_copy_idx = -1; i += best_match.run_len; } } } DECOMPRESS_DEF(lz_decompress) { um i; for(i=0; i<input.count-3; ) { u8 offset = input.data[i++]; u16 length = *(u16 *)(input.data + i); i += 2; if(offset == 0) { if(i+length > input.count)return false; data_buffer_append_memory(output, {input.data+i, length}); i += length; } else { if((sm)output->count - (sm)offset < 0)return false; data_buffer_ensure_room_for(output, length); for(um j=0; j<length; j++) { output->data[output->count+j] = output->data[output->count-offset+j]; } output->count += length; } } if(i != input.count)return false; return true; } <file_sep>/src/RLE.cpp COMPRESS_DEF(rle_compress) { um MAX_RUN_LEN = 32767; um MIN_RUN_LEN = 4; sm last_copy_idx = -1; um last_copy_len = 0; for(um i=0; i < input.count; ) { u8 c = input.data[i]; u16 run_len = 1; // grap the following characters if they are the same as this character. while(i+run_len < input.count && run_len < MAX_RUN_LEN && c == input.data[i+run_len])run_len++; // If the run of repeated characters is above a minimum length if(run_len >= MIN_RUN_LEN) { // push the run length as 16bit Little Endian (the 16th bit is always zero). data_buffer_append(output, run_len); // push the repeated character. data_buffer_append(output, c); last_copy_idx = -1; } else { if(last_copy_idx == -1 || last_copy_len >= MAX_RUN_LEN) { // Initialize a data copy run. last_copy_idx = output->count; last_copy_len = 0; // push the initial run size as 16bit-LE (the 16th bit is always one). data_buffer_append(output, (u16)0x8000); } // ensure the run size doesn't exceed MAX_RUN_LEN run_len = MIN(run_len, MAX_RUN_LEN - last_copy_len); // append data to previous copy run. last_copy_len += run_len; for(um j=0; j<run_len; j++)data_buffer_append(output, input.data[i+j]); // overwrite the old run size with the new one as 16bit-LE (the 16th bit is always one). *(u16 *)(output->data+last_copy_idx) = 0x8000 + last_copy_len; } i += run_len; } } DECOMPRESS_DEF(rle_decompress) { um i; for(i=0; i<input.count-2; ) { // read 16bit-LE u16 run_len = *(u16 *)(input.data + i); i += 2; // If the 16th bit is set then it is a copy run if(run_len & 0x8000) { run_len = run_len & 0x7fff; if(i+run_len > input.count)return false; data_buffer_append_memory(output, {input.data+i, run_len}); i += run_len; } else // it is a repeated run. { if(i >= input.count)return false; u8 repeated_byte = input.data[i++]; // write the repeated byte to output. data_buffer_ensure_room_for(output, run_len); for(um j=0; j<run_len; j++) { output->data[output->count++] = repeated_byte; } } } if(i != input.count)return false; return true; } <file_sep>/src/mystd.h #include <stdint.h> #include <string.h> #include <stdlib.h> typedef uint8_t u8; typedef uint16_t u16; typedef size_t um; typedef intptr_t sm; #ifndef MAX #define MAX(a, b) ( (a) > (b) ? (a) : (b) ) #endif #ifndef MIN #define MIN(a, b) ( (a) < (b) ? (a) : (b) ) #endif struct DataView { u8 *data; um count; }; struct DataBuffer { u8 *data; um size, count; DataView to_data_view(){ return {data, count}; } }; #ifdef MYSTD_IMPLEMENTATION void data_buffer_ensure_room_for(DataBuffer *buffer, um room_for) { if(buffer->count+room_for > buffer->size) { um new_size = MAX(8, 2 * buffer->size); new_size = MAX(new_size, buffer->count+room_for); buffer->data = (u8 *)realloc(buffer->data, new_size); buffer->size = new_size; } } void data_buffer_append(DataBuffer *buffer, u8 byte) { data_buffer_ensure_room_for(buffer, 1); buffer->data[buffer->count] = byte; buffer->count += 1; } void data_buffer_free(DataBuffer *buffer) { free(buffer->data); buffer->data = NULL; buffer->count = 0; buffer->size = 0; } void data_buffer_append(DataBuffer *buffer, u16 two_bytes) { data_buffer_ensure_room_for(buffer, 2); *(u16 *)(buffer->data + buffer->count) = two_bytes; buffer->count += 2; } void data_buffer_append_memory(DataBuffer *buffer, DataView memory) { data_buffer_ensure_room_for(buffer, memory.count); memcpy(buffer->data+buffer->count, memory.data, memory.count); buffer->count += memory.count; } bool data_equal(DataView a, DataView b) { if(a.count != b.count)return false; return memcmp(a.data, b.data, a.count) == 0; } #endif <file_sep>/src/compressor-interface.h #define COMPRESS_DEF(name) void name(DataView input, DataBuffer *output) #define DECOMPRESS_DEF(name) bool name(DataView input, DataBuffer *output) typedef COMPRESS_DEF(compress_fn); typedef DECOMPRESS_DEF(decompress_fn); <file_sep>/src/simple_compressor.cpp #define MYSTD_IMPLEMENTATION #include "mystd.h" #include "file.h" #include "compressor-interface.h" #include "RLE.cpp" #include "LZ.cpp" #define VERIFY_COMPRESSION 1 void usage() { printf("\n"); printf(" Usage: simple_compressor compress <raw-file> <output-file>\n"); printf(" simple_compressor decompress <output-file> <raw-file>\n"); printf("\n"); } struct CompressorDesc { char *name; compress_fn *compress; decompress_fn *decompress; }; #define COMPRESSIO_RLE 0 #define COMPRESSIO_LZ 1 CompressorDesc compressors[] = { {"RLE", rle_compress, rle_decompress}, {"LZ", lz_compress, lz_decompress}, }; enum AppCommand { AppCommand_Unknown, AppCommand_Compress, AppCommand_Decompress, }; int main(int argc, char **argv) { if(argc != 4) { printf("\nError: incorrect number of arguments.\n"); usage(); return 1; } char *command_str = argv[1]; char *input_file_path = argv[2]; char *output_file_path = argv[3]; AppCommand command = AppCommand_Unknown; if(strcmpi(command_str, "compress") == 0) { command = AppCommand_Compress; } else if(strcmpi(command_str, "decompress") == 0) { command = AppCommand_Decompress; } else { printf("\nError: unknown command '%s'.\n", command_str); usage(); return 2; } auto read_result = read_input_file(input_file_path); if(!read_result.succeeded) { printf("\nError: failed to load input file '%s'\n", input_file_path); return 3; } auto input_data = read_result.data; auto compressor = compressors[COMPRESSIO_LZ]; switch(command) { case AppCommand_Compress:{ DataBuffer compressed_data = {}; compressor.compress(input_data, &compressed_data); if(VERIFY_COMPRESSION) { DataBuffer decompressed_data = {}; auto succeeded = compressor.decompress(compressed_data.to_data_view(), &decompressed_data); if(!succeeded || !data_equal(input_data, decompressed_data.to_data_view())) { printf("\nError: We didn't get the same data after decompressing the compressed output!\n\n"); return 5; } data_buffer_free(&decompressed_data); } if(!write_output_file(output_file_path, compressed_data.to_data_view())) { printf("\nError: Failed to write the compressed file to '%s'\n\n", output_file_path); return 4; } printf("\n"); printf("Original size: %llu\n", input_data.count); printf("Compressed size: %llu\n", compressed_data.count); printf("Compression percentage: %%%.2f\n", 100.0 * compressed_data.count/input_data.count); printf("\n"); data_buffer_free(&compressed_data); }break; case AppCommand_Decompress:{ DataBuffer uncompressed_data = {}; if(!compressor.decompress(input_data, &uncompressed_data)) { printf("\nError: the file is corrupted. Could not decompress\n\n"); return 5; } if(!write_output_file(output_file_path, uncompressed_data.to_data_view())) { printf("\nError: Failed to write the decompressed file to '%s'\n\n", output_file_path); return 4; } data_buffer_free(&uncompressed_data); }break; default: { printf("\nInternal Error: unhandled command '%d'\n", command); return 999; }break; } read_file_result_free(&input_data); return 0; }
1e09b85b474dd781e68b70b3597c30994181bc56
[ "C", "C++" ]
6
C
aameen951/simple_compressor
a0c9bb86cdec0c31cf34f87f084c474e2b92867d
a30bbbd534fef82d99a3c814af6b6d91536920f7
refs/heads/master
<repo_name>RegularTriangle/Study<file_sep>/Python/draw_owl.py #部分代码参考CSDN, 但是时间有点久, 记不清参考哪个帖子了 from turtle import * #设置画板大小 wight = 900 height = 1000 setup(wight,height) #绘制速率 speed(10) #取消画布的延迟 #Turtle().screen.delay(1) #绘制网格 for i in range(17): up() goto(0+i*50-wight/2+50,0-height/2+50) down() seth(90) forward(1000) for i in range(20): up() goto(0-wight/2+50,0+i*50-height/2+50) down() seth(0) forward(800) #颜色设置 branch_color = "#E66129" #树枝 leaf_color = "#BD4416" #树叶 head_color = "#5F2C89" #头 face_color = "#B292C3" #脸 mouth_color = "#F7BB61" #嘴巴 eye_color1 = "#FFFFFF" #眼睛 eye_color2 = "#000000" #眼球 eyelid_color = "#CBB6D7" #眼帘 feather_color1 = "#CCB3D3" #胸脯 feather_color2 = "#9377A7" #羽毛 foot_color = "#5E4133" #脚 sign_color = "#8CCDED" #签名 #树枝 width(10) color(branch_color) fillcolor(branch_color) up() goto(-170,-50) down() seth(-15) for i in range(400): left(0.1) forward(1) #树叶 leaf_fillcolor = "#00FF40" color(leaf_color) ##下面叶子 seth(5) width(3) begin_fill() fillcolor(leaf_fillcolor) for i in range(2): for j in range(1,61): forward(3) right(2) right(60) end_fill() ##树叶中间的线 seth(-83) for i in range(190): left(0.3) forward(0.8) ##上面叶子 up() goto(220,-10) down() begin_fill() fillcolor(leaf_fillcolor) seth(130) for i in range(2): for j in range(1,61): forward(3) right(2) right(60) end_fill() ##树叶中间的线 seth(100) for i in range(190): right(0.3) forward(0.8) #头 width(10) up() goto(0,0) down() seth(0) color(head_color) begin_fill() fillcolor(head_color) circle(200) end_fill() #脸 ##左边直线 begin_fill() color(face_color) fillcolor(face_color) up() goto(-150,70) down() width(3) color(face_color) seth(90) forward(265) right(25) forward(170) right(120) forward(137) seth(270) forward(303) goto(-150,70) end_fill() ##右边直线 begin_fill() color(face_color) fillcolor(face_color) up() goto(150,70) down() width(3) seth(90) forward(265) left(25) forward(170) left(120) forward(137) seth(270) forward(303) goto(150,70) end_fill() #嘴巴 up() goto(30,260) down() begin_fill() color(mouth_color) fillcolor(mouth_color) seth(0) #left(4) width(3) for i in range(3): right(120) forward(60) end_fill() #眼睛 up() goto(-60,250) down() begin_fill() color(eye_color1) fillcolor(eye_color1) seth(0) width(3) circle(60) up() goto(60,250) down() circle(60) end_fill() #眼珠 up() goto(45,300) down() begin_fill() color(eye_color2) fillcolor(eye_color2) circle(15) up() goto(-45,300) down() circle(15) end_fill() #眼皮 width(8) ##左边 up() goto(-115,290) down() begin_fill() color(eyelid_color) fillcolor(eyelid_color) left(35) forward(111) seth(138) circle(60,154) end_fill() ##右边 begin_fill() up() goto(115,290) down() seth(180) right(35) forward(111) seth(44) circle(-60,154) end_fill() #胸部 #胸脯 ##左边圆弧 width(10) begin_fill() color(feather_color1) fillcolor(feather_color1) up() goto(0,0) down() seth(180) circle(-200,47.5) seth(0) forward(153) goto(0,0) ##右边圆弧 width(10) seth(0) circle(200,47.5) seth(180) forward(153) goto(0,0) end_fill() ##上面圆弧 width(3) begin_fill() color(feather_color1) fillcolor(feather_color1) up() goto(-150,70) down() seth(85) circle(-150,170) end_fill() ##羽毛 width(2) color(feather_color2) fillcolor(feather_color2) for i in range(3): up() goto(-80 - i*20,170 - i*35) down() for j in range(4): if j < 2: seth(260) circle(20 + i*5, 180) else: seth(280) circle(20 + i*5, 180) #脚 color(foot_color) ##左脚 up() goto(-60,10) down() seth(270) width(10) forward(50) seth(-150) forward(80) up() goto(-60,-40) down() seth(-120) forward(85) up() goto(-60,-40) down() seth(-55) forward(78) ##右脚 up() goto(60,10) down() seth(270) width(10) forward(50) seth(-130) forward(80) up() goto(60,-40) down() seth(-75) forward(85) up() goto(60,-40) down() seth(-40) forward(78) #签名 up() goto(-300,-250) color(sign_color) write("十万九千七",font=("微软雅黑",30)) goto(-280,-300) write("2020年1月1日",font=("微软雅黑",30)) #隐藏海龟并结束 hideturtle() done() <file_sep>/README.md # Study Learning Record
9b68607f49a37b5d8f3fc00a48d620ec99f2fd80
[ "Markdown", "Python" ]
2
Python
RegularTriangle/Study
8366b3fa962f425bcfc561ac9e1ef8ec9def26a8
9fe3f1701fa00d95b23248e5215a13d1bb2e58c2
refs/heads/master
<repo_name>kevinkovalchik/RealTimeOrbiWiz<file_sep>/RealTimeOrbiWiz/Program.cs using System; using System.IO; using System.Security.Permissions; using System.Threading.Tasks; using ThermoFisher.CommonCore.Data.Business; using ThermoFisher.CommonCore.Data; using System.Linq; namespace RealTimeOrbiWiz { class Program { public static void Main(string[] args) { Run(args); } [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] // I don't remember why this is here. I think something to do with watching the filesystem, but maybe try deleting it and see if things still work. private static void Run(string[] args) { // If a directory is not specified, exit program. if (args.Length != 1) { // Display the proper way to call the program. Console.WriteLine("Usage: RealTimeOrbiWiz.exe (directory)"); return; } // Create a new FileSystemWatcher and set its properties. using (FileSystemWatcher watcher = new FileSystemWatcher()) { watcher.Path = args[0]; // Watch for changes in LastAccess and LastWrite times, and // the renaming of files or directories. watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime; // Only watch .raw files. watcher.Filter = "*.raw"; // Add event handlers. //watcher.Changed += OnChanged; watcher.Created += OnCreated; //watcher.Deleted += OnChanged; //watcher.Renamed += OnRenamed; // Begin watching. watcher.EnableRaisingEvents = true; // Wait for the user to quit the program. // Console.WriteLine("Press 'q' to quit the sample."); Console.WriteLine("Running. Waiting for new files to show up... Press 'q' to quit"); while (Console.Read() != 'q') { }; } } // Define the event handlers. private static void OnChanged(object source, FileSystemEventArgs e) => // Specify what is done when a file is changed, created, or deleted. Console.WriteLine($"File: {e.FullPath} {e.ChangeType}"); private static void OnRenamed(object source, RenamedEventArgs e) => // Specify what is done when a file is renamed. Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}"); private static void OnCreated(object source, FileSystemEventArgs e) { Console.WriteLine($"File: {e.FullPath} created"); Task.Run(() => WatchFile(e.FullPath)).Wait(); } private static void WatchFile(string pathToRawFile) { using (var f = new StreamWriter("rawFileAcquisitionInfo.txt", append: true)) { using (var rawFile = RawFileReaderFactory.CreateThreadManager(pathToRawFile).CreateThreadAccessor()) { rawFile.SelectMsData(); DateTime created = DateTime.Now; f.WriteLine($"{pathToRawFile} created at {created}"); f.WriteLine($"InAcquisition: {rawFile.InAcquisition}"); f.WriteLine($"Run header: {rawFile.RunHeader.ToString()}"); f.WriteLine($"Spectra count: {rawFile.RunHeaderEx.SpectraCount}"); Console.WriteLine($"{pathToRawFile} created at {created}"); Console.WriteLine($"InAcquisition: {rawFile.InAcquisition}"); Console.WriteLine($"Run header: {rawFile.RunHeader.ToString()}"); Console.WriteLine($"Spectra count: {rawFile.RunHeaderEx.SpectraCount}"); int lastSpectrum = rawFile.RunHeader.LastSpectrum; int spectraCount = rawFile.RunHeaderEx.SpectraCount; while (spectraCount == rawFile.RunHeaderEx.SpectraCount || lastSpectrum == rawFile.RunHeader.LastSpectrum) { Console.WriteLine($"Waiting for a spectrum to be recorded. {(DateTime.Now - created).TotalSeconds} seconds elapsed."); f.WriteLine($"Waiting for a spectrum to be recorded. {(DateTime.Now - created).TotalSeconds} seconds elapsed."); Task.Delay(5000).Wait(); rawFile.RefreshViewOfFile(); } Console.WriteLine("A spectrum has been recorded."); f.WriteLine("A spectrum has been recorded."); var firstRecordedSpec = rawFile.RunHeader.FirstSpectrum; var rtInSecBeforeFirstScan = rawFile.RetentionTimeFromScanNumber(firstRecordedSpec) * 60; var deadTime = (DateTime.Now - created).TotalSeconds - rtInSecBeforeFirstScan; Console.WriteLine($"Dead time: {deadTime}"); f.WriteLine($"Dead time: {deadTime}"); Console.WriteLine("Now watching the file as new spectra are recorded."); f.WriteLine("Now watching the file as new spectra are recorded."); while (rawFile.InAcquisition) { rawFile.RefreshViewOfFile(); lastSpectrum = rawFile.RunHeader.LastSpectrum; spectraCount = rawFile.RunHeaderEx.SpectraCount; var scan = rawFile.GetScanEventForScanNumber(lastSpectrum); Console.WriteLine($"Seconds since file creation: {(DateTime.Now - created).TotalSeconds}"); Console.WriteLine($"Current retention time: {rawFile.RetentionTimeFromScanNumber(lastSpectrum)}"); Console.WriteLine($"Estimated time until end of run: {rawFile.RunHeader.ExpectedRuntime - rawFile.RetentionTimeFromScanNumber(lastSpectrum)}"); Console.WriteLine($"Latest spectrum: {lastSpectrum}\tTotal spectra: {spectraCount}"); Console.WriteLine($"Base intensity of latest scan: {rawFile.GetSegmentedScanFromScanNumber(lastSpectrum, null).Intensities.Max()}"); Console.WriteLine($"MS order of latest scan: {scan.MSOrder}"); Console.WriteLine(); f.WriteLine($"Seconds since file creation: {(DateTime.Now - created).TotalSeconds}"); f.WriteLine($"Current retention time: {rawFile.RetentionTimeFromScanNumber(lastSpectrum)}"); f.WriteLine($"Estimated time until end of run: {rawFile.RunHeader.ExpectedRuntime - rawFile.RetentionTimeFromScanNumber(lastSpectrum)}"); f.WriteLine($"Latest spectrum: {lastSpectrum}\tTotal spectra: {spectraCount}"); f.WriteLine($"Base intensity of latest scan: {rawFile.GetSegmentedScanFromScanNumber(lastSpectrum, null).Intensities.Max()}"); f.WriteLine($"MS order of latest scan: {scan.MSOrder}"); f.WriteLine(); Task.Delay(30000).Wait(); } f.WriteLine($"{rawFile.FileName} reports it is done being acquired!"); Console.WriteLine($"{rawFile.FileName} reports it is done being acquired! Press any key to exit."); Console.ReadKey(); Environment.Exit(0); } } } } }
31d2ea0fb7739511666ccaa9d2f6a0d808ca0451
[ "C#" ]
1
C#
kevinkovalchik/RealTimeOrbiWiz
14cf1092fdcf7cd61ef559ba11ebfac9f565fdfd
1d5d47577d7239e91204f2170979debb57a02a35
refs/heads/main
<file_sep>require 'time' class Hiker attr_reader :name, :experience_level, :snacks, :parks_visited def initialize(name, experience_level) @name = name @experience_level = experience_level @snacks = Hash.new(0) @parks_visited = [] end def pack(snack, quantity) @snacks[snack] += quantity end def visit(park, date = Date.today.strftime('%d%m%y')) @parks_visited << park park.mark_vistor_log(self, date) end def possible_trails @parks_visited.flat_map do |park| park.trails.find_all do |trail| trail.level == @experience_level end end end def favorite_snack favorite_snack = @snacks.max_by do |snack, quantity| quantity end favorite_snack.first end end<file_sep>class Trail attr_reader :name, :length, :level def initialize(attributes) @name = attributes[:name] @length = attributes[:length].split().first.to_f @level = attributes[:level] end end<file_sep>require 'rspec' require './lib/trail' RSpec.describe Trail do before do @trail = Trail.new({name: 'Grand Wash', length: '2.2 miles', level: :easy}) end describe '#initialize' do it 'exists' do expect(@trail).to be_a(Trail) end it 'has attributes' do expect(@trail.name).to eq('Grand Wash') expect(@trail.length).to eq(2.2) expect(@trail.level).to eq(:easy) end end end <file_sep>class Park attr_reader :name, :trails, :log def initialize(name) @name = name @trails = [] @log = {} end def add_trail(trail) @trails << trail end def trails_shorter_than(length) @trails.find_all do |trail| trail.length < 2.5 end end def hikeable_miles @trails.sum do |trail| trail.length end end def trails_by_level @trails.each_with_object({}) do |trail, hash| hash[trail.level] = names_of_trails_at_level(trail.level) end end def mark_vistor_log(hiker, date) @log[hiker] = date end def visitors_log #wasted too much time trying to get the stub to actually do this :'( visitors_log = {} @log.each do |hiker, date| visitors_log[date] = hiker end end private def trails_at_level(experience_level) @trails.find_all do |trail| trail.level == experience_level end end def names_of_trails_at_level(experience_level) trails_at_level(experience_level).map do |trail| trail.name end end end<file_sep>require 'rspec' require './lib/park' require './lib/trail' RSpec.describe Park do before do @trail1 = Trail.new({name: 'Grand Wash', length: '2.2 miles', level: :easy}) @trail2 = Trail.new({name: '<NAME>', length: '1.7 miles', level: :moderate}) @trail3 = Trail.new({name: 'Chimney Rock Loop', length: '3.6 miles', level: :strenuous}) @trail4 = Trail.new({name: "Queen's/Navajo Loop", length: '2.9 miles', level: :moderate}) @trail5 = Trail.new({name: 'Rim Trail', length: '11 miles', level: :easy}) @trail6 = Trail.new({name: 'Tower Bridge', length: '3 miles', level: :moderate}) @park1 = Park.new('Capitol Reef') @park2 = Park.new('Bryce Canyon') @hiker1 = Hiker.new('Dora', :moderate) @hiker2 = Hiker.new('Frank', :easy) @hiker3 = Hiker.new('Jack', :strenuous) @hiker4 = Hiker.new('Sally', :strenuous) end describe '#initialize' do it 'exists' do expect(@park1).to be_a(Park) end it 'has attributes' do expect(@park1.name).to eq('Capitol Reef') expect(@park1.trails).to eq([]) end end describe '#add_trail' do it 'allows you to add trails' do @park1.add_trail(@trail1) @park1.add_trail(@trail2) expect(@park1.trails).to eq([@trail1, @trail2]) end end describe '#trails_shorter_than' do it 'returns trails shorter than a specified value' do @park1.add_trail(@trail1) @park1.add_trail(@trail2) @park1.add_trail(@trail3) @park2.add_trail(@trail4) @park2.add_trail(@trail5) @park2.add_trail(@trail6) expect(@park1.trails_shorter_than(2.5)).to eq([@trail1, @trail2]) expect(@park2.trails_shorter_than(2.5)).to eq([]) end end describe '#hikeable_miles' do it 'returns the total hikeable miles in a park' do @park1.add_trail(@trail1) @park1.add_trail(@trail2) @park1.add_trail(@trail3) @park2.add_trail(@trail4) @park2.add_trail(@trail5) @park2.add_trail(@trail6) expect(@park1.hikeable_miles).to eq(7.5) expect(@park2.hikeable_miles).to eq(16.9) end end describe '#trails_by_level' do it 'returns a hash of trails by level' do @park1.add_trail(@trail1) @park1.add_trail(@trail2) @park1.add_trail(@trail3) @park2.add_trail(@trail4) @park2.add_trail(@trail5) @park2.add_trail(@trail6) park1_trails_by_level = { :easy => ['Grand Wash'], :moderate => ['Cohab Canyon'], :strenuous => ["Chimney Rock Loop"] } park2_trails_by_level = { :easy => ["Rim Trail"], :moderate => ["Queen's/Navajo Loop", "Tower Bridge"] } expect(@park1.trails_by_level).to eq(park1_trails_by_level) expect(@park2.trails_by_level).to eq(park2_trails_by_level) end end describe '#visitors_log' do it 'returns a hash detailing the visitor logs' do #will clean up hooking later, time allowing trail1 = Trail.new({name: 'Rim Trail', length: '11 miles', level: :easy}) trail2 = Trail.new({name: "Queen's/Navajo Loop", length: '2.9 miles', level: :moderate}) trail3 = Trail.new({name: 'Tower Bridge', length: '3 miles', level: :moderate}) trail4 = Trail.new({name: 'Peekaboo Loop', length: '5.5 miles', level: :strenuous}) @park2.add_trail(trail1) @park2.add_trail(trail2) @park2.add_trail(trail3) @park2.add_trail(trail4) #STUBS ARE THE BANE OF MY EXISTENCE!!!!!!! # allow(@hiker1).to receive(:visit).with(@park2, 'dogs') @hiker1.visit(@park2, '19800623') @hiker2.visit(@park2, '19800624') @hiker3.visit(@park2, '19800624') @hiker4.visit(@park2, '19800625') @hiker1.visit(@park2, '20200623') @hiker2.visit(@park2, '20200624') @hiker3.visit(@park2, '20200624') @hiker4.visit(@park2, '20200625') expect(@park2.visitors_log).to be_a(Hash) end end end<file_sep>require 'rspec' require './lib/hiker' require './lib/park' require './lib/trail' RSpec.describe Hiker do before do @trail1 = Trail.new({name: 'Grand Wash', length: '2.2 miles', level: :easy}) @trail2 = Trail.new({name: '<NAME>', length: '1.7 miles', level: :moderate}) @trail3 = Trail.new({name: 'Chimney Rock Loop', length: '3.6 miles', level: :strenuous}) @trail4 = Trail.new({name: "Queen's/Navajo Loop", length: '2.9 miles', level: :moderate}) @trail5 = Trail.new({name: 'Rim Trail', length: '11 miles', level: :easy}) @trail6 = Trail.new({name: 'Tower Bridge', length: '3 miles', level: :moderate}) @park1 = Park.new('Capitol Reef') @park2 = Park.new('Bryce Canyon') @hiker = Hiker.new('Dora', :moderate) end describe '#initialize' do it 'exists' do expect(@hiker).to be_a(Hiker) end it 'has attributes' do expect(@hiker.name).to eq('Dora') expect(@hiker.experience_level).to eq(:moderate) expect(@hiker.snacks).to eq({}) expect(@hiker.parks_visited).to eq([]) end end describe '#pack' do it 'adds snacks for the hiker' do @hiker.pack('water', 1) @hiker.pack('trail mix', 3) expect(@hiker.snacks).to eq({"water"=>1, "trail mix"=>3}) @hiker.pack('water', 1) expect(@hiker.snacks).to eq({"water"=>2, "trail mix"=>3}) end end describe '#visit' do it 'lets the hiker visit parks' do @hiker.visit(@park1) @hiker.visit(@park2) # allow(@park1).to receive(:mark_vistor_log) #{visitors_log[@hiker] => '19800623'} # allow(@park2).to receive(:mark_vistor_log)# {visitors_log[@hiker] => '19800623'} expect(@hiker.parks_visited).to eq([@park1, @park2]) end end describe '#possible_trails' do it 'returns and array of trails matching the hikers experience lvl for visited parks' do @park1.add_trail(@trail1) @park1.add_trail(@trail2) @park1.add_trail(@trail3) @park2.add_trail(@trail4) @park2.add_trail(@trail5) @park2.add_trail(@trail6) @hiker.visit(@park1) @hiker.visit(@park2) expect(@hiker.possible_trails).to eq([@trail2, @trail4, @trail6]) end end describe '#favorite_snack' do it 'tells you which snack the hiker packed the most of' do @hiker.pack('water', 2) @hiker.pack('trail mix', 1) @hiker.pack('apple', 4) @hiker.pack('carrot', 3) expect(@hiker.favorite_snack).to eq('apple') end end end
3f7e94ff9c5dcc1f129c64d0a41abf84d5efa6dc
[ "Ruby" ]
6
Ruby
netia1128/adventure_2103
b207eee32bef327bee85f58807818b75a66a4fbf
987efdd1e919e51dfa10c232f15b963d43a088bd
refs/heads/master
<repo_name>JakeDillon/model-a-car<file_sep>/Model a car/main.swift // // main.swift // Model a car // // Created by <NAME> on 8/20/18. // Copyright © 2018 <NAME>. All rights reserved. // import Foundation print("Hello, World!")
9099dc486aa6a8a24c776c0d4385c33f7a119c82
[ "Swift" ]
1
Swift
JakeDillon/model-a-car
56de2e6890533341d4e817fa188922244bad9281
ef08f85790aa2258400a9b87a644af6a6fbc96b2
refs/heads/master
<file_sep>package view.Empreededor; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; public final class Alterar extends JFrame{ //Instancia private static Alterar instancia; //Variáveis do JFrame private javax.swing.JButton alterarLoja; private javax.swing.JButton alterarProduto; private javax.swing.JPanel jPanel1; //Singleton private Alterar(){ initComponents(); } public static Alterar getInstance(){ if(instancia == null) instancia = new Alterar(); return instancia; } //Eventos private void alterarProdutoActionPerformed(java.awt.event.ActionEvent evt) { } private void alterarLojaActionPerformed(java.awt.event.ActionEvent evt) { AlterarLoja.getInstance().setVisible(true); instancia.setVisible(false); } //Inicia os componentes private void initComponents() { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); jPanel1 = new javax.swing.JPanel(); alterarProduto = new javax.swing.JButton(); alterarLoja = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent we){ Alterar.getInstance().setVisible(false); Plataforma.getInstance().setVisible(true); } }); setTitle("Alterar"); alterarProduto.setText("Alterar dados de um produto"); alterarProduto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { alterarProdutoActionPerformed(evt); } }); alterarLoja.setText("Alterar dados da loja"); alterarLoja.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { alterarLojaActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(64, 64, 64) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(alterarProduto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(alterarLoja, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(71, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(60, Short.MAX_VALUE) .addComponent(alterarProduto, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39) .addComponent(alterarLoja, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(53, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); } } <file_sep>package view.Cliente; import controller.LojaDAO; import controller.ProdutoDAO; import java.awt.Component; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; import model.Endereco; import model.Loja; import model.Produto; import view.ControladorDeJanelas; import view.Exceptions.GUIException; import view.Exceptions.InvalidTextException; public class ClienteConsultaEspecifica extends JFrame{ //Instancia do singleton private static ClienteConsultaEspecifica instancia; //Variáveis do JFrame private javax.swing.JTextField cityTextField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField neighbourTextField; private javax.swing.JTextField pesquisaTextField; private javax.swing.JButton searchButton; //Singleton private ClienteConsultaEspecifica(){ initComponents(); } public static ClienteConsultaEspecifica getInstance(){ if(instancia == null){ instancia = new ClienteConsultaEspecifica(); } return instancia; } //Eventos private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException { ArrayList<Produto> produtos = new ArrayList<>(); ArrayList<Produto> produtos_validos = new ArrayList<>(); String nome_produto_busca; String cidade; String bairro; Loja loja; ArrayList<Integer> lojas; ControladorDeJanelas.clearRows(jTable1); try{ //Captura os dados dos text fields nome_produto_busca = ControladorDeJanelas.getTextField(pesquisaTextField); cidade = ControladorDeJanelas.getTextField(cityTextField); bairro = ControladorDeJanelas.getTextField(neighbourTextField); //Captura todos os produtos com o nome no campo do text field produtos = ProdutoDAO.obterProdutos(nome_produto_busca); //Obtem as lojas que possuem aquele produto lojas = ProdutoDAO.obterIdLojas(nome_produto_busca); //Atribui a loja a qual pertence para cada produto for(int i = 0; i < produtos.size();i++){ loja = LojaDAO.obterLoja(lojas.get(i)); produtos.get(i).setLoja(loja); } //Separa os produtos que são válidos for(int i = 0; i < produtos.size();i++){ Produto produto_atual = produtos.get(i); Loja loja_atual = produto_atual.getLoja(); Endereco endereco_atual = loja_atual.getEndereco(); if((endereco_atual.getBairro().compareTo(bairro)) == 0 && (endereco_atual.getCidade().compareTo(cidade)) == 0) { produtos_validos.add(produto_atual); } } if(produtos_validos.size() == 0){ JOptionPane.showMessageDialog(null, "Nenhum produto encontrado", "Lamentamos", JOptionPane.INFORMATION_MESSAGE); }else{ ControladorDeJanelas.fillTableEspecifica(jTable1, produtos_validos); } }catch(InvalidTextException e){ new GUIException(e.getMessage()); } } private void pesquisaTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException { searchButtonActionPerformed(evt); } private void cityTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException { searchButtonActionPerformed(evt); } private void neighbourTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException { searchButtonActionPerformed(evt); } //Inicia os componentes private void initComponents() { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); setTitle("Consulta por bairro"); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); pesquisaTextField = new javax.swing.JTextField(); pesquisaTextField.setName("pesquisa"); searchButton = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); cityTextField = new javax.swing.JTextField(); cityTextField.setName("cidade"); neighbourTextField = new javax.swing.JTextField(); neighbourTextField.setName("bairro"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent we){ cityTextField.setText(""); neighbourTextField.setText(""); pesquisaTextField.setText(""); instancia.setVisible(false); PonteCliente.getInstance().setVisible(true); ControladorDeJanelas.clearRows(jTable1); } }); jTable1.setAutoCreateRowSorter(true); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Nome:", "Quantidade:", "Preço:", "Loja:" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(jTable1); pesquisaTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { pesquisaTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { Logger.getLogger(ClienteConsultaEspecifica.class.getName()).log(Level.SEVERE, null, ex); } } }); searchButton.setText("Procurar"); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { searchButtonActionPerformed(evt); } catch (InvalidTextException ex) { Logger.getLogger(ClienteConsultaEspecifica.class.getName()).log(Level.SEVERE, null, ex); } } }); jLabel1.setText("Digite o nome do produto que deseja buscar:"); jLabel2.setText("Em qual bairro deseja buscar ?"); jLabel3.setText("Em qual cidade deseja buscar ?"); cityTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { cityTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { Logger.getLogger(ClienteConsultaEspecifica.class.getName()).log(Level.SEVERE, null, ex); } } }); neighbourTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { neighbourTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { Logger.getLogger(ClienteConsultaEspecifica.class.getName()).log(Level.SEVERE, null, ex); } } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 520, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(neighbourTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(36, 36, 36)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel2) .addGap(150, 150, 150)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(cityTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(36, 36, 36)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel3) .addGap(147, 147, 147)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pesquisaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(36, 36, 36)))) .addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(28, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(pesquisaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cityTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(neighbourTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(searchButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); } } <file_sep>package view.Exceptions; import javax.swing.JOptionPane; public class GUIException { /** * Exibe uma tela de exceção com o texto "text" * @param text Texto a ser exibo na GUI de erro */ public GUIException(String text){ JOptionPane.showMessageDialog(null, text, "Erro", JOptionPane.WARNING_MESSAGE,null); } } <file_sep>package view.Cliente; import controller.*; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JOptionPane; import model.Produto; import view.ControladorDeJanelas; import view.Exceptions.GUIException; import view.Exceptions.InvalidTextException; public class ClienteConsultaGeral extends JFrame{ //Variáveis do JFrame private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField pesquisaTextField; private javax.swing.JButton searchButton; //Instancia Singleton private static ClienteConsultaGeral instancia; //Singleton private ClienteConsultaGeral(){ initComponents(); } public static ClienteConsultaGeral getInstance(){ if(instancia == null) instancia = new ClienteConsultaGeral(); return instancia; } //Eventos private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException, SQLException { try{ ControladorDeJanelas.clearRows(jTable1); String query; ArrayList<Produto> produtos = new ArrayList<>(); query = ControladorDeJanelas.getTextField(pesquisaTextField); produtos = ProdutoDAO.obterProdutos(query); if(produtos.size() <= 0){ JOptionPane.showMessageDialog(null, "Nenhum produto encontrado!", "Lamentamos", JOptionPane.WARNING_MESSAGE); }else{ ControladorDeJanelas.fillTableGeral(jTable1, produtos); } }catch(InvalidTextException e){ new GUIException(e.getMessage()); } } private void pesquisaTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException, SQLException { searchButtonActionPerformed(evt); } //Inicia os componentes private void initComponents() { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); pesquisaTextField = new javax.swing.JTextField(); pesquisaTextField.setName("pesquisa"); searchButton = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setTitle("Consulta"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent we){ PonteCliente.getInstance().setVisible(true); ControladorDeJanelas.clearRows(jTable1); pesquisaTextField.setText(""); instancia.setVisible(false); } }); jTable1.setAutoCreateRowSorter(true); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Nome:", "Quantidade:", "Preço:", "Loja:" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(jTable1); pesquisaTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { pesquisaTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { Logger.getLogger(ClienteConsultaGeral.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(ClienteConsultaGeral.class.getName()).log(Level.SEVERE, null, ex); } } }); searchButton.setText("Procurar"); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { searchButtonActionPerformed(evt); } catch (InvalidTextException ex) { Logger.getLogger(ClienteConsultaGeral.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(ClienteConsultaGeral.class.getName()).log(Level.SEVERE, null, ex); } } }); jLabel1.setText("Digite o nome do produto que deseja buscar:"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(pesquisaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addGap(62, 62, 62) .addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 520, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(37, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(pesquisaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(searchButton)) .addGap(26, 26, 26) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(39, Short.MAX_VALUE)) ); pack(); } } <file_sep>package view.Empreededor; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import model.*; import controller.*; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JOptionPane; import view.ControladorDeJanelas; import view.Exceptions.GUIException; import view.Exceptions.InvalidTextException; import view.RoundedBorder; public final class CadastroNovaLoja extends JFrame{ //Instância do Singleton private static CadastroNovaLoja instancia; //Construtor private CadastroNovaLoja(){ initComponents(); } public static CadastroNovaLoja getInstance(){ if(instancia == null){ instancia = new CadastroNovaLoja(); } return instancia; } //Variáveis do JFrame private javax.swing.JTextField bairroTextField; private javax.swing.JButton cadastrarNovaLoja; private javax.swing.JTextField cidadeTextField; private javax.swing.JTextField cnpjTextField; private javax.swing.JTextField estadoTextField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JTextField razaoSocialTextField; private javax.swing.JTextField ruaTextField; private javax.swing.JPasswordField senhaTextField; //Inicia os componentes private void initComponents() { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); cnpjTextField = new javax.swing.JTextField(); cnpjTextField.setName("cnpj"); razaoSocialTextField = new javax.swing.JTextField(); razaoSocialTextField.setName("razão social"); senhaTextField = new javax.swing.JPasswordField(); senhaTextField.setName("senha"); ruaTextField = new javax.swing.JTextField(); ruaTextField.setName("rua"); bairroTextField = new javax.swing.JTextField(); bairroTextField.setName("bairro"); cidadeTextField = new javax.swing.JTextField(); cidadeTextField.setName("cidade"); estadoTextField = new javax.swing.JTextField(); estadoTextField.setName("estado"); cadastrarNovaLoja = new javax.swing.JButton(); cadastrarNovaLoja.setBorder(new RoundedBorder(20)); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent we){ cnpjTextField.setText(""); senhaTextField.setText(""); ruaTextField.setText(""); bairroTextField.setText(""); estadoTextField.setText(""); cidadeTextField.setText(""); razaoSocialTextField.setText(""); Login.clearPasswordField(); Login.getInstance().setVisible(true); } }); setTitle("Cadastrar nova loja"); jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel1.setText("Digite o cnpj da empresa (somente números):"); jLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel2.setText("Informe a sua senha:"); jLabel3.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel3.setText("Informações sobre o endereço:"); jLabel4.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel4.setText("Rua:"); jLabel5.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel5.setText("Bairro:"); jLabel6.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel6.setText("Cidade:"); jLabel7.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel7.setText("Estado:"); jLabel8.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N jLabel8.setText("Informe a razão social:"); cnpjTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt){ try{ cnpjTextFieldActionPerformed(evt); }catch(InvalidTextException e){ System.out.println(e.getMessage()); } catch (CNPJException ex) { System.out.println(ex.getMessage()); } } }); razaoSocialTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { razaoSocialTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { System.out.println(ex.getMessage()); } catch (CNPJException ex) { System.out.println(ex.getMessage()); } } }); senhaTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { senhaTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { System.out.println(ex.getMessage()); } catch (CNPJException ex) { System.out.println(ex.getMessage()); } } }); ruaTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { ruaTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { System.out.println(ex.getMessage()); } catch (CNPJException ex) { System.out.println(ex.getMessage()); } } }); bairroTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { bairroTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { System.out.println(ex.getMessage()); } catch (CNPJException ex) { System.out.println(ex.getMessage()); } } }); cidadeTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { cidadeTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { System.out.println(ex.getMessage()); } catch (CNPJException ex) { System.out.println(ex.getMessage()); } } }); estadoTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { estadoTextFieldActionPerformed(evt); } catch (InvalidTextException ex) { System.out.println(ex.getMessage()); } catch (CNPJException ex) { } } }); jLabel9.setFont(new java.awt.Font("Lucida Grande", 0, 36)); // NOI18N jLabel9.setText("Cadastro"); cadastrarNovaLoja.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N cadastrarNovaLoja.setText("Cadastrar"); cadastrarNovaLoja.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try{ cadastrarNovaLojaActionPerformed(evt); }catch(InvalidTextException e){ System.out.println(e); } catch (CNPJException ex) { System.out.println(ex); } } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(38, 38, 38) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2) .addComponent(jLabel8) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3) .addComponent(razaoSocialTextField) .addComponent(cnpjTextField) .addComponent(senhaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 323, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(47, 47, 47) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ruaTextField) .addComponent(bairroTextField) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(jLabel5) .addComponent(jLabel4) .addComponent(jLabel7)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(cidadeTextField, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(estadoTextField)))) .addGroup(layout.createSequentialGroup() .addGap(99, 99, 99) .addComponent(jLabel9)))) .addGroup(layout.createSequentialGroup() .addGap(97, 97, 97) .addComponent(cadastrarNovaLoja, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(84, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel9) .addGap(18, 18, 18) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(razaoSocialTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel1) .addGap(7, 7, 7) .addComponent(cnpjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(senhaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4) .addGap(5, 5, 5) .addComponent(ruaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bairroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cidadeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(estadoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cadastrarNovaLoja, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(22, Short.MAX_VALUE)) ); pack(); } //Eventos private void senhaTextFieldActionPerformed(java.awt.event.ActionEvent evt)throws InvalidTextException,CNPJException { cadastrarNovaLojaActionPerformed(evt); } private void razaoSocialTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException,CNPJException{ cadastrarNovaLojaActionPerformed(evt); } private void cnpjTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException,CNPJException { cadastrarNovaLojaActionPerformed(evt); } private void ruaTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException,CNPJException{ cadastrarNovaLojaActionPerformed(evt); } private void bairroTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException,CNPJException { cadastrarNovaLojaActionPerformed(evt); } private void cidadeTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException,CNPJException { cadastrarNovaLojaActionPerformed(evt); } private void estadoTextFieldActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException,CNPJException { cadastrarNovaLojaActionPerformed(evt); } /** * Cadastra uma nova loja inserido esta no banco de dados * @param evt Evento que será acionado * @throws InvalidTextException e CNPJ Exception */ private void cadastrarNovaLojaActionPerformed(java.awt.event.ActionEvent evt) throws InvalidTextException,CNPJException{ Endereco end; Loja loja; boolean flag = false; try{ String razao_social = ControladorDeJanelas.getTextField(razaoSocialTextField); String cnpj = ControladorDeJanelas.getTextField(cnpjTextField); String rua = ControladorDeJanelas.getTextField(ruaTextField); String bairro = ControladorDeJanelas.getTextField(bairroTextField); String cidade = ControladorDeJanelas.getTextField(cidadeTextField); String estado = ControladorDeJanelas.getTextField(estadoTextField); String senha = String.valueOf(ControladorDeJanelas.getTextField(senhaTextField).hashCode()); Loja.validarCNPJ(cnpj); end = new Endereco(rua,bairro,cidade,estado); loja = new Loja(razao_social,cnpj,senha,end); LojaDAO.createLoja(loja); flag = true; }catch(CNPJException e){ new GUIException(e.getMessage()); }catch(InvalidTextException e){ new GUIException(e.getMessage()); } if(flag){ JOptionPane.showMessageDialog(null, "Loja criada com sucesso!\nVocê já pode logar em sua conta", "Sucesso", JOptionPane.INFORMATION_MESSAGE); instancia.setVisible(false); Login.getInstance().setVisible(true); instancia.bairroTextField.setText(""); instancia.cidadeTextField.setText(""); instancia.cnpjTextField.setText(""); instancia.estadoTextField.setText(""); instancia.razaoSocialTextField.setText(""); instancia.ruaTextField.setText(""); instancia.senhaTextField.setText(""); } } } <file_sep>package model; public class CNPJException extends Exception{ CNPJException(String s){ super(s); } } <file_sep>package model; import controller.ProdutoDAO; import model.Endereco; import java.util.ArrayList; public class Loja { private int id; private String razaoSocial; private String cnpj; private String senha; private Endereco endereco; private ArrayList<Produto> produtos = new ArrayList<>(); //construtor public Loja(){}; public Loja(String razaoSocial, String cnpj, String senha, Endereco endereco){ this.razaoSocial = razaoSocial; this.cnpj = cnpj; this.senha = senha; this.endereco = endereco; } /** * Método que valida um CNPJ * @param cnpj CNPJ que será validado * @throws CNPJException - Lança a exceção de CNPJ inválido caso ele seja. */ public static void validarCNPJ(String cnpj) throws CNPJException{ if(cnpj.length() != 14) throw new CNPJException("O cnpj digitado não possui um formato válido"); int[] primeira_etapa = {5,4,3,2,9,8,7,6,5,4,3,2};// 12 digitos int[] segunda_etapa = {6,5,4,3,2,9,8,7,6,5,4,3,2};// 13 digitos int primeiro_digito = 0; int segundo_digito = 0; //Calculo do primeiro digito for(int i = 0; i < 12;i++){ primeiro_digito += (Integer.parseInt(Character.toString(cnpj.charAt(i)))*primeira_etapa[i]); } primeiro_digito %= 11; if(primeiro_digito < 2){ primeiro_digito = 0; }else{ primeiro_digito = 11 - primeiro_digito; } //Fim do cálculo do primeiro digito //Calculo do segudo dígito for(int i = 0; i < 13; i ++){ segundo_digito += (Integer.parseInt(Character.toString(cnpj.charAt(i)))*segunda_etapa[i]); } segundo_digito %= 11; if(segundo_digito < 2){ segundo_digito = 0; }else{ segundo_digito = 11 - segundo_digito; } //Fim do cálculo do segundo dígito //Verificando se o CNPJ é válido if(Integer.parseInt(Character.toString(cnpj.charAt(12))) != primeiro_digito || Integer.parseInt(Character.toString(cnpj.charAt(13))) != segundo_digito) { throw new CNPJException("O CNPJ informado não é válido"); } } /** * Preenche a lista de produtos de uma determinada loja */ public void preencherProdutos(){ produtos.clear(); this.produtos = ProdutoDAO.obterProdutos(this.id); } //setters e getters public void setId(int id){ this.id = id; } public int getId(){ return this.id; } public void setRazaoSocial(String razaoSocial){ this.razaoSocial = razaoSocial; } public String getRazaoSocial(){ return this.razaoSocial; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public void setEndereco(Endereco endereco){ this.endereco = endereco; } public Endereco getEndereco(){ return this.endereco; } public ArrayList<Produto> getProdutos(){ return produtos; } } <file_sep><h1> Trabalho POO 2018</h1> <p> Participantes do grupo: <NAME> e <NAME>.</br> Cenário 1. </p>
0bb18e47320bfe86b9eda31c59e7dd1840d525e9
[ "Markdown", "Java" ]
8
Java
Trabalho-POO-UFG-2018/conpro
e25654eb192d4b347280843adb1750c1e46db5b0
3b55ea86aca5517029b87a9dc159a956f128e072
refs/heads/master
<repo_name>Genstrom/Vocabulary-Trainer<file_sep>/LanguageLibrary/WordList.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace LanguageLibrary { public class WordList { private static readonly char[] CharArray = {';'}; private readonly List<Word> _words = new List<Word>(); public WordList(string name, params string[] languages) { Name = name.ToLower(); Languages = languages; } private string Name { get; } public string[] Languages { get; } public static string[] GetLists() { Folder.CreateFolder(); var files = Directory.GetFiles(Folder.SpecificFolder) .Select(Path.GetFileNameWithoutExtension) .ToArray(); return files; } public static WordList LoadList(string name) { Folder.CreateFolder(); if (!File.Exists(Folder.GetFilePath(name.ToLower()))) return null; using var sr = new StreamReader(Folder.GetFilePath(name)); var line1 = sr.ReadLine(); if (line1 == null) return null; var languages = line1.ToLower().Split(CharArray, StringSplitOptions.RemoveEmptyEntries); var wordList = new WordList(name, languages); var line = ""; while ((line = sr.ReadLine()) != null) wordList.Add(line.Split(CharArray, StringSplitOptions.RemoveEmptyEntries)); sr.Close(); return wordList; } public void Save() { LoadList(Name); var file = Folder.GetFilePath(Name); using var fs = File.Create(file); fs.Close(); foreach (var t in Languages) if (!string.IsNullOrWhiteSpace(t)) File.AppendAllText(file, $"{t};"); foreach (var t in _words) { { File.AppendAllText(file, "\n"); } for (var j = 0; j < Languages.Length; j++) File.AppendAllText(file, $"{t.Translations[j]};"); } } public void Add(params string[] translations1) { if (translations1.Length != Languages.Length) throw new ArgumentException(); _words.Add(new Word(translations1)); } public bool Remove(int translations, string word) { if (_words.All(i => i.Translations[translations] != word.ToLower())) { return false; } var removeAtIndex = _words.IndexOf(_words.First(i => i.Translations[translations] == word.ToLower())); _words.RemoveAt(removeAtIndex); Save(); return true; } public int Count() { return _words.Count; } public void List(int sortByTranslation, Action<string[]> showTranslations) { var sortedTranslations = _words.OrderBy(x => x.Translations[sortByTranslation]).ToArray(); LoadList(Name); foreach (var translation in sortedTranslations) showTranslations(translation.Translations); } public Word GetWordToPractice() { var rnd = new Random(); var randomWord = rnd.Next(_words.Count); var fromLanguage = rnd.Next(Languages.Length); var toLanguage = rnd.Next(Languages.Length); while (toLanguage == fromLanguage) toLanguage = rnd.Next(Languages.Length); return new Word(fromLanguage, toLanguage, _words[randomWord].Translations); } } }<file_sep>/LanguageTrainerWinForms/AddNewList.cs using System; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Windows.Forms; using LanguageLibrary; namespace LanguageTrainerWinForms { public partial class AddNewList : Form { public AddNewList() { InitializeComponent(); } private void CreateButton_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(NameTextBoxInput.Text)) { var name = NameTextBoxInput.Text; var languageList = LanguageTextBoxInput.Lines.ToList(); var languageArray = languageList.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray(); if (languageArray.Length < 2) { var caption = "Error Detected in Input"; var message = "You need to add atleast 2 langauges. \nThe list will not be saved"; var buttons = MessageBoxButtons.OK; MessageBox.Show(message, caption, buttons); } else { var wordList = new WordList(name, languageArray); wordList.Save(); Close(); } } else { var caption = "Error Detected in Input"; var message = "You need to add a name to the list. \nThe list will not be saved"; var buttons = MessageBoxButtons.OK; MessageBox.Show(message, caption, buttons); } } private void CancelButton_Click(object sender, EventArgs e) { Close(); } private void AddNewList_Load(object sender, EventArgs e) { LanguageTextBoxInput.Text = $"Language 1{Environment.NewLine}Language 2{Environment.NewLine}...."; } private void NameTextBoxInput_TextChanged(object sender, EventArgs e) { LanguageTextBoxInput.Text = string.Empty; } } }<file_sep>/Console.Language.Trainer/Program.cs using System; using LanguageLibrary; namespace LanguageTeacher { internal static class Program { private static void Main(string[] args) { if (args.Length == 0) { PrintInfo(); return; } var inputArray = ArgsToLower(args); switch (inputArray[0]) { case "-lists": ListCommand(); break; case "-new": NewCommand(inputArray); break; case "-add": if (inputArray.Length > 1) { AddCommand(inputArray[1]); } else { Console.WriteLine("that list does not exist"); Console.WriteLine(); PrintInfo(); } break; case "-remove": RemoveCommand(inputArray); break; case "-words": WordsCommand(inputArray); break; case "-count": if (inputArray.Length > 1) { CountCommand(inputArray[1]); } else { Console.WriteLine("that list does not exist"); Console.WriteLine(); PrintInfo(); } break; case "-practice": if (inputArray.Length > 1) { PracticeCommand(inputArray[1]); } else { Console.WriteLine("that list does not exist"); Console.WriteLine(); PrintInfo(); } break; } } private static void PracticeCommand(string name) { var wordList = WordList.LoadList(name); if (wordList == null) { Console.WriteLine("That is not a valid list on your computer."); return; } if (wordList.Count() == 0) { Console.WriteLine("The selected list is empty, you cant practice with an empty list"); return; } var languageArray = wordList.Languages; var points = 0; var tries = 0; while (true) { var practiceWord = wordList.GetWordToPractice(); Console.WriteLine( $"Here is the {languageArray[practiceWord.FromLanguage]} word {practiceWord.Translations[practiceWord.FromLanguage]}"); Console.WriteLine( $"Do you know the {languageArray[practiceWord.ToLanguage]} translation?"); var input = Console.ReadLine().ToLower(); if (input == practiceWord.Translations[practiceWord.ToLanguage].ToLower()) { Console.WriteLine("Good job that is the correct answer"); points++; tries++; } else if (!string.IsNullOrWhiteSpace(input)) { Console.WriteLine("Sorry that is not the correct answer"); tries++; } if (string.IsNullOrWhiteSpace(input)) { Console.WriteLine($"You got {points} right answers out of {tries}"); break; } } } private static void CountCommand(string name) { var wordList = WordList.LoadList(name); if (wordList == null) { Console.WriteLine("That is not a valid list on your computer."); return; } Console.WriteLine($"There are {wordList.Count()} words in the list"); } private static void WordsCommand(string[] args) { var name = args[1]; var wordList = WordList.LoadList(name); if (wordList == null) { Console.WriteLine("That is not a valid list on your computer."); return; } var languageArray = wordList.Languages; var sortBy = GetLanguageIndex(args, languageArray); foreach (var languages in languageArray) { Console.Write(languages.PadLeft(20).ToUpper()); } Console.WriteLine(); wordList.List(sortBy, x => { foreach (var t in x) { Console.Write(t.PadLeft(20)); } Console.WriteLine(); }); } private static int GetLanguageIndex(string[] args, string[] languageArray) { if (args.Length < 3) return 0; for (var i = 0; i < languageArray.Length; i++) { if (args[2] == languageArray[i]) { return i; } } return 0; } private static void RemoveCommand(string[] args) { var name = args[1]; var wordList = WordList.LoadList(name); if (wordList == null) { Console.WriteLine("That is not a valid list on your computer."); return; } var language = GetLanguageIndex(args,wordList.Languages); for (var i = 3; i < args.Length; i++) { Console.WriteLine(); var wasRemoved = wordList.Remove(language, args[i]); Console.WriteLine(wasRemoved ? $"The {wordList.Languages[language]} word {args[i]} was removed" : "No Word were removed"); } } private static void AddCommand(string name) { var wordList = WordList.LoadList(name); if (wordList == null) { Console.WriteLine("That is not a valid list on your computer."); return; } AddWords(name, wordList.Languages); } private static void NewCommand(string[] args) { var name = args[1]; if (args.Length < 4) { Console.WriteLine($"You need to add at least 2 languages you added {args.Length - 2} languages"); return; } var languageArray = new string[args.Length - 2]; for (var i = 2; i < args.Length; i++) languageArray[i - 2] = args[i]; var wordlist = new WordList(name, languageArray); wordlist.Save(); AddWords(name, languageArray); } private static void PrintInfo() { Console.WriteLine("Use any of the following parameters: "); Console.WriteLine("-lists"); Console.WriteLine("-new <list name> <language 1> <language 2> .. <language n>"); Console.WriteLine("-add <list name>"); Console.WriteLine("-remove <list name > <language> <word1> <word2>... "); Console.WriteLine("-words <listname> <sortByLanguage>"); Console.WriteLine("-count <listname>"); Console.WriteLine("-practice <listname>"); } private static void ListCommand() { var files = WordList.GetLists(); if (files.Length > 1) { foreach (var file in files) if (WordList.LoadList(file) != null) Console.WriteLine(file); } else { Console.WriteLine("you dont have any lists make a list and then you can see it."); } } private static void AddWords(string name, string[] languages) { Console.WriteLine("To stop adding words, input an empty string"); var wordList = WordList.LoadList(name); var enterNotPressed = true; while (enterNotPressed) { var words = new string[languages.Length]; for (var i = 0; i < languages.Length; i++) { Console.WriteLine(i == 0 ? $"Please write the {languages[i]} word" : $"Please write the {languages[i]} translation"); var input = Console.ReadLine().ToLower(); if (string.IsNullOrWhiteSpace(input)) { wordList.Save(); enterNotPressed = false; break; } words[i] = input; } if (enterNotPressed) wordList.Add(words); } } private static string[] ArgsToLower(string[] args) { var userInput = args; for (var i = 0; i < args.Length; i++) userInput[i] = args[i].ToLower(); return userInput; } } }<file_sep>/LanguageTrainerWinForms/PracticeForm.cs using System; using System.Windows.Forms; using LanguageLibrary; namespace LanguageTrainerWinForms { public partial class PracticeForm : Form { public PracticeForm(string listName) { InitializeComponent(); ListName = listName; } public PracticeForm() { InitializeComponent(); } private string ListName { get; } private Word WordForPractice { get; set; } private int Score { get; set; } private int Tries { get; set; } private int Fails { get; set; } private Word PracticeGenerator() { var _name = ListName; WordForPractice = WordList.LoadList(_name).GetWordToPractice(); return WordForPractice; } private void PracticeForm_Load(object sender, EventArgs e) { PracticeGenerator(); var _name = ListName; var languageArray = WordList.LoadList(_name).Languages; PracticeWordBox.Text = $"Here is the {languageArray[WordForPractice.FromLanguage]} word {WordForPractice.Translations[WordForPractice.FromLanguage]}\r\n Please submit the {languageArray[WordForPractice.ToLanguage]} translation"; } private void SubmitButton_Click_1(object sender, EventArgs e) { var _name = ListName; var languageArray = WordList.LoadList(_name).Languages; var answer = AnswerBox.Text.ToLower(); AnswerBox.Text = string.Empty; if (answer == WordForPractice.Translations[WordForPractice.ToLanguage].ToLower()) { Score++; Tries++; } else { var caption = "Wrong Answer"; var message = $"You answered wrong. Your answer was {answer} and the correct answer is {WordForPractice.Translations[WordForPractice.ToLanguage].ToLower()} "; var buttons = MessageBoxButtons.OK; MessageBox.Show(message, caption, buttons); Tries++; Fails++; } PracticeGenerator(); PracticeWordBox.Text = $"Here is the {languageArray[WordForPractice.FromLanguage]} word {WordForPractice.Translations[WordForPractice.FromLanguage]}\r\n Please submit the {languageArray[WordForPractice.ToLanguage]} translation"; ScoreAmount.Text = Score.ToString(); FailAmount.Text = Fails.ToString(); TriesAmount.Text = Tries.ToString(); } private void StopButton_Click_1(object sender, EventArgs e) { var caption = "End of Session"; var message = $"Out of your {Tries} tries you managed to get {Score} correct answers. You failed on {Fails} words"; var buttons = MessageBoxButtons.OK; MessageBox.Show(message, caption, buttons); Close(); } } }<file_sep>/LanguageTrainerWinForms/MainForm.cs using System; using System.Windows.Forms; using LanguageLibrary; namespace LanguageTrainerWinForms { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private string FileName { get; set; } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedItem == null) { TranslationGrid.Hide(); InformationBox.Show(); InformationBox.Text = "this is not a valid list"; return; } FileName = listBox1.SelectedItem.ToString(); var wordList = WordList.LoadList(FileName); if (wordList == null) { return; } TranslationGrid.Show(); AddButton.Show(); NewListButton.Show(); RemoveButton.Show(); SaveButton.Show(); PracticeButton.Show(); AddButton.Enabled = true; SaveButton.Enabled = true; RemoveButton.Enabled = true; InformationBox.Hide(); var languageArray = wordList.Languages; var sortBy = 0; CountLabel.Text = $"There are {wordList.Count()} words in the list"; TranslationGrid.Rows.Clear(); TranslationGrid.Columns.Clear(); TranslationGrid.Refresh(); foreach (var languages in languageArray) TranslationGrid.Columns.Add("newColumnName", languages.ToUpper()); TranslationGrid.Rows.Clear(); wordList.List(sortBy, x => { TranslationGrid.Rows.Add(x); }); } private void MainForm_Activated(object sender, EventArgs e) { listBox1.Show(); listBox1.Enabled = true; ListLabel.Show(); listBox1.Items.Clear(); TranslationGrid.Hide(); var listsOnComputer = WordList.GetLists(); foreach (var lists in listsOnComputer) { var wordList = WordList.LoadList(lists); if (wordList != null && wordList.Languages.Length > 1) { listBox1.Items.Add(lists); } } } private void Save() { if (listBox1.SelectedItem?.ToString() == null) { return; } FileName = listBox1.SelectedItem.ToString(); var modifiedList = new WordList(FileName, WordList.LoadList(FileName).Languages); var correctLength = true; for (var i = 0; i < TranslationGrid.Rows.Count; i++) { var words = new string[modifiedList.Languages.Length]; for (var j = 0; j < words.Length; j++) { if (TranslationGrid.Rows[i].Cells[j].Value != null && !string.IsNullOrWhiteSpace(TranslationGrid.Rows[i].Cells[j].Value.ToString())) { words[j] = TranslationGrid.Rows[i].Cells[j].Value.ToString().ToLower(); } else { var emptySlots = TranslationGrid.Rows.Count - modifiedList.Count(); for (var k = 0; k < emptySlots; k++) TranslationGrid.Rows.RemoveAt(modifiedList.Count()); var caption = "Error Detected in Input"; var message = "You did not add a word for every language. \nThe empty indexes will not be saved"; var buttons = MessageBoxButtons.OK; MessageBox.Show(message, caption, buttons); correctLength = false; break; } } if (!correctLength) break; modifiedList.Add(words); modifiedList.Save(); CountLabel.Text = $"There are {WordList.LoadList(FileName).Count()} words in the list"; } } private void AddButton_Click(object sender, EventArgs e) { TranslationGrid.Rows.Add(""); } private void RemoveButton_Click(object sender, EventArgs e) { if (listBox1.SelectedItem != null) FileName = listBox1.SelectedItem.ToString(); if (TranslationGrid.SelectedRows.Count != 0) { var selectedRows = TranslationGrid.SelectedRows; var word = selectedRows[0].Cells[0].Value.ToString(); WordList.LoadList(FileName).Remove(0, word); } foreach (DataGridViewRow item in TranslationGrid.SelectedRows) TranslationGrid.Rows.RemoveAt(item.Index); CountLabel.Text = $"There are {WordList.LoadList(FileName).Count()} words in the list"; } private void NewListButton_Click(object sender, EventArgs e) { var newList = new AddNewList(); newList.Show(); } private void SaveButton_Click(object sender, EventArgs e) { if (listBox1.SelectedItem == null) { TranslationGrid.Hide(); InformationBox.Text = "You need to select a list before you save"; InformationBox.Show(); } else { Save(); } } private void MainForm_Load(object sender, EventArgs e) { AddButton.Enabled = false; SaveButton.Enabled = false; RemoveButton.Enabled = false; } private void PracticeButton_Click(object sender, EventArgs e) { if (listBox1.SelectedItem == null) { return; } listBox1.Enabled = false; var name = listBox1.SelectedItem.ToString(); if (WordList.LoadList(name).Count() != 0) { var practice = new PracticeForm(name); TranslationGrid.Hide(); practice.TopMost = true; practice.Show(); } else { var caption = "Error Detected"; var message = "The selected list is empty, you cant practice with an empty list"; var buttons = MessageBoxButtons.OK; MessageBox.Show(message, caption, buttons); } } } }<file_sep>/LanguageTrainerWinForms/Form1.cs using System; using System.Windows.Forms; using LanguageLibrary; namespace LanguageTrainerWinForms { public partial class Form1 : Form { public Form1(string name) { InitializeComponent(); Name = name; } public string Name { get; } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedItem != null) { InformationBox.Hide(); var name = listBox1.SelectedItem.ToString(); new Form1(name); var languageArray = WordList.LoadList(name).Languages; var sortBy = 0; CountLabel.Text = $"There are {WordList.LoadList(name).Count()} words in the list"; TranslationGrid.Rows.Clear(); TranslationGrid.Columns.Clear(); TranslationGrid.Refresh(); foreach (var languages in languageArray) TranslationGrid.Columns.Add("newColumnName", languages.ToUpper()); TranslationGrid.Rows.Clear(); WordList.LoadList(name).List(sortBy, x => { TranslationGrid.Rows.Add(x); }); } } private void NewButton_Click(object sender, EventArgs e) { var newList = new AddNewList(); newList.Show(); } private void SelectButton_Click(object sender, EventArgs e) { var name = ""; if (listBox1.SelectedItem != null) name = listBox1.SelectedItem.ToString(); } private void newToolStripMenuItem_Click(object sender, EventArgs e) { var newList = new AddNewList(); newList.Show(); } public void RefreshListbox() { listBox1.Items.Clear(); } private void Form1_Activated(object sender, EventArgs e) { var addnewlist = new AddNewList(); listBox1.Show(); ListLabel.Show(); listBox1.Items.Clear(); var vs = WordList.GetLists(); foreach (var v in vs) listBox1.Items.Add(v); } private void Save() { var modifiedList = new WordList(Name, WordList.LoadList(Name).Languages); var counter = 0; for (var i = 0; i < TranslationGrid.Rows.Count; i++) { var words = new string[modifiedList.Languages.Length]; for (var j = 0; j < words.Length; j++) { if (!string.IsNullOrWhiteSpace(TranslationGrid.Rows[i].Cells[j].Value.ToString())) { words[j] = TranslationGrid.Rows[i].Cells[j].Value.ToString(); counter++; } } if (counter == words.Length) { modifiedList.Add(words); modifiedList.Save(); } } } private void AddButton_Click(object sender, EventArgs e) { TranslationGrid.Rows.Add(""); } private void SaveButton_Click(object sender, EventArgs e) { var modifiedList = new WordList(Name, WordList.LoadList(Name).Languages); for (var i = 0; i < TranslationGrid.Rows.Count; i++) { var words = new string[modifiedList.Languages.Length]; for (var j = 0; j < words.Length; j++) words[j] = TranslationGrid.Rows[i].Cells[j].Value.ToString(); modifiedList.Add(words); modifiedList.Save(); } } } }
d0a8675dd4a45d2e92230414e12e071957bb956c
[ "C#" ]
6
C#
Genstrom/Vocabulary-Trainer
12335cc6c8b5e08f94d06bc19cd88750c9766b9f
ed1efd69b3b9c1a77d93141fc37a0f4490d261e3
refs/heads/master
<file_sep><?php namespace MicroGames\Http\Controllers; use MicroGames\gameObject; use MicroGames\gamePages; use Chumper\Zipper\Facades\Zipper; use Illuminate\Http\Request; use Cviebrock\EloquentSluggable\Sluggable; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Storage; use ZipArchive; class CreatorGameController extends Controller { use Sluggable; public function create() { return view('creator.game.create'); } public function createLayout($id) { return view('creator.game.createLayout', compact('id')); } public function storeLayout(Request $request) { $gameId = $request->gameId; $game = gamePages::findOrFail($gameId); if ($game->user_id != Auth::user()->id) { return redirect(route('game')); } if ($game->gameObject != null) { return redirect(route('game')); } $whatIsRequested = explode(',', $request->totalDivs); array_shift($whatIsRequested); $testArray = array(); $i = 0; foreach ($whatIsRequested as $element) { $i++; if (strpos($element, 'title') === 0) { $name = 'title'.$i; gameObject::create(['game_pages_id' => $gameId, 'order_number' => $i, 'kind' => 'title', 'what' => $request->$name]); } elseif (strpos($element, 'file') === 0) { $name = 'file'.$i; request()->validate([ $name => 'required|image|mimes:jpeg,png,jpg,gif,svg', ]); request()->$name->move(public_path('images/games/page'), $gameId.".".$i.".".request()->$name->getClientOriginalExtension()); gameObject::create(['game_pages_id' => $gameId, 'order_number' => $i, 'kind' => 'file', 'what' => $gameId.".".$i.".".request()->$name->getClientOriginalExtension()]); } elseif (strpos($element, 'text') === 0) { $name = 'text'.$i; gameObject::create(['game_pages_id' => $gameId, 'order_number' => $i, 'kind' => 'text', 'what' => $request->$name]); } } return redirect(route('gameDetail', [$gameId, 'game'])); } public function sluggable() { return [ 'slug' => [ 'source' => 'name' ] ]; } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { request()->validate([ 'mainPicture' => 'required|image|mimes:jpeg,png,jpg,gif,svg', 'game' => 'required', ]); $input = $request->validate([ 'title' => 'required|max:191', 'selectedTags' => 'max:191', ]); $game = gamePages::create(['name' => $input['title'], 'user_id' => Auth::user()->id]); request()->mainPicture->move(public_path('images/games/main'), $game['id'].".".request()->mainPicture->getClientOriginalExtension()); request()->game->move(public_path('games'), $game['id'].".".request()->game->getClientOriginalExtension()); $Path = public_path("games/".$game['id'].".".request()->game->getClientOriginalExtension()); $za = new ZipArchive(); $za->open($Path); $name = explode('/', $za->statIndex(0)['name'])[0]; \Zipper::make($Path)->extractTo('games'); rename(public_path('games')."/".$name, public_path("games/".$game['id'])); //tags $tags = json_decode($input['selectedTags']); $game->tags()->sync($tags); return redirect(route('game')); } } <file_sep><?php use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('users')->insert([ 'id' => 'fa0da26e-278b-4344-9e27-71c19c1b0f0f', 'name' => 'Joey', 'email' => '<EMAIL>', 'password' => <PASSWORD>', ]); DB::table('model_has_roles')->insert([ 'role_id' => '3', 'model_type' => 'MicroGames\User', 'model_id' => 'fa0da26e-278b-4344-9e27-71c19c1b0f0f', ]); } } <file_sep>var first = true; getGameExp(true); setInterval(function() { getGameExp(); }, 300000); function getGameExp(empty = false) { $.ajax({ method: "GET", url: "../../randomNumber", }) .done(function( data ) { $.ajax({ method: "GET", url: "../../getExp", data: { number: data, empty: empty } }) .done(function ( data ) { var newData = JSON.parse(data); if (newData.level != undefined) { $("#xp").text(newData.currentExp + " | " + newData.neededExp); $(".levelTitle").text(newData.level); if (first) { first = false; getGameExp(); } } }); }); } <file_sep>$( document ).ready(function() { $("#searchUser").keyup(function() { var tagsData = ""; var name = $("#searchUser").val(); if (name == "") { tagsData = "Type something in to search for a user"; $("#searchedUsers").html(tagsData); } else { $.ajax({ method: "GET", url: "../users/"+name, }) .done(function( data ) { if (data == "[]") { tagsData = "We could not find anybody with that name"; } else { $.each(jQuery.parseJSON(data), function( index, data ) { tagsData += "<button type='button' class='userButtons' id='user"+data.name+"' onclick='selectUser(\""+data.id+"\", \""+data.name+"\")'>"+data.name+"</button>"; }); } $("#searchedUsers").html(tagsData); }); } }); }); function selectUser(id, name) { $(".userButtons").css('border-color', 'white'); // this.style('color: blue'); $("#user_id_receiver").val(id); $("#user"+name).css('border-color', 'blue'); } <file_sep><?php namespace MicroGames; use Illuminate\Database\Eloquent\Model; class Inbox extends Model { protected $fillable = [ 'user_id_receiver', 'user_id_sender', 'title', 'text', ]; public function user() { return $this->belongsTo('MicroGames\User', 'user_id_sender', 'id'); } } <file_sep><?php namespace MicroGames\Http\Controllers; use MicroGames\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; class MemberProfileController extends Controller { public function index() { $user = Auth::user(); return view('member.profile.index', compact('user')); } public function edit() { $user = Auth::user(); return view('member.profile.edit', compact('user')); } public function patch(Request $request) { $input = $request->validate([ 'name' => 'required|max:191', 'first_name' => 'max:191', 'last_name' => 'max:191', 'email' => 'email|required|max:191', ]); $user = User::findOrFail(Auth::user()->id); if ($user->password != null) { /* if (!Hash::check($input['oldPassword'], $user->password)) { return $user->password; // return redirect(route('memberProfileEditForm'))->withErrors(['msg', 'You need to type the right password in']);; } */ if (isset($request['password1'])) { if ($request['password1'] == $request['password2']) { $input['password'] = Hash::make($request['password1']); } else { return redirect(route('memberProfileEditForm'))->withErrors(['msg', 'Your passwords do not match']);; } } } User::findOrFail($user->id)->update($input); return redirect(route('memberProfile')); } } <file_sep><?php namespace MicroGames\Http\Controllers; use MicroGames\tags; use MicroGames\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class AjaxController extends Controller { public function tags($name) { $tags = tags::where('name', 'LIKE', '%'.$name.'%')->get(); return json_encode($tags); } public function tag($id) { $tag = tags::findOrFail($id); return json_encode($tag); } public function users($name) { $user = User::where('name', 'LIKE', '%'.$name.'%')->get(); return json_encode($user); } public function randomNumber() { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < 50; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } session(['randomString' => $randomString]); return $randomString; } public function getExp(Request $request) { if (Auth::check()) { $empty = $request->empty; if ($request->number == session('randomString')) { if (session('time') == "") { session(['time' => time()]); return 'false'; } else { if (time() - (int)session('time') >= 300) { session(['time' => time()]); $user = User::findOrFail(Auth::user()->id); $currentExp = $user->exp; $currentLevel = (int)$user->level; $neededExp = 150 * $currentLevel * $currentLevel/3; if ($currentExp >= $neededExp) { $currentLevel++; $currentExp = 0; } $user->update(['exp' => (int)$currentExp+50, 'level' => $currentLevel]); return json_encode(['currentExp' => (int)$currentExp+50 , 'level' => $currentLevel, 'neededExp' => $neededExp]); } else { return 'false'; } } } else { return 'false'; } } else { return 'false'; } } } <file_sep><?php namespace MicroGames\Http\Controllers; use MicroGames\tags; use MicroGames\User; use Illuminate\Http\Request; use Spatie\Permission\Models\Role; class AdminUsersController extends Controller { public function index() { return view('admin.users.index'); } public function detail($id) { return view('admin.users.detail'); } public function assignRole(Request $request) { $user = User::findOrFail($request->user_id); switch ($request->role) { case 'Member': $user->syncRoles('Member'); break; case 'Creator': $user->syncRoles('Creator'); break; case 'Admin': $user->syncRoles('Admin'); break; default: return redirect(route('adminUsersRoles')); } return redirect(route('adminUsersRoles')); } public function roles() { $users = User::paginate(1); return view('admin.roles.index', compact('users')); } public function createTagForm() { return view('admin.tags.create'); } public function createTag(Request $request) { Tags::create(['name' => $request->name]); return redirect(route('game')); } //testing remove when done public function setAllRoles() { Role::create(['name' => 'Member']); Role::create(['name' => 'Creator']); Role::create(['name' => 'Admin']); } } <file_sep>var bannerHeight var bannerWidth $(document).ready(function(){ window.setInterval(function(){ bannerHeight = $('.banner').height(); $('.underImage').css('height', bannerHeight+'px'); bannerWidth = $('.banner').width(); $('.underImage').css('width', bannerWidth+'px'); }, 10); }); <file_sep><?php namespace MicroGames; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Database\Eloquent\Model; use Spatie\Permission\Traits\HasRoles; use Illuminate\Support\Str; class User extends Authenticatable { use HasRoles; use Notifiable; public $incrementing = false; protected $guard_name = 'web'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'first_name', 'last_name', 'email', 'password', 'provider_id', 'provider', 'level', 'exp', 'profile_picture', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; protected static function boot() { parent::boot(); static::creating(function ($post) { $post->{$post->getKeyName()} = (string) Str::uuid(); }); } public function getKeyType() { return 'id'; } public function gamePages() { return $this->hasMany('MicroGames\gamePages'); } public function inbox() { return $this->hasMany('MicroGames\Inbox', 'user_id_receiver'); } public function inboxSender() { return $this->hasMany('MicroGames\Inbox', 'user_id_sender'); } public function banned() { return $this->hasMany('MicroGames\Banned'); } public function bannedBy() { return $this->hasMany('MicroGames\Banned', 'banned_by'); } public function requests() { return $this->hasMany('MicroGames\Requests'); } public function requestsChecked() { return $this->hasMany('MicroGames\Requests', 'checked_by'); } public function reactions() { return $this->hasMany('MicroGames\Reactions'); } } <file_sep><?php namespace MicroGames\Http\Controllers; use MicroGames\Inbox; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class MemberInboxController extends Controller { public function index() { $user = Auth::user(); $inbox = $user->inbox()->get(); return view('member.inbox.index', compact('inbox')); } public function detail($id) { $message = Inbox::find($id)->where('user_id_receiver', Auth::user()->id)->first(); return view('member.inbox.detail',compact('message')); } public function create() { return view('member.inbox.create'); } public function store(Request $request) { $input = $request->validate([ 'user_id_receiver' => 'required|max:191', 'title' => 'required|max:191', 'text' => 'required', ]); $input['user_id_sender'] = Auth::user()->id; Inbox::create($input); return redirect(route('memberInboxIndex')); } public function createId($id) { return view('member.inbox.create'); } public function destroy($id) { Inbox::find($id)->where('user_id_receiver', Auth::user()->id)->first()->delete(); return redirect(route('game')); } } <file_sep><?php namespace MicroGames\Http\Controllers; use MicroGames\gameObject; use MicroGames\gamePages; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class MemberGameController extends Controller { public function index() { $games = gamePages::orderBy('created_at')->get(); return view('games.index', compact('games')); } public function search($name) { $games = gamePages::where('name', 'LIKE', '%'.$name.'%')->get(); return view('games.index', compact('games')); } public function searchBar(Request $request) { return $this->search($request->name); } public function detail($id, $name) { $pages = gameObject::where('game_pages_id', $id)->orderBy('order_number', 'asc')->get(); return view('games.detail', compact('pages', 'id', 'name')); } public function play($id, $name) { return redirect('games/'.$id.'/index.html'); // return view('games.play', compact('id')); } } <file_sep>$( document ).ready(function() { $("#searchTags").keyup(function() { var tagsData = ""; var name = $("#searchTags").val(); if (name == "") { tagsData = "Type something in to search for a tag"; $("#searchedTags").html(tagsData); } else { $.ajax({ method: "GET", url: "../tags/"+name, }) .done(function( data ) { $.each(jQuery.parseJSON(data), function( index, data ) { tagsData += "<button type='button' onclick='selectTag("+data.id+")'>"+data.name+"</button>"; }); $("#searchedTags").html(tagsData); }); } }); }); function selectTag(id) { var inside = false; var val = $("#selectedTagsHidden").val(); if (val == "") { $("#selectedTagsHidden").val(JSON.stringify([id])); inside = true; } else { var valJson = jQuery.parseJSON(val); if (jQuery.inArray(id, valJson) == -1) { valJson.push(id); $("#selectedTagsHidden").val(JSON.stringify(valJson)); inside = true; } } if (inside) { var selected = $("#selectedTags").html(); $.ajax({ method: "GET", url: "../tag/"+id, }) .done(function( data ) { var newData = jQuery.parseJSON(data); $("#selectedTags").html(selected + "<button type='button' id='button"+id+"' onclick='removeTag("+id+")'>"+newData.name+"</button>"); }); } inside = false; } function removeTag(id) { var val = $("#selectedTagsHidden").val(); var valJson = jQuery.parseJSON(val); console.log(valJson); var index = valJson.indexOf(id); if (index > -1) { valJson.splice(index, 1); } console.log(valJson); $("#selectedTagsHidden").val(JSON.stringify(valJson)); $("#button"+id).remove(); } <file_sep><?php namespace MicroGames; use Illuminate\Database\Eloquent\Model; class reactions extends Model { protected $fillable = [ 'game_id', 'user_id', 'rating', 'title', 'text', ]; public function user() { return $this->belongsTo('MicroGames\User'); } public function gamePage() { return $this->belongsTo('MicroGames\GamePages', 'id', 'game_id'); } } <file_sep><?php namespace MicroGames; use Illuminate\Database\Eloquent\Model; class Banned extends Model { protected $fillable = [ 'user_id', 'reason', 'permanent', 'until', 'banned_by', ]; } <file_sep>var select = false; var idSelect; var numberOfElements = 0; function selected(id) { if (select) { if (id == idSelect) { select = false; $('#'+idSelect).css('background-color','white'); $('#' + idSelect + ' > p:first').css('color','#3CB46D'); idSelect = ''; } else { $('#'+id).css('background-color','#3CB46D'); $('#' + id + ' > p:first').css('color','white'); $('#'+idSelect).css('background-color','white'); $('#' + idSelect + ' > p:first').css('color','#3CB46D'); idSelect = id; } } else { select = true; $('#'+id).css('background-color','#3CB46D'); $('#' + id + ' > p:first').css('color','white'); idSelect = id; } console.log(select); } function createDiv() { if (select){ numberOfElements++; var heightClass = $(".height").html(); var addClass = ''; switch (idSelect) { case 1: addClass = "<div>"+ "<textarea name='text" + numberOfElements + "' class='form-control designPage' placeholder='Typ your text here...'></textarea>"+ "</div><hr />"; $("#totalDivs").val($("#totalDivs").val()+',text'+numberOfElements); break; case 2: addClass = "<div>"+ "<input type='text' name='title" + numberOfElements + "' class='form-control designPage' placeholder='Typ your title here...'>"+ "</div><hr />"; $("#totalDivs").val($("#totalDivs").val()+',title'+numberOfElements); break; case 3: addClass = "<div class='custom-file'>"+ "<input type='file' class='custom-file-input designPage' id='customFile' name='file" + numberOfElements + "'" + numberOfElements + ">"+ "<label class='custom-file-label' for='customFile'>Choose file</label>"+ "</div><hr />"; $("#totalDivs").val($("#totalDivs").val()+',file'+numberOfElements); break; } $('#exampleModal').modal('hide'); select = false; idSelect = false; $('.selectors').css('background-color','white'); $('.elementText').css('color','#3CB46D'); $("#createDivs").append(addClass); } } <file_sep><?php namespace MicroGames\Http\Controllers; use Illuminate\Http\Request; class MemberUsersController extends Controller { public function index() { return view('member.users.index'); } } <file_sep><?php namespace MicroGames; use Illuminate\Database\Eloquent\Model; class requests extends Model { protected $fillable = [ 'user_id', 'kind', 'game_id', 'accepted', 'checked_by', 'checked_text', ]; public function game_pages() { return $this->belongsTo('MicroGames\GamePages'); } } <file_sep>This is a project we created in 3 days. Creators of the website: Back-end: Joey Front-end: Bas <file_sep><?php namespace MicroGames; use Cviebrock\EloquentSluggable\Sluggable; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class GamePages extends Model { use Sluggable; public $incrementing = false; protected $fillable = [ 'id', 'name', 'user_id', ]; protected static function boot() { parent::boot(); static::creating(function ($game) { $game->{$game->getKeyName()} = (string) Str::uuid(); }); } /** * Return the sluggable configuration array for this model. * * @return array */ public function sluggable() { return [ 'slug' => [ 'source' => 'name' ] ]; } public function getKeyName() { return 'id'; } public function gameObject() { return $this->hasOne('MicroGames\GameObject', 'game_pages_id'); } public function requests() { return $this->hasOne('MicroGames\Requests'); } public function reactions() { return $this->hasMany('MicroGames\Reactions', 'game_id'); } public function tags() { return $this->belongsToMany('MicroGames\Tags'); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Auth::routes(); Route::get('/', 'MemberGameController@index')->name('game'); Route::group(['middleware' => ['role:Member|Creator|Admin']], function () { //inbox Route::get('/inbox', 'MemberInboxController@index')->name('memberInboxIndex'); Route::delete('/inbox/{id}', 'MemberInboxController@destroy')->name('memberInboxDestroy'); Route::get('/inbox/create', 'MemberInboxController@create')->name('memberInboxCreateForm'); Route::post('/inbox/create', 'MemberInboxController@store')->name('memberInboxCreate'); Route::get('/inbox/create/{id}', 'MemberInboxController@createId')->name('memberInboxCreateWithId'); Route::get('/inbox/{id}', 'MemberInboxController@detail')->name('memberInboxDetail'); //profile Route::get('/profile', 'MemberProfileController@index')->name('memberProfile'); Route::get('/profile/edit', 'MemberProfileController@edit')->name('memberProfileEditForm'); Route::patch('/profile/edit', 'MemberProfileController@patch')->name('memberProfileEdit'); //users Route::get('/users', 'MemberUsersController@index')->name('memberUsers'); }); Route::group(['middleware' => ['role:Creator|Admin']], function () { //game Route::get('/game/create', 'CreatorGameController@create')->name('creatorGameCreate'); Route::post('/game/create', 'CreatorGameController@store')->name('creatorGameCreatePost'); Route::get('/gameLayout/{id}/{name}', 'CreatorGameController@createLayout')->name('creatorGameLayout'); Route::post('/game/createLayout', 'CreatorGameController@storeLayout')->name('creatorGameCreatePostLayout'); }); Route::group(['middleware' => ['role:Admin']], function () { //admin users Route::get('/admin/users/roles', 'AdminUsersController@roles')->name('adminUsersRoles'); Route::post('/admin/users/roles/assignRole', 'AdminUsersController@assignRole')->name('adminUsersRolesAssign'); Route::get('/admin/tags/create', 'AdminUsersController@createTagForm')->name('adminTagCreatForm'); Route::post('/admin/tags/create', 'AdminUsersController@createTag')->name('adminTagCreat'); }); //games Route::get('/searchBar', 'MemberGameController@searchBar')->name('gameDetailSearchBar'); Route::get('/game/{name}', 'MemberGameController@search')->name('gameDetailName'); Route::get('/game/{id}/{name}', 'MemberGameController@detail')->name('gameDetail'); Route::get('/play/{id}/{name}', 'MemberGameController@play')->name('gamePlay'); //socialite Route::get('login/{service}', 'Auth\LoginController@redirectToProvider')->name('loginService'); Route::get('login/{service}/callback', 'Auth\LoginController@handleProviderCallback'); //js loaders Route::get('tags/{name}', 'AjaxController@tags')->name('AjaxTags'); Route::get('tag/{name}', 'AjaxController@tag')->name('AjaxTag'); Route::get('users/{name}', 'AjaxController@users')->name('AjaxTag'); Route::get('getExp', 'AjaxController@getExp')->name('AjaxGetExp'); Route::get('randomNumber', 'AjaxController@randomNumber')->name('AjaxRandomNumber'); //test need to remove Route::get('test/setAllRoles', 'AdminUsersController@setAllRoles'); //Route::get('test/assignRole/{userId}/{ruleName}', 'AdminUsersController@assignRole'); <file_sep><?php namespace MicroGames; use Illuminate\Database\Eloquent\Model; class GameObject extends Model { protected $fillable = [ 'game_pages_id', 'order_number', 'kind', 'what', ]; public function gamePages() { return $this->belongsTo('MicroGames\gamePages', 'game_pages_id', 'id'); } }
19ebad4d0260402971ae09a9c69a9fa76bcd691e
[ "JavaScript", "Markdown", "PHP" ]
22
PHP
joey-dev/microgames
6333d249f3e8f317de4eea7e744784a5eb9191c9
dd958797efb6d050da6fc152171dc20bc5746dce
refs/heads/master
<repo_name>codeneverstop/JavascriptRoad<file_sep>/Tetris/game/connection_manager.js class ConnectionManager { constructor() { this.conn = null; } connect(address) { this.conn = new WebSocket(address); /* 这个open和new有什么区别? 应该是 如果new了以后 server没反应,这个open也应该不会有执行*/ this.conn.addEventListener('open', () => { console.log('conn established'); /*create-session已经是程序自己指定的来*/ this.initSession(); }); this.conn.addEventListener('message', event => { console.log("receive message:" + event.data); this.receive(event.data); }); } initSession() { /*获取url的#后面的所有的内容*/ const sessionId = window.location.hash.split('#')[1]; if (sessionId) { this.send({ type: "join-session", id: sessionId, }); } else { this.send({ type: 'create-session', }); } } receive(msg) { const data = JSON.parse(msg); if (data.type === "session-created") { window.location.hash = data.id; } } send(data) { const msg = JSON.stringify(data); console.log(`Sending msg ${msg}`); this.conn.send(msg); } }<file_sep>/Tetris/game/tetris.js class Tetris { /* 这里传html的document就没意义,最终它是要画不同的tetris,canvas是不同的 包括class是game的div的里面的score等所有元素都是不同的 所以要改成传特定的game的div或者特定的canvas都可以 */ constructor(canvas, index) { this.canvas_bkg = canvas; this.context_bkg = this.canvas_bkg.getContext('2d'); /*never change*/ this.context_bkg.scale(20, 20); this.arena = new Arena(12, 20); this.player = new Player({x: 2, y: 2}, 0, this.arena); this.index = index; let lastTime = 0; //必须要用指针,否则在tetrisAddEventListener上下文,this就是不是tetris实例了。 const update = (time = 0) => { const deltaTime = time - lastTime; lastTime = time; dropCounter += deltaTime; if (dropCounter > dropInterval) { this.player.drop(1); } let row = this.arena.eliminate(); this.player.updateScore(row * 10); this.draw(); requestAnimationFrame(update); } update(); } _drawMatrix(matrix, offset){ matrix.forEach((row, y) => { row.forEach((value, x) => { if (value !== 0){ this.context_bkg.fillStyle = colorarr[value - 1]; this.context_bkg.fillRect(x + offset.x, y + offset.y, 1, 1); } }); }); } draw(){ /*renew back ground*/ this.context_bkg.fillStyle = '#000'; this.context_bkg.fillRect(0, 0, this.canvas_bkg.width, this.canvas_bkg.height); this._drawMatrix(this.arena.arena, {x: 0, y: 0}); this._drawMatrix(this.player.block, this.player.pos); document.getElementById("score_" + this.index).innerText = this.player.score; } }<file_sep>/Tetris/game/main.js const matrix_block = [ [ [0, 0, 0], [1, 1, 1], [0, 1, 0], ], [ [2, 2], [2, 2], ], [ [0, 3, 0, 0], [0, 3, 0, 0], [0, 3, 0, 0], [0, 3, 0, 0], ], [ [4, 0, 0], [4, 0, 0], [4, 4, 0], ], [ [0, 0, 5], [0, 0, 5], [0, 5, 5], ], [ [6, 6, 0], [0, 6, 6], [0, 0, 0], ], [ [0, 7, 7], [7, 7, 0], [0, 0, 0], ], ]; const connectionManager = new ConnectionManager(); connectionManager.connect("ws://localhost:9000"); const colorarr = ['red', 'blue', 'yellow', 'pink', 'purple', 'cyan', 'gray']; const dropInterval = 1000; let dropCounter = 0; const tetris = []; var game_canvas; const playerElement = document.querySelectorAll('.game'); [...playerElement].forEach((element, index) => { game_canvas = element.querySelector('canvas'); const tetrisInstance = new Tetris(game_canvas, index); tetris.push(tetrisInstance); }); function tetrisAddEventListener() { //这里面的this就是Tetris var key = [ [65, 68, 81, 69, 83], [72, 75, 89, 73, 74], ]; key.forEach((value, i) => { document.addEventListener('keydown', event => { if (event.keyCode === value[0]) { // left tetris[i].player.moveHorizontally(-1); if (tetris[i].arena.isCollideWithPlayer(tetris[i].player)) { tetris[i].player.moveHorizontally(1); } } else if (event.keyCode === value[1]) { tetris[i].player.moveHorizontally(1); if (tetris[i].arena.isCollideWithPlayer(tetris[i].player)) { tetris[i].player.moveHorizontally(-1); } } else if (event.keyCode === value[4]) { tetris[i].player.drop(1); } else if (event.keyCode === value[2]) { tetris[i].player.rotate(-1); if (tetris[i].arena.isCollideWithPlayer(tetris[i].player)) { tetris[i].player.rotate(1); } } else if (event.keyCode === value[3]) { tetris[i].player.rotate(1); if (tetris[i].arena.isCollideWithPlayer(tetris[i].player)) { tetris[i].player.rotate(-1); } } }); }); } tetrisAddEventListener();<file_sep>/Tetris/server/client.js class Client { constructor(conn) { this.conn = conn; this.session = null; } send(data) { const msg = JSON.stringify(data); console.log(`send msg is ${msg}`); this.conn.send(msg, function ack(err) { if (err) { console.error("send msg failed. session id is " + this.session.id + ", err is " + err); } }); } } module.exports = Client;<file_sep>/Tetris/game/player.js class Player { constructor(pos, matrix_type, arena) { this.pos = pos; this.block = matrix_block[matrix_type]; this.arena = arena; this.score = 0; } reset() { this.pos.y = 2; this.pos.x = 3;//canvas_bkg.width / 20 / 2 - 1; var type = Math.random() * colorarr.length| 0; this.block = matrix_block[type]; } moveHorizontally(x_len) { this.pos.x += x_len; } drop(height) { this.pos.y += height; if (this.arena.isCollideWithPlayer(this)){ this.pos.y--; this.arena.merge(this); this.reset(); if (this.arena.isCollideWithPlayer(this)) { //TODO: back to menu for (var i = 0; i < this.arena.arena.length; i++) { for (var j = 0; j < this.arena.arena[i].length; j++) { this.arena.arena[i][j] = 0; } } this.score = 0; } } dropCounter = 0; } rotate(dir) { for (let y = 0; y < this.block.length; y++){ for (let x = 0; x < y; x++){ [ this.block[x][y], this.block[y][x], ] = [ this.block[y][x], this.block[x][y], ] } } //TODO: dir should be an enum if (dir > 0){ this.block.forEach(row => row.reverse()); } else { this.block.reverse(); } } updateScore(score) { this.score += score; } }<file_sep>/Tetris/game/arena.js class Arena { constructor(width, height) { this.pos = {x: 0, y: 0}; this.arena = []; for (let y = 0; y < height; y++) { this.arena.push(new Array(width).fill(0)); } } isCollideWithPlayer(player) { const [pos, matrix] = [player.pos, player.block]; /* 在forEach里break是没有用的,因为这里forEach是个函数,是肯定都要执行的。 所以这里用forEach不合适。 */ for (let y = 0; y < matrix.length; ++y) { for (let x = 0; x < matrix[y].length; ++x){ //console.log("-pos origin(" + y + ", " + x + "), matrix pos is " + matrix[y][x]); if (matrix[y][x] !== 0 && (this.arena[y + pos.y] && this.arena[y + pos.y][x + pos.x]) !== 0){ return true; } } } return false; } eliminate() { let row = 0; start: for (let y = 0; y < this.arena.length; y++) { for (let x = 0; x < this.arena[y].length; x++) { if (this.arena[y][x] === 0) { continue start; } } this.arena.splice(y, 1); this.arena.unshift(new Array(this.arena[0].length).fill(0)); row += 1; } return row; } merge(player) { const [pos, matrix] = [player.pos, player.block]; matrix.forEach((row, y) => { row.forEach((value, x) => { if (value !== 0){ this.arena[y + pos.y][x + pos.x] = value; } }); }); } }
83975c6814407a2bccd7ba6c71c150a8218cc7eb
[ "JavaScript" ]
6
JavaScript
codeneverstop/JavascriptRoad
f41755f0a6aa2b7a41b10f941e1bd866fa44c6e1
4b4a08f5fe2342b8e645f42dd165e16e0f480ef5
refs/heads/master
<file_sep>alias pbcopy='xclip -selection clipboard' alias pbpaste='xclip -selection clipboard -o' alias emacs='emacs -nw' alias vim=nvim <file_sep>if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi export EDITOR=nvim # GIT_PROMPT_ONLY_IN_REPO=1 # source ~/.bash-git-prompt/gitprompt.sh export HISTFILESIZE=10000 export HISTSIZE=10000 export HISTTIMEFORMAT="[%F %T] " # Change the file location because certain bash sessions truncate .bash_history file upon close. # http://superuser.com/questions/575479/bash-history-truncated-to-500-lines-on-each-login export HISTFILE=~/.bash_history_large # Force prompt to write history after every command. # http://superuser.com/questions/20900/bash-history-loss PROMPT_COMMAND="history -a; $PROMPT_COMMAND" export CDPATH=$HOME/handydev/repos:$HOME/handydev/repos/datapipeline-infrastructure export GOPATH=$HOME/go export PATH=$PATH:$GOPATH/bin:$HOME/.npm-global/bin export JAVA_HOME=/nix/store/drzxnbx08lmkb2knhyyifi5szz17910j-openjdk-8u212-ga #### BEGIN GENERATED BY HANDYDEV TOOLKIT #### source /home/spietz/handydev/meta/init.sh #### END GENERATED BY HANDYDEV TOOLKIT #### ###-tns-completion-start-### if [ -f /home/spietz/.tnsrc ]; then source /home/spietz/.tnsrc fi ###-tns-completion-end-###
da3dfd9b5c9f9f661c4187e64edd1b0d81e1a32b
[ "Shell" ]
2
Shell
sgeop/dotfiles
c5d2847d23620750859c4e515553214a84802ffe
f308453e41dd37dcbffaa46eba7132d6ca27d9c8
refs/heads/master
<file_sep>package kr.ac.jejunu; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.sql.SQLException; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class ProductDaoTest { private ProductDao productDao; @Before public void setup() { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(DaoFactory.class); productDao = applicationContext.getBean("productDao", ProductDao.class); } @Test public void get() throws SQLException { Long id = 1L; String title = "제주감귤"; Integer price = 15000; Product product = productDao.get(id); assertEquals(id, product.getId()); assertEquals(title, product.getTitle()); assertEquals(price, product.getPrice()); } @Test public void add() throws SQLException { Product product = new Product(); Long id = insertForTest(product); Product insertedProduct = productDao.get(id); assertThat(id, is(insertedProduct.getId())); assertThat(product.getTitle(), is(insertedProduct.getTitle())); assertThat(product.getPrice(), is(insertedProduct.getPrice())); } @Test public void update() throws SQLException { Product product = new Product(); Long id = insertForTest(product); product.setId(id); product.setTitle("바꾼감귤"); product.setPrice(99999); productDao.update(product); Product updatedProduct = productDao.get(id); assertThat(id, is(updatedProduct.getId())); assertThat(product.getTitle(), is(updatedProduct.getTitle())); assertThat(product.getPrice(), is(updatedProduct.getPrice())); } @Test public void delete() throws SQLException { Product product = new Product(); Long id = insertForTest(product); productDao.delete(id); Product deletedProduct = productDao.get(id); assertThat(deletedProduct, nullValue()); } private Long insertForTest(Product product) throws SQLException { product.setTitle("제제주주감귤귤"); product.setPrice(12345); return productDao.insert(product); } }
a0b6a32e0ef530d228cd37281e82b694c8b572cf
[ "Java" ]
1
Java
seung-yeol/java-framework-class-miexam
3082e7a4359d2a56e3358c647b0394b1ff87faf3
de0bca875fa6a43f3fad586b752a31c19ceb02e7
refs/heads/master
<repo_name>JustinGuese/tensortrade-experiments<file_sep>/README.md My fix / implementation of tensortrade examples ----- install the following pip install git+https://github.com/tensortrade-org/tensortrade stochastic ta # how to start it in the cloud 1. choose an aws ec2 instance 2. in the bootstrap area copy the "cloudbootstrap.sh" script 3. ssh into the instance with port forwarding ssh -L 8888:localhost:8888 4. in the home folder there should be the tensortrade-experiments folde, cd into it 5. run the cloudinit.sh script (you might need to "chmod +x cloudinit.sh" first, then just type ./cloudinit.sh 6. in your console the jupyter notebook address should be marked. copy paste it into your local browser 7. jupyter notebook should appear. - the environment might not activate via script. in that case just copy paste the commands of the cloudinit.sh into your console <file_sep>/cloudinit.sh #!/bin/bash source activate tensorflow2_p36 jupyter notebook --no-browser <file_sep>/cloudbootstrap.sh #!/bin/bash # aws ec2 deep learning ami git clone https://github.com/JustinGuese/tensortrade-experiments /home/ubuntu/tensortrade-experiments /home/ubuntu/anaconda3/envs/tensorflow2_p36/bin/pip install git+https://github.com/tensortrade-org/tensortrade.git stochastic ta yfinance
72b5255a61ef34139ea6d54d4dffa9522fe9536b
[ "Markdown", "Shell" ]
3
Markdown
JustinGuese/tensortrade-experiments
c97fe51c7bb90860ffbeeb38404d35dcaf242026
9d4b54c93beba187516c13882fef41ba1f73685d
refs/heads/master
<repo_name>everystone/is105<file_sep>/lab2.py # -*- coding: latin-1 -*-# # IS-105 LAB2 # # lab2.py - kildekode som inneholder studentenes lQsning. # # # import sys # Skriv inn fullt navn paa gruppemedlemene (erstatte '-' med navn slikt '<NAME>') gruppe = { 'student1': '<NAME>', \ 'student2': '<NAME>', \ } # # Oppgave 1 # Leke med utskrift # Skriv ut fQlgende "ascii art" i en funksjon # Funksjonen skal hete ascii_fugl() og skal vaere uten argumenter og uten returverdier # Den skal skrive ut fQlgende naar den brukes ascii_fugl # # \/_ # \, /( ,/ # \\\' /// # \_ /_/ # (./ # '` def ascii_fugl(): print " \\/_" print " \\, /( ,/" print " \\\\\\' ///" print " \\_ /_/" print " (./" print " '`" # # Oppgave 2 # 'return 2' - 2 skal erstattes med en korrekt returverdi, 2 er kun en stedsholder # bitAnd - x&y # Eksempel: bitAnd(6, 5) = 4 # def bitAnd(x, y): return x & y # Oppgave 3 # bitAnd - x&y # Eksempel: bitAnd(6, 5) = 4 # #def bitAnd(x, y): # return 2 # # Oppgave 4 # bitXor - x^y # Eksempel: bitXor(4, 5) = 1 # def bitXor(x, y): return x ^ y # # Oppgave 5 # bitOr - x|y # Eksempel: bitOr(0, 1) = 1 # def bitOr(x, y): return (x | y) # # Oppgave 6 # ascii8Bin - ta et tegn som argument og returnerer ascii-verdien som 8 bits streng binaert # Eksempel: ascii8('A) = 01000001 # # Tips: # For aa finne desimalverdien til et tegn bruk funksjonen ord, for eksempel # ord('A) , det vil gi et tall 65 i ti-tallssystemet # For aa formattere 6 i ti-tallssystemet til 00000110 i to-tallssystemet # '{0:08b}'.format(6) # 00000110 # # Formatteringsstrengen forklart: # {} setter en variabel inn i strengen # 0 tar variabelen i argument posisjon 0 # : legger til formatteringsmuligheter for denne variabelen (ellers hadde den 6 desimalt) # 08 formatterer tall til 8 tegn og fuller med nuller til venstre hvis nQdvendig # b konverterer tallet til dets binAEre representasjon def ascii8Bin(bokstav): decVal = ord(bokstav) return "Ascii: ", bokstav, " Decimal: ", decVal, " Binary: ", '{0:08b}'.format(decVal) # # Oppgave 7 # transferBin - ta en tilfeldig streng som argument og skriver ut en blokk av 8-bits strenger # som er den binre representasjon av strengen # Eksempel: transferBin("Hi") skriver ut: # 01001000 # 01101001 # def transferBin(string): l = list(string) print "length of list: ", len(l) for c in l: print ascii8Bin(c) # skriv ut den binQre representasjon av hvert tegn (bruk ascii8Bin funksjonen din) def ascii2Hex(bokstav): decVal = ord(bokstav) return "Ascii ", bokstav, "Decimal : ", decVal, "Hex: ", '{0:02x}'.format(decVal) # Oppgave 8 # transferHex - gjQr det samme som transferBin, bare skriver ut representasjonen #av strengen heksadesimalt (bruk formattering forklart i Oppgave 6) #Skriv gjerne en stQttefunksjon ascii2Hex, som representerer et tegn #med 2 heksadesimale tegn def transferHex(string): l = list(string) for c in l: print ascii2Hex(c) #tests print "Lab2 - IS105" print gruppe print "\nOppgave 1 - ascii_fugl():" ascii_fugl() print "\nOppgave 3 - bitAnd(6,5):", bitAnd(6,5) print "\nOppgave 4 - bitXor(4,5):", bitXor(4,5) print "\nOppgave 5 - bitOr(0,1):", bitOr(0,1) print "\nOppgave 6 - ascii8Bin:" bokstav = raw_input(">bokstav: ") print ascii8Bin(bokstav) print "\nOppgave 7 - transferBin" setning = raw_input(">Skriv inn et ord:") transferBin(setning) print "\nOppgave 8 - transferHex" setning = raw_input(">Skriv inn et ord:") transferHex(setning) <file_sep>/ext1.py #!/usr/bin/python from sys import argv script, user_name = argv prompt = '> ' print "Hello %s, im the %s script." % (user_name, script) #skriver ut script + argv 0 print "is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 # returnerer true/false print "what is 3 + 2?", 3+2 print "what is 5-7?", 5-7 print "give me a number" number = raw_input(prompt) #input print "You gave me %r" % (number ) print """ flere linjer i en print very clever. """ <file_sep>/lab4.py # -*- coding: latin-1 -*- # # IS-105 LAB4 # # lab4.py - kildekode som inneholder studentenes løsning. # # # import sys import os import subprocess import re import psutil # Kan installeres med "pip2.7 install psutil" # Skriv inn fullt navn på gruppemedlemene (erstatte '-' med navn slikt 'Kari Trå') gruppe = { 'student1': '<NAME>', \ } # Oppgave 1 # Funksjonen lager en strukturert utskrift av resultater fra # kallet psutil.cpu_times(). # Modulen psutil må være installert. # # Utskriften skal være følgende (verdiene skal selvsagt være forskjellige): # user = 3088.16 # nice = 0.99 # system = 897.37 # idle = 72353.81 # iowait = 19.29 # irq = 6.82 # softirq = 3.07 # steal = 0.00 # guest = 0.00 # def psutils_use(): print """ Henter lister med systeminformasjon fra /proc og bearbeider disse """ data = str(psutil.cpu_times(True)) # hente output fra cpu_times inn i string data data2 = data.replace("cputimes(", "") # fjerne cputimes( fra starten av stringen data2 = data2[1:-2] #fjerner første char '[' og de 2 siste '])' list = data2.split(',') # splitte på komma for i in list: print i.replace("=", " = ") # legge til space før og etter = og printer psutils_use() # Oppgave 2 # Gitt følgende liste (inn-data): # proglangs = [('Python', '1989', '<NAME>'), ('C', '1969', '<NAME>'), ('Java/Oak', '1991', '<NAME>'), ('C++', '1979', 'Bjarne Stroustrup'), ('Ruby', '1991', 'Yukihiro "Matz" Matsumoto'), ('Perl', '1987' , '<NAME>'), ('Go/golang', '2007', '<NAME>, <NAME>, and <NAME>')] # # skal funksjonen produsere følgende ut-data: # # C ble startet 1969 av <NAME>. # C++ ble startet 1979 av Bjarne Stroustrup. # Perl ble startet 1987 av <NAME>. # Python ble startet 1989 av <NAME>. # Java/Oak ble startet 1991 av <NAME>. # Ruby ble startet 1991 av Yukihiro "Matz" Matsumoto. # Go/golang ble startet 2007 av <NAME>, <NAME>, and <NAME>. # def print_history(proglangs): # Implementer funksjonen her sortert = sorted(proglangs, key=lambda year: year[1]) # sorter for line in sortert: print "\t%s ble startet i %s av %s" %(line[0], line[1], line[2]) proglangs = [('Python', '1989', '<NAME>'), ('C', '1969', '<NAME>'), ('Java/Oak', '1991', '<NAME>'), ('C++', '1979', '<NAME>'), ('Ruby', '1991', 'Yukihiro "Matz" Matsumoto'), ('Perl', '1987' , '<NAME>'), ('Go/golang', '2007', '<NAME>, <NAME>, and <NAME>')] print_history(proglangs) # Standardkall for evalueringen print 5*"-" + " Studenter: " + 5*"-" for s in gruppe.values(): if s is not "-": print s <file_sep>/poker-client.py # -*- coding: latin-1 -*- """ Poker klient v 0.2 <NAME> """ import socket import sys import select host = 'localhost' port = 10000 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #connect to server try: s.connect((host,port)); except: sys.stdout.write("Connection failed"); sys.exit(); sys.stdout.write('[+]Connected to server\n'); while 1: socket_list = [sys.stdin, s] # userinput og netsocket # get readable socket ( tcp socket or stdin ( user input ) ) ready_to_read,ready_to_write,in_error = select.select(socket_list, [], []); for sock in ready_to_read: if sock == s: #incoming message from server data = sock.recv(size); if not data: sys.stdout.write("[!] Disconnected.\n\n"); sys.exit(0); else : #print data from server sys.stdout.write(">>"+data+"\n"); sys.stdout.write('%'); sys.stdout.flush(); #flush output buffer else : # User input msg = sys.stdin.readline().rstrip(); #strip newline s.send(msg); #send meldingen s.close() sys.stdout.write("Terminating client.."); <file_sep>/math.py #!/usr/bin/python # LAB2 - <NAME> import operator; # operator functions from sys import exit # to invoke exit #operators ops = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div} #try parse integer from string, returns false if int(string) fails. def try_parse_int(s, base=10): try: int(s, base) return True except ValueError: return False #Check if operator is valid ( check if op is in list ) def valid_operator(op): if op in ('+', '-', '*', '/'): return True else: return False #respond to math request. def math(n1, op, n2): if( try_parse_int(n1) and try_parse_int(n2) and valid_operator(op) ): #evaluate user input operand = ops[op]; # assign valid operator function result = operand(int(n1), int(n2)); # perform math operation return "%s %s %s = %d" % (n1, op, n2, result) # return answer else: return " (!) Syntax: x [+,-,*,/] y, ex: 5 * 2" # return error message print "LAB2 - functions. Im a simple Math bot,\nI accept questions like this: x [+,-,*,/] y\n" # main loop while True: question = raw_input("> ") # input fra bruker q = question.split(' '); # splitte opp question ved hver space #print "debug: %d items in q" % (len(q)) # debug msg to check number of items in array if( len(q) < 3 ): # om q arrayet inneholder mindre enn 3 elementer print " (!) Syntax: x [+,-,*,/] y" else: ans = math(q[0], q[1], q[2]) print ans if ("exit" in question): print "Good bye!" exit(0) <file_sep>/ircbot.py #!/usr/bin/python #Simple IRC bot # <NAME> import socket; import operator; nick = 'everyb0t' network = 'irc.quakenet.org' port = 6667; chan = "#uia.cs" #operators ops = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div} #define socket irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "Connecting to ", network irc.connect((network,port)) #connect print "Connected! sending user info" # send info irc.recv(4096) irc.send('NICK ' + nick + '\r\n') #send nickname irc.send('USER everyb0t everyb0t everyb0t :everystone_bot\r\n') #send user info print "********* Bot online *********" #try parse integer from string def try_parse_int(s, base=10): try: int(s, base) return True except ValueError: return False #Check if operator is valid def valid_operator(op): if op in ('+', '-', '*', '/'): return True else: return False # hente username of user sending PRIVMSG to channel #:[email protected] PRIVMSG #uia.cs :hei def getUserNick(data): nick = data.split('!'); return nick[0].lstrip('#:'); #respond to ">hva er x + y math request def math(user, n1, op, n2): if( try_parse_int(n1) and try_parse_int(n2) and valid_operator(op) ): #evaluate user input operand = ops[op]; result = operand(int(n1), int(n2)); return " :%s: %s %s %s = %d" % (user, n1, op, n2, result) else: return " :%s: (!) Syntax: >hva er x [+,-,*,/] y" % (user) while True: # Main loop data=irc.recv(4096) #receive data from socket print data # ( debug - print all socket data ) if data.find('PING') != -1: #If PING is Found in the Data irc.send('PONG ' + data.split()[1] + '\r\n') #Send back a PONG print "PONG ",data.split()[1] ################ JOIN CHANNEL ############### if data.find(':[email protected] MODE everyb0t +i') != -1: #we are connected irc.send('JOIN ' + chan + '\r\n') #join channel print "** Joining channel ", chan irc.send('PRIVMSG ' + chan + ' hello\r\n') #say hello to chan ################# CS SERVER STATUS ###################### if data.find('!status') != -1: #CS SERVER STATUS ( TODO: query port 27015 with status query ) irc.send('PRIVMSG ' + chan + ' :server status: 0\r\n') ################## Matte operasjoner ##################### if data.find('>hva er') != -1: #hva er x (op) y raw=data.split(' '); user = getUserNick(data) svar = math(user, raw[5], raw[6], raw[7].rstrip('\n\r')) irc.send('PRIVMSG ' + chan + svar + '\r\n') #print raw <file_sep>/README.md is105 ===== Diverse python kode for faget is105 <NAME> <file_sep>/poker-server.py # -*- coding: latin-1 -*- # http://pymotw.com/2/select/ # http://www.tutorialspoint.com/python/python_dictionary.htm # Sockets programmering i Python # Utforskning av sockets api og andre Python moduler # Module kan betraktes som en slags plug-in som utvider funksjonaliteten til et grunnlag # Et grunnlag er programmeringsmiljø som man kan bruke for å gjøre "beregninger" / implementere "systemer" # select module gir tilgang til platform-spesifikke INN/UT monitorerings-funksjoner # select() er en POSIX funksjon som det finnes gode implementasjoner for i både UNIX- og Windows miljøer # POSIX er et forsøk på å standardisere et operativsystem import select import socket import sys import Queue import poker # Her er data for pokerspillet # For enkelhets skyld deler vi ut kort i det vi starter server # Dette bør skje på forespørsel fra en klient i neste versjon av programmet hands = poker.deal(3) handsdelt = 0 # Vi trenger en variabel som holder styr på hvor mange hender er delt ut players = 0; players_ready = 0; # Lage en TCP/IP socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setblocking(0) # Binde socketen på lokalmaskinen til porten 10000 server_address = ('localhost', 10000) print >>sys.stderr, '[+]starter socket på %s og port %s' % server_address server.bind(server_address) # Høre / vente på innkommende forbindelser server.listen(5) # Med select() kan man følge med på mer enn en forbindelse av gangen # Argumenter til select() er tre lister som inneholder kommunikasjonskanaler som skal observeres / monitoreres # (1) liste av objekter for data som kommer inn fra andre enheter og skal leses/avleses/konsumeres # (2) liste av objekter som vil motta data som er på vei ut, dvs. en slags lagerplass for data som sendes ut til andre enheter # (3) en liste over de objektene som har feilet, kan være objekter fra både "input" og "output" kanaler # Man må sette opp lister som inneholder INN-kilder og UT-bestemmelsessted # Forbindelser blir lagt til og fjernet fra disse listen av hovedløkken til serveren # Sockets som vi forventer å lese fra (kilder) inputs = [ server ] # Sockets hvilke vi forventer å skrive til (bestemmelsessted) outputs = [ ] # Man kan ha forskjellige kommunikasjonsstrategier # Server kan vente for at en socket blir skrivbar (man kan skrive til den) før man sender noen data, # istedenfor å sende responsen umiddelbart. # I et slikt tilfelle, trenger hver UT-forbindelse en meldingskø, som fungerer som en mellomlager (buffer) # Data må da sendes gjennom denne "bufferen", typen som brukes her er dictionary message_queues = {} #playernames playerNames = {} #player's hand playerHands = {} #Broadcast - send to all connected clients def broadcast(message): for key in message_queues.keys(): message_queues[key].put(message); # legg til message i meldings køen outputs.append(key) # legg til socket mottaker i outputs #Announce Winner def showdown(s): global players_ready; if(players_ready < 2): #ikke nok spillere er klare message_queues[s].put("[!]Not enough players are ready ("+str(players_ready)+")"); outputs.append(s); #tell player else: #Show cards response = "*** Player Cards ***\n"; for key in playerNames.keys(): cards = ' '.join(str(x) for x in playerHands.get(key)) response = response + playerNames.get(key)+": "+cards+"\n"; broadcast(response); #TODO: kalkulere vinner med poker.hand_rank() poker_winner(); players_ready = 0; # new round def poker_winner(): size=0; announce = "*** WINNER ***\n-------------\n"; msg = ""; for key in playerNames.keys(): hand = playerHands.get(key); player = playerNames.get(key); result = poker.hand_rank(hand); size = len(result); if size == 2: if result[0] == 0: #player has nothing ( 0 ) msg = player + "has nothing.\n "; elif result[0] == 4: msg = player +" has Straigt! " + str(result[1])+"\n"; elif size == 3: if result[0] == 1: #One pairs msg = player + " has One pair of " + str(result[1])+"\n"; elif result[0] == 2: #Two pairs msg = player + " has Two pairs of" + str(result[1])+"\n"; elif result[0] == 3: #Three of a kind msg = player + " has Three of a kind! " + str(result[1])+"\n"; #Take away players cards del playerHands[key]; announce = announce+msg; #append message #send message broadcast(announce); def dealCard(s): global players_ready; if playerHands.get(s) == None: #player has no cards hands = poker.deal(1) cards = ' '.join(str(x) for x in hands[0]) #playerHands.update({s:cards}); #give cards to player playerHands.update({s:hands[0]}); message_queues[s].put("Welcome!\nYour hand: "+cards+"\n"); # add message to queue outputs.append(s); #send to player players_ready+=1; #one more player is ready #broadcast that player joined broadcast(playerNames.get(s)+"Is ready to play!\n"); else : #player already has cards cards = ' '.join(str(x) for x in playerHands.get(s)) message_queues[s].put("You already joined!\nYour hand: "+cards); outputs.append(s); def showPlayers(s): response = "\n*** POKER PLAYERS ***\n"; for key in playerNames.keys(): response = response + playerNames.get(key)+"\n"; message_queues[s].put(response); #send playerlist outputs.append(s); #to client asking def isRegistered(s): test = playerNames.get(s); if test == None: return -1; # not registered else: return 0; # registered def register_player(name, s): if isRegistered(s) == -1: #not registered playerNames.update({s:name}); #message_queues[s].put(">>Registered!"); #outputs.append(s); #broadcast that player registered broadcast("[+]"+name+" Registered!"); else: message_queues[s].put("You are already registered as: "+playerNames.get(s)); # Hoveddelen av serverprogrammet er denne løkken som løper, og kaller select() som blokkerer utførelsen og # venter på nettverksaktivitet while inputs: # Vent inntil minst en av socketene er klar for prosessering #print >>sys.stderr, '\nventer på neste hendelse' readable, writable, exceptional = select.select(inputs, outputs, inputs) # select returnerer tre nye lister, som er subset av de opprinnelige listene # (1) alle socketene i readable listen har mellomlagret INN-data og er klare til å bli lest # (2) alle socketene i writable har fri lagringsplass i deres lager og kan bli skrevet til # (3) socketene som er returnert gjennom exceptional har hatt en feil (definisjon av uttak er platformavhengig) #for key in message_queues.keys(): #print >>sys.stderr, '[!]spiller %s er meldt seg for spill' % str(key.getpeername()) # Behandler inputs her for s in readable: if s is server: # En lesbar (readable) server socket er klar til å akseptere forbindelser connection, client_address = s.accept() print >>sys.stderr, '[+]en ny forbindelse fra', client_address connection.setblocking(0) inputs.append(connection) players+=1; #increase total players welcome_status = "Welcome to root poker!\nTotal players: %d\n------------------------\nuse \"help\" if you are stuck\n" % players # Gi forbindelse en kø for data som man ønsker å sende message_queues[connection] = Queue.Queue() message_queues[connection].put(welcome_status); #broadcast at en ny bruker har joina broadcast("[+]"+client_address[0]+" has joined!"); # (2) Dette er tilfelle når man har en allerede etablert forbindelse som man allerede # har brukt for å sende data # Data leses med recv(), så blir plassert i en kø, slik at den kan bli sendt gjennom socketen tilbake til klienten else: data = s.recv(1024) if data: #if newline in data, remove it if '\n' in data: data = data.rstrip('\n'); # En lesbar klient-socket som har data print >>sys.stderr, "mottok \"%s\" fra %s" % (data, s.getpeername()) # Koden skrevet av studenter # Sjekk meldingskø og også inputs # Her kan man behandle data som man mottar # Man kan også gi forskjellig respons til forskjellige klienter # OPPGAVE: del ut en hånd til en klient som sender JOIN # Her må du tenke på en algoritme som klarer å begrense antall klienter som kan spille # og hvor du også må finne en måte å dele ut kort på til hver av spillere # hands er her laget ved start av server, men finn også ut if data.startswith("REG"): register_player(data[4:], s); #start at char 4 after reg, and host s.getpeername()[0] #check if player is registered elif playerNames.get(s) == None: data = "\nPlease register first with REG <name>"; message_queues[s].put(data); elif data == 'JOIN': dealCard(s); #deal hand to player elif data == "SHOWDOWN": showdown(s) # Announce winner elif data == "help": #help message data = "\nJOIN\t-Join a game of poker!\nSHOWDOWN\t-Show winner of hand\nsay <msg>\t-send chat to everyone\nPLAYERS\t-Show connected players\n"; message_queues[s].put(data); elif data == "PLAYERS": #show total players showPlayers(s); elif data.startswith("say"): # chat melding meld = playerNames.get(s) + ": "+data[4:]; broadcast(meld); else: message_queues[s].put("Unknown command - try \"help\""); # Legg til UT-kanalen for responsen if s not in outputs: outputs.append(s) # (3) En lesbar socket uten tilgjengelige data er fra en klient som har koblet seg fra, slik at strømmen kan lukkes else: # Interpreter en tom resultat som en lukket forbindelse print >>sys.stderr, 'lukker', client_address, 'etter at ingen data kunne leses' # Stopper å høre for IN-data på denne forbindelsen if s in outputs: outputs.remove(s) inputs.remove(s) s.close() # Fjern meldingskø del message_queues[s] #fjern spillerens kort if playerHands.get(s) != None: del playerHands[s]; #broadcast at spilleren har forlatt spillet if playerNames.get(s) != None: broadcast(playerNames.get(s)+" has left the game!"); #fjern playerName fra playerNames del playerNames[s]; # Det er mindre antall muligheter for writable # Hvis det er data i køen for en forbindelse, neste melding blir sendt # Ellers, forbindelsen fjernes fra liste for UT-forbindelser, slik at i neste omgang i løkken select() # ikke skal indikere at socketen er klar til å sende data for s in writable: try: next_msg = message_queues[s].get_nowait() except Queue.Empty: # Ingen meldinger venter -> stoppe sjekking for skrivbarhet print >>sys.stderr, 'UT køen for', s.getpeername(), 'er tom' outputs.remove(s) else: print >>sys.stderr, 'sender "%s" til %s' % (next_msg, s.getpeername()) s.send(next_msg) # Til slutt, hvis det er en feil i socketen, den blir lukket for s in exceptional: print >>sys.stderr, 'behandler feilsituasjon for', s.getpeername() # Stoppe å høre for input for forbindelsen inputs.remove(s) if s in outputs: outputs.remove(s) s.close() # Fjern meldingskø del message_queues[s] #for key in message_queues.keys(): #print >>sys.stderr, '[!]spiller %s er meldt seg for spill' % str(key.getpeername()) s.close() sys.stdout.write("Terminating Server..");
202e8482af0d74c57c24ee7e60110e85bbfde027
[ "Markdown", "Python" ]
8
Python
everystone/is105
ed8e7ad7a450237f8da8f1b1e76ef7559d61cf05
c08c371940f62a16842d9c8f433c553af89b6b9f
refs/heads/master
<repo_name>lotrikys/DZ_9<file_sep>/app/src/main/java/ua/org/lotrik/dz_9/MainActivity.java package ua.org.lotrik.dz_9; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import java.util.TreeSet; public class MainActivity extends AppCompatActivity { private static final int PICK_RESULT = 0; Integer number = 0; ArrayAdapter<?> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button contacts = (Button)findViewById(R.id.contacts); Button contact = (Button)findViewById(R.id.contact); Button call = (Button)findViewById(R.id.call); final Button map = (Button)findViewById(R.id.map); contacts.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent contacts = new Intent(Intent.ACTION_VIEW, ContactsContract.Contacts.CONTENT_URI); startActivity(contacts); } }); contact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.ContactsContract.Contacts.CONTENT_URI); startActivityForResult(pickIntent, PICK_RESULT); } }); call.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (number != 0) { Intent call = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number)); startActivity(call); } } }); map.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String coordinates = "geo:48.473043, 35.026825"; Intent mapIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(coordinates)); startActivity(mapIntent); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { final Spinner spinner = (Spinner)findViewById(R.id.spinner); TreeSet<String> choose = new TreeSet<String>(); String phoneNumber = ""; TextView textView = (TextView)findViewById(R.id.textView); if (requestCode == PICK_RESULT && resultCode == RESULT_OK) { Uri contactUri = data.getData(); Cursor c = getContentResolver().query(contactUri, null, null, null, null); c.moveToNext(); String name = c.getString(c.getColumnIndexOrThrow( ContactsContract.Contacts.DISPLAY_NAME)); String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)); Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null); while (phones.moveToNext()) { switch (phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE))) { case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE : phoneNumber += "Mobile: " + phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); if (!phones.isLast()) { phoneNumber += ", "; } choose.add(phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER))); break; case ContactsContract.CommonDataKinds.Phone.TYPE_HOME : phoneNumber += "Home: " + phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); if (!phones.isLast()) { phoneNumber += ", "; } choose.add(phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER))); break; case ContactsContract.CommonDataKinds.Phone.TYPE_WORK : phoneNumber += "Work: " + phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); if (!phones.isLast()) { phoneNumber += ", "; } choose.add(phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER))); break; } } String[] phones_array = {}; phones_array = choose.toArray(new String[choose.size()]); adapter = new ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, phones_array); textView.setText("Имя: " + name + " " + phoneNumber); spinner.setAdapter(adapter); adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { number = Integer.parseInt(spinner.getSelectedItem().toString().replaceAll(" ", "")); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } } } <file_sep>/README.md # DZ_9 https://github.com/lotrikys/DZ_9
23d4f16816f28194944f39aa9fc04e290b719414
[ "Markdown", "Java" ]
2
Java
lotrikys/DZ_9
a00f2ba42b8592c560e1cbfa3fe4cae0aaf750be
52d8be6b553bbf4d5d31eb401210b5582ea92a8c
refs/heads/master
<repo_name>Umrzoq-developer/autosmonsters<file_sep>/src/Components/ChatPage/ChatPage.jsx import React from 'react' import socketClient from "socket.io-client"; import Chat from './Chat'; const SERVER = "http://127.0.0.1:8080"; const ChatPage = () => { var socket = socketClient (SERVER); return ( <div style={{margin: "150px auto", height: "400px", width: "80%"}}> <h5 style={{textAlign: "left"}}>Chat panel</h5> <Chat /> </div> ) } export default React.memo(ChatPage) <file_sep>/src/Components/AdminPanel/ChatAdmin.jsx import React from 'react' import AdminPanelHeader from '../../Containers/AdminPanelHeader/AdminPanelHeader' import Chat from '../ChatPage/Chat' const ChatAdmin = () => { return ( <AdminPanelHeader> <Chat /> </AdminPanelHeader> ) } export default React.memo(ChatAdmin) <file_sep>/src/Components/ChatPage/ChannelList.js import React from "react"; import Channel from "./Channel"; const ChannelList = ({ onSelectChannel, channels }) => { const handleClick = (id) => { onSelectChannel(id); }; let list = ( <div className="no-content-message">There is no channels to show</div> ); if (channels && channels.map) { list = channels.map((c) => ( <Channel key={c.id} id={c.id} name={c.name} participants={c.participants} onClick={handleClick} /> )); } return <div className="channel-list">{list}</div>; }; export default ChannelList;
e8b755f3b5f97d5d9dde6bdbfe9f05a9404c368b
[ "JavaScript" ]
3
JavaScript
Umrzoq-developer/autosmonsters
231f09c7582d517e25782b1319eb864c6c9896ee
548f48846cf29d629a99bece7ce1bf2007224a0f
refs/heads/master
<file_sep># encoding: utf-8 require "logstash/inputs/base" require "logstash/inputs/elasticsearch" require_relative "../../logstash/inputs/value_tracking" require "logstash/json" require "time" # This plugin is a simple extension of Elasticsearch input plugin. We added tracking_column property # for search in elasticsearch query all hits that contains the 'last_update' value bigger that the value_tracker. # The value_tracker contains the last consult to that index stored in a last run file created. # We build the query based on the above described. # This is a sample of elastic_jdbc plugin statement: # input { # # Read all documents from Elasticsearch matching the given query # elastic_jdbc { # hosts => "localhost" # tracking_column => "last_update" # last_run_metadata_path => "/opt/logstash/last_run/index_name" # } # } # class LogStash::Inputs::ElasticJdbc < LogStash::Inputs::Elasticsearch config_name "elastic_jdbc" # Overwrite query default of elasticsearch plugin. We build a default query in this plugins. config :query, :validate => :string, :default => '{}' #region tracking configuration # Path to file with last run time config :last_run_metadata_path, :validate => :string, :default => "#{ENV['HOME']}/.logstash_jdbc_last_run" # If tracking column value rather than timestamp, the column whose value is to be tracked config :tracking_column, :validate => :string # Type of tracking column. Currently only "numeric" and "timestamp" config :tracking_column_type, :validate => ['timestamp'], :default => 'timestamp' # Whether the previous run state should be preserved config :clean_run, :validate => :boolean, :default => false # Whether to save state or not in last_run_metadata_path config :record_last_run, :validate => :boolean, :default => true #endregion public def register if @tracking_column.nil? raise(LogStash::ConfigurationError, "Must set :tracking_column if :use_column_value is true.") end @value_tracker = ValueTracking.build_last_value_tracker(self) super build_query end # def register def set_value_tracker(instance) @value_tracker = instance end def build_query input_query = @base_query # Remove sort tag from base query. We only sort by tracking column input_query.delete("sort") time_now = Time.now.utc last_value = @value_tracker ? Time.parse(@value_tracker.value.to_s).iso8601 : Time.parse(time_now).iso8601 column = @tracking_column.to_s query_default = {query: { bool: { must: [ {range: {column => {gt: last_value.to_s}}} ]}}} if !input_query.nil? and !input_query.empty? query_conditions = input_query["query"] if query_conditions must_statement = query_default[:query][:bool][:must] final_must_cond = must_statement.append(query_conditions) query_default[:query][:bool][:must] = final_must_cond end end sort_condition = [{column => {order: "asc"}}] query_default[:sort] = sort_condition @base_query = LogStash::Json.load(query_default.to_json) end def run(output_queue) super end # def run def do_run_slice(output_queue, slice_id=nil) slice_query = @base_query slice_query = slice_query.merge('slice' => { 'id' => slice_id, 'max' => @slices}) unless slice_id.nil? slice_options = @options.merge(:body => LogStash::Json.dump(slice_query) ) logger.info("Slice starting", slice_id: slice_id, slices: @slices) unless slice_id.nil? r = search_request(slice_options) r['hits']['hits'].each { |hit| push_hit(hit, output_queue) } logger.debug("Slice progress", slice_id: slice_id, slices: @slices) unless slice_id.nil? has_hits = r['hits']['hits'].any? while has_hits && r['_scroll_id'] && !stop? r = process_next_scroll(output_queue, r['_scroll_id']) logger.debug("Slice progress", slice_id: slice_id, slices: @slices) unless slice_id.nil? has_hits = r['has_hits'] end logger.info("Slice complete", slice_id: slice_id, slices: @slices) unless slice_id.nil? end def push_hit(hit, output_queue) event = LogStash::Event.new(hit['_source']) if @docinfo # do not assume event[@docinfo_target] to be in-place updatable. first get it, update it, then at the end set it in the event. docinfo_target = event.get(@docinfo_target) || {} unless docinfo_target.is_a?(Hash) @logger.error("Elasticsearch Input: Incompatible Event, incompatible type for the docinfo_target=#{@docinfo_target} field in the `_source` document, expected a hash got:", :docinfo_target_type => docinfo_target.class, :event => event) # TODO: (colin) I am not sure raising is a good strategy here? raise Exception.new("Elasticsearch input: incompatible event") end @docinfo_fields.each do |field| docinfo_target[field] = hit[field] end event.set(@docinfo_target, docinfo_target) end decorate(event) output_queue << event # Write in the file the last_update value register in the event. @value_tracker.set_value(event.get(@tracking_column)) @value_tracker.write end def stop super end end # class LogStash::Inputs::ElasticJdbc <file_sep># Logstash input plugin [GitHub](https://github.com/ernesrocker/logstash-input-elastic_jdbc). This is a plugin for [Logstash](https://github.com/elastic/logstash). RubyGems repository [logstash-input-elastic_jdbc](https://rubygems.org/gems/logstash-input-elastic_jdbc) It is fully free and fully open source. ## How install ```sh sudo /usr/share/logstash/bin/logstash-plugin install logstash-input-elastic_jdbc ``` ## Documentation This plugin inherit of elasticsearch(**ES**) input plugin, and added a tracking_column using in jdbc input plugin for make a query to obtain the updates values. Sample : ```logstash input{ elastic_jdbc{ hosts => "localhost" index => "documents" tracking_column => "last_update" query => '{"query":{"range":{"created":{"gte":"2021-08-13T00:17:58+00:00"}}}}' last_run_metadata_path => "/opt/logstash/last_run/elastic_jdbc_documents" } } filter { } output{ stdout{} } ``` In the sample before, we read from ES cluster, **documents** index, where documents hits have last_update field as a **date** type field (recommend use [Ingest pipelines](https://www.elastic.co/guide/en/elasticsearch/reference/7.x/ingest.html)), then we look for all documents that have a field value **last_update** greater than the value stored in `/opt/logstash/last_run/elastic jdbc_documents" `. #### Required parameters: * `hosts`: ES cluster url * `index`: ES index * `tracking_column`: Date field to tracking in ES index * `last_run_metadata_path` : File path where stored the last value from last hist readed from ES index. By the default have the date `1960-01-01` #### Optional parameters: * All [logstash-input-elasticsearch](https://rubygems.org/gems/logstash-input-elasticsearch) parameters can use in this plugins. * `query`: By the default we use a bool query where we get a hits with `tracking column` greater that last value stored in `last_run_metadata_path`. You can insert a query, but keep in mind that your query always be appended with the default query ( *if you don't need search by tracking column, please use [logstash-input-elasticsearch](https://rubygems.org/gems/logstash-input-elasticsearch) plugin*). Sample, for this query parameter ``query => '{"query":{"range":{"created":{"gte":"2021-08-13T00:17:58+00:00"}}}}'``, the final query using this plugin would be: ```{ "query":{ "bool":{ "must":[ {"range": {"last_update":{"gt": "date_time_value_stored"}}}, {"range":{"abonado_date":{"gte": "2021-08-13T00:17:58+00:00"}}} ] } }, "sort": [{"last_update"=>{:order=>"asc"}}] } ``` **Note:** If you insert a sort statement inside the query, we always overwrite it with the sort statement value that shown above. ## Contributing All contributions are welcome: ideas, patches, documentation, bug reports, complaints, and even something you drew up on a napkin. Programming is not a required skill. Whatever you've seen about open source and maintainers or community members saying "send patches or die" - you will not see that here. It is more important to the community that you are able to contribute. For more information about contributing, see the [CONTRIBUTING](https://github.com/ernesrocker/logstash-input-elastic_jdbc/blob/master/CONTRIBUTORS) file. <file_sep># logstash-input-elastic_jdbc Example input plugin. This should help bootstrap your effort to write your own input plugin! <file_sep>require "yaml" # persistence class ValueTracking def self.build_last_value_tracker(plugin) handler = NullFileHandler.new(plugin.last_run_metadata_path) if plugin.record_last_run handler = FileHandler.new(plugin.last_run_metadata_path) end if plugin.clean_run handler.clean end instance = DateTimeValueTracker.new(handler) end attr_reader :value def initialize(handler) @file_handler = handler set_value(get_initial) end def get_initial # override in subclass end def set_value(value) # override in subclass end def write @file_handler.write(@value.to_s) end end class DateTimeValueTracker < ValueTracking def get_initial @file_handler.read || DateTime.new(1970) end def set_value(value) if value.respond_to?(:to_datetime) @value = value.to_datetime else @value = DateTime.parse(value) end end end class FileHandler def initialize(path) @path = path @exists = ::File.exist?(@path) end def clean return unless @exists ::File.delete(@path) @exists = false end def read return unless @exists YAML.load(::File.read(@path)) end def write(value) ::File.write(@path, YAML.dump(value)) @exists = true end end class NullFileHandler def initialize(path) end def clean end def read end def write(value) end end
c848de5d5b7559c9f6c726045f8ed41633dc07ca
[ "Markdown", "Ruby" ]
4
Ruby
ernesrocker/logstash-input-elastic_jdbc
5d31ab2cf94ac1d6e44250b81af7f2642c5c7a5a
feb6ac20bc1526c8b2709c7679225a029bdd2485
refs/heads/main
<file_sep>#[macro_use] extern crate serde_derive; use std::io; use std::process; use std::io::Write; mod blockchain; fn main() { let mut miner_addr = String::new(); let mut difficulty = String::new(); let mut choice = String::new(); print!("input miner address: "); io::stdout().flush(); io::stdin().read_line(&mut miner_addr); print!("difficulty: "); io::stdout().flush(); io::stdin().read_line(&mut difficulty); let diff = difficulty.trim().parse::<u32>().expect("difficulty must be an integer."); println!("generating genesis block..."); let mut blockchain = blockchain::Blockchain::new(miner_addr.trim().to_string(), diff); loop { println!("Menu"); println!("1) New Transaction"); println!("2) Mine block"); println!("3) Change Difficulty"); println!("4) Change Reward"); println!("0) Exit"); print!("Enter your choice: "); io::stdout().flush(); choice.clear(); io::stdin().read_line(&mut choice); println!(""); match choice.trim().parse().unwrap() { 0 => { print!("exiting program..."); process::exit(0); }, 1 => { let mut sender = String::new(); let mut receiver = String::new(); let mut amount = String::new(); let trans_res; print!("sender address: "); io::stdout().flush(); io::stdin().read_line(&mut sender); print!("receiver address: "); io::stdout().flush(); io::stdin().read_line(&mut receiver); print!("amount: "); io::stdout().flush(); io::stdin().read_line(&mut amount); trans_res = blockchain.new_transaction( sender.trim().to_string(), receiver.trim().to_string(), amount.trim().parse().unwrap() ); }, _ => println!("invalid option..."), } } }
7d4e1b79e49a964fcad3c8c73955a588e215eaba
[ "Rust" ]
1
Rust
sebdeveloper6952/rust-blockchain
c6ed334144e451d07e84f5167079c63d03f72086
b836c229cd79e95e3100328b42b21ab666d05ec1
refs/heads/main
<file_sep>/* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ /* Modified by <NAME> <EMAIL> */ #ifndef BUFFER_H #define BUFFER_H #include "Globals.h" #include <algorithm> #include "utils.h" namespace mash { namespace core { #define USE_64BIT_MEMORY 1 class Buffer { public: Buffer(uint64 size_) { ASSERT(size_ != 0); #if (USE_64BIT_MEMORY) uint64 size64 = size_ / 8; if (size64 * 8 < size_) size64 += 1; buffer = new uint64[size64]; #else buffer = new byte[size_]; #endif size = size_; } ~Buffer() { delete buffer; } uint64 Size() const { return size; } byte* Pointer() const { return (byte*)buffer; } #if (USE_64BIT_MEMORY) uint64* Pointer64() const { return buffer; } #endif void Extend(uint64 size_, bool copy_ = false) { #if (USE_64BIT_MEMORY) uint64 size64 = size / 8; if (size64 * 8 < size) size64 += 1; uint64 newSize64 = size_ / 8; if (newSize64 * 8 < size_) newSize64 += 1; if (size > size_) return; if (size64 == newSize64) { size = size_; return; } uint64* p = new uint64[newSize64]; if (copy_) std::copy(buffer, buffer + size64, p); #else if (size > size_) return; byte* p = new byte[size_]; if (copy_) std::copy(buffer, buffer + size, p); #endif delete[] buffer; buffer = p; size = size_; } void Swap(Buffer& b) { TSwap(b.buffer, buffer); TSwap(b.size, size); } private: Buffer(const Buffer& ) {} Buffer& operator= (const Buffer& ) { return *this; } #if (USE_64BIT_MEMORY) uint64* buffer; #else byte* buffer; #endif uint64 size; }; struct DataChunk { static const uint64 DefaultBufferSize = 1 << 20; // 1 << 22 Buffer data; uint64 size; DataChunk *next = NULL;//[haoz:]added for all seqchunk in one part DataChunk(const uint64 bufferSize_ = DefaultBufferSize) : data(bufferSize_) , size(0) {} void Reset() { size = 0; next = NULL; } }; struct DataPairChunk { DataChunk* left_part; DataChunk* right_part; }; } // namespace core } // namespace mash #endif // BUFFER_H <file_sep>/* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ #ifndef H_DATA_POOL #define H_DATA_POOL #include "Globals.h" #include <vector> #include <iostream> #include <algorithm> #ifdef USE_BOOST_THREAD #include <boost/thread.hpp> namespace th = boost; #else #include <thread> #include <mutex> #include <condition_variable> namespace th = std; #endif namespace mash { namespace core { template <class _TDataType> class TDataPool { typedef _TDataType DataType; typedef std::vector<DataType*> part_pool; const uint32 maxPartNum; const uint32 bufferPartSize; part_pool availablePartsPool; part_pool allocatedPartsPool; th::mutex mutex; th::condition_variable partsAvailableCondition; public: volatile uint32 partNum; static const uint32 DefaultMaxPartNum = 32; static const uint32 DefaultBufferPartSize = 1 << 22; TDataPool(uint32 maxPartNum_ = DefaultMaxPartNum, uint32 bufferPartSize_ = DefaultBufferPartSize) : maxPartNum(maxPartNum_) , bufferPartSize(bufferPartSize_) , partNum(0) { availablePartsPool.resize(maxPartNum); allocatedPartsPool.reserve(maxPartNum); } ~TDataPool() { for (typename part_pool::iterator i = allocatedPartsPool.begin(); i != allocatedPartsPool.end(); ++i) { ASSERT(*i != NULL); delete *i; } } void Acquire(DataType* &part_) { th::unique_lock<th::mutex> lock(mutex); while (partNum >= maxPartNum) partsAvailableCondition.wait(lock); ASSERT(availablePartsPool.size() > 0); DataType*& pp = availablePartsPool.back(); availablePartsPool.pop_back(); if (pp == NULL) { pp = new DataType(bufferPartSize); allocatedPartsPool.push_back(pp); } else { pp->Reset(); } partNum++; part_ = pp; } void Release(const DataType* part_) { th::lock_guard<th::mutex> lock(mutex); ASSERT(part_ != NULL); ASSERT(partNum != 0 && partNum <= maxPartNum); ASSERT(std::find(allocatedPartsPool.begin(), allocatedPartsPool.end(), part_) != allocatedPartsPool.end()); availablePartsPool.push_back((DataType*)part_); partNum--; partsAvailableCondition.notify_one(); } }; } // namespace core } // namespace mash #endif // H_DATA_POOL <file_sep>/* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ #include <cstdio> #include <vector> #include <map> #include <cstdio> //#include "../Sketch.h" #include "Reference.h" #include "FastxIO.h" #include "Buffer.h" #include "FastxStream.h" //#include "read.h" //#include "Sequence.h" using namespace std; namespace mash { namespace fa { /* FastaChunk* FastaReader::readNextChunk(){ FastaDataChunk* part = NULL; recordsPool.Acquire(part); FastaChunk *dataPart = new FastaChunk; dataPart->chunk = part; if(fileReader.ReadNextChunk(dataPart, this->seqInfos)) { return dataPart; } else { recordsPool.Release(part); return NULL; } } */ //int chunkFormat(FastaDataChunk* &chunk, std::vector<Sequence*> &data, bool mHasQuality){ // //format a whole chunk and return number of reads // int seq_count = 0; // int line_count = 0; // int pos_ = 0; // // while(true){ // //TODO rewrite to deal with part sequence // //string name = getLine(chunk, pos_); // //if(name.empty()) break;//dsrc guarantees that read are completed! // //std::cout << name << std::endl; // // //string sequence = getSequence(chunk, pos_); // //std::cout << sequence << std::endl; // // //data.push_back(new Read(name, sequence)); // //seq_count++; // // } // // return seq_count; //} //FIXME:support enter = \n only string getSequence(FastaDataChunk * &chunk, uint64 &pos) { int start_pos = pos; char * data = (char *)chunk->data.Pointer(); //cerr << "start pos: " << pos << endl << flush; //cerr << "chunk size: " << chunk->size << endl << flush; //cerr << "data[pos]: " << (int)data[pos] << endl << flush; string res=""; while(pos < chunk->size - 1 ) { if(data[pos] == '\n'){ res += string(data+start_pos, pos-start_pos); pos++; start_pos = pos; if(data[pos] == '>') return res; } else{ pos++; } } //deal with last char if(pos == chunk->size - 1) { if(data[pos] == '\n') res += string(data+start_pos, pos - start_pos); else res += string(data+start_pos, pos - start_pos + 1); return res; } return ""; } //only support uinx-like '\n' string getLine(FastaDataChunk * &chunk, uint64 &pos) { int start_pos = pos; char* data = (char *)chunk->data.Pointer(); while(pos < chunk->size){ if(data[pos] == '\n'){ pos++; return string(data+start_pos, pos-start_pos - 1); } else{ pos++; } } return ""; } int chunkFormat(FastaChunk & fachunk, vector<Reference> & refs) { uint64 pos = 0; bool done = false; //cerr << "into chunkFormat" << endl; while(true){ Reference ref = getNextSeq(fachunk, done, pos); if(done) break; refs.push_back(ref); } ASSERT(refs.size() == fachunk.nseqs); return refs.size(); } //design to filter out kmer apps int chunkFormat(FastaChunk & fachunk, vector<Reference> & refs, int kmerSize) { uint64 pos = 0; bool done = false; //cerr << "into chunkFormat" << endl; uint64 short_count = 0; //counter for seqs shorter than kmer while(true){ Reference ref = getNextSeq(fachunk, done, pos); if(done) break; if(ref.seq.length() < kmerSize) short_count++; else refs.push_back(ref); } ASSERT(refs.size() + short_count == fachunk.nseqs); return refs.size(); } Reference getNextSeq(FastaChunk & fachunk, bool & done, uint64 & pos) { Reference ref; if(pos >= fachunk.chunk->size - 1){ done = true; return ref; } char *data = (char *)fachunk.chunk->data.Pointer(); //while(data[pos] == '\n') pos++;//jump empty lines if(data[pos] != '>') { ref.seq = getSequence(fachunk.chunk, pos); ref.length = ref.seq.size(); ref.gid = fachunk.start; fachunk.start++; }else{ string line = getLine(fachunk.chunk, pos); int str_pos = line.find_first_of(' '); ref.name = line.substr(1, str_pos-1); //remove '>' and ' ' if(str_pos < line.size()) ref.comment = line.substr(str_pos + 1); //cerr << "name: " << ref.name << endl << flush; ref.seq = getSequence(fachunk.chunk, pos); //cerr << "seq: " << ref.seq << endl << flush; ref.length = ref.seq.size(); ref.gid = fachunk.start; fachunk.start++; } return ref; } } // namesapce fa namespace fq { /* void FastqReader::readChunk() { FastqDataChunk* part = NULL; recordsPool.Acquire(part); printf("fastqio: ready to into while\n"); //while (!errorHandler.IsError() && fileReader.ReadNextChunk(part)) while(fileReader.ReadNextChunk(part)) { ASSERT(part->size > 0); //recordsQueue.Push(numParts, part); //[haoz:] Push:把<numparts, part>组成pair然后放到recordsQueue里面然后notifiy_one printf("numParts is %d\n", numParts); numParts++; recordsPool.Release(part); recordsPool.Acquire(part); } ASSERT(part->size == 0); recordsPool.Release(part); // the last empty part //recordsQueue.SetCompleted(); } FastqDataChunk* FastqReader::readNextChunk(){ FastqDataChunk* part = NULL; recordsPool.Acquire(part); if(fileReader.ReadNextChunk(part)) { return part; } else { recordsPool.Release(part); return NULL; } } */ //FastqDataChunk* FastqReader::readNextPairedChunk(){ // FastqDataChunk* part = NULL; // recordsPool.Acquire(part); // if(fileReader.ReadNextPairedChunk(part)) // { // //std::cout <<"read one chunk: " << std::endl; // //std::cerr << (char*)part->data.Pointer() << endl; // //std::cerr << "chunk end" << endl; // return part; // } // else // { // //std::cout <<"read one chunk failed : " << std::endl; // recordsPool.Release(part); // return NULL; // } //} void print_read(neoReference& ref){ std::cout << std::string((char*)ref.base+ref.pname, ref.lname) << std::endl; std::cout << std::string((char*)ref.base+ref.pseq, ref.lseq) << std::endl; std::cout << std::string((char*)ref.base+ref.pstrand, ref.lstrand) << std::endl; std::cout << std::string((char*)ref.base+ref.pqual, ref.lqual) << std::endl; } int chunkFormat(FastqChunk* &fqChunk, std::vector<neoReference> &data, bool mHasQuality = true){ FastqDataChunk * chunk = fqChunk->chunk; uint64_t seq_count = 0; uint64_t line_count = 0; uint64_t pos_ = 0; neoReference ref; while(true){ ref.base = chunk->data.Pointer(); ref.pname = pos_; if(neoGetLine(chunk, pos_, ref.lname)){ ref.pseq = pos_; } else{ break;} neoGetLine(chunk, pos_, ref.lseq); ref.pstrand = pos_; neoGetLine(chunk, pos_, ref.lstrand); ref.pqual = pos_; neoGetLine(chunk, pos_, ref.lqual); seq_count++; //print_read(ref); data.emplace_back(ref); } return seq_count; } /* int chunkFormat(FastqChunk* &fqChunk, std::vector<Reference> &data, bool mHasQuality = true){ //format a whole chunk and return number of reads FastqDataChunk * chunk = fqChunk->chunk; int seq_count = 0; int line_count = 0; int pos_ = 0; Reference ref; while(true){ string name = getLine(chunk, pos_); if(name.empty()) break;//dsrc guarantees that read are completed! //std::cerr << name << std::endl; string sequence = getLine(chunk, pos_); //std::cerr<< sequence << std::endl; string strand = getLine(chunk, pos_); //std::cerr << strand << std::endl; ref.name = name; ref.seq = sequence; ref.strand = strand; if(!mHasQuality){ string quality = string(sequence.length(), 'K'); //std::cerr << quality << std::endl; //data.push_back(new Read(name, sequence, strand, quality)); //data.emplace_back(Sketch::Reference(name, "", sequence, strand, quality)); ref.quality = quality; data.push_back(ref); seq_count++; }else{ string quality = getLine(chunk, pos_); //std::cerr << quality << std::endl; //data.push_back(new Read(name, sequence, strand, quality)); //data.emplace_back(Sketch::Reference(name, "", sequence, strand, quality)); ref.quality = quality; data.push_back(ref); seq_count++; } } return seq_count; } */ //int pairedChunkFormat(FastqDataChunk* &chunk, std::vector<ReadPair*> &data, bool mHasQuality){ // //format a whole chunk and return number of reads // int seq_count = 0; // int pos_ = 0; // //处理一开始的两条序列 // Read* first = getOnePairedRead(chunk,pos_,mHasQuality); // Read* second = getOnePairedRead(chunk,pos_,mHasQuality); // // // if(first->mName.substr(0, first->mName.find(' ')) == second->mName.substr(0, second->mName.find(' ')) ){ // //cerr << first->mName<<" + " << endl; // // data.push_back(new ReadPair(first,second)); // seq_count++; // // }else{ // //std::cout<<"Right"<<std::endl; // //cerr << first->mName<<" - "<<endl; // Read* third = getOnePairedRead(chunk,pos_,mHasQuality); // data.push_back(new ReadPair(second,third)); // seq_count++; // } // while(true){ // Read* t1=getOnePairedRead(chunk,pos_,mHasQuality); // if(t1 == NULL){ // break; // } // Read* t2 =getOnePairedRead(chunk,pos_,mHasQuality); // if(t2 == NULL){ // //cerr << t1->mName << " with + without -" << endl; // break; // } // data.push_back(new ReadPair(t1,t2)); // seq_count++; // } // // //for(int i =0;i<seq_count;i++){ // // cerr << data[i]->mLeft->mName<<endl; // // cerr << data[i]->mLeft->mSeq.mStr<<endl; // // cerr << data[i]->mLeft->mStrand<<endl; // // cerr << data[i]->mLeft->mQuality<<endl; // // cerr << data[i]->mRight->mName<<endl; // // cerr << data[i]->mRight->mSeq.mStr<<endl; // // cerr << data[i]->mRight->mStrand<<endl; // // cerr << data[i]->mRight->mQuality<<endl; // // // //} // //cerr << data[seq_count-1]->mLeft->mName<<endl; // // return seq_count; //} //Read* getOnePairedRead(FastqDataChunk* &chunk,int &pos_, bool mHasQuality){ // while(true){ // string name = getLine(chunk, pos_); // if(name.empty()) return NULL; // //std::cerr << name << std::endl; // string sequence = getLine(chunk, pos_); // // string strand = getLine(chunk, pos_); // if(!mHasQuality){ // string quality = string(sequence.length(), 'K'); // return new Read(name, sequence, strand, quality); // // }else{ // string quality = getLine(chunk, pos_); // //std::cerr << quality << std::endl; // return new Read(name, sequence, strand, quality); // } // } //} string getLine(FastqDataChunk* &chunk, int &pos){ int start_pos = pos; char* data = (char *)chunk->data.Pointer(); while(pos <= (chunk->size + 1)){ if(data[pos] == '\n' || data[pos] == '\r' || pos == (chunk->size + 1)){ //find a line pos++; return string(data+start_pos, pos-start_pos - 1); } else{ pos++; } } return ""; } int neoGetLine(FastqDataChunk* &chunk, uint64_t &pos, uint64_t &len){ int start_pos = pos; const char* data = (char *)chunk->data.Pointer(); const uint64_t chunk_size = chunk->size + 1; /* while (pos <= chunk_size && data[pos] != '\n'){ pos++; } len = pos - start_pos - 1; return len; */ //while(pos <= (chunk->size + 1)){ while(pos <= chunk_size){ //if(data[pos] == '\n' || data[pos] == '\r' || pos == (chunk->size + 1)){ if(data[pos] == '\n'){ //find a line pos++; //return string(data+start_pos, pos-start_pos - 1); //pos = start_pos; len = pos - start_pos - 1; return len; } else{ pos++; } } return 0; } /* int neoGetLine(FastqDataChunk* &chunk, char* &pos, uint64_t &len){ char* start_pos = pos; char* data = (char *)chunk->data.Pointer(); char* chunkend = data + chunk->size + 1; //the end address of this chunk(memory address) while(pos <= chunkend){ if(*pos == '\n' || *pos == '\r' || pos == chunkend){ //find a line pos++; len = (pos - start_pos)/sizeof(char); //-------if need the division??-------// //return string(data+start_pos, pos-start_pos - 1); return len; } else{ pos++; } } return 0; } */ } // namesapce fq } // namespace mash <file_sep>/* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 last modified by <NAME> 2020/5/18 */ #include "FastxStream.h" //#include "../Sketch.h" #include <iostream> #include <string> #include "Reference.h" namespace mash { namespace fa { FastaChunk* FastaFileReader::readNextChunk(){ FastaDataChunk* part = NULL; recordsPool.Acquire(part); FastaChunk *dataPart = new FastaChunk; dataPart->chunk = part; if(ReadNextChunk(dataPart, this->seqInfos)) { return dataPart; } else { std::cout << "read over!" << std::endl; recordsPool.Release(part); return NULL; } } /* Description: this function make sure one FastaChunk(dataPart) contains at least one whole sequence, because */ FastaChunk* FastaFileReader::readNextChunkList(){ FastaDataChunk* part = NULL; recordsPool.Acquire(part); FastaChunk *dataPart = new FastaChunk; dataPart->chunk = part; FastaDataChunk* currnet = NULL; bool continue_read = false; if(ReadNextFaChunk(dataPart->chunk, this->seqInfos, continue_read)) { FastaDataChunk* current = part; while(continue_read){ FastaDataChunk *append = NULL; recordsPool.Acquire(append); if(ReadNextFaChunk(append, this->seqInfos, continue_read)){ current->next = append; currnet = append; }else{ recordsPool.Release(append); break; } } return dataPart; } else { recordsPool.Release(part); return NULL; } } bool FastaFileReader::ReadNextChunk(FastaChunk* dataChunk_, SeqInfos& seqInfos) { //std::cout << "==================Next Chunk =========================" << std::endl; FastaDataChunk *chunk_ = dataChunk_->chunk; if (Eof()) { chunk_->size = 0; return false; } // flush the data from previous incomplete chunk uchar* data = chunk_->data.Pointer(); const uint64 cbufSize = chunk_->data.Size(); chunk_->size = 0; int64 toRead = cbufSize - bufferSize;// buffersize: size left from last chunk if (bufferSize > 0) { std::copy(swapBuffer.Pointer(), swapBuffer.Pointer() + bufferSize, data); chunk_->size = bufferSize; bufferSize = 0; } // read the next chunk int64 r = this->Read(data + chunk_->size, toRead); //std::cout << "r is :" << r << std::endl; //std::cout << "toRead: " << toRead << std::endl; if (r > 0) { if (r == toRead) // somewhere before end { //uint64 chunkEnd = cbufSize - SwapBufferSize; // Swapbuffersize: 1 << 13 ////std::cout << "chunkend cbufsize Swapbuffersize: " << chunkEnd <<" "<< cbufSize << " " << SwapBufferSize << std::endl; //chunkEnd = GetNextRecordPos(data, chunkEnd, cbufSize); //chunk_->size = chunkEnd - 1; //remove \n //if (usesCrlf) // chunk_->size -= 1; //std::copy(data + chunkEnd, data + cbufSize, swapBuffer.Pointer()); //bufferSize = cbufSize - chunkEnd; //dealing with halo region uint64 chunkEnd = FindCutPos(dataChunk_, data, cbufSize, mHalo, seqInfos); chunk_->size = chunkEnd;// - 1; //1 char back from last '>' //debug only //std::string content((char*)data, chunk_->size); //std::cout << "chunkEnd data: " << (char)data[chunkEnd-1] << std::endl; //std::cout << "chunkEnd: " << (uint64)chunkEnd << std::endl; //std::cout << "chunk_->size: " << chunk_->size << std::endl; //std::cout << "content_ori: " << data << std::endl; //std::cout << "content : " << content << std::endl; //end debug if (usesCrlf) chunk_->size -= 1; //copy tail to swapBuffer //if(data[chunkEnd] == '\n') chunkEnd++; //TODO: dealing with halo region //get rid of '\n' in halo region FIXME: Crlf not supported int haloCount = 0; uint64 tmpPtr = chunkEnd - 1; if(mHalo > 0){ while(true){ if(data[tmpPtr] != '\n') { haloCount++; //std::cerr << (char)data[tmpPtr] << std::endl; if(haloCount == mHalo) break; } tmpPtr--; } //std::cerr << "haloCount: " << haloCount << std::endl; }else{ tmpPtr = chunkEnd; //nocopy } //std::copy(data + chunkEnd - mHalo, data + cbufSize, swapBuffer.Pointer()); std::copy(data + tmpPtr, data + cbufSize, swapBuffer.Pointer()); //bufferSize = cbufSize - chunkEnd + mHalo; bufferSize = cbufSize - tmpPtr; } else // at the end of file { chunk_->size += r - 1; // skip the last EOF symbol if (usesCrlf) chunk_->size -= 1; //only for get seqsinfo uint64 chunkEnd = FindCutPos(dataChunk_, data, chunk_->size, mHalo, seqInfos); //debug only //std::string content((char*)data, chunk_->size); //std::cout << "tail content ori: " << data << std::endl; //std::cout << "tail content : " << content << std::endl; //end debug eof = true; } } else { eof = true; } return true; } uint64 FastaFileReader::FindCutPos(FastaChunk* dataChunk_, uchar* data_, const uint64 size_, const uint64 halo_, SeqInfos& seqInfos) { int count = 0; uint64 pos_ = 0; uint64 cut_ = 0; //cut_ point to next '>' uint64 lastSeq_ = 0; //-> the start of last sequences content uint64 lastName_ = 0; //-> the last '>' OneSeqInfo seqInfo; /* [haoz:] dataChunk_ -> start和dataChunk_ -> end 是表示当前这个chunk的开始部分的序列的index和 最终部分序列的index */ if(data_[0] == '>') //start with '>' { dataChunk_->start = this->totalSeqs; while(pos_ < size_){ if(data_[pos_] == '>'){ lastName_ = pos_; if(FindEol(data_, pos_, size_)) //find name { ++pos_; lastSeq_ = pos_; seqInfo.gid = this->totalSeqs; seqInfos.push_back(seqInfo); this->totalSeqs++; }else{ cut_ = pos_; //find a cut: incomplete name //std::cerr << "cut char: " << (char)data_[cut_] << std::endl; break; } }else{ ++pos_; } } }else{ //start with {ACGT} dataChunk_->start = this->totalSeqs - 1; while(pos_ < size_){ if(data_[pos_] == '>'){ lastName_ = pos_; if(FindEol(data_, pos_, size_)) //find name { ++pos_; lastSeq_ = pos_; seqInfo.gid = this->totalSeqs; seqInfos.push_back(seqInfo); this->totalSeqs++; }else{ cut_ = pos_; //find a cut -> '>' //std::cout << "cut char: " << (char)data_[cut_] << std::endl; break; } }else{ ++pos_; } } } //no tail cut //make sure that cbufSize > name_len + halo if(cut_ == 0){ uint64 lastSeqLen_ = size_ - lastSeq_; if(lastSeqLen_ < halo_){ cut_ = lastName_; this->totalSeqs--; } } dataChunk_->nseqs = this->totalSeqs - dataChunk_->start; dataChunk_->end = this->totalSeqs - 1; //if(cut_ != 0) std::cout << "cut: " << cut_ << std::endl; return cut_ ? cut_ : size_; } bool find_next_seq_start(uchar* data, uint64 size, uint64 &pos_){ if(pos_ == size - 1) return false; do{ pos_++; }while(pos_ < size && data[pos_] != '>'); return data[pos_] == '>' ? true : false; } //bool FastaFileReader::ReadNextFaChunk(FastaChunk* dataChunk_, SeqInfos& seqInfos, bool &continue_read){ bool FastaFileReader::ReadNextFaChunk(FastaDataChunk* chunk_, SeqInfos& seqInfos, bool &continue_read){ if (Eof()) { chunk_->size = 0; return false; } // flush the data from previous incomplete chunk uchar* data = chunk_->data.Pointer(); const uint64 cbufSize = chunk_->data.Size(); chunk_->size = 0; int64 toRead = cbufSize - bufferSize;// buffersize: size left from last chunk if (bufferSize > 0) { std::copy(swapBuffer.Pointer(), swapBuffer.Pointer() + bufferSize, data); chunk_->size = bufferSize; bufferSize = 0; } // read the next chunk int64 r = this->Read(data + chunk_->size, toRead); //std::cout << "r is :" << r << std::endl; //std::cout << "toRead: " << toRead << std::endl; if (r > 0) { if (r == toRead) // somewhere before end { if(data[0] == '>'){ uint64 chunkEnd = 0, pos_ = 0; pos_ = chunk_->size; while(find_next_seq_start(data, cbufSize, pos_)){ chunkEnd = pos_; } if(chunkEnd == 0){ //means this chunk is a big one, one chunk can not contain all continue_read = true; chunkEnd = cbufSize; }else{ continue_read = false; } chunk_->size = chunkEnd - 1; if (usesCrlf) chunk_->size -= 1; std::copy(data + chunkEnd, data + cbufSize, swapBuffer.Pointer()); bufferSize = cbufSize - chunkEnd; }else{ // means this is a continue chunk for last sequence uint64 chunkEnd = 0, pos_ = 0; pos_ = chunk_->size; if(find_next_seq_start(data, cbufSize, pos_)){ chunkEnd = pos_; } if(chunkEnd == 0){ //means this chunk is a big one, one chunk can not contain all continue_read = true; chunkEnd = cbufSize; }else{ continue_read = false; } chunk_->size = chunkEnd - 1; if (usesCrlf) chunk_->size -= 1; std::copy(data + chunkEnd, data + cbufSize, swapBuffer.Pointer()); bufferSize = cbufSize - chunkEnd; } }else{ // at the end of file chunk_ -> size += r - 1; //skip the last eof symbol if(usesCrlf) chunk_->size -= 1; eof = true; } } else { eof = true; } return true; } } // namespace fa namespace fq { int64 count_line(uchar* contenx, int64 read_bytes){ int64 count_n = 0; for(int i = 0; i < read_bytes; ++i){ //printf("%c",contenx[i]); if(contenx[i] == '\n') count_n++; } return count_n; } void FastqFileReader::readChunk() { FastqDataChunk* part = NULL; recordsPool.Acquire(part); printf("fastqio: ready to into while\n"); //while (!errorHandler.IsError() && fileReader.ReadNextChunk(part)) while(ReadNextChunk(part)) { ASSERT(part->size > 0); //recordsQueue.Push(numParts, part); //[haoz:] Push:把<numparts, part>组成pair然后放到recordsQueue里面然后notifiy_one printf("numParts is %d\n", numParts); numParts++; recordsPool.Release(part); recordsPool.Acquire(part); } ASSERT(part->size == 0); recordsPool.Release(part); // the last empty part //recordsQueue.SetCompleted(); } FastqDataChunk* FastqFileReader::readNextChunk(){ FastqDataChunk* part = NULL; recordsPool.Acquire(part); if(ReadNextChunk(part)) { return part; } else { recordsPool.Release(part); return NULL; } } FastqDataPairChunk* FastqFileReader::readNextPairChunk(){ FastqDataPairChunk* pair = new FastqDataPairChunk; FastqDataChunk *leftPart = NULL; recordsPool.Acquire(leftPart); //song: all in one datapool FastqDataChunk *rightPart = NULL; recordsPool.Acquire(rightPart); int64 left_line_count = 0; int64 right_line_count = 0; int64 chunkEnd = 0; int64 chunkEnd_right = 0; //---------read left chunk------------ if(eof){ leftPart->size = 0; rightPart->size = 0; //return false; recordsPool.Release(leftPart); recordsPool.Release(rightPart); return NULL; } //flush the data from previous incomplete chunk uchar* data = leftPart->data.Pointer(); const uint64 cbufSize = leftPart->data.Size(); leftPart -> size = 0; int64 toRead; toRead = cbufSize - bufferSize; if(bufferSize > 0){ std::copy(swapBuffer.Pointer(), swapBuffer.Pointer()+bufferSize, data); leftPart->size = bufferSize; bufferSize = 0; } int64 r; r = Read(data + leftPart->size, toRead); if(r > 0){ if(r == toRead){ chunkEnd = cbufSize - (1<<13);//SwapBufferSize; // SwapBuffersize defined in FastqStream.h as constant value : 1<<13; chunkEnd = GetNextRecordPos(data, chunkEnd, cbufSize); //leftPart->size = chunkEnd - 1; //if(usesCrlf) // leftPart->size -= 1; //std::copy(data + chunkEnd, data + cbufSize, swapBuffer_left.Pointer()); //bufferSize_left = cbufSize - chunkEnd; }else{ //chunkEnd = r; leftPart->size += r - 1; if(usesCrlf) leftPart->size -= 1; eof = true; } }else{ eof = true; //fastqPool_left -> Release(leftPart); //fastqPool_right->Release(rightPart); return NULL; } //------read left chunk end------// //-----------------read right chunk---------------------// uchar* data_right = rightPart->data.Pointer(); const uint64 cbufSize_right = rightPart->data.Size(); rightPart -> size = 0; toRead = cbufSize_right - bufferSize2; if(bufferSize2 > 0){ std::copy(swapBuffer2.Pointer(), swapBuffer2.Pointer()+bufferSize2 , data_right); rightPart->size = bufferSize2; bufferSize2 = 0; } r = Read2(data_right + rightPart->size, toRead); if(r > 0){ if(r == toRead){ chunkEnd_right = cbufSize_right - (1<<13); //SwapBufferSize; // SwapBuffersize defined in FastqStream.h as constant value : 1<<13; chunkEnd_right = GetNextRecordPos(data_right, chunkEnd_right, cbufSize_right); //leftPart->size = chunkEnd - 1; //if(usesCrlf) // leftPart->size -= 1; //std::copy(data + chunkEnd, data + cbufSize, swapBuffer_left.Pointer()); //bufferSize_left = cbufSize - chunkEnd; }else{ //chunkEnd_right += r; rightPart->size += r - 1; if(usesCrlf) rightPart->size -= 1; eof = true; } }else{ eof = true; return NULL; } //--------------read right chunk end---------------------// if(!eof){ //std::cout << "chunkEnd chunkEnd_right: " << chunkEnd <<" "<< chunkEnd_right << std::endl; left_line_count = count_line(data, chunkEnd); right_line_count = count_line(data_right, chunkEnd_right); //int64 difference = right_line_count - left_line_count; int64 difference = left_line_count - right_line_count; //if((r != toRead) && (difference != 0)){ // cerr << "read error! inconsistent end!!"; // exit(0); //} //std::cout<<"left right difference: " << left_line_count <<" "<< right_line_count <<" "<< difference << std::endl; if(difference>0){ //move rightPart difference lines before //std::cout << "difference > 0 "<<left_line_count <<" " <<right_line_count << " " << difference <<std::endl; std::cout << "start: " << chunkEnd_right << std::endl; //while(true){ while(chunkEnd_right < cbufSize){ if(data_right[chunkEnd_right] == '\n'){ difference--; if(difference == 0){ chunkEnd_right++; break; } } chunkEnd_right++; } std::cout << "end: " << chunkEnd_right << std::endl; }else if(difference < 0){ //move leftPart difference lines before //std::cout << "difference < 0 " <<left_line_count <<" " <<right_line_count << " " << difference << std::endl; //while(true){ while(chunkEnd < cbufSize){ if(data[chunkEnd] == '\n'){ difference++; if(difference == 0){ chunkEnd++; break; } } chunkEnd++; } } leftPart->size = chunkEnd - 1; if(usesCrlf) leftPart->size -= 1; std::copy(data + chunkEnd, data + cbufSize, swapBuffer.Pointer()); bufferSize = cbufSize - chunkEnd; rightPart->size = chunkEnd_right - 1; if(usesCrlf) rightPart->size -= 1; std::copy(data_right + chunkEnd_right, data_right + cbufSize_right, swapBuffer2.Pointer()); bufferSize2 = cbufSize_right - chunkEnd_right; } pair->left_part = leftPart; pair->right_part = rightPart; return pair; } //bool IFastqStreamReader::ReadNextChunk(FastqDataChunk* chunk_) bool FastqFileReader::ReadNextChunk(FastqDataChunk* chunk_) { if (Eof()) { chunk_->size = 0; return false; } // flush the data from previous incomplete chunk uchar* data = chunk_->data.Pointer(); const uint64 cbufSize = chunk_->data.Size(); chunk_->size = 0; int64 toRead = cbufSize - bufferSize; //--------------------------------- if (bufferSize > 0) { std::copy(swapBuffer.Pointer(), swapBuffer.Pointer() + bufferSize, data); chunk_->size = bufferSize; bufferSize = 0; } // read the next chunk int64 r = Read(data + chunk_->size, toRead); //std::cout << "r is :" << r << std::endl; if (r > 0) { if (r == toRead) // somewhere before end { uint64 chunkEnd = cbufSize - SwapBufferSize; // Swapbuffersize: 1 << 13 //std::cout << "chunkend cbufsize Swapbuffersize: " << chunkEnd <<" "<< cbufSize << " " << SwapBufferSize << std::endl; chunkEnd = GetNextRecordPos(data, chunkEnd, cbufSize); chunk_->size = chunkEnd - 1; if (usesCrlf) chunk_->size -= 1; std::copy(data + chunkEnd, data + cbufSize, swapBuffer.Pointer()); bufferSize = cbufSize - chunkEnd; } else // at the end of file { chunk_->size += r - 1; // skip the last EOF symbol if (usesCrlf) chunk_->size -= 1; eof = true; } } else { eof = true; } return true; } //bool FastqFileReader::ReadNextPairedChunk(FastqDataChunk* chunk_) //{ //std::cout<<"ReadNextPairedChunk: enter" <<std::endl; // if (Eof()) // { // chunk_->size = 0; // return false; // } // // // flush the data from previous incomplete chunk // uchar* data = chunk_->data.Pointer(); // const uint64 cbufSize = chunk_->data.Size(); // chunk_->size = 0; // int64 toRead = cbufSize - bufferSize; // //--------------------------------- // if (bufferSize > 0) // { // std::copy(swapBuffer.Pointer(), swapBuffer.Pointer() + bufferSize, data); // chunk_->size = bufferSize; // bufferSize = 0; // } // // // read the next chunk // int64 r = Read(data + chunk_->size, toRead); // //std::cout << "r is :" << r << std::endl; // // if (r > 0) // { // if (r == toRead) // somewhere before end // { // //uint64 chunkEnd = cbufSize - SwapBufferSize; // Swapbuffersize: 1 << 13 // //std::cout << "chunkend : " << cbufSize-1 <<std::endl; // lastOneReadPos = GetPreviousRecordPos(data, cbufSize-1,cbufSize); // //std::cout << "one:" << lastOneReadPos<<std::endl; // lastTwoReadPos = GetPreviousRecordPos(data, lastOneReadPos-1,cbufSize); // //std::cout << "two :" << lastTwoReadPos<<std::endl; // chunk_->size = lastOneReadPos - 1; // if (usesCrlf) // TODO windows先不管 // chunk_->size -= 1; // // std::copy(data + lastTwoReadPos, data + cbufSize, swapBuffer.Pointer()); // bufferSize = cbufSize - lastTwoReadPos; // } // else // at the end of file // { // chunk_->size += r - 1; // skip the last EOF symbol // if (usesCrlf) // chunk_->size -= 1; // // eof = true; // } // } // else // { // eof = true; // } // //std::cout<<"ReadNextPairedChunk: success@!!!!!!!" <<std::endl; // return true; //} // //需要向前找到倒数第2条read的开头,不仅仅是@号这么简单 uint64 FastqFileReader::GetPreviousRecordPos(uchar* data_, uint64 pos_,const uint64 size_) { int offset =2; SkipToSol(data_,pos_,size_); if(usesCrlf){ offset=3; } while(data_[pos_+offset] !='@'){ //+2 //std::cout<<"pos_"<<pos_<<std::endl; SkipToSol(data_,pos_,size_); } //标记一下,看是否是质量分 uint64 pos0=pos_+offset; SkipToSol(data_,pos_,size_); if(data_[pos_+offset]== '+'){ //说明上一个@号是质量分 SkipToSol(data_,pos_,size_); SkipToSol(data_,pos_,size_); //此时应该是name if(data_[pos_+offset]!='@'){ std::cout << "core dump is " << data_[pos_+offset] << std::endl; return pos_+offset; }else{ return pos_+offset; } } else{ return pos0; } } //uint64 IFastqStreamReader::GetNextRecordPos(uchar* data_, uint64 pos_, const uint64 size_) //chunkEnd = GetNextRecordPos(data, chunkEnd, cbufSize); uint64 FastqFileReader::GetNextRecordPos(uchar* data_, uint64 pos_, const uint64 size_) { SkipToEol(data_, pos_, size_); ++pos_; // find beginning of the next record while (data_[pos_] != '@') { SkipToEol(data_, pos_, size_); ++pos_; } uint64 pos0 = pos_; SkipToEol(data_, pos_, size_); ++pos_; if (data_[pos_] == '@') // previous one was a quality field return pos_; //-----[haoz:] is the following code necessary??-------------// SkipToEol(data_, pos_, size_); ++pos_; if(data_[pos_] != '+') std::cout << "core dump is pos: " << pos_ << " char: " << data_[pos_] << std::endl; ASSERT(data_[pos_] == '+'); // pos0 was the start of tag return pos0; } } // namespace fq } // namespace mash <file_sep>cmake_minimum_required(VERSION 3.0) project(RabbitIO-Ktrim) #openmp find_package(OpenMP REQUIRED) if(OPENMP_FOUND) message("OPENMP FOUND") set(CMAKE_CXX_COMPILER "/usr/bin/g++") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DVERB") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}") set(EXECUTABLE_OUTPUT_PATH .) endif() #link set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "-O3 -g -ffast-math ${CMAKE_CXX_FLAGS}") add_subdirectory(src/io) #message(${SOURCE_LIST}) #include_directories(./src) add_executable (${PROJECT_NAME} src/main.cpp) #add_executable (RabbitIO ${SOURCE_LIST}) target_link_libraries(${PROJECT_NAME} z) target_link_libraries(${PROJECT_NAME} io_lib) <file_sep>/* This file is a part of DSRC software distributed under GNU GPL 2 licence. The homepage of the DSRC project is http://sun.aei.polsl.pl/dsrc Authors: <NAME> and <NAME> Version: 2.00 */ #ifndef H_FASTXREADER #define H_FASTXREADER #include <vector> #include <string> #include "Globals.h" #include "Common.h" #include "DataQueue.h" #include "DataPool.h" #include "FastxStream.h" #include "FastxChunk.h" //#include "Sequence.h" //#include "../Sketch.h" #include "Reference.h" namespace mash { namespace fa { /* class FastaReader { public: FastaReader(FastaFileReader& reader_, FastaDataPool& pool_) : recordsPool(pool_) , fileReader(reader_) , numParts(0) {}; FastaChunk* readNextChunk(); int64 Read(byte* memory_, uint64 size_) { int64 n = fileReader.Read(memory_, size_); return n; } public: SeqInfos seqInfos; private: FastaDataPool& recordsPool; FastaFileReader& fileReader; uint32 numParts; }; */ //int chunkFormat(FastaDataChunk* &chunk, std::vector<Sequence*>&, bool); std::string getSequence(FastaDataChunk* &chunk, uint64 &pos); //addbyxxm std::string getLine(FastaDataChunk* &chunk, uint64 &pos); int chunkFormat(FastaChunk & fachunk, std::vector<Reference> & refs); int chunkFormat(FastaChunk & fachunk, std::vector<Reference> & refs, int kmerSize); Reference getNextSeq(FastaChunk & fachunk, bool & done, uint64 & pos); } // namespace fa namespace fq { //moved to FastxChunk.h //typedef core::TDataQueue<FastqDataChunk> FastqDataQueue; //typedef core::TDataPool<FastqDataChunk> FastqDataPool; /* class FastqReader //: public IFastqIoOperator { public: FastqReader(FastqFileReader& reader_, FastqDataPool& pool_) : recordsPool(pool_) , fileReader(reader_) , numParts(0) {}; void readChunk(); FastqDataChunk* readNextChunk(); //single pe file FastqDataChunk* readNextPairedChunk(); int64 Read(byte* memory_, uint64 size_) { int64 n = fileReader.Read(memory_, size_); return n; } private: FastqDataPool& recordsPool; FastqFileReader& fileReader; uint32 numParts; }; */ int chunkFormat(FastqChunk* &chunk, std::vector<Reference> &,bool); int chunkFormat(FastqChunk* &chunk, std::vector<neoReference> &,bool); //single pe file //int pairedChunkFormat(FastqDataChunk* &chunk, std::vector<ReadPair*>&,bool mHasQuality); //Read* getOnePairedRead(FastqDataChunk* &chunk,int &pos_, bool mHasQuality); //end single pe file std::string getLine(FastqDataChunk* &chunk, int &pos); int neoGetLine(FastqDataChunk* &chunk, uint64_t &pos, uint64_t &len); } // namespace fq } // namespace mash #endif <file_sep>#ifndef __REFERENCE_H_ #define __REFERENCE_H_ #include <string> #include <vector> #include "Globals.h" struct Reference{ std::string name; std::string comment; std::string seq; std::string quality; std::string strand; uint64_t length; uint64_t gid; }; struct neoReference{ uint64_t pname; //name offset uint64_t pcom; //comment ?? uint64_t pseq; //sequence uint64_t pqual; //quality uint64_t pstrand; uint64_t lname; uint64_t lcom; uint64_t lseq; uint64_t lqual; uint64_t lstrand; //uint64_t length; uint64_t gid; mash::byte* base; }; typedef std::vector<Reference> SeqInfos; typedef Reference OneSeqInfo; #endif
a910fcfafc796f731587ba5e3bccc8b95357e7e1
[ "CMake", "C++" ]
7
C++
LeiHaoa/RabbitIO-Ktrim
1c065145341731e4f5b4382b6c591d952d43af6b
9a4d5e9e34a03a3895c30564b0433c9e549ea60d
refs/heads/master
<repo_name>SaturnR/geogram<file_sep>/run.sh #!/usr/bin/env bash export FLASK_APP=main.py flask run <file_sep>/dbcontroller.py #!/usr/bin/env python3 import sqlite3 class Controller: def __init__(self, db_path='./words.db'): self.words = {} self.db_path = db_path def save(self, data, append=False): '''data: type dictionary, like : {'გამარჯობა' : 10}''' conn = sqlite3.connect(self.db_path) c = conn.cursor() if not append: c.execute('CREATE TABLE words (word text, occurrence real)') for n in data: print(n) c.execute("INSERT INTO words VALUES ('"+n+"',0)") #c.execute("INSERT INTO words VALUES ('"+n+"',"+str(data[n])+")") conn.commit() conn.close() def load(self, dbfilter=""): conn = sqlite3.connect(self.db_path) c = conn.cursor() c.execute("SELECT * FROM words" + dbfilter) dbwords = c.fetchall() words = {} for w in dbwords: words[w[0]] = w[1] return words def delete(self, word): pass if __name__ == "__main__": pass <file_sep>/main.py from flask import render_template, request from flask import Flask, json import sqlite3 from dbcontroller import Controller app = Flask(__name__) dbcon = Controller(db_path='extended.db') db = './extended.db' words = {} @app.route('/') def hello(): global words words = dbcon.load() return render_template('main.html') @app.route('/post', methods=["POST"]) def retValue(): html = "" try: recv = request.json['data'] for word in recv.split(): wd = word.strip().strip(".").strip(",")\ .strip(":").strip(";").strip("!")\ .strip("(").strip(")").strip("'")\ .strip('"') if wd in words: html+='<b><font color="black">'+ word +'</font></b>' else: html+='<b><font color="red">'+ word +'</font></b>' html+=' ' except Exception as es: print('error', es) data = {"text": html} response = app.response_class(response=json.dumps(data), status=200, mimetype='application/json') return response @app.route('/text_feed', methods = ['POST', 'GET']) def result(): global words if request.method == 'POST': result = request.form text = result['text_feed'] print(text) psswd = '<PASSWORD>' if psswd in text: ws = text.strip(psswd).split() dbcon.save(ws, append=True) words = dbcon.load() return render_template("main.html") <file_sep>/README.md # geogram Georgian grammar and orthography checker Repository intended for georgian language grammar checker website. links: - PyCHM is a Python library to manipulate CHM files https://github.com/dottedmag/pychm - ენობრივ შეცდომათა ლექსიკონი errata.ge - GeoWordsDatabase https://github.com/bumbeishvili/GeoWordsDatabase - ქართული ორთოგრაფიული ლექსიკონი - https://github.com/gamag/ka_GE.spell <file_sep>/requirements.txt attrs==19.3.0 backcall==0.1.0 Click==7.0 decorator==4.4.1 Flask==1.1.1 importlib-metadata==1.4.0 ipython==7.11.1 ipython-genutils==0.2.0 itsdangerous==1.1.0 jedi==0.15.2 Jinja2==2.10.3 MarkupSafe==1.1.1 more-itertools==8.1.0 packaging==20.0 parso==0.5.2 pexpect==4.7.0 pickleshare==0.7.5 pluggy==0.13.1 prompt-toolkit==3.0.2 ptyprocess==0.6.0 py==1.8.1 Pygments==2.5.2 pyparsing==2.4.6 pytest==5.3.2 six==1.13.0 traitlets==4.3.3 wcwidth==0.1.8 Werkzeug==0.16.0 zipp==0.6.0
f35c5dc9ac988fd99c19e1cc98a7fec3856bb664
[ "Markdown", "Python", "Text", "Shell" ]
5
Shell
SaturnR/geogram
7cfc3489370edacf2eaef14f89f8ecb509f8107c
67e4c0a58ecece92595e6a285ce4d72885c20675
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2019/3/2 16:02 # @Author: Vincent # @File : test.py import random from functools import reduce from numpy import * from DL.xjtupy.dl.network.network import Network class Normalizer(object): def __init__(self): self.mask = [0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80] def norm(self, number): return map(lambda m: 0.9 if number & m else 0.1, self.mask) def denorm(self, vec): binary = map(lambda i: 1 if i > 0.5 else 0, vec) binary = list(binary) for i in range(len(self.mask)): binary[i] = binary[i] * self.mask[i] return reduce(lambda x, y: x + y, binary) def mean_square_error(vec1, vec2): return 0.5 * reduce(lambda a, b: a + b, map(lambda v: (v[0] - v[1]) * (v[0] - v[1]), zip(vec1, vec2) ) ) def gradient_check(network, sample_feature, sample_label): ''' 梯度检查 network: 神经网络对象 sample_feature: 样本的特征 sample_label: 样本的标签 ''' # 计算网络误差 network_error = lambda vec1, vec2: 0.5 * reduce(lambda a, b: a + b, map(lambda v: (v[0] - v[1]) * (v[0] - v[1]), zip(vec1, vec2))) # 获取网络在当前样本下每个连接的梯度 network.get_gradient(sample_feature, sample_label) # 对每个权重做梯度检查 print("gradient check:") for conn in network.connections.connections: # 获取指定连接的梯度 actual_gradient = conn.get_gradient() # 增加一个很小的值,计算网络的误差 epsilon = 0.0001 conn.weight += epsilon error1 = network_error(network.predict(sample_feature), sample_label) # 减去一个很小的值,计算网络的误差 conn.weight -= 2 * epsilon # 刚才加过了一次,因此这里需要减去2倍 error2 = network_error(network.predict(sample_feature), sample_label) # 根据式6计算期望的梯度值 expected_gradient = (error2 - error1) / (2 * epsilon) # 打印 print('expected gradient: %f\t\tactual gradient: %f' % (expected_gradient, actual_gradient)) def train_data_set(): normalizer = Normalizer() data_set = [] labels = [] for i in range(0, 256, 8): n = normalizer.norm(int(random.uniform(0, 256))) data_set.append(n) labels.append(n) return labels, data_set def train(network): labels, data_set = train_data_set() network.train(labels, data_set, 0.3, 50) def test(network, data): normalizer = Normalizer() norm_data = normalizer.norm(data) predict_data = network.predict(norm_data) print('\ttestdata(%u)\tpredict(%u)' % (data, normalizer.denorm(predict_data))) def correct_ratio(network): normalizer = Normalizer() correct = 0.0; for i in range(256): if normalizer.denorm(network.predict(normalizer.norm(i))) == i: correct += 1.0 print('correct_ratio: %.2f%%' % (correct / 256 * 100)) def gradient_check_test(): net = Network([2, 2, 2]) sample_feature = [0.9, 0.1] sample_label = [0.9, 0.1] gradient_check(net, sample_feature, sample_label) if __name__ == '__main__': net = Network([8, 3, 8]) train(net) net.dump() correct_ratio(net) gradient_check_test() <file_sep># DL 深度学习实践之路 <file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2019/3/3 15:02 # @Author: Vincent # @File : dropout.py # coding:utf-8 import numpy as np def dropout(x, level): """ dropout函数的实现 :param x: 当前输入值 :param level: 隐藏神经元的概率 :return: """ if level < 0. or level >= 1: # level是概率值,必须在0~1之间 raise ValueError('Dropout level must be in interval [0, 1[.') retain_prob = 1. - level # 我们通过binomial函数,生成与x一样的维数向量。binomial函数就像抛硬币一样,我们可以把每个神经元当做抛硬币一样 # 硬币正面的概率为p,n表示每个神经元试验的次数 # 因为我们每个神经元只需要抛一次就可以了所以n=1,size参数是我们有多少个硬币。 # 即将生成一个0、1分布的向量,0表示这个神经元被屏蔽,不工作了,也就是dropout了 random_tensor = np.random.binomial(n=1, p=retain_prob, size=x.shape) print(random_tensor) x *= random_tensor print(x) x /= retain_prob return x # 对dropout的测试,了解一个输入x向量,经过dropout的结果 x = np.asarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float32) print(dropout(x, 0.4)) <file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2019/3/2 16:58 # @Author: Vincent # @File : sigmoid.py import numpy as np class SigmoidActivator(object): """ Sigmoid激活函数类 """ def forward(self, weighted_input): return 1.0 / (1.0 + np.exp(-weighted_input)) def backward(self, output): return output * (1 - output) <file_sep>#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2019/3/2 15:58 # @Author: Vincent # @File : connections.py class Connections(object): """ Connections对象,提供Connection集合操作。 """ def __init__(self): self.connections = [] def add_connection(self, connection): self.connections.append(connection) def dump(self): for conn in self.connections: print(conn)
486580a3d48cc09664057888649c20ca25ff9f11
[ "Markdown", "Python" ]
5
Python
xjtupy/DL
6a877c62d3ac82f27cd65fd85850d74c988e544d
c62dabb17683cf08f4878df56b37c8dad5ab0b76
refs/heads/master
<repo_name>pierorolando1/balongonline<file_sep>/config.firebase.js import firebase from 'firebase/app'; import 'firebase/firestore'; const firebaseConfig = { apiKey: "<KEY>", authDomain: "balongonline.firebaseapp.com", projectId: "balongonline", storageBucket: "balongonline.appspot.com", messagingSenderId: "566884581538", appId: "1:566884581538:web:6dcb66cc4595f8f047d7fb", measurementId: "G-F4D89T37P3" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.analytics(); export default firebase.firestore();
a893480071b22036786e1b11ae3d59e9b4546940
[ "JavaScript" ]
1
JavaScript
pierorolando1/balongonline
f1144d1d55ed457fb846a3699a84c90c53e0bca3
c36c02bf69e32923dd28474a4b8f4625c0898839
refs/heads/master
<file_sep># BLEDemo a demonstration of notifications coming from iBeacon <file_sep>// // ViewController.swift // BLEDemo // // Created by <NAME> on 8/22/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit import CoreLocation import UserNotifications class ViewController: UIViewController, CLLocationManagerDelegate { var locationManager: CLLocationManager! override func viewDidLoad() { super.viewDidLoad() let center = UNUserNotificationCenter.current() center.requestAuthorization(options:[.alert, .sound]) { (granted, error) in } locationManager = CLLocationManager() locationManager.delegate = self locationManager.requestAlwaysAuthorization() locationManager.requestWhenInUseAuthorization() } // checking here to see if the user gave us permission or not then we scan func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedAlways || status == .authorizedWhenInUse { if CLLocationManager.isMonitoringAvailable(for: CLBeaconRegion.self) { if CLLocationManager.isRangingAvailable() { startScanning() } } } } // setting up the beacon entering the region func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { guard region is CLBeaconRegion else { return } // this is the notification let content = UNMutableNotificationContent() content.title = "David Porter" content.body = "Can you please help?" content.sound = .default() let request = UNNotificationRequest(identifier: "BLEDemo", content: content, trigger: nil) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } // here we are scanning for the beacons uuid func startScanning() { let uuid = UUID(uuidString: "9118606C-C0C4-4AF3-9E7E-B839FDA1AB19")! let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: 143, minor: 456, identifier: "Samaritan") locationManager.startMonitoring(for: beaconRegion) locationManager.startRangingBeacons(in: beaconRegion) } }
04b0bc129902e0a984a16372f768f3f116ab010f
[ "Markdown", "Swift" ]
2
Markdown
thegrimheep/BLEDemo
63e74bd035ae2a35c8ed2571b6c17a9b8c463abd
688afe2d6c8bf122afff1274d42b6fc1f51d6975
refs/heads/master
<repo_name>averlor/blog-note2.0<file_sep>/app/app.py from flask import Flask from config.conf import Configuration app = Flask(__name__) app.config.from_object(Configuration)<file_sep>/app/templates/index.html {% extends 'base.html' %} {% block title %} Главная {% endblock %} {% block content %} <section class="content"> <p>Hello, world</p> </section> {% endblock %}<file_sep>/app/config/conf.py class Configuration: DEBUG = True SECRET_KEY = 'Toby Maguaer the true spider-man'
d9105c96326c2b7bf2c5c51b0a739478fdef1e3e
[ "Python", "HTML" ]
3
Python
averlor/blog-note2.0
af34b4a764f4565c769eecbc6971b3eb9f59b0f9
97b84bdbbdb136b45487d8ff81e40b6185b42d4e
refs/heads/master
<repo_name>iamcucusa/e2e<file_sep>/iDareUI/PageInteractions/LoginPage.cs using System; using iDareUI.Common; using OpenQA.Selenium; using OpenQA.Selenium.Remote; namespace iDareUI.PageInteractions { public class LoginPage { private readonly RemoteWebDriver driver; private readonly ILog log; public LoginPage(RemoteWebDriver driver, ILog log) { this.driver = driver; this.log = log; } public void NavigateTo() { driver.Manage().Window.Maximize(); var targetUrl = Constants.PageUri; this.log.Info($"Navigating to {targetUrl}"); driver.Navigate().GoToUrl(targetUrl); FlowUtilities.WaitUntil( () => { try { IWebElement rocheLogo = driver.FindElement(By.CssSelector("svg.prv-roche-icon")); return true; } catch (NoSuchElementException ex) { log.Error("The URL specified could not be found" + ex); return false; } }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100), "The URL specified could not be found"); } private IWebElement userName => driver.FindElements(By.XPath("//input[@id='undefinedInput']"))[0]; private IWebElement password => driver.FindElements(By.XPath("//input[@id='undefinedInput']"))[1]; private IWebElement loginButton => driver.FindElement(By.XPath("//button[@type='submit']")); private IWebElement errorMessage => driver.FindElement(By.XPath("//span[contains(.,' Authentication failed: Wrong credentials.')]")); public string UserName { set { userName.SendKeys(value); } } public string Password { set { password.SendKeys(value); } } public CaseMainPage LoginApplication() { loginButton.Click(); return new CaseMainPage(driver); } public string ErrorMessageText => errorMessage.Text; } } <file_sep>/iDareUI/Common/InteractionUtilities.cs using System; using OpenQA.Selenium; namespace iDareUI.Common { public static class InteractionUtilities { public static void SendKeysCharByChar(IWebElement element, string keys) { for (int i = 0; i < keys.Length; i++) { element.SendKeys(Char.ToString(keys[i])); } } public static bool IsVisible(string id, IWebDriver webDriver) { bool displayed; try { displayed = webDriver.FindElement(By.XPath("//*[@attr.data-idare-id='" + id + "']")).Displayed; } catch (NoSuchElementException) { // As the element is not present in DOM, it returns true. displayed = false; } catch (StaleElementReferenceException) { // The stale element reference implies that element is no longer visible, hence returns true. displayed = false; } return displayed; } } } <file_sep>/iDareUI/Common/TestingEnvironment.cs using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Remote; using System; using System.IO; using System.Reflection; using Xunit.Abstractions; namespace iDareUI.Common { public class TestingEnvironment:IDisposable { public bool IsIDE { get { return System.Diagnostics.Debugger.IsAttached; } } private RemoteWebDriver driver = null; public RemoteWebDriver Driver { get { ChromeOptions chromeOptions = new ChromeOptions(); if (this.driver == null) { if (!IsIDE) { chromeOptions.AddArgument("headless"); } this.driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),chromeOptions); this.driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); } return driver; } } public TestingEnvironment(ITestOutputHelper helper) { this.Log = new Log(helper); } public ILog Log; public void Dispose() { if (this.driver != null) { this.driver.Dispose(); this.driver = null; } } } } <file_sep>/iDareUI/PageInteractions/CaseInvestigationPage.cs using OpenQA.Selenium; using OpenQA.Selenium.Remote; using System.Collections.Generic; namespace iDareUI.PageInteractions { public class CaseInvestigationPage { private RemoteWebDriver driver; public CaseInvestigationPage(RemoteWebDriver driver) { this.driver = driver; } private IWebElement instrumentInformationCard => driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfo']")); private IWebElement instrumentInformationHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoHeader']")); private IWebElement countersCard => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailHardwareCounters']")); private IWebElement countersHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailHardwareCountersHeader']")); private IWebElement instrumentStatesCard => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailInvestigateTimelineBox']")); private IWebElement instrumentStatesHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailInvestigateTimelineTitle']")); private IWebElement recordedRunsCard => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailInvestigateRunBox']")); private IWebElement recordedRunsHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailInvestigateRunsTitle']")); private IWebElement flagsCard => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailInvestigateFlagsBox']")); private IWebElement flagsHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailInvestigateFlagsTitle']")); private IWebElement flagsTabsContainer => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailFlagsTabs']")); private IList<IWebElement> flagsTabs => flagsTabsContainer.FindElements(By.CssSelector("div.mat-tab-label")); private IWebElement flagsProcessingModuleA => flagsTabs[0]; private IWebElement flagsProcessingModuleB => flagsTabs[1]; private IWebElement InvestigateTab => driver.FindElement(By.XPath("/html/body/prv-root/prv-case-details/div/section/mat-tab-group/mat-tab-header/div[2]/div/div/div[2]")); public void PressInvestigateTab() { InvestigateTab.Click(); } public void PressMatExpansionPanelInstrumentInformation() { instrumentInformationHeader.Click(); } public void PressMatExpansionPanelCounters() { countersHeader.Click(); } public void PressFlagProcessingModuleATab() { flagsProcessingModuleA.Click(); } public void PressFlagProcessingModuleBTab() { flagsProcessingModuleB.Click(); } } } <file_sep>/iDareUI/PageInteractions/TeachingMainPage.cs using iDareUI.Common; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using System; using System.Collections.Generic; using System.Text; namespace iDareUI.PageInteractions { class TeachingMainPage { private IWebElement teachingUserInfo => driver.FindElement(By.XPath("//*[@attr.data-idare-id='TeachingUserInfo']")); private IWebElement teachingHeadlineComponentGreeting => driver.FindElement(By.XPath("//*[@attr.data-idare-id='TeachingHeadlineComponentGreeting']")); private IWebElement teachingHeadlineComponentName => driver.FindElement(By.XPath("//*[@attr.data-idare-id='TeachingHeadlineComponentName']")); private IWebElement teachingHeadlineComponentRole => driver.FindElement(By.XPath("//*[@attr.data-idare-id='TeachingHeadlineComponentRole']")); public IssuesRulesPage issuesRulesPage; private RemoteWebDriver driver; public TeachingMainPage(RemoteWebDriver driver) { this.driver = driver; issuesRulesPage = new IssuesRulesPage(driver); } public void NavigateToTeachingModule() { driver.Manage().Window.Maximize(); var targetUrl = Constants.PageTeachingUri; driver.Navigate().GoToUrl(targetUrl); FlowUtilities.WaitUntil( () => { try { IWebElement teachingRocheIconHeader = driver.FindElement(By.XPath("//*[@attr.data-idare-id='TeachingRocheIcon']")); return true; } catch (NoSuchElementException ex) { return false; } }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100), "The URL specified could not be found"); } public bool userIsLoggedInAs(string role, string username) { return teachingUserInfo != null && teachingHeadlineComponentName != null && teachingHeadlineComponentName != null && teachingHeadlineComponentRole != null && teachingHeadlineComponentRole.Text == role && teachingHeadlineComponentName.Text == username; } } } <file_sep>/iDareUI/LoginSteps.cs using iDareUI.Common; using iDareUI.Models; using iDareUI.PageInteractions; using TechTalk.SpecFlow; using Xunit; namespace iDareUI { [Binding] public class LoginSteps { private TestingEnvironment environment; private CaseMainPage mainCasesPage; private LoginPage loginPage; public LoginSteps(TestingEnvironment environment) { this.environment = environment; this.loginPage = new LoginPage(environment.Driver, environment.Log); this.mainCasesPage = new CaseMainPage(environment.Driver); } [Given(@"I am in the Overview screen")] public void GivenIAmInTheOverviewScreen() { this.environment.Driver.Manage().Window.Maximize(); this.loginPage.NavigateTo(); } [Then(@"I should see the Cases screen for (.*)")] public void ThenIShouldSeeTheCasesScreenfor(string userName) { string userWebName = mainCasesPage.UserRole; Assert.Equal(userName, userWebName); } } } <file_sep>/iDareUI/Common/FlowUtilities.cs using System; using System.Diagnostics; using System.Threading; namespace iDareUI.Common { public static class FlowUtilities { public static WaitResponse WaitUntil(Func<bool> waitUntilResult, TimeSpan timeout, TimeSpan period, string errorMessage = "", bool throwException=true, bool ignoreErrors = true) { Stopwatch watch = Stopwatch.StartNew(); while (watch.Elapsed < timeout) { try { if (waitUntilResult()) { return new WaitResponse {Success = true}; } } catch (Exception e) { if (ignoreErrors == true) { Console.WriteLine("Error Ignored:\r\n" + e); continue; } return new WaitResponse { Exception = e, Reason = e.Message, TimedOut = false }; } Thread.Sleep(period); } if (!waitUntilResult() && throwException) { return new WaitResponse{Exception = new TimeoutException(errorMessage), TimedOut = true, Reason = "TimedOut"} ; } return new WaitResponse{Success = true}; } public static WaitResponse WaitUntilWithoutException(Func<bool> waitUntilResult, TimeSpan timeout, TimeSpan period) { return WaitUntil(waitUntilResult, timeout, period, "", false); } } } <file_sep>/iDareUI/CasesOverviewSteps.cs using iDareUI.Common; using iDareUI.Models; using OpenQA.Selenium; using System; using System.Collections.Generic; using System.Linq; using iDareUI.PageInteractions; using TechTalk.SpecFlow; using Xunit; namespace iDareUI { [Binding] public class CasesOverviewSteps { private TestingEnvironment environment; private CaseMainPage mainCasesPage; private CaseDetailsPage casesDetailsPage; private CaseCreationSteps caseCreationSteps; private ScenarioContext scenarioContext; private FeatureContext featureContext; private Case caseCreatedForSearch; public enum CaseSearchProperty { CaseId, SerialNumber, Customer, Country } public CasesOverviewSteps(TestingEnvironment environment, ScenarioContext scenarioContext, FeatureContext featureContext) { this.environment = environment; this.mainCasesPage = new CaseMainPage(environment.Driver); this.casesDetailsPage = new CaseDetailsPage(environment.Driver); this.caseCreationSteps = new CaseCreationSteps(environment, featureContext); this.scenarioContext = scenarioContext; this.featureContext = featureContext; } [When(@"I go to the Cases overview screen")] public void WhenIGoToTheCasesOverviewScreen() { mainCasesPage.PressCasesButton(); } [When(@"I enter to the details of a case")] public void WhenIEnterToTheDetailsOfACase() { FlowUtilities.WaitUntil( () => (mainCasesPage.firstIdRowText.Contains("CAS-0123")), TimeSpan.FromSeconds(20), TimeSpan.FromMilliseconds(100), "The created case is not located in the first position of the Cases Overview grid"); FlowUtilities.WaitUntil( () => { try { mainCasesPage.PressDetailsButton(); casesDetailsPage.PressCloseCaseDetailsButton(); return mainCasesPage.firstCaseSWVersionText.Contains("01."); } catch { return false; } }, TimeSpan.FromSeconds(20), TimeSpan.FromMilliseconds(1000)); mainCasesPage.PressDetailsButton(); Assert.True(casesDetailsPage.closeCaseDetailsButton.Enabled, "The case details page was not opened."); } [Then(@"the cases grid with the correct columns is displayed")] public void ThenTheCasesGridWithTheCorrectColumnsIsDisplayed() { string[] casesGridColumns = new string[] { "Case ID", "System", "Serial No.", "SW Version", "Created (UTC)", "Customer", "Country", "Created by", "Issues" }; var obtainColumns = mainCasesPage.GetGridHeaderNames(); Assert.True(casesGridColumns.SequenceEqual(obtainColumns), $"The grid headers are not the expected ones. \nExpected: {string.Join(", ", casesGridColumns)}, \nActual: {string.Join(", ", obtainColumns)}"); } [Then(@"cases are sorted by creation time")] public void ThenCasesAreSortedByCreationTime() { IEnumerable<DateTime> obtainedCreationDateTime = null; IEnumerable<DateTime> orderedCreationDateTime = null; FlowUtilities.WaitUntil( () => { try { obtainedCreationDateTime = mainCasesPage.GetCreationDateTime(); orderedCreationDateTime = mainCasesPage.GetSortedDates(); return orderedCreationDateTime.SequenceEqual(obtainedCreationDateTime); } catch (StaleElementReferenceException ex) { environment.Log.Error("Error getting data: " + ex.Message); return false; } }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100)); } [Given(@"I create two duplicate cases and a different case")] public void GivenICreateTwoDuplicateCasesAndADifferentCase() { caseCreatedForSearch = Case.GetRandomCase(); this.CreateCase(caseCreatedForSearch); this.CreateCase(caseCreatedForSearch); var myCase2 = Case.GetRandomCase(); this.CreateCase(myCase2); mainCasesPage.WaitUntilCasesAreUpdated(myCase2.CaseID, myCase2.CaseID); } private void CreateCase(Case c) { caseCreationSteps.GivenIEnterToCreateANewCase(); caseCreationSteps.WhenIEnterAsRexisID(c.CaseID); caseCreationSteps.WhenIEnterAsSerialNumber(c.SerialNo); caseCreationSteps.WhenIEnterAsCountry(c.Country); caseCreationSteps.WhenIEnterAsCustomer(c.Customer); caseCreationSteps.WhenIEnterTheOptionOfTheDropdownAsTimezone(2); caseCreationSteps.WhenIPressTheSaveButton(); } [When(@"I search by (.*) of the duplicate cases")] public void WhenISearchByOfTheDuplicateCases(CaseSearchProperty property) { switch (property) { case CaseSearchProperty.CaseId: mainCasesPage.SearchFilterCases(caseCreatedForSearch.CaseID); break; case CaseSearchProperty.Country: mainCasesPage.SearchFilterCases(caseCreatedForSearch.Country); break; case CaseSearchProperty.Customer: mainCasesPage.SearchFilterCases(caseCreatedForSearch.Customer); break; case CaseSearchProperty.SerialNumber: mainCasesPage.SearchFilterCases(caseCreatedForSearch.SerialNo); break; default: throw new InvalidOperationException("The search property is wrong."); } mainCasesPage.PressEnterToFilter(); } [Then(@"the only two cases with the same (.*) I created are displayed")] public void ThenTheOnlyTwoCasesWithTheSameICreatedAreDisplayed(CaseSearchProperty property) { FlowUtilities.WaitUntil( () => (mainCasesPage.SelectCases(caseCreatedForSearch, property)), TimeSpan.FromSeconds(2000), TimeSpan.FromMilliseconds(25)); Assert.True(mainCasesPage.SelectCases(caseCreatedForSearch, property), "The searching filter is not working"); } } } <file_sep>/iDareUI/Common/Log.cs using System; using TechTalk.SpecFlow; using Xunit.Abstractions; namespace iDareUI.Common { internal class Log : ILog { private readonly ITestOutputHelper helper; public Log(ITestOutputHelper helper) { this.helper = helper; } public void Info(string s) { this.LogLine("INFO", s); } public void Debug(string s) { this.LogLine("DEBUG", s); } public void Trace(string s) { this.LogLine("TRACE", s); } public void Error(string s) { this.LogLine("ERROR", s); } public void Fatal(string s) { this.LogLine("FATAL", s); } private void LogLine(string level, string s) { var line = $"{DateTime.Now.ToString("yyyyMMdd - HH:mm:ss.fff")} {level} - {s}"; this.helper.WriteLine(line); } } } <file_sep>/iDareUI/Common/DataLocation.cs using System; using System.Collections.Generic; using System.IO; namespace iDareUI.Common { public static class DataLocation { public static string GetProblemReportsDirectory(List<string> fileNamesList) { string fileNameConcat = GetProblemReportFilePath(fileNamesList[0]); fileNamesList.RemoveAt(0); foreach (string name in fileNamesList) { string nextFileName = GetProblemReportFilePath(name); fileNameConcat = fileNameConcat + "\r\n" + nextFileName; } return fileNameConcat; } public static string GetProblemReportFilePath(string fileName) { string filePath = Path.GetDirectoryName(typeof(DataLocation).Assembly.Location) + "\\TestData\\ProblemReport\\" + fileName; if (!File.Exists(filePath)) { throw new FileNotFoundException("Could not find the path: " + filePath); } return filePath; } } } <file_sep>/iDareUI/Common/WindowsApi.cs using System; using System.Runtime.InteropServices; namespace iDareUI.Common { public static class WindowsApi { [DllImport("user32.dll", EntryPoint = "FindWindow")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetForegroundWindow(IntPtr hWnd); } } <file_sep>/iDareUI/PageInteractions/CaseUpdatePage.cs using OpenQA.Selenium; using OpenQA.Selenium.Remote; using System.Collections.Generic; using System.Linq; using Xunit; namespace iDareUI.PageInteractions { class CaseUpdatePage { private readonly RemoteWebDriver driver; public CaseUpdatePage(RemoteWebDriver driver) { this.driver = driver; } private IWebElement editCaseButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseListComponentEditCaseButton']")); private IList<IWebElement> fileUploadedRow => driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseFileListTableHeaderRows']")); public void OpenCaseUpdate() { editCaseButton.Click(); } public IEnumerable<string> GetFileUploadedNameListText() { var filesUploadedText = this.GetFileUploadedNameList(); return filesUploadedText.Select(element => element.Text); } public IList<IWebElement> GetFileUploadedNameList() { IList<IWebElement> allFilesUploaded = driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseFileListTableHeaderRows']")); return allFilesUploaded; } public string GetFileUploadedStatus (string fileName) { string status = null; foreach (IWebElement row in fileUploadedRow) { if (row.Text.Contains(fileName)) { IWebElement currentStatusFileUploaded = row.FindElement(By.XPath("//*[@attr.data-idare-id='CaseFileListTableStatus']")); status = currentStatusFileUploaded.Text; } } Assert.NotNull(status); return status; } public void PressFileUploadedDeleteButton(string fileName) { IWebElement deleteButton = null; foreach (IWebElement row in fileUploadedRow) { if (row.Text.Contains(fileName)) { deleteButton = row.FindElement(By.XPath("//*[@attr.data-idare-id='CaseFileListTableDeleteButton']")); } } Assert.NotNull(deleteButton); deleteButton.Click(); } } } <file_sep>/iDareUI/PageInteractions/CasesMainPage.cs using iDareUI.Common; using iDareUI.Models; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Xunit; using static iDareUI.CasesOverviewSteps; namespace iDareUI.PageInteractions { public class CaseMainPage { private RemoteWebDriver driver; public CaseMainPage(RemoteWebDriver driver) { this.driver = driver; } private IWebElement userLabel => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IDareUserInfoUserName']")); private IWebElement newCaseButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseListComponentAddCaseButton']")); private IWebElement rangeLabel => driver.FindElement(By.ClassName("mat-paginator-range-label")); private IWebElement firstIdRow => driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseListComponentCaseRow']"))[0]; private IWebElement casesButton => driver.FindElements(By.CssSelector("span.prv-sidebar__title"))[0]; private IWebElement caseEditFirstButton => driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseListComponentEditCaseIcon']"))[0]; private IWebElement detailsButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='DetectedIssuesContainerViewButton']")); private IWebElement firstCaseSWVersion => driver.FindElement(By.XPath("/html/body/prv-root/prv-layout/prv-template/div/section[2]/mat-drawer-container/mat-drawer-content/prv-list-cases/div/div[2]/section/div[1]/mat-table/mat-row[1]/mat-cell[4]")); public IWebElement nextPageClickableButton => driver.FindElement(By.CssSelector("button.mat-paginator-navigation-next.mat-icon-button")); private IWebElement searchFilter => driver.FindElement(By.XPath("/html/body/prv-root/prv-layout/prv-template/div/section[2]/mat-drawer-container/mat-drawer-content/prv-case-detected-issue/div/div[1]/div/mat-form-field/div/div[1]/div/input")); private IEnumerable<IWebElement> caseRows => driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseListComponentCaseRow']")); public string[] caseCreationValues = new string[] { "CAS-0123", "1234", "Spain", "Customer" }; private IWebElement searchButton => driver.FindElements(By.CssSelector("button.mat-icon-button"))[1]; public IEnumerable<string> GetGridHeaderNames() { var headers = this.GetGridHeaderElements(); return headers.Select(element => element.Text); } public IList<IWebElement> GetGridHeaderElements() { IList<IWebElement> allHeaders = driver.FindElements(By.CssSelector("button.mat-sort-header-button")); return allHeaders; } public IList<IWebElement> GetRowsElements() { IList<IWebElement> rows = driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseListComponentCaseRow']")); return rows; } public IEnumerable<Case> GetRowsElementsCases() { var ret = new List<Case>(); var rows = this.GetRowsElements(); foreach (var row in rows) { IWebElement rowCaseID = row.FindElement(By.CssSelector("td.mat-cell.cdk-cell.cdk-column-caseReference.mat-column-caseReference.ng-star-inserted")); IWebElement rowSerialNo = row.FindElement(By.CssSelector("td.mat-cell.cdk-cell.cdk-column-serialNumber.mat-column-serialNumber.ng-star-inserted")); IWebElement rowCustomer = row.FindElement(By.CssSelector("td.mat-cell.cdk-cell.cdk-column-customer.mat-column-customer.ng-star-inserted")); IWebElement rowCountry = row.FindElement(By.CssSelector("td.mat-cell.cdk-cell.cdk-column-country.mat-column-country.ng-star-inserted")); IWebElement rowSWV = row.FindElement(By.CssSelector("td.mat-cell.cdk-cell.cdk-column-softwareVersion.mat-column-softwareVersion.ng-star-inserted")); var myCase = new Case(); myCase.CaseID = rowCaseID.Text; myCase.SerialNo = rowSerialNo.Text; myCase.Customer = rowCustomer.Text; myCase.Country = rowCountry.Text; myCase.SWVersion = rowSWV.Text; ret.Add(myCase); } return ret; } public IList<IWebElement> GetRowsIds() { IList<IWebElement> caseIds = driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseListComponentCaseIDValue']")); return caseIds; } public IEnumerable<DateTime> GetCreationDateTime() { var dateTimes = this.GetCreationTimeText(); return dateTimes.Select(element => DateTime.ParseExact(element, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)); } public IEnumerable<DateTime> GetSortedDates() { return this.GetCreationDateTime().OrderByDescending(element => element.Ticks); } public IEnumerable<string> GetCreationTimeText() { var dateTimesText = this.GetCreationTimeElements(); return dateTimesText.Select(element => element.Text); } public IList<IWebElement> GetCreationTimeElements() { IList<IWebElement> allCreationTimeElements = driver.FindElements(By.CssSelector("mat-cell.cdk-column-creation-time.mat-column-creation-time.ng-star-inserted")).ToList(); return allCreationTimeElements; } public string UserRole => userLabel.Text; public string RangeLabelText => rangeLabel.Text; public string firstIdRowText => firstIdRow.Text; public string firstCaseSWVersionText => firstCaseSWVersion.Text; public void PressNextPageButton() { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement nextPageClickableButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector("button.mat-paginator-navigation-next.mat-icon-button"))); nextPageClickableButton.Click(); } public void PressPreviousPageButton() { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement previousPageClickableButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector("button.mat-paginator-navigation-previous.mat-icon-button.mat-button-base"))); previousPageClickableButton.Click(); } public void PressFirstCaseEditButton() { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); this.caseEditFirstButton.Click(); } public void NewCase() { newCaseButton.Click(); } public void PressCasesButton() { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); IWebElement nextPageClickableButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.CssSelector("span.prv-sidebar__title"))); casesButton.Click(); } public void PressDetailsButton() { detailsButton.Click(); } public void SearchFilterCases(string value) { searchFilter.Click(); searchFilter.SendKeys(value); } public void PressEnterToFilter() { searchFilter.SendKeys(Keys.Enter); } internal void WaitUntilRangeLabelChanges() { FlowUtilities.WaitUntil(() => RangeLabelText.StartsWith("1 -"), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(100)); } public void WaitUntilCasesAreUpdated(string caseId, string fieldUpdated) { FlowUtilities.WaitUntil( () => { try { var caseRows = GetRowsElements(); var ret = caseRows.Where(row => row.Text.Contains(caseId)); return ret.Any(row => row.Text.Contains(fieldUpdated)); } catch { return false; } }, TimeSpan.FromSeconds(2000), TimeSpan.FromMilliseconds(25)); } public bool SelectCases(Case caseCreatedForSearch, CaseSearchProperty property) { Thread.Sleep(TimeSpan.FromSeconds(5)); var ret = GetRowsElementsCases(); string caseProperty = null; bool value = false; switch (property) { case CaseSearchProperty.CaseId: caseProperty = caseCreatedForSearch.CaseID; value = ret.All(myCase => myCase.CaseID.Contains(caseProperty)); break; case CaseSearchProperty.Country: caseProperty = caseCreatedForSearch.Country; value = ret.All(myCase => myCase.Country.Contains(caseProperty)); break; case CaseSearchProperty.Customer: caseProperty = caseCreatedForSearch.Customer; value = ret.All(myCase => myCase.Customer.Contains(caseProperty)); break; case CaseSearchProperty.SerialNumber: caseProperty = caseCreatedForSearch.SerialNo; value = ret.All(myCase => myCase.SerialNo.Contains(caseProperty)); break; default: throw new InvalidOperationException("The search property is wrong."); } return value; } public int ReadPageLabel() { int numberOfCases = -1; var response = FlowUtilities.WaitUntilWithoutException( () => { IWebElement componentPaginator = driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseListComponentPaginator']")); IWebElement inside1 = componentPaginator.FindElement(By.CssSelector("div.mat-paginator-range-label")); string rangeLabel = inside1.Text; int start = rangeLabel.LastIndexOf(" "); if (start < 0) { return false; } string labelCut = rangeLabel.Substring(start); numberOfCases = Int32.Parse(labelCut); return numberOfCases > 0; }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(25)); Assert.True(response.Success, response.ToString()); return numberOfCases; } public void AssertThatNoProgressBarIsShown() { //dont want a progress bar - if one appears we fail - so a timeout is good var response = FlowUtilities.WaitUntil(() => driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseUploadFileProgressBar']")).Count >= 1, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100)); Assert.True(response.TimedOut); } public void WaitUntilProgressBarIsShown(int numberOfUploads) { for (int i = 0; i < numberOfUploads; i++) { FlowUtilities.WaitUntil( () => driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseUploadFileProgressBar']")).Count == numberOfUploads, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(100)); } } public void AssertThatAllProgressBarsAreRemoved() { bool elementHasDisappeared = false; var response = FlowUtilities.WaitUntil(() => { elementHasDisappeared = !InteractionUtilities.IsVisible("CaseUploadFileProgressBar", this.driver); return elementHasDisappeared; }, TimeSpan.FromSeconds(300), TimeSpan.FromMilliseconds(500)); Assert.True(response.Success, "The progress bars were not removed at the end of the upload"); } public void WaitUntilProgressBarShowsUpdatedStatusSuccess(int maxWaitSeconds) { FlowUtilities.WaitUntil(() => { return driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseUploadFileSuccess']")) != null; }, TimeSpan.FromSeconds(maxWaitSeconds), TimeSpan.FromMilliseconds(100)); } public void WaitUntilProgressBarShowsUpdatedStatusError(int maxWaitSeconds) { FlowUtilities.WaitUntil(() => { return driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseUploadFileError']")) != null; }, TimeSpan.FromSeconds(maxWaitSeconds), TimeSpan.FromMilliseconds(100)); } } } <file_sep>/iDareUI/Models/Case.cs using System; namespace iDareUI.Models { public class Case { public string CaseID {get;set;} public string System {get;set;} public string SerialNo {get;set;} public string SWVersion {get;set;} public string Created {get;set;} public string Customer {get;set;} public string Country { get; set;} public string CreatedBy { get; set;} public string Issues { get; set;} public static Case GetRandomCase() { return new Case() { CaseID = Guid.NewGuid().ToString(), SerialNo = Guid.NewGuid().ToString(), Customer = Guid.NewGuid().ToString(), Country = Guid.NewGuid().ToString(), }; } } } <file_sep>/iDareUI/PageInteractions/IssuesRulesPage.cs using System; using System.Collections.Generic; using iDareUI.Models; using OpenQA.Selenium; using OpenQA.Selenium.Remote; namespace iDareUI.PageInteractions { public class IssuesRulesPage { private RemoteWebDriver driver; public IssuesRulesPage(RemoteWebDriver driver) { this.driver = driver; } private IWebElement newIssueButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueRuleContainerActionsButton']")); private IWebElement newIssueButtonIcon => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueRuleContainerActionsIcon']")); private IWebElement issueListContainer => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueRuleContainerList']")); private IWebElement supportedIssuesList => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesList']")); private IWebElement supportedIssuesListFilter => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListFilter']")); private IWebElement supportedIssuesListFilterInput => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListFilterValue']")); private IWebElement supportedIssuesListTable => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListTable']")); private IWebElement supportedIssuesListPaginator => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListPaginator']")); private IWebElement supportedIssuesListHeaderRow => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListHeaderRow']")); private IWebElement supportedIssuesListRuleInWorkHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListRuleInWorkHeader']")); private IWebElement supportedIssuesListTitleHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListTitleHeader']")); private IWebElement supportedIssuesListCategoryHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListCategoryHeader']")); private IWebElement supportedIssuesListSystemHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListSystemHeader']")); private IWebElement supportedIssuesListFootprintsHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListFootprintsHeader']")); private IWebElement supportedIssuesListModifiedByHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListModifiedByHeader']")); private IWebElement supportedIssuesListModifiedHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListModifiedHeader']")); private IWebElement supportedIssuesListEditHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListEditHeader']")); private IList<IWebElement> supportedIssuesListCellRows => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListCellRows']")); private IList<IWebElement> supportedIssuesListRuleInWorkCells => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListRuleInWorkCell']")); private IList<IWebElement> supportedIssuesListTitleCells => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListTitleCell']")); private IList<IWebElement> supportedIssuesListCategoryCells => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListCategoryCell']")); private IList<IWebElement> supportedIssuesListSystemCells => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListSystemCell']")); private IList<IWebElement> supportedIssuesListFootprintsCells => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListFootprintsCell']")); private IList<IWebElement> supportedIssuesListModifiedByCells => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListModifiedByCell']")); private IList<IWebElement> supportedIssuesListModifiedCells => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListModifiedCell']")); private IList<IWebElement> supportedIssuesListEditCells => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListEditCell']")); private IList<IWebElement> supportedIssuesListEditCellButtons => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListEditCellButton']")); private IList<IWebElement> supportedIssuesListEditCellIcons => driver.FindElements(By.XPath("//*[@attr.data-idare-id='SupportedIssuesListEditCellIcon']")); public bool NewIssue() { var NewIssueButtonLoaded = true; NewIssueButtonLoaded = this.newIssueButton != null && NewIssueButtonLoaded; NewIssueButtonLoaded = this.newIssueButtonIcon != null && NewIssueButtonLoaded; newIssueButton.Click(); return NewIssueButtonLoaded; } public bool IssueListIsLoaded() { var IssueListElementsLoaded = true; IssueListElementsLoaded = this.issueListContainer != null && IssueListElementsLoaded; IssueListElementsLoaded = this.supportedIssuesList != null && IssueListElementsLoaded; IssueListElementsLoaded = this.supportedIssuesListFilter != null && IssueListElementsLoaded; IssueListElementsLoaded = this.supportedIssuesListFilterInput != null && IssueListElementsLoaded; IssueListElementsLoaded = this.supportedIssuesListTable != null && IssueListElementsLoaded; IssueListElementsLoaded = this.supportedIssuesListPaginator != null && IssueListElementsLoaded; return IssueListElementsLoaded; } public bool IssueListTableHeaderIsCorrect() { return supportedIssuesListHeaderRow != null && supportedIssuesListRuleInWorkHeader != null && supportedIssuesListTitleHeader != null && supportedIssuesListCategoryHeader != null && supportedIssuesListSystemHeader != null && supportedIssuesListFootprintsHeader != null && supportedIssuesListModifiedByHeader != null && supportedIssuesListModifiedHeader != null && supportedIssuesListEditHeader != null && supportedIssuesListCellRows.Count > 0; } public bool IssueListTableIsPopulatedWithAtLeastOneRow() { return supportedIssuesListRuleInWorkCells.Count > 0 && supportedIssuesListTitleCells.Count > 0 && supportedIssuesListCategoryCells.Count > 0 && supportedIssuesListSystemCells.Count > 0 && supportedIssuesListFootprintsCells.Count > 0 && supportedIssuesListModifiedByCells.Count > 0 && supportedIssuesListEditCells.Count > 0 && supportedIssuesListModifiedCells.Count > 0; } public bool IssueIsAddedOnTopOfTheList(IssueRow issueRow) { return supportedIssuesListTitleCells[0].Text == issueRow.Title && supportedIssuesListCategoryCells[0].Text == issueRow.Category && supportedIssuesListSystemCells[0].Text == issueRow.System && supportedIssuesListFootprintsCells[0].Text == issueRow.Footprints && supportedIssuesListModifiedByCells[0].Text == issueRow.ModifiedBy; } public bool IssueEditButtonIsCorrect(int index) { return supportedIssuesListEditCells[index] != null && supportedIssuesListEditCellButtons[index] != null && supportedIssuesListEditCellButtons[index].TagName == "button" && supportedIssuesListEditCellIcons[index] != null; } public int numberOfIssuesInTheList() { return supportedIssuesListCellRows.Count; } } } <file_sep>/iDareUI/CaseCreationSteps.cs using iDareUI.Common; using System; using System.Collections.Generic; using System.Threading; using iDareUI.Models; using iDareUI.PageInteractions; using TechTalk.SpecFlow; using Xunit; namespace iDareUI { [Binding] public class CaseCreationSteps { private TestingEnvironment environment; private CaseMainPage mainCasesPage; private CaseCreationPage caseCreationPage; private FeatureContext featureContext; private string rexisId; public CaseCreationSteps(TestingEnvironment environment, FeatureContext featureContext) { this.environment = environment; this.mainCasesPage = new CaseMainPage(environment.Driver); this.caseCreationPage = new CaseCreationPage(environment.Driver); this.featureContext = featureContext; } [Given(@"I navigate to the next case page")] public void GivenINavigateToTheNextCasePage() { mainCasesPage.PressNextPageButton(); } [Given(@"I enter to create a new case")] public void GivenIEnterToCreateANewCase() { mainCasesPage.NewCase(); Assert.True(caseCreationPage.CaseCreationDialog.Displayed, "The dialog to create a new case was not displayed"); } [When(@"I enter a Rexis ID with a unique ID")] public void WhenIEnterARexisIDWithAUniqueID() { rexisId = caseCreationPage.SetUniqueRexisId(); } [When(@"I enter (.*) as Rexis ID")] public void WhenIEnterAsRexisID(string value) { caseCreationPage.SetRexisId(value); } [When(@"I enter (.*) as Serial number")] public void WhenIEnterAsSerialNumber(string value) { caseCreationPage.SetSerialNo(value); } [When(@"I enter (.*) as Customer")] public void WhenIEnterAsCustomer(string value) { caseCreationPage.SetCustomer(value); } [When(@"I enter (.*) as Country")] public void WhenIEnterAsCountry(string value) { caseCreationPage.SetCountry(value); } [When(@"I enter the option (.*) of the dropdown as Timezone")] public void WhenIEnterTheOptionOfTheDropdownAsTimezone(int optionNumber) { caseCreationPage.SelectOptionInTimezoneDropdown(optionNumber); } [When(@"I leave the ID field empty")] public void WhenILeaveTheIDFieldEmpty() { caseCreationPage.SetRexisId(""); } [Then(@"The files list shows the files I have added (.*)")] public void ThenTheFilesListShowsTheFilesIHaveAdded(List<string> fileNameList) { foreach (var fileName in fileNameList) { caseCreationPage.AssertFileUploadListFileIsDisplayed(fileName); } } [When(@"I upload a Problem Report with name (.*)")] public void WhenIUploadAProblemReportWithName(List<string> fileNameList) { List<string> uploadingFilesList = fileNameList; string filePath = DataLocation.GetProblemReportsDirectory(fileNameList); caseCreationPage.SimulateFileUploading(filePath); foreach (string fileName in uploadingFilesList) { caseCreationPage.AssertFileUploadListFileIsDisplayed(fileName); } } [Then(@"The case creation dialog is closed")] public void ThenTheCaseCreationDialogIsClosed() { var response = FlowUtilities.WaitUntil(() => !InteractionUtilities.IsVisible("CaseDialog", this.environment.Driver), TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(1)); Assert.True(response.Success, "The case creation page should not be displayed."); } [When(@"I press the Save button")] public void WhenIPressTheSaveButton() { caseCreationPage.PressSaveButton(); } [When(@"I enter the RexisId in the filter")] public void ThenIEnterTheRexisIdInTheFilter() { mainCasesPage.SearchFilterCases(this.rexisId); mainCasesPage.PressEnterToFilter(); //Not nice - but need to wait for the results to be updated. Thread.Sleep(1000); } [Then(@"The case is displayed in the list with the RexisId")] public void ThenTheCaseIsDisplayedInTheListWithTheRexisId() { mainCasesPage.SelectCases(new Case { CaseID = rexisId}, CasesOverviewSteps.CaseSearchProperty.CaseId); } [Then(@"I click the edit case button for the first case")] public void ThenIClickTheEditCaseButtonForTheFirstCase() { mainCasesPage.PressFirstCaseEditButton(); } [When(@"I press the Cancel button")] public void WhenIPressTheCancelButton() { caseCreationPage.PressCancelButton(); } [Then(@"the Save button is disabled")] public void ThenTheSaveButtonIsDisabled() { Assert.False(caseCreationPage.SaveButton.Enabled, "The Save button is enabled"); } [Then(@"the first page of the cases overview is shown")] public void ThenTheFirstPageOfTheCasesOverviewIsShown() { mainCasesPage.PressPreviousPageButton(); mainCasesPage.WaitUntilRangeLabelChanges(); Assert.StartsWith("1 -", mainCasesPage.RangeLabelText); } [Then(@"the case with the unique ID as Rexis ID is on the top of the list")] public void ThenTheCaseWithTheUniqueIdAsRexisIDIsOnTheTopOfTheList() { var response = FlowUtilities.WaitUntil(() => mainCasesPage.firstIdRowText.Contains(rexisId), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(100)); Assert.True(response.Success, "The case is not displayed."); } [When(@"I create a new Case for details")] public void WhenICreateANewCaseForDetails() { Case caseDetails = Case.GetRandomCase(); this.featureContext["caseDetails"] = caseDetails; this.GivenIEnterToCreateANewCase(); this.WhenIEnterAsRexisID(caseDetails.CaseID); this.WhenIEnterTheOptionOfTheDropdownAsTimezone(2); List<string> fileName = new List<string>(); fileName.Add(Constants.ProblemReportOnlySummary); this.WhenIUploadAProblemReportWithName(fileName); this.WhenIPressTheSaveButton(); } [Given(@"there are at least (.*) cases created")] public void ThereAreAtLeastCasesCreated(int cases) { FlowUtilities.WaitUntil(() => { if (!(mainCasesPage.ReadPageLabel() > cases)) { this.GivenICreateANewCaseWithoutProblemReport(); } return mainCasesPage.ReadPageLabel() > cases; }, TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(100)); } [Given(@"I create a new case without problem report")] public void GivenICreateANewCaseWithoutProblemReport() { this.GivenIEnterToCreateANewCase(); this.WhenIEnterARexisIDWithAUniqueID(); this.WhenIEnterAsSerialNumber("12345"); this.WhenIEnterAsCountry("Spain"); this.WhenIEnterAsCustomer("Customer"); this.WhenIEnterTheOptionOfTheDropdownAsTimezone(2); this.WhenIPressTheSaveButton(); } [Then(@"I should see the progress of the (.*) uploads")] public void ThenIShouldSeeTheProgressOfTheUpload(int numberOfUploads) { mainCasesPage.WaitUntilProgressBarIsShown(numberOfUploads); } [Then(@"The progress of the uploads should disappear")] public void ThenTheProgressOfTheUploadsShouldDisappear() { mainCasesPage.AssertThatAllProgressBarsAreRemoved(); } [Then(@"I should not see any upload progress bars")] public void ThenIShouldNotSeeAnyProgressBars() { mainCasesPage.AssertThatNoProgressBarIsShown(); } [Then(@"the status gets updated as successful")] public void ThenTheStatusGetsUpdatedAsSuccessful() { FlowUtilities.WaitUntil(() => rexisId.Contains(mainCasesPage.firstIdRowText), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(100)); } [Then(@"the status gets updated as error")] public void ThenTheStatusGetsUpdatedAsError() { mainCasesPage.WaitUntilProgressBarShowsUpdatedStatusError(300); } [Then(@"I remove a file (.*)")] public void ThenIRemoveAFile(string fileName) { caseCreationPage.PressFirstFileSelectComponentDeleteButton(); caseCreationPage.AssertFileUploadListFileIsRemoved(fileName); } [Then(@"The Progress Shows Updated Status Success")] public void ThenTheProgressShowsUpdatedStatusSuccess() { mainCasesPage.WaitUntilProgressBarShowsUpdatedStatusSuccess(10); } } } <file_sep>/iDareUI/Common/Constants.cs using System; namespace iDareUI.Common { public class Constants { private const string pageUri = @"https://idare-qa-webapp.azurewebsites.net/cases"; public static string PageUri { get { var environmentUrl = Environment.GetEnvironmentVariable("testUrl", EnvironmentVariableTarget.Process); if(environmentUrl != null && environmentUrl.Length != 0) { return environmentUrl; } return pageUri; } } private const string pageTeachingUri = @"https://idare-qa-teaching-webapp.azurewebsites.net"; public static string PageTeachingUri { get { return pageTeachingUri; } } public const string TeacherUserName = "teacher"; public const string TeacherPassword = "<PASSWORD>"; public const string InvestigatorName = "investigator"; public const string InvestigatorPassword = "<PASSWORD>"; public const string ProblemReportOnlySummary = "ProblemReport_OnlySummary.zip"; } } <file_sep>/iDareUI/IssueCreationSteps.cs using iDareUI.Common; using iDareUI.Models; using System; using System.Collections.Generic; using iDareUI.PageInteractions; using TechTalk.SpecFlow; using TechTalk.SpecFlow.Assist; using Xunit; namespace iDareUI { [Binding] public class IssueCreationSteps { private TestingEnvironment environment; private TeachingMainPage mainTeachingPage; private IssueCreationPage issueCreationPage; public IssueCreationSteps(TestingEnvironment environment) { this.environment = environment; this.mainTeachingPage = new TeachingMainPage(environment.Driver); this.issueCreationPage = new IssueCreationPage(environment.Driver); } [Given(@"I navigate successfully to the teaching module")] public void GivenINavigateSuccessfullyToTheTeachingModule() { environment.Driver.Manage().Window.Maximize(); mainTeachingPage.NavigateToTeachingModule(); } [Given(@"I am in the issue list in teaching module")] public void GivenIAmInTheIssueListInTeachingModule() { Assert.True(mainTeachingPage.issuesRulesPage.IssueListIsLoaded()); Assert.True(mainTeachingPage.issuesRulesPage.IssueListTableHeaderIsCorrect()); Assert.True(mainTeachingPage.issuesRulesPage.IssueListTableIsPopulatedWithAtLeastOneRow()); } [Given(@"I am logged in as teacher user")] public void IAmLoggedInAsTeacherUser() { Assert.True(mainTeachingPage.userIsLoggedInAs("Teacher", "DebugUser")); } [Given(@"I click add issue button")] public void GivenIClickAddIssueButton() { Assert.True(this.mainTeachingPage.issuesRulesPage.NewIssue()); } [Given(@"Issue Dialog is open")] public void GivenIssueDialogIsOpen() { Assert.True(this.issueCreationPage.NewIssueDialogIsOpen()); } [Given(@"I enter the following fields")] public void GivenIEnterTheFollowingFields(Table table) { var issueFormFields = table.CreateInstance<IssueForm>(); issueCreationPage.issueFormPage.populateIssueForm(issueFormFields); Assert.True(issueCreationPage.issueFormPage.validateIssueFormFields(issueFormFields)); } [When(@"I enter '(.*)' as Category")] public void WhenIEnterAsCategory(string category) { issueCreationPage.issueFormPage.SetCategory(category); Assert.True(issueCreationPage.issueFormPage.validateIssueCategoryField(category)); } [When(@"I enter '(.*)' as System")] public void WhenIEnterAsSystem(string system) { issueCreationPage.issueFormPage.SetSystem(system); Assert.True(issueCreationPage.issueFormPage.validateIssueSystemField(system)); } [When(@"I enter '(.*)' as Title")] public void WhenIEnterAsTitle(string title) { issueCreationPage.issueFormPage.SetTitle(title); Assert.True(issueCreationPage.issueFormPage.validateIssueTitleField(title)); } [When(@"I click save button is enabled")] public void WhenIClickSaveButtonIsEnabled() { Assert.True(issueCreationPage.SaveIssueButtonIsEnabled()); issueCreationPage.SaveNewIssue(); } [Then(@"the save button must be disabled")] public void ThenTheSaveButtonMustBeDisabled() { Assert.True(issueCreationPage.SaveIssueButtonIsDisabled()); } [Then(@"the save button must be enabled")] public void ThenTheSaveButtonMustBeEnabled() { Assert.True(issueCreationPage.SaveIssueButtonIsEnabled()); } [Then(@"the issue list is updated successfully and includes the new created issue")] public void ThenTheIssueListIsUpdatedSuccessfullyAndIncludesTheNewCreatedIssue(Table table) { var issueRowFields = table.CreateInstance<IssueRow>(); Assert.True(mainTeachingPage.issuesRulesPage.IssueListIsLoaded()); Assert.True(mainTeachingPage.issuesRulesPage.IssueListTableHeaderIsCorrect()); Assert.True(mainTeachingPage.issuesRulesPage.IssueListTableIsPopulatedWithAtLeastOneRow()); Assert.True(mainTeachingPage.issuesRulesPage.IssueIsAddedOnTopOfTheList(issueRowFields)); } [Then(@"the first issue edit button must be the last cell with the defined icon")] public void ThenTheFirstIssueEditButtonMustBeTheLastCellWithTheDefinedIcon() { Assert.True(mainTeachingPage.issuesRulesPage.IssueEditButtonIsCorrect(0)); } [Then(@"I cancel the issue creation and no new issue is created in the list")] public void ICancelTheIssueCreationAndNoNewIssueIsCreatedInTheList() { var issueListTotal = mainTeachingPage.issuesRulesPage.numberOfIssuesInTheList(); issueCreationPage.CancelNewIssue(); Assert.Equal(issueListTotal, mainTeachingPage.issuesRulesPage.numberOfIssuesInTheList()); } } } <file_sep>/iDareUI/TestData/CustomConversions.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using TechTalk.SpecFlow; namespace iDareUI.TestData { [Binding] class CustomConversions { [StepArgumentTransformation] [Scope(Tag = "FileUploadingCases")] public List<string> GetFileNameList(string fileNameDelimited) { List<string> fileNameList = new List<string>(); if (!fileNameDelimited.Contains(',')) { fileNameList.Add(fileNameDelimited); return fileNameList; } else { var fileNames = fileNameDelimited.Split(",", StringSplitOptions.RemoveEmptyEntries); for (var index = 0; index < fileNames.Length; index++) { fileNames[index] = fileNames[index].Trim(); } return fileNames.ToList(); } } } } <file_sep>/iDareUI/Models/IssueForm.cs using System; namespace iDareUI.Models { public class IssueForm { public IssueForm() { } public string Title { get; set; } public string Description { get; set; } public string ObservedInInstrument { get; set; } public string System { get; set; } public string Category { get; set; } public string ExcludedSoftwareVersions { get; set; } } } <file_sep>/iDareUI/Common/DisposeDriverService.cs using System; using System.Diagnostics; namespace iDareUI.Common { public static class DisposeDriverService { public static void KillChromeDriver(DateTime testRunStartTime) { Process[] chromeDriverProcesses = Process.GetProcessesByName("chromedriver"); foreach (var chromeDriverProcess in chromeDriverProcesses) { if (chromeDriverProcess.StartTime < testRunStartTime) { chromeDriverProcess.Kill(); } } } } } <file_sep>/iDareUI/Common/Ilog.cs namespace iDareUI.Common { public interface ILog { void Info(string s); void Debug(string s); void Trace(string s); void Error(string s); void Fatal(string s); } } <file_sep>/iDareUI/PageInteractions/IssueCreationPage.cs using System; using System.Collections.Generic; using iDareUI.Common; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Support.UI; namespace iDareUI.PageInteractions { public class IssueCreationPage { private IWebElement supportedIssuesNewContainer => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesNew']")); private IWebElement supportedIssuesNewHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesNewHeader']")); private IWebElement supportedIssuesNewHeaderTitle => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesNewHeaderTitle']")); private IWebElement supportedIssuesNewHeaderButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesNewHeaderButton']")); private IWebElement supportedIssuesNewHeaderIcon => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesNewHeaderIcon']")); private IWebElement supportedIssuesNewCancelButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesNewCancelButton']")); private IWebElement supportedIssuesNewSaveButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesNewSaveButton']")); private IWebElement supportedIssuesNewNote => driver.FindElement(By.XPath("//*[@attr.data-idare-id='SupportedIssuesNewNote']")); public IssueFormPage issueFormPage; private RemoteWebDriver driver; public IssueCreationPage(RemoteWebDriver driver) { this.driver = driver; this.issueFormPage = new IssueFormPage(driver); } public bool NewIssueDialogIsOpen() { var NewIssueDialogIsOpen = true; NewIssueDialogIsOpen = this.supportedIssuesNewContainer != null && NewIssueDialogIsOpen; NewIssueDialogIsOpen = this.supportedIssuesNewHeader != null && NewIssueDialogIsOpen; NewIssueDialogIsOpen = this.supportedIssuesNewHeaderTitle != null && NewIssueDialogIsOpen; NewIssueDialogIsOpen = this.supportedIssuesNewHeaderButton != null && NewIssueDialogIsOpen; NewIssueDialogIsOpen = this.supportedIssuesNewHeaderIcon != null && NewIssueDialogIsOpen; NewIssueDialogIsOpen = this.supportedIssuesNewCancelButton != null && NewIssueDialogIsOpen; NewIssueDialogIsOpen = this.supportedIssuesNewSaveButton != null && NewIssueDialogIsOpen; NewIssueDialogIsOpen = this.supportedIssuesNewNote != null && NewIssueDialogIsOpen; return NewIssueDialogIsOpen && this.issueFormPage.AreIssueFormElementsLoaded(); } public bool SaveIssueButtonIsEnabled() { SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(supportedIssuesNewSaveButton); return supportedIssuesNewSaveButton.GetAttribute("disabled") == null; } public bool SaveIssueButtonIsDisabled() { return supportedIssuesNewSaveButton.GetAttribute("disabled") == "true"; } public void SaveNewIssue() { supportedIssuesNewSaveButton.Click(); } public void CancelNewIssue() { supportedIssuesNewCancelButton.Click(); } } } <file_sep>/iDareUI/PageInteractions/CaseCreationPage.cs using System; using System.Collections.Generic; using System.Linq; using iDareUI.Common; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using Xunit; namespace iDareUI.PageInteractions { public class CaseCreationPage { private readonly RemoteWebDriver driver; public CaseCreationPage(RemoteWebDriver driver) { this.driver = driver; } private IWebElement RexisId => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseComponentCaseIDInput']")); private IWebElement SerialNo => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseComponentSerialNoInput']")); private IWebElement Customer => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseComponentCustomerInput']")); private IWebElement Country => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseComponentCountryInput']")); private IWebElement CancelButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseComponentCancelButton']")); private IWebElement CloseButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseComponentCloseButton']")); private IWebElement CaseFilesUploadList => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseFilesToUploadList']")); private IWebElement FileUploadInput => driver.FindElement(By.XPath("//*[@attr.data-idare-id='FileUploadInput']")); public IWebElement SaveButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseComponentSaveButton']")); public IWebElement UploadFileButton => driver.FindElement(By.XPath("//*[@attr.data-idare-id='FileUploadSubmitButton']")); public IWebElement CaseFilesToUploadList => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseFilesToUploadList']")); public IWebElement TimezoneElement => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseComponentTimezoneLabel']")); public IWebElement CaseCreationDialog => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDialog']")); public IList<IWebElement> FileSelectComponentDeleteButtons => driver.FindElements(By.XPath("//*[@attr.data-idare-id='FileSelectComponentDeleteIcon']")).ToList(); public IList<IWebElement> GetTimezoneOptions() { IList<IWebElement> timezoneOptions = driver.FindElements(By.XPath("//*[@attr.data-idare-id='CaseComponentTimezoneOption']")); return timezoneOptions; } public void SetRexisId(string value) { InteractionUtilities.SendKeysCharByChar(RexisId, value); } public void SetSerialNo(string value) { SerialNo.SendKeys(value); } public void SetCustomer(string value) { Customer.SendKeys(value); } public void SetCountry(string value) { Country.SendKeys(value); } public string SetUniqueRexisId() { Guid guid = Guid.NewGuid(); string unicId = guid.ToString(); InteractionUtilities.SendKeysCharByChar(RexisId, unicId); return unicId; } public void PressCancelButton() { CancelButton.Click(); } public void PressSaveButton() { SaveButton.Click(); } public void PressUploadFileButton() { UploadFileButton.Click(); } public void SimulateFileUploading(string filePath) { IWebElement inputFile = this.FileUploadInput; inputFile.SendKeys(filePath); } public void AssertFileUploadListFileIsDisplayed(string fileName) { var response = FlowUtilities.WaitUntil(() => { IWebElement caseFileUploaded = this.CaseFilesToUploadList; return caseFileUploaded.Text.Contains(fileName); }, TimeSpan.FromSeconds(60), TimeSpan.FromMilliseconds(100)); Assert.True(response.Success, response.ToString()); } public void AssertFileUploadListFileIsRemoved(string fileName) { var response = FlowUtilities.WaitUntil(() => { IWebElement caseFileUploaded = this.CaseFilesToUploadList; return !caseFileUploaded.Text.Contains(fileName); }, TimeSpan.FromSeconds(60), TimeSpan.FromMilliseconds(100)); Assert.True(response.Success, response.ToString()); } public void SelectOptionInTimezoneDropdown(int optionIndex) { TimezoneElement.Click(); TimezoneElement.SendKeys("U"); var response = FlowUtilities.WaitUntil(() => { var optionsLoaded = GetTimezoneOptions().Count >= optionIndex - 1; if (!optionsLoaded) { TimezoneElement.Click(); } return optionsLoaded; }, TimeSpan.FromSeconds(4), TimeSpan.FromMilliseconds(100)); Assert.True(response.Success, response.ToString()); IWebElement timezoneOption = GetTimezoneOptions().ToArray()[optionIndex - 1]; timezoneOption.Click(); } public void PressFirstFileSelectComponentDeleteButton() { FileSelectComponentDeleteButtons[0].Click(); } } } <file_sep>/iDareUI/Common/WaitResponse.cs using System; using System.Text; namespace iDareUI.Common { public class WaitResponse { public bool Success; public string Reason { get; set; } public bool TimedOut { get; set; } public Exception Exception { get; set; } public override string ToString() { StringBuilder sb = new StringBuilder(); if (this.TimedOut) sb.Append("TimedOut=True"); if (!string.IsNullOrEmpty(this.Reason)) sb.Append($"Reason={this.Reason}"); if (this.Exception != null) sb.Append($"Exception={this.Exception}"); return sb.ToString(); } } }<file_sep>/iDareUI/KillChromeDriver.cs using iDareUI.Common; using System; using TechTalk.SpecFlow; namespace iDareUI { [Binding] public sealed class KillChromeDriver { [BeforeTestRun] public static void BeforeTestRun() { DisposeDriverService.KillChromeDriver(DateTime.Now); } } } <file_sep>/iDareUI/Models/IssueRow.cs using System; namespace iDareUI.Models { public class IssueRow { public bool RuleInWork { get; set; } public string Title { get; set; } public string Category { get; set; } public string System { get; set; } public string Footprints { get; set; } public string ModifiedBy { get; set; } public string Modified { get; set; } public IssueRow() { } } } <file_sep>/iDareUI/PageInteractions/IssueFormPage.cs using System; using System.Collections.Generic; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using iDareUI.Models; using OpenQA.Selenium.Support.UI; namespace iDareUI.PageInteractions { public class IssueFormPage { private RemoteWebDriver driver; public IssueFormPage(RemoteWebDriver driver) { this.driver = driver; } private IWebElement supportedIssueForm => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueForm']")); private IWebElement supportedIssueFormFieldTitle => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldTitle']")); private IWebElement supportedIssueFormFieldTitleLabel => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldTitleLable']")); private IWebElement supportedIssueFormFieldTitleValue => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldValue']")); private IWebElement supportedIssueFormFieldDescription => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldDescription']")); private IWebElement supportedIssueFormFieldDescriptionLabel => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldDescriptionLabel']")); private IWebElement supportedIssueFormFieldDescriptionValue => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldDescriptionValue']")); private IWebElement supportedIssueFormFieldInstrument => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldInstrument']")); private IWebElement supportedIssueFormFieldInstrumentLabel => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldInstrumentLabel']")); private IWebElement supportedIssueFormFieldInstrumentValue => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldInstrumentValue']")); private IWebElement supportedIssueFormFieldSystem => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldSystem']")); private IWebElement supportedIssueFormFieldSystemLabel => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldSystemLabel']")); private IWebElement supportedIssueFormSystemsSelect => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldSystemSelect']")); private IList<IWebElement> supportedIssueFormSystems => driver.FindElements(By.XPath("//*[@attr.data-idare-id='IssueFormFieldSystemSelectOption']")); private IWebElement supportedIssueFormFieldCategory => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldCategory']")); private IWebElement supportedIssueFormFieldCategoryLabel => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldCategoryLabel']")); private IWebElement supportedIssueFormFieldCategoryValue => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldCategoryValue']")); private IWebElement supportedIssueFormFieldSWVersions => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldSWVersions']")); private IWebElement supportedIssueFormFieldSWVersionsLabel => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldSWVersionsLabel']")); private IWebElement supportedIssueFormFieldSWVersionsValue => driver.FindElement(By.XPath("//*[@attr.data-idare-id='IssueFormFieldSWVersionsValue']")); public void SetTitle(string value) { supportedIssueFormFieldTitleValue.SendKeys(value); } public void SetDescription(string value) { supportedIssueFormFieldDescriptionValue.SendKeys(value); } public void SetInstrument(string value) { supportedIssueFormFieldInstrumentValue.SendKeys(value); } public void SetSystem(string value) { if (value != "") { supportedIssueFormSystemsSelect.Click(); var SystemOption = driver.FindElement(By.XPath("//mat-option/span[contains(.,'" + " " + value + " " + "')]")); WebDriverWait Wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); Wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(SystemOption)); SystemOption.Click(); } } public void SetCategory(string value) { supportedIssueFormFieldCategoryValue.SendKeys(value); } public void SetSWVersions(string value) { supportedIssueFormFieldSWVersionsValue.SendKeys(value); } public IList<IWebElement> GetSystemOptions() { return supportedIssueFormSystems; } public bool AreIssueFormElementsLoaded() { var IssueFormElementsLoaded = true; IssueFormElementsLoaded = supportedIssueFormFieldTitle != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldTitleLabel != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldDescription != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldDescriptionLabel != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldDescriptionValue != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldInstrument != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldInstrumentLabel != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldInstrumentValue != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldSystem != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldSystemLabel != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormSystemsSelect != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldCategory != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldCategoryLabel != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldCategoryValue != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldSWVersions != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldSWVersionsLabel != null && IssueFormElementsLoaded; IssueFormElementsLoaded = supportedIssueFormFieldSWVersionsValue != null && IssueFormElementsLoaded; return IssueFormElementsLoaded; } public void populateIssueForm(IssueForm issueFormFields) { SetTitle(issueFormFields.Title); SetCategory(issueFormFields.Category); SetInstrument(issueFormFields.ObservedInInstrument); SetSWVersions(issueFormFields.ExcludedSoftwareVersions); SetSystem(issueFormFields.System); SetDescription(issueFormFields.Description); } public bool validateIssueTitleField(string title) { return supportedIssueFormFieldTitleValue.GetAttribute("value") == title; ; } public bool validateIssueDescriptionField(string description) { return supportedIssueFormFieldDescriptionValue.GetAttribute("value") == description; } public bool validateIssueInstrumentField(string instrument) { return supportedIssueFormFieldInstrumentValue.GetAttribute("value") == instrument; } public bool validateIssueSWVersionField(string swVersion) { return supportedIssueFormFieldSWVersionsValue.GetAttribute("value") == swVersion; } public bool validateIssueSystemField(string system) { if (system != "") { var SystemOptionValueSpan = driver.FindElement(By.XPath("//*[@id='mat-select-1']/div/div[1]/span/span")); return SystemOptionValueSpan.Text == system; } return true; } public bool validateIssueCategoryField(string category) { return supportedIssueFormFieldCategoryValue.GetAttribute("value") == category; } public bool validateIssueFormFields(IssueForm issueFormFields) { var issueFormValid = true; issueFormValid = issueFormValid && validateIssueTitleField(issueFormFields.Title); issueFormValid = issueFormValid && validateIssueDescriptionField(issueFormFields.Description); issueFormValid = issueFormValid && validateIssueInstrumentField(issueFormFields.ObservedInInstrument); issueFormValid = issueFormValid && validateIssueSWVersionField(issueFormFields.ExcludedSoftwareVersions); issueFormValid = issueFormValid && validateIssueSystemField(issueFormFields.System); issueFormValid = issueFormValid && validateIssueCategoryField(issueFormFields.Category); return issueFormValid; } } } <file_sep>/iDareUI/CaseDetailsSteps.cs using iDareUI.Common; using iDareUI.Models; using OpenQA.Selenium; using System; using System.Collections.Generic; using System.Linq; using iDareUI.PageInteractions; using TechTalk.SpecFlow; using Xunit; namespace iDareUI { [Binding] public class CaseDetailsSteps { private TestingEnvironment environment; private CaseDetailsPage caseDetailsPage; private CaseCreationSteps caseCreationSteps; private FeatureContext featureContext; private CaseMainPage caseMainPage; private CaseInvestigationPage caseInvestigationPage; public CaseDetailsSteps(TestingEnvironment environment, FeatureContext featureContext) { this.environment = environment; this.caseInvestigationPage = new CaseInvestigationPage(environment.Driver); this.caseDetailsPage = new CaseDetailsPage(environment.Driver); this.caseMainPage = new CaseMainPage(environment.Driver); this.caseCreationSteps = new CaseCreationSteps(environment, featureContext); this.featureContext = featureContext; } [Then(@"I enter to the details of a case")] public void ThenIEnterToTheDetailsOfACase() { caseMainPage.PressDetailsButton(); } [When(@"all files of the (.*) case have been processed")] public void WhenAllFilesOfTheCASCaseHaveBeenProcessed(string caseId) { caseMainPage.WaitUntilCasesAreUpdated(caseId, "01."); } [Then(@"the Instrument Information should be shown under the Instrument Information section")] public void ThenTheInstrumentInformationShouldBeShownUnderTheInstrumentInformationSection() { string[] expectedInstrumentInformationTitles = new string[]{ "Lab name", "Lab address", "Instrument type", "Instrument serial number", "Software version", "Instrument time zone" }; string[] expectedInstrumentInformationData = new string[] { "ศูนย์บริการโลหิตแห่งชาติ สภากาชาดไทย", "Forrenstrasse 2, 6343 Rotkreuz", "cobas 6800 movable", "WSIM001234", "01.03.08.1011", "(UTC-11:00) Coordinated Universal Time-11" }; var obtainedTitles = caseDetailsPage.GetInstrumentInformationTitles(); var obtainedData = caseDetailsPage.GetInstrumentInformationData(); Assert.True(expectedInstrumentInformationTitles.SequenceEqual(obtainedTitles), $"The Information Titles are not the expected ones. \nExpected: {string.Join(", ", expectedInstrumentInformationTitles)}, \nActual: {string.Join(", ", obtainedTitles)}"); Assert.True(expectedInstrumentInformationData.SequenceEqual(obtainedData), $"The Information Titles are not the expected ones. \nExpected: {string.Join(", ", expectedInstrumentInformationData)}, \nActual: {string.Join(", ", obtainedData)}"); } [Then(@"the titles shown in the Details of the case are correct")] public void ThenTheTitlesShownInTheDetailsOfTheCaseAreCorrect() { string[] expectedDetailsHeaders = new string[] { "Instrument states", "Detected issues", "Footprint", "Instrument information", "Recorded runs" }; var obtainedTitles = caseDetailsPage.GetDetailsCardHeaders(); Assert.True(expectedDetailsHeaders.SequenceEqual(obtainedTitles), $"The Detail titles are not the expected ones. \nExpected: {string.Join(", ", expectedDetailsHeaders)}, \nActual: {string.Join(", ", obtainedTitles)}"); } [Then(@"the system shall fill the case fields automatically")] public void ThenTheSystemShallFillTheCaseFieldsAutomatically() { caseCreationSteps.ThenTheProgressOfTheUploadsShouldDisappear(); Case currentCaseCreated = new Case(); Case caseDetails = (Case)this.featureContext["caseDetails"]; caseMainPage.WaitUntilCasesAreUpdated(caseDetails.CaseID, "01."); IEnumerable<Case> caseListComponent = caseMainPage.GetRowsElementsCases(); IEnumerable<Case> caseDetailsCreated = caseListComponent.Where(myCase => myCase.CaseID.Contains(caseDetails.CaseID)); if (caseDetailsCreated.Count() == 1) { currentCaseCreated.SWVersion = caseDetailsCreated.ElementAt(0).SWVersion; currentCaseCreated.SerialNo = caseDetailsCreated.ElementAt(0).SerialNo; currentCaseCreated.Customer = caseDetailsCreated.ElementAt(0).Customer; currentCaseCreated.Country = caseDetailsCreated.ElementAt(0).Country; } Assert.False(String.IsNullOrEmpty(currentCaseCreated.SWVersion), "The fields were not automatically filled"); Assert.False(String.IsNullOrEmpty(currentCaseCreated.SerialNo), "The fields were not automatically filled"); Assert.False(String.IsNullOrEmpty(currentCaseCreated.Customer), "The fields were not automatically filled"); Assert.False(String.IsNullOrEmpty(currentCaseCreated.Country), "The fields were not automatically filled"); } [Then(@"The user navigates to the investigation view")] public void ThenTheUserNavigatesToTheInvestigationView() { caseInvestigationPage.PressInvestigateTab(); } } } <file_sep>/iDareUI/PageInteractions/CaseDetailsPage.cs using System; using System.Collections.Generic; using System.Linq; using iDareUI.Common; using OpenQA.Selenium; using OpenQA.Selenium.Remote; namespace iDareUI.PageInteractions { public class CaseDetailsPage { private RemoteWebDriver driver; public CaseDetailsPage(RemoteWebDriver driver) { this.driver = driver; } public IWebElement closeCaseDetailsButton => driver.FindElement(By.CssSelector("button.prv-context-info__close.mat-icon-button")); private IWebElement DetailsTitleCaseId => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CasedDetailHeaderHeading1']")); private IWebElement instrumentInformationCard => driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfo']")); private IWebElement instrumentInformationHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoHeader']")); private IWebElement recordedRunsCard => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailRecordedRunsInfoContainer']")); private IWebElement recordedRunsHeader => driver.FindElement(By.XPath("//*[@attr.data-idare-id='CaseDetailRecordedRunsInfoContainerTitle']")); public void PressMatExpansionPanelInstrumentInformation() { instrumentInformationHeader.Click(); } public void PressMatExpansionPanelRecordedRuns() { recordedRunsHeader.Click(); } public IEnumerable<string> GetDetailsCardHeaders() { IList<IWebElement> detailsHeaders = driver.FindElements(By.CssSelector("span.section-title")); List<string> detailsHeadersText = new List<string> (detailsHeaders.Select(element => element.Text)); detailsHeadersText.Add(instrumentInformationHeader.Text); detailsHeadersText.Add(recordedRunsHeader.Text); return detailsHeadersText; } public IEnumerable<string> GetInstrumentInformationTitles() { IList<IWebElement> instrumentInformationFieldsElements = new List<IWebElement>(); instrumentInformationFieldsElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoLabNameLabel']"))); instrumentInformationFieldsElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoLabAddressLabel']"))); instrumentInformationFieldsElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoInstrumentTypeLabel']"))); instrumentInformationFieldsElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoSerialNumberLabel']"))); instrumentInformationFieldsElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoSfVersionLabel']"))); instrumentInformationFieldsElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoTimeZoneLabel']"))); var instrumentInformationFieldsText = instrumentInformationFieldsElements.Select(element => element.Text); return instrumentInformationFieldsText; } public IEnumerable<string> GetInstrumentInformationData() { IList<IWebElement> instrumentInformationDataElements = new List<IWebElement>(); instrumentInformationDataElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoLabNameValue']"))); instrumentInformationDataElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoLabAddressValue']"))); instrumentInformationDataElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoInstrumentTypeValue']"))); instrumentInformationDataElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoSerialNumberValue']"))); instrumentInformationDataElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoSfVersionValue']"))); instrumentInformationDataElements.Add(driver.FindElement(By.XPath("//*[@attr.data-idare-id='InstrumentInfoTimeZoneValue']"))); var instrumentInformationDataText = instrumentInformationDataElements.Select(element => element.Text); return instrumentInformationDataText; } public void PressCloseCaseDetailsButton() { FlowUtilities.WaitUntil(() => closeCaseDetailsButton.Enabled, TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(100)); closeCaseDetailsButton.Click(); } } }
b46e7d244a59ea3393cf6c0b678734aefe292d6f
[ "C#" ]
30
C#
iamcucusa/e2e
fb90010217ff9fc00147c894bebbd098a7823957
a3ad2de6000bb60211d571b109f6b257d58b0e8d
refs/heads/master
<repo_name>ohack38/vue_kurs_test<file_sep>/src/router/index.js import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' Vue.use(VueRouter) const routes = [{ path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import ( /* webpackChunkName: "about" */ '../views/About.vue') }, { path: '/activities', name: 'ActivityView', component: () => import ( /* webpackChunkName: "about" */ '../views/ActivityView.vue') }, { path: '/events', name: 'EventView', component: () => import ( /* webpackChunkName: "about" */ '../views/EventView.vue') }, { path: '/places', name: 'PlaceView', component: () => import ( /* webpackChunkName: "about" */ '../views/PlaceView.vue') }, { path: '/register', name: 'RegisterView', component: () => import ( /* webpackChunkName: "about" */ '../views/RegisterView.vue') }, { path: '/profile', name: 'ProfileView', component: () => import ( /* webpackChunkName: "about" */ '../views/ProfileView.vue') }, { path: '/wallet', name: 'WalletView', component: () => import ( /* webpackChunkName: "about" */ '../views/WalletView.vue') }, { path: '/myevents', name: 'MyeventsView', component: () => import ( /* webpackChunkName: "about" */ '../views/MyeventsView.vue') }, { path: '/contacts', name: 'ContactsView', component: () => import ( /* webpackChunkName: "about" */ '../views/ContactsView.vue') }, { path: '/settings', name: 'SettingsView', component: () => import ( /* webpackChunkName: "about" */ '../views/SettingsView.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
697bee15d8e96a1f0012d0a207918c78a189bd00
[ "JavaScript" ]
1
JavaScript
ohack38/vue_kurs_test
29ae19e26bcc36cedcb391eaebdc2707cb70aa9d
15ffaa388022601a98a1cee81a0a0d97242cb4f7
refs/heads/master
<repo_name>prezaie/Skill-Matching-Python-Flask<file_sep>/preproces.py from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split def preprocess(df, X_te): """Standardize data Args: df (str, or DataFrame): input data test_size (float) : size of test set Returns: X_tr (Dataframe): Train DataFrame X_te (Dataframe): Test DataFrame X_tr_sc (Numpy array): Standardized Train DataFrame X_te_sc (Numpy array): Standardized Test DataFrame """ df = df.astype(float) X_te = X_te.astype(float) sc = StandardScaler() X_tr = df.drop(columns='project_employee_id') X_te = X_te.drop(columns='project_employee_id') X_tr_sc = sc.fit_transform(X_tr) X_te_sc = sc.transform(X_te) return X_tr, X_te, X_tr_sc, X_te_sc<file_sep>/read.py import pandas as pd from sqlalchemy.engine import create_engine def data_reader(): """Reads data from SQL database and transform data to a DataFrame Args: none Returns: df (Dataframe): Dataframe contains employee skills and employee id """ engine = create_engine('postgresql://parisarezaie@localhost/kapa') df = pd.read_sql('''SELECT name, level, project_employee_id FROM criteria, employee_criteria WHERE (criteria.id = employee_criteria.criteria_id) AND (criteria.type = 'SKILL') ''', engine) df = df.pivot(index='project_employee_id', columns='name', values='level') df.fillna(0,inplace=True) df = df.reset_index() return df <file_sep>/model.py from sklearn.neighbors import NearestNeighbors def knn(X_tr_sc, n_neighbors, radius): """ Unsupervised learner for implementing neighbor searches Args: X_tr_sc (DataFrame): Standardized Train DataFrame n_neighbors (int): Number of neighbors radius (float): Range of parameter space Returns: model (Class): DataModel that fitted to the training data """ neigh = NearestNeighbors(n_neighbors, radius,metric='euclidean') model = neigh.fit(X_tr_sc) return model<file_sep>/prediction.py from model import knn def prediction(model,X_tr, X_te, X_tr_sc, X_te_sc): """ Prediction closest employees to our query position Args: model (Class): DataModel created from our training data X_tr (DataFrame): Train Dataframe X_te (DataFrame): Test Dataframe X_tr_sc (DataFrame): Standardized Train DataFrame X_te_sc (DataFrame): Standardized Test DataFrame Returns: X_tr.loc[m1,m2] (DataFrame): Query results """ poi = X_te_sc closest_points = model.kneighbors(poi.reshape(1, -1), 3, return_distance=False) # for i,close_id in enumerate(closest_points[0]): # idx = X_tr.index[close_id] # m1 = (X_tr.index == idx) # m2 = (X_tr[m1] != 0).all() #return X_tr.loc[m1,m2] return X_tr.loc[closest_points[0],:] <file_sep>/main.py from read import data_reader from preproces import preprocess from model import knn import pandas as pd import numpy as np from prediction import prediction from flask import Flask, request, jsonify from flask_cors import CORS, cross_origin import json """Connects to Flask to get the search query. Using KNN to return most similar results for skill match Args: json data Returns: df (Dataframe): Dataframe contains best matches employee IDs and skills """ app = Flask(__name__) CORS(app) @app.route('/api/predict', methods = ['POST']) def predict(): skills= request.json['skill'] headers = [str(i) for i in skills.split(',')] payload= request.json['data'] values = [float(i) for i in payload.split(',')] df=data_reader() col_list=list(df.columns) df_new=pd.DataFrame(columns=col_list) X=pd.DataFrame([values],columns=headers, dtype=float) X_te=pd.concat([df_new,X], axis=0,sort=False) X_te.fillna(0,inplace=True) X_tr, X_te, X_tr_sc, X_te_sc = preprocess(df,X_te) my_model = knn(X_tr_sc, 5, 0.4) prediction_results=prediction(my_model,X_tr, X_te, X_tr_sc, X_te_sc) prediction_results=prediction_results.loc[:, (prediction_results != 0).any(axis=0)] return json.dumps(json.loads(prediction_results.to_json(orient='index'))) if __name__ == '__main__': app.run(port=6000, debug=True)
c24e33f438dbc9e131cb321332c0701813001644
[ "Python" ]
5
Python
prezaie/Skill-Matching-Python-Flask
845bbe3106cc91bd7106504e1296956da242a2d9
5fa3fc1af5fb114df9870f2b2a7771d5d73b63b3
refs/heads/master
<repo_name>xShadov/NetworkConnectivity<file_sep>/src/main/java/com/shadov/networkconnectivity/task2/CustomEdge.java package com.shadov.networkconnectivity.task2; import org.jgrapht.graph.DefaultEdge; public class CustomEdge extends DefaultEdge { private final int maxBandwidth; private int bandwidth = 0; public CustomEdge(int maxBandwidth) { this.maxBandwidth = maxBandwidth; } public int getMaxBandwidth() { return maxBandwidth; } public int getBandwidth() { return bandwidth; } public void setBandwidth(int bandwidth) { this.bandwidth = bandwidth; } public String toString() { return getSource() + " -> " + getTarget() + ": " + bandwidth; } } <file_sep>/src/main/java/com/shadov/networkconnectivity/task1/SubtaskC.java package com.shadov.networkconnectivity.task1; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.SimpleWeightedGraph; public class SubtaskC extends SubtaskB { public SimpleWeightedGraph<Integer, DefaultWeightedEdge> createGraph() { super.createGraph(); graph.setEdgeWeight(graph.addEdge(1, 10), 0.8); graph.setEdgeWeight(graph.addEdge(5, 15), 0.7); return graph; } @Override public String toString() { return "Graph-C"; } } <file_sep>/src/main/java/com/shadov/networkconnectivity/task1/Task1.java package com.shadov.networkconnectivity.task1; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Task1 { public static final int MONTE_CARLO_ATTEMPTS = 10000; public static final boolean LOG = false; public void start() { List<GraphFactory> graphs = new ArrayList<GraphFactory>(); graphs.add(new SubtaskA()); graphs.add(new SubtaskB()); graphs.add(new SubtaskC()); ExecutorService executor = Executors.newFixedThreadPool(4); List<Future<String>> list = new ArrayList<Future<String>>(); for (final GraphFactory graphFactory : graphs) { Future<String> futureString = executor.submit(new TestingTaskABC(graphFactory)); list.add(futureString); } Future<String> futureString = executor.submit(new TestingTaskD(new SubtaskD())); list.add(futureString); for (Future<String> string : list) { try { String futured = string.get(); System.out.println(futured); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } executor.shutdown(); } } <file_sep>/src/main/java/com/shadov/networkconnectivity/App.java package com.shadov.networkconnectivity; import com.shadov.networkconnectivity.task1.Task1; import com.shadov.networkconnectivity.task2.Task2; public class App { private static final String LOCATION = "exampleGraphs\\example1"; public static void main(String[] args) { try(Scanner scanner = new Scanner(System.in)) { switch (scanner.nexInt()) { case 1: new Task1().start(); break; case 2: new Task2().start(LOCATION); break; default: System.err.println("Wrong task number"); } } } } <file_sep>/src/main/java/com/shadov/networkconnectivity/task2/GraphData.java package com.shadov.networkconnectivity.task2; import org.jgrapht.graph.SimpleGraph; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class GraphData { private SimpleGraph<Integer, CustomEdge> graph; private int[][] flows; private double reliability; private double maxDelay; private final double size = 65535.0; private int attempts; public GraphData(String fileLocation) throws IOException { String line; File graphFile = new File(fileLocation + File.separator + "graph.txt"); try (BufferedReader brGraph = new BufferedReader(new FileReader(graphFile))) { String[] splitLine = brGraph.readLine().split(" "); reliability = Double.parseDouble(splitLine[0]); maxDelay = Double.parseDouble(splitLine[1]); attempts = Integer.parseInt(splitLine[2]); graph = new SimpleGraph<>(CustomEdge.class); while ((line = brGraph.readLine()) != null && (splitLine = line.split(" ")).length == 3) { int v1 = Integer.parseInt(splitLine[0]); int v2 = Integer.parseInt(splitLine[1]); int edgeBandwidth = Integer.parseInt(splitLine[2]); graph.addVertex(v1); graph.addVertex(v2); graph.addEdge(v1, v2, new CustomEdge(edgeBandwidth)); } } int graphSize = graph.vertexSet().size(); flows = new int[graphSize][graphSize]; graphFile = new File(fileLocation + File.separator + "transfers.txt"); try (BufferedReader brGraph = new BufferedReader(new FileReader(graphFile))) { String[] splitLine; while ((line = brGraph.readLine()) != null && (splitLine = line.split(" ")).length == 3) { int source = Integer.parseInt(splitLine[0]) - 1; int destination = Integer.parseInt(splitLine[1]) - 1; int quantity = Integer.parseInt(splitLine[2]); flows[source][destination] = quantity; } } } public SimpleGraph<Integer, CustomEdge> getGraph() { return graph; } public int[][] getFlows() { return flows; } public double getReliability() { return reliability; } public double getMaxDelay() { return maxDelay; } public double getSize() { return size; } public int getAttempts() { return attempts; } }
f1a9f31fdc1d3bf79ea3a8dac3b5a7364cc0570f
[ "Java" ]
5
Java
xShadov/NetworkConnectivity
7b9b5ebd503981f1dae0a7a7a99e56719141a92d
72fd9e51475d366122189daa5cc5245ff387472d
refs/heads/master
<file_sep>package com.b_lam.resplash.ui.photo.detail import androidx.lifecycle.* import com.b_lam.resplash.data.collection.model.Collection import com.b_lam.resplash.data.photo.model.Photo import com.b_lam.resplash.di.Properties import com.b_lam.resplash.domain.collection.CollectionRepository import com.b_lam.resplash.domain.login.LoginRepository import com.b_lam.resplash.domain.photo.PhotoRepository import com.b_lam.resplash.util.Result import com.b_lam.resplash.util.livedata.lazyMap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.util.* class PhotoDetailViewModel( private val photoRepository: PhotoRepository, private val collectionRepository: CollectionRepository, private val loginRepository: LoginRepository ) : ViewModel() { private val _photoDetailsLiveData: Map<String, LiveData<Photo>> = lazyMap { val liveData = MutableLiveData<Photo>() viewModelScope.launch { val result = photoRepository.getPhotoDetails(it) when (result) { is Result.Success -> { liveData.postValue(result.value) _currentUserCollectionIds.postValue( result.value.current_user_collections?.map { it.id }?.toMutableList()) } } } return@lazyMap liveData } private val _currentUserCollectionIds = MutableLiveData<MutableList<Int>?>() val currentUserCollectionIds: LiveData<MutableList<Int>?> = _currentUserCollectionIds private val _userCollections = MutableLiveData<MutableList<Collection>?>() val userCollections: LiveData<MutableList<Collection>?> = _userCollections var downloadId: Long? = null var downloadUUID: UUID? = null fun photoDetailsLiveData(id: String): LiveData<Photo> = _photoDetailsLiveData.getValue(id) fun likePhoto(id: String) = viewModelScope.launch { photoRepository.likePhoto(id) } fun unlikePhoto(id: String) = viewModelScope.launch { photoRepository.unlikePhoto(id) } fun isUserAuthorized() = loginRepository.isAuthorized() fun addPhotoToCollection(collectionId: Int, photoId: String, position: Int) = liveData(viewModelScope.coroutineContext) { emit(Result.Loading) val result = collectionRepository.addPhotoToCollection(collectionId, photoId) if (result is Result.Success) { val newIdList = _currentUserCollectionIds.value ?: mutableListOf() newIdList.add(collectionId) _currentUserCollectionIds.postValue(newIdList) val newCollectionsList = _userCollections.value result.value.collection?.let { newCollectionsList?.set(position, it) } _userCollections.postValue(newCollectionsList) } emit(result) } fun removePhotoFromCollection(collectionId: Int, photoId: String, position: Int) = liveData(viewModelScope.coroutineContext) { emit(Result.Loading) val result = collectionRepository.removePhotoFromCollection(collectionId, photoId) if (result is Result.Success) { val newList = _currentUserCollectionIds.value ?: mutableListOf() newList.remove(collectionId) _currentUserCollectionIds.postValue(newList) val newCollectionsList = _userCollections.value result.value.collection?.let { newCollectionsList?.set(position, it) } _userCollections.postValue(newCollectionsList) } emit(result) } private var page = 1 var isLoading = false var onLastPage = false fun refresh() { page = 1 isLoading = false onLastPage = false loadMore() } fun loadMore() { viewModelScope.launch(Dispatchers.Default) { isLoading = true val username = loginRepository.getUsername() ?: return@launch val result = collectionRepository.getUserCollections(username, page) if (result is Result.Success) { val newList = _userCollections.value ?: mutableListOf() newList.addAll(result.value) _userCollections.postValue(newList) onLastPage = result.value.isEmpty() || result.value.size < Properties.DEFAULT_PAGE_SIZE page++ } isLoading = false } } fun createCollection( title: String, description: String?, private: Boolean?, photoId: String ) = liveData { emit(Result.Loading) val createResult = collectionRepository.createCollection(title, description, private) if (createResult is Result.Success) { var newCollection = createResult.value val addResult = collectionRepository.addPhotoToCollection(newCollection.id, photoId) if (addResult is Result.Success) { val newIdList = _currentUserCollectionIds.value ?: mutableListOf() newIdList.add(newCollection.id) _currentUserCollectionIds.postValue(newIdList) addResult.value.collection?.let { newCollection = it } } val newList = _userCollections.value ?: mutableListOf() newList.add(0, newCollection) _userCollections.postValue(newList) } emit(createResult) } } <file_sep>package com.b_lam.resplash.data.autowallpaper import androidx.room.Database import androidx.room.RoomDatabase import com.b_lam.resplash.data.autowallpaper.model.AutoWallpaperCollection import com.b_lam.resplash.data.autowallpaper.model.AutoWallpaperHistory @Database( entities = [ AutoWallpaperHistory::class, AutoWallpaperCollection::class ], version = 1, exportSchema = false ) abstract class AutoWallpaperDatabase : RoomDatabase() { abstract fun autoWallpaperHistoryDao(): AutoWallpaperHistoryDao abstract fun autoWallpaperCollectionDao(): AutoWallpaperCollectionDao }<file_sep>package com.b_lam.resplash.di import com.b_lam.resplash.worker.AutoWallpaperWorker import com.b_lam.resplash.worker.DownloadWorker import com.b_lam.resplash.worker.MuzeiWorker import org.koin.androidx.workmanager.dsl.worker import org.koin.dsl.module val workerModule = module { worker { AutoWallpaperWorker(get(), get(), get(), get(), get(), get()) } worker { AutoWallpaperWorker.FutureAutoWallpaperWorker(get(), get(), get()) } worker { DownloadWorker(get(), get(), get(), get()) } worker { MuzeiWorker(get(), get(), get(), get()) } }
72516dedd85245450a2451a8fc73cd51c44c3ce9
[ "Kotlin" ]
3
Kotlin
ChristosBouronikos/Resplash
23ddd1cebaa4ef5dec046f241bbe02c6dbac94e7
6a871d9e88294a538dee6386371aacb544d35aeb
refs/heads/master
<file_sep>// stdafx.h : include file for standard system include files // // This is a part of the Microsoft Foundation Classes C++ library. // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and Microsoft // QuickHelp and/or WinHelp documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #define AFX_CRT_ERRORCHECK(expr) \ AtlCrtErrorCheck(expr) #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxole.h> #include <afxcmn.h> #include <afxpriv.h> #include <atlbase.h> #include <atlwin.h> #include "windowsx.h" #include "ehvecdtr.h" #include <xstddef> #pragma warning( disable: 4706 4100 ) _STD_BEGIN extern "C" { //using ::exception; using ::terminate_handler; using ::unexpected; using ::unexpected_handler; }; _STD_END extern "C" inline __declspec(noreturn) void __cdecl __std_terminate(void) { ::terminate(); } <file_sep>/*** *ehvecdtr.cxx - EH-aware version of destructor iterator helper function * * Copyright (c) Microsoft Corporation. All rights reserved. * *Purpose: * These functions are called when constructing and destructing arrays of * objects. Their purpose is to assure that constructed elements get * destructed if the constructor for one of the elements throws. * * Must be compiled using "-d1Binl" to be able to specify __thiscall * at the user level ****/ #pragma once #include "ehdata.h" #include <eh.h> #if defined _M_CEE #define CALLTYPE __clrcall #define CALLEETYPE __clrcall #define __RELIABILITY_CONTRACT \ [System::Runtime::ConstrainedExecution::ReliabilityContract( \ System::Runtime::ConstrainedExecution::Consistency::WillNotCorruptState, \ System::Runtime::ConstrainedExecution::Cer::Success \ )] #define ASSERT_UNMANAGED_CODE_ATTRIBUTE [System::Security::Permissions::SecurityPermissionAttribute(System::Security::Permissions::SecurityAction::Assert, UnmanagedCode = true)] #define SECURITYCRITICAL_ATTRIBUTE [System::Security::SecurityCritical] #else #define CALLEETYPE __stdcall #define __RELIABILITY_CONTRACT #define ASSERT_UNMANAGED_CODE_ATTRIBUTE #define SECURITYCRITICAL_ATTRIBUTE #if defined _M_IX86 #define CALLTYPE __thiscall #else #define CALLTYPE __stdcall #endif #endif using destructor_type = void (CALLTYPE*)(void*); __RELIABILITY_CONTRACT void CALLEETYPE __ArrayUnwind( void* ptr, // Pointer to array to destruct size_t size, // Size of each element (including padding) size_t count, // Number of elements in the array destructor_type destructor // The destructor to call ); __RELIABILITY_CONTRACT SECURITYCRITICAL_ATTRIBUTE inline void CALLEETYPE __ehvec_dtor( void* ptr, // Pointer to array to destruct size_t size, // Size of each element (including padding) size_t count, // Number of elements in the array destructor_type destructor // The destructor to call ) { bool success{false}; // Advance pointer past end of array ptr = static_cast<char*>(ptr) + size * count; __try { // Destruct elements while (count-- > 0) { ptr = static_cast<char*>(ptr) - size; destructor(ptr); } success = true; } __finally { if (!success) { __ArrayUnwind(ptr, size, count, destructor); } } } __RELIABILITY_CONTRACT ASSERT_UNMANAGED_CODE_ATTRIBUTE SECURITYCRITICAL_ATTRIBUTE static int ArrayUnwindFilter(EXCEPTION_POINTERS* pExPtrs) { EHExceptionRecord *pExcept = (EHExceptionRecord*)pExPtrs->ExceptionRecord; switch(PER_CODE(pExcept)) { case EH_EXCEPTION_NUMBER: terminate(); #ifdef ALLOW_UNWIND_ABORT case EH_ABORT_FRAME_UNWIND_PART: return EXCEPTION_EXECUTE_HANDLER; #endif default: return EXCEPTION_CONTINUE_SEARCH; } } __RELIABILITY_CONTRACT SECURITYCRITICAL_ATTRIBUTE inline void CALLEETYPE __ArrayUnwind( void* ptr, // Pointer to array to destruct size_t size, // Size of each element (including padding) size_t count, // Number of elements in the array destructor_type destructor // The destructor to call ) { // 'unwind' rest of array __try { for (size_t i{0}; i != count; ++i) { ptr = static_cast<char*>(ptr) - size; destructor(ptr); } } __except(ArrayUnwindFilter(exception_info())) { ; // Deliberately do nothing } } __RELIABILITY_CONTRACT SECURITYCRITICAL_ATTRIBUTE inline void CALLEETYPE __ehvec_dtor( void* ptr, // Pointer to array to destruct size_t size, // Size of each element (including padding) int count, // Number of elements in the array destructor_type destructor // The destructor to call ) { __ehvec_dtor(ptr, size, static_cast<size_t>(count), destructor); }
e5d7777af0a4acb38cbe967418f7e04e634fec07
[ "C" ]
2
C
DiablosOffens/VCSamples
f223c3058d900b9a8f0556e3f141ddd19d6d967f
3ccc6138efb52a0aa778ffdb4a3892dcde6076c0
refs/heads/master
<file_sep>const viewHandler = () => { const previousRow = document.querySelector("#previousRow"); const previousPage = document.querySelector("#previousPage"); const nextRow = document.querySelector("#nextRow"); const nextPage = document.querySelector("#nextPage"); // Keeps track of state let offset = 0; nextRow.addEventListener("click", () => { offset += 5; getContent(); }); previousRow.addEventListener("click", () => { if (offset >= 5) { offset -= 5; getContent(); } else { alert("No previous Pokémon!"); } }); nextPage.addEventListener("click", () => { offset += 20; getContent(); }); previousPage.addEventListener("click", () => { if (offset >= 20) { offset -= 20; getContent(); } else if (offset <= 20 && offset >= 5) { offset -= offset; getContent(); } else { alert("No previous Pokémon!"); } }); // Handles view logic async function getContent() { try { for (i = 0; i < 20; i++) { // Offsets the value of i to modify API endpoint const pokeId = i + offset + 1; const query = `${pokeApiUrl}${pokeId}`; // Fetches resource based on modified endpoint const pokeUrl = await getPokeApi(query); // Grabs HTMl elements const img = document.querySelector(`#img-div-${i + 1}`) .firstChild; const p = document.querySelector(`#p-div-${i + 1}`).firstChild; // Set contents img.src = pokeUrl.sprites.front_default; // Click functionality img.addEventListener("mouseenter", () => { img.src = pokeUrl.sprites.back_default; }); img.addEventListener("mouseleave", () => { img.src = pokeUrl.sprites.front_default; }); p.innerHTML = pokeUrl.name; } } catch (error) { console.error(`Error: ${error.message}`); } } };<file_sep>// Stores path to RESTful API in variable let pokeApiUrl = "https://pokeapi.co/api/v2/pokemon/"; // Returns a promise containing resource parsed in JSON format const getPokeApi = async (path = pokeApiUrl) => { try { const response = await fetch(path); const pokeApi = await response.json(); // console.log(path); return pokeApi; // Handles potential errors } catch (error) { console.error(`Error: ${error.message}`); } }; <file_sep>API: https://pokeapi.co/
b1330192c7372fa3784fc00b4846dda4f148ad10
[ "JavaScript", "Markdown" ]
3
JavaScript
GAdowei/pokedex
f7c4263ce5de3762c0f4313e5fbee6b28f6b7d71
af6cb1a87153d4233bbfe73d3bc71dceef41f2ce
refs/heads/master
<file_sep>var helicopterIMG, helicopterSprite, packageSprite, packageIMG; var packageBody,ground function preload() { helicopterIMG=loadImage("helicopter.png") packageIMG=loadImage("package.png") } function setup() { createCanvas(800, 700); rectMode(CENTER); packageBody = createSprite(width/2 , 200 , 5 ); packageSprite=createSprite(width/2, 80, 10,10); packageSprite.addImage(packageIMG); packageSprite.scale=0.2; //packageSprite.x = packageBody.position.x; //packageSprite.y = packageBody.position.y; packageSprite.visible = false; helicopterSprite=createSprite(width/2, 200, 10,10); helicopterSprite.addImage(helicopterIMG) helicopterSprite.scale=0.6 //groundSprite=createSprite(width/2, height-35, width,10); //groundSprite.shapeColor=color(255); //Create a Ground ground = createSprite(width/2, 650, width, 10 ); } function draw() { rectMode(CENTER); background(0); packageBody.visible = false; packageIMG.visible = false; //packageSprite.x= packageBody.position.x //packageSprite.y= packageBody.position.y keyPressed(); drawSprites(); } function keyPressed() { if (keyCode === DOWN_ARROW) { packageSprite.visible = true; packageSprite.y = helicopterSprite.y+5; packageSprite.velocityY = 2; packageSprite.collide(ground); } }
ad91b625d07e7332ea569d928a2c79da8207e0e0
[ "JavaScript" ]
1
JavaScript
krrish012/Project-SupplyMission-1
83873de4f781671ae7fa7bd66b08a7864a368b57
f9965d5334d4f5c33574c28063a0031e67431a3f
refs/heads/master
<repo_name>aurelien-w/games<file_sep>/src/Entity/Season.php <?php namespace App\Entity; use Carbon\Carbon; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\SeasonRepository") * @ORM\HasLifecycleCallbacks() */ class Season { const STATUS_WAITING = 0; const STATUS_IN_PROGRESS = 1; const STATUS_COMPLETED = 2; /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @var integer * * @ORM\Column(type="smallint") */ private $status; /** * @var \DateTime * * @ORM\Column(type="datetime") */ private $startAt; /** * @var \DateTime * * @ORM\Column(type="datetime") */ private $finishAt; /** * @var ArrayCollection * * @ORM\OneToMany(targetEntity="App\Entity\PlayerSeasonData", mappedBy="season") * @ORM\OrderBy({"rank" = "DESC"}) */ private $playerSeasonData; /** * @var ArrayCollection * * @ORM\OneToMany(targetEntity="App\Entity\SeasonDuel", mappedBy="season") */ private $duels; /** * @var \DateTime * * @ORM\Column(type="datetime") */ private $createdAt; /** * @var \DateTime * * @ORM\Column(type="datetime") */ private $updatedAt; public function __construct() { $this->playerSeasonData = new ArrayCollection(); $this->duels = new ArrayCollection(); } public function isCurrentMonthSeason(): bool { return (new \DateTime())->format('m') === $this->startAt->format('m'); } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id): void { $this->id = $id; } /** * @return int */ public function getStatus(): int { return $this->status; } /** * @param int $status */ public function setStatus(int $status): void { $this->status = $status; } /** * @return \DateTime */ public function getStartAt(): \DateTime { return $this->startAt; } /** * @param \DateTime $startAt */ public function setStartAt(\DateTime $startAt): void { $this->startAt = $startAt; } /** * @return \DateTime */ public function getFinishAt(): \DateTime { return $this->finishAt; } /** * @param \DateTime $finishAt */ public function setFinishAt(\DateTime $finishAt): void { $this->finishAt = $finishAt; } /** * @return ArrayCollection */ public function getPlayerSeasonData() { return $this->playerSeasonData; } /** * @param ArrayCollection $playerSeasonData */ public function setPlayerSeasonData(ArrayCollection $playerSeasonData): void { $this->playerSeasonData = $playerSeasonData; } /** * @param Player $player * @return bool */ public function hasPlayer(Player $player): bool { foreach ($this->getPlayerSeasonData() as $seasonDatum) { if ($seasonDatum->getPlayer()->getId() === $player->getId()) { return true; } } return false; } /** * @return int */ public function getNbPlayers(): int { return $this->playerSeasonData->count(); } /** * @return int */ public function getNbMissingPlayerToStart() { $diff = 2 - $this->playerSeasonData->count(); if ($diff < 0) { $diff = 0; } return $diff; } /** * @return ArrayCollection */ public function getDuels() { return $this->duels; } /** * @param ArrayCollection $duels */ public function setDuels(ArrayCollection $duels): void { $this->duels = $duels; } /** * @return \DateTime */ public function getCreatedAt(): \DateTime { return $this->createdAt; } /** * @param \DateTime $createdAt */ public function setCreatedAt(\DateTime $createdAt): void { $this->createdAt = $createdAt; } /** * @return \DateTime */ public function getUpdatedAt(): \DateTime { return $this->updatedAt; } /** * @param \DateTime $updatedAt */ public function setUpdatedAt(\DateTime $updatedAt): void { $this->updatedAt = $updatedAt; } /** * @ORM\PrePersist() */ public function prePersist() { $this->status = self::STATUS_WAITING; $this->setCreatedAt(new \DateTime()); $this->setUpdatedAt(new \DateTime()); } /** * @ORM\PreUpdate() */ public function preUpdate() { $this->setUpdatedAt(new \DateTime()); } } <file_sep>/src/Entity/PlayerSeasonData.php <?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\PlayerSeasonDataRepository") * @ORM\HasLifecycleCallbacks() */ class PlayerSeasonData { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @var integer * * @ORM\Column(type="integer") */ private $rank = 0; /** * @var Player * * @ORM\ManyToOne(targetEntity="App\Entity\Player", inversedBy="playerSeasonData") */ private $player; /** * @var Season * * @ORM\ManyToOne(targetEntity="App\Entity\Season", inversedBy="playerSeasonData") */ private $season; /** * @var ArrayCollection * * @ORM\OneToMany(targetEntity="App\Entity\SeasonDuel", mappedBy="playerSeasonDataA") */ private $duelsA; /** * @var ArrayCollection * * @ORM\OneToMany(targetEntity="App\Entity\SeasonDuel", mappedBy="playerSeasonDataB") */ private $duelsB; /** * @var integer * * @ORM\Column(type="smallint") */ private $duelPlayed; /** * @var integer * * @ORM\Column(type="smallint") */ private $duelWin; /** * @var integer * * @ORM\Column(type="smallint") */ private $duelNull; /** * @var integer * * @ORM\Column(type="smallint") */ private $duelLoose; /** * PlayerSeasonData constructor. */ public function __construct() { $this->duelsA = new ArrayCollection(); $this->duelsB = new ArrayCollection(); } /** * @ORM\PrePersist() */ public function prePersist() { $this->rank = 0; $this->duelPlayed = 0; $this->duelWin = 0; $this->duelNull = 0; $this->duelLoose = 0; } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id): void { $this->id = $id; } /** * @return int */ public function getRank(): int { return $this->rank; } /** * @param int $rank */ public function setRank(int $rank): void { $this->rank = $rank; } /** * @return Player */ public function getPlayer(): Player { return $this->player; } /** * @param Player $player */ public function setPlayer(Player $player): void { $this->player = $player; } /** * @return Season */ public function getSeason(): Season { return $this->season; } /** * @param Season $season */ public function setSeason(Season $season): void { $this->season = $season; } /** * @return ArrayCollection */ public function getDuelsA(): ArrayCollection { return $this->duelsA; } /** * @param ArrayCollection $duelsA */ public function setDuelsA(ArrayCollection $duelsA): void { $this->duelsA = $duelsA; } /** * @return ArrayCollection */ public function getDuelsB(): ArrayCollection { return $this->duelsB; } /** * @param ArrayCollection $duelsB */ public function setDuelsB(ArrayCollection $duelsB): void { $this->duelsB = $duelsB; } /** * @return int */ public function getDuelPlayed(): int { return $this->duelPlayed; } /** * @param int $duelPlayed */ public function setDuelPlayed(int $duelPlayed): void { $this->duelPlayed = $duelPlayed; } /** * @return int */ public function getDuelWin(): int { return $this->duelWin; } /** * @param int $duelWin */ public function setDuelWin(int $duelWin): void { $this->duelWin = $duelWin; } /** * @return int */ public function getDuelNull(): int { return $this->duelNull; } /** * @param int $duelNull */ public function setDuelNull(int $duelNull): void { $this->duelNull = $duelNull; } /** * @return int */ public function getDuelLoose(): int { return $this->duelLoose; } /** * @param int $duelLoose */ public function setDuelLoose(int $duelLoose): void { $this->duelLoose = $duelLoose; } } <file_sep>/src/Entity/Player.php <?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\PlayerRepository") * @ORM\HasLifecycleCallbacks() */ class Player { public function __construct() { $this->duelsA = new ArrayCollection(); $this->duelsB = new ArrayCollection(); $this->playerSeasonData = new ArrayCollection(); } /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $name; /** * @ORM\Column(type="integer") */ private $rank = 1000; /** * @ORM\OneToMany(targetEntity="App\Entity\Duel", mappedBy="playerA") */ private $duelsA; /** * @ORM\OneToMany(targetEntity="App\Entity\Duel", mappedBy="playerB") */ private $duelsB; /** * @var ArrayCollection * * @ORM\OneToMany(targetEntity="App\Entity\PlayerSeasonData", mappedBy="player") */ private $playerSeasonData; /** * @ORM\Column(type="datetime") */ private $updated_at; /** * @ORM\Column(type="datetime") */ private $created_at; /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } /** * @return mixed */ public function getName() { return $this->name; } /** * @param mixed $name */ public function setName($name) { $this->name = $name; } /** * @return mixed */ public function getRank() { return $this->rank; } /** * @param mixed $rank */ public function setRank($rank) { $this->rank = $rank; } /** * @return mixed */ public function getDuelsA() { return $this->duelsA; } /** * @param mixed $duelsA */ public function setDuels($duelsA) { $this->duelsA = $duelsA; } /** * @param Duel $duel */ public function addDuelA(Duel $duel) { if (!$this->duelsA->contains($duel)) { $this->duelsA[] = $duel; } } /** * @return mixed */ public function getDuelsB() { return $this->duelsB; } /** * @param mixed $duelB */ public function setDuelsB($duelB) { $this->duelsB = $duelB; } /** * @param Duel $duel */ public function addDuelB(Duel $duel) { if (!$this->duelsB->contains($duel)) { $this->duelsB[] = $duel; } } /** * @return Duel[] */ public function getDuels() { return array_merge($this->getDuelsA()->toArray(), $this->getDuelsB()->toArray()); } /** * @return array */ public function getDuelsWin() { $duels = $this->getDuels(); $duelsWin = []; foreach ($duels as $duel) { if ($duel->getPlayerA()->getId() === $this->getId() && $duel->getScoreA() > $duel->getScoreB()) { $duelsWin[] = $duel; } elseif ($duel->getPlayerB()->getId() === $this->getId() && $duel->getScoreB() > $duel->getScoreA()) { $duelsWin[] = $duel; } } return $duelsWin; } /** * @return array */ public function getDuelsLose() { $duels = $this->getDuels(); $duelsLose = []; foreach ($duels as $duel) { if ($duel->getPlayerA()->getId() === $this->getId() && $duel->getScoreA() < $duel->getScoreB()) { $duelsLose[] = $duel; } elseif ($duel->getPlayerB()->getId() === $this->getId() && $duel->getScoreB() < $duel->getScoreA()) { $duelsLose[] = $duel; } } return $duelsLose; } /** * @return array */ public function getDuelsEquality() { $duels = $this->getDuels(); $duelsEquality = []; foreach ($duels as $duel) { if ($duel->getScoreA() === $duel->getScoreB()) { $duelsEquality[] = $duel; } } return $duelsEquality; } /** * @return ArrayCollection */ public function getPlayerSeasonData(): ArrayCollection { return $this->playerSeasonData; } /** * @param ArrayCollection $playerSeasonData */ public function setPlayerSeasonData(ArrayCollection $playerSeasonData): void { $this->playerSeasonData = $playerSeasonData; } /** * @return mixed */ public function getUpdatedAt() { return $this->updated_at; } /** * @param mixed $updated_at */ public function setUpdatedAt($updated_at) { $this->updated_at = $updated_at; } /** * @return mixed */ public function getCreatedAt() { return $this->created_at; } /** * @param mixed $created_at */ public function setCreatedAt($created_at) { $this->created_at = $created_at; } /** * @ORM\PrePersist * @ORM\PreUpdate */ public function updatedTimestamps() { $this->setUpdatedAt(new \DateTime('now')); if ($this->getCreatedAt() == null) { $this->setCreatedAt(new \DateTime('now')); } } } <file_sep>/src/Service/Ranking.php <?php namespace App\Service; class Ranking { /** * @var int The K Factor used. */ const KFACTOR = 50; const WIN = 1; const DRAW = 0.5; const LOST = 0; /** * Protected & private variables. */ private $_ratingA; private $_ratingB; private $_scoreA; private $_scoreB; private $_expectedA; private $_expectedB; private $_newRatingA; private $_newRatingB; /** * Set new input data. * * @param int $ratingA Current rating of A * @param int $ratingB Current rating of B * @param int $scoreA Score of A * @param int $scoreB Score of B * @return array */ public function setNewSettings($ratingA, $ratingB, $scoreA, $scoreB) { $this->_ratingA = $ratingA; $this->_ratingB = $ratingB; $this->_scoreA = $scoreA; $this->_scoreB = $scoreB; $expectedScores = $this->getExpectedScores($this->_ratingA, $this->_ratingB); $this->_expectedA = $expectedScores['a']; $this->_expectedB = $expectedScores['b']; $newRatings = $this->getNewRatings($this->_ratingA, $this->_ratingB, $this->_expectedA, $this->_expectedB, $this->_scoreA, $this->_scoreB); $this->_newRatingA = $newRatings['a']; $this->_newRatingB = $newRatings['b']; return array ( 'ratingA' => $this->_newRatingA, 'diffA' => ($this->_newRatingA - $this->_ratingA), 'ratingB' => $this->_newRatingB, 'diffB' => ($this->_newRatingB - $this->_ratingB) ); } /** * @param int $ratingA The Rating of Player A * @param int $ratingB The Rating of Player B * @return array */ private function getExpectedScores($ratingA, $ratingB) { $expectedScoreA = 1 / (1 + ( pow( 10 , ($ratingB - $ratingA) / 400))); $expectedScoreB = 1 / (1 + ( pow( 10 , ($ratingA - $ratingB) / 400))); return array ( 'a' => $expectedScoreA, 'b' => $expectedScoreB ); } /** * @param int $ratingA The Rating of Player A * @param int $ratingB The Rating of Player A * @param int $expectedA The expected score of Player A * @param int $expectedB The expected score of Player B * @param int $scoreA The score of Player A * @param int $scoreB The score of Player B * @return array */ private function getNewRatings($ratingA, $ratingB, $expectedA, $expectedB, $scoreA, $scoreB) { $newRatingA = $ratingA + (self::KFACTOR * ($scoreA - $expectedA)); $newRatingB = $ratingB + (self::KFACTOR * ($scoreB - $expectedB)); return array ( 'a' => $newRatingA, 'b' => $newRatingB ); } }<file_sep>/webpack.config.js var Encore = require('@symfony/webpack-encore'); Encore // the project directory where compiled assets will be stored .setOutputPath('public/build/') // the public path used by the web server to access the previous directory .setPublicPath('/build') // will create public/build/main.js and public/build/main.css .addEntry('app', './assets/js/app.js') .enableVueLoader() // this creates a 'vendor.js' file with jquery and the bootstrap JS module // these modules will *not* be included in page1.js or page2.js anymore .createSharedEntry('vendor', [ 'jquery', 'bootstrap', 'bootstrap/scss/bootstrap.scss' ]) // allow sass/scss files to be processed .enableSassLoader(function(sassOptions) {}, { resolveUrlLoader: false }) // allow legacy applications to use $/jQuery as a global variable .autoProvidejQuery() .enableSourceMaps(!Encore.isProduction()) // empty the outputPath dir before each build .cleanupOutputBeforeBuild() // show OS notifications when builds finish/fail .enableBuildNotifications() // create hashed filenames (e.g. app.abc123.css) .enableVersioning() ; module.exports = Encore.getWebpackConfig(); <file_sep>/src/Controller/DefaultController.php <?php namespace App\Controller; use App\Entity\Duel; use App\Entity\Player; use App\Form\DuelType; use App\Service\Ranking; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; class DefaultController extends Controller { /** * @Route("/", name="index") * @param Request $request * @return \Symfony\Component\HttpFoundation\Response */ public function index(Request $request) { $players = $this->getDoctrine()->getRepository(Player::class)->findBy([], ['rank' => 'DESC']); $duels = $this->getDoctrine()->getRepository(Duel::class)->findBy([], ['created_at' => 'DESC'], 10); $duel = new Duel(); $formDuel = $this->createForm(DuelType::class, $duel); $formDuel->handleRequest($request); if ($formDuel->isSubmitted() && $formDuel->isValid()) { $scoreA = Ranking::DRAW; $scoreB = Ranking::DRAW; if ($duel->getScoreA() > $duel->getScoreB()) { $scoreA = Ranking::WIN; $scoreB = Ranking::LOST; } elseif ($duel->getScoreB() > $duel->getScoreA()) { $scoreA = Ranking::LOST; $scoreB = Ranking::WIN; } // Ranking $ranking = $this->get('App\Service\Ranking')->setNewSettings( $duel->getPlayerA()->getRank(), $duel->getPlayerB()->getRank(), $scoreA, $scoreB ); $duel->getPlayerA()->setRank($ranking['ratingA']); $duel->setRankA($ranking['diffA']); $duel->getPlayerB()->setRank($ranking['ratingB']); $duel->setRankB($ranking['diffB']); // Save $em = $this->getDoctrine()->getManager(); $em->persist($duel); $em->flush(); // Prevent refresh return $this->redirectToRoute('index'); } return $this->render('default/index.html.twig', [ 'players' => $players, 'duels' => $duels, 'formDuel' => $formDuel->createView() ]); } }<file_sep>/src/Repository/DuelRepository.php <?php namespace App\Repository; use App\Entity\Duel; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Symfony\Bridge\Doctrine\RegistryInterface; class DuelRepository extends ServiceEntityRepository { /** * DuelRepository constructor. * @param RegistryInterface $registry */ public function __construct(RegistryInterface $registry) { parent::__construct($registry, Duel::class); } } <file_sep>/src/Controller/SeasonController.php <?php namespace App\Controller; use App\Entity\PlayerSeasonData; use App\Entity\Season; use App\Entity\SeasonDuel; use Carbon\Carbon; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Translation\TranslatorInterface; /** * Fuck PSR-2 ! ;) * * @package */ class SeasonController extends Controller { /** * @Route("/saisons", name="season_index") * * @return \Symfony\Component\HttpFoundation\Response */ public function index() { return $this->render('season/index.html.twig', [ 'seasons' => $this->getDoctrine()->getRepository('App:Season')->findBy([], ['startAt' => 'DESC']), 'current_season' => $this->getDoctrine()->getRepository('App:Season')->findOneBy(['status' => Season::STATUS_IN_PROGRESS]), 'players' => $this->getDoctrine()->getRepository('App:Player')->findAll() ]); } /** * @Route("/saisons/{id}", requirements={ "id" : "\d+" }, name="season_show") * * @param $id * @return \Symfony\Component\HttpFoundation\Response */ public function show($id) { return $this->render('season/show.html.twig', [ 'current_season' => $this->getDoctrine()->getRepository('App:Season')->find($id) ]); } /** * @Route("/saisons/nouveau", name="season_create") * * @param TranslatorInterface $translator * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function create(TranslatorInterface $translator) { $em = $this->getDoctrine()->getManager(); $lastCreatedSeason = $em->getRepository('App:Season')->findOneBy([], ['startAt' => 'DESC']); $today = Carbon::now(); if ( null === $lastCreatedSeason || $today->greaterThan($lastCreatedSeason->getFinishAt()) || $today->format('m') === $lastCreatedSeason->getStartAt()->format('m') ) { $season = new Season(); $start = $today; if ( null !== $lastCreatedSeason && $today->format('m') === $lastCreatedSeason->getStartAt()->format('m') ) { $start->addMonth(); } $start->day = 1; $start->setTime(0,0, 0, 0); $season->setStartAt($start); $finish = clone $start; $finish->endOfMonth(); $finish->setTime(23,59, 59); $season->setFinishAt($finish); $em->persist($season); $em->flush(); $this->addFlash('success', "La saison du mois de ".$translator->trans($start->format('F'))." a été ajoutée."); } else { $this->addFlash('danger', "Vous ne pouvez pas ajouter d'autres saisons pour le moment."); } return $this->redirectToRoute('season_index'); } /** * @Route("/saison/inscription", name="season_player_register") * * @param Request $request * @param TranslatorInterface $translator * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function registerPlayer(Request $request, TranslatorInterface $translator) { $em = $this->getDoctrine()->getManager(); $season = $em->getRepository('App:Season')->find($request->query->get('season')); $player = $em->getRepository('App:Player')->find($request->query->get('player')); if (!$season->hasPlayer($player)) { $playerSeasonData = new PlayerSeasonData(); $playerSeasonData->setSeason($season); $playerSeasonData->setPlayer($player); $em->persist($playerSeasonData); foreach ($season->getPlayerSeasonData() as $seasonDatum) { for ($i = 0; $i < 2; $i++) { $seasonDuel = new SeasonDuel(); $seasonDuel->setSeason($season); if ($i % 2 === 0) { $seasonDuel->setPlayerSeasonDataA($playerSeasonData); $seasonDuel->setPlayerSeasonDataB($seasonDatum); } else { $seasonDuel->setPlayerSeasonDataA($seasonDatum); $seasonDuel->setPlayerSeasonDataB($playerSeasonData); } $em->persist($seasonDuel); } } $em->flush(); $this->addFlash('success', 'Vous êtes maintenant inscrit à la saison : ' . $translator->trans($season->getStartAt()->format('F'))); } else { $this->addFlash('danger', 'Vous êtes déjà inscrit à cette saison.'); } return $this->redirectToRoute('season_index'); } /** * @Route("/saisons/commencer/{id}", requirements={ "id" : "\d+" }, name="season_start") * * @param TranslatorInterface $translator * @param $id * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function startSeason(TranslatorInterface $translator, $id) { $em = $this->getDoctrine()->getManager(); $season = $em->getRepository('App:Season')->find($id); $today = new \DateTime(); if ($today->format('m') === $season->getStartAt()->format('m')) { $season->setStatus(Season::STATUS_IN_PROGRESS); $em->persist($season); $em->flush(); $this->addFlash('success', 'La saison ' . $translator->trans($season->getStartAt()->format('F')) . ' a commencé.'); } else { $this->addFlash('danger', 'Cette saison ne peut pas commencer.'); } return $this->redirectToRoute('season_index'); } /** * @Route("/saisons/matches/score/{id}", requirements={ "id" : "\d+" }, name="season_save_duel_score") * * @param Request $request * @param $id * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function saveScore(Request $request, $id) { if ("" !== $request->query->get('score-a') && "" !== $request->query->get('score-b')) { $em = $this->getDoctrine()->getManager(); $duel = $em->getRepository('App:SeasonDuel')->find($id); $duel->setScoreA($request->query->get('score-a')); $duel->setScoreB($request->query->get('score-b')); $em->persist($duel); $playerA = $duel->getPlayerSeasonDataA(); $playerB = $duel->getPlayerSeasonDataB(); $playerA->setDuelPlayed($playerA->getDuelPlayed() + 1); $playerB->setDuelPlayed($playerB->getDuelPlayed() + 1); if ((int) $request->query->get('score-a') > (int) $request->query->get('score-b')) { $playerA->setDuelWin($playerA->getDuelWin() + 1); $playerA->setRank($playerA->getRank() + 3); $playerB->setDuelLoose($playerB->getDuelLoose() + 1); } elseif ((int) $request->query->get('score-a') < (int) $request->query->get('score-b')) { $playerA->setDuelLoose($playerA->getDuelLoose() + 1); $playerB->setDuelWin($playerB->getDuelWin() + 1); $playerB->setRank($playerB->getRank() + 3); } else { $playerA->setDuelNull($playerA->getDuelNull() + 1); $playerA->setRank($playerA->getRank() + 1); $playerB->setDuelNull($playerB->getDuelNull() + 1); $playerB->setRank($playerB->getRank() + 1); } $em->persist($playerA); $em->persist($playerB); $em->flush(); $this->addFlash('success', 'Les scores ont été enregistrés'); } else { $this->addFlash('danger', 'Les scores n\'ont pas pu être enregistrés'); } return $this->redirectToRoute('season_index'); } /** * @Route("/saisons/terminer/{id}", requirements={ "id" : "\d+" }, name="season_end") * * @param $id * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function endSeason($id) { $em = $this->getDoctrine()->getManager(); $season = $em->getRepository('App:Season')->find($id); $season->setStatus(Season::STATUS_COMPLETED); $em->persist($season); $em->flush(); return $this->redirectToRoute('season_index'); } }<file_sep>/src/Entity/SeasonDuel.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\SeasonDuelRepository") */ class SeasonDuel { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @var Season * * @ORM\ManyToOne(targetEntity="App\Entity\Season", inversedBy="duels") */ private $season; /** * @var PlayerSeasonData * * @ORM\ManyToOne(targetEntity="App\Entity\PlayerSeasonData", inversedBy="duelsA") */ private $playerSeasonDataA; /** * @var PlayerSeasonData * * @ORM\ManyToOne(targetEntity="App\Entity\PlayerSeasonData", inversedBy="duelsB") */ private $playerSeasonDataB; /** * @var integer * * @ORM\Column(type="smallint", nullable=true) */ private $scoreA; /** * @var integer * * @ORM\Column(type="smallint", nullable=true) */ private $scoreB; /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id): void { $this->id = $id; } /** * @return Season */ public function getSeason(): Season { return $this->season; } /** * @param Season $season */ public function setSeason(Season $season): void { $this->season = $season; } /** * @return PlayerSeasonData */ public function getPlayerSeasonDataA(): PlayerSeasonData { return $this->playerSeasonDataA; } /** * @param PlayerSeasonData $playerSeasonDataA */ public function setPlayerSeasonDataA(PlayerSeasonData $playerSeasonDataA): void { $this->playerSeasonDataA = $playerSeasonDataA; } /** * @return PlayerSeasonData */ public function getPlayerSeasonDataB(): PlayerSeasonData { return $this->playerSeasonDataB; } /** * @param PlayerSeasonData $playerSeasonDataB */ public function setPlayerSeasonDataB(PlayerSeasonData $playerSeasonDataB): void { $this->playerSeasonDataB = $playerSeasonDataB; } /** * @return int */ public function getScoreA() { return $this->scoreA; } /** * @param int $scoreA */ public function setScoreA(int $scoreA): void { $this->scoreA = $scoreA; } /** * @return int */ public function getScoreB() { return $this->scoreB; } /** * @param int $scoreB */ public function setScoreB(int $scoreB): void { $this->scoreB = $scoreB; } } <file_sep>/src/Entity/Duel.php <?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity(repositoryClass="App\Repository\DuelRepository") * @ORM\HasLifecycleCallbacks() */ class Duel { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\ManyToOne(targetEntity="App\Entity\Player", inversedBy="duels", cascade={"persist"}) * @ORM\JoinColumn(nullable=true) * @Assert\NotBlank() */ private $playerA; /** * @ORM\ManyToOne(targetEntity="App\Entity\Player", inversedBy="duels", cascade={"persist"}) * @ORM\JoinColumn(nullable=true) * @Assert\NotBlank() */ private $playerB; /** * @ORM\Column(type="integer") * @Assert\NotBlank() * @Assert\GreaterThanOrEqual(0) */ private $scoreA; /** * @ORM\Column(type="integer") * @Assert\NotBlank() * @Assert\GreaterThanOrEqual(0) */ private $scoreB; /** * @ORM\Column(type="integer") */ private $rankA; /** * @ORM\Column(type="integer") */ private $rankB; /** * @ORM\Column(type="datetime") */ private $updated_at; /** * @ORM\Column(type="datetime") */ private $created_at; /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id */ public function setId($id) { $this->id = $id; } /** * @return mixed */ public function getPlayerA() { return $this->playerA; } /** * @param mixed $playerA */ public function setPlayerA($playerA) { $this->playerA = $playerA; } /** * @return mixed */ public function getPlayerB() { return $this->playerB; } /** * @param mixed $playerB */ public function setPlayerB($playerB) { $this->playerB = $playerB; } /** * @return mixed */ public function getScoreA() { return $this->scoreA; } /** * @param mixed $scoreA */ public function setScoreA($scoreA) { $this->scoreA = $scoreA; } /** * @return mixed */ public function getScoreB() { return $this->scoreB; } /** * @param mixed $scoreB */ public function setScoreB($scoreB) { $this->scoreB = $scoreB; } /** * @return mixed */ public function getRankA() { return $this->rankA; } /** * @param mixed $rankA */ public function setRankA($rankA) { $this->rankA = $rankA; } /** * @return mixed */ public function getRankB() { return $this->rankB; } /** * @param mixed $rankB */ public function setRankB($rankB) { $this->rankB = $rankB; } /** * @return mixed */ public function getUpdatedAt() { return $this->updated_at; } /** * @param mixed $updated_at */ public function setUpdatedAt($updated_at) { $this->updated_at = $updated_at; } /** * @return mixed */ public function getCreatedAt() { return $this->created_at; } /** * @param mixed $created_at */ public function setCreatedAt($created_at) { $this->created_at = $created_at; } /** * @ORM\PrePersist * @ORM\PreUpdate */ public function updatedTimestamps() { $this->setUpdatedAt(new \DateTime('now')); if ($this->getCreatedAt() == null) { $this->setCreatedAt(new \DateTime('now')); } } }
dd6e0fbf0d2f181e66f464c5c539476e9883cd15
[ "JavaScript", "PHP" ]
10
PHP
aurelien-w/games
9fce378177b3f3db94860a327108c388f0893ef6
742907fbfc44abc355e391d58367cb867ec64a70
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { User } from 'firebase'; import {AngularFireAuth } from '@angular/fire/auth'; import { first } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AuthService { public user:User; constructor(public afAuth: AngularFireAuth) { } async login(email:string, password:string){ try{ const result = await this.afAuth.auth.signInWithEmailAndPassword( email, password ); return result; }catch (error) { console.log(error); } } async register(email:string,password:string){ try{ const result = await this.afAuth.auth.createUserWithEmailAndPassword( email, password ); return result; }catch(error){console.log(error)} } async logout(){ try{ await this.afAuth.auth.signOut(); }catch(error){ console.log(error); } } getCurrentUser(){ return this.afAuth.authState.pipe(first()).toPromise(); } } <file_sep>Descripción *************************** Este es la documentación de unproyecto realizado en angular 10 Contenido =========================== 1. Descripción 2. Desario 1 3. Desafio 2 4. Desafio 4 <file_sep>import { TestBed } from '@angular/core/testing'; import { MunicipiosColombiaService } from './municipios-colombia.service'; describe('MunicipiosColombiaService', () => { let service: MunicipiosColombiaService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(MunicipiosColombiaService); }); it('should be created', () => { expect(service).toBeTruthy(); }); }); <file_sep>********* Registro ********* 1. Descripción En este componente se debe mostrar todos los registros almacenados en la base de datos. 2. Importaciones Para este componente de debe importar el servicio a la base de datos, el servicio para la autentificación de usuarios y el servicio a una API para obtener los municipios y departamentos de Colombia. :: import { RegistrosService } from 'src/app/services/registros.service'; import { AngularFireAuth } from '@angular/fire/auth'; import {MunicipiosColombiaService} from 'src/app/services/municipios-colombia.service' También se importan componentes de Angular Material para la implementación de ventana emergente o modal y de se importa el componente Router para un redireccionamiento al concluir el registro. :: import { MatDialog, MatDialogConfig } from '@angular/material/dialog'; import { DialogComponent } from '../dialog/dialog.component'; import { Router } from '@angular/router'; 3. Desarrollo El constructor se inyectan todos los objetos a necesarios para el desarrollo del componente. :: private afAuth: AngularFireAuth, private registrosServiceF : RegistrosService, private municipiosService:MunicipiosColombiaService, private matDialog: MatDialog, private router:Router, private fb:FormBuilder Para la captura de datos se emplea los formularios reactivos, para ello se declara un objeto de la clase FormGroup y se inicializa creando un FormControl para cada campo requerido, declarando su estado y sus respectivo valida daciones. :: this.registerForm= this.fb.group({ photoUrl: new FormControl(''), cedula: new FormControl('', [Validators.required, this.validarCedula]), . . . descripcion: new FormControl('', [Validators.required]), }) En el método ngOnInit se realiza la obtención de todos los registros almacenados en la base de datos con el fin de realizar validaciones con dichos datos, estos datos son almacenados en un array. :: this.registrosServiceF.getRegistros().subscribe((rgSnapshot) => { this.listaRegistros = []; rgSnapshot.forEach((rgData: any) => { this.listaRegistros.push({ id: rgData.payload.doc.id, data: rgData.payload.doc.data() }); }) }); En el mismo método se obtienen los datos de la API sobre los municipios y departamentos de Colombia y se asignan en un array. :: this.municipiosService.getDatos().subscribe(datos =>{ // Se almacenan los municipios this.datosMunicipios=datos.map(data=> data.municipio); // Se almacenan los departamentos this.datosDepartamentos=datos.map(data=> data.departamento); // Se elimina los departamentos repetidos let NuevosDatosDepartamentos:string[]=[]; for (let posicion = 0; posicion < this.datosDepartamentos.length; posicion++) { const element = this.datosDepartamentos[posicion]; if(posicion==0) { NuevosDatosDepartamentos.push(element.toString()); } else{ if(NuevosDatosDepartamentos.includes(element.toString())==false) { NuevosDatosDepartamentos.push(element.toString()); } } } En el método ngOnInit también se declara un array observador para municipio y otro para departamento encargado del filtrado en el componente html. :: this.filteredMunicipios = this.registerForm.controls.ciudad.valueChanges .pipe( startWith(''), map(value => this._filterMunicipios(value)) ); this.filteredDepartamentos = this.registerForm.controls.departamento.valueChanges .pipe( startWith(''), map(value => this._filterDepartamentos(value)) ); Al mismo tiempo se realiza a los métodos que devuelve un array con las filtraciones realizadas :: _filterMunicipios(value: string): string[] { const filterValue = value.toLowerCase(); return this.datosMunicipios.filter(option => option.toLowerCase().includes(filterValue)); } _filterDepartamentos(value: string): string[] { const filterValue = value.toLowerCase(); return this.datosDepartamentos.filter(option => option.toLowerCase().includes(filterValue)); } Cada campo del formulario tiene su respectivo control y todos son requeridos, ahora hay campos especiales que requieren validaciones personalizadas empezando por el campo del numero de cedula el cual no debe estar registrado con anterioridad en la base de datos. En la declaración del control de para el campo de cedula se añade su validador personalizado :: cedula: new FormControl('', [Validators.required, this.validarCedula]), Para la validación personalizada se crea el siguiente método. :: private validarCedula: ValidatorFn =(control: AbstractControl): ValidationErrors | null => { const cedula = control.value; let respuesta= null; if (this.ValidarExistenciaCedula(cedula)==true) { return{ ms: 'para otro forma de error' }; } return null; } Internamente este método llama a otro método encargado de revisar si la cedula ya existe en los registros obtenidos de la base de datos. :: ValidarExistenciaCedula(cedulaIn: string): boolean { let existeCedula: boolean = false; let respuesta: boolean = true; // Se compara la cedula ingresada con la cedula de cada registro for (let i = 0; i < this.listaRegistros.length; i++) { const element = this.listaRegistros[i]; const { cedula } = element.data; if (cedulaIn == cedula) { existeCedula = true; } } if (existeCedula == true) { respuesta = true; } else { respuesta = false; } return respuesta; } Cuando hay la validación verifica la existencia de la cedula ingresada en los registros de la base de datos, el formulario informa inmediatamente al usuario que hay un erro mediante el uso de formularios reactivos y la sincronización entre la vista y el controlador. Campo de Cedula en el HTML :: <mat-form-field appearance="outline"> <mat-label>Número de cédula</mat-label> <input matInput type="number" formControlName="cedula"> <mat-error *ngIf="registerForm.controls.cedula.errors">{{errorCedula()}}</mat-error> </mat-form-field> Método encargado de informar el tipo de error. :: errorCedula() { if (this.registerForm.controls.cedula.hasError('required')) { return 'Ingrese un número de cédula'; } if (this.registerForm.controls.cedula.hasError('ms')) { return 'El número de cedula ya ha sido registrado'; } } El mismo comportamiento presenta el campo de Email. Declaración del control email con su validador personalizado :: email: new FormControl('', [Validators.required, Validators.email, this.validarEmail]), Metodo para la validación personalizada. :: private validarEmail: ValidatorFn =(control: AbstractControl): ValidationErrors | null => { const email = control.value; let respuesta= null; if (this.ValidarExistenciaCorreo(email)==true) { return{ ms: 'para otro forma de error' }; } return null; } Método encargado de revisar si el email ya existe en los registros obtenidos de la base de datos. :: ValidarExistenciaCorreo(correo: string): boolean { let existeCorreo: boolean = false; let respuesta: boolean = true; // Se compara el correo ingresado con el email de cada registro for (let i = 0; i < this.listaRegistros.length; i++) { const element = this.listaRegistros[i]; const { email } = element.data; if (correo == email) { existeCorreo = true; } } if (existeCorreo == true) { respuesta = true; } else { respuesta = false; } return respuesta; } Campo de Email en el HTML :: <mat-form-field appearance="outline"> <mat-label>E-mail</mat-label> <input matInput placeholder="<EMAIL>" formControlName="email" required> <mat-error *ngIf="registerForm.controls.email.errors">{{errorEmail()}}</mat-error> </mat-form-field > Método encargado de informar el tipo de error :: errorEmail() { if (this.registerForm.controls.email.hasError('required')) { return 'Debe ingresar un email'; } if (this.registerForm.controls.email.hasError('ms')) { return 'El email ya ha sido registrado'; } return this.registerForm.controls.email.hasError('email') ? 'Email no válido' : ''; } Otro de los campos con funciones especiales son los de municipio y departamento que emplean un filtro de autocompletado y su estructura en HTML es el siguiente aplicable para los dos casos cambiando su contenido. :: <mat-form-field appearance="outline"> <mat-label>Ciudad</mat-label> <input type="text" aria-label="Number" matInput formControlName="ciudad" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let municipio of filteredMunicipios | async" [value]="municipio"> {{municipio}} </mat-option> </mat-autocomplete> <mat-error *ngIf="registerForm.controls.ciudad.invalid">Ingrese una ciudad</mat-error> </mat-form-field> El formulario incluía una sesión donde se debía ingresar de 1 a 3 habilidades mediante checkbox, para ello se declaró e inicializo un array con las habilidades preestablecida y un contador de habilidades. :: listaHabi: any = [ { id: 1, name: 'Autoconocimiento' }, { id: 2, name: 'Empatía' }, { id: 3, name: 'Comunicación asertiva' }, { id: 4, name: 'Pensamiento crítico' }, { id: 5, name: 'Toma de decisiones' }, { id: 6, name: 'Adaptación' }, { id: 7, name: 'Comunicación' }, { id: 8, name: 'Trabajo en equipo' }, { id: 9, name: 'Capacidad de asociación' }, { id: 10, name: 'Razonamiento' }, ]; nHabilidaddes:number=0; Para el control y majeo de los checkbox se creó un formGoup con un array de forms :: checkboxForm = new FormGroup({ habiForm: new FormArray([], Validators.required) }); El campo de los checkbox en el HTML es el siguiente. :: <form [formGroup]="checkboxForm"> <table id="tbl-habilidades"> <section class="section"> <ul > <li *ngFor="let hab of listaHabi"> < mat-checkbox class="example-margin" [value]="hab.name" (change)="onCheckboxChange($event)">{{hab.name}}</mat-checkbox> </li> </ul> </section> </table> <p></p> </form> Cada vez que un checkbox sea seleccionado o cambie su estado se ejecuta el siguiente método que obtiene el array de forms y se comprueba si ha sido seleccionado y el contador de habilidades esta en el rango entre 1 y 3 se suma el formContro al array de forms y se suma el contador de habilidades, si contador de habilidades llega al límite entonces si el checkbox seleccionado es des marcado se elimina ese formControl del array de forms de lo contrario no permitirá seleccionar más checkbox. Si el contador de habilidades vuelve a ser 0 por deseleccionar todas las habilidades el fromControl principal es limpiado y actualizado su validador de requerido inhabilitando el botón de enviar el formulario. :: onCheckboxChange(e) { const habiForm: FormArray = this.checkboxForm.get('habiForm') as FormArray; //si lo chuliaron agrega al array siempre que numero de habilidades sea menor 3 if (e.checked && this.nHabilidaddes<=2) { habiForm.push(new FormControl(e.source.value)); this.nHabilidaddes++; //metodo que actuliza las habilidades con el formControl principal this.validarHabilidades(); } else { //si numero la habilidad se desmarca elimina habilidad if(e.checked==false) { const index = habiForm.controls.findIndex(x => x.value === e.source.value); habiForm.removeAt(index); //metodo que actuliza las habilidades con el formControl principal this.validarHabilidades(); this.nHabilidaddes--; } //si numero de habilidades esta al limite (3) no agrega nada y no permite chulear else{ e.source._checked=false; } } //si no hay habilidades selecionadas no habilita el boton de registrarse if(this.nHabilidaddes==0) { //restauro el formControl principal, limpiandolo, agregando el validador y actualizandolo this.registerForm.controls.habilidades.setValue([]); this.registerForm.controls.habilidades.setValidators([Validators.required]); this.registerForm.controls.habilidades.updateValueAndValidity(); } //console.log(this.registerForm.controls.habilidades.value); } El método validarHabilidades() llamado internamente cuando un checkbox cambia su estado es el encargado de obtener el valor de la habilidad y asignarlo al formControl principal de habilidades del cual se tomara su valor parar registrarlo en la base de datos. :: validarHabilidades(){ //obtengo los valores de FormGroup const ob = this.checkboxForm.value; //obtengo el array habForm de ob ostenido de FormGroup const { habiForm } = ob; //para almacenar las habilidades let habilidadesIn: string = ''; for (let i = 0; i < habiForm.length; i++) { habilidadesIn += habiForm[i] + " / "; } //asigno las habilidaesIn al valor del formcontrol habilidaes para que lo registre en la bd this.registerForm.controls.habilidades.setValue([habilidadesIn]); } Para registrar en la base de datos se emplea el siguiente método donde hace otra verificación sobre la cedula y el email que es redundante dado que ya se validó, se le asigna una foto al formControl photoUrl por defecto para su perfil y se procede a realizar el registro en la base de datos, también se muestra un modal agradeciendo el registro y se redirige a la vista de inicio. Al momento hacer el registro también se crea un usuario en el sistema mediante su email, siendo este de email y contraseña con el cual tendrá acceso al sistema. :: public onRegister(form, documentId = this.documentId) { //verifica el resultado del metodo verificar existencia de correo if (this.ValidarExistenciaCorreo(this.registerForm.get('email').value) == false && this.ValidarExistenciaCedula(this.registerForm.get('cedula').value) == false ) { // se le asigan una foto por defecto this.registerForm.controls.photoUrl.setValue("https://firebasestorage.googleapis.com/v0/b/teamdc-c1083.appspot.com/o/uploads%2FLogo.png?alt=media&token=<PASSWORD>"); // se realiza el registro en la bd this.registrosServiceF.crearRegistro(this.registerForm.value).then(() => { //se presenta un modal const data={mensaje:'Gracias por registrarte'}; this.openDialog(data); //se redirige a la pagina home this.router.navigate(['/home']); }, (error) => { console.error(error); }); const result= this.afAuth.auth.createUserWithEmailAndPassword( this.registerForm.controls.email.value, this.registerForm.controls.email.value); } }| <file_sep>.. DCTEAM documentation master file, created by sphinx-quickstart on Tue Sep 1 15:04:31 2020. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Bienvenido a la documentación de DCTEAM! ========================================= Contenido ==================== .. toctree:: :maxdepth: 2 descripcion home login mi Perfil registro registros video Descripción *************************** TEAM DC es una plataforma web responsiva de tipo dashboard, con varias secciones. La plataforma permite a los usuarios registrarse y acceder a todas los módulos de la plataforma. En la sección mi perfil se visuliza la información del usuario, permitiendo que se editen estos datos y agregar una foto de usuario. La seccion de registros muestra información de todos los usuarios registrados. Framework ------------------------------ El proyecto es desarrollado en el framework Angular creado por Google. La finalidad de Angular es facilitar el desarrollo de aplicaciones web SPA y además dar herramientas para trabajar con los elementos de una web de una manera más sencilla y óptima. Lenguaje de programación ------------------------------------------- El proyecto es desarrollado en el lenguaje TypeScript. Es un lenguaje de programación libre y de código abierto desarrollado y mantenido por Microsoft. Es un superconjunto de JavaScript, que esencialmente añade tipos estáticos y objetos basados en clases. Estilos -------------------------------- Se trabajó con el lenguaje de etiquetas HTML con el que se define el contenido de las páginas web. Para dar estilo se usó SCSS y la librería de estilos Angular Material. .. sphinx-build -b html source build <file_sep>********* Mi perfil ********* 1. Descripción Este componente contiene un formulario en donde se muestra la información del usuario logueado, permite mediante un botón acceder al mismo y editar algunos campos, ademas permite subir una imagen de perfil. del proyecto. 2. Importaciones Para este componente de debe importar el servicio de registros y de municipios, y el fireAuth de firebase. :: import { AngularFireAuth } from '@angular/fire/auth'; import { RegistrosService } from 'src/app/services/registros.service'; import { MunicipiosColombiaService } from 'src/app/services/municipios-colombia.service'; También se importa el servicio de storage de firebase, para mantener la imagen que se sube. :: import { AngularFireStorage } from '@angular/fire/storage'; import { finalize } from 'rxjs/operators'; Además se hacen las importaciones del formulario y sus validadores. :: import { FormBuilder, FormGroup, Validators, FormControl, FormArray, ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms'; 3. Desarrollo En el constructor se inyectan todos los objetos necesarios para el desarrollo del componente. Para manejar el estado de la sesion :: private afAuth: AngularFireAuth Para la conexion con la BD :: private registroService:RegistrosService Para el formulario :: private fb:FormBuilder, El servicio encargado de municipios de colombia :: private municipiosService:MunicipiosColombiaService, Para subir la imagen al storage de firebase :: private storage:AngularFireStorage Se crea el método para subir la imagen al storage de firebase, condicionando que solo se permite subir imágenes png o jpg y que no superen el tamaño de un MB. Además de los metodos que permiten asociar la información del usario logueado y mostrarla en el perfil. Cuenta con un botón de editar que habilita los campos del formulario para hacer la respectiva edición. Y un botón de guardar para enviar los nuevos cambios a la base de datos. <file_sep>.. DCTEAM documentation master file, created by sphinx-quickstart on Tue Sep 1 15:04:31 2020. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Bienvenido a la documentación de DCTEAM! ========================================= Descripción *************************** Este es la documentación de unproyecto realizado en angular 10 1. Descripción 2. Desario 1 3. Desafio 2 4. Desafio 4 .. toctree:: :maxdepth: 2 :caption: Contents: descripcion home login mi Perfil registro registros video .. Indices and tables ================== * :ref:`genindex` * :ref:`home` * :ref:`search` .. sphinx-build -b html source build <file_sep>import { Component } from '@angular/core'; import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout'; import { Observable } from 'rxjs'; import { map, shareReplay } from 'rxjs/operators'; import { AuthService } from '../../services/auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-sidenav', templateUrl: './sidenav.component.html', styleUrls: ['./sidenav.component.scss'], }) export class SidenavComponent { //puntos de quiebre del tamaño de la pantalla isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset) .pipe( map(result => result.matches), shareReplay() ); //estado del usuario public user$: Observable<any> = this.authSvc.afAuth.user; constructor(private breakpointObserver: BreakpointObserver, private authSvc: AuthService, private router: Router,) { } public isLogged: boolean= false; //método para salir async onLogout(){ try{ await this.authSvc.logout(); this.router.navigate(['/login']); } catch(error){console.log(error)} } //método para validar si el usuario esta logueado o no onCheckUser():void { if (this.authSvc.getCurrentUser()==null) { this.isLogged=false; } else { this.isLogged=true; } } } <file_sep>********* Iniciar Sesión ********* 1. Descripción Este componente es un formulario para dar ingreso a los usuarios registrados a todas las secciones del proyecto. 2. Importaciones Para este componente de debe importar el servicio de autenticación y de registros, y el fireAuth de firebase. :: import { AuthService } from '../../services/auth.service'; import { RegistrosService } from 'src/app/services/registros.service'; import { AngularFireAuth } from '@angular/fire/auth'; También se importan componentes de Angular Material para la implementación de ventana emergente o modal y de se importa el componente Router para el redireccionamiento :: import { MatDialogConfig, MatDialog } from '@angular/material/dialog'; import { DialogComponent } from '../dialog/dialog.component'; import { Router } from '@angular/router'; Además se hacen las importaciones del formulario y sus validadores. :: import { FormControl, FormGroup, Validators, } from '@angular/forms'; 3. Desarrollo El constructor se inyectan todos los objetos a necesarios para el desarrollo del componente. :: private authSvc:AuthService, private router: Router, private registroService:RegistrosService, private matDialog: MatDialog, public afAuth: AngularFireAuth Para el inicio de sesión se verifica que el correo ya se encuentre registrado en la base de datos. :: this.ValidarExistenciaCorreo(this.loginForm.controls.email.value)==true Al realizar esta verificación se muestra un modal si el usuario no está en la base de datos. Si el usuario esta registrado, permite ingresar al sistema, redirigiendolo a la página de inicio. <file_sep>********* Registros ********* 1. Descripción En este componente se debe realizar el registro de cada nuevo usuario, donde el usuario debe ingresar una serie de datos necesaria para su registro. 2. Importaciones Para este componente de debe importar MatTableDataSource para la tabulación de los datos. :: import { MatTableDataSource } from '@angular/material/table';. También se importa el servicio con el cual se establece la conexión con la base de datos. :: import { RegistrosService } from 'src/app/services/registros.service';. 3. Desarrollo Se declara y se inicializa un array con los nombres de las columnas a mostrar. :: displayedColumns: string[] = ['nombres',...,'descripcion'];. Se declara una un objeto de la clase que importamos. :: dataSource = new MatTableDataSource();. En el constructor se inyecta el servicio. :: private registroService:RegistrosService En el método ngOnInit se obtienen todos los datos de la base de datos y se los asigna al objeto dataSource. :: this.registroService.getAllUser().subscribe(res => this.dataSource.data=res);. <file_sep>//RegistrosI la I de interfaces export interface RegistrosI{ photoUrl?: string; nombres: string; apellidos: string; cedula: number; email: string; fechaNacimiento: string; direccion: string; ciudad: string; departamento: string; pais:string; codigoPostal:string; profesion: string; habilidades: string; descripcion:string; } export interface ContactosI{ nombresCompleto: string; email: string; motivo: string; mensaje: string; } <file_sep>export const environment = { production: true, firebaseConfig: { apiKey: "<KEY>", authDomain: "teamdc-c1083.firebaseapp.com", databaseURL: "https://teamdc-c1083.firebaseio.com", projectId: "teamdc-c1083", storageBucket: "teamdc-c1083.appspot.com", messagingSenderId: "487516474484", appId: "1:487516474484:web:3514ec6d1e078126195521" } }; <file_sep>import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; // servicio para el manejo de la bd de contactos import {ContactosService} from 'src/app/services/contactos.service' // para el manejo de enviar email del nuevo contacto import 'src/assets/smtp.js'; declare let Email: any; @Component({ selector: 'app-contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.scss'] }) export class ContactComponent implements OnInit { //para el formGroup contactForm: FormGroup; listaContactos; // para la validacion del email emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$"; // para el selecionar el motivo motivos= [ {value: 'Contratos' }, {value: 'Proyectos'}, {value: 'Cobranzas'} ]; motivoSeleccionado:string; constructor( //para el formulario private fb:FormBuilder, //para el servicio private contactosService:ContactosService, ) { this.contactForm= this.fb.group({ nombreCompleto: new FormControl('', [Validators.required]), email: new FormControl('', [Validators.required, Validators.required, Validators.pattern(this.emailPattern), /*this.validarEmail*/]), motivo: new FormControl('', [Validators.required]), mensaje: new FormControl('', [Validators.required]), }); } ngOnInit(): void { //limpiar campos this.contactForm.setValue({ nombreCompleto: '', email: '', motivo: '', mensaje: '' }); this.getRegistros(); } getRegistros(){ this.contactosService.getContactos().subscribe((rgSnapshot) => { this.listaContactos = []; rgSnapshot.forEach((rgData: any) => { this.listaContactos.push({ id: rgData.payload.doc.id, data: rgData.payload.doc.data() }); }) console.log(this.listaContactos); }); } //metodo para informar errores en el campo de email errorEmail() { if (this.contactForm.controls.email.hasError('required')) { return 'Debe ingresar un email'; } if (this.contactForm.controls.email.hasError('ms')) { return 'El email ya ha sido registrado'; } return this.contactForm.controls.email.hasError('pattern') ? 'Email no válido' : ''; } //metodo para registrar un nuevo contacto oncreate(form){ //contraseña <PASSWORD> this.contactosService.crearContacto(this.contactForm.value).then(() => { //toco importar en el archivo angular.json ln 34 y 99 //"scripts": ["src/assets/smtp.js"] //tomado de https://medium.com/javascript-in-plain-english/send-emails-without-a-server-side-code-with-angular-e<PASSWORD> Email.send({ Host : 'smtp.elasticemail.com', Username : '<EMAIL>', Password : '<PASSWORD>', To : '<EMAIL>',//<EMAIL> From : '<EMAIL>', Subject : 'Dc Team Nuevo contacto', Body : ` <h1> Nuevo registro de Contacto</h1> <p></p> <h3> Nombre: ${this.contactForm.controls.nombreCompleto.value}</h3> <h3> Correo: ${this.contactForm.controls.email.value}</h3> <h3> Motivo: ${this.contactForm.controls.motivo.value}</h3> <h3> Mensaje</h3> <p>${this.contactForm.controls.mensaje.value}</p> ` }).then( message => { alert(message); } ); this.contactForm.setValue({ nombreCompleto: '', email: '', motivo: '', mensaje: '' }); }, (error) => { console.error(error); }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { RegistrosI } from '../../models/registros.interface'; import { MatTableDataSource } from '@angular/material/table'; //paso 1. Importar service import { RegistrosService } from 'src/app/services/registros.service'; @Component({ selector: 'app-records', templateUrl: './records.component.html', styleUrls: ['./records.component.scss'] }) export class RecordsComponent implements OnInit { //nombre de las columnas de la tabla displayedColumns: string[] = ['nombres', 'apellidos', 'cedula','email','fechaNacimiento', 'direccion','ciudad','departamento','pais','codigoPostal','profesion','habilidades', 'descripcion']; dataSource = new MatTableDataSource(); //paso 2. Inyectar service constructor(private registroService:RegistrosService) { } ngOnInit(): void { this.registroService.getAllUser().subscribe(res => this.dataSource.data=res); } //1.Importar Service //2.Inyectar Service //3. Utilizar } <file_sep>Página de Inicio ============================ Descripción ---------------------------- En esta sección se muestra información de los desarrolladores. Importaciones ---------------------------- Para este componente se debe importar el módulo de Angular Material denominado MatCard para las tarjetas de cada integrante del equipo. import { MatCardModule } from '@angular/material/card'; Desarrollo ---------------------------- El MatCard permite agregar una imagen y un texto en este caso los datos del desarrollador. <file_sep>********* Página de inicio ********* 1. Descripción En este componente se debe mostrar los desarrolladores del proyecto 2. Importaciones Para este componente no se requieren importaciones pues trabaja mas la parte front. Es una visualización de tarjetas. 3. Desarrollo Las card encapsulan los textos y las imagenes para dar una mejor vista de la página. <file_sep>import { Component, OnInit } from '@angular/core'; import { FormControl, Validators, FormGroup, FormArray, AbstractControl, FormBuilder, ValidatorFn, ValidationErrors } from '@angular/forms'; //Importar servicio encargada de ls bd import { RegistrosService } from 'src/app/services/registros.service'; //para el loguin import { AngularFireAuth } from '@angular/fire/auth'; //Importar servici encargada de los municipios de colombia import {MunicipiosColombiaService} from 'src/app/services/municipios-colombia.service' //para el manejo del modal import { MatDialog, MatDialogConfig } from '@angular/material/dialog'; import { DialogComponent } from '../dialog/dialog.component'; import {map, startWith} from 'rxjs/operators'; import {Observable} from 'rxjs'; import { Router } from '@angular/router'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'], }) export class RegisterComponent implements OnInit { //donde se van a almacenar los registros de la bd public listaRegistros=[]; //donde se van a almacenar los datos de la api datosMunicipios:string[]=[]; datosDepartamentos:string[]=[]; //respuesta del Dialog resDialog:boolean=false; //para el autocompletar filteredMunicipios: Observable<string[]>; filteredDepartamentos: Observable<string[]>; //donde se va almacenar el id de un registro public documentId = null; //Si el valor es 1, la aplicación estará en modo creación si es 2 se habilita el modo edicion public currentStatus = 1; //para el formulario registerForm: FormGroup; //inyectar el servicio rgistros servis encargada de la bd constructor( private registrosServiceF : RegistrosService, /// servicio encargado de municipios de colombia private municipiosService:MunicipiosColombiaService, //inyecto el modal o ventana emergente private matDialog: MatDialog, //para navegacion private router:Router, // para loguin private afAuth: AngularFireAuth, //para el formbuilder private fb:FormBuilder ) { this.registerForm= this.fb.group({ photoUrl: new FormControl(''), nombres: new FormControl('', [Validators.required]), apellidos: new FormControl('', [Validators.required]), cedula: new FormControl('', [Validators.required, this.validarCedula]), email: new FormControl('', [Validators.required, Validators.email, this.validarEmail]), fechaNacimiento: new FormControl('', [Validators.required]), direccion: new FormControl('', [Validators.required]), ciudad: new FormControl('', [Validators.required]), departamento: new FormControl('', [Validators.required]), pais: new FormControl('', [Validators.required]), codigoPostal: new FormControl('', [Validators.required]), profesion: new FormControl('', [Validators.required]), habilidades: new FormControl('', [Validators.required]), descripcion: new FormControl('', [Validators.required]), }) //asigna los valores al formulario como vacios this.registerForm.setValue({ photoUrl:'', nombres: '', apellidos: '', cedula: null, email: '', fechaNacimiento: '', direccion: '', ciudad: '', departamento: '', pais: '', codigoPostal: '', profesion: '', habilidades: '', descripcion: '', }); } ngOnInit() { //obtiene todos los registros de la bd this.registrosServiceF.getRegistros().subscribe((rgSnapshot) => { this.listaRegistros = []; rgSnapshot.forEach((rgData: any) => { this.listaRegistros.push({ id: rgData.payload.doc.id, data: rgData.payload.doc.data() }); }) }); //obtengo los datos del service de departamentos y municipios this.municipiosService.getDatos().subscribe(datos =>{ //almaceno todos los municipios this.datosMunicipios=datos.map(data=> // del map retorna algo data.municipio); this.datosDepartamentos=datos.map(data=> // del map retorna algo data.departamento); //elimino los departamentos repetidos let NuevosDatosDepartamentos:string[]=[]; for (let posicion = 0; posicion < this.datosDepartamentos.length; posicion++) { const element = this.datosDepartamentos[posicion]; if(posicion==0) { NuevosDatosDepartamentos.push(element.toString()); } else{ if(NuevosDatosDepartamentos.includes(element.toString())==false) { NuevosDatosDepartamentos.push(element.toString()); } } } this.datosDepartamentos=NuevosDatosDepartamentos; }); // para el autocompletado y es empleado el html this.filteredMunicipios = this.registerForm.controls.ciudad.valueChanges .pipe( startWith(''), map(value => this._filterMunicipios(value)) ); this.filteredDepartamentos = this.registerForm.controls.departamento.valueChanges .pipe( startWith(''), map(value => this._filterDepartamentos(value)) ); } //para requerimientos personalizados //para el correo private validarEmail: ValidatorFn =(control: AbstractControl): ValidationErrors | null => { const email = control.value; let respuesta= null; if (this.ValidarExistenciaCorreo(email)==true) { return{ ms: 'para otro forma de error' }; } return null; } //metodo para informar errores en el campo de email errorEmail() { if (this.registerForm.controls.email.hasError('required')) { return 'Debe ingresar un email'; } if (this.registerForm.controls.email.hasError('ms')) { return 'El email ya ha sido registrado'; } return this.registerForm.controls.email.hasError('email') ? 'Email no válido' : ''; } //para la cedula private validarCedula: ValidatorFn =(control: AbstractControl): ValidationErrors | null => { const cedula = control.value; let respuesta= null; if (this.ValidarExistenciaCedula(cedula)==true) { return{ ms: 'para otro forma de error' }; } return null; } //metodo para informar errores en el campo de cedula errorCedula() { if (this.registerForm.controls.cedula.hasError('required')) { return 'Ingrese un número de cédula'; } if (this.registerForm.controls.cedula.hasError('ms')) { return 'El número de cedula ya ha sido registrado'; } } //retorna un array con la filtracion para los autocompletados _filterMunicipios(value: string): string[] { const filterValue = value.toLowerCase(); return this.datosMunicipios.filter(option => option.toLowerCase().includes(filterValue)); } _filterDepartamentos(value: string): string[] { const filterValue = value.toLowerCase(); return this.datosDepartamentos.filter(option => option.toLowerCase().includes(filterValue)); } //Valida la existencia del correoen la bd, retorna un boolean ValidarExistenciaCorreo(correo: string): boolean { let existeCorreo: boolean = false; let respuesta: boolean = true; //Obtengo los correos en un array for (let i = 0; i < this.listaRegistros.length; i++) { const element = this.listaRegistros[i]; //obtengo el email const { email } = element.data; //comparo que si existe if (correo == email) { existeCorreo = true; } } if (existeCorreo == true) { //otra forma de informar empleando el modal //const data={ titulo:'Advertencia', mensaje:'El correo ingresado ya está registrado'}; //this.openDialog(data); respuesta = true; } else { respuesta = false; } return respuesta; } //Valida la existencia del la C.C en la bd, retorna un boolean ValidarExistenciaCedula(cedulaIn: string): boolean { let existeCedula: boolean = false; let respuesta: boolean = true; //Obtengo los correos en un array for (let i = 0; i < this.listaRegistros.length; i++) { const element = this.listaRegistros[i]; //obtengo la cedula const { cedula } = element.data; //comparo que si existe if (cedulaIn == cedula) { existeCedula = true; } } if (existeCedula == true) { //otra forma de informar empleando el modal //const data={ titulo:'Advertencia', mensaje:'La cedula ingresada ya está registrada'}; //this.openDialog(data); respuesta = true; } else { respuesta = false; } return respuesta; } // para el checkbox empleando *ngFor en el html listaHabi: any = [ { id: 1, name: 'Autoconocimiento' }, { id: 2, name: 'Empatía' }, { id: 3, name: 'Comunicación asertiva' }, { id: 4, name: 'Pensamiento crítico' }, { id: 5, name: 'Toma de decisiones' }, { id: 6, name: 'Adaptación' }, { id: 7, name: 'Comunicación' }, { id: 8, name: 'Trabajo en equipo' }, { id: 9, name: 'Capacidad de asociación' }, { id: 10, name: 'Razonamiento' }, ]; //Conteno de habilidades nHabilidaddes:number=0; //crea un formgoroup para los checkBox checkboxForm = new FormGroup({ //un array de Form habiForm: new FormArray([], Validators.required) }); onCheckboxChange(e) { const habiForm: FormArray = this.checkboxForm.get('habiForm') as FormArray; //si lo chuliaron agrega al array siempre que numero de habilidades sea menor 3 if (e.checked && this.nHabilidaddes<=2) { habiForm.push(new FormControl(e.source.value)); this.nHabilidaddes++; //metodo que actuliza las habilidades con el formControl principal this.validarHabilidades(); } else { //si numero la habilidad se desmarca elimina habilidad if(e.checked==false) { const index = habiForm.controls.findIndex(x => x.value === e.source.value); habiForm.removeAt(index); //metodo que actuliza las habilidades con el formControl principal this.validarHabilidades(); this.nHabilidaddes--; } //si numero de habilidades esta al limite (3) no agrega nada y no permite chulear else{ e.source._checked=false; } } //si no hay habilidades selecionadas no habilita el boton de registrarse if(this.nHabilidaddes==0) { //restauro el formControl principal, limpiandolo, agregando el validador y actualizandolo this.registerForm.controls.habilidades.setValue([]); this.registerForm.controls.habilidades.setValidators([Validators.required]); this.registerForm.controls.habilidades.updateValueAndValidity(); } //console.log(this.registerForm.controls.habilidades.value); } // para asignar las habilidades al Formgroup principal validarHabilidades(){ //obtengo los valores de FormGroup const ob = this.checkboxForm.value; //obtengo el array habForm de ob ostenido de FormGroup const { habiForm } = ob; //para almacenar las habilidades let habilidadesIn: string = ''; for (let i = 0; i < habiForm.length; i++) { habilidadesIn += habiForm[i] + " / "; // \n } //asigno las habilidaesIn al valor del formcontrol habilidaes para que lo registre en la bd this.registerForm.controls.habilidades.setValue([habilidadesIn]); } //para hacer un nuevo registro en la bd public onRegister(form, documentId = this.documentId) { //verifica el resultado del metodo verificar existencia de correo if (this.ValidarExistenciaCorreo(this.registerForm.get('email').value) == false && this.ValidarExistenciaCedula(this.registerForm.get('cedula').value) == false ) { //console.log(`Status: ${this.currentStatus}`); //si es 1 es para la creacion de un nuevo registro if (this.currentStatus == 1) { // se le asigan una foto por defecto this.registerForm.controls.photoUrl.setValue("https://firebasestorage.googleapis.com/v0/b/teamdc-c1083.appspot.com/o/uploads%2FLogo.png?alt=media&token=4<KEY>"); this.registrosServiceF.crearRegistro(this.registerForm.value).then(() => { //si se aprobo el registro const data={mensaje:'Gracias por registrarte'}; this.openDialog(data); //console.log("respuesta del dialogo:"+this.resDialog); this.router.navigate(['/home']); //limpia el formulario this.registerForm.setValue({ photoUrl:'', nombres: '', apellidos: '', cedula: null, email: '', fechaNacimiento: '', direccion: '', ciudad: '', departamento: '', pais: '', codigoPostal: '', profesion: '', habilidades: '', descripcion: '', }); }, (error) => { console.error(error); }); } } else { } // se crea un usuario en la autentificacion de firebase con su email const result= this.afAuth.auth.createUserWithEmailAndPassword( this.registerForm.controls.email.value, this.registerForm.controls.email.value); //parte de codigo no aplicado, es para editar basado en una ejemplo seguido para el crud if (this.currentStatus != 1) { //modo edicion => no funciona porque falta formulario de edicion this.registrosServiceF.updateRegistro(documentId, this.registerForm.value).then(() => { this.currentStatus = 1; //limpia el formulario this.registerForm.setValue({ nombres: '', apellidos: '', cedula: null, email: '', fechaNacimiento: '', direccion: '', ciudad: '', departamento: '', pais: '', codigoPostal: '', profesion: '', habilidades: '', descripcion: '', }); console.log('Documento editado exitósamente'); }, (error) => { console.log(error); }); } } //abrir dialogo openDialog(data:any) { const dialogConfig = new MatDialogConfig(); dialogConfig.data = data; //dialogConfig.data = { titulo:'Estado de registro', mensaje:'Exitoso'}; let dialogRef = this.matDialog.open(DialogComponent, dialogConfig) dialogRef.afterClosed().subscribe(value => { this.resDialog=value; //console.log(`Dialog sent: ${value}`); });; } //funciones del crud que no se aplican pero que se adaptaron de un ejemplo seguido para el crud //para la edicion de un registro aun no funciona porque no hay fromulario de edicion public editarRegistro(documentId) { let editSubscribe = this.registrosServiceF.getRegistro(documentId).subscribe((registro) => { this.currentStatus = 2; this.documentId = documentId; this.registerForm.setValue({ id: documentId, nombre: registro.payload.data()['nombre'], apellidos: registro.payload.data()['apellidos'], cedula: registro.payload.data()['cedula'], email: registro.payload.data()['email'], fechaNacimiento: registro.payload.data()['fechaNacimiento'], direccion: registro.payload.data()['direccion'], ciudad: registro.payload.data()['ciudad'], departamento: registro.payload.data()['departamento'], pais: registro.payload.data()['pais'], codigoPostal: registro.payload.data()['codigoPostal'], profesion: registro.payload.data()['profesion'], habilidades: registro.payload.data()['habilidades'], descripcion: registro.payload.data()['descripcion'], }); editSubscribe.unsubscribe(); }); } //elimina el registro de la bd public eliminarRegistro(documentId) { this.registrosServiceF.eliminarRegistro(documentId).then(() => { console.log('Documento eliminado!'); }, (error) => { console.error(error); }); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; //Inportacion del modulo encargado de Material import{MaterialModule} from './material/material.module'; import { SidenavComponent } from './components/sidenav/sidenav.component'; //Importacion para trabajar con el formulario import {FormsModule, ReactiveFormsModule} from '@angular/forms'; //Inportacion del servicio encargado de los registros import {RegistrosService} from './services/registros.service'; //importaciones para el manejo de FireBase import { environment } from '../environments/environment'; import{ AngularFireModule } from '@angular/fire'; import{ AngularFirestoreModule } from '@angular/fire/firestore'; import { AngularFireAuthModule} from '@angular/fire/auth'; //Con este modulo no necesitas usar fetch ni ajax ni nada para llamadas a apis import { HttpClientModule } from "@angular/common/http"; //importacion para el manejo de responsive import { FlexLayoutModule} from '@angular/flex-layout'; import { LayoutModule } from '@angular/cdk/layout'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; import { MatSidenavModule } from '@angular/material/sidenav'; import { MatIconModule } from '@angular/material/icon'; import { MatListModule } from '@angular/material/list'; import { DialogComponent } from './components/dialog/dialog.component'; import { YouTubePlayerModule } from '@angular/youtube-player' ; import { AngularFireStorageModule } from '@angular/fire/storage'; import { FooterComponent } from './components/footer/footer.component'; import { AuthService } from './services/auth.service'; import { ContactComponent } from './components/contact/contact.component'; @NgModule({ declarations: [ AppComponent, SidenavComponent, DialogComponent, FooterComponent, ContactComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, //Importaciones de FireBase AngularFireModule.initializeApp(environment.firebaseConfig), AngularFirestoreModule, AngularFireAuthModule, //para llamadas http HttpClientModule, //Modulo encargado de Material MaterialModule, //Encargado del formulario FormsModule, ReactiveFormsModule, //encargado del modo responsive FlexLayoutModule, LayoutModule, MatToolbarModule, MatButtonModule, MatSidenavModule, MatIconModule, MatListModule, //para embeber videos de youtube YouTubePlayerModule, //para subir la imagen al storage AngularFireStorageModule, ], providers: [ //Servicio de firabese para BD RegistrosService, // servicio para la autentificacion AuthService, //servicio de api //MunicipiosColombiaService ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Injectable } from '@angular/core'; //importaciones para gestionar el servicio a la BD import{AngularFirestore, AngularFirestoreCollection} from '@angular/fire/firestore'; import { Observable } from 'rxjs'; import { map, switchMap } from 'rxjs/operators'; //importamos la interface import {RegistrosI} from 'src/app/models/registros.interface'; //ID para la interface export interface RegistrosID extends RegistrosI{id:string;} @Injectable({ providedIn: 'root' }) export class RegistrosService { //Crear propiedad private registrosCollection: AngularFirestoreCollection<RegistrosI>; //propiedad para guardar todos los usuarios registros: Observable<RegistrosID[]>; //inyectamos el servicio a la bd constructor(private readonly firestore:AngularFirestore) { //nombre de la coleccion va en parentesis this.registrosCollection = firestore.collection<RegistrosI>('registros'); this.registros = this.registrosCollection.snapshotChanges().pipe( map(actions => actions.map(a =>{ const data = a.payload.doc.data() as RegistrosI; const id = a.payload.doc.id; return{ id, ...data}; })) ); } getAllUser(){ //return todos los usuarios return this.registros; } //-------------------------------------------- // conecion y manejo de base de datos tomado de: // https://medium.com/angular-chile/angular-6-y-firestore-b7f270adcc96 //-------------------------------------------- //metodos //Recibe un objeto de la interface crearRegistro(registro: RegistrosI) { return this.firestore.collection('registros').add(registro); } //Recibe el id para un obtener un unico registro getRegistro(registroId: string) { return this.firestore.collection('registros').doc(registroId).snapshotChanges(); } //obtiene todos los registros getRegistros() { return this.firestore.collection('registros').snapshotChanges(); } //actualiza un registro public updateRegistro(documentId: string, registro: RegistrosI) { return this.firestore.collection('registros').doc(documentId).set(registro); } //elimina un registro eliminarRegistro(registroID: string){ return this.firestore.doc('registros/' + registroID).delete();; } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ContactComponent } from './components/contact/contact.component'; //redireccion a la pagina de register const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', loadChildren: () => import('./components/home/home.module').then(m => m.HomeModule) }, { path: 'register', loadChildren: () => import('./components/register/register.module').then(m => m.RegisterModule) }, { path: 'records', loadChildren: () => import('./components/records/records.module').then(m => m.RecordsModule) }, { path: 'video', loadChildren: () => import('./components/video/video.module').then(m => m.VideoModule) }, { path: 'login', loadChildren: () => import('./components/login/login.module').then(m => m.LoginModule) }, { path: 'profile', loadChildren: () => import('./components/profile/profile.module').then(m => m.ProfileModule) }, {path:'contact', component:ContactComponent}, { path: 'team', loadChildren: () => import('./components/team/team.module').then(m => m.TeamModule) }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>Descripción *************************** Este es la documentación de un proyecto realizado en angular 10. El proyecto es desarrollado con el fin de poner en práctica los conocimientos adquiridos en el transcurso de la carrera de Ingeniería de Sistemas en la UNAB. Además de aprender nuevos lenguajes y herramientas que son útiles en el desarrollo de una plataforma web. Esta página web es un dashboard que permite realizar un registro y guardar los datos del usuario, para luego ingresar al sistema y poder acceder a todos los módulos de la plataforma.La asignación de actividades para el desarrollo de la página web se definió mediante desafíos asignados por el supervisor. Contenido =========================== Desafío 1 ---------------------------- Tiene un formulario responsivo con los campos definidos por el supervisor, en donde se usan campos de tipo texto, númerico, de fecha, de selección y de chequeo, alojando la información recolectada en una base de datos. Desafío 2 ------------------------------ Sobre el formulario desarrollado, se incluyen validaciones y alertas de campos erróneos e inválidos. Se traen datos de municipios y departamentos de Colombia de un WebService. Tiene un estilo estipulado por el supervisor, incluyendo aviso de un registro exitoso. Se tienen las secciones de Home, Registro, Inicio de sesión, Registros y video. En el Home se agregan fotos del equipo desarrollador. Registros permite visualizar los datos de los usuarios registrados. La sección de video muestra un video del equipo DC. Desafío 3 ----------------------------------- Se restringue el acceso. Los usuarios que no estan logueados tienen accesso a la página principal, al registro, a inicio de sesión y al video. Los usuarios que han iniciado sesión estan habilidatos para navegar por todas las secciones. Desafío 4 -------------------------------- Se acomoda un logo correspondiente al equipo DC en la esquina superior izquierda, y en modo responsivo en el centro del dispositivo. Tiene una sección de mi perfil en donde se muestra toda la información del usuario logueado y se permite la edición de los datos y añadir una foto de usuario tipo avatar. <file_sep>********* Registro ********* 1. Descripción En este componente se debe mostrar todos los registros almacenados en la base de datos. 2. Importaciones Para este componente de debe importar el servicio a la base de datos, el servicio para la autentificación de usuarios y el servicio a una api para obtener los municipios y departamentos de Colombia. :: import { RegistrosService } from 'src/app/services/registros.service'; import { AngularFireAuth } from '@angular/fire/auth'; import {MunicipiosColombiaService} from 'src/app/services/municipios-colombia.service'. También se importan componentes de Angular Material para la implementación de ventana emergente o modal y de se importa el componente Router para un redireccionamiento al concluir el registro. :: import { MatDialog, MatDialogConfig } from '@angular/material/dialog'; import { DialogComponent } from '../dialog/dialog.component'; import { Router } from '@angular/router';. 3. Desarrollo El constructor se inyectan todos los objetos a necesarios para el desarrollo del componente. :: private afAuth: AngularFireAuth, private registrosServiceF : RegistrosService, private municipiosService:MunicipiosColombiaService, private matDialog: MatDialog, private router:Router, private fb:FormBuilder. Para la captura de datos se emplea los formularios reactivos, para ello se declara un objeto de la clase FormGroup y se inicializa creando un FormControl para cada campo requerido, declarando su estado y sus respectivo valida daciones. :: this.registerForm= this.fb.group({ photoUrl: new FormControl(''), cedula: new FormControl('', [Validators.required, this.validarCedula]), . . . descripcion: new FormControl('', [Validators.required]), }). En el método ngOnInit se realiza la obtención de todos los registros almacenados en la base de datos con el fin de realizar validaciones con dichos datos, estos datos son almacenados en un array. :: this.registrosServiceF.getRegistros().subscribe((rgSnapshot) => { this.listaRegistros = []; rgSnapshot.forEach((rgData: any) => { this.listaRegistros.push({ id: rgData.payload.doc.id, data: rgData.payload.doc.data() }); }) }); sacaaaaaaaaaaaaaaaaaaaa <file_sep>import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators, EmailValidator } from '@angular/forms'; import { Router } from '@angular/router'; import { auth } from 'firebase'; import { AuthService } from '../../services/auth.service'; import { RegistrosService } from 'src/app/services/registros.service'; import { MatDialogConfig, MatDialog } from '@angular/material/dialog'; import { DialogComponent } from '../dialog/dialog.component'; import { AngularFireAuth } from '@angular/fire/auth'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], }) export class LoginComponent implements OnInit { loginForm= new FormGroup({ email: new FormControl('',[Validators.required, Validators.email]), }) resDialog: any; constructor(private authSvc:AuthService, private router: Router, private registroService:RegistrosService, private matDialog: MatDialog, public afAuth: AngularFireAuth) { } listaRegistros; ngOnInit(): void { this.registroService.getRegistros().subscribe((rgSnapshot) => { this.listaRegistros = []; rgSnapshot.forEach((rgData: any) => { this.listaRegistros.push({ id: rgData.payload.doc.id, data: rgData.payload.doc.data() }); }) }); } async onLogin(){ console.log("funciona"+ this.loginForm.controls.email.value); if(this.ValidarExistenciaCorreo(this.loginForm.controls.email.value)==true) { const user= await this.authSvc.login(this.loginForm.controls.email.value, this.loginForm.controls.email.value); if (user) { //redirect to homePage this.router.navigate(['/home']) } } else{ //window.alert('correo no registrado'); const data={ titulo:'Advertencia', mensaje:'El correo no esta registrado en la BD'}; this.openDialog(data); } } get email(){ return this.loginForm.get('email');} get password(){ return this.loginForm.get('password');} //Valida la existencia del correo en la bd, retorna un boolean ValidarExistenciaCorreo(correo: string): boolean { console.log("validacion"+correo) let existeCorreo: boolean = false; let respuesta: boolean = true; //Obtengo los correos en un array for (let i = 0; i < this.listaRegistros.length; i++) { const element = this.listaRegistros[i]; const { email } = element.data; if (correo == email) { existeCorreo = true; } } if (existeCorreo == true) { respuesta = true; } else { respuesta = false; } return respuesta; } openDialog(data:any) { const dialogConfig = new MatDialogConfig(); dialogConfig.data = data; //dialogConfig.data = { titulo:'Estado de registro', mensaje:'Exitoso'}; let dialogRef = this.matDialog.open(DialogComponent, dialogConfig) dialogRef.afterClosed().subscribe(value => { this.resDialog=value; console.log(`Dialog sent: ${value}`); });; } } <file_sep>import { Component, OnInit } from '@angular/core'; //para el loguin import { AngularFireAuth } from '@angular/fire/auth'; import { RegistrosService } from 'src/app/services/registros.service'; import { FormBuilder, FormGroup, Validators, FormControl, FormArray, ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms'; import { DatePipe } from '@angular/common'; import { Observable } from 'rxjs'; import { MunicipiosColombiaService } from 'src/app/services/municipios-colombia.service'; import { startWith, map } from 'rxjs/operators'; //para recuperar la imagen que se subio import { AngularFireStorage } from '@angular/fire/storage'; import { finalize } from 'rxjs/operators'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.scss'] }) export class ProfileComponent implements OnInit { //almacena el usuario logueado private UserEmail:string; // lista de registros public listaRegistros=[]; //registro a modificar registroUsuario //para el formGroup editForm: FormGroup; checkboxForm :FormGroup; //cambiar estados de los botones btnEditarDisabled=false; btnGuardarDisabled=true; //donde se va almacenar el id de un registro public documentId = null; datosMunicipios:string[]=[]; datosDepartamentos:string[]=[]; filteredMunicipios: Observable<string[]>; filteredDepartamentos: Observable<string[]>; //para la fecha de nacimiento datePipe = new DatePipe('en-US'); breakpoint: number; constructor( // para manejar el estado de la sesion private afAuth: AngularFireAuth, // para la conexion con la BD private registroService:RegistrosService, //para el formulario private fb:FormBuilder, /// servicio encargado de municipios de colombia private municipiosService:MunicipiosColombiaService, //para subir la imagen al storage de firebase private storage:AngularFireStorage ) { //crea un formgoroup para los checkBox this.checkboxForm= this.fb.group({ //un array de Form habiForm: new FormArray([], Validators.required)}); this.editForm= this.fb.group({ photoUrl: new FormControl(''), nombres: new FormControl('', [Validators.required]), apellidos: new FormControl('', [Validators.required]), cedula: new FormControl('', [Validators.required, this.validarCedula]), email: new FormControl('', [Validators.required, Validators.email, /*this.validarEmail*/]), fechaNacimiento: new FormControl('', [Validators.required]), direccion: new FormControl('', [Validators.required]), ciudad: new FormControl('', [Validators.required]), departamento: new FormControl('', [Validators.required]), pais: new FormControl('', [Validators.required]), codigoPostal: new FormControl('', [Validators.required]), profesion: new FormControl('', [Validators.required]), habilidades: new FormControl('', [Validators.required]), descripcion: new FormControl('', [Validators.required]), }) } //para la imagen basado en https://dev.to/fayvik/uploading-an-image-to-firebase-cloud-storage-with-angular-2aeh uploadPercent: Observable<number>; downloadURL: Observable<string>; urlImage; ngOnInit(): void { this.breakpoint = (window.innerWidth <= 400) ? 1 : 6; this.getDatosMuniYDeap(); this.UserEmail=this.afAuth.auth.currentUser.email; this.editForm.setValue({ photoUrl:'', nombres: '', apellidos: '', cedula: null, email: '', fechaNacimiento: '', direccion: '', ciudad: '', departamento: '', pais: '', codigoPostal: '', profesion: '', habilidades: '', descripcion: '', }); //desactivo el formulario this.editForm.disable(); this.getRegistros(); } onResize(event) { this.breakpoint = (event.target.innerWidth <= 400) ? 1 : 6; } //metodo para subir la imagen al storage onUpload(e){ //console.log('subir', e); //generar un id unico para la imagen const id = Math.random().toString(36).substring(2); //aqui se tiene el archivo const file = e.target.files[0]; const filePath = `uploads/profile_${id}`; //ruta del fichero const ref = this.storage.ref(filePath); //se realiza la subida del fichero const task = this.storage.upload(filePath,file); this.uploadPercent = task.percentageChanges(); //obtiene el tamaño de la imagen y lo pasa a MB const Filesize = e.target.files[0].size/1024/1024; if (Filesize>1) { alert('El archivo excede el tamaño permitido de 1MB') }else{ //para recuperar la url task.snapshotChanges() .pipe( finalize(() => { this.downloadURL = ref.getDownloadURL(); this.downloadURL.subscribe(url => { if (url) { this.urlImage = url; this.editForm.enable(); this.editForm.controls.photoUrl.setValue([this.urlImage]); this.editForm.controls.fechaNacimiento.setValue(this.registroUsuario.data.fechaNacimiento); this.onUpdate(this.editForm.value); } console.log(this.urlImage); }); }) ).subscribe(); } } //metodo para informar errores en el campo de cedula errorCedula() { if (this.editForm.controls.cedula.hasError('required')) { return 'Ingrese un número de cédula'; } if (this.editForm.controls.cedula.hasError('ms')) { return 'El número de cedula ya ha sido registrado'; } } //para la cedula private validarCedula: ValidatorFn =(control: AbstractControl): ValidationErrors | null => { const cedula = control.value; let respuesta= null; if (this.ValidarExistenciaCedula(cedula)==true) { return{ ms: 'para otro forma de error' }; } return null; } getRegistros(){ this.registroService.getRegistros().subscribe((rgSnapshot) => { this.listaRegistros = []; rgSnapshot.forEach((rgData: any) => { this.listaRegistros.push({ id: rgData.payload.doc.id, data: rgData.payload.doc.data() }); }) //console.log(this.listaRegistros); this.setDatosFormulario(); }); } setDatosFormulario(){ for (let index = 0; index < this.listaRegistros.length; index++) { const element = this.listaRegistros[index]; const { email } = element.data; if(email==this.UserEmail) { this.registroUsuario=element break; } }; //console.log( this.registroUsuario.id ); //console.log('sdsadadas'); //console.log( this.documentId ); //para el id del documento a actualizar this.documentId = this.registroUsuario.id; this.urlImage=this.registroUsuario.data.photoUrl; let editSubscribe = this.registroService.getRegistro(this.documentId).subscribe((registro) => { let myFormattedDate = this.datePipe.transform(registro.payload.data()['fechaNacimiento'].seconds*1000, 'dd/MM/yyyy'); this.editForm.setValue({ photoUrl:registro.payload.data()['photoUrl'], nombres: registro.payload.data()['nombres'], apellidos: registro.payload.data()['apellidos'], cedula: registro.payload.data()['cedula'], email: registro.payload.data()['email'], fechaNacimiento: /*registro.payload.data()['fechaNacimiento'],*/myFormattedDate, direccion: registro.payload.data()['direccion'], ciudad: registro.payload.data()['ciudad'], departamento: registro.payload.data()['departamento'], pais: registro.payload.data()['pais'], codigoPostal: registro.payload.data()['codigoPostal'], profesion: registro.payload.data()['profesion'], habilidades: registro.payload.data()['habilidades'], descripcion: registro.payload.data()['descripcion'], }); editSubscribe.unsubscribe(); }); } //boton de editar onEditar(){ this.editForm.enable(); //para no cambiar el correo this.editForm.get('email').disable(); this.btnEditarDisabled=true; this.editForm.controls.habilidades.setValue([]); this.editForm.controls.habilidades.setValidators([Validators.required]); this.editForm.controls.habilidades.updateValueAndValidity(); this.editForm.controls.fechaNacimiento.setValue([]); this.editForm.controls.fechaNacimiento.setValidators([Validators.required]); this.editForm.controls.fechaNacimiento.updateValueAndValidity(); this.nHabilidaddes=0; const habiForm: FormArray = this.checkboxForm.get('habiForm') as FormArray; let i=2; while (habiForm.controls.length!=0) { habiForm.removeAt(i); i--; } //this.checkboxForm.controls.habiForm console.log(this.checkboxForm.controls.habiForm); } onUpdate(form){ this.editForm.get('email').enable(); this.editForm.controls.email.setValue(this.UserEmail); //verifica el resultado del metodo verificar existencia de correo if (this.ValidarExistenciaCorreo(this.editForm.get('email').value) == false && this.ValidarExistenciaCedula(this.editForm.get('cedula').value) == false ) { this.registroService.updateRegistro(this.documentId, this.editForm.value).then(() => { this.editForm.disable(); this.btnEditarDisabled=false; this.btnGuardarDisabled=true; //para actualizar el correo y contraseña pero esta desabilitado //this.afAuth.auth.currentUser.updateEmail(this.editForm.controls.email.value); //this.afAuth.auth.currentUser.updatePassword(this.editForm.controls.email.value); console.log('Documento editado exitósamente'); }, (error) => { console.log(error); }); }else{ console.log(" no es valido para el registro"); } } //Valida la existencia del correoen la bd, retorna un boolean ValidarExistenciaCorreo(correo: string): boolean { let existeCorreo: boolean = false; let respuesta: boolean = true; //Obtengo los correos en un array for (let i = 0; i < this.listaRegistros.length; i++) { const element = this.listaRegistros[i]; const { email } = element.data; //excluyo el documento que se va a editar if(element.id!= this.registroUsuario.id) { if (correo == email) { existeCorreo = true; } } } if (existeCorreo == true) { console.log('El correo ingresado ya está registrado'); //const data={ titulo:'Advertencia', mensaje:'El correo ingresado ya está registrado'}; //this.openDialog(data); respuesta = true; } else { respuesta = false; } return respuesta; } //Valida la existencia del la C.C en la bd, retorna un boolean ValidarExistenciaCedula(cedulaIn: string): boolean { let existeCedula: boolean = false; let respuesta: boolean = true; //Obtengo los correos en un array for (let i = 0; i < this.listaRegistros.length; i++) { const element = this.listaRegistros[i]; const { cedula } = element.data; //excluyo el documento que se va a editar if(element.id!= this.registroUsuario.id) { if (cedulaIn == cedula) { existeCedula = true; } } } if (existeCedula == true) { console.log('La cedula ingresada ya está registrado'); //const data={ titulo:'Advertencia', mensaje:'La cedula ingresada ya está registrada'}; //this.openDialog(data); respuesta = true; } else { respuesta = false; } return respuesta; } // para el checkbox empleando *ngFor en el html listaHabi: any = [ { id: 1, name: 'Autoconocimiento' }, { id: 2, name: 'Empatía' }, { id: 3, name: 'Comunicación asertiva' }, { id: 4, name: 'Pensamiento crítico' }, { id: 5, name: 'Toma de decisiones' }, { id: 6, name: 'Adaptación' }, { id: 7, name: 'Comunicación' }, { id: 8, name: 'Trabajo en equipo' }, { id: 9, name: 'Capacidad de asociación' }, { id: 10, name: 'Razonamiento' }, ]; //Conteno de habilidades nHabilidaddes:number=0; onCheckboxChange(e) { const habiForm: FormArray = this.checkboxForm.get('habiForm') as FormArray; //si lo chuliaron hagrega al array siempre que numero de habilidades menor 4 if (e.checked && this.nHabilidaddes<=2) { habiForm.push(new FormControl(e.source.value)); this.nHabilidaddes++; this.validarHabilidades(); } else { //si numero la habilidad se desmarca elimina habilidad if(e.checked==false) { const index = habiForm.controls.findIndex(x => x.value === e.source.value); habiForm.removeAt(index); this.validarHabilidades(); this.nHabilidaddes--; } //si numero de habilidades esta al limite (3) no agrega nada y no permite chulear else{ e.source._checked=false; } } //si no hay habilidades selecionadas no habilita el boton if(this.nHabilidaddes==0) { this.editForm.controls.habilidades.setValue([]); this.editForm.controls.habilidades.setValidators([Validators.required]); this.editForm.controls.habilidades.updateValueAndValidity(); } //console.log(this.editForm.controls.habilidades.value); } // para asignar las habilidades al Formgroup principal validarHabilidades(){ //obtengo los valores de FormGroup const ob = this.checkboxForm.value; //obtengo el array habForm de ob ostenido de FormGroup const { habiForm } = ob; //para almacenar las habilidades let habilidadesIn: string = ''; for (let i = 0; i < habiForm.length; i++) { habilidadesIn += habiForm[i] + " / "; // \n } //asigno las habilidaesIn al valor del formcontrol habilidaes para que lo registre en la bd this.editForm.controls.habilidades.setValue([habilidadesIn]); } _filterMunicipios(value: string): string[] { const filterValue = value.toLowerCase(); return this.datosMunicipios.filter(option => option.toLowerCase().includes(filterValue)); } _filterDepartamentos(value: string): string[] { const filterValue = value.toLowerCase(); return this.datosDepartamentos.filter(option => option.toLowerCase().includes(filterValue)); } getDatosMuniYDeap(){ //obtengo los datos del service de departamentos y municipios this.municipiosService.getDatos().subscribe(datos =>{ //almaceno todos los municipios this.datosMunicipios=datos.map(data=> // del map retorna algo data.municipio); this.datosDepartamentos=datos.map(data=> // del map retorna algo data.departamento); //elimino los departamentos repetidos let NuevosDatosDepartamentos:string[]=[]; for (let posicion = 0; posicion < this.datosDepartamentos.length; posicion++) { const element = this.datosDepartamentos[posicion]; if(posicion==0) { NuevosDatosDepartamentos.push(element.toString()); } else{ if(NuevosDatosDepartamentos.includes(element.toString())==false) { NuevosDatosDepartamentos.push(element.toString()); } } } this.datosDepartamentos=NuevosDatosDepartamentos; }); this.filteredMunicipios = this.editForm.controls.ciudad.valueChanges .pipe( startWith(''), map(value => this._filterMunicipios(value)) ); this.filteredDepartamentos = this.editForm.controls.departamento.valueChanges .pipe( startWith(''), map(value => this._filterDepartamentos(value)) ); } } <file_sep>import { Injectable } from '@angular/core'; //Para manejo de llamadas a apis con este modulo no necesitas usar fetch ni ajax import { HttpClient } from "@angular/common/http"; import { Observable } from 'rxjs/internal/Observable'; @Injectable({ providedIn: 'root' }) export class MunicipiosColombiaService { //inyecto el httpClient constructor( private http: HttpClient) { } //metodos getDatos():Observable<any>{ return this.http.get("https://www.datos.gov.co/resource/xdk5-pm3f.json"); } } <file_sep>import { Injectable } from '@angular/core'; //importaciones para gestionar el servicio a la BD import{AngularFirestore, AngularFirestoreCollection} from '@angular/fire/firestore'; import { Observable } from 'rxjs'; import { map} from 'rxjs/operators'; //importamos la interface import {ContactosI} from 'src/app/models/registros.interface'; //ID para la interface export interface ContactosID extends ContactosI{id:string;} @Injectable({ providedIn: 'root' }) export class ContactosService { //Crear propiedad private contactosCollection: AngularFirestoreCollection<ContactosI>; //propiedad para guardar todos los usuarios contactos: Observable<ContactosID[]>; //inyectamos el servicio a la bd constructor(private readonly firestore:AngularFirestore) { //nombre de la coleccion va en parentesis this.contactosCollection = firestore.collection<ContactosI>('contactos'); this.contactos = this.contactosCollection.snapshotChanges().pipe( map(actions => actions.map(a =>{ const data = a.payload.doc.data() as ContactosI; const id = a.payload.doc.id; return{ id, ...data}; })) ); } getAllUser(){ //return todos los contactos return this.contactos; } //-------------------------------------------- // conecion y manejo de base de datos tomado de: // https://medium.com/angular-chile/angular-6-y-firestore-b7f270adcc96 //-------------------------------------------- //metodos //Recibe un objeto de la interface crearContacto(contacto: ContactosI) { return this.firestore.collection('contactos').add(contacto); } //Recibe el id para un obtener un unico contacto getContacto(contactoId: string) { return this.firestore.collection('contactos').doc(contactoId).snapshotChanges(); } //obtiene todos los contactos getContactos() { return this.firestore.collection('contactos').snapshotChanges(); } //actualiza un contactos public updateContacto(documentId: string, contacto: ContactosI) { return this.firestore.collection('contactos').doc(documentId).set(contacto); } //elimina un contacto eliminarContacto(contactoID: string){ return this.firestore.doc('contactos/' + contactoID).delete();; } }
ffc9f6cf891e87c58f24347b0441b126a082eb58
[ "TypeScript", "reStructuredText" ]
26
TypeScript
dev28aiatic/teamDC
df2d753c81b6578a0fda07acdd102440fd2f58ed
facdb23d533209cdaaa4ded151e22da043fe3498
refs/heads/master
<repo_name>nishantrana2/UsersList<file_sep>/src/App.js import React, { useContext } from 'react'; import Users from './components/Users/Users'; const App = props => { return <Users /> }; export default App; <file_sep>/src/components/Users/UserList.js import React from 'react'; import './UserList.css'; const UserList = props => { console.log('RENDERING USERLIST'); return ( <section className="user-list"> <h2>Users List</h2> <ul> {props.users.map(ig => ( <li key={ig.id} onClick={props.onRemoveItem.bind(this, ig.id)}> <div>{ig.first} {ig.last}</div> <div><h5>ID: {ig.unique}</h5></div> <div>{ig.description}</div> </li> ))} </ul> </section> ); }; export default UserList;
d1d341c87b9ae0523c4b50e05d2fbc296148cce5
[ "JavaScript" ]
2
JavaScript
nishantrana2/UsersList
548b26a3d88a41586614295e461d3945593b4299
9ad32e775ada77ef39a80c2b0a7ca0ccd3f6178d
refs/heads/master
<file_sep>React project copying look feel of reddit post. State is used for up/downvoting posts and rearranging posts based on voteCount. <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import './Post.css'; function Post({ post, onUpVote, onDownVote }) { return ( <div className="PostContainer"> {/* count */} <Count post={post} onUpVote={onUpVote} onDownVote={onDownVote} /> {/* avatar */} <div> <img className="Post-photo" src={ post.photo || 'https://instagram.fisb1-1.fna.fbcdn.net/vp/dbd174e0ea12ed00ca1cdb5409b62bcd/5D0566F1/t51.2885-19/44884218_345707102882519_2446069589734326272_n.jpg?_nc_ht=instagram.fisb1-1.fna.fbcdn.net' } /> </div> {/* text */} <div className="Post-text"> <h1 className="Post-title red-text">{post.title}</h1> <h3>{post.site}</h3> <h3> Submitted {post.date_submitted} hours ago by {post.contributor}{' '} </h3> <Actions post={post} /> </div> </div> ); } Post.propTypes = { post: PropTypes.object.isRequired }; function Count({ post, onUpVote, onDownVote }) { return ( <div> <div> <span className="cursor" onClick={() => onUpVote(post)}> + </span> </div> <div>{post.voteCount}</div> <div> <span className="cursor" onClick={() => onDownVote(post)}> - </span> </div> </div> ); } function Actions({ post }) { return ( <ul> <li className="Post-li red-text"> {post.comments > 0 ? post.comments + ' comments' : 'comment'} </li> <li className="Post-li">share</li> <li className="Post-li">save</li> <li className="Post-li">hide</li> <li className="Post-li">report</li> </ul> ); } export default Post; <file_sep>let posts = [ { id: 0, title: 'Netlify: Our conversion from angular to react', site: 'netlify.com', date_submitted: 9, contributor: 'brianllamar', comments: 10, voteCount: 22 }, { id: 1, title: 'React in patterns - List of design patterns/techniques used while developing with React', site: 'github.com', date_submitted: 12, contributor: 'magenta_placenta', comments: 0, voteCount: 18 }, { id: 2, title: 'Redux vs MobX vs Flux vs... Do you even need that?', site: 'goshakkk.name', date_submitted: 8, contributor: 'goshakkkk', comments: 0, voteCount: 7 } ] export { posts };
e9acdbf0f35763b3cfa3a59c7899acbf9059c073
[ "Markdown", "JavaScript" ]
3
Markdown
ewarrenG/reddit-react
3726efc0b53f1455cc409409ade71885780a9e2b
6200ba179b4192148d00d7d9d2be5fd49becdccc
refs/heads/master
<repo_name>haginus/pao-labs<file_sep>/lab2/ex2.java package lab2; public class ex2 { public static void main(String[] args) { Person p1 = new Person("John", "Doe", 24, 1123444L, "student"); Person p2 = new Person("Jane", "Roe", 56, 2233444L, "teacher"); System.out.println(p1.getName() + " " + p1.getSurname() + "(age " + p1.getAge() + ") " + p1.getId() + " " + p1.getType()); System.out.println(p2.getName() + " " + p2.getSurname() + " (age " + p2.getAge() + ") " + p2.getId() + " " + p2.getType()); } } <file_sep>/proiect/src/databaseServices/ProductDatabaseService.java package databaseServices; import config.DatabaseConfiguration; import priceConventions.PricePerQuantity; import products.Product; import java.sql.*; import java.util.HashMap; public class ProductDatabaseService { private static ProductDatabaseService single_instance = null; HashMap<String, Product> products; private ProductDatabaseService() { try { this.products = this.loadFromDatabase(); } catch (SQLException e) { e.printStackTrace(); this.products = new HashMap<>(); } } public HashMap<String, Product> getProducts() { return products; } public HashMap<String, Product> addToDatabase(Product product) throws SQLException { Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection(); PreparedStatement stmt = databaseConnection.prepareStatement("INSERT INTO products VALUES (?, ?, ?, ?); "); stmt.setString(1, product.getBarcode()); stmt.setString(2, product.getName()); stmt.setDouble(3, product.getPrice().price); String unit = product.getPrice() instanceof PricePerQuantity ? ((PricePerQuantity) product.getPrice()).measureUnit : null; stmt.setString(4, unit); stmt.executeUpdate(); return loadFromDatabase(); } public HashMap<String, Product> editInDatabase(Product product) throws SQLException { Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection(); PreparedStatement stmt = databaseConnection.prepareStatement("UPDATE products SET name = ?, price = ?, unit = ?" + " WHERE barcode = ?;"); stmt.setString(4, product.getBarcode()); stmt.setString(1, product.getName()); stmt.setDouble(2, product.getPrice().price); String unit = product.getPrice() instanceof PricePerQuantity ? ((PricePerQuantity) product.getPrice()).measureUnit : null; stmt.setString(3, unit); stmt.executeUpdate(); return loadFromDatabase(); } public HashMap<String, Product> deleteFromDatabaseByBarcode(String barcode) throws SQLException { Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection(); PreparedStatement stmt = databaseConnection.prepareStatement("DELETE FROM products WHERE barcode = ?;"); stmt.setString(1, barcode); stmt.executeUpdate(); return loadFromDatabase(); } public HashMap<String, Product> loadFromDatabase() throws SQLException { Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection(); Statement stmt = databaseConnection.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM products;"); HashMap<String, Product> products = new HashMap<>(); while(rs.next()) { Product product; String unit = rs.getString(4); if(unit == null) product = new Product(rs.getString(1), rs.getString(2), rs.getDouble(3)); else product = new Product(rs.getString(1), rs.getString(2), rs.getDouble(3), unit); products.put(product.getBarcode(), product); } return products; } public static ProductDatabaseService getInstance() { if (single_instance == null) single_instance = new ProductDatabaseService(); return single_instance; } }<file_sep>/proiect/README.md # Changelog ### Checkpoint 3 - Șters servicii citire/ștergere în CSV - Adăugat baza de date - Adăugat clasă serviciu pentru configurarea inițială bază de date - Adăugat servicii pentru citire, inserare, editare, ștergere din baza de date ### Checkpoint 2 - Organizat în pachete - Adăugat servicii de scriere/citire în CSV # Detalii despre baza de date - Programul se conectează la baza de date MySQL ```register``` folosind user-ul ```register``` și parola ```register``` ce rulează pe ```localhost:3306```. - Rulați: ```mysql CREATE DATABASE register; CREATE USER 'register'@'localhost' IDENTIFIED BY 'register'; GRANT ALL PRIVILEGES ON * . * TO 'register'@'localhost'; ``` # Instrucțiuni sintaxă comandă - ```+ <barcode> <quantity>```: Adaugă produsul corespunzător codului de bare în cantitatea specificată la comanda curentă; - ```- <barcode>```: Șterge produsul corespunzător codului de bare (în toată cantitatea) din comanda curentă; - ```?```: Afișează totalul comenzii; - - ```P Cash <handled_cash>```: Plătirea comenzii în numerar, cu suma specificată; - ```P Card <card_number> <card_type>```: Plătirea comenzii în numerar, cu un anume card (cele două câmpuri sunt date de umplutură); - ```D```: Anulează comanda curentă. <file_sep>/lab2/ex4.java package lab2; public class ex4 { public static void main(String[] args) { Room r1 = new Room("12A", "normal", 3); Person p1 = new Person("Jane", "Roe", 56, 2233444L, "teacher"); Room r2 = new Room("15", "lab", 2); Person p2 = new Person("Alex", "Popescu", 42, 2237L, "teacher"); Subject s1 = new Subject(r1, p1, 20); Subject s2 = new Subject(r2, p2, 14); System.out.println(s1); System.out.println(); System.out.println(s2); } } <file_sep>/lab1/pb3_7.java import java.util.Scanner; public class pb3_7 { public static void t3() { Scanner scanner = new Scanner (System. in ); String integ = scanner.nextLine(); Integer n = Integer.parseInt(integ); Integer sum = 0; for(Integer i = 1; i <= n; i++) { if(i % 3 == 0 || i % 5 == 0) sum += i; } System.out.print(sum); } public static void t4() { Scanner scanner = new Scanner (System. in ); String integ = scanner.nextLine(); Integer n = Integer.parseInt(integ); Integer fact = 1; for(Integer i = 2; i <= n; i++) { fact *= i; } System.out.print(fact); } public static void t5() { Scanner scanner = new Scanner (System. in ); String integ = scanner.nextLine(); Integer n = Integer.parseInt(integ); Integer div = 2; Boolean f = true; while(f && div <= n/2) { if(n % div == 0) f = false; div++; } System.out.print(f); } public static Integer fib(Integer n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); } public static void t6() { Scanner scanner = new Scanner (System. in ); String integ = scanner.nextLine(); Integer n = Integer.parseInt(integ); System.out.print(fib(n)); } public static void t7() { Scanner scanner = new Scanner (System. in ); String integ = scanner.nextLine(); Integer n = Integer.parseInt(integ); for(Integer i = n; i >= 2; i--) { if(n % i == 0) { Integer div = 2; Boolean f = true; while(f && div <= i/2) { if(i % div == 0) f = false; div++; } if(f) { System.out.print(i); break; } } } } }<file_sep>/lab2/ex1.java package lab2; import java.util.Scanner; public class ex1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] studentGrades = new int[20]; int grade = scanner.nextInt(); int i = 0; float avg = 0; while(grade != -1 && i < studentGrades.length) { studentGrades[i] = grade; i++; avg += grade; grade = scanner.nextInt(); } if(i != 0) { avg /= i; System.out.println(avg); } else System.out.println("Nu se poate face media."); } } <file_sep>/proiect/src/paymentMethods/PaymentMethod.java package paymentMethods; public class PaymentMethod { protected double totalPaid; } <file_sep>/proiect/src/Driver.java import order.Order; import order.ProductItem; import priceConventions.PricePerQuantity; import priceConventions.PricePerUnit; import products.Product; import java.util.HashMap; import java.util.List; import java.util.Scanner; public class Driver { public static void main(String[] args) { CashRegister register = new CashRegister(); menu(register); } public static void menu(CashRegister register) { System.out.println("\n1. Listati produsele\n2. Adauga produs\n3. Editeaza Produs\n4. Sterge produs\n5. Comanda noua\n6. Istoric comenzi\n7. Adauga categorie\n8. Listare categorii\n9. Audit\n10. Exit"); Scanner scanner = new Scanner(System.in); int choice = scanner.nextInt(); switch (choice) { case 1: listProducts(register); break; case 2: addProduct(register); break; case 3: editProduct(register); break; case 4: deleteProduct(register); break; case 5: newOrder(register); break; case 6: listOrders(register); break; case 7: addCategory(register); break; case 8: listCategories(register); break; case 9: listLogs(register); break; case 10: break; default: menu(register); } } private static void listLogs(CashRegister register) { register.listLogs(); menu(register); } private static void listOrders(CashRegister register) { register.listOrders(); menu(register); } private static void newOrder(CashRegister register) { register.createNewOrder(); Scanner scanner = new Scanner(System.in); String line; while(scanner.hasNextLine()) { line = scanner.nextLine(); String[] spl = line.split(" "); if(spl[0].equals("+")) { ProductItem pi = new ProductItem(register.getProduct(spl[1]), Double.parseDouble(spl[2])); if (register.addToOrder(spl[1], Double.parseDouble(spl[2]))) System.out.println(pi + "SUBTOTAL: " + register.getCurrentOrder().getTotalPrice() + " RON"); else System.out.println("Produsul nu exista!"); } if(spl[0].equals("?")) System.out.println(register.getCurrentOrder()); if(spl[0].equals("-")) { if (register.removeFromOrder(spl[1])) System.out.println("Produs sters."); else System.out.println("Produsul nu era in comanda!"); } if(spl[0].equals("P")) { if(spl[1].equals("Cash")) register.payCurrentOrderCash(Double.parseDouble(spl[2])); if(spl[1].equals("Card")) register.payCurrentOrderCard(spl[2], spl[3]); System.out.println(register.getCurrentOrder()); System.out.println("Zi buna! Urmatoarea comanda."); break; } if(spl[0].equals("D")) { register.discardCurrentOrder(); System.out.println("Comanda anulata.\nZi buna! Urmatoarea comanda."); break; } } menu(register); } private static void deleteProduct(CashRegister register) { Scanner scanner = new Scanner(System.in); String barcode; System.out.print("Cod bare produs: "); barcode = scanner.next(); Product product = register.getProduct(barcode); boolean res = register.deleteProduct(barcode); if(res) System.out.println("Produsul a fost sters cu succes."); else System.out.println("Produsul nu exista."); menu(register); } private static void editProduct(CashRegister register) { String barcode, name, unit; String price; Scanner scanner = new Scanner(System.in); System.out.print("Cod bare produs: "); barcode = scanner.next(); Product product = register.getProduct(barcode); if(product != null) { System.out.print(String.format("Nume produs (%s): ", product.getName())); scanner.nextLine(); name = scanner.nextLine(); if(name.length() > 0) product.setName(name); unit = (product.getPrice() instanceof PricePerUnit) ? "bucata" : ((PricePerQuantity) product.getPrice()).measureUnit; System.out.print(String.format("Unitate masura (%s): ", unit)); unit = scanner.nextLine(); System.out.print(String.format("Pret (%.2f): ", product.getPrice().price)); price = scanner.nextLine(); double _price; if(price.length() > 0) _price = Double.parseDouble(price); else _price = product.getPrice().price; if(unit.length() == 0) unit = (product.getPrice() instanceof PricePerUnit) ? "bucata" : ((PricePerQuantity) product.getPrice()).measureUnit; if(unit.equals("bucata")) { product.setPrice(_price); } else product.setPrice(_price, unit); if(register.editProduct(product)) { System.out.println("Produsul a fost modificat cu succes."); } else System.out.println("Eroare."); } else System.out.println("Produsul nu exista."); menu(register); } private static void addProduct(CashRegister register) { String barcode, name, unit; double price; Scanner scanner = new Scanner(System.in); System.out.print("Cod bare produs: "); barcode = scanner.next(); scanner.nextLine(); System.out.print("Nume produs: "); name = scanner.nextLine(); System.out.print("Unitate masura (implicit bucata): "); unit = scanner.nextLine(); System.out.print("Pret: "); price = scanner.nextDouble(); boolean res; if(unit.length() == 0) { res = register.addProduct(barcode, name, price); } else { res = register.addProduct(barcode, name, price, unit); } if(res) System.out.println("Produs adaugat."); else System.out.println("Exista deja un produs cu acest cod de bare!"); menu(register); } public static void listProducts(CashRegister register) { System.out.println("Produse in baza de date: "); register.listProducts(); menu(register); } public static void addCategory(CashRegister register) { String name; Scanner scanner = new Scanner(System.in); System.out.print("Nume categorie: "); name = scanner.nextLine(); register.addCategory(name); menu(register); } public static void listCategories(CashRegister register) { register.listCategories(); menu(register); } } <file_sep>/proiect/src/products/Product.java package products; import priceConventions.Price; import priceConventions.PricePerQuantity; import priceConventions.PricePerUnit; public class Product { private String barcode; private String name; Price price; public Product(String barcode, String name, double price) { this.barcode = barcode; this.name = name; this.price = new PricePerUnit(price); } public Product(String barcode, String name, double price, String unit) { this.barcode = barcode; this.name = name; this.price = new PricePerQuantity(price, unit); } public String getBarcode() { return barcode; } public void setBarcode(String barcode) { this.barcode = barcode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Price getPrice() { return price; } public void setPrice(double price) { this.price = new PricePerUnit(price); } public void setPrice(double price, String unit) { this.price = new PricePerQuantity(price, unit); } public void setPrice(Price price) { this.price = price; } @Override public String toString() { return barcode + " | " + name + " | " + price.toString() + "\n"; } } <file_sep>/proiect/src/config/Test.java package config; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Test { public static void main(String[] args) { Connection db = DatabaseConfiguration.getDatabaseConnection(); try { DatabaseSetup.setup(); } catch (SQLException e) { e.printStackTrace(); } /*try { Statement stmt = db.createStatement(); ResultSet rs = stmt.executeQuery("select * from pet"); while(rs.next()) System.out.println(rs.getString(1)+" "+rs.getString(2)); } catch (SQLException e) { e.printStackTrace(); } */ } } <file_sep>/proiect/src/priceConventions/PricePerUnit.java package priceConventions; public class PricePerUnit extends Price { public PricePerUnit(double p) { this.price = p; } @Override public String toString() { return String.format("%.2f", price) + " RON"; } } <file_sep>/proiect/src/config/DatabaseSetup.java package config; import java.sql.*; public class DatabaseSetup { public static void setup() throws SQLException { DatabaseSetup.setupTableProducts(); DatabaseSetup.setupTableCategories(); DatabaseSetup.setupTableOrders(); DatabaseSetup.setupTableAudit(); } private static void setupTableProducts() { Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection(); String sql = "CREATE TABLE IF NOT EXISTS products ( barcode varchar(40) NOT NULL PRIMARY KEY, name varchar(40) NOT NULL, " + "price double NOT NULL, unit varchar(40));"; try { Statement stmt = databaseConnection.createStatement(); stmt.execute(sql); } catch (SQLException e) { e.printStackTrace(); } } private static void setupTableCategories() { Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection(); String sql = "CREATE TABLE IF NOT EXISTS product_categories ( id integer AUTO_INCREMENT PRIMARY KEY, name varchar(40) NOT NULL);"; try { Statement stmt = databaseConnection.createStatement(); stmt.execute(sql); } catch (SQLException e) { e.printStackTrace(); } } private static void setupTableOrders() { Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection(); String sql = "CREATE TABLE IF NOT EXISTS orders (\n" + "id integer AUTO_INCREMENT PRIMARY KEY,\n" + "total_price double NOT NULL,\n" + "payment_method varchar(40) NOT NULL,\n" + "card_number varchar(40),\n" + "card_type varchar(40),\n" + "handled_cash varchar(40)\n" + ");"; String sql2 = "CREATE TABLE IF NOT EXISTS order_products (\n" + "id integer AUTO_INCREMENT PRIMARY KEY,\n" + "order_id integer NOT NULL,\n" + "product_barcode varchar(40) NOT NULL REFERENCES products(id) ON DELETE CASCADE,\n" + "quantity double NOT NULL,\n" + "FOREIGN KEY (order_id)\n" + "REFERENCES orders(id) ON DELETE CASCADE,\n" + "FOREIGN KEY (product_barcode)\n" + "REFERENCES products(barcode) ON DELETE CASCADE);"; try { Statement stmt = databaseConnection.createStatement(); stmt.execute(sql); stmt.execute(sql2); } catch (SQLException e) { e.printStackTrace(); } } private static void setupTableAudit() { Connection databaseConnection = DatabaseConfiguration.getDatabaseConnection(); String sql = "CREATE TABLE IF NOT EXISTS audit ( id integer AUTO_INCREMENT PRIMARY KEY, action_name varchar(40) NOT NULL, timestamp timestamp NOT NULL);"; try { Statement stmt = databaseConnection.createStatement(); stmt.execute(sql); } catch (SQLException e) { e.printStackTrace(); } } } <file_sep>/lab1/pb2.java import java.util.Scanner; public class pb2 { public static void main(String[] args) { Scanner scanner = new Scanner (System. in ); String integ = scanner.nextLine(); Integer a = Integer.parseInt(integ); integ = scanner.nextLine(); Integer b = Integer.parseInt(integ); String r1 = a.toString(); String r2 = a.toString(); String r3 = a.toString(); if(a == b) r1 += " == " + b; else r1 += " != " + b; if(a < b) { r2 += " < " + b; r3 += " <= " + b; } else { r2 += " > " + b; r3 += " >= " + b; } System.out.println(r1); System.out.println(r2); System.out.println(r3); } }<file_sep>/README.md # Teme la PAO <NAME>, Gr. 231 <file_sep>/proiect/src/priceConventions/PricePerQuantity.java package priceConventions; public class PricePerQuantity extends Price { public String measureUnit; public PricePerQuantity(double p, String unit) { this.price = p; this.measureUnit = unit; } @Override public String toString() { return String.format("%.2f", price) + " RON/" + measureUnit; } } <file_sep>/lab1/pb1.java public class pb1 { public static void main(String[] args) { for(Integer i = 1; i <= 99; i++) if(i % 2 == 1) { String myString = i.toString(); System.out.println(myString); } } }<file_sep>/proiect/src/paymentMethods/PaymentMethodCard.java package paymentMethods; public class PaymentMethodCard extends PaymentMethod { String cardNumber; String cardType; public PaymentMethodCard(String cardNumber, String cardType, double totalPaid) { this.cardNumber = cardNumber; this.cardType = cardType; this.totalPaid = totalPaid; } public String getCardNumber() { return cardNumber; } public String getCardType() { return cardType; } @Override public String toString() { return String.format("Platit cu cardul %s %s. Total platit %.2f RON", cardType, cardNumber, totalPaid); } }
74e457f75934aefe3616386c63e32323acdee703
[ "Markdown", "Java" ]
17
Java
haginus/pao-labs
4554599c1cd1f9e16d26f3aaa20e4cbe6873b3c0
52e6b4741f15b3f8eddf27aeda206164df8ddb3c
refs/heads/master
<file_sep>const path = require('path'); const webpack = require('webpack'); const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const V8LazyParseWebpackPlugin = require('v8-lazy-parse-webpack-plugin'); const CompressionWebpackPlugin = require('compression-webpack-plugin'); module.exports = { devtool: 'sourcemap', entry: { app: './src/index.js', vendor: './src/vendor.js' }, output: { filename: '[name].chunk.js', path: path.resolve(__dirname, "./dist") }, resolve: { alias: { vue: 'vue/dist/vue.js' } }, module: { rules: [ {test: /\.js/, loader: 'babel-loader'}, {test: /\.html/, loader: 'html-loader'}, {test: /\.png|jpg/, loader: 'url-loader?limit=4000'}, {test: /\.css/, loader: ExtractTextWebpackPlugin.extract({loader: 'css-loader?modules=true&localIdentName=[name]__[local]___[hash:base64:5]'})} ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: ['vendor', 'inline'], minChunks: Infinity }), new V8LazyParseWebpackPlugin(), // new webpack.optimize.UglifyJsPlugin({ // output: { // comments: false // }, // compress: { // warnings: false, // conditionals: true, // unused: true, // comparisons: true, // sequences: true, // dead_code: true, // evaluate: true, // if_return: true, // join_vars: true, // negate_iife: false // } // }), new ExtractTextWebpackPlugin({filename: '[name].css', allChunks: true}), new webpack.ProgressPlugin(), new CompressionWebpackPlugin({ asset: "[path].gz[query]", algorithm: "gzip", test: /\.js$|\.html$/, threshold: 10240, minRatio: 0.8 }), new HtmlWebpackPlugin({ template: './src/index.html' }), ] }<file_sep>export * from './wa-header';<file_sep>import 'vue';<file_sep>import Vue from 'vue'; import config from './app/app.config'; // All upfront Vue components import './app/components'; //Register Vue Runtime new Vue(config);<file_sep>import Vue from 'vue'; import template from './template.html'; import data from './model'; const component = { data, template, created() { console.log("Holy freaking crap I'm lazy loaded"); } }; export default component;<file_sep>import styles from './style.css'; console.log("LAZY LOADED", styles); export default function() { const data = { component: { }, styles: styles } return data; }<file_sep>import styles from './style.css'; console.log("Not lazy loaded styles: ", styles); export default function() { const data = { component: { header: "webpack academy" }, styles } return data; }<file_sep># starter-page VueJS (Self-grokked) Homepage for webpack-academy ## Installation Fork and clone the repo! or `git clone https://github.com/webpack-academy/starter-page` - `cd` into the repository you just cloned - run `npm install` ## Usage ### dev server - run `npm run dev` - open browser, goto localhost:8080 - enjoy exploring around <file_sep>import Vue from 'vue'; import template from './template.html'; import data from './model'; const component = { data, template, components: { navigation: () => { return System.import('../wa-navigation/').then((module)=>{ return module.default; }); } } }; export default Vue.component('wa-header', component);
f61b2aefdcc8ad3374b61b182e146dd487075e1e
[ "JavaScript", "Markdown" ]
9
JavaScript
webpack-academy/starter-page
a78b6305face6f831c88083acfb927e48f5fd6ab
185d59de2ce29a0280707e65c96ae4e0781272c8
refs/heads/master
<file_sep>import React from "react"; import "./buyItem.css"; import NumberFormat from "react-number-format"; import db from "../CONFIG"; import ProductHover from "./ProductHover"; function BuyItem({ gameIcon, name, image, price, quantity, id, gameName, hero, quality, type, rarity, }) { const handleBuyClick = (event) => { event.preventDefault(); const cartItem = db.collection("buy").doc(id); cartItem.get().then((doc) => { if (doc.data().quantity > 1) { cartItem.update({ quantity: doc.data().quantity - 1, }); } else { cartItem.delete(); } }); const productItem = db.collection("product").doc(id); productItem.get().then((doc) => { if (doc.exists) { productItem.update({ quantity: doc.data().quantity + 1, }); } else { productItem.set({ gameIcon: gameIcon, name: name, image: image, price: price, quantity: 1, }); } }); }; return ( <div className="buyItem" onClick={handleBuyClick}> <div className="buyItem__image"> <img src={image} alt="" /> </div> <h4> <NumberFormat value={price} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Rs: "} /> </h4> <p>x{quantity}</p> <div className="buyItem__gameIcon"> <img src={gameIcon} alt="" /> </div> <ProductHover name={name} rarity={rarity} type={type} hero={hero} /> </div> ); } export default BuyItem; <file_sep>import React, { useEffect, useState } from "react"; import "./liveData.css"; //Database import import db from "../CONFIG"; //Component Import import RecentPurchase from "./RecentPurchase"; function LiveData() { const [liveData, setLiveData] = useState([]); useEffect(() => { db.collection("liveData") .orderBy("time", "desc") .onSnapshot((snapshot) => setLiveData( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }, []); return ( <div className="container"> <div className="title">Recent Purchases</div> <div className="liveData__dataContainer"> {liveData.map((item) => ( <RecentPurchase id={item.id} key={item.id} image={item.data.image} name={item.data.name} RpOrBal={item.data.RpOrBal} price={item.data.price} rarity={item.data.rarity} type={item.data.type} time={item.data.time} userImg={item.data.userImg} source={item.data.source} /> ))} </div> </div> ); } export default LiveData; <file_sep>import React from "react"; import { useHistory } from "react-router-dom"; //Material-ui imports import StoreRoundedIcon from "@material-ui/icons/StoreRounded"; import LocalAtmIcon from "@material-ui/icons/LocalAtm"; import EmailIcon from "@material-ui/icons/Email"; import ContactSupportIcon from "@material-ui/icons/ContactSupport"; import DeckRoundedIcon from "@material-ui/icons/DeckRounded"; import StyleIcon from "@material-ui/icons/Style"; //Css import import "./headerCenter.css"; function HeaderCenter() { const history = useHistory(); return ( <div className="header__center"> <div className="header__option" onClick={() => history.push("/store")}> <StoreRoundedIcon /> <div className="header__optionTitle">Store</div> </div> <div className="header__option" onClick={() => history.push("/community")} > <DeckRoundedIcon /> <div className="header__optionTitle">Marketplace</div> </div> <div className="header__option" onClick={() => history.push("/inventory")} > <StyleIcon /> <div className="header__optionTitle">inventory</div> </div> <div className="header__option" onClick={() => history.push("/sell")}> <LocalAtmIcon /> <div className="header__optionTitle">sell</div> </div> <div className="header__option"> <EmailIcon /> <div className="header__optionTitle">support</div> </div> <div className="header__option"> <ContactSupportIcon /> <div className="header__optionTitle">guide</div> </div> </div> ); } export default HeaderCenter; <file_sep>import React from "react"; /* import BuySection from "./BuySection"; import StoreSection from "./StoreSection"; */ import LandingPage from "./LandingPage"; import { useSelector } from "react-redux"; import { selectUser } from "../features/user/userSlice"; import "./storeMarket.css"; function StoreMarket() { const user = useSelector(selectUser); return ( <div className="storeMarket"> {!user ? <LandingPage /> : ""} <div style={{ height: "100vh", backgroundColor: "#1a1830", color: "#69cacb", display: "flex", alignItems: "center", flexDirection: "column", }} > <h1>Welcome</h1> <h4>A webpage is still in progress</h4> <h4> This empty page will be replaced by landing page and some extra stuffs </h4> </div> {/* <div className="storeSection"> <BuySection /> <StoreSection /> </div> */} </div> ); } export default StoreMarket; <file_sep>import React, { useEffect, useState } from "react"; import ShoppingCartIcon from "@material-ui/icons/ShoppingCart"; import "./buysection.css"; import BuyItem from "../Product/buyItem"; import db from "../CONFIG"; import Bill from "./Bill"; function BuySection() { const [cartItem, setCartItem] = useState([]); useEffect(() => { db.collection("buy").onSnapshot((snapshot) => setCartItem( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }, []); return ( <div className="storemarket__buySection"> <div className="storemarket__buyList"> <div className="buylist__header"> <ShoppingCartIcon /> <h4>You Receive</h4> </div> <div className="buylist__list"> {cartItem.map((item) => ( <BuyItem id={item.id} key={item.id} gameIcon={item.data.gameIcon} name={item.data.name} image={item.data.image} price={item.data.price} quantity={item.data.quantity} hero={item.data.hero} gameName={item.data.gameName} type={item.data.type} quality={item.data.quality} rarity={item.data.rarity} /> ))} </div> </div> <Bill cartItem={cartItem} /> </div> ); } export default BuySection; <file_sep>import React from "react"; //Css import import "./community.css"; //Material-Imports import Tabs from "@material-ui/core/Tabs"; import Tab from "@material-ui/core/Tab"; import Typography from "@material-ui/core/Typography"; import Box from "@material-ui/core/Box"; import PropTypes from "prop-types"; // Other import //Component import import MarketItems from "./MarketItems"; import ActiveListing from "./ActiveListing"; function TabPanel(props) { const { children, value, index, ...other } = props; return ( <div role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} {...other} > {value === index && ( <Box span={2}> <Typography component={"span"}>{children}</Typography> </Box> )} </div> ); } TabPanel.propTypes = { children: PropTypes.node, index: PropTypes.any.isRequired, value: PropTypes.any.isRequired, }; function a11yProps(index) { return { id: `simple-tab-${index}`, "aria-controls": `simple-tabpanel-${index}`, }; } function CommunityMarket() { const [value, setValue] = React.useState(0); const handleChange = (event, newValue) => { setValue(newValue); }; return ( <div className="community"> <div className="community__topBar"> <h1>Community Market</h1> <p> Buy and sell items with community members for Balance and Reward Points. </p> </div> <div className="community__choice"> <Tabs value={value} onChange={handleChange} aria-label="simple tabs example" > <Tab label="Market" {...a11yProps(0)} /> <Tab label="My active Listings" {...a11yProps(1)} /> </Tabs> </div> <TabPanel value={value} index={0}> <MarketItems /> </TabPanel> <TabPanel value={value} index={1}> <ActiveListing /> </TabPanel> </div> ); } export default CommunityMarket; <file_sep>import React from "react"; import "./dialog.css"; import NumberFormat from "react-number-format"; function DialogFinalConfirm({ id, key, gameIcon, name, image, price, quantity, }) { return ( <div className="dialog__box"> <div className="dialog__product"> <div className="dialog__productName">{name}</div> <div className="dialog__productDetails"> <div className="dialog__productQuantity"> <div>Quantity :</div> <div>{quantity}</div> </div> <div className="dialog__productRate"> <div>Rate :</div> <NumberFormat value={price} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" /> </div> <div className="dialog__productAmount"> <div>Amount :</div> <NumberFormat value={quantity * price} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" /> </div> </div> </div> </div> ); } export default DialogFinalConfirm; <file_sep>import { configureStore } from "@reduxjs/toolkit"; import userReducer from "../features/user/userSlice"; import productReducer from "../features/product/productSlice"; import balanceReducer from "../features/balance/balanceSlice"; export default configureStore({ reducer: { user: userReducer, product: productReducer, balance: balanceReducer, }, }); <file_sep>import React, { useEffect, useState } from "react"; import TransactionDetail from "./TransactionDetail"; import db from "../CONFIG"; import "./transactionHistory.css"; function TransactionHistory() { const [transactionData, setTransactionData] = useState([]); //store all transaction history data /*--------------Pagination---------------*/ const [currentPage, setCurrentPage] = useState(1); //Current page const itemPerPage = Number(50); //Number of extra item load on each click //Get current items: const indexOfLastItem = currentPage * itemPerPage; //get index of last item of every page... //index of first item of every page...we need first transaction item always... const indexOfFirstItem = 0; //If we need middle part of page then 0 will be replaced by indexOfLastItem-itemPerPage... const currentPost = transactionData.slice(indexOfFirstItem, indexOfLastItem); //Render only specific part of array const totalItem = transactionData.length; const totalItemPagination = currentPost.length; const handlePagination = (event) => { event.preventDefault(); setCurrentPage(currentPage + 1); }; useEffect(() => { db.collection("transaction") .orderBy("date", "desc") .onSnapshot((snapshot) => setTransactionData( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }, []); return ( <div className="transaction__body"> <div className="transaction__header"> <div className="transaction__headerDate">Date</div> <div className="transaction__headerDescription">Description</div> <div className="transaction__headerChange"> <div className="transaction__change">Change</div> <div className="transaction__changeRB"> <div className="transaction__changeRP">RP</div> <div className="transaction__changeBalance">Balance</div> </div> </div> <div className="transaction__headerWallet"> <div className="transaction__wallet">Wallet</div> <div className="transaction__walletRB"> <div className="transaction__walletRP">RP</div> <div className="transaction__walletBalance">Balance</div> </div> </div> </div> <div className="transaction__history"> {currentPost.map((item) => ( <TransactionDetail id={item.id} key={item.id} date={item.data.date} message={item.data.message} signRP={item.data.signRP} costRP={item.data.costRP} signBalance={item.data.signBalance} costBalance={item.data.costBalance} walletRP={item.data.walletRP} walletBalance={item.data.walletBalance} /> ))} <div className="transaction__pagination"> {totalItem !== totalItemPagination && ( <button className="transaction__btn" onClick={handlePagination}> Load More Transaction </button> )} </div> </div> </div> ); } export default TransactionHistory; <file_sep>import React from "react"; import "./storeItem.css"; import styled from "styled-components"; function ProductHover({ name, rarity, type, hero }) { return ( <span className="onHover__giveDetails"> <HoverTitle> <HoverName>{name}</HoverName> <HoverType> {rarity} {type} </HoverType> </HoverTitle> <HoverHero>Used by: {hero}</HoverHero> </span> ); } export default ProductHover; const HoverTitle = styled.div` box-shadow: 0px 5px 8px -9px rgba(255, 255, 255, 1); `; const HoverName = styled.div` font-size: 14px; box-shadow: 0px 5px 8px -9px rgba(255, 255, 255, 1); padding: 5px 0px; `; const HoverType = styled.div` font-size: 12px; padding: 5px 0px; `; const HoverHero = styled.div` padding-top: 5px; font-size: 12px; `; <file_sep>import React, { useEffect, useState } from "react"; import db from "../CONFIG"; import NotificationMessage from "./NotificationMessage"; function Notification() { const [notificationMessage, setNotificationMessage] = useState([]); useEffect(() => { db.collection("notification") .orderBy("time", "desc") .onSnapshot((snapshot) => setNotificationMessage( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }, []); return ( <> {notificationMessage.map((item) => ( <NotificationMessage id={item.id} key={item.id} image={item.data.image} time={item.data.time} message={item.data.message} /> ))} </> ); } export default Notification; <file_sep>import React, { useEffect, useState } from "react"; import "./discountStore.css"; //Database Import import db from "../CONFIG"; import DiscountBotItem from "./DiscountBotItem"; function DiscountStore() { const [discountItem, setDiscountItem] = useState([]); useEffect(() => { db.collection("instantSell") .orderBy("price", "asc") .onSnapshot((snapshot) => setDiscountItem( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }, []); return ( <div className="discountContainer"> <div className="discountBody"> {discountItem.map((item) => ( <DiscountBotItem id={item.id} key={item.id} image={item.data.image} name={item.data.name} price={item.data.price} hero={item.data.hero} gameIcon={item.data.gameIcon} gameName={item.data.gameName} type={item.data.type} rarity={item.data.rarity} quality={item.data.quality} /> ))} </div> </div> ); } export default DiscountStore; <file_sep>import React from "react"; import styled from "styled-components"; function SideDrawerOption({ title, Icon, clickMe }) { return ( <> <Option onClick={clickMe}> <Icon /> <Title>{title}</Title> </Option> </> ); } export default SideDrawerOption; const Option = styled.div` box-shadow: 0px 5px 8px -9px rgba(255, 255, 255, 0.75); display: flex; align-items: center; margin: 7px 0px; padding: 7px 0px 7px 20px; cursor: pointer; :hover { background-color: rgba(255, 255, 255, 0.7); color: #000; .MuiSvgIcon-root { color: #000; } } .MuiSvgIcon-root { font-size: x-large; color: #9acd32; } `; const Title = styled.div` margin-left: 10px; text-transform: capitalize; font-weight: 700; `; <file_sep>import { createSlice } from "@reduxjs/toolkit"; export const productSlice = createSlice({ name: "product", initialState: { loadImage: null, loadGameName: null, loadType: null, loadHeroName: null, loadRarity: null, loadGameIcon: null, }, reducers: { loadImage: (state, action) => { state.loadImage = action.payload; }, loadGameName: (state, action) => { state.loadGameName = action.payload; }, loadGameIcon: (state, action) => { state.loadGameIcon = action.payload; }, loadHeroName: (state, action) => { state.loadHeroName = action.payload; }, loadType: (state, action) => { state.loadType = action.payload; }, loadRarity: (state, action) => { state.loadRarity = action.payload; }, }, }); export const { loadImage, loadType, loadRarity, loadHeroName, loadGameName, loadGameIcon, } = productSlice.actions; export const selectImage = (state) => state.product.loadImage; export const selectType = (state) => state.product.loadType; export const selectRarity = (state) => state.product.loadRarity; export const selectHero = (state) => state.product.loadHeroName; export const selectGame = (state) => state.product.loadGameName; export const selectGameIcon = (state) => state.product.loadGameIcon; export default productSlice.reducer; <file_sep>import React from "react"; import NumberFormat from "react-number-format"; import Popover from "@material-ui/core/Popover"; import { Avatar, Typography } from "@material-ui/core"; import { makeStyles } from "@material-ui/core/styles"; import PopupState, { bindTrigger, bindPopover } from "material-ui-popup-state"; const useStyles = makeStyles((theme) => ({ popover: { pointerEvents: "none", }, })); function RecentPurchase({ id, image, name, RpOrBal, price, rarity, type, time, userImg, source, }) { const classes = useStyles(); const [anchorEl, setAnchorEl] = React.useState(null); const handlePopoverOpen = (event) => { setAnchorEl(event.currentTarget); }; const handlePopoverClose = () => { setAnchorEl(null); }; const open = Boolean(anchorEl); return ( <PopupState variant="popover"> {(popupState) => ( <> <Typography {...bindTrigger(popupState)} className="recentPurchase" onMouseEnter={handlePopoverOpen} onMouseLeave={handlePopoverClose} > <img src={image} alt="" /> </Typography> <Popover {...bindPopover(popupState)} className={classes.popover} open={open} anchorEl={anchorEl} anchorOrigin={{ vertical: "bottom", horizontal: "center" }} transformOrigin={{ vertical: "top", horizontal: "center" }} onClose={handlePopoverClose} disableRestoreFocus > <div className="recentPurchase__detail"> <div className="purchased__top"> <div className="purchased__itemName">{name}</div> <div className="purchased__itemRarity"> {rarity} {type} </div> </div> <div className="purchased__middle"> <div className="purchased__itemPrice"> {RpOrBal ? ( <NumberFormat value={price} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Rs: "} suffix={" /-"} /> ) : ( <NumberFormat value={price} displayType="text" suffix={" RP"} /> )} </div> <div className="purchased__source">{source} purchase</div> </div> <div className="purchased__bottom"> <div className="purchased__person"> Purchased By : <Avatar src={userImg} /> </div> <div className="purchased__date"> <p>Purchase Date :</p>{" "} {new Date(time?.toDate()).toLocaleString()} </div> </div> </div> </Popover> </> )} </PopupState> ); } export default RecentPurchase; <file_sep>import React from "react"; import db from "../CONFIG"; //Database import import firebase from "firebase"; //Timestamp from firebase : like this "firebase.firestore.FieldValue.serverTimestamp()" import { notificationCount } from "../features/user/userSlice"; import { useDispatch } from "react-redux"; function ItemInventory({ name, image, rarity, type, id }) { //Can't perform a React state update on an unmounted component. //This is a no-op, but it indicates a memory leak in your application. //To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. //I got this fucking stupid error on console....kaam chai vairaxa tara yo muji le dimaag kharab banayo... const dispatch = useDispatch(); const handleWithdraw = () => { db.collection("inventory").doc(id).delete(); dispatch(notificationCount()); db.collection("notification").add({ message: `Trade offer to your steam account with item named ${name} has been made. Check your steam account.`, time: firebase.firestore.FieldValue.serverTimestamp(), image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAABF1BMVEX///8AAAMAn9P/lgD/LEcAAAAA5Yv/Lkr/mwAA6Y0ArGhWDxgAKxsA7pF9SQIAibYAklkA2YQAd54ApdsAnM8AyHrNzc0Ak8S/v7/vKUN6enri4uLdJj7SJDvoKEHw8PC7IDQqKiuhHC2tra04ODjX19fJIzi2trbr6+uJiYm+cAEAQVYATWdCQkNNTU1xFCAsCA1jERyTGSmAFiQ7ChGWlpbrigBDKANmPAIAYYEAM0QAbpIAEBZeXl4XFxmEhIVIDBWuHjEbGxwgBgpsbG0XBAiioqOLUgKnYgHZfwAAKTcAHikAR18AcZYAv3QAbEIAgE4AJhglBgtR<KEY> }); }; return ( <div className="webInventory__item"> <div className="webInventory__itemTop"> <img src={image} alt="" /> <div className="webInventory__name">{name}</div> <div className="webInventory__rarity"> {rarity} {type} </div> </div> <button className="webInventory__send" onClick={handleWithdraw}> Withdraw </button> </div> ); } export default ItemInventory; <file_sep>import React, { useState } from "react"; import "./buysection.css"; import "./dialog.css"; import ShoppingCartIcon from "@material-ui/icons/ShoppingCart"; import NumberFormat from "react-number-format"; import Dialog from "@material-ui/core/Dialog"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import DialogTitle from "@material-ui/core/DialogTitle"; import DialogFinalConfirm from "./DialogFinalConfirm"; import { useSelector, useDispatch } from "react-redux"; import { selectUser, loginName, loginPhoto } from "../features/user/userSlice"; import { auth, provider } from "../CONFIG"; import db from "../CONFIG"; //import Button from "@material-ui/core/Button"; import Snackbar from "@material-ui/core/Snackbar"; import MuiAlert from "@material-ui/lab/Alert"; import { selectBalance, balanceCut, selectReward, rewardCut, rewardUp, } from "../features/balance/balanceSlice"; function Bill({ cartItem }) { const dispatch = useDispatch(); const user = useSelector(selectUser); //---------------------------------------------// const [confirmBillOpen, setConfirmBillOpen] = useState(false); //To open bill type of dialog const [confirmBillOpenRP, setConfirmBillOpenRP] = useState(false); //To open bill type of dialog const [successMessage, setSuccessMessage] = useState(false); //Message at bottom after purchase const [noItemMessage, setNoItemMessage] = useState(false); //Message when user clicked purchase without putting item in buy container. const [balanceLowMessage, setBalanceLowMessage] = useState(false); const [rewardLowMessage, setRewardLowMessage] = useState(false); const balance = useSelector(selectBalance); const reward = useSelector(selectReward); const handleClickOpenBalance = () => { if (totalCount() === 0) { setNoItemMessage(true); } else { if (totalPrice() > balance) { setBalanceLowMessage(true); } else { setConfirmBillOpen(true); } } }; const handleClickOpenRP = () => { if (totalCount() === 0) { setNoItemMessage(true); } else { if (totalPrice() > reward) { setRewardLowMessage(true); } else { setConfirmBillOpenRP(true); } } }; const handleClose = () => { setConfirmBillOpen(false); setConfirmBillOpenRP(false); }; //-----------------------------------------// const handleLogin = () => { auth .signInWithPopup(provider) .then((result) => { dispatch(loginName(result.user.displayName)); dispatch(loginPhoto(result.user.photoURL)); }) .catch((error) => { console.log(error.message); }); }; const handleConfirm = () => { //Some db stuffs need to be done....make new db collection called inventory...move db collection buy to db collection inventory cartItem.map((item) => db.collection("inventory").doc().set({ gameIcon: item.data.gameIcon, name: item.data.name, image: item.data.image, price: item.data.price, quantity: item.data.quantity, hero: item.data.hero, quality: item.data.quality, gameName: item.data.gameName, type: item.data.type, rarity: item.data.rarity, }) ); //Test item on sell container...directly send...just for test.... cartItem.map((item) => db.collection("sell").doc().set({ gameIcon: item.data.gameIcon, name: item.data.name, image: item.data.image, price: item.data.price, quantity: item.data.quantity, hero: item.data.hero, quality: item.data.quality, gameName: item.data.gameName, type: item.data.type, rarity: item.data.rarity, }) ); //delete item from buy box.... cartItem.map((item) => db.collection("buy").doc(item.id).delete()); dispatch(balanceCut(totalPrice())); dispatch(rewardUp(Number(purchaseReward) || 0)); setConfirmBillOpen(false); setSuccessMessage(true); }; const handleConfirmRP = () => { //Some db stuffs need to be done....make new db collection called inventory...move db collection buy to db collection inventory cartItem.map((item) => db.collection("inventory").doc().set({ gameIcon: item.data.gameIcon, name: item.data.name, image: item.data.image, price: item.data.price, quantity: item.data.quantity, }) ); //Test item on sell container...directly send...just for test.... cartItem.map((item) => db.collection("sell").doc().set({ gameIcon: item.data.gameIcon, name: item.data.name, image: item.data.image, price: item.data.price, quantity: item.data.quantity, }) ); //delete item from buy box.... cartItem.map((item) => db.collection("buy").doc(item.id).delete()); dispatch(rewardCut(totalPrice())); dispatch(rewardUp(Number(purchaseReward) || 0)); setConfirmBillOpenRP(false); setSuccessMessage(true); }; const totalCount = () => { let count = 0; cartItem.forEach((item) => { count += item.data.quantity; }); return count; }; const totalPrice = () => { let total = 0; cartItem.forEach((item) => { total += item.data.quantity * item.data.price; }); return total; }; const purchaseReward = parseInt(0.02 * totalPrice()).toFixed(2); function Alert(props) { return <MuiAlert elevation={6} variant="filled" {...props} />; } const handleCloseMessage = (event, reason) => { if (reason === "clickaway") { return; } setSuccessMessage(false); setNoItemMessage(false); setBalanceLowMessage(false); setRewardLowMessage(false); }; return ( <div className="storemarket__buyCheckout"> <div className="checkout__header"> <ShoppingCartIcon /> <h4>Bill</h4> </div> <div className="checkout__description"> <div className="checkout__descriptionDetails"> <p> Item Count: <NumberFormat className="checkout__number" value={totalCount()} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" /> </p> <p> Total price (Rs): <NumberFormat className="checkout__number" value={totalPrice()} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" suffix={"/-"} /> </p> </div> <div className="checkout__descriptionConfirm"> {!user ? ( <> <img onClick={handleLogin} style={{ cursor: "pointer" }} src="https://steamcdn-a.akamaihd.net/steamcommunity/public/images/steamworks_docs/english/sits_small.png" alt="logo" /> <p style={{ border: "2px solid green", borderRadius: 5, marginTop: 10, padding: 5, }} > You need to login in order to make purchase. </p> </> ) : ( <> <button className="checkout__button" onClick={handleClickOpenBalance} > Purchase from Balance </button> <button className="checkout__button" onClick={handleClickOpenRP}> Purchase from RP </button> <div className="checkout__descriptionConfirmMessage"> <p> <NumberFormat value={Number(purchaseReward)} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Reward Point (RP) : "} /> </p> <p>2% reward point on purchase.</p> <p>Check items on inventory after purchase.</p> </div> </> )} {/*Dialog Box for Purchase through Balance */} <Dialog open={confirmBillOpen} onClose={handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title"> {"Are you sure you want to purchase the following items?"} </DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> {cartItem.map((item) => ( <DialogFinalConfirm id={item.id} key={item.id} gameIcon={item.data.gameIcon} name={item.data.name} image={item.data.image} price={item.data.price} quantity={item.data.quantity} /> ))} </DialogContentText> <div className="dialog__footer"> <div className="dialog__footerName">Grand Total</div> <div className="dialog__footerAmount"> <NumberFormat value={totalPrice()} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"(Rs): "} suffix={"/-"} /> </div> </div> </DialogContent> <DialogActions> <button className="button__cancel" onClick={handleClose}> Cancel </button> <button className="button__confirm" onClick={handleConfirm}> Confirm </button> </DialogActions> </Dialog> {/*Dialog Box for Purchase through Reward point */} <Dialog open={confirmBillOpenRP} onClose={handleClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title"> {"Are you sure you want to purchase the following items?"} </DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> {cartItem.map((item) => ( <DialogFinalConfirm id={item.id} key={item.id} gameIcon={item.data.gameIcon} name={item.data.name} image={item.data.image} price={item.data.price} quantity={item.data.quantity} /> ))} </DialogContentText> <div className="dialog__footer"> <div className="dialog__footerName">Grand Total</div> <div className="dialog__footerAmount"> <NumberFormat value={totalPrice()} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"(Rs): "} suffix={"/-"} /> </div> </div> </DialogContent> <DialogActions> <button className="button__cancel" onClick={handleClose}> Cancel </button> <button className="button__confirm" onClick={handleConfirmRP}> Confirm </button> </DialogActions> </Dialog> {/*Success message snackbar*/} <Snackbar open={successMessage} autoHideDuration={6000} onClose={handleCloseMessage} anchorOrigin={{ vertical: "top", horizontal: "center", }} > <Alert onClose={handleCloseMessage} severity="success"> Thank you for the purchase! </Alert> </Snackbar> {/*No item snackbar */} <Snackbar open={noItemMessage} autoHideDuration={6000} onClose={handleCloseMessage} anchorOrigin={{ vertical: "top", horizontal: "center", }} > <Alert onClose={handleCloseMessage} severity="error"> You have not selected any item! </Alert> </Snackbar> {/*Balance low message snackbar*/} <Snackbar open={balanceLowMessage} autoHideDuration={6000} onClose={handleCloseMessage} anchorOrigin={{ vertical: "top", horizontal: "center", }} > <Alert onClose={handleCloseMessage} severity="error"> Insufficient balance! </Alert> </Snackbar> {/*Reward point low message snackbar*/} <Snackbar open={rewardLowMessage} autoHideDuration={6000} onClose={handleCloseMessage} anchorOrigin={{ vertical: "top", horizontal: "center", }} > <Alert onClose={handleCloseMessage} severity="error"> Insufficient Reward point! </Alert> </Snackbar> </div> </div> </div> ); } export default Bill; <file_sep>import React, { useState } from "react"; //Redux and slices import { useDispatch, useSelector } from "react-redux"; import { notificationCount } from "../features/user/userSlice"; import { recharge, rewardUp, selectBalance, selectReward, } from "../features/balance/balanceSlice"; //Material-UI imports import Dialog from "@material-ui/core/Dialog"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogTitle from "@material-ui/core/DialogTitle"; import CloseIcon from "@material-ui/icons/Close"; import Snackbar from "@material-ui/core/Snackbar"; import MuiAlert from "@material-ui/lab/Alert"; //Database import import db from "../CONFIG"; import firebase from "firebase"; //Only for notification timestamp //Other imports import NumberFormat from "react-number-format"; function SteamInventory({ gameIcon, name, image, price, quantity, id, gameName, hero, type, quality, rarity, }) { const dispatch = useDispatch(); const [sell, setSell] = useState(false); //On clicking an item, opening and closing first dialog box state..... const [instantSell, setInstantSell] = useState(false); //Dialog box open after clicking (Ok, Instant sell) button state... const [communityDialogOpen, setCommunityDialogOpen] = useState(false); //Dialog box open after clicking sell on community button.. const instantSellRate = Number(parseInt(price - price * 0.3)); //instant Sell price const instantReward = Number(parseInt(instantSellRate * 0.03).toFixed(2)); //instant reward point value const [communitySell, setCommunitySell] = useState(); // You receive: (Seller price input) state const [noInputPrice, setNoInputPrice] = useState(false); // Error Snackbar open if user click (Ok, sell on community) button without putting price in You Receive Input field. const [itemSetOnCommunity, setItemSetOnCommunity] = useState(false); //Snackbar open after user successfully listed the item in community market. const balance = useSelector(selectBalance); //Fetch balance from balanceSlice const reward = useSelector(selectReward); //Fetch reward from balanceSlice const communityBuyerRate = Number( parseInt(Number(communitySell) + Number(communitySell * 0.1)) ); //Buyer Pays: price(10% charge) const communityReward = Number(parseInt(communitySell * 0.02)); //reward point when selling in community market //A material-ui Lab code for snackbar (it's imported from material-ui) function Alert(props) { return <MuiAlert elevation={6} variant="filled" {...props} />; } /*1:First Dialog box function when clicking an item. */ //1(a) Opening a dialog box const handleSell = () => { setSell(true); }; //1(b) Closing a first dialog box const handleClose = () => { setSell(false); }; /*2: Dialog box function when clicking (Ok, Instant sell) button. */ //2(a) Opening a dialog box const handleInstant = () => { setInstantSell(true); }; //2(b) Closing a dialog box (triggered on clicking Cancel button and outside the dialog box) const handleCloseInstantSell = () => { setInstantSell(false); }; //2(c) Triggered on clicking confirm button in final confirmation dialog box of instant sell choice. //This will also close all dialog box...(both first and second) const handleInstantConfirm = () => { dispatch(recharge(Number(instantSellRate) || 0)); dispatch(rewardUp(Number(instantReward) || 0)); db.collection("sell").doc(id).delete(); setInstantSell(false); setSell(false); dispatch(notificationCount()); db.collection("notification").add({ message: `${name} sold instantly to website. Balance (Rs) : ${instantSellRate} /- has been credited to your website wallet.`, time: firebase.firestore.FieldValue.serverTimestamp(), image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSaD0Q45xrXb6J_YCgnefcHz76apJspQSho7M0mqS7vQnZP3mPj1jjWkBJngPSD4Lhi2UI&usqp=CAU", }); db.collection("instantSell").add({ image: image, name: name, rarity: rarity, type: type, price: instantSellRate, gameName: gameName, gameIcon: gameIcon, hero: hero, quality: quality, }); db.collection("transaction").add({ date: firebase.firestore.FieldValue.serverTimestamp(), message: "Store transaction. ( Item sold Instantly )", signRP: true, costRP: Number(instantReward), signBalance: true, costBalance: Number(instantSellRate), walletRP: Number(reward) + Number(instantReward), walletBalance: Number(balance) + Number(instantSellRate), }); }; /*3: Dialog box function when clicking (Ok, sell on community) button. */ //3(a) Opening a dialog box on clicking (Ok, sell on community) button. const handleCommunity = () => { //generate error snackbar if user forget to input price... if (!communitySell) { setNoInputPrice(true); } else { setCommunityDialogOpen(true); } }; //3(b) Closing a error snackbar const handleErrorSnackbar = (event, reason) => { if (reason === "clickaway") { return; } setNoInputPrice(false); }; //3(c) Closing a dialog on clicking cancel button as well as outside the dialog box const handleCloseCommunitySell = () => { setCommunityDialogOpen(false); }; //3(d) Triggered on clicking confirm button in final confirmation dialog box of community sell choice. //This will also close all dialog box...(both first and second) //This will also trigger a snackbar which tells the item is listed in community market. const handleCommunityConfirm = () => { db.collection("community").doc(id).set({ gameIcon: gameIcon, image: image, name: name, price: communityBuyerRate, quantity: 1, hero: hero, quality: quality, gameName: gameName, type: type, rarity: rarity, }); db.collection("listing").doc(id).set({ image: image, name: name, sellPrice: communityBuyerRate, getPrice: communitySell, time: firebase.firestore.FieldValue.serverTimestamp(), quality: quality, type: type, rarity: rarity, }); setItemSetOnCommunity(true); setCommunityDialogOpen(false); setSell(false); db.collection("sell").doc(id).delete(); dispatch(notificationCount()); db.collection("notification").add({ message: `Your item ${name} is listed on community market for sale.`, time: firebase.firestore.FieldValue.serverTimestamp(), image: "https://pngimage.net/wp-content/uploads/2018/05/estoque-icon-png-7.png", }); //Transaction history if item is sold...for future use... /* db.collection("transaction").add({ date: firebase.firestore.FieldValue.serverTimestamp(), message: "Community Market transaction. ( Purchase )", signRP: true, costRP: Number(purchaseReward), signBalance: false, costBalance: Number(price), walletRP: Number(reward) + Number(purchaseReward), walletBalance: Number(balance) + Number(price), }); */ }; //3(e) Closing success snackbar const handleSuccessSnackbar = (event, reason) => { if (reason === "clickaway") { return; } setItemSetOnCommunity(false); }; //-------------------------------------------------------------------// return ( <> <div className="steamInventory__item" onClick={handleSell}> <div className="steamInventory__itemTop"> <img src={image} /* src={` https://community.akamai.steamstatic.com/economy/image/${image}`} */ alt="" /> <div className="steamInventory__name">{name}</div> <div className="steamInventory__rarity"> {rarity} {type} </div> </div> <p> <NumberFormat value={price} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Rs: "} suffix={" /-"} /> </p> <button className="steamInventory__sell">Sell Now</button> </div> {/*First dialog box when clicking an item to sell */} <Dialog open={sell} onClose={handleClose} fullWidth={true} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title" className="dialog__title"> <div className="dialog__titleArrange"> <p>PUT AN ITEM UP FOR SALE</p> <CloseIcon onClick={handleClose} /> </div> </DialogTitle> <DialogContent> <div className="dialog__body"> <div className="dialog__header"> <div className="item__photo"> <img src={image} alt="" /> </div> <div className="item__details"> <div className="item__name">{name}</div> <h6> {rarity} {type} </h6> <div className="item__gameIcon"> <img src={gameIcon} alt="" /> <p>{gameName}</p> </div> </div> </div> <div className="dialog__deals"> <div className="deals__instantSell"> <div className="instantSell__rate"> <h4> <NumberFormat value={instantSellRate} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Instant Sell This At Rs: "} suffix={"/-"} /> </h4> </div> <div className="instantSell__reward"> <p> <NumberFormat value={instantReward} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Reward Point (RP) : "} /> </p> <p>3% round off RP on instant sell.</p> </div> </div> <div className="deals__communitySell"> <div className="communitySell__header">Sell on community</div> <div className="youReceive"> You Receive (Rs) : <input placeholder="Enter amount" type="number" value={communitySell} onChange={(e) => setCommunitySell(e.target.value)} /> </div> <div className="buyerPays"> <p> <NumberFormat value={communityBuyerRate} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Buyer Pays (Rs) : "} suffix={" /- (includes fees)"} /> </p> </div> <div className="communitySell__reward"> <p> <NumberFormat value={communityReward} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Reward Point (RP) : "} /> </p> <p>2% round off RP on community sell.</p> </div> </div> </div> </div> </DialogContent> <DialogActions className="dialog__action"> <button onClick={handleInstant} color="primary"> Ok, Instant Sell </button> <button color="primary" onClick={handleCommunity}> OK, Sell On Community </button> </DialogActions> </Dialog> {/*Instant sell confirmation dialog box(This dialog box opens when we clicked (ok, Instant sell) button) */} <Dialog open={instantSell} onClose={handleCloseInstantSell} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title" className="dialog__title"> Are you sure you want to instantly sell your item {name} ? </DialogTitle> <DialogContent> <div style={{ color: "#61c9ce" }}> <h4>You will receive :</h4> <h4> <NumberFormat value={instantSellRate} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Balance (Rs) : "} suffix={" /-"} /> </h4> <h4>Reward Point (RP) : {instantReward}</h4> </div> </DialogContent> <DialogActions className="dialog__action"> <button onClick={handleCloseInstantSell}>Cancel</button> <button onClick={handleInstantConfirm}>Confirm</button> </DialogActions> </Dialog> {/* Community sell confirmation dialog box */} <Dialog open={communityDialogOpen} onClose={handleCloseCommunitySell} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title" className="dialog__title"> Are you sure you want to list your item {name} on community market? </DialogTitle> <DialogContent> <div style={{ color: "#61c9ce" }}> <p> Someone from community will buy your item. Upon successful community transaction, you will receive : </p> <h4> <NumberFormat value={parseInt(communitySell, 10)} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Balance (Rs) : "} suffix={" /-"} /> </h4> <h4>Reward point (RP) : {communityReward}</h4> </div> </DialogContent> <DialogActions className="dialog__action"> <button onClick={handleCloseCommunitySell}>Cancel</button> <button onClick={handleCommunityConfirm}>Confirm</button> </DialogActions> </Dialog> {/*Error snackbar if price is not set by user on community market */} <Snackbar open={noInputPrice} autoHideDuration={6000} onClose={handleErrorSnackbar} > <Alert onClose={handleErrorSnackbar} severity="error"> You must put your selling price! </Alert> </Snackbar> {/*Success snackbar after user successfully listed item on community market */} <Snackbar open={itemSetOnCommunity} autoHideDuration={6000} onClose={handleSuccessSnackbar} anchorOrigin={{ horizontal: "center", vertical: "top", }} > <Alert onClose={handleSuccessSnackbar} severity="success"> Your item is listed on community market </Alert> </Snackbar> </> ); } export default SteamInventory; <file_sep># steambazarnepal This is a simple project - something related to ecommerce. You can check the demo version here https://steambazarnepal.web.app/store <file_sep>import { createSlice } from "@reduxjs/toolkit"; export const userSlice = createSlice({ name: "user", initialState: { name: "Demo Project", photo: "https://icon-library.com/images/cool-profile-icon/cool-profile-icon-10.jpg", /* name: null, photo: null, */ count: 0, }, reducers: { loginName: (state, action) => { state.name = action.payload; }, loginPhoto: (state, action) => { state.photo = action.payload; }, notificationCount: (state) => { state.count += 1; }, notificationReset: (state) => { state.count = 0; }, logoutName: (state, action) => { state.name = action.payload; }, logoutPhoto: (state, action) => { state.photo = action.payload; }, }, }); export const { loginName, loginPhoto, logoutName, logoutPhoto, notificationCount, notificationReset, } = userSlice.actions; export const selectUser = (state) => state.user.name; export const selectPhoto = (state) => state.user.photo; export const selectNotification = (state) => state.user.count; export default userSlice.reducer; <file_sep>import React, { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; //Import redux and slices import { selectImage, selectGame, selectHero, selectType, selectRarity, selectGameIcon, } from "../features/product/productSlice"; import { useSelector } from "react-redux"; //Import database import db from "../CONFIG"; //Css import import "./communitySelectItem.css"; //Import components import CommunityEachProduct from "./CommunityEachProduct"; //Import material-UI import Pagination from "@material-ui/lab/Pagination"; function CommunitySelectItem() { const image = useSelector(selectImage); //Get image const gameName = useSelector(selectGame); //Get item name const hero = useSelector(selectHero); //Get hero name const type = useSelector(selectType); //Get item type const rarity = useSelector(selectRarity); //Get item rarity const gameIcon = useSelector(selectGameIcon); //Get game icon const { name } = useParams(); //Dynamic routing params const [itemFetch, setItemFetch] = useState([]); // Get all item of same name------ /*--------------Pagination---------------*/ //total number of items in community const totalItem = itemFetch.length; const [currentPage, setCurrentPage] = useState(1); //Current page of pagination const itemPerPage = Number(5); //Number of items in each page //Get current items: const indexOfLastItem = currentPage * itemPerPage; //get index of last item of every page... const indexOfFirstItem = indexOfLastItem - itemPerPage; //index of first item of every page... const currentPost = itemFetch.slice(indexOfFirstItem, indexOfLastItem); //total pagination pages const noOfPage = Number(parseInt(totalItem / itemPerPage)) + Number(1); //Pagination function---- const handlePagination = (event, value) => { setCurrentPage(value); }; //Used in pagination result sentence let result = indexOfLastItem; if (indexOfLastItem >= totalItem) { result = totalItem; } else { result = indexOfLastItem; } //Use effect hook---------------------------------- //Here it loads all the item from same name in an ascending order--------------- useEffect(() => { db.collection("community") .where("name", "==", name) .orderBy("price", "asc") .onSnapshot((snapshot) => setItemFetch( snapshot.docs.map((item) => ({ id: item.id, data: item.data(), })) ) ); }, [name]); return ( <div className="itemContainer"> <div className="item__allDetails"> <div className="item__image"> <img src={image} alt="" /> </div> <div className="item__description"> <div className="item__name"> <h2>{name}</h2> </div> <div className="item__game"> <div className="game__logo"> <img src={gameIcon} alt="" /> </div> <div className="game__title"> <h5>{gameName}</h5> <h5> {rarity} {type} </h5> </div> </div> <div className="hero__name">Used by : {hero}</div> </div> </div> <div className="item__lists"> {currentPost.map((item) => ( <CommunityEachProduct id={item.id} key={item.id} name={item.data.name} price={item.data.price} gameIcon={item.data.gameIcon} image={item.data.image} hero={item.data.hero} quality={item.data.quality} gameName={item.data.gameName} rarity={item.data.rarity} type={item.data.type} /> ))} </div> <div className="community__pagination"> <div className="pagination__results"> Showing {indexOfFirstItem + 1}-{result} of {totalItem} results </div> <div className="pagination__jump"> <Pagination count={noOfPage} defaultPage={currentPage} boundaryCount={2} size="small" onChange={handlePagination} /> </div> </div> </div> ); } export default CommunitySelectItem; <file_sep>import React from "react"; import { Link } from "react-router-dom"; //Redux and slices import { useDispatch } from "react-redux"; import { loadImage, loadType, loadRarity, loadGameName, loadHeroName, loadGameIcon, } from "../features/product/productSlice"; //Other imports import NumberFormat from "react-number-format"; function CommunityProduct({ name, quantity, price, gameIcon, image, gameName, hero, type, quality, rarity, }) { const dispatch = useDispatch(); //This will be changed later...Now this is just to send some data to redux and render the selected item after clicking an item from community market------ const sendImage = () => { dispatch(loadImage(image)); dispatch(loadType(type)); dispatch(loadRarity(rarity)); dispatch(loadGameName(gameName)); dispatch(loadHeroName(hero)); dispatch(loadGameIcon(gameIcon)); }; return ( <Link to={`/community/${name}`} className="link__to" onClick={sendImage}> <div className="community__product"> <div className="community__productImage"> <img src={image} alt="" /> <div className="community__productQuantity"> Quantity : {quantity} </div> <div className="product__gameIcon"> <img src={gameIcon} alt="" /> </div> </div> <div className="community__productTitle"> <h4>{name}</h4> <div className="community__productPrice"> <p> <NumberFormat value={price} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Starting at (Rs) : "} suffix={" /-"} /> </p> </div> </div> </div> </Link> ); } export default CommunityProduct; <file_sep>import React, { useEffect, useState } from "react"; //Redux and slices import { useDispatch } from "react-redux"; import { loadGameName } from "../features/product/productSlice"; //Material imports import Pagination from "@material-ui/lab/Pagination"; import ExpandMoreIcon from "@material-ui/icons/ExpandMore"; import ExpandLessIcon from "@material-ui/icons/ExpandLess"; import SearchIcon from "@material-ui/icons/Search"; //Css import import "./marketItems.css"; //Component import import CommunityProduct from "./CommunityProduct"; //Database Import import db from "../CONFIG"; function CommunityMarket() { const dispatch = useDispatch(); const [community, setcommunity] = useState([]); //loads item with number of quantity const [priceSort, setPriceSort] = useState(false); //Sort price useState const [quantitySort, setQuantitySort] = useState(false); //Sort quantity useState /*--------------Pagination---------------*/ const totalItem = community.length; //total number of items in community const [currentPage, setCurrentPage] = useState(1); //Current page of pagination const itemPerPage = Number(10); //Number of items in each page //Get current items: const indexOfLastItem = currentPage * itemPerPage; //get index of last item of every page... const indexOfFirstItem = indexOfLastItem - itemPerPage; //index of first item of every page... const currentPost = community.slice(indexOfFirstItem, indexOfLastItem); //Render only specific part of array //total pagination pages const noOfPage = Number(parseInt(totalItem / itemPerPage)) + Number(1); //Pagination extra----to render a result line------------- let result = indexOfLastItem; if (indexOfLastItem >= totalItem) { result = totalItem; } else { result = indexOfLastItem; } //End of pagination---------------------------------------------------------------------------------- //Use effect hook---------------------------------------------------------- useEffect(() => { db.collection("community").onSnapshot((snapshot) => setcommunity( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }, []); //Filter by game---------------- //Dota2 const handleDota2 = () => { setCurrentPage(1); dispatch(loadGameName("Dota 2")); db.collection("community") .where("gameName", "==", "Dota 2") .onSnapshot((snapshot) => setcommunity( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }; //Csgo const handleCsgo = () => { setCurrentPage(1); dispatch(loadGameName("Counter-Strike: Global Offensive")); db.collection("community") .where("gameName", "==", "Counter-Strike: Global Offensive") .onSnapshot((snapshot) => setcommunity( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }; //sorting price (ascending and descending both) const sortPrice = () => { setPriceSort(!priceSort); priceSort ? community.sort((first, second) => { return first.data.price - second.data.price; }) : community.sort((first, second) => { return second.data.price - first.data.price; }); }; //Same function as price sorting....currently it does price sort....later on we just change price with quantity in function return part.. const sortQuantity = () => { setQuantitySort(!quantitySort); quantitySort ? community.sort((first, second) => { return first.data.price - second.data.price; }) : community.sort((first, second) => { return second.data.price - first.data.price; }); }; //Pagination function---clicking different page and showing up the items--- const handlePagination = (event, value) => { setCurrentPage(value); }; return ( <div className="community__body"> <div className="community__navbar"> <div className="community__navbarLeft"> <div className="community__navbarLeftGameFilter" onClick={handleDota2} > <img src="https://1.bp.blogspot.com/-GplgZlvkXSc/Uk_3BipvAlI/AAAAAAAAAJE/NIU9Sm2vSVU/s1600/Dota2-Filled.png" alt="" /> <div className="gameTitle">Dota2</div> </div> <div className="community__navbarLeftGameFilter" onClick={handleCsgo}> <img src="https://www.meme-arsenal.com/memes/d81f1fc73c38e2cfacbd493b5d58509c.jpg" alt="" /> <div className="gameTitle">CSGO</div> </div> <div className="filterPriceQuantity"> <div className="filterBy" onClick={sortPrice}> <p>Price</p> {priceSort ? <ExpandMoreIcon /> : <ExpandLessIcon />} </div> <div className="filterBy" onClick={sortQuantity}> <p>Quantity</p> {quantitySort ? <ExpandMoreIcon /> : <ExpandLessIcon />} </div> </div> </div> <div className="community__navbarRight"> <div className="searchBox"> <input placeholder="search item" /> </div> <div className="search__icon"> <SearchIcon /> </div> </div> </div> <div className="community__data"> <div className="community__itemsContainer"> {currentPost.map((item) => ( <CommunityProduct id={item.id} key={item.id} gameIcon={item.data.gameIcon} name={item.data.name} price={item.data.price} image={item.data.image} quantity={item.data.quantity} hero={item.data.hero} quality={item.data.quality} gameName={item.data.gameName} rarity={item.data.rarity} type={item.data.type} /> ))} </div> <div className="community__pagination"> <div className="pagination__results"> Showing {indexOfFirstItem + 1}-{result} of {totalItem} results </div> <div className="pagination__jump"> <Pagination count={noOfPage} page={currentPage} size="small" onChange={handlePagination} /> </div> </div> </div> </div> ); } export default CommunityMarket; <file_sep>import React, { useEffect, useRef, useState } from "react"; import "./storesection.css"; import StoreItem from "../Product/StoreItem"; import StoreRoundedIcon from "@material-ui/icons/StoreRounded"; import SearchIcon from "@material-ui/icons/Search"; import ArrowDropDownIcon from "@material-ui/icons/ArrowDropDown"; import { useDispatch } from "react-redux"; import { loadGameName } from "../features/product/productSlice"; import db from "../CONFIG"; import { ClickAwayListener } from "@material-ui/core"; function StoreSection() { const dispatch = useDispatch(); const [product, setProduct] = useState([]); const [open, setOpen] = useState(false); const handleDropdown = (event) => { event.preventDefault(); setOpen(!open); }; const handleLowToHighSort = (event) => { product.sort((first, second) => { return first.data.price - second.data.price; }); setOpen(false); }; const handleHighToLowSort = (event) => { product.sort((first, second) => { return second.data.price - first.data.price; }); setOpen(false); }; const anchorRef = useRef(null); const handleSortDropdownClose = (event) => { if (anchorRef.current && anchorRef.current.contains(event.target)) { return; } setOpen(false); }; const prevOpen = useRef(open); useEffect(() => { db.collection("product").onSnapshot((snapshot) => setProduct( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); if (prevOpen.current === true && open === false) { anchorRef.current.focus(); } prevOpen.current = open; // eslint-disable-next-line }, []); const handleDota2 = () => { dispatch(loadGameName("Dota 2")); db.collection("product") .where("gameName", "==", "Dota 2") .onSnapshot((snapshot) => setProduct( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }; const handleCsgo = () => { dispatch(loadGameName("Counter-Strike: Global Offensive")); db.collection("product") .where("gameName", "==", "Counter-Strike: Global Offensive") .onSnapshot((snapshot) => setProduct( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }; return ( <div className="store__productContainer"> <div className="store__productHeader"> <div className="productHeader__title"> <StoreRoundedIcon /> <p>Store</p> </div> <div className="productHeader__searchInput"> <div className="searchInput__input"> <input placeholder="Search Item" /> </div> <div className="searchInput__inputSearchIcon"> <SearchIcon /> </div> </div> <div className="productHeader__filter"> <div className="sort__byGame"> <div className="sort__gameLogo" onClick={handleDota2}> <img src="https://1.bp.blogspot.com/-GplgZlvkXSc/Uk_3BipvAlI/AAAAAAAAAJE/NIU9Sm2vSVU/s1600/Dota2-Filled.png" alt="" /> </div> <div className="sort__gameLogo" onClick={handleCsgo}> <img src="https://www.meme-arsenal.com/memes/d81f1fc73c38e2cfacbd493b5d58509c.jpg" alt="" /> </div> {/*Rust Icon <div className="sort__gameLogo"> <img src="https://i.imgur.com/znQvBMih.jpg" alt="" /> </div> */} </div> <div className="button__sort"> <button onClick={handleDropdown} ref={anchorRef}> Price <ArrowDropDownIcon /> </button> {open ? ( <ClickAwayListener onClickAway={handleSortDropdownClose}> <span className="filter__sort"> <div className="filter__sortOption" onClick={handleLowToHighSort} > Low </div> <div className="filter__sortOption" onClick={handleHighToLowSort} > High </div> </span> </ClickAwayListener> ) : ( "" )} </div> </div> </div> <div className="store__productList"> {product.map((item) => ( <StoreItem id={item.id} key={item.id} gameIcon={item.data.gameIcon} image={item.data.image} name={item.data.name} price={item.data.price} quantity={item.data.quantity} hero={item.data.hero} gameName={item.data.gameName} type={item.data.type} quality={item.data.quality} rarity={item.data.rarity} /> ))} </div> </div> ); } export default StoreSection; <file_sep>import React, { useEffect, useRef, useState } from "react"; import { useHistory } from "react-router-dom"; //Redux and slices import { useSelector, useDispatch } from "react-redux"; //A redux import { loginName, loginPhoto, logoutName, logoutPhoto, notificationCount, notificationReset, selectUser, selectPhoto, selectNotification, } from "../features/user/userSlice"; //Importing actions related to user import { selectBalance, recharge, selectReward, balanceCut, } from "../features/balance/balanceSlice"; //Importing actions related to balance //Database import { auth, provider } from "../CONFIG"; import db from "../CONFIG"; import firebase from "firebase"; //Component imports import HeaderCenter from "./HeaderCenter"; import Backdrop from "./Backdrop"; import SideDrawer from "./SideDrawer"; import Notification from "./Notification"; //Css and other imports import logo from "../logo.png"; import "./header.css"; import NumberFormat from "react-number-format"; //Material-UI imports import ArrowDropDownIcon from "@material-ui/icons/ArrowDropDown"; import { Avatar, ClickAwayListener, IconButton } from "@material-ui/core"; import MenuIcon from "@material-ui/icons/Menu"; import CloseIcon from "@material-ui/icons/Close"; import Dialog from "@material-ui/core/Dialog"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogTitle from "@material-ui/core/DialogTitle"; import Snackbar from "@material-ui/core/Snackbar"; import MuiAlert from "@material-ui/lab/Alert"; import TransactionHistory from "./TransactionHistory"; import NotificationsNoneIcon from "@material-ui/icons/NotificationsNone"; //A material-ui Lab code for snackbar (it's imported from material-ui) function Alert(props) { return <MuiAlert elevation={6} variant="filled" {...props} />; } function Header() { const history = useHistory(); //Routes const dispatch = useDispatch(); const notificationCountValue = useSelector(selectNotification); //Notification count value const photo = useSelector(selectPhoto); //User photo const user = useSelector(selectUser); //User name const balance = useSelector(selectBalance); //User balance const reward = useSelector(selectReward); //User Reward Point const [sideDrawerToggle, setSideDrawerToggle] = useState(false); //Sidedrawer for mobile nav const [rechargeDialog, setRechargeDialog] = useState(false); //To open recharge dialog box.... const [rechargeAmount, setRechargeAmount] = useState(); //To get user input recharge amount.... const [transferDialog, setTransferDialog] = useState(false); //To open transfer dialog box.... const [transferAmount, setTransferAmount] = useState(); //To get user input transfer amount.... const [highTransferBalance, setHighTransferBalance] = useState(false); //Show error snackbar if user withdraws more amount than site balance const [profileDropdown, setProfileDropdown] = useState(false); //A dropdown menu when clicking userName on top right navbar. const [notificationDropdown, setNotificationDropdown] = useState(false); //A dropdown state of notification... const [tradeDialog, setTradeDialog] = useState(false); //Open set trade url dialog box const [tradeUrl, settradeUrl] = useState(); //To get user trade url const [transactionDialog, setTransactionDialog] = useState(false); // Open transaction history dialog //Function part--------------------------------------------------------------- //Login function - Google Auth through firebase const handleLogin = async () => { auth .signInWithPopup(provider) .then((result) => { dispatch(loginName(result.user.displayName)); dispatch(loginPhoto(result.user.photoURL)); }) .catch((error) => { console.log(error.message); }); }; //LogOut function const handleLogOut = () => { dispatch(logoutName(null)); dispatch(logoutPhoto(null)); }; //Notification dropdown function const handleNotificationDropdown = (event) => { setNotificationDropdown((prevOpen) => !prevOpen); setProfileDropdown(false); dispatch(notificationReset()); }; //A function used for profile dropdown const handleProfileDropdown = (event) => { setProfileDropdown((prevOpen) => !prevOpen); setNotificationDropdown(false); }; //A function to open trade Url dialog box const handleTradeUrl = () => { setTradeDialog(true); }; //Trade Url dialog box close const handleTradeUrlClose = () => { setTradeDialog(false); }; //Save button function const handleTradeUrlSuccess = () => { //Need to save the user input trade url in user's database....so some stuffs is need to be done later here.. setTradeDialog(false); }; //Recharge functions----------------------------------- //1: Recharge Dialog Box open const handleRecharge = () => { setRechargeDialog(true); }; //Recharge dialogBox close const handleRechargeClose = () => { setRechargeDialog(false); }; //Recharge balance proceed const handleRechargeSuccess = () => { dispatch(recharge(Number(rechargeAmount) || 0)); dispatch(notificationCount()); db.collection("notification").add({ message: `Your steamBazar wallet has been credited for Rs: ${rechargeAmount} /-`, time: firebase.firestore.FieldValue.serverTimestamp(), image: "https://cdn1.iconfinder.com/data/icons/business-and-finance-97/64/wallet-money-finance-cash-dollar-512.png", }); db.collection("transaction").add({ date: firebase.firestore.FieldValue.serverTimestamp(), message: "Wallet Credited from Esewa", signBalance: true, costBalance: Number(rechargeAmount), walletBalance: Number(rechargeAmount) + Number(balance), }); setRechargeDialog(false); }; //Cash out transfer balance functions //1: Open cashout dialog box const handleTransfer = () => { setTransferDialog(true); }; //2: Close cashout dialog box const handleTransferClose = () => { setTransferDialog(false); }; //3: Cashout proceed function const handleTransferSuccess = () => { if (transferAmount > balance) { setHighTransferBalance(true); } else { dispatch(balanceCut(Number(transferAmount) || 0)); dispatch(notificationCount()); db.collection("notification").add({ message: `A transfer from webpage to your Esewa has been made. Cashout value Rs: ${transferAmount} /-`, time: firebase.firestore.FieldValue.serverTimestamp(), image: "https://cdn3.iconfinder.com/data/icons/terminal-and-atm/100/ATM_terminal_pay_cash_out_cash_bank-07-512.png", }); db.collection("transaction").add({ date: firebase.firestore.FieldValue.serverTimestamp(), message: "Wallet cashout to Esewa", signBalance: false, costBalance: Number(transferAmount), walletBalance: Number(balance) - Number(transferAmount), }); } setTransferDialog(false); }; //4: Transaction history const handleTransaction = () => { setTransactionDialog(true); }; //Mobile sideDrawer toggle functions---------------- //1: Open sidedrawer const handleToggle = () => { setSideDrawerToggle(!sideDrawerToggle); }; //2: Close sidedrawer const backdropClickHandler = () => { setSideDrawerToggle(false); }; //UX functions snackbars-------------------------------- //A function to pop up error snackbar const handleErrorSnackbar = () => { setHighTransferBalance(false); }; //Close notification dropdown and user profile dropdown const anchorRef = useRef(null); const handleDropdownClose = (event) => { if (anchorRef.current && anchorRef.current.contains(event.target)) { return; } setProfileDropdown(false); setNotificationDropdown(false); setTransactionDialog(false); }; const prevOpen = useRef(profileDropdown); //End of function part------------------------------------------------------------------ //The use effect------------------------------------------------------------- useEffect(() => { if (prevOpen.current === true && profileDropdown === false) { anchorRef.current.focus(); } prevOpen.current = profileDropdown; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); //React Render---------------------------------------------------------------- return ( <div className="header"> <div className="header__left" onClick={() => history.push("/")}> <img src={logo} alt="SteamBazar" /> </div> <HeaderCenter /> <div className="header__right"> {/*If user is not logged in*/ /* <a href="/auth/steam">Login with Steam</a> */} {!user ? ( <img onClick={handleLogin} style={{ cursor: "pointer" }} src="https://steamcdn-a.akamaihd.net/steamcommunity/public/images/steamworks_docs/english/sits_small.png" alt="logo" /> ) : ( <> {/*If user is logged in */} <div className="header__accountLogo" onClick={handleNotificationDropdown} > <Avatar alt="Profile" src={photo} /> {/*No new notification and new notification*/} {notificationCountValue === 0 ? ( <div className="notification__countNull"></div> ) : ( <div className="notification__count"> {notificationCountValue} </div> )} </div> {/*Notification drop down component part */} {notificationDropdown ? ( <ClickAwayListener onClickAway={handleDropdownClose}> <div className="notification__container"> <div className="notification__header">Notifications</div> <Notification /> </div> </ClickAwayListener> ) : ( "" )} {/*End of notification dropdown component part */} {/*Account name and balance display */} <div className="header__accountInfo"> <div className="header__accountName">{user}</div> <div className="header__accountRpBalance"> <div className="header__account"> <div className="header__accountBalance"> <div> <NumberFormat value={reward} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" /> </div> <p>Rp</p> </div> </div> <div className="header__account"> <div className="header__accountBalance"> <div> <NumberFormat value={balance} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Rs:"} suffix={"/-"} /> </div> <p>Balance</p> </div> </div> </div> </div> <div className="header__accountDropdown" onClick={handleProfileDropdown} ref={anchorRef} > <ArrowDropDownIcon /> {/*Profile dropdown part */} {profileDropdown ? ( <ClickAwayListener onClickAway={handleDropdownClose}> <div className="dropdown__menu"> <div className="dropdown__option" onClick={handleTradeUrl}> Set Trade URL </div> <div className="dropdown__option" onClick={handleRecharge}> Recharge Balance </div> <div className="dropdown__option" onClick={handleTransfer}> Withdraw Balance </div> <div className="dropdown__option" onClick={handleTransaction} > Transaction History </div> <div className="dropdown__option" onClick={handleLogOut}> Log Out </div> </div> </ClickAwayListener> ) : ( "" )} </div> </> )} </div> {/*Mobile view toggle option */} <div className="header__mobile"> <div className="header__mobileNotification" onClick={handleNotificationDropdown} > <NotificationsNoneIcon /> {/*No new notification and new notification*/} {notificationCountValue === 0 ? ( <div className="notification__countNull"></div> ) : ( <div className="notification__countMobile"> {notificationCountValue} </div> )} </div> {/*Notification drop down component part */} {notificationDropdown ? ( <ClickAwayListener onClickAway={handleDropdownClose}> <div className="notification__container"> <div className="notification__header">Notifications</div> <Notification /> </div> </ClickAwayListener> ) : ( "" )} {/*End of notification dropdown component part */} <div className="header__toggle" onClick={handleToggle}> <IconButton> {sideDrawerToggle ? <CloseIcon /> : <MenuIcon />} </IconButton> <SideDrawer show={sideDrawerToggle} handleLogin={handleLogin} handleLogOut={handleLogOut} /> {sideDrawerToggle ? ( <Backdrop backdropClickHandler={backdropClickHandler} /> ) : ( "" )} </div> </div> {/*Starting of header function dialog box */} {/*Trade Url dialog box */} <Dialog open={tradeDialog} onClose={handleTradeUrlClose} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title" className="balance__title"> Enter your trade URL </DialogTitle> <DialogContent className="tradeUrl__content"> <div className="trade__message"> We need to know your Trade URL so our site can send you trade offer requests. </div> <div className="tradeUrl__input"> <input placeholder="Trade URL" type="text" value={tradeUrl} onChange={(e) => settradeUrl(e.target.value)} /> </div> <div className="tradeUrl__guide"> " Steps to find your steam Trade Url " <ol> <li> Go to your steam inventory and click "Trade Offers" button. </li> <li> After that, click on "Who can send me Trade Offers?" button. </li> <li> You'll see 3 options : "Friends", "Trading Forums" and "Third-Party Sites". </li> <li> Copy Trade URL from Third-Party Sites option and paste it here. </li> <li> Your Trade Url looks something like this : https://steamcommunity.com/tradeoffer/new/?partner="number"&token="words" </li> <li>Click "Save".</li> </ol> </div> </DialogContent> <DialogActions> <button onClick={handleTradeUrlClose} className="button__rechargeCancel" > Cancel </button> <button onClick={handleTradeUrlSuccess} className="button__recharge"> Save </button> </DialogActions> </Dialog> {/*Recharge balance dialog box */} <Dialog open={rechargeDialog} onClose={handleRechargeClose} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title" className="balance__title"> Filling up the balance </DialogTitle> <DialogContent> <div className="balance__input"> <input placeholder="Enter amount (Rs)" type="number" value={rechargeAmount} onChange={(e) => setRechargeAmount(e.target.value)} /> </div> </DialogContent> <DialogActions> <button onClick={handleRechargeClose} className="button__rechargeCancel" > Cancel </button> <button onClick={handleRechargeSuccess} className="button__recharge"> Recharge </button> </DialogActions> </Dialog> {/*Cashout balance dialog box */} <Dialog open={transferDialog} onClose={handleTransferClose} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title" className="balance__title"> Cashout </DialogTitle> <DialogContent> <div className="balance__input"> <input placeholder="Enter amount (Rs)" type="number" value={transferAmount} onChange={(e) => setTransferAmount(e.target.value)} /> </div> </DialogContent> <DialogActions> <button onClick={handleTransferClose} className="button__rechargeCancel" > Cancel </button> <button onClick={handleTransferSuccess} className="button__recharge"> Transfer </button> </DialogActions> </Dialog> {/*Transaction History Dialog box */} <Dialog fullScreen open={transactionDialog} onClose={handleDropdownClose} aria-labelledby="form-dialog-title" > <DialogTitle id="form-dialog-title" className="transaction__historyTop"> <div className="transaction__title"> {`${user}'s Transaction History`} <CloseIcon onClick={handleDropdownClose} /> </div> </DialogTitle> <DialogContent> <TransactionHistory /> </DialogContent> </Dialog> {/*Error snackbar when user input higher cashout value than available balance */} <Snackbar open={highTransferBalance} autoHideDuration={6000} onClose={handleErrorSnackbar} anchorOrigin={{ horizontal: "center", vertical: "top", }} > <Alert onClose={handleErrorSnackbar} severity="error"> Transfer failed!!! Transfer amount is higher than your balance. </Alert> </Snackbar> </div> ); } export default Header; <file_sep>import React from "react"; import "./transactionDetail.css"; import NumberFormat from "react-number-format"; function TransactionDetail({ date, message, costRP, costBalance, signRP, signBalance, walletRP, walletBalance, }) { return ( <div> <div className="transaction__historyDetail"> <div className="transaction__historyDate"> {new Date(date?.toDate()).toLocaleDateString()} </div> <div className="transaction__historyDescription">{message}</div> <div className="transaction__costRP"> <NumberFormat value={costRP} displayType="text" prefix={`${signRP ? "+" : "-"}`} /> </div> <div className="transaction__costBalance"> <NumberFormat value={costBalance} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={`${signBalance ? "+" : "-"}Rs: `} suffix={" /-"} /> </div> <div className="transaction__remainingRP"> <NumberFormat value={walletRP} displayType="text" /> </div> <div className="transaction__remainingBalance"> <NumberFormat value={walletBalance} displayType="text" thousandSeparator={true} thousandsGroupStyle="lakh" prefix={"Rs: "} suffix={" /-"} /> </div> </div> </div> ); } export default TransactionDetail; <file_sep>import React from "react"; import "./App.css"; import Header from "./Header/Header"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import StoreMarket from "./StoreMarket/StoreMarket"; import Store from "./Store/Store"; import Inventory from "./Inventory/Inventory"; import Sell from "./sell/Sell"; import CommunityMarket from "./Community/CommunityMarket"; import CommunitySelectItem from "./Community/CommunitySelectItem"; import LiveData from "./LiveData/LiveData"; function App() { return ( <div className="app"> <Router> <LiveData /> <Header /> <Switch> <Route exact path="/store"> <Store /> </Route> <Route exact path="/community"> <CommunityMarket /> </Route> <Route path="/community/:name" children={<CommunitySelectItem />} /> <Route exact path="/inventory"> <Inventory /> </Route> <Route exact path="/sell"> <Sell /> </Route> <Route exact path="/"> <StoreMarket /> </Route> </Switch> </Router> </div> ); } export default App; <file_sep>import React, { useEffect, useState } from "react"; //Redux and slices import { useDispatch } from "react-redux"; import { loadGameName } from "../features/product/productSlice"; //DB import import db from "../CONFIG"; //Database import firebase firestore //import axios from "../axios"; //Local axios that we created--because we need to connect to our backend...which we have set in axios.js file... //Material-UI imports import StoreRoundedIcon from "@material-ui/icons/StoreRounded"; import SearchIcon from "@material-ui/icons/Search"; import ExpandMoreIcon from "@material-ui/icons/ExpandMore"; import ExpandLessIcon from "@material-ui/icons/ExpandLess"; //Component Import import StoreBotItem from "./StoreBotItem"; //Css import import "./store.css"; function StandardStore() { const dispatch = useDispatch(); const [storeItem, setStoreItem] = useState([]); //All object type items of the bot account in a array.... const [sort, setSort] = useState(false); //Price sorting //Use effect hook-------------------- useEffect(() => { //Here we tried to get data from mongo db which we connect through express. /* async function fetchProduct() { const request = await axios.get("/store/product"); setStoreItem(request.data); } fetchProduct(); */ //this is fetching data from firebase db.collection("product").onSnapshot((snapshot) => setStoreItem( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }, []); //console.log(storeItem); //Price sorting const sortPrice = () => { setSort(!sort); sort ? storeItem.sort((first, second) => { return first.data.price - second.data.price; }) : storeItem.sort((first, second) => { return second.data.price - first.data.price; }); }; //Game sorting---------------------- //Dota2 const handleDota2 = () => { dispatch(loadGameName("Dota 2")); db.collection("product") .where("gameName", "==", "Dota 2") .onSnapshot((snapshot) => setStoreItem( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }; //Csgo const handleCsgo = () => { dispatch(loadGameName("Counter-Strike: Global Offensive")); db.collection("product") .where("gameName", "==", "Counter-Strike: Global Offensive") .onSnapshot((snapshot) => setStoreItem( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }; //Function invoked when clicking "Store in secondary navbar(navbar of body container)" const resetFilter = () => { db.collection("product").onSnapshot((snapshot) => setStoreItem( snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ) ); }; return ( <div className="store"> <div className="storeHeader"> <div className="storeHeader__left" onClick={resetFilter}> <StoreRoundedIcon /> <p>Store</p> </div> <div className="storeHeader__center"> <div className="filterByGame" onClick={handleDota2}> <img src="https://1.bp.blogspot.com/-GplgZlvkXSc/Uk_3BipvAlI/AAAAAAAAAJE/NIU9Sm2vSVU/s1600/Dota2-Filled.png" alt="" /> <div className="gameTitle">Dota2</div> </div> <div className="filterByGame" onClick={handleCsgo}> <img src="https://www.meme-arsenal.com/memes/d81f1fc73c38e2cfacbd493b5d58509c.jpg" alt="" /> <div className="gameTitle">CSGO</div> </div> <div className="filterByPrice" onClick={sortPrice}> <p>Price</p> {sort ? <ExpandMoreIcon /> : <ExpandLessIcon />} </div> </div> <div className="storeHeader__right"> <div className="searchBox"> <input placeholder="search item" /> </div> <div className="search__icon"> <SearchIcon /> </div> </div> </div> <div className="storeBody"> {storeItem.map((item) => ( <StoreBotItem id={item.id} key={item.id} image={item.data.image} name={item.data.name} price={item.data.price} hero={item.data.hero} gameIcon={item.data.gameIcon} gameName={item.data.gameName} type={item.data.type} rarity={item.data.rarity} quality={item.data.quality} /> ))} </div> </div> ); } export default StandardStore;
a34836322e56357add2c623db3b1be3f25e406d4
[ "JavaScript", "Markdown" ]
28
JavaScript
kriztkrtmg/steambazarnepal
971eca378563d4b7cf5ec073b17f132b323dfe60
b3395203c9f8181101675a793e0cbe1aa8003d96
refs/heads/master
<file_sep>/* * Copyright (c) 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.ui import android.content.Context import android.graphics.Typeface import android.os.Handler import android.os.HandlerThread import androidx.core.provider.FontRequest import androidx.core.provider.FontsContractCompat import androidx.core.provider.FontsContractCompat.FontRequestCallback import io.sweers.catchup.R import io.sweers.catchup.util.d import io.sweers.catchup.util.e import io.sweers.catchup.util.injection.qualifiers.ApplicationContext import javax.inject.Inject import javax.inject.Singleton @Singleton class FontHelper @Inject constructor(@ApplicationContext context: Context) { private var font: Typeface? = null init { load(context) } fun load(context: Context) { d { "Downloading font" } val request = FontRequest("com.google.android.gms.fonts", "com.google.android.gms", "Nunito", R.array.com_google_android_gms_fonts_certs) val callback = object : FontRequestCallback() { override fun onTypefaceRetrieved(typeface: Typeface) { d { "Font received" } font = typeface } override fun onTypefaceRequestFailed(reason: Int) { e { "Font download failed with reason $reason" } } } FontsContractCompat.requestFont(context.applicationContext, request, callback, Handler(HandlerThread("FontDownloader").apply { start() }.looper)) } /** * Returns the font, or null if it's not present. */ fun getFont() = font }
2b951b8dd35947704776f32443c6b1ac5d2692bf
[ "Kotlin" ]
1
Kotlin
airmax93/CatchUp
d93b42ec7bf19c27b3569a766c5280fbed0c9122
17b19f49a847920163e431520b6da0c8974414f0
refs/heads/main
<file_sep>import * as firebase from 'firebase'; require('@firebase/firestore'); const firebaseConfig = { apiKey: "<KEY>", authDomain: "c71p-7bd59.firebaseapp.com", projectId: "c71p-7bd59", storageBucket: "c71p-7bd59.appspot.com", messagingSenderId: "555477332696", appId: "1:555477332696:web:b9bcf6453438c077f75dad" }; firebase.initializeApp(firebaseConfig); export default firebase.firestore() ;
b2dccafe485b789a6cddc2e2ab748653e246db26
[ "JavaScript" ]
1
JavaScript
achillesshui/C72-P
f9fd45981f62fca753046169e5591016c5dc63ab
a5b33f9770ea0f706624bd67fceb3f621cc5d310
refs/heads/master
<repo_name>iosclubT/iosTree<file_sep>/README.md # iosTree The first practice(calculator) <file_sep>/calculator/calculator/ViewController.swift // // ViewController.swift // calculator // // Created by 上海海洋大学 on 17/3/12. // Copyright © 2017年 上海海洋大学. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var result: UILabel! @IBOutlet weak var interestRateField: UITextField! @IBOutlet weak var loanTermField: UITextField! @IBOutlet weak var loanAmountField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func calculateField(_ sender: Any) { let calculate1 = simpleCalculate() result.text = calculate1.calculate(loanAmount: Double(loanAmountField.text!)!, years:Int(loanTermField.text!)!, interestRate: Double(interestRateField.text!)!).description let ac = UIAlertController(title: "提示", message: "计算完成", preferredStyle: .alert) let btn = UIAlertAction(title: "ok", style: .default, handler: nil) ac.addAction(btn) self.present(ac, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } class simpleCalculate { func calculate(loanAmount:Double,years:Int,interestRate:Double) ->Double{ let rate = interestRate / 100 let interest = loanAmount * rate * Double(years) return loanAmount * interest } }
e1487813c3874cd7d606de5e0a46e10279ab39bc
[ "Markdown", "Swift" ]
2
Markdown
iosclubT/iosTree
8c1ebbc8b4e9bd972aa102c24262f1969f3485cf
1c0c01416033ecf5608378e885b48b731ba9fa89
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> /////////////////////////////////////////////////////////////////////////////// //Liste de fonction appel √ ©dans le programme //////////////////// double saisi() { //fonction saisi des nombres √ †traiter. double x = 0; printf("saisi nombre √† traiter\n>> "); scanf("%lf", &x); return x; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////liste des op √ ©rations appel √ ©s dans le programme //////////////////// double addition(double x, double y) { return x + y; } double soustraction(double x, double y) { return x - y; } double multiplication(double x, double y) { return x * y; } double division(double x, double y) { return x / y; } double x(double x) { return x; } double x2(double x) { return pow(x, 2); } double x3(double x) { return pow(x, 3); } double Cos(double x) { return cos(x); } double Sin(double x) { return sin(x); } double Tan(double x) { return tan(x); } double inverse(double x) { return 1 / x; } double ln(double x) { return log(x); } double expo(double x) { return exp(x); } /////////////////////////////////////////////////////////////////////////////// /////Fonction permettant de choisir une fonction √ †integrer ///////////////: double fonction() { int f = 0; //variable permettant de choisir une fonction a calculer double r; printf(" f(x)= \n1. x 2. x¬≤ 3. x¬≥ "); printf("\n4. cos(x) 5. sin(x) 6. tan(x)"); printf("\n7. 1/x 8. ln(x) 9. exp(x)\n>>"); scanf("%d", &f); //saisi de l 'op√©ration √† effectuer switch (f) { case 1: ptr_fonction = &x; break; case 2: ptr_fonction = &x2; break; case 3: ptr_fonction = &x3; break; case 4: ptr_fonction = &Cos; break; case 5: ptr_fonction = &Sin; break; case 6: ptr_fonction = &Tan; break; case 7: ptr_fonction = &inverse; break; case 8: ptr_fonction = &ln; break; case 9: ptr_fonction = &expo; break; } return ptr_fonction; } //////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /////////Fonction pour l 'int√©gration de Simpson//////////////// double integral(double a, double b, int n, double *fonction()) { int i; double s = 0, s1 = 0, s2 = 0, dx = 0, d2 = 0; double x = 0, f = 0; f = &fonction; x = a - dx; dx = (b - a) / n; s = f(a) + f(b); d2 = 2 * dx; s1 = 0; for (i = 1; i <= n - 1; i = i + 2) { x = x + d2; s1 = s1 + f(x); } x = a; s2 = 0; for (i = 2; i <= n - 2; i = i + 2) { x = x + d2; s2 = s2 + f(x); } s = dx * (s + 4 * s1 + 2 * s2) / 3; return s; } //////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //Programme principal /////////////////////////////// /////////////////////////////////// int main() { int op = 0, validation = 1, test = 0, n = 0; //op est la variable pour le choix de l 'op√©ration, validation sert de condition pour refaire un calcul ou non. double nb1 = 0, nb2 = 0, result = 0, a = 0, b = 0; double (*ptr_fonction) (double); ptr_fonction = fonction; while (validation == 1) { printf(" op√©ration √† effecuter\n1. + \n2. - \n3. x \n4. / \n5.Calcul d'une fonction \n6.Calcul integral \n>> "); scanf("%d", &op); //saisi de l 'op√©ration √† effectuer if (0 < op && op < 7) { //il faut que la valeur de op soit comprise entre 1 et 6 pour effectuer une op √ ©ration. validation = 0; switch (op) { case 1: result = addition(nb1 = saisi(), nb2 = saisi()); break; case 2: result = soustraction(nb1 = saisi(), nb2 = saisi()); break; case 3: result = multiplication(nb1 = saisi(), nb2 = saisi()); break; case 4: result = division(nb1 = saisi(), nb2 = saisi()); break; case 5: result = fonction(nb1 = saisi()); break; case 6: while (test == 0) { printf("saisir la borne inferieure -a-\n>> "); scanf("%lf", &a); printf("saisir la borne superieure -b-\n>> "); scanf("%lf", &b); printf("saisir le pas\n>> "); scanf("%d", &n); if (a > b) { printf("veuillez saisir -a- plus petit que -b-\n\n"); } else { test = 1; } } test = 0; result = integral(a, b, n, *fonction); break; } printf("=%lf\n\n", result); //affichage du r √ ©sultat } else { printf("entrez une valeur valide\n"); } //message d 'erreur printf("tapez 1 pour effectuer un calcul\ntapez 0 pour quitter\n"); scanf("%d", &validation); } return 0; } <file_sep> #include <stdio.h> #include <stdlib.h> #include <math.h> //////////////////////// definition structure vecteur /////////////////////////// typedef struct vecteur vecteur; struct vecteur { int taille; double *stockage; char type; }; ///////////////////////fonction somme de vecteurs ////////////////////////////// vecteur addition(vecteur v1, vecteur v2) { int i = 0; vecteur resultat; resultat.taille = v1.taille; resultat.type = v1.type; resultat.stockage = malloc(resultat.taille * sizeof(double)); //le test doit validé si les deux matrice sont de même type et de même taille. if (v1.taille == v2.taille && v1.type == v2.type) { for (i = 0; i < resultat.taille; i++) { resultat.stockage[i] = v1.stockage[i] + v2.stockage[i]; //printf("%lf ", resultat.stockage[i]); } } else { printf("\n!!!opération impossible!!!\n"); } return resultat; } ///////////////////////fonction somme de vecteurs ////////////////////////////// vecteur soustraction(vecteur v1, vecteur v2) { int i = 0; vecteur resultat; resultat.taille = v1.taille; resultat.type = v1.type; resultat.stockage = malloc(resultat.taille * sizeof(double)); //Même test que pour la fonction addition. if (v1.taille == v2.taille && v1.type == v2.type) { for (i = 0; i < resultat.taille; i++) { resultat.stockage[i] = v1.stockage[i] - v2.stockage[i]; } } else { printf("\n!!!opération impossible!!!\n"); } return resultat; } ///////////////////////fonction somme de vecteurs ////////////////////////////// vecteur multiplication(vecteur v1, vecteur v2) { int i = 0; vecteur resultat; resultat.taille = v1.taille; resultat.type = v1.type; resultat.stockage = malloc(resultat.taille * sizeof(double)); //le test doit validé si les deux matrice ne sont pas de même type, mais les matrices doivent avoir la même taille if (v1.taille == v2.taille && v1.type != v2.type) { for (i = 0; i < resultat.taille; i++) { resultat.stockage[i] = v1.stockage[i] * v2.stockage[i]; } } else { printf("\n!!!opération impossible!!!\n"); } return resultat; } ////////////////////fonction du remplissage //////////////////////////////////// void remplissage(vecteur * vect, int dim, char Type, double t[]) { vect->type = Type; vect->taille = dim; vect->stockage = malloc(dim * sizeof(double)); int j; for (j = 0; j < vect->taille; j++) { vect->stockage[j] = t[j]; } //test malloc if (vect->stockage == NULL) { printf("allocation impossible\n"); } } ////////////////////fonction pour afficher //////////////////////////////////// void affichage(vecteur * vect) { int i; if (vect->type == 'C') { for (i = 0; i < vect->taille; i++) { printf("%lf", vect->stockage[i]); printf("\n"); } } if (vect->type == 'L') { for (i = 0; i < vect->taille; i++) { printf("%lf ", vect->stockage[i]); } } } /////////////////programme principale ////////////////////////////////////////// int main() { //definition des trois vecteurs double tab1 [2] = {1, 0}; double tab2 [2] = {1, 1}; double tab3 [2] = {-1, 0}; vecteur V1; vecteur V2; vecteur V3; vecteur Somme; vecteur Difference; vecteur Produit; remplissage(&V1, 2, 'L', tab1); remplissage(&V2, 2, 'C', tab2); remplissage(&V3, 2, 'C', tab3); printf("\nV1=\n"); affichage(&V1); printf("\n\nV2=\n"); affichage(&V2); printf("\nV3=\n"); affichage(&V3); Somme = addition(V2, V3); Difference = soustraction(V2, V3); Produit = multiplication(V1, V2); printf("\nsomme=\n"); affichage(&Somme); printf("\ndifference=\n"); affichage(&Difference); printf("\nproduit=\n"); affichage(&Produit); return 0; }
71fa0c3afc721d1533641070fe203cde79570011
[ "C" ]
2
C
xlf425/CalculStructure
1058cecd396e7abd652bda6466ff3f449f693947
aea01aaa722acfca6e39cb22a9c0633d327860d7
refs/heads/master
<repo_name>Omkar1493/myproject<file_sep>/rfile.py '''n=raw_input('enter the number of record to fetch'); f=open('russia.txt','r'); column = [] arr1=[] for line in f: column = line.split("|") column.append() print column[2];''' '''for data in column: print data[2]; print (arr1.sort())''' '''file = open("russia.txt") column = [] arr=[] arr1=[] for line in file: column = line.split("|") arr.append(int(column[3])) #arr.append(column[3].sort()); print arr; sorted_data=sorted(f.readlines(), key=lambda item: int(item.rsplit("|",1)[-2].strip())) print (sorted_data) with open("russia.txt", "r") as f: sorted_data = sorted(f.readlines(), key=lambda item: int(item.strip().split("|")[-1])) sort = ["|".join(line.strip().split("|")) for line in sorted_data] print(sorted)''' '''hi check this''' import csv import operator c=0; sample = open("india.txt") csv1 = csv.reader(sample, delimiter='|') sort = sorted(csv1, key=operator.itemgetter(3)) for eachline in sort: print eachline c=c+1; if c==10: break; echo "hi" print "==========================================" echo "hello" c=0; sample = open("india.txt") csv1 = csv.reader(sample, delimiter='|') sort = sorted(csv1, key=operator.itemgetter(4)) for eachline in sort: print eachline c=c+1; if c==10: break; sample.close();
4733cd64f3c231140ea993de7ed347837253bb9e
[ "Python" ]
1
Python
Omkar1493/myproject
67e57989a7190dbe0cedecb7688f463b5cd48728
d11cdc34edc965063d7d87505dc2776ecf068928
refs/heads/main
<file_sep><?php namespace App\Controller; use Cake\Controller\Controller; class BooksController extends Controller { public function index () { $books = $this->Books->find()->fetchAll(); $this->set('books', $books); $this->render('index'); } }<file_sep><?php var_dump($books);<file_sep># sebo-rural-cakephp<file_sep><?php namespace App\Controller; use Cake\Controller\Controller; class CoursesController extends Controller { public function initialize() { parent::initialize(); $this->loadComponent('RequestHandler'); } public function index () { $courses = $this->Courses->find('all'); $this->set('courses', $courses); $this->set('_serialize', 'courses'); } public function view($id) { $course = $this->Courses->get($id); $this->set('course', $course); $this->set('_serialize', 'course'); } }<file_sep><?php namespace App\Model\Table; use Cake\ORM\Table; class BooksTable extends Table { }
c6b5636aee58644afc1a30dd07096297aa85b00c
[ "Markdown", "PHP" ]
5
PHP
merciof/sebo-rural-cakephp
3254bc12a50f646f4b3e525e151aba876957e63e
842c19b11a123beef5a9f5c2f0556344f3522229
refs/heads/master
<file_sep># gschedule Simple scheduling script to be used with Google Spreadsheet (and Javascript) <file_sep>/** * Smith ML Automated Scheduler * JCR -- (<EMAIL>) * ver 1.51b * MIT License * * Basic scheduling with Google spreadsheet and Google forms. Can be extended as necessary. */ function onOpen() { var spreadsheet = SpreadsheetApp.getActive(); var entries = [ { name : "Schedule", functionName : "schedule" },{ name : "Export to Calendar", functionName : "exportToCalendar" },{ name : "Clear the Calendar", functionName : "clearCalendar" } ]; spreadsheet.addMenu("BCM Rad", entries); } // http://stackoverflow.com/questions/962802#962890 function shuffled_array(maxElements) { // create ordered array : 0,1,2,3..maxElements for (var temArr = [], i = 0; i < maxElements; i++) { temArr[i] = i; } for (var finalArr = [maxElements], i = 0; i < maxElements; i++) { // remove random element from the temArr and push it into finalArrr finalArr[i] = temArr.splice(Math.floor(Math.random() * (maxElements - i)), 1)[0]; } return finalArr; } // Take input responses from form, and output to schedule function schedule() { var spreadsheet = SpreadsheetApp.getActive(); var formsheet = spreadsheet.getSheetByName('FormResponses'); var schedulesheet = spreadsheet.getSheetByName('Schedule'); var adminsheet = spreadsheet.getSheetByName('Admin'); var currentmonth = adminsheet.getRange("M1").getValue(); var monthname = { 'January' : '1', 'February' : '2', 'March' : '3', 'April' : '4', 'May' : '5', 'June' : '6', 'July' : '7', 'August' : '8', 'September' : '9', 'October' : '10', 'November' : '11', 'December' : '12' } Logger.log(currentmonth); /* Create date hash */ var scheduleRange = schedulesheet.getRange("A2:C400") var scheduleData = scheduleRange.getValues(); var dateHash = {}; // Create hash table with values representing who is available for each date for (x=0; x < scheduleData.length; x++) { // Set row var r = scheduleData[x]; // Skip conditions if (r[0] != "" || r[1] == "") continue; // skip if date is invalid or blank // Check validity of date/month var tempdate = new Date(r[1]); tempdate.setHours(tempdate.getHours() + 8); // Daylight savings hotfix if (tempdate.getMonth()+1 != monthname[currentmonth]) continue; Logger.log("Date: " + tempdate.toString()); dateHash[tempdate.getDate()] = []; } Logger.log("Datehash: " + dateHash.toString()); /* Add to date hash based on responses */ var responseData = formsheet.getRange("A2:E1000").getValues(); var pool_of_people = []; var len_responseData = responseData.length; for (x=len_responseData-1; x >= 0 ; x--) { var r = responseData[x]; if ( r[0] == "" || r[2] != currentmonth || pool_of_people.indexOf(r[1]) != -1 ) continue; pool_of_people.push(r[1]); var temparr = r[3]; temparr = temparr.split(' ').join('').split(','); //Logger.log(temparr); for (i=0; i < temparr.length; i++) { // //Logger.log(i); if(dateHash.hasOwnProperty(temparr[i])) dateHash[temparr[i]].push(r[1]); } } Logger.log(dateHash); Logger.log("--"); Logger.log(dateHash[3]); /* Get people info, and hash it */ var peopleData = adminsheet.getRange("A2:D50").getValues(); //Logger.log(peopleData) //var pTally = {5:[], 4:[], 3:[], 2:[]}; var pTally = []; for (i=1; i<peopleData.length; i++) { var eRow = peopleData[i]; if (eRow[0] == "" || pool_of_people.indexOf(eRow[0]) == -1) continue; //pTally[eRow[1]].push( [eRow[0],eRow[2]] ); pTally.push( [eRow[0],eRow[2]] ); } pTally.sort( function(a,b) { return a[1] - b[1]; } ); Logger.log(pTally); //return; //Logger.log(peopleHash); var sA = shuffled_array(scheduleData.length); /* Place people */ for (i=0; i < scheduleData.length; i++) { var x = sA[i]; // Set row var r = scheduleData[x]; // Skip conditions if (r[0] != "" || r[1] == "") continue; // skip if date is invalid or blank // Check validity of date/month var tempdate = new Date(r[1]); tempdate.setHours(tempdate.getHours() + 8); // Daylight savings hotfix if (tempdate.getMonth()+1 != monthname[currentmonth]) continue; Logger.log("Acting on date: " + r[1]); Logger.log(dateHash[tempdate.getDate()]); //Logger.log("--"); // Sort tally list pTally.sort( function(a,b) { return a[1] - b[1]; } ); //Logger.log(pTally); // Place someone for (p=0; p < pTally.length; p++) { index = dateHash[tempdate.getDate()].indexOf(pTally[p][0]); //Logger.log(index); var tempvar = pTally[p][0]; //Logger.log(tempvar); if (index != -1) { r[2] = pTally[p][0]; pTally[p][1] = pTally[p][1] + 1; break; } } Logger.log("Placed: " + r[2] + " on " + r[1]); Logger.log("---------------"); } /* BEGIN SWAP SEGMENT - Iterate through dates one more time, and this time swap people */ pTally.sort( function(a,b) { return a[1] - b[1]; } ); Logger.log(pTally); if (pTally[pTally.length-1][1] - pTally[0][1] > 1){ Logger.log("Attempt swap"); var overPerson = pTally[pTally.length-1][0]; var underPerson = pTally[0][0]; var overPINDX = 1; var count = 0; while ( (pTally[pTally.length-1][1] - pTally[0][1]) > 1 ){ var swap_happened = -1; // keep track of whether a swap happened (for scenario when same people remain as over/under) for (x=0; x < scheduleData.length; x++) { // Set row var r = scheduleData[x]; // Skip conditions if (r[0] != "" || r[1] == "") continue; // skip if date is invalid or blank // Check validity of date/month var tempdate = new Date(r[1]); tempdate.setHours(tempdate.getHours() + 8); // Daylight savings hotfix if (tempdate.getMonth()+1 != monthname[currentmonth]) continue; // skip the date if overperson is not working if (r[2] != overPerson) continue; // skip the date if underperson is already working if (r[2] == underPerson) continue; index = dateHash[tempdate.getDate()].indexOf(underPerson); if (index != -1) { r[2] = underPerson; pTally[0][1] = pTally[0][1] + 1; pTally[pTally.length - overPINDX][1] = pTally[pTally.length - overPINDX][1] - 1; swap_happened = 1; Logger.log("For date : " + tempdate.toString()); Logger.log("oP:" + overPerson + " | uP:" + underPerson); break; } } pTally.sort( function(a,b) { return a[1] - b[1]; } ); // CHECK SWAPS, AND TRY LOWER PERSON INDICES // if (swap_happened == 1){ overPINDX = 1; overPerson = pTally[pTally.length - overPINDX][0]; underPerson = pTally[0][0]; } else { overPINDX = overPINDX + 1; if ( (pTally[pTally.length - overPINDX][1] - pTally[0][1]) > 1){ overPerson = pTally[pTally.length - overPINDX][0]; underPerson = pTally[0][0]; } else { //ui.alert('Imbalanced Schedule', ui.ButtonSet.OK); break; } } } } // END SWAP SEGMENT /* Set schedule */ scheduleRange.setValues(scheduleData); } var calId = "?????<EMAIL>"; /** * Export events from spreadsheet to calendar */ function exportToCalendar() { var spreadsheet = SpreadsheetApp.getActive(); var schedulesheet = spreadsheet.getSheetByName('Schedule'); var calsheet = spreadsheet.getSheetByName('calData'); // Check for change in mastersheet data, and if so, update the calsheet var tempRange1 = schedulesheet.getRange("A:E").getValues(); var tempD2 = calsheet.getRange("A:E"); var tempRange2 = tempD2.getValues(); var changed = 0; for (a=0; a<tempRange1.length; a++) { // load row var row1 = tempRange1[a]; var row2 = tempRange2[a]; if (row1[1] == "") continue; // skip if row blank for (b=0; b < row1.length; b++) { if (row1[b] == row2[b]) continue; else { if (b == 1) { var D1 = new Date(row2[b]); D1.setHours(D1.getHours() + 8); // Daylight savings hotfix var D2 = new Date(row1[b]); D2.setHours(D2.getHours() + 8); // Daylight savings hotfix //Logger.log(D1.getMonth() + " " + D1.getDate() + " " + D1.getYear()); if (D1.getMonth() == D2.getMonth() && D1.getDate() == D2.getDate() && D1.getYear() == D2.getYear()) continue; } changed = 1; row2[b] = row1[b]; Logger.log("Changes noted"); break; } } } if (changed == 0) { Logger.log("No changes noted. Ending."); return; } // Update calsheet only if change in mastersheet tempD2.setValues(tempRange1); //return; var headerRows = 2; // Number of rows of header info (to skip) var range = calsheet.getRange("A1:G400"); var data = range.getValues(); // Access Calendar var cal = CalendarApp.getCalendarById(calId); var pauser = 0; for (i=headerRows; i<data.length; i++) { // load row var row = data[i]; if (row[1] == "") continue; // skip if row is a blank date // Define Date var date_value = new Date(row[1]); date_value.setHours(date_value.getHours() + 8); // Daylight savings hotfix // Make/Update Event ------------------------------------------------- // CalendarEventID var eventID = row[6]; Logger.log('Date: ' + date_value); var name = row[2]; // First see if the spreadsheet has any event ID if (eventID == "") { // If blank name, then just skip it if (row[2] == "") continue; // Otherwise, a name is defined... so create an event with name var eventObj = cal.createAllDayEvent(name, date_value); row[6] = eventObj.getId(); Logger.log('Event ID: ' + row[6]); // Need to pause once in a while because Google limits actions/second pauser = pauser + 1; if (pauser > 10) { Utilities.sleep(3000); pauser = 0; } } else { // try { var eventObj = cal.getEventSeriesById(eventID); if (eventObj.getTitle() != name) eventObj.setTitle(name); } catch (e) { // do nothing - just avoiding stupid exception } // Need to pause once in a while because Google limits actions/second pauser = pauser + 1; if (pauser > 10) { Utilities.sleep(3000); pauser = 0; } } } // Record all event IDs to spreadsheet range.setValues(data); } /** * Invoke to clear all events from the calendar */ function clearCalendar(){ // Access Calendar var cal = CalendarApp.getCalendarById(calId); // Clear Calendar var fromDate = new Date(2016,0,1,0,0,0); var toDate = new Date(2030,0,1,0,0,0); var events = cal.getEvents(fromDate, toDate); var pauser = 0; for(var i=0; i<events.length;i++){ pauser = pauser + 1; if (pauser > 10) { Utilities.sleep(3000); pauser = 0; } var ev = events[i]; //Logger.log(ev.getTitle()); // show event name in log ev.deleteEvent(); } var spreadsheet = SpreadsheetApp.getActive(); var calsheet = spreadsheet.getSheetByName('calData'); calsheet.clearContents(); }
7f251a234a4eb9e5f6230c239da856202f747629
[ "Markdown", "JavaScript" ]
2
Markdown
jcsagar/gschedule
d47c299451ece94fe3621c3accb2198b18d03c51
290dd0ae6d23fead449686b4f88ae2a9cdbb3f4e
refs/heads/master
<repo_name>gavalon/seattletimesbot<file_sep>/README.md seattletimesbot =============== This is the code for a bot that scrapes articles from the Local section of The Seattle Times, gets the google cached versions of the articles, and posts them to a subreddit. The idea was to find a way around the paywall. It worked nicely, though I was simply running it out of idle. I retired the bot. <file_sep>/bot.py import praw, urllib, time, re, pickle from urllib import urlopen # Authenticate praw, the Reddit API user_agent = ('itsmybot') r = praw.Reddit(user_agent=user_agent, log_requests=1) r.login() #So I don't repost links posted_links = [] while True: f = urllib.urlopen('http://seattletimes.com/html/localnews/') words = f.read().decode('utf-8') all_links = re.findall("/html/localnews/(.+)\.html", words) #Scrapes to find articles labeled local news for j in all_links: a = j full_link = 'http://seattletimes.com/html/localnews/%s.html'%(a) g = urllib.urlopen(full_link) wordit = g.read().decode('utf-8') findtitle = re.findall("<title>(.+)\| Local News", wordit) #searches html of article to find title if full_link not in posted_links: if len(findtitle) == 1: cached_link = 'http://webcache.googleusercontent.com/search?q=cache:%s'%(full_link) #gets google cache version r.submit('FreeSeattleTimes', findtitle[0], url=cached_link) #posts link w/title posted_links.append(full_link) #saves info in a file in case I want to stop running idle, but want to know what links have been posted outFile = open('times_articles.txt', 'wb') pickle.dump(posted_links, outFile) outFile.close() time.sleep(600)
7c8455f1562f886e17472ee84d9ff09c3a258b49
[ "Markdown", "Python" ]
2
Markdown
gavalon/seattletimesbot
eb2f85664a4fe89ee3ffbb9fc5950ec8e2cd358b
691dc2acdfbe486bd132c42a928f40bfab78648d
refs/heads/master
<repo_name>Alcuri/Alg_BQI<file_sep>/Alg_BQI/src/Interacao/Menu_ComInteracao.java package Interacao; import java.util.Calendar; import java.util.Scanner; import BubbleSort.Bubble; import InsertionSort.Insertion; import QuickSort.Quick; public class Menu_ComInteracao { /*Esta eh a versão final utilizando os algoritmos Bubble, Quick e Insertion Sort. Para utilizar outros algoritmos de ordenacao, basta criar novos packages e classes com esses algoritmos e substituir os objetos instanciados (bem como as variaveis, deixando-as de acordo com suas funcoes*/ @SuppressWarnings("static-access") public static void main(String [] args){ DadosInternos dadosInternos = new DadosInternos(); LendoExcel dadosExternos = new LendoExcel(); Bubble bubble = new Bubble(); Quick quick = new Quick(); Insertion insertion = new Insertion(); Scanner leTeclado = new Scanner(System.in); int sair = 1; do{ System.out.println("Escolha qual algoritmo deseja analisar:"); System.out.println("1 - BubbleSort"); System.out.println("2 - QuickSort"); System.out.println("3 - InsertionSort"); System.out.println("Digite 'Sair' para encerrar o programa!"); String escolha = leTeclado.nextLine(); switch(escolha){ case "1": long tempoInicialb = System.currentTimeMillis(); String horaI = hora(); System.out.println(horaI); int[] veBubble = dadosExternos.capturaExcel(); int[] viBubble = dadosInternos.random(); bubble.bubbleSort(veBubble); bubble.bubbleSort(viBubble); long tempoFinalb = System.currentTimeMillis(); System.out.println("----------------------------------------------------------------"); System.out.println("Tempo de execucao do BubbleSort: " + (tempoFinalb - tempoInicialb) + "ms."); System.out.println("----------------------------------------------------------------"); String horaF = hora(); System.out.println(horaF); System.out.println(); for(int i = 0; i < viBubble.length; i++){ if(i%10 == 0){ System.out.println(""); }else{ if(i < 10){ System.out.print("000" + i + " - " + viBubble[i] + " | "); }else if(i < 100){ System.out.print("00" + i + " - " + viBubble[i] + " | "); }else if(i < 1000){ System.out.print("0" + i + " - " + viBubble[i] + " | "); }else if(i < 10000){ System.out.print(+ i + " - " + viBubble[i] + " | "); } } } System.out.println("\n"); break; case "2": long tempoInicialq = System.currentTimeMillis(); horaI = hora(); System.out.println(horaI); int[] veQuick = dadosExternos.capturaExcel(); int[] viQuick = dadosInternos.random(); quick.quickSort(veQuick, 0, veQuick.length-1); quick.quickSort(viQuick, 0, viQuick.length-1); long tempoFinalq = System.currentTimeMillis(); System.out.println("----------------------------------------------------------------"); System.out.println("Tempo de execucao do QuickSort: " + (tempoFinalq - tempoInicialq) + "ms."); System.out.println("----------------------------------------------------------------"); horaF = hora(); System.out.println(horaF); System.out.println(); for(int i = 0; i < viQuick.length; i++){ if(i%10 == 0){ System.out.println(""); }else{ if(i < 10){ System.out.print("000" + i + " - " + viQuick[i] + " | "); }else if(i < 100){ System.out.print("00" + i + " - " + viQuick[i] + " | "); }else if(i < 1000){ System.out.print("0" + i + " - " + viQuick[i] + " | "); }else if(i < 10000){ System.out.print(+ i + " - " + viQuick[i] + " | "); } } } System.out.println("\n"); break; case "3": long tempoIniciali = System.currentTimeMillis(); horaI = hora(); System.out.println(horaI); int[] veInsertion = dadosExternos.capturaExcel(); int[] viInsertion = dadosInternos.random(); insertion.interstionSort(veInsertion); insertion.interstionSort(viInsertion); long tempoFinali = System.currentTimeMillis(); System.out.println("----------------------------------------------------------------"); System.out.println("Tempo de execucao do InsertionSort: " + (tempoFinali - tempoIniciali) + "ms."); System.out.println("----------------------------------------------------------------"); horaF = hora(); System.out.println(horaF); System.out.println(); for(int i = 0; i < viInsertion.length; i++){ if(i%10 == 0){ System.out.println(""); }else{ if(i < 10){ System.out.print("000" + i + " - " + viInsertion[i] + " | "); }else if(i < 100){ System.out.print("00" + i + " - " + viInsertion[i] + " | "); }else if(i < 1000){ System.out.print("0" + i + " - " + viInsertion[i] + " | "); }else if(i < 10000){ System.out.print(+ i + " - " + viInsertion[i] + " | "); } } } System.out.println("\n"); break; case "Sair": case "sair": sair = 0; System.exit(0); default: System.out.println("Por favor selecione uma das opcoes acima!"); } }while(sair == 1); leTeclado.close(); } public static String hora(){ Calendar data = Calendar.getInstance(); int hora = data.get(Calendar.HOUR_OF_DAY); int min = data.get(Calendar.MINUTE); int seg = data.get(Calendar.SECOND); int miliseg = data.get(Calendar.MILLISECOND); return (hora + "h " +min+ "min " +seg+ "seg " +miliseg+ "ms"); } } <file_sep>/README.md # Alg_BQI Programa que possui três algoritmos de ordenação e visa mostrar qual deles é mais rápido nesta função. Dois vetores são lidos e organizados: 1. Um vetor interno dentro de um método com elementos já declarados (há uma classe no programa que imprime elementos aleatórios de uma maneira ao qual basta copiar e colar os elementos para um vetor. 2. Um vetor lido de uma planilha Excel (há 3 no programa: uma com mil elementos, outra com dez mil e a última com cem mil). <file_sep>/Alg_BQI/src/Interacao/Criacao_Dados.java package Interacao; public class Criacao_Dados { public static void main (String [] args){ int[] vetor = new int[50]; int i = 0; for(i = 0; i < vetor.length; i++){ vetor[i] = (int) (Math.random()*1000); } for(i = 0; i < vetor.length; i++){ if(i%10 == 0){ System.out.println(); }else System.out.print(vetor[i] + ", "); } } }
7df5272ebf2ea98ed4d1fc5da493a31b03a087c8
[ "Markdown", "Java" ]
3
Java
Alcuri/Alg_BQI
68dfd37a497cf9e97bcd966c55e15c1eea983914
88bb467682c7f58434ee4ba4be3b319dd7e1a360
refs/heads/master
<repo_name>pisa-engine/wapopp<file_sep>/src/wapopp.cpp #include <wapopp/detail.hpp> #include <iostream> using namespace wapopp; template <class C, class Fn> void append_content(nlohmann::json const &node, std::vector<Content> &contents, Fn read_content) { auto content = read_content(node); if (detail::holds<C>(content)) { contents.push_back(detail::take<C>(std::move(content))); } } [[nodiscard]] auto Record::read(std::istream &is) -> Result { std::string line; std::getline(is, line); try { nlohmann::json data = nlohmann::json::parse(line); std::vector<Content> contents; for (auto &&content_entry : data["contents"]) { if (auto type_pos = content_entry.find("type"); type_pos != content_entry.end()) { auto type = type_pos->get<std::string>(); if (type == "kicker") { append_content<Kicker>( content_entry, contents, detail::read_simple_content<Kicker>); } else if (type == "title") { append_content<Title>( content_entry, contents, detail::read_simple_content<Title>); } else if (type == "byline") { append_content<Byline>( content_entry, contents, detail::read_simple_content<Byline>); } else if (type == "sanitized_html") { append_content<Text>( content_entry, contents, detail::read_simple_content<Text>); } else if (type == "date") { append_content<Date>(content_entry, contents, detail::read_date); } else if (type == "author_info") { append_content<AuthorInfo>(content_entry, contents, detail::read_author_info); } else if (type == "image") { append_content<Image>(content_entry, contents, detail::read_image); } } } return Record{data["id"], detail::read_field_or<std::string>(data, "article_url", ""), detail::read_field_or<std::string>(data, "title", ""), detail::read_field_or<std::string>(data, "author", ""), detail::read_field_or<std::string>(data, "type", ""), detail::read_field_or<std::string>(data, "source", ""), detail::read_field_or<std::uint64_t>(data, "published_date", 0u), std::move(contents)}; } catch (nlohmann::detail::exception const& error) { return Error{error.what(), line}; } } <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.0) project(wapopp VERSION 1.0 LANGUAGES CXX) if (CMAKE_BUILD_TYPE) message(STATUS "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}") endif() include(cmake/verify_version.cmake) # # CONFIGURATION # set(WAPOPP_TARGET_NAME ${PROJECT_NAME}) set(WAPOPP_CONFIG_INSTALL_DIR "lib/cmake/${PROJECT_NAME}" CACHE INTERNAL "") set(WAPOPP_INCLUDE_BUILD_DIR "${PROJECT_SOURCE_DIR}/include") set(WAPOPP_INCLUDE_INSTALL_DIR "include") set(WAPOPP_TARGETS_EXPORT_NAME "${PROJECT_NAME}Targets") set(WAPOPP_CMAKE_CONFIG_TEMPLATE "cmake/config.cmake.in") set(WAPOPP_CMAKE_CONFIG_DIR "${CMAKE_CURRENT_BINARY_DIR}") set(WAPOPP_CMAKE_VERSION_CONFIG_FILE "${WAPOPP_CMAKE_CONFIG_DIR}/${PROJECT_NAME}ConfigVersion.cmake") set(WAPOPP_CMAKE_PROJECT_CONFIG_FILE "${WAPOPP_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Config.cmake") set(WAPOPP_CMAKE_PROJECT_TARGETS_FILE "${WAPOPP_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Targets.cmake") set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) # # OPTIONS # option(WAPOPP_ENABLE_TESTING "Enable testing of the library." ON) # # DEPENDENCIES # add_subdirectory(external) # # ADD LIBRARY # add_library(${WAPOPP_TARGET_NAME} "${PROJECT_SOURCE_DIR}/include/wapopp/wapopp.hpp" "${PROJECT_SOURCE_DIR}/src/wapopp.cpp") target_link_libraries(${WAPOPP_TARGET_NAME} PRIVATE nlohmann_json::nlohmann_json) target_include_directories(${WAPOPP_TARGET_NAME} PUBLIC $<BUILD_INTERFACE:${WAPOPP_INCLUDE_BUILD_DIR}> $<INSTALL_INTERFACE:${WAPOPP_INCLUDE_INSTALL_DIR}> ) # # TESTING # if (WAPOPP_ENABLE_TESTING AND BUILD_TESTING) enable_testing() add_subdirectory(test) endif() # # INSTALL install header files, generate and install cmake config files for # find_package() # include(CMakePackageConfigHelpers) write_basic_package_version_file(${WAPOPP_CMAKE_VERSION_CONFIG_FILE} COMPATIBILITY SameMajorVersion) configure_file(${WAPOPP_CMAKE_CONFIG_TEMPLATE} ${WAPOPP_CMAKE_PROJECT_CONFIG_FILE} @ONLY) install(FILES "${WAPOPP_INCLUDE_BUILD_DIR}/${PROJECT_NAME}/wapopp.hpp" DESTINATION ${WAPOPP_INCLUDE_INSTALL_DIR}) install(FILES ${WAPOPP_CMAKE_PROJECT_CONFIG_FILE} ${WAPOPP_CMAKE_VERSION_CONFIG_FILE} DESTINATION ${WAPOPP_CONFIG_INSTALL_DIR}) export(TARGETS ${WAPOPP_TARGET_NAME} NAMESPACE ${PROJECT_NAME}:: FILE ${WAPOPP_CMAKE_PROJECT_TARGETS_FILE}) install(TARGETS ${WAPOPP_TARGET_NAME} EXPORT ${WAPOPP_TARGETS_EXPORT_NAME} INCLUDES DESTINATION ${WAPOPP_INCLUDE_INSTALL_DIR} ARCHIVE DESTINATION lib LIBRARY DESTINATION lib COMPONENT library) install(EXPORT ${WAPOPP_TARGETS_EXPORT_NAME} NAMESPACE ${PROJECT_NAME}:: DESTINATION ${WAPOPP_CONFIG_INSTALL_DIR}) <file_sep>/external/CMakeLists.txt EXECUTE_PROCESS(COMMAND git submodule update --init WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/.. OUTPUT_QUIET ) # Add JSON for Modern C++ if(NOT TARGET nlohmann_json) set(JSON_BuildTests OFF CACHE INTERNAL "") add_subdirectory(json EXCLUDE_FROM_ALL) endif() # Add CLI11 if(NOT TARGET CLI11) set(CLI11_TESTING OFF CACHE INTERNAL "") add_subdirectory(CLI11) endif() # Add Catch if(NOT TARGET Catch2) add_subdirectory(Catch2) endif() <file_sep>/test/CMakeLists.txt add_executable(test_detail test_detail.cpp) target_include_directories(test_detail PRIVATE "${PROJECT_SOURCE_DIR}/include/") target_link_libraries(test_detail nlohmann_json Catch2 ) add_test(test_detail test_detail) add_executable(test_wapopp test_wapopp.cpp) target_link_libraries(test_wapopp wapopp nlohmann_json Catch2 ) add_test(test_wapopp test_wapopp) <file_sep>/cmake/config.cmake.in include(FindPackageHandleStandardArgs) set(${CMAKE_FIND_PACKAGE_NAME}_CONFIG ${CMAKE_CURRENT_LIST_FILE}) find_package_handle_standard_args(@PROJECT_NAME@ CONFIG_MODE) if(NOT TARGET wapopp::wapopp) include("${CMAKE_CURRENT_LIST_DIR}/wapoppTargets.cmake") endif() <file_sep>/include/wapopp/detail.hpp #pragma once #include <istream> #include <ostream> #include <sstream> #include <string> #include <variant> #include <nlohmann/json.hpp> #include "wapopp.hpp" namespace wapopp { namespace detail { // Due to AppleClang's lack of support template <class T, class... Types> [[nodiscard]] auto take(std::variant<Types...> &&v) -> T && { if (auto ptr = std::get_if<T>(&v); ptr != nullptr) { return std::move(*ptr); } else { throw std::invalid_argument("Couldn't access required type"); } } // Due to AppleClang's lack of support template <class T, class... Types> [[nodiscard]] auto holds(std::variant<Types...> const &v) -> bool { return std::get_if<T>(&v) != nullptr; } template <class T> [[nodiscard]] auto read_field_or(nlohmann::json const &node, std::string const &field, T default_value) -> T { if (auto pos = node.find(field); pos != node.end()) { try { return pos->get<T>(); } catch (std::exception const &) { return default_value; } } else { return default_value; } } template <class T> [[nodiscard]] auto read_mandatory_field(nlohmann::json const &node, std::string const &field) -> std::variant<T, Error> { if (auto pos = node.find(field); pos != node.end()) { try { return pos->get<T>(); } catch (std::exception const &) { std::ostringstream os; os << "Failed to parse " << field << " (" << *pos << ") to a requested type"; return Error{os.str(), node.dump()}; } } else { return Error{std::string("Missing ") + field, node.dump()}; } } template <class T> [[nodiscard]] auto read_simple_content(nlohmann::json const &node) -> std::variant<T, Error> { auto content = read_mandatory_field<std::string>(node, "content"); if (holds<Error>(content)) { return take<Error>(std::move(content)); } auto mime = read_mandatory_field<std::string>(node, "mime"); if (holds<Error>(mime)) { return take<Error>(std::move(mime)); } return T{take<std::string>(std::move(content)), take<std::string>(std::move(mime))}; } [[nodiscard]] auto read_date(nlohmann::json const &node) -> std::variant<Date, Error> { auto date = read_mandatory_field<std::uint64_t>(node, "content"); if (holds<Error>(date)) { return take<Error>(std::move(date)); } return Date{take<std::uint64_t>(std::move(date))}; } [[nodiscard]] auto read_author_info(nlohmann::json const &node) -> std::variant<AuthorInfo, Error> { auto role = read_mandatory_field<std::string>(node, "role"); if (holds<Error>(role)) { return take<Error>(std::move(role)); } auto name = read_mandatory_field<std::string>(node, "name"); if (holds<Error>(name)) { return take<Error>(std::move(name)); } auto bio = read_mandatory_field<std::string>(node, "bio"); if (holds<Error>(bio)) { return take<Error>(std::move(bio)); } return AuthorInfo{take<std::string>(std::move(role)), take<std::string>(std::move(name)), take<std::string>(std::move(bio))}; } [[nodiscard]] auto read_image(nlohmann::json const &node) -> std::variant<Image, Error> { auto caption = read_mandatory_field<std::string>(node, "fullcaption"); if (holds<Error>(caption)) { return take<Error>(std::move(caption)); } auto blurb = read_mandatory_field<std::string>(node, "blurb"); if (holds<Error>(blurb)) { return take<Error>(std::move(blurb)); } auto url = read_mandatory_field<std::string>(node, "imageURL"); if (holds<Error>(url)) { return take<Error>(std::move(url)); } auto height = read_mandatory_field<int>(node, "imageHeight"); if (holds<Error>(height)) { return take<Error>(std::move(height)); } auto width = read_mandatory_field<int>(node, "imageWidth"); if (holds<Error>(width)) { return take<Error>(std::move(width)); } return Image{take<std::string>(std::move(caption)), take<std::string>(std::move(blurb)), take<std::string>(std::move(url)), take<int>(std::move(height)), take<int>(std::move(width))}; } } // namespace detail } // namespace wapopp <file_sep>/include/wapopp/wapopp.hpp #pragma once #include <istream> #include <ostream> #include <string> #include <variant> namespace wapopp { struct Error { std::string msg{}; std::string json{}; }; struct Record; using Result = std::variant<Record, Error>; struct SimpleContent { std::string content; std::string mime; }; struct Kicker : public SimpleContent { }; struct Title : public SimpleContent { }; struct Byline : public SimpleContent { }; struct Text : public SimpleContent { }; struct Date { std::uint64_t timestamp; }; struct AuthorInfo { std::string role; std::string name; std::string bio; }; struct Image { std::string caption; std::string blurb; std::string url; int height; int width; }; using Content = std::variant<Kicker, Title, Byline, Text, Date, AuthorInfo, Image>; struct Record { std::string id; std::string url; std::string title; std::string author; std::string type; std::string source; std::uint64_t published; std::vector<Content> contents; [[nodiscard]] static auto read(std::istream &is) -> Result; }; } // namespace wapopp <file_sep>/test/test_wapopp.cpp #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include <nlohmann/json.hpp> #include "wapopp/wapopp.hpp" using namespace wapopp; TEST_CASE("Read record", "[unit]") { auto r = R"({"id": "b2e89334-33f9-11e1-825f-dabc29fd7071",)" R"("article_url": "https://www.washingtonpost.com/truncated.html",)" R"("title": "<NAME>, <NAME> are a perfect 1-2 punch for Virginia Tech",)" R"("author": null,)" R"("published_date": 1325376562000,)" R"("contents": [)" R"({)" R"( "content":"Colleges",)" R"( "mime":"text/plain",)" R"( "type":"kicker")" R"(},)" R"({)" R"( "content":"<NAME>, <NAME> are a perfect 1-2 punch for Virginia Tech",)" R"( "mime":"text/plain",)" R"( "type":"title")" R"(},)" R"({)" R"( "fullcaption":"Virginia Tech wide receiver Danny Coale",)" R"( "imageURL":"https://img.washingtonpost.com/somepic.jpg",)" R"( "mime":"image/jpeg",)" R"( "imageHeight":2260,)" R"( "imageWidth":2775,)" R"( "type":"image",)" R"( "blurb":"Virginia Tech Blurb")" R"(},)" R"({)" R"( "content":"By <NAME>",)" R"( "mime":"text/plain",)" R"( "type":"byline")" R"(},)" R"({)" R"( "content":1325376562000,)" R"( "mime":"text/plain",)" R"( "type":"date")" R"(},)" R"({)" R"( "content":"<span class=\"dateline\">NEW ORLEANS</span>.",)" R"( "subtype":"paragraph",)" R"( "type":"sanitized_html",)" R"( "mime":"text/html")" R"(},)" R"({)" R"( "corrupted":"content",)" R"( "subtype":"paragraph",)" R"( "type":"sanitized_html",)" R"( "mime":"text/html")" R"(},)" R"({)" R"( "type":"unknown")" R"(},)" R"({)" R"( "role":"Reporter",)" R"( "type":"author_info",)" R"( "name":"<NAME>",)" R"( "bio":"<NAME> bio")" R"(})" R"(],)" R"("type": "article",)" R"("source": "The Washington Post")" "}"; std::istringstream is(r); auto result = Record::read(is); REQUIRE(std::get_if<Record>(&result) != nullptr); auto record = *std::get_if<Record>(&result); auto j = nlohmann::json::parse(r); REQUIRE(record.id == j["id"]); REQUIRE(record.url == j["article_url"]); REQUIRE(record.title == j["title"]); REQUIRE(record.author == ""); REQUIRE(record.published == j["published_date"]); REQUIRE(record.type == j["type"]); REQUIRE(record.source == j["source"]); { REQUIRE(std::get_if<Kicker>(&record.contents[0]) != nullptr); auto kicker = *std::get_if<Kicker>(&record.contents[0]); REQUIRE(kicker.content == "Colleges"); REQUIRE(kicker.mime == "text/plain"); } { REQUIRE(std::get_if<Title>(&record.contents[1]) != nullptr); auto title = *std::get_if<Title>(&record.contents[1]); REQUIRE(title.content == "<NAME>, <NAME> are a perfect 1-2 punch for Virginia Tech"); REQUIRE(title.mime == "text/plain"); } { REQUIRE(std::get_if<Image>(&record.contents[2]) != nullptr); auto image = *std::get_if<Image>(&record.contents[2]); REQUIRE(image.caption == "Virginia Tech wide receiver <NAME>"); REQUIRE(image.url == "https://img.washingtonpost.com/somepic.jpg"); REQUIRE(image.height == 2260); REQUIRE(image.width == 2775); REQUIRE(image.blurb == "Virginia Tech Blurb"); } { REQUIRE(std::get_if<Byline>(&record.contents[3]) != nullptr); auto byline = *std::get_if<Byline>(&record.contents[3]); REQUIRE(byline.content == "By <NAME>"); REQUIRE(byline.mime == "text/plain"); } { REQUIRE(std::get_if<Date>(&record.contents[4]) != nullptr); auto date = *std::get_if<Date>(&record.contents[4]); REQUIRE(date.timestamp == 1325376562000); } { REQUIRE(std::get_if<Text>(&record.contents[5]) != nullptr); auto text = *std::get_if<Text>(&record.contents[5]); REQUIRE(text.content == "<span class=\"dateline\">NEW ORLEANS</span>."); REQUIRE(text.mime == "text/html"); } { REQUIRE(std::get_if<AuthorInfo>(&record.contents[6]) != nullptr); auto author_info = *std::get_if<AuthorInfo>(&record.contents[6]); REQUIRE(author_info.role == "Reporter"); REQUIRE(author_info.name == "<NAME>"); REQUIRE(author_info.bio == "<NAME>'s bio"); } } <file_sep>/test/test_detail.cpp #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "wapopp/detail.hpp" using namespace wapopp; using namespace wapopp::detail; TEST_CASE("Read simple content", "[unit]") { SECTION("Missing content") { auto j = R"({ "mime": "text/plain", "type": "kicker" })"_json; auto content = read_simple_content<Kicker>(j); REQUIRE(std::get_if<Error>(&content) != nullptr); REQUIRE(std::get_if<Error>(&content)->msg == "Missing content"); } SECTION("Missing mime") { auto j = R"({ "content": "Colleges", "type": "kicker" })"_json; auto content = read_simple_content<Kicker>(j); REQUIRE(std::get_if<Error>(&content) != nullptr); REQUIRE(std::get_if<Error>(&content)->msg == "Missing mime"); } SECTION("Kicker") { auto j = R"({ "content": "Colleges", "mime": "text/plain", "type": "kicker" })"_json; auto content = read_simple_content<Kicker>(j); REQUIRE(std::get_if<Kicker>(&content) != nullptr); REQUIRE(std::get_if<Kicker>(&content)->content == j["content"]); REQUIRE(std::get_if<Kicker>(&content)->mime == j["mime"]); } SECTION("Title") { auto j = R"({ "content": "<NAME>, <NAME> are a perfect 1-2 punch for Virginia Tech", "mime": "text/plain", "type": "title" })"_json; auto content = read_simple_content<Title>(j); REQUIRE(std::get_if<Title>(&content) != nullptr); REQUIRE(std::get_if<Title>(&content)->content == j["content"]); REQUIRE(std::get_if<Title>(&content)->mime == j["mime"]); } SECTION("Byline") { auto j = R"({ "content": "By <NAME>", "mime": "text/plain", "type": "title" })"_json; auto content = read_simple_content<Byline>(j); REQUIRE(std::get_if<Byline>(&content) != nullptr); REQUIRE(std::get_if<Byline>(&content)->content == j["content"]); REQUIRE(std::get_if<Byline>(&content)->mime == j["mime"]); } SECTION("Text") { auto j = R"({ "content": "<span>paragraph</span>", "subtype":"paragraph", "mime": "text/html", "type": "sanitized_html" })"_json; auto content = read_simple_content<Text>(j); REQUIRE(std::get_if<Text>(&content) != nullptr); REQUIRE(std::get_if<Text>(&content)->content == j["content"]); REQUIRE(std::get_if<Text>(&content)->mime == j["mime"]); } } TEST_CASE("Read date content", "[unit]") { SECTION("Missing date field") { auto j = R"({ "mime": "text/plain", "type": "date" })"_json; auto content = read_date(j); REQUIRE(std::get_if<Error>(&content) != nullptr); REQUIRE(std::get_if<Error>(&content)->msg == "Missing content"); } SECTION("Correct date") { auto j = R"({ "mime": "text/plain", "content": 1325376562000, "type": "date" })"_json; auto content = read_date(j); REQUIRE(std::get_if<Date>(&content) != nullptr); REQUIRE(std::get_if<Date>(&content)->timestamp == j["content"]); } SECTION("Corrupted date") { auto j = R"({ "mime": "text/plain", "content": "oops", "type": "date" })"_json; auto content = read_date(j); REQUIRE(std::get_if<Error>(&content) != nullptr); REQUIRE(std::get_if<Error>(&content)->msg == "Failed to parse content (\"oops\") to a requested type"); } } TEST_CASE("Read author info", "[unit]") { SECTION("Correct author info") { auto j = R"({ "role":"Reporter", "type":"author_info", "name":"<NAME>", "bio":"<NAME> is a Montgomery County native ..." })"_json; auto content = read_author_info(j); REQUIRE(std::get_if<AuthorInfo>(&content) != nullptr); REQUIRE(std::get_if<AuthorInfo>(&content)->role == "Reporter"); REQUIRE(std::get_if<AuthorInfo>(&content)->name == "<NAME>"); REQUIRE(std::get_if<AuthorInfo>(&content)->bio == "<NAME> is a Montgomery County native ..."); } SECTION("Missing role") { auto j = R"({ "type":"author_info", "name":"<NAME>", "bio":"<NAME> is a Montgomery County native ..." })"_json; auto content = read_author_info(j); REQUIRE(std::get_if<Error>(&content) != nullptr); REQUIRE(std::get_if<Error>(&content)->msg == "Missing role"); } SECTION("Missing name") { auto j = R"({ "role":"Reporter", "type":"author_info", "bio":"<NAME> is a Montgomery County native ..." })"_json; auto content = read_author_info(j); REQUIRE(std::get_if<Error>(&content) != nullptr); REQUIRE(std::get_if<Error>(&content)->msg == "Missing name"); } SECTION("Missing bio") { auto j = R"({ "role": "Reporter", "type": "author_info", "name": "<NAME>" })"_json; auto content = read_author_info(j); REQUIRE(std::get_if<Error>(&content) != nullptr); REQUIRE(std::get_if<Error>(&content)->msg == "Missing bio"); } } TEST_CASE("Read image", "[unit]") { SECTION("Correct image") { auto j = R"({ "fullcaption": "Full Caption", "imageURL": "https://img.washingtonpost.com/somepic.jpg", "mime": "image/jpeg", "imageHeight": 2260, "imageWidth": 2775, "type": "image", "blurb": "Virginia Tech wide receiver Danny Coale..." })"_json; auto content = read_image(j); if (holds<Error>(content)) { std::cerr << take<Error>(std::move(content)).msg << std::endl; FAIL(""); } REQUIRE(std::get_if<Image>(&content) != nullptr); REQUIRE(std::get_if<Image>(&content)->caption == "Full Caption"); REQUIRE(std::get_if<Image>(&content)->url == "https://img.washingtonpost.com/somepic.jpg"); REQUIRE(std::get_if<Image>(&content)->blurb == "Virginia Tech wide receiver Danny Coale..."); REQUIRE(std::get_if<Image>(&content)->height == 2260); REQUIRE(std::get_if<Image>(&content)->width == 2775); } }
dbbf753cb50bf333d3caeec420c00f5f28c4617c
[ "CMake", "C++" ]
9
C++
pisa-engine/wapopp
25ff64e373bfaf51b24191cc7181b7db56119654
676f8bcab10c1d3584cad629e1e2da95cac607b4
refs/heads/main
<file_sep>import React, {Fragment} from 'react'; import './Nav.css' const Nav = () => { return ( <div className="nav"> <div className="row" > <div className="col-6" style={{textAlign:"left"}}> <h1 style={{color:"blue", paddingLeft:"40px"}}>User DashBoard</h1> </div> <div className="col-6" style={{paddingLeft:"200px"}}> <div className="row"> <div className="col-3" style={{paddingLeft:"70px"}}><button className="signin_button" onClick={(event) => window.location.href='/signin'}>Signin</button></div> <div className="col-3" style={{paddingLeft:"70px"}}><button className="signout_button" onClick={(event) => window.location.href='/'}>Signout</button></div> <div className="col-5" style={{paddingLeft:"120px"}}> <input className="form-control" placeholder="Type here to search......." style={{background:"#222", border:"1px solid blue",height:"35px", width:"250px", color:"white"}}></input> </div> <div className="col-1" ><img className="nav_avatar" src="https://upload.wikimedia.org/wikipedia/commons/0/0b/Netflix-avatar.png" alt="Avatar Logo"></img></div> </div> </div> </div> </div> ) } export default Nav;<file_sep>import React, { useState } from "react"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import 'bootstrap/dist/css/bootstrap.css'; import './Signin.css' import './App.css' const Signin = () => { return ( <div className="Login"> <form> <div className="form-inner"> <h2 style={{fontSize:"40px", paddingTop:"10px"}}>Login Here!</h2> <div className="form-group" style={{paddingTop:"40px"}}> <div className="row"> <div className="col-4" style={{textAlign:"right"}}> <label htmlFor="name" >Name</label> </div> <div className="col-8" style={{textAlign:"left"}}> <input type="text" name="name" id="name" /> </div> </div> <div className="form-group" style={{paddingTop:"20px"}}> <div className="row"> <div className="col-4" style={{textAlign:"right"}}> <label htmlFor="email">Email</label> </div> <div className="col-8" style={{textAlign:"left"}}> <input type="email" name="email" id="email"/> </div> </div> </div> <div className="form-group" style={{paddingTop:"10px"}}> <div className="row"> <div className="col-4" style={{textAlign:"right"}}> <label htmlFor="password" >Password</label> </div> <div className="col-8" style={{textAlign:"left"}}> <input type="password" name="password" id="password" /> </div> </div> </div> </div> <button className="submit_button">Login</button> </div> </form> </div> ) } export default Signin <file_sep>import React from 'react' import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Nav from './Nav' import './App.css'; import Mainpage from './Mainpage' import Signin from './Signin' import signup from './Signup' import Dashboard from './Dashboard' function App() { return ( <div className="App"> <React.Fragment> <Router> <Nav/> <Switch> <Route exact path="/" component={Mainpage} /> <Route exact path="/signin" component={Signin} /> </Switch> </Router> </React.Fragment> </div> ); } export default App; <file_sep>const Dashboard = () => { return ( <div style={{color:"blue"}}> Hello </div> ) } export default Dashboard <file_sep>import React , {useState} from "react" const Signup = () => { const [values, setValues] = useState({ name:"", email:"", password:"" }) const {name, email, password} = values const handelChange = name => event => { setValues({...values, error: false, [name] : event.target.value}) } const onSubmit = event => { event.preventDefault(); setValues({...values, error: false}); } return ( <div className="row"> <div className="col-md-4 offset-sm-4 text-left"> <form> <div className="form-group" > <label className="text-light">Name</label> <input className="form-control" onChange={handelChange("name")} type="text" value={name}/> </div> <div className="form-group" > <label className="text-light">Email</label> <input className="form-control" onChange={handelChange("email")} type="email" value={email}/> </div> <div className="form-group" > <label className="text-light">Password</label> <input className="form-control" onChange={handelChange("password")} type="<PASSWORD>" value={password}/> </div> <div className="py-3"> <button onClick={onSubmit} className="btn btn-info btn-block offset-sm-4" >Submit</button> </div> </form> </div> </div> ) } export default Signup;
5224ca76f18372ab0e1e3f99994acad1f50c349b
[ "JavaScript" ]
5
JavaScript
shanu-droid/PlayAroundMovie-DashBoard
95ac4562e1b5256ac7f83691d8652cd08a7ce25f
81456aaef304125c6d7c1c4fd89bc566253cf63f
refs/heads/master
<file_sep>#!/usr/bin/env node process.title = 'watch'; var argv = require('minimist')(process.argv.slice(2)); var watch = require('../'); var pattern = argv._.shift() || argv.p || argv.pattern || argv.f || argv.files var command = argv._.shift() || argv.c || argv.cmd || argv.command; var options = { pattern: pattern, command: command }; watch(options); <file_sep>describe('sample test', function () { it('to run', function (done) { setTimeout(done, 20); }); it('add something to test', function (){}); });
b6fd5d8a0bcca2d8ade7b1aec9e355415dd7ceb1
[ "JavaScript" ]
2
JavaScript
0xflotus/watch-cli
b5fd61de2dddc3ecc9b55f9efd0b7aa17c0c0042
6db52c36c72cf99f4c7d76a5777352f896e91114
refs/heads/main
<file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A utility class to run a function in a separate daemon thread.""" import abc import enum import queue import threading from typing import Optional from absl import logging class ThreadFunction(metaclass=abc.ABCMeta): """Base class that encapsulates long-lived functions in a separate thread.""" class Signal(enum.IntEnum): """Defines commands we can use to communicate with the internal thread.""" # The thread should be stopped to allow for graceful termination. KILL = 1 def __init__(self, block_input: bool, block_output: bool, name: str): """Initializes this ThreadFunction. Args: block_input: Whether to block this thread when reading its input queue. block_output: Whether to block this thread when writing to its output queue. name: Name of the thread. Used to keep track of threads in logging. """ self._block_input = block_input self._block_output = block_output self._name = name self._input_queue = queue.Queue() self._output_queue = queue.Queue() self._should_run = True self._internal_thread = threading.Thread(target=self._run) self._internal_thread.daemon = True self._internal_thread.start() def read(self, block: bool = True, timeout: Optional[float] = None): """'Public' method for clients to read values _from_ this thread. Args: block: Whether the client should block. timeout: Timeout for getting output from the queue, in seconds. Returns: The value produced by the underlying thread. """ try: return self._output_queue.get(block=block, timeout=timeout) except queue.Empty: return None def write(self, value, block: bool = True, timeout: Optional[float] = None): """'Public' method for clients to write values _to_ this thread. Args: value: The value to send to the underlying thread. block: Whether the client should block. timeout: Timeout for setting input in the queue, in seconds. Returns: The value produced by the underlying thread. """ self._input_queue.put(value, block=block, timeout=timeout) @abc.abstractmethod def main(self): """main() function that subclasses need to override.""" pass def kill(self): """Shorthand for clients to terminate this thread.""" logging.info('Killing %s thread', self._name) # Sending a kill signal to clean up blocked read_values. self.write(ThreadFunction.Signal.KILL, block=True) # Stopping the _run loop. self._should_run = False def _run(self): """'Private' method that reruns main() until explicit termination.""" logging.info('Starting %s thread.', self._name) while self._should_run: self.main() logging.info('Finished %s thread.', self._name) def _read_value(self): """'Protected' method for subclasses to read values from their input.""" try: return self._input_queue.get(block=self._block_input) except queue.Empty: pass # Ignore empty queues. Keep going. def _write_value(self, value): """'Protected' method for subclasses to write values to their output.""" self._output_queue.put(value, block=self._block_output) <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.logcat_thread.""" import re import subprocess import threading from typing import Match, Pattern from absl.testing import absltest from android_env.components import logcat_thread from android_env.proto import task_pb2 import mock class FakeStream(): """This class simulates the logs coming from ADB.""" def __init__(self): self._values = [] self._kill = False self._lock = threading.Lock() def send_value(self, value): with self._lock: self._values.append(value) def has_next_value(self): return bool(self._values) def kill(self): self._kill = True def __iter__(self): while True: if self._kill: return if not self._values: continue else: with self._lock: next_value = self._values.pop(0) yield next_value def _log_parsing_config(): """Returns log_parsing_config object for testing.""" return task_pb2.LogParsingConfig( filters=['AndroidRLTask:V']) class FakeProc(): """Fake process that exposes a fake stdout stream.""" def __init__(self): self.stdout = FakeStream() self.is_alive = True def kill(self): self.stdout.kill() self.is_alive = False def make_stdout(data): """Returns a valid log output with given data as message.""" return ' 1553110400.424 5583 5658 D Tag: %s' % data class LogcatThreadTest(absltest.TestCase): def setUp(self): super().setUp() self.mock_popen = self.enter_context( mock.patch.object(subprocess, 'Popen', autospec=True)) self.fake_proc = FakeProc() self.mock_popen.return_value = self.fake_proc def tearDown(self): self.fake_proc.stdout.kill() super().tearDown() def test_cmd(self): _ = logcat_thread.LogcatThread( adb_command_prefix=['adb_bin', '-P', '12345', '-s', 'my_device'], log_parsing_config=_log_parsing_config()) expected_cmd = [ 'adb_bin', '-P', '12345', '-s', 'my_device', 'logcat', '-v', 'epoch', 'AndroidRLTask:V', '*:S', ] self.mock_popen.assert_called_once_with( expected_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, universal_newlines=True) def test_cmd_with_filters(self): _ = logcat_thread.LogcatThread( adb_command_prefix=['adb', '-P', '5037'], log_parsing_config=_log_parsing_config()) expected_cmd = [ 'adb', '-P', '5037', 'logcat', '-v', 'epoch', 'AndroidRLTask:V', '*:S' ] self.mock_popen.assert_called_once_with( expected_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, universal_newlines=True) def test_kill(self): logcat = logcat_thread.LogcatThread( adb_command_prefix=['adb', '-P', '5037'], log_parsing_config=_log_parsing_config()) self.assertTrue(self.fake_proc.is_alive) logcat.kill() self.assertFalse(self.fake_proc.is_alive) def test_listeners(self): """Ensures that we can wait for a specific message without polling.""" logcat = logcat_thread.LogcatThread( adb_command_prefix=['adb', '-P', '5037'], log_parsing_config=_log_parsing_config(), print_all_lines=True) self.mock_popen.assert_called_once() # Set up a listener that modifies an arbitrary state. some_state = False def my_handler(event: Pattern[str], match: Match[str]): del event, match nonlocal some_state some_state = True # Create a desired event and hook up the listener. my_event = re.compile('Hello world') listener = logcat_thread.EventListener(my_event, my_handler) logcat.add_event_listener(listener) self.fake_proc.stdout.send_value('Hi there!') # This should not match. self.assertFalse(some_state) self.fake_proc.stdout.send_value(make_stdout('Hello world')) logcat.wait(event=my_event, timeout_sec=1.0) self.assertTrue(some_state) # Waiting for any events should also trigger the listener. some_state = False self.fake_proc.stdout.send_value(make_stdout('Hello world')) logcat.wait(event=None, timeout_sec=1.0) self.assertTrue(some_state) # After removing the listener, it should not be called anymore. some_state = False logcat.remove_event_listener(listener) self.fake_proc.stdout.send_value(make_stdout('Hello world')) logcat.wait(event=my_event, timeout_sec=1.0) self.assertFalse(some_state) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.task_manager.py.""" import json from absl.testing import absltest from android_env.components import adb_controller from android_env.components import dumpsys_thread from android_env.components import logcat_thread from android_env.components import setup_step_interpreter from android_env.components import task_manager from android_env.proto import task_pb2 import mock import numpy as np class TaskManagerTest(absltest.TestCase): def setUp(self): super().setUp() self.addCleanup(mock.patch.stopall) # Disable previous patches. self._adb_controller = mock.create_autospec(adb_controller.AdbController) self._setup_step_interpreter = mock.create_autospec( setup_step_interpreter.SetupStepInterpreter) self._dumpsys_thread = mock.create_autospec(dumpsys_thread.DumpsysThread) self._logcat_thread = mock.create_autospec(logcat_thread.LogcatThread) mock.patch.object( adb_controller, 'AdbController', return_value=self._adb_controller).start() mock.patch.object( setup_step_interpreter, 'SetupStepInterpreter', return_value=self._setup_step_interpreter).start() mock.patch.object( dumpsys_thread, 'DumpsysThread', return_value=self._dumpsys_thread).start() mock.patch.object( logcat_thread, 'LogcatThread', return_value=self._logcat_thread).start() def test_setup_task(self): task_mgr = task_manager.TaskManager(task=task_pb2.Task()) task_mgr.setup_task(adb_controller=self._adb_controller) assert hasattr(task_mgr, '_logcat_thread') assert hasattr(task_mgr, '_setup_step_interpreter') def test_get_current_reward(self): # Replace `LogcatThread.add_event_listener` with one that simply calls `fn` # right away. def my_add_ev_listener(event_listener: logcat_thread.EventListener): # Check that the event matches what's expected. match = event_listener.regexp.match('Reward: 123.0') if match is None: # Ignore events that are not rewards. return event_listener.handler_fn(event_listener.regexp, match) task = task_pb2.Task() task.log_parsing_config.log_regexps.reward.extend([ '^[Rr]eward: ([-+]?[0-9]*\\.?[0-9]*)$' ]) task_mgr = task_manager.TaskManager(task=task) self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener task_mgr.setup_task(adb_controller=self._adb_controller) self.assertEqual(task_mgr.get_current_reward(), 123.0) def test_reward_event(self): # Replace `LogcatThread.add_event_listener` with one that simply calls `fn` # right away. def my_add_ev_listener(event_listener: logcat_thread.EventListener): # Check that the event matches what's expected. match_1 = event_listener.regexp.match('foo_1') match_2 = event_listener.regexp.match('foo_2') match_3 = event_listener.regexp.match('Reward: 2.0') if match_1: event_listener.handler_fn(event_listener.regexp, match_1) if match_2: event_listener.handler_fn(event_listener.regexp, match_2) if match_3: event_listener.handler_fn(event_listener.regexp, match_3) task = task_pb2.Task() reward_event_1 = task_pb2.LogParsingConfig.LogRegexps.RewardEvent( event='foo_1', reward=5.0) reward_event_2 = task_pb2.LogParsingConfig.LogRegexps.RewardEvent( event='foo_2', reward=-1.0) task.log_parsing_config.log_regexps.reward_event.extend( [reward_event_1, reward_event_2]) task.log_parsing_config.log_regexps.reward.extend( ['^[Rr]eward: ([-+]?[0-9]*\\.?[0-9]*)$']) task_mgr = task_manager.TaskManager(task=task) self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener task_mgr.setup_task(adb_controller=self._adb_controller) self.assertEqual(task_mgr.get_current_reward(), 6.0) def test_get_current_reward_via_score(self): # Replace `LogcatThread.add_event_listener` with one that simply calls `fn` # right away. def my_add_ev_listener(event_listener: logcat_thread.EventListener): # Check that the event matches what's expected. event = event_listener.regexp match = event.match('score: 200.0') if match is None: # Ignore events that are not scores. return event_listener.handler_fn(event, match) # Scores are accumulated by their differences, so a subsequent lower score # means that the final reward decreases. match = event.match('score: 185') event_listener.handler_fn(event, match) task = task_pb2.Task() task.log_parsing_config.log_regexps.score = ( '^score: ([-+]?[0-9]*\\.?[0-9]*)$') task_mgr = task_manager.TaskManager(task=task) self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener task_mgr.setup_task(adb_controller=self._adb_controller) self.assertEqual(task_mgr.get_current_reward(), 185.0) def test_get_current_extras(self): # Replace `LogcatThread.add_event_listener` with one that simply calls `fn` # right away. def my_add_ev_listener(event_listener: logcat_thread.EventListener): # Check that the event matches what's expected. event = event_listener.regexp match = event.match('extra: some_extra [1, 2]') if match is None: # Ignore events that are not extras. return # Emit events. fn = event_listener.handler_fn fn(event, event.match('extra: an_extra [1, 2, 3]')) fn(event, event.match('extra: an_extra [4, 5, 6]')) fn(event, event.match('extra: another_extra 0.5')) fn(event, event.match('extra: multi_dimension_extra [[9,8,7],[6,5,4]]')) fn(event, event.match('extra: boolean_extra')) # Setup the task and trigger the listener. task = task_pb2.Task() task.log_parsing_config.log_regexps.extra.extend([ '^extra: (?P<name>[^ ]*)[ ]?(?P<extra>.*)$' ]) task_mgr = task_manager.TaskManager(task=task) self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener task_mgr.setup_task(adb_controller=self._adb_controller) # Check expectations. extras = task_mgr.get_current_extras() np.testing.assert_almost_equal([[1, 2, 3], [4, 5, 6]], extras.get('an_extra')) np.testing.assert_almost_equal([0.5], extras.get('another_extra')) np.testing.assert_almost_equal([[[9, 8, 7], [6, 5, 4]]], extras.get('multi_dimension_extra')) np.testing.assert_equal([1], extras.get('boolean_extra')) def test_get_current_extras_json_format(self): # Replace `LogcatThread.add_event_listener` with one that simply calls `fn` # right away. def my_add_ev_listener(event_listener: logcat_thread.EventListener): # Check that the event matches what's expected. event = event_listener.regexp match = event.match('json_extra: {}') if match is None: # Ignore events that are not extras. return # Emit events. extra = { 'extra_scalar': 0, 'extra_list': [1, 2, 3, 4], 'extra_dict': { 'foo': 'bar' }, 'extra_string': 'a_string' } extra_update = {'extra_string': 'a_new_string', 'extra_float': 0.6} fn = event_listener.handler_fn fn(event, event.match(f'json_extra: {json.dumps(extra)}')) fn(event, event.match(f'json_extra: {json.dumps(extra_update)}')) # Setup the task and trigger the listener. task = task_pb2.Task() task.log_parsing_config.log_regexps.json_extra.extend([ '^json_extra: (?P<json_extra>.*)$' ]) task_mgr = task_manager.TaskManager(task=task) self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener task_mgr.setup_task(adb_controller=self._adb_controller) # Check expectations. expected_extra = { 'extra_scalar': [0], 'extra_list': [[1, 2, 3, 4]], 'extra_dict': [{ 'foo': 'bar' }], 'extra_string': ['a_string', 'a_new_string'], 'extra_float': [0.6] } extras = task_mgr.get_current_extras() np.testing.assert_almost_equal( expected_extra.get('extra_scalar'), extras.get('extra_scalar')) np.testing.assert_almost_equal( expected_extra.get('extra_list'), extras.get('extra_list')) np.testing.assert_equal( expected_extra.get('extra_string'), extras.get('extra_string')) np.testing.assert_almost_equal( expected_extra.get('extra_float'), extras.get('extra_float')) np.testing.assert_equal( expected_extra.get('extra_dict'), extras.get('extra_dict')) def test_multi_log_regexp(self): # Replace `LogcatThread.add_event_listener` with one that simply calls `fn` # right away. def my_add_ev_listener(event_listener: logcat_thread.EventListener): # Check that the event matches what's expected. match = event_listener.regexp.match('Reward_2: 123.0') if match is None: # Ignore events that are not rewards. return event_listener.handler_fn(event_listener.regexp, match) task = task_pb2.Task() task.log_parsing_config.log_regexps.reward.extend([ '^[Rr]eward_1: ([-+]?[0-9]*\\.?[0-9]*)$', '^[Rr]eward_2: ([-+]?[0-9]*\\.?[0-9]*)$' ]) task_mgr = task_manager.TaskManager(task=task) self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener task_mgr.setup_task(adb_controller=self._adb_controller) self.assertEqual(task_mgr.get_current_reward(), 123.0) def test_multi_reward_regexp(self): # Replace `LogcatThread.add_event_listener` with one that simply calls `fn` # right away.' def my_add_ev_listener(event_listener: logcat_thread.EventListener): # Check that the event matches what's expected. match_1 = event_listener.regexp.match('Reward_1: 5.0') match_2 = event_listener.regexp.match('Reward_2: 10.0') if match_1: event_listener.handler_fn(event_listener.regexp, match_1) if match_2: event_listener.handler_fn(event_listener.regexp, match_2) task = task_pb2.Task() task.log_parsing_config.log_regexps.reward.extend([ '^[Rr]eward_1: ([-+]?[0-9]*\\.?[0-9]*)$', '^[Rr]eward_2: ([-+]?[0-9]*\\.?[0-9]*)$', ]) task_mgr = task_manager.TaskManager(task=task) self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener task_mgr.setup_task(adb_controller=self._adb_controller) self.assertEqual(task_mgr.get_current_reward(), 15.0) def test_check_episode_end(self): # Replace `LogcatThread.add_event_listener` with one that simply calls `fn` # right away. def my_add_ev_listener(event_listener: logcat_thread.EventListener): # Check that the event matches what's expected. event = event_listener.regexp match = event.match('I am done!') if match is None: # Ignore events that are not episode end. return event_listener.handler_fn(event, match) task = task_pb2.Task() task.log_parsing_config.log_regexps.episode_end.extend(['I am done!']) task_mgr = task_manager.TaskManager(task=task) self._logcat_thread.add_event_listener.side_effect = my_add_ev_listener task_mgr.setup_task(adb_controller=self._adb_controller) episode_end = task_mgr.check_if_episode_ended() self.assertTrue(episode_end) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.emulator_launcher.""" import os from absl.testing import absltest from android_env.components import emulator_launcher import mock from pexpect import popen_spawn import builtins class EmulatorLauncherTest(absltest.TestCase): def setUp(self): super().setUp() self._emulator_path = 'fake/path/emulator' self._adb_port = 5554 self._adb_server_port = 1234 self._emulator_console_port = 5555 self._avd_name = 'my_avd_name' self._emulator = mock.create_autospec(popen_spawn.PopenSpawn) self._emulator.after = 'after' self._emulator_output = mock.create_autospec(open) self._emulator_output.close = lambda: None self._expected_command = [ self._emulator_path, '-no-snapshot', '-gpu', 'swiftshader_indirect', '-no-audio', '-verbose', '-avd', self._avd_name, ] self._ports = ['-ports', f'{self._emulator_console_port},{self._adb_port}'] base_lib_dir = self._emulator_path[:-8] + 'lib64/' ld_library_path = ':'.join([ base_lib_dir + 'x11/', base_lib_dir + 'qt/lib/', base_lib_dir + 'gles_swiftshader/', base_lib_dir ]) self._expected_env_vars = { 'ANDROID_HOME': '', 'ANDROID_SDK_ROOT': '', 'ANDROID_AVD_HOME': '', 'ANDROID_EMULATOR_KVM_DEVICE': '/dev/kvm', 'ANDROID_ADB_SERVER_PORT': '1234', 'LD_LIBRARY_PATH': ld_library_path, 'QT_DEBUG_PLUGINS': '1', 'QT_XKB_CONFIG_ROOT': str(self._emulator_path[:-8] + 'qt_config/'), } @mock.patch.object(os, 'environ', autospec=True, return_value=dict()) def test_launch(self, os_environ): del os_environ launcher = emulator_launcher.EmulatorLauncher( adb_port=self._adb_port, adb_server_port=self._adb_server_port, emulator_console_port=self._emulator_console_port, emulator_path=self._emulator_path, avd_name=self._avd_name, grpc_port=-1) with mock.patch.object( popen_spawn, 'PopenSpawn', autospec=True, return_value=self._emulator) as emulator_init, \ mock.patch.object( builtins, 'open', autospec=True, return_value=self._emulator_output): launcher.launch() emulator_init.assert_called_once_with( cmd=self._expected_command + self._ports, logfile=self._emulator_output, env=self._expected_env_vars) @mock.patch.object(os, 'environ', autospec=True, return_value=dict()) def test_grpc_port(self, os_environ): del os_environ launcher = emulator_launcher.EmulatorLauncher( adb_port=self._adb_port, adb_server_port=self._adb_server_port, emulator_console_port=self._emulator_console_port, emulator_path=self._emulator_path, avd_name=self._avd_name, grpc_port=8554) with mock.patch.object( popen_spawn, 'PopenSpawn', autospec=True, return_value=self._emulator) as emulator_init, \ mock.patch.object( builtins, 'open', autospec=True, return_value=self._emulator_output): launcher.launch() emulator_init.assert_called_once_with( cmd=self._expected_command + ['-grpc', '8554'] + self._ports, logfile=self._emulator_output, env=self._expected_env_vars) @mock.patch.object(os, 'environ', autospec=True, return_value=dict()) def test_restart(self, os_environ): del os_environ launcher = emulator_launcher.EmulatorLauncher( adb_port=self._adb_port, adb_server_port=self._adb_server_port, emulator_console_port=self._emulator_console_port, emulator_path=self._emulator_path, avd_name=self._avd_name, grpc_port=-1) with mock.patch.object( popen_spawn, 'PopenSpawn', autospec=True, return_value=self._emulator) as emulator_init, \ mock.patch.object( builtins, 'open', autospec=True, return_value=self._emulator_output): launcher.launch() launcher.restart() self._emulator.kill.assert_called_once() emulator_init.assert_has_calls([mock.call( cmd=self._expected_command + self._ports, logfile=self._emulator_output, env=self._expected_env_vars)]*2) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Extends Android observation with the latest action taken.""" from typing import Dict from android_env.components import action_type from android_env.components import utils from android_env.wrappers import base_wrapper import dm_env from dm_env import specs import numpy as np class LastActionWrapper(base_wrapper.BaseWrapper): """Extends Android observations with information about the last action taken. The position of the last action is denoted by a single white pixel (with a value of 255) in a channel of all black pixels (with a value of 0). As this wrapper makes use of temporarily stored information about the last action taken, it is important to apply on the environment side rather than the agent side. Recommended not to apply before an ImageRescaleWrapper, to avoid distortion of the single pixel denoting the action position. """ def __init__(self, env: dm_env.Environment, concat_to_pixels: bool = True): """Initializes the internal state of this wrapper. Args: env: the environment to wrap. concat_to_pixels: If True, will add a channel to the pixel observation. If False, will pass the action as an extra observation. """ super().__init__(env) self._concat_to_pixels = concat_to_pixels self._screen_dimensions = self._env.observation_spec()['pixels'].shape[:2] def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep: observation = timestep.observation.copy() processed_observation = self._process_observation(observation) return timestep._replace(observation=processed_observation) def _process_observation( self, observation: Dict[str, np.ndarray] ) -> Dict[str, np.ndarray]: """Extends observation with last_action data.""" processed_observation = observation.copy() last_action_layer = self._get_last_action_layer(observation['pixels']) if self._concat_to_pixels: pixels = observation['pixels'].copy() processed_pixels = np.dstack((pixels, last_action_layer)) processed_observation['pixels'] = processed_pixels else: processed_observation['last_action'] = last_action_layer return processed_observation def _get_last_action_layer(self, pixels: np.ndarray) -> np.ndarray: """Makes sure the rescaling doesn't distort the last_action layer.""" last_action = self._env.raw_action last_action_layer = np.zeros(self._screen_dimensions, dtype=pixels.dtype) if ('action_type' in last_action and last_action['action_type'] == action_type.ActionType.TOUCH): touch_position = last_action['touch_position'] x, y = utils.touch_position_to_pixel_position( touch_position, width_height=self._screen_dimensions[::-1]) last_action_layer[y, x] = 255 return last_action_layer def reset(self) -> dm_env.TimeStep: timestep = self._env.reset() return self._process_timestep(timestep) def step(self, action) -> dm_env.TimeStep: timestep = self._env.step(action) return self._process_timestep(timestep) def observation_spec(self) -> Dict[str, specs.Array]: parent_spec = self._env.observation_spec().copy() shape = parent_spec['pixels'].shape if self._concat_to_pixels: parent_spec['pixels'] = specs.Array( shape=(shape[0], shape[1], shape[2] + 1), dtype=parent_spec['pixels'].dtype, name=parent_spec['pixels'].name) else: parent_spec.update({ 'last_action': specs.Array( shape=(shape[0], shape[1]), dtype=parent_spec['pixels'].dtype, name='last_action') }) return parent_spec <file_sep># AndroidEnv - Available tasks This page gives a detailed overview of the example tasks provided with AndroidEnv. The purpose is to give researchers an idea of the different kinds of challenges that AndroidEnv poses. To use any of these tasks in your own experiments, click on **Download** to download a ZIP file containing textprotos and the corresponding APKs. After downloading, move the `.apk` and `.textproto` files to a directory of your choice and take note of their path. This information is needed for [running](instructions.md#create-the-env) an AndroidEnv instance with the given task. <!-- mdformat off(multi-line tables are not supported well) --> | App / Game | Interface | Time reactive | Multi-level | Rewards | Extras | Download | | --------------------------------------------------- | -------------------- | -------------- | ----------------------------- | ---------- | ------------ | -------- | | [Vokram (MDP)](#vokram) | Tapping (buttons) | No | Yes (4 variants) | Dense | Yes | [Download](https://storage.googleapis.com/android_env-tasks/mdp.tar.gz) | | [Accessibility Forwarder](#accessibility-forwarder) | Tapping (buttons) | No | No | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/accessibility_forwarder.tar.gz) | | [Apple Flinger](#apple-flinger) | Drag & drop | No | Yes (6 variants) | Dense | No | [Download](https://storage.googleapis.com/android_env-tasks/apple_flinger.tar.gz) | | [Blockinger](#blockinger) | Tapping (buttons) | Yes | No | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/blockinger.tar.gz) | | [Catch](#catch) | Touch | Yes | No | Dense | Yes | [Download](https://storage.googleapis.com/android_env-tasks/catch_the_ball.tar.gz) | | [Classic 2048](#classic-2048) | Swiping | No | No | Dense | Yes | [Download](https://storage.googleapis.com/android_env-tasks/classic_2048.tar.gz) | | [Dodge](#dodge) | Tapping | Yes | No | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/dodge.tar.gz) | | [DroidFish (Chess)](#droidfish) | Tapping | No | Yes (3 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/droidfish.tar.gz) | | [FlappyDroid](#flappydroid) | Tapping | Yes | Yes (2 levels) | Dense | No | [Download](https://storage.googleapis.com/android_env-tasks/systemui_egg_land.tar.gz) | | [Frozen Bubble](#frozen-bubble) | Dragging, tapping | No | No | Sparse | No | [Download](https://storage.googleapis.com/android_env-tasks/frozen_bubble.tar.gz) | | [Memory Game](#memory-game) | Tapping | No | Yes (6 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/memory_game.tar.gz) | | [Minesweeper](#minesweeper) | Tapping | No | Yes (3 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/minesweeper.tar.gz) | | [Open Sudoku](#open-sudoku) | Tapping (buttons) | No | Yes (3 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/open_sudoku.tar.gz) | | [Perfection](#perfection) | Drag & drop | No | Yes (3 game types) | Dense | Yes | [Download](https://storage.googleapis.com/android_env-tasks/perfection.tar.gz) | | [Rocket Sleigh](#rocket-sleigh) | Tapping | Yes | No | Dense | No | [Download](https://storage.googleapis.com/android_env-tasks/rocket_sleigh.tar.gz) | | [Pong](#pong) | Drag | Yes | Yes (3 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/pong.tar.gz) | | [SGT Puzzles - Blackbox](#sgt-puzzles-blackbox) | Tapping | No | Yes (4 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Bridge](#sgt-puzzles-bridge) | Drag & drop | No | Yes (5 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Cube](#sgt-puzzles-cube) | Tapping | No | Yes (3 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Dominosa](#sgt-puzzles-dominosa) | Tapping | No | Yes (5 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Fifteen](#sgt-puzzles-fifteen) | Tapping | No | Yes (4 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Flip](#sgt-puzzles-flip) | Tapping | No | Yes (3 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/apple_flinger.tar.gz) | | [SGT Puzzles - Flood](#sgt-puzzles-flood) | Tapping | No | Yes (3 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Galaxies](#sgt-puzzles-galaxies) | Tapping | No | Yes (6 sizes) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Guess](#sgt-puzzles-guess) | Tapping | No | Yes (4 levels) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Inertia](#sgt-puzzles-inertia) | Tapping | No | Yes (2 sizes) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Light Up](#sgt-puzzles-light-up) | Tapping | No | Yes (5 sizes) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Loopy](#sgt-puzzles-loopy) | Tapping | No | Yes (3 sizes) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [SGT Puzzles - Net](#sgt-puzzles-net) | Tapping | No | Yes (5 sizes) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/sgtpuzzles.tar.gz) | | [Shattered Pixel Dungeon](#shattered-pixel-dungeon) | Tapping | Yes | Yes (4 variants) | Sparse | No | [Download](https://storage.googleapis.com/android_env-tasks/shattered_pixel_dungeon.tar.gz) | | [Simple Solitaire](#simple-solitaire) | Drag & drop | No | Yes (19 tasks) | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/simple_solitaire.tar.gz) | | [Snake](#snake) | Tapping (buttons) | Yes | No | Sparse | Yes | [Download](https://storage.googleapis.com/android_env-tasks/aosp_samples_snake.tar.gz) | | [Vector Pinball](#vector-pinball) | Tapping | Yes | Yes (5 variants) | Sparse | No | [Download](https://storage.googleapis.com/android_env-tasks/vector_pinball.tar.gz) | <!-- mdformat on --> ## Vokram Vokram is our in-house implementation of an Android app that displays a Markov-Decision-Process (MDP) graph as buttons on the screen which the agent must use to select its actions. The observation is simply the color of the background, and the actions are the buttons themselves which are presented in different colors. * **mdp_0000**: This is a task that presents the agent with two colored, but unlabeled buttons on the screen. Pressing one of the buttons gives the agent a reward of `-1` and redraws the buttons on the screen. The other button gives a reward of `+1` and terminates the episode. The color of the buttons is the same throughout the episode. The sizes of the buttons are randomized at each screen draw. Pressing anywhere else on the screen gives a reward of zero. The task lasts up 60 seconds, at which point the episode is restarted. The underlying dynamics governing the buttons is a simple 2-state 2-action Markov Decision Process (MDP). The MDP is intentionally simple environment that can be used to debug agents. * **mdp_0001**: This is similar to `mdp_0000` but it's even simpler. It presents the agent with a single button which gives a reward of `+1` and terminates the episode when pressed. This task can be used for example to train agents to click buttons. * **mdp_0002**: In this task there are two buttons, pressing either of which will terminate the episode with a return of `+1`. * **mdp_0003**: An equivalent of `mdp_0000` with rewards reversed: the episode ends when the wrong button is clicked, and carries on with a new set of buttons when the correct one is clicked. <details> <summary>Extras returned</summary> * `actions`: - Set of all buttons present, e.g. `['A', 'B']`. - Returned when any button is pressed. - Has `shape=[2], dtype=STRING_U1`. * `clicks`: - Character representing the button pressed. - Returned when any button is pressed. - Has `shape=[1], dtype=STRING_U1`. * `buttons`: - Coordinates of the top left and bottom right corners of each button, e.g `[[x_a_0, y_a_0, x_a_1, y_a_1], [x_b_0, y_a_0, x_b_1, y_b_1]]`. - Returned when any button is pressed. - Has `shape=[2, 4], dtype=INT32`. </details> **mdp_0000** | **mdp_0001** | **mdp_0002** | **mdp_0003** ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------ ![Screenshot of 'mdp_0000'](images/mdp_0000.gif) | ![Screenshot of 'mdp_0001'](images/mdp_0001.gif) | ![Screenshot of 'mdp_0002'](images/mdp_0002.gif) | ![Screenshot of 'mdp_0003'](images/mdp_0003.gif) ## Accessibility Forwarder This application returns all [accessibility service events](https://developer.android.com/reference/android/accessibilityservice/AccessibilityService) in the form of task extras, and, if specified, rewards the agent for specific events. Most often this means receiving the description of an accessibility event in string format, such as `A button was pressed.` or `A menu was opened.` etc. The two specific tasks provided here associate rewards with opening the "History" menu in the Calculator app, and setting and resetting a timer in the Clock app, but any goal can be provided in a similar manner if it can be associated with an accessibility event. <details> <summary>Extras returned</summary> * `clicks`: - Content description of UI element (e.g. "Settings"). - Returned the given UI element is clicked. - Has `shape=[1], dtype=STRING_U250`. * `event`: - Text of the accessibility event (e.g. button text "Accept & Continue"). - Returned upon accessibility event. - Has `shape=[1], dtype=STRING_U250`. </details> **calculator_history** | **clock_set_timer** -------------------------------------------------------------------- | ------------------- ![Screenshot of 'calculator_history'](images/calculator_history.gif) | ![Screenshot of 'clock_set_timer'](images/clock.gif) ## Apple Flinger A clone of Angry Birds. Even though the game offers many levels, we currently expose six levels. See the original github repo for more info: https://gitlab.com/ar-/apple-flinger. <details> <summary>Extras returned</summary> Returns no extras. </details> **apple_flinger_M_1_1** | **apple_flinger_M_1_2** | **apple_flinger_M_1_18** ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------------ ![Screenshot of 'apple_flinger_M_1_1'](images/apple_flinger_M_1_1.gif) | ![Screenshot of 'apple_flinger_M_1_2'](images/apple_flinger_M_1_2.gif) | ![Screenshot of 'apple_flinger_M_1_18'](images/apple_flinger_M_1_18.gif) **apple_flinger_M_2_1** | **apple_flinger_M_2_2** | **apple_flinger_M_2_18** ----------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------------ ![Screenshot of 'apple_flinger_M_2_1'](images/apple_flinger_M_2_1.gif)) | ![Screenshot of 'apple_flinger_M_2_2'](images/apple_flinger_M_2_2.gif) | ![Screenshot of 'apple_flinger_M_2_18'](images/apple_flinger_M_2_18.gif) ## Blockinger This is a Tetris clone implemented with on-screen controls. See the original github repo for more info: https://github.com/tasioleiva/Blockinger.git. <details> <summary>Extras returned</summary> * `down_pressed`, `left_pressed`, `right_pressed`, `rotate_right_pressed`, `drop_pressed`: - Indicates that said button has been pressed. - Returned when said button has been pressed. - Has `shape=[1], dtype=INT32`. * `current_board`: - One-hot encoded state of the board. - Has `shape=[18, 10], dtype=INT32`. * `current_line`, `cleared_lines`: - Index of the relevant line. - Has `shape=[1], dtype=INT32`. * `current_piece`, `next_piece`: - Index representing the type of piece. - Has `shape=[1], dtype=INT32`. </details> ![Screenshot of 'blockinger'](images/blockinger.gif) ## Catch Classic Catch game. <details> <summary>Extras returned</summary> * `ball`: - `x, y` coordinates of the ball. - Returned every timestep. - Has `shape=[2], dtype=INT32`. * `paddle`: - `x, y` coordinates of the paddle. - Returned every timestep. - Has `shape=[2], dtype=INT32`. * `paddle_width`: - Width of the paddle. - Returned every timestep. - Has `shape=[1], dtype=INT32`. * `lives`: - Number of lives left. - Returned every timestep. - Has `shape=[1], dtype=INT32`. </details> ![Screenshot of 'catch_the_ball_default'](images/catch_the_ball_default.gif) ## Classic 2048 This is an Android implementation of a popular game in the 2010s. See the original github repo for more info: https://github.com/tpcstld/2048.git. <details> <summary>Extras returned</summary> * `grid`: - State of the board. - Returned when the board changes. - Has `shape=[4, 4], dtype=INT32`. * `direction`: - Index representing the direction of the last swipe (between 0-3). - Returned when the swipe prompted a board change. - Has `shape=[1], dtype=INT32`. </details> ![Screenshot of 'classic_2048'](images/classic_2048.gif) ## Dodge Guide the ball from the red line to the green line without getting hit by the floating dots. <details> <summary>Extras returned</summary> * `lives`: - Number of lives left. - Returned when its value changes. - Has `shape=[1], dtype=INT32`. * `level`: - Current level. - Returned when its value changes. - Has `shape=[1], dtype=INT32`. </details> ![Screenshot of 'dodge_default'](images/dodge_default.gif) ## DroidFish Standard chess game. You can choose whether to play as a specific player (black/white), or have the player colour randomly assigned at the beginning of each episode. The numbers 1, 10 and 100 indicate the level of difficulty. Take a look at a few sample moves below to get an idea of roughly how well the bot plays for each level of difficulty. You can see that the 1% and 10% bots often make very obvious mistakes. See the original github repo for more info: https://github.com/peterosterlund2/droidfish. <details> <summary>Extras returned</summary> * `board`: - State of the board, representing pieces by indices. No piece - 0 - White pieces - 1: king, 2: queen, 3: rook, 4: bishop, 5: knight, 6: pawn - Black pieces - 7: king, 8: queen, 9: rook, 10: bishop, 11: knight, 12: pawn - Returned when the board changes. - Has `shape=[8, 8], dtype=INT32`. * `selection`: - Coordinate of selected piece (between 0-64, -1 if selection is removed) - Returned when a piece is selected (or unselected). - Has `shape=[1], dtype=INT32`. * `moved`: - Coordinates "from" and "to" cells when a piece is moved (between 0-64) - Returned when a piece is moved. - Has `shape=[2], dtype=INT32`. * `invalid`: - Coordinates "from" and "to" cells of an invalid move attempt (between 0-64) - Returned upon invalid move request - Has `shape=[2], dtype=INT32`. </details> **droidfish_black_1** | **droidfish_black_10** | **droidfish_black_100** ------------------------------------------------------------------ | -------------------------------------------------------------------- | ----------------------- ![Screenshot of 'droidfish_black_1'](images/droidfish_black_1.gif) | ![Screenshot of 'droidfish_black_10'](images/droidfish_black_10.gif) | ![Screenshot of 'droidfish_black_100'](images/droidfish_black_100.gif) **droidfish_white_1** | **droidfish_white_10** | **droidfish_white_100** ------------------------------------------------------------------ | -------------------------------------------------------------------- | ----------------------- ![Screenshot of 'droidfish_white_1'](images/droidfish_white_1.gif) | ![Screenshot of 'droidfish_white_10'](images/droidfish_white_10.gif) | ![Screenshot of 'droidfish_white_100'](images/droidfish_white_100.gif) **droidfish_random_1** | **droidfish_random_10** | **droidfish_random_100** -------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------------ ![Screenshot of 'droidfish_random_1'](images/droidfish_random_1.gif) | ![Screenshot of 'droidfish_random_10'](images/droidfish_random_10.gif) | ![Screenshot of 'droidfish_random_100'](images/droidfish_random_100.gif) ## FlappyDroid A clone of the well-known game Flappy Birds. <details> <summary>Extras returned</summary> Returns no extras. </details> **systemui_egg_land_default** | **systemui_egg_land_half_speed** ---------------------------------------------------------------------------------- | -------------------------------- ![Screenshot of 'systemui_egg_land_default'](images/systemui_egg_land_default.gif) | ![Screenshot of 'systemui_egg_land_half_speed'](images/systemui_egg_land_half_speed.gif) ## Frozen Bubble Shoot the coloured bubbles in a direction of your choice. Groups of bubbles with the same colour will drop. Remove all bubbles from the board before the time runs out. See the original github repo for more info: https://github.com/robinst/frozen-bubble-android.git. <details> <summary>Extras returned</summary> Returns no extras. </details> ![Screenshot of 'frozen_bubble'](images/frozen_bubble.gif) ## Memory Game Classic memory game. Find the pairs of images. See the original github repo for more info: https://github.com/sromku/memory-game/. <details> <summary>Extras returned</summary> * `flip`: - Index of the card flipped - Returned when a card is clicked. - Has `shape=[1], dtype=INT32`. * `cards`: - Number of cards still on the board. - Returned upon finding a pair. - Has `shape=[1], dtype=INT32`. * `remained`: - Number of cards remaining at the end of the episode. - Returned when an episode is over. - Has `shape=[1], dtype=INT32`. * `stars`: - Number of stars achieved at the end of the game. - Returned upon finishing the game. - Has `shape=[1], dtype=INT32`. * `achieved`: - Score obtained by the end of the episode. - Returned when an episode is over. - Has `shape=[1], dtype=INT32`. </details> **memory_game_animals_beginner** | **memory_game_animals_easy** | **memory_game_monsters_medium** ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------- ![Screenshot of 'memory_game_animals_beginner'](images/memory_game_animals_beginner.gif) | ![Screenshot of 'memory_game_animals_easy'](images/memory_game_animals_easy.gif) | ![Screenshot of 'memory_game_monsters_medium'](images/memory_game_monsters_medium.gif) **memory_game_monsters_hard** | **memory_game_emojis_hardest** | **memory_game_emojis_master** ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ----------------------------- ![Screenshot of 'memory_game_monsters_hard'](images/memory_game_monsters_hard.gif) | ![Screenshot of 'memory_game_emojis_hardest'](images/memory_game_emojis_hardest.gif) | ![Screenshot of 'memory_game_emojis_master'](images/memory_game_emojis_master.gif) ## Minesweeper This is an Android implementation of a popular game on Desktop in the 1990s. See the original github repo for more info: https://gitlab.com/ar-/apple-flinger. <details> <summary>Extras returned</summary> * `hidden`: - Number of hidden cells. - Returned whenever the board changes. - Has `shape=[1], dtype=INT32`. * `revealed`: - Number of revealed cells. - Returned whenever the board changes. - Has `shape=[1], dtype=INT32`. * `bombs`: - Number of bombs in the game. - Returned whenever the board changes. - Has `shape=[1], dtype=INT32`. * `click`: - Coordinates of the cell clicked (row, column). - Returned whenever the board changes. - Has `shape=[2], dtype=INT32`. * `grid`: - State of the board. - -1 = hidden, -2 = marked, 9 = bomb, 0-8 = number of nearby bombs - Returned whenever the board changes. - Has `shape=[grid_height, grid_width], dtype=INT32`. </details> **minesweeper_easy** | **minesweeper_medium** | **minesweeper_hard** ---------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------- ![Screenshot of 'minesweeper_easy'](images/minesweeper_easy.gif) | ![Screenshot of 'minesweeper_medium'](images/minesweeper_medium.gif) | ![Screenshot of 'minesweeper_hard'](images/minesweeper_hard.gif) ## Open Sudoku Classic Sudoku game with different levels of difficulty. The board is randomised over a set of 30 boards for each level. See the original github repo for more info: https://github.com/ogarcia/opensudoku. <details> <summary>Extras returned</summary> * `value`: - Number pressed (between 1-9, 0 if the "delete" button is pressed). - Returned upon clicking said button. - Has `shape=[1], dtype=INT32`. </details> **open_sudoku_easy** | **open_sudoku_medium** | **open_sudoku_hard** ---------------------------------------------------------------- | -------------------------------------------------------------------- | -------------------- ![Screenshot of 'open_sudoku_easy'](images/open_sudoku_easy.gif) | ![Screenshot of 'open_sudoku_medium'](images/open_sudoku_medium.gif) | ![Screenshot of 'open_sudoku_hard'](images/open_sudoku_hard.gif) ## Perfection Drag the items corresponding to the targets with the same shape. <details> <summary>Extras returned</summary> * `moving`: - The ID of the piece being dragged on the screen or 0. - Returned when its value changes. - Has `shape=[1], dtype=INT32`. * `todo`: - Number of pieces yet to be moved to a hole. - Returned when its value changes. - Has `shape=[1], dtype=INT32`. * `done`: - Number of pieces correctly moved to a hole. - Returned when its value changes. - Has `shape=[1], dtype=INT32`. </details> **perfection_1_circle_static** | **perfection_1_cube_static** | **perfection_1_plus_static** | **perfection_1_triangle_static** ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | -------------------------------- ![Screenshot of 'perfection_1_circle_static'](images/perfection_1_circle_static.gif) | ![Screenshot of 'perfection_1_square_static'](images/perfection_1_square_static.gif) | ![Screenshot of 'perfection_1_plus_static'](images/perfection_1_plus_static.gif) | ![Screenshot of 'perfection_1_triangle_static'](images/perfection_1_triangle_static.gif) **perfection_default** | **perfection_4_colors_square_static** | **perfection_4_pieces_static** -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------ ![Screenshot of 'perfection_default'](images/perfection_default.gif) | ![Screenshot of 'perfection_4_colors_square_static'](images/perfection_4_colors_square_static.gif) | ![Screenshot of 'perfection_4_pieces_static'](images/perfection_4_pieces_static.gif) ## Rocket Sleigh A Flappy Bird-like game where you have to collect christmas presents while avoiding trees. The sleigh is powered by a rocket that needs to recharge over time after you use up its fuel. <details> <summary>Extras returned</summary> Returns no extras. </details> ![Screenshot of 'rocket_sleigh_default'](images/rocket_sleigh.gif) ## Pong Classic Pong game. <details> <summary>Extras returned</summary> * `ball`: - The ball coordinates: [left, top, right, bottom]. - Returned when its value changes. - Has `shape=[4], dtype=INT32`. * `computer`: - The computer paddle coordinates: [left, top, right, bottom]. - Returned when its value changes. - Has `shape=[4], dtype=INT32`. * `human`: - The human paddle coordinates: [left, top, right, bottom]. - Returned when its value changes. - Has `shape=[4], dtype=INT32`. * `collision`: - Indicates collision of paddle and ball: (0=no collision, 1=collision). - Returned when its value changes. - Has `shape=[1], dtype=INT32`. * `state`: - The current state of the game: (0=pause, 1=ready, 2=running, 3=lose, 4=win). - Returned when its value changes. - Has `shape=[1], dtype=INT32`. </details> **pong_easy** | **pong_default** | **pong_hard** -------------------------------------------------- | -------------------------------------------------------- | ------------- ![Screenshot of 'pong_easy'](images/pong_easy.gif) | ![Screenshot of 'pong_default'](images/pong_default.gif) | ![Screenshot of 'pong_hard'](images/pong_hard.gif) ## SGT Puzzles - Blackbox There's an invisible laser beam originating from each of the cells at the edge of the grid. There are also a given number of balls inside the grid, hidden from the player whose aim is to guess where those balls are. The player can figure out where those balls might be by looking at how they *deflect* the laser beams. Clicking on an edge cell the player can reveal information about how that particular laser beam travels. Click on a cell; if the cell reveals an `H`, it means the straight laser beam leaving this cell hits a ball frontally. If the cell reveals a *number* along with another cell with the same number, that means the laser beam originating in the first cell ends up getting absorbed in the corresponding pair cell. If the cell reveals an `R`, that means the laser beam was *reflected*: either its origin and the cell it gets absorbed in is the *same*, or the beam gets bent before entering the grid. See the description below. The balls affect the travel of the laser beam in the following way: * If a laser beam hits it straight, it gets absorbed. This is denoted by the letter `H`. * If a laser beam hits *its corner*, the beam gets deflected by 90 degrees. * If a laser beam hits a balls corner right at the edge of the grid, i.e. before it enters the grid, it is considered *reflected*. * If a laser beam enters the same cell that it originally left, it is considered *reflected* too. Once the player has placed the given number of balls on the screen, a green dot appears that allows the player to check if their solution was correct. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `balls`: - The number of balls in the game arena. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `guesses`: - The number of guessed balls made by the agent. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `wrong`: - 1 if the guesses are wrong, 0 otherwise. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `lasers`: - The number of lasers in the grid - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `grid`: - Representation of the grid cells: - In the arena: `G`=guessed ball `' '`=empty - In the range: `[0-9]`=the number of lasers, `H`=beam hit, `R`=beam reflected, - `?` unknown, `' '` for the corners - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=STRING_U1`. </details> **blackbox_3x3_1_ball** | **blackbox_5x5_3_balls** | **blackbox_8x8_5_balls** | **blackbox_10x10_5_balls** --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------- ![Screenshot of 'blackbox_3x3_1_ball'](images/sgtpuzzles_blackbox_3x3_1_ball.gif) | ![Screenshot of 'blackbox_5x5_3_balls'](images/sgtpuzzles_blackbox_5x5_3_balls.gif) | ![Screenshot of 'blackbox_8x8_5_balls'](images/sgtpuzzles_blackbox_8x8_5_balls.gif) | ![Screenshot of 'blackbox_10x10_5_balls'](images/sgtpuzzles_blackbox_10x10_5_balls.gif) ## SGT Puzzles - Bridge Connect nodes on the board so that each number denotes the degree of the given vertex. Edges are not allowed to cross each other and the graph has to be connected. Edges have to be horizontal or vertical, and there can be at most two parallel bridges between any pair of nodes. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `islands`: - Number of nodes on the board. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `grid`: - Representation of the current state of the board. - `[0-9]=island, ' '=empty` - `'|'=vertical line, '"'=double vertical line, '!'=wrong vertical line` - `'-'=horizontal line, '='=double horizontal line, '~'=wrong horizontal line` - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=STRING_U1`. </details> **bridge_7x7_easy** | **bridge_7x7_medium** | **bridge_7x7_hard** | **bridge_10x10_medium** | **bridge_15x15_medium** ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- | ----------------------- ![Screenshot of 'sgtpuzzles_bridge_7x7_easy'](images/sgtpuzzles_bridge_7x7_easy.gif) | ![Screenshot of 'sgtpuzzles_bridge_7x7_medium'](images/sgtpuzzles_bridge_7x7_medium.gif) | ![Screenshot of 'sgtpuzzles_bridge_7x7_hard'](images/sgtpuzzles_bridge_7x7_hard.gif) | ![Screenshot of 'sgtpuzzles_bridge_10x10_medium'](images/sgtpuzzles_bridge_10x10_medium.gif) | ![Screenshot of 'sgtpuzzles_bridge_15x15_medium'](images/sgtpuzzles_bridge_15x15_medium.gif) ## SGT Puzzles - Cube There are six coloured squares that you have to collect with a moving cube. If the cube rolls on top of a coloured cell, the colour gets attached to that side of the cube; and if a coloured side of the cube rolls on an empty cell, the colour is removed from the cube. The goal is to have all six sides of the cube coloured. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `current`: - Index of the current grid cell the cube is on. - Returned whenever the cube moves. - Has `shape=[1], dtype=INT32`. * `previous`: - Index of the previous grid cell the cube was on. - Returned whenever the cube moves. - Has `shape=[1], dtype=INT32`. * `grid`: - The grid state (0 = dark, 1 = blue) - Returned whenever the cube moves. - Has `shape=[grid_size, grid_size], dtype=INT32`. * `face_count`: - The number of dark faces on the cube. - Returned whenever the cube moves. - Has `shape=[1], dtype=INT32`. * `face_colour_count`: - The number of blue faces on the cube. - Returned whenever the cube moves. - Has `shape=[1], dtype=INT32`. * `faces`: - The cube faces (0 = dark, 1 = blue) - Returned whenever the cube moves. - Has `shape=[6], dtype=INT32`. </details> **cube_c3x3** | **cube_c4x4** | **cube_c8x8** ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------- ![Screenshot of 'sgtpuzzles_cube_c3x3'](images/sgtpuzzles_cube_c3x3.gif) | ![Screenshot of 'sgtpuzzles_cube_c4x4'](images/sgtpuzzles_cube_c4x4.gif) | ![Screenshot of 'sgtpuzzles_cube_c8x8'](images/sgtpuzzles_cube_c8x8.gif) ## SGT Puzzles - Dominosa Place 2x1 size dominoes on the board such that the full board is covered, making sure that no two dominoes have the same pair of numbers on them. There needs to be exactly one of (0, 0), (0, 1) (0, 2), ... (1, 1), (1, 2) etc. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `numbers`: - Numbers as they appear in the grid. - Returned whenever the grid changes. - Has `shape=[height, width], dtype=INT32`. * `grid`: - Letters representing the dominoes currently placed on the board. - 'R=right, L=left, T=top, B=bottom' - Returned whenever the grid changes. - Has `shape=[height, with], dtype=INT32`. * `clash`: - Represents clashes on the board (i.e. if two dominoes have the same pair) - '1=clash, 0=no clash' - Returned whenever the grid changes. - Has `shape=[height, width], dtype=INT32`. </details> **dominosa_1** | **dominosa_3** | **dominosa_3a** | **dominosa_6** | **dominosa_9** -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------- ![Screenshot of 'sgtpuzzles_dominosa_1'](images/sgtpuzzles_dominosa_1.gif) | ![Screenshot of 'sgtpuzzles_dominosa_3'](images/sgtpuzzles_dominosa_3.gif) | ![Screenshot of 'sgtpuzzles_dominosa_3a'](images/sgtpuzzles_dominosa_3a.gif) | ![Screenshot of 'sgtpuzzles_dominosa_6'](images/sgtpuzzles_dominosa_6.gif) | ![Screenshot of 'sgtpuzzles_dominosa_9'](images/sgtpuzzles_dominosa_9.gif) ## SGT Puzzles - Fifteen Order the tiles in increasing order, starting from the top left corner. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `grid`: - Current state of the grid. - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=INT32`. * `empty`: - Index of the single empty cell in the grid. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `movecount`: - Number of moves made so far. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. </details> **fifteen_2x2** | **fifteen_3x3** | **fifteen_4x4** | **fifteen_6x6** ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | --------------- ![Screenshot of 'sgtpuzzles_fifteen_2x2'](images/sgtpuzzles_fifteen_2x2.gif) | ![Screenshot of 'sgtpuzzles_fifteen_3x3'](images/sgtpuzzles_fifteen_3x3.gif) | ![Screenshot of 'sgtpuzzles_fifteen_4x4'](images/sgtpuzzles_fifteen_4x4.gif) | ![Screenshot of 'sgtpuzzles_fifteen_6x6'](images/sgtpuzzles_fifteen_6x6.gif) ## SGT Puzzles - Flip Clicking on a cell will flip the colour of some of its neighbours, which are determined by the symbol in the cell. The goal is to make all the cells have the same colour. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `light`: - The number of light cells. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `dark`: - The number of dark cells - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `moves`: - The number of moves made by the player. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `grid`: - State of the board (0 = dark, 1 = light). - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=INT32`. * `gridMatrix`: - The grid matrix of square neighbours (-1 = outside, 1 = neighbour, 0 = not neighbour) - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size, 3, 3s], dtype=INT32`. </details> **flip_3x3c** | **flip_4x4c** | **flip_5x5r** ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------- ![Screenshot of 'sgtpuzzles_flip_3x3c'](images/sgtpuzzles_flip_3x3c.gif) | ![Screenshot of 'sgtpuzzles_flip_4x4c'](images/sgtpuzzles_flip_4x4c.gif) | ![Screenshot of 'sgtpuzzles_flip_5x5r'](images/sgtpuzzles_flip_5x5r.gif) ## SGT Puzzles - Flood FloodIt is a game where the player needs to fill the board with a single color. The dynamics of the game are driven by colored areas of the board, which when pressed cause the currently active region to change its color to the color of the pressed button. When this active region changes color it absorbs neighboring squares that have the same color, thus expanding the active region. The active region starts as a single square at the top-left corner of the board. The game gives a single reward at the end of the game if the player manages to fill the entire board with the same color within the maximum number steps, otherwise the reward is just zero. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `board`: - State of the board, representing colours by their indices. - 0: red, 1: yellow, 2: green, 3: blue, 4: orange, 5: purple, - 6: brown, 7: light blue, 8: light green, 9: pink - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=INT32`. </details> **sgtpuzzles_flood_3x3_easy** | **sgtpuzzles_flood_12x12_medium** | **sgtpuzzles_flood_16x16_hard** ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------- ![Screenshot of 'sgtpuzzles_flood_3x3_easy'](images/sgtpuzzles_flood_3x3_easy.gif) | ![Screenshot of 'sgtpuzzles_flood_12x12_medium'](images/sgtpuzzles_flood_12x12_medium.gif) | ![Screenshot of 'sgtpuzzles_flood_16x16_hard'](images/sgtpuzzles_flood_16x16_hard.gif) ## SGT Puzzles - Galaxies Split the grid up into centrally symmetric areas. The centre of symmetry for each area is denoted by a dot on the grid. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `dot`: - Number of dots on the board. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `grid`: - String representation of the board: - `o`=dot, `' '`=empty, `+`, `-`, `|` = cell corners. - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=STRING_U1`. </details> **galaxies_3x3_normal** | **galaxies_5x5_normal** | **galaxies_7x7_normal** --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ----------------------- ![Screenshot of 'galaxies_3x3_normal'](images/sgtpuzzles_galaxies_3x3_normal.gif) | ![Screenshot of 'galaxies_5x5_normal'](images/sgtpuzzles_galaxies_5x5_normal.gif) | ![Screenshot of 'galaxies_7x7_normal'](images/sgtpuzzles_galaxies_7x7_normal.gif) **galaxies_7x7_unreasonable** | **galaxies_10x10_normal** | **galaxies_15x15_normal** --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------- ![Screenshot of 'galaxies_7x7_normal'](images/sgtpuzzles_galaxies_7x7_normal.gif) | ![Screenshot of 'galaxies_10x10_normal'](images/sgtpuzzles_galaxies_10x10_normal.gif) | ![Screenshot of 'galaxies_15x15_normal'](images/sgtpuzzles_galaxies_15x15_normal.gif) ## SGT Puzzles - Guess The computer has thought of a sequence of colours that you have to guess. Fill the top row with colours of your choice, and wait for the computer to give you feedback about your sequence. It will show a black dot for each colour that is placed in the correct position, and a white dot for each that is present in the hidden sequence, but not at the position your guess. Try to figure out the hidden sequence before you run out of guesses! See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `peg`: - Indices representing the colours selected in the latest row. - Returned after the row is completed and evaluated. - Has `shape=[row_length], dtype=INT32`. * `feedback`: - Evaluation of the latest guess (0: incorrect, 1: correct place, 2: correct colour) - Returned after the row is completed and evaluated. - Has `shape=[row_length], dtype=INT32`. </details> **guess_basic** | **guess_quick** | **guess_standard** | **guess_super** ---------------------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------------------------------------- | --------------- ![Screenshot of 'sgtpuzzles_guess_basic'](images/sgtpuzzles_guess_basic.gif) | ![Screenshot of 'guess_quick'](images/sgtpuzzles_guess_quick.gif) | ![Screenshot of 'guess_standard'](images/sgtpuzzles_guess_standard.gif) | ![Screenshot of 'guess_super'](images/sgtpuzzles_guess_super.gif) ## SGT Puzzles - Inertia Collect all the blue diamonds on the board without colliding into a bomb. You can move the ball in the 8 main directions (including the diagonals). The ball will keep on moving in that direction until it hits a wall, a bomb, a diamond or a circle. Circles and diamonds have grip, i.e. it will stop the ball from continuing to move in the direction it was going towards. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `gems`: - Current number of gems still on the board. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `distancemoved`: - Number of cells just moved. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `grid`: - Symbols of grid cells (b=blank, g=gem, m=mine, s=stop, w=wall) - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=INT32`. </details> **inertia_5x5** | **inertia_10x10** ----------------------------------------------------------------- | ----------------- ![Screenshot of 'inertia_5x5'](images/sgtpuzzles_inertia_5x5.gif) | ![Screenshot of 'inertia_10x10'](images/sgtpuzzles_inertia_10x10.gif) ## SGT Puzzles - Light Up You have a grid of squares. Some are empty (black) and some are *walls* (grey); some of the walls are numbered. Your aim is to *light up* all the empty squares by placing light bulbs in some of them. The numbers denote how many bulbs' light hits these directly in a straight sight. Meanwhile, no two bulbs should light up each other (i.e. only one bulb allowed in straight sight). See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `grid`: - String representation of the board: - '#' = blocked, ' ' = empty/black, 'L' = light, 'l' = illuminated, - 'X' = impossible, 'number' = number of bulbs hitting this cell. - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=STRING_U1`. </details> **light_up_3x3_easy** | **light_up_5x5_easy** | **light_up_7x7_easy** | **light_up_10x10_tricky** | **light_up_14x14_easy** ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------- ![Screenshot of 'sgtpuzzles_light_up_3x3_easy'](images/sgtpuzzles_light_up_3x3_easy.gif) | ![Screenshot of 'sgtpuzzles_light_up_5x5_easy'](images/sgtpuzzles_light_up_5x5_easy.gif) | ![Screenshot of 'sgtpuzzles_light_up_7x7_easy'](images/sgtpuzzles_light_up_7x7_easy.gif) | ![Screenshot of 'light_up_10x10_tricky'](images/sgtpuzzles_light_up_10x10_tricky.gif) | ![Screenshot of 'sgtpuzzles_light_up_14x14_easy'](images/sgtpuzzles_light_up_14x14_easy.gif) ## SGT Puzzles - Loopy Draw a closed loop along the edges of the grid. A number in a cell denotes the number of edges adjacent to that cell. The loop cannot intersect itself. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `grid`: - String representation of the board: - The grid lines and cells: - `.` = dots (cell corners) - `0-9` = number on cell face or ` ` for empty face - `?` = unknown (default),`x` = no line,`-` = `|` = line,`~` = `/` = error - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=STRING_U1`. </details> **loopy_3x3_easy** | **loopy_5x5_easy** | **loopy_7x7_easy** | **loopy_7x7_normal** | **loopy_7x7_hard** ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------ ![Screenshot of 'sgtpuzzles_loopy_3x3_easy'](images/sgtpuzzles_loopy_3x3_easy.gif) | ![Screenshot of 'sgtpuzzles_loopy_5x5_easy'](images/sgtpuzzles_loopy_5x5_easy.gif) | ![Screenshot of 'sgtpuzzles_loopy_7x7_easy'](images/sgtpuzzles_loopy_7x7_easy.gif) | ![Screenshot of 'sgtpuzzles_loopy_7x7_normal'](images/sgtpuzzles_loopy_7x7_normal.gif) | ![Screenshot of 'sgtpuzzles_loopy_7x7_hard'](images/sgtpuzzles_loopy_7x7_hard.gif) ## SGT Puzzles - Net There are a number of light bulbs, wires and a single light source in the middle. Connect the wires such that all bulbs are lit up, without loose ends or loops in the wiring. You can rotate the tiles by clicking on them. If the task name has a *w* suffix in it then it is allowed to connect wires on opposing edges of the grid. See the original github repo for more info: https://github.com/chrisboyle/sgtpuzzles. <details> <summary>Extras returned</summary> * `active`: - The number of active/completed cells. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `total`: - The total number of cells - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `grid`: - The grid cells represented by numbers. - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=INT32`. * `gridCompleted`: - The grid cells' active/completed status (0 = false, 1 = true). - Returned whenever the grid changes. - Has `shape=[grid_size, grid_size], dtype=INT32`. </details> **net_3x3** | **net_5x5** | **net_7x7w** | **net_9x9** | **net_11x11w** -------------------------------------------------------------------- | -------------------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------- | -------------- ![Screenshot of 'sgtpuzzles_net_3x3'](images/sgtpuzzles_net_3x3.gif) | ![Screenshot of 'sgtpuzzles_net_5x5'](images/sgtpuzzles_net_5x5.gif) | ![Screenshot of 'sgtpuzzles_net_7x7w'](images/sgtpuzzles_net_7x7w.gif) | ![Screenshot of 'sgtpuzzles_net_9x9'](images/sgtpuzzles_net_9x9.gif) | ![Screenshot of 'sgtpuzzles_net_11x11w'](images/sgtpuzzles_net_11x11w.gif) ## Shattered Pixel Dungeon Shattered Pixel Dungeon is a Roguelike RPG, with pixel art graphics and lots of variety and replayability. Every game is unique, with four different playable characters, randomized levels and enemies, and over 150 items to collect and use. The game is simple to get into, but has lots of depth. Strategy is required if you want to win! See the original github repo for more info: https://github.com/00-Evan/shattered-pixel-dungeon.git. <details> <summary>Extras returned</summary> Returns no extras. </details> huntress | mage | rogue | warrior ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------- ![Screenshot of 'shattered_pixel_dungeon_huntress'](images/shattered_pixel_dungeon_huntress.gif) | ![Screenshot of 'shattered_pixel_dungeon_mage'](images/shattered_pixel_dungeon_mage.gif) | ![Screenshot of 'shattered_pixel_dungeon_rogue'](images/shattered_pixel_dungeon_rogue.gif) | ![Screenshot of 'shattered_pixel_dungeon_warrior'](images/shattered_pixel_dungeon_warrior.gif) ## Simple Solitaire This is an Android implementation of [Solitaire](https://en.wikipedia.org/wiki/Solitaire) card games. We currently support 19 variants listed here in alphabetical order. Note that the full task_IDs take the form `simple_solitaire_aces_up`, `simple_solitaire_calculation` etc. See the original github repo for more info: https://github.com/TobiasBielefeld/Simple-Solitaire.git. <details> <summary>Extras returned</summary> * `card`: - The new visible card `[kind, suit]`: - kind: `a=ace, k=king, q=queen, j=jack, x=10, 2-9=digit`. - suit: `c=clubs, d=diamonds, h=hearts, s=spades`. - Returned when a card is moved. - Has `shape=[2], dtype=STRING_U1`. * `stack_i`: - A non-empty stack of visible cards `[kind, suit]`. - `i` different extras (`stack_0`, `stack_1`, `...`), one corresponding to each stack. - Returned when a card is moved. - Has `shape=[52, 2], dtype=STRING_U1`. </details> **aces_up** | **calculation** | **canfield** | **forty_eight** | **freecell** -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------ ![Screenshot of 'simple_solitaire_aces_up'](images/simple_solitaire_aces_up.gif) | ![Screenshot of 'simple_solitaire_calculation'](images/simple_solitaire_calculation.gif) | ![Screenshot of 'simple_solitaire_canfield'](images/simple_solitaire_canfield.gif) | ![Screenshot of 'simple_solitaire_forty_eight'](images/simple_solitaire_forty_eight.gif) | ![Screenshot of 'simple_solitaire_freecell'](images/simple_solitaire_freecell.gif) **golf** | **grandfathers_clock** | **gypsy** | **klondike** | **maze** -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | -------- ![Screenshot of 'simple_solitaire_golf'](images/simple_solitaire_golf.gif) | ![Screenshot of 'simple_solitaire_grandfathers_clock'](images/simple_solitaire_grandfathers_clock.gif) | ![Screenshot of 'simple_solitaire_gypsy'](images/simple_solitaire_gypsy.gif) | ![Screenshot of 'simple_solitaire_klondike'](images/simple_solitaire_klondike.gif) | ![Screenshot of 'simple_solitaire_maze'](images/simple_solitaire_maze.gif) **mod3** | **napoleons_tomb** | **pyramid** | **simple_simon** | **spider** -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ---------- ![Screenshot of 'simple_solitaire_mod3'](images/simple_solitaire_mod3.gif) | ![Screenshot of 'simple_solitaire_napoleons_tomb'](images/simple_solitaire_napoleons_tomb.gif) | ![Screenshot of 'simple_solitaire_pyramid'](images/simple_solitaire_pyramid.gif) | ![Screenshot of 'simple_solitaire_simple_simon'](images/simple_solitaire_simple_simon.gif) | ![Screenshot of 'simple_solitaire_spider'](images/simple_solitaire_spider.gif) **spiderette** | **tri_peaks** | **vegas** | **yukon** -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------- | --------- ![Screenshot of 'simple_solitaire_spiderette'](images/simple_solitaire_spiderette.gif) | ![Screenshot of 'simple_solitaire_tri_peaks'](images/simple_solitaire_tri_peaks.gif) | ![Screenshot of 'simple_solitaire_vegas'](images/simple_solitaire_vegas.gif) | ![Screenshot of 'simple_solitaire_yukon'](images/simple_solitaire_yukon.gif) ## Snake Classic Snake game. <details> <summary>Extras returned</summary> * `move`: - The desired direction of movement: `0`=left, `1`=up, `2`=down, `3`=right. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `direction`: - The direction of the snake: `1`=north, `2`=south, `3`=east, `4`=west. - Returned whenever the grid changes. - Has `shape=[1], dtype=INT32`. * `grid`: - The grid cells: `x`=border, `' '`=empty, `s`=snake, `a`=apple. - Returned whenever the grid changes. - Has `shape=[13, 19], dtype=STRING_U1`. </details> ![Screenshot of 'aosp_samples_snake_default'](images/aosp_samples_snake_default.gif) ## Vector Pinball A simple vector-based Pinball game with realistic physics. See the original github repo for more info: https://github.com/dozingcat/Vector-Pinball. <details> <summary>Extras returned</summary> Returns no extras. </details> **vector_pinball_table_1** | **vector_pinball_table_2** | **vector_pinball_table_3** ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------- ![Screenshot of 'vector_pinball_table_1'](images/vector_pinball_table_1.gif) | ![Screenshot of 'vector_pinball_table_2'](images/vector_pinball_table_2.gif) | ![Screenshot of 'vector_pinball_table_3'](images/vector_pinball_table_3.gif) **vector_pinball_table_4** | **vector_pinball_table_5** ---------------------------------------------------------------------------- | -------------------------- ![Screenshot of 'vector_pinball_table_4'](images/vector_pinball_table_4.gif) | ![Screenshot of 'vector_pinball_table_5'](images/vector_pinball_table_5.gif) <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.setup_step_interpreter.""" from absl.testing import absltest from android_env.components import adb_controller from android_env.components import errors from android_env.components import logcat_thread from android_env.components import setup_step_interpreter from android_env.proto import task_pb2 import mock from google.protobuf import text_format def _to_proto(proto_class, text): proto = proto_class() text_format.Parse(text, proto) return proto class SetupStepInterpreterTest(absltest.TestCase): def setUp(self): super().setUp() self.logcat = mock.create_autospec(logcat_thread.LogcatThread) self.adb_controller = mock.create_autospec(adb_controller.AdbController) def test_empty_setup_steps(self): """Simple test where nothing should break, and nothing should be done. The test simply expects this test to not crash. """ interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([]) def test_none_setup_steps(self): """Simple test where nothing should break, and nothing should be done. The test simply expects this test to not crash. """ interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) # Empty setup steps should be ignored. interpreter.interpret([None]) def test_invalid_setup_step(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) # Empty setup steps should be ignored. with self.assertRaises(AssertionError): interpreter.interpret([_to_proto(task_pb2.SetupStep, '')]) def test_adb_install_apk_filesystem(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ adb_call: { install_apk: { filesystem: { path: "/my/favorite/dir/my_apk.apk" } } }""") ]) self.adb_controller.install_apk.assert_called_once_with( '/my/favorite/dir/my_apk.apk') def test_adb_force_stop(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ adb_call: { force_stop: { package_name: "my.app.Activity" } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.force_stop.assert_called_once_with('my.app.Activity') def test_adb_clear_cache(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ adb_call: { clear_cache: { package_name: "my.app.Activity" } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.clear_cache.assert_called_once_with('my.app.Activity') def test_adb_grant_permissions(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ adb_call: { grant_permissions: { package_name: "my.app.Activity" permissions: [ "my.namespace.READ_DATA", "another.namespace.WRITE" ] } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.grant_permissions.assert_called_once_with( 'my.app.Activity', ['my.namespace.READ_DATA', 'another.namespace.WRITE']) def test_adb_start_activity(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ adb_call: { start_activity: { full_activity: "my.app.Activity" extra_args: "arg1" extra_args: "arg2" } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.start_activity.assert_called_once_with( 'my.app.Activity', ['arg1', 'arg2']) def test_adb_single_tap(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto(task_pb2.SetupStep, """ adb_call: { tap: { x: 321 y: 654 } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.input_tap.assert_called_once_with(321, 654) def test_adb_rotate(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) # Check landscape. interpreter.interpret([ _to_proto(task_pb2.SetupStep, """ adb_call: { rotate: { orientation: LANDSCAPE_90 } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.rotate_device.assert_called_once_with( task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_90) self.adb_controller.reset_mock() # Check portrait. interpreter.interpret([ _to_proto(task_pb2.SetupStep, """ adb_call: { rotate: { orientation: PORTRAIT_0 } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.rotate_device.assert_called_once_with( task_pb2.AdbCall.Rotate.Orientation.PORTRAIT_0) self.adb_controller.reset_mock() # Check landscape inverted. interpreter.interpret([ _to_proto(task_pb2.SetupStep, """ adb_call: { rotate: { orientation: LANDSCAPE_270} }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.rotate_device.assert_called_once_with( task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_270) self.adb_controller.reset_mock() # Check portrait up-side-down. interpreter.interpret([ _to_proto(task_pb2.SetupStep, """ adb_call: { rotate: { orientation: PORTRAIT_180 } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.rotate_device.assert_called_once_with( task_pb2.AdbCall.Rotate.Orientation.PORTRAIT_180) def test_adb_press_button(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto(task_pb2.SetupStep, """ adb_call: { press_button: { button: HOME } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.input_key.assert_called_once_with('KEYCODE_HOME') self.adb_controller.reset_mock() interpreter.interpret([ _to_proto(task_pb2.SetupStep, """ adb_call: { press_button: { button: BACK } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.input_key.assert_called_once_with('KEYCODE_BACK') def test_adb_start_accessibility_service(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ adb_call: { start_accessibility_service: { full_service: "my.app.AccessibilityService" } }""") ]) # AdbController should be called exactly once with the following arguments. self.adb_controller.start_accessibility_service.assert_called_once_with( 'my.app.AccessibilityService') def test_adb_start_screen_pinning(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ adb_call: { start_screen_pinning: { full_activity: "my.app.HighlanderApp" # "There can be only one". } }""") ]) # AdbController should be called once with the following arguments. self.adb_controller.start_screen_pinning.assert_called_with( u'my.app.HighlanderApp') @mock.patch('time.sleep') def test_time_sleep(self, mock_sleep): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret( [_to_proto(task_pb2.SetupStep, """sleep: { time_sec: 0.875 }""")]) assert mock_sleep.call_count == 2 mock_sleep.assert_has_calls([mock.call(0.875), mock.call(0.5)]) @mock.patch('time.sleep') def test_wait_for_app_screen_empty_activity(self, unused_mock_sleep): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) with self.assertRaises(errors.StepCommandError): interpreter.interpret([ _to_proto(task_pb2.SetupStep, """success_condition: {wait_for_app_screen: { }}""") ]) def test_wait_for_message_fail(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) self.assertRaises(errors.StepCommandError, interpreter.interpret, [ _to_proto( task_pb2.SetupStep, """ success_condition: { wait_for_message: { message:'foo' timeout_sec: 0.0001 } } """) ]) def test_wait_for_message_success(self): interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) # Replace `LogcatThread.add_event_listener` with one that simply calls `fn` # right away, ignoring `event`. def mock_add_ev_listener(event_listener): event_listener.handler_fn('some_event', 'some_match') self.logcat.add_event_listener.side_effect = mock_add_ev_listener # The test checks that this command raises no AssertionError. interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ success_condition: { wait_for_message: { message:'foo' timeout_sec: 1.0 } } """) ]) @mock.patch('time.sleep') def test_check_install_not_installed(self, unused_mock_sleep): self.adb_controller.is_package_installed.return_value = False interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) with self.assertRaises(errors.StepCommandError): interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ success_condition: { check_install: { package_name: "faz" timeout_sec: 0.0001 } } """) ]) def test_check_install_installed(self): self.adb_controller.is_package_installed.return_value = True interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) # The test checks that this command raises no AssertionError. interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ success_condition: { check_install: { package_name: "baz" timeout_sec: 0.0001 } }""") ]) self.adb_controller.is_package_installed.assert_called_once_with('baz') def test_num_retries_failure(self): self.adb_controller.is_package_installed.side_effect = [False] * 3 interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) with self.assertRaises(errors.StepCommandError): interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ success_condition: { check_install: { package_name: "faz" timeout_sec: 0.0001 } num_retries: 3 }""") ]) # We retried 3 times after the first call, so we expect 3+1 calls. self.assertEqual(3, self.adb_controller.is_package_installed.call_count) @mock.patch('time.sleep') def test_num_retries_success(self, unused_mock_sleep): self.adb_controller.is_package_installed.side_effect = [ False, False, True, False ] interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ success_condition: { check_install: { package_name: "bar" timeout_sec: 0.0001 } num_retries: 5 }""") ]) # The check should succeed on the third try. self.assertEqual(3, self.adb_controller.is_package_installed.call_count) def test_retry_step(self): self.adb_controller.is_package_installed.side_effect = [False, True] interpreter = setup_step_interpreter.SetupStepInterpreter( adb_controller=self.adb_controller, logcat=self.logcat) interpreter.interpret([ _to_proto( task_pb2.SetupStep, """ adb_call: { press_button: { button: HOME } } success_condition: { check_install: { package_name: "bar" timeout_sec: 0.0001 } num_retries: 2 }""") ]) # We expect the check to fail twice and succeed on the third pass. self.adb_controller.input_key.assert_has_calls( [mock.call('KEYCODE_HOME')] * 2) self.assertEqual(2, self.adb_controller.is_package_installed.call_count) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Converts pixel observation to from int to float32 between 0.0 and 1.0.""" from typing import Dict from android_env.components import utils from android_env.wrappers import base_wrapper import dm_env from dm_env import specs import numpy as np class FloatPixelsWrapper(base_wrapper.BaseWrapper): """Wraps AndroidEnv for Panultimate agent.""" def __init__(self, env: dm_env.Environment): super().__init__(env) self._should_convert_int_to_float = np.issubdtype( self._env.observation_spec()['pixels'].dtype, np.integer) def _process_observation( self, observation: Dict[str, np.ndarray] ) -> Dict[str, np.ndarray]: if self._should_convert_int_to_float: float_pixels = utils.convert_int_to_float( observation['pixels'], self._env.observation_spec()['pixels'], np.float32) observation['pixels'] = float_pixels return observation def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep: step_type, reward, discount, observation = timestep return dm_env.TimeStep( step_type=step_type, reward=reward, discount=discount, observation=self._process_observation(observation)) def reset(self) -> dm_env.TimeStep: timestep = self._env.reset() return self._process_timestep(timestep) def step(self, action: Dict[str, np.ndarray]) -> dm_env.TimeStep: timestep = self._env.step(action) return self._process_timestep(timestep) def observation_spec(self) -> Dict[str, specs.Array]: if self._should_convert_int_to_float: observation_spec = self._env.observation_spec() observation_spec['pixels'] = specs.BoundedArray( shape=self._env.observation_spec()['pixels'].shape, dtype=np.float32, minimum=0.0, maximum=1.0, name=self._env.observation_spec()['pixels'].name) return observation_spec return self._env.observation_spec() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Wraps the AndroidEnv environment to make its interface flat.""" from typing import Union, Dict, Any from android_env.wrappers import base_wrapper import dm_env from dm_env import specs import numpy as np RGB_CHANNELS = (0, 1, 2) def _extract_screen_pixels(obs: np.ndarray): """Get only screen pixels by removing previous action layer.""" is_grayscale_image = obs.shape[-1] == 2 if is_grayscale_image: return np.expand_dims(obs[..., 0], -1) return obs[..., RGB_CHANNELS] def _get_no_action_observation_spec(obs_spec: specs.BoundedArray): """Create an observation spec without the action layer.""" shape = np.array(obs_spec.shape) shape[2] -= 1 minimum = obs_spec.minimum maximum = obs_spec.maximum is_scalar = lambda x: np.isscalar(x) or np.ndim(x) == 0 if not is_scalar(minimum): minimum = _extract_screen_pixels(minimum) if not is_scalar(maximum): maximum = _extract_screen_pixels(maximum) return obs_spec.replace(shape=shape, minimum=minimum, maximum=maximum) class FlatInterfaceWrapper(base_wrapper.BaseWrapper): """Simple interface for AndroidEnv. Removes the structure from observations and actions, keeping only the pixel observations. Also exposes action as an int32 scalar, making it easier to use with conventional discrete agents. This wrapper expects a discretized action space. """ def __init__(self, env: dm_env.Environment, flat_actions: bool = True, flat_observations: bool = True, keep_action_layer: bool = True): super().__init__(env) self._flat_actions = flat_actions self._flat_observations = flat_observations self._keep_action_layer = keep_action_layer self._action_name = list(self._env.action_spec())[0] self._assert_base_env() def _assert_base_env(self): base_action_spec = self._env.action_spec() assert len(base_action_spec) == 1, self._env.action_spec() assert isinstance(base_action_spec, dict) assert isinstance(base_action_spec[self._action_name], specs.BoundedArray) def _process_action(self, action: Union[int, np.ndarray, Dict[str, Any]]): if self._flat_actions: return {self._action_name: action} else: return action def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep: if self._flat_observations: step_type, reward, discount, observation = timestep # Keep only the pixels. pixels = observation['pixels'] pixels = pixels if self._keep_action_layer else _extract_screen_pixels( pixels) return dm_env.TimeStep( step_type=step_type, reward=reward, discount=discount, observation=pixels) else: return timestep def reset(self) -> dm_env.TimeStep: timestep = self._env.reset() return self._process_timestep(timestep) def step(self, action: int) -> dm_env.TimeStep: timestep = self._env.step(self._process_action(action)) return self._process_timestep(timestep) def observation_spec(self) -> specs.Array: if self._flat_observations: pixels_spec = self._env.observation_spec()['pixels'] if not self._keep_action_layer: return _get_no_action_observation_spec(pixels_spec) return pixels_spec else: return self._env.observation_spec() def action_spec(self) -> specs.Array: if self._flat_actions: return self._env.action_spec()[self._action_name] else: return self._env.action_spec() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A class the launches a thread to read Android logcat outputs.""" import re import subprocess import threading # `typing.Pattern` has been deprecated in Python 3.9 in favor of `re.Pattern`, # but it is not available even in slightly older Python versions. # Please see https://www.python.org/dev/peps/pep-0585/ from typing import Callable, List, Match, NamedTuple, Optional, Pattern from absl import logging from android_env.components import thread_function from android_env.proto import task_pb2 class EventListener(NamedTuple): regexp: Pattern[str] handler_fn: Callable[[Pattern[str], Match[str]], None] class LogcatThread(thread_function.ThreadFunction): """Reads ADB logcat entries in a separate thread.""" def __init__( self, adb_command_prefix: List[str], log_parsing_config: task_pb2.LogParsingConfig, print_all_lines: bool = False, name: str = 'logcat', ): """Initializes this LogcatThread with optional filters. Please see https://developer.android.com/studio/command-line/logcat for more info on `logcat`. Args: adb_command_prefix: Command for connecting to a particular ADB. log_parsing_config: Determines the types of messages we want logcat to match. Contains `filters` and `log_regexps`. print_all_lines: Whether to print all lines we observe in the logcat stream. This is useful to debug problems in Android itself. name: Name of the thread. """ self._print_all_lines = print_all_lines self._regexps = log_parsing_config.log_regexps self._listeners = {} self._desired_event = None self._thread_event = threading.Event() self._max_buffer_size = 100 filters = list(log_parsing_config.filters) + ['*:S'] cmd = adb_command_prefix + ['logcat', '-v', 'epoch'] + filters logging.info('Logcat command: %s', ' '.join(cmd)) self._proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, universal_newlines=True) self._stdout = self._proc.stdout super().__init__(block_input=True, block_output=False, name=name) def add_event_listener(self, event_listener: EventListener) -> None: """Adds `fn` to the list of handlers to call when `event` occurs.""" event_regexp = event_listener.regexp if event_regexp not in self._listeners: self._listeners[event_regexp] = [] self._listeners[event_regexp].append(event_listener.handler_fn) def remove_event_listener(self, event_listener: EventListener) -> None: """Removes `fn` from the list of handlers to call when `event` occurs.""" event_regexp = event_listener.regexp if event_regexp not in self._listeners: logging.error('Event: %r is not registered.', event_regexp) return self._listeners[event_regexp].remove(event_listener.handler_fn) def wait(self, event: Optional[Pattern[str]] = None, timeout_sec: Optional[float] = None) -> None: """Blocks (caller) execution for up to `timeout_sec` until `event` is fired. Args: event: Event to wait for. If None, any new event will cause this function to return. timeout_sec: Maximum time to block waiting for an event. """ self._desired_event = event self._thread_event.wait(timeout=timeout_sec) self._thread_event.clear() def kill(self): self._proc.kill() super().kill() def main(self) -> None: # pylint: disable=g-line-too-long # Format is: "TIME_SEC PID TID PRIORITY TAG: MESSAGE" # # Example: # ' 1553110400.424 5583 5658 D NostalgicRacer: com.google.example.games.nostalgicracer.views.renderers.OpenGLRenderDriver@912fb8.onSurfaceChanged 480x320' # # # If a log_prefix is given, then the format becomes: # "TIME_SEC PID TID PRIORITY TAG: LOG_PREFIX MESSAGE" # pylint: enable=g-line-too-long regexp = r""" ^ # Beginning of the line. [ ]+(?P<timestamp>[0-9]+\.[0-9]+) # Spaces and a float. [ ]+(?P<pid>[0-9]+) # Spaces and an int. [ ]+(?P<tid>[0-9]+) # Spaces and an int. [ ]+(?P<priority>.) # Spaces and any single character. [ ]+(?P<tag>[^:]*): # Spaces and any char that's not ':'. """ regexp += r"""[ ](?P<message>.*)$""" logline_re = re.compile(regexp, re.VERBOSE) for line in self._stdout: # We never hand back control to ThreadFunction._run() so we need to # explicitly check for self._should_run here. if not self._should_run: break if self._print_all_lines: logging.info('line: %r', line) if not line: # Skip empty lines. continue # We're currently only consuming `message`, but we may use the other # fields in the future. matches = logline_re.match(line) if not matches or len(matches.groups()) != 6: continue content = matches.group('message') for ev, listeners in self._listeners.items(): ev_matches = ev.match(content) if ev_matches: # Unblock consumers that may be waiting for events. if not self._thread_event.is_set(): if self._desired_event: if self._desired_event == ev: self._thread_event.set() else: self._thread_event.set() # Notify listeners. for listener in listeners: listener(ev, ev_matches) <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.emulator_simulator.""" from absl.testing import absltest from android_env.components import action_type from android_env.components import adb_controller from android_env.components import emulator_launcher from android_env.components import emulator_simulator from android_env.proto import emulator_controller_pb2 from android_env.proto import emulator_controller_pb2_grpc import grpc import mock import numpy as np from PIL import Image class EmulatorSimulatorTest(absltest.TestCase): def setUp(self): super().setUp() self.addCleanup(mock.patch.stopall) # Disable previous patches. self._adb_controller = mock.create_autospec(adb_controller.AdbController) self._launcher = mock.create_autospec(emulator_launcher.EmulatorLauncher) self._emulator_stub = mock.create_autospec( emulator_controller_pb2_grpc.EmulatorControllerStub) self._grpc_channel = mock.create_autospec(grpc.Channel) mock.patch.object( adb_controller, 'AdbController', return_value=self._adb_controller).start() mock.patch.object( emulator_launcher, 'EmulatorLauncher', return_value=self._launcher).start() @mock.patch('grpc.aio.insecure_channel') @mock.patch('grpc.insecure_channel') def test_adb_device_name_not_empty(self, aio_channel, channel): tmp_dir = absltest.get_default_test_tmpdir() aio_channel.return_value = self._grpc_channel channel.return_value = self._grpc_channel simulator = emulator_simulator.EmulatorSimulator( emulator_launcher_args={'grpc_port': 1234}, emulator_console_args={}, adb_path='/my/adb', adb_server_port=5037, tmp_dir=tmp_dir, prompt_regex='awesome>') self.assertNotEmpty(simulator.adb_device_name()) @mock.patch('grpc.aio.insecure_channel') @mock.patch('grpc.insecure_channel') def test_close(self, aio_channel, channel): tmp_dir = absltest.get_default_test_tmpdir() aio_channel.return_value = self._grpc_channel channel.return_value = self._grpc_channel simulator = emulator_simulator.EmulatorSimulator( emulator_launcher_args={'grpc_port': 1234}, emulator_console_args={}, adb_path='/my/adb', adb_server_port=5037, tmp_dir=tmp_dir, prompt_regex='awesome>') # The simulator should launch and not crash. self._adb_controller.get_screen_dimensions.return_value = (1234, 5678) simulator.launch() # For whatever reason clients may want to close the EmulatorSimulator. # We just want to check that the simulator does not crash and/or leak # resources. simulator.close() @mock.patch('grpc.aio.insecure_channel') @mock.patch('grpc.insecure_channel') def test_restart(self, aio_channel, channel): tmp_dir = absltest.get_default_test_tmpdir() aio_channel.return_value = self._grpc_channel channel.return_value = self._grpc_channel simulator = emulator_simulator.EmulatorSimulator( emulator_launcher_args={'grpc_port': 1234}, emulator_console_args={}, adb_path='/my/adb', adb_server_port=5037, tmp_dir=tmp_dir, prompt_regex='awesome>') # The simulator should launch and not crash. self._adb_controller.get_screen_dimensions.return_value = (1234, 5678) simulator.launch() # For whatever reason clients may want to restart the EmulatorSimulator. simulator.restart() @mock.patch('grpc.aio.insecure_channel') @mock.patch('grpc.insecure_channel') def test_get_observation(self, aio_channel, channel): tmp_dir = absltest.get_default_test_tmpdir() aio_channel.return_value = self._grpc_channel channel.return_value = self._grpc_channel simulator = emulator_simulator.EmulatorSimulator( emulator_launcher_args={'grpc_port': 1234}, emulator_console_args={}, adb_path='/my/adb', adb_server_port=5037, tmp_dir=tmp_dir, prompt_regex='awesome>') # The simulator should launch and not crash. self._adb_controller.get_screen_dimensions.return_value = (1234, 5678) simulator.launch() simulator._emulator_stub.getScreenshot = mock.MagicMock( return_value=emulator_controller_pb2.Image( format=emulator_controller_pb2.ImageFormat(width=5678, height=1234), image=Image.new('RGB', (1234, 5678)).tobytes(), timestampUs=123)) observation = simulator.get_observation() # The observation should have three components: # - an image # - the timedelta # - the orientation. self.assertLen(observation, 3) # The first element (the "image") should have the same screen dimensions as # reported by ADB and it should have 3 channels (RGB). self.assertEqual(observation['pixels'].shape, (1234, 5678, 3)) self.assertEqual(observation['timedelta'], 123) @mock.patch('grpc.aio.insecure_channel') @mock.patch('grpc.insecure_channel') def test_send_action(self, aio_channel, channel): tmp_dir = absltest.get_default_test_tmpdir() aio_channel.return_value = self._grpc_channel channel.return_value = self._grpc_channel simulator = emulator_simulator.EmulatorSimulator( emulator_launcher_args={'grpc_port': 1234}, emulator_console_args={}, adb_path='/my/adb', adb_server_port=5037, tmp_dir=tmp_dir, prompt_regex='awesome>') # The simulator should launch and not crash. self._adb_controller.get_screen_dimensions.return_value = (5000, 1000) simulator.launch() simulator._emulator_stub.sendTouch = mock.MagicMock(return_value=None) simulator.send_action( {'action_type': np.array([action_type.ActionType.TOUCH]), 'touch_position': np.array([0.25, 0.75])}) simulator.send_action( {'action_type': np.array([action_type.ActionType.TOUCH]), 'touch_position': np.array([0.75, 0.50])}) simulator.send_action( {'action_type': np.array([action_type.ActionType.LIFT]), 'touch_position': np.array([0.66, 0.33])}) # We expect EmulatorSimulator to send the following calls: # 1st call: # x-coordinate: 10000 * 0.25 = 250 # y-coordinate: 50000 * 0.75 = 3750 # down: True # It's a touch command. # 2nd call: # x-coordinate: 10000 * 0.75 = 750 # y-coordinate: 50000 * 0.50 = 2500 # down: True # It's a touch command. # 3rd call: # x-coordinate: 0 # y-coordinate: 0 # down: False # It's a lift command. if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Wraps the AndroidEnv environment to provide tap actions of a given duration.""" from typing import Dict, Sequence from android_env.components import action_type from android_env.wrappers import base_wrapper import dm_env import numpy as np ActionType = action_type.ActionType class TapActionWrapper(base_wrapper.BaseWrapper): """AndroidEnv with tap actions.""" def __init__(self, env: dm_env.Environment, num_frames: int = 5, touch_only: bool = False): super().__init__(env) assert 'action_type' in env.action_spec() self._touch_only = touch_only self._num_frames = num_frames self._env_steps = 0 def android_logs(self): """Returns a dictionary of metrics logged by the environment.""" logs = self._env.android_logs() logs.update({'env_steps': self._env_steps}) return logs def _process_action( self, action: Dict[str, np.ndarray] ) -> Sequence[Dict[str, np.ndarray]]: if self._touch_only: assert action['action_type'] == 0 touch_action = action.copy() touch_action['action_type'] = np.array(ActionType.TOUCH).astype( self.action_spec()['action_type'].dtype) actions = [touch_action] * self._num_frames lift_action = action.copy() lift_action['action_type'] = np.array(ActionType.LIFT).astype( self.action_spec()['action_type'].dtype) actions.append(lift_action) else: if action['action_type'] == ActionType.TOUCH: actions = [action] * self._num_frames lift_action = action.copy() lift_action['action_type'] = np.array(ActionType.LIFT).astype( self.action_spec()['action_type'].dtype) actions.append(lift_action) else: actions = [action] * (self._num_frames + 1) return actions def step(self, action: Dict[str, np.ndarray]) -> dm_env.TimeStep: """Takes a step in the environment.""" self._env_steps += self._num_frames + 1 actions = self._process_action(action) total_reward = 0 for idx in range(len(actions)): step_type, reward, discount, observation = self._env.step(actions[idx]) if reward: total_reward += reward if step_type == dm_env.StepType.LAST: return dm_env.TimeStep( step_type=step_type, reward=total_reward, discount=discount, observation=observation) return dm_env.TimeStep( step_type=step_type, reward=total_reward, discount=discount, observation=observation) def action_spec(self) -> Dict[str, dm_env.specs.Array]: if self._touch_only: return { 'action_type': dm_env.specs.DiscreteArray(num_values=1, name='action_type'), 'touch_position': self._env.action_spec()['touch_position'], } else: return self._env.action_spec() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Determines if the current app screen matches an expected app screen.""" import enum import re from typing import Callable, List, Optional, Sequence, Pattern from absl import logging from android_env.components import adb_controller as adb_control from android_env.proto import task_pb2 class DumpsysNode(): """A node in a dumpsys tree.""" def __init__(self, data: Optional[str] = None): self._children = [] self._data = data @property def data(self) -> str: return self._data @property def children(self) -> List['DumpsysNode']: return self._children def find_child(self, predicate: Callable[['DumpsysNode'], bool], max_levels: int = 0) -> Optional['DumpsysNode']: """Returns the first direct child that matches `predicate`, None otherwise. Args: predicate: Function-like that accepts a DumpsysNode and returns boolean. max_levels: Maximum number of levels down the tree to search for a child. If non-positive, only direct children will be searched for. Returns: A DumpsysNode or None. """ if not self.children: return None try: return next(x for x in self.children if predicate(x)) except StopIteration: logging.info('Failed to find child. max_levels: %i.', max_levels) # Search children. if max_levels: for child in self.children: child_result = child.find_child(predicate, max_levels - 1) if child_result is not None: return child_result return None def __repr__(self): return self._data def print_tree(self, indent: int = 2): """Prints this tree in logging.info().""" logging.info(' ' * indent + self.data) for c in self.children: c.print_tree(indent + 2) def build_tree_from_dumpsys_output(dumpsys_output: str) -> DumpsysNode: """Constructs a tree from a dumpsys string output. Args: dumpsys_output: string Verbatim output from adb dumpsys. The expected format is a list where each line is a node and the indentation marks the relationship with its parent or sibling. Returns: DumpsysNode The root of the tree. """ lines = dumpsys_output.split('\n') # Split by lines. lines = [x.rstrip(' \r') for x in lines] lines = [x for x in lines if len(x)] # Remove empty lines. root = DumpsysNode('___root___') # The root of all nodes. parents_stack = [root] for line in lines: stripped_line = line.lstrip(' ') indent = len(line) - len(stripped_line) # Number of indent spaces. new_node = DumpsysNode(stripped_line) # Create a node without indentation. parent = parents_stack.pop() if parent.data == '___root___': # The root is an exception for indentation. parent_indent = -2 else: parent_indent = (len(parents_stack) - 1) * 2 if indent == parent_indent: # `new_node` is a sibiling. parent = parents_stack.pop() elif indent < parent_indent: # Indentation reduced (i.e. a block finished) num_levels = (indent // 2) + 1 parents_stack = parents_stack[:num_levels] parent = parents_stack.pop() elif indent > parent_indent: # `new_node` is a child. pass # No need to change the current parent. parent.children.append(new_node) parents_stack.append(parent) parents_stack.append(new_node) return root def matches_path(dumpsys_activity_output: str, expected_view_hierarchy_path: Sequence[Pattern[str]], max_levels: int = 0) -> bool: """Returns True if the current dumpsys output matches the expected path. Args: dumpsys_activity_output: The output of running `dumpsys activity ...`. expected_view_hierarchy_path: [regex] A list of regular expressions to be tested at each level of the tree. max_levels: How many levels to search from root for View Hierarchy. Returns: True if the dumpsys tree contains one path that matches all regexes. """ root = build_tree_from_dumpsys_output(dumpsys_activity_output) # Find the View Hierarchy. view_hierarchy = root.find_child( lambda x: x.data.startswith('View Hierarchy'), max_levels) if view_hierarchy is None: logging.error( 'view_hierarchy is None. Dumpsys activity output: %s. tree: %r', str(dumpsys_activity_output), root.print_tree()) logging.error('Tree root: %s', str(root)) return None current_node = view_hierarchy for i, regex in enumerate(expected_view_hierarchy_path): def regex_predicate(node, expr=regex): matches = expr.match(node.data) return matches is not None child = current_node.find_child(regex_predicate) if child is None: logging.error('Mismatched regex (%i, %s). current_node: %s', i, regex.pattern, current_node) logging.error('Dumpsys activity output: %s', str(dumpsys_activity_output)) logging.error('Tree root: %s', str(root)) return None else: current_node = child return True class AppScreenChecker(): """Checks that the current app screen matches an expected screen.""" class Outcome(enum.IntEnum): """Possible return vales from checking the current app screen.""" # The current app screen matches the expected app screen. SUCCESS = 0 # There's no activity to check. EMPTY_EXPECTED_ACTIVITY = 1 # We were unable to determine the current activity. FAILED_ACTIVITY_EXTRACTION = 2 # The current activity does not match the expected activity. UNEXPECTED_ACTIVITY = 3 # The current view hierarchy does not match the expected view hierarchy. UNEXPECTED_VIEW_HIERARCHY = 4 def __init__(self, adb_controller: adb_control.AdbController, expected_app_screen: task_pb2.AppScreen): self._adb_controller = adb_controller self._expected_activity = expected_app_screen.activity self._expected_view_hierarchy_path = [ re.compile(regex) for regex in expected_app_screen.view_hierarchy_path ] # Return type is AppScreenChecker.Outcome, but pytype doesn't understand that. def matches_current_app_screen(self) -> enum.IntEnum: """Determines whether the current app screen matches `expected_app_screen`.""" if not self._expected_activity: return AppScreenChecker.Outcome.EMPTY_EXPECTED_ACTIVITY # Check if we are still on the expected Activity. current_activity = self._adb_controller.get_current_activity() if current_activity is None: return AppScreenChecker.Outcome.FAILED_ACTIVITY_EXTRACTION if current_activity != self._expected_activity: logging.error('current_activity: %s, expected_activity: %s', current_activity, self._expected_activity) return AppScreenChecker.Outcome.UNEXPECTED_ACTIVITY # Extract just the package name from the full activity name. package_name = self._expected_activity.split('/')[0] # Check if we are in the expected view hierarchy path. if self._expected_view_hierarchy_path: dumpsys_activity_output = self._adb_controller.get_activity_dumpsys( package_name) if dumpsys_activity_output: if not matches_path( dumpsys_activity_output, self._expected_view_hierarchy_path, max_levels=3): return AppScreenChecker.Outcome.UNEXPECTED_VIEW_HIERARCHY return AppScreenChecker.Outcome.SUCCESS <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A component that parses and processes SetupSteps.""" import copy import random import re import time from typing import Any, Dict, Optional, Sequence from absl import logging from android_env.components import adb_controller as adb_control from android_env.components import app_screen_checker from android_env.components import errors from android_env.components import logcat_thread from android_env.proto import task_pb2 class SetupStepInterpreter(): """An interpreter for SetupSteps.""" def __init__(self, adb_controller: adb_control.AdbController, logcat: logcat_thread.LogcatThread): """Initializes this interpreter. Args: adb_controller: An object to communicate with Android via ADB. logcat: A LogcatThread instance connected to the same Android simulator as AdbController. """ self._adb_controller = adb_controller self._logcat_thread = logcat self._last_activity = '' self._log_dict = { 'error_count_adb_call': 0, 'error_count_wait_for_app_screen': 0, 'error_count_check_install': 0, 'error_count_wait_for_message': 0, 'total_time_waiting_for_app_screen': 0 } def log_dict(self) -> Dict[str, Any]: return copy.deepcopy(self._log_dict) def interpret(self, setup_steps: Sequence[task_pb2.SetupStep]) -> None: """Returns True if parsing and processing `setup_steps` is successful.""" if setup_steps: logging.info('Executing setup steps: %s', setup_steps) for step in setup_steps: self._process_step_command(step) logging.info('Done executing setup steps.') def _process_step_command(self, step_cmd: task_pb2.SetupStep) -> None: """Processes a single step command from a reset or extra setup.""" if not step_cmd: logging.info('Empty step_cmd') return logging.info('Executing step_cmd: %r', step_cmd) step_type = step_cmd.WhichOneof('step') success_condition = step_cmd.success_condition success_check = success_condition.WhichOneof('check') assert step_type or success_check, ( 'At least one of step and success_condition must be defined.') num_tries = 0 max_retries = max(success_condition.num_retries, 3) while num_tries < max_retries: num_tries += 1 try: self._execute_step_cmd(step_cmd, step_type) time.sleep(0.5) self._check_success(success_check, success_condition) return except NotImplementedError: logging.exception('Not implemented error! Skipping this step command.') return except errors.AdbControllerError: self._log_dict['error_count_adb_call'] += 1 logging.warning('ADB call [%r] has failed. Try %d of %d.', step_cmd.adb_call, num_tries, max_retries) except errors.WaitForAppScreenError: self._log_dict['error_count_wait_for_app_screen'] += 1 logging.warning('Failed to wait for app screen. Try %d of %d.', num_tries, max_retries) except errors.WaitForMessageError: self._log_dict['error_count_wait_for_message'] += 1 logging.warning('Failed to wait for message. Try %d of %d.', num_tries, max_retries) except errors.CheckInstallError: self._log_dict['error_count_check_install'] += 1 logging.warning('Package [%r] not installed. Try %d of %d.', success_condition.check_install.package_name, num_tries, max_retries) raise errors.StepCommandError('Step failed: [%r]' % step_cmd) def _execute_step_cmd(self, step_cmd: task_pb2.SetupStep, step_type: Optional[str]) -> None: """Executes a step command of given type.""" if not step_type: return if step_type == 'sleep': time.sleep(step_cmd.sleep.time_sec) elif step_type == 'adb_call': self._parse_adb_call(step_cmd.adb_call) else: raise NotImplementedError('No step command of type [%s].' % step_type) def _check_success(self, success_check: Optional[str], success_condition: task_pb2.SuccessCondition) -> None: """Checks whether the given success condition was met.""" if not success_check: return if success_check == 'wait_for_app_screen': self._wait_for_app_screen(success_condition.wait_for_app_screen) elif success_check == 'check_install': self._check_install(success_condition.check_install) elif success_check == 'wait_for_message': self._wait_for_message(success_condition.wait_for_message) else: raise NotImplementedError('No success check called [%s].' % success_check) def _parse_adb_call(self, adb_cmd: task_pb2.AdbCall) -> None: """Parses an adb command into set of allowed calls.""" call_type = adb_cmd.WhichOneof('command') logging.info('Parsing ADB call of type: %s', call_type) if call_type == 'tap': tap = adb_cmd.tap self._adb_controller.input_tap(tap.x, tap.y) elif call_type == 'rotate': self._adb_controller.rotate_device(adb_cmd.rotate.orientation) elif call_type == 'press_button': if (adb_cmd.press_button.button == task_pb2.AdbCall.PressButton.Button.HOME): self._adb_controller.input_key('KEYCODE_HOME') elif (adb_cmd.press_button.button == task_pb2.AdbCall.PressButton.Button.BACK): self._adb_controller.input_key('KEYCODE_BACK') elif call_type == 'start_random_activity': self._last_activity = random.choice( list(adb_cmd.start_random_activity.activity_list)) logging.info('Random activity: %s', self._last_activity) self._adb_controller.start_activity( self._last_activity, list(adb_cmd.start_random_activity.extra_args)) wait_proto = task_pb2.WaitForAppScreen() wait_proto.app_screen.activity = self._last_activity wait_proto.timeout_sec = adb_cmd.start_random_activity.timeout_sec self._wait_for_app_screen(wait_proto) elif call_type == 'start_activity': self._adb_controller.start_activity( adb_cmd.start_activity.full_activity, list(adb_cmd.start_activity.extra_args)) elif call_type == 'start_intent': self._adb_controller.start_intent( action=adb_cmd.start_intent.action, data_uri=adb_cmd.start_intent.data_uri, package_name=adb_cmd.start_intent.package_name) elif call_type == 'force_stop': self._adb_controller.force_stop(adb_cmd.force_stop.package_name) elif call_type == 'force_stop_random_activity': if self._last_activity: package_name = self._last_activity.split('/')[0] logging.info('Force stop package (%s)', package_name) self._adb_controller.force_stop(package_name) elif call_type == 'clear_cache': self._adb_controller.clear_cache(adb_cmd.clear_cache.package_name) elif call_type == 'clear_cache_random_activity': if self._last_activity: package_name = self._last_activity.split('/')[0] logging.info('Clear cache package (%s)', package_name) self._adb_controller.force_stop(package_name) elif call_type == 'grant_permissions': self._adb_controller.grant_permissions( adb_cmd.grant_permissions.package_name, adb_cmd.grant_permissions.permissions) elif call_type == 'install_apk': install_apk_cmd = adb_cmd.install_apk location_type = install_apk_cmd.WhichOneof('location') logging.info('location_type: %s', location_type) if location_type == 'filesystem': self._adb_controller.install_apk(install_apk_cmd.filesystem.path) else: logging.error('Unsupported location type: %r', install_apk_cmd) elif call_type == 'start_accessibility_service': self._adb_controller.start_accessibility_service( adb_cmd.start_accessibility_service.full_service) elif call_type == 'start_screen_pinning': self._adb_controller.start_screen_pinning( adb_cmd.start_screen_pinning.full_activity) elif call_type == 'disable_animations': self._adb_controller.disable_animations() else: raise NotImplementedError('No ADB call type [%s].' % call_type) def _wait_for_app_screen( self, wait_for_app_screen: task_pb2.WaitForAppScreen) -> None: """Waits for a given `app_screen` to be the current screen.""" logging.info('Waiting for app screen...') app_screen = wait_for_app_screen.app_screen screen_checker = app_screen_checker.AppScreenChecker( self._adb_controller, app_screen) start_time = time.time() while time.time() - start_time < wait_for_app_screen.timeout_sec: if (screen_checker.matches_current_app_screen() == app_screen_checker.AppScreenChecker.Outcome.SUCCESS): wait_time = time.time() - start_time self._log_dict['total_time_waiting_for_app_screen'] += wait_time logging.info('Successfully waited for app screen in %r seconds: [%r]', wait_time, app_screen) return time.sleep(0.1) wait_time = time.time() - start_time self._log_dict['total_time_waiting_for_app_screen'] += wait_time logging.error('Failed to wait for app screen in %r seconds: [%r].', wait_time, app_screen) raise errors.WaitForAppScreenError() def _wait_for_message( self, wait_for_message: task_pb2.WaitForMessage) -> None: """Waits for a given message in logcat.""" message = wait_for_message.message logging.info('Waiting for message: %s...', message) event = re.compile(message) got_message = False def f(ev, match): del ev, match nonlocal got_message got_message = True listener = logcat_thread.EventListener(regexp=event, handler_fn=f) self._logcat_thread.add_event_listener(listener) self._logcat_thread.wait( event=event, timeout_sec=wait_for_message.timeout_sec) self._logcat_thread.remove_event_listener(listener) if got_message: logging.info('Message received: [%r]', message) else: logging.error('Failed to wait for message: [%r].', message) raise errors.WaitForMessageError() def _check_install(self, check_install: task_pb2.CheckInstall) -> None: """Checks that the given package is installed.""" package = check_install.package_name logging.info('Checking if package is installed: [%r]', package) start_time = time.time() while time.time() - start_time < check_install.timeout_sec: if self._adb_controller.is_package_installed(package): logging.info('Done confirming that package is installed.') return time.sleep(0.1) logging.error('Package not found.') raise errors.CheckInstallError() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Wraps the AndroidEnv to expose an OpenAI Gym interface.""" from typing import Any, Dict, Tuple from android_env.wrappers import base_wrapper import dm_env from dm_env import specs import gym from gym import spaces import numpy as np class GymInterfaceWrapper(base_wrapper.BaseWrapper, gym.Env): """AndroidEnv with OpenAI Gym interface.""" def __init__(self, env: dm_env.Environment): base_wrapper.BaseWrapper.__init__(self, env) self.spec = None self.action_space = self._spec_to_space(self._env.action_spec()) self.observation_space = self._spec_to_space(self._env.observation_spec()) self.metadata = {'render.modes': ['rgb_array']} def _spec_to_space(self, spec: specs.Array) -> spaces.Space: """Converts dm_env specs to OpenAI Gym spaces.""" if isinstance(spec, list): return spaces.Tuple([self._spec_to_space(s) for s in spec]) if isinstance(spec, dict): return spaces.Dict( {name: self._spec_to_space(s) for name, s in spec.items()}) if isinstance(spec, specs.DiscreteArray): return spaces.Box( shape=(), dtype=spec.dtype, low=0, high=spec.num_values-1) if isinstance(spec, specs.BoundedArray): return spaces.Box( shape=spec.shape, dtype=spec.dtype, low=spec.minimum, high=spec.maximum) if isinstance(spec, specs.Array): return spaces.Box( shape=spec.shape, dtype=spec.dtype, low=-np.inf, high=np.inf) raise ValueError('Unknown type for specs: {}'.format(spec)) def render(self, mode='rgb_array'): """Renders the environment.""" if mode == 'rgb_array': if self._latest_observation is None: return return self._latest_observation['pixels'] else: raise ValueError('Only supported render mode is rgb_array.') def reset(self) -> np.ndarray: timestep = self._env.reset() return timestep.observation def step(self, action: Dict[str, int]) -> Tuple[Any, ...]: """Take a step in the base environment.""" timestep = self._env.step(self._process_action(action)) observation = timestep.observation reward = timestep.reward done = timestep.step_type == dm_env.StepType.LAST info = {'discount': timestep.discount} return observation, reward, done, info <file_sep># AndroidEnv - Environment features AndroidEnv is a complex environment that, while offering an almost endless range of possibilites for RL research and investigation, poses multiple kinds of challenges simultaneously. In this document we outline AndroidEnv's main features that render it such a unique learning environment. ## Real-time environment AndroidEnv is built on top of an emulated Android device, allowing the agent to communicate with the emulator through touch actions. Android emulators are created independently from our environment implementation and simulate real Android devices in the most realistic manner. This simulation runs real-time, independently of the agent, meaning that the simulaton will not wait for agent input between frames. This aspect of the environment renders the RL setup similar to a robotics problem, where the challenges of real-time interaction and consequent noise in observations have to be overcome. Please note there is currently no straightforward way to slow down the simulation either. ## Action space <img align="right" src="images/classic_2048.gif" width="160" height="240"> Perhaps one of the most interesting features of AndroidEnv is its large and complex action interface. The raw action space of the environment consists of a tuple `(x,y) in [0,1]x[0,1]` determining the location of the action on the Android screen, and a discrete value `ActionType in {LIFT, TOUCH, REPEAT}` indicating whether the agent wants to touch the screen at this chosen location or not. This action space is uniform across all tasks/apps. **Gestures.** The complexity of the interface arises from the fact that individual raw actions on their own do not neccessarily trigger a meaningful change in the environment. Most Android applications are designed such that they can be controlled/navigated through common touchscreen gestures such as pressing buttons, swiping, scrolling, pinching, drag and drop etc. Each of these can be thought of as particular sequences of raw actions: for example, *touching* the screen at a particular location, then immediately *lifting* the imaginary finger might be interpreted as a *press of a button*; while a sequence of *touches* aligned in a vertical line might be interpreted as *scrolling*. We note that AndroidEnv does not support multitouch actions at the moment, but it is a possible feature to add. It is important to point out that it is out of the environment's control to determine how particular sequences of raw actions get interpreted by the Android simulator - much like when humans interact with physical devices, a certain gesture on the screen might be interpreted differently if it is performed at a slightly different angle or speed. Tap | Double Tap | Touch & Hold | Flick Left | Flick Right | Scroll (H) | Scroll (V) | Drag & Drop -------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | ----------- ![Screenshot of 'tap'](images/gestures/1-Finger-Tap.gif) | ![Screenshot of 'double_tap'](images/gestures/1-Finger-Double-Tap.gif) | ![Screenshot of 'touch_hold'](images/gestures/1-Finger-Touch-&-Hold.gif) | ![Screenshot of 'flick_left'](images/gestures/1-Finger-Flick-Left.gif) | ![Screenshot of 'flick_right'](images/gestures/1-Finger-Flick-Right.gif) | ![Screenshot of 'horizontal_scroll'](images/gestures/1-Finger-Horizontal-Scroll.gif) | ![Screenshot of 'vertical_scroll'](images/gestures/1-Finger-Vertical-Scroll.gif) | ![Screenshot of 'move'](images/gestures/1-Finger-Move.gif) **Wrappers.** It is possible to alter the raw action space of the environment by applying [wrappers](#wrappers). For example one might discretize the action space by splitting the screen up into a grid of a desired size; restrict the ActionType to *touch* only; or fix certain gesture skills. We note here that these wrappers, again, will not alter how the particular sequence of performed raw actions gets interpreted by the Android simulator. ## Observation space The observation space of AndroidEnv consists of three main components: (`pixels`, `timedelta`, `orientation`), the most notable of these being `pixels`. The original screen size will depend on the type of emulator used, but given that it will correspond to real device screen sizes, this will usually be quite large (of course, this can be scaled down, e.g. with wrappers). The `timedelta` component captures the amount of time passed since the last observation was fetched. The `orientation`, even though it does not affect the layout of the RGB image in the observation, might carry relevant information for the agent. For example, if there is text on the screen, it is important to know how it is oriented. Again, a benefit of this observation space is that it is uniform across all tasks. As mentioned above, observations often carry spatial cues and are suggestive of the kind of actions/gestures that are meaningful to perform in a given state. ## Task extras On top of the default observations (`pixels`, `timedelta`, `orientation`), some tasks might expose additional structured observations after each step. An *extra* in AndroidEnv is any information that an app may send to aid the understanding of the task. The type of information sent through this channel is usually something difficult to obtain from raw pixels and may include meaningful information such as: * The current board configuration (e.g. of a chess game or of a tetris game) in matrix or string form. * The position of the avatar in a map. * Events such as whether a button was pressed or whether a checkpoint was achieved. Note that these are entirely optional and may not be available at all. Analogously to `env.observation_spec()` and `env.action_spec()`, AndroidEnv exposes `env.task_extras_spec()`, which will return a dictionary of `dm_env.specs.Arrays`, capturing the specs of different extra information provided by the given task. To request extras from the environment, you can call `env.task_extras()` after each `env.step()`, which will return a dictionary of all the extra observations observed during the previous step (or an empty dict is there's none available). For example: ```python for _ in range(FLAGS.n_steps): action = agent.select_action(timestep.observation) timestep = env.step(action) logging.info('observation: %s', timestep.observation) logging.info('extra observations: %s', env.task_extras()) ``` Please note however that the env might not return extras at every timestep, only when something meaningful happened (e.g. only when a button was pressed, or when the state of the board has changed). When integrating your own APK as a new task for the environment, you can define your own extras by following the instructions [here](tasks_guide.md#log-messages-and-custom-apks). ## Wrappers AndroidEnv's action- and observation spaces can be altered by applying suitable wrappers. While custom wrappers can be built easily, we have provided a number of useful wrappers that demonstrate their usage: * `discrete_action_wrapper`: Discretizes the action space into an `nxk` grid. * `flat_interface_wrapper`: Removes the dictionary structure from the observation and action specs. * `float_pixels_wrapper`: Projects the pixel RGB values from the integer range `[0, 255]` to the float range `[0, 1]`. * `image_rescale_wrapper`: Resizes the pixel observations by the selected ratio. * `gym_wrapper`: Changes the environment interface from [dm_env](https://github.com/deepmind/dm_env) to [OpenAI](https://gym.openai.com/) gym interface. * `last_action_wrapper`: Extends the observation with a one-hot encoded location of the previously taken action, in order to aid agents without built-in memory. ## Internal structure of AndroidEnv The chart below gives an overview of the internal workings of the system, illustrating how different classes interact with each other and what their individual roles are. See the source code for more details. ![Components Chart](images/misc/components_chart.svg) <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Acme DQN agent interacting with AndroidEnv.""" from absl import app from absl import flags from absl import logging import acme from acme import specs from acme import wrappers as acme_wrappers from acme.agents.tf import dqn from acme.tf import networks import android_env from android_env import wrappers # Simulator args flags.DEFINE_string('avd_name', None, 'Name of AVD to use.') flags.DEFINE_string('android_avd_home', '~/.android/avd', 'Path to AVD.') flags.DEFINE_string('android_sdk_root', '~/Android/Sdk', 'Path to SDK.') flags.DEFINE_string('emulator_path', '~/Android/Sdk/emulator/emulator', 'Path to emulator.') flags.DEFINE_string('adb_path', '~/Android/Sdk/platform-tools/adb', 'Path to ADB.') # Environment args flags.DEFINE_string('task_path', None, 'Path to task textproto file.') # Experiment args flags.DEFINE_integer('num_episodes', 100, 'Number of episodes.') FLAGS = flags.FLAGS def apply_wrappers(env): """Applies a series of wrappers to the environment.""" env = wrappers.DiscreteActionWrapper(env, action_grid=(10, 10)) env = wrappers.ImageRescaleWrapper(env, zoom_factors=(0.25, 0.25)) env = wrappers.FloatPixelsWrapper(env) env = acme_wrappers.SinglePrecisionWrapper(env) return env def main(_): env = android_env.load( emulator_path=FLAGS.emulator_path, android_sdk_root=FLAGS.android_sdk_root, android_avd_home=FLAGS.android_avd_home, avd_name=FLAGS.avd_name, adb_path=FLAGS.adb_path, task_path=FLAGS.task_path, run_headless=False, ) env = apply_wrappers(env) env_spec = specs.make_environment_spec(env) agent = dqn.DQN( environment_spec=env_spec, network=networks.DQNAtariNetwork( num_actions=env_spec.actions.num_values), batch_size=10, samples_per_insert=2, min_replay_size=10) loop = acme.EnvironmentLoopV2(env, agent) loop.run(num_episodes=FLAGS.num_episodes) env.close() if __name__ == '__main__': logging.set_verbosity('info') logging.set_stderrthreshold('info') flags.mark_flags_as_required(['task_path', 'avd_name']) app.run(main) <file_sep># AndroidEnv - Running the environment In order to create an AndroidEnv instance you will need to provide two main components: a [simulator](#the-simulator) and a [task](#the-task). In the following sections you will learn how you can create them. ### The simulator First, you will need to provide your Android virtual device (AVD) that the environment (and through it, the agent) can communicate with. While this can also be a physical device, in most cases you will need a virtual emulated device. There are many ways to emulate an AVD - in our examples, we will use [Android Studio](https://developer.android.com/studio) to create one. 1. In Android Studio, create a virtual device by following this step-by-step [guide](emulator_guide.md). 2. Follow the steps below to attach the AVD to your environment. ### The task and examples with games and other apps A `task` is a particular definition of an RL problem that the agent will be interacting with. A `task` may include critical RL information, such as what the rewards are, when the episodes are supposed to terminate, and what the reset procedures are that the environment should perform upon episode termination (e.g. start or relaunch an app, clear cache, etc.). This information is packaged into a `Task()` proto message, which gets passed passed to AndroidEnv. * For ready-made example tasks provided with AndroidEnv, check out the [Available tasks](example_tasks.md), featuring Vokram (with Markov Decision Process (MDP)), Pong, DroidFish (a chess clone), Blockinger (a tetris clone), and more. * See the [Tasks guide](tasks_guide.md) for details on features and capabilities of tasks, as well as how to create custom ones. ### Create the environment After setting up the simulator and creating a task, you may find the [`android_env.load()`](https://github.com/deepmind/android_env/blob/main/android_env/loader.py) function handy for creating an environment instance by providing relevant arguments, such as: * `task_path`: the path pointing to the `.textproto` file describing the desired task. * `avd_name`: the name of the AVD specified when your created it in Android Studio. * `android_avd_home` (Optional): the path to where the AVD is installed. (default value: `~/.android/avd`). * `android_sdk_root` (Optional): the root directory of the Android SDK. (default value: `~/Android/Sdk`). * `emulator_path` (Optional): the path to the emulator binary. (default: `~/Android/Sdk/emulator/emulator`). * `adb_path` (Optional): the path to the ADB ([Android Debug Bridge](https://developer.android.com/studio/command-line/adb)). (default value: `~/Android/Sdk/platform-tools/adb`). For the AVD name and path, in Android Studio, go to **Tools** > **AVD Manager**, right click on your virtual device, and select **View Details**, where you will find the `avd_name` and its path. For the Android SDK location, in Android Studio, go to **Preferences** > **Appearance & Behavior** > **System Settings** > **Android SDKs** and note the _Android SDK Location_. In the SDK folder, you will find `/emulator/emulator` as well as the ADB path (`/platform-tools/adb`). Your example configuration may look like this, depending on how you set up your emulator: ```python import android_env env = android_env.load( avd_name='my_avd', android_avd_home='/Users/username/.android/avd', android_sdk_root='/Users/username/Library/Android/sdk', emulator_path='/Users/username/Library/Android/sdk/emulator/emulator', adb_path='/Users/username/Library/Android/sdk/platform-tools/adb', task_path='/Users/username/android_env/my_tasks/my_task.textproto', ) ``` ## Example RL agent scripts The `examples` directory contains a few simple example agent setups, such as: * [`run_random_agent.py`](https://github.com/deepmind/android_env/blob/main/examples/run_random_agent.py): Runs a simple loop performing randomly selected actions in the environment. * [`run_acme_agent.py`](https://github.com/deepmind/android_env/blob/main/examples/run_acme_agent.py): (Linux only) Runs a training loop with an [Acme](https://deepmind.com/research/publications/Acme) DQN agent, implemented in the popular DeepMind RL framework. This will require to install the [`acme`](https://github.com/deepmind/acme) dependency. * [`run_human_agent.py`](https://github.com/deepmind/android_env/blob/main/examples/run_human_agent.py): Creates a [`pygame`](https://www.pygame.org) instance that lets a human user interact with the environment and observe environment mechanics, such as rewards or task extras. You will need to install the [PyGame] dependency. For instance, here is how you can run [`run_random_agent.py`](https://github.com/8bitmp3/android_env/blob/main/examples/run_random_agent.py) in a folder where you have your APK file, such as [Apple Flinger](https://github.com/deepmind/android_env/blob/main/docs/example_tasks.md#apple-flinger) from [Example tasks](https://github.com/deepmind/android_env/blob/main/docs/example_tasks.md). (The downloaded TAR file contains the APK file and `.textproto` definitions.) ```shell python3 run_random_agent.py \ --avd_name='my_avd', --android_avd_home=/Users/username/.android/avd \ --android_sdk_root=/Users/username/Library/Android/sdk \ --emulator_path=/Users/username/Library/Android/sdk/emulator/emulator \ --adb_path=/Users/username/Library/Android/sdk/platform-tools/adb \ --num_steps=1000 \ --task_path=/Users/username/<PATH-TO-APP-TASK-FILES>/apple_flinger_M_1_1.textproto ``` <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utils for AndroidEnv.""" from typing import Sequence, Tuple from android_env.proto import task_pb2 import numpy as np def touch_position_to_pixel_position( touch_position: np.ndarray, width_height: Sequence[int], ) -> Tuple[int, int]: """Maps touch position in [0,1] to the corresponding pixel on the screen.""" touch_pixels = (touch_position * width_height).astype(np.int32) cap_idx = lambda v, idx_len: min(v, idx_len - 1) return tuple(map(cap_idx, touch_pixels, width_height)) def transpose_pixels(frame: np.ndarray) -> np.ndarray: """Converts image from shape (H, W, C) to (W, H, C) and vice-versa.""" return np.transpose(frame, axes=(1, 0, 2)) def orient_pixels( frame: np.ndarray, orientation: task_pb2.AdbCall.Rotate.Orientation) -> np.ndarray: """Rotates screen pixels according to the given orientation.""" if orientation == task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_90: frame = np.rot90(frame, k=3, axes=(0, 1)) elif orientation == task_pb2.AdbCall.Rotate.Orientation.PORTRAIT_180: frame = np.rot90(frame, k=2, axes=(0, 1)) elif orientation == task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_270: frame = np.rot90(frame, k=1, axes=(0, 1)) return frame <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.app_screen_checker.""" import re from typing import Sequence from absl.testing import absltest from android_env.components import app_screen_checker def flatten_tree(tree: app_screen_checker.DumpsysNode, flat_tree: Sequence[str], indent: int = 2): """Appends a list of strings to `flat_tree` from `tree`.""" flat_tree.append(' ' * indent + tree.data) for c in tree.children: flatten_tree(c, flat_tree, indent + 2) class AppScreenCheckerTest(absltest.TestCase): # Ensures that build_tree_from_dumpsys_output produces a node whose flat # representation matches our expectation from an arbitrary hierarchy. def test_build_tree_from_dumpsys_output(self): dumpsys_output = """ Queen Elizabeth II Charles William George Charlotte Louis Harry Archie Anne Peter Savannah Isla Zara Mia Lena Andrew Beatrice Eugenie Edward Louise James """ tree = app_screen_checker.build_tree_from_dumpsys_output(dumpsys_output) flat_tree = [] flatten_tree(tree, flat_tree, indent=2) self.assertEqual(flat_tree, [ ' ___root___', ' Queen Elizabeth II', ' Charles', ' William', ' George', ' Charlotte', ' Louis', ' Harry', ' Archie', ' Anne', ' Peter', ' Savannah', ' Isla', ' Zara', ' Mia', ' Lena', ' Andrew', ' Beatrice', ' Eugenie', ' Edward', ' Louise', ' James', ]) # Ensures that build_tree_from_dumpsys_output produces a node whose flat # representation matches our expectation from an arbitrary hierarchy. def test_build_forest_from_dumpsys_output(self): dumpsys_output = """ Tree1 Branch1 Leaf1 Leaf2 Branch2 Leaf3 Leaf4 Leaf5 Tree2 Branch3 Leaf6 Leaf7 Branch4 Leaf8 Leaf9 Leaf10 Leaf11 """ tree = app_screen_checker.build_tree_from_dumpsys_output(dumpsys_output) flat_tree = [] flatten_tree(tree, flat_tree, indent=2) self.assertEqual(flat_tree, [ ' ___root___', ' Tree1', ' Branch1', ' Leaf1', ' Leaf2', ' Branch2', ' Leaf3', ' Leaf4', ' Leaf5', ' Tree2', ' Branch3', ' Leaf6', ' Leaf7', ' Branch4', ' Leaf8', ' Leaf9', ' Leaf10', ' Leaf11', ]) def test_no_view_hierarchy_matches_path(self): dumpsys_output = """ TASK ACTIVITY Missing View Hierarchy A B C D E F """ expected_path = ['^A$', 'B$'] expected_view_hierarchy_path = [ re.compile(regex) for regex in expected_path ] self.assertFalse( app_screen_checker.matches_path(dumpsys_output, expected_view_hierarchy_path)) def test_matches_path(self): dumpsys_output = """ TASK ACTIVITY Some node we don't care Blah View Hierarchy Hirohito Akihito Naruhito Aiko Fumihito Mako Kako Hisahito Masahito """ expected_path = ['^Hirohito$', 'Akihito$', 'Fumihito$', 'Kako$'] expected_view_hierarchy_path = [ re.compile(regex) for regex in expected_path ] self.assertTrue( app_screen_checker.matches_path( dumpsys_output, expected_view_hierarchy_path, max_levels=2)) # Also check that the following path does not match anything in the tree. expected_path = ['^Hirohito$', 'Akihito$', 'Fumihito$', 'Kenji$'] expected_view_hierarchy_path = [ re.compile(regex) for regex in expected_path ] self.assertFalse( app_screen_checker.matches_path(dumpsys_output, expected_view_hierarchy_path)) def test_matches_path_one_level_deep(self): dumpsys_output = """ TASK ACTIVITY Some node we don't care Blah Some intermediate node View Hierarchy Hirohito Akihito Naruhito Aiko Fumihito Mako Kako Hisahito Masahito """ expected_path = ['^Hirohito$', 'Akihito$', 'Fumihito$', 'Kako$'] expected_view_hierarchy_path = [ re.compile(regex) for regex in expected_path ] self.assertTrue( app_screen_checker.matches_path( dumpsys_output, expected_view_hierarchy_path, max_levels=3)) # Also check that the view hierarchy is not found when searching only grand # children of TASK. expected_path = ['^Hirohito$', 'Akihito$', 'Fumihito$', 'Kako$'] expected_view_hierarchy_path = [ re.compile(regex) for regex in expected_path ] self.assertFalse( app_screen_checker.matches_path( dumpsys_output, expected_view_hierarchy_path, max_levels=2)) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Definitions of exceptions used by AndroidEnv.""" class ReadObservationError(Exception): """When the environment is unable to obtain an observation from a simulator.""" class ObservationDecodingError(ReadObservationError): """When the environment is unable to decode the observation from a simulator.""" class PipeTimedOutError(ReadObservationError): """When the environment waited for too long for part of an observation.""" class CoordinatorError(Exception): """Error raised by the Coordinator.""" class TooManyRestartsError(CoordinatorError): """The number of restarts has exceeded _MAX_RESTART_TRIES.""" class NotAllowedError(Exception): """When the player does something that outside of the task scope.""" class PlayerExitedActivityError(NotAllowedError): """When the player quits the current Android activity.""" class PlayerExitedViewHierarchyError(NotAllowedError): """When the player quits the current Android app screen.""" class AdbControllerError(Exception): """Errors that can be raised by ADBController.""" class AdbControllerShellInitError(AdbControllerError): """Raised when an error occurred when initializing ADB shell.""" class AdbControllerPexpectError(AdbControllerError): """Raise when a problem with pexpect communication occurs.""" class AdbControllerDeviceTimeoutError(AdbControllerError): """Raised when a device takes too long to respond.""" class AdbControllerConnectionError(AdbControllerError): """Error connecting to tcpip address.""" class SimulatorCrashError(Exception): """Raised when an AndroidSimulator crashed.""" class ConsoleConnectionError(Exception): """Raised when cannot connect to the emulator console.""" class SendActionError(Exception): """Raised when action couldn't be sent successfully.""" class StepCommandError(Exception): """Raised when setup step interpreter cannot process a command.""" class WaitForAppScreenError(StepCommandError): """Raised when the wait_for_app_screen success check is not met.""" class CheckInstallError(StepCommandError): """Raised when the check_install success check is not met.""" class WaitForMessageError(StepCommandError): """Raised when the wait_for_message success check is not met.""" <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.utils.""" from absl.testing import absltest from absl.testing import parameterized from android_env.components import utils from android_env.proto import task_pb2 import numpy as np class UtilsTest(parameterized.TestCase): @parameterized.parameters( ([0.5, 0.5], [320, 480], (160, 240)), ([0.25, 0.75], [320, 480], (80, 360)), ([0.0, 0.0], [320, 480], (0, 0)), ([1.0, 1.0], [320, 480], (319, 479)), ) def test_touch_position_to_pixel_position( self, touch_pos, width_height, pixel_pos): self.assertEqual(utils.touch_position_to_pixel_position( np.array(touch_pos), width_height), pixel_pos) def test_transpose_pixels(self): image = np.reshape(np.array(range(12)), (3, 2, 2)) expected = [[[0, 1], [4, 5], [8, 9]], [[2, 3], [6, 7], [10, 11]]] self.assertEqual(utils.transpose_pixels(image).shape, (2, 3, 2)) self.assertTrue((utils.transpose_pixels(image) == expected).all()) def test_orient_pixels(self): image = np.reshape(np.array(range(12)), (3, 2, 2)) expected_90 = [[[8, 9], [4, 5], [0, 1]], [[10, 11], [6, 7], [2, 3]]] rot_90 = task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_90 rotated = utils.orient_pixels(image, rot_90) self.assertEqual(rotated.shape, (2, 3, 2)) self.assertTrue((rotated == expected_90).all()) expected_180 = [[[10, 11], [8, 9]], [[6, 7], [4, 5]], [[2, 3], [0, 1]]] rot_180 = task_pb2.AdbCall.Rotate.Orientation.PORTRAIT_180 rotated = utils.orient_pixels(image, rot_180) self.assertEqual(rotated.shape, (3, 2, 2)) self.assertTrue((rotated == expected_180).all()) expected_270 = [[[2, 3], [6, 7], [10, 11]], [[0, 1], [4, 5], [8, 9]]] rot_270 = task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_270 rotated = utils.orient_pixels(image, rot_270) self.assertEqual(rotated.shape, (2, 3, 2)) self.assertTrue((rotated == expected_270).all()) rot_0 = task_pb2.AdbCall.Rotate.Orientation.PORTRAIT_0 rotated = utils.orient_pixels(image, rot_0) self.assertEqual(rotated.shape, (3, 2, 2)) self.assertTrue((rotated == image).all()) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.base_simulator.""" from typing import Optional, List from absl.testing import absltest from android_env.components import action_type from android_env.components import adb_controller from android_env.components import base_simulator import mock import numpy as np class FakeSimulator(base_simulator.BaseSimulator): """A simulator that spits injected data.""" def __init__(self, injected_adb_controller, **kwargs): self._injected_adb_controller = injected_adb_controller super().__init__(**kwargs) def adb_device_name(self) -> str: return 'FakeSimulator' def create_adb_controller(self) -> adb_controller.AdbController: return self._injected_adb_controller def send_action(self, action) -> None: pass def _restart_impl(self) -> None: pass def _launch_impl(self) -> None: pass def _get_observation(self) -> Optional[List[np.ndarray]]: return [np.ones(shape=(640, 480, 3)), self._timestamp] def set_timestamp(self, timestamp: int): self._timestamp = timestamp class BaseSimulatorTest(absltest.TestCase): def setUp(self): super().setUp() self._adb_controller = self.enter_context( mock.patch.object(adb_controller, 'AdbController', autospec=True)) tmp_dir = absltest.get_default_test_tmpdir() self._simulator = FakeSimulator( adb_path='/my/adb', adb_server_port=5037, tmp_dir=tmp_dir, prompt_regex='awesome>', injected_adb_controller=self._adb_controller) def test_adb_server_init(self): # The simulator init should start the adb server. self._adb_controller.init_server.assert_called_once() def test_device_name(self): self.assertNotEmpty(self._simulator.adb_device_name()) def test_launch(self): # Before a successful launch(), screen_dimensions() should raise. self.assertRaises(AssertionError, self._simulator.screen_dimensions) # The simulator should launch and not crash. self._adb_controller.get_screen_dimensions.return_value = (640, 480) self._simulator.launch() # After a successful launch(), screen_dimensions() should return something. np.testing.assert_equal(self._simulator.screen_dimensions(), [640, 480]) def test_launch_close(self): # The simulator should launch and not crash. self._adb_controller.get_screen_dimensions.return_value = (640, 480) self._simulator.launch() # Closing the simulator should also not crash. self._simulator.close() def test_get_observation(self): # The simulator should launch and not crash. self._adb_controller.get_screen_dimensions.return_value = (640, 480) self._simulator.launch() self._simulator.set_timestamp(123456) observation = self._simulator.get_observation() # Even though the FakeSimulator returns a 640x480x3 image, BaseSimulator # should add an extra layer for the last action. np.testing.assert_equal(observation['pixels'].shape, [640, 480, 3]) # Because there was only a single step, the timestamp delta should be just # the timestamp returned by FakeSimulator. self.assertEqual(observation['timedelta'], 123456) # The orientation format should be a 4-dimension one-hot. np.testing.assert_equal(observation['orientation'].shape, [4]) # Initially the orientation should not be set so we expect [0, 0, 0, 0]. self.assertEqual(np.sum(observation['orientation']), 0) # After updating the device orientation, we do expect to get an actual # one-hot. self._adb_controller.get_orientation.return_value = '3' self._simulator.update_device_orientation() self._simulator.set_timestamp(123459) updated_observation = self._simulator.get_observation() np.testing.assert_equal(updated_observation['orientation'], [0, 0, 0, 1]) # After setting the initial timestamp, we expect the timestamp delta to be # the difference between the current timestamp and the initial timestamp: # 123459 - 123456 = 3 self.assertEqual(updated_observation['timedelta'], 3) def test_prepare_action(self): # The simulator should launch and not crash. self._adb_controller.get_screen_dimensions.return_value = (480, 640) self._simulator.launch() self._simulator.set_timestamp(123456) self.assertRaises( ValueError, self._simulator._prepare_action, { 'action_type': np.array(action_type.ActionType.REPEAT), 'touch_position': [0.0, 0.0] }) self.assertEqual( self._simulator._prepare_action({ 'action_type': np.array(action_type.ActionType.LIFT), 'touch_position': [0.0, 0.0] }), (0, 0, False)) self.assertEqual( self._simulator._prepare_action({ 'action_type': np.array(action_type.ActionType.TOUCH), 'touch_position': [0.0, 0.0] }), (0, 0, True)) self.assertEqual( self._simulator._prepare_action({ 'action_type': np.array(action_type.ActionType.TOUCH), 'touch_position': [0.5, 0.2] }), (320, 96, True)) self.assertEqual( self._simulator._prepare_action({ 'action_type': np.array(action_type.ActionType.TOUCH), 'touch_position': [1.0, 1.0] }), (639, 479, True)) if __name__ == '__main__': absltest.main() <file_sep># AndroidEnv - Emulator Setup Guide In this document we provide a step-by-step guide for creating a virtual Android device with Android Studio. After creating an AVD ([Android Virtual Device](https://developer.android.com/studio/run/managing-avds)) you will be able to connect it to an AndroidEnv instance and you're ready to go. To get started, you will need to download [Android Studio](https://developer.android.com/studio) - an IDE widely used by Android developers. ## Install an SDK Platform Package Android Studio comes with the Android Software Development Toolkit (SDK) which, among others, allows you to install different versions of Android. Click on **Tools** > **SDK Manager** and select the SDK version that you would like to use. ![Screenshot of 'android_studio_2'](images/android_studio/android_studio_2.png) We recommend that you set the `Android SDK Location` to be in your home directory (for example, on Linux the default one is `~/Android/Sdk`, while on macOS - `~/Library/Android/sdk`). You can always find the SDK location in Android Studio under **Preferences** > **Appearance & Behavior** > **System Settings** > **Android SDKs** > _Android SDK Location_. If you set the the custom `Android SDK Location`, make note of it - you will need it for connecting AndroidEnv to your AVD. ![Screenshot of 'android_studio_0'](images/android_studio/android_studio_0.png) ## Create an AVD Now it is time to create a virtual device (AVD). Go to **Tools** > **AVD Manager**. ![Screenshot of 'android_studio_1'](images/android_studio/android_studio_1.png) In the pop-up window you will find an option to **Create Virtual Device**. ![Screenshot of 'android_studio_3'](images/android_studio/android_studio_3.png) Configure the virtual device. You can select the model or choose from more advanced settings (refer to the [Android docs](https://developer.android.com/studio/run/managing-avds) for step-by-step instructions). ![Screenshot of 'android_studio_4'](images/android_studio/android_studio_4.png) Name your AVD and take note of this value. It will be neccessary for connecting AndroidEnv to this virtual device. ![Screenshot of 'android_studio_6'](images/android_studio/android_studio_6.png) Once you are done, you will see the new AVD show up in the **AVD Manager**. Click on **View details** to inspect some of its properties. ![Screenshot of 'android_studio_8'](images/android_studio/android_studio_8.png) Take note of the `AVD Path`. This value will be neccessary for connecting AndroidEnv to this device. We recommend that you set this to be your home directory (for instance, on Linux or macOS it may be `~/.android/avd`). ![Screenshot of 'android_studio_9'](images/android_studio/android_studio_9.png) ## Ready to use With SDK and AVD both set up, you are now ready to use this emulated device with AndroidEnv. Don't forget to take note of the following three values: your AVD name, the AVD path, and the SDK path. For example, on Linux they may be: ``` --avd_name=my_avd --avd_package_path=~/.android/avd --android_sdk_root=~/Android/Sdk ``` Next, once you have set up the AVD, follow the [Task steps](instructions.md#the-task) in the [Running the environment guide](instructions.md) to finish setting up AndroidEnv. However, if you want to just interact with the newly created device, click on the run button next to your AVD in the **AVD Manager** in Android Studio (this step is optional). ![Screenshot of 'android_studio_7'](images/android_studio/android_studio_7.png) You will see an emulator window pop up. You can interact with it by clicking on the screen. ![Screenshot of 'android_studio_10'](images/android_studio/android_studio_10.png) There are many other features in Android Studio that let you customize your device. For example, you can create custom images with pre-installed applications or configured settings. <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.thread_function.""" from absl.testing import absltest from android_env.components import thread_function class ThreadFunctionTest(absltest.TestCase): def test_hello_world(self): class HelloFunction(thread_function.ThreadFunction): def main(self): v = self._read_value() if v: self._write_value('hello') else: self._write_value('world') hello_fn = HelloFunction(block_input=True, block_output=True, name='Hello') hello_fn.write(True, block=True) self.assertEqual(hello_fn.read(block=True), 'hello') hello_fn.write(False, block=True) self.assertEqual(hello_fn.read(block=True), 'world') hello_fn.kill() # Not strictly necessary, but it's good hygiene. def test_class_with_state(self): """Derived class with internal state to change the thread output.""" class HaveState(thread_function.ThreadFunction): def __init__(self, value, *args, **kwargs): self._value = value super().__init__(*args, **kwargs) def main(self): v = self._read_value() if v: self._write_value(v + self._value) have_state_fn = HaveState( value=123, block_input=True, block_output=True, name='HaveState') have_state_fn.write(3, block=True) self.assertEqual(have_state_fn.read(block=True), 126) have_state_fn.write(9, block=True) self.assertEqual(have_state_fn.read(block=True), 132) have_state_fn.kill() if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.adb_controller.""" import os import subprocess import time from absl.testing import absltest from absl.testing import parameterized from android_env.components import adb_controller from android_env.components import errors from android_env.proto import task_pb2 import mock # Timeout to be used by default in tests below. Set to a small value to avoid # hanging on a failed test. _TIMEOUT = 2 class AdbControllerTest(parameterized.TestCase): def setUp(self): super().setUp() self._mock_execute_command = self.enter_context( mock.patch.object( adb_controller.AdbController, '_execute_command', autospec=True)) self._adb_controller = adb_controller.AdbController( adb_path='my_adb', device_name='awesome_device', adb_server_port=9999, shell_prompt='l33t>') @mock.patch.object( adb_controller.AdbController, '_wait_for_device', autospec=True) def test_set_touch_indicators(self, mock_wait_for_device): self._adb_controller.set_touch_indicators( show_touches=True, pointer_location=False, timeout=_TIMEOUT) mock_wait_for_device.assert_called_once() self._mock_execute_command.assert_has_calls([ mock.call(self._adb_controller, ['shell', 'settings', 'put', 'system', 'show_touches', '1'], _TIMEOUT), mock.call( self._adb_controller, ['shell', 'settings', 'put', 'system', 'pointer_location', '0'], _TIMEOUT) ]) def test_force_stop(self): self._adb_controller.force_stop('com.amazing.package', timeout=_TIMEOUT) self._mock_execute_command.assert_called_once_with( self._adb_controller, ['shell', 'am', 'force-stop', 'com.amazing.package'], _TIMEOUT) def test_clear_cache(self): self._adb_controller.clear_cache('com.amazing.package', timeout=_TIMEOUT) self._mock_execute_command.assert_called_with( self._adb_controller, ['shell', 'pm', 'clear', 'com.amazing.package'], _TIMEOUT) def test_grant_permissions(self): self._adb_controller.grant_permissions( 'com.amazing.package', ['hey.READ', 'ho.WRITE'], timeout=_TIMEOUT) self._mock_execute_command.assert_has_calls([ mock.call(self._adb_controller, ['shell', 'pm', 'grant', 'com.amazing.package', 'hey.READ'], _TIMEOUT), mock.call(self._adb_controller, ['shell', 'pm', 'grant', 'com.amazing.package', 'ho.WRITE'], _TIMEOUT), ]) def test_start_activity(self): self._adb_controller.start_activity( 'hello.world/hello.world.MainActivity', [], timeout=_TIMEOUT) self._adb_controller.start_activity( full_activity='hello.world/hello.world.MainActivity', extra_args=['Planet 1', 'Planet 2'], timeout=_TIMEOUT) self._mock_execute_command.assert_has_calls([ mock.call(self._adb_controller, [ 'shell', 'am', 'start', '-S', '-n', 'hello.world/hello.world.MainActivity' ], _TIMEOUT), mock.call(self._adb_controller, [ 'shell', 'am', 'start', '-S', '-n', 'hello.world/hello.world.MainActivity', 'Planet 1', 'Planet 2' ], _TIMEOUT) ]) def test_start_intent(self): self._adb_controller.start_intent( action='action', data_uri='data', package_name='my.package', timeout=_TIMEOUT) self._mock_execute_command.assert_called_once_with( self._adb_controller, ['shell', 'am', 'start', '-a', 'action', '-d', 'data', 'my.package'], _TIMEOUT) def test_broadcast(self): self._adb_controller.broadcast( 'hello.world/hello.world.BroadcastReceiver', 'android.intent.action.TEST', [], timeout=_TIMEOUT) self._adb_controller.broadcast( receiver='hello.world/hello.world.BroadcastReceiver', action='android.intent.action.TEST', extra_args=['--es', 'KEY', 'VALUE'], timeout=_TIMEOUT) self._mock_execute_command.assert_has_calls([ mock.call(self._adb_controller, [ 'shell', 'am', 'broadcast', '-n', 'hello.world/hello.world.BroadcastReceiver', '-a', 'android.intent.action.TEST' ], _TIMEOUT), mock.call(self._adb_controller, [ 'shell', 'am', 'broadcast', '-n', 'hello.world/hello.world.BroadcastReceiver', '-a', 'android.intent.action.TEST', '--es', 'KEY', 'VALUE' ], _TIMEOUT) ]) def test_setprop(self): self._adb_controller.setprop('myprop', 'true', timeout=_TIMEOUT) self._adb_controller.setprop('myotherprop', 'false', timeout=_TIMEOUT) self._mock_execute_command.assert_has_calls([ mock.call(self._adb_controller, ['shell', 'setprop', 'myprop', 'true'], _TIMEOUT), mock.call(self._adb_controller, ['shell', 'setprop', 'myotherprop', 'false'], _TIMEOUT), ]) def test_rotate_device(self): self._adb_controller.rotate_device( task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_90, timeout=_TIMEOUT) self._adb_controller.rotate_device( task_pb2.AdbCall.Rotate.Orientation.PORTRAIT_0, timeout=_TIMEOUT) self._adb_controller.rotate_device( task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_270, timeout=_TIMEOUT) self._adb_controller.rotate_device( task_pb2.AdbCall.Rotate.Orientation.PORTRAIT_180, timeout=_TIMEOUT) self._mock_execute_command.assert_has_calls([ mock.call( self._adb_controller, args=['shell', 'settings', 'put', 'system', 'user_rotation', '1'], timeout=_TIMEOUT), mock.call( self._adb_controller, args=['shell', 'settings', 'put', 'system', 'user_rotation', '0'], timeout=_TIMEOUT), mock.call( self._adb_controller, args=['shell', 'settings', 'put', 'system', 'user_rotation', '3'], timeout=_TIMEOUT), mock.call( self._adb_controller, args=['shell', 'settings', 'put', 'system', 'user_rotation', '2'], timeout=_TIMEOUT) ]) @mock.patch.object( adb_controller.AdbController, '_wait_for_device', autospec=True) def test_get_screen_dimensions_failed_wait(self, mock_wait_for_device): mock_wait_for_device.side_effect = errors.AdbControllerDeviceTimeoutError( 'Time is up.') self.assertRaises(errors.AdbControllerDeviceTimeoutError, self._adb_controller.get_screen_dimensions) mock_wait_for_device.assert_called_once() @mock.patch.object( adb_controller.AdbController, '_wait_for_device', autospec=True) def test_get_screen_dimensions_success(self, mock_wait_for_device): self._mock_execute_command.return_value = b'Physical size: 1280x800' screen_dimensions = self._adb_controller.get_screen_dimensions( timeout=_TIMEOUT) mock_wait_for_device.assert_called() self._mock_execute_command.assert_called_with(self._adb_controller, ['shell', 'wm', 'size'], _TIMEOUT) self.assertEqual(screen_dimensions, (800, 1280)) def test_activity_dumpsys(self): package_name = 'com.world.hello' self._mock_execute_command.return_value = b'My awesome dumpsys output!!!' activity_dumpsys = self._adb_controller.get_activity_dumpsys( package_name, timeout=_TIMEOUT) self._mock_execute_command.assert_called_once_with( self._adb_controller, ['shell', 'dumpsys', 'activity', package_name, package_name], _TIMEOUT) # Compare activity_dumpsys to what we want. Notice that we expect a UTF-8 # string, NOT bytes. self.assertEqual(activity_dumpsys, 'My awesome dumpsys output!!!') def test_input_tap(self): self._mock_execute_command.return_value = b'' self._adb_controller.input_tap(123, 456, timeout=_TIMEOUT) self._mock_execute_command.assert_called_once_with( self._adb_controller, ['shell', 'input', 'tap', '123', '456'], _TIMEOUT) def test_input_text(self): self._mock_execute_command.return_value = b'' self._adb_controller.input_text('my_text', timeout=_TIMEOUT) self._mock_execute_command.assert_called_once_with( self._adb_controller, ['shell', 'input', 'text', 'my_text'], _TIMEOUT) def test_input_key(self): self._mock_execute_command.return_value = b'' self._adb_controller.input_key('KEYCODE_HOME', timeout=_TIMEOUT) self._adb_controller.input_key('KEYCODE_BACK', timeout=_TIMEOUT) self._adb_controller.input_key('KEYCODE_ENTER', timeout=_TIMEOUT) self._mock_execute_command.assert_has_calls([ mock.call(self._adb_controller, ['shell', 'input', 'keyevent', 'KEYCODE_HOME'], _TIMEOUT), mock.call(self._adb_controller, ['shell', 'input', 'keyevent', 'KEYCODE_BACK'], _TIMEOUT), mock.call(self._adb_controller, ['shell', 'input', 'keyevent', 'KEYCODE_ENTER'], _TIMEOUT), ]) # A key code outside of the accepted codes should raise an exception. self.assertRaises(AssertionError, self._adb_controller.input_key, 'KEYCODE_0') def test_install_apk(self): self._mock_execute_command.return_value = b'' # Passing an invalid path should raise an exception. self.assertRaises(AssertionError, self._adb_controller.install_apk, '') local_apk_path = os.path.join(absltest.get_default_test_tmpdir(), 'my_app.apk') with open(local_apk_path, 'wb') as f: f.write(b'blah. whatever') self._adb_controller.install_apk(local_apk_path, timeout=_TIMEOUT) self._mock_execute_command.assert_has_calls([ mock.call(self._adb_controller, ['install', '-r', '-t', '-g', local_apk_path], _TIMEOUT), ]) def test_start_accessibility_service(self): self._mock_execute_command.return_value = b'' self._adb_controller.start_accessibility_service( 'my.service', timeout=_TIMEOUT) self._mock_execute_command.assert_has_calls([ mock.call(self._adb_controller, [ 'shell', 'settings', 'put', 'secure', 'enabled_accessibility_services', 'my.service' ], _TIMEOUT) ]) @mock.patch.object( adb_controller.AdbController, '_fetch_current_task_id', autospec=True) def test_start_screen_pinning_task_not_found(self, mock_fetch_current_task_id): self._mock_execute_command.return_value = b'' mock_fetch_current_task_id.return_value = -1 self._adb_controller.start_screen_pinning( 'my.app.CoolActivity', timeout=_TIMEOUT) self._mock_execute_command.assert_not_called() @mock.patch.object( adb_controller.AdbController, '_fetch_current_task_id', autospec=True) def test_start_screen_pinning(self, mock_fetch_current_task_id): self._mock_execute_command.return_value = b'' mock_fetch_current_task_id.return_value = 123 self._adb_controller.start_screen_pinning( 'my.app.CoolActivity', timeout=_TIMEOUT) self._mock_execute_command.assert_has_calls([ mock.call(self._adb_controller, ['shell', 'am', 'task', 'lock', '123'], _TIMEOUT) ]) def test_fetch_current_task_id(self): full_activity_name = ( 'com.google.example.games.nostalgicracer/' 'com.google.example.games.nostalgicracer.MainActivity') bad_task = ( ' taskId=8: ' 'com.google.android.apps.maps/com.google.android.maps.MapsActivity ' 'bounds=[0,0][480,320] userId=0 visible=true ' 'topActivity=ComponentInfo{%s}' % full_activity_name) good_task_not_visible = ( 'taskId=49: %s bounds=[0,0][320,480] userId=0 visible=false more_stuff' % full_activity_name) good_task = ( 'taskId=50: %s bounds=[0,0][320,480] userId=0 visible=true more_stuff' % full_activity_name) stack_list = '\n'.join([bad_task, good_task_not_visible, good_task]).encode('utf-8') self._mock_execute_command.return_value = stack_list self.assertEqual( 50, self._adb_controller._fetch_current_task_id( full_activity_name, timeout=_TIMEOUT)) def test_check_install_not_installed(self): self._mock_execute_command.return_value = b""" package:foo package:bar package:baz """ self.assertFalse( self._adb_controller.is_package_installed('faz', timeout=_TIMEOUT)) def test_check_install_installed(self): self._mock_execute_command.return_value = b""" package:foo package:bar package:baz """ self.assertTrue( self._adb_controller.is_package_installed('baz', timeout=_TIMEOUT)) @parameterized.parameters( (True, True, 'null*'), (True, False, 'immersive.status=*'), (False, True, 'immersive.navigation=*'), (False, False, 'immersive.full=*'), (None, None, 'immersive.full=*'), # Defaults to hiding both. ) def test_set_bar_visibility(self, navigation, status, expected): expected_output = b'Message.' self._mock_execute_command.return_value = expected_output self.assertEqual( expected_output, self._adb_controller.set_bar_visibility( navigation=navigation, status=status, timeout=_TIMEOUT)) self._mock_execute_command.assert_has_calls([ mock.call( self._adb_controller, ['shell', 'settings', 'put', 'global', 'policy_control', expected], _TIMEOUT), ]) @mock.patch.object(time, 'sleep', autospec=True) def test_init_server(self, mock_sleep): self._adb_controller.init_server(timeout=_TIMEOUT) self._mock_execute_command.assert_called_once_with(self._adb_controller, ['devices'], _TIMEOUT) mock_sleep.assert_called_once() class AdbControllerInitTest(absltest.TestCase): def test_deletes_problem_env_vars(self): os.environ['ANDROID_HOME'] = '/usr/local/Android/Sdk' os.environ['ANDROID_ADB_SERVER_PORT'] = '1337' adb_controller.AdbController( adb_path='my_adb', device_name='awesome_device', adb_server_port=9999, shell_prompt='l33t>', default_timeout=_TIMEOUT) self.assertNotIn('ANDROID_HOME', os.environ) self.assertNotIn('ANDROID_ADB_SERVER_PORT', os.environ) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A class that manages an Android Emulator.""" from typing import Any, Dict, Optional, List from absl import logging from android_env.components import base_simulator from android_env.components import emulator_console from android_env.components import emulator_launcher from android_env.components import errors from android_env.proto import emulator_controller_pb2 from android_env.proto import emulator_controller_pb2_grpc import grpc import numpy as np import portpicker def is_existing_emulator_provided(launcher_args: Dict[str, Any]) -> bool: """Returns true if all necessary args were provided.""" return bool(launcher_args.get('adb_port') and launcher_args.get('emulator_console_port') and launcher_args.get('grpc_port')) class EmulatorSimulator(base_simulator.BaseSimulator): """Controls an Android Emulator.""" def __init__(self, emulator_launcher_args: Dict[str, Any], emulator_console_args: Dict[str, Any], **kwargs): # If adb_port and console_port are both already provided, # we assume the emulator already exists and there's no need to launch. if is_existing_emulator_provided(emulator_launcher_args): self._existing_emulator_provided = True self._adb_port = emulator_launcher_args['adb_port'] self._console_port = emulator_launcher_args['emulator_console_port'] self._grpc_port = emulator_launcher_args['grpc_port'] logging.info('Connecting to existing emulator "%r"', self._adb_port) else: self._existing_emulator_provided = False self._adb_port = portpicker.pick_unused_port() self._console_port = portpicker.pick_unused_port() self._grpc_port = emulator_launcher_args.get( 'grpc_port', portpicker.pick_unused_port()) super().__init__(**kwargs) self._emulator_stub = None self._image_format = None # Create EmulatorLauncher. emulator_launcher_args.update({ 'adb_port': self._adb_port, 'adb_server_port': self._adb_server_port, 'emulator_console_port': self._console_port, 'local_tmp_dir': self._local_tmp_dir, 'kvm_device': self._kvm_device, 'grpc_port': self._grpc_port, }) logging.info('emulator_launcher_args: %r', emulator_launcher_args) if not self._existing_emulator_provided: self._launcher = emulator_launcher.EmulatorLauncher( **emulator_launcher_args) # Prepare EmulatorConsole. emulator_console_args.update({ 'console_port': self._console_port, 'tmp_dir': self._local_tmp_dir, }) logging.info('emulator_console_args: %r', emulator_console_args) self._emulator_console_args = emulator_console_args self._console = None def adb_device_name(self) -> str: return 'emulator-%s' % (self._adb_port - 1) def _start_console(self) -> None: self._console = emulator_console.EmulatorConsole( **self._emulator_console_args) def _restart_impl(self) -> None: if self._console is not None: self._console.close() if not self._existing_emulator_provided: self._launcher.restart() if self._grpc_port < 0: self._start_console() def _launch_impl(self) -> None: try: if not self._existing_emulator_provided: self._launcher.launch() if self._grpc_port < 0: self._start_console() except errors.SimulatorCrashError: # If the simulator crashes on the initial launch, we try to restart once. self.restart() def _post_launch_setup(self): super()._post_launch_setup() if self._grpc_port >= 0: self._emulator_stub = self._create_emulator_stub() self._image_format = emulator_controller_pb2.ImageFormat( format=emulator_controller_pb2.ImageFormat.ImgFormat.RGB888, height=self._screen_dimensions[0], width=self._screen_dimensions[1], ) def _create_emulator_stub(self, use_async: bool = False): """Returns a stub to the EmulatorController service.""" port = f'localhost:{self._grpc_port}' options = [('grpc.max_send_message_length', -1), ('grpc.max_receive_message_length', -1)] if use_async: self._channel = grpc.aio.insecure_channel(port, options=options) else: self._channel = grpc.insecure_channel(port, options=options) logging.info('Added gRPC channel for the Emulator on port %s', port) return emulator_controller_pb2_grpc.EmulatorControllerStub(self._channel) def send_action(self, action: Dict[str, np.ndarray]) -> None: """Sends a touch event to the emulator.""" if self._grpc_port < 0: # Use the Emulator Console assert self._console, 'Console has not been initialized yet.' action = self._prepare_action(action) self._console.send_mouse_action(*action) else: # Use gRPC connection assert self._emulator_stub, 'Emulator stub has not been initialized yet.' x, y, down = self._prepare_action(action) self._emulator_stub.sendTouch( emulator_controller_pb2.TouchEvent(touches=[ emulator_controller_pb2.Touch(x=x, y=y, pressure=int(down))])) def _get_observation(self) -> Optional[List[np.ndarray]]: """Fetches the latest observation from the emulator.""" if self._grpc_port < 0: assert self._console, 'Console has not been initialized yet.' return self._console.fetch_screenshot() else: assert self._emulator_stub, 'Emulator stub has not been initialized yet.' assert self._image_format, 'ImageFormat has not been initialized yet.' image_proto = self._emulator_stub.getScreenshot(self._image_format) h, w = image_proto.format.height, image_proto.format.width image = np.frombuffer(image_proto.image, dtype='uint8', count=h*w*3) image.shape = (h, w, 3) return [image, np.int64(image_proto.timestampUs)] def close(self): if self._console is not None: self._console.close() if hasattr(self, '_channel'): self._channel.close() if hasattr(self, '_emulator_stub'): del self._emulator_stub if hasattr(self, '_launcher') and not self._existing_emulator_provided: self._launcher.close() super().close() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Loads an interactive session where a human acts on behalf of an agent.""" import time from typing import Any, Dict from absl import app from absl import flags from absl import logging import android_env from android_env.components import action_type from android_env.components import utils from android_env.proto import task_pb2 import dm_env import numpy as np import pygame # Simulator args. flags.DEFINE_string('avd_name', None, 'Name of AVD to use.') flags.DEFINE_string('android_avd_home', '~/.android/avd', 'Path to AVD.') flags.DEFINE_string('android_sdk_root', '~/Android/Sdk', 'Path to SDK.') flags.DEFINE_string('emulator_path', '~/Android/Sdk/emulator/emulator', 'Path to emulator.') flags.DEFINE_string('adb_path', '~/Android/Sdk/platform-tools/adb', 'Path to ADB.') flags.DEFINE_boolean('run_headless', True, 'Optionally turn off display.') # Environment args. flags.DEFINE_string('task_path', None, 'Path to task textproto file.') # Pygame args. flags.DEFINE_list('screen_size', '480,720', 'Screen width, height in pixels.') flags.DEFINE_float('frame_rate', 1.0/30.0, 'Frame rate in seconds.') FLAGS = flags.FLAGS def _get_action_from_event( event: pygame.event.Event, screen: pygame.Surface, orientation: task_pb2.AdbCall.Rotate.Orientation) -> Dict[str, Any]: """Returns the current action by reading data from a pygame Event object.""" act_type = action_type.ActionType.LIFT if event.type == pygame.MOUSEBUTTONDOWN: act_type = action_type.ActionType.TOUCH return { 'action_type': np.array(act_type, dtype=np.int32), 'touch_position': _scale_position(event.pos, screen, orientation), } def _get_action_from_mouse( screen: pygame.Surface, orientation: task_pb2.AdbCall.Rotate.Orientation) -> Dict[str, Any]: """Returns the current action by reading data from the mouse.""" act_type = action_type.ActionType.LIFT if pygame.mouse.get_pressed()[0]: act_type = action_type.ActionType.TOUCH return { 'action_type': np.array(act_type, dtype=np.int32), 'touch_position': _scale_position(pygame.mouse.get_pos(), screen, orientation), } def _scale_position( position: np.ndarray, screen: pygame.Surface, orientation: task_pb2.AdbCall.Rotate.Orientation) -> np.ndarray: """AndroidEnv accepts mouse inputs as floats so we need to scale it.""" scaled_pos = np.divide(position, screen.get_size(), dtype=np.float32) if orientation == task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_90: scaled_pos = scaled_pos[::-1] scaled_pos[0] = 1 - scaled_pos[0] return scaled_pos def _accumulate_reward( timestep: dm_env.TimeStep, episode_return: float) -> float: """Accumulates rewards collected over the course of an episode.""" if timestep.reward and timestep.reward != 0: logging.info('Reward: %s', timestep.reward) episode_return += timestep.reward if timestep.first(): episode_return = 0 elif timestep.last(): logging.info('Episode return: %s', episode_return) return episode_return def _render_pygame_frame( surface: pygame.Surface, screen: pygame.Surface, orientation: task_pb2.AdbCall.Rotate.Orientation, timestep: dm_env.TimeStep) -> None: """Displays latest observation on pygame surface.""" frame = timestep.observation['pixels'][:, :, :3] # (H x W x C) (RGB) frame = utils.transpose_pixels(frame) # (W x H x C) frame = utils.orient_pixels(frame, orientation) pygame.surfarray.blit_array(surface, frame) pygame.transform.smoothscale(surface, screen.get_size(), screen) pygame.display.flip() def main(_): pygame.init() pygame.display.set_caption('android_human_agent') with android_env.load( emulator_path=FLAGS.emulator_path, android_sdk_root=FLAGS.android_sdk_root, android_avd_home=FLAGS.android_avd_home, avd_name=FLAGS.avd_name, adb_path=FLAGS.adb_path, task_path=FLAGS.task_path, run_headless=FLAGS.run_headless) as env: # Reset environment. first_timestep = env.reset() orientation = np.argmax(first_timestep.observation['orientation']) # Create pygame canvas. screen_size = list(map(int, FLAGS.screen_size)) # (W x H) obs_shape = env.observation_spec()['pixels'].shape[:2] # (H x W) if (orientation == task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_90 or orientation == task_pb2.AdbCall.Rotate.Orientation.LANDSCAPE_270): screen_size = screen_size[::-1] obs_shape = obs_shape[::-1] screen = pygame.display.set_mode(screen_size) # takes (W x H) surface = pygame.Surface(obs_shape[::-1]) # takes (W x H) # Start game loop. prev_frame = time.time() episode_return = 0 while True: if pygame.key.get_pressed()[pygame.K_ESCAPE]: return all_events = pygame.event.get() for event in all_events: if event.type == pygame.QUIT: return # Filter event queue for mouse click events. mouse_click_events = [ event for event in all_events if event.type in [pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP] ] # Process all mouse click events. for event in mouse_click_events: action = _get_action_from_event(event, screen, orientation) timestep = env.step(action) episode_return = _accumulate_reward(timestep, episode_return) _render_pygame_frame(surface, screen, orientation, timestep) # Sample the current position of the mouse either way. action = _get_action_from_mouse(screen, orientation) timestep = env.step(action) episode_return = _accumulate_reward(timestep, episode_return) _render_pygame_frame(surface, screen, orientation, timestep) # Limit framerate. now = time.time() frame_time = now - prev_frame if frame_time < FLAGS.frame_rate: time.sleep(FLAGS.frame_rate - frame_time) prev_frame = now if __name__ == '__main__': logging.set_verbosity('info') logging.set_stderrthreshold('info') flags.mark_flags_as_required(['avd_name', 'task_path']) app.run(main) <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Coordinator handles interaction between internal components of AndroidEnv.""" import copy import socket import time from typing import Any, Dict, Optional, Tuple from absl import logging from android_env.components import action_type as action_type_lib from android_env.components import base_simulator from android_env.components import errors from android_env.components import specs from android_env.components import task_manager as task_manager_lib import dm_env import numpy as np class Coordinator(): """Handles interaction between internal components of AndroidEnv.""" def __init__( self, simulator: base_simulator.BaseSimulator, task_manager: task_manager_lib.TaskManager, step_timeout_sec: int = 10, max_steps_per_sec: float = 5.0, periodic_restart_time_min: float = 0.0, force_simulator_launch: bool = True, ): """Handles communication between AndroidEnv and its components. Args: simulator: A BaseSimulator instance. task_manager: The TaskManager, responsible for coordinating RL tasks. step_timeout_sec: Timeout in seconds between steps. If step is not called within that time, the episode will reset at the next step. Set to 0 to disable. max_steps_per_sec: Maximum steps per second. If the simulator is faster, the Coordinator will wait before returning an observation. periodic_restart_time_min: Time between periodic restarts in minutes. If > 0.0, will trigger a simulator restart at the end of the next episode once the time has been reached. force_simulator_launch: Forces the simulator to relaunch even if it is already launched. """ self._simulator = simulator self._task_manager = task_manager self._step_timeout_sec = step_timeout_sec self._max_steps_per_sec = max_steps_per_sec self._periodic_restart_time_min = periodic_restart_time_min self._force_simulator_launch = force_simulator_launch # Logging settings. self._log_dict = { 'total_steps': 0, 'episode_steps': 0, 'restart_count': 0, 'restart_count_periodic': 0, 'restart_count_setup_steps': 0, 'restart_count_reset_steps': 0, 'restart_count_simulator_launch': 0, 'restart_count_simulator_reset': 0, 'restart_count_execute_action': 0, 'restart_count_fetch_observation': 0, 'reset_count_step_timeout': 0, } # Initialize counters. self._should_restart = False self._latest_observation_time = None self._simulator_start_time = None self._restart_simulator() def action_spec(self) -> Dict[str, dm_env.specs.Array]: return specs.base_action_spec() def observation_spec(self) -> Dict[str, dm_env.specs.Array]: screen_dims = self._simulator.screen_dimensions() return specs.base_observation_spec( height=screen_dims[0], width=screen_dims[1]) def task_extras_spec(self) -> Dict[str, dm_env.specs.Array]: return specs.base_task_extras_spec(task=self._task_manager.task()) def reset_environment_state(self): """Resets the state of the simulation for a new RL episode. This involves resetting relevant counters and performing reset steps specific to the running task (e.g. restarting an application). A lift action is also performed to ensure that sequential touches are not interconnected between separate RL episodes. """ # Restart the simulation if neccessary. if self._should_restart or self._should_periodic_restart(): self._restart_simulator() # Reset counters. self._latest_observation_time = None for key in self._log_dict: if key.startswith('episode'): self._log_dict[key] = 0.0 # Execute a lift action before resetting the task. self._send_action_to_simulator({ 'action_type': np.array(action_type_lib.ActionType.LIFT), 'touch_position': np.array([0, 0]), }) # Reset the task. try: self._task_manager.reset_task() self._simulator.update_device_orientation() except errors.StepCommandError: logging.exception('Failed to reset the task. Restarting simulator.') self._log_dict['restart_count_simulator_reset'] += 1 self._should_restart = True def _should_periodic_restart(self) -> bool: """Checks if it is time to restart the simulator. If a periodic restart time was specified, the Coordinator will re-launch the simulator at regular time intervals. This helps to make sure that the simulator is not is a stale state even if the environment has been running for a significant amount of time. Returns: Boolean indicating if it is time to restart the simulator. """ if self._periodic_restart_time_min and self._simulator_start_time: sim_alive_time = (time.time() - self._simulator_start_time) / 60.0 logging.info('Simulator has been running for %f mins', sim_alive_time) if sim_alive_time > self._periodic_restart_time_min: logging.info('Maximum alive time reached. Restarting simulator.') self._log_dict['restart_count_periodic'] += 1 return True return False def _restart_simulator(self, max_retries: int = 3): """Restarts the simulation. Closes and re-launches the system, restarting the simulator process and reinitializing the task in the newly started simulator. Args: max_retries: Number of times to attempt a restart before raising an error. """ # Reset counters. self._should_restart = False # Attempt to restart the system a given number of times. num_tries = 1 while True: if num_tries > max_retries: logging.error('Maximum number of restarts reached.') raise errors.TooManyRestartsError logging.info('Simulator launch attempt %d of %d', num_tries, max_retries) # Launch the simulator (will restart if already launched). try: if self._force_simulator_launch or not self._simulator.is_launched(): self._task_manager.pause_task() self._simulator.launch() self._simulator_start_time = time.time() adb_controller = self._simulator.create_adb_controller() except errors.AdbControllerError: logging.error('Error launching the simulator.') self._log_dict['restart_count_simulator_launch'] += 1 num_tries += 1 continue # Start the task. try: self._task_manager.setup_task(adb_controller=adb_controller) except errors.StepCommandError: logging.error('Failed to set up the task. Restarting simulator.') self._log_dict['restart_count_setup_steps'] += 1 num_tries += 1 continue # Restart was successful. break def execute_action( self, action: Optional[Dict[str, np.ndarray]], ) -> Tuple[Optional[Dict[str, np.ndarray]], float, Dict[str, Any], bool]: """Executes the selected action and returns transition info. Args: action: Selected action to perform on the simulated Android device. Returns: observation: Pixel observations as displayed on the screen. reward: Total reward collected since the last call. extras: Task extras observed since the last call. episode_end: Boolean indicating if the RL episode should be terminated. """ # Increment counters. self._task_manager.increment_steps() if action is not None: self._log_dict['total_steps'] += 1 self._log_dict['episode_steps'] += 1 # If a restart is neccessary, end the episode. if self._should_restart or self._check_timeout(): return None, 0.0, {}, True # If the action is a TOUCH or LIFT, send it to the simulator. if (action is not None and action['action_type'].item() != action_type_lib.ActionType.REPEAT): self._send_action_to_simulator(action) # Sleep to maintain a steady interaction rate. self._wait_for_next_frame() # Read necessary transition information and return it to the agent. try: self._latest_observation_time = time.time() observation = self._simulator.get_observation() reward = self._task_manager.get_current_reward() task_extras = self._task_manager.get_current_extras() episode_end = self._task_manager.check_if_episode_ended() return observation, reward, task_extras, episode_end except (errors.ReadObservationError, socket.error): logging.exception('Unable to fetch observation. Restarting simulator.') self._log_dict['restart_count_fetch_observation'] += 1 self._should_restart = True return None, 0.0, {}, True def _send_action_to_simulator(self, action: Dict[str, np.ndarray]) -> None: """Sends the selected action to the simulator. The simulator will interpret the action as a touchscreen event and perform it accordingly. The effect this action triggers in the Android OS will be determined by the currently running application. Args: action: action which will get interpreted as a touchscreen event. """ try: self._simulator.send_action(action) except (socket.error, errors.SendActionError): logging.exception('Unable to execute action. Restarting simulator.') self._log_dict['restart_count_execute_action'] += 1 self._should_restart = True def _check_timeout(self) -> bool: """Checks if timeout between steps have exceeded. If too much time has passed since the last step was performed, it is assumed that the simulation is in a bad state, so the Coordinator will re-launch the simulator to make sure interaction proceeds from a clean state. Returns: Boolean indicating if the step timeout limit has been reached. """ if self._step_timeout_sec and self._latest_observation_time: time_since_last_obs = self._get_time_since_last_observation() if time_since_last_obs > self._step_timeout_sec: self._should_restart = True return True return False def _wait_for_next_frame(self) -> None: """Pauses the environment so that the interaction is around 1/FPS.""" time_since_observation = self._get_time_since_last_observation() time_to_wait = 1. / self._max_steps_per_sec - time_since_observation if time_to_wait > 0.0: time.sleep(time_to_wait) def _get_time_since_last_observation(self) -> float: """Computes time passed since the last observation was fetched.""" if self._latest_observation_time is not None: return time.time() - self._latest_observation_time else: return np.inf def get_logs(self) -> Dict[str, Any]: """Returns internal counter values.""" log_dict = copy.deepcopy(self._log_dict) log_dict.update(self._task_manager.log_dict()) return log_dict def close(self): """Cleans up the state of this Coordinator.""" if hasattr(self, '_task_manager'): self._task_manager.close() if hasattr(self, '_simulator'): self._simulator.close() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A ThreadFunction that runs and parses adb dumpsys.""" import enum from absl import logging from android_env.components import app_screen_checker as screen_checker from android_env.components import thread_function AppScreenChecker = screen_checker.AppScreenChecker class DumpsysThread(thread_function.ThreadFunction): """A class that executes dumpsys in a separate thread.""" class Signal(enum.IntEnum): """Defines commands we can use to communicate with the dumpsys thread.""" # To ask the thread to fetch dumpsys from Android. FETCH_DUMPSYS = 0 # The user has left the activity that contains the AndroidEnv task. USER_EXITED_ACTIVITY = 1 # The user exited the view hierarchy that we expect. USER_EXITED_VIEW_HIERARCHY = 2 # App screen checker determined none of the errors above happened. OK = 3 # App screen checker was not queried. DID_NOT_CHECK = 4 def __init__( self, app_screen_checker: AppScreenChecker, check_frequency: int, max_failed_current_activity: int, block_input: bool, block_output: bool, name: str = 'dumpsys', ): """Initializes the dumpsys reader thread. This loops forever waiting for inputs from the main thread and outputting its analyses of the output of ADB dumpsys. These analyses are too expensive to be in the critical path of AndroidEnv::step() so we consume them async from this separate thread. Args: app_screen_checker: The class that actually determines if the current screen matches the expected screen. check_frequency: Integer. We only call dumpsys 1/check_frequency times in each iteration of the while loop below. max_failed_current_activity: Integer. We try to fetch the current activity but sometimes it fails. If it fails more than `max_failed_current_activity` consecutive times, we declare that the user has exited `expected_activity`. block_input: Whether to block this thread when reading its input queue. block_output: Whether to block this thread when writing to its output queue. name: Name of the thread. """ self._app_screen_checker = app_screen_checker self._main_loop_counter = 0 self._check_frequency = check_frequency self._max_failed_activity_extraction = max_failed_current_activity self._num_failed_activity_extraction = 0 super().__init__( block_input=block_input, block_output=block_output, name=name) def main(self): v = self._read_value() if v != DumpsysThread.Signal.FETCH_DUMPSYS: self._write_value(DumpsysThread.Signal.DID_NOT_CHECK) return # Update and check loop_counter against check_frequency. self._main_loop_counter += 1 if (self._check_frequency <= 0 or self._main_loop_counter < self._check_frequency): self._write_value(DumpsysThread.Signal.DID_NOT_CHECK) return self._main_loop_counter = 0 outcome = self._app_screen_checker.matches_current_app_screen() # We were unable to determine the current activity. if outcome == AppScreenChecker.Outcome.FAILED_ACTIVITY_EXTRACTION: self._num_failed_activity_extraction += 1 logging.info('self._num_failed_activity_extraction: %s', self._num_failed_activity_extraction) if (self._num_failed_activity_extraction >= self._max_failed_activity_extraction): logging.error('Maximum number of failed activity extraction reached.') self._num_failed_activity_extraction = 0 self._write_value(DumpsysThread.Signal.USER_EXITED_ACTIVITY) return else: self._num_failed_activity_extraction = 0 # The current app screen matches all expectations. if (outcome == AppScreenChecker.Outcome.SUCCESS or outcome == AppScreenChecker.Outcome.EMPTY_EXPECTED_ACTIVITY): self._write_value(DumpsysThread.Signal.OK) return # Player has exited the app. Terminate the episode. elif outcome == AppScreenChecker.Outcome.UNEXPECTED_ACTIVITY: self._write_value(DumpsysThread.Signal.USER_EXITED_ACTIVITY) return # Player has exited the main game. Terminate the episode. elif outcome == AppScreenChecker.Outcome.UNEXPECTED_VIEW_HIERARCHY: self._write_value(DumpsysThread.Signal.USER_EXITED_VIEW_HIERARCHY) return <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base specs for AndroidEnv.""" from typing import Dict from android_env.components import action_type from android_env.proto import task_pb2 import dm_env from dm_env import specs import numpy as np _PROTO_DTYPE_TO_NUMPY_DTYPE = { task_pb2.ArraySpec.DataType.FLOAT: np.float32, task_pb2.ArraySpec.DataType.DOUBLE: np.float64, task_pb2.ArraySpec.DataType.INT8: np.int8, task_pb2.ArraySpec.DataType.INT16: np.int16, task_pb2.ArraySpec.DataType.INT32: np.int32, task_pb2.ArraySpec.DataType.INT64: np.int64, task_pb2.ArraySpec.DataType.UINT8: np.uint8, task_pb2.ArraySpec.DataType.UINT16: np.uint16, task_pb2.ArraySpec.DataType.UINT32: np.uint32, task_pb2.ArraySpec.DataType.UINT64: np.uint64, task_pb2.ArraySpec.DataType.BOOL: np.bool_, task_pb2.ArraySpec.DataType.STRING_U1: np.dtype(('U1')), task_pb2.ArraySpec.DataType.STRING_U16: np.dtype(('<U16')), task_pb2.ArraySpec.DataType.STRING_U25: np.dtype(('<U25')), task_pb2.ArraySpec.DataType.STRING_U250: np.dtype(('<U250')), } def base_action_spec() -> Dict[str, specs.Array]: """Default action spec for AndroidEnv. Returns: action_type: An integer of type ActionType: TOUCH=0, LIFT=1, REPEAT=2 touch_position: Position [x, y] of the touch action, where x, y are float values between 0.0 and 1.0 corresponding to the relative position on the screen. IGNORED when (action_type != ActionType.TOUCH). """ return { 'action_type': specs.DiscreteArray( num_values=len(action_type.ActionType), name='action_type'), 'touch_position': specs.BoundedArray( shape=(2,), dtype=np.float32, minimum=[0.0, 0.0], maximum=[1.0, 1.0], name='touch_position'), } def base_observation_spec(height: int, width: int) -> Dict[str, specs.Array]: """Default observation spec for AndroidEnv. Args: height: Height of the device screen in pixels. width: Width of the device screen in pixels. Returns: pixels: Spec for the RGB screenshot of the device. Has shape (H, W, 3) timedelta: Spec for time delta since the last observation (in microseconds). orientation: Spec for the latest orientation in a one-hot representation: [1, 0, 0, 0]: PORTRAIT (0 degrees) [0, 1, 0, 0]: LANDSCAPE (90 degrees clockwise) [0, 0, 1, 0]: PORTRAIT (180 degrees) ("upside down") [0, 0, 0, 1]: LANDSCAPE (270 degrees clockwise) """ return { 'pixels': specs.Array( shape=(height, width, 3), dtype=np.uint8, name='pixels'), 'timedelta': specs.Array(shape=(), dtype=np.int64, name='timedelta'), 'orientation': specs.Array(shape=np.array([4]), dtype=np.uint8, name='orientation'), } def base_task_extras_spec(task: task_pb2.Task) -> Dict[str, dm_env.specs.Array]: """Task extras spec for AndroidEnv, as read from a task_pb2.Task.""" return { spec.name: _convert_spec(spec) for spec in task.extras_spec } def _convert_spec(array_spec: task_pb2.ArraySpec) -> specs.Array: """Converts ArraySpec proto to dm_env specs.Array.""" return specs.Array( shape=array_spec.shape, dtype=_PROTO_DTYPE_TO_NUMPY_DTYPE[array_spec.dtype], name=array_spec.name) <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.coordinator.""" import time from absl.testing import absltest from android_env.components import action_type from android_env.components import coordinator from android_env.components import emulator_simulator from android_env.components import errors from android_env.components import task_manager import mock import numpy as np class CoordinatorTest(absltest.TestCase): def setUp(self): super().setUp() self.addCleanup(mock.patch.stopall) # Disable previous patches. self._simulator = mock.create_autospec(emulator_simulator.EmulatorSimulator) self._task_manager = mock.create_autospec(task_manager.TaskManager) self._coordinator = coordinator.Coordinator( simulator=self._simulator, task_manager=self._task_manager, step_timeout_sec=2, max_steps_per_sec=60, periodic_restart_time_min=0) def test_restart_simulator(self): self._coordinator._restart_simulator() def test_reset(self): self._coordinator.reset_environment_state() def test_process_action(self): self._simulator.get_observation.return_value = {'observation': 0} self._task_manager.get_current_reward.return_value = 10.0 self._task_manager.get_current_extras.return_value = {'extra': [0.0]} self._task_manager.check_if_episode_ended.return_value = False obs, reward, task_extras, episode_end = self._coordinator.execute_action( action={'action_type': np.array(action_type.ActionType.LIFT)}) self.assertDictEqual(obs, {'observation': 0}) self.assertEqual(reward, 10.0) self.assertEqual(task_extras, {'extra': [0.0]}) self.assertFalse(episode_end) def test_process_action_error(self): self._simulator.get_observation.side_effect = errors.ReadObservationError() self._task_manager.get_current_reward.return_value = 0.0 self._task_manager.get_current_extras.return_value = {} self._task_manager.check_if_episode_ended.return_value = True obs, reward, task_extras, episode_end = self._coordinator.execute_action( action={'action_type': np.array(action_type.ActionType.LIFT)}) self.assertTrue(self._coordinator._should_restart) self.assertIsNone(obs) self.assertEqual(reward, 0.0) self.assertEqual(task_extras, {}) self.assertTrue(episode_end) def test_execute_action_touch(self): self._simulator.get_observation.return_value = {'observation': 0} self._simulator.send_action.return_value = True action = {'action_type': np.array(action_type.ActionType.TOUCH)} _ = self._coordinator.execute_action(action) self._simulator.send_action.assert_called_once_with(action) def test_execute_action_repeat(self): self._simulator.get_observation.return_value = {'observation': 0} self._simulator.send_action.return_value = True _ = self._coordinator.execute_action( {'action_type': np.array(action_type.ActionType.REPEAT)}) self._simulator.send_action.assert_not_called() def test_execute_action_error(self): self._simulator.get_observation.return_value = {'observation': 0} self._simulator.send_action.side_effect = errors.SendActionError _ = self._coordinator.execute_action( {'action_type': np.array(action_type.ActionType.TOUCH)}) self.assertTrue(self._coordinator._should_restart) def test_check_timeout_false(self): self._coordinator._latest_observation_time = time.time() timeout = self._coordinator._check_timeout() self.assertFalse(timeout) def test_check_timeout_true(self): self._coordinator._latest_observation_time = time.time() time.sleep(3) timeout = self._coordinator._check_timeout() self.assertTrue(timeout) def test_max_restarts_adb_error(self): # The method was called once at init. init_fn_call = self._simulator.create_adb_controller.call_count self._simulator.create_adb_controller.side_effect = ( errors.AdbControllerError) self.assertRaises(errors.TooManyRestartsError, self._coordinator._restart_simulator) # The method was called three more times when attempting to restart. self.assertEqual(init_fn_call + 3, self._simulator.create_adb_controller.call_count) def test_max_restarts_setup_steps(self): init_fn_call = self._task_manager.setup_task.call_count self._task_manager.setup_task.side_effect = errors.StepCommandError self.assertRaises(errors.TooManyRestartsError, self._coordinator._restart_simulator) # The method was called three more times when attempting to restart. self.assertEqual(init_fn_call + 3, self._task_manager.setup_task.call_count) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Wraps the AndroidEnv environment to provide discrete actions.""" from typing import Optional, Sequence, Dict from android_env.components import action_type from android_env.wrappers import base_wrapper import dm_env from dm_env import specs import numpy as np NOISE_CLIP_VALUE = 0.4999 class DiscreteActionWrapper(base_wrapper.BaseWrapper): """AndroidEnv with discrete actions.""" def __init__(self, env: dm_env.Environment, action_grid: Optional[Sequence[int]] = (10, 10), redundant_actions: bool = True, noise: float = 0.1): super().__init__(env) self._parent_action_spec = self._env.action_spec() self._assert_base_env() self._action_grid = action_grid # [height, width] self._grid_size = np.product(self._action_grid) self._num_action_types = self._parent_action_spec['action_type'].num_values self._redundant_actions = redundant_actions self._noise = noise def _assert_base_env(self): """Checks that the wrapped env has the right action spec format.""" assert len(self._parent_action_spec) == 2 assert not self._parent_action_spec['action_type'].shape assert self._parent_action_spec['touch_position'].shape == (2,) @property def num_actions(self) -> int: """Number of discrete actions.""" if self._redundant_actions: return np.product(self._action_grid) * self._num_action_types else: return np.product(self._action_grid) + self._num_action_types - 1 def step(self, action: Dict[str, int]) -> dm_env.TimeStep: """Take a step in the base environment.""" return self._env.step(self._process_action(action)) def _process_action(self, action: Dict[str, int]) -> Dict[str, np.ndarray]: """Transforms action so that it agrees with AndroidEnv's action spec.""" return { 'action_type': np.array(self._get_action_type(action['action_id']), dtype=self._parent_action_spec['action_type'].dtype), 'touch_position': np.array(self._get_touch_position(action['action_id']), dtype=self._parent_action_spec['touch_position'].dtype) } def _get_action_type(self, action_id: int) -> action_type.ActionType: """Compute action type corresponding to the given action_id. When `self._redundant_actions` == True the `grid_size` is "broadcast" over all the possible actions so you end up with `grid_size` discrete actions of type 0, `grid_size` discrete actions of type 1, etc. for all action types. When `self._redundant_actions` == False the first `grid_size` actions are reserved for "touch" and the rest are just added (NOT multiplied) to the total number of discrete actions (exactly one of LIFT and REPEAT). Args: action_id: A discrete action. Returns: action_type: The action_type of the action. """ if self._redundant_actions: assert action_id < self._num_action_types * self._grid_size return action_id // self._grid_size else: assert action_id <= self._grid_size + 1 if action_id < self._grid_size: return action_type.ActionType.TOUCH elif action_id == self._grid_size: return action_type.ActionType.LIFT else: return action_type.ActionType.REPEAT def _get_touch_position(self, action_id: int) -> Sequence[float]: """Compute the position corresponding to the given action_id. Note: in the touch_position (x, y) of an action, x corresponds to the horizontal axis (width), and y corresponds to the vertical axis (height) of the screen. BUT, the screen has dimensions (height, width), i.e. the first coordinate corresponds to y, and the second coordinate corresponds to x. Pay attention to this mismatch in the calculations below. Args: action_id: A discrete action. Returns: touch_position: The [0,1]x[0,1] coordinate of the action. """ position_idx = action_id % self._grid_size x_pos_grid = position_idx % self._action_grid[1] # WIDTH y_pos_grid = position_idx // self._action_grid[1] # HEIGHT noise_x = np.random.normal(loc=0.0, scale=self._noise) noise_y = np.random.normal(loc=0.0, scale=self._noise) # Noise is clipped so that the action will strictly stay in the cell. noise_x = max(min(noise_x, NOISE_CLIP_VALUE), -NOISE_CLIP_VALUE) noise_y = max(min(noise_y, NOISE_CLIP_VALUE), -NOISE_CLIP_VALUE) x_pos = (x_pos_grid + 0.5 + noise_x) / self._action_grid[1] # WIDTH y_pos = (y_pos_grid + 0.5 + noise_y) / self._action_grid[0] # HEIGHT # Project action space to action_spec ranges. For the default case of # minimum = [0, 0] and maximum = [1, 1], this will not do anything. x_min, y_min = self._parent_action_spec['touch_position'].minimum x_max, y_max = self._parent_action_spec['touch_position'].maximum x_pos = x_min + x_pos * (x_max - x_min) y_pos = y_min + y_pos * (y_max - y_min) return [x_pos, y_pos] def action_spec(self) -> Dict[str, specs.Array]: """Action spec of the wrapped environment.""" return { 'action_id': specs.DiscreteArray( num_values=self.num_actions, name='action_id') } <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.emulator_console.""" import builtins import os import telnetlib import time from absl.testing import absltest from android_env.components import emulator_console from android_env.components import errors from android_env.proto import raw_observation_pb2 import mock import numpy as np class EmulatorConsoleTest(absltest.TestCase): def setUp(self): super().setUp() self.addCleanup(mock.patch.stopall) # Disable previous patches. # Create a mock file with a fake auth code. self._mock_auth_file = mock.MagicMock() self._mock_auth_file.__enter__ = mock.MagicMock( return_value=self._mock_auth_file) self._mock_auth_file.read.return_value = 'some_code_i_dont_care' # Create a mock file to hold the FIFO. self._mock_fifo_file = mock.MagicMock() self._mock_fifo_file.__enter__ = mock.MagicMock( return_value=self._mock_fifo_file) self._mock_open = mock.patch.object(builtins, 'open', autospec=True).start() def fake_open(fname, mode=''): """A closure that returns auth file the first time, then fifo.""" del fname, mode fake_open.open_counter += 1 if fake_open.open_counter == 1: return self._mock_auth_file return self._mock_fifo_file fake_open.open_counter = 0 # Function attribute ("static" local variable). self._mock_open.side_effect = fake_open @mock.patch.object(time, 'sleep', autospec=True) @mock.patch.object( telnetlib, 'Telnet', side_effect=ConnectionRefusedError('oops'), autospec=True) def test_connection_error(self, telnet_connection, mock_sleep): self.assertRaises( errors.ConsoleConnectionError, emulator_console.EmulatorConsole, console_port=1234, auth_code='<PASSWORD>', tmp_dir=absltest.get_default_test_tmpdir()) telnet_connection.assert_has_calls([mock.call('localhost', 1234)] * 3) mock_sleep.assert_called() def test_auth_error(self): telnet_connection = mock.create_autospec(telnetlib.Telnet) telnet_connection.read_until.return_value = 'whatever. I will not be used' telnet_connection.read_until.side_effect = EOFError('oh no') with mock.patch.object( telnetlib, 'Telnet', autospec=True, return_value=telnet_connection) as telnet_init: self.assertRaises( EOFError, emulator_console.EmulatorConsole, console_port=1234, auth_code='<PASSWORD>', tmp_dir=absltest.get_default_test_tmpdir()) telnet_init.assert_called_once_with('localhost', 1234) @mock.patch.object(os.path, 'expanduser', autospec=True) def test_no_auth_should_look_in_home_folder(self, mock_expanduser): telnet_connection = mock.create_autospec(telnetlib.Telnet) telnet_connection.read_until.return_value = 'OK' with mock.patch.object( telnetlib, 'Telnet', autospec=True, return_value=telnet_connection) as telnet_init: console = emulator_console.EmulatorConsole( console_port=1234, auth_code=None, tmp_dir=absltest.get_default_test_tmpdir()) telnet_init.assert_called_once_with('localhost', 1234) mock_expanduser.assert_called_once() console.close() @mock.patch.object(os, 'remove', autospec=True) @mock.patch.object(os.path, 'isfile', autospec=True) def test_existing_fifo_should_be_deleted(self, mock_isfile, mock_remove): telnet_connection = mock.create_autospec(telnetlib.Telnet) telnet_connection.read_until.return_value = 'OK' # Pretend that a fifo with that name already exists so that we verify that # EmulatorConsole is deleting and recreating it. mock_isfile.return_value = True self._mock_fifo_file.read.return_value = b'' with mock.patch.object( telnetlib, 'Telnet', autospec=True, return_value=telnet_connection) as telnet_init: console = emulator_console.EmulatorConsole( console_port=1234, auth_code=None, tmp_dir=absltest.get_default_test_tmpdir()) telnet_init.assert_called_once_with('localhost', 1234) mock_isfile.assert_called_once() mock_remove.assert_called_once() console.close() @mock.patch.object(os, 'remove', autospec=True) @mock.patch.object(os, 'close', autospec=True) def test_send_mouse_action(self, mock_close, mock_remove): telnet_connection = mock.create_autospec(telnetlib.Telnet) telnet_connection.read_until.return_value = 'OK' with mock.patch.object( telnetlib, 'Telnet', autospec=True, return_value=telnet_connection) as telnet_init: console = emulator_console.EmulatorConsole( console_port=1234, auth_code=None, tmp_dir=absltest.get_default_test_tmpdir()) telnet_init.assert_called_once_with('localhost', 1234) console.send_mouse_action(7, 8, True) telnet_connection.write.assert_called() # Close the console. console.close() # Because fetch_screenshot() was not called, the pipe was not actually # opened so we don't expect it to be closed. mock_close.assert_has_calls([]) mock_remove.assert_has_calls([]) def test_fetch_screenshot_timedout(self): """Ensures that we get an exception if `fetch_screenshot` takes >20s.""" telnet_connection = mock.create_autospec(telnetlib.Telnet) telnet_connection.read_until.return_value = 'OK' pipe_read_timeout = 1.0 def stuck_read(): """A .read() call that takes a long time to return something.""" time.sleep(pipe_read_timeout + 5) return b'hello there' self._mock_fifo_file.read.side_effect = stuck_read with mock.patch.object( telnetlib, 'Telnet', autospec=True, return_value=telnet_connection) as telnet_init: console = emulator_console.EmulatorConsole( console_port=1234, auth_code=None, tmp_dir=absltest.get_default_test_tmpdir(), pipe_read_timeout_sec=pipe_read_timeout) telnet_init.assert_called_once_with('localhost', 1234) self.assertRaises(errors.PipeTimedOutError, console.fetch_screenshot) console.close() def test_fetch_screenshot_io_error(self): telnet_connection = mock.create_autospec(telnetlib.Telnet) telnet_connection.read_until.return_value = 'OK' # Create a fake flat image with 4 channels. fake_img = np.array(list(range(10)) * 4, dtype=np.uint8) fake_raw_obs = raw_observation_pb2.RawObservation() fake_raw_obs.screen.data = fake_img.tobytes() fake_raw_obs.screen.height = 5 fake_raw_obs.screen.width = 2 fake_raw_obs.screen.num_channels = 4 fake_raw_obs.timestamp_us = 123456789 # Setup fifo as thread starts reading in the constructor. def io_error_read(): io_error_read.counter += 1 if io_error_read.counter % 2 == 1: return fake_raw_obs.SerializeToString() raise IOError('Nooo, f.read() crashed!') io_error_read.counter = 0 self._mock_fifo_file.read.side_effect = io_error_read with mock.patch.object( telnetlib, 'Telnet', autospec=True, return_value=telnet_connection) as telnet_init: console = emulator_console.EmulatorConsole( console_port=1234, auth_code=None, tmp_dir=absltest.get_default_test_tmpdir()) telnet_init.assert_called_once_with('localhost', 1234) self.assertRaises(IOError, console.fetch_screenshot) console.close() def test_fetch_screenshot_decoding_error(self): telnet_connection = mock.create_autospec(telnetlib.Telnet) telnet_connection.read_until.return_value = 'OK' # Setup fifo as thread starts reading in the constructor. def bad_proto_read(): bad_proto_read.counter += 1 if bad_proto_read.counter % 2 == 1: return b'I am definitely not a RawObservation!' else: return b'' bad_proto_read.counter = 0 self._mock_fifo_file.read.side_effect = bad_proto_read with mock.patch.object( telnetlib, 'Telnet', autospec=True, return_value=telnet_connection) as telnet_init: console = emulator_console.EmulatorConsole( console_port=1234, auth_code=None, tmp_dir=absltest.get_default_test_tmpdir()) telnet_init.assert_called_once_with('localhost', 1234) self.assertRaises(errors.ObservationDecodingError, console.fetch_screenshot) console.close() def test_fetch_screenshot_ok(self): telnet_connection = mock.create_autospec(telnetlib.Telnet) telnet_connection.read_until.return_value = 'OK' # Create a fake flat image with 4 channels. fake_img = np.array(list(range(10)) * 4, dtype=np.uint8) fake_raw_obs = raw_observation_pb2.RawObservation() fake_raw_obs.screen.data = fake_img.tobytes() fake_raw_obs.screen.height = 5 fake_raw_obs.screen.width = 2 fake_raw_obs.screen.num_channels = 4 fake_raw_obs.timestamp_us = 123456789 # Setup fifo as thread starts reading in the constructor. def good_read(): good_read.counter += 1 if good_read.counter % 2 == 1: return fake_raw_obs.SerializeToString() else: return b'' good_read.counter = 0 self._mock_fifo_file.read.side_effect = good_read with mock.patch.object( telnetlib, 'Telnet', autospec=True, return_value=telnet_connection) as telnet_init: console = emulator_console.EmulatorConsole( console_port=1234, auth_code=None, tmp_dir=absltest.get_default_test_tmpdir()) telnet_init.assert_called_once_with('localhost', 1234) observation = console.fetch_screenshot() reference_img = fake_img.reshape((5, 2, 4)) reference_img = np.delete(reference_img, 3, 2) np.testing.assert_equal(reference_img, observation[0]) self.assertEqual(observation[1], 123456789) # Close the console. console.close() if __name__ == '__main__': absltest.main() <file_sep># AndroidEnv - Tasks With AndroidEnv we provide a mechanism for easily defining RL tasks for the agent to learn. This includes various types of information such as what app/game it should train on, what rewards the environment returns, or the start state distribution and the episode end criteria. ## Task structure A *task* definition is captured in the form of a `Task()` proto message. These are most easily created by writing a `.textproto` file, then parsing it into a proto message. In this section you can find a detailed description about the types of information that make up a task, and an example demonstrating exactly how to put these into code. <details> <summary>Expand this tab to view the main types of information captured in these messages: </summary> * `id`: An ID used to identify the task. * `setup_steps`: These are steps the environment will perform right after launching the simulator. Possible steps include: * `install_apk`: Installs an application from a specified path to the APK file. * `start_activity`: Launches the requested app/activity. * `rotate`: Sets the orientation of the device (landscape/portrait). * `reset_steps`: These are steps the environment will perform right at the beginning of a new RL episode. Possible steps include: * `force_stop`: Stops a given app. * `start_activity`: Launches the requested app/activity. * `start_screen_pinning`: Restricts the agent's interaction to a particular activity through [screen pinning](https://support.google.com/android/answer/9455138?hl=en), meaning the agent will not be able to quit the given app. * `clear_cache`: Clears the cache of a given app. * `success_conditions`: For each success condition defined, the environment will make sure that these conditions were met after finishing `setup_steps` and `reset_steps`. They might include conditions such as: * `check_install`: Makes sure that the request app was successfully installed. * `wait_for_app_screen`: Waits until the request app was successfully launched. * `expected_app_screen`: If this value is set to a particular activity, the environment will periodically check if the agent is still interacting with said activity, making sure it has not accidentally quit the application we want it to be training on. * `max_duration_sec`: Puts a time limit on the episodes, triggering an episode reset if the current episode has lasted too long. * `max_duration_steps`: Puts a step limit on the episodes, triggering an episode reset once the agent has reached the specified limit. * `log_parsing_config`: If the environment is parsing logcat messages, this field will determine what information it should listen for using regular expressions. * `filters`: The environment filters log messages for these labels which signify that such messages were meant to be parsed by AndroidEnv. * `log_regexps`: Once a log message was identified as relevant using the filters, the environment parses its contents using these regular expressions. For example, an application might be sending log messages of the form `reward: 1.0`, then the task will capture this info using the regexp `^[Rr]eward: ([-+]?[0-9]*\\.?[0-9]*)$`. * `extras_spec`: Determines the type and shape of extras exposed by the task. Extras are usually parsed from logcat messages. </details> <details> <summary>Expand this tab to see what an example `.textproto` file might look like in practice:</summary> ```python id: "classic_2048" name: "Classic 2048 - Default" description: "Slide numbered tiles on a grid to combine them to create a tile with the number 2048" package_name: "com.tpcstld.twozerogame" full_activity_name: "com.tpcstld.twozerogame/com.tpcstld.twozerogame.MainActivity" # Perform these upon launching the environment setup_steps: [ { # Install the 2048 app adb_call: { install_apk: { filesystem: { path: path/to/classic_2048.apk } } } # Check if it was installed correctly success_condition: { check_install: { package_name: "com.tpcstld.twozerogame" timeout_sec: 10.0 } } }, # Orient the screen in portait mode { adb_call: { rotate: { orientation: PORTRAIT_0 } } } ] # Perform these upon episode resets reset_steps: [ # Stop the 2048 app { adb_call: { force_stop: { package_name: "com.tpcstld.twozerogame" } } }, { adb_call: { clear_cache: { package_name: "com.tpcstld.twozerogame" } } }, # Start the 2048 app { adb_call: { start_activity: { full_activity: "com.tpcstld.twozerogame/com.tpcstld.twozerogame.MainActivity" extra_args: [ "--ez", '"RL_TASK_ENABLED"', '"true"', "--es", '"RL_TASK_GAME_CONFIG"', '"{}"' ] } } # Wait until the app has launched successfully success_condition: { wait_for_app_screen: { app_screen: { activity: "com.tpcstld.twozerogame/com.tpcstld.twozerogame.MainActivity" view_hierarchy_path: [ ] } timeout_sec: 10.0 } num_retries: 10 } }, # Make sure the agent cannot quit the 2048 app { adb_call: { start_screen_pinning: { full_activity: "com.tpcstld.twozerogame/com.tpcstld.twozerogame.MainActivity" } } } ] # Periodically check if the agent has accidentally quit the app expected_app_screen: { activity: "com.tpcstld.twozerogame/com.tpcstld.twozerogame.MainActivity" view_hierarchy_path: [] } max_num_steps: 500 # Capture expected format of log messages log_parsing_config: { filters: ["AndroidRLTask:V"] log_regexps: { score: "^[Ss]core: ([-+]?[0-9]*\\.?[0-9]*)$" reward: "^[Rr]eward: ([-+]?[0-9]*\\.?[0-9]*)$" episode_end: "^episode[ _]end$" extra: "^extra: (?P<name>[^ ]*)[ ]?(?P<extra>.*)$" json_extra: "^json_extra: (?P<json_extra>.*)$" } } # Capture expected shape and type of extras extras_spec: [ # Grid representing the state of the board. { name: "grid" shape: [4, 4], dtype: INT32}, # Direction of the last swipe action that prompted that change in the state. # 0: up, 1: right, 2: down, 3: left { name: "direction" shape: [1], dtype: INT32 } ] ``` </details> ## Log messages and custom APKs You might have noticed that tasks often rely on log messages exposed by the Android system, which AndroidEnv can intercept and translate into items such as rewards, episode end signals or task extras. One way to define rewards is by using `log_parsing_config.LogRegexps.RewardEvent` messages in the task proto. These consist of a regular expression and a numeric value indicating the intended reward. If the regexp is matched in any of the lines of the logcat stream, the agent will receive the given reward. It is also possible to have multiple of these RewardEvents, allowing us to give rewards for different log messages. The same applies for episode end signals: logcat messages that match the regexps defined in `log_parsing_config.LogRegexps.episode_end` will trigger an episode reset. Of course, applications might not send suitable messages by default, so in order to have access to such messages, we often add them to the apps' source code to match our expectations. For example, in the case of the 2048 app, we find in the game's source code the exact lines where the score is computed, and add a line to log this value in the format that is expected by the textproto (or conversely, make sure the textproto matches the format you specified here). For example: ```java // Make sure thet LOG_FILTER matches 'filters' in the textproto public static final String LOG_FILTER = "AndroidRLTask"; // Make sure that the corresponding part of 'log_regexps' will match this string Log.i(LOG_FILTER, String.format(Locale.ENGLISH, "reward: %r", reward_value)) ``` You can take a look at example APKs extended with log messages in the example tasks (see the section below). ## Example tasks Along with the environment implementation we provide a set of example task definitions. These were chosen so that they would demonstrate the large variety of different challenges (e.g. app navigtion, puzzle games, time-reactive games, adventure games, card games...) and corresponding interfaces (e.g. button pressing, swiping, drag-and-drop...) available in AndroidEnv. You can find a list and detailed description of each of these tasks in [example_tasks.md](example_tasks.md). <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Wraps the AndroidEnv environment to rescale the observations.""" from typing import Optional, Sequence, Dict from android_env.wrappers import base_wrapper import dm_env from dm_env import specs import numpy as np from PIL import Image # Taken from https://pillow.readthedocs.io/en/3.2.x/reference/Image.html#PIL.Image.Image.convert # # This array maps an RGB image to a grayscale image using the ITU-R 709 # specification which is good for computer displays and HDTV. RGB_TO_GRAYSCALE_COEFFICIENTS = [0.2126, 0.7152, 0.0722] class ImageRescaleWrapper(base_wrapper.BaseWrapper): """AndroidEnv with rescaled observations.""" def __init__( self, env: dm_env.Environment, zoom_factors: Optional[Sequence[float]] = (0.5, 0.5), grayscale: bool = False): super().__init__(env) assert 'pixels' in self._env.observation_spec() assert self._env.observation_spec()['pixels'].shape[-1] in [1, 3], ( 'Number of pixel channels should be 1 or 3.') self._grayscale = grayscale if zoom_factors is None: zoom_factors = (1.0, 1.0) # We only zoom the width and height of each layer, and we explicitly do not # want to zoom the number of channels so we just multiply it by 1.0. self._zoom_factors = tuple(zoom_factors) + (1.0,) # Save the raw image for making videos, for example. self._raw_pixels = None @property def raw_pixels(self): return self._raw_pixels def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep: observation = timestep.observation self._raw_pixels = observation['pixels'].copy() processed_observation = observation.copy() processed_observation['pixels'] = self._process_pixels( observation['pixels']) return timestep._replace(observation=processed_observation) def _process_pixels(self, raw_observation: np.ndarray) -> np.ndarray: # We expect `raw_observation` to have shape (W, H, 3) - 3 for RGB new_shape = np.array( self._zoom_factors[0:2] * np.array(raw_observation.shape[0:2]), dtype=np.int)[::-1] if self._grayscale: # When self._grayscale == True, we squash the RGB into a single layer image = np.dot(raw_observation, RGB_TO_GRAYSCALE_COEFFICIENTS) else: image = raw_observation return self._resize_image_array(image, new_shape) def _resize_image_array( self, grayscale_or_rbg_array: np.ndarray, new_shape: Sequence[int]) -> np.ndarray: """Resize color or grayscale/action_layer array to new_shape.""" assert np.array(new_shape).ndim == 1 assert len(new_shape) == 2 resized_array = np.array(Image.fromarray( grayscale_or_rbg_array.astype('uint8')).resize(new_shape)) if resized_array.ndim == 2: return np.expand_dims(resized_array, axis=-1) return resized_array def reset(self) -> dm_env.TimeStep: timestep = self._env.reset() return self._process_timestep(timestep) def step(self, action) -> dm_env.TimeStep: timestep = self._env.step(action) return self._process_timestep(timestep) def observation_spec(self) -> Dict[str, specs.Array]: parent_spec = self._env.observation_spec().copy() out_shape = np.multiply(parent_spec['pixels'].shape, self._zoom_factors).astype(np.int32) if self._grayscale: # In grayscale mode we want the output shape to be [W, H, 1] out_shape[-1] = 1 parent_spec['pixels'] = specs.Array( shape=out_shape, dtype=parent_spec['pixels'].dtype, name=parent_spec['pixels'].name) return parent_spec <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for android_env.components.dumpsys_thread.""" from absl.testing import absltest from android_env.components import app_screen_checker as screen_checker from android_env.components import dumpsys_thread import mock class DumpsysThreadTest(absltest.TestCase): def setUp(self): super().setUp() self._dumpsys_thread = dumpsys_thread.DumpsysThread( app_screen_checker=mock.create_autospec( screen_checker.AppScreenChecker), check_frequency=1, max_failed_current_activity=5, block_input=True, block_output=True) def test_unexpected_activity(self): outcome = screen_checker.AppScreenChecker.Outcome.UNEXPECTED_ACTIVITY self._dumpsys_thread._app_screen_checker.matches_current_app_screen.return_value = outcome self._dumpsys_thread.write( dumpsys_thread.DumpsysThread.Signal.FETCH_DUMPSYS) v = self._dumpsys_thread.read(block=True) expected = dumpsys_thread.DumpsysThread.Signal.USER_EXITED_ACTIVITY self.assertEqual(expected, v) def test_unexpected_view_hierarchy(self): outcome = screen_checker.AppScreenChecker.Outcome.UNEXPECTED_VIEW_HIERARCHY self._dumpsys_thread._app_screen_checker.matches_current_app_screen.return_value = outcome self._dumpsys_thread.write( dumpsys_thread.DumpsysThread.Signal.FETCH_DUMPSYS) v = self._dumpsys_thread.read(block=True) expected = dumpsys_thread.DumpsysThread.Signal.USER_EXITED_VIEW_HIERARCHY self.assertEqual(expected, v) def test_success(self): outcome = screen_checker.AppScreenChecker.Outcome.SUCCESS self._dumpsys_thread._app_screen_checker.matches_current_app_screen.return_value = outcome self._dumpsys_thread.write( dumpsys_thread.DumpsysThread.Signal.FETCH_DUMPSYS) v = self._dumpsys_thread.read(block=True) expected = dumpsys_thread.DumpsysThread.Signal.OK self.assertEqual(expected, v) def test_not_requested(self): self._dumpsys_thread.write('wrong_signal') v = self._dumpsys_thread.read(block=True) expected = dumpsys_thread.DumpsysThread.Signal.DID_NOT_CHECK self.assertEqual(expected, v) def test_skipped(self): outcome = screen_checker.AppScreenChecker.Outcome.SUCCESS self._dumpsys_thread._app_screen_checker.matches_current_app_screen.return_value = outcome self._dumpsys_thread._check_frequency = 5 self._dumpsys_thread._main_loop_counter = 0 for _ in range(4): self._dumpsys_thread.write( dumpsys_thread.DumpsysThread.Signal.FETCH_DUMPSYS) v = self._dumpsys_thread.read(block=True) expected = dumpsys_thread.DumpsysThread.Signal.DID_NOT_CHECK self.assertEqual(expected, v) self._dumpsys_thread.write( dumpsys_thread.DumpsysThread.Signal.FETCH_DUMPSYS) v = self._dumpsys_thread.read(block=True) expected = dumpsys_thread.DumpsysThread.Signal.OK self.assertEqual(expected, v) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base class for AndroidEnv wrappers.""" from typing import Any, Dict import dm_env from dm_env import specs class BaseWrapper(dm_env.Environment): """AndroidEnv wrapper.""" def __init__(self, env): self._env = env def reset(self) -> dm_env.TimeStep: self._reset_state() timestep = self._process_timestep(self._env.reset()) return timestep def step(self, action: Any) -> dm_env.TimeStep: action = self._process_action(action) return self._process_timestep(self._env.step(action)) def _reset_state(self): pass def _process_action(self, action: Any) -> Any: return action def _process_timestep(self, timestep: dm_env.TimeStep) -> dm_env.TimeStep: return timestep def observation_spec(self) -> Dict[str, specs.Array]: return self._env.observation_spec() def action_spec(self) -> Dict[str, specs.Array]: return self._env.action_spec() def _wrapper_logs(self) -> Dict[str, Any]: """Add wrapper specific logging here.""" return {} def android_logs(self) -> Dict[str, Any]: info = self._env.android_logs() info.update(self._wrapper_logs()) return info @property def raw_env(self): """Recursively unwrap until we reach the true 'raw' env.""" wrapped = self._env if hasattr(wrapped, 'raw_env'): return wrapped.raw_env return wrapped def __getattr__(self, attr): """Delegate attribute access to underlying environment.""" return getattr(self._env, attr) def close(self): self._env.close() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests for AndroidEnv.""" from absl.testing import absltest from android_env import environment from android_env.components import coordinator as coordinator_lib import dm_env import mock import numpy as np class AndroidEnvTest(absltest.TestCase): def test_specs(self): coordinator = mock.create_autospec(coordinator_lib.Coordinator) coordinator.action_spec.return_value = { 'action_type': dm_env.specs.DiscreteArray(num_values=3), 'touch_position': dm_env.specs.BoundedArray( shape=(2,), dtype=np.float32, minimum=0.0, maximum=1.0), } coordinator.observation_spec.return_value = { 'pixels': dm_env.specs.Array(shape=(123, 456, 3), dtype=np.uint8), 'timedelta': dm_env.specs.Array(shape=(), dtype=np.int64), 'orientation': dm_env.specs.Array(shape=(4,), dtype=np.uint8), } coordinator.task_extras_spec.return_value = { 'click': dm_env.specs.Array(shape=(), dtype=np.int64), } env = environment.AndroidEnv(coordinator) # Check action spec. self.assertNotEmpty(env.action_spec()) self.assertIn('action_type', env.action_spec()) self.assertIsInstance(env.action_spec()['action_type'], dm_env.specs.DiscreteArray) self.assertIn('touch_position', env.action_spec()) self.assertIsInstance(env.action_spec()['touch_position'], dm_env.specs.BoundedArray) # Check observation spec. self.assertNotEmpty(env.observation_spec()) self.assertIn('pixels', env.observation_spec()) self.assertIsInstance(env.observation_spec()['pixels'], dm_env.specs.Array) # The `pixels` entry in the observation spec should match the screen size of # the simulator with three color channels (RGB). self.assertEqual(env.observation_spec()['pixels'].shape, (123, 456, 3)) self.assertIn('timedelta', env.observation_spec()) self.assertIsInstance(env.observation_spec()['timedelta'], dm_env.specs.Array) # The `timedelta` should be a scalar. self.assertEqual(env.observation_spec()['timedelta'].shape, ()) self.assertIn('orientation', env.observation_spec()) # The `orientation` should be a one-hot vector with four dimensions. self.assertIsInstance(env.observation_spec()['orientation'], dm_env.specs.Array) self.assertEqual(env.observation_spec()['orientation'].shape, (4,)) # Check extras spec. self.assertNotEmpty(env.task_extras_spec()) self.assertIn('click', env.task_extras_spec()) self.assertEqual(env.task_extras_spec()['click'].shape, ()) self.assertEqual(env.task_extras_spec()['click'].dtype, np.int64) def test_reset_and_step(self): coordinator = mock.create_autospec(coordinator_lib.Coordinator) coordinator.action_spec.return_value = { 'action_type': dm_env.specs.DiscreteArray(num_values=3), 'touch_position': dm_env.specs.BoundedArray( shape=(2,), dtype=np.float32, minimum=0.0, maximum=1.0), } coordinator.observation_spec.return_value = { 'pixels': dm_env.specs.Array(shape=(123, 456, 3), dtype=np.uint8), 'timedelta': dm_env.specs.Array(shape=(), dtype=np.int64), 'orientation': dm_env.specs.Array(shape=(4,), dtype=np.uint8), } coordinator.task_extras_spec.return_value = { 'click': dm_env.specs.Array(shape=(1,), dtype=np.int64), } env = environment.AndroidEnv(coordinator) coordinator.execute_action.return_value = ( { 'pixels': np.random.rand(987, 654, 3), 'timedelta': 123456, 'orientation': np.array((1, 0, 0, 0)), }, # Observation 0.0, # Reward. { 'click': np.array([[246]], dtype=np.int64) }, # Task extras. False # Episode ended? ) ts = env.reset() self.assertIsInstance(ts, dm_env.TimeStep) # After a `reset()` the TimeStep should follow some expectations. self.assertTrue(ts.first()) self.assertEqual(ts.reward, 0.0) self.assertEqual(ts.discount, 0.0) obs = ts.observation self.assertIn('pixels', obs) self.assertEqual(obs['pixels'].shape, (987, 654, 3)) self.assertIn('timedelta', obs) self.assertEqual(obs['timedelta'], 123456) self.assertIn('orientation', obs) self.assertEqual(obs['orientation'].shape, (4,)) np.testing.assert_equal(obs['orientation'], (1, 0, 0, 0)) # Extras should also be provided. extras = env.task_extras() self.assertIn('click', extras) self.assertEqual(extras['click'], np.array([246], dtype=np.int64)) coordinator.get_logs.return_value = { 'my_measurement': 135, } # Step again in the environment and check expectations again. ts = env.step({'action_type': 1, 'touch_position': (10, 20)}) self.assertIsInstance(ts, dm_env.TimeStep) # The StepType now should NOT be FIRST. self.assertFalse(ts.first()) self.assertEqual(ts.reward, 0.0) self.assertEqual(ts.discount, 0.0) obs = ts.observation self.assertIn('pixels', obs) self.assertEqual(obs['pixels'].shape, (987, 654, 3)) self.assertIn('timedelta', obs) self.assertEqual(obs['timedelta'], 123456) self.assertIn('orientation', obs) self.assertEqual(obs['orientation'].shape, (4,)) np.testing.assert_equal(obs['orientation'], (1, 0, 0, 0)) # Extras should still be provided. extras = env.task_extras() self.assertIn('click', extras) self.assertEqual(extras['click'], np.array([246], dtype=np.int64)) # At this point these methods and properties should return something. self.assertNotEmpty(env.android_logs()) self.assertNotEmpty(env.raw_observation) self.assertNotEmpty(env.raw_action) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for loader.""" import builtins import os from absl.testing import absltest from android_env import environment from android_env import loader from android_env.components import coordinator as coordinator_lib from android_env.components import emulator_simulator from android_env.components import task_manager as task_manager_lib from android_env.proto import task_pb2 import mock class LoaderTest(absltest.TestCase): @mock.patch.object(task_manager_lib, 'TaskManager', autospec=True) @mock.patch.object(emulator_simulator, 'EmulatorSimulator', autospec=True) @mock.patch.object(coordinator_lib, 'Coordinator', autospec=True) @mock.patch.object(builtins, 'open', autospec=True) def test_load(self, mock_open, coordinator, simulator, task_manager): mock_open.return_value.__enter__ = mock_open mock_open.return_value.read.return_value = '' env = loader.load( task_path='some/path/', avd_name='my_avd', android_avd_home='~/.android/avd', android_sdk_root='~/Android/Sdk', emulator_path='~/Android/Sdk/emulator/emulator', adb_path='~/Android/Sdk/platform-tools/adb', run_headless=False, ) self.assertIsInstance(env, environment.AndroidEnv) simulator.assert_called_with( emulator_launcher_args=dict( avd_name='my_avd', android_avd_home=os.path.expanduser('~/.android/avd'), android_sdk_root=os.path.expanduser('~/Android/Sdk'), emulator_path=os.path.expanduser('~/Android/Sdk/emulator/emulator'), run_headless=False, gpu_mode='swiftshader_indirect', grpc_port=-1), emulator_console_args={}, adb_path=os.path.expanduser('~/Android/Sdk/platform-tools/adb'), adb_server_port=5037, prompt_regex=r'\w*:\/ \$', ) coordinator.assert_called_with( simulator.return_value, task_manager.return_value, ) @mock.patch.object(task_manager_lib, 'TaskManager', autospec=True) @mock.patch.object(emulator_simulator, 'EmulatorSimulator', autospec=True) @mock.patch.object(coordinator_lib, 'Coordinator', autospec=True) @mock.patch.object(builtins, 'open', autospec=True) def test_task(self, mock_open, coordinator, simulator, task_manager): del coordinator, simulator mock_open.return_value.__enter__ = mock_open mock_open.return_value.read.return_value = r''' id: "fake_task" name: "Fake Task" description: "Task for testing loader." max_duration_sec: 0 ''' env = loader.load( task_path='some/path/', avd_name='my_avd', ) expected_task = task_pb2.Task() expected_task.id = 'fake_task' expected_task.name = 'Fake Task' expected_task.description = 'Task for testing loader.' expected_task.max_duration_sec = 0 task_manager.assert_called_with(expected_task) assert isinstance(env, environment.AndroidEnv) if __name__ == '__main__': absltest.main() <file_sep># coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Android environment implementation.""" from typing import Any, Dict from absl import logging from android_env.components import coordinator as coordinator_lib import dm_env import numpy as np class AndroidEnv(dm_env.Environment): """An RL environment that interacts with Android apps.""" def __init__(self, coordinator: coordinator_lib.Coordinator): """Initializes the state of this AndroidEnv object.""" self._coordinator = coordinator self._latest_action = {} self._latest_observation = {} self._latest_extras = {} self._reset_next_step = True logging.info('Action spec: %s', self.action_spec()) logging.info('Observation spec: %s', self.observation_spec()) logging.info('Task extras spec: %s', self.task_extras_spec()) def action_spec(self) -> Dict[str, dm_env.specs.Array]: return self._coordinator.action_spec() def observation_spec(self) -> Dict[str, dm_env.specs.Array]: return self._coordinator.observation_spec() def task_extras_spec(self) -> Dict[str, dm_env.specs.Array]: return self._coordinator.task_extras_spec() @property def raw_action(self): return self._latest_action @property def raw_observation(self): return self._latest_observation def android_logs(self) -> Dict[str, Any]: return self._coordinator.get_logs() def reset(self) -> dm_env.TimeStep: """Resets the environment for a new RL episode.""" logging.info('Resetting AndroidEnv...') # Reset state of the environment. self._coordinator.reset_environment_state() # Execute selected action (None when resetting). obs, _, extras, _ = self._coordinator.execute_action(action=None) # Process relevant information. if obs is not None: self._latest_observation = obs.copy() self._latest_extras = extras.copy() self._latest_action = {} self._reset_next_step = False logging.info('Done resetting AndroidEnv.') logging.info('************* NEW EPISODE *************') return dm_env.TimeStep( step_type=dm_env.StepType.FIRST, observation=self._latest_observation, reward=0.0, discount=0.0) def step(self, action: Dict[str, np.ndarray]) -> dm_env.TimeStep: """Takes a step in the environment.""" # Check if it's time to reset the episode. if self._reset_next_step: return self.reset() # Execute selected action. obs, reward, extras, episode_end = self._coordinator.execute_action(action) # Process relevant information. if obs is not None: self._latest_observation = obs.copy() self._latest_extras = extras.copy() self._latest_action = action.copy() self._reset_next_step = episode_end # Return timestep with reward and observation just computed. if episode_end: return dm_env.termination( observation=self._latest_observation, reward=reward) else: return dm_env.transition( observation=self._latest_observation, reward=reward, discount=0.0) def task_extras(self, latest_only: bool = True) -> Dict[str, np.ndarray]: """Returns latest task extras.""" task_extras = {} for key, spec in self.task_extras_spec().items(): if key in self._latest_extras: extra_values = self._latest_extras[key].astype(spec.dtype) for extra in extra_values: spec.validate(extra) task_extras[key] = extra_values[-1] if latest_only else extra_values return task_extras def close(self) -> None: """Cleans up running processes, threads and local files.""" logging.info('Cleaning up AndroidEnv...') if hasattr(self, '_coordinator'): self._coordinator.close() logging.info('Done cleaning up AndroidEnv.') def __del__(self) -> None: self.close()
a4a1423e679c091fec6bbf8a0d62a53dc74ad2bc
[ "Markdown", "Python" ]
41
Python
smbale/android_env
5ecfbfe56bb5843b298791d3c8c73b01a79e864a
db1bd314ff13b97487c64800dab4e6956236f4af
refs/heads/master
<file_sep>import { CounterAction } from '../action/counter'; const INITIAL_STATE = { count: 0, }; export function CounterReducer(state = INITIAL_STATE, action) { switch (action.type) { case CounterAction.INCREMENT_COUNTER: return Object.assign({}, state, { count: state.count + 1 }); case CounterAction.DECREMENT_COUNTER: return Object.assign({}, state, { count: state.count - 1 }); default: return state; } }<file_sep>import React, { Component } from 'react'; import { connect } from 'react-redux'; import { CounterAction } from './store/action/counter'; class CounterComponent extends Component { componentWillReceiveProps(props) { console.log('props ', props) } render() { return ( <div> Counter: {this.props.count} <p> <button onClick={this.props.increment}>Increment ++</button> <strong>|</strong> <button onClick={this.props.decrement}>Decrement --</button> </p> </div> ); } } const mapStateToProps = state => { return { count: state.CounterReducer['count'] } } const mapDispatchToProps = dispatch => { return { increment: () => dispatch(CounterAction.increment()), decrement: () => dispatch(CounterAction.decrement()) } } export default connect(mapStateToProps, mapDispatchToProps)(CounterComponent); <file_sep>import React, { Component } from 'react'; import './App.css'; class UserView extends Component { componentWillReceiveProps(nextProps) { if(nextProps.user.id == 44) { console.log('this ', this.props.user.name) console.log('next ', nextProps.user.name) } // console.log('componentWillReceiveProps ', nextProps) } componentDidMount() { console.log('this.props, ', this.props); } deleteFromChild = () => { this.props.delete(this.props.user); } render() { return ( <div> {this.props.user.name} <button onClick={this.deleteFromChild}>Delete </button> <button>Edit </button> </div> ); } } export default UserView; <file_sep>import { createAction } from 'redux-actions'; export class GitAction { static GET_REPOS = 'GET_REPOS'; static GET_REPOS_SUCCESS = 'GET_REPOS_SUCCESS'; static GET_FOLLOWERS = 'GET_FOLLOWERS'; static GET_FOLLOWERS_SUCCESS = 'GET_FOLLOWERS_SUCCESS'; static getRepos(uid) { console.log('1', uid) return { type: GitAction.GET_REPOS, payload: uid }; } static getFollowers(uid) { return { type: GitAction.GET_FOLLOWERS, payload: uid }; } static getRepoSuccessful(data) { // console.log('repo success', data); return { type: GitAction.GET_REPOS_SUCCESS, payload: data }; } static getFollowersSuccessful(data) { console.log('follower success', data); return { type: GitAction.GET_FOLLOWERS_SUCCESS, payload: data }; } }<file_sep>import { GitAction } from '../action/github'; const INITIAL_STATE = { loader: false, repo: null, followers: null }; export function GithubReducer(state = INITIAL_STATE, action) { switch (action.type) { case GitAction.GET_REPOS: console.log('2 reducer', ) return {...state, loader: true}; case GitAction.GET_REPOS_SUCCESS: return Object.assign({}, state, { loader: false , repo: action.payload }); // case GitAction.GET_FOLLOWERS: // return Object.assign({}, state, { loader: true }); default: return state; } }<file_sep>import { Observable } from 'rxjs'; import { GitAction } from '../action/github'; export class GitEpic { static getRepoData(action$) { console.log(action$); return action$.ofType(GitAction.GET_REPOS) .switchMap(({payload}) => { console.log('3 epic: payload', payload); return Observable.ajax(`https://api.github.com/users/${payload}/repos`) .pluck("response") .map((jsonData) => { console.log('4 got data', jsonData); // console.log("jsondata ==>/ repos ", jsonData) // return Observable.of(GitAction.getRepoSuccessful(jsonData)); return { type: GitAction.GET_REPOS_SUCCESS, payload: jsonData }; }); }); } static getFollowersData(action$) { console.log(action$); return action$.ofType(GitAction.GET_REPOS_SUCCESS) .mergeMap(() => { return Observable.ajax(`https://api.github.com/users/${action$.payload}/followers`) .pluck("response") .switchMap((jsonData) => { console.log('5555555555555, got data', jsonData) // console.log("jsondata ==> followers ", jsonData) return Observable.of(GitAction.getFollowersSuccessful(jsonData)); }); }); } }<file_sep>function sum(a, b) { return a + b; } function multiply(a, b) { return a * b; } function sub(a, b) { return a / b; } export { multiply, sub }; export default sum;<file_sep>import React, { Component } from 'react'; class TodoInput extends Component { state = { appName: 'My App Name', task: '', mode: 'Add' } constructor(props) { super(props); // alert('rendring todoInput') // setTimeout(() => { // console.log('changing app name') // this.setState({appName: 'Changed......via state'}) // }, 2000) // this.onChangeHandler = this.onChangeHandler.bind(this); } // inputbox; onChangeHandler = (ev) => { console.log(ev.target.name); console.log(ev.target.value); // this.inputbox = ev.target.value; // this.setState({'task': ev.target.value}); this.setState({[ev.target.name]: ev.target.value}); } componentWillReceiveProps(nextProps) { if(nextProps.updateUser){ this.setState({mode: 'Update'}) } else { this.setState({mode: 'Add'}) } } submitHandler = (ev) => { if(this.state.mode == 'Add') { // addd } else { // update } console.log(ev) this.props.submit({ id: Date.now(), name: this.state.task }) this.setState({task: ''}); ev.preventDefault(); } render() { return ( <div> <h1>Todo Input Component - {this.state.appName}</h1> <form onSubmit={this.submitHandler}> <div> <input type="text" name="task" value={this.state.task} onChange={this.onChangeHandler}/> <input type="submit" name="add" value={this.state.mode}/> </div> </form> </div> ); } } export default TodoInput; <file_sep>import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import UserView from './UserView'; import TodoInput from './TodoInput'; import Sample from './Sample'; class App extends Component { state = { users: [{id: 1, name: 'user1'}, {id: 2, name: 'user2'}, {id: 3, name: 'user3'}], updateUser: null, childText: 'Sample 1' } deleteItem = (user) => { console.log('App.js delete item...', user.id); const abc = [...this.state.users]; abc[1] = {id: 44, name: 'user44'}; this.setState({users: abc}); } updateItem = () => { console.log('App.js update item...'); } addUser = (obj) => { let _user = [...this.state.users]; _user.push(obj); this.setState({users: _user}); } changeParentText = () => { this.setState({childText: 'Parent Text Changes' + Date.now()}); } updateParent = (obj) => { console.log('Child text Changed', obj); this.setState({childText: obj.text}) } render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> <div> <TodoInput submit={this.addUser} user={this.state.updateUser}/> </div> <div> { this.state.users.map(val => { return( <UserView user={val} delete={this.deleteItem} update={this.updateItem} /> ); }) } </div> <p> <button onClick={this.changeParentText}> chnage the text</button> </p> <Sample text={this.state.childText} output={this.updateParent} /> </div> ); } } export default App;
ec18baef1749500e1d96194cfbb6c23f2d47ab4e
[ "JavaScript" ]
9
JavaScript
Hamzakhann/uit-module-b
b458c8a18e0784fc2f836b2f361b333192896fba
2e713e25fad0dbf24240cffeb7a944c94b48c59b
refs/heads/master
<repo_name>henrytwo/EdsBlock<file_sep>/injection.js (function() { // just place a div at top right setTimeout(function() { var div = document.createElement('script'); var blacklist = ['Ahmad', 'Ahemd', 'Ahmed', 'Hamza', 'Ali', 'Jerry', 'Kennedy', 'Syed', 'Hasan']; console.log('heres da blacklist', blacklist) div.textContent = "var blacklist = " + JSON.stringify(blacklist) + ';'+ "function scan() {$(document).ready(function() {\ \ \ function filter(thing) {\ for (var z = 0; z < blacklist.length; z++) {\ console.log(thing.text());\ if (thing.text().includes(blacklist[z])) {\ thing.html('<b>Wallahi bro detected!!!</b> (' + blacklist[z] + ')<br><iframe src=\"https://giphy.com/embed/3oKIPchYaXx2YQybcY\" width=\"480\" height=\"270\" frameBorder=\"0\" class=\"giphy-embed\" allowFullScreen></iframe><p><a href=\"https://giphy.com/gifs/debbyryan-debby-ryan-3oKIPchYaXx2YQybcY\">via GIPHY</a></p>');\ \ break;\ }\ }\ }\ \ $('.xds-feedItem-type-4_0').each(function(i) {\ filter($(this));\ });\ $('.xds-feedItem-type-4_23').each(function(i) {\ filter($(this));\ }); \ }); };\ setInterval(scan, 1000);\ scan();" document.body.appendChild(div); }, 1000); })();<file_sep>/README.md # Blocks annoying kids on Edsby
1a62970e5b58906d5068994ad108f8a4f2bb1423
[ "JavaScript", "Markdown" ]
2
JavaScript
henrytwo/EdsBlock
a31c52b1a41fbd14b58f77e887429d0f3cfa1fb5
b6d92bc2498c32c41bd4b218dc89301334e243c0
refs/heads/master
<repo_name>thomazcarvalho/csgo_data-web_scraping<file_sep>/studying_web-scraping-(p2)(getting-hltv-data).py from bs4 import BeautifulSoup import requests import mysql.connector conn = mysql.connector.connect( host='localhost', user='root', password='' ) cursor = conn.cursor() cursor.execute('USE csgo_hltv') c = 100 date = '' site = 'https://www.hltv.org/results' while True: c += 100 try: source = requests.get(site).text except Exception as error: print(error) else: soup = BeautifulSoup(source, 'lxml') for sublist in soup.find_all('div', class_='results-sublist'): date = sublist.text[11:40].split('\n') date = date[0] print(date) for match in sublist.find_all('div', class_='result-con'): team1 = match.find( 'div', class_='line-align team1' ).text.replace( '\n', '' ) team2 = match.find( 'div', class_='line-align team2' ).text.replace( '\n', '' ) result = match.find('td', class_='result-score').text.replace( '\n', '' ) result = result.split(' - ') event = match.find('td', class_='event').text.replace('\n', '') rec = ( 'default', team1, team2, result[0], result[1], event, date ) cursor.execute( 'INSERT INTO csgo_results_hltv ' 'VALUES (%s, %s, %s, %s, %s, %s, %s) ', rec ) conn.commit() site = 'https://www.hltv.org/results?offset=' + str(c) conn.commit() cursor.close() conn.close() <file_sep>/README.md # csgo_data - web-scraping Colecting data from a specialized counter-strike global offensive website. The colected data is related to the matches since 2012 and in the database you will find information like: team1, team2, results, event, date and winner of the match. <file_sep>/studying_web-scraping-(p3)(creating-winner-column).py import mysql.connector as ms import pandas as pd conn = ms.connect( host='localhost', user='root', password='' ) cursor = conn.cursor() cursor.execute('USE csgo_hltv') cursor.execute( 'SELECT * FROM csgo_results_hltv' ) rec = cursor.fetchall() df = pd.DataFrame( rec, columns=('id', 'team1', 'team2', 'result team1', 'result team2', 'event', 'date') ) cursor.execute( 'ALTER TABLE csgo_results_hltv ' 'ADD COLUMN winner VARCHAR(25) NOT NULL;' ) winner = list() c = 0 for register in rec: if int(register[3]) > int(register[4]): winner.append(register[1]) elif int(register[4]) > int(register[3]): winner.append(register[2]) else: winner.append(None) cursor.execute( 'UPDATE csgo_results_hltv ' f'SET `winner` = "{winner[c]}" ' f'WHERE `id`={c+1}' ) print(c) c += 1 df['winner'] = winner print(df.head()) conn.commit() cursor.close() conn.close()
d16d1bcea69707eb90a7160e1c14ecdaffa60747
[ "Markdown", "Python" ]
3
Python
thomazcarvalho/csgo_data-web_scraping
52259b98e9b55acafb4b10bcc9a222100e43ee95
f19278846b2b83f567880617f70cfe2e06077fd4
refs/heads/master
<file_sep>var apl = angular.module('apl', []);<file_sep>AppdevPremierLeague =================== <file_sep>apl.factory('data', function(){ var listOfPlayers = [ { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'I am a good opener. I can provide a good start to the team. Also I am a good fielder.', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'NA', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'I am a good opener. I can provide a good start to the team. Also I am a good fielder.', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'I have dropped all the catches that ever came to me. Planning to write a book on How To Catch', image: 'images/team/abhisheknalwaya.png' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Primarily a Batsman, can bowl few spin, medium pace overs as well.', image: 'images/team/sachin.jpg' }, // { // name: '<NAME>', // bats: true, // bowls: true, // team: '', // cost:100, // sold: false, // active: true, // description: 'Played at college level.', // image: 'image/sachin.jpg' // }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'You know me well. Super fitness with exceptional fielding and bowling. Dare to have a face off :)', image: 'images/team/akshaygupta.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Left Arm Fast Bowler', image: 'images/team/akshaya.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Can Catch the ball with eyes closed apart from brilliant batting and bowling', image: 'images/team/aman.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'I was member of Cricket team in my previous organization & used to open the innings. Can bowl medium pace as well.', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Love to Open.', image: 'images/team/arpit.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'With win win attitude I ensure I fight to win till the last ball is bowled be it batting, bowling or fielding, My contribution will always be more than 100%.', image: 'images/team/manchanda.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'I love to play cricket', image: 'images/team/Awanish.jpg' }, { name: 'Biju', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Can hit sixes as much as the team wants. Get opposition teams top order batsmen out at will!', image: 'images/team/biju.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Played at college level.', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'NA', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Opening Batsman and Medium pace part time bowler. Good fielding and catching skills.', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'I Bat defensively and very slowly for hours. I bowl even slower but get batsmen caught out on the boundary(sometimes). I field ok and do not let go of any catches and I do not misfield!', image: 'images/team/jyoti.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'NA', image: 'images/team/karanarora.jpg' }, // { // name: '<NAME>', // bats: true, // bowls: true, // team: '', // cost:100, // sold: false, // active: true, // description: 'NA', // image: 'image/sachin.jpg' // }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'NA', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'NA', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Currently training in South Africa with the team that defeated India. Highly motivated player with impeccable track record in gully cricket.', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'NA', image: 'images/team/pankajarora.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Right Arm Medium Bowler, Right Hand Batsmen. Played for MSO XI and won the third position in the last Mckinsey Cricket League.', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'I am a medium fast bowler and mid level batsman. I like playing in pressure situations and could come handy.', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'I am passionate about cricket. I am a bowler but appdev players treat me as batsman , now I am all rounder', image: 'images/team/prayag.png' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'I play as a fast bowler in team and usually bat at number 4-5', image: 'images/team/sachin.jpg' }, { name: 'Ranjeet', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'NA', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'NA', image: 'images/team/sanjeev.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost: 100, sold: false, active: true, description: 'Bowler', image: 'images/team/sanjeevmishra.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'Like my favourite language Ruby, I blend sound base technique along with scope of great flexibility.', image: 'images/team/shadab.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'A batsman who can bowl and a bolwer who can bat.', image: 'images/team/siddharth.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'NA', image: 'images/team/sourabhgupta.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost:100, sold: false, active: true, description: 'A solid WicketKeeper', image: 'images/team/sumitjolly.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost: 100, sold: false, active: true, description: 'NA', image: 'images/team/sachin.jpg' }, { name: '<NAME>', bats: true, bowls: true, team: '', cost: 100, sold: false, active: true, description: 'Although I have last played cricket long ago, I had been the best bowler of my colony Team and very good batsman as well. I have mostly played with Tennis ball(Flash and Mark ball) and sometimes with leather', image: 'images/team/sachin.jpg' } ]; function saveListOfPlayers(players){ localStorage.setItem('players', JSON.stringify(players)); } function getListOfPlayers(){ return JSON.parse(localStorage.getItem('players')) || listOfPlayers; } return { getListOfPlayers: getListOfPlayers, saveListOfPlayers : saveListOfPlayers } });
56274340981a25f5fae4239aa689d0c2bc3ab8fb
[ "JavaScript", "Markdown" ]
3
JavaScript
adityasaxena/AppdevPremierLeague
1e8ef75157dc3c09a9c93b63be3e29cbe814632d
b9183506759657c933a51556609614e0bd4348d9